Browse Source

Merge remote-tracking branch 'remotes/upstream/development' into bridgeProperties

杨博 11 years ago
parent
commit
33e66c1e17
100 changed files with 2284 additions and 884 deletions
  1. 1 0
      .gitignore
  2. 17 26
      .travis.yml
  3. 9 7
      Makefile
  4. 5 0
      ast.ml
  5. 36 13
      codegen.ml
  6. 17 8
      common.ml
  7. 40 2
      extra/CHANGES.txt
  8. 12 2
      extra/extract.patch
  9. 6 3
      filters.ml
  10. 97 26
      gencommon.ml
  11. 313 91
      gencpp.ml
  12. 67 10
      gencs.ml
  13. 3 1
      genjava.ml
  14. 24 2
      genjs.ml
  15. 505 238
      genpy.ml
  16. 3 0
      haxe.hxproj
  17. 28 5
      interp.ml
  18. 45 20
      main.ml
  19. 29 18
      parser.ml
  20. 39 48
      std/Math.hx
  21. 31 33
      std/StringTools.hx
  22. 19 0
      std/cpp/BasePointer.hx
  23. 3 0
      std/cpp/Char.hx
  24. 19 0
      std/cpp/ConstPointer.hx
  25. 3 0
      std/cpp/Float32.hx
  26. 3 0
      std/cpp/Float64.hx
  27. 20 0
      std/cpp/Function.hx
  28. 3 0
      std/cpp/Int16.hx
  29. 3 0
      std/cpp/Int32.hx
  30. 3 0
      std/cpp/Int64.hx
  31. 3 0
      std/cpp/Int8.hx
  32. 12 0
      std/cpp/NativeString.hx
  33. 18 9
      std/cpp/Pointer.hx
  34. 3 0
      std/cpp/UInt16.hx
  35. 3 0
      std/cpp/UInt32.hx
  36. 3 0
      std/cpp/UInt64.hx
  37. 3 0
      std/cpp/UInt8.hx
  38. 1 1
      std/cpp/vm/Deque.hx
  39. 7 0
      std/cpp/vm/Gc.hx
  40. 3 0
      std/cs/_std/Array.hx
  41. 3 0
      std/cs/_std/Date.hx
  42. 2 0
      std/cs/_std/EReg.hx
  43. 13 0
      std/cs/_std/Type.hx
  44. 6 0
      std/cs/internal/HxObject.hx
  45. 4 1
      std/cs/internal/Null.hx
  46. 6 5
      std/cs/internal/Runtime.hx
  47. 1 1
      std/flash/display/Stage3D.hx
  48. 4 4
      std/flash/display3D/Context3D.hx
  49. 6 0
      std/flash/display3D/Context3DBufferUsage.hx
  50. 1 0
      std/flash/display3D/Context3DProfile.hx
  51. 4 0
      std/flash/display3D/Context3DTextureFilter.hx
  52. 1 0
      std/flash/display3D/Context3DTextureFormat.hx
  53. 2 0
      std/flash/display3D/Context3DWrapMode.hx
  54. 0 15
      std/flash/utils/Telemetry.hx
  55. 85 0
      std/haxe/crypto/Hmac.hx
  56. 197 0
      std/haxe/crypto/Sha256.hx
  57. 13 5
      std/haxe/ds/Vector.hx
  58. 5 4
      std/haxe/format/JsonPrinter.hx
  59. 6 0
      std/haxe/io/Path.hx
  60. 6 2
      std/haxe/macro/Compiler.hx
  61. 1 0
      std/haxe/rtti/CType.hx
  62. 10 0
      std/haxe/web/Dispatch.hx
  63. 16 1
      std/java/Lib.hx
  64. 11 0
      std/js/Lib.hx
  65. 87 0
      std/js/_std/Math.hx
  66. 2 2
      std/neko/_std/Date.hx
  67. 1 1
      std/neko/vm/Deque.hx
  68. 135 77
      std/python/Boot.hx
  69. 1 1
      std/python/KwArgs.hx
  70. 7 6
      std/python/Lib.hx
  71. 4 6
      std/python/NativeIterable.hx
  72. 3 4
      std/python/NativeIterator.hx
  73. 11 11
      std/python/Syntax.hx
  74. 8 10
      std/python/_std/Array.hx
  75. 1 2
      std/python/_std/Math.hx
  76. 2 0
      std/python/_std/Reflect.hx
  77. 18 12
      std/python/_std/Std.hx
  78. 2 7
      std/python/_std/String.hx
  79. 2 2
      std/python/_std/StringBuf.hx
  80. 5 7
      std/python/_std/haxe/ds/StringMap.hx
  81. 9 3
      std/python/internal/AnonObject.hx
  82. 21 21
      std/python/internal/ArrayImpl.hx
  83. 38 0
      std/python/internal/HxBuiltin.hx
  84. 11 7
      std/python/internal/HxOverrides.hx
  85. 16 11
      std/python/internal/Internal.hx
  86. 13 13
      std/python/internal/StringImpl.hx
  87. 7 7
      std/python/io/IoTools.hx
  88. 4 4
      std/python/lib/Builtin.hx
  89. 1 6
      std/python/lib/Bytes.hx
  90. 1 3
      std/python/lib/Codecs.hx
  91. 3 16
      std/python/lib/Dict.hx
  92. 1 1
      std/python/lib/FuncTools.hx
  93. 1 7
      std/python/lib/Glob.hx
  94. 1 5
      std/python/lib/Inspect.hx
  95. 1 4
      std/python/lib/Json.hx
  96. 1 5
      std/python/lib/Math.hx
  97. 1 7
      std/python/lib/Msvcrt.hx
  98. 1 6
      std/python/lib/Os.hx
  99. 1 4
      std/python/lib/PPrint.hx
  100. 1 5
      std/python/lib/Random.hx

+ 1 - 0
.gitignore

