ソースを参照

generate @:coreType abstracts and move Enum implementation to internal.EnumImpl

Simon Krajewski 11 年 前
コミット
1d153fbd71
3 ファイル変更137 行追加139 行削除
  1. 72 98
      genpy.ml
  2. 42 41
      std/python/Boot.hx
  3. 23 0
      std/python/internal/EnumImpl.hx

+ 72 - 98
genpy.ml

@@ -14,30 +14,8 @@ _hx_c = _hx_AnonObject()
 
 _hx_c._hx_AnonObject = _hx_AnonObject
 
-
 import functools as _hx_functools
 
-class Enum:
-    # String tag;
-    # int index;
-    # List params;
-    def __init__(self, tag, index, params):
-        self.tag = tag
-        self.index = index
-        self.params = params
-
-    def __str__(self):
-        if self.params == None:
-            res = self.tag
-        else:
-            res = self.tag + '(' + ','.join(self.params) + ')'
-        res
-
-Enum._hx_class_name = 'Enum'
-Enum._hx_class = Enum
-_hx_classes['Enum'] = Enum
-_hx_c.Enum = Enum
-
 class _HxException(Exception):
     # String tag;
     # int index;
@@ -50,47 +28,6 @@ class _HxException(Exception):
         Exception.__init__(self, message)
         self.val = val
 
-class Int:
-    pass
-
-Int._hx_class_name = 'Int'
-Int._hx_class = Int
-_hx_classes['Int'] = Int
-_hx_c.Int = Int
-
-class Bool:
-    pass
-
-Bool._hx_class_name = 'Bool'
-Bool._hx_class = Bool
-
-_hx_classes['Bool'] = Bool
-_hx_c.Bool = Bool
-
-class Float:
-    pass
-
-Float._hx_class_name = 'Float'
-Float._hx_class = Float
-_hx_classes['Float'] = Float
-_hx_c.Float = Float
-
-class Dynamic:
-    pass
-
-Dynamic._hx_class_name = 'Dynamic'
-Dynamic._hx_class = Dynamic
-_hx_classes['Dynamic'] = Dynamic
-_hx_c.Dynamic = Dynamic
-
-class Class:
-    pass
-
-Class._hx_class_name = 'Class'
-Class._hx_class = Class
-_hx_classes['Class'] = Class
-_hx_c.Class = Class
-
 def _hx_rshift(val, n):
     return (val % 0x100000000) >> n
 def _hx_modf(a,b):
@@ -1519,28 +1456,25 @@ module Generator = struct
 			print ctx "%s.%s = %s" (get_path (t_infos (TClassDecl c))) name field_name
 		end
 
-	let gen_class_constructor ctx c = match c.cl_constructor with
-		| None ->
-			()
-		| Some cf ->
-			let member_inits = get_members_with_init_expr c in
-			newline ctx;
-			let py_metas = filter_py_metas cf.cf_meta in
-			begin match member_inits,cf.cf_expr with
-				| _,Some ({eexpr = TFunction f} as ef) ->
-					let ethis = mk (TConst TThis) (TInst(c,List.map snd c.cl_types)) cf.cf_pos in
-					let member_data = List.map (fun cf ->
-						let ef = mk (TField(ethis,FDynamic cf.cf_name)) cf.cf_type cf.cf_pos in
-						mk (TBinop(OpAssign,ef,null ef.etype ef.epos)) ef.etype ef.epos
-					) member_inits in
-					let e = {f.tf_expr with eexpr = TBlock (member_data @ [f.tf_expr])} in
-					cf.cf_expr <- Some {ef with eexpr = TFunction {f with tf_expr = e}};
-				| _ ->
-					(* TODO: is this correct? *)
-					()
-			end;
-			gen_func_expr ctx (match cf.cf_expr with None -> assert false | Some e -> e) c "__init__" py_metas ["self"] "\t" false;
-			newline ctx
+	let gen_class_constructor ctx c cf =
+		let member_inits = get_members_with_init_expr c in
+		newline ctx;
+		let py_metas = filter_py_metas cf.cf_meta in
+		begin match member_inits,cf.cf_expr with
+			| _,Some ({eexpr = TFunction f} as ef) ->
+				let ethis = mk (TConst TThis) (TInst(c,List.map snd c.cl_types)) cf.cf_pos in
+				let member_data = List.map (fun cf ->
+					let ef = mk (TField(ethis,FDynamic cf.cf_name)) cf.cf_type cf.cf_pos in
+					mk (TBinop(OpAssign,ef,null ef.etype ef.epos)) ef.etype ef.epos
+				) member_inits in
+				let e = {f.tf_expr with eexpr = TBlock (member_data @ [f.tf_expr])} in
+				cf.cf_expr <- Some {ef with eexpr = TFunction {f with tf_expr = e}};
+			| _ ->
+				(* TODO: is this correct? *)
+				()
+		end;
+		gen_func_expr ctx (match cf.cf_expr with None -> assert false | Some e -> e) c "__init__" py_metas ["self"] "\t" false;
+		newline ctx
 
 	let gen_class_field ctx c p cf =
 		let field = handle_keywords cf.cf_name in
