crystal-lang / crystal_lib

Automatic binding generator for native libraries in Crystal
138 stars 30 forks source link

Enumerated types support #37

Closed olbat closed 7 years ago

olbat commented 7 years ago

The current implementation does not seems to support enumerated types, is that desired ?

Example:

$ cat <<'EOF' > mylib.h
enum MyEnumeratedType {
    MY_FIRST,
    MY_SECOND,
    MY_THIRD,
};
EOF

$ cat <<'EOF' > mylib.cr
@[Include("./mylib.h", prefix: %w(My MY_))]
lib MyLib
end
EOF

$ crystal src/main.cr -- mylib.cr
input.c:1:10: error: './mylib.h' file not found with <angled> include; use "quotes" instead
lib MyLib
end

Tests has been made with https://github.com/crystal-lang/crystal_lib/commit/029bd721a0d5107ba9a2140fe9c9780988f2e454 and Crystal 0.20.5 .

olbat commented 7 years ago

I've proposed an implementation in #38 if the feature request is confirmed.

mverzilli commented 7 years ago

Enums are supported. If you provide the absolute path for mylib.h, like this:

$ cat <<'EOF' > mylib.cr
@[Include("./mylib.h", prefix: %w(My MY_))]
lib MyLib
end
EOF

You'll see the error goes away. You'll still notice that the enum doesn't get added. That's because crystal_lib only transforms the minimum needed for exported functions to work.

So, if you change your mylib.h to be:

enum MyEnumeratedType {
    MY_FIRST,
    MY_SECOND,
    MY_THIRD,
};

enum MyEnumeratedType Myfoo();

You'll get the following mylib.cr output:

@[Include("[ABSOLUTE_PATH_TO_LIB/mylib.h", prefix: %w(My MY_))]
lib MyLib
  fun 
end
olbat commented 7 years ago

I'm not sure I understand: isn't the MyEnumeratedType enum supposed to be transformed to a crystal enum defining MyFirst, MySecond and MyThird ?

In this short example, the path is not absolute but I actually had this issue trying to port a C lib that uses enumerated types to define error statuses, options, ... Since this types does not appear in the generated code (which, regarding to the code, seems normal : only enums with an empty name are considered) it's not usable "out of the box".

Okay my bad, I did not noticed that the enum had to be used somewhere to appear in the generated code ... Sorry and thank you for your help !

mverzilli commented 7 years ago

You're welcome! :)