@@ -57,6 +57,7 @@ build.bat
 tests/unit/compile.php.hxml
 tests/unit/compile.php.hxml
 /extra/*.xml
 /extra/*.xml
 tests/optimization/testopt.js
 tests/optimization/testopt.js
+tests/unit/native_python/__pycache__
 tests/unit/unit.py
 tests/unit/unit.py
 tests/unit/unit.py.res1.txt
 tests/unit/unit.py.res1.txt
 tests/unit/unit.py.res2.bin
 tests/unit/unit.py.res2.bin

+ 17 - 26
.travis.yml

@@ -7,46 +7,37 @@ env:
     # SAUCE_ACCESS_KEY
     # SAUCE_ACCESS_KEY
     - secure: sUvWUjCyPuWht4seNa4f2VG9DkvXkhZyLZfjJO9TUAHB2JndS16E2j/qrvKEjycyH6w8tU/B9vnjDRvvGrYXxEXcBEwsJVfkorFnRl9uwGCGIYrzjMhssEl3fMYZK7P304f+gAp5ULrDBX2gIaKeSa8lUNRtz2PsZOieE4kMdhk=
     - secure: sUvWUjCyPuWht4seNa4f2VG9DkvXkhZyLZfjJO9TUAHB2JndS16E2j/qrvKEjycyH6w8tU/B9vnjDRvvGrYXxEXcBEwsJVfkorFnRl9uwGCGIYrzjMhssEl3fMYZK7P304f+gAp5ULrDBX2gIaKeSa8lUNRtz2PsZOieE4kMdhk=
   matrix:
   matrix:
-    - TARGET=macro
-    - TARGET=neko
-    - TARGET=js
-    - TARGET=php
-    - TARGET=cpp
-    - TARGET=flash9
-    - TARGET=as3
-    - TARGET=java
-    - TARGET=cs
-    - TARGET=python
-    - TARGET=flash8
-    - TARGET=neko-sys
-    - TARGET=python-sys
-    - TARGET=cpp-sys
-    - TARGET=misc
-    - TARGET=polygonal-ds
-    - TARGET=flambe
-    - TARGET=hxtemplo
-    - TARGET=munit
-    - TARGET=openfl-samples
-    - TARGET=flixel-demos
-    - TARGET=bytecode
+    - TEST=third-party
+    - TEST=macro
+    - TEST=neko
+    - TEST=js
+    - TEST=php
+    - TEST=cpp
+    - TEST=flash9
+    - TEST=as3
+    - TEST=java
+    - TEST=cs
+    - TEST=python
+    - TEST=flash8
 
 
 matrix:
 matrix:
   fast_finish: true
   fast_finish: true
   allow_failures:
   allow_failures:
-    - env: TARGET=flash8
+    - env: TEST=flash8
 
 
-before_install:
+install:
   - travis_retry sudo apt-get update
   - travis_retry sudo apt-get update
   - travis_retry sudo apt-get install ocaml zlib1g-dev libgc-dev -y
   - travis_retry sudo apt-get install ocaml zlib1g-dev libgc-dev -y
   - travis_retry git clone https://github.com/HaxeFoundation/neko.git ~/neko
   - travis_retry git clone https://github.com/HaxeFoundation/neko.git ~/neko
   - cd ~/neko && make && sudo make install && cd $TRAVIS_BUILD_DIR
   - cd ~/neko && make && sudo make install && cd $TRAVIS_BUILD_DIR
 
 
 script:
 script:
-  - /bin/sh -c '[ $TARGET = "bytecode" ] && make BYTECODE=1 || make'
+  - make
   - make tools
   - make tools
   - sudo make install
   - sudo make install
   - cd tests/
   - cd tests/
   - mkdir ~/haxelib && haxelib setup ~/haxelib
   - mkdir ~/haxelib && haxelib setup ~/haxelib
   - haxelib git hx-yaml https://github.com/mikestead/hx-yaml master src
   - haxelib git hx-yaml https://github.com/mikestead/hx-yaml master src
   - haxe -version
   - haxe -version
-  - haxe -main RunTravis -lib hx-yaml --interp
+  - haxe -neko RunTravis.n -main RunTravis -lib hx-yaml
+  - neko RunTravis.n

+ 9 - 7
Makefile

@@ -30,18 +30,20 @@ NATIVE_LIBS=-cclib libs/extc/extc_stubs.o -cclib -lz -cclib libs/objsize/c_objsi
 
 
 ifeq ($(BYTECODE),1)
 ifeq ($(BYTECODE),1)
 	TARGET_FLAG = bytecode
 	TARGET_FLAG = bytecode
-	CC_CMD = $(OCAMLC)
+	COMPILER = $(OCAMLC)
 	LIB_EXT = cma
 	LIB_EXT = cma
 	MODULE_EXT = cmo
 	MODULE_EXT = cmo
 	NATIVE_LIB_FLAG = -custom
 	NATIVE_LIB_FLAG = -custom
 else
 else
 	TARGET_FLAG = native
 	TARGET_FLAG = native
-	CC_CMD = $(OCAMLOPT)
+	COMPILER = $(OCAMLOPT)
 	LIB_EXT = cmxa
 	LIB_EXT = cmxa
 	MODULE_EXT = cmx
 	MODULE_EXT = cmx
 endif
 endif
 
 
-CC_PARSER_CMD = $(CC_CMD) -pp camlp4o $(CFLAGS) -c parser.ml
+CC_CMD = $(COMPILER) $(CFLAGS) -c $<
+
+CC_PARSER_CMD = $(COMPILER) -pp camlp4o $(CFLAGS) -c parser.ml
 
 
 RELDIR=../../..
 RELDIR=../../..
 
 
@@ -79,7 +81,7 @@ libs:
 	make -C libs/objsize OCAMLOPT=$(OCAMLOPT) OCAMLC=$(OCAMLC) $(TARGET_FLAG)
 	make -C libs/objsize OCAMLOPT=$(OCAMLOPT) OCAMLC=$(OCAMLC) $(TARGET_FLAG)
 
 
 haxe: $(MODULES:=.$(MODULE_EXT))
 haxe: $(MODULES:=.$(MODULE_EXT))
-	$(CC_CMD) -o $(OUTPUT) $(NATIVE_LIBS) $(NATIVE_LIB_FLAG) $(LFLAGS) $(LIBS:=.$(LIB_EXT)) $(MODULES:=.$(MODULE_EXT))
+	$(COMPILER) -o $(OUTPUT) $(NATIVE_LIBS) $(NATIVE_LIB_FLAG) $(LFLAGS) $(LIBS:=.$(LIB_EXT)) $(MODULES:=.$(MODULE_EXT))
 
 
 haxelib:
 haxelib:
 	(cd $(CURDIR)/extra/haxelib_src && $(CURDIR)/$(OUTPUT) haxelib.hxml && nekotools boot bin/haxelib.n)
 	(cd $(CURDIR)/extra/haxelib_src && $(CURDIR)/$(OUTPUT) haxelib.hxml && nekotools boot bin/haxelib.n)
@@ -175,7 +177,7 @@ ast.$(MODULE_EXT):
 
 
 version.$(MODULE_EXT):
 version.$(MODULE_EXT):
 	echo $(VERSION_EXTRA) > version.ml
 	echo $(VERSION_EXTRA) > version.ml
-	$(CC_CMD) $(CFLAGS) -c version.ml
+	$(COMPILER) $(CFLAGS) -c version.ml
 
 
 # Clean
 # Clean
 
 
@@ -202,10 +204,10 @@ clean_tools:
 # SUFFIXES
 # SUFFIXES
 
 
 .ml.cmx:
 .ml.cmx:
-	$(CC_CMD) $(CFLAGS) -c $<
+	$(CC_CMD)
 
 
 .ml.cmo:
 .ml.cmo:
-	$(CC_CMD) $(CFLAGS) -c $<
+	$(CC_CMD)
 
 
 .mll.ml:
 .mll.ml:
 	ocamllex $<
 	ocamllex $<

+ 5 - 0
ast.ml

@@ -84,11 +84,13 @@ module Meta = struct
 		| HxGen
 		| HxGen
 		| IfFeature
 		| IfFeature
 		| Impl
 		| Impl
+		| PythonImport
 		| Include
 		| Include
 		| InitPackage
 		| InitPackage
 		| Internal
 		| Internal
 		| IsVar
 		| IsVar
 		| JavaNative
 		| JavaNative
+		| JsRequire
 		| Keep
 		| Keep
 		| KeepInit
 		| KeepInit
 		| KeepSub
 		| KeepSub
@@ -98,6 +100,7 @@ module Meta = struct
 		| MergeBlock
 		| MergeBlock
 		| MultiType
 		| MultiType
 		| Native
 		| Native
+		| NativeChildren
 		| NativeGen
 		| NativeGen
 		| NativeGeneric
 		| NativeGeneric
 		| NoCompletion
 		| NoCompletion
@@ -131,6 +134,7 @@ module Meta = struct
 		| SkipReflection
 		| SkipReflection
 		| Sound
 		| Sound
 		| Struct
 		| Struct
+		| StructAccess
 		| SuppressWarnings
 		| SuppressWarnings
 		| This
 		| This
 		| Throws
 		| Throws
@@ -145,6 +149,7 @@ module Meta = struct
 		| Unsafe
 		| Unsafe
 		| Usage
 		| Usage
 		| Used
 		| Used
+		| Void
 		| Last
 		| Last
 		(* do not put any custom metadata after Last *)
 		(* do not put any custom metadata after Last *)
 		| Dollar of string
 		| Dollar of string

+ 36 - 13
codegen.ml

@@ -298,7 +298,7 @@ let rec build_generic ctx c p tl =
 	if !recurse then begin
 	if !recurse then begin
 		TInst (c,tl) (* build a normal instance *)
 		TInst (c,tl) (* build a normal instance *)
 	end else begin
 	end else begin
-	let gctx = try make_generic ctx c.cl_types tl p with Generic_Exception (msg,p) -> error msg p in
+	let gctx = make_generic ctx c.cl_types tl p in
 	let name = (snd c.cl_path) ^ "_" ^ gctx.name in
 	let name = (snd c.cl_path) ^ "_" ^ gctx.name in
 	try
 	try
 		Typeload.load_instance ctx { tpackage = pack; tname = name; tparams = []; tsub = None } p false
 		Typeload.load_instance ctx { tpackage = pack; tname = name; tparams = []; tsub = None } p false
@@ -648,13 +648,13 @@ module Abstract = struct
 
 
 	let find_to ab pl b =
 	let find_to ab pl b =
 		if follow b == t_dynamic then
 		if follow b == t_dynamic then
-			List.find (fun (t,_) -> t == t_dynamic) ab.a_to
+			List.find (fun (t,_) -> follow t == t_dynamic) ab.a_to
 		else
 		else
 			List.find (Type.unify_to_field ab pl b) ab.a_to
 			List.find (Type.unify_to_field ab pl b) ab.a_to
 
 
 	let find_from ab pl a b =
 	let find_from ab pl a b =
 		if follow a == t_dynamic then
 		if follow a == t_dynamic then
-			List.find (fun (t,_) -> t == t_dynamic) ab.a_from
+			List.find (fun (t,_) -> follow t == t_dynamic) ab.a_from
 		else
 		else
 			List.find (Type.unify_from_field ab pl a b) ab.a_from
 			List.find (Type.unify_from_field ab pl a b) ab.a_from
 
 
@@ -913,21 +913,44 @@ let detect_usage com =
 	let usage = ref [] in
 	let usage = ref [] in
 	List.iter (fun t -> match t with
 	List.iter (fun t -> match t with
 		| TClassDecl c ->
 		| TClassDecl c ->
+			let check_constructor c p =
+				try
+					let _,cf = get_constructor (fun cf -> cf.cf_type) c in
+					if Meta.has Meta.Usage cf.cf_meta then
+						usage := p :: !usage;
+				with Not_found ->
+					()
+			in
 			let rec expr e = match e.eexpr with
 			let rec expr e = match e.eexpr with
-				| TField(_,fa) ->
-					begin match extract_field fa with
-						| Some cf when Meta.has Meta.Usage cf.cf_meta ->
-							let p = {e.epos with pmin = e.epos.pmax - (String.length cf.cf_name)} in
-							usage := p :: !usage;
-						| _ ->
-							()
-					end;
+				| TField(_,FEnum(_,ef)) when Meta.has Meta.Usage ef.ef_meta ->
+					let p = {e.epos with pmin = e.epos.pmax - (String.length ef.ef_name)} in
+					usage := p :: !usage;
+					Type.iter expr e
+				| TField(_,(FAnon cf | FInstance (_,cf) | FStatic (_,cf) | FClosure (_,cf))) when Meta.has Meta.Usage cf.cf_meta ->
+					let p = {e.epos with pmin = e.epos.pmax - (String.length cf.cf_name)} in
+					usage := p :: !usage;
 					Type.iter expr e
 					Type.iter expr e
 				| TLocal v when Meta.has Meta.Usage v.v_meta ->
 				| TLocal v when Meta.has Meta.Usage v.v_meta ->
 					usage := e.epos :: !usage
 					usage := e.epos :: !usage
+				| TVar (v,_) when com.display = DMPosition && Meta.has Meta.Usage v.v_meta ->
+					raise (Typecore.DisplayPosition [e.epos])
+				| TFunction tf when com.display = DMPosition && List.exists (fun (v,_) -> Meta.has Meta.Usage v.v_meta) tf.tf_args ->
+					raise (Typecore.DisplayPosition [e.epos])
+				| TTypeExpr mt when (Meta.has Meta.Usage (t_infos mt).mt_meta) ->
+					usage := e.epos :: !usage
+				| TNew (c,_,_) ->
+					check_constructor c e.epos;
+					Type.iter expr e;
+				| TCall({eexpr = TConst TSuper},_) ->
+					begin match c.cl_super with
+						| Some (c,_) ->
+							check_constructor c e.epos
+						| _ ->
+							()
+					end
 				| _ -> Type.iter expr e
 				| _ -> Type.iter expr e
 			in
 			in
-			let field cf = match cf.cf_expr with None -> () | Some e -> expr e in
+			let field cf = ignore(follow cf.cf_type); match cf.cf_expr with None -> () | Some e -> expr e in
 			(match c.cl_constructor with None -> () | Some cf -> field cf);
 			(match c.cl_constructor with None -> () | Some cf -> field cf);
 			(match c.cl_init with None -> () | Some e -> expr e);
 			(match c.cl_init with None -> () | Some e -> expr e);
 			List.iter field c.cl_ordered_statics;
 			List.iter field c.cl_ordered_statics;
@@ -1710,4 +1733,4 @@ module DeprecationCheck = struct
 			| _ ->
 			| _ ->
 				()
 				()
 		) com.types
 		) com.types
-end
+end

+ 17 - 8
common.ml

@@ -104,8 +104,8 @@ type display_mode =
 	| DMNone
 	| DMNone
 	| DMDefault
 	| DMDefault
 	| DMUsage
 	| DMUsage
-	| DMMetadata
 	| DMPosition
 	| DMPosition
+	| DMToplevel
 
 
 type context = {
 type context = {
 	(* config *)
 	(* config *)
@@ -168,6 +168,7 @@ module Define = struct
 		| As3
 		| As3
 		| CheckXmlProxy
 		| CheckXmlProxy
 		| CoreApi
 		| CoreApi
+		| CoreApiSerialize
 		| Cppia
 		| Cppia
 		| Dce
 		| Dce
 		| DceDebug
 		| DceDebug
@@ -228,6 +229,7 @@ module Define = struct
 		| SwfScriptTimeout
 		| SwfScriptTimeout
 		| SwfUseDoAbc
 		| SwfUseDoAbc
 		| Sys
 		| Sys
+		| UnityStdTarget
 		| Unsafe
 		| Unsafe
 		| UseNekoc
 		| UseNekoc
 		| UseRttiDoc
 		| UseRttiDoc
@@ -241,6 +243,7 @@ module Define = struct
 		| As3 -> ("as3","Defined when outputing flash9 as3 source code")
 		| As3 -> ("as3","Defined when outputing flash9 as3 source code")
 		| CheckXmlProxy -> ("check_xml_proxy","Check the used fields of the xml proxy")
 		| CheckXmlProxy -> ("check_xml_proxy","Check the used fields of the xml proxy")
 		| CoreApi -> ("core_api","Defined in the core api context")
 		| CoreApi -> ("core_api","Defined in the core api context")
+		| CoreApiSerialize -> ("core_api_serialize","Sets so some generated core api classes be marked with the Serializable attribute on C#")
 		| Cppia -> ("cppia", "Generate experimental cpp instruction assembly")
 		| Cppia -> ("cppia", "Generate experimental cpp instruction assembly")
 		| Dce -> ("dce","The current DCE mode")
 		| Dce -> ("dce","The current DCE mode")
 		| DceDebug -> ("dce_debug","Show DCE log")
 		| DceDebug -> ("dce_debug","Show DCE log")
@@ -302,6 +305,7 @@ module Define = struct
 		| SwfScriptTimeout -> ("swf_script_timeout", "Maximum ActionScript processing time before script stuck dialog box displays (in seconds)")
 		| SwfScriptTimeout -> ("swf_script_timeout", "Maximum ActionScript processing time before script stuck dialog box displays (in seconds)")
 		| SwfUseDoAbc -> ("swf_use_doabc", "Use DoAbc swf-tag instead of DoAbcDefine")
 		| SwfUseDoAbc -> ("swf_use_doabc", "Use DoAbc swf-tag instead of DoAbcDefine")
 		| Sys -> ("sys","Defined for all system platforms")
 		| Sys -> ("sys","Defined for all system platforms")
+		| UnityStdTarget -> ("unity_std_target", "Changes C# sources location so that each generated C# source is relative to the Haxe source location. If the location is outside the current directory, the value set here will be used")
 		| Unsafe -> ("unsafe","Allow unsafe code when targeting C#")
 		| Unsafe -> ("unsafe","Allow unsafe code when targeting C#")
 		| UseNekoc -> ("use_nekoc","Use nekoc compiler instead of internal one")
 		| UseNekoc -> ("use_nekoc","Use nekoc compiler instead of internal one")
 		| UseRttiDoc -> ("use_rtti_doc","Allows access to documentation during compilation")
 		| UseRttiDoc -> ("use_rtti_doc","Allows access to documentation during compilation")
@@ -386,11 +390,13 @@ module MetaInfo = struct
 		| HxGen -> ":hxGen",("Annotates that an extern class was generated by Haxe",[Platforms [Java;Cs]; UsedOnEither [TClass;TEnum]])
 		| HxGen -> ":hxGen",("Annotates that an extern class was generated by Haxe",[Platforms [Java;Cs]; UsedOnEither [TClass;TEnum]])
 		| IfFeature -> ":ifFeature",("Causes a field to be kept by DCE if the given feature is part of the compilation",[HasParam "Feature name";UsedOn TClassField])
 		| IfFeature -> ":ifFeature",("Causes a field to be kept by DCE if the given feature is part of the compilation",[HasParam "Feature name";UsedOn TClassField])
 		| Impl -> ":impl",("Used internally to mark abstract implementation fields",[UsedOn TAbstractField; Internal])
 		| Impl -> ":impl",("Used internally to mark abstract implementation fields",[UsedOn TAbstractField; Internal])
+		| PythonImport -> ":pythonImport",("Generates python import statement for extern classes",[Platforms [Python]; UsedOn TClass])
 		| Include -> ":include",("",[Platform Cpp])
 		| Include -> ":include",("",[Platform Cpp])
 		| InitPackage -> ":initPackage",("?",[])
 		| InitPackage -> ":initPackage",("?",[])
 		| Meta.Internal -> ":internal",("Generates the annotated field/class with 'internal' access",[Platforms [Java;Cs]; UsedOnEither[TClass;TEnum;TClassField]])
 		| Meta.Internal -> ":internal",("Generates the annotated field/class with 'internal' access",[Platforms [Java;Cs]; UsedOnEither[TClass;TEnum;TClassField]])
 		| IsVar -> ":isVar",("Forces a physical field to be generated for properties that otherwise would not require one",[UsedOn TClassField])
 		| IsVar -> ":isVar",("Forces a physical field to be generated for properties that otherwise would not require one",[UsedOn TClassField])
 		| JavaNative -> ":javaNative",("Automatically added by -java-lib on classes generated from JAR/class files",[Platform Java; UsedOnEither[TClass;TEnum]; Internal])
 		| JavaNative -> ":javaNative",("Automatically added by -java-lib on classes generated from JAR/class files",[Platform Java; UsedOnEither[TClass;TEnum]; Internal])
+		| JsRequire -> ":jsRequire",("Generate javascript module require expression for given extern",[Platform Js; UsedOn TClass])
 		| Keep -> ":keep",("Causes a field or type to be kept by DCE",[])
 		| Keep -> ":keep",("Causes a field or type to be kept by DCE",[])
 		| KeepInit -> ":keepInit",("Causes a class to be kept by DCE even if all its field are removed",[UsedOn TClass])
 		| KeepInit -> ":keepInit",("Causes a class to be kept by DCE even if all its field are removed",[UsedOn TClass])
 		| KeepSub -> ":keepSub",("Extends @:keep metadata to all implementing and extending classes",[UsedOn TClass])
 		| KeepSub -> ":keepSub",("Extends @:keep metadata to all implementing and extending classes",[UsedOn TClass])
@@ -400,7 +406,8 @@ module MetaInfo = struct
 		| MergeBlock -> ":mergeBlock",("Internally used by typer to mark block that should be merged into the outer scope",[Internal])
 		| MergeBlock -> ":mergeBlock",("Internally used by typer to mark block that should be merged into the outer scope",[Internal])
 		| MultiType -> ":multiType",("Specifies that an abstract chooses its this-type from its @:to functions",[UsedOn TAbstract; HasParam "Relevant type parameters"])
 		| MultiType -> ":multiType",("Specifies that an abstract chooses its this-type from its @:to functions",[UsedOn TAbstract; HasParam "Relevant type parameters"])
 		| Native -> ":native",("Rewrites the path of a class or enum during generation",[HasParam "Output type path";UsedOnEither [TClass;TEnum]])
 		| Native -> ":native",("Rewrites the path of a class or enum during generation",[HasParam "Output type path";UsedOnEither [TClass;TEnum]])
-		| NativeGen -> ":nativeGen",("Annotates that a type should be treated as if it were an extern definition - platform native",[Platforms [Java;Cs]; UsedOnEither[TClass;TEnum]])
+		| NativeChildren -> ":nativeChildren",("Annotates that all children from a type should be treated as if it were an extern definition - platform native",[Platforms [Java;Cs]; UsedOn TClass])
+		| NativeGen -> ":nativeGen",("Annotates that a type should be treated as if it were an extern definition - platform native",[Platforms [Java;Cs;Python]; UsedOnEither[TClass;TEnum]])
 		| NativeGeneric -> ":nativeGeneric",("Used internally to annotate native generic classes",[Platform Cs; UsedOnEither[TClass;TEnum]; Internal])
 		| NativeGeneric -> ":nativeGeneric",("Used internally to annotate native generic classes",[Platform Cs; UsedOnEither[TClass;TEnum]; Internal])
 		| NoCompletion -> ":noCompletion",("Prevents the compiler from suggesting completion on this field",[UsedOn TClassField])
 		| NoCompletion -> ":noCompletion",("Prevents the compiler from suggesting completion on this field",[UsedOn TClassField])
 		| NoDebug -> ":noDebug",("Does not generate debug information into the Swf even if -debug is set",[UsedOnEither [TClass;TClassField];Platform Flash])
 		| NoDebug -> ":noDebug",("Does not generate debug information into the Swf even if -debug is set",[UsedOnEither [TClass;TClassField];Platform Flash])
@@ -433,6 +440,7 @@ module MetaInfo = struct
 		| SkipReflection -> ":skipReflection",("Used internally to annotate a field that shouldn't have its reflection data generated",[Platforms [Java;Cs]; UsedOn TClassField; Internal])
 		| SkipReflection -> ":skipReflection",("Used internally to annotate a field that shouldn't have its reflection data generated",[Platforms [Java;Cs]; UsedOn TClassField; Internal])
 		| Sound -> ":sound",( "Includes a given .wav or .mp3 file into the target Swf and associates it with the class (must extend flash.media.Sound)",[HasParam "File path";UsedOn TClass;Platform Flash])
 		| Sound -> ":sound",( "Includes a given .wav or .mp3 file into the target Swf and associates it with the class (must extend flash.media.Sound)",[HasParam "File path";UsedOn TClass;Platform Flash])
 		| Struct -> ":struct",("Marks a class definition as a struct.",[Platform Cs; UsedOn TClass])
 		| Struct -> ":struct",("Marks a class definition as a struct.",[Platform Cs; UsedOn TClass])
+		| StructAccess -> ":structAccess",("Marks an extern class as using struct access('.') not pointer('->').",[Platform Cpp; UsedOn TClass])
 		| SuppressWarnings -> ":suppressWarnings",("Adds a SuppressWarnings annotation for the generated Java class",[Platform Java; UsedOn TClass])
 		| SuppressWarnings -> ":suppressWarnings",("Adds a SuppressWarnings annotation for the generated Java class",[Platform Java; UsedOn TClass])
 		| Throws -> ":throws",("Adds a 'throws' declaration to the generated function.",[HasParam "Type as String"; Platform Java; UsedOn TClassField])
 		| Throws -> ":throws",("Adds a 'throws' declaration to the generated function.",[HasParam "Type as String"; Platform Java; UsedOn TClassField])
 		| This -> ":this",("Internally used to pass a 'this' expression to macros",[Internal; UsedOn TExpr])
 		| This -> ":this",("Internally used to pass a 'this' expression to macros",[Internal; UsedOn TExpr])
@@ -447,6 +455,7 @@ module MetaInfo = struct
 		| Unsafe -> ":unsafe",("Declares a class, or a method with the C#'s 'unsafe' flag",[Platform Cs; UsedOnEither [TClass;TClassField]])
 		| Unsafe -> ":unsafe",("Declares a class, or a method with the C#'s 'unsafe' flag",[Platform Cs; UsedOnEither [TClass;TClassField]])
 		| Usage -> ":usage",("?",[])
 		| Usage -> ":usage",("?",[])
 		| Used -> ":used",("Internally used by DCE to mark a class or field as used",[Internal])
 		| Used -> ":used",("Internally used by DCE to mark a class or field as used",[Internal])
+		| Void -> ":void",("Use Cpp native 'void' return type",[Platform Cpp])
 		| Last -> assert false
 		| Last -> assert false
 		(* do not put any custom metadata after Last *)
 		(* do not put any custom metadata after Last *)
 		| Dollar s -> "$" ^ s,("",[])
 		| Dollar s -> "$" ^ s,("",[])
@@ -772,7 +781,7 @@ let flash_versions = List.map (fun v ->
 	let maj = int_of_float v in
 	let maj = int_of_float v in
 	let min = int_of_float (mod_float (v *. 10.) 10.) in
 	let min = int_of_float (mod_float (v *. 10.) 10.) in
 	v, string_of_int maj ^ (if min = 0 then "" else "_" ^ string_of_int min)
 	v, string_of_int maj ^ (if min = 0 then "" else "_" ^ string_of_int min)
-) [9.;10.;10.1;10.2;10.3;11.;11.1;11.2;11.3;11.4;11.5;11.6;11.7;11.8;11.9;12.0;12.1;12.2;12.3;12.4;12.5]
+) [9.;10.;10.1;10.2;10.3;11.;11.1;11.2;11.3;11.4;11.5;11.6;11.7;11.8;11.9;12.0;13.0;14.0;15.0;16.0;17.0]
 
 
 let flash_version_tag = function
 let flash_version_tag = function
 	| 6. -> 6
 	| 6. -> 6
@@ -793,11 +802,11 @@ let flash_version_tag = function
 	| 11.8 -> 21
 	| 11.8 -> 21
 	| 11.9 -> 22
 	| 11.9 -> 22
 	| 12.0 -> 23
 	| 12.0 -> 23
-	| 12.1 -> 24
-	| 12.2 -> 25
-	| 12.3 -> 26
-	| 12.4 -> 27
-	| 12.5 -> 28
+	| 13.0 -> 24
+	| 14.0 -> 25
+	| 15.0 -> 26
+	| 16.0 -> 27
+	| 17.0 -> 28
 	| v -> failwith ("Invalid SWF version " ^ string_of_float v)
 	| v -> failwith ("Invalid SWF version " ^ string_of_float v)
 
 
 let raw_defined ctx v =
 let raw_defined ctx v =

+ 40 - 2
extra/CHANGES.txt

@@ -1,8 +1,46 @@
 2014-??-??: 3.2.0
 2014-??-??: 3.2.0
 
 
-	all : fixed nullability of abstracts over functions
+	New features:
+
+	all : add --display mode for toplevel completion
+	all : add --display mode for position and usage information
+	python : added python target
+	flash : flash player 12-14 support
+	js : add @:jsRequire and js.Lib.require
 	cs  : add @:bridgeProperties, which creates native property bridges for all haxe properties in the annotated class
 	cs  : add @:bridgeProperties, which creates native property bridges for all haxe properties in the annotated class
 
 
+	Bugfixes:
+
+	all : fixed nullability of abstracts over functions
+	all : fixed some equality checks between UInt and Int
+	all : fixed rare issue with abstract casts
+	all : fixed some internal code which relied on unspecified evaluation order
+	all : fixed exhaustiveness checks involving guards
+	all : fixed issue involving recursively constrained type parameters and @:generic
+	all : fixed type inference issue in map literals
+	all : fixed type inference issue when calling abstract method from within the abstract
+	cpp : fixed issue with the side-effect handler
+	cpp : fixed issue with NativeArray in --no-inline mode
+	php : fixed issue with invalid references for closures in for-loops
+
+	General improvements and optimizations:
+
+	all : disallowed using `super` in value positions
+	all : check exhaustiveness of explicit Null types
+	all : resolve unqualified identifiers to @:enum abstract constructors
+	all : determine @:generic type parameters from constructor call if possible
+	all : properly disallowed field redefinition in extending interface
+	neko : create output directory if it does not exist
+	js : inline Math methods and fields
+
+	Macro features and changes:
+
+	macro : added Context.getLocalTVars
+
+	Deprecations:
+
+	all : deprecated structurally extending classes and interfaces
+
 2014-04-13: 3.1.3
 2014-04-13: 3.1.3
 
 
 	Bugfixes:
 	Bugfixes:
@@ -606,7 +644,7 @@
 	php: minor optimization (removed foreach from std code)
 	php: minor optimization (removed foreach from std code)
 	php: implemented haxe.Stack
 	php: implemented haxe.Stack
 	php: changed exception handler to use Haxe call stack
 	php: changed exception handler to use Haxe call stack
-	php: changed special vars to use the » prefix instead of __
+	php: changed special vars to use the ?prefix instead of __
 	php: fixed use of reserved keywords for var names
 	php: fixed use of reserved keywords for var names
 	php: List iterator is now class based (faster)
 	php: List iterator is now class based (faster)
 	php: fixed behavior of class variables having assigned functions
 	php: fixed behavior of class variables having assigned functions

+ 12 - 2
extra/extract.patch

@@ -879,7 +879,7 @@ flash.globalization.StringTools.lastOperationStatus : LastOperationStatus;
 @:require(flash10_2) flash.media.Microphone.enhancedOptions;
 @:require(flash10_2) flash.media.Microphone.enhancedOptions;
 @:require(flash10_2) static flash.media.Microphone.getEnhancedMicrophone;
 @:require(flash10_2) static flash.media.Microphone.getEnhancedMicrophone;
 
 
-@:require(flash11) static flash.system.Capabilities.allowsFullScreen;
+@:require(flash10_2) flash.system.Capabilities.allowsFullScreen;
 
 
 @:require(flash10_2) static flash.ui.Keyboard.AUDIO;
 @:require(flash10_2) static flash.ui.Keyboard.AUDIO;
 @:require(flash10_2) static flash.ui.Keyboard.BACK;
 @:require(flash10_2) static flash.ui.Keyboard.BACK;
@@ -937,7 +937,6 @@ enum flash.display.FocusDirection;
 
 
 @:require(flash11) flash.display.MovieClip.isPlaying;
 @:require(flash11) flash.display.MovieClip.isPlaying;
 
 
-@:require(flash11) flash.display.Stage.allowsFullScreen;
 @:require(flash11) flash.display.Stage.displayContextInfo;
 @:require(flash11) flash.display.Stage.displayContextInfo;
 @:require(flash11) flash.display.Stage.softKeyboardRect;
 @:require(flash11) flash.display.Stage.softKeyboardRect;
 @:require(flash11) flash.display.Stage.stage3Ds;
 @:require(flash11) flash.display.Stage.stage3Ds;
@@ -1224,3 +1223,14 @@ flash.display3D.Context3D.$mipfilter : Context3DMipFilter;
 @:require(flash11_8) flash.display.DisplayObjectContainer.stopAllMovieClips
 @:require(flash11_8) flash.display.DisplayObjectContainer.stopAllMovieClips
 @:require(flash11_8) flash.display3D.Context3D.createRectangleTexture
 @:require(flash11_8) flash.display3D.Context3D.createRectangleTexture
 
 
+@:require(flash12) flash.display.Stage3D.requestContext3DMatchingProfiles
+@:require(flash12) flash.display3D.Context3D.profile
+
+flash.display3D.Context3D.$bufferUsage : Context3DBufferUsage
+enum flash.display3D.Context3DBufferUsage
+
+@:native("flash.profiler.Telemetry") flash.utils.Telemetry
+
+@:require(flash12) flash.display3D.Context3DBufferUsage
+
+

+ 6 - 3
filters.ml

@@ -1079,11 +1079,14 @@ let post_process_end() =
 	incr pp_counter
 	incr pp_counter
 
 
 let run com tctx main =
 let run com tctx main =
-	if com.display = DMUsage then
-		Codegen.detect_usage com;
+	begin match com.display with
+		| DMUsage | DMPosition ->
+			Codegen.detect_usage com;
+		| _ ->
+			()
+	end;
 	if not (Common.defined com Define.NoDeprecationWarnings) then
 	if not (Common.defined com Define.NoDeprecationWarnings) then
 		Codegen.DeprecationCheck.run com;
 		Codegen.DeprecationCheck.run com;
-
 	(* PASS 1: general expression filters *)
 	(* PASS 1: general expression filters *)
  	let filters = [
  	let filters = [
  		Codegen.UnificationCallback.run (check_unification com);
  		Codegen.UnificationCallback.run (check_unification com);

+ 97 - 26
gencommon.ml

@@ -49,6 +49,7 @@ open Type
 open Common
 open Common
 open Option
 open Option
 open Printf
 open Printf
+open ExtString
 
 
 let debug_type_ctor = function
 let debug_type_ctor = function
 	| TMono _ -> "TMono"
 	| TMono _ -> "TMono"
@@ -779,10 +780,10 @@ let reorder_modules gen =
 	let con = gen.gcon in
 	let con = gen.gcon in
 	con.modules <- [];
 	con.modules <- [];
 	let processed = Hashtbl.create 20 in
 	let processed = Hashtbl.create 20 in
-	Hashtbl.iter (fun md_path _ ->
+	Hashtbl.iter (fun md_path md ->
 		if not (Hashtbl.mem processed md_path) then begin
 		if not (Hashtbl.mem processed md_path) then begin
 			Hashtbl.add processed md_path true;
 			Hashtbl.add processed md_path true;
-			con.modules <- { m_id = alloc_mid(); m_path = md_path; m_types = List.rev ( Hashtbl.find_all modules md_path ); m_extra = module_extra "" "" 0. MFake } :: con.modules
+			con.modules <- { m_id = alloc_mid(); m_path = md_path; m_types = List.rev ( Hashtbl.find_all modules md_path ); m_extra = (t_infos md).mt_module.m_extra } :: con.modules
 		end
 		end
 	) modules
 	) modules
 
 
@@ -915,17 +916,9 @@ let run_filters gen =
 
 
 let write_file gen w source_dir path extension =
 let write_file gen w source_dir path extension =
 	let t = timer "write file" in
 	let t = timer "write file" in
-	let s_path = gen.gcon.file ^ "/" ^	source_dir	^ "/" ^ (String.concat "/" (fst path)) ^ "/" ^ (snd path) ^ "." ^ (extension) in
+	let s_path = source_dir	^ "/" ^ (snd path) ^ "." ^ (extension) in
 	(* create the folders if they don't exist *)
 	(* create the folders if they don't exist *)
-	let rec create acc = function
-		| [] -> ()
-		| d :: l ->
-				let dir = String.concat "/" (List.rev (d :: acc)) in
-				if not (Sys.file_exists dir) then Unix.mkdir dir 0o755;
-				create (d :: acc) l
-	in
-	let p = gen.gcon.file :: source_dir :: fst path in
-	create [] p;
+	mkdir_from_path s_path;
 
 
 	let contents = SourceWriter.contents w in
 	let contents = SourceWriter.contents w in
 	let should_write = if not (Common.defined gen.gcon Define.ReplaceFiles) && Sys.file_exists s_path then begin
 	let should_write = if not (Common.defined gen.gcon Define.ReplaceFiles) && Sys.file_exists s_path then begin
@@ -1016,17 +1009,25 @@ let dump_descriptor gen name path_s module_s =
 	SourceWriter.newline w;
 	SourceWriter.newline w;
 	SourceWriter.write w "begin libs";
 	SourceWriter.write w "begin libs";
 	SourceWriter.newline w;
 	SourceWriter.newline w;
+	let path file ext =
+		if Sys.file_exists file then
+			file
+		else try Common.find_file gen.gcon file with
+			| Not_found -> try Common.find_file gen.gcon (file ^ ext) with
+			| Not_found ->
+				file
+	in
 	if Common.platform gen.gcon Java then
 	if Common.platform gen.gcon Java then
 		List.iter (fun (s,std,_,_,_) ->
 		List.iter (fun (s,std,_,_,_) ->
 			if not std then begin
 			if not std then begin
-				SourceWriter.write w s;
+				SourceWriter.write w (path s ".jar");
 				SourceWriter.newline w;
 				SourceWriter.newline w;
 			end
 			end
 		) gen.gcon.java_libs
 		) gen.gcon.java_libs
 	else if Common.platform gen.gcon Cs then
 	else if Common.platform gen.gcon Cs then
 		List.iter (fun (s,std,_,_) ->
 		List.iter (fun (s,std,_,_) ->
 			if not std then begin
 			if not std then begin
-				SourceWriter.write w s;
+				SourceWriter.write w (path s ".dll");
 				SourceWriter.newline w;
 				SourceWriter.newline w;
 			end
 			end
 		) gen.gcon.net_libs;
 		) gen.gcon.net_libs;
@@ -1037,32 +1038,84 @@ let dump_descriptor gen name path_s module_s =
 	output_string f contents;
 	output_string f contents;
 	close_out f
 	close_out f
 
 
+let path_regex = Str.regexp "[/\\]+"
+
+let normalize path =
+	let rec normalize acc m = match m with
+		| [] ->
+			List.rev acc
+		| Str.Text "." :: Str.Delim _ :: tl when acc = [] ->
+			normalize [] tl
+		| Str.Text ".." :: Str.Delim _ :: tl -> (match acc with
+			| [] -> raise Exit
+			| _ :: acc -> normalize acc tl)
+		| Str.Text t :: Str.Delim _ :: tl ->
+			normalize (t :: acc) tl
+		| Str.Delim _ :: tl ->
+			normalize ("" :: acc) tl
+		| Str.Text t :: [] ->
+			List.rev (t :: acc)
+		| Str.Text _ :: Str.Text  _ :: _ -> assert false
+	in
+	String.concat "/" (normalize [] (Str.full_split path_regex path))
+
+let is_relative cwd rel =
+	try
+		let rel = normalize rel in
+		Filename.is_relative rel || (String.starts_with rel cwd || String.starts_with (Common.unique_full_path rel) cwd)
+	with | Exit ->
+		String.starts_with rel cwd || String.starts_with (Common.unique_full_path rel) cwd
+
 (*
 (*
 	helper function to create the source structure. Will send each module_def to the function passed.
 	helper function to create the source structure. Will send each module_def to the function passed.
 	If received true, it means that module_gen has generated this content, so the file must be saved.
 	If received true, it means that module_gen has generated this content, so the file must be saved.
 	See that it will write a whole module
 	See that it will write a whole module
 *)
 *)
 let generate_modules gen extension source_dir (module_gen : SourceWriter.source_writer->module_def->bool) =
 let generate_modules gen extension source_dir (module_gen : SourceWriter.source_writer->module_def->bool) =
+	let cwd = Common.unique_full_path (Sys.getcwd()) in
 	List.iter (fun md_def ->
 	List.iter (fun md_def ->
+		let source_dir =
+			if Common.defined gen.gcon Define.UnityStdTarget then
+				let file = md_def.m_extra.m_file in
+				let file = if file = "" then "." else file in
+				if is_relative cwd file then
+					let base_path = try
+							let last = Str.search_backward path_regex file (String.length file - 1) in
+							String.sub file 0 last
+						with | Not_found ->
+							"."
+					in
+					match List.rev (fst md_def.m_path) with
+						| "editor" :: _ ->
+							base_path ^ "/" ^ gen.gcon.file ^ "/Editor"
+						| _ ->
+							base_path ^ "/" ^ gen.gcon.file
+				else match List.rev (fst md_def.m_path) with
+					| "editor" :: _ ->
+						Common.defined_value gen.gcon Define.UnityStdTarget ^ "/Editor/" ^ (String.concat "/" (fst md_def.m_path))
+					| _ ->
+						Common.defined_value gen.gcon Define.UnityStdTarget ^ "/Haxe-Std/" ^ (String.concat "/" (fst md_def.m_path))
+			else
+				gen.gcon.file ^ "/" ^ source_dir ^ "/" ^ (String.concat "/" (fst md_def.m_path))
+		in
 		let w = SourceWriter.new_source_writer () in
 		let w = SourceWriter.new_source_writer () in
 		(*let should_write = List.fold_left (fun should md -> module_gen w md or should) false md_def.m_types in*)
 		(*let should_write = List.fold_left (fun should md -> module_gen w md or should) false md_def.m_types in*)
 		let should_write = module_gen w md_def in
 		let should_write = module_gen w md_def in
 		if should_write then begin
 		if should_write then begin
 			let path = md_def.m_path in
 			let path = md_def.m_path in
 			write_file gen w source_dir path extension;
 			write_file gen w source_dir path extension;
-
-
 		end
 		end
 	) gen.gcon.modules
 	) gen.gcon.modules
 
 
 let generate_modules_t gen extension source_dir change_path (module_gen : SourceWriter.source_writer->module_type->bool) =
 let generate_modules_t gen extension source_dir change_path (module_gen : SourceWriter.source_writer->module_type->bool) =
+	let source_dir = gen.gcon.file ^ "/" ^ source_dir in
 	List.iter (fun md ->
 	List.iter (fun md ->
 		let w = SourceWriter.new_source_writer () in
 		let w = SourceWriter.new_source_writer () in
 		(*let should_write = List.fold_left (fun should md -> module_gen w md or should) false md_def.m_types in*)
 		(*let should_write = List.fold_left (fun should md -> module_gen w md or should) false md_def.m_types in*)
 		let should_write = module_gen w md in
 		let should_write = module_gen w md in
 		if should_write then begin
 		if should_write then begin
 			let path = change_path (t_path md) in
 			let path = change_path (t_path md) in
-			write_file gen w source_dir path extension;
+			write_file gen w (source_dir ^ "/" ^ (String.concat "/" (fst path))) path extension;
 		end
 		end
 	) gen.gcon.types
 	) gen.gcon.types
 
 
@@ -1451,15 +1504,28 @@ struct
 	let default_hxgen_func md =
 	let default_hxgen_func md =
 		match md with
 		match md with
 			| TClassDecl cl ->
 			| TClassDecl cl ->
-				let rec is_hxgen_class c =
+				let rec is_hxgen_class (c,_) =
 					if c.cl_extern then begin
 					if c.cl_extern then begin
-						if Meta.has Meta.HxGen c.cl_meta then true else Option.map_default (fun (c,_) -> is_hxgen_class c) false c.cl_super
+						if Meta.has Meta.HxGen c.cl_meta then true else Option.map_default (is_hxgen_class) false c.cl_super
 					end else begin
 					end else begin
-						if Meta.has Meta.NativeGen c.cl_meta then Option.map_default (fun (c, _) -> is_hxgen_class c) false c.cl_super else true
+						if Meta.has Meta.NativeChildren c.cl_meta || Meta.has Meta.NativeGen c.cl_meta then
+							Option.map_default (is_hxgen_class) false c.cl_super
+						else
+							let rec has_nativec (c,p) =
+								if is_hxgen_class (c,p) then
+									false
+								else
+									(Meta.has Meta.NativeChildren c.cl_meta && not (Option.map_default is_hxgen_class false c.cl_super))
+									|| Option.map_default has_nativec false c.cl_super
+							in
+							if Option.map_default has_nativec false c.cl_super then
+								false
+							else
+								true
 					end
 					end
 				in
 				in
 
 
-				is_hxgen_class cl
+				is_hxgen_class (cl,[])
 			| TEnumDecl e -> if e.e_extern then Meta.has Meta.HxGen e.e_meta else not (Meta.has Meta.NativeGen e.e_meta)
 			| TEnumDecl e -> if e.e_extern then Meta.has Meta.HxGen e.e_meta else not (Meta.has Meta.NativeGen e.e_meta)
 			| TAbstractDecl a -> not (Meta.has Meta.NativeGen a.a_meta)
 			| TAbstractDecl a -> not (Meta.has Meta.NativeGen a.a_meta)
 			| TTypeDecl t -> (* TODO see when would we use this *)
 			| TTypeDecl t -> (* TODO see when would we use this *)
@@ -1471,12 +1537,13 @@ struct
 	*)
 	*)
 	let run_filter gen is_hxgen_func =
 	let run_filter gen is_hxgen_func =
 		let filter md =
 		let filter md =
-			if is_hxgen_func md then begin
+			let meta = if is_hxgen_func md then Meta.HxGen else Meta.NativeGen in
+			begin
 				match md with
 				match md with
-					| TClassDecl cl -> cl.cl_meta <- (Meta.HxGen, [], cl.cl_pos) :: cl.cl_meta
-					| TEnumDecl e -> e.e_meta <- (Meta.HxGen, [], e.e_pos) :: e.e_meta
-					| TTypeDecl t -> t.t_meta <- (Meta.HxGen, [], t.t_pos) :: t.t_meta
-					| TAbstractDecl a -> a.a_meta <- (Meta.HxGen, [], a.a_pos) :: a.a_meta
+					| TClassDecl cl -> cl.cl_meta <- (meta, [], cl.cl_pos) :: cl.cl_meta
+					| TEnumDecl e -> e.e_meta <- (meta, [], e.e_pos) :: e.e_meta
+					| TTypeDecl t -> t.t_meta <- (meta, [], t.t_pos) :: t.t_meta
+					| TAbstractDecl a -> a.a_meta <- (meta, [], a.a_pos) :: a.a_meta
 			end
 			end
 		in
 		in
 		List.iter filter gen.gcon.types
 		List.iter filter gen.gcon.types
@@ -8635,6 +8702,10 @@ struct
 			en.e_meta <- (Meta.Class, [], pos) :: en.e_meta;
 			en.e_meta <- (Meta.Class, [], pos) :: en.e_meta;
 			cl.cl_module <- en.e_module;
 			cl.cl_module <- en.e_module;
 			cl.cl_meta <- ( Meta.Enum, [], pos ) :: cl.cl_meta;
 			cl.cl_meta <- ( Meta.Enum, [], pos ) :: cl.cl_meta;
+			(match gen.gcon.platform with
+				| Cs when Common.defined gen.gcon Define.CoreApiSerialize ->
+					cl.cl_meta <- ( Meta.Meta, [ (EField( (EConst (Ident "System"), null_pos ), "Serializable" ), null_pos) ], null_pos ) :: cl.cl_meta
+				| _ -> ());
 			let c_types =
 			let c_types =
 				if handle_type_params then
 				if handle_type_params then
 					List.map (fun (s,t) -> (s, TInst (map_param (get_cl_t t), []))) en.e_types
 					List.map (fun (s,t) -> (s, TInst (map_param (get_cl_t t), []))) en.e_types

+ 313 - 91
gencpp.ml

@@ -63,12 +63,23 @@ let join_class_path path separator =
 let is_internal_class = function
 let is_internal_class = function
    |  ([],"Int") | ([],"Void") |  ([],"String") | ([], "Null") | ([], "Float")
    |  ([],"Int") | ([],"Void") |  ([],"String") | ([], "Null") | ([], "Float")
    |  ([],"Array") | ([], "Class") | ([], "Enum") | ([], "Bool")
    |  ([],"Array") | ([], "Class") | ([], "Enum") | ([], "Bool")
-   |  ([], "Dynamic") | ([], "ArrayAccess") | (["cpp"], "FastIterator") | (["cpp"],"Pointer") -> true
+   |  ([], "Dynamic") | ([], "ArrayAccess") | (["cpp"], "FastIterator")
+   |  (["cpp"],"Pointer") | (["cpp"],"ConstPointer")
+   |  (["cpp"],"BasePointer") | (["cpp"],"Function") -> true
    |  ([],"Math") | (["haxe";"io"], "Unsigned_char__") -> true
    |  ([],"Math") | (["haxe";"io"], "Unsigned_char__") -> true
+   |  (["cpp"],"Int8") | (["cpp"],"UInt8") | (["cpp"],"Char")
+   |  (["cpp"],"Int16") | (["cpp"],"UInt16")
+   |  (["cpp"],"Int32") | (["cpp"],"UInt32")
+   |  (["cpp"],"Int64") | (["cpp"],"UInt64")
+   |  (["cpp"],"Float32") | (["cpp"],"Float64") -> true
    | _ -> false;;
    | _ -> false;;
 
 
-let get_include_prefix common_ctx =
-   try (Common.defined_value common_ctx Define.IncludePrefix) ^ "/" with Not_found -> "";;
+let get_include_prefix common_ctx with_slash =
+   try
+     (Common.defined_value common_ctx Define.IncludePrefix) ^ (if with_slash then "/" else "")
+   with
+     Not_found -> ""
+;;
 
 
 
 
 let should_prefix_include = function
 let should_prefix_include = function
@@ -99,10 +110,14 @@ class source_writer common_ctx write_func close_func =
 
 
 
 
    method add_include class_path =
    method add_include class_path =
-      this#write ("#ifndef INCLUDED_" ^ (join_class_path class_path "_") ^ "\n");
-      let prefix = if should_prefix_include class_path then "" else get_include_prefix common_ctx in
-      this#write ("#include <" ^ prefix ^ (join_class_path class_path "/") ^ ".h>\n");
-      this#write ("#endif\n")
+      ( match class_path with
+         | (["@verbatim"],file) -> this#write ("#include <" ^ file ^ ">\n");
+         | _ ->
+            let prefix = if should_prefix_include class_path then "" else get_include_prefix common_ctx true in
+            this#write ("#ifndef INCLUDED_" ^ (join_class_path class_path "_") ^ "\n");
+            this#write ("#include <" ^ prefix ^ (join_class_path class_path "/") ^ ".h>\n");
+            this#write ("#endif\n")
+      )
 end;;
 end;;
 
 
 let file_source_writer common_ctx filename =
 let file_source_writer common_ctx filename =
@@ -140,10 +155,13 @@ let make_base_directory dir =
    make_class_directories "" ( ( Str.split_delim (Str.regexp "[\\/]+") dir ) );;
    make_class_directories "" ( ( Str.split_delim (Str.regexp "[\\/]+") dir ) );;
 
 
 let new_source_file common_ctx base_dir sub_dir extension class_path =
 let new_source_file common_ctx base_dir sub_dir extension class_path =
-   let include_prefix = get_include_prefix common_ctx in
+   let include_prefix = get_include_prefix common_ctx true in
    let full_dir =
    let full_dir =
       if (sub_dir="include") && (include_prefix<>"") then begin
       if (sub_dir="include") && (include_prefix<>"") then begin
-         let dir = base_dir ^ "/include/" ^ include_prefix ^ ( String.concat "/" (fst class_path) )  in
+         let dir = match fst class_path with
+            | [] -> base_dir ^ "/include/" ^ (get_include_prefix common_ctx false)
+            | path -> base_dir ^ "/include/" ^ include_prefix ^ ( String.concat "/" path )
+         in
          make_base_directory dir;
          make_base_directory dir;
          dir
          dir
       end else begin
       end else begin
@@ -177,6 +195,7 @@ type context =
    mutable ctx_return_from_internal_node : bool;
    mutable ctx_return_from_internal_node : bool;
    mutable ctx_debug_level : int;
    mutable ctx_debug_level : int;
    mutable ctx_real_this_ptr : bool;
    mutable ctx_real_this_ptr : bool;
+   mutable ctx_real_void : bool;
    mutable ctx_dynamic_this_ptr : bool;
    mutable ctx_dynamic_this_ptr : bool;
    mutable ctx_dump_src_pos : unit -> unit;
    mutable ctx_dump_src_pos : unit -> unit;
    mutable ctx_static_id_curr : int;
    mutable ctx_static_id_curr : int;
@@ -206,6 +225,7 @@ let new_context common_ctx writer debug file_info =
    ctx_tcall_expand_args = false;
    ctx_tcall_expand_args = false;
    ctx_return_from_internal_node = false;
    ctx_return_from_internal_node = false;
    ctx_real_this_ptr = true;
    ctx_real_this_ptr = true;
+   ctx_real_void = false;
    ctx_dynamic_this_ptr = false;
    ctx_dynamic_this_ptr = false;
    ctx_static_id_curr = 0;
    ctx_static_id_curr = 0;
    ctx_static_id_used = 0;
    ctx_static_id_used = 0;
@@ -346,11 +366,14 @@ let add_include writer class_path =
 let gen_forward_decl writer class_path =
 let gen_forward_decl writer class_path =
    begin
    begin
       let output = writer#write in
       let output = writer#write in
-      let name = fst (remap_class_path class_path) in
-      output ("HX_DECLARE_CLASS" ^ (string_of_int (List.length name ) ) ^ "(");
-      List.iter (fun package_part -> output (package_part ^ ",") ) name;
-      output ( (snd class_path) ^ ")\n")
-   end;;
+      match class_path with
+      | (["@verbatim"],file) -> writer#write ("#include <" ^ file ^ ">\n");
+      | _ ->
+         let name = fst (remap_class_path class_path) in
+         output ("HX_DECLARE_CLASS" ^ (string_of_int (List.length name ) ) ^ "(");
+         List.iter (fun package_part -> output (package_part ^ ",") ) name;
+         output ( (snd class_path) ^ ")\n")
+end;;
 
 
 let real_interfaces =
 let real_interfaces =
 List.filter (function (t,pl) ->
 List.filter (function (t,pl) ->
@@ -397,10 +420,24 @@ let gen_close_namespace output class_path =
 (* The basic types can have default values and are passesby value *)
 (* The basic types can have default values and are passesby value *)
 let is_numeric = function
 let is_numeric = function
    | "Int" | "Bool" | "Float" |  "::haxe::io::Unsigned_char__" | "unsigned char" -> true
    | "Int" | "Bool" | "Float" |  "::haxe::io::Unsigned_char__" | "unsigned char" -> true
+   | "::cpp::UInt8" | "::cpp::Int8" | "::cpp::Char"
+   | "::cpp::UInt16" | "::cpp::Int16"
+   | "::cpp::UInt32" | "::cpp::Int32"
+   | "::cpp::UInt64" | "::cpp::Int64"
+   | "::cpp::Float32" | "::cpp::Float64"
    | "int" | "bool" | "double" | "float" -> true
    | "int" | "bool" | "double" | "float" -> true
    | _ -> false
    | _ -> false
 
 
 
 
+let rec remove_parens expression =
+   match expression.eexpr with
+   | TParenthesis e -> remove_parens e
+   | TMeta(_,e) -> remove_parens e
+   | TCast ( e,None) -> remove_parens e
+   | _ -> expression
+;;
+
+
 let cant_be_null type_string =
 let cant_be_null type_string =
    is_numeric type_string
    is_numeric type_string
 ;;
 ;;
@@ -415,7 +452,70 @@ let is_interface_type t =
    | _ -> false
    | _ -> false
 ;;
 ;;
 
 
+let is_cpp_function_instance haxe_type =
+   match follow haxe_type with
+   | TInst (klass,params) ->
+      (match klass.cl_path with
+      | ["cpp"] , "Function" -> true
+      | _ -> false )
+   | _ -> false
+   ;;
+
 
 
+let is_cpp_function_class haxe_type =
+   match follow haxe_type with
+   | TType (klass,params) ->
+      (match klass.t_path with
+      | ["cpp"] , "Function" -> true
+      | _ -> false )
+   | _ -> false
+   ;;
+
+let is_fromStaticFunction_call func =
+   match (remove_parens func).eexpr with
+   | TField (_,FStatic ({cl_path=["cpp"],"Function"},{cf_name="fromStaticFunction"} ) ) -> true
+   | _ -> false
+;;
+
+let is_addressOf_call func =
+   match (remove_parens func).eexpr with
+   | TField (_,FStatic ({cl_path=["cpp"],"Pointer"},{cf_name="addressOf"} ) ) -> true
+   | _ -> false
+;;
+
+let is_lvalue var =
+   match (remove_parens var).eexpr with
+   | TLocal _ -> true
+   | TField (_,FStatic(_,field) ) | TField (_,FInstance(_,field) ) -> is_var_field field
+   | _ -> false
+;;
+
+
+
+let is_pointer haxe_type =
+   match follow haxe_type with
+   | TInst (klass,params) ->
+      (match klass.cl_path with
+      | ["cpp"] , "Pointer"
+      | ["cpp"] , "ConstPointer"
+      | ["cpp"] , "BasePointer"
+      | ["cpp"] , "Function" -> true
+      | _ -> false )
+   | TType (type_def,params) ->
+      (match type_def.t_path with
+      | ["cpp"] , "Pointer"
+      | ["cpp"] , "ConstPointer"
+      | ["cpp"] , "BasePointer"
+      | ["cpp"] , "Function" -> true
+      | _ -> false )
+   | _ -> false
+   ;;
+
+let is_dynamic_type_param class_kind =
+   match class_kind with
+   | KTypeParameter _ -> true
+   | _ -> false
+;;
 
 
 (*  Get a string to represent a type.
 (*  Get a string to represent a type.
    The "suffix" will be nothing or "_obj", depending if we want the name of the
    The "suffix" will be nothing or "_obj", depending if we want the name of the
@@ -429,9 +529,13 @@ let rec class_string klass suffix params =
    (* FastIterator class *)
    (* FastIterator class *)
    |  (["cpp"],"FastIterator") -> "::cpp::FastIterator" ^ suffix ^ "< " ^ (String.concat ","
    |  (["cpp"],"FastIterator") -> "::cpp::FastIterator" ^ suffix ^ "< " ^ (String.concat ","
                (List.map type_string  params) ) ^ " >"
                (List.map type_string  params) ) ^ " >"
-   |  (["cpp"],"Pointer") -> "::cpp::Pointer" ^ suffix ^ "< " ^ (String.concat ","
-               (List.map type_string  params) ) ^ " >"
-   | _ when (match klass.cl_kind with KTypeParameter _ -> true | _ -> false) -> "Dynamic"
+   |  (["cpp"],"Pointer")
+   |  (["cpp"],"ConstPointer")
+   |  (["cpp"],"BasePointer") ->
+        "::cpp::Pointer< " ^ (String.concat "," (List.map type_string params) ) ^ " >"
+   |  (["cpp"],"Function") ->
+        "::cpp::Function< " ^ (cpp_function_signature_params params) ^ " >"
+   | _ when is_dynamic_type_param klass.cl_kind -> "Dynamic"
    |  ([],"#Int") -> "/* # */int"
    |  ([],"#Int") -> "/* # */int"
    |  (["haxe";"io"],"Unsigned_char__") -> "unsigned char"
    |  (["haxe";"io"],"Unsigned_char__") -> "unsigned char"
    |  ([],"Class") -> "::Class"
    |  ([],"Class") -> "::Class"
@@ -489,10 +593,13 @@ and type_string_suff suffix haxe_type =
          (match params with
          (match params with
          | [t] -> "::cpp::FastIterator< " ^ (type_string (follow t) ) ^ " >"
          | [t] -> "::cpp::FastIterator< " ^ (type_string (follow t) ) ^ " >"
          | _ -> assert false)
          | _ -> assert false)
-      | ["cpp"] , "Pointer" ->
+      | ["cpp"] , "Pointer"
+      | ["cpp"] , "ConstPointer"
+      | ["cpp"] , "BasePointer" ->
          (match params with
          (match params with
          | [t] -> "::cpp::Pointer< " ^ (type_string (follow t) ) ^ " >"
          | [t] -> "::cpp::Pointer< " ^ (type_string (follow t) ) ^ " >"
          | _ -> assert false)
          | _ -> assert false)
+      | ["cpp"] , "Function" -> "::cpp::Function< " ^ (cpp_function_signature_params params) ^ " >"
       | _ ->  type_string_suff suffix (apply_params type_def.t_types params type_def.t_type)
       | _ ->  type_string_suff suffix (apply_params type_def.t_types params type_def.t_type)
       )
       )
    | TFun (args,haxe_type) -> "Dynamic" ^ suffix
    | TFun (args,haxe_type) -> "Dynamic" ^ suffix
