Macros.hx 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package python;
  2. import haxe.macro.Expr;
  3. import haxe.macro.Context;
  4. #if macro
  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. #if !macro macro #end public static function callNamed (e:Expr, args:Expr):haxe.macro.Expr {
  47. var fArgs = switch (Context.typeof(e)) {
  48. case TFun(args, ret): args;
  49. case _ : haxe.macro.Context.error("e must be of type function", e.pos);
  50. }
  51. switch (args.expr) {
  52. case EObjectDecl(fields):
  53. for (f in fields) {
  54. var found = false;
  55. for (a in fArgs) {
  56. found = a.name == f.field;
  57. if (found) break;
  58. }
  59. if (!found) {
  60. haxe.macro.Context.error("field " + f.field + " is not a valid argument (valid names " + [for (a in fArgs) a.name].join(",") + ")", args.pos);
  61. }
  62. }
  63. // TODO check at least if fields are valid (maybe if types match);
  64. case _ : haxe.macro.Context.error("args must be an ObjectDeclaration like { name : 1 }", args.pos);
  65. }
  66. return macro @:pos(e.pos) untyped __named__($e, $args);
  67. }
  68. }