FfiBuilderMacro.hx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package lua.jit;
  2. import haxe.macro.Context;
  3. import haxe.macro.Expr;
  4. import haxe.macro.Type;
  5. using haxe.macro.TypeTools;
  6. using haxe.macro.ComplexTypeTools;
  7. @:noPackageRestrict
  8. class FfiBuilderMacro {
  9. static function ctype(t : Type) : String{
  10. return if (t.unify(Context.getType("Int"))){
  11. "int ";
  12. } else if (t.unify(Context.getType("String"))){
  13. "const char *";
  14. } else {
  15. "const char *";
  16. }
  17. }
  18. macro public function build() : Array<Field>{
  19. var fields = Context.getBuildFields();
  20. var b = [];
  21. var cls = Context.getLocalClass().get();
  22. if (cls.meta.has(":luaFfiLoad")){
  23. var loads = cls.meta.extract(":luaFfiLoad");
  24. for (load in loads){
  25. for (param in load.params){
  26. b.push(macro lua.Ffi.load($param));
  27. }
  28. }
  29. }
  30. for (f in fields){
  31. switch(f.kind){
  32. case FieldType.FFun(fn) : {
  33. var ret_type = fn.ret.toType();
  34. var ret = ctype(ret_type);
  35. var args = [];
  36. for (arg in fn.args){
  37. var type = ctype(arg.type.toType());
  38. args.push('${type}${arg.name}');
  39. }
  40. b.push(macro lua.Ffi.cdef('${ret}${f.name}(${args.join(", ")});'));
  41. }
  42. default : null;
  43. }
  44. }
  45. fields.push({
  46. name : "__init__",
  47. access : [Access.AStatic],
  48. pos : Context.currentPos(),
  49. kind :FieldType.FFun({
  50. args : [],
  51. expr : macro $b{b},
  52. params : [],
  53. ret : Context.getType("Void").toComplexType()
  54. })
  55. });
  56. cls.meta.add(":native", [ macro "__lua_Ffi.C"], Context.currentPos());
  57. return fields;
  58. }
  59. }