Browse Source

support native haxe string interpolation and OpAdd chains in Syntax.pythonCode

frabbit 11 years ago
parent
commit
2a732f3f7c
2 changed files with 38 additions and 5 deletions
  1. 9 5
      genpy.ml
  2. 29 0
      tests/unit/TestPython.hx

+ 9 - 5
genpy.ml

@@ -1239,11 +1239,15 @@ module Printer = struct
 			| "super",_ ->
 			| "super",_ ->
 				let s_el = print_exprs pctx ", " el in
 				let s_el = print_exprs pctx ", " el in
 				Printf.sprintf "super().__init__(%s)" s_el
 				Printf.sprintf "super().__init__(%s)" s_el
-			| ("python_Syntax.pythonCode"),[e1] ->
-				begin match e1.eexpr with
-					| TConst (TString s) -> s
-					| e -> print_expr pctx e1
-				end
+			| ("python_Syntax.pythonCode"),[e] ->
+				(* supports native haxe string interpolation *)
+				let rec loop x =
+					(match x with
+					| { eexpr = TBinop(OpAdd,a,b)} -> (loop a) ^ (loop b)
+					| { eexpr = TConst (TString s) } -> s
+					| e -> print_expr pctx e)
+				in
+				loop e
 			| "python_Syntax._callNamedUntyped",el ->
 			| "python_Syntax._callNamedUntyped",el ->
 				let res,fields = match List.rev el with
 				let res,fields = match List.rev el with
 					| {eexpr = TObjectDecl fields} :: el ->
 					| {eexpr = TObjectDecl fields} :: el ->

+ 29 - 0
tests/unit/TestPython.hx

@@ -1,6 +1,7 @@
 package unit;
 package unit;
 
 
 import python.KwArgs;
 import python.KwArgs;
+import python.Syntax;
 import python.VarArgs;
 import python.VarArgs;
 import sys.io.File;
 import sys.io.File;
 import sys.io.Process;
 import sys.io.Process;
@@ -262,4 +263,32 @@ class TestPython extends Test {
 	function testIsViaParentInterface() {
 	function testIsViaParentInterface() {
 		t(Std.is(new B(), IA));
 		t(Std.is(new B(), IA));
 	}
 	}
+
+
+	// Syntax Tests
+
+	function testPythonCodeStringInterpolation () {
+		var z = 1;
+		var a = (Syntax.pythonCode('[$z, ${2}]'):Array<Int>);
+
+		eq(a[0], z);
+		eq(a[1], 2);
+
+		inline function test2 (x:Int) {
+			x += 1;
+			return (Syntax.pythonCode('$x'):Int);
+		}
+
+		inline function test3 (x:Int) {
+			return (Syntax.pythonCode('[$x]'):Array<Int>);
+		}
+		var x = 1;
+
+		eq(2, test2(x));
+		eq(1, x);
+		eq(1, test3(1)[0]);
+
+		eq("foo1bar", Syntax.pythonCode("'foo' + str(" + x + ") + 'bar'"));
+
+	}
 }
 }