Macros.hx 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package python;
  2. #if macro
  3. import haxe.macro.Expr;
  4. import haxe.macro.Context;
  5. import haxe.macro.ExprTools;
  6. #end
  7. #if !macro
  8. import python.lib.Types.PyIterator;
  9. #end
  10. class Macros {
  11. @:noUsing macro public static function importModule (module:String):haxe.macro.Expr {
  12. return macro untyped __python__($v{"import " + module});
  13. }
  14. @:noUsing macro public static function importAs (module:String, className : String):haxe.macro.Expr
  15. {
  16. var n = className.split(".").join("_");
  17. var e = "import " + module + " as " + n;
  18. var e1 = "_hx_c."+n+" = "+n;
  19. return macro{
  20. untyped __python__($v{e});
  21. untyped __python__($v{e1});
  22. }
  23. }
  24. @:noUsing macro public static function pyFor <T>(v:Expr, it:Expr, b:Expr):haxe.macro.Expr
  25. {
  26. var id = switch (v.expr) {
  27. case EConst(CIdent(x)):x;
  28. case _ : Context.error("unexpected " + ExprTools.toString(v) + ": const ident expected", v.pos);
  29. }
  30. var res = macro @:pos(it.pos) {
  31. var $id = $it.getNativeIterator().__next__();
  32. $it;
  33. $b;
  34. }
  35. return macro (untyped __python_for__)($res);
  36. }
  37. @:noUsing macro public static function importFromAs (from:String, module:String, className : String):haxe.macro.Expr {
  38. var n = className.split(".").join("_");
  39. var e = "from " + from + " import " + module + " as " + n;
  40. var e1 = "_hx_c."+n+" = " + n;
  41. return macro {
  42. untyped __python__($v{e});
  43. untyped __python__($v{e1});
  44. }
  45. }
  46. @:noUsing macro public static function callField (o:Expr, field:ExprOf<String>, params:Array<Expr>):haxe.macro.Expr {
  47. var field = macro untyped __field__($o, $field);
  48. return macro untyped __call__($a{[field].concat(params)});
  49. }
  50. #if !macro macro #end public static function callNamed (e:Expr, args:Expr):haxe.macro.Expr {
  51. var fArgs = switch (Context.typeof(e)) {
  52. case TFun(args, ret): args;
  53. case _ : haxe.macro.Context.error("e must be of type function", e.pos);
  54. }
  55. switch (args.expr) {
  56. case EObjectDecl(fields):
  57. for (f in fields) {
  58. var found = false;
  59. for (a in fArgs) {
  60. found = a.name == f.field;
  61. if (found) break;
  62. }
  63. if (!found) {
  64. haxe.macro.Context.error("field " + f.field + " is not a valid argument (valid names " + [for (a in fArgs) a.name].join(",") + ")", args.pos);
  65. }
  66. }
  67. // TODO check at least if fields are valid (maybe if types match);
  68. case _ : haxe.macro.Context.error("args must be an ObjectDeclaration like { name : 1 }", args.pos);
  69. }
  70. return macro @:pos(e.pos) untyped __named__($e, $args);
  71. }
  72. }