@@ -524,11 +631,30 @@ and is_dynamic_array_param haxe_type =
    else (match follow haxe_type with
    else (match follow haxe_type with
    | TInst (klass,params) ->
    | TInst (klass,params) ->
          (match klass.cl_path with
          (match klass.cl_path with
-         | ([],"Array") | ([],"Class") | (["cpp"],"FastIterator") -> false
+         | ([],"Array") | ([],"Class") | (["cpp"],"FastIterator")
+         | (["cpp"],"Pointer") |(["cpp"],"ConstPointer")|(["cpp"],"Function") -> false
          | _ -> (match klass.cl_kind with KTypeParameter _ -> true | _ -> false)
          | _ -> (match klass.cl_kind with KTypeParameter _ -> true | _ -> false)
          )
          )
    | _ -> false
    | _ -> false
    )
    )
+and cpp_function_signature tfun =
+   match follow tfun with
+   | TFun(args,ret) -> (type_string ret) ^ "(" ^ (gen_tfun_interface_arg_list args) ^ ")"
+   | _ -> "void *"
+
+and cpp_function_signature_params params = match params with
+   | [t] -> cpp_function_signature t
+   | _ ->  assert false;
+
+and gen_interface_arg_type_name name opt typ =
+   let type_str = (type_string typ) in
+   (if (opt && (cant_be_null type_str) ) then
+      "hx::Null< " ^ type_str ^ " > "
+   else
+      type_str )
+   ^ " " ^ (keyword_remap name)
+and gen_tfun_interface_arg_list args =
+   String.concat "," (List.map (fun (name,opt,typ) -> gen_interface_arg_type_name name opt typ) args)
 ;;
 ;;
 
 
 
 
@@ -550,19 +676,6 @@ let is_array haxe_type =
    ;;
    ;;
 
 
 
 
-let is_pointer haxe_type =
-   match follow haxe_type with
-   | TInst (klass,params) ->
-      (match klass.cl_path with
-      | ["cpp"] , "Pointer" -> true
-      | _ -> false )
-   | TType (type_def,params) ->
-      (match type_def.t_path with
-      | ["cpp"] , "Pointer" -> true
-      | _ -> false )
-   | _ -> false
-   ;;
-
 let is_array_implementer haxe_type =
 let is_array_implementer haxe_type =
    match follow haxe_type with
    match follow haxe_type with
    | TInst (klass,params) ->
    | TInst (klass,params) ->
@@ -581,6 +694,30 @@ let is_numeric_field field =
 
 
 
 
 
 
+let is_static_access obj =
+   match (remove_parens obj).eexpr with
+   | TTypeExpr _ -> true
+   | _ -> false
+;;
+
+let is_native_with_space func =
+   match (remove_parens func).eexpr with
+   | TField(obj,field) when is_static_access obj ->
+      String.contains (get_field_access_meta field Meta.Native) ' '
+   | _ -> false
+;;
+
+
+let rec is_cpp_function_member func =
+   match (remove_parens func).eexpr with
+   | TField(obj,field) when is_cpp_function_instance obj.etype -> true
+   | TCall(obj,_) -> is_cpp_function_member obj
+   | _ -> false
+;;
+
+
+
+
 (* Get the type and output it to the stream *)
 (* Get the type and output it to the stream *)
 let gen_type ctx haxe_type =
 let gen_type ctx haxe_type =
    ctx.ctx_output (type_string haxe_type)
    ctx.ctx_output (type_string haxe_type)
@@ -617,6 +754,19 @@ let is_extern_class class_def =
    class_def.cl_extern || (has_meta_key class_def.cl_meta Meta.Extern)
    class_def.cl_extern || (has_meta_key class_def.cl_meta Meta.Extern)
 ;;
 ;;
 
 
+let is_extern_class_instance obj =
+   match follow obj.etype with
+   | TInst (klass,params) -> klass.cl_extern
+   | _ -> false
+;;
+
+
+let is_struct_access t =
+   match follow t with
+   | TInst (class_def,_) -> (has_meta_key class_def.cl_meta Meta.StructAccess)
+   | _ -> false
+;;
+
 
 
 
 
 let rec is_dynamic_accessor name acc field class_def =
 let rec is_dynamic_accessor name acc field class_def =
@@ -635,19 +785,6 @@ let gen_arg_type_name name default_val arg_type prefix =
    | Some constant  -> (type_str,prefix ^ remap_name)
    | Some constant  -> (type_str,prefix ^ remap_name)
    | _ -> (type_str,remap_name);;
    | _ -> (type_str,remap_name);;
 
 
-let gen_interface_arg_type_name name opt typ =
-   let type_str = (type_string typ) in
-   (if (opt && (cant_be_null type_str) ) then
-      "hx::Null< " ^ type_str ^ " > "
-   else
-      type_str )
-   ^ " " ^ (keyword_remap name)
-;;
-
-let gen_tfun_interface_arg_list args =
-   String.concat "," (List.map (fun (name,opt,typ) -> gen_interface_arg_type_name name opt typ) args)
-;;
-
 (* Generate prototype text, including allowing default values to be null *)
 (* Generate prototype text, including allowing default values to be null *)
 let gen_arg name default_val arg_type prefix =
 let gen_arg name default_val arg_type prefix =
    let pair = gen_arg_type_name name default_val arg_type prefix in
    let pair = gen_arg_type_name name default_val arg_type prefix in
@@ -769,9 +906,15 @@ let const_char_star s =
 let clear_real_this_ptr ctx dynamic_this =
 let clear_real_this_ptr ctx dynamic_this =
    let old_flag = ctx.ctx_real_this_ptr in
    let old_flag = ctx.ctx_real_this_ptr in
    let old_dynamic = ctx.ctx_dynamic_this_ptr in
    let old_dynamic = ctx.ctx_dynamic_this_ptr in
+   let old_void = ctx.ctx_real_void in
    ctx.ctx_real_this_ptr <- false;
    ctx.ctx_real_this_ptr <- false;
    ctx.ctx_dynamic_this_ptr <- dynamic_this;
    ctx.ctx_dynamic_this_ptr <- dynamic_this;
-   fun () -> ( ctx.ctx_real_this_ptr <- old_flag; ctx.ctx_dynamic_this_ptr <- old_dynamic; );;
+   fun () -> (
+      ctx.ctx_real_this_ptr <- old_flag;
+      ctx.ctx_dynamic_this_ptr <- old_dynamic;
+      ctx.ctx_real_void <- old_void;
+      )
+;;
 
 
 
 
 (* Generate temp variable names *)
 (* Generate temp variable names *)
@@ -1071,11 +1214,12 @@ and is_dynamic_member_lookup_in_cpp ctx field_object field =
             try ( let mem_type = (Hashtbl.find ctx.ctx_class_member_types full_name) in
             try ( let mem_type = (Hashtbl.find ctx.ctx_class_member_types full_name) in
                ctx.ctx_dbgout ("/* =" ^ mem_type ^ "*/");
                ctx.ctx_dbgout ("/* =" ^ mem_type ^ "*/");
                false )
                false )
-            with Not_found -> true
+            with Not_found -> not (is_extern_class_instance field_object)
    )
    )
 and is_dynamic_member_return_in_cpp ctx field_object field =
 and is_dynamic_member_return_in_cpp ctx field_object field =
    let member = field_name field in
    let member = field_name field in
    if (is_array field_object.etype) then false else
    if (is_array field_object.etype) then false else
+   if (is_pointer field_object.etype) then false else
    if (is_internal_member member) then false else
    if (is_internal_member member) then false else
    match field_object.eexpr with
    match field_object.eexpr with
    | TTypeExpr t ->
    | TTypeExpr t ->
@@ -1129,6 +1273,14 @@ let return_type_string t =
    | _ -> ""
    | _ -> ""
 ;;
 ;;
 
 
+
+let get_return_type field =
+   match follow field.cf_type with
+      | TFun (_,return_type) -> return_type
+      | _ -> raise Not_found
+;;
+
+
 (*
 (*
 let rec has_side_effects expr =
 let rec has_side_effects expr =
    match expr.eexpr with
    match expr.eexpr with
@@ -1575,6 +1727,7 @@ and gen_expression ctx retval expression =
       match follow array_type with
       match follow array_type with
       | TInst (klass,[element]) ->
       | TInst (klass,[element]) ->
          ( match type_string element with
          ( match type_string element with
+         | _ when is_struct_access element -> ()
          | x when cant_be_null x -> ()
          | x when cant_be_null x -> ()
          | _ when is_interface_type element -> ()
          | _ when is_interface_type element -> ()
          | "::String" | "Dynamic" -> ()
          | "::String" | "Dynamic" -> ()
@@ -1627,7 +1780,9 @@ and gen_expression ctx retval expression =
          (* toString is the only internal member that can be set... *)
          (* toString is the only internal member that can be set... *)
          let settingInternal = assigning && member="toString" in
          let settingInternal = assigning && member="toString" in
          let isString = (type_string field_object.etype)="::String" in
          let isString = (type_string field_object.etype)="::String" in
-         if (is_internal_member member && not settingInternal) then begin
+         if (is_struct_access field_object.etype) then
+            output ( "." ^ member )
+         else if (is_internal_member member && not settingInternal) then begin
             output ( (if isString then "." else "->") ^ member );
             output ( (if isString then "." else "->") ^ member );
          end else if (settingInternal || is_dynamic_member_lookup_in_cpp ctx field_object field) then begin
          end else if (settingInternal || is_dynamic_member_lookup_in_cpp ctx field_object field) then begin
             if assigning then
             if assigning then
@@ -1672,7 +1827,39 @@ and gen_expression ctx retval expression =
          | _ -> false) ->
          | _ -> false) ->
       ( match arg_list with
       ( match arg_list with
       | [{ eexpr = TConst (TString code) }] -> output code;
       | [{ eexpr = TConst (TString code) }] -> output code;
-      | _ -> error "__cpp__ accepts only one string as an argument" func.epos;
+      | ({ eexpr = TConst (TString code) } as ecode) :: tl ->
+        let exprs = Array.of_list tl in
+        let i = ref 0 in
+        let err msg =
+          let pos = { ecode.epos with pmin = ecode.epos.pmin + !i } in
+          ctx.ctx_common.error msg pos
+        in
+        let regex = Str.regexp "[{}]" in
+        let rec loop m = match m with
+          | [] -> ()
+          | Str.Text txt :: tl ->
+            i := !i + String.length txt;
+            output txt;
+            loop tl
+          | Str.Delim a :: Str.Delim b :: tl when a = b ->
+            i := !i + 2;
+            output a;
+            loop tl
+          | Str.Delim "{" :: Str.Text n :: Str.Delim "}" :: tl ->
+            (try
+              let expr = Array.get exprs (int_of_string n) in
+              gen_expression ctx true expr;
+              i := !i + 2 + String.length n;
+              loop tl
+            with | Failure "int_of_string" ->
+              err ("Index expected. Got " ^ n)
+            | Invalid_argument _ ->
+              err ("Out-of-bounds __cpp__ special parameter: " ^ n))
+          | Str.Delim x :: _ ->
+            err ("Unexpected " ^ x)
+        in
+        loop (Str.full_split regex code)
+      | _ -> error "__cpp__'s first argument must be a string" func.epos;
       )
       )
    | TCall (func, arg_list) when tcall_expand_args->
    | TCall (func, arg_list) when tcall_expand_args->
       let use_temp_func = has_side_effects func in
       let use_temp_func = has_side_effects func in
@@ -1699,6 +1886,23 @@ and gen_expression ctx retval expression =
          gen_expression ctx true func;
          gen_expression ctx true func;
       end;
       end;
       output ("(" ^ !arg_string ^ ");\n");
       output ("(" ^ !arg_string ^ ");\n");
+   | TCall (func, arg_list) when is_fromStaticFunction_call func ->
+      (match arg_list with
+         | [ {eexpr = TField( _, FStatic(klass,field)) } ] ->
+            let signature = cpp_function_signature field.cf_type in
+            let name = keyword_remap field.cf_name in
+            let void_cast = has_meta_key field.cf_meta Meta.Void in
+            output ("::cpp::Function<" ^ signature ^">(");
+            if (void_cast) then output "hx::AnyCast(";
+            output ("&::" ^(join_class_path klass.cl_path "::")^ "_obj::" ^ name );
+            if (void_cast) then output ")";
+            output (" )");
+         | _ -> error "fromStaticFunction must take a static function" expression.epos;
+      )
+
+   | TCall (func, [arg]) when is_addressOf_call func && not (is_lvalue arg) ->
+      error "addressOf must take a local or member variable" expression.epos;
+
    | TCall (func, arg_list) ->
    | TCall (func, arg_list) ->
       let rec is_variable e = match e.eexpr with
       let rec is_variable e = match e.eexpr with
       | TField _ | TEnumParameter _ -> false
       | TField _ | TEnumParameter _ -> false
@@ -1716,30 +1920,52 @@ and gen_expression ctx retval expression =
                (cpp_type<>expr_type) && (expr_type<>"Void") in
                (cpp_type<>expr_type) && (expr_type<>"Void") in
             if (fixed && (ctx.ctx_debug_level>1) ) then begin
             if (fixed && (ctx.ctx_debug_level>1) ) then begin
                output ("/* " ^ (cpp_type) ^ " != " ^ expr_type ^ " -> cast */");
                output ("/* " ^ (cpp_type) ^ " != " ^ expr_type ^ " -> cast */");
-               (* print_endline (cpp_type ^ " != " ^ expr_type ^ " -> cast"); *)
             end;
             end;
             fixed
             fixed
          )
          )
       | TParenthesis p | TMeta(_,p) -> is_fixed_override p
       | TParenthesis p | TMeta(_,p) -> is_fixed_override p
       | _ -> false
       | _ -> false
       in
       in
+      let check_extern_pointer_cast e = match (remove_parens e).eexpr with
+      | TField (_,FInstance(class_def,_) )
+      | TField (_,FStatic(class_def,_) )
+         when class_def.cl_extern ->
+         (try
+            let return_type = expression.etype in
+            is_pointer return_type &&
+               ( output ( (type_string return_type) ^ "(" ); true; )
+         with Not_found -> false )
+      | _ -> false
+      in
       let is_super = (match func.eexpr with | TConst TSuper -> true | _ -> false ) in
       let is_super = (match func.eexpr with | TConst TSuper -> true | _ -> false ) in
       if (ctx.ctx_debug_level>1) then output ("/* TCALL ret=" ^ expr_type ^ "*/");
       if (ctx.ctx_debug_level>1) then output ("/* TCALL ret=" ^ expr_type ^ "*/");
       let is_block_call = call_has_side_effects func arg_list in
       let is_block_call = call_has_side_effects func arg_list in
       let cast_result =  (not is_super) && (is_fixed_override func) in
       let cast_result =  (not is_super) && (is_fixed_override func) in
       if (cast_result) then output ("hx::TCast< " ^ expr_type ^ " >::cast(");
       if (cast_result) then output ("hx::TCast< " ^ expr_type ^ " >::cast(");
+      let cast_result = cast_result || check_extern_pointer_cast func in
       if (is_block_call) then
       if (is_block_call) then
          gen_local_block_call()
          gen_local_block_call()
       else begin
       else begin
+         (* If a static function has @:native('new abc')
+             c++ new has lower precedence than in haxe so ( ) must be used *)
+         let paren_result =
+           if is_native_with_space func then
+              ( output "("; true )
+           else
+              false
+         in
          ctx.ctx_calling <- true;
          ctx.ctx_calling <- true;
          gen_expression ctx true func;
          gen_expression ctx true func;
 
 
          output "(";
          output "(";
          gen_expression_list arg_list;
          gen_expression_list arg_list;
          output ")";
          output ")";
+         if paren_result then
+            output ")";
       end;
       end;
       if (cast_result) then output (")");
       if (cast_result) then output (")");
-      if ( (is_variable func) && (expr_type<>"Dynamic") && (not is_super) && (not is_block_call)) then
+      if ( (is_variable func) && (not (is_cpp_function_member func) ) &&
+           (expr_type<>"Dynamic") && (not is_super) && (not is_block_call)) then
          ctx.ctx_output (".Cast< " ^ expr_type ^ " >()" );
          ctx.ctx_output (".Cast< " ^ expr_type ^ " >()" );
 
 
       let rec cast_array_output func =
       let rec cast_array_output func =
@@ -1795,7 +2021,7 @@ and gen_expression ctx retval expression =
       | Some return_expression ->
       | Some return_expression ->
          output "return ";
          output "return ";
          gen_expression ctx true return_expression
          gen_expression ctx true return_expression
-      | _ -> output "return null()"
+      | _ -> output (if ctx.ctx_real_void then "return" else "return null()")
       )
       )
 
 
    | TConst const ->
    | TConst const ->
@@ -1852,13 +2078,17 @@ and gen_expression ctx retval expression =
          output "->__get(";
          output "->__get(";
          gen_expression ctx true index;
          gen_expression ctx true index;
          output ")";
          output ")";
-         check_array_element_cast array_expr.etype ".StaticCast" "()";
+         if not (is_pointer array_expr.etype ) then
+            check_array_element_cast array_expr.etype ".StaticCast" "()";
       end
       end
    (* Get precidence matching haxe ? *)
    (* Get precidence matching haxe ? *)
    | TBinop (op,expr1,expr2) -> gen_bin_op op expr1 expr2
    | TBinop (op,expr1,expr2) -> gen_bin_op op expr1 expr2
    | TField (expr,_) | TEnumParameter (expr,_,_) when (is_null expr) -> output "Dynamic()"
    | TField (expr,_) | TEnumParameter (expr,_,_) when (is_null expr) -> output "Dynamic()"
-   | TEnumParameter (expr,_,i) ->
-      let enum = match follow expr.etype with TEnum(enum,_) -> enum | _ -> assert false in
+   | TEnumParameter (expr,ef,i) ->
+      let enum = match follow ef.ef_type with
+         | TEnum(en,_) | TFun(_,TEnum(en,_)) -> en
+         | _ -> assert false
+      in
       output (  "(::" ^ (join_class_path_remap enum.e_path "::") ^ "(");
       output (  "(::" ^ (join_class_path_remap enum.e_path "::") ^ "(");
       gen_expression ctx true expr;
       gen_expression ctx true expr;
       output ( "))->__Param(" ^ (string_of_int i) ^ ")")
       output ( "))->__Param(" ^ (string_of_int i) ^ ")")
@@ -2163,6 +2393,8 @@ let rec all_virtual_functions clazz =
 ;;
 ;;
 
 
 
 
+
+
 let field_arg_count field =
 let field_arg_count field =
    match follow field.cf_type, field.cf_kind  with
    match follow field.cf_type, field.cf_kind  with
       | _, Method MethDynamic -> -1
       | _, Method MethDynamic -> -1
@@ -2211,11 +2443,14 @@ let gen_field ctx class_def class_name ptr_name dot_name is_static is_interface
 
 
       if (not (is_dynamic_haxe_method field)) then begin
       if (not (is_dynamic_haxe_method field)) then begin
          (* The actual function definition *)
          (* The actual function definition *)
-         output return_type;
+         let real_void = is_void  && (has_meta_key field.cf_meta Meta.Void) in
+         let fake_void = is_void  && not real_void in
+         output (if real_void then "void" else return_type );
          output (" " ^ class_name ^ "::" ^ remap_name ^ "( " );
          output (" " ^ class_name ^ "::" ^ remap_name ^ "( " );
          output (gen_arg_list function_def.tf_args "__o_");
          output (gen_arg_list function_def.tf_args "__o_");
          output ")";
          output ")";
          ctx.ctx_real_this_ptr <- true;
          ctx.ctx_real_this_ptr <- true;
+         ctx.ctx_real_void <- real_void;
          ctx.ctx_dynamic_this_ptr <- false;
          ctx.ctx_dynamic_this_ptr <- false;
          let code = (get_code field.cf_meta Meta.FunctionCode) in
          let code = (get_code field.cf_meta Meta.FunctionCode) in
          let tail_code = (get_code field.cf_meta Meta.FunctionTailCode) in
          let tail_code = (get_code field.cf_meta Meta.FunctionTailCode) in
@@ -2226,7 +2461,7 @@ let gen_field ctx class_def class_name ptr_name dot_name is_static is_interface
             output code;
             output code;
             gen_expression ctx false function_def.tf_expr;
             gen_expression ctx false function_def.tf_expr;
             output tail_code;
             output tail_code;
-            if (is_void) then output "return null();\n";
+            if (fake_void) then output "return null();\n";
             ctx.ctx_writer#end_block;
             ctx.ctx_writer#end_block;
          end else begin
          end else begin
             let add_block = is_void || (code <> "") || (tail_code <> "") in
             let add_block = is_void || (code <> "") || (tail_code <> "") in
@@ -2236,7 +2471,7 @@ let gen_field ctx class_def class_name ptr_name dot_name is_static is_interface
             gen_expression ctx false (to_block function_def.tf_expr);
             gen_expression ctx false (to_block function_def.tf_expr);
             output tail_code;
             output tail_code;
             if (add_block) then begin
             if (add_block) then begin
-               if (is_void) then output "return null();\n";
+               if (fake_void) then output "return null();\n";
                ctx.ctx_writer#end_block;
                ctx.ctx_writer#end_block;
             end;
             end;
          end;
          end;
@@ -2348,8 +2583,10 @@ let gen_member_def ctx class_def is_static is_interface field =
          end
          end
       end else begin
       end else begin
          let return_type = (type_string function_def.tf_type) in
          let return_type = (type_string function_def.tf_type) in
+
          if (not is_static) then output "virtual ";
          if (not is_static) then output "virtual ";
-         output return_type;
+         output (if return_type="Void" && (has_meta_key field.cf_meta Meta.Void) then "void" else return_type );
+
          output (" " ^ remap_name ^ "( " );
          output (" " ^ remap_name ^ "( " );
          output (gen_arg_list function_def.tf_args "" );
          output (gen_arg_list function_def.tf_args "" );
          output ");\n";
          output ");\n";
@@ -2388,12 +2625,8 @@ let gen_member_def ctx class_def is_static is_interface field =
    end
    end
    ;;
    ;;
 
 
-let path_of_string verbatim path =
-   if verbatim then ( ["@verbatim"], path ) else
-   match List.rev (Str.split_delim (Str.regexp "/") path ) with
-   | [] -> ([],"")
-   | [single] -> ([],single)
-   | head :: rest -> (List.rev rest, head)
+let path_of_string path =
+   ["@verbatim"], path
 ;;
 ;;
 
 
 
 
@@ -2415,7 +2648,7 @@ let find_referenced_types ctx obj super_deps constructor_deps header_only for_de
    let add_extern_class klass =
    let add_extern_class klass =
       let include_file = get_meta_string klass.cl_meta (if for_depends then Meta.Depend else Meta.Include) in
       let include_file = get_meta_string klass.cl_meta (if for_depends then Meta.Depend else Meta.Include) in
       if (include_file<>"") then
       if (include_file<>"") then
-         add_type ( path_of_string for_depends include_file )
+         add_type ( path_of_string include_file )
       else if (not for_depends) && (has_meta_key klass.cl_meta Meta.Include) then
       else if (not for_depends) && (has_meta_key klass.cl_meta Meta.Include) then
          add_type klass.cl_path
          add_type klass.cl_path
    in
    in
@@ -2426,10 +2659,10 @@ let find_referenced_types ctx obj super_deps constructor_deps header_only for_de
       | TEnum ({ e_path = ([],"Bool") },[]) -> () *)
       | TEnum ({ e_path = ([],"Bool") },[]) -> () *)
       | TEnum (enum,params) -> add_type enum.e_path
       | TEnum (enum,params) -> add_type enum.e_path
       (* If a class has a template parameter, then we treat it as dynamic - except
       (* If a class has a template parameter, then we treat it as dynamic - except
-         for the Array or Class class, for which we do a fully typed object *)
+         for the Array, Class, FastIterator or Pointer classes, for which we do a fully typed object *)
       | TInst (klass,params) ->
       | TInst (klass,params) ->
          (match klass.cl_path with
          (match klass.cl_path with
-         | ([],"Array") | ([],"Class") | (["cpp"],"FastIterator") | (["cpp"],"Pointer")-> List.iter visit_type params
+         | ([],"Array") | ([],"Class") | (["cpp"],"FastIterator") | (["cpp"],"Pointer") | (["cpp"],"ConstPointer") | (["cpp"],"Function") -> List.iter visit_type params
          | _ when is_extern_class klass -> add_extern_class klass
          | _ when is_extern_class klass -> add_extern_class klass
          | _ -> (match klass.cl_kind with KTypeParameter _ -> () | _ -> add_type klass.cl_path);
          | _ -> (match klass.cl_kind with KTypeParameter _ -> () | _ -> add_type klass.cl_path);
          )
          )
@@ -2474,12 +2707,12 @@ let find_referenced_types ctx obj super_deps constructor_deps header_only for_de
             | TFunction func_def ->
             | TFunction func_def ->
                List.iter (fun (v,_) -> visit_type v.v_type) func_def.tf_args;
                List.iter (fun (v,_) -> visit_type v.v_type) func_def.tf_args;
             | TConst TSuper ->
             | TConst TSuper ->
-               (match expression.etype with
+               (match follow expression.etype with
                | TInst (klass,params) ->
                | TInst (klass,params) ->
                   (try let construct_type = Hashtbl.find constructor_deps klass.cl_path in
                   (try let construct_type = Hashtbl.find constructor_deps klass.cl_path in
                      visit_type construct_type.cf_type
                      visit_type construct_type.cf_type
                   with Not_found -> () )
                   with Not_found -> () )
-               | _ -> print_endline ("TSuper : Odd etype?")
+               | _ -> print_endline ("TSuper : Odd etype ?" ^ ( (type_string expression.etype)) )
                )
                )
             | _ -> ()
             | _ -> ()
          );
          );
@@ -2586,11 +2819,7 @@ let generate_boot common_ctx boot_classes init_classes =
    let boot_file = new_cpp_file common_ctx base_dir ([],"__boot__") in
    let boot_file = new_cpp_file common_ctx base_dir ([],"__boot__") in
    let output_boot = (boot_file#write) in
    let output_boot = (boot_file#write) in
    output_boot "#include <hxcpp.h>\n\n";
    output_boot "#include <hxcpp.h>\n\n";
-   List.iter ( fun class_path ->
-      let prefix = get_include_prefix common_ctx in
-      output_boot ("#include <" ^
-         prefix ^ ( join_class_path class_path "/" ) ^ ".h>\n")
-         ) boot_classes;
+   List.iter ( fun class_path -> boot_file#add_include class_path ) boot_classes;
 
 
    output_boot "\nvoid __files__boot();\n";
    output_boot "\nvoid __files__boot();\n";
    output_boot "\nvoid __boot_all()\n{\n";
    output_boot "\nvoid __boot_all()\n{\n";
@@ -3178,7 +3407,12 @@ let generate_class_files common_ctx member_types super_deps constructor_deps cla
          | Var _ when is_abstract_impl -> false
          | Var _ when is_abstract_impl -> false
          | _ -> true) in
          | _ -> true) in
 
 
-      let reflective field = not (Meta.has Meta.Unreflective field.cf_meta) in
+      let reflective field = not ( (Meta.has Meta.Unreflective field.cf_meta) ||
+          (match field.cf_type with
+          | TInst (klass,_) ->  Meta.has Meta.Unreflective klass.cl_meta
+          | _ -> false
+          )
+      ) in
       let reflect_fields = List.filter reflective (statics_except_meta @ class_def.cl_ordered_fields) in
       let reflect_fields = List.filter reflective (statics_except_meta @ class_def.cl_ordered_fields) in
       let reflect_writable = List.filter is_writable reflect_fields in
       let reflect_writable = List.filter is_writable reflect_fields in
       let reflect_readable = List.filter is_readable reflect_fields in
       let reflect_readable = List.filter is_readable reflect_fields in
@@ -3534,15 +3768,11 @@ let generate_class_files common_ctx member_types super_deps constructor_deps cla
    (match class_def.cl_super with
    (match class_def.cl_super with
    | Some super ->
    | Some super ->
       let super_path = (fst super).cl_path in
       let super_path = (fst super).cl_path in
-      let prefix = get_include_prefix common_ctx in
-      output_h ("#include <" ^ prefix ^ ( join_class_path super_path "/" ) ^ ".h>\n")
+      h_file#add_include super_path
    | _ -> () );
    | _ -> () );
 
 
    (* And any interfaces ... *)
    (* And any interfaces ... *)
-   List.iter (fun imp->
-      let imp_path = (fst imp).cl_path in
-      let prefix = get_include_prefix common_ctx in
-      output_h ("#include <" ^ prefix ^ ( join_class_path imp_path "/" ) ^ ".h>\n") )
+   List.iter (fun imp-> h_file#add_include (fst imp).cl_path)
       (real_interfaces class_def.cl_implements);
       (real_interfaces class_def.cl_implements);
 
 
    (* Only need to foreward-declare classes that are mentioned in the header file
    (* Only need to foreward-declare classes that are mentioned in the header file
@@ -3698,7 +3928,7 @@ let write_resources common_ctx =
 
 
 let write_build_data common_ctx filename classes main_deps build_extra exe_name =
 let write_build_data common_ctx filename classes main_deps build_extra exe_name =
    let buildfile = open_out filename in
    let buildfile = open_out filename in
-   let include_prefix = get_include_prefix common_ctx in
+   let include_prefix = get_include_prefix common_ctx true in
    let add_class_to_buildfile class_def =
    let add_class_to_buildfile class_def =
       let class_path = fst class_def in
       let class_path = fst class_def in
       let deps = snd class_def in
       let deps = snd class_def in
@@ -3959,14 +4189,6 @@ let gen_extern_enum common_ctx enum_def file_info =
    file#close
    file#close
 ;;
 ;;
 
 
-let rec remove_parens expression =
-   match expression.eexpr with
-   | TParenthesis e -> remove_parens e
-   | TMeta(_,e) -> remove_parens e
-   | TCast ( e,None) -> remove_parens e
-   | _ -> expression
-;;
-
 let is_this expression =
 let is_this expression =
    match (remove_parens expression).eexpr with
    match (remove_parens expression).eexpr with
    | TConst TThis -> true
    | TConst TThis -> true

+ 67 - 10
gencs.ml

@@ -2655,15 +2655,16 @@ let configure gen =
 	CSharpSpecificSynf.configure gen (CSharpSpecificSynf.traverse gen runtime_cl);
 	CSharpSpecificSynf.configure gen (CSharpSpecificSynf.traverse gen runtime_cl);
 	CSharpSpecificESynf.configure gen (CSharpSpecificESynf.traverse gen runtime_cl);
 	CSharpSpecificESynf.configure gen (CSharpSpecificESynf.traverse gen runtime_cl);
 
 
-	let mkdir dir = if not (Sys.file_exists dir) then Unix.mkdir dir 0o755 in
-	mkdir gen.gcon.file;
-	mkdir (gen.gcon.file ^ "/src");
-
 	(* copy resource files *)
 	(* copy resource files *)
 	if Hashtbl.length gen.gcon.resources > 0 then begin
 	if Hashtbl.length gen.gcon.resources > 0 then begin
-		mkdir (gen.gcon.file ^ "/src/Resources");
+		let src =
+			if Common.defined gen.gcon Define.UnityStdTarget then
+				Common.defined_value gen.gcon Define.UnityStdTarget ^ "/../Resources"
+			else
+				gen.gcon.file ^ "/src/Resources"
+		in
 		Hashtbl.iter (fun name v ->
 		Hashtbl.iter (fun name v ->
-			let full_path = gen.gcon.file ^ "/src/Resources/" ^ name in
+			let full_path = src ^ "/" ^ name in
 			mkdir_from_path full_path;
 			mkdir_from_path full_path;
 
 
 			let f = open_out full_path in
 			let f = open_out full_path in
@@ -2725,8 +2726,8 @@ let configure gen =
 
 
 	generate_modules gen "cs" "src" module_gen;
 	generate_modules gen "cs" "src" module_gen;
 
 
-	dump_descriptor gen ("hxcs_build.txt") path_s module_s;
-	if ( not (Common.defined gen.gcon Define.NoCompilation) ) then begin
+	if ( not (Common.defined gen.gcon Define.NoCompilation || Common.defined gen.gcon Define.UnityStdTarget) ) then begin
+		dump_descriptor gen ("hxcs_build.txt") path_s module_s;
 		let old_dir = Sys.getcwd() in
 		let old_dir = Sys.getcwd() in
 		Sys.chdir gen.gcon.file;
 		Sys.chdir gen.gcon.file;
 		let cmd = "haxelib run hxcs hxcs_build.txt --haxe-version " ^ (string_of_int gen.gcon.version) in
 		let cmd = "haxelib run hxcs hxcs_build.txt --haxe-version " ^ (string_of_int gen.gcon.version) in
@@ -3102,6 +3103,7 @@ let convert_ilmethod ctx p m is_explicit_impl =
 	in
 	in
 	let acc = match m.moverride with
 	let acc = match m.moverride with
 		| None -> acc
 		| None -> acc
+		| _ when cff_name = "new" -> acc
 		| Some (path,s) -> match lookup_ilclass ctx.nstd ctx.ncom path with
 		| Some (path,s) -> match lookup_ilclass ctx.nstd ctx.ncom path with
 			| Some ilcls when not (List.mem SInterface ilcls.cflags.tdf_semantics) ->
 			| Some ilcls when not (List.mem SInterface ilcls.cflags.tdf_semantics) ->
 				AOverride :: acc
 				AOverride :: acc
@@ -3218,6 +3220,12 @@ let convert_fun ctx p ret args =
 	let args = List.map (convert_fun_arg ctx p) args in
 	let args = List.map (convert_fun_arg ctx p) args in
 	CTFunction(args, convert_signature ctx p ret)
 	CTFunction(args, convert_signature ctx p ret)
 
 
+let get_clsname cpath =
+	match cpath with
+		| (_,[],n) -> netcl_to_hx n
+		| (_,nested,n) ->
+			String.concat "_" nested ^ "_" ^ netcl_to_hx n
+
 let convert_delegate ctx p ilcls =
 let convert_delegate ctx p ilcls =
 	let p = { p with pfile =	p.pfile ^" (abstract delegate)" } in
 	let p = { p with pfile =	p.pfile ^" (abstract delegate)" } in
 	(* will have the following methods: *)
 	(* will have the following methods: *)
@@ -3225,6 +3233,9 @@ let convert_delegate ctx p ilcls =
 	(* - FromHaxeFunction(haxeType) *)
 	(* - FromHaxeFunction(haxeType) *)
 	(* - Invoke() *)
 	(* - Invoke() *)
 	(* - AsDelegate():Super *)
 	(* - AsDelegate():Super *)
+	(* - @:op(A+B) Add(d:absType) *)
+	(* - @:op(A-B) Remove(d:absType) *)
+	let abs_type = mk_type_path ctx (ilcls.cpath) (List.map (fun t -> TPType (mk_type_path ctx ([],[],"T" ^ string_of_int t.tnumber) [])) ilcls.ctypes) in
 	let invoke = List.find (fun m -> m.mname = "Invoke") ilcls.cmethods in
 	let invoke = List.find (fun m -> m.mname = "Invoke") ilcls.cmethods in
 	let ret = invoke.mret.snorm in
 	let ret = invoke.mret.snorm in
 	let args = List.map (fun (_,_,s) -> s.snorm) invoke.margs in
 	let args = List.map (fun (_,_,s) -> s.snorm) invoke.margs in
@@ -3236,6 +3247,30 @@ let convert_delegate ctx p ilcls =
 			tp_constraints = [];
 			tp_constraints = [];
 		}
 		}
 	) ilcls.ctypes in
 	) ilcls.ctypes in
+	let mk_op_fn op name p =
+		let fn_name = List.assoc op cs_binops in
+		let clsname = match ilcls.cpath with
+			| (ns,inner,n) -> get_clsname (ns,inner,"Delegate_"^n)
+		in
+		let expr = (ECall( (EField( (EConst(Ident (clsname)),p), fn_name ),p), [(EConst(Ident"arg1"),p);(EConst(Ident"arg2"),p)]),p) in
+		FFun {
+			f_params = types;
+			f_args = ["arg1",false,Some abs_type,None;"arg2",false,Some abs_type,None];
+			f_type = Some abs_type;
+			f_expr = Some ( (EReturn (Some expr), p) );
+		}
+	in
+	let mk_op op name =
+		let p = { p with pfile = p.pfile ^" (op " ^ name ^ ")" } in
+		{
+			cff_name = name;
+			cff_doc = None;
+			cff_pos = p;
+			cff_meta = [ Meta.Extern,[],p ; Meta.Op, [ (EBinop(op, (EConst(Ident"A"),p), (EConst(Ident"B"),p)),p) ], p ];
+			cff_access = [APublic;AInline;AStatic];
+			cff_kind = mk_op_fn op name p;
+		}
+	in
 	let params = (List.map (fun s ->
 	let params = (List.map (fun s ->
 		TPType (mk_type_path ctx ([],[],s.tp_name) [])
 		TPType (mk_type_path ctx ([],[],s.tp_name) [])
 	) types) in
 	) types) in
@@ -3278,7 +3313,7 @@ let convert_delegate ctx p ilcls =
 		f_args = [];
 		f_args = [];
 		f_type = None;
 		f_type = None;
 		f_expr = Some(
 		f_expr = Some(
-			EReturn( Some ( EUntyped( EConst(Ident "this"), p ), p ) ), p
+			EReturn( Some ( EConst(Ident "this"), p ) ), p
 		);
 		);
 	} in
 	} in
 	let fn_new = mk_abstract_fun "new" p fn_new [Meta.Extern] [APublic;AInline] in
 	let fn_new = mk_abstract_fun "new" p fn_new [Meta.Extern] [APublic;AInline] in