@@ -1656,7 +1590,10 @@ module Generator = struct
 			) c.cl_implements in
 			spr ctx ":";
 			open_block ctx;
-			gen_class_constructor ctx c;
+			begin match c.cl_constructor with
+				| Some cf -> gen_class_constructor ctx c cf;
+				| None -> ()
+			end;
 			List.iter (fun cf -> gen_class_field ctx c p cf) c.cl_ordered_fields;
 			let x = collect_class_field_data c.cl_ordered_fields in
 			let use_pass = match x.cfd_methods with
@@ -1715,9 +1652,42 @@ module Generator = struct
 		print ctx "_hx_c.%s = %s\n" p p;
 		gen_enum_metadata ctx en p
 
+	let gen_abstract ctx a =
+		gen_pre_code_meta ctx a.a_meta;
+		print ctx "# print %s.%s\n" (s_type_path a.a_module.m_path) (snd a.a_path);
+		let mt = (t_infos (TAbstractDecl a)) in
+		let p = get_path mt in
+		let p_name = get_full_name mt in
+		print ctx "class %s" p;
+		spr ctx ":";
+		open_block ctx;
+		begin match a.a_impl with
+			| Some c ->
+				List.iter (fun cf ->
+					if cf.cf_name = "_new" then
+						gen_class_constructor ctx c cf
+					else
+						gen_class_field ctx c p cf
+				) c.cl_ordered_statics;
+			| None ->
+				spr_line ctx "\tpass";
+		end;
+		close_block ctx;
+		print ctx "%s._hx_class = %s\n" p p;
+		print ctx "%s._hx_class_name = \"%s\"\n" p p_name;
+		print ctx "_hx_classes[\"%s\"] = %s\n" p_name p;
+		print ctx "_hx_c.%s = %s\n" p p
+
+(* 	Bool._hx_class_name = 'Bool'
+Bool._hx_class = Bool
+
+_hx_classes['Bool'] = Bool
+_hx_c.Bool = Bool	 *)
+
 	let gen_type ctx mt = match mt with
 		| TClassDecl c -> gen_class ctx c
 		| TEnumDecl en -> gen_enum ctx en
+		| TAbstractDecl a when Meta.has Meta.CoreType a.a_meta -> gen_abstract ctx a
 		| _ -> ()
 
 	(* Generator parts *)
@@ -1742,18 +1712,22 @@ module Generator = struct
 		(* TODO: ... *)
 		spr ctx bootcode
 
-	let gen_boot_class ctx =
-		let boot = List.find (fun mt -> match mt with
-			| TClassDecl {cl_path = ["python"],"Boot"} -> true
-			| _ -> false
-		) ctx.com.types in
-		gen_type ctx boot
-
 	let gen_types ctx =
-		List.iter (fun mt -> match mt with
-			| TClassDecl {cl_path = ["python"],"Boot"} ->
-				()
-			| _ ->
+		let used_paths = Hashtbl.create 0 in
+		let find_type path =
+			Hashtbl.add used_paths path true;
+			try
+				List.find (fun mt -> match mt with
+					| TAbstractDecl _ -> false
+					| _ -> (t_infos mt).mt_path = path
+				) ctx.com.types
+			with Not_found ->
+				error (Printf.sprintf "Could not find type %s\n" (s_type_path path)) null_pos;
+		in
+		gen_type ctx (find_type (["python"],"Boot"));
+		gen_type ctx (find_type ([],"Enum"));
+		List.iter (fun mt ->
+			if not (Hashtbl.mem used_paths (t_infos mt).mt_path) then
 				gen_type ctx mt
 		) ctx.com.types
 
@@ -1773,7 +1747,7 @@ module Generator = struct
 		let ctx = mk_context com in
 		gen_resources ctx;
 		gen_boot_code ctx;
-		gen_boot_class ctx;
+		(* gen_boot_class ctx; *)
 		gen_types ctx;
 		gen_static_inits ctx;
 		gen_main ctx;

+ 42 - 41
std/python/Boot.hx

@@ -2,6 +2,7 @@
 package python;
 
 import python.lib.Builtin;
+import python.internal.EnumImpl;
 
 @:keep class Boot {
 
@@ -12,7 +13,7 @@ import python.lib.Builtin;
 		Macros.importAs("inspect", "inspect");
 		Boot.inspect = untyped __python__("inspect");
 		Boot.builtin = untyped __python__("_hx_builtin");
-		
+
 
 	}
 
@@ -26,25 +27,25 @@ import python.lib.Builtin;
     }
 
 
