diku-dk / futhark

:boom::computer::boom: A data-parallel functional programming language
http://futhark-lang.org
ISC License
2.41k stars 166 forks source link

How to generate opaque types for arrays? #2172

Closed entropylost closed 3 months ago

entropylost commented 3 months ago

When writing my code, I'm using array of typedefs, but futhark still generates the hashed opaque type and then produces functions like:

int futhark_index_opaque_arr1d_Particle(struct futhark_context *ctx, struct futhark_opaque_2d6ee3396b62030339f319a874a90322 **out, struct futhark_opaque_arr1d_Particle *arr, int64_t i0);

Source code:

type Vec2 = [2]f32

type Particle = {
  pos: Vec2,
  vel: Vec2,
  rotation: f32,
  angular_velocity: f32,
}

def (+) (a: Vec2) (b: Vec2): Vec2 =
  [a[0] + b[0], a[1] + b[1]]

entry step (particles: []Particle): []Particle =
  map (\p ->
        let new_pos = p.pos + p.vel
        let new_vel = p.vel
        in {rotation=p.rotation, angular_velocity=p.angular_velocity, pos=new_pos, vel=new_vel}
      ) particles

Is there any way to get futhark to actually name opaque_2d6ee3396b62030339f319a874a90322 as opaque_Particle instead?

athas commented 3 months ago

The whole business about naming of types in the C interface is quite subtle and weird, because it tries to do two things at once: use the type names of the original program (which may not exist), and expose the actual structure of types when possible. It is possible to end up with different C types that represent the same underlying Futhark type, as you've discovered. This was extremely rare before we added all the convenience functions (like array indexing), but now it sadly happens easily.

I've considered various solutions. One is to generate the opaque-named structs, and then use typedefs to give them better names. This would allow one C type to have multiple names.

As a workaround, you can hide the fact that []Particle is an array, for example by wrapping it in a sum type or record:

type Particles = #Particle []Particle

and then write your own (explicitly typed) indexing entry points.

athas commented 3 months ago

Oh, actually this particular case can be fixed easily enough, since we have all the information in the type ascription.

entropylost commented 3 months ago

One is to generate the opaque-named structs and then use typedefs to give them better names. This would allow one C type to have multiple names.

I'd greatly appreciate that, it'd make things way nicer. Although this is C, so we can't have associated methods on the types and then naming the functions would be a problem; I suppose you can have multiple repeats of those and it'd be fine..