@@ -3292,7 +3327,7 @@ let convert_delegate ctx p ilcls =
 		d_params = types;
 		d_params = types;
 		d_meta = mk_metas [Meta.Delegate] p;
 		d_meta = mk_metas [Meta.Delegate] p;
 		d_flags = [AIsType underlying_type];
 		d_flags = [AIsType underlying_type];
-		d_data = [fn_new;fn_from_hx;fn_invoke;fn_asdel];
+		d_data = [fn_new;fn_from_hx;fn_invoke;fn_asdel;mk_op Ast.OpAdd "Add";mk_op Ast.OpSub "Remove"];
 	}
 	}
 
 
 let convert_ilclass ctx p ?(delegate=false) ilcls = match ilcls.csuper with
 let convert_ilclass ctx p ?(delegate=false) ilcls = match ilcls.csuper with
@@ -3378,6 +3413,28 @@ let convert_ilclass ctx p ?(delegate=false) ilcls = match ilcls.csuper with
 					tp_constraints = [];
 					tp_constraints = [];
 				}) ilcls.ctypes
 				}) ilcls.ctypes
 			in
 			in
+
+			if delegate then begin
+				(* add op_Addition and op_Subtraction *)
+				let path = ilcls.cpath in
+				let thist = mk_type_path ctx path (List.map (fun t -> TPType (mk_type_path ctx ([],[],"T" ^ string_of_int t.tnumber) [])) ilcls.ctypes) in
+				let op name =
+					{
+						cff_name = name;
+						cff_doc = None;
+						cff_pos = p;
+						cff_meta = [];
+						cff_access = [APublic;AStatic];
+						cff_kind = FFun {
+							f_params = params;
+							f_args = ["arg1",false,Some thist,None;"arg2",false,Some thist,None];
+							f_type = Some thist;
+							f_expr = None;
+						};
+					}
+				in
+				fields := op "op_Addition" :: op "op_Subtraction" :: !fields;
+			end;
 			let path = match ilcls.cpath with
 			let path = match ilcls.cpath with
 				| ns,inner,name when delegate ->
 				| ns,inner,name when delegate ->
 					ns,inner,"Delegate_"^name
 					ns,inner,"Delegate_"^name

+ 3 - 1
genjava.ml

@@ -707,6 +707,8 @@ let configure gen =
 	let change_param_type md params =
 	let change_param_type md params =
 		match md with
 		match md with
 			| TClassDecl( { cl_path = (["java"], "NativeArray") } ) -> params
 			| TClassDecl( { cl_path = (["java"], "NativeArray") } ) -> params
+			| TAbstractDecl { a_path=[],("Class" | "Enum") } | TClassDecl { cl_path = (["java";"lang"],("Class"|"Enum")) } ->
+				List.map (fun _ -> t_dynamic) params
 			| _ ->
 			| _ ->
 				match params with
 				match params with
 					| [] -> []
 					| [] -> []
@@ -803,7 +805,7 @@ let configure gen =
 			| TAbstract( { a_path = ([], "Class") }, p	)
 			| TAbstract( { a_path = ([], "Class") }, p	)
 			| TAbstract( { a_path = ([], "Enum") }, p  )
 			| TAbstract( { a_path = ([], "Enum") }, p  )
 			| TInst( { cl_path = ([], "Class") }, p  )
 			| TInst( { cl_path = ([], "Class") }, p  )
-			| TInst( { cl_path = ([], "Enum") }, p	) -> TInst(cl_cl,p)
+			| TInst( { cl_path = ([], "Enum") }, p	) -> TInst(cl_cl,[t_dynamic])
 			| TEnum(e,params) -> TEnum(e, List.map (fun _ -> t_dynamic) params)
 			| TEnum(e,params) -> TEnum(e, List.map (fun _ -> t_dynamic) params)
 			| TInst(c,params) when Meta.has Meta.Enum c.cl_meta ->
 			| TInst(c,params) when Meta.has Meta.Enum c.cl_meta ->
 				TInst(c, List.map (fun _ -> t_dynamic) params)
 				TInst(c, List.map (fun _ -> t_dynamic) params)

+ 24 - 2
genjs.ml

@@ -107,7 +107,7 @@ let kwds2 =
 		"Infinity"; "NaN"; "decodeURI"; "decodeURIComponent"; "encodeURI"; "encodeURIComponent";
 		"Infinity"; "NaN"; "decodeURI"; "decodeURIComponent"; "encodeURI"; "encodeURIComponent";
 		"escape"; "eval"; "isFinite"; "isNaN"; "parseFloat"; "parseInt"; "undefined"; "unescape";
 		"escape"; "eval"; "isFinite"; "isNaN"; "parseFloat"; "parseInt"; "undefined"; "unescape";
 
 
-		"JSON"; "Number"; "Object"; "console"; "window";
+		"JSON"; "Number"; "Object"; "console"; "window"; "require";
 	];
 	];
 	h
 	h
 
 
@@ -1105,6 +1105,25 @@ let generate_static ctx (c,f,e) =
 	gen_value ctx e;
 	gen_value ctx e;
 	newline ctx
 	newline ctx
 
 