-    @:keep private static function _add_dynamic(a:Dynamic,b:Dynamic):Dynamic 
+    @:keep private static function _add_dynamic(a:Dynamic,b:Dynamic):Dynamic
     {
 		if (builtin.isinstance(a, untyped __python__("str")) || builtin.isinstance(b, untyped __python__("str"))) {
 			return __string_rec(a,"") + __string_rec(b,"");
 		}
 		return untyped __python__("a+b");
     }
-	
+
 	@:keep private static function __string_rec(o:Dynamic,s:String):String {
-		
-		
+
+
 
 		if (s == null) s = "";
 		if( o == null ) return "null";
-		
+
 		if( s.length >= 5 ) return "<...>"; // too much deep recursion
-		
-		
-		
+
+
+
 
 		if (builtin.isinstance(o, untyped __python__("str"))) return o;
 
@@ -58,7 +59,7 @@ import python.lib.Builtin;
 		if (builtin.isinstance(o, untyped __python__("float"))) {
 			try {
 				if (o == Builtin.int(o)) {
-					return builtin.str(Math.round(o));	
+					return builtin.str(Math.round(o));
 				} else {
 					return builtin.str(o);
 				}
@@ -66,18 +67,18 @@ import python.lib.Builtin;
 				return builtin.str(o);
 			}
 		}
-		
+
 
 		if (inspect.isfunction(o) || inspect.ismethod(o)) return "<function>";
-		
-		
-		
-		
-		if (builtin.isinstance(o, Array)) 
+
+
+
+
+		if (builtin.isinstance(o, Array))
 		{
 			var o1:Array<Dynamic> = o;
 			var l = o1.length;
-			
+
 			var st = "[";
 			s += "\t";
 			for( i in 0...l ) {
@@ -97,37 +98,37 @@ import python.lib.Builtin;
 		} catch (e:Dynamic) {
 
 		}
-		
-		if (builtin.hasattr(o, "__class__")) 
+
+		if (builtin.hasattr(o, "__class__"))
 		{
 
-			if (builtin.isinstance(o, untyped __python__("_hx_c._hx_AnonObject"))) 
+			if (builtin.isinstance(o, untyped __python__("_hx_c._hx_AnonObject")))
 			{
 				var toStr = null;
-				try 
+				try
 				{
 					var fields = Reflect.fields(o);
 					var fieldsStr = [for (f in fields) '$f : ${__string_rec(Reflect.field(o,f), s+"\t")}'];
-					
+
 					toStr = "{ " + fieldsStr.join(", ") + " }";
-				} 
+				}
 				catch (e:Dynamic) {
 					trace(e);
 				}
 
-				if (toStr == null) 
+				if (toStr == null)
 				{
-					return "{ ... }";	
-				} 
-				else 
+					return "{ ... }";
+				}
+				else
 				{
-					return toStr;	
+					return toStr;
 				}
-				
+
 			}
 			if (builtin.isinstance(o, untyped __python__("_hx_c.Enum"))) {
-				
-				
+
+
 				var l = builtin.len(o.params);
 				var hasParams = l > 0;
 				if (hasParams) {
@@ -150,7 +151,7 @@ import python.lib.Builtin;
 
 				var fields = Type.getInstanceFields(o);
 				var fieldsStr = [for (f in fields) '$f : ${__string_rec(Reflect.field(o,f), s+"\t")}'];
-				
+
 				var toStr = o._hx_class_name + "( " + fieldsStr.join(", ") + " )";
 				return toStr;
 			}
@@ -159,21 +160,21 @@ import python.lib.Builtin;
 
 				var fields = Type.getClassFields(o);
 				var fieldsStr = [for (f in fields) '$f : ${__string_rec(Reflect.field(o,f), s+"\t")}'];
-					
+
 				var toStr = "#" + o._hx_class_name + "( " + fieldsStr.join(", ") + " )";
 				return toStr;
 			}
 			if (o == String) {
 				return "#String";
 			}
-			
+
 			//if (builtin.hasattr(o, "_hx_name")) {
 			//	return "#" + untyped o._hx_name;
 			//}
 			if (o == Array) {
 				return "#Array";
 			}
-			
+
 			if (builtin.callable(o)) {
 				return "function";
 			}
@@ -192,8 +193,8 @@ import python.lib.Builtin;
 			}
 			return "???";
 
-			
-			
+
+
 
 
 
@@ -205,10 +206,10 @@ import python.lib.Builtin;
 				return "???";
 			}
 		}
-	
-	
-			
-		
+
+
+
+
 	}
 
 }

+ 23 - 0
std/python/internal/EnumImpl.hx

@@ -0,0 +1,23 @@
+package python.internal;
+
+@:keep
+@:native("Enum")
+class EnumImpl {
+	public var tag:String;
+	public var index:Int;
+	public var params:Array<Dynamic>;
+
+	public function new(tag, index, params) {
+		this.tag = tag;
+		this.index = index;
+		this.params = params;
+	}
+
+	function __str__() untyped {
+		return if (self.params == null) {
+			tag;
+		} else {
+			tag + "(" + params.join(",") + ")";
+		}
+	}
+}