+let generate_require ctx c =
+	let _, args, mp = Meta.get Meta.JsRequire c.cl_meta in
+	let p = (s_path ctx c.cl_path) in
+
+	if ctx.js_flatten then
+		spr ctx "var "
+	else
+		generate_package_create ctx c.cl_path;
+
+	(match args with
+	| [(EConst(String(module_name)),_)] ->
+		print ctx "%s = require(\"%s\")" p module_name
+	| [(EConst(String(module_name)),_) ; (EConst(String(object_path)),_)] ->
+		print ctx "%s = require(\"%s\").%s" p module_name object_path
+	| _ ->
+		error "Unsupported @:jsRequire format" mp);
+
+	newline ctx
+
 let generate_type ctx = function
 let generate_type ctx = function
 	| TClassDecl c ->
 	| TClassDecl c ->
 		(match c.cl_init with
 		(match c.cl_init with
@@ -1116,6 +1135,8 @@ let generate_type ctx = function
 		if p = "Math" then generate_class___name__ ctx c;
 		if p = "Math" then generate_class___name__ ctx c;
 		if not c.cl_extern then
 		if not c.cl_extern then
 			generate_class ctx c
 			generate_class ctx c
+		else if Meta.has Meta.JsRequire c.cl_meta then
+			generate_require ctx c
 		else if not ctx.js_flatten && Meta.has Meta.InitPackage c.cl_meta then
 		else if not ctx.js_flatten && Meta.has Meta.InitPackage c.cl_meta then
 			(match c.cl_path with
 			(match c.cl_path with
 			| ([],_) -> ()
 			| ([],_) -> ()
@@ -1161,7 +1182,8 @@ let alloc_ctx com =
 	ctx.type_accessor <- (fun t ->
 	ctx.type_accessor <- (fun t ->
 		let p = t_path t in
 		let p = t_path t in
 		match t with
 		match t with
-		| TClassDecl { cl_extern = true }
+		| TClassDecl ({ cl_extern = true } as c) when not (Meta.has Meta.JsRequire c.cl_meta)
+			-> dot_path p
 		| TEnumDecl { e_extern = true }
 		| TEnumDecl { e_extern = true }
 			-> dot_path p
 			-> dot_path p
 		| _ -> s_path ctx p);
 		| _ -> s_path ctx p);

File diff suppressed because it is too large
+ 505 - 238
genpy.ml


+ 3 - 0
haxe.hxproj

@@ -136,6 +136,9 @@
     <hidden path="filters.obj" />
     <hidden path="filters.obj" />
     <hidden path="filters.cmi" />
     <hidden path="filters.cmi" />
     <hidden path="filters.cmx" />
     <hidden path="filters.cmx" />
+    <hidden path="genpy.obj" />
+    <hidden path="genpy.cmi" />
+    <hidden path="genpy.cmx" />
   </hiddenPaths>
   </hiddenPaths>
   <!-- Executed before build -->
   <!-- Executed before build -->
   <preBuildCommand>make -j4 MSVC=1 FD_OUTPUT=1 -f Makefile.win kill haxe</preBuildCommand>
   <preBuildCommand>make -j4 MSVC=1 FD_OUTPUT=1 -f Makefile.win kill haxe</preBuildCommand>

+ 28 - 5
interp.ml

@@ -1637,11 +1637,25 @@ let std_lib =
 			Unix.chdir (vstring s);
 			Unix.chdir (vstring s);
 			VNull;
 			VNull;
 		);
 		);
-		"sys_string", Fun0 (fun() ->
-			VString (match Sys.os_type with
-			| "Unix" -> "Linux"
-			| "Win32" | "Cygwin" -> "Windows"
-			| s -> s)
+		"sys_string", (
+			let cached_sys_name = ref None in
+			Fun0 (fun() ->
+				VString (match Sys.os_type with
+				| "Unix" ->
+					(match !cached_sys_name with
+					| Some n -> n
+					| None ->
+						let ic = Unix.open_process_in "uname" in
+						let uname = (match input_line ic with
+							| "Darwin" -> "Mac"
+							| n -> n
+						) in
+						close_in ic;
+						cached_sys_name := Some uname;
+						uname)
+				| "Win32" | "Cygwin" -> "Windows"
+				| s -> s)
+			)
 		);
 		);
 		"sys_is64", Fun0 (fun() ->
 		"sys_is64", Fun0 (fun() ->
 			VBool (Sys.word_size = 64)
 			VBool (Sys.word_size = 64)
@@ -2491,6 +2505,15 @@ let macro_lib =
 				(match com.platform with
 				(match com.platform with
 				| Flash -> Genswf.add_swf_lib com file false
 				| Flash -> Genswf.add_swf_lib com file false
 				| Java -> Genjava.add_java_lib com file false
 				| Java -> Genjava.add_java_lib com file false
+				| Cs ->
+					let file, is_std = match ExtString.String.nsplit file "@" with
+						| [file] ->
+							file,false
+						| [file;"std"] ->
+							file,true
+						| _ -> failwith ("unsupported file@`std` format: " ^ file)
+					in
+					Gencs.add_net_lib com file is_std
 				| _ -> failwith "Unsupported platform");
 				| _ -> failwith "Unsupported platform");
 				VNull
 				VNull
 			| _ ->
 			| _ ->

+ 45 - 20
main.ml

@@ -1139,17 +1139,28 @@ try
 			| _ ->
 			| _ ->
 				let file, pos = try ExtString.String.split file_pos "@" with _ -> failwith ("Invalid format : " ^ file_pos) in
 				let file, pos = try ExtString.String.split file_pos "@" with _ -> failwith ("Invalid format : " ^ file_pos) in
 				let file = unquote file in
 				let file = unquote file in
-				let pos, mode = try ExtString.String.split pos "@" with _ -> pos,"" in
-				let mode = match mode with
-					| "position" -> DMPosition
-					| "usage" -> DMUsage
-					| "metadata" -> DMMetadata
-					| _ -> DMDefault
+				let pos, smode = try ExtString.String.split pos "@" with _ -> pos,"" in
+				let activate_special_display_mode () =
+					Common.define com Define.NoCOpt;
+					Parser.use_parser_resume := false
+				in
+				let mode = match smode with
+					| "position" ->
+						activate_special_display_mode();
+						DMPosition
+					| "usage" ->
+						activate_special_display_mode();
+						DMUsage
+					| "toplevel" ->
+						activate_special_display_mode();
+						DMToplevel
+					| _ ->
+						DMDefault
 				in
 				in
 				let pos = try int_of_string pos with _ -> failwith ("Invalid format : "  ^ pos) in
 				let pos = try int_of_string pos with _ -> failwith ("Invalid format : "  ^ pos) in
 				com.display <- mode;
 				com.display <- mode;
 				Common.display_default := mode;
 				Common.display_default := mode;
-				Common.define com Define.Display;
+				Common.define_value com Define.Display (if smode <> "" then smode else "1");
 				Parser.use_doc := true;
 				Parser.use_doc := true;
 				Parser.resume_display := {
 				Parser.resume_display := {
 					Ast.pfile = Common.unique_full_path file;
 					Ast.pfile = Common.unique_full_path file;
@@ -1360,7 +1371,12 @@ try
 			"python"
 			"python"
 	) in
 	) in
 	(* if we are at the last compilation step, allow all packages accesses - in case of macros or opening another project file *)
 	(* if we are at the last compilation step, allow all packages accesses - in case of macros or opening another project file *)
-	if com.display <> DMNone && not ctx.has_next then com.package_rules <- PMap.foldi (fun p r acc -> match r with Forbidden -> acc | _ -> PMap.add p r acc) com.package_rules PMap.empty;
+	begin match com.display with
+		| DMNone | DMToplevel ->
+			()
+		| _ ->
+			if not ctx.has_next then com.package_rules <- PMap.foldi (fun p r acc -> match r with Forbidden -> acc | _ -> PMap.add p r acc) com.package_rules PMap.empty;
+	end;
 	com.config <- get_config com; (* make sure to adapt all flags changes defined after platform *)
 	com.config <- get_config com; (* make sure to adapt all flags changes defined after platform *)
 
 
 	(* check file extension. In case of wrong commandline, we don't want
 	(* check file extension. In case of wrong commandline, we don't want
@@ -1389,7 +1405,7 @@ try
 		t();
 		t();
 		if ctx.has_error then raise Abort;
 		if ctx.has_error then raise Abort;
 		begin match com.display with
 		begin match com.display with
-			| DMNone | DMUsage ->
+			| DMNone | DMUsage | DMPosition ->
 				()
 				()
 			| _ ->
 			| _ ->
 				if ctx.has_next then raise Abort;
 				if ctx.has_next then raise Abort;
@@ -1487,6 +1503,8 @@ with
 		message ctx msg p;
 		message ctx msg p;
 		List.iter (message ctx "Called from") l;
 		List.iter (message ctx "Called from") l;
 		error ctx "Aborted" Ast.null_pos;
 		error ctx "Aborted" Ast.null_pos;
+	| Codegen.Generic_Exception(m,p) ->
+		error ctx m p
 	| Arg.Bad msg ->
 	| Arg.Bad msg ->
 		error ctx ("Error: " ^ msg) Ast.null_pos
 		error ctx ("Error: " ^ msg) Ast.null_pos
 	| Failure msg when not (is_debug_run()) ->
 	| Failure msg when not (is_debug_run()) ->
@@ -1522,23 +1540,30 @@ with
 	| Typecore.DisplayPosition pl ->
 	| Typecore.DisplayPosition pl ->
 		let b = Buffer.create 0 in
 		let b = Buffer.create 0 in
 		let error_printer file line = sprintf "%s:%d:" (Common.unique_full_path file) line in
 		let error_printer file line = sprintf "%s:%d:" (Common.unique_full_path file) line in
+		Buffer.add_string b "<list>\n";
 		List.iter (fun p ->
 		List.iter (fun p ->
 			let epos = Lexer.get_error_pos error_printer p in
 			let epos = Lexer.get_error_pos error_printer p in
-			Buffer.add_string b "<pos>\n";
+			Buffer.add_string b "<pos>";
 			Buffer.add_string b epos;
 			Buffer.add_string b epos;
-			Buffer.add_string b "\n</pos>\n";
+			Buffer.add_string b "</pos>\n";
 		) pl;
 		) pl;
+		Buffer.add_string b "</list>";
 		raise (Completion (Buffer.contents b))
 		raise (Completion (Buffer.contents b))
-	| Typer.DisplayMetadata m ->
+	| Typer.DisplayToplevel il ->
 		let b = Buffer.create 0 in
 		let b = Buffer.create 0 in
-		List.iter (fun (m,el,p) ->
-			Buffer.add_string b ("<meta name=\"" ^ (fst (MetaInfo.to_string m)) ^ "\"");
-			if el = [] then Buffer.add_string b "/>" else begin
-				Buffer.add_string b ">\n";
-				List.iter (fun e -> Buffer.add_string b ((htmlescape (Ast.s_expr e)) ^ "\n")) el;
-				Buffer.add_string b "</meta>\n";
-			end
-		) m;
+		Buffer.add_string b "<il>\n";
+		let ctx = print_context() in
+		let s_type t = htmlescape (s_type ctx t) in
+		List.iter (fun id -> match id with
+			| Typer.ITLocal v -> Buffer.add_string b (Printf.sprintf "<i k=\"local\" t=\"%s\">%s</i>\n" (s_type v.v_type) v.v_name);
+			| Typer.ITMember(c,cf) -> Buffer.add_string b (Printf.sprintf "<i k=\"member\" t=\"%s\">%s</i>\n" (s_type cf.cf_type) cf.cf_name);
+			| Typer.ITStatic(c,cf) -> Buffer.add_string b (Printf.sprintf "<i k=\"static\" t=\"%s\">%s</i>\n" (s_type cf.cf_type) cf.cf_name);
+			| Typer.ITEnum(en,ef) -> Buffer.add_string b (Printf.sprintf "<i k=\"enum\" t=\"%s\">%s</i>\n" (s_type ef.ef_type) ef.ef_name);
+			| Typer.ITGlobal(mt,s,t) -> Buffer.add_string b (Printf.sprintf "<i k=\"global\" p=\"%s\" t=\"%s\">%s</i>\n" (s_type_path (t_infos mt).mt_path) (s_type t) s);
+			| Typer.ITType(mt) -> Buffer.add_string b (Printf.sprintf "<i k=\"type\" p=\"%s\">%s</i>\n" (s_type_path (t_infos mt).mt_path) (snd (t_infos mt).mt_path));
+			| Typer.ITPackage s -> Buffer.add_string b (Printf.sprintf "<i k=\"package\">%s<i>\n" s)
+		) il;
+		Buffer.add_string b "</il>";
 		raise (Completion (Buffer.contents b))
 		raise (Completion (Buffer.contents b))
 	| Parser.TypePath (p,c) ->
 	| Parser.TypePath (p,c) ->
 		(match c with
 		(match c with

+ 29 - 18
parser.ml

@@ -70,6 +70,7 @@ let unquote_ident f =
 let cache = ref (DynArray.create())
 let cache = ref (DynArray.create())
 let last_doc = ref None
 let last_doc = ref None
 let use_doc = ref false
 let use_doc = ref false
+let use_parser_resume = ref true
 let resume_display = ref null_pos
 let resume_display = ref null_pos
 let in_macro = ref false
 let in_macro = ref false
 
 
@@ -85,7 +86,7 @@ let display e = raise (Display e)
 
 
 let is_resuming p =
 let is_resuming p =
 	let p2 = !resume_display in
 	let p2 = !resume_display in
-	p.pmax = p2.pmin && Common.unique_full_path p.pfile = p2.pfile
+	p.pmax = p2.pmin && !use_parser_resume && Common.unique_full_path p.pfile = p2.pfile
 
 
 let set_resume p =
 let set_resume p =
 	resume_display := { p with pfile = Common.unique_full_path p.pfile }
 	resume_display := { p with pfile = Common.unique_full_path p.pfile }
@@ -369,7 +370,20 @@ let reify in_macro =
 				to_obj fields p
 				to_obj fields p
 			) vl p]
 			) vl p]
 		| EFunction (name,f) ->
 		| EFunction (name,f) ->
-			expr "EFunction" [to_opt to_string name p; to_fun f p]
+			let name = match name with
+				| None ->
+					to_null p
+				| Some name ->
+					if ExtString.String.starts_with name "inline_$" then begin
+						let real_name = (String.sub name 7 (String.length name - 7)) in
+						let e_name = to_string real_name p in
+						let e_inline = to_string "inline_" p in
+						let e_add = (EBinop(OpAdd,e_inline,e_name),p) in
+						e_add
+					end else
+						to_string name p
+			in
+			expr "EFunction" [name; to_fun f p]
 		| EBlock el ->
 		| EBlock el ->
 			expr "EBlock" [to_expr_array el p]
 			expr "EBlock" [to_expr_array el p]
 		| EFor (e1,e2) ->
 		| EFor (e1,e2) ->
@@ -774,8 +788,11 @@ and parse_class_flags = parser
 	| [< '(Kwd Class,p) >] -> [] , p
 	| [< '(Kwd Class,p) >] -> [] , p
 	| [< '(Kwd Interface,p) >] -> [HInterface] , p
 	| [< '(Kwd Interface,p) >] -> [HInterface] , p
 
 
+and parse_type_hint = parser
+	| [< '(DblDot,_); t = parse_complex_type >] -> t
+
 and parse_type_opt = parser
 and parse_type_opt = parser
-	| [< '(DblDot,_); t = parse_complex_type >] -> Some t
+	| [< t = parse_type_hint >] -> Some t
 	| [< >] -> None
 	| [< >] -> None
 
 
 and parse_complex_type s =
 and parse_complex_type s =
@@ -869,7 +886,7 @@ and parse_complex_type_next t = parser
 
 
 and parse_type_anonymous opt = parser
 and parse_type_anonymous opt = parser
 	| [< '(Question,_) when not opt; s >] -> parse_type_anonymous true s
 	| [< '(Question,_) when not opt; s >] -> parse_type_anonymous true s
-	| [< name, p1 = ident; '(DblDot,_); t = parse_complex_type; s >] ->
+	| [< name, p1 = ident; t = parse_type_hint; s >] ->
 		let next p2 acc =
 		let next p2 acc =
 			{
 			{
 				cff_name = name;
 				cff_name = name;
@@ -898,10 +915,7 @@ and parse_enum s =
 		| [< '(POpen,_); l = psep Comma parse_enum_param; '(PClose,_) >] -> l
 		| [< '(POpen,_); l = psep Comma parse_enum_param; '(PClose,_) >] -> l
 		| [< >] -> []
 		| [< >] -> []
 		) in
 		) in
-		let t = (match s with parser
-		| [< '(DblDot,_); t = parse_complex_type >] -> Some t
-		| [< >] -> None
-		) in
+		let t = parse_type_opt s in
 		let p2 = (match s with parser
 		let p2 = (match s with parser
 			| [< p = semicolon >] -> p
 			| [< p = semicolon >] -> p
 			| [< >] -> serror()
 			| [< >] -> serror()
@@ -917,8 +931,8 @@ and parse_enum s =
 		}
 		}
 
 
 and parse_enum_param = parser
 and parse_enum_param = parser
-	| [< '(Question,_); name, _ = ident; '(DblDot,_); t = parse_complex_type >] -> (name,true,t)
-	| [< name, _ = ident; '(DblDot,_); t = parse_complex_type >] -> (name,false,t)
+	| [< '(Question,_); name, _ = ident; t = parse_type_hint >] -> (name,true,t)
+	| [< name, _ = ident; t = parse_type_hint >] -> (name,false,t)
 
 
 and parse_class_field s =
 and parse_class_field s =
 	let doc = get_doc s in
 	let doc = get_doc s in
@@ -928,10 +942,7 @@ and parse_class_field s =
 		| [< '(Kwd Var,p1); name, _ = dollar_ident; s >] ->
 		| [< '(Kwd Var,p1); name, _ = dollar_ident; s >] ->
 			(match s with parser
 			(match s with parser
 			| [< '(POpen,_); i1 = property_ident; '(Comma,_); i2 = property_ident; '(PClose,_) >] ->
 			| [< '(POpen,_); i1 = property_ident; '(Comma,_); i2 = property_ident; '(PClose,_) >] ->
-				let t = (match s with parser
-					| [< '(DblDot,_); t = parse_complex_type >] -> Some t
-					| [< >] -> None
-				) in
+				let t = parse_type_opt s in
 				let e , p2 = (match s with parser
 				let e , p2 = (match s with parser
 				| [< '(Binop OpAssign,_); e = toplevel_expr; p2 = semicolon >] -> Some e , p2
 				| [< '(Binop OpAssign,_); e = toplevel_expr; p2 = semicolon >] -> Some e , p2
 				| [< '(Semicolon,p2) >] -> None , p2
 				| [< '(Semicolon,p2) >] -> None , p2
@@ -995,8 +1006,8 @@ and parse_fun_param_value = parser
 	| [< >] -> None
 	| [< >] -> None
 
 
 and parse_fun_param_type = parser
 and parse_fun_param_type = parser
-	| [< '(Question,_); name = ident; '(DblDot,_); t = parse_complex_type >] -> (name,true,t)
-	| [< name = ident; '(DblDot,_); t = parse_complex_type >] -> (name,false,t)
+	| [< '(Question,_); name = ident; t = parse_type_hint >] -> (name,true,t)
+	| [< name = ident; t = parse_type_hint >] -> (name,false,t)
 
 
 and parse_constraint_params = parser
 and parse_constraint_params = parser
 	| [< '(Binop OpLt,_); l = psep Comma parse_constraint_param; '(Binop OpGt,_) >] -> l
 	| [< '(Binop OpLt,_); l = psep Comma parse_constraint_param; '(Binop OpGt,_) >] -> l
@@ -1143,7 +1154,7 @@ and expr = parser
 		| [< >] -> serror())
 		| [< >] -> serror())
 	| [< '(POpen,p1); e = expr; s >] -> (match s with parser
 	| [< '(POpen,p1); e = expr; s >] -> (match s with parser
 		| [< '(PClose,p2); s >] -> expr_next (EParenthesis e, punion p1 p2) s
 		| [< '(PClose,p2); s >] -> expr_next (EParenthesis e, punion p1 p2) s
-		| [< '(DblDot,_); t = parse_complex_type; '(PClose,p2); s >] -> expr_next (EParenthesis (ECheckType(e,t),punion p1 p2), punion p1 p2) s)
+		| [< t = parse_type_hint; '(PClose,p2); s >] -> expr_next (EParenthesis (ECheckType(e,t),punion p1 p2), punion p1 p2) s)
 	| [< '(BkOpen,p1); l = parse_array_decl; '(BkClose,p2); s >] -> expr_next (EArrayDecl l, punion p1 p2) s
 	| [< '(BkOpen,p1); l = parse_array_decl; '(BkClose,p2); s >] -> expr_next (EArrayDecl l, punion p1 p2) s
 	| [< inl, p1 = inline_function; name = popt dollar_ident; pl = parse_constraint_params; '(POpen,_); al = psep Comma parse_fun_param; '(PClose,_); t = parse_type_opt; s >] ->
 	| [< inl, p1 = inline_function; name = popt dollar_ident; pl = parse_constraint_params; '(POpen,_); al = psep Comma parse_fun_param; '(PClose,_); t = parse_type_opt; s >] ->
 		let make e =
 		let make e =
@@ -1295,7 +1306,7 @@ and parse_switch_cases eswitch cases = parser
 and parse_catch etry = parser
 and parse_catch etry = parser
 	| [< '(Kwd Catch,p); '(POpen,_); name, _ = dollar_ident; s >] ->
 	| [< '(Kwd Catch,p); '(POpen,_); name, _ = dollar_ident; s >] ->
 		match s with parser
 		match s with parser
-		| [< '(DblDot,_); t = parse_complex_type; '(PClose,_); s >] ->
+		| [< t = parse_type_hint; '(PClose,_); s >] ->
 			(try
 			(try
 				(name,t,secure_expr s)
 				(name,t,secure_expr s)
 			with
 			with

+ 39 - 48
std/Math.hx

@@ -22,11 +22,11 @@
 /**
 /**
 	This class defines mathematical functions and constants.
 	This class defines mathematical functions and constants.
 **/
 **/
-#if cpp @:include("hxMath") #end
+#if cpp @:include("hxMath.h") #end
 extern class Math
 extern class Math
 {
 {
 	/**
 	/**
-		Represents the ratio of the circumference of a circle to its diameter, 
+		Represents the ratio of the circumference of a circle to its diameter,
 		specified by the constant, π. `PI` is approximately 3.141592653589793.
 		specified by the constant, π. `PI` is approximately 3.141592653589793.
 	**/
 	**/
 	static var PI(default,null) : Float;
 	static var PI(default,null) : Float;
@@ -37,7 +37,7 @@ extern class Math
 		For example, this is the result of -1.0 / 0.0.
 		For example, this is the result of -1.0 / 0.0.
 
 
 		Operations with NEGATIVE_INFINITY as an operand may result in
 		Operations with NEGATIVE_INFINITY as an operand may result in
-		NEGATIVE_INFINITY, POSITIVE_INFINITY or NaN. 
+		NEGATIVE_INFINITY, POSITIVE_INFINITY or NaN.
 
 
 		If this constant is converted to an Int, e.g. through Std.int(), the
 		If this constant is converted to an Int, e.g. through Std.int(), the
 		result is unspecified.
 		result is unspecified.
@@ -50,7 +50,7 @@ extern class Math
 		For example, this is the result of 1.0 / 0.0.
 		For example, this is the result of 1.0 / 0.0.
 
 
 		Operations with POSITIVE_INFINITY as an operand may result in
 		Operations with POSITIVE_INFINITY as an operand may result in
-		NEGATIVE_INFINITY, POSITIVE_INFINITY or NaN. 
+		NEGATIVE_INFINITY, POSITIVE_INFINITY or NaN.
 
 
 		If this constant is converted to an Int, e.g. through Std.int(), the
 		If this constant is converted to an Int, e.g. through Std.int(), the
 		result is unspecified.
 		result is unspecified.
@@ -72,7 +72,7 @@ extern class Math
 		In order to test if a value is NaN, you should use Math.isNaN() function.
 		In order to test if a value is NaN, you should use Math.isNaN() function.
 
 
 		@php In PHP versions prior to 5.3.1 VC 9 there may be unexpected
 		@php In PHP versions prior to 5.3.1 VC 9 there may be unexpected
-		results when performing arithmetic operations with NaN on Windows, 
+		results when performing arithmetic operations with NaN on Windows,
 		see [https://bugs.php.net/bug.php?id=42143]
 		see [https://bugs.php.net/bug.php?id=42143]
 	**/
 	**/
 	static var NaN(default, null) : Float;
 	static var NaN(default, null) : Float;
@@ -80,12 +80,12 @@ extern class Math
 	/**
 	/**
 		Returns the absolute value of `v`.
 		Returns the absolute value of `v`.
 
 
-		If `v` is positive or 0, the result is unchanged. Otherwise the result 
+		If `v` is positive or 0, the result is unchanged. Otherwise the result
 		is -`v`.
 		is -`v`.
-		
-		If `v` is NEGATIVE_INFINITY or POSITIVE_INFINITY, the result is 
+
+		If `v` is NEGATIVE_INFINITY or POSITIVE_INFINITY, the result is
 		POSITIVE_INFINITY.
 		POSITIVE_INFINITY.
-		
+
 		If `v` is NaN, the result is NaN.
 		If `v` is NaN, the result is NaN.
 	**/
 	**/
 	static function abs(v:Float):Float;
 	static function abs(v:Float):Float;
@@ -110,62 +110,62 @@ extern class Math
 
 
 	/**
 	/**
 		Returns the trigonometric sine of the specified angle `v`, in radians.
 		Returns the trigonometric sine of the specified angle `v`, in radians.
-		
+
 		If `v` is NaN or infinite, the result is NaN.
 		If `v` is NaN or infinite, the result is NaN.
 	**/
 	**/
 	static function sin(v:Float):Float;
 	static function sin(v:Float):Float;
 
 
 	/**
 	/**
 		Returns the trigonometric cosine of the specified angle `v`, in radians.
 		Returns the trigonometric cosine of the specified angle `v`, in radians.
-		
+
 		If `v` is NaN or infinite, the result is NaN.
 		If `v` is NaN or infinite, the result is NaN.
 	**/
 	**/
 	static function cos(v:Float):Float;
 	static function cos(v:Float):Float;
 
 
 	/**
 	/**
 		Returns the trigonometric tangent of the specified angle `v`, in radians.
 		Returns the trigonometric tangent of the specified angle `v`, in radians.
-		
+
 		If `v` is NaN or infinite, the result is NaN.
 		If `v` is NaN or infinite, the result is NaN.
 	**/
 	**/
 	static function tan(v:Float):Float;
 	static function tan(v:Float):Float;
 
 
 	/**
 	/**
 		Returns the trigonometric arc of the specified angle `v`, in radians.
 		Returns the trigonometric arc of the specified angle `v`, in radians.
-		
+
 		If `v` is NaN or infinite, the result is NaN.
 		If `v` is NaN or infinite, the result is NaN.
 	**/
 	**/
 	static function asin(v:Float):Float;
 	static function asin(v:Float):Float;
 
 
 	/**
 	/**
-		Returns the trigonometric arc cosine of the specified angle `v`, 
+		Returns the trigonometric arc cosine of the specified angle `v`,
 		in radians.
 		in radians.
-		
+
 		If `v` is NaN or infinite, the result is NaN.
 		If `v` is NaN or infinite, the result is NaN.
 	**/
 	**/
 	static function acos(v:Float):Float;
 	static function acos(v:Float):Float;
 
 
 	/**
 	/**
-		Returns the trigonometric arc tangent of the specified angle `v`, 
+		Returns the trigonometric arc tangent of the specified angle `v`,
 		in radians.
 		in radians.
-		
+
 		If `v` is NaN or infinite, the result is NaN.
 		If `v` is NaN or infinite, the result is NaN.
 	**/
 	**/
 	static function atan(v:Float):Float;
 	static function atan(v:Float):Float;
 
 
 	/**
 	/**
-		Returns the trigonometric arc tangent whose tangent is the quotient of 
+		Returns the trigonometric arc tangent whose tangent is the quotient of
 		two specified numbers, in radians.
 		two specified numbers, in radians.
-		
-		If parameter `x` or `y`  is NaN, NEGATIVE_INFINITY or POSITIVE_INFINITY, 
+
+		If parameter `x` or `y`  is NaN, NEGATIVE_INFINITY or POSITIVE_INFINITY,
 		the result is NaN.
 		the result is NaN.
 	**/
 	**/
 	static function atan2(y:Float, x:Float):Float;
 	static function atan2(y:Float, x:Float):Float;
 
 
 	/**
 	/**
 		Returns Euler's number, raised to the power of `v`.
 		Returns Euler's number, raised to the power of `v`.
-		
+
 		exp(1.0) is approximately 2.718281828459.
 		exp(1.0) is approximately 2.718281828459.
-		
+
 		If `v` is POSITIVE_INFINITY, the result is POSITIVE_INFINITY.
 		If `v` is POSITIVE_INFINITY, the result is POSITIVE_INFINITY.
 		If `v` is NEGATIVE_INFINITY, the result is 0.0.
 		If `v` is NEGATIVE_INFINITY, the result is 0.0.
 		If `v` is NaN, the result is NaN.
 		If `v` is NaN, the result is NaN.
@@ -174,11 +174,11 @@ extern class Math
 
 
 	/**
 	/**
 		Returns the natural logarithm of `v`.
 		Returns the natural logarithm of `v`.
-		
-		This is the mathematical inverse operation of exp, 
+
+		This is the mathematical inverse operation of exp,
 		i.e. `log(exp(v)) == v` always holds.
 		i.e. `log(exp(v)) == v` always holds.
-		
-		If `v` is negative (including NEGATIVE_INFINITY) or NaN, the result 
+
+		If `v` is negative (including NEGATIVE_INFINITY) or NaN, the result
 		is NaN.
 		is NaN.
 		If `v` is POSITIVE_INFINITY, the result is POSITIVE_INFINITY.
 		If `v` is POSITIVE_INFINITY, the result is POSITIVE_INFINITY.
 		If `v` is 0.0, the result is NEGATIVE_INFINITY.
 		If `v` is 0.0, the result is NEGATIVE_INFINITY.
@@ -192,8 +192,8 @@ extern class Math
 
 
 	/**
 	/**
 		Returns the square root of `v`.
 		Returns the square root of `v`.
-		
-		If `v` is negative (including NEGATIVE_INFINITY) or NaN, the result 
+
+		If `v` is negative (including NEGATIVE_INFINITY) or NaN, the result
 		is NaN.
 		is NaN.
 		If `v` is POSITIVE_INFINITY, the result is POSITIVE_INFINITY.
 		If `v` is POSITIVE_INFINITY, the result is POSITIVE_INFINITY.
 		If `v` is 0.0, the result is 0.0.
 		If `v` is 0.0, the result is 0.0.
@@ -202,8 +202,8 @@ extern class Math
 
 
 	/**
 	/**
 		Rounds `v` to the nearest integer value.
 		Rounds `v` to the nearest integer value.
-		
-		If `v` is outside of the signed Int32 range, or is NaN, NEGATIVE_INFINITY 
+
+		If `v` is outside of the signed Int32 range, or is NaN, NEGATIVE_INFINITY
 		or POSITIVE_INFINITY, the result is unspecified.
 		or POSITIVE_INFINITY, the result is unspecified.
 	**/
 	**/
 	static function round(v:Float):Int;
 	static function round(v:Float):Int;
@@ -211,7 +211,7 @@ extern class Math
 	/**
 	/**
 		Returns the largest integer value that is not greater than `v`.
 		Returns the largest integer value that is not greater than `v`.
 
 
-		If `v` is outside of the signed Int32 range, or is NaN, NEGATIVE_INFINITY 
+		If `v` is outside of the signed Int32 range, or is NaN, NEGATIVE_INFINITY
 		or POSITIVE_INFINITY, the result is unspecified.
 		or POSITIVE_INFINITY, the result is unspecified.
 	**/
 	**/
 	static function floor(v:Float):Int;
 	static function floor(v:Float):Int;
@@ -219,13 +219,13 @@ extern class Math
 	/**
 	/**
 		Returns the smallest integer value that is not less than `v`.
 		Returns the smallest integer value that is not less than `v`.
 
 
-		If `v` is outside of the signed Int32 range, or is NaN, NEGATIVE_INFINITY 
+		If `v` is outside of the signed Int32 range, or is NaN, NEGATIVE_INFINITY
 		or POSITIVE_INFINITY, the result is unspecified.
 		or POSITIVE_INFINITY, the result is unspecified.
 	**/
 	**/
 	static function ceil(v:Float):Int;
 	static function ceil(v:Float):Int;
 
 
 	/**
 	/**
-		Returns a pseudo-random number which is greater than or equal to 0.0, 
+		Returns a pseudo-random number which is greater than or equal to 0.0,
 		and less than 1.0.
 		and less than 1.0.
 	**/
 	**/
 	static function random() : Float;
 	static function random() : Float;
@@ -234,7 +234,7 @@ extern class Math
 	/**
 	/**
 		Returns the largest integer value that is not greater than `v`, as a Float.
 		Returns the largest integer value that is not greater than `v`, as a Float.
 
 
-		If `v` is is NaN, NEGATIVE_INFINITY or POSITIVE_INFINITY, 
+		If `v` is is NaN, NEGATIVE_INFINITY or POSITIVE_INFINITY,
 		the result is unspecified.
 		the result is unspecified.
 	**/
 	**/
 	static function ffloor( v : Float ) : Float;
 	static function ffloor( v : Float ) : Float;
@@ -242,7 +242,7 @@ extern class Math
 	/**
 	/**
 		Returns the smallest integer value that is not less than `v`, as a Float.
 		Returns the smallest integer value that is not less than `v`, as a Float.
 
 
-		If `v` is is NaN, NEGATIVE_INFINITY or POSITIVE_INFINITY, 
+		If `v` is is NaN, NEGATIVE_INFINITY or POSITIVE_INFINITY,
 		the result is unspecified.
 		the result is unspecified.
 	**/
 	**/
 	static function fceil( v : Float ) : Float;
 	static function fceil( v : Float ) : Float;
@@ -250,7 +250,7 @@ extern class Math
 	/**
 	/**
 		Rounds `v` to the nearest integer value, as a Float.
 		Rounds `v` to the nearest integer value, as a Float.
 
 
-		If `v` is is NaN, NEGATIVE_INFINITY or POSITIVE_INFINITY, 
+		If `v` is is NaN, NEGATIVE_INFINITY or POSITIVE_INFINITY,
 		the result is unspecified.
 		the result is unspecified.
 	**/
 	**/
 	static function fround( v : Float ) : Float;
 	static function fround( v : Float ) : Float;
@@ -275,7 +275,7 @@ extern class Math
 	/**
 	/**
 		Tells if `f` is a finite number.
 		Tells if `f` is a finite number.
 
 
-		If `f` is POSITIVE_INFINITY, NEGATIVE_INFINITY or NaN, the result 
+		If `f` is POSITIVE_INFINITY, NEGATIVE_INFINITY or NaN, the result
 		is false, otherwise the result is true.
 		is false, otherwise the result is true.
 	**/
 	**/
 	static function isFinite( f : Float ) : Bool;
 	static function isFinite( f : Float ) : Bool;
@@ -283,7 +283,7 @@ extern class Math
 	/**
 	/**
 		Tells if `f` is not a valid number.
 		Tells if `f` is not a valid number.
 
 
-		If `f` is NaN, the result is true, otherwise the result is false. 
+		If `f` is NaN, the result is true, otherwise the result is false.
 		In particular, both POSITIVE_INFINITY and NEGATIVE_INFINITY are
 		In particular, both POSITIVE_INFINITY and NEGATIVE_INFINITY are
 		not considered NaN.
 		not considered NaN.
 	**/
 	**/
@@ -295,15 +295,10 @@ extern class Math
 		NEGATIVE_INFINITY = __global__["Number"].NEGATIVE_INFINITY;
 		NEGATIVE_INFINITY = __global__["Number"].NEGATIVE_INFINITY;
 		POSITIVE_INFINITY = __global__["Number"].POSITIVE_INFINITY;
 		POSITIVE_INFINITY = __global__["Number"].POSITIVE_INFINITY;
 	#else
 	#else
-		#if !js // genjs.ml will insert this only if necessary.
-			Math.__name__ = ["Math"];
-		#end
+		Math.__name__ = ["Math"];
 		Math.NaN = Number["NaN"];
 		Math.NaN = Number["NaN"];
 		Math.NEGATIVE_INFINITY = Number["NEGATIVE_INFINITY"];
 		Math.NEGATIVE_INFINITY = Number["NEGATIVE_INFINITY"];
 		Math.POSITIVE_INFINITY = Number["POSITIVE_INFINITY"];
 		Math.POSITIVE_INFINITY = Number["POSITIVE_INFINITY"];
-	#end
-	#if js
-		__feature__("Type.resolveClass",$hxClasses['Math'] = Math);
 	#end
 	#end
 		Math.isFinite = function(i) {
 		Math.isFinite = function(i) {
 			return
 			return
@@ -311,8 +306,6 @@ extern class Math
 			__global__["isFinite"](i);
 			__global__["isFinite"](i);
 			#elseif flash
 			#elseif flash
 			_global["isFinite"](i);
 			_global["isFinite"](i);
-			#elseif js
-			__js__("isFinite")(i);
 			#else
 			#else
 			false;
 			false;
 			#end
 			#end
@@ -323,8 +316,6 @@ extern class Math
 			__global__["isNaN"](i);
 			__global__["isNaN"](i);
 			#elseif flash
 			#elseif flash
 			_global["isNaN"](i);
 			_global["isNaN"](i);
-			#elseif js
-			__js__("isNaN")(i);
 			#else
 			#else
 			false;
 			false;
 			#end
 			#end

+ 31 - 33
std/StringTools.hx

@@ -33,26 +33,25 @@ class StringTools {
 	/**
 	/**
 		Encode an URL by using the standard format.
 		Encode an URL by using the standard format.
 	**/
 	**/
-	#if (!java && !cpp) inline #end public static function urlEncode( s : String ) : String untyped {
+	#if (!java && !cpp) inline #end public static function urlEncode( s : String ) : String {
 		#if flash9
 		#if flash9
-			return __global__["encodeURIComponent"](s);
+			return untyped __global__["encodeURIComponent"](s);
 		#elseif flash
 		#elseif flash
-			return _global["escape"](s);
+			return untyped _global["escape"](s);
 		#elseif neko
 		#elseif neko
-			return new String(_urlEncode(s.__s));
+			return untyped new String(_urlEncode(s.__s));
 		#elseif js
 		#elseif js
-			return encodeURIComponent(s);
+			return untyped encodeURIComponent(s);
 		#elseif cpp
 		#elseif cpp
-			return s.__URLEncode();
+			return untyped s.__URLEncode();
 		#elseif java
 		#elseif java
 			try
 			try
 				return untyped __java__("java.net.URLEncoder.encode(s, \"UTF-8\")")
 				return untyped __java__("java.net.URLEncoder.encode(s, \"UTF-8\")")
 			catch (e:Dynamic) throw e;
 			catch (e:Dynamic) throw e;
 		#elseif cs
 		#elseif cs
-			return cs.system.Uri.EscapeUriString(s);
+			return untyped cs.system.Uri.EscapeUriString(s);
 		#elseif python
 		#elseif python
-			python.Syntax.pythonCode("from urllib.parse import quote");
-			return quote(s);
+			return python.lib.urllib.Parse.quote(s);
 		#else
 		#else
 			return null;
 			return null;
 		#end
 		#end
@@ -61,26 +60,25 @@ class StringTools {
 	/**
 	/**
 		Decode an URL using the standard format.
 		Decode an URL using the standard format.
 	**/
 	**/
-	#if (!java && !cpp) inline #end public static function urlDecode( s : String ) : String untyped {
+	#if (!java && !cpp) inline #end public static function urlDecode( s : String ) : String {
 		#if flash9
 		#if flash9
-			return __global__["decodeURIComponent"](s.split("+").join(" "));
+			return untyped __global__["decodeURIComponent"](s.split("+").join(" "));
 		#elseif flash
 		#elseif flash
-			return _global["unescape"](s);
+			return untyped _global["unescape"](s);
 		#elseif neko
 		#elseif neko
-			return new String(_urlDecode(s.__s));
+			return untyped new String(_urlDecode(s.__s));
 		#elseif js
 		#elseif js
-			return decodeURIComponent(s.split("+").join(" "));
+			return untyped decodeURIComponent(s.split("+").join(" "));
 		#elseif cpp
 		#elseif cpp
-			return s.__URLDecode();
+			return untyped s.__URLDecode();
 		#elseif java
 		#elseif java
 			try
 			try
 				return untyped __java__("java.net.URLDecoder.decode(s, \"UTF-8\")")
 				return untyped __java__("java.net.URLDecoder.decode(s, \"UTF-8\")")
 			catch (e:Dynamic) throw e;
 			catch (e:Dynamic) throw e;
 		#elseif cs
 		#elseif cs
-			return cs.system.Uri.UnescapeDataString(s);
+			return untyped cs.system.Uri.UnescapeDataString(s);
 		#elseif python
 		#elseif python
-			python.Syntax.pythonCode("from urllib.parse import unquote");
-			return unquote(s);
+			return python.lib.urllib.Parse.unquote(s);
 		#else
 		#else
 			return null;
 			return null;
 		#end
 		#end
@@ -348,38 +346,38 @@ class StringTools {
 	}
 	}
 
 
 	/**
 	/**
-		Returns the character code at position `index` of String `s`.
+		Returns the character code at position `index` of String `s`, or an
+		end-of-file indicator at if `position` equals `s.length`.
 
 
-		This method is faster than String.charCodeAt() on most platforms.
-		However, unlike String.charCodeAt(), the result is unspecified if
-		`index` is negative or exceeds `s.length`.
+		This method is faster than String.charCodeAt() on some platforms, but
+		the result is unspecified if `index` is negative or greater than
+		`s.length`.
+
+		End of file status can be checked by calling `StringTools.isEof` with
+		the returned value as argument.
 
 
 		This operation is not guaranteed to work if `s` contains the \0
 		This operation is not guaranteed to work if `s` contains the \0
 		character.
 		character.
 	**/
 	**/
-	public static inline function fastCodeAt( s : String, index : Int ) : Int untyped {
+	public static inline function fastCodeAt( s : String, index : Int ) : Int {
 		#if neko
 		#if neko
 		return untyped __dollar__sget(s.__s, index);
 		return untyped __dollar__sget(s.__s, index);
 		#elseif cpp
 		#elseif cpp
-		return s.cca(index);
+		return untyped s.cca(index);
 		#elseif flash9
 		#elseif flash9
-		return s.cca(index);
+		return untyped s.cca(index);
 		#elseif flash
 		#elseif flash
-		return s["cca"](index);
+		return untyped s["cca"](index);
 		#elseif java
 		#elseif java
 		return ( index < s.length ) ? cast(_charAt(s, index), Int) : -1;
 		return ( index < s.length ) ? cast(_charAt(s, index), Int) : -1;
 		#elseif cs
 		#elseif cs
-		return ( cast(index, UInt) < s.length ) ? cast(untyped s[index], Int) : -1;
+		return ( cast(index, UInt) < s.length ) ? cast(s[index], Int) : -1;
 		#elseif js
 		#elseif js
-			#if mt
-		return (untyped s).cca(index);
-			#else
 		return (untyped s).charCodeAt(index);
 		return (untyped s).charCodeAt(index);
-			#end
 		#elseif python
 		#elseif python
-		return if (index >= s.length) -1 else untyped(ord(untyped s[index]));
+		return if (index >= s.length) -1 else python.lib.Builtin.ord(python.Syntax.arrayAccess(s, index));
 		#else
 		#else
-		return s.cca(index);
+		return untyped s.cca(index);
 		#end
 		#end
 	}
 	}
 
 

+ 19 - 0
std/cpp/BasePointer.hx

@@ -0,0 +1,19 @@
+package cpp;
+
+@:coreType @:include("cpp/Pointer.h")
+extern class BasePointer<T>
+{
+   // ptr actually returns the pointer - not strictly a 'T' - for pointers to smart pointers
+   // Use value or ref to get dereferenced value
+	public var ptr:T;
+
+	public var value(get,never):T;
+
+	public function lt(inOther:BasePointer<T>):Bool;
+	public function leq(inOther:BasePointer<T>):Bool;
+	public function gt(inOther:BasePointer<T>):Bool;
+	public function geq(inOther:BasePointer<T>):Bool;
+
+}
+
+

+ 3 - 0
std/cpp/Char.hx

@@ -0,0 +1,3 @@
+package cpp;
+
+@:coreType @:notNull @:runtimeValue abstract Char from Int to Int {}

+ 19 - 0
std/cpp/ConstPointer.hx

@@ -0,0 +1,19 @@
+package cpp;
+
+@:coreType @:include("cpp/Pointer.h") @:native("cpp.Pointer")
+extern class ConstPointer<T> extends BasePointer<T>
+{
+   public static function fromPointer<T>(inNativePointer:Dynamic) : ConstPointer<T>;
+
+	public function reinterpret<Other>():Pointer<Other>;
+
+	public function at(inIndex:Int):T;
+
+	public function inc():ConstPointer<T>;
+	public function dec():ConstPointer<T>;
+	public function postIncVal():T;
+	public function incBy(inT:Int):ConstPointer<T>;
+	public function add(inT:Int):ConstPointer<T>;
+
+}
+

+ 3 - 0
std/cpp/Float32.hx

@@ -0,0 +1,3 @@
+package cpp;
+
+@:coreType @:notNull @:runtimeValue abstract Float32 from Float to Float {}

+ 3 - 0
std/cpp/Float64.hx

@@ -0,0 +1,3 @@
+package cpp;
+
+@:coreType @:notNull @:runtimeValue abstract Float64 from Float to Float {}

+ 20 - 0
std/cpp/Function.hx

@@ -0,0 +1,20 @@
+package cpp;
+
+@:coreType @:structAccess @:include("cpp/Pointer.h")
+extern class Function<T>
+{
+   // Actually a function pointer, but can be called using haxe notation
+	public var call(default,null):T;
+
+   public static function getProcAddress<T>(inModule:String, inFunction:String) : Function<T>;
+   public static function fromStaticFunction<T>(inStaticFunction:T) : Function<T>;
+
+	public function lt(inOther:Function<T>):Bool;
+	public function leq(inOther:Function<T>):Bool;
+	public function gt(inOther:Function<T>):Bool;
+	public function geq(inOther:Function<T>):Bool;
+
+
+}
+
+

+ 3 - 0
std/cpp/Int16.hx

@@ -0,0 +1,3 @@
+package cpp;
+
+@:coreType @:notNull @:runtimeValue abstract Int16 from Int to Int {}

+ 3 - 0
std/cpp/Int32.hx

@@ -0,0 +1,3 @@
+package cpp;
+
+@:coreType @:notNull @:runtimeValue abstract Int32 from Int to Int {}

+ 3 - 0
std/cpp/Int64.hx

@@ -0,0 +1,3 @@
+package cpp;
+
+@:coreType @:notNull @:runtimeValue abstract Int64 from Int to Int {}

+ 3 - 0
std/cpp/Int8.hx

@@ -0,0 +1,3 @@
+package cpp;
+
+@:coreType @:notNull @:runtimeValue abstract Int8 from Int to Int {}

+ 12 - 0
std/cpp/NativeString.hx

@@ -0,0 +1,12 @@
+package cpp;
+
+extern class NativeString {
+
+	public static inline function c_str( inString:String ) : ConstPointer<Char> {
+		return cpp.ConstPointer.fromPointer(untyped inString.__s);
+   }
+	public static inline function fromPointer(inPtr:ConstPointer<Char> ) : String {
+      return untyped __global__.String(inPtr.ptr);
+   }
+}
+

+ 18 - 9
std/cpp/Pointer.hx

@@ -1,17 +1,26 @@
 package cpp;
 package cpp;
 
 
-
-extern class Pointer<T> implements ArrayAccess<T>
+@:coreType
+extern class Pointer<T> extends ConstPointer<T> implements ArrayAccess<T>
 {
 {
-	public static function fromArray<T>(array:Array<T>, inIdx:Int):Pointer<T>;
+	public var ref(get,set):T;
+
+   public static function fromHandle<T>(inHandle:Dynamic,?inKind:String) : Pointer<T>;
+
+   public static function fromPointer<T>(inNativePointer:Dynamic) : Pointer<T>;
+
+   public static function addressOf<T>(inVariable:T) : Pointer<T>;
+
+	public static function arrayElem<T>(array:Array<T>, inElem:Int):Pointer<T>;
 
 
-	public function inc():Void;
-	public function dec():Void;
-	public function add(inT:Int):Void;
+	override public function inc():Pointer<T>;
+	override public function dec():Pointer<T>;
+	override public function incBy(inT:Int):Pointer<T>;
+	override public function add(inT:Int):Pointer<T>;
 
 
-   // ptr actually returns the pointer, so the ->member sysntax will work
-   // Use [0] for a reference to the item
-	public function ptr():T;
+	public function postIncRef():T;
 
 
+	public function destroy():Void;
+	public function destroyArray():Void;
 }
 }
 
 

+ 3 - 0
std/cpp/UInt16.hx

@@ -0,0 +1,3 @@
+package cpp;
+
+@:coreType @:notNull @:runtimeValue abstract UInt16 from Int to Int {}

+ 3 - 0
std/cpp/UInt32.hx

@@ -0,0 +1,3 @@
+package cpp;
+
+@:coreType @:notNull @:runtimeValue abstract UInt32 from Int to Int {}

+ 3 - 0
std/cpp/UInt64.hx

@@ -0,0 +1,3 @@
+package cpp;
+
+@:coreType @:notNull @:runtimeValue abstract UInt64 from Int to Int {}

+ 3 - 0
std/cpp/UInt8.hx

@@ -0,0 +1,3 @@
+package cpp;
+
+@:coreType @:notNull @:runtimeValue abstract UInt8 from Int to Int {}

+ 1 - 1
std/cpp/vm/Deque.hx

@@ -33,7 +33,7 @@ class Deque<T> {
 	public function push( i : T ) {
 	public function push( i : T ) {
 		untyped __global__.__hxcpp_deque_push(q,i);
 		untyped __global__.__hxcpp_deque_push(q,i);
 	}
 	}
-	public function pop( block : Bool ) : T {
+	public function pop( block : Bool ) : Null<T> {
 		return untyped __global__.__hxcpp_deque_pop(q,block);
 		return untyped __global__.__hxcpp_deque_pop(q,block);
 	}
 	}
 }
 }

+ 7 - 0
std/cpp/vm/Gc.hx

@@ -91,4 +91,11 @@ class Gc
    {
    {
       untyped __global__.__hxcpp_exit_gc_free_zone();
       untyped __global__.__hxcpp_exit_gc_free_zone();
    }
    }
+
+   @:unreflective
+   inline static public function setFinalizer<T>(inObject:T, inFinalizer:cpp.Function<T->Void> ) : Void
+   {
+      untyped __global__.__hxcpp_set_finalizer(inObject, inFinalizer);
+   }
 }
 }
+

+ 3 - 0
std/cs/_std/Array.hx

@@ -28,6 +28,9 @@ import cs.NativeArray;
 		this.length = native.Length;
 		this.length = native.Length;
 	}
 	}
 ')
 ')
+#if core_api_serialize
+@:meta(System.Serializable)
+#end
 @:final @:coreApi class Array<T> implements ArrayAccess<T> {
 @:final @:coreApi class Array<T> implements ArrayAccess<T> {
 
 
 	public var length(default,null) : Int;
 	public var length(default,null) : Int;

+ 3 - 0
std/cs/_std/Date.hx

@@ -24,6 +24,9 @@ import cs.system.DateTime;
 import cs.system.TimeSpan;
 import cs.system.TimeSpan;
 import haxe.Int64;
 import haxe.Int64;
 
 
+#if core_api_serialize
+@:meta(System.Serializable)
+#end
 @:coreApi class Date
 @:coreApi class Date
 {
 {
 	private var date:DateTime;
 	private var date:DateTime;

+ 2 - 0
std/cs/_std/EReg.hx

@@ -42,8 +42,10 @@ class EReg {
 					isGlobal = true;
 					isGlobal = true;
 				case 'm'.code:
 				case 'm'.code:
 					opts |= cast(Multiline, Int);
 					opts |= cast(Multiline, Int);
+#if (!unity && !unity_std_target)
 				case 'c'.code:
 				case 'c'.code:
 					opts |= cast(Compiled, Int);
 					opts |= cast(Compiled, Int);
+#end
 			}
 			}
 		}
 		}
 
 

+ 13 - 0
std/cs/_std/Type.hx

@@ -131,6 +131,19 @@ import cs.internal.Runtime;
 			name = "haxe.root." + name;
 			name = "haxe.root." + name;
 #end
 #end
 		var t:cs.system.Type = cs.system.Type._GetType(name);
 		var t:cs.system.Type = cs.system.Type._GetType(name);
+#if !CF
+		if (t == null)
+		{
+			var all = cs.system.AppDomain.CurrentDomain.GetAssemblies().GetEnumerator();
+			while (all.MoveNext())
+			{
+				var t2:cs.system.reflection.Assembly = all.Current;
+				t = t2.GetType(name);
+				if (t != null)
+					break;
+			}
+		}
+#end
 		if (t == null)
 		if (t == null)
 		{
 		{
 			switch(name)
 			switch(name)

+ 6 - 0
std/cs/internal/HxObject.hx

@@ -33,6 +33,9 @@ private interface IHxObject
 {
 {
 }
 }
 
 
+#if core_api_serialize
+@:meta(System.Serializable)
+#end
 @:keep @:native('haxe.lang.DynamicObject')
 @:keep @:native('haxe.lang.DynamicObject')
 private class DynamicObject extends HxObject implements Dynamic
 private class DynamicObject extends HxObject implements Dynamic
 {
 {
@@ -66,6 +69,9 @@ private class DynamicObject extends HxObject implements Dynamic
 
 
 @:native('haxe.lang.Enum')
 @:native('haxe.lang.Enum')
 @:keep @:skipCtor
 @:keep @:skipCtor
+#if core_api_serialize
+@:meta(System.Serializable)
+#end
 private class Enum
 private class Enum
 {
 {
 	@:readOnly private var index:Int;
 	@:readOnly private var index:Int;

+ 4 - 1
std/cs/internal/Null.hx

@@ -37,6 +37,9 @@ package cs.internal;
 		}
 		}
 	}
 	}
 ')
 ')
+#if core_api_serialize
+@:meta(System.Serializable)
+#end
 @:keep @:struct @:nativeGen @:native("haxe.lang.Null") private class Nullable<T>
 @:keep @:struct @:nativeGen @:native("haxe.lang.Null") private class Nullable<T>
 {
 {
 
 
@@ -84,4 +87,4 @@ package cs.internal;
 	{
 	{
 		return null;
 		return null;
 	}
 	}
-}
+}

+ 6 - 5
std/cs/internal/Runtime.hx

@@ -543,16 +543,17 @@ import cs.system.Type;
 		for (i in 0...params.Length)
 		for (i in 0...params.Length)
 		{
 		{
 			var param = params[i].ParameterType;
 			var param = params[i].ParameterType;
-			var strParam = param + "";
+			var strParam = param + "",
+					arg = oargs[i];
 			if (StringTools.startsWith(strParam, "haxe.lang.Null"))
 			if (StringTools.startsWith(strParam, "haxe.lang.Null"))
 			{
 			{
-				oargs[i] = mkNullable(oargs[i], param);
+				oargs[i] = mkNullable(arg, param);
 			} else if (cast(untyped __typeof__(IConvertible), Type).IsAssignableFrom(param)) {
 			} else if (cast(untyped __typeof__(IConvertible), Type).IsAssignableFrom(param)) {
-				if (oargs[i] == null) {
+				if (arg == null) {
 					if (param.IsValueType)
 					if (param.IsValueType)
 						oargs[i] = Activator.CreateInstance(param);
 						oargs[i] = Activator.CreateInstance(param);
-				} else {
-					oargs[i] = cast(oargs[i], IConvertible).ToType(param, null);
+				} else if (!cs.Lib.nativeType(arg).IsAssignableFrom(param)) {
+					oargs[i] = cast(arg, IConvertible).ToType(param, null);
 				}
 				}
 			}
 			}
 		}
 		}

+ 1 - 1
std/flash/display/Stage3D.hx

@@ -6,5 +6,5 @@ package flash.display;
 	var x : Float;
 	var x : Float;
 	var y : Float;
 	var y : Float;
 	function requestContext3D(?context3DRenderMode : String, ?profile : flash.display3D.Context3DProfile) : Void;
 	function requestContext3D(?context3DRenderMode : String, ?profile : flash.display3D.Context3DProfile) : Void;
-	@:require(flash12) function requestContext3DMatchingProfiles(profiles:Vector<String>) : Void;
+	@:require(flash12) function requestContext3DMatchingProfiles(profiles : flash.Vector<String>) : Void;
 }
 }

+ 4 - 4
std/flash/display3D/Context3D.hx

@@ -3,15 +3,15 @@ package flash.display3D;
 @:final extern class Context3D extends flash.events.EventDispatcher {
 @:final extern class Context3D extends flash.events.EventDispatcher {
 	var driverInfo(default,null) : String;
 	var driverInfo(default,null) : String;
 	var enableErrorChecking : Bool;
 	var enableErrorChecking : Bool;
-	@:require(flash12) var profile : String;
+	@:require(flash12) var profile(default,null) : String;
 	function clear(red : Float = 0, green : Float = 0, blue : Float = 0, alpha : Float = 1, depth : Float = 1, stencil : UInt = 0, mask : UInt = 0xFFFFFFFF) : Void;
 	function clear(red : Float = 0, green : Float = 0, blue : Float = 0, alpha : Float = 1, depth : Float = 1, stencil : UInt = 0, mask : UInt = 0xFFFFFFFF) : Void;
 	function configureBackBuffer(width : Int, height : Int, antiAlias : Int, enableDepthAndStencil : Bool = true, wantsBestResolution : Bool = false) : Void;
 	function configureBackBuffer(width : Int, height : Int, antiAlias : Int, enableDepthAndStencil : Bool = true, wantsBestResolution : Bool = false) : Void;
 	function createCubeTexture(size : Int, format : Context3DTextureFormat, optimizeForRenderToTexture : Bool, streamingLevels : Int = 0) : flash.display3D.textures.CubeTexture;
 	function createCubeTexture(size : Int, format : Context3DTextureFormat, optimizeForRenderToTexture : Bool, streamingLevels : Int = 0) : flash.display3D.textures.CubeTexture;
-	function createIndexBuffer(numIndices : Int) : IndexBuffer3D;
+	function createIndexBuffer(numIndices : Int, ?bufferUsage : Context3DBufferUsage) : IndexBuffer3D;
 	function createProgram() : Program3D;
 	function createProgram() : Program3D;
 	@:require(flash11_8) function createRectangleTexture(width : Int, height : Int, format : Context3DTextureFormat, optimizeForRenderToTexture : Bool) : flash.display3D.textures.RectangleTexture;
 	@:require(flash11_8) function createRectangleTexture(width : Int, height : Int, format : Context3DTextureFormat, optimizeForRenderToTexture : Bool) : flash.display3D.textures.RectangleTexture;
 	function createTexture(width : Int, height : Int, format : Context3DTextureFormat, optimizeForRenderToTexture : Bool, streamingLevels : Int = 0) : flash.display3D.textures.Texture;
 	function createTexture(width : Int, height : Int, format : Context3DTextureFormat, optimizeForRenderToTexture : Bool, streamingLevels : Int = 0) : flash.display3D.textures.Texture;
-	function createVertexBuffer(numVertices : Int, data32PerVertex : Int) : VertexBuffer3D;
+	function createVertexBuffer(numVertices : Int, data32PerVertex : Int, ?bufferUsage : Context3DBufferUsage) : VertexBuffer3D;
 	function dispose(recreate : Bool = true) : Void;
 	function dispose(recreate : Bool = true) : Void;
 	function drawToBitmapData(destination : flash.display.BitmapData) : Void;
 	function drawToBitmapData(destination : flash.display.BitmapData) : Void;
 	function drawTriangles(indexBuffer : IndexBuffer3D, firstIndex : Int = 0, numTriangles : Int = -1) : Void;
 	function drawTriangles(indexBuffer : IndexBuffer3D, firstIndex : Int = 0, numTriangles : Int = -1) : Void;
@@ -25,7 +25,7 @@ package flash.display3D;
 	function setProgramConstantsFromMatrix(programType : Context3DProgramType, firstRegister : Int, matrix : flash.geom.Matrix3D, transposedMatrix : Bool = false) : Void;
 	function setProgramConstantsFromMatrix(programType : Context3DProgramType, firstRegister : Int, matrix : flash.geom.Matrix3D, transposedMatrix : Bool = false) : Void;
 	function setProgramConstantsFromVector(programType : Context3DProgramType, firstRegister : Int, data : flash.Vector<Float>, numRegisters : Int = -1) : Void;
 	function setProgramConstantsFromVector(programType : Context3DProgramType, firstRegister : Int, data : flash.Vector<Float>, numRegisters : Int = -1) : Void;
 	function setRenderToBackBuffer() : Void;
 	function setRenderToBackBuffer() : Void;
-	function setRenderToTexture(texture : flash.display3D.textures.TextureBase, enableDepthAndStencil : Bool = false, antiAlias : Int = 0, surfaceSelector : Int = 0) : Void;
+	function setRenderToTexture(texture : flash.display3D.textures.TextureBase, enableDepthAndStencil : Bool = false, antiAlias : Int = 0, surfaceSelector : Int = 0, colorOutputIndex : Int = 0) : Void;
 	@:require(flash11_6) function setSamplerStateAt(sampler : Int, wrap : Context3DWrapMode, filter : Context3DTextureFilter, mipfilter : Context3DMipFilter) : Void;
 	@:require(flash11_6) function setSamplerStateAt(sampler : Int, wrap : Context3DWrapMode, filter : Context3DTextureFilter, mipfilter : Context3DMipFilter) : Void;
 	function setScissorRectangle(rectangle : flash.geom.Rectangle) : Void;
 	function setScissorRectangle(rectangle : flash.geom.Rectangle) : Void;
 	function setStencilActions(?triangleFace : Context3DTriangleFace, ?compareMode : Context3DCompareMode, ?actionOnBothPass : Context3DStencilAction, ?actionOnDepthFail : Context3DStencilAction, ?actionOnDepthPassStencilFail : Context3DStencilAction) : Void;
 	function setStencilActions(?triangleFace : Context3DTriangleFace, ?compareMode : Context3DCompareMode, ?actionOnBothPass : Context3DStencilAction, ?actionOnDepthFail : Context3DStencilAction, ?actionOnDepthPassStencilFail : Context3DStencilAction) : Void;

+ 6 - 0
std/flash/display3D/Context3DBufferUsage.hx

@@ -0,0 +1,6 @@
+package flash.display3D;
+
+@:require(flash12) @:fakeEnum(String) extern enum Context3DBufferUsage {
+	DYNAMIC_DRAW;
+	STATIC_DRAW;
+}

+ 1 - 0
std/flash/display3D/Context3DProfile.hx

@@ -4,4 +4,5 @@ package flash.display3D;
 	BASELINE;
 	BASELINE;
 	BASELINE_CONSTRAINED;
 	BASELINE_CONSTRAINED;
 	BASELINE_EXTENDED;
 	BASELINE_EXTENDED;
+	STANDARD;
 }
 }

+ 4 - 0
std/flash/display3D/Context3DTextureFilter.hx

@@ -1,6 +1,10 @@
 package flash.display3D;
 package flash.display3D;
 
 
 @:fakeEnum(String) extern enum Context3DTextureFilter {
 @:fakeEnum(String) extern enum Context3DTextureFilter {
+	ANISOTROPIC16X;
+	ANISOTROPIC2X;
+	ANISOTROPIC4X;
+	ANISOTROPIC8X;
 	LINEAR;
 	LINEAR;
 	NEAREST;
 	NEAREST;
 }
 }

+ 1 - 0
std/flash/display3D/Context3DTextureFormat.hx

@@ -6,4 +6,5 @@ package flash.display3D;
 	BGR_PACKED;
 	BGR_PACKED;
 	COMPRESSED;
 	COMPRESSED;
 	COMPRESSED_ALPHA;
 	COMPRESSED_ALPHA;
+	RGBA_HALF_FLOAT;
 }
 }

+ 2 - 0
std/flash/display3D/Context3DWrapMode.hx

@@ -2,5 +2,7 @@ package flash.display3D;
 
 
 @:fakeEnum(String) extern enum Context3DWrapMode {
 @:fakeEnum(String) extern enum Context3DWrapMode {
 	CLAMP;
 	CLAMP;
+	CLAMP_U_REPEAT_V;
 	REPEAT;
 	REPEAT;
+	REPEAT_U_CLAMP_V;
 }
 }

+ 0 - 15
std/flash/utils/Telemetry.hx

@@ -1,15 +0,0 @@
-package flash.utils;
-
-@:require(flash11_2) extern class Telemetry extends flash.events.EventDispatcher {
-	var bufferLength : UInt;
-	var connected(default,null) : Bool;
-	function new() : Void;
-	function enableMetric(metric : String, enable : Bool) : Void;
-	function flush() : Void;
-	function isMetricEnabled(metric : String) : Bool;
-	function registerMethod(functionId : String, f : Dynamic) : Void;
-	function sendMetric(metric : String, value : Dynamic) : Void;
-	function sendSpanMetric(metric : String, startMarker : Float) : Void;
-	static var marker(default,null) : Float;
-	static var telemetry(default,null) : Telemetry;
-}

+ 85 - 0
std/haxe/crypto/Hmac.hx

@@ -0,0 +1,85 @@
+/*
+ * Copyright (C)2005-2012 Haxe Foundation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+package haxe.crypto;
+
+enum HashMethod {
+	MD5;
+	SHA1;
+	SHA256;
+}
+
+class Hmac {
+	
+	var method : HashMethod;
+	var blockSize : Int;
+	var length : Int;
+	
+	public function new( hashMethod : HashMethod ) {
+		method = hashMethod;
+		blockSize = switch ( hashMethod ) {
+			case MD5, SHA1, SHA256: 64;
+		}
+		length = switch ( hashMethod ) {
+			case MD5: 16;
+			case SHA1: 20;
+			case SHA256: 32;
+		}
+	}
+	
+	inline function doHash( b : haxe.io.Bytes ) : haxe.io.Bytes {
+		return switch ( method ) {
+			case MD5: Md5.make(b);
+			case SHA1: Sha1.make(b);
+			case SHA256: Sha256.make(b);
+		}
+	}
+	
+	function nullPad( s : haxe.io.Bytes, chunkLen : Int ) : haxe.io.Bytes {
+		var r = chunkLen - (s.length % chunkLen);
+		if(r == chunkLen && s.length != 0)
+			return s;
+		var sb = new haxe.io.BytesBuffer();
+		sb.add(s);
+		for(x in 0...r)
+			sb.addByte(0);
+		return sb.getBytes();
+	}
+	
+	public function make( key : haxe.io.Bytes, msg : haxe.io.Bytes ) : haxe.io.Bytes {
+		if(key.length > blockSize) {
+			key = doHash(key);
+		}
+		key = nullPad(key, blockSize);
+
+		var Ki = new haxe.io.BytesBuffer();
+		var Ko = new haxe.io.BytesBuffer();
+		for (i in 0...key.length) {
+			Ko.addByte(key.get(i) ^ 0x5c);
+			Ki.addByte(key.get(i) ^ 0x36);
+		}
+		// hash(Ko + hash(Ki + message))
+		Ki.add(msg);
+		Ko.add(doHash(Ki.getBytes()));
+		return doHash(Ko.getBytes());
+	}
+	
+}

+ 197 - 0
std/haxe/crypto/Sha256.hx

@@ -0,0 +1,197 @@
+/*
+ * Copyright (C)2005-2012 Haxe Foundation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+package haxe.crypto;
+
+class Sha256 {
+	
+	public static function encode( s:String ) : String {
+		#if php
+		return untyped __call__("hash", "sha256", s);
+		#else
+		var sh = new Sha256();
+		var h = sh.doEncode(str2blks(s), s.length*8);
+		return sh.hex(h);
+		#end
+	}
+
+	public static function make( b : haxe.io.Bytes ) : haxe.io.Bytes {
+		#if php
+		return haxe.io.Bytes.ofData(untyped __call__("hash", "sha256", b.getData(), true));
+		#else
+		var h = new Sha256().doEncode(bytes2blks(b), b.length*8);
+		var out = haxe.io.Bytes.alloc(32);
+		var p = 0;
+		for( i in 0...8 ) {
+			out.set(p++,h[i]>>>24);
+			out.set(p++,(h[i]>>16)&0xFF);
+			out.set(p++,(h[i]>>8)&0xFF);
+			out.set(p++,h[i]&0xFF);
+		}
+		return out;
+		#end
+	}
+	
+	public function new() {
+	}
+	
+	function doEncode( m : Array<Int>, l : Int ) : Array<Int> {
+		var K : Array<Int> = [
+			0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,
+			0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,
+			0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,
+			0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,
+			0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,
+			0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,
+			0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,
+			0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,
+			0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,
+			0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,
+			0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,
+			0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,
+			0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2
+		];
+		var HASH : Array<Int> = [
+			0x6A09E667,0xBB67AE85,0x3C6EF372,0xA54FF53A,
+			0x510E527F,0x9B05688C,0x1F83D9AB,0x5BE0CD19
+		];
+
+		var W = new Array<Int>();
+		W[64] = 0;
+		var a:Int,b:Int,c:Int,d:Int,e:Int,f:Int,g:Int,h:Int;
+		var T1, T2;
+		m[l >> 5] |= 0x80 << (24 - l % 32);
+		m[((l + 64 >> 9) << 4) + 15] = l;
+		var i : Int = 0;
+		while ( i < m.length ) {
+			a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7];
+			for ( j in 0...64 ) {
+				if (j < 16)
+					W[j] = m[j + i];
+				else
+					W[j] = safeAdd(safeAdd(safeAdd(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);
+				T1 = safeAdd(safeAdd(safeAdd(safeAdd(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);
+				T2 = safeAdd(Sigma0256(a), Maj(a, b, c));
+				h = g; g = f; f = e; e = safeAdd(d, T1); d = c; c = b; b = a; a = safeAdd(T1, T2);
+			}
+			HASH[0] = safeAdd(a, HASH[0]);
+			HASH[1] = safeAdd(b, HASH[1]);
+			HASH[2] = safeAdd(c, HASH[2]);
+			HASH[3] = safeAdd(d, HASH[3]);
+			HASH[4] = safeAdd(e, HASH[4]);
+			HASH[5] = safeAdd(f, HASH[5]);
+			HASH[6] = safeAdd(g, HASH[6]);
+			HASH[7] = safeAdd(h, HASH[7]);
+			i += 16;
+		}
+		return HASH;
+	}
+	
+	/*
+		Convert a string to a sequence of 16-word blocks, stored as an array.
+		Append padding bits and the length, as described in the SHA1 standard.
+	 */
+	static function str2blks( s :String ) : Array<Int> {
+		var nblk = ((s.length + 8) >> 6) + 1;
+		var blks = new Array<Int>();
+
+		for (i in 0...nblk*16)
+			blks[i] = 0;
+		for (i in 0...s.length){
+			var p = i >> 2;
+			blks[p] |= s.charCodeAt(i) << (24 - ((i & 3) << 3));
+		}
+		var i = s.length;
+		var p = i >> 2;
+		blks[p] |= 0x80 << (24 - ((i & 3) << 3));
+		blks[nblk * 16 - 1] = s.length * 8;
+		return blks;
+	}
+
+	static function bytes2blks( b : haxe.io.Bytes ) : Array<Int> {
+		var nblk = ((b.length + 8) >> 6) + 1;
+		var blks = new Array<Int>();
+
+		for (i in 0...nblk*16)
+			blks[i] = 0;
+		for (i in 0...b.length){
+			var p = i >> 2;
+			blks[p] |= b.get(i) << (24 - ((i & 3) << 3));
+		}
+		var i = b.length;
+		var p = i >> 2;
+		blks[p] |= 0x80 << (24 - ((i & 3) << 3));
+		blks[nblk * 16 - 1] = b.length * 8;
+		return blks;
+	}
+
+	function S(X, n) {
+		return ( X >>> n ) | (X << (32 - n));
+	}
+	
+	function R(X, n) {
+		return ( X >>> n );
+	}
+	
+	function Ch(x, y, z) {
+		return ((x & y) ^ ((~x) & z));
+	}
+	
+	function Maj(x, y, z) {
+		return ((x & y) ^ (x & z) ^ (y & z));
+	}
+	
+	function Sigma0256(x) {
+		return (S(x, 2) ^ S(x, 13) ^ S(x, 22));
+	}
+	
+	function Sigma1256(x) {
+		return (S(x, 6) ^ S(x, 11) ^ S(x, 25));
+	}
+	
+	function Gamma0256(x) {
+		return (S(x, 7) ^ S(x, 18) ^ R(x, 3));
+	}
+	
+	function Gamma1256(x) {
+		return (S(x, 17) ^ S(x, 19) ^ R(x, 10));
+	}
+	
+	function safeAdd(x, y) {
+		var lsw = (x & 0xFFFF) + (y & 0xFFFF);
+		var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
+		return (msw << 16) | (lsw & 0xFFFF);
+	}
+	
+	function hex( a : Array<Int> ){
+		var str = "";
+		var hex_chr = "0123456789abcdef";
+		for( num in a ) {
+			var j = 7;
+			while( j >= 0 ) {
+				str += hex_chr.charAt( (num >>> (j<<2)) & 0xF );
+				j--;
+			}
+		}
+		return str;
+	}
+
+}

+ 13 - 5
std/haxe/ds/Vector.hx

@@ -65,12 +65,10 @@ abstract Vector<T>(VectorData<T>) {
 		#elseif java
 		#elseif java
 			this = new java.NativeArray(length);
 			this = new java.NativeArray(length);
 		#elseif cpp
 		#elseif cpp
-			this = untyped (new Array<T>()).__SetSizeExact(length);
+			this = new Array<T>();
+			untyped this.__SetSizeExact(length);
 		#elseif python
 		#elseif python
-			this = new Array();
-			for (i in 0...length) {
-				this[i] = null;
-			}
+			this = python.Syntax.pythonCode("[{0}]*{1}", null, length);
 		#else
 		#else
 			this = [];
 			this = [];
 			untyped this.length = length;
 			untyped this.length = length;
@@ -86,6 +84,8 @@ abstract Vector<T>(VectorData<T>) {
 	@:arrayAccess public inline function get(index:Int):Null<T> {
 	@:arrayAccess public inline function get(index:Int):Null<T> {
 		#if cpp
 		#if cpp
 		return this.unsafeGet(index);
 		return this.unsafeGet(index);
+		#elseif python
+		return python.internal.ArrayImpl.unsafeGet(this, index);
 		#else
 		#else
 		return this[index];
 		return this[index];
 		#end
 		#end
@@ -100,6 +100,8 @@ abstract Vector<T>(VectorData<T>) {
 	@:arrayAccess public inline function set(index:Int, val:T):T {
 	@:arrayAccess public inline function set(index:Int, val:T):T {
 		#if cpp
 		#if cpp
 		return this.unsafeSet(index,val);
 		return this.unsafeSet(index,val);
+		#elseif python
+		return python.internal.ArrayImpl.unsafeSet(this, index, val);
 		#else
 		#else
 		return this[index] = val;
 		return this[index] = val;
 		#end
 		#end
@@ -155,6 +157,8 @@ abstract Vector<T>(VectorData<T>) {
 	public #if (flash || cpp) inline #end function toArray():Array<T> {
 	public #if (flash || cpp) inline #end function toArray():Array<T> {
 		#if cpp
 		#if cpp
 			return this.copy();
 			return this.copy();
+		#elseif python
+			return this.copy();
 		#else
 		#else
 			var a = new Array();
 			var a = new Array();
 			var len = length;
 			var len = length;
@@ -199,10 +203,14 @@ abstract Vector<T>(VectorData<T>) {
 	**/
 	**/
 	#if as3 @:extern #end
 	#if as3 @:extern #end
 	static public inline function fromArrayCopy<T>(array:Array<T>):Vector<T> {
 	static public inline function fromArrayCopy<T>(array:Array<T>):Vector<T> {
+		#if python
+		return cast array.copy();
+		#else
 		// TODO: Optimize this for flash (and others?)
 		// TODO: Optimize this for flash (and others?)
 		var vec = new Vector<T>(array.length);
 		var vec = new Vector<T>(array.length);
 		for (i in 0...array.length)
 		for (i in 0...array.length)
 			vec.set(i, array[i]);
 			vec.set(i, array[i]);
 		return vec;
 		return vec;
+		#end
 	}
 	}
 }
 }

+ 5 - 4
std/haxe/format/JsonPrinter.hx

@@ -13,7 +13,7 @@ class JsonPrinter {
 	var indent:String;
 	var indent:String;
 	var pretty:Bool;
 	var pretty:Bool;
 	var nind:Int;
 	var nind:Int;
-	
+
 	function new(replacer:Dynamic -> Dynamic -> Dynamic, space:String) {
 	function new(replacer:Dynamic -> Dynamic -> Dynamic, space:String) {
 		this.replacer = replacer;
 		this.replacer = replacer;
 		this.indent = space;
 		this.indent = space;
@@ -28,11 +28,11 @@ class JsonPrinter {
 		buf = new StringBuf();
 		buf = new StringBuf();
 		#end
 		#end
 	}
 	}
-	
+
 	inline function ipad ():Void {
 	inline function ipad ():Void {
 		if (pretty) add(StringTools.lpad('', indent, nind * indent.length));
 		if (pretty) add(StringTools.lpad('', indent, nind * indent.length));
 	}
 	}
-	
+
 	inline function newl ():Void {
 	inline function newl ():Void {
 		if (pretty) addChar('\n'.code);
 		if (pretty) addChar('\n'.code);
 	}
 	}
@@ -129,11 +129,12 @@ class JsonPrinter {
 		addChar('{'.code);
 		addChar('{'.code);
 		var len = fields.length;
 		var len = fields.length;
 		var last = len - 1;
 		var last = len - 1;
+		var first = true;
 		for( i in 0...len ) {
 		for( i in 0...len ) {
 			var f = fields[i];
 			var f = fields[i];
 			var value = Reflect.field(v,f);
 			var value = Reflect.field(v,f);
 			if( Reflect.isFunction(value) ) continue;
 			if( Reflect.isFunction(value) ) continue;
-			if( i > 0 ) addChar(','.code) else nind++;
+			if( first ) { nind++; first = false; } else addChar(','.code);
 			newl();
 			newl();
 			ipad();
 			ipad();
 			quote(f);
 			quote(f);

+ 6 - 0
std/haxe/io/Path.hx

@@ -74,6 +74,12 @@ class Path {
 		properties.
 		properties.
 	**/
 	**/
 	public function new( path : String ) {
 	public function new( path : String ) {
+		switch (path) {
+			case "." | "..":
+				dir = path;
+				file = "";
+				return;
+		}
 		var c1 = path.lastIndexOf("/");
 		var c1 = path.lastIndexOf("/");
 		var c2 = path.lastIndexOf("\\");
 		var c2 = path.lastIndexOf("\\");
 		if( c1 < c2 ) {
 		if( c1 < c2 ) {

+ 6 - 2
std/haxe/macro/Compiler.hx

@@ -106,11 +106,15 @@ class Compiler {
 		} else {
 		} else {
 			function(c) return Lambda.has(ignore, c);
 			function(c) return Lambda.has(ignore, c);
 		}
 		}
+		var displayValue = Context.definedValue("display");
 		if( classPaths == null ) {
 		if( classPaths == null ) {
 			classPaths = Context.getClassPath();
 			classPaths = Context.getClassPath();
 			// do not force inclusion when using completion
 			// do not force inclusion when using completion
-			if( Context.defined("display") )
-				return;
+			switch (displayValue) {
+				case null:
+				case "usage":
+				case _: return;
+			}
 			// normalize class path
 			// normalize class path
 			for( i in 0...classPaths.length ) {
 			for( i in 0...classPaths.length ) {
 				var cp = StringTools.replace(classPaths[i], "\\", "/");
 				var cp = StringTools.replace(classPaths[i], "\\", "/");

+ 1 - 0
std/haxe/rtti/CType.hx

@@ -26,6 +26,7 @@ typedef Path = String
 typedef Platforms = List<String>
 typedef Platforms = List<String>
 
 
 typedef FunctionArgument = { name : String, opt : Bool, t : CType, ?value:String }
 typedef FunctionArgument = { name : String, opt : Bool, t : CType, ?value:String }
+
 enum CType {
 enum CType {
 	CUnknown;
 	CUnknown;
 	CEnum( name : Path, params : List<CType> );
 	CEnum( name : Path, params : List<CType> );

+ 10 - 0
std/haxe/web/Dispatch.hx

@@ -39,6 +39,7 @@ enum MatchRule {
 	MRBool;
 	MRBool;
 	MRFloat;
 	MRFloat;
 	MRString;
 	MRString;
+	MRDate;
 	MREnum( e : String );
 	MREnum( e : String );
 	MRDispatch;
 	MRDispatch;
 	MRSpod( c : String, lock : Bool );
 	MRSpod( c : String, lock : Bool );
@@ -167,6 +168,13 @@ class Dispatch {
 			return v;
 			return v;
 		case MRBool:
 		case MRBool:
 			return v != null && v != "0" && v != "false" && v != "null";
 			return v != null && v != "0" && v != "false" && v != "null";
+		case MRDate:
+			if( v == null ) throw DEMissing;
+			try{
+				return Date.fromString(v);
+			} catch (e:Dynamic) {
+				throw DEInvalidValue;
+			}
 		case MREnum(e):
 		case MREnum(e):
 			if( v == null ) throw DEMissing;
 			if( v == null ) throw DEMissing;
 			if( opt && v == "" ) return null;
 			if( opt && v == "" ) return null;
@@ -258,6 +266,8 @@ class Dispatch {
 				return MRFloat;
 				return MRFloat;
 			case "String":
 			case "String":
 				return MRString;
 				return MRString;
+			case "Date":
+				return MRDate;
 			case "haxe.web.Dispatch":
 			case "haxe.web.Dispatch":
 				return MRDispatch;
 				return MRDispatch;
 			default:
 			default:

+ 16 - 1
std/java/Lib.hx

@@ -46,7 +46,7 @@ package java;
 	}
 	}
 
 
 	/**
 	/**
-		Gets the native System.Type from the supplied object. Will throw an exception in case of null being passed.
+		Gets the native java.lang.Class from the supplied object. Will throw an exception in case of null being passed.
 	**/
 	**/
 	@:functionCode('
 	@:functionCode('
 		return (java.lang.Class<T>) obj.getClass();
 		return (java.lang.Class<T>) obj.getClass();
@@ -55,6 +55,21 @@ package java;
 	{
 	{
 		return null;
 		return null;
 	}
 	}
+	/**
+		Returns a Class<> equivalent to the native java.lang.Class type.
+	**/
+	public static inline function fromNativeType<T>(t:java.lang.Class<T>):Class<T>
+	{
+		return untyped t;
+	}
+
+	/**
+		Returns a java.lang.Class equivalent to the Haxe Class<> type.
+	**/
+	public static inline function toNativeType<T>(cl:Class<T>):java.lang.Class<T>
+	{
+		return untyped cl;
+	}
 
 
 	/**
 	/**
 		Returns a Haxe Array of a native Array.
 		Returns a Haxe Array of a native Array.

+ 11 - 0
std/js/Lib.hx

@@ -41,4 +41,15 @@ class Lib {
 		return untyped __js__("eval")(code);
 		return untyped __js__("eval")(code);
 	}
 	}
 
 
+	/**
+		Inserts a `require` expression that loads JavaScript object from
+		a module or file specified in the `module` argument.
+
+		This is only supported in environments where `require` function
+		is available, such as Node.js or RequireJS.
+	**/
+	public static inline function require( module:String ) : Dynamic {
+		return untyped __js__("require")(module);
+	}
+
 }
 }

+ 87 - 0
std/js/_std/Math.hx

@@ -0,0 +1,87 @@
+/*
+ * Copyright (C)2005-2012 Haxe Foundation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+package;
+
+// Can't enable @:coreApi because some fields are now inline getters
+// @:coreApi
+extern class Math
+{
+	static var PI(default,null) : Float;
+
+	static var NEGATIVE_INFINITY(get, null) : Float;
+	static inline function get_NEGATIVE_INFINITY () : Float {
+		return -(untyped __js__("Infinity"));
+	}
+
+	static var POSITIVE_INFINITY(get,null) : Float;
+	static inline function get_POSITIVE_INFINITY () : Float {
+		return (untyped __js__("Infinity"));
+	}
+
+	static var NaN(get, null) : Float;
+	static inline function get_NaN () : Float {
+		return (untyped __js__("NaN"));
+	}
+
+	static function abs(v:Float):Float;
+	static function acos(v:Float):Float;
+	static function asin(v:Float):Float;
+	static function atan(v:Float):Float;
+	static function atan2(y:Float, x:Float):Float;
+	static function ceil(v:Float):Int;
+	static function cos(v:Float):Float;
+	static function exp(v:Float):Float;
+	static function floor(v:Float):Int;
+	static function log(v:Float):Float;
+	static function max(a:Float, b:Float):Float;
+	static function min(a:Float, b:Float):Float;
+	static function pow(v:Float, exp:Float):Float;
+	static function random() : Float;
+	static function round(v:Float):Int;
+	static function sin(v:Float):Float;
+	static function sqrt(v:Float):Float;
+	static function tan(v:Float):Float;
+
+	static inline function ffloor( v : Float ) : Float {
+		return floor(v);
+	}
+
+	static inline function fceil( v : Float ) : Float {
+		return ceil(v);
+	}
+
+	static inline function fround( v : Float ) : Float {
+		return round(v);
+	}
+
+	static inline function isFinite( f : Float ) : Bool {
+		return (untyped __js__("isFinite"))(f);
+	}
+
+	static inline function isNaN( f : Float ) : Bool {
+		return (untyped __js__("isNaN"))(f);
+	}
+
+	static function __init__() : Void {
+		untyped __feature__("Type.resolveClass", $hxClasses["Math"] = Math);
+	}
+}

+ 2 - 2
std/neko/_std/Date.hx

@@ -62,7 +62,7 @@ import neko.Lib;
 		return Std.parseInt( new String(date_format(__t,untyped "%w".__s)) );
 		return Std.parseInt( new String(date_format(__t,untyped "%w".__s)) );
 	}
 	}
 
 
-	public function toString():String {
+	@:keep public function toString():String {
 		return new String(date_format(__t,null));
 		return new String(date_format(__t,null));
 	}
 	}
 
 
@@ -98,7 +98,7 @@ import neko.Lib;
 	static var int32_to_float = Lib.load("std","int32_to_float",1);
 	static var int32_to_float = Lib.load("std","int32_to_float",1);
 	static var int32_add = Lib.load("std","int32_add",2);
 	static var int32_add = Lib.load("std","int32_add",2);
 	static var int32_shl = Lib.load("std","int32_shl",2);
 	static var int32_shl = Lib.load("std","int32_shl",2);
-	static function __string() : String { return untyped "Date".__s; }
+	@:keep static function __string() : String { return untyped "Date".__s; }
 
 
 }
 }
 
 

+ 1 - 1
std/neko/vm/Deque.hx

@@ -32,7 +32,7 @@ class Deque<T> {
 	public function push( i : T ) {
 	public function push( i : T ) {
 		deque_push(q,i);
 		deque_push(q,i);
 	}
 	}
-	public function pop( block : Bool ) : T {
+	public function pop( block : Bool ) : Null<T> {
 		return deque_pop(q,block);
 		return deque_pop(q,block);
 	}
 	}
 	static var deque_create = neko.Lib.loadLazy("std","deque_create",0);
 	static var deque_create = neko.Lib.loadLazy("std","deque_create",0);

+ 135 - 77
std/python/Boot.hx

@@ -7,6 +7,7 @@ import python.internal.EnumImpl;
 import python.internal.HxOverrides;
 import python.internal.HxOverrides;
 import python.internal.HxException;
 import python.internal.HxException;
 import python.internal.AnonObject;
 import python.internal.AnonObject;
+import python.internal.HxBuiltin;
 
 
 import python.Syntax;
 import python.Syntax;
 
 
@@ -16,36 +17,91 @@ private extern class Set<T> {
 	}
 	}
 }
 }
 
 
+@:pythonImport("math") private extern class Math {
+	public static function floor (x:Float):Int;
+}
+@:pythonImport("inspect") private extern class Inspect {}
 
 
-@:preCode("
-import builtins as _hx_builtin
-import functools as _hx_functools
-import math as _hx_math
+typedef HxClassBase = {
+    _hx_class:Dynamic,
+    _hx_class_name:String
+}
 
 
-_hx_classes = dict()
+private typedef HxAbstract = {
+    >HxClassBase,
+}
+
+private typedef HxEnum = {
+    >HxClassBase,
+    _hx_constructs:Array<String>
+}
 
 
-class _hx_AnonObject(object):
-	def __init__(self, fields):
-		self.__dict__ = fields
+private typedef HxClass = {
+    >HxClassBase,
+    _hx_fields:Array<String>,
+    _hx_props:Array<String>,
+    _hx_methods:Array<String>,
+    _hx_statics:Array<String>,
+    _hx_interfaces:Array<HxClassBase>,
+    _hx_super:HxClass
+}
 
 
-_hx_c = _hx_AnonObject({})
+@:keep
+@:nativeGen
+@:native("_hx_ClassRegistry")
+private class ClassRegistry extends python.lib.Dict<String, HxClassBase> {
+    function _register(cls:HxClassBase, name:String):Void {
+        cls._hx_class = cls;
+        cls._hx_class_name = name;
+        set(name, cls);
+    }
+
+    function registerAbstract(name:String):HxAbstract->HxAbstract {
+        function wrapper(cls:HxAbstract):HxAbstract {
+            _register(cls, name);
+            return cls;
+        }
+        return wrapper;
+    }
+
+    function registerEnum(name:String, constructs:Array<String>):HxEnum->HxEnum {
+        function wrapper(cls:HxEnum):HxEnum {
+            _register(cls, name);
+            cls._hx_constructs = constructs;
+            return cls;
+        }
+        return wrapper;
+    }
+
+    function registerClass(name:String, ?fields:Array<String>, ?props:Array<String>, ?methods:Array<String>, ?statics:Array<String>, ?interfaces:Array<HxClassBase>, ?superClass:HxClass):HxClass->HxClass {
+        if (fields == null) fields = [];
+        if (props == null) props = [];
+        if (methods == null) methods = [];
+        if (statics == null) statics = [];
+        if (interfaces == null) interfaces = [];
+        function wrapper(cls:HxClass):HxClass {
+            _register(cls, name);
+            cls._hx_fields = fields;
+            cls._hx_props = props;
+            cls._hx_methods = methods;
+            cls._hx_statics = statics;
+            cls._hx_interfaces = interfaces;
+            if (superClass != null)
+                cls._hx_super = superClass;
+            return cls;
+        }
+        return wrapper;
+    }
+}
 
 
-_hx_c._hx_AnonObject = _hx_AnonObject
-")
+@:preCode("_hx_classes = _hx_ClassRegistry()")
 @:keep class Boot {
 @:keep class Boot {
 
 
-	static function __init__ () {
-		Internal.importAsPrefixed("inspect", "boot_inspect");
-		Boot.inspect = Internal.pythonCodePrefixed("boot_inspect");
-		Boot.math = Internal.pythonCodePrefixed("math");
-		Boot.builtin = Internal.pythonCodePrefixed("builtin");
-	}
-
 	static inline function mathRound (v:Float) {
 	static inline function mathRound (v:Float) {
-		return math.floor(v + 0.5);
+		return Math.floor(v + 0.5);
 	}
 	}
 
 
-	inline static function mkSet <T>(a:Array<T>):Set<T> return Syntax.callField(builtin, "set", a);
+	inline static function mkSet <T>(a:Array<T>):Set<T> return Syntax.callField(HxBuiltin, "set", a);
 
 
 	static var keywords:Set<String> = mkSet(
 	static var keywords:Set<String> = mkSet(
 	[
 	[
@@ -60,96 +116,93 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 	]);
 	]);
 
 
 	inline static function arrayJoin <T>(x:Array<T>, sep:String):String {
 	inline static function arrayJoin <T>(x:Array<T>, sep:String):String {
-		return Syntax.field(sep, "join")(x.map(python.Boot.toString));
+		return Syntax.field(sep, "join")(Syntax.pythonCode("[{0}(x1,'') for x1 in {1}]", python.Boot.toString1, x));
 	}
 	}
 
 
 	inline static function isInstance(o:Dynamic, x:Dynamic):Bool {
 	inline static function isInstance(o:Dynamic, x:Dynamic):Bool {
-		return Syntax.callField(builtin, "isinstance", o, x);
+		return HxBuiltin.isinstance(o,x);
 	}
 	}
 
 
 	inline static function builtinStr(o:Dynamic):String {
 	inline static function builtinStr(o:Dynamic):String {
-		return Syntax.callField(builtin, "str", o);
+		return HxBuiltin.str(o);
 	}
 	}
 
 
 	inline static function builtinHasAttr(o:Dynamic, x:String):Bool {
 	inline static function builtinHasAttr(o:Dynamic, x:String):Bool {
-		return Syntax.callField(builtin, "hasattr", o, x);
+		return HxBuiltin.hasattr(o, x);
 	}
 	}
 
 
 	inline static function builtinGetAttr(o:Dynamic, x:String):Dynamic {
 	inline static function builtinGetAttr(o:Dynamic, x:String):Dynamic {
-		return Syntax.callField(builtin, "getattr", o, x);
+		return HxBuiltin.getattr(o, x);
 	}
 	}
 
 
 	inline static function isPyBool(o:Dynamic):Bool {
 	inline static function isPyBool(o:Dynamic):Bool {
-		return isInstance(o, Syntax.field(builtin, "bool"));
+		return isInstance(o, HxBuiltin.bool);
 	}
 	}
 
 
 	inline static function isPyInt(o:Dynamic):Bool {
 	inline static function isPyInt(o:Dynamic):Bool {
-		return isInstance(o, Syntax.field(builtin, "int"));
+		return isInstance(o, HxBuiltin.int);
 	}
 	}
 
 
 	inline static function isPyFloat(o:Dynamic):Bool {
 	inline static function isPyFloat(o:Dynamic):Bool {
-		return isInstance(o, Syntax.field(builtin, "float"));
+		return isInstance(o, HxBuiltin.float);
 	}
 	}
 
 
 	inline static function builtinLen(o:Dynamic):Int {
 	inline static function builtinLen(o:Dynamic):Int {
-		return Syntax.callField(builtin, "len", o);
+		return Syntax.callField(HxBuiltin, "len", o);
 	}
 	}
 
 
 	inline static function builtinInt(o:Dynamic):Int {
 	inline static function builtinInt(o:Dynamic):Int {
-		return Syntax.callField(builtin, "int", o);
+		return Syntax.callField(HxBuiltin, "int", o);
 	}
 	}
 
 
 	inline static function builtinCallable(o:Dynamic):Bool {
 	inline static function builtinCallable(o:Dynamic):Bool {
-		return Syntax.callField(builtin, "callable", o);
+		return Syntax.callField(HxBuiltin, "callable", o);
 	}
 	}
 
 
 	inline static function inspectGetMembers(o:Dynamic, f:String->Bool):Void {
 	inline static function inspectGetMembers(o:Dynamic, f:String->Bool):Void {
-		Syntax.callField(inspect, "getmembers", o, f);
+		Syntax.callField(Inspect, "getmembers", o, f);
 	}
 	}
 
 
 	inline static function inspectIsClass(o:Dynamic):Bool {
 	inline static function inspectIsClass(o:Dynamic):Bool {
-		return Syntax.callField(inspect, "isclass", o);
+		return Syntax.callField(Inspect, "isclass", o);
 	}
 	}
 
 
 	inline static function inspectIsFunction(o:Dynamic):Bool {
 	inline static function inspectIsFunction(o:Dynamic):Bool {
-		return Syntax.callField(inspect, "isclass", o);
+		return Syntax.callField(Inspect, "isfunction", o);
 	}
 	}
 
 
 	inline static function inspectIsMethod(o:Dynamic):Bool {
 	inline static function inspectIsMethod(o:Dynamic):Bool {
-		return Syntax.callField(inspect, "isclass", o);
+		return Syntax.callField(Inspect, "ismethod", o);
 	}
 	}
 
 
-	static var builtin:Dynamic;
-	static var inspect:Dynamic;
-	static var math:Dynamic;
 
 
 	static inline function isClass(o:Dynamic) : Bool {
 	static inline function isClass(o:Dynamic) : Bool {
 		return o != null && (o == String || inspectIsClass(o));
 		return o != null && (o == String || inspectIsClass(o));
 	}
 	}
 
 
-	static inline function isAnonObject (o:Dynamic) {
+	static function isAnonObject (o:Dynamic) {
 		return isInstance(o, AnonObject);
 		return isInstance(o, AnonObject);
 	}
 	}
 
 
 	private static function _add_dynamic(a:Dynamic,b:Dynamic):Dynamic {
 	private static function _add_dynamic(a:Dynamic,b:Dynamic):Dynamic {
 		if (isInstance(a, String) || isInstance(b, String)) {
 		if (isInstance(a, String) || isInstance(b, String)) {
-			return toString1(a,"") + toString1(b,"");
+			return Syntax.binop(toString1(a,""), "+", toString1(b,""));
 		}
 		}
 		return Syntax.binop(a, "+", b);
 		return Syntax.binop(a, "+", b);
 	}
 	}
 
 
-	static function toString (o:Dynamic) {
+	static inline function toString (o:Dynamic) {
 		return toString1(o, "");
 		return toString1(o, "");
 	}
 	}
 
 
 	private static function toString1(o:Dynamic,s:String):String {
 	private static function toString1(o:Dynamic,s:String):String {
 
 
-		if (s == null) s = "";
 		if( o == null ) return "null";
 		if( o == null ) return "null";
 
 
-		if( s.length >= 5 ) return "<...>"; // too much deep recursion
+		if (isString(o)) return o;
 
 
-		if (isInstance(o, String)) return o;
+		if (s == null) s = "";
+		if( s.length >= 5 ) return "<...>"; // too much deep recursion
 
 
 		if (isPyBool(o)) {
 		if (isPyBool(o)) {
 			if ((o:Bool)) return "true" else return "false";
 			if ((o:Bool)) return "true" else return "false";
@@ -160,7 +213,7 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 		// 1.0 should be printed as 1
 		// 1.0 should be printed as 1
 		if (isPyFloat(o)) {
 		if (isPyFloat(o)) {
 			try {
 			try {
-				if (o == builtinInt(o)) {
+				if ( (o:Float) == builtinInt(o)) {
 					return builtinStr(mathRound(o));
 					return builtinStr(mathRound(o));
 				} else {
 				} else {
 					return builtinStr(o);
 					return builtinStr(o);
@@ -170,9 +223,7 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 			}
 			}
 		}
 		}
 
 
-		if (inspectIsFunction(o) || inspectIsMethod(o)) return "<function>";
-
-		if (isInstance(o, Array))
+		if (isArray(o))
 		{
 		{
 			var o1:Array<Dynamic> = o;
 			var o1:Array<Dynamic> = o;
 			var l = o1.length;
 			var l = o1.length;
@@ -189,18 +240,20 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 			st += "]";
 			st += "]";
 			return st;
 			return st;
 		}
 		}
+
 		try {
 		try {
 			if (builtinHasAttr(o, "toString")) {
 			if (builtinHasAttr(o, "toString")) {
-				return o.toString();
+				return Syntax.callField(o, "toString");
 			}
 			}
 		} catch (e:Dynamic) {
 		} catch (e:Dynamic) {
-
 		}
 		}
 
 
+		if (inspectIsFunction(o) || inspectIsMethod(o)) return "<function>";
+
 		if (builtinHasAttr(o, "__class__"))
 		if (builtinHasAttr(o, "__class__"))
 		{
 		{
 
 
-			if (isInstance(o, AnonObject))
+			if (isAnonObject(o))
 			{
 			{
 				var toStr = null;
 				var toStr = null;
 				try
 				try
@@ -244,29 +297,26 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 				}
 				}
 			}
 			}
 
 
+			if (Internal.hasClassName(o)) {
+				if (Syntax.field(Syntax.field(o, "__class__"), "__name__") != "type") {
+					var fields = getInstanceFields(o);
+					var fieldsStr = [for (f in fields) '$f : ${toString1(field(o,f), s+"\t")}'];
 
 
-			if (Internal.hasClassName(o) && Syntax.field(Syntax.field(o, "__class__"), "__name__") != "type") {
-
-				var fields = getInstanceFields(o);
-				var fieldsStr = [for (f in fields) '$f : ${toString1(field(o,f), s+"\t")}'];
-
-				var toStr = Internal.fieldClassName(o) + "( " + arrayJoin(fieldsStr, ", ") + " )";
-				return toStr;
+					var toStr = Internal.fieldClassName(o) + "( " + arrayJoin(fieldsStr, ", ") + " )";
+					return toStr;
+				} else {
+					var fields = getClassFields(o);
+					var fieldsStr = [for (f in fields) '$f : ${toString1(field(o,f), s+"\t")}'];
+					var toStr = "#" + Internal.fieldClassName(o) + "( " + arrayJoin(fieldsStr, ", ") + " )";
+					return toStr;
+				}
 			}
 			}
 
 
-			if (Internal.hasClassName(o) && Syntax.field(Syntax.field(o, "__class__"), "__name__") == "type") {
-
-				var fields = getClassFields(o);
-				var fieldsStr = [for (f in fields) '$f : ${toString1(field(o,f), s+"\t")}'];
-
-				var toStr = "#" + Internal.fieldClassName(o) + "( " + arrayJoin(fieldsStr, ", ") + " )";
-				return toStr;
-			}
-			if (o == String) {
+			if (isMetaType(o,String)) {
 				return "#String";
 				return "#String";
 			}
 			}
 
 
-			if (o == Array) {
+			if (isMetaType(o,Array)) {
 				return "#Array";
 				return "#Array";
 			}
 			}
 
 
@@ -297,6 +347,10 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 		}
 		}
 	}
 	}
 
 
+	static inline function isMetaType(v:Dynamic, t:Dynamic):Bool {
+		return python.Syntax.binop(v, "==", t);
+	}
+
 	static function fields (o:Dynamic) {
 	static function fields (o:Dynamic) {
 		var a = [];
 		var a = [];
 		if (o != null) {
 		if (o != null) {
@@ -306,8 +360,8 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 			}
 			}
 			if (isInstance(o, AnonObject)) {
 			if (isInstance(o, AnonObject)) {
 
 
-				var d:Dynamic = Syntax.field(o, "__dict__");
-				var keys = d.keys();
+				var d = Syntax.field(o, "__dict__");
+				var keys = Syntax.callField(d, "keys");
 				var handler = unhandleKeywords;
 				var handler = unhandleKeywords;
 
 
 				Syntax.pythonCode("for k in keys:");
 				Syntax.pythonCode("for k in keys:");
@@ -315,8 +369,8 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 			}
 			}
 			else if (builtinHasAttr(o, "__dict__")) {
 			else if (builtinHasAttr(o, "__dict__")) {
 				var a = [];
 				var a = [];
-				var d:Dynamic = Syntax.field(o, "__dict__");
-				var keys1  = d.keys();
+				var d = Syntax.field(o, "__dict__");
+				var keys1  = Syntax.callField(d, "keys");
 				Syntax.pythonCode("for k in keys1:");
 				Syntax.pythonCode("for k in keys1:");
 				Syntax.pythonCode("	a.append(k)");
 				Syntax.pythonCode("	a.append(k)");
 
 
@@ -326,11 +380,11 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 	}
 	}
 
 
 	static inline function isString (o:Dynamic):Bool {
 	static inline function isString (o:Dynamic):Bool {
-		return isInstance(o, String);
+		return isInstance(o, HxBuiltin.str);
 	}
 	}
 
 
 	static inline function isArray (o:Dynamic):Bool {
 	static inline function isArray (o:Dynamic):Bool {
-		return isInstance(o, Array);
+		return isInstance(o, HxBuiltin.list);
 	}
 	}
 
 
 	static function field( o : Dynamic, field : String ) : Dynamic {
 	static function field( o : Dynamic, field : String ) : Dynamic {
@@ -338,7 +392,6 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 
 
 		switch (field) {
 		switch (field) {
 			case "length" if (isString(o)): return StringImpl.get_length(o);
 			case "length" if (isString(o)): return StringImpl.get_length(o);
-			case "length" if (isArray(o)): return ArrayImpl.get_length(o);
 			case "toLowerCase" if (isString(o)): return StringImpl.toLowerCase.bind(o);
 			case "toLowerCase" if (isString(o)): return StringImpl.toLowerCase.bind(o);
 			case "toUpperCase" if (isString(o)): return StringImpl.toUpperCase.bind(o);
 			case "toUpperCase" if (isString(o)): return StringImpl.toUpperCase.bind(o);
 			case "charAt" if (isString(o)): return StringImpl.charAt.bind(o);
 			case "charAt" if (isString(o)): return StringImpl.charAt.bind(o);
@@ -349,7 +402,7 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 			case "substr" if (isString(o)): return StringImpl.substr.bind(o);
 			case "substr" if (isString(o)): return StringImpl.substr.bind(o);
 			case "substring" if (isString(o)): return StringImpl.substring.bind(o);
 			case "substring" if (isString(o)): return StringImpl.substring.bind(o);
 			case "toString" if (isString(o)): return StringImpl.toString.bind(o);
 			case "toString" if (isString(o)): return StringImpl.toString.bind(o);
-
+			case "length" if (isArray(o)): return ArrayImpl.get_length(o);
 			case "map" if (isArray(o)): return ArrayImpl.map.bind(o);
 			case "map" if (isArray(o)): return ArrayImpl.map.bind(o);
 			case "filter" if (isArray(o)): return ArrayImpl.filter.bind(o);
 			case "filter" if (isArray(o)): return ArrayImpl.filter.bind(o);
 			case "concat" if (isArray(o)): return ArrayImpl.concat.bind(o);
 			case "concat" if (isArray(o)): return ArrayImpl.concat.bind(o);
@@ -371,6 +424,7 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 			case "splice" if (isArray(o)): return ArrayImpl.splice.bind(o);
 			case "splice" if (isArray(o)): return ArrayImpl.splice.bind(o);
 		}
 		}
 
 
+
 		var field = handleKeywords(field);
 		var field = handleKeywords(field);
 		return if (builtinHasAttr(o, field)) builtinGetAttr(o, field) else null;
 		return if (builtinHasAttr(o, field)) builtinGetAttr(o, field) else null;
 	}
 	}
@@ -430,10 +484,14 @@ _hx_c._hx_AnonObject = _hx_AnonObject
 
 
 
 
 
 
+	static inline function unsafeFastCodeAt (s, index) {
+		return HxBuiltin.ord(python.Syntax.arrayAccess(s, index));
+	}
+
 	static inline function handleKeywords(name:String):String {
 	static inline function handleKeywords(name:String):String {
 		return if (keywords.has(name)) {
 		return if (keywords.has(name)) {
 			Internal.getPrefixed(name);
 			Internal.getPrefixed(name);
-		} else if (name.length > 2 && name.substr(0,2) == "__" && name.charAt(name.length-1) != "_") {
+		} else if (name.length > 2 && unsafeFastCodeAt(name,0) == "_".code && unsafeFastCodeAt(name,1) == "_".code && unsafeFastCodeAt(name, name.length-1) != "_".code) {
 			Internal.getPrefixed(name);
 			Internal.getPrefixed(name);
 		}
 		}
 		else name;
 		else name;

+ 1 - 1
std/python/KwArgs.hx

@@ -7,7 +7,7 @@ abstract KwArgs (Dict<String, Dynamic>)
 {
 {
 	inline function new (d:Dict<String, Dynamic>) this = d;
 	inline function new (d:Dict<String, Dynamic>) this = d;
 
 
-	@:to inline function toDict ():Dict<String, Dynamic>
+	@:to public inline function toDict ():Dict<String, Dynamic>
 	{
 	{
 		return this;
 		return this;
 	}
 	}

+ 7 - 6
std/python/Lib.hx

@@ -1,5 +1,7 @@
 package python;
 package python;
 
 
+import python.internal.AnonObject;
+import python.internal.HxBuiltin;
 import python.lib.Dict;
 import python.lib.Dict;
 import python.NativeStringTools;
 import python.NativeStringTools;
 
 
@@ -23,16 +25,15 @@ class Lib {
 
 
 	public static function dictToAnon (v:Dict<String, Dynamic>):Dynamic
 	public static function dictToAnon (v:Dict<String, Dynamic>):Dynamic
 	{
 	{
-		var o = {};
-		Syntax.assign(Syntax.field(o, "__dict__"), v);
-		return o;
+		return new AnonObject(v.copy());
 	}
 	}
 
 
-	@:access(python.Boot) public static function anonToDict (o:{}):Dynamic
+
+	public static function anonToDict (o:{}):Dict<String, Dynamic>
 	{
 	{
-		return if (python.Boot.isAnonObject(o))
+		return if (HxBuiltin.isinstance(o, AnonObject))
 		{
 		{
-			Syntax.field(o, "__dict__");
+			(Syntax.field(o, "__dict__"):Dict<String,Dynamic>).copy();
 		}
 		}
 		else null;
 		else null;
 
 

+ 4 - 6
std/python/NativeIterable.hx

@@ -5,14 +5,12 @@ import python.HaxeIterable;
 import python.NativeIterator;
 import python.NativeIterator;
 
 
 abstract NativeIterable <T>(NativeIterableRaw<T>) to NativeIterableRaw<T> from NativeIterableRaw<T> {
 abstract NativeIterable <T>(NativeIterableRaw<T>) to NativeIterableRaw<T> from NativeIterableRaw<T> {
-	@:to public static inline function toHaxeIterable <T>(p:NativeIterableRaw<T>):HaxeIterable<T> return new HaxeIterable(p);
+	@:to public inline function toHaxeIterable():HaxeIterable<T> return new HaxeIterable(this);
 
 
-	//@:from public static inline function fromArray <T>(p:Array<T>):PyIterable<T> return cast p;
+	public inline function iterator():HaxeIterator<T> return toHaxeIterable().iterator();
 
 
-	public inline function iterator <T>() return toHaxeIterable().iterator();
-
-	public function getNativeIterable <T>():NativeIterableRaw<T> return this;
-	public function getNativeIterator <T>():NativeIteratorRaw<T> return this.__iter__();
+	public inline function getNativeIterable():NativeIterableRaw<T> return this;
+	public inline function getNativeIterator():NativeIteratorRaw<T> return this.__iter__();
 
 
 }
 }
 typedef NativeIterableRaw<T> = {
 typedef NativeIterableRaw<T> = {

+ 3 - 4
std/python/NativeIterator.hx

@@ -6,14 +6,13 @@ import python.NativeIterable.NativeIterableRaw;
 abstract NativeIterator <T>(NativeIteratorRaw<T>) to NativeIteratorRaw<T> to NativeIterable<T> {
 abstract NativeIterator <T>(NativeIteratorRaw<T>) to NativeIteratorRaw<T> to NativeIterable<T> {
 	public inline function new (p:NativeIteratorRaw<T>) this = p;
 	public inline function new (p:NativeIteratorRaw<T>) this = p;
 
 
-	@:to public static inline function toHaxeIterator <T>(p:NativeIteratorRaw<T>):HaxeIterator<T> return new HaxeIterator(p);
-	@:to public static inline function toNativeIterable <T>(p:NativeIteratorRaw<T>):NativeIterable<T> return p;
+	@:to public inline function toHaxeIterator():HaxeIterator<T> return new HaxeIterator(this);
+	@:to public inline function toNativeIterable():NativeIterable<T> return this;
 
 
-	public function getNativeIteratorRaw <T>():NativeIteratorRaw<T> return this;
+	public inline function getNativeIteratorRaw():NativeIteratorRaw<T> return this;
 }
 }
 
 
 typedef NativeIteratorRaw<T> = {
 typedef NativeIteratorRaw<T> = {
 	> NativeIterableRaw<T>,
 	> NativeIterableRaw<T>,
 	function __next__ ():T;
 	function __next__ ():T;
-	//function __iter__ ():NativeIterator<T>;
 }
 }

+ 11 - 11
std/python/Syntax.hx

@@ -20,12 +20,8 @@ extern class Syntax {
 	{
 	{
 		var n = className.split(".").join("_");
 		var n = className.split(".").join("_");
 		var e = "import " + module + " as " + n;
 		var e = "import " + module + " as " + n;
-		var e1 = "_hx_c."+n+" = "+n;
 
 
-		return macro ({
-			$self.pythonCode($v{e});
-			$self.pythonCode($v{e1});
-		}:Void);
+		return macro ($self.pythonCode($v{e}):Void);
 	}
 	}
 
 
 	@:noUsing
 	@:noUsing
@@ -48,8 +44,15 @@ extern class Syntax {
 	public static function assign(a:Dynamic, b:Dynamic):Void { }
 	public static function assign(a:Dynamic, b:Dynamic):Void { }
 
 
 	@:noUsing
 	@:noUsing
-	public static function pythonCode<T>(b:String):T { return null; };
+	macro public static function pythonCode(b:ExprOf<String>, rest:Array<Expr>):Expr {
+		if (rest == null) rest = [];
+		return macro @:pos(Context.currentPos()) $self._pythonCode($b, $a{rest});
+	};
 
 
+	#if !macro
+	@:noUsing
+	public static function _pythonCode<T>(b:String, args:Array<Dynamic>):T { return null; };
+	#end
 	@:noUsing
 	@:noUsing
 	macro public static function arrayAccess(x:Expr, rest:Array<Expr>):ExprOf<Dynamic> {
 	macro public static function arrayAccess(x:Expr, rest:Array<Expr>):ExprOf<Dynamic> {
 		return macro $self._arrayAccess($x, $a{rest});
 		return macro $self._arrayAccess($x, $a{rest});
@@ -98,11 +101,8 @@ extern class Syntax {
 		var n = className.split(".").join("_");
 		var n = className.split(".").join("_");
 
 
 		var e = "from " + from + " import " + module + " as " + n;
 		var e = "from " + from + " import " + module + " as " + n;
-		var e1 = "_hx_c."+n+" = " + n;
-		return macro ({
-			$self.pythonCode($v{e});
-			$self.pythonCode($v{e1});
-		}:Void);
+
+		return macro ($self.pythonCode($v{e}):Void);
 	}
 	}
 
 
 	@:noUsing
 	@:noUsing

+ 8 - 10
std/python/_std/Array.hx

@@ -115,26 +115,24 @@ extern class Array<T> implements ArrayAccess<T> extends ArrayImpl {
 		return ArrayImpl.filter(this,f);
 		return ArrayImpl.filter(this,f);
 	}
 	}
 
 
-
-
-	@:keep private inline function __get(idx:Int):T
+	@:keep private inline function _get(idx:Int):T
 	{
 	{
-		return ArrayImpl.__get(this, idx);
+		return ArrayImpl._get(this, idx);
 	}
 	}
 
 
-	@:keep private inline function __set(idx:Int, val:T):T
+	@:keep private inline function _set(idx:Int, val:T):T
 	{
 	{
-		return ArrayImpl.__set(this, idx,val);
+		return ArrayImpl._set(this, idx,val);
 	}
 	}
 
 
-	@:keep private inline function __unsafe_get(idx:Int):T
+	@:keep private inline function unsafeGet(idx:Int):T
 	{
 	{
-		return ArrayImpl.__unsafe_get(this, idx);
+		return ArrayImpl.unsafeGet(this, idx);
 	}
 	}
 
 
-	@:keep private inline function __unsafe_set(idx:Int, val:T):T
+	@:keep private inline function unsafeSet(idx:Int, val:T):T
 	{
 	{
-		return ArrayImpl.__unsafe_set(this, idx,val);
+		return ArrayImpl.unsafeSet(this, idx,val);
 	}
 	}
 
 
 	@:noCompletion private function __iter__ ():NativeIterator<T>;
 	@:noCompletion private function __iter__ ():NativeIterator<T>;

+ 1 - 2
std/python/_std/Math.hx

@@ -27,7 +27,7 @@ import python.lib.Builtin;
 /**
 /**
 	This class defines mathematical functions and constants.
 	This class defines mathematical functions and constants.
 **/
 **/
-@:native("_hx_math")
+@:pythonImport("math")
 @:coreApi
 @:coreApi
 extern class Math
 extern class Math
 {
 {
@@ -310,7 +310,6 @@ extern class Math
 	}
 	}
 
 
 	static function __init__():Void {
 	static function __init__():Void {
-		python.Syntax.importAs("math", "_hx_math");
 		NEGATIVE_INFINITY = Builtin.float('-inf');
 		NEGATIVE_INFINITY = Builtin.float('-inf');
 		POSITIVE_INFINITY = Builtin.float('inf');
 		POSITIVE_INFINITY = Builtin.float('inf');
 		NaN = Builtin.float("nan");
 		NaN = Builtin.float("nan");

+ 2 - 0
std/python/_std/Reflect.hx

@@ -150,6 +150,8 @@ class Reflect {
 		return o2;
 		return o2;
 	}
 	}
 
 
+
+
 	@:overload(function( f : Array<Dynamic> -> Void ) : Dynamic {})
 	@:overload(function( f : Array<Dynamic> -> Void ) : Dynamic {})
 	public static function makeVarArgs( f : Array<Dynamic> -> Dynamic ) : Dynamic {
 	public static function makeVarArgs( f : Array<Dynamic> -> Dynamic ) : Dynamic {
 		return function (v:VarArgs) {
 		return function (v:VarArgs) {

+ 18 - 12
std/python/_std/Std.hx

@@ -39,7 +39,12 @@ import python.Syntax;
 		}
 		}
 	}
 	}
 
 
-	@:access(python.Boot.getSuperClass)
+	@:access(python.Boot)
+	static inline function isMetaType(v:Dynamic, t:Dynamic):Bool {
+		return Boot.isMetaType(v,t);
+	}
+
+	@:access(python.Boot)
 	public static function is( v : Dynamic, t : Dynamic ) : Bool {
 	public static function is( v : Dynamic, t : Dynamic ) : Bool {
 
 
 		if (v == null && t == null) {
 		if (v == null && t == null) {
@@ -49,39 +54,40 @@ import python.Syntax;
 
 
 			return false;
 			return false;
 		}
 		}
-		if (t == Dynamic) {
+		if (isMetaType(t,Dynamic)) {
 			return true;
 			return true;
 		}
 		}
 		var isBool = Builtin.isinstance(v, Builtin.bool);
 		var isBool = Builtin.isinstance(v, Builtin.bool);
 
 
-		if (t == Bool && isBool) {
+		if (isMetaType(t, Bool) && isBool) {
 			return true;
 			return true;
 		}
 		}
-		if (!isBool && t != Bool && t == Int && Builtin.isinstance(v, Builtin.int )) {
+		if (!isBool && !isMetaType(t, Bool) && isMetaType(t,Int) && Builtin.isinstance(v, Builtin.int )) {
 			return true;
 			return true;
 		}
 		}
 		var vIsFloat = Builtin.isinstance(v, Builtin.float);
 		var vIsFloat = Builtin.isinstance(v, Builtin.float);
 
 
-		if (!isBool && vIsFloat && t == Int && Math.isFinite(v) && v == Std.int(v) && v <= 2147483647 && v >= -2147483648) {
+		if (!isBool && vIsFloat && isMetaType(t,Int) && Math.isFinite(v) && v == Std.int(v) && v <= 2147483647 && v >= -2147483648) {
 			return true;
 			return true;
 		}
 		}
 
 
 
 
-		if (!isBool &&  t == Float && ( Builtin.isinstance(v, python.Syntax.pythonCode("(float,int)")))) {
+		if (!isBool &&  isMetaType(t,Float) && ( Builtin.isinstance(v, python.Syntax.pythonCode("(float,int)")))) {
 			return true;
 			return true;
 		}
 		}
 
 
-		if ( t == Builtin.str) {
+		if ( isMetaType(t, Builtin.str)) {
 			return Builtin.isinstance(v, String);
 			return Builtin.isinstance(v, String);
 		}
 		}
-		if (t == Enum && Inspect.isclass(v) && Internal.hasConstructs(v)) return true;
-
-		if (t == Enum) return false;
+		var isEnumType = isMetaType(t,Enum);
+		if (isEnumType && Inspect.isclass(v) && Internal.hasConstructs(v)) return true;
 
 
+		if (isEnumType) return false;
 
 
-		if (t == Class && !Builtin.isinstance(v, Enum) && Inspect.isclass(v) && Internal.hasClassName(v) && !Internal.hasConstructs(v)) return true;
+		var isClassType = isMetaType(t,Class);
+		if (isClassType && !Builtin.isinstance(v, Enum) && Inspect.isclass(v) && Internal.hasClassName(v) && !Internal.hasConstructs(v)) return true;
 
 
-		if (t == Class) return false;
+		if (isClassType) return false;
 
 
 		if (try Builtin.isinstance(v, t) catch (e:Dynamic) false) {
 		if (try Builtin.isinstance(v, t) catch (e:Dynamic) false) {
 			return true;
 			return true;

+ 2 - 7
std/python/_std/String.hx

@@ -34,6 +34,7 @@ package;
 #if !macro
 #if !macro
 import python.internal.StringImpl;
 import python.internal.StringImpl;
 #end
 #end
+@:pythonImport("builtins", "str")
 @:coreApi
 @:coreApi
 extern class String {
 extern class String {
 
 
@@ -194,13 +195,7 @@ extern class String {
 		If [code] is negative or has another invalid value, the result is
 		If [code] is negative or has another invalid value, the result is
 		unspecified.
 		unspecified.
 	**/
 	**/
-	public static function fromCharCode( code : Int ) : String {
+	public static inline function fromCharCode( code : Int ) : String {
 		return StringImpl.fromCharCode(code);
 		return StringImpl.fromCharCode(code);
 	}
 	}
-
-	@:keep static function __init__ ():Void {
-		python.Syntax.importFromAs("builtins", "str", "String");
-	}
-
-
 }
 }

+ 2 - 2
std/python/_std/StringBuf.hx

@@ -56,9 +56,9 @@ class StringBuf {
 
 
 	public function get_length ():Int {
 	public function get_length ():Int {
 		var pos = b.tell();
 		var pos = b.tell();
-		b.seek(0, SeekSet.SeekEnd);
+		b.seek(0, SeekEnd);
 		var len = b.tell();
 		var len = b.tell();
-		b.seek(pos, SeekSet.SeekSet);
+		b.seek(pos, SeekSet);
 		return len;
 		return len;
 	}
 	}
 
 

+ 5 - 7
std/python/_std/haxe/ds/StringMap.hx

@@ -12,20 +12,18 @@ class StringMap<T> implements Map.IMap<String, T> {
 	}
 	}
 
 
 	public inline function set( key : String, value : T ) : Void {
 	public inline function set( key : String, value : T ) : Void {
-		h.set("$"+key, value);
+		h.set(key, value);
 	}
 	}
 
 
 	public inline function get( key : String ) : Null<T> {
 	public inline function get( key : String ) : Null<T> {
-		return h.get("$"+key, null);
-
+		return h.get(key, null);
 	}
 	}
 
 
 	public inline function exists( key : String ) : Bool {
 	public inline function exists( key : String ) : Bool {
-		return h.hasKey("$" + key);
+		return h.hasKey(key);
 	}
 	}
 
 
 	public function remove( key : String ) : Bool {
 	public function remove( key : String ) : Bool {
-		var key = "$"+key;
 		var has = h.hasKey(key);
 		var has = h.hasKey(key);
 		if (has) h.remove(key);
 		if (has) h.remove(key);
 		return has;
 		return has;
@@ -34,7 +32,7 @@ class StringMap<T> implements Map.IMap<String, T> {
 	public function keys() : Iterator<String> {
 	public function keys() : Iterator<String> {
 		var a = [];
 		var a = [];
 		Syntax.foreach(key, h, {
 		Syntax.foreach(key, h, {
-			a.push( key.substr(1));
+			a.push( key);
 		});
 		});
 		return a.iterator();
 		return a.iterator();
 	}
 	}
@@ -44,7 +42,7 @@ class StringMap<T> implements Map.IMap<String, T> {
 		var ref = h;
 		var ref = h;
 		return {
 		return {
 			hasNext : function() { return iter.hasNext(); },
 			hasNext : function() { return iter.hasNext(); },
-			next : function() { var i = iter.next(); return ref.get("$"+i, null); }
+			next : function() { var i = iter.next(); return ref.get(i, null); }
 		};
 		};
 	}
 	}
 
 

+ 9 - 3
std/python/internal/AnonObject.hx

@@ -1,7 +1,13 @@
 
 
 package python.internal;
 package python.internal;
 
 
-@:native("_hx_AnonObject")
-extern class AnonObject {
+import python.Syntax;
 
 
-}
+@:keep
+@:nativeGen
+@:native("_hx_AnonObject")
+class AnonObject {
+    public function new(fields) {
+        Syntax.assign(Internal.fieldDict(this), fields);
+    }
+}

+ 21 - 21
std/python/internal/ArrayImpl.hx

@@ -23,24 +23,22 @@
 package python.internal;
 package python.internal;
 
 
 import python.lib.FuncTools;
 import python.lib.FuncTools;
-//import python.lib.Builtin;
-
-private abstract Builtin(Dynamic) {}
+import python.internal.HxBuiltin;
 
 
 @:allow(Array)
 @:allow(Array)
 @:keep
 @:keep
 class ArrayImpl {
 class ArrayImpl {
 
 
-	static inline function builtin():Builtin return Internal.builtin();
 
 
-	public static inline function get_length <T>(x:Array<T>):Int return Syntax.callField(builtin(), "len", x);
+
+	public static inline function get_length <T>(x:Array<T>):Int return HxBuiltin.len(x);
 
 
 	public static inline function concat<T>( a1:Array<T>, a2 : Array<T>) : Array<T> {
 	public static inline function concat<T>( a1:Array<T>, a2 : Array<T>) : Array<T> {
 		return Syntax.binop(a1, "+", a2);
 		return Syntax.binop(a1, "+", a2);
 	}
 	}
 
 
 	public static inline function copy<T>(x:Array<T>) : Array<T> {
 	public static inline function copy<T>(x:Array<T>) : Array<T> {
-		return Syntax.field(builtin(), "list")(x);
+		return Syntax.field(HxBuiltin, "list")(x);
 	}
 	}
 
 
 	public static inline function iterator<T>(x:Array<T>) : Iterator<T> {
 	public static inline function iterator<T>(x:Array<T>) : Iterator<T> {
@@ -48,32 +46,34 @@ class ArrayImpl {
 	}
 	}
 
 
 	public static function indexOf<T>(a:Array<T>, x : T, ?fromIndex:Int) : Int {
 	public static function indexOf<T>(a:Array<T>, x : T, ?fromIndex:Int) : Int {
+		var len = a.length;
 		var l =
 		var l =
 			if (fromIndex == null) 0
 			if (fromIndex == null) 0
-			else if (fromIndex < 0) a.length + fromIndex
+			else if (fromIndex < 0) len + fromIndex
 			else fromIndex;
 			else fromIndex;
 		if (l < 0) l = 0;
 		if (l < 0) l = 0;
-		for (i in l...a.length) {
-			if (a[i] == x) return i;
+		for (i in l...len) {
+			if (unsafeGet(a,i) == x) return i;
 		}
 		}
 		return -1;
 		return -1;
 	}
 	}
 
 
 	public static function lastIndexOf<T>(a:Array<T>, x : T, ?fromIndex:Int) : Int {
 	public static function lastIndexOf<T>(a:Array<T>, x : T, ?fromIndex:Int) : Int {
+		var len = a.length;
 		var l =
 		var l =
-			if (fromIndex == null) a.length
-			else if (fromIndex < 0) a.length + fromIndex + 1
+			if (fromIndex == null) len
+			else if (fromIndex < 0) len + fromIndex + 1
 			else fromIndex+1;
 			else fromIndex+1;
-		if (l > a.length) l = a.length;
+		if (l > len) l = len;
 		while (--l > -1) {
 		while (--l > -1) {
-			if (a[l] == x) return l;
+			if (unsafeGet(a,l) == x) return l;
 		}
 		}
 		return -1;
 		return -1;
 	}
 	}
 
 
 	@:access(python.Boot)
 	@:access(python.Boot)
 	public static inline function join<T>(x:Array<T>, sep : String ) : String {
 	public static inline function join<T>(x:Array<T>, sep : String ) : String {
-		return Syntax.field(sep, "join")(x.map(python.Boot.toString));
+		return Boot.arrayJoin(x, sep);
 	}
 	}
 
 
 	public static inline function toString<T>(x:Array<T>) : String {
 	public static inline function toString<T>(x:Array<T>) : String {
@@ -124,11 +124,11 @@ class ArrayImpl {
 	}
 	}
 
 
 	public static inline function map<S,T>(x:Array<T>, f : T -> S ) : Array<S> {
 	public static inline function map<S,T>(x:Array<T>, f : T -> S ) : Array<S> {
-		return Syntax.field(builtin(), "list")(Syntax.field(builtin(), "map")(f, x));
+		return Syntax.field(HxBuiltin, "list")(Syntax.field(HxBuiltin, "map")(f, x));
 	}
 	}
 
 
 	public static inline function filter<T>(x:Array<T>, f : T -> Bool ) : Array<T> {
 	public static inline function filter<T>(x:Array<T>, f : T -> Bool ) : Array<T> {
-		return Syntax.field(builtin(), "list")(Syntax.field(builtin(), "filter")(f, x));
+		return Syntax.field(HxBuiltin, "list")(Syntax.field(HxBuiltin, "filter")(f, x));
 	}
 	}
 
 
 	public static inline function insert<T>(a:Array<T>, pos : Int, x : T ) : Void {
 	public static inline function insert<T>(a:Array<T>, pos : Int, x : T ) : Void {
@@ -139,11 +139,11 @@ class ArrayImpl {
 		Syntax.callField(a, "reverse");
 		Syntax.callField(a, "reverse");
 	}
 	}
 
 
-	private static inline function __get<T>(x:Array<T>, idx:Int):T {
-		return if (idx < x.length && idx > -1) Syntax.arrayAccess(x, idx) else null;
+	private static inline function _get<T>(x:Array<T>, idx:Int):T {
+		return if (idx > -1 && idx < x.length) unsafeGet(x, idx) else null;
 	}
 	}
 
 
-	private static inline function __set<T>(x:Array<T>, idx:Int, v:T):T {
+	private static inline function _set<T>(x:Array<T>, idx:Int, v:T):T {
 		var l = x.length;
 		var l = x.length;
 		while (l < idx) {
 		while (l < idx) {
 			x.push(null);
 			x.push(null);
@@ -157,11 +157,11 @@ class ArrayImpl {
 		return v;
 		return v;
 	}
 	}
 
 
-	private static inline function __unsafe_get<T>(x:Array<T>,idx:Int):T {
+	public static inline function unsafeGet<T>(x:Array<T>,idx:Int):T {
 		return Syntax.arrayAccess(x, idx);
 		return Syntax.arrayAccess(x, idx);
 	}
 	}
 
 
-	private static inline function __unsafe_set<T>(x:Array<T>,idx:Int, val:T):T {
+	public static inline function unsafeSet<T>(x:Array<T>,idx:Int, val:T):T {
 		Syntax.assign(Syntax.arrayAccess(x, idx), val);
 		Syntax.assign(Syntax.arrayAccess(x, idx), val);
 		return val;
 		return val;
 	}
 	}

+ 38 - 0
std/python/internal/HxBuiltin.hx

@@ -0,0 +1,38 @@
+package python.internal;
+
+@:pythonImport("builtins") extern class HxBuiltin
+{
+	public static function bool(x:Dynamic):Bool;
+
+	public static function issubclass(x:Class<Dynamic>, from:Class<Dynamic>):Bool;
+	public static function callable(x:Dynamic):Bool;
+
+	public static function isinstance(obj:Dynamic, cl:Dynamic):Bool;
+
+	public static function hasattr(obj:Dynamic, attr:String):Bool;
+	public static function getattr(obj:Dynamic, attr:String):Dynamic;
+
+	public static function delattr(o:Dynamic, attr:String):Void;
+	public static function setattr(o:Dynamic, attr:String, val:Dynamic):Void;
+
+	public static function len(x:Dynamic):Int;
+	public static function int(x:Dynamic):Int;
+	public static function ord(s:String):Int;
+
+	public static function map (a:Dynamic, b:Dynamic):Dynamic;
+	public static function str(o:Dynamic):String;
+
+	public static function float(x:Dynamic):Float;
+
+	public static function list<T>(i:Dynamic):Array<T>;
+
+	public static function chr(c:Int):String;
+
+	@:overload(function (a1:Float, a2:Float, ?a3:Float, ?a4:Float, ?a5:Float, ?a6:Float, ?a7:Float, ?a8:Float, ?a9:Float):Float {})
+	public static function max(a1:Int, a2:Int, ?a3:Int, ?a4:Int, ?a5:Int, ?a6:Int, ?a7:Int, ?a8:Int, ?a9:Int):Int;
+
+	public static function round(f:Float):Int;
+
+	@:overload(function (a1:Float, a2:Float, ?a3:Float, ?a4:Float, ?a5:Float, ?a6:Float, ?a7:Float, ?a8:Float, ?a9:Float):Float {})
+	public static function min(a1:Int, a2:Int, ?a3:Int, ?a4:Int, ?a5:Int, ?a6:Int, ?a7:Int, ?a8:Int, ?a9:Int):Int;
+}

+ 11 - 7
std/python/internal/HxOverrides.hx

@@ -14,19 +14,23 @@ class HxOverrides {
 	// we need to modify the transformer to call Reflect directly
 	// we need to modify the transformer to call Reflect directly
 
 
 	static public function iterator(x) {
 	static public function iterator(x) {
-		if (Std.is(x, Array)) {
+		if (Boot.isArray(x)) {
 			return (x:Array<Dynamic>).iterator();
 			return (x:Array<Dynamic>).iterator();
 		}
 		}
-		return Reflect.callMethod(null, Reflect.field(x, "iterator"), []);
+		return Syntax.callField(x, "iterator");
 	}
 	}
 
 
 	static function eq( a:Dynamic, b:Dynamic ) : Bool {
 	static function eq( a:Dynamic, b:Dynamic ) : Bool {
 		if (Boot.isArray(a) || Boot.isArray(b)) {
 		if (Boot.isArray(a) || Boot.isArray(b)) {
-			return Syntax.pythonCode('$a is $b');
+			return Syntax.pythonCode('a is b');
 		}
 		}
 		return Syntax.binop(a, "==", b);
 		return Syntax.binop(a, "==", b);
 	}
 	}
 
 
+	static function stringOrNull (s:String):String {
+		return if (s == null) "null" else s;
+	}
+
 	static public function shift(x) {
 	static public function shift(x) {
 		return Reflect.callMethod(null, Reflect.field(x, "shift"), []);
 		return Reflect.callMethod(null, Reflect.field(x, "shift"), []);
 	}
 	}
@@ -47,16 +51,16 @@ class HxOverrides {
 	}
 	}
 
 
 	static public function arrayGet<T>(a:Dynamic, i:Int):Dynamic {
 	static public function arrayGet<T>(a:Dynamic, i:Int):Dynamic {
-		if (Std.is(a, Array)) {
-			return ArrayImpl.__get(a, i);
+		if (Boot.isArray(a)) {
+			return ArrayImpl._get(a, i);
 		} else {
 		} else {
 			return Syntax.arrayAccess(a, i);
 			return Syntax.arrayAccess(a, i);
 		}
 		}
 	}
 	}
 
 
 	static public function arraySet(a:Dynamic, i:Int, v:Dynamic) {
 	static public function arraySet(a:Dynamic, i:Int, v:Dynamic) {
-		if (Std.is(a, Array)) {
-			return ArrayImpl.__set(a, i, v);
+		if (Boot.isArray(a)) {
+			return ArrayImpl._set(a, i, v);
 		} else {
 		} else {
 			Syntax.assign(Syntax.arrayAccess(a, i), v);
 			Syntax.assign(Syntax.arrayAccess(a, i), v);
 			return v;
 			return v;

+ 16 - 11
std/python/internal/Internal.hx

@@ -10,7 +10,6 @@ class Internal {
 
 
 	static var _prefix = "_hx_";
 	static var _prefix = "_hx_";
 
 
-	static var _builtin = _prefix + "builtin";
 
 
 	static var _className = _prefix + "class_name";
 	static var _className = _prefix + "class_name";
 	static var _class = _prefix + "class";
 	static var _class = _prefix + "class";
@@ -25,13 +24,17 @@ class Internal {
 
 
 	static var _classes = _prefix + "classes";
 	static var _classes = _prefix + "classes";
 
 
+	static var _dict = "__dict__";
+
 	static function _getPrefixed (x:Expr):Expr {
 	static function _getPrefixed (x:Expr):Expr {
 		return switch (x.expr) {
 		return switch (x.expr) {
 			case EConst(CString(x)): macro @:pos(Context.currentPos()) $v{_prefix + x};
 			case EConst(CString(x)): macro @:pos(Context.currentPos()) $v{_prefix + x};
-			case _ : macro @:pos(Context.currentPos()) $v{_prefix} + $x;
+			case _ : macro @:pos(Context.currentPos()) (python.Syntax.binop($v{_prefix},"+",$x):String);
 		}
 		}
 	}
 	}
 
 
+
+
 	static function withPos(x:String):Expr {
 	static function withPos(x:String):Expr {
 		return macro @:pos(Context.currentPos()) $v{x};
 		return macro @:pos(Context.currentPos()) $v{x};
 	}
 	}
@@ -41,13 +44,16 @@ class Internal {
 	}
 	}
 
 
 	static function has (o:Expr, field:String):Expr {
 	static function has (o:Expr, field:String):Expr {
-		return macro python.Syntax.pythonCode($v{_builtin}).hasattr($o, $v{field});
+		return macro python.internal.HxBuiltin.hasattr($o, $v{field});
 	}
 	}
 
 
 	#end
 	#end
 
 
-	macro public static function builtin ():Expr {
-		return macro (python.Syntax.pythonCode($v{_builtin}):Dynamic);
+	macro public static function getPrefixed (x:ExprOf<String>):Expr {
+		return switch (x.expr) {
+			case EConst(CString(x)): macro @:pos(Context.currentPos()) $v{_prefix + x};
+			case _ : macro @:pos(Context.currentPos()) (python.Syntax.binop($v{_prefix},"+",$x):String);
+		}
 	}
 	}
 
 
 	macro public static function classRegistry ():Expr {
 	macro public static function classRegistry ():Expr {
@@ -69,12 +75,7 @@ class Internal {
 		return macro @:pos(Context.currentPos()) python.Syntax.field($a{args});
 		return macro @:pos(Context.currentPos()) python.Syntax.field($a{args});
 	}
 	}
 
 
-	macro public static function getPrefixed (x:ExprOf<String>):Expr {
-		return switch (x.expr) {
-			case EConst(CString(x)): macro @:pos(Context.currentPos()) $v{_prefix + x};
-			case _ : macro @:pos(Context.currentPos()) $v{_prefix} + $x;
-		}
-	}
+
 
 
 	macro public static function importAsPrefixed (o:String, x:String) {
 	macro public static function importAsPrefixed (o:String, x:String) {
 		return macro @:pos(Context.currentPos()) python.Syntax.importAs($v{o}, $v{_prefix + x});
 		return macro @:pos(Context.currentPos()) python.Syntax.importAs($v{o}, $v{_prefix + x});
@@ -196,6 +197,10 @@ class Internal {
 		return fieldWithPos(o, _constructs);
 		return fieldWithPos(o, _constructs);
 	}
 	}
 
 
+	macro public static function fieldDict (o:Expr):Expr {
+		return fieldWithPos(o, _dict);
+	}
+
 	macro public static function fieldEmptyInit (o:Expr):Expr {
 	macro public static function fieldEmptyInit (o:Expr):Expr {
 		return fieldWithPos(o, _emptyInit);
 		return fieldWithPos(o, _emptyInit);
 	}
 	}

+ 13 - 13
std/python/internal/StringImpl.hx

@@ -1,22 +1,22 @@
 package python.internal;
 package python.internal;
 
 
 import python.internal.Internal;
 import python.internal.Internal;
+import python.internal.HxBuiltin;
+
 
 
 
 
 @:keep
 @:keep
 @:native("HxString")
 @:native("HxString")
 class StringImpl {
 class StringImpl {
 
 
-	static inline function builtin ():Dynamic return Internal.builtin();
-
-	public static function split (s:String, d:String) {
-		return if (d == "") Syntax.field(builtin(), "list")(s) else Syntax.callField(s, "split", d);
+	public static inline function split (s:String, d:String) {
+		return if (d == "") Syntax.field(HxBuiltin, "list")(s) else Syntax.callField(s, "split", d);
 	}
 	}
 
 
 	public static function charCodeAt(s:String, index:Int) {
 	public static function charCodeAt(s:String, index:Int) {
 		return
 		return
 			if (s == null || s.length == 0 || index < 0 || index >= s.length) null
 			if (s == null || s.length == 0 || index < 0 || index >= s.length) null
-			else Syntax.callField(builtin(), "ord", Syntax.arrayAccess(s, index));
+			else Syntax.callField(HxBuiltin, "ord", Syntax.arrayAccess(s, index));
 	}
 	}
 
 
 	public static inline function charAt(s:String, index:Int) {
 	public static inline function charAt(s:String, index:Int) {
@@ -29,7 +29,7 @@ class StringImpl {
 		} else {
 		} else {
 
 
 			var i = Syntax.callField(s, "rfind", str, 0, startIndex+1);
 			var i = Syntax.callField(s, "rfind", str, 0, startIndex+1);
-			var startLeft = i == -1 ? Syntax.callField(builtin(), "max", 0,startIndex+1-str.length) : i+1;
+			var startLeft = i == -1 ? Syntax.callField(HxBuiltin, "max", 0,startIndex+1-str.length) : i+1;
 			var check = Syntax.callField(s,"find", str, startLeft, s.length);
 			var check = Syntax.callField(s,"find", str, startLeft, s.length);
 			if (check > i && check <= startIndex) {
 			if (check > i && check <= startIndex) {
 				return check;
 				return check;
@@ -39,26 +39,26 @@ class StringImpl {
 		}
 		}
 	}
 	}
 
 
-	public static function toUpperCase (s:String) {
+	public static inline function toUpperCase (s:String) {
 		return Syntax.callField(s, "upper");
 		return Syntax.callField(s, "upper");
 	}
 	}
 
 
-	public static function toLowerCase (s:String) {
+	public static inline function toLowerCase (s:String) {
 		return Syntax.callField(s, "lower");
 		return Syntax.callField(s, "lower");
 	}
 	}
-	public static function indexOf (s:String, str:String, ?startIndex:Int) {
+	public static inline function indexOf (s:String, str:String, ?startIndex:Int) {
 		if (startIndex == null)
 		if (startIndex == null)
 			return Syntax.callField(s, "find", str);
 			return Syntax.callField(s, "find", str);
 		else
 		else
 			return Syntax.callField(s, "find", str, startIndex);
 			return Syntax.callField(s, "find", str, startIndex);
 	}
 	}
 
 
-	public static function toString (s:String) {
+	public static inline function toString (s:String) {
 		return s;
 		return s;
 	}
 	}
 
 
-	public static function get_length (s:String) {
-		return Syntax.field(builtin(), "len")(s);
+	public static inline function get_length (s:String) {
+		return Syntax.field(HxBuiltin, "len")(s);
 	}
 	}
 
 
 	public static inline function fromCharCode( code : Int ) : String {
 	public static inline function fromCharCode( code : Int ) : String {
@@ -67,7 +67,7 @@ class StringImpl {
 		#else
 		#else
 		var c = code;
 		var c = code;
 		return Syntax.callField('', "join",
 		return Syntax.callField('', "join",
-			Syntax.callField(builtin(), "map", Syntax.field(builtin(), "chr"), [c])); // TODO: check cast
+			Syntax.callField(HxBuiltin, "map", Syntax.field(HxBuiltin, "chr"), [c])); // TODO: check cast
 		#end
 		#end
 	}
 	}
 
 

+ 7 - 7
std/python/io/IoTools.hx

@@ -35,14 +35,14 @@ class IoTools {
 	{
 	{
  		var pos = switch (pos) {
  		var pos = switch (pos) {
  			case SeekBegin:
  			case SeekBegin:
- 				SeekSet.SeekSet;
+ 				SeekSet;
  			case SeekCur:
  			case SeekCur:
  				p = tell() + p;
  				p = tell() + p;
- 				SeekSet.SeekSet;
+ 				SeekSet;
  			case SeekEnd :
  			case SeekEnd :
- 				stream.seek(0, SeekSet.SeekEnd);
+ 				stream.seek(0, SeekEnd);
  				p = tell() + p;
  				p = tell() + p;
- 				SeekSet.SeekSet;
+ 				SeekSet;
  		}
  		}
  		stream.seek(p, pos);
  		stream.seek(p, pos);
 	}
 	}
@@ -51,9 +51,9 @@ class IoTools {
 	{
 	{
  		var pos = switch(pos)
  		var pos = switch(pos)
 		{
 		{
-			case SeekBegin: SeekSet.SeekSet;
-			case SeekCur: SeekSet.SeekCur;
-			case SeekEnd: SeekSet.SeekEnd;
+			case SeekBegin: SeekSet;
+			case SeekCur: SeekCur;
+			case SeekEnd: SeekEnd;
 		};
 		};
 		stream.seek(p, pos);
 		stream.seek(p, pos);
 	}
 	}

+ 4 - 4
std/python/lib/Builtin.hx

@@ -2,12 +2,12 @@
 package python.lib;
 package python.lib;
 
 
 
 
-import python.lib.io.IOBase;
+import python.lib.io.FileIO;
 import python.lib.Dict;
 import python.lib.Dict;
 import python.NativeIterable;
 import python.NativeIterable;
 import python.NativeIterator;
 import python.NativeIterator;
 
 
-@:native("_hx_builtin")
+@:pythonImport("builtins")
 extern class Builtin {
 extern class Builtin {
 
 
 
 
@@ -41,7 +41,7 @@ extern class Builtin {
 	@:overload(function (f:Tuple<Dynamic>):Int {})
 	@:overload(function (f:Tuple<Dynamic>):Int {})
 	public static function len(x:String):Int;
 	public static function len(x:String):Int;
 
 
-	public static function open(file:String, mode:String, ?buffering:Int = -1, ?encoding:String = null, ?errors : String, ?newline:String, ?closefd:Bool, ?opener:String->Int->FileDescriptor):IOBase;
+	public static function open(file:String, mode:String, ?buffering:Int = -1, ?encoding:String = null, ?errors : String, ?newline:String, ?closefd:Bool, ?opener:String->Int->FileDescriptor):FileIO;
 
 
 	//public static function divmod():Void;
 	//public static function divmod():Void;
 	//public static function input():Void;
 	//public static function input():Void;
@@ -50,7 +50,7 @@ extern class Builtin {
 	//public static function enumerate():Void;
 	//public static function enumerate():Void;
 	@:overload(function (x:Dynamic, base:Int):Int {})
 	@:overload(function (x:Dynamic, base:Int):Int {})
 	public static function int(x:Dynamic):Int;
 	public static function int(x:Dynamic):Int;
-	//public static function ord():Void;
+	public static function ord(s:String):Int;
 	public static inline function str(o:Dynamic):String {
 	public static inline function str(o:Dynamic):String {
 		return python.Syntax.field(Builtin, "str")(o);
 		return python.Syntax.field(Builtin, "str")(o);
 	}
 	}

+ 1 - 6
std/python/lib/Bytes.hx

@@ -3,14 +3,9 @@ package python.lib;
 
 
 import python.lib.ByteArray;
 import python.lib.ByteArray;
 
 
+@:pythonImport("builtins", "bytes")
 extern class Bytes extends ByteArray {
 extern class Bytes extends ByteArray {
 
 
 	//public function decode(encoding:String="utf-8", errors:String="strict"):String;
 	//public function decode(encoding:String="utf-8", errors:String="strict"):String;
 
 
-	static function __init__ ():Void
-	{
-		Syntax.importFromAs("builtins", "bytes", "python.lib.Bytes");
-	}
-
-
 }
 }

+ 1 - 3
std/python/lib/Codecs.hx

@@ -43,11 +43,9 @@ extern class StreamReaderWriterText implements StreamReader implements StreamWri
 }
 }
 
 
 
 
+@:pythonImport("codecs")
 extern class Codecs {
 extern class Codecs {
 
 
 	public static function open(filename:String, mode:String, ?encoding:String, ?errors:String, ?buffering:Bool):StreamReaderWriterText;
 	public static function open(filename:String, mode:String, ?encoding:String, ?errors:String, ?buffering:Bool):StreamReaderWriterText;
 
 
-	static function __init__ ():Void {
-		Syntax.importAs("codecs", "python.lib.Codecs");
-	}
 }
 }

+ 3 - 16
std/python/lib/Dict.hx

@@ -23,6 +23,7 @@ extern class DictView<T> {
 	}
 	}
 }
 }
 
 
+@:pythonImport("builtins", "dict")
 extern class Dict <K, V>
 extern class Dict <K, V>
 {
 {
 	public function new ():Void;
 	public function new ():Void;
@@ -46,9 +47,7 @@ extern class Dict <K, V>
 	public function values ():DictView<V>;
 	public function values ():DictView<V>;
 	public function items ():DictView<Tup2<K,V>>;
 	public function items ():DictView<Tup2<K,V>>;
 
 
-	public static inline function fromObject (x:{}):Dict<String,Dynamic> {
-		return DictImpl.fromObject(x);
-	}
+
 	public inline function set (key:K, val:V):Void {
 	public inline function set (key:K, val:V):Void {
 		DictImpl.set(this, key, val);
 		DictImpl.set(this, key, val);
 	}
 	}
@@ -63,22 +62,10 @@ extern class Dict <K, V>
 		return values().iter();
 		return values().iter();
 	}
 	}
 	public function __iter__():NativeIterator<K>;
 	public function __iter__():NativeIterator<K>;
-
-	static function __init__ ():Void
-	{
-		Syntax.importFromAs("builtins", "dict", "python.lib.Dict");
-	}
-
 }
 }
 
 
 class DictImpl {
 class DictImpl {
-	public static inline function fromObject (x:{}) {
-		var d = new Dict();
-		for (f in Reflect.fields(x)) {
-			d.set(f, Reflect.field(x,f));
-		}
-		return d;
-	}
+
 	public static inline function hasKey <X>(d:Dict<X, Dynamic>, key:X) {
 	public static inline function hasKey <X>(d:Dict<X, Dynamic>, key:X) {
 		return Syntax.isIn(key, d);
 		return Syntax.isIn(key, d);
 	}
 	}

+ 1 - 1
std/python/lib/FuncTools.hx

@@ -2,7 +2,7 @@
 package python.lib;
 package python.lib;
 
 
 
 
-@:native("_hx_functools")
+@:pythonImport("functools")
 extern class FuncTools {
 extern class FuncTools {
 
 
 	public static function cmp_to_key<A>(f:A->A->Int):Dynamic;
 	public static function cmp_to_key<A>(f:A->A->Int):Dynamic;

+ 1 - 7
std/python/lib/Glob.hx

@@ -4,16 +4,10 @@ package python.lib;
 
 
 import python.NativeIterator;
 import python.NativeIterator;
 
 
+@:pythonImport("glob")
 extern class Glob {
 extern class Glob {
 
 
 	public static function glob (pathname:String):Array<String>;
 	public static function glob (pathname:String):Array<String>;
 	public static function iglob (pathname:String):NativeIterator<String>;
 	public static function iglob (pathname:String):NativeIterator<String>;
 
 
-
-
-	static function __init__ ():Void
-	{
-		Syntax.importAs("glob", "python.lib.Glob");
-	}
-
 }
 }

+ 1 - 5
std/python/lib/Inspect.hx

@@ -3,13 +3,9 @@ package python.lib;
 
 
 import python.Syntax;
 import python.Syntax;
 
 
+@:pythonImport("inspect")
 extern class Inspect {
 extern class Inspect {
 
 
-	static function __init__ ():Void
-	{
-		python.Syntax.importAs("inspect", "python.lib.Inspect");
-	}
-
 	static function getmembers (value:Dynamic, ?filter:Dynamic->Bool):Bool;
 	static function getmembers (value:Dynamic, ?filter:Dynamic->Bool):Bool;
 	static function ismethod (value:Dynamic):Bool;
 	static function ismethod (value:Dynamic):Bool;
 	static function isclass (value:Dynamic):Bool;
 	static function isclass (value:Dynamic):Bool;

+ 1 - 4
std/python/lib/Json.hx

@@ -5,6 +5,7 @@ import python.KwArgs;
 import python.lib.Dict;
 import python.lib.Dict;
 import python.lib.Tuple.Tup2;
 import python.lib.Tuple.Tup2;
 
 
+@:pythonImport("json")
 extern class Json {
 extern class Json {
 
 
 
 
@@ -19,8 +20,4 @@ extern class Json {
 		cls:Null<Dynamic> = null, indent:Null<String> = null,
 		cls:Null<Dynamic> = null, indent:Null<String> = null,
 		separators:Null<Tup2<String,String>>, /*default*/def:Null<Dynamic->String> = null, sort_keys:Bool=false, kw:KwArgs = null):String;
 		separators:Null<Tup2<String,String>>, /*default*/def:Null<Dynamic->String> = null, sort_keys:Bool=false, kw:KwArgs = null):String;
 
 
-	static function __init__ ():Void
-	{
-		python.Syntax.importAs("json", "python.lib.Json");
-	}
 }
 }

+ 1 - 5
std/python/lib/Math.hx

@@ -1,5 +1,6 @@
 package python.lib;
 package python.lib;
 
 
+@:pythonImport("math")
 extern class Math {
 extern class Math {
 
 
 	public static function isnan (f:Float):Bool;
 	public static function isnan (f:Float):Bool;
@@ -16,9 +17,4 @@ extern class Math {
 	static function atan(v:Float):Float;
 	static function atan(v:Float):Float;
 	static function atan2(y:Float, x:Float):Float;
 	static function atan2(y:Float, x:Float):Float;
 
 
-	static function __init__():Void {
-		python.Syntax.importAs("math", "python.lib.Math");
-
-	}
-
 }
 }

+ 1 - 7
std/python/lib/Msvcrt.hx

@@ -1,15 +1,9 @@
 
 
 package python.lib;
 package python.lib;
 
 
+@:pythonImport("msvcrt", ignoreError=true)
 extern class Msvcrt {
 extern class Msvcrt {
 
 
 	public static function getch ():python.lib.Bytes;
 	public static function getch ():python.lib.Bytes;
 
 
-	static function __init__ ():Void
-	{
-		try {
-			python.Syntax.importAs("msvcrt", "python.lib.Msvcrt");
-		} catch (e:Dynamic) {}
-	}
-
 }
 }

+ 1 - 6
std/python/lib/Os.hx

@@ -30,6 +30,7 @@ extern class Stat {
 	@:optional public var st_type:Int;
 	@:optional public var st_type:Int;
 }
 }
 
 
+@:pythonImport("os")
 extern class Os {
 extern class Os {
 
 
 	public static var environ : Dict<String, String>;
 	public static var environ : Dict<String, String>;
@@ -68,10 +69,4 @@ extern class Os {
 	public static function makedirs (path:String, mode : Int = 511 /* Oktal 777 */, exist_ok:Bool = false):Void;
 	public static function makedirs (path:String, mode : Int = 511 /* Oktal 777 */, exist_ok:Bool = false):Void;
 
 
 	public static function mkdir (path:String, mode : Int = 511 /* Oktal 777 */):Void;
 	public static function mkdir (path:String, mode : Int = 511 /* Oktal 777 */):Void;
-
-	static function __init__ ():Void
-	{
-		python.Syntax.importAs("os", "python.lib.Os");
-	}
-
 }
 }

+ 1 - 4
std/python/lib/PPrint.hx

@@ -1,6 +1,7 @@
 
 
 package python.lib;
 package python.lib;
 
 
+@:pythonImport("pprint")
 extern class PPrint {
 extern class PPrint {
 
 
 
 
@@ -8,8 +9,4 @@ extern class PPrint {
 
 
 	public static function pformat(object:Dynamic, indent:Int=1, width:Int=80, depth:Int=null):String;
 	public static function pformat(object:Dynamic, indent:Int=1, width:Int=80, depth:Int=null):String;
 
 
-	static function __init__ ():Void {
-		python.Syntax.importAs("pprint", "python.lib.PPrint");
-	}
-
 }
 }

+ 1 - 5
std/python/lib/Random.hx

@@ -2,13 +2,9 @@
 package python.lib;
 package python.lib;
 
 
 
 
-
+@:pythonImport("random")
 extern class Random {
 extern class Random {
 
 
 	public static function random ():Float;
 	public static function random ():Float;
 
 
-	static function __init__ ():Void {
-		Syntax.importAs("random", "python.lib.Random");
-	}
-
 }
 }

Some files were not shown because too many files changed in this diff