Browse Source

add std files from hx2python

Simon Krajewski 11 năm trước cách đây
mục cha
commit
d9ed72f630
76 tập tin đã thay đổi với 8978 bổ sung0 xóa
  1. 214 0
      std/python/Boot.hx
  2. 13 0
      std/python/Debug.hx
  3. 59 0
      std/python/FileSystem.hx
  4. 115 0
      std/python/Lib.hx
  5. 91 0
      std/python/Macros.hx
  6. 12 0
      std/python/Sys.hx
  7. 36 0
      std/python/Tools.hx
  8. 138 0
      std/python/_std/Array.hx
  9. 142 0
      std/python/_std/Date.hx
  10. 220 0
      std/python/_std/DateTools.hx
  11. 259 0
      std/python/_std/EReg.hx
  12. 8 0
      std/python/_std/HxOverrides.hx
  13. 259 0
      std/python/_std/Lambda.hx
  14. 251 0
      std/python/_std/List.hx
  15. 311 0
      std/python/_std/Math.hx
  16. 183 0
      std/python/_std/Reflect.hx
  17. 228 0
      std/python/_std/Std.hx
  18. 208 0
      std/python/_std/String.hx
  19. 110 0
      std/python/_std/StringBuf.hx
  20. 284 0
      std/python/_std/StringTools.hx
  21. 327 0
      std/python/_std/Type.hx
  22. 335 0
      std/python/_std/Xml.hx
  23. 185 0
      std/python/_std/haxe/Int32.hx
  24. 274 0
      std/python/_std/haxe/Int64.hx
  25. 490 0
      std/python/_std/haxe/Json.hx
  26. 139 0
      std/python/_std/haxe/Log.hx
  27. 180 0
      std/python/_std/haxe/Resource.hx
  28. 547 0
      std/python/_std/haxe/Serializer.hx
  29. 163 0
      std/python/_std/haxe/Timer.hx
  30. 63 0
      std/python/_std/haxe/ds/IntMap.hx
  31. 58 0
      std/python/_std/haxe/ds/ObjectMap.hx
  32. 67 0
      std/python/_std/haxe/ds/StringMap.hx
  33. 173 0
      std/python/_std/haxe/ds/Vector.hx
  34. 375 0
      std/python/_std/haxe/io/Bytes.hx
  35. 356 0
      std/python/_std/haxe/io/Input.hx
  36. 71 0
      std/python/_std/haxe/rtti/Meta.hx
  37. 175 0
      std/python/internal/ArrayImpl.hx
  38. 38 0
      std/python/internal/KeywordHandler.hx
  39. 41 0
      std/python/internal/StringImpl.hx
  40. 19 0
      std/python/lib/ArrayTools.hx
  41. 146 0
      std/python/lib/Builtin.hx
  42. 53 0
      std/python/lib/Codecs.hx
  43. 10 0
      std/python/lib/FuncTools.hx
  44. 18 0
      std/python/lib/Glob.hx
  45. 20 0
      std/python/lib/Inspect.hx
  46. 15 0
      std/python/lib/Json.hx
  47. 73 0
      std/python/lib/Os.hx
  48. 15 0
      std/python/lib/PPrint.hx
  49. 14 0
      std/python/lib/Random.hx
  50. 179 0
      std/python/lib/Re.hx
  51. 13 0
      std/python/lib/ShUtil.hx
  52. 32 0
      std/python/lib/StringTools.hx
  53. 34 0
      std/python/lib/Subprocess.hx
  54. 32 0
      std/python/lib/Sys.hx
  55. 11 0
      std/python/lib/Tempfile.hx
  56. 17 0
      std/python/lib/ThreadLowLevel.hx
  57. 12 0
      std/python/lib/Time.hx
  58. 667 0
      std/python/lib/Types.hx
  59. 45 0
      std/python/lib/datetime/DateTime.hx
  60. 21 0
      std/python/lib/datetime/TimeDelta.hx
  61. 11 0
      std/python/lib/datetime/Timezone.hx
  62. 11 0
      std/python/lib/datetime/TzInfo.hx
  63. 8 0
      std/python/lib/io/BufferedRWPair.hx
  64. 8 0
      std/python/lib/io/BufferedRandom.hx
  65. 8 0
      std/python/lib/io/BufferedWriter.hx
  66. 8 0
      std/python/lib/io/BytesIO.hx
  67. 10 0
      std/python/lib/io/FileIO.hx
  68. 16 0
      std/python/lib/io/IOBase.hx
  69. 14 0
      std/python/lib/io/RawIOBase.hx
  70. 17 0
      std/python/lib/io/StringIO.hx
  71. 11 0
      std/python/lib/io/TextIOBase.hx
  72. 68 0
      std/python/lib/os/Path.hx
  73. 66 0
      std/python/lib/subprocess/Popen.hx
  74. 11 0
      std/python/lib/threading/Thread.hx
  75. 10 0
      std/python/lib/types/ClassType.hx
  76. 57 0
      std/python/lib/xml/etree/ElementTree.hx

+ 214 - 0
std/python/Boot.hx

@@ -0,0 +1,214 @@
+
+package python;
+
+import python.lib.Builtin;
+
+@:keep class Boot {
+
+	static var inspect:Dynamic;
+	static var builtin:Dynamic;
+
+	@:keep static function __init__ () {
+		Macros.importAs("inspect", "inspect");
+		Boot.inspect = untyped __python__("inspect");
+		Boot.builtin = untyped __python__("_hx_builtin");
+		
+
+	}
+
+	@:keep static inline function isClass(o:Dynamic) : Bool {
+		return o != null && (o == String || python.lib.Inspect.isclass(o));
+        //return untyped __define_feature__("python.Boot.isClass", o._hx_class);
+    }
+
+    @:keep static function isAnonObject (o:Dynamic) {
+    	return Builtin.isinstance(o, untyped __python__("_hx_c._hx_AnonObject"));
+    }
+
+
+    @:keep private static function _add_dynamic(a:Dynamic,b:Dynamic):Dynamic 
+    {
+		if (builtin.isinstance(a, untyped __python__("str")) || builtin.isinstance(b, untyped __python__("str"))) {
+			return __string_rec(a,"") + __string_rec(b,"");
+		}
+		return untyped __python__("a+b");
+    }
+	
+	@:keep private static function __string_rec(o:Dynamic,s:String):String {
+		
+		
+
+		if (s == null) s = "";
+		if( o == null ) return "null";
+		
+		if( s.length >= 5 ) return "<...>"; // too much deep recursion
+		
+		
+		
+
+		if (builtin.isinstance(o, untyped __python__("str"))) return o;
+
+		if (builtin.isinstance(o, untyped __python__("bool"))) {
+			if (untyped o) return "true" else return "false";
+		}
+		if (builtin.isinstance(o, untyped __python__("int"))) {
+			return builtin.str(o);
+		}
+		// 1.0 should be printed as 1
+		if (builtin.isinstance(o, untyped __python__("float"))) {
+			try {
+				if (o == Builtin.int(o)) {
+					return builtin.str(Math.round(o));	
+				} else {
+					return builtin.str(o);
+				}
+			} catch (e:Dynamic) {
+				return builtin.str(o);
+			}
+		}
+		
+
+		if (inspect.isfunction(o) || inspect.ismethod(o)) return "<function>";
+		
+		
+		
+		
+		if (builtin.isinstance(o, Array)) 
+		{
+			var o1:Array<Dynamic> = o;
+			var l = o1.length;
+			
+			var st = "[";
+			s += "\t";
+			for( i in 0...l ) {
+				var prefix = "";
+				if (i > 0) {
+					prefix = ",";
+				}
+				st += prefix + __string_rec(o1[i],s);
+			}
+			st += "]";
+			return st;
+		}
+		try {
+			if (builtin.hasattr(o, "toString")) {
+				return o.toString();
+			}
+		} catch (e:Dynamic) {
+
+		}
+		
+		if (builtin.hasattr(o, "__class__")) 
+		{
+
+			if (builtin.isinstance(o, untyped __python__("_hx_c._hx_AnonObject"))) 
+			{
+				var toStr = null;
+				try 
+				{
+					var fields = Reflect.fields(o);
+					var fieldsStr = [for (f in fields) '$f : ${__string_rec(Reflect.field(o,f), s+"\t")}'];
+					
+					toStr = "{ " + fieldsStr.join(", ") + " }";
+				} 
+				catch (e:Dynamic) {
+					trace(e);
+				}
+
+				if (toStr == null) 
+				{
+					return "{ ... }";	
+				} 
+				else 
+				{
+					return toStr;	
+				}
+				
+			}
+			if (builtin.isinstance(o, untyped __python__("_hx_c.Enum"))) {
+				
+				
+				var l = builtin.len(o.params);
+				var hasParams = l > 0;
+				if (hasParams) {
+					var paramsStr = "";
+					for (i in 0...l) {
+						var prefix = "";
+						if (i > 0) {
+							prefix = ",";
+						}
+						paramsStr += prefix + __string_rec(o.params[i],s);
+					}
+					return o.tag + "(" + paramsStr + ")";
+				} else {
+					return o.tag;
+				}
+			}
+
+
+			if (builtin.hasattr(o, "_hx_class_name") && o.__class__.__name__ != "type") {
+
+				var fields = Type.getInstanceFields(o);
+				var fieldsStr = [for (f in fields) '$f : ${__string_rec(Reflect.field(o,f), s+"\t")}'];
+				
+				var toStr = o._hx_class_name + "( " + fieldsStr.join(", ") + " )";
+				return toStr;
+			}
+
+			if (builtin.hasattr(o, "_hx_class_name") && o.__class__.__name__ == "type") {
+
+				var fields = Type.getClassFields(o);
+				var fieldsStr = [for (f in fields) '$f : ${__string_rec(Reflect.field(o,f), s+"\t")}'];
+					
+				var toStr = "#" + o._hx_class_name + "( " + fieldsStr.join(", ") + " )";
+				return toStr;
+			}
+			if (o == String) {
+				return "#String";
+			}
+			
+			//if (builtin.hasattr(o, "_hx_name")) {
+			//	return "#" + untyped o._hx_name;
+			//}
+			if (o == Array) {
+				return "#Array";
+			}
+			
+			if (builtin.callable(o)) {
+				return "function";
+			}
+			try {
+				if (builtin.hasattr(o, "__repr__")) {
+					return untyped o.__repr__();
+				}
+			} catch (e:Dynamic) {}
+
+			if (builtin.hasattr(o, "__str__")) {
+				return untyped o.__str__();
+			}
+
+			if (builtin.hasattr(o, "__name__")) {
+				return untyped o.__name__;
+			}
+			return "???";
+
+			
+			
+
+
+
+		} else {
+			try {
+				inspect.getmembers(o, function (_) return true);
+				return builtin.str(o);
+			} catch (e:Dynamic) {
+				return "???";
+			}
+		}
+	
+	
+			
+		
+	}
+
+}

+ 13 - 0
std/python/Debug.hx

@@ -0,0 +1,13 @@
+
+package python;
+
+import python.lib.Inspect;
+import python.lib.PPrint;
+
+class Debug {
+
+	public static function dump (x:Dynamic) {
+		PPrint.pprint(Inspect.getmembers(x));
+	}
+
+}

+ 59 - 0
std/python/FileSystem.hx

@@ -0,0 +1,59 @@
+
+package python;
+
+import python.lib.Os;
+import python.lib.os.Path;
+
+class FileSystem {
+
+	public static function exists( path : String ) : Bool {
+		return Path.exists(path);
+	}
+
+	public static function stat( path : String ) : sys.FileStat {
+		var s = Os.stat(path);
+		return {
+	        gid : s.st_gid,
+	        uid : s.st_uid,
+	        atime : Date.fromTime(s.st_atime),
+	        mtime : Date.fromTime(s.st_mtime),
+	        ctime : Date.fromTime(s.st_ctime),
+	        size : s.st_size,
+	        dev : s.st_dev,
+	        ino : s.st_ino,
+	        nlink : s.st_nlink,
+	        rdev : s.st_rdev,
+	        mode : s.st_mode
+		}
+	}
+
+	public static function rename( path : String, newPath : String ) : Void {
+		Os.rename(path, newPath);
+	}
+
+	public static function fullPath( relPath : String ) : String {
+		return Path.abspath(relPath);
+	}
+
+	public static function isDirectory( path : String ) : Bool
+	{
+		return Path.isdir(path);
+	}
+	public static function createDirectory( path : String ) : Void
+	{
+		Os.mkdir(path);
+	}
+	public static function deleteFile( path : String ) : Void
+	{
+		Os.remove(path);
+	}
+	public static function deleteDirectory( path : String ) : Void
+	{
+		Os.rmdir(path);
+	}
+	public static function readDirectory( path : String ) : Array<String>
+	{
+		return Os.listdir(path);
+	}
+
+}

+ 115 - 0
std/python/Lib.hx

@@ -0,0 +1,115 @@
+package python;
+
+import python.lib.Types;
+
+
+
+class HaxeIterable<T> 
+{
+  var x :NativeIterable<T>;
+  public inline function new (x:NativeIterable<T>) {
+    this.x = x;
+    
+  }
+
+  public inline function iterator ():HaxeIterator<T> return new HaxeIterator(x.__iter__());
+}
+
+class HaxeIterator<T> 
+{
+  var it :NativeIterator<T>;
+  var x:Null<T> = null;
+  var has = false;
+  var checked = false;
+
+  public function new (it:NativeIterator<T>) {
+    this.it = it;
+  }
+
+  public inline function next ():T
+  {
+    checked = false;
+    return x;
+  }
+
+  public function hasNext ():Bool
+  {
+    if (checked) {
+      return has;
+    } else {
+      try {
+        x = it.__next__();
+        has = true;
+      } catch (s:StopIteration) {
+        has = false;
+        x = null;
+      }
+      checked = true;
+      return has;  
+    }
+    
+  }
+}
+
+class Lib
+{
+	/*
+    public static inline function assert(value:Dynamic)
+    {
+        untyped __assert__(value);
+    }
+
+    public static function random(max:Int)
+    {
+       var r = new dart.math.Random(); //TODO(av) benchmark / test caching Random instance as static
+       return r.nextInt(max);
+    }
+    */
+
+    public static function print(v:Dynamic)
+    {
+       python.lib.Sys.stdout.write(Std.string(v));
+       python.lib.Sys.stdout.flush();
+    }
+
+    public static function println(v:Array<Dynamic>)
+    {
+       for (e in v) {
+          untyped __python__("print")(Std.string(e));
+       }
+    }
+
+    public static function toPythonIterable <T>(it:Iterable<T>):python.lib.Types.NativeIterable<T> 
+    {
+      return {
+        __iter__ : function () {
+          var it1 = it.iterator();
+          var self:PyIterator<T> = null;
+          self = new PyIterator({
+            __next__ : function ():T {
+              if (it1.hasNext()) {
+                return it1.next();
+              } else {
+                throw new python.lib.Types.StopIteration();
+              }
+            },
+            __iter__ : function () return self
+          });
+          return self;
+        }
+      }
+    }
+
+    public static inline function toHaxeIterable <T>(it:NativeIterable<T>):HaxeIterable<T> 
+    {
+      return new HaxeIterable(it);
+    }
+
+    public static inline function toHaxeIterator <T>(it:NativeIterator<T>):HaxeIterator<T> 
+    {
+      return new HaxeIterator(it);
+    }
+
+
+    
+}

+ 91 - 0
std/python/Macros.hx

@@ -0,0 +1,91 @@
+package python;
+
+
+import haxe.macro.Expr;
+
+import haxe.macro.Context;
+#if macro
+import haxe.macro.ExprTools;
+#end
+#if !macro
+
+import python.lib.Types.PyIterator;
+#end
+
+
+class Macros {
+
+	@:noUsing macro public static function importModule (module:String):haxe.macro.Expr {
+		return macro untyped __python__($v{"import " + module});
+	}
+
+	@:noUsing macro public static function importAs (module:String, className : String):haxe.macro.Expr 
+    {
+        
+        var n = className.split(".").join("_");
+
+        var e = "import " + module + " as " + n;
+        var e1 = "_hx_c."+n+" = "+n;
+
+
+	    return macro{
+            untyped __python__($v{e});
+            untyped __python__($v{e1});
+        }
+    }
+
+    
+    @:noUsing macro public static function pyFor <T>(v:Expr, it:Expr, b:Expr):haxe.macro.Expr 
+    {
+        var id = switch (v.expr) {
+            case EConst(CIdent(x)):x;
+            case _ : Context.error("unexpected " + ExprTools.toString(v) + ": const ident expected", v.pos);
+        }
+        
+
+
+        var res = macro @:pos(it.pos) {
+            var $id = $it.getNativeIterator().__next__();
+            $it;
+            $b;
+        }
+        return macro (untyped __python_for__)($res);
+    }
+
+    @:noUsing macro public static function importFromAs (from:String, module:String, className : String):haxe.macro.Expr {
+        
+        var n = className.split(".").join("_");
+
+        var e = "from " + from + " import " + module + " as " + n;
+        var e1 = "_hx_c."+n+" = " + n;
+	    return macro {
+            untyped __python__($v{e});
+            untyped __python__($v{e1});
+        }
+    }
+
+    #if !macro macro #end public static function callNamed (e:Expr, args:Expr):haxe.macro.Expr {
+        var fArgs = switch (Context.typeof(e)) {
+            case TFun(args, ret): args;
+            case _ : haxe.macro.Context.error("e must be of type function", e.pos);
+        }
+        switch (args.expr) {
+            case EObjectDecl(fields):
+                for (f in fields) {
+                    var found = false;
+                    for (a in fArgs) {
+                        found = a.name == f.field;
+                        if (found) break;
+                    }
+                    if (!found) {
+                        haxe.macro.Context.error("field " + f.field + " is not a valid argument (valid names " + [for (a in fArgs) a.name].join(",") + ")", args.pos);   
+                    }
+                }
+                // TODO check at least if fields are valid (maybe if types match);
+            case _ : haxe.macro.Context.error("args must be an ObjectDeclaration like { name : 1 }", args.pos);
+        }
+        return macro @:pos(e.pos) untyped __named__($e, $args);
+    }
+
+
+}

+ 12 - 0
std/python/Sys.hx

@@ -0,0 +1,12 @@
+
+package python;
+
+import python.lib.Time;
+
+class Sys {
+
+	public static function time () {
+		return Time.time()/1000;
+	}
+
+}

+ 36 - 0
std/python/Tools.hx

@@ -0,0 +1,36 @@
+
+package python;
+
+class Tools {
+
+	
+
+	public static function substring( s:String, startIndex : Int, ?endIndex : Int ) : String {
+		if (startIndex < 0) startIndex = 0;
+		if (endIndex == null) {
+			return untyped __python__("s[startIndex:]");		
+		} else {
+			if (endIndex < 0) endIndex = 0;
+			if (endIndex < startIndex) {
+				
+				return untyped __python__("s[endIndex:startIndex]");
+			} else {
+				
+				return untyped __python__("s[startIndex:endIndex]");
+			}
+			
+		}
+	}	
+
+	public static function substr( s:String, startIndex : Int, ?len : Int ) : String {
+		if (len == null) {
+			return untyped __python__("s[startIndex:]");
+		} else {
+			if (len == 0) return "";
+			return untyped __python__("s[startIndex:startIndex+len]");
+		}
+		
+	}
+
+
+}

+ 138 - 0
std/python/_std/Array.hx

@@ -0,0 +1,138 @@
+/*
+ * 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.
+ */
+
+import python.lib.Builtin;
+import python.internal.ArrayImpl;
+import python.lib.Types;
+
+@:native("list")
+extern class Array<T> implements ArrayAccess<T> extends ArrayImpl {
+
+	public var length(get,null) : Int;
+
+	private inline function get_length ():Int return ArrayImpl.get_length(this);
+	
+
+	public function new() : Void;
+
+
+	public inline function concat( a : Array<T>) : Array<T> {
+		
+		return ArrayImpl.concat(this, a);
+	}
+
+	public inline function copy() : Array<T> {
+		return ArrayImpl.copy(this);
+	}
+
+	@:runtime public inline function iterator() : Iterator<T> {
+		return ArrayImpl.iterator(this);
+	}
+
+	public function insert( pos : Int, x : T ) : Void;
+
+
+	public inline function join( sep : String ) : String {
+		return ArrayImpl.join(this, sep);
+	}
+
+	public inline function toString() : String {
+		return ArrayImpl.toString(this);
+	}
+
+	@:runtime public inline function pop() : Null<T> {
+		return ArrayImpl.pop(this);
+	}
+
+	@:runtime public inline function push(x:T) : Int {
+		return ArrayImpl.push(this,x);
+	}
+
+	public inline function unshift(x : T) : Void {
+		return ArrayImpl.unshift(this,x);
+	}
+
+	public inline function indexOf(x : T, ?fromIndex:Int) : Int {
+		return ArrayImpl.indexOf(this,x, fromIndex);
+	}
+
+	public inline function lastIndexOf(x : T, ?fromIndex:Int) : Int {
+		return ArrayImpl.lastIndexOf(this,x, fromIndex);
+	}
+
+	public inline function remove(x : T) : Bool {
+		return ArrayImpl.remove(this,x);
+		
+	}
+
+	public function reverse() : Void;
+
+	@:runtime public inline function shift() : Null<T> {
+		return ArrayImpl.shift(this);
+	}
+
+	public inline function slice( pos : Int, ?end : Int ) : Array<T> {
+		return ArrayImpl.slice(this, pos, end);
+	}
+
+	public inline function sort(f:T->T->Int) : Void {
+		return ArrayImpl.sort(this, f);
+	}
+
+	public inline function splice( pos : Int, len : Int ) : Array<T> {
+		return ArrayImpl.splice(this, pos, len);
+	}
+
+	public inline function map<S>( f : T -> S ) : Array<S> {
+		return ArrayImpl.map(this, f);
+	}
+
+	public inline function filter( f : T -> Bool ) : Array<T> {
+		return ArrayImpl.filter(this,f);
+	}
+
+
+	
+	@:keep private inline function __get(idx:Int):T
+	{
+		return ArrayImpl.__get(this, idx);
+	}
+
+	@:keep private inline function __set(idx:Int, val:T):T
+	{
+		return ArrayImpl.__set(this, idx,val);
+	}
+
+	@:keep private inline function __unsafe_get(idx:Int):T
+	{
+		return ArrayImpl.__unsafe_get(this, idx);
+	}
+
+	@:keep private inline function __unsafe_set(idx:Int, val:T):T
+	{
+		return ArrayImpl.__unsafe_set(this, idx,val);
+	}
+
+	@:noCompletion public function __iter__ ():PyIterator<T>;
+
+	
+}

+ 142 - 0
std/python/_std/Date.hx

@@ -0,0 +1,142 @@
+
+
+
+/*
+ * 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;
+
+import python.lib.datetime.DateTime;
+
+
+
+@:coreApi class Date
+{
+	// since January 1, 1970, 00:00:00 GMT
+	//static var BASE = new DateTime(1970, 1, 1);
+
+	private var date:DateTime;
+
+	public function new(year : Int, month : Int, day : Int, hour : Int, min : Int, sec : Int ) : Void
+	{
+		if (year < DateTime.min.year) year = DateTime.min.year;
+		if (day == 0) day = 1;
+		date = new DateTime(year, month+1, day, hour, min, sec);
+	}
+
+	public inline function getTime() : Float
+	{
+			
+		return date.timestamp()*1000.0;
+	}
+
+	public inline function getHours() : Int
+	{
+		return date.hour;
+	}
+
+	public inline function getMinutes() : Int
+	{
+		return date.minute;
+	}
+
+	public inline function getSeconds() : Int
+	{
+		return date.second;
+	}
+
+	public inline function getFullYear() : Int
+	{
+		return date.year;
+	}
+
+	public inline function getMonth() : Int
+	{
+		return date.month-1;
+	}
+
+	public inline function getDate() : Int
+	{
+		return date.day;
+	}
+
+	public inline function getDay() : Int
+	{
+		return date.isoweekday();
+	}
+
+	public function toString():String
+	{
+		inline function st (x) return Std.string(x);
+
+		var m = getMonth()+1;
+		var d = getDate();
+		var h = getHours();
+		var mi = getMinutes();
+		var s = getSeconds();
+		return st(getFullYear())
+			+"-"+(if( m < 10 ) "0"+st(m) else ""+st(m))
+			+"-"+(if( d < 10 ) "0"+st(d) else ""+st(d))
+			+" "+(if( h < 10 ) "0"+st(h) else ""+st(h))
+			+":"+(if( mi < 10 ) "0"+st(mi) else ""+st(mi))
+			+":"+(if( s < 10 ) "0"+st(s) else ""+st(s));
+	}
+
+	static public function now() : Date
+	{
+		var d = new Date(1970, 0, 1, 0, 0, 0);
+		d.date = DateTime.now();
+		return d;
+	}
+
+	static public function fromTime( t : Float ) : Date
+	{
+		var d = new Date(1970, 0, 1, 0, 0, 0);
+		d.date = DateTime.fromtimestamp(t/1000.0);
+		return d;
+	}
+
+	static function UTC( year : Int, month : Int, day : Int, hour : Int, min : Int, sec : Int ) : Float
+	{
+		return new DateTime(year, month+1, day, hour, min, sec, 0, python.lib.datetime.Timezone.utc).timestamp()*1000.0;
+	}
+
+	static public function fromString( s : String ) : Date
+	{
+		switch( s.length )
+		{
+			case 8: // hh:mm:ss
+				var k = s.split(":");
+				var d : Date = new Date(0, 0, 0, Std.parseInt(k[0]), Std.parseInt(k[1]), Std.parseInt(k[2]));
+				return d;
+			case 10: // YYYY-MM-DD
+				var k = s.split("-");
+				return new Date(Std.parseInt(k[0]),Std.parseInt(k[1]) - 1,Std.parseInt(k[2]),0,0,0);
+			case 19: // YYYY-MM-DD hh:mm:ss
+				var k = s.split(" ");
+				var y = k[0].split("-");
+				var t = k[1].split(":");
+				return new Date(Std.parseInt(y[0]),Std.parseInt(y[1]) - 1,Std.parseInt(y[2]),Std.parseInt(t[0]),Std.parseInt(t[1]),Std.parseInt(t[2]));
+			default:
+				throw "Invalid date format : " + s;
+		}
+	}
+}

+ 220 - 0
std/python/_std/DateTools.hx

@@ -0,0 +1,220 @@
+/*
+ * Copyright (C)2005-2013 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.
+ */
+
+/**
+	The DateTools class contains some extra functionalities for handling `Date`
+	instances and timestamps.
+	
+	In the context of haxe dates, a timestamp is defined as the number of
+	milliseconds elapsed since 1st January 1970.
+**/
+class DateTools {
+
+	#if php
+	#elseif (neko && !(macro || interp))
+	static var date_format = neko.Lib.load("std","date_format",2);
+	#else
+	private static function __format_get( d : Date, e : String ) : String {
+		return switch( e ){
+			case "%":
+				"%";
+			case "C":
+				untyped StringTools.lpad(Std.string(Std.int(d.getFullYear()/100)),"0",2);
+			case "d":
+				untyped StringTools.lpad(Std.string(d.getDate()),"0",2);
+			case "D":
+				__format(d,"%m/%d/%y");
+			case "e":
+				untyped Std.string(d.getDate());
+			case "H","k":
+				untyped StringTools.lpad(Std.string(d.getHours()),if( e == "H" ) "0" else " ",2);
+			case "I","l":
+				var hour = d.getHours()%12;
+				untyped StringTools.lpad(Std.string(hour == 0 ? 12 : hour),if( e == "I" ) "0" else " ",2);
+			case "m":
+				untyped StringTools.lpad(Std.string(d.getMonth()+1),"0",2);
+			case "M":
+				untyped StringTools.lpad(Std.string(d.getMinutes()),"0",2);
+			case "n":
+				"\n";
+			case "p":
+				untyped if( d.getHours() > 11 ) "PM"; else "AM";
+			case "r":
+				__format(d,"%I:%M:%S %p");
+			case "R":
+				__format(d,"%H:%M");
+			case "s":
+				Std.string(Std.int(d.getTime()/1000));
+			case "S":
+				untyped StringTools.lpad(Std.string(d.getSeconds()),"0",2);
+			case "t":
+				"\t";
+			case "T":
+				__format(d,"%H:%M:%S");
+			case "u":
+				untyped{
+					var t = d.getDay();
+					if( t == 0 ) "7"; else Std.string(t);
+				}
+			case "w":
+				untyped Std.string(d.getDay());
+			case "y":
+				untyped StringTools.lpad(Std.string(d.getFullYear()%100),"0",2);
+			case "Y":
+				untyped Std.string(d.getFullYear());
+			default:
+				throw "Date.format %"+e+"- not implemented yet.";
+		}
+	}
+
+	private static function __format( d : Date, f : String ) : String {
+		var r = new StringBuf();
+		var p = 0;
+		while( true ){
+			var np = f.indexOf("%", p);
+			if( np < 0 )
+				break;
+
+			r.addSub(f,p,np-p);
+			r.add( __format_get(d, f.substr(np+1,1) ) );
+
+			p = np+2;
+		}
+		r.addSub(f,p,f.length-p);
+		return r.toString();
+	}
+	#end
+
+	/**
+		Format the date `d` according to the format `f`. The format is
+		compatible with the `strftime` standard format, except that there is no
+		support in Flash and JS for day and months names (due to lack of proper
+		internationalization API). On haXe/Neko/Windows, some formats are not
+		supported.
+	**/
+	public static function format( d : Date, f : String ) : String {
+		#if (neko && !(macro || interp))
+			return new String(untyped date_format(d.__t, f.__s));
+		#elseif php
+			return untyped __call__("strftime",f,d.__t);
+		#else
+			return __format(d,f);
+		#end
+	}
+
+	/**
+		Returns the result of adding timestamp `t` to Date `d`.
+		
+		This is a convenience function for calling
+		`Date.fromTime(d.getTime() + t)`.
+	**/
+	public static inline function delta( d : Date, t : Float ) : Date {
+		return Date.fromTime( d.getTime() + t );
+	}
+
+	static var DAYS_OF_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+
+	/**
+		Returns the number of days in the month of Date `d`.
+		
+		This method handles leap years.
+	**/
+	public static function getMonthDays( d : Date ) : Int {
+		var month = d.getMonth();
+		var year = d.getFullYear();
+
+		if (month != 1)
+			return DAYS_OF_MONTH[month];
+
+		var isB = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
+		return if (isB) 29 else 28;
+	}
+
+	/**
+		Converts a number of seconds to a timestamp.
+	**/
+	public static inline function seconds( n : Float ) : Float {
+		return n * 1000.0;
+	}
+
+	/**
+		Converts a number of minutes to a timestamp.
+	**/
+	public static inline function minutes( n : Float ) : Float {
+		return n * 60.0 * 1000.0;
+	}
+
+	/**
+		Converts a number of hours to a timestamp.
+	**/
+	public static inline function hours( n : Float ) : Float {
+		return n * 60.0 * 60.0 * 1000.0;
+	}
+
+	/**
+		Converts a number of days to a timestamp.
+	**/
+	public static inline function days( n : Float ) : Float {
+		return n * 24.0 * 60.0 * 60.0 * 1000.0;
+	}
+
+	/**
+		Separate a date-time into several components
+	**/
+	public static function parse( t : Float ) {
+		var s = t / 1000;
+		var m = s / 60;
+		var h = m / 60;
+		return {
+			ms : t % 1000,
+			seconds : Std.int(s % 60),
+			minutes : Std.int(m % 60),
+			hours : Std.int(h % 24),
+			days : Std.int(h / 24),
+		};
+	}
+
+	/**
+		Build a date-time from several components
+	**/
+	public static function make( o : { ms : Float, seconds : Int, minutes : Int, hours : Int, days : Int } ) {
+		return o.ms + 1000.0 * (o.seconds + 60.0 * (o.minutes + 60.0 * (o.hours + 24.0 * o.days)));
+	}
+	
+	#if (js || flash || php || cpp || python)
+	/**
+		Retrieve Unix timestamp value from Date components. Takes same argument sequence as the Date constructor.
+	**/
+	public static #if (js || flash || php || python) inline #end function makeUtc(year : Int, month : Int, day : Int, hour : Int, min : Int, sec : Int ):Float {
+	    #if (js || flash || python)
+		   return untyped Date.UTC(year, month, day, hour, min, sec);
+		#elseif php
+		   return untyped __call__("gmmktime", hour, min, sec, month + 1, day, year) * 1000;
+		#elseif cpp
+		  return untyped __global__.__hxcpp_utc_date(year,month,day,hour,min,sec)*1000.0 ;
+		#else
+			//TODO
+		   return 0.;
+		#end
+	}
+	#end
+}

+ 259 - 0
std/python/_std/EReg.hx

@@ -0,0 +1,259 @@
+import python.lib.Builtin;
+import python.lib.Re;
+import python.lib.Re.MatchObject;
+import python.lib.Re.Pattern;
+
+class EReg {
+
+	/**
+		Creates a new regular expression with pattern `r` and modifiers `opt`.
+		
+		This is equivalent to the shorthand syntax `~/r/opt`
+		
+		If `r` or `opt` are null, the result is unspecified.
+	**/
+
+	var pattern:Regex;
+	var matchObj:MatchObject;
+	var global:Bool;
+	
+
+
+
+	public function new( r : String, opt : String ) {
+		global = false;
+		var options = 0;
+		for (i in 0...opt.length) {
+			var c = StringTools.fastCodeAt(opt, i);
+			if (c == "m".code) options |= Re.M;
+			if (c == "i".code) options |= Re.I;
+			if (c == "s".code) options |= Re.S;
+			if (c == "u".code) options |= Re.U;
+			if (c == "g".code) global = true;
+		}
+		pattern = Re.compile(r, options);
+	}
+
+	/**
+		Tells if `this` regular expression matches String `s`.
+		
+		This method modifies the internal state.
+		
+		If `s` is `null`, the result is unspecified.
+	**/
+	public function match( s : String ) : Bool {
+		matchObj = Re.search(pattern, s);
+		return matchObj != null;
+	}
+
+	/**
+		Returns the matched sub-group `n` of `this` EReg.
+		
+		This method should only be called after `this.match` or
+		`this.matchSub`, and then operates on the String of that operation.
+		
+		The index `n` corresponds to the n-th set of parentheses in the pattern
+		of `this` EReg. If no such sub-group exists, an exception is thrown.
+		
+		If `n` equals 0, the whole matched substring is returned.
+	**/
+	public function matched( n : Int ) : String {
+		return matchObj.group(n);
+	}
+
+	/**
+		Returns the part to the left of the last matched substring.
+		
+		If the most recent call to `this.match` or `this.matchSub` did not
+		match anything, the result is unspecified.
+		
+		If the global g modifier was in place for the matching, only the
+		substring to the left of the leftmost match is returned.
+		
+		The result does not include the matched part.
+	**/
+	public function matchedLeft() : String {
+		return matchObj.string.substr(0, matchObj.start());
+	}
+
+	/**
+		Returns the part to the right of the last matched substring.
+		
+		If the most recent call to `this.match` or `this.matchSub` did not
+		match anything, the result is unspecified.
+		
+		If the global g modifier was in place for the matching, only the
+		substring to the right of the leftmost match is returned.
+		
+		The result does not include the matched part.
+	**/
+	public function matchedRight() : String {
+		return matchObj.string.substr(matchObj.end());
+	}
+
+	/**
+		Returns the position and length of the last matched substring, within
+		the String which was last used as argument to `this.match` or
+		`this.matchSub`.
+		
+		If the most recent call to `this.match` or `this.matchSub` did not
+		match anything, the result is unspecified.
+		
+		If the global g modifier was in place for the matching, the position and
+		length of the leftmost substring is returned.
+	**/
+	public function matchedPos() : { pos : Int, len : Int } {
+		return { pos : matchObj.start(), len : matchObj.end() - matchObj.start() };
+	}
+
+	/**
+		Tells if `this` regular expression matches a substring of String `s`.
+		
+		This function expects `pos` and `len` to describe a valid substring of
+		`s`, or else the result is unspecified. To get more robust behavior,
+		`this.matchSub(s.substr(pos,len))` can be used instead.
+		
+		This method modifies the internal state.
+		
+		If `s` is null, the result is unspecified.
+	**/
+	public function matchSub( s : String, pos : Int, ?len : Int):Bool {
+		if (len != null) {
+			matchObj = pattern.search(s, pos, pos+len);
+		} else {
+			matchObj = pattern.search(s, pos);
+		}
+		
+		return this.matchObj != null;
+		
+	}
+
+	/**
+		Splits String `s` at all substrings `this` EReg matches.
+		
+		If a match is found at the start of `s`, the result contains a leading
+		empty String "" entry.
+		
+		If a match is found at the end of `s`, the result contains a trailing
+		empty String "" entry.
+		
+		If two matching substrings appear next to each other, the result
+		contains the empty String "" between them.
+		
+		By default, this method splits `s` into two parts at the first matched
+		substring. If the global g modifier is in place, `s` is split at each
+		matched substring.
+		
+		If `s` is null, the result is unspecified.
+	**/
+	public function split( s : String ) : Array<String> {
+		return if (global) {
+			var ret = [];
+			var lastEnd = 0;
+			
+			for (x in Re.finditer(pattern, s)) {
+
+				ret.push(s.substring(lastEnd, x.start() ));
+				lastEnd = x.end();
+			}
+			ret.push(s.substr(lastEnd));
+			return ret;
+		} else {
+			this.match(s);
+			if (matchObj == null) {
+				
+				return [s];
+			} else {
+				return [ s.substring(0, matchObj.start()), s.substr(matchObj.end()) ];
+			}
+
+		}
+	}
+
+	/**
+		Replaces the first substring of `s` which `this` EReg matches with `by`.
+		
+		If `this` EReg does not match any substring, the result is `s`.
+		
+		By default, this method replaces only the first matched substring. If
+		the global g modifier is in place, all matched substrings are replaced.
+		
+		If `by` contains `$1` to `$9`, the digit corresponds to number of a
+		matched sub-group and its value is used instead. If no such sub-group
+		exists, the replacement is unspecified. The string `$$` becomes `$`.
+		
+		If `s` or `by` are null, the result is unspecified.
+	**/
+	public function replace( s : String, by : String ) : String 
+	{
+		var by = by.split("$$").join("_hx_#repl#__");
+		function replace (x:MatchObject) {
+			var res = by;
+			var g = x.groups();
+			for (i in 0...g.length) {
+
+				res = res.split("$"+Builtin.str(i+1)).join(g[i]);
+			}
+			res = res.split("_hx_#repl#__").join("$");
+			return res;
+		}
+		return Re.sub(pattern, replace, s, global ? 0 : 1 );
+	}
+
+	/**
+		For each occurence of the pattern in the string `s`, the function `f` is called and
+		can return the string that needs to be replaced. All occurences are matched anyway,
+		and setting the `g` flag might cause some incorrect behavior on some platforms.
+	**/
+	public function map( s : String, f : EReg -> String ) : String {
+		
+		var buf = new StringBuf();
+		var pos = 0;
+		var right = s;
+		
+		var cur = this;
+		while( pos < s.length ) {
+			
+			if (matchObj == null) {
+				matchObj = Re.search(pattern, s);
+			} else {
+				matchObj = matchObj.re.search(s, pos);
+			}
+
+			if( matchObj == null )
+				break;
+			
+			
+
+			var pos1 = matchObj.end();
+
+			var curPos = cur.matchedPos();
+
+
+			buf.add(cur.matchedLeft().substr(pos));
+			buf.add(f(cur));
+
+			right = cur.matchedRight();
+			
+			
+
+			if (!global) {
+				buf.add(right);
+				return buf.toString();
+			}
+			
+			if (curPos.len == 0) {
+				buf.add(s.charAt(pos1));
+				right = right.substr(1);
+				pos = pos1+1;
+			} else {
+				pos = pos1;
+			}
+
+			
+		}
+		buf.add(right);
+		return buf.toString();
+
+	}
+}

+ 8 - 0
std/python/_std/HxOverrides.hx

@@ -0,0 +1,8 @@
+
+package;
+
+class HxOverrides {
+
+	
+
+}

+ 259 - 0
std/python/_std/Lambda.hx

@@ -0,0 +1,259 @@
+/*
+ * 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.
+ */
+
+/**
+	The `Lambda` class is a collection of methods to support functional
+	programming. It is ideally used with 'using Lambda' and then acts as an
+	extension to Iterable types.
+
+	On static platforms, working with the Iterable structure might be slower
+	than performing the operations directly on known types, such as Array and
+	List.
+
+	If the first argument to any of the methods is null, the result is
+	unspecified.
+**/
+class Lambda {
+
+	/**
+		Creates an Array from Iterable `it`.
+
+		If `it` is an Array, this function returns a copy of it.
+	**/
+	public static function array<A>( it : Iterable<A> ) : Array<A> {
+		var a = new Array<A>();
+		for(i in it)
+			a.push(i);
+		return a;
+	}
+
+	/**
+		Creates a List form Iterable `it`.
+
+		If `it` is a List, this function returns a copy of it.
+	**/
+	public static function list<A>( it : Iterable<A> ) : List<A> {
+		var l = new List<A>();
+		for(i in it)
+			l.add(i);
+		return l;
+	}
+
+	/**
+		Creates a new List by applying function `f` to all elements of `it`.
+
+		The order of elements is preserved.
+
+		If `f` is null, the result is unspecified.
+	**/
+	public static function map<A,B>( it : Iterable<A>, f : A -> B ) : List<B> {
+		var l = new List<B>();
+		for( x in it )
+			l.add(f(x));
+		return l;
+	}
+
+	/**
+		Similar to map, but also passes the index of each element to `f`.
+
+		The order of elements is preserved.
+
+		If `f` is null, the result is unspecified.
+	**/
+	public static function mapi<A,B>( it : Iterable<A>, f : Int -> A -> B ) : List<B> {
+		var l = new List<B>();
+		var i = 0;
+		for( x in it )
+			l.add(f(i++,x));
+		return l;
+	}
+
+	/**
+		Tells if `it` contains `elt`.
+
+		This function returns true as soon as an element is found which is equal
+		to `elt` according to the `==` operator.
+
+		If no such element is found, the result is false.
+	**/
+	public static function has<A>( it : Iterable<A>, elt : A ) : Bool {
+		for( x in it )
+			if( x == elt )
+				return true;
+		return false;
+	}
+
+	/**
+		Tells if `it` contains an element for which `f` is true.
+
+		This function returns true as soon as an element is found for which a
+		call to `f` returns true.
+
+		If no such element is found, the result is false.
+
+		If `f` is null, the result is unspecified.
+	**/
+	public static function exists<A>( it : Iterable<A>, f : A -> Bool ) {
+		for( x in it )
+			if( f(x) )
+				return true;
+		return false;
+	}
+
+	/**
+		Tells if `f` is true for all elements of `it`.
+
+		This function returns false as soon as an element is found for which a
+		call to `f` returns false.
+
+		If no such element is found, the result is true.
+
+		In particular, this function always returns true if `it` is empty.
+
+		If `f` is null, the result is unspecified.
+	**/
+	public static function foreach<A>( it : Iterable<A>, f : A -> Bool ) {
+		for( x in it )
+			if( !f(x) )
+				return false;
+		return true;
+	}
+
+	/**
+		Calls `f` on all elements of `it`, in order.
+
+		If `f` is null, the result is unspecified.
+	**/
+	public static function iter<A>( it : Iterable<A>, f : A -> Void ) {
+		for( x in it )
+			f(x);
+	}
+
+	/**
+		Returns a List containing those elements of `it` for which `f` returned
+		true.
+
+		If `it` is empty, the result is the empty List even if `f` is null.
+
+		Otherwise if `f` is null, the result is unspecified.
+	**/
+	public static function filter<A>( it : Iterable<A>, f : A -> Bool ) {
+		var l = new List<A>();
+		for( x in it )
+			if( f(x) )
+				l.add(x);
+		return l;
+	}
+
+	/**
+		Functional fold on Iterable `it`, using function `f` with start argument
+		`first`.
+
+		If `it` has no elements, the result is `first`.
+
+		Otherwise the first element of `it` is passed to `f` alongside `first`.
+		The result of that call is then passed to `f` with the next element of
+		`it`, and so on until `it` has no more elements.
+
+		If `it` or `f` are null, the result is unspecified.
+	**/
+	public static function fold<A,B>( it : Iterable<A>, f : A -> B -> B, first : B ) : B {
+		for( x in it )
+			first = f(x,first);
+		return first;
+	}
+
+	/**
+		Returns the number of elements in `it` for which `pred` is true, or the
+		total number of elements in `it` if `pred` is null.
+
+		This function traverses all elements.
+	**/
+	public static function count<A>( it : Iterable<A>, ?pred : A -> Bool ) {
+		var n = 0;
+		if( pred == null )
+			for( _ in it )
+				n++;
+		else
+			for( x in it )
+				if( pred(x) )
+					n++;
+		return n;
+	}
+
+	/**
+		Tells if Iterable `it` does not contain any element.
+	**/
+	public static function empty<T>( it : Iterable<T> ) : Bool {
+		return !it.iterator().hasNext();
+	}
+
+	/**
+		Returns the index of the first element `v` within Iterable `it`.
+
+		This function uses operator `==` to check for equality.
+
+		If `v` does not exist in `it`, the result is -1.
+	**/
+	public static function indexOf<T>( it : Iterable<T>, v : T ) : Int {
+		var i = 0;
+		for( v2 in it ) {
+			if( v == v2 )
+				return i;
+			i++;
+		}
+		return -1;
+	}
+
+	/**
+		Returns the first element of `it` for which `f` is true.
+
+		This function returns true as soon as an element is found for which a
+		call to `f` returns true.
+
+		If no such element is found, the result is null.
+
+		If `f` is null, the result is unspecified.
+	**/
+	public static function find<T>( it : Iterable<T>, f : T -> Bool ) : Null<T> {
+		for( v in it ) {
+			if(f(v)) return v;
+		}
+		return null;
+	}
+
+	/**
+		Returns a new List containing all elements of Iterable `a` followed by
+		all elements of Iterable `b`.
+
+		If `a` or `b` are null, the result is unspecified.
+	**/
+	public static function concat<T>( a : Iterable<T>, b : Iterable<T> ) : List<T> {
+		var l = new List();
+		for( x in a )
+			l.add(x);
+		for( x in b )
+			l.add(x);
+		return l;
+	}
+
+}

+ 251 - 0
std/python/_std/List.hx

@@ -0,0 +1,251 @@
+/*
+ * 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.
+ */
+/**
+	A linked-list of elements. The list is composed of two-elements arrays
+	that are chained together. It is optimized so that adding or removing an
+	element does not imply copying the whole array content every time.
+**/
+class List<T> {
+
+	private var h : Array<Dynamic>;
+	private var q : Array<Dynamic>;
+
+	/**
+		The length of `this` List.
+	**/
+	public var length(default,null) : Int;
+
+	/**
+		Creates a new empty list.
+	**/
+	public function new() {
+		length = 0;
+	}
+
+	/**
+		Adds element `item` at the end of `this` List.
+		
+		`this.length` increases by 1.
+	**/
+	public function add( item : T ) {
+		var x:Array<Dynamic> = [item];
+		if( h == null )
+			h = x;
+		else
+			q[1] = x;
+		q = x;
+		length++;
+	}
+
+	/**
+		Adds element `item` at the beginning of `this` List.
+		
+		`this.length` increases by 1.
+	**/
+	public function push( item : T ) {
+		var x : Array<Dynamic> = [item,h];
+		
+		h = x;
+		if( q == null )
+			q = x;
+		length++;
+	}
+
+	/**
+		Returns the first element of `this` List, or null if no elements exist.
+		
+		This function does not modify `this` List.
+	**/
+	public function first() : Null<T> {
+		return if( h == null ) null else h[0];
+	}
+
+	/**
+		Returns the last element of `this` List, or null if no elements exist.
+		
+		This function does not modify `this` List.
+	**/
+	public function last() : Null<T> {
+		return if( q == null ) null else q[0];
+	}
+
+
+	/**
+		Returns the first element of `this` List, or null if no elements exist.
+		
+		The element is removed from `this` List.
+	**/
+	public function pop() : Null<T> {
+		if( h == null )
+			return null;
+		var x = h[0];
+		h = h[1];
+		if( h == null )
+			q = null;
+		length--;
+		return x;
+	}
+
+	/**
+		Tells if `this` List is empty.
+	**/
+	public function isEmpty() : Bool {
+		return (h == null);
+	}
+
+	/**
+		Empties `this` List.
+		
+		This function does not traverse the elements, but simply sets the
+		internal references to null and `this.length` to 0.
+	**/
+	public function clear() : Void {
+		h = null;
+		q = null;
+		length = 0;
+	}
+
+	/**
+		Removes the first occurence of `v` in `this` List.
+		
+		If `v` is found by checking standard equality, it is removed from `this`
+		List and the function returns true.
+		
+		Otherwise, false is returned.
+	**/
+	public function remove( v : T ) : Bool {
+		var prev = null;
+		var l = h;
+		while( l != null ) {
+			if( l[0] == v ) {
+				if( prev == null )
+					h = l[1];
+				else
+					prev[1] = l[1];
+				if( q == l )
+					q = prev;
+				length--;
+				return true;
+			}
+			prev = l;
+			l = l[1];
+		}
+		return false;
+	}
+
+	/**
+		Returns an iterator on the elements of the list.
+	**/
+	public function iterator() : Iterator<T> {
+		
+		var h = h;
+		return cast {
+			hasNext : function() {
+				return (h != null);
+			},
+			next : function() {
+				{
+					if( h == null )
+						return null;
+					var x = h[0];
+					h = h[1];
+					return x;
+				}
+			}
+		}
+		
+	}
+
+	/**
+		Returns a string representation of `this` List.
+		
+		The result is enclosed in { } with the individual elements being
+		separated by a comma.
+	**/
+	public function toString() {
+		var s = new StringBuf();
+		var first = true;
+		var l = h;
+		s.add("{");
+		while( l != null ) {
+			if( first )
+				first = false;
+			else
+				s.add(", ");
+			s.add(Std.string(l[0]));
+			l = l[1];
+		}
+		s.add("}");
+		return s.toString();
+	}
+
+	/**
+		Returns a string representation of `this` List, with `sep` separating
+		each element.
+	**/
+	public function join(sep : String) {
+		var s = new StringBuf();
+		var first = true;
+		var l = h;
+		while( l != null ) {
+			if( first )
+				first = false;
+			else
+				s.add(sep);
+			s.add(l[0]);
+			l = l[1];
+		}
+		return s.toString();
+	}
+
+	/**
+		Returns a list filtered with `f`. The returned list will contain all
+		elements for which `f(x) == true`.
+	**/
+	public function filter( f : T -> Bool ) {
+		var l2 = new List();
+		var l = h;
+		while( l != null ) {
+			var v = l[0];
+			l = l[1];
+			if( f(v) )
+				l2.add(v);
+		}
+		return l2;
+	}
+
+	/**
+		Returns a new list where all elements have been converted by the
+		function `f`.
+	**/
+	public function map<X>(f : T -> X) : List<X> {
+		var b = new List();
+		var l = h;
+		while( l != null ) {
+			var v = l[0];
+			l = l[1];
+			b.add(f(v));
+		}
+		return b;
+	}
+
+}

+ 311 - 0
std/python/_std/Math.hx

@@ -0,0 +1,311 @@
+
+package;
+
+import python.lib.Builtin;
+
+/*
+ * 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.
+ */
+/**
+	This class defines mathematical functions and constants.
+**/
+@:native("_hx_math")
+extern class Math
+{
+	static var PI(get,null) : Float;
+
+	static inline function get_PI():Float return untyped Math.pi;	
+	/**
+		A special Float constant which denotes negative infinity.
+		
+		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. For detailed information,
+		see ...
+		
+		If this constant is converted to an Int, e.g. through Std.int(), the
+		result is unspecified.
+	**/
+	static var NEGATIVE_INFINITY(get, null) : Float;
+
+	static inline function get_NEGATIVE_INFINITY():Float return untyped __python__("float")('-inf');
+	/**
+		A special Float constant which denotes negative infinity.
+		
+		For example, this is the result of 1.0 / 0.0.
+		
+		Operations with POSITIVE_INFINITY as an operand may result in
+		NEGATIVE_INFINITY, POSITIVE_INFINITY or NaN. For detailed information,
+		see ...
+	
+		If this constant is converted to an Int, e.g. through Std.int(), the
+		result is unspecified.
+	**/
+	static var POSITIVE_INFINITY(get,null) : Float;
+
+	static inline function get_POSITIVE_INFINITY():Float return untyped __python__("float")('inf');
+	/**
+		A special Float constant which denotes an invalid number.
+		
+		NaN stands for "Not a Number". It occurs when a mathematically incorrect
+		operation is executed, such as taking the square root of a negative
+		number: Math.sqrt(-1).
+		
+		All further operations with NaN as an operand will result in NaN.
+		
+		If this constant is converted to an Int, e.g. through Std.int(), the
+		result is unspecified.
+		
+		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
+		results when performing arithmetic operations with NaN on Windows, see:
+			https://bugs.php.net/bug.php?id=42143
+	**/
+	static var NaN(get, null) : Float;
+
+	static inline function get_NaN():Float return untyped __python__("float")('nan');
+
+	/**
+		Returns the absolute value of `v`.
+		
+		If `v` is positive or 0, the result is unchanged. Otherwise the result
+		is -`v`.
+		
+		If `v` is NEGATIVE_INFINITY or POSITIVE_INFINITY, the result is
+		POSITIVE_INFINITY.
+		
+		If `v` is NaN, the result is NaN.
+	**/
+	public static inline function abs(v:Float):Float
+	{
+		return (Math:Dynamic).fabs(v);
+	}
+	
+	/**
+		Returns the smaller of values `a` and `b`.
+		
+		If `a` or `b` are NaN, the result is NaN.
+		
+		If `a` or `b` are NEGATIVE_INFINITY, the result is NEGATIVE_INFINITY.
+		
+		If `a` and `b` are POSITIVE_INFINITY, the result is POSITIVE_INFINITY.
+	**/
+
+	public static inline function min(a:Float, b:Float):Float {
+		return if (isNaN(a)) a else if (isNaN(b)) b else Builtin.min(a,b);
+	}
+	
+	/**
+		Returns the greater of values `a` and `b`.
+		
+		If `a` or `b` are NaN, the result is NaN.
+		
+		If `a` or `b` are POSITIVE_INFINITY, the result is POSITIVE_INFINITY.
+		
+		If `a` and `b` are NEGATIVE_INFINITY, the result is NEGATIVE_INFINITY.
+	**/
+	public static inline function max(a:Float, b:Float):Float 
+	{
+		return if (isNaN(a)) a else if (isNaN(b)) b else Builtin.max(a,b);
+	}
+	
+	/**
+		Returns the trigonometric sine of `v`.
+		
+		The unit of `v` is radians.
+		
+		If `v` is NaN or infinite, the result is NaN.
+	**/
+	public static inline function sin(v:Float):Float {
+		return if (v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY) NaN else (Math:Dynamic).sin(v);
+	}
+	
+	/**
+		Returns the trigonometric cosine of `v`.
+		
+		The unit of `v` is radians.
+		
+		If `v` is NaN or infinite, the result is NaN.
+	**/
+	public static inline function cos(v:Float):Float {
+		return if (v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY) NaN else (Math:Dynamic).cos(v);
+	}
+	
+	// TODO
+	static function tan(v:Float):Float;
+	static function asin(v:Float):Float;
+	static function acos(v:Float):Float;
+	static function atan(v:Float):Float;
+	static function atan2(y:Float, x:Float):Float;
+	
+	/**
+		Returns Euler's number, raised to the power of `v`.
+		
+		exp(1.0) is approximately 2.718281828459.
+		
+		If `v` is POSITIVE_INFINITY, the result is POSITIVE_INFINITY.
+		
+		If `v` is NEGATIVE_INFINITY, the result is 0.0.
+		
+		If `v` is NaN, the result is NaN.
+	**/
+	public static inline function exp(v:Float):Float 
+	{
+		if (v == NEGATIVE_INFINITY) {
+			return 0.0;
+		} else if (v == POSITIVE_INFINITY) {
+			return POSITIVE_INFINITY;
+		} else {
+			return (Math:Dynamic).exp(v);
+		}
+	}
+	
+	/**
+		Returns the natural logarithm of `v`.
+		
+		If `v` is negative (including NEGATIVE_INFINITY) or NaN, the result is
+		NaN.
+		
+		If `v` is POSITIVE_INFINITY, the result is POSITIVE_INFINITY.
+		
+		If `v` is 0.0, the result is NEGATIVE_INFINITY.
+		
+		This is the inverse operation of exp, i.e. log(exp(v)) == v always
+		holds.
+	**/
+	public static inline function log(v:Float):Float {
+		return if (v == 0.0) NEGATIVE_INFINITY else if (v < 0.0) NaN else (Math:Dynamic).log(v);
+	}
+	
+	// TODO
+	// http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html#pow(double, double) <-- wtf?
+	static function pow(v:Float, exp:Float):Float;
+	
+	/**
+		Returns the square root of `v`.
+		
+		If `v` is negative (including NEGATIVE_INFINITY) or NaN, the result is
+		NaN.
+		
+		If `v` is POSITIVE_INFINITY, the result is POSITIVE_INFINITY.
+		
+		If `v` is 0.0, the result is 0.0.
+	**/
+	public static inline function sqrt(v:Float):Float
+	{
+		return if (v < 0) NaN else (Math:Dynamic).sqrt(v);
+	}
+	
+	/**
+		Rounds `v` to the nearest Int value.
+
+		If v is outside of the signed Int32 range, or is NaN, NEGATIVE_INFINITY or POSITIVE_INFINITY, the result is unspecified.
+		
+		TODO: need spec
+	**/
+	public static inline function round(v:Float):Int {
+		return Math.floor(v + 0.5);
+	}
+	
+	/**
+		Returns the largest Int value that is not greater than `v`.
+		
+		If v is outside of the signed Int32 range, or is NaN, NEGATIVE_INFINITY or POSITIVE_INFINITY, the result is unspecified.		
+		
+		TODO: need spec
+	**/
+	static function floor(v:Float):Int;
+	
+	/**
+		Returns the smallest Int value that is not less than `v`.
+
+		If v is outside of the signed Int32 range, or is NaN, NEGATIVE_INFINITY or POSITIVE_INFINITY, the result is unspecified.
+		
+		TODO: need spec
+	**/
+	static function ceil(v:Float):Int;
+	
+	/**
+		Returns a pseudo-random number which is greater than or equal to 0.0,
+		and less than 1.0.
+	**/
+	inline static function random() : Float {
+		return python.lib.Random.random();
+	}
+	
+	
+	
+	static inline function ffloor( v : Float ) : Float 
+	{
+		if (v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY) return v;
+		if (isNaN(v)) return NaN;
+		return floor(v);
+	}
+
+	static inline function fceil( v : Float ) : Float 
+	{
+		if (v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY) return v;
+		if (isNaN(v)) return NaN;
+		return ceil(v);
+	}
+
+	static inline function fround( v : Float ) : Float 
+	{
+		if (v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY) return v;
+		if (isNaN(v)) return NaN;
+		return round(v);
+	}
+	
+	
+	
+
+	/**
+		Tells if `f` is a finite number.
+		
+		If `f` is POSITIVE_INFINITY, NEGATIVE_INFINITY or NaN, the result is
+		false.
+		
+		Otherwise the result is true.
+	**/
+	static inline function isFinite( f : Float ) : Bool return f != POSITIVE_INFINITY && f != NEGATIVE_INFINITY && !isNaN(f);
+	
+	/**
+		Tells if `f` is not a valid number.
+		
+		If `f` is NaN, the result is true.
+		
+		Otherwise the result is false. In particular, both POSITIVE_INFINITY and
+		NEGATIVE_INFINITY are not considered NaN.
+	**/
+	static inline function isNaN( f : Float ) : Bool {
+		return untyped _hx_math.isnan(f);
+	}
+
+	static function __init__():Void {
+		python.Macros.importAs("math", "_hx_math");
+	}
+
+}
+
+

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

@@ -0,0 +1,183 @@
+import Map;
+import haxe.ds.StringMap;
+import python.internal.KeywordHandler;
+import python.lib.Builtin;
+import python.lib.Inspect;
+import python.lib.Types;
+
+
+
+/*
+ * 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.
+ */
+@:coreApi class Reflect {
+
+	public static function hasField( o : Dynamic, field : String ) : Bool 
+	{
+		var field = KeywordHandler.handleKeywords(field);
+		//return untyped __js__('Object').prototype.hasOwnProperty.call(o, field);
+		return Builtin.hasattr(o, field);
+		
+	}
+
+	public static function field( o : Dynamic, field : String ) : Dynamic 
+	{
+		if (field == null) return null;
+		var field = KeywordHandler.handleKeywords(field);	
+		return if (Builtin.hasattr(o, field)) Builtin.getattr(o, field) else null;
+		
+	}
+
+	public inline static function setField( o : Dynamic, field : String, value : Dynamic ) : Void untyped 
+	{
+		var field = KeywordHandler.handleKeywords(field);
+		return __define_feature__("Reflect.setField",Builtin.setattr(o,field,value));
+	}
+
+	public static function getProperty( o : Dynamic, field : String ) : Dynamic 
+	{
+		var field = KeywordHandler.handleKeywords(field);
+		//var tmp;
+		//return if( o == null ) __define_feature__("Reflect.getProperty",null) else if( o.__properties__ && (tmp=o.__properties__["get_"+field]) ) o[tmp]() else o[field];
+		var tmp = null;
+		if (o == null) {
+			return null;
+		} else {
+			tmp = Reflect.field(o, "get_" + field);
+			if (tmp != null && Builtin.callable(tmp)) {
+				return tmp();
+			} else {
+				return Reflect.field(o, field);
+			}
+		}
+		//return if (o == null) null else if ( (tmp=Reflect.field(o, "get_" + field)) != null && Builtin.callable(tmp)) tmp() else Reflect.field(o, field);
+	}
+
+	public static inline function setProperty( o : Dynamic, field : String, value : Dynamic ) : Void {
+		
+		var field = KeywordHandler.handleKeywords(field);
+
+		return if (Builtin.hasattr(o,"set_"+field)) {
+			var tmp = Builtin.getattr(o,"set_"+field);
+			tmp(value);
+		}
+		else Builtin.setattr(o,field, untyped __define_feature__("Reflect.setProperty",value));
+		
+		
+		
+	}
+
+	public static function callMethod( o : Dynamic, func : Dynamic, args : Array<Dynamic> ) : Dynamic 
+	{
+		var args:VarArgs = args;
+		return if (Builtin.callable(func)) func(untyped __python_varargs__(args)) else null;
+	}
+
+	public static function fields( o : Dynamic ) : Array<String> 
+	{
+		var a = [];
+		if (o != null) 
+		{
+			if (Builtin.hasattr(o, "_hx_fields")) 
+			{
+				
+				var fields:Array<String> = o._hx_fields;
+				return fields.copy();
+			}
+			if (Builtin.isinstance(o, untyped __python__("_hx_c._hx_AnonObject"))) 
+			{
+				
+				var d:Dict<String, Dynamic> = Builtin.getattr(o, "__dict__");
+				var keys  = d.keys();
+				var handler = python.internal.KeywordHandler.unhandleKeywords;
+				untyped __python__("for k in keys:");
+				untyped __python__("	a.append(handler(k))");
+				
+			} 
+			else if (Builtin.hasattr(o, "__dict__")) 
+			{
+				var a = [];
+				var d:Dict<String, Dynamic> = Builtin.getattr(o, "__dict__");
+				var keys  = untyped d.keys();
+				untyped __python__("for k in keys:");
+				untyped __python__("	a.append(k)");
+
+			}
+		}
+		return a;
+
+	}
+
+	public static function isFunction( f : Dynamic ) : Bool 
+	{
+		return Inspect.isfunction(f) || Inspect.ismethod(f);
+	}
+
+	public static function compare<T>( a : T, b : T ) : Int {
+		if (a == null && b == null) return 0;
+		return 
+		if (a == null) 1 else if (b == null) -1 else
+		( a == b ) ? 0 : (((cast a) > (cast b)) ? 1 : -1);
+		//return throw "not implemented";
+	}
+
+	public static function compareMethods( f1 : Dynamic, f2 : Dynamic ) : Bool {
+		if( f1 == f2 )
+			return true;
+		if( !isFunction(f1) || !isFunction(f2) )
+			return false;
+		
+		return false;
+	}
+
+	public static function isObject( v : Dynamic ) : Bool {
+
+		return switch (Type.typeof(v)) {
+			case TObject, TClass(_): true;
+			case _ : false;
+		}
+
+	}
+	
+	public static function isEnumValue( v : Dynamic ) : Bool {
+		return v != Enum && Builtin.isinstance(v, untyped Enum);
+	}
+
+	public static function deleteField( o : Dynamic, field : String ) : Bool {
+		if( !hasField(o,field) ) return false;
+		untyped __python__("o.__delattr__")(field);
+		return true;
+	}
+
+	public static function copy<T>( o : T ) : T {
+		var o2 : Dynamic = {};
+		for( f in Reflect.fields(o) )
+			Reflect.setField(o2,f,Reflect.field(o,f));
+		return o2;
+	}
+
+	@:overload(function( f : Array<Dynamic> -> Void ) : Dynamic {})
+	public static function makeVarArgs( f : Array<Dynamic> -> Dynamic ) : Dynamic {
+		return throw "not implemented";
+		
+	}
+
+}

+ 228 - 0
std/python/_std/Std.hx

@@ -0,0 +1,228 @@
+package;
+
+import python.lib.Builtin;
+import python.lib.Inspect;
+import python.Boot;
+/*
+ * 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.
+ */
+//import flash.Boot;
+
+@:keepInit
+@:coreApi /*extern*/ class Std {
+
+    public static inline function instance<T:{}, S:T>( value : T, c : Class<S> ) : S {
+        try {
+            return Builtin.isinstance(value,c) ? cast value : null;
+        } catch (e:Dynamic) {
+            return null;
+        }
+
+
+    }
+    public static function is( v : Dynamic, t : Dynamic ) : Bool {
+
+        if (v == null && t == null) {
+            return false;
+        }
+        if (t == null) {
+
+            return false;
+        }
+        if (t == (untyped __python__("Dynamic"))) {
+            return true;
+        }
+        var isBool = Builtin.isinstance(v, (untyped __python__("bool")));
+
+        if (t == (untyped __python__("Bool")) && isBool) {
+            return true;
+        }
+        if (!isBool && t != (untyped __python__("Bool")) && t ==  (untyped __python__("Int")) && Builtin.isinstance(v, (untyped __python__("int")) )) {
+            return true;
+        }
+        var vIsFloat = Builtin.isinstance(v, (untyped __python__("float")));
+
+        if (!isBool && vIsFloat && t == (untyped __python__("Int")) && Math.isFinite(v) && v == Std.int(v)) {
+            return true;
+        }
+
+        if (!isBool &&  t == (untyped __python__("Float")) && ( Builtin.isinstance(v, (untyped __python__("(float,int)"))))) {
+            return true;
+        }
+
+        if ( t == (untyped __python__("str"))) {
+            return Builtin.isinstance(v, String);
+        }
+        if (t == Enum && Inspect.isclass(v) && Builtin.hasattr(v, "_hx_constructs")) return true;
+
+        if (t == Enum) return false;
+
+        if (t == Date && Builtin.isinstance(v, Date)) return true;
+
+        if (t == Date) return false;
+
+        if (Builtin.isinstance(v, Date)) return false;
+
+        if (t == Class && !Builtin.isinstance(v, untyped Enum) && Inspect.isclass(v) && Builtin.hasattr(v, "_hx_class_name") && !Builtin.hasattr(v, "_hx_constructs")) return true;
+
+        if (t == Class) return false; // && !Builtin.isinstance(v, untyped Enum) && Builtin.hasattr(v, "__class__") && untyped Builtin.hasattr(v.__class__, "_hx_class_name") && !untyped Builtin.hasattr(v.__class__, "_hx_constructs")) return true;
+
+
+
+        if (try Builtin.isinstance(v, t) catch (e:Dynamic) false) {
+            return true;
+        }
+        if (Inspect.isclass(t)) {
+
+            function loop (intf)
+            {
+                var f:Array<Dynamic> = Reflect.field(intf, "_hx_interfaces");
+                if (f != null) {
+                    for (i in f) {
+                        if ( i == t) {
+                            return true;
+                        } else {
+                            var l = loop(i);
+                            if (l) {
+                                return true;
+                            }
+                        }
+                    }
+                    return false;
+                } else {
+                    return false;
+                }
+            }
+            return loop(untyped v.__class__);
+
+
+        } else {
+            return false;
+        }
+        //return untyped __is__(v , t);  //TODO(av) macro to check t is a Type and not null as dart only perfomrs "is" at compile time despite having a runtime Type
+    }
+
+//    public static inline function instance<T>( v : {}, c : Class<T> ) : T {
+//        return untyped __as__(v, c);
+//    }
+
+    @:access(python.Boot)
+    @:keep
+    public static function string( s : Dynamic ) : String
+    {
+
+        return python.Boot.__string_rec(s, "");
+    }
+
+    public static inline function int( x : Float ) : Int
+    {
+        try {
+            return (untyped __python__("int"))(x);
+        } catch (e:Dynamic) {
+            return null;
+        }
+    }
+
+    public static function parseInt( x : String ) : Null<Int> {
+        if (x == null) return null;
+        try {
+            return (untyped __python__("int"))(x);
+        } catch (e:Dynamic) {
+            try {
+                var prefix = x.substr(0,2).toLowerCase();
+
+                if (prefix == "0x") {
+                    return (untyped __python__("int"))(x,16);
+                }
+                throw "fail";
+            } catch (e:Dynamic) {
+
+
+                var r = int(parseFloat(x));
+
+                if (r == null) {
+                    var r1 = shortenPossibleNumber(x);
+                    if (r1 != x) {
+                        return parseInt(r1);
+                    } else {
+                        return null;
+                    }
+                }
+                return r;
+            }
+        }
+
+
+    }
+
+    static function shortenPossibleNumber (x:String):String
+    {
+        var r = "";
+        for (i in 0...x.length) {
+            var c = x.charAt(i);
+            switch (c.charCodeAt(0)) {
+                case "0".code
+                | "1".code
+                | "2".code
+                | "3".code
+                | "4".code
+                | "5".code
+                | "6".code
+                | "7".code
+                | "8".code
+                | "9".code
+                | ".".code : r += c;
+                case _ : break;
+            }
+        }
+        return r;
+    }
+
+    public static function parseFloat( x : String ) : Float
+    {
+        try {
+            return untyped __python__("float")(x);
+        } catch (e:Dynamic) {
+
+            if (x != null) {
+                var r1 = shortenPossibleNumber(x);
+                if (r1 != x) {
+                    return parseFloat(r1);
+                }
+            }
+            return Math.NaN;
+
+        }
+
+    }
+
+
+    public static inline function random( x : Int ) : Int {
+        if (x <= 0) {
+            return 0;
+        } else {
+            return int(Math.random()*x);
+        }
+
+        //return dart.Lib.random(x);
+//        return untyped __cascade__(new dartt.math.Random(), nextInt(x));// //untyped x <= 0 ? 0 : Math.floor(Math.random()*x);        import 'dart:marth'; new Random()..nextInt(x);
+    }
+}

+ 208 - 0
std/python/_std/String.hx

@@ -0,0 +1,208 @@
+package;
+/*
+ * 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.
+ */
+/**
+	The basic String class.
+	
+	A haxe String is immutable, it is not possible to modify individual
+	characters. No method of this class changes the state of [this] String.
+	
+	Strings can be constructed using the string literal syntax "string value".
+	
+	String can be concatenated by using the + operator. If an operand is not a
+	String, it is passed through Std.string() first.
+**/
+import python.internal.StringImpl;
+import python.lib.Builtin;
+
+extern class String extends StringImpl {
+
+
+	/**
+		The number of characters in [this] String.
+	**/
+	var length(get,null) : Int;
+
+	private inline function get_length ():Int {
+		return python.lib.Builtin.len(this);
+	}
+
+	/**
+		Creates a copy from a given String.
+	**/
+	function new(string:String) : Void;
+
+	/**
+		Returns a String where all characters of [this] String are upper case.
+		
+		Affects the characters [a-z]. Other characters remain unchanged.
+	**/
+    @:runtime public inline function toUpperCase() : String {
+    	return untyped this.upper();
+    }
+
+	/**
+		Returns a String where all characters of [this] String are lower case.
+		
+		Affects the characters [A-Z]. Other characters remain unchanged.
+	**/
+	inline function toLowerCase() : String {
+		return untyped this.lower();
+	}
+
+	/**
+		Returns the character at position [index] of [this] String.
+		
+		If [index] is negative or exceeds [this].length, the empty String ""
+		is returned.
+	**/
+	inline public function charAt(index : Int) : String
+    {
+        return StringImpl.charAt(this, index);
+    }
+
+	/**
+		Returns the character code at position [index] of [this] String.
+		
+		If [index] is negative or exceeds [this].length, null is returned.
+		
+		To obtain the character code of a single character, "x".code can be used
+		instead to inline the character code at compile time. Note that this
+		only works on String literals of length 1.
+	**/
+	inline public function charCodeAt( index : Int) : Null<Int>
+    {
+        return StringImpl.charCodeAt(this, index);
+    }
+
+	/**
+		Returns the position of the leftmost occurence of [str] within [this]
+		String.
+		
+		If [startIndex] is given, the search is performed within the substring
+		of [this] String starting from [startIndex]. Otherwise the search is
+		performed within [this] String. In either case, the returned position
+		is relative to the beginning of [this] String.
+		
+		If [str] cannot be found, -1 is returned.
+	**/
+	inline function indexOf( str : String, ?startIndex : Int ) : Int {
+		if (startIndex == null)
+			return untyped this.find(str)
+		else
+			return untyped this.find(str, startIndex);
+	}
+
+	/**
+		Returns the position of the rightmost occurence of [str] within [this]
+		String.
+		
+		If [startIndex] is given, the search is performed within the substring
+		of [this] String from 0 to [startIndex]. Otherwise the search is
+		performed within [this] String. In either case, the returned position
+		is relative to the beginning of [this] String.
+		
+		If [str] cannot be found, -1 is returned.
+	**/
+    inline function lastIndexOf( str : String, ?startIndex : Int ) : Int {
+    	return StringImpl.lastIndexOf(this, str, startIndex);
+    }
+
+	/**
+		Splits [this] String at each occurence of [delimiter].
+		
+		If [delimiter] is the empty String "", [this] String is split into an
+		Array of [this].length elements, where the elements correspond to the
+		characters of [this] String.
+		
+		If [delimiter] is not found within [this] String, the result is an Array
+		with one element, which equals [this] String.
+		
+		If [delimiter] is null, the result is unspecified.
+		
+		Otherwise, [this] String is split into parts at each occurence of
+		[delimiter]. If [this] String starts (or ends) with [delimiter}, the
+		result Array contains a leading (or trailing) empty String "" element.
+		Two subsequent delimiters also result in an empty String "" element.
+	**/
+	inline function split( delimiter : String ) : Array<String> return StringImpl.split(this, delimiter);
+
+	/**
+		Returns [len] characters of [this] String, starting at position [pos].
+		
+		If [len] is omitted, all characters from position [pos] to the end of
+		[this] String are included.
+		
+		If [pos] is negative, its value is calculated from the end of [this]
+		String by [this].length + [pos]. If this yields a negative value, 0 is
+		used instead.
+		
+		If the calculated position + [len] exceeds [this].length, the characters
+		from that position to the end of [this] String are returned.
+		
+		If [len] is negative, the result is unspecified.
+	**/
+	inline public function substr( pos : Int, ?len : Int ) : String
+    {
+        return python.Tools.substr(this, pos, len);
+    }
+
+	/**
+		Returns the part of [this] String from [startIndex] to [endIndex].
+		
+		If [startIndex] or [endIndex] are negative, 0 is used instead.
+		
+		If [startIndex] exceeds [endIndex], they are swapped.
+		
+		If the (possibly swapped) [endIndex] is omitted or exceeds
+		[this].length, [this].length is used instead.
+		
+		If the (possibly swapped) [startIndex] exceeds [this].length, the empty
+		String "" is returned.
+	**/
+	inline function substring( startIndex : Int, ?endIndex : Int ) : String {
+		return python.Tools.substring(this, startIndex, endIndex);
+	}
+
+	/**
+		Returns the String itself.
+	**/
+	inline function toString() : String return this;
+
+	/**
+		Returns the String corresponding to the character code [code].
+		
+		If [code] is negative or has another invalid value, the result is
+		unspecified.
+	**/
+	public static inline function fromCharCode( code : Int ) : String {
+		return StringImpl.fromCharCode(code);
+	}
+
+	static function __init__ ():Void {
+		
+		python.Macros.importFromAs("builtins", "str", "String");
+		//untyped __python__("String = __builtin__.str");
+	}
+
+    
+}

+ 110 - 0
std/python/_std/StringBuf.hx

@@ -0,0 +1,110 @@
+import python.lib.Builtin;
+import python.lib.io.StringIO;
+
+/*
+ * 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.
+ */
+/**
+	A String buffer is an efficient way to build a big string by appending small
+	elements together.
+	
+	Its cross-platform implementation uses String concatenation internally, but
+	StringBuf may be optimized for different targets.
+	
+	Unlike String, an instance of StringBuf is not immutable in the sense that
+	it can be passed as argument to functions which modify it by appending more
+	values. However, the internal buffer cannot be modified.
+**/
+
+@:coreApi
+class StringBuf {
+
+	/**
+		Creates a new StringBuf instance.
+		
+		This may involve initialization of the internal buffer.
+	**/
+
+	private var b : StringIO;
+
+    public function new():Void {
+    	this.b = new StringIO();
+    }
+
+    public var length(get, never):Int;
+
+    public inline function get_length ():Int {
+    	// TODO improve implementation
+    	return toString().length;
+    }
+
+	/**
+		Appends the representation of [x] to [this] StringBuf.
+		
+		The exact representation of [x] may vary per platform. To get more
+		consistent behavior, this function should be called with
+		Std.string(x).
+		
+		If [x] is null, the String "null" is appended.
+	**/
+    public inline function add<T>( x : T ) : Void {
+        add1(Std.string(x));
+    }
+
+    inline function add1(s:String):Void {
+    	untyped b.write(s);
+    }
+
+/**
+		Appends the character identified by [c] to [this] StringBuf.
+		
+		If [c] is negative or has another invalid value, the result is
+		unspecified.
+	**/
+    public inline function addChar( c : Int ) : Void {
+        add1(String.fromCharCode(c));
+    }
+
+/**
+		Appends a substring of [s] to [this] StringBuf.
+		
+		This function expects [pos] and [len] to describe a valid substring of
+		[s], or else the result is unspecified. To get more robust behavior,
+		[this].add(s.substr(pos,len)) can be used instead.
+		
+		If [s] or [pos] are null, the result is unspecified.
+		
+		If [len] is omitted or null, the substring ranges from [pos] to the end
+		of [s].
+	**/
+    public inline function addSub( s : String, pos : Int, ?len : Int) : Void {
+        add1((len == null ? s.substr(pos) : s.substr(pos, len)));
+    }
+
+/**
+		Returns the content of [this] StringBuf as String.
+		
+		The buffer is not emptied by this operation.
+	**/
+    public inline function toString() : String {
+    	return untyped b.getvalue();
+    }
+}

+ 284 - 0
std/python/_std/StringTools.hx

@@ -0,0 +1,284 @@
+/*
+ * 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.
+ */
+/**
+	This class provides advanced methods on Strings. It is ideally used with
+	'using StringTools' and then acts as an extension to the String class.
+
+	If the first argument to any of the methods is null, the result is
+	unspecified.
+**/
+
+class StringTools {
+	/**
+		Encode an URL by using the standard format.
+	**/
+	public static function urlEncode( s : String ) : String untyped {
+		__python__("from urllib.parse import quote");
+		return untyped quote(s);
+	}
+
+	/**
+		Decode an URL using the standard format.
+	**/
+	public static function urlDecode( s : String ) : String untyped {
+		__python__("from urllib.parse import unquote");
+		
+		return untyped unquote(s);
+	}
+
+	/**
+		Escapes HTML special characters of the string `s`.
+
+		The following replacements are made:
+			
+		- `&` becomes `&amp`;
+		- `<` becomes `&lt`;
+		- `>` becomes `&gt`;
+		
+		If `quotes` is true, the following characters are also replaced:
+		
+		- `"` becomes `&quot`;
+		- `'` becomes `&#039`;
+	**/
+	public static function htmlEscape( s : String, ?quotes : Bool ) : String {
+		s = s.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;");
+		return quotes ? s.split('"').join("&quot;").split("'").join("&#039;") : s;
+	}
+
+	/**
+		Unescapes HTML special characters of the string `s`.
+
+		This is the inverse operation to htmlEscape, i.e. the following always
+		holds: htmlUnescape(htmlEscape(s)) == s
+
+		The replacements follow:
+			
+		- `&amp;` becomes `&`
+		- `&lt;` becomes `<`
+		- `&gt;` becomes `>`
+		- `&quot;` becomes `"`
+		- `&#039;` becomes `'`
+	**/
+	public static function htmlUnescape( s : String ) : String {
+		return s.split("&gt;").join(">").split("&lt;").join("<").split("&quot;").join('"').split("&#039;").join("'").split("&amp;").join("&");
+	}
+
+	/**
+		Tells if the string `s` starts with the string `start`.
+
+		If `start` is null, the result is unspecified.
+
+		If `start` is the empty String "", the result is true.
+	**/
+	public static #if (cs || java) inline #end function startsWith( s : String, start : String ) : Bool {
+		return( s.length >= start.length && s.substr(0, start.length) == start );
+	}
+
+	/**
+		Tells if the string `s` ends with the string `end`.
+
+		If `end` is null, the result is unspecified.
+
+		If `end` is the empty String "", the result is true.
+	**/
+	public static #if (cs || java) inline #end function endsWith( s : String, end : String ) : Bool {
+		var elen = end.length;
+		var slen = s.length;
+		return( slen >= elen && s.substr(slen - elen, elen) == end );
+	}
+
+	/**
+		Tells if the character in the string `s` at position `pos` is a space.
+
+		A character is considered to be a space character if its character code
+		is 9,10,11,12,13 or 32.
+
+		If `s` is the empty String "", or if pos is not a valid position within
+		`s`, the result is false.
+	**/
+	public static function isSpace( s : String, pos : Int ) : Bool {
+		if (s.length == 0 || pos < 0 || pos >= s.length) return false;
+		var c = s.charCodeAt( pos );
+		return (c > 8 && c < 14) || c == 32;
+	}
+
+	/**
+		Removes leading space characters of `s`.
+
+		This function internally calls isSpace() to decide which characters to
+		remove.
+
+		If `s` is the empty String "" or consists only of space characters, the
+		result is the empty String "".
+	**/
+	public #if cs inline #end static function ltrim( s : String ) : String {
+		
+		var l = s.length;
+		var r = 0;
+		while( r < l && isSpace(s,r) ){
+			r++;
+		}
+		if( r > 0 )
+			return s.substr(r, l-r);
+		else
+			return s;
+	}
+
+	/**
+		Removes trailing space characters of `s`.
+
+		This function internally calls isSpace() to decide which characters to
+		remove.
+
+		If `s` is the empty String "" or consists only of space characters, the
+		result is the empty String "".
+	**/
+	public #if cs inline #end static function rtrim( s : String ) : String {
+		var l = s.length;
+		var r = 0;
+		while( r < l && isSpace(s,l-r-1) ){
+			r++;
+		}
+		if( r > 0 ){
+			return s.substr(0, l-r);
+		}else{
+			return s;
+		}
+	}
+
+	/**
+		Removes leading and trailing space characters of `s`.
+
+		This is a convenience function for ltrim(rtrim(s)).
+	**/
+	public static function trim( s : String ) : String {
+		return ltrim(rtrim(s));
+	}
+
+	/**
+		Concatenates `c` to `s` until `s.length` is at least `l`.
+
+		If `c` is the empty String "" or if `l` does not exceed `s.length`,
+		`s` is returned unchanged.
+
+		If `c.length` is 1, the resulting String length is exactly `l`.
+
+		Otherwise the length may exceed `l`.
+
+		If `c` is null, the result is unspecified.
+	**/
+	public static function lpad( s : String, c : String, l : Int ) : String {
+		if (c.length <= 0)
+			return s;
+
+		while (s.length < l) {
+			s = c + s;
+		}
+		return s;
+	}
+
+	/**
+		Appends `c` to `s` until `s.length` is at least `l`.
+
+		If `c` is the empty String "" or if `l` does not exceed `s.length`,
+		`s` is returned unchanged.
+
+		If `c.length` is 1, the resulting String length is exactly `l`.
+
+		Otherwise the length may exceed `l`.
+
+		If `c` is null, the result is unspecified.
+	**/
+	public static function rpad( s : String, c : String, l : Int ) : String {
+		if (c.length <= 0)
+			return s;
+
+		while (s.length < l) {
+			s = s + c;
+		}
+		return s;
+	}
+
+	/**
+		Replace all occurences of the String `sub` in the String `s` by the
+		String `by`.
+
+		If `sub` is the empty String "", `by` is inserted after each character
+		of `s`. If `by` is also the empty String "", `s` remains unchanged.
+
+		This is a convenience function for `s.split(sub).join(by)`.
+
+		If `sub` or `by` are null, the result is unspecified.
+	**/
+	public static function replace( s : String, sub : String, by : String ) : String {
+		return s.split(sub).join(by);
+	}
+
+	/**
+		Encodes `n` into a hexadecimal representation.
+
+		If `digits` is specified, the resulting String is padded with "0" until
+		its length equals `digits`.
+	**/
+	public static function hex( n : Int, ?digits : Int ) {
+
+		var s = "";
+		var hexChars = "0123456789ABCDEF";
+		do {
+			s = hexChars.charAt(n&15) + s;
+			n >>>= 4;
+		} while( n > 0 );
+		if (digits != null && s.length < digits) {
+			var diff = digits - s.length;
+			for (_ in 0...diff) {
+				s = "0" + s;
+			}
+		}
+		return s;
+		
+	}
+
+	/**
+		Returns the character code at position `index` of String `s`.
+
+		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 operation is not guaranteed to work if `s` contains the \0
+		character.
+	**/
+	public static inline function fastCodeAt( s : String, index : Int ) : Int untyped {
+		
+		return if (index >= s.length) -1 else untyped(ord(untyped s[index]));
+	}
+
+	/*
+		Tells if `c` represents the end-of-file (EOF) character.
+	*/
+	@:noUsing public static inline function isEof( c : Int ) : Bool {
+		return c == -1;
+	}
+
+
+
+}

+ 327 - 0
std/python/_std/Type.hx

@@ -0,0 +1,327 @@
+import python.lib.Builtin;
+
+/*
+ * 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.
+ */
+enum ValueType {
+	TNull;
+	TInt;
+	TFloat;
+	TBool;
+	TObject;
+	TFunction;
+	TClass( c : Class<Dynamic> );
+	TEnum( e : Enum<Dynamic> );
+	TUnknown;
+}
+
+@:access(python.Boot)
+@:coreApi class Type {
+
+	public static function getClass<T>( o : T ) : Class<T> {
+
+		
+
+		if( o == null )
+			return null;
+		
+
+		if (python.Boot.isClass(o)) return null;
+
+		if (python.Boot.isAnonObject(o)) return null;
+
+		if (Builtin.hasattr(o, "_hx_class")) {	
+			return untyped o._hx_class;
+		}
+		if (Builtin.hasattr(o, "__class__")) {	
+			return untyped o.__class__;
+		} else {
+			return null;
+		}
+	}
+
+	public static function getEnum( o : EnumValue ) : Enum<Dynamic> untyped {
+		if( o == null )
+			return null;
+		return untyped o.__class__;
+	}
+
+	public static function getSuperClass( c : Class<Dynamic> ) : Class<Dynamic> untyped {
+		if( c == null )
+			return null;
+		
+		try {
+			if (Builtin.hasattr(c, "_hx_super")) {
+				return untyped c._hx_super;
+			}
+			return untyped __python_array_get(c.__bases__,0);
+		} catch (e:Dynamic) {
+
+		}
+		return null;
+
+	}
+
+
+	public static function getClassName( c : Class<Dynamic> ) : String 
+	{
+		
+		if (Builtin.hasattr(c, "_hx_class_name")) {
+			return untyped c._hx_class_name;
+		} else {
+			// not a haxe class
+			if (c == Array) return "Array";
+			if (c == Math) return "Math";
+			if (c == String) return "String";
+
+			try {
+				var s :String = untyped c.__name__;
+			} catch (e:Dynamic) {
+			
+			}
+		}
+		var res = null;
+		
+
+		return res;
+	}
+
+	public static function getEnumName( e : Enum<Dynamic> ) : String {
+		return untyped e._hx_class_name;
+	}
+
+	public static function resolveClass( name : String ) : Class<Dynamic> {
+		
+		if (name == "Array") return Array;
+		if (name == "Math") return Math;
+		if (name == "String") return String;
+		var cl : Class<Dynamic> = (untyped _hx_classes : python.lib.Types.Dict<String, Class<Dynamic>>).get(name, null);
+        // ensure that this is a class
+        if( cl == null || !python.Boot.isClass(cl) )
+                return null;
+        return cl;
+	}
+
+	public static function resolveEnum( name : String ) : Enum<Dynamic> {
+		if (name == "Bool") return cast Bool;
+		var o = resolveClass(name);
+		return if (Builtin.hasattr(o, "_hx_constructs")) cast o else null;
+	}
+
+	public static function createInstance<T>( cl : Class<T>, args : Array<Dynamic> ) : T untyped 
+	{
+		var l = args.length;
+		switch( l ) 
+		{
+			case 0:
+				return __new__(cl);
+			case 1:
+				return __new__(cl,args[0]);
+			case 2:
+				return __new__(cl,args[0],args[1]);
+			case 3:
+				return __new__(cl,args[0],args[1],args[2]);
+			case 4:
+				return __new__(cl,args[0],args[1],args[2],args[3]);
+			case 5:
+				return __new__(cl,args[0],args[1],args[2],args[3],args[4]);
+			case 6:
+				return __new__(cl,args[0],args[1],args[2],args[3],args[4],args[5]);
+			case 7:
+				return __new__(cl,args[0],args[1],args[2],args[3],args[4],args[5],args[6]);
+			case 8:
+				return __new__(cl,args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7]);
+			default:
+				throw "Too many arguments";
+		}
+		return null;
+	}
+
+	public static function createEmptyInstance<T>( cl : Class<T> ) : T 
+	{
+		var i = untyped cl.__new__(cl);
+
+		function callInit (cl) {
+			var sc = getSuperClass(cl);
+			if (sc != null) {
+				callInit(sc);
+			}
+			if (Builtin.hasattr(cl, "_hx_empty_init")) {
+				
+				untyped cl._hx_empty_init(i);
+			}	
+		}
+		callInit(cl);
+		
+		return i;
+	}
+
+	public static function createEnum<T>( e : Enum<T>, constr : String, ?params : Array<Dynamic> ) : T 
+	{
+		var f = Reflect.field(e,constr);
+		if( f == null ) throw "No such constructor "+constr;
+		if( Reflect.isFunction(f) ) {
+			if( params == null ) throw "Constructor "+constr+" need parameters";
+
+			return Reflect.callMethod(e,f,params);
+		}
+		if( params != null && params.length != 0 )
+			throw "Constructor "+constr+" does not need parameters";
+		return f;
+	}
+
+	public static function createEnumIndex<T>( e : Enum<T>, index : Int, ?params : Array<Dynamic> ) : T {
+
+		var c : String = (untyped e._hx_constructs)[index];
+		if( c == null ) throw index+" is not a valid enum constructor index";
+		return createEnum(e,c,params);
+	}
+
+	public static function getInstanceFields( c : Class<Dynamic> ) : Array<String> {
+		// dict((name, getattr(f, name)) for name in dir(c) if not name.startswith('__'))
+		var f = if (Builtin.hasattr(c, "_hx_fields")) {
+			var x:Array<String> = untyped c._hx_fields;
+			var x2:Array<String> = untyped c._hx_methods;
+			x.concat(x2);
+		} else {
+			[];
+		}
+
+		var sc = getSuperClass(c);
+
+		if (sc == null) {
+			return f;
+		} else {
+			var scArr = getInstanceFields(sc);
+			var scMap = [for (f in scArr) f => f];
+			var res = [];
+			for (f1 in f) {
+				if (!scMap.exists(f1)) {
+					scArr.push(f1);
+				}
+			}
+			
+			return scArr;
+		}
+
+		
+		//return throw "getInstanceFields not implemented";
+	}
+
+	public static function getClassFields( c : Class<Dynamic> ) : Array<String> {
+		if (Builtin.hasattr(c, "_hx_statics")) {
+			var x:Array<String> = untyped c._hx_statics;
+			return x.copy();
+		} else {
+			return [];
+		}
+	}
+
+	public static function getEnumConstructs( e : Enum<Dynamic> ) : Array<String> {
+		if (Builtin.hasattr(e, "_hx_constructs")) {
+			var x:Array<String> = untyped e._hx_constructs;
+			return x.copy();
+		} else {
+			return [];
+		}
+	}
+
+
+
+	public static function typeof( v : Dynamic ) : ValueType {
+		if (v == null) {
+			return TNull;
+		} else if (Builtin.isinstance(v, untyped __python__("bool") )) {
+			return TBool;
+		} else if (Builtin.isinstance(v, untyped __python__("int"))) {
+			return TInt;
+		} else if (Builtin.isinstance(v, untyped __python__("float"))) {
+			return TFloat;
+		} else if (Builtin.isinstance(v, String)) {
+			return TClass(String);
+		} else if (Builtin.isinstance(v, Array)) {
+			return TClass(Array);
+		} else if (Builtin.isinstance(v, untyped __python__("_hx_c._hx_AnonObject")) || python.lib.Inspect.isclass(v)) {
+			return TObject;
+		}
+		else if (Builtin.isinstance(v, untyped __python__("_hx_c.Enum"))) {
+			return TEnum(untyped v.__class__);
+		}
+		else if (Builtin.isinstance(v, untyped __python__("type")) || Builtin.hasattr(v, "_hx_class")) {
+			return TClass(untyped v.__class__);
+		} else if (Builtin.callable(v)) {
+			return TFunction;
+		} else {
+			return TUnknown;
+		}
+	}
+
+	public static function enumEq<T>( a : T, b : T ) : Bool {
+		if( a == b )
+			return true;
+		try {
+			if (b == null && a != b) return false;
+			if( untyped a.tag != untyped b.tag )
+				return false;
+			var p1:Array<Dynamic> = untyped a.params;
+			var p2:Array<Dynamic> = untyped b.params;
+			if (p1.length != p2.length) return false;
+
+			for( i in 0...p1.length )
+				if( !enumEq(p1[i],p2[i]) )
+					return false;
+			//var e = Type.getClass(a);
+
+			if( untyped a._hx_class != untyped b._hx_class)
+				return false;
+		} catch( e : Dynamic ) {
+			return false;
+		}
+		return true;
+	}
+
+	public static inline function enumConstructor( e : EnumValue ) : String {
+		return untyped e.tag;
+	}
+
+	public static inline function enumParameters( e : EnumValue ) : Array<Dynamic> {
+		return untyped e.params;
+	}
+
+	public static inline function enumIndex( e : EnumValue ) : Int {
+		return untyped e.index;
+	}
+
+	public static function allEnums<T>( e : Enum<T> ) : Array<T>
+    {
+            var ctors = getEnumConstructs(e);
+            var ret = [];
+            for (ctor in ctors)
+            {
+                    var v = Reflect.field(e, ctor);
+                    if (Std.is(v, e))
+                            ret.push(v);
+            }
+
+            return ret;
+    }
+
+}

+ 335 - 0
std/python/_std/Xml.hx

@@ -0,0 +1,335 @@
+/*
+ * 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.
+ */
+enum XmlType {
+}
+
+@:coreApi class Xml {
+
+	public static var Element(default,null) : XmlType;
+	public static var PCData(default,null) : XmlType;
+	public static var CData(default,null) : XmlType;
+	public static var Comment(default,null) : XmlType;
+	public static var DocType(default,null) : XmlType;
+	public static var ProcessingInstruction(default,null) : XmlType;
+	public static var Document(default,null) : XmlType;
+
+	public var nodeType(default,null) : XmlType;
+	public var nodeName(get,set) : String;
+	public var nodeValue(get,set) : String;
+	public var parent(get,null) : Xml;
+
+	var _nodeName : String;
+	var _nodeValue : String;
+	var _attributes : haxe.ds.StringMap<String>;
+	var _children : Array<Xml>;
+	var _parent : Xml;
+
+	public static function parse( str : String ) : Xml {
+		return haxe.xml.Parser.parse(str);
+	}
+
+	private function new() : Void {
+	}
+
+	public static function createElement( name : String ) : Xml {
+		var r = new Xml();
+		r.nodeType = Xml.Element;
+		r._children = new Array();
+		r._attributes = new haxe.ds.StringMap();
+		r.set_nodeName( name );
+		return r;
+	}
+
+	public static function createPCData( data : String ) : Xml {
+		var r = new Xml();
+		r.nodeType = Xml.PCData;
+		r.set_nodeValue( data );
+		return r;
+	}
+
+	public static function createCData( data : String ) : Xml {
+		var r = new Xml();
+		r.nodeType = Xml.CData;
+		r.set_nodeValue( data );
+		return r;
+	}
+
+	public static function createComment( data : String ) : Xml {
+		var r = new Xml();
+		r.nodeType = Xml.Comment;
+		r.set_nodeValue( data );
+		return r;
+	}
+
+	public static function createDocType( data : String ) : Xml {
+		var r = new Xml();
+		r.nodeType = Xml.DocType;
+		r.set_nodeValue( data );
+		return r;
+	}
+
+	public static function createProcessingInstruction( data : String ) : Xml {
+		var r = new Xml();
+		r.nodeType = Xml.ProcessingInstruction;
+		r.set_nodeValue( data );
+		return r;
+	}
+
+	public static function createDocument() : Xml {
+		var r = new Xml();
+		r.nodeType = Xml.Document;
+		r._children = new Array();
+		return r;
+	}
+
+	private function get_nodeName() : String {
+		if( nodeType != Xml.Element )
+			throw "bad nodeType";
+		return _nodeName;
+	}
+
+	private function set_nodeName( n : String ) : String {
+		if( nodeType != Xml.Element )
+			throw "bad nodeType";
+		return _nodeName = n;
+	}
+
+	private function get_nodeValue() : String {
+		if( nodeType == Xml.Element || nodeType == Xml.Document )
+			throw "bad nodeType";
+		return _nodeValue;
+	}
+
+	private function set_nodeValue( v : String ) : String {
+		if( nodeType == Xml.Element || nodeType == Xml.Document )
+			throw "bad nodeType";
+		return _nodeValue = v;
+	}
+
+	private function get_parent() : Xml {
+		return _parent;
+	}
+
+	public function get( att : String ) : String {
+		if( nodeType != Xml.Element )
+			throw "bad nodeType";
+		return _attributes.get( att );
+	}
+
+	public function set( att : String, value : String ) : Void {
+		if( nodeType != Xml.Element )
+			throw "bad nodeType";
+		_attributes.set( att, value );
+	}
+
+	public function remove( att : String ) : Void{
+		if( nodeType != Xml.Element )
+			throw "bad nodeType";
+		_attributes.remove( att );
+	}
+
+	public function exists( att : String ) : Bool {
+		if( nodeType != Xml.Element )
+			throw "bad nodeType";
+		return _attributes.exists( att );
+	}
+
+	public function attributes() : Iterator<String> {
+		if( nodeType != Xml.Element )
+			throw "bad nodeType";
+		return _attributes.keys();
+	}
+
+	public function iterator() : Iterator<Xml> {
+		if( _children == null ) throw "bad nodetype";
+		var cur = 0;
+		var x = this._children;
+		return {
+			
+			hasNext : function(){
+				return cur < x.length;
+			},
+			next : function(){
+				return x[cur++];
+			}
+		}
+	}
+
+	public function elements() : Iterator<Xml> {
+		if( _children == null ) throw "bad nodetype";
+		var cur = 0;
+		var x = this._children;
+		return {
+			
+			hasNext : function() {
+				var k = cur;
+				var l = x.length;
+				while( k < l ) {
+					if( x[k].nodeType == Xml.Element )
+						break;
+					k += 1;
+				}
+				cur = k;
+				return k < l;
+			},
+			next : function() {
+				var k = cur;
+				var l = x.length;
+				while( k < l ) {
+					var n = x[k];
+					k += 1;
+					if( n.nodeType == Xml.Element ) {
+						cur = k;
+						return n;
+					}
+				}
+				return null;
+			}
+		}
+	}
+
+	public function elementsNamed( name : String ) : Iterator<Xml> {
+		if( _children == null ) throw "bad nodetype";
+		var cur = 0;
+		var x = this._children;
+		return {
+			
+			hasNext : function() {
+				var k = cur;
+				var l = x.length;
+				while( k < l ) {
+					var n = x[k];
+					if( n.nodeType == Xml.Element && n._nodeName == name )
+						break;
+					k++;
+				}
+				cur = k;
+				return k < l;
+			},
+			next : function() {
+				var k = cur;
+				var l = x.length;
+				while( k < l ) {
+					var n = x[k];
+					k++;
+					if( n.nodeType == Xml.Element && n._nodeName == name ) {
+						cur = k;
+						return n;
+					}
+				}
+				return null;
+			}
+		}
+	}
+
+	public function firstChild() : Xml {
+		if( _children == null ) throw "bad nodetype";
+		return _children[0];
+	}
+
+	public function firstElement() : Xml {
+		if( _children == null ) throw "bad nodetype";
+		var cur = 0;
+		var l = _children.length;
+		while( cur < l ) {
+			var n = _children[cur];
+			if( n.nodeType == Xml.Element )
+				return n;
+			cur++;
+		}
+		return null;
+	}
+
+	public function addChild( x : Xml ) : Void {
+		if( _children == null ) throw "bad nodetype";
+		if( x._parent != null ) x._parent._children.remove(x);
+		x._parent = this;
+		_children.push( x );
+	}
+
+	public function removeChild( x : Xml ) : Bool {
+		if( _children == null ) throw "bad nodetype";
+		var b = _children.remove( x );
+		if( b )
+			x._parent = null;
+		return b;
+	}
+
+	public function insertChild( x : Xml, pos : Int ) : Void {
+		if( _children == null ) throw "bad nodetype";
+		if( x._parent != null ) x._parent._children.remove(x);
+		x._parent = this;
+		_children.insert( pos, x );
+	}
+
+	public function toString() : String {
+		if( nodeType == Xml.PCData )
+			return StringTools.htmlEscape(_nodeValue);
+		if( nodeType == Xml.CData )
+			return "<![CDATA["+_nodeValue+"]]>";
+		if( nodeType == Xml.Comment )
+			return "<!--"+_nodeValue+"-->";
+		if( nodeType == Xml.DocType )
+			return "<!DOCTYPE "+_nodeValue+">";
+		if( nodeType == Xml.ProcessingInstruction )
+			return "<?"+_nodeValue+"?>";
+		var s = new StringBuf();
+
+		if( nodeType == Xml.Element ) {
+			s.add("<");
+			s.add(_nodeName);
+			for( k in _attributes.keys() ){
+				s.add(" ");
+				s.add(k);
+				s.add("=\"");
+				s.add(_attributes.get(k));
+				s.add("\"");
+			}
+			if( _children.length == 0 ) {
+				s.add("/>");
+				return s.toString();
+			}
+			s.add(">");
+		}
+
+		for( x in iterator() )
+			s.add(x.toString());
+
+		if( nodeType == Xml.Element ) {
+			s.add("</");
+			s.add(_nodeName);
+			s.add(">");
+		}
+		return s.toString();
+	}
+
+	static function __init__() : Void untyped {
+		Xml.Element = "element";
+		Xml.PCData = "pcdata";
+		Xml.CData = "cdata";
+		Xml.Comment = "comment";
+		Xml.DocType = "doctype";
+		Xml.ProcessingInstruction = "processingInstruction";
+		Xml.Document = "document";
+	}
+
+}

+ 185 - 0
std/python/_std/haxe/Int32.hx

@@ -0,0 +1,185 @@
+/*
+ * Copyright (C)2005-2013 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;
+
+ /**
+ 	Int32 provides a 32-bit integer with consistent overflow behavior across
+ 	all platforms.
+ **/
+abstract Int32(Int) from Int to Int {
+	@:op(-A) public function negate():Int32;
+
+	@:op(++A) public inline function preIncrement():Int32
+		return this = clamp(++this);
+
+	@:op(A++) public inline function postIncrement():Int32 {
+		var ret = this++;
+		this = clamp(this);
+		return ret;
+	}
+
+	@:op(--A) inline public function preDecrement():Int32
+		return this = clamp(--this);
+
+	@:op(A--) inline public function postDecrement():Int32 {
+		var ret = this--;
+		this = clamp(this);
+		return ret;
+	}
+
+	@:op(A + B) inline public static function add(a:Int32, b:Int32):Int32
+		return clamp( a + b );
+
+	@:op(A + B) inline public static function addInt(a:Int32, b:Int):Int32
+		return clamp( (a : Int) + b );
+
+	@:op(A + B) public static function addFloat(a:Int32, b:Float):Float;
+
+	@:op(A - B) inline public static function sub(a:Int32, b:Int32):Int32
+		return clamp( a - b );
+
+	@:op(A - B) public static function subInt(a:Int32, b:Int):Int32
+		return clamp( (a : Int) - b );
+
+	@:op(A - B) public static function subFloat(a:Int32, b:Int32):Float;
+
+	#if (as3 || flash8 || js || php || python)
+
+	@:op(A * B) inline public static function mul(a:Int32, b:Int32):Int32
+		return clamp( a * (b & 0xFFFF) + clamp( a * (b >>> 16) << 16 ) );
+
+	@:op(A * B) inline public static function mulInt(a:Int32, b:Int):Int32
+		return mul(a, b);
+
+	#else
+
+	@:op(A * B) public static function mul(a:Int32, b:Int32):Int32;
+	@:op(A * B) @:commutative public static function mulInt(a:Int32, b:Int):Int32;
+
+	#end
+
+	@:op(A * B) @:commutative public static function mulFloat(a:Int32, b:Float):Float;
+
+	@:op(A / B) public static function div(a:Int32, b:Int32):Float;
+	@:op(A / B) @:commutative public static function divInt(a:Int32, b:Int):Float;
+	@:op(A / B) @:commutative public static function divFloat(a:Int32, b:Float):Float;
+
+	@:op(A % B) public static function mod(a:Int32, b:Int32):Int32;
+	@:op(A % B) @:commutative public static function modInt(a:Int32, b:Int):Int;
+	@:op(A % B) @:commutative public static function modFloat(a:Int32, b:Float):Float;
+
+	@:op(A == B) public static function eq(a:Int32, b:Int32):Bool;
+	@:op(A == B) @:commutative public static function eqInt(a:Int32, b:Int):Bool;
+	@:op(A == B) @:commutative public static function eqFloat(a:Int32, b:Float):Bool;
+
+	@:op(A != B) public static function neq(a:Int32, b:Int32):Bool;
+	@:op(A != B) @:commutative public static function neqInt(a:Int32, b:Int):Bool;
+	@:op(A != B) @:commutative public static function neqFloat(a:Int32, b:Float):Bool;
+
+	@:op(A < B) public static function lt(a:Int32, b:Int32):Bool;
+	@:op(A < B) @:commutative public static function ltInt(a:Int32, b:Int):Bool;
+	@:op(A < B) @:commutative public static function ltFloat(a:Int32, b:Float):Bool;
+
+	@:op(A <= B) public static function lte(a:Int32, b:Int32):Bool;
+	@:op(A <= B) @:commutative public static function lteInt(a:Int32, b:Int):Bool;
+	@:op(A <= B) @:commutative public static function lteFloat(a:Int32, b:Float):Bool;
+
+	@:op(A > B) public static function gt(a:Int32, b:Int32):Bool;
+	@:op(A > B) @:commutative public static function gtInt(a:Int32, b:Int):Bool;
+	@:op(A > B) @:commutative public static function gtFloat(a:Int32, b:Float):Bool;
+
+	@:op(A >= B) public static function gte(a:Int32, b:Int32):Bool;
+	@:op(A >= B) @:commutative public static function gteInt(a:Int32, b:Int):Bool;
+	@:op(A >= B) @:commutative public static function gteFloat(a:Int32, b:Float):Bool;
+
+	@:op(~A) public function complement():Int32;
+
+	@:op(A & B) public static function and(a:Int32, b:Int32):Int32;
+	@:op(A & B) @:commutative public static function andInt(a:Int32, b:Int):Int32;
+
+	@:op(A | B) public static function or(a:Int32, b:Int32):Int32;
+	@:op(A | B) @:commutative public static function orInt(a:Int32, b:Int):Int32;
+
+	@:op(A ^ B) public static function xor(a:Int32, b:Int32):Int32;
+	@:op(A ^ B) @:commutative public static function xorInt(a:Int32, b:Int):Int32;
+
+
+	@:op(A >> B) public static function shr(a:Int32, b:Int32):Int32;
+	@:op(A >> B) @:commutative public static function shrInt(a:Int32, b:Int):Int32;
+
+	@:op(A >>> B) public static function ushr(a:Int32, b:Int32):Int32;
+	@:op(A >>> B) @:commutative public static function ushrInt(a:Int32, b:Int):Int32;
+
+	#if (php || python)
+
+	// PHP may be 64-bit, so shifts must be clamped
+	@:op(A << B) public static function shl(a:Int32, b:Int32):Int32
+		return clamp( a << b );
+
+	@:op(A << B) @:commutative public static function shlInt(a:Int32, b:Int):Int32
+		return clamp( a << b );
+
+	#else
+
+	@:op(A << B) public static function shl(a:Int32, b:Int32):Int32;
+	@:op(A << B) @:commutative public static function shlInt(a:Int32, b:Int):Int32;
+
+	#end
+
+	@:to public inline function toFloat():Float
+		return this;
+
+	/**
+		Compare two Int32 in unsigned mode.
+	**/
+	public static function ucompare( a : Int32, b : Int32 ) : Int {
+		if( a < 0 )
+			return b < 0 ? ( ~b - ~a ) : 1;
+		return b < 0 ? -1 : (a - b);
+	}
+
+	#if php
+	static var extraBits : Int = untyped __php__("PHP_INT_SIZE") * 8 - 32;
+	#end
+
+	static function clamp( x : Int ) : Int {
+		// force to-int conversion on platforms that require it
+		#if ((as3 || flash8 || js) && !python)
+		
+		return x | 0;
+		
+		#elseif php
+		
+		// we might be on 64-bit php, so sign extend from 32-bit
+		return (x << extraBits) >> extraBits;
+		
+		#elseif python
+		// thx to http://stackoverflow.com/questions/385572/need-help-typecasting-in-python#385583
+		return untyped __python__("(x + 2**31) % 2**32 - 2**31");
+		
+		
+		
+		#else
+		return (x);
+		#end
+	}
+}

+ 274 - 0
std/python/_std/haxe/Int64.hx

@@ -0,0 +1,274 @@
+/*
+ * 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;
+
+class Int64 { 
+
+	var high : Int;
+	var low : Int;
+
+	inline function new(high, low) {
+		this.high = i32(high);
+		this.low = i32(low);
+	}
+
+	#if php
+	/*
+		private function to correctly handle 32-bit integer overflow on php 
+		see: http://stackoverflow.com/questions/300840/force-php-integer-overflow
+	*/
+	private static function i32php(value:Int):Int { 
+			value = (value & untyped __php__("0xFFFFFFFF"));
+ 		    if ( (value & untyped __php__("0x80000000"))!=0 )
+		        value = -(((~value) & untyped __php__("0xFFFFFFFF")) + 1);
+		    return value;
+	}
+	#end
+
+	/*
+		private function to correctly handle 32-bit ushr on php
+		see: https://github.com/HaxeFoundation/haxe/commit/1a878aa90708040a41b0dd59f518d83b09ede209
+	*/
+	private static inline function ushr32(v:Int,n:Int):Int { 
+		#if php
+		 	return (v >> n) & (untyped __php__("0x7fffffff") >> (n-1));
+		#else
+			return v>>>n;
+		#end
+	}
+
+	static function i32(i) {
+		#if python
+			return untyped __python__("(i + 2**31) % 2**32 - 2**31");
+		#elseif (js || flash8)
+			return i | 0;
+		#elseif php
+			return i32php(i); // handle overflow of 32-bit integers correctly 
+		#else
+			return i;
+		#end
+	}
+
+	@:extern static inline function i32mul(a:Int,b:Int) {
+		#if (php || js || flash8)
+		/*
+			We can't simply use i32(a*b) since we might overflow (52 bits precision in doubles)
+		*/
+		return i32(i32((a * (b >>> 16)) << 16) + (a * (b&0xFFFF)));
+		#else
+		return a * b;
+		#end
+	}
+	
+	#if as3 public #end function toString() {
+		if ((high|low) == 0 )
+			return "0";
+		var str = "";
+		var neg = false;
+		var i = this;
+		if( isNeg(i) ) {
+			neg = true;
+			i = Int64.neg(i);
+		}
+		var ten = ofInt(10);
+		while( !isZero(i) ) {
+			var r = divMod(i, ten);
+			str = r.modulus.low + str; 
+			i = r.quotient; 
+		}
+		if( neg ) str = "-" + str;
+		return str;
+	}
+
+	public static inline function make( high : Int, low : Int ) : Int64 {
+		return new Int64(high, low); 
+	}
+
+	public static inline function ofInt( x : Int ) : Int64 {
+		return new Int64(x >> 31,x);
+	}
+
+	public static function toInt( x : Int64 ) : Int {
+		if( x.high != 0 ) {
+			if( x.high < 0 )
+				return -toInt(neg(x));
+			throw "Overflow";
+		}
+		return x.low; 
+	}
+
+	public static function getLow( x : Int64 ) : Int {
+		return x.low;
+	}
+
+	public static function getHigh( x : Int64 ) : Int {
+		return x.high;
+	}
+
+	public static function add( a : Int64, b : Int64 ) : Int64 {
+		var high = i32(a.high + b.high);
+		var low = i32(a.low + b.low);
+		if( uicompare(low,a.low) < 0 )
+			high++;
+		return new Int64(high, low);
+	}
+
+	public static function sub( a : Int64, b : Int64 ) : Int64 {
+		var high = i32(a.high - b.high); // i32() call required to match add
+		var low = i32(a.low - b.low); // i32() call required to match add
+		if( uicompare(a.low,b.low) < 0 )
+			high--;
+		return new Int64(high, low);
+	}
+
+	public static function mul( a : Int64, b : Int64 ) : Int64 {
+		var mask = 0xFFFF;
+		var al = a.low & mask, ah = ushr32(a.low , 16); 
+		var bl = b.low & mask, bh = ushr32(b.low , 16); 
+		var p00 = al * bl;
+		var p10 = ah * bl;
+		var p01 = al * bh;
+		var p11 = ah * bh;
+		var low = p00;
+		var high = i32(p11 + ushr32(p01 , 16) + ushr32(p10 , 16));
+		p01 = i32(p01 << 16); low = i32(low + p01); if( uicompare(low, p01) < 0 ) high = i32(high + 1);
+		p10 = i32(p10 << 16); low = i32(low + p10); if( uicompare(low, p10) < 0 ) high = i32(high + 1);
+		high = i32(high + i32mul(a.low,b.high));
+		high = i32(high + i32mul(a.high,b.low));
+		return new Int64(high, low);
+	}
+
+	static function divMod( modulus : Int64, divisor : Int64 ) {
+		var quotient = new Int64(0, 0);
+		var mask = new Int64(0, 1);
+		divisor = new Int64(divisor.high, divisor.low);
+		while( divisor.high >= 0 ) { 
+			var cmp = ucompare(divisor, modulus);
+			divisor.high = i32( i32(divisor.high << 1) | ushr32(divisor.low , 31) ); 
+			divisor.low = i32(divisor.low << 1); 
+			mask.high = i32( i32(mask.high << 1) | ushr32(mask.low , 31) ); 
+			mask.low = i32(mask.low << 1);
+			if( cmp >= 0 ) break;
+		}
+		while( i32(mask.low | mask.high) != 0 ) { 
+			if( ucompare(modulus, divisor) >= 0 ) {
+				quotient.high= i32(quotient.high | mask.high); 
+				quotient.low= i32(quotient.low | mask.low); 
+				modulus = sub(modulus,divisor);
+			}
+			mask.low = i32( ushr32(mask.low , 1) | i32(mask.high << 31) ); 
+			mask.high = ushr32(mask.high , 1); 
+
+			divisor.low = i32( ushr32(divisor.low , 1) | i32(divisor.high << 31) ); 
+			divisor.high = ushr32(divisor.high , 1); 
+		}
+		return { quotient : quotient, modulus : modulus };
+	}
+
+	public static function div( a : Int64, b : Int64 ) : Int64 { 
+		if(b.high==0) // handle special cases of 0 and 1
+			switch(b.low) {
+			case 0:	throw "divide by zero";
+			case 1: return new Int64(a.high,a.low);
+			} 
+		var sign = ((a.high<0) || (b.high<0)) && (!( (a.high<0) && (b.high<0))); // make sure we get the correct sign
+		if( a.high < 0 ) a = neg(a);
+		if( b.high < 0 ) b = neg(b);
+		var q = divMod(a, b).quotient;
+		return sign ? neg(q) : q;
+	}
+
+	public static function mod( a : Int64, b : Int64 ) : Int64 {
+		if(b.high==0) // handle special cases of 0 and 1
+			switch(b.low) {
+			case 0:	throw "modulus by zero";
+			case 1: return ofInt(0);
+			}
+		var sign = a.high<0; // the sign of a modulus is the sign of the value being mod'ed
+		if( a.high < 0 ) a = neg(a);
+		if( b.high < 0 ) b = neg(b);
+		var m = divMod(a, b).modulus;
+		return sign ? neg(m) : m;
+	}
+
+	public static inline function shl( a : Int64, b : Int ) : Int64 {
+		return if( b & 63 == 0 ) a else if( b & 63 < 32 ) new Int64( (a.high << b) | ushr32(a.low, i32(32-(b&63))), a.low << b ) else new Int64( a.low << i32(b - 32), 0 );
+	}
+
+	public static inline function shr( a : Int64, b : Int ) : Int64 {
+		return if( b & 63 == 0 ) a else if( b & 63 < 32 ) new Int64( a.high >> b, ushr32(a.low,b) | (a.high << i32(32 - (b&63))) ) else new Int64( a.high >> 31, a.high >> i32(b - 32) );
+	}
+
+	public static inline function ushr( a : Int64, b : Int ) : Int64 {
+		return if( b & 63 == 0 ) a else if( b & 63 < 32 ) new Int64( ushr32(a.high, b), ushr32(a.low, b) | (a.high << i32(32 - (b&63))) ) else new Int64( 0, ushr32(a.high, i32(b - 32)) );
+	}
+
+	public static inline function and( a : Int64, b : Int64 ) : Int64 {
+		return new Int64( a.high & b.high, a.low & b.low );
+	}
+
+	public static inline function or( a : Int64, b : Int64 ) : Int64 {
+		return new Int64( a.high | b.high, a.low | b.low );
+	}
+
+	public static inline function xor( a : Int64, b : Int64 ) : Int64 {
+		return new Int64( a.high ^ b.high, a.low ^ b.low );
+	}
+
+	public static inline function neg( a : Int64 ) : Int64 {
+		var high = i32(~a.high); 
+		var low = i32(-a.low); 
+		if( low == 0 )
+			high++;
+		return new Int64(high,low);
+	}
+
+	public static inline function isNeg( a : Int64 ) : Bool {
+		return a.high < 0;
+	}
+
+	public static inline function isZero( a : Int64 ) : Bool {
+		return (a.high | a.low) == 0;
+	}
+
+	static function uicompare( a : Int, b : Int ) {
+		return a < 0 ? (b < 0 ? i32(~b - ~a) : 1) : (b < 0 ? -1 : i32(a - b));
+	}
+
+	public static inline function compare( a : Int64, b : Int64 ) : Int {
+		var v = i32(a.high - b.high); 
+		return if( v != 0 ) v else uicompare(a.low,b.low);
+	}
+
+	/**
+		Compare two Int64 in unsigned mode.
+	**/
+	public static inline function ucompare( a : Int64, b : Int64 ) : Int {
+		var v = uicompare(a.high,b.high);
+		return if( v != 0 ) v else uicompare(a.low, b.low);
+	}
+
+	public static inline function toStr( a : Int64 ) : String {
+		return a.toString();
+	}
+
+}

+ 490 - 0
std/python/_std/haxe/Json.hx

@@ -0,0 +1,490 @@
+/*
+ * 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;
+
+/**
+	Crossplatform JSON API : it will automatically use the optimized native API if available.
+	Use -D haxeJSON to force usage of the Haxe implementation even if a native API is found : this will provide
+	extra encoding features such as enums (replaced by their index), Hashs and Iterable.
+**/
+#if (!python && (flash11 || (js && !old_browser)) && !haxeJSON)
+@:native('JSON') extern
+#end
+class Json {
+
+#if (python || haxeJSON || !(flash11 || (js && !old_browser)))
+	var buf : #if flash9 flash.utils.ByteArray #else StringBuf #end;
+	var str : String;
+	var pos : Int;
+
+	function new() {
+	}
+
+	@:extern inline function addChar(c:Int) {
+		#if flash9
+		buf.writeByte(c);
+		#else
+		buf.addChar(c);
+		#end
+	}
+
+	@:extern inline function add(v:String) {
+		#if flash9
+		// argument is not always a string but will be automatically casted
+		buf.writeUTFBytes(v);
+		#else
+		buf.add(v);
+		#end
+	}
+
+	var replacer:Dynamic -> Dynamic -> Dynamic;
+
+	function toString(v:Dynamic, ?replacer:Dynamic -> Dynamic -> Dynamic) {
+		#if flash9
+		buf = new flash.utils.ByteArray();
+		buf.endian = flash.utils.Endian.BIG_ENDIAN;
+		buf.position = 0;
+		#else
+		buf = new StringBuf();
+		#end
+		this.replacer = replacer;
+		toStringRec("", v);
+		return buf.toString();
+	}
+
+	function fieldsString( v : Dynamic, fields : Array<String> )
+	{
+		var first = true;
+		addChar('{'.code);
+		for( f in fields ) {
+			var value = Reflect.field(v,f);
+			if( Reflect.isFunction(value) ) continue;
+			if( first ) first = false else addChar(','.code);
+			quote(f);
+			addChar(':'.code);
+			toStringRec(f, value);
+		}
+		addChar('}'.code);
+	}
+
+	#if flash9
+	function classString ( v : Dynamic ) {
+		fieldsString(v,Type.getInstanceFields(Type.getClass(v)));
+	}
+	#end
+
+	function objString( v : Dynamic ) {
+		fieldsString(v,Reflect.fields(v));
+	}
+
+	function toStringRec(k:Dynamic, v:Dynamic) {
+		if (replacer != null) v = replacer(k, v);
+		switch( Type.typeof(v) ) {
+		case TUnknown:
+			add('"???"');
+		case TObject:
+			objString(v);
+		case TInt:
+			add(v);
+		case TFloat:
+			add(Math.isFinite(v) ? v : 'null');
+		case TFunction:
+			add('"<fun>"');
+		case TClass(c):
+			if( c == String )
+				quote(v);
+			else if( c == Array ) {
+				var v : Array<Dynamic> = v;
+				addChar('['.code);
+				var len = v.length;
+				if( len > 0 ) {
+					toStringRec(0, v[0]);
+					var i = 1;
+					while( i < len ) {
+						addChar(','.code);
+						toStringRec(i, v[i++]);
+					}
+				}
+				addChar(']'.code);
+			} else if( c == haxe.ds.StringMap ) {
+				var v : haxe.ds.StringMap<Dynamic> = v;
+				var o = {};
+				for( k in v.keys() )
+					Reflect.setField(o,k,v.get(k));
+				objString(o);
+			} else
+				#if flash9
+				classString(v);
+				#else
+				objString(v);
+				#end
+		case TEnum(_):
+			var i : Dynamic = Type.enumIndex(v);
+			add(i);
+		case TBool:
+			add(#if php (v ? 'true' : 'false') #else v #end);
+		case TNull:
+			add('null');
+		}
+	}
+
+	function quote( s : String ) {
+		#if (neko || php || cpp)
+		if( s.length != haxe.Utf8.length(s) ) {
+			quoteUtf8(s);
+			return;
+		}
+		#end
+		addChar('"'.code);
+		var i = 0;
+		while( true ) {
+			var c = StringTools.fastCodeAt(s, i++);
+			if( StringTools.isEof(c) ) break;
+			switch( c ) {
+			case '"'.code: add('\\"');
+			case '\\'.code: add('\\\\');
+			case '\n'.code: add('\\n');
+			case '\r'.code: add('\\r');
+			case '\t'.code: add('\\t');
+			case 8: add('\\b');
+			case 12: add('\\f');
+			default:
+				#if flash9
+				if( c >= 128 ) add(String.fromCharCode(c)) else addChar(c);
+				#else
+				addChar(c);
+				#end
+			}
+		}
+		addChar('"'.code);
+	}
+
+	#if (neko || php || cpp)
+	function quoteUtf8( s : String ) {
+		var u = new haxe.Utf8();
+		haxe.Utf8.iter(s,function(c) {
+			switch( c ) {
+			case '\\'.code, '"'.code: u.addChar('\\'.code); u.addChar(c);
+			case '\n'.code: u.addChar('\\'.code); u.addChar('n'.code);
+			case '\r'.code: u.addChar('\\'.code); u.addChar('r'.code);
+			case '\t'.code: u.addChar('\\'.code); u.addChar('t'.code);
+			case 8: u.addChar('\\'.code); u.addChar('b'.code);
+			case 12: u.addChar('\\'.code); u.addChar('f'.code);
+			default: u.addChar(c);
+			}
+		});
+		buf.add('"');
+		buf.add(u.toString());
+		buf.add('"');
+	}
+	#end
+
+	function doParse( str : String ) {
+		this.str = str;
+		this.pos = 0;
+		return parseRec();
+	}
+
+	function invalidChar() {
+		pos--; // rewind
+		throw "Invalid char "+StringTools.fastCodeAt(str,pos)+" at position "+pos;
+	}
+
+	inline function nextChar() {
+		return StringTools.fastCodeAt(str,pos++);
+	}
+
+	function parseRec() : Dynamic {
+		while( true ) {
+			var c = nextChar();
+			switch( c ) {
+			case ' '.code, '\r'.code, '\n'.code, '\t'.code:
+				// loop
+			case '{'.code:
+				var obj = {}, field = null, comma : Null<Bool> = null;
+				while( true ) {
+					var c = nextChar();
+					switch( c ) {
+					case ' '.code, '\r'.code, '\n'.code, '\t'.code:
+						// loop
+					case '}'.code:
+						if( field != null || comma == false )
+							invalidChar();
+						return obj;
+					case ':'.code:
+						if( field == null )
+							invalidChar();
+						Reflect.setField(obj,field,parseRec());
+						field = null;
+						comma = true;
+					case ','.code:
+						if( comma ) comma = false else invalidChar();
+					case '"'.code:
+						if( comma ) invalidChar();
+						field = parseString();
+					default:
+						invalidChar();
+					}
+				}
+			case '['.code:
+				var arr = [], comma : Null<Bool> = null;
+				while( true ) {
+					var c = nextChar();
+					switch( c ) {
+					case ' '.code, '\r'.code, '\n'.code, '\t'.code:
+						// loop
+					case ']'.code:
+						if( comma == false ) invalidChar();
+						return arr;
+					case ','.code:
+						if( comma ) comma = false else invalidChar();
+					default:
+						if( comma ) invalidChar();
+						pos--;
+						arr.push(parseRec());
+						comma = true;
+					}
+				}
+			case 't'.code:
+				var save = pos;
+				if( nextChar() != 'r'.code || nextChar() != 'u'.code || nextChar() != 'e'.code ) {
+					pos = save;
+					invalidChar();
+				}
+				return true;
+			case 'f'.code:
+				var save = pos;
+				if( nextChar() != 'a'.code || nextChar() != 'l'.code || nextChar() != 's'.code || nextChar() != 'e'.code ) {
+					pos = save;
+					invalidChar();
+				}
+				return false;
+			case 'n'.code:
+				var save = pos;
+				if( nextChar() != 'u'.code || nextChar() != 'l'.code || nextChar() != 'l'.code ) {
+					pos = save;
+					invalidChar();
+				}
+				return null;
+			case '"'.code:
+				return parseString();
+			case '0'.code, '1'.code,'2'.code,'3'.code,'4'.code,'5'.code,'6'.code,'7'.code,'8'.code,'9'.code,'-'.code:
+				return parseNumber(c);
+			default:
+				invalidChar();
+			}
+		}
+	}
+
+	function parseString() {
+		var start = pos;
+		var buf = new StringBuf();
+		while( true ) {
+			var c = nextChar();
+			if( c == '"'.code )
+				break;
+			if( c == '\\'.code ) {
+				buf.addSub(str,start, pos - start - 1);
+				c = nextChar();
+				switch( c ) {
+				case "r".code: buf.addChar("\r".code);
+				case "n".code: buf.addChar("\n".code);
+				case "t".code: buf.addChar("\t".code);
+				case "b".code: buf.addChar(8);
+				case "f".code: buf.addChar(12);
+				case "/".code, '\\'.code, '"'.code: buf.addChar(c);
+				case 'u'.code:
+					var uc = Std.parseInt("0x" + str.substr(pos, 4));
+					pos += 4;
+					#if (neko || php || cpp)
+					if( uc <= 0x7F )
+						buf.addChar(uc);
+					else if( uc <= 0x7FF ) {
+						buf.addChar(0xC0 | (uc >> 6));
+						buf.addChar(0x80 | (uc & 63));
+					} else if( uc <= 0xFFFF ) {
+						buf.addChar(0xE0 | (uc >> 12));
+						buf.addChar(0x80 | ((uc >> 6) & 63));
+						buf.addChar(0x80 | (uc & 63));
+					} else {
+						buf.addChar(0xF0 | (uc >> 18));
+						buf.addChar(0x80 | ((uc >> 12) & 63));
+						buf.addChar(0x80 | ((uc >> 6) & 63));
+						buf.addChar(0x80 | (uc & 63));
+					}
+					#else
+					buf.addChar(uc);
+					#end
+				default:
+					throw "Invalid escape sequence \\" + String.fromCharCode(c) + " at position " + (pos - 1);
+				}
+				start = pos;
+			}
+			#if (neko || php || cpp)
+			// ensure utf8 chars are not cut
+			else if( c >= 0x80 ) {
+				pos++;
+				if( c >= 0xFC ) pos += 4;
+				else if( c >= 0xF8 ) pos += 3;
+				else if( c >= 0xF0 ) pos += 2;
+				else if( c >= 0xE0 ) pos++;
+			}
+			#end
+			else if( StringTools.isEof(c) )
+				throw "Unclosed string";
+		}
+		buf.addSub(str,start, pos - start - 1);
+		return buf.toString();
+	}
+
+	function invalidNumber( start : Int ) {
+		throw "Invalid number at position "+start+": " + str.substr(start, pos - start);
+	}
+
+	inline function parseNumber( c : Int ) {
+		var start = pos - 1;
+		var minus = c == '-'.code, digit = !minus, zero = c == '0'.code;
+		var point = false, e = false, pm = false, end = false;
+		while( true ) {
+			c = nextChar();
+			switch( c ) {
+				case '0'.code :
+					if (zero && !point) invalidNumber(start);
+					if (minus) {
+						minus = false; zero = true;
+					}
+					digit = true;
+				case '1'.code,'2'.code,'3'.code,'4'.code,'5'.code,'6'.code,'7'.code,'8'.code,'9'.code :
+					if (zero && !point) invalidNumber(start);
+					if (minus) minus = false;
+					digit = true; zero = false;
+				case '.'.code :
+					if (minus || point) invalidNumber(start);
+					digit = false; point = true;
+				case 'e'.code, 'E'.code :
+					if (minus || zero || e) invalidNumber(start);
+					digit = false; e = true;
+				case '+'.code, '-'.code :
+					if (!e || pm) invalidNumber(start);
+					digit = false; pm = true;
+				default :
+					if (!digit) invalidNumber(start);
+					pos--;
+					end = true;
+			}
+			if (end) break;
+		}
+		var f = Std.parseFloat(str.substr(start, pos - start));
+		var i = Std.int(f);
+		return if( i == f ) i else f;
+	}
+
+#end
+
+	public static function parse( text : String ) : Dynamic {
+		#if (php && !haxeJSON)
+		return phpJsonDecode(text);
+		#elseif (flash11 && !haxeJSON)
+		return null;
+		#else
+		return new Json().doParse(text);
+		#end
+	}
+
+	public static function stringify( value : Dynamic, ?replacer:Dynamic -> Dynamic -> Dynamic ) : String {
+		#if (php && !haxeJSON)
+		return phpJsonEncode(value, replacer);
+		#elseif (flash11 && !haxeJSON)
+		return null;
+		#else
+		return new Json().toString(value, replacer);
+		#end
+	}
+
+	#if !haxeJSON
+		#if (!python && (js && old_browser))
+		static function __init__() untyped {
+			if( __js__('typeof(JSON)') != 'undefined' )
+				Json = __js__('JSON');
+		}
+		#end
+	#end
+
+	#if php
+	static function phpJsonDecode(json:String):Dynamic {
+		var val = untyped __call__("json_decode", json);
+		return convertAfterDecode(val);
+	}
+
+	static function convertAfterDecode(val:Dynamic):Dynamic {
+		var arr:php.NativeArray;
+		if (untyped __call__("is_object", val)) {
+			arr = phpMapArray(php.Lib.associativeArrayOfObject(val), convertAfterDecode);
+			return untyped __call__("_hx_anonymous", arr);
+		}
+		else if (untyped __call__("is_array", val)) {
+			arr = phpMapArray(val, convertAfterDecode);
+			return php.Lib.toHaxeArray(arr);
+		}
+		else
+			return val;
+	}
+
+	static function phpJsonEncode(val:Dynamic, ?replacer:Dynamic -> Dynamic -> Dynamic):String {
+		if(null != replacer)
+			return new Json().toString(val, replacer);
+		var json = untyped __call__("json_encode", convertBeforeEncode(val));
+		if (untyped __physeq__(json, false))
+			return throw "invalid json";
+		else
+			return json;
+	}
+
+	static function convertBeforeEncode(val:Dynamic):Dynamic {
+		var arr:php.NativeArray;
+		if (untyped __call__("is_object", val)) {
+			switch (untyped __call__("get_class", val)) {
+				case "_hx_anonymous", "stdClass" : arr = php.Lib.associativeArrayOfObject(val);
+				case "_hx_array" : arr = php.Lib.toPhpArray(val);
+				case "Date" : return Std.string(val); //.split(" ").join("T"); //better with "T"?
+				case "HList" : arr = php.Lib.toPhpArray(Lambda.array(val)); //convert List to array?
+				case "_hx_enum" : return Type.enumIndex(val);
+				case "StringMap", "IntMap" : arr = php.Lib.associativeArrayOfHash(val);
+				default : arr = php.Lib.associativeArrayOfObject(val);
+			}
+		}
+		else if (untyped __call__("is_array", val)) arr = val;
+		else {
+			if (untyped __call__("is_float",val) && !__call__("is_finite",val)) val = null;
+			return val;
+		}
+		return phpMapArray(arr, convertBeforeEncode);
+	}
+
+	inline static function phpMapArray(arr:php.NativeArray
+	, func:Dynamic->Dynamic):php.NativeArray {
+		return untyped __call__("array_map", func, arr);
+	}
+
+	#end
+
+}

+ 139 - 0
std/python/_std/haxe/Log.hx

@@ -0,0 +1,139 @@
+/*
+ * 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;
+
+
+
+/**
+	Log primarily provides the trace() method, which is invoked upon a call to
+	trace() in haxe code.
+**/
+class Log {
+
+	/**
+		Outputs `v` in a platform-dependent way.
+
+		The second parameter `infos` is injected by the compiler and contains
+		information about the position where the trace() call was made.
+
+		This method can be rebound to a custom function:
+			var oldTrace = haxe.Log.trace; // store old function
+			haxe.Log.trace = function(v,infos) { // handle trace }
+			...
+			haxe.Log.trace = oldTrace;
+
+		If it is bound to null, subsequent calls to trace() will cause an
+		exception.
+	**/
+	public static dynamic function trace( v : Dynamic, ?infos : PosInfos ) : Void {
+		#if flash
+			#if (fdb || native_trace)
+				var pstr = infos == null ? "(null)" : infos.fileName + ":" + infos.lineNumber;
+				var str = flash.Boot.__string_rec(v, "");
+				if( infos != null && infos.customParams != null ) for( v in infos.customParams ) str += "," + flash.Boot.__string_rec(v, "");
+				untyped #if flash9 __global__["trace"] #else __trace__ #end(pstr+": "+str);
+			#else
+				untyped flash.Boot.__trace(v,infos);
+			#end
+		#elseif neko
+			untyped {
+				$print(infos.fileName + ":" + infos.lineNumber + ": ", v);
+				if( infos.customParams != null ) for( v in infos.customParams ) $print(",", v);
+				$print("\n");
+			}
+		#elseif (js && !python)
+			untyped js.Boot.__trace(v,infos);
+		
+		#elseif php
+			if (infos!=null && infos.customParams!=null) {
+				var extra:String = "";
+				for( v in infos.customParams )
+					extra += "," + v;
+				untyped __call__('_hx_trace', v + extra, infos);
+			}
+			else
+				untyped __call__('_hx_trace', v, infos);		
+		#elseif cpp
+			if (infos!=null && infos.customParams!=null) {
+				var extra:String = "";
+				for( v in infos.customParams )
+					extra += "," + v;
+				untyped __trace(v + extra,infos);
+			}
+			else
+				untyped __trace(v,infos);
+		#elseif (cs || java)
+			var str:String = null;
+			if (infos != null) {
+				str = infos.fileName + ":" + infos.lineNumber + ": " + v;
+				if (infos.customParams != null)
+				{
+					str += "," + infos.customParams.join(",");
+				}
+			} else {
+				str = v;
+			}
+			#if cs
+			untyped __cs__("System.Console.WriteLine(str)");
+			#elseif java
+			untyped __java__("java.lang.System.out.println(str)");
+			
+			#end
+		#elseif (python)
+			var str:String = null;
+			if (infos != null) {
+				str = infos.fileName + ":" + Std.string(infos.lineNumber) + ": " + v;
+				if (python.lib.Builtin.hasattr(infos, "customParams"))
+				{
+					str += "," + infos.customParams.join(",");
+				}
+			} else {
+				str = v;
+			}
+			untyped __python__('print(str)');
+		
+		#end
+	}
+
+	#if (flash || js)
+	/**
+		Clears the trace output.
+	**/
+	public static dynamic function clear() : Void {
+		#if flash
+		untyped flash.Boot.__clear_trace();
+		#elseif js
+		untyped js.Boot.__clear_trace();
+		#end
+	}
+	#end
+
+	#if flash
+	/**
+		Sets the color of the trace output to `rgb`.
+	**/
+	public static dynamic function setColor( rgb : Int ) {
+		untyped flash.Boot.__set_trace_color(rgb);
+	}
+	#end
+
+}

+ 180 - 0
std/python/_std/haxe/Resource.hx

@@ -0,0 +1,180 @@
+/*
+ * Copyright (C)2005-2013 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;
+
+/**
+	Resource can be used to access resources that were added through the
+	-resource file@name command line parameter.
+
+	Depending on their type they can be obtained as String through
+	getString(name), or as binary data through getBytes(name).
+
+	A list of all available resource names can be obtained from listNames().
+**/
+class Resource {
+
+	#if (java || cs)
+	@:keep static var content : Array<String>;
+	#elseif python
+	static var content : python.lib.Types.Dict<String, String>;
+	#else
+	static var content : Array<{ name : String, data : String, str : String }>;
+	
+	#end
+
+	#if cs
+	static var paths : haxe.ds.StringMap<String>;
+
+	#if cs @:keep #end private static function getPaths():haxe.ds.StringMap<String>
+	{
+		if (paths != null)
+			return paths;
+		var p = new haxe.ds.StringMap();
+		var all:cs.NativeArray<String> = untyped __cs__("typeof(haxe.Resource).Assembly.GetManifestResourceNames()");
+		for (i in 0...all.Length)
+		{
+			var path = all[i];
+			var name = path.substr(path.indexOf("Resources.") + 10);
+			p.set(name, path);
+		}
+
+		return paths = p;
+	}
+	#end
+
+	/**
+		Lists all available resource names. The resource name is the name part
+		of the -resource file@name command line parameter.
+	**/
+	public static function listNames() : Array<String> {
+		var names = new Array();
+		#if (java || cs)
+		for ( x in content )
+			names.push(x);
+		#elseif python
+		for ( k in content.keys().iter())
+			names.push(k);
+		#else
+		for ( x in content )
+			names.push(x.name);
+		#end
+		return names;
+	}
+
+	/**
+		Retrieves the resource identified by `name` as a String.
+
+		If `name` does not match any resource name, null is returned.
+	**/
+	public static function getString( name : String ) : String {
+		#if java
+		var stream = cast(Resource, java.lang.Class<Dynamic>).getResourceAsStream("/" + name);
+		if (stream == null)
+			return null;
+		var stream = new java.io.NativeInput(stream);
+		return stream.readAll().toString();
+		#elseif cs
+		var path = getPaths().get(name);
+		var str:cs.system.io.Stream = untyped __cs__("typeof(haxe.Resource).Assembly.GetManifestResourceStream(path)");
+		if (str != null)
+			return new cs.io.NativeInput(str).readAll().toString();
+		return null;
+		#elseif python
+		for( k in content.keys().iter() )
+			if( k == name ) {
+				var b : haxe.io.Bytes = haxe.crypto.Base64.decode(content.get(k, null));
+				return b.toString();
+				
+			}
+		return null;
+		#else
+		for( x in content )
+			if( x.name == name ) {
+				#if neko
+				return new String(x.data);
+				#else
+				if( x.str != null ) return x.str;
+				var b : haxe.io.Bytes = haxe.crypto.Base64.decode(x.data);
+				return b.toString();
+				#end
+			}
+		return null;
+		#end
+	}
+
+	/**
+		Retrieves the resource identified by `name` as an instance of
+		haxe.io.Bytes.
+
+		If `name` does not match any resource name, null is returned.
+	**/
+	public static function getBytes( name : String ) : haxe.io.Bytes {
+		#if java
+		var stream = cast(Resource, java.lang.Class<Dynamic>).getResourceAsStream("/" + name);
+		if (stream == null)
+			return null;
+		var stream = new java.io.NativeInput(stream);
+		return stream.readAll();
+		#elseif cs
+		var path = getPaths().get(name);
+		var str:cs.system.io.Stream = untyped __cs__("typeof(haxe.Resource).Assembly.GetManifestResourceStream(path)");
+		if (str != null)
+			return new cs.io.NativeInput(str).readAll();
+		return null;
+		#elseif python
+		for( k in content.keys().iter() )
+			if( k == name ) {
+				var b : haxe.io.Bytes = haxe.crypto.Base64.decode(content.get(k, null));
+				return b;
+				
+			}
+		return null;
+		#else
+		for( x in content )
+			if( x.name == name ) {
+				#if neko
+				return haxe.io.Bytes.ofData(cast x.data);
+				#else
+				if( x.str != null ) return haxe.io.Bytes.ofString(x.str);
+				return haxe.crypto.Base64.decode(x.data);
+				#end
+			}
+		return null;
+		#end
+	}
+
+	static function __init__() {
+		#if neko
+		var tmp = untyped __resources__();
+		content = untyped Array.new1(tmp,__dollar__asize(tmp));
+		#elseif php
+		content = null;
+		#elseif as3
+		null;
+		#elseif (java || cs)
+		//do nothing
+		#else
+		content = untyped _hx_resources__();
+		#end
+	}
+
+}

+ 547 - 0
std/python/_std/haxe/Serializer.hx

@@ -0,0 +1,547 @@
+/*
+ * Copyright (C)2005-2013 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;
+
+/**
+	The Serializer class can be used to encode values and objects into a String,
+	from which the Unserializer class can recreate the original representation.
+
+	This class can be used in two ways:
+	
+	- create a new Serializer() instance, call its serialize() method with
+		any argument and finally retrieve the String representation from
+		toString()
+	- call Serializer.run() to obtain the serialized representation of a
+		single argument
+
+	Serialization is guaranteed to work for all haxe-defined classes, but may
+	or may not work for instances of external/native classes.
+
+	The specification of the serialization format can be found here:
+	`http://haxe.org/manual/serialization/format`
+**/
+class Serializer {
+
+	/**
+		If the values you are serializing can contain circular references or
+		objects repetitions, you should set USE_CACHE to true to prevent
+		infinite loops.
+
+		This may also reduce the size of serialization Strings at the expense of
+		performance.
+
+		This value can be changed for individual instances of Serializer by
+		setting their useCache field.
+	**/
+	public static var USE_CACHE = false;
+
+	/**
+		Use constructor indexes for enums instead of names.
+
+		This may reduce the size of serialization Strings, but makes them less
+		suited for long-term storage: If constructors are removed or added from
+		the enum, the indices may no longer match.
+
+		This value can be changed for individual instances of Serializer by
+		setting their useEnumIndex field.
+	**/
+	public static var USE_ENUM_INDEX = false;
+
+	static var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%:";
+
+	var buf : StringBuf;
+	var cache : Array<Dynamic>;
+	var shash : haxe.ds.StringMap<Int>;
+	var scount : Int;
+
+	/**
+		The individual cache setting for `this` Serializer instance.
+
+		See USE_CACHE for a complete description.
+	**/
+	public var useCache : Bool;
+
+	/**
+		The individual enum index setting for `this` Serializer instance.
+
+		See USE_ENUM_INDEX for a complete description.
+	**/
+	public var useEnumIndex : Bool;
+
+	/**
+		Creates a new Serializer instance.
+
+		Subsequent calls to `this.serialize` will append values to the
+		internal buffer of this String. Once complete, the contents can be
+		retrieved through a call to `this.toString`.
+
+		Each Serializer instance maintains its own cache if this.useCache` is
+		true.
+	**/
+	public function new() {
+		buf = new StringBuf();
+		cache = new Array();
+		useCache = USE_CACHE;
+		useEnumIndex = USE_ENUM_INDEX;
+		shash = new haxe.ds.StringMap();
+		scount = 0;
+	}
+
+	/**
+		Return the String representation of `this` Serializer.
+
+		The exact format specification can be found here:
+		http://haxe.org/manual/serialization/format
+	**/
+	public function toString() {
+		return buf.toString();
+	}
+
+	/* prefixes :
+		a : array
+		b : hash
+		c : class
+		d : Float
+		e : reserved (float exp)
+		f : false
+		g : object end
+		h : array/list/hash end
+		i : Int
+		j : enum (by index)
+		k : NaN
+		l : list
+		m : -Inf
+		n : null
+		o : object
+		p : +Inf
+		q : haxe.ds.IntMap
+		r : reference
+		s : bytes (base64)
+		t : true
+		u : array nulls
+		v : date
+		w : enum
+		x : exception
+		y : urlencoded string
+		z : zero
+		M : haxe.ds.ObjectMap
+		C : custom
+	*/
+
+	function serializeString( s : String ) {
+		var x = shash.get(s);
+		if( x != null ) {
+			buf.add("R");
+			buf.add(x);
+			return;
+		}
+		shash.set(s,scount++);
+		#if old_serialize
+			// no more support for -D old_serialize due to 'j' reuse
+			#if error #end
+		#end
+		buf.add("y");
+		s = StringTools.urlEncode(s);
+		buf.add(s.length);
+		buf.add(":");
+		buf.add(s);
+	}
+
+	function serializeRef(v) {
+		#if (js && !python)
+		var vt = untyped __js__("typeof")(v);
+		#end
+		for( i in 0...cache.length ) {
+			#if (js && !python)
+			var ci = cache[i];
+			if( untyped __js__("typeof")(ci) == vt && ci == v ) {
+			#else
+			if( cache[i] == v ) {
+			#end
+				buf.add("r");
+				buf.add(i);
+				return true;
+			}
+		}
+		cache.push(v);
+		return false;
+	}
+
+	#if flash9
+	// only the instance variables
+
+	function serializeClassFields(v,c) {
+		var xml : flash.xml.XML = untyped __global__["flash.utils.describeType"](c);
+		var vars = xml.factory[0].child("variable");
+		for( i in 0...vars.length() ) {
+			var f = vars[i].attribute("name").toString();
+			if( !v.hasOwnProperty(f) )
+				continue;
+			serializeString(f);
+			serialize(Reflect.field(v,f));
+		}
+		buf.add("g");
+	}
+	#end
+
+	function serializeFields(v) {
+		for( f in Reflect.fields(v) ) {
+			serializeString(f);
+			serialize(Reflect.field(v,f));
+		}
+		buf.add("g");
+	}
+
+	/**
+		Serializes `v`.
+
+		All haxe-defined values and objects with the exception of functions can
+		be serialized. Serialization of external/native objects is not
+		guaranteed to work.
+
+		The values of `this.useCache` and `this.useEnumIndex` may affect
+		serialization output.
+	**/
+	public function serialize( v : Dynamic ) {
+		switch( Type.typeof(v) ) {
+		case TNull:
+			buf.add("n");
+		case TInt:
+			if( v == 0 ) {
+				buf.add("z");
+				return;
+			}
+			buf.add("i");
+			buf.add(v);
+		case TFloat:
+			if( Math.isNaN(v) )
+				buf.add("k");
+			else if( !Math.isFinite(v) )
+				buf.add(if( v < 0 ) "m" else "p");
+			else {
+				buf.add("d");
+				buf.add(v);
+			}
+		case TBool:
+			buf.add(if( v ) "t" else "f");
+		case TClass(c):
+
+			if( #if neko untyped c.__is_String #else c == String #end ) {
+				serializeString(v);
+				return;
+			}
+			
+			if( useCache && serializeRef(v) )
+				return;
+
+			
+
+			switch( #if (neko || cs || python) Type.getClassName(c) #else c #end ) {
+			case #if (neko || cs || python) "Array" #else cast Array #end:
+				var ucount = 0;
+				buf.add("a");
+				#if (flash9 || python)
+				var v : Array<Dynamic> = v;
+				#end
+				var l = #if (neko || flash9 || php || cs || java || python) v.length #elseif cpp v.__length() #else v[untyped "length"] #end;
+				for( i in 0...l ) {
+					if( v[i] == null )
+						ucount++;
+					else {
+						if( ucount > 0 ) {
+							if( ucount == 1 )
+								buf.add("n");
+							else {
+								buf.add("u");
+								buf.add(ucount);
+							}
+							ucount = 0;
+						}
+						serialize(v[i]);
+					}
+				}
+				if( ucount > 0 ) {
+					if( ucount == 1 )
+						buf.add("n");
+					else {
+						buf.add("u");
+						buf.add(ucount);
+					}
+				}
+
+				buf.add("h");
+			case #if (neko || cs || python) "List" #else cast List #end:
+				buf.add("l");
+				var v : List<Dynamic> = v;
+				for( i in v )
+					serialize(i);
+					
+				buf.add("h");
+			case #if (neko || cs || python) "Date" #else cast Date #end:
+				var d : Date = v;
+				buf.add("v");
+				buf.add(d.toString());
+			case #if (neko || cs || python) "haxe.ds.StringMap" #else cast haxe.ds.StringMap #end:
+				buf.add("b");
+				var v : haxe.ds.StringMap<Dynamic> = v;
+				for( k in v.keys() ) {
+					serializeString(k);
+					serialize(v.get(k));
+				}
+				buf.add("h");
+			case #if (neko || cs || python) "haxe.ds.IntMap" #else cast haxe.ds.IntMap #end:
+				buf.add("q");
+				var v : haxe.ds.IntMap<Dynamic> = v;
+				for( k in v.keys() ) {
+					buf.add(":");
+					buf.add(k);
+					serialize(v.get(k));
+				}
+				buf.add("h");
+			case #if (neko || cs || python) "haxe.ds.ObjectMap" #else cast haxe.ds.ObjectMap #end:
+				buf.add("M");
+				var v : haxe.ds.ObjectMap<Dynamic,Dynamic> = v;
+				for ( k in v.keys() ) {
+					#if (js || flash8 || neko)
+					var id = Reflect.field(k, "__id__");
+					Reflect.deleteField(k, "__id__");
+					serialize(k);
+					Reflect.setField(k, "__id__", id);
+					#else
+					serialize(k);
+					#end
+					serialize(v.get(k));
+				}
+				buf.add("h");
+			case #if (neko || cs || python) "haxe.io.Bytes" #else cast haxe.io.Bytes #end:
+				var v : haxe.io.Bytes = v;
+				#if neko
+				var chars = new String(base_encode(v.getData(),untyped BASE64.__s));
+				#else
+				var i = 0;
+				var max = v.length - 2;
+				var charsBuf = new StringBuf();
+				var b64 = BASE64;
+				while( i < max ) {
+					var b1 = v.get(i++);
+					var b2 = v.get(i++);
+					var b3 = v.get(i++);
+
+					charsBuf.add(b64.charAt(b1 >> 2));
+					charsBuf.add(b64.charAt(((b1 << 4) | (b2 >> 4)) & 63));
+					charsBuf.add(b64.charAt(((b2 << 2) | (b3 >> 6)) & 63));
+					charsBuf.add(b64.charAt(b3 & 63));
+				}
+				if( i == max ) {
+					var b1 = v.get(i++);
+					var b2 = v.get(i++);
+					charsBuf.add(b64.charAt(b1 >> 2));
+					charsBuf.add(b64.charAt(((b1 << 4) | (b2 >> 4)) & 63));
+					charsBuf.add(b64.charAt((b2 << 2) & 63));
+				} else if( i == max + 1 ) {
+					var b1 = v.get(i++);
+					charsBuf.add(b64.charAt(b1 >> 2));
+					charsBuf.add(b64.charAt((b1 << 4) & 63));
+				}
+				var chars = charsBuf.toString();
+				#end
+				buf.add("s");
+				buf.add(chars.length);
+				buf.add(":");
+				buf.add(chars);
+			default:
+				cache.pop();
+				if( #if flash9 try v.hxSerialize != null catch( e : Dynamic ) false #elseif (cs || java || python) Reflect.hasField(v, "hxSerialize") #else v.hxSerialize != null #end  ) {
+					buf.add("C");
+					serializeString(Type.getClassName(c));
+					cache.push(v);
+					v.hxSerialize(this);
+					buf.add("g");
+				} else {
+					buf.add("c");
+					serializeString(Type.getClassName(c));
+					cache.push(v);
+					#if flash9
+					serializeClassFields(v,c);
+					#else
+					serializeFields(v);
+					#end
+				}
+			}
+		case TObject:
+
+			if( useCache && serializeRef(v) )
+				return;
+			buf.add("o");
+
+			serializeFields(v);
+			
+		case TEnum(e):
+			if( useCache && serializeRef(v) )
+				return;
+			cache.pop();
+			buf.add(useEnumIndex?"j":"w");
+			serializeString(Type.getEnumName(e));
+			#if neko
+			if( useEnumIndex ) {
+				buf.add(":");
+				buf.add(v.index);
+			} else
+				serializeString(new String(v.tag));
+			buf.add(":");
+			if( v.args == null )
+				buf.add(0);
+			else {
+				var l : Int = untyped __dollar__asize(v.args);
+				buf.add(l);
+				for( i in 0...l )
+					serialize(v.args[i]);
+			}
+			#elseif flash9
+			if( useEnumIndex ) {
+				buf.add(":");
+				buf.add(v.index);
+			} else
+				serializeString(v.tag);
+			buf.add(":");
+			var pl : Array<Dynamic> = v.params;
+			if( pl == null )
+				buf.add(0);
+			else {
+				buf.add(pl.length);
+				for( p in pl )
+					serialize(p);
+			}
+			#elseif cpp
+			if( useEnumIndex ) {
+				buf.add(":");
+				buf.add(v.__Index());
+			} else
+				serializeString(v.__Tag());
+			buf.add(":");
+			var pl : Array<Dynamic> = v.__EnumParams();
+			if( pl == null )
+				buf.add(0);
+			else {
+				buf.add(pl.length);
+				for( p in pl )
+					serialize(p);
+			}
+			#elseif php
+			if( useEnumIndex ) {
+				buf.add(":");
+				buf.add(v.index);
+			} else
+				serializeString(v.tag);
+			buf.add(":");
+			var l : Int = untyped __call__("count", v.params);
+			if( l == 0 || v.params == null)
+				buf.add(0);
+			else {
+				buf.add(l);
+				for( i in 0...l )
+					serialize(untyped __field__(v, __php__("params"), i));
+			}
+			#elseif (java || cs || python)
+			if( useEnumIndex ) {
+				buf.add(":");
+				buf.add(Type.enumIndex(v));
+			} else
+				serializeString(Type.enumConstructor(v));
+			buf.add(":");
+			
+			var arr:Array<Dynamic> = Type.enumParameters(v);
+			
+			
+			if (arr != null)
+			{
+				buf.add(arr.length);
+				for (v in arr)
+					serialize(v);
+			} else {
+				
+				buf.add("0");
+				
+
+			}
+			#else
+			if( useEnumIndex ) {
+				buf.add(":");
+				buf.add(v[1]);
+			} else
+				serializeString(v[0]);
+			buf.add(":");
+			var l = v[untyped "length"];
+			buf.add(l - 2);
+			for( i in 2...l )
+				serialize(v[i]);
+			#end
+			cache.push(v);
+		case TFunction:
+			throw "Cannot serialize function";
+		default:
+			#if neko
+			if( untyped (__i32__kind != null && __dollar__iskind(v,__i32__kind)) ) {
+				buf.add("i");
+				buf.add(v);
+				return;
+			}
+			#end
+			throw "Cannot serialize "+Std.string(v);
+		}
+	}
+
+	public function serializeException( e : Dynamic ) {
+		buf.add("x");
+		#if flash9
+		if( untyped __is__(e,__global__["Error"]) ) {
+			var e : flash.errors.Error = e;
+			var s = e.getStackTrace();
+			if( s == null )
+				serialize(e.message);
+			else
+				serialize(s);
+			return;
+		}
+		#end
+		serialize(e);
+	}
+
+	/**
+		Serializes `v` and returns the String representation.
+
+		This is a convenience function for creating a new instance of
+		Serializer, serialize `v` into it and obtain the result through a call
+		to toString().
+	**/
+	public static function run( v : Dynamic ) {
+		var s = new Serializer();
+		s.serialize(v);
+		return s.toString();
+	}
+
+	#if neko
+	static var base_encode = neko.Lib.load("std","base_encode",2);
+	#end
+
+}
+

+ 163 - 0
std/python/_std/haxe/Timer.hx

@@ -0,0 +1,163 @@
+
+
+/*
+ * Copyright (C)2005-2013 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;
+
+/**
+	The Timer class allows you to create asynchronous timers on platforms that
+	support events.
+	
+	The intended usage is to create an instance of the Timer class with a given
+	interval, set its run() method to a custom function to be invoked and
+	eventually call stop() to stop the Timer.
+	
+	It is also possible to extend this class and override its run() method in
+	the child class.
+**/
+class Timer {
+	#if (neko || php || cpp || python)
+	#else
+
+	private var id : Null<Int>;
+
+	/**
+		Creates a new timer that will run every `time_ms` milliseconds.
+		
+		After creating the Timer instance, it calls `this].run` repeatedly,
+		with delays of `time_ms` milliseconds, until `this.stop` is called.
+		
+		The first invocation occurs after `time_ms` milliseconds, not
+		immediately.
+		
+		The accuracy of this may be platform-dependent.
+	**/
+	public function new( time_ms : Int ){
+		#if flash9
+			var me = this;
+			id = untyped __global__["flash.utils.setInterval"](function() { me.run(); },time_ms);
+		#elseif flash
+			var me = this;
+			id = untyped _global["setInterval"](function() { me.run(); },time_ms);
+		#elseif js
+			var me = this;
+			id = untyped setInterval(function() me.run(),time_ms);
+		#end
+	}
+
+	/**
+		Stops `this` Timer.
+		
+		After calling this method, no additional invocations of `this.run`
+		will occur.
+		
+		It is not possible to restart `this` Timer once stopped.
+	**/
+	public function stop() {
+		if( id == null )
+			return;
+		#if flash9
+			untyped __global__["flash.utils.clearInterval"](id);
+		#elseif flash
+			untyped _global["clearInterval"](id);
+		#elseif js
+			untyped clearInterval(id);
+		#end
+		id = null;
+	}
+
+	/**
+		This method is invoked repeatedly on `this` Timer.
+		
+		It can be overridden in a subclass, or rebound directly to a custom
+		function:
+			var timer = new haxe.Timer(1000); // 1000ms delay
+			timer.run = function() { ... }
+			
+		Once bound, it can still be rebound to different functions until `this`
+		Timer is stopped through a call to `this.stop`.
+	**/
+	public dynamic function run() {
+
+	}
+
+	/**
+		Invokes `f` after `time_ms` milliseconds.
+		
+		This is a convenience function for creating a new Timer instance with
+		`time_ms` as argument, binding its run() method to `f` and then stopping
+		`this` Timer upon the first invocation.
+		
+		If `f` is null, the result is unspecified.
+	**/
+	public static function delay( f : Void -> Void, time_ms : Int ) {
+		var t = new haxe.Timer(time_ms);
+		t.run = function() {
+			t.stop();
+			f();
+		};
+		return t;
+	}
+
+	#end
+
+	/**
+		Measures the time it takes to execute `f`, in seconds with fractions.
+		
+		This is a convenience function for calculating the difference between
+		Timer.stamp() before and after the invocation of `f`.
+		
+		The difference is passed as argument to Log.trace(), with "s" appended
+		to denote the unit. The optional `pos` argument is passed through.
+		
+		If `f` is null, the result is unspecified.
+	**/
+	public static function measure<T>( f : Void -> T, ?pos : PosInfos ) : T {
+		var t0 = stamp();
+		var r = f();
+		Log.trace((stamp() - t0) + "s", pos);
+		return r;
+	}
+
+	/**
+		Returns a timestamp, in seconds with fractions.
+		
+		The value itself might differ depending on platforms, only differences
+		between two values make sense.
+	**/
+	public static function stamp() : Float {
+		#if flash
+			return flash.Lib.getTimer() / 1000;
+		#elseif (neko || php)
+			return Sys.time();
+		#elseif js
+			return Date.now().getTime() / 1000;
+		#elseif cpp
+			return untyped __global__.__time_stamp();
+		#elseif sys
+			return Sys.time();
+		#else
+			return 0;
+		#end
+	}
+
+}

+ 63 - 0
std/python/_std/haxe/ds/IntMap.hx

@@ -0,0 +1,63 @@
+package haxe.ds;
+
+import python.lib.Types.Dict;
+
+class IntMap<T> implements Map.IMap<Int, T> {
+	private var h : Dict<Int, T>;
+
+	public function new() : Void {
+		h = new Dict();
+	}
+
+	public function set( key : Int, value : T ) : Void {
+		h.set(key, value);
+	}
+
+	public inline function get( key : Int ) : Null<T> {
+		return h.get(key, null);
+	}
+
+	public inline function exists( key : Int ) : Bool {
+		return h.hasKey(key);
+	}
+
+	public function remove( key : Int ) : Bool 
+	{
+		if(!h.hasKey(key)) return false;
+		untyped __python__("del self.h[key]");
+		return true;
+	}
+
+	public function keys() : Iterator<Int> {
+		var a = [];
+		
+		untyped __python__("for key in self.h:");
+		untyped __python__("	a.append(key)");
+		
+		return a.iterator();
+	}
+
+	public function iterator() : Iterator<T> {
+		var iter = keys();
+		var ref = h;
+		return {
+			hasNext : function() { return iter.hasNext(); },
+			next : function() { var i = iter.next(); return ref.get(i, null); }
+		};
+	}
+	
+	public function toString() : String {
+		var s = new StringBuf();
+		s.add("{");
+		var it = keys();
+		for( i in it ) {
+			s.add(i);
+			s.add(" => ");
+			s.add(Std.string(get(i)));
+			if( it.hasNext() )
+				s.add(", ");
+		}
+		s.add("}");
+		return s.toString();
+	}
+}

+ 58 - 0
std/python/_std/haxe/ds/ObjectMap.hx

@@ -0,0 +1,58 @@
+package haxe.ds;
+
+import python.lib.Builtin;
+import python.lib.Types;
+
+class ObjectMap<K:{},V> implements Map.IMap<K, V> {
+	
+	var h : Dict<K,V>;
+	
+	
+	public function new() : Void {
+		h = new Dict();
+	}
+	
+	public function set(key:K, value:V):Void {
+		h.set(key, value);
+	}
+	
+	public inline function get(key:K):Null<V> {
+		return h.get(key, null);
+	}
+	
+	public inline function exists(key:K):Bool {
+		return h.hasKey(key);
+	}
+	
+	public function remove( key : K ) : Bool 
+	{
+		var r = h.hasKey(key);
+		
+		if (r) h.remove(key);
+		
+		return r;
+	}
+	
+	public function keys() : Iterator<K> {
+		return h.keys().iter();
+	}
+	
+	public function iterator() : Iterator<V> {
+		return h.values().iter();
+	}
+	
+	public function toString() : String {
+		var s = new StringBuf();
+		s.add("{");
+		var it = keys();
+		for( i in it ) {
+			s.add(Std.string(i));
+			s.add(" => ");
+			s.add(Std.string(get(i)));
+			if( it.hasNext() )
+				s.add(", ");
+		}
+		s.add("}");
+		return s.toString();
+	}
+}

+ 67 - 0
std/python/_std/haxe/ds/StringMap.hx

@@ -0,0 +1,67 @@
+package haxe.ds;
+
+import python.lib.Types.Dict;
+
+class StringMap<T> implements Map.IMap<String, T> {
+	private var h : Dict<String,T>;
+
+	public function new() : Void {
+		h = untyped __python__("{}");
+	}
+
+	public function set( key : String, value : T ) : Void {
+		h.set("$"+key, value);
+	}
+
+	public function get( key : String ) : Null<T> {
+		return h.get("$"+key, null);
+		
+	}
+
+	public function exists( key : String ) : Bool {
+		return h.hasKey("$" + key);
+	}
+
+	public function remove( key : String ) : Bool {
+		key = "$"+key;
+
+		if( !h.hasKey(key) ) return false;
+		untyped __python__("del self.h[key]");
+		return true;
+	}
+
+	public function keys() : Iterator<String> {
+		
+		var a = [];
+		
+		untyped __python__("for key in self.h:");
+		untyped __python__("	a.append(key[1:])");
+		
+		return a.iterator();
+	}
+	public function iterator() : Iterator<T> {
+		var iter = keys();
+		var ref = h;
+		return {
+			hasNext : function() { return iter.hasNext(); },
+			next : function() { var i = iter.next(); return ref.get("$"+i, null); }
+		};
+	}
+	
+	public function toString() : String {
+
+		var s = new StringBuf();
+
+		s.add("{");
+		var it = keys();
+		for( i in it ) {
+			s.add(i);
+			s.add(" => ");
+			s.add(Std.string(get(i)));
+			if( it.hasNext() )
+				s.add(", ");
+		}
+		s.add("}");
+		return s.toString();
+	}
+}

+ 173 - 0
std/python/_std/haxe/ds/Vector.hx

@@ -0,0 +1,173 @@
+/*
+ * Copyright (C)2005-2013 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.ds;
+
+private typedef VectorData<T> = #if flash10
+	flash.Vector<T>
+#elseif neko
+	neko.NativeArray<T>
+#elseif cs
+	cs.NativeArray<T>
+#elseif java
+	java.NativeArray<T>
+#else
+	Array<T>
+#end
+
+/**
+	A Vector is a storage of fixed size. It can be faster than Array on some
+	targets, and is never slower.
+**/
+@:arrayAccess
+abstract Vector<T>(VectorData<T>) {
+	/**
+		Creates a new Vector of length [length].
+
+		Initially [this] Vector contains [length] neutral elements:
+			- always null on dynamic targets
+			- 0, 0.0 or false for Int, Float and Bool respectively on static
+			targets
+			- null for other types on static targets
+
+		If [length] is less than or equal to 0, the result is unspecified.
+	**/
+	public inline function new(length:Int) {
+		#if flash9
+			this = new flash.Vector<T>(length, true);
+		#elseif neko
+			this = untyped __dollar__amake(length);
+		#elseif python
+			this = new Array();
+			for (i in 0...length) {
+				this[i] = null;
+			}
+		#elseif js
+			this = untyped __new__(Array, length);
+		#elseif cs
+			this = new cs.NativeArray(length);
+		#elseif java
+			this = new java.NativeArray(length);
+		#elseif cpp
+			this = untyped (new Array<T>()).__SetSizeExact(length);
+		#else
+			this = [];
+			untyped this.length = length;
+		#end
+	}
+
+	/**
+		Returns the value at index [index].
+
+		If [index] is negative or exceeds [this].length, the result is
+		unspecified.
+	**/
+	public inline function get(index:Int):Null<T> {
+		return this[index];
+	}
+
+	/**
+		Sets the value at index [index] to [val].
+
+		If [index] is negative or exceeds [this].length, the result is
+		unspecified.
+	**/
+	public inline function set(index:Int, val:T):T {
+		return this[index] = val;
+	}
+
+	/**
+		Returns the length of [this] Vector.
+	**/
+	public var length(get, never):Int;
+
+	inline function get_length():Int {
+		#if neko
+			return untyped __dollar__asize(this);
+		#elseif cs
+			return this.Length;
+		#elseif java
+			return this.length;
+		#elseif python
+			return this.length;
+		#else
+			return untyped this.length;
+		#end
+	}
+
+	/**
+		Copies [length] of elements from [src] Vector, beginning at [srcPos] to [dest] Vector, beginning at [destPos]
+
+		The results are unspecified if [length] results in out-of-bounds access, or if [src] or [dest] are null
+	**/
+	public static #if (cs || java || neko) inline #end function blit<T>(src:Vector<T>, srcPos:Int, dest:Vector<T>, destPos:Int, len:Int):Void
+	{
+		#if neko
+			untyped __dollar__ablit(dest,destPos,src,srcPos,len);
+		#elseif java
+			java.lang.System.arraycopy(src, srcPos, dest, destPos, len);
+		#elseif cs
+			cs.system.Array.Copy(cast src, srcPos,cast dest, destPos, len);
+		#else
+			for (i in 0...len)
+			{
+				dest[destPos + i] = src[srcPos + i];
+			}
+		#end
+	}
+
+	/**
+		Extracts the data of [this] Vector.
+
+		This returns the internal representation type.
+	**/
+	public inline function toData():VectorData<T>
+		return cast this;
+
+	/**
+		Initializes a new Vector from [data].
+
+		Since [data] is the internal representation of Vector, this is a no-op.
+
+		If [data] is null, the corresponding Vector is also [null].
+	**/
+	static public inline function fromData<T>(data:VectorData<T>):Vector<T>
+		return cast data;
+
+	/**
+		Creates a new Vector by copying the elements of [array].
+
+		This always creates a copy, even on platforms where the internal
+		representation is Array.
+
+		The elements are not copied and retain their identity, so
+		a[i] == Vector.fromArrayCopy(a).get(i) is true for any valid i.
+
+		If [array] is null, the result is unspecified.
+	**/
+	static public inline function fromArrayCopy<T>(array:Array<T>):Vector<T> {
+		// TODO: Optimize this for flash (and others?)
+		var vec = new Vector<T>(array.length);
+		for (i in 0...array.length)
+			vec.set(i, array[i]);
+		return vec;
+	}
+}

+ 375 - 0
std/python/_std/haxe/io/Bytes.hx

@@ -0,0 +1,375 @@
+/*
+ * 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.io;
+
+class Bytes {
+
+	public var length(default,null) : Int;
+	var b : BytesData;
+
+	function new(length,b) {
+		this.length = length;
+		this.b = b;
+	}
+
+	public inline function get( pos : Int ) : Int {
+		#if neko
+		return untyped __dollar__sget(b,pos);
+		#elseif flash9
+		return b[pos];
+		#elseif php
+		return untyped __call__("ord", b[pos]);
+		#elseif cpp
+		return untyped b[pos];
+		#elseif java
+		return untyped b[pos] & 0xFF;
+		#else
+		return b[pos];
+		#end
+	}
+
+	public inline function set( pos : Int, v : Int ) : Void {
+		#if neko
+		untyped __dollar__sset(b,pos,v);
+		#elseif flash9
+		b[pos] = v;
+		#elseif php
+		b[pos] = untyped __call__("chr", v);
+		#elseif cpp
+		untyped b[pos] = v;
+		#elseif java
+		b[pos] = cast v;
+		#elseif cs
+		b[pos] = cast v;
+		#else
+		b[pos] = v & 0xFF;
+		#end
+	}
+
+	public function blit( pos : Int, src : Bytes, srcpos : Int, len : Int ) : Void {
+		#if !neko
+		if( pos < 0 || srcpos < 0 || len < 0 || pos + len > length || srcpos + len > src.length ) throw Error.OutsideBounds;
+		#end
+		#if neko
+		try untyped __dollar__sblit(b,pos,src.b,srcpos,len) catch( e : Dynamic ) throw Error.OutsideBounds;
+		#elseif php
+		b = untyped __php__("substr($this->b, 0, $pos) . substr($src->b, $srcpos, $len) . substr($this->b, $pos+$len)"); //__call__("substr", b, 0, pos)+__call__("substr", src.b, srcpos, len)+__call__("substr", b, pos+len);
+		#elseif flash9
+		b.position = pos;
+		if( len > 0 ) b.writeBytes(src.b,srcpos,len);
+		#elseif java
+		java.lang.System.arraycopy(src.b, srcpos, b, pos, len);
+		#elseif cs
+		cs.system.Array.Copy(src.b, srcpos, b, pos, len);
+		#else
+		var b1 = b;
+		var b2 = src.b;
+		if( b1 == b2 && pos > srcpos ) {
+			var i = len;
+			while( i > 0 ) {
+				i--;
+				b1[i + pos] = b2[i + srcpos];
+			}
+			return;
+		}
+		for( i in 0...len )
+			b1[i+pos] = b2[i+srcpos];
+		#end
+	}
+	
+	public function fill( pos : Int, len : Int, value : Int ) {
+		#if flash9
+		var v4 = value&0xFF;
+		v4 |= v4<<8;
+		v4 |= v4<<16;
+		b.position = pos;
+		for( i in 0...len>>2 )
+			b.writeUnsignedInt(v4);		
+		pos += len&~3;
+		for( i in 0...len&3 )
+			set(pos++,value);
+		#else
+		for( i in 0...len )
+			set(pos++, value);
+		#end
+	}
+
+	public function sub( pos : Int, len : Int ) : Bytes {
+		#if !neko
+		if( pos < 0 || len < 0 || pos + len > length ) throw Error.OutsideBounds;
+		#end
+		#if neko
+		return try new Bytes(len,untyped __dollar__ssub(b,pos,len)) catch( e : Dynamic ) throw Error.OutsideBounds;
+		#elseif flash9
+		b.position = pos;
+		var b2 = new flash.utils.ByteArray();
+		b.readBytes(b2,0,len);
+		return new Bytes(len,b2);
+		#elseif php
+		return new Bytes(len, untyped __call__("substr", b, pos, len));
+		#elseif java
+		var newarr = new java.NativeArray(len);
+		java.lang.System.arraycopy(b, pos, newarr, 0, len);
+		return new Bytes(len, newarr);
+		#elseif cs
+		var newarr = new cs.NativeArray(len);
+		cs.system.Array.Copy(b, pos, newarr, 0, len);
+		return new Bytes(len, newarr);
+		#else
+		return new Bytes(len,b.slice(pos,pos+len));
+		#end
+	}
+
+	public function compare( other : Bytes ) : Int {
+		#if neko
+		return untyped __dollar__compare(b,other.b);
+		#elseif flash9
+		var len = (length < other.length) ? length : other.length;
+		var b1 = b;
+		var b2 = other.b;
+		b1.position = 0;
+		b2.position = 0;
+		for( i in 0...len>>2 )
+			if( b1.readUnsignedInt() != b2.readUnsignedInt() ) {
+				b1.position -= 4;
+				b2.position -= 4;
+				return b1.readUnsignedInt() - b2.readUnsignedInt();
+			}
+		for( i in 0...len & 3 )
+			if( b1.readUnsignedByte() != b2.readUnsignedByte() )
+				return b1[b1.position-1] - b2[b2.position-1];
+		return length - other.length;
+		#elseif php
+		return untyped __php__("$this->b < $other->b ? -1 : ($this->b == $other->b ? 0 : 1)");
+		//#elseif cs
+		//TODO: memcmp if unsafe flag is on
+		#else
+		var b1 = b;
+		var b2 = other.b;
+		var len = (length < other.length) ? length : other.length;
+		for( i in 0...len )
+			if( b1[i] != b2[i] )
+				#if cpp
+				return untyped b1[i] - untyped b2[i];
+				#else
+				return untyped b1[i] - untyped b2[i];
+				#end
+		return length - other.length;
+		#end
+	}
+
+	public function readString( pos : Int, len : Int ) : String {
+		#if !neko
+		if( pos < 0 || len < 0 || pos + len > length ) throw Error.OutsideBounds;
+		#end
+		#if neko
+		return try new String(untyped __dollar__ssub(b,pos,len)) catch( e : Dynamic ) throw Error.OutsideBounds;
+		#elseif flash9
+		b.position = pos;
+		return b.readUTFBytes(len);
+		#elseif php
+		return untyped __call__("substr", b, pos, len);
+		#elseif cpp
+		var result:String="";
+		untyped __global__.__hxcpp_string_of_bytes(b,result,pos,len);
+		return result;
+		#elseif cs
+		return cs.system.text.Encoding.UTF8.GetString(b, pos, len);
+		#elseif java
+		try
+			return new String(b, pos, len, "UTF-8")
+		catch (e:Dynamic) throw e;
+		#else
+		var s = "";
+		var b = b;
+		inline function fcc(x) return String.fromCharCode(x);
+		var i = pos;
+		var max = pos+len;
+		// utf8-encode
+		while( i < max ) {
+			var c = b[i++];
+			if( c < 0x80 ) {
+				if( c == 0 ) break;
+				s += fcc(c);
+			} else if( c < 0xE0 )
+				s += fcc( ((c & 0x3F) << 6) | (b[i++] & 0x7F) );
+			else if( c < 0xF0 ) {
+				var c2 = b[i++];
+				s += fcc( ((c & 0x1F) << 12) | ((c2 & 0x7F) << 6) | (b[i++] & 0x7F) );
+			} else {
+				var c2 = b[i++];
+				var c3 = b[i++];
+				s += fcc( ((c & 0x0F) << 18) | ((c2 & 0x7F) << 12) | ((c3 << 6) & 0x7F) | (b[i++] & 0x7F) );
+			}
+		}
+		return s;
+		#end
+	}
+
+	public function toString() : String {
+		#if neko
+		return new String(untyped __dollar__ssub(b,0,length));
+		#elseif flash9
+		b.position = 0;
+		return b.readUTFBytes(length);
+		#elseif php
+		return cast b;
+		#elseif cs
+		return cs.system.text.Encoding.UTF8.GetString(b, 0, length);
+		#elseif java
+		try
+		{
+			return new String(b, 0, length, "UTF-8");
+		}
+		catch (e:Dynamic) throw e;
+		#else
+		return readString(0,length);
+		#end
+	}
+
+	public function toHex() : String {
+		var s = new StringBuf();
+		var chars = [];
+		var str = "0123456789abcdef";
+		for( i in 0...str.length )
+			chars.push(str.charCodeAt(i));
+		for( i in 0...length ) {
+			var c = get(i);
+			s.addChar(chars[c >> 4]);
+			s.addChar(chars[c & 15]);
+		}
+		return s.toString();
+	}
+
+	public inline function getData() : BytesData {
+		return b;
+	}
+
+	public static function alloc( length : Int ) : Bytes {
+		#if neko
+		return new Bytes(length,untyped __dollar__smake(length));
+		#elseif flash9
+		var b = new flash.utils.ByteArray();
+		b.length = length;
+		return new Bytes(length,b);
+		#elseif php
+		return new Bytes(length, untyped __call__("str_repeat", __call__("chr", 0), length));
+		#elseif cpp
+		var a = new BytesData();
+		if (length>0) a[length-1] = untyped 0;
+		return new Bytes(length, a);
+		#elseif cs
+		return new Bytes(length, new cs.NativeArray(length));
+		#elseif java
+		return new Bytes(length, new java.NativeArray(length));
+		#else
+		var a = new Array();
+		for( i in 0...length )
+			a.push(0);
+		return new Bytes(length,a);
+		#end
+	}
+
+	public static function ofString( s : String ) : Bytes {
+		#if neko
+		return new Bytes(s.length,untyped __dollar__ssub(s.__s,0,s.length));
+		#elseif flash9
+		var b = new flash.utils.ByteArray();
+		b.writeUTFBytes(s);
+		return new Bytes(b.length,b);
+		#elseif php
+		return new Bytes(untyped __call__("strlen", s), cast s);
+//		return ofData(untyped __call__("new _hx_array", __call__("array_values", __call__("unpack", "C*",  s))));
+		#elseif cpp
+		var a = new BytesData();
+		untyped __global__.__hxcpp_bytes_of_string(a,s);
+		return new Bytes(a.length, a);
+		#elseif cs
+		var b = cs.system.text.Encoding.UTF8.GetBytes(s);
+		return new Bytes(b.Length, b);
+		#elseif java
+		try
+		{
+			var b:BytesData = untyped s.getBytes("UTF-8");
+			return new Bytes(b.length, b);
+		}
+		catch (e:Dynamic) throw e;
+		#else
+		var a = new Array();
+		// utf8-decode
+		for( i in 0...s.length ) {
+			var c : Int = StringTools.fastCodeAt(s,i);
+			if( c <= 0x7F )
+				a.push(c);
+			else if( c <= 0x7FF ) {
+				a.push( 0xC0 | (c >> 6) );
+				a.push( 0x80 | (c & 63) );
+			} else if( c <= 0xFFFF ) {
+				a.push( 0xE0 | (c >> 12) );
+				a.push( 0x80 | ((c >> 6) & 63) );
+				a.push( 0x80 | (c & 63) );
+			} else {
+				a.push( 0xF0 | (c >> 18) );
+				a.push( 0x80 | ((c >> 12) & 63) );
+				a.push( 0x80 | ((c >> 6) & 63) );
+				a.push( 0x80 | (c & 63) );
+			}
+		}
+		return new Bytes(a.length,a);
+		#end
+	}
+
+	public static function ofData( b : BytesData ) {
+		#if flash9
+		return new Bytes(b.length,b);
+		#elseif neko
+		return new Bytes(untyped __dollar__ssize(b),b);
+		#elseif php
+		return new Bytes(untyped __call__("strlen", b), b);
+		#elseif cs
+		return new Bytes(b.Length,b);
+		#else
+		return new Bytes(b.length,b);
+		#end
+	}
+
+	/**
+		Read the most efficiently possible the n-th byte of the data.
+		Behavior when reading outside of the available data is unspecified.
+	**/
+	public inline static function fastGet( b : BytesData, pos : Int ) : Int {
+		#if neko
+		return untyped __dollar__sget(b,pos);
+		#elseif flash9
+		return b[pos];
+		#elseif php
+		return untyped __call__("ord", b[pos]);
+		#elseif cpp
+		return untyped b[pos];
+		#elseif java
+		return untyped b[pos] & 0xFF;
+		#else
+		return b[pos];
+		#end
+	}
+
+}

+ 356 - 0
std/python/_std/haxe/io/Input.hx

@@ -0,0 +1,356 @@
+/*
+ * 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.io;
+
+/**
+	An Input is an abstract reader. See other classes in the [haxe.io] package
+	for several possible implementations.
+**/
+class Input {
+
+	public var bigEndian(default,set) : Bool;
+	#if cs
+	private var helper:BytesData;
+	#elseif java
+	private var helper:java.nio.ByteBuffer;
+	#end
+
+	public function readByte() : Int {
+	#if cpp
+		throw "Not implemented";
+		return 0;
+	#else
+		return throw "Not implemented";
+	#end
+	}
+
+	public function readBytes( s : Bytes, pos : Int, len : Int ) : Int {
+		var k = len;
+		var b = s.getData();
+		if( pos < 0 || len < 0 || pos + len > s.length )
+			throw Error.OutsideBounds;
+		while( k > 0 ) {
+			#if neko
+				untyped __dollar__sset(b,pos,readByte());
+			#elseif php
+				b[pos] = untyped __call__("chr", readByte());
+			#elseif cpp
+				b[pos] = untyped readByte();
+			#else
+				b[pos] = cast readByte();
+			#end
+			pos++;
+			k--;
+		}
+		return len;
+	}
+
+	public function close() {
+	}
+
+	function set_bigEndian(b) {
+		bigEndian = b;
+		return b;
+	}
+
+	/* ------------------ API ------------------ */
+
+	public function readAll( ?bufsize : Int ) : Bytes {
+		if( bufsize == null )
+		#if php
+			bufsize = 8192; // default value for PHP and max under certain circumstances
+		#else
+			bufsize = (1 << 14); // 16 Ko
+		#end
+
+		var buf = Bytes.alloc(bufsize);
+		var total = new haxe.io.BytesBuffer();
+		try {
+			while( true ) {
+				var len = readBytes(buf,0,bufsize);
+				if( len == 0 )
+					throw Error.Blocked;
+				total.addBytes(buf,0,len);
+			}
+		} catch( e : Eof ) {
+		}
+		return total.getBytes();
+	}
+
+	public function readFullBytes( s : Bytes, pos : Int, len : Int ) {
+		while( len > 0 ) {
+			var k = readBytes(s,pos,len);
+			pos += k;
+			len -= k;
+		}
+	}
+
+	public function read( nbytes : Int ) : Bytes {
+		var s = Bytes.alloc(nbytes);
+		var p = 0;
+		while( nbytes > 0 ) {
+			var k = readBytes(s,p,nbytes);
+			if( k == 0 ) throw Error.Blocked;
+			p += k;
+			nbytes -= k;
+		}
+		return s;
+	}
+
+	public function readUntil( end : Int ) : String {
+		var buf = new StringBuf();
+		var last : Int;
+		while( (last = readByte()) != end )
+			buf.addChar( last );
+		return buf.toString();
+	}
+
+	public function readLine() : String {
+		var buf = new StringBuf();
+		var last : Int;
+		var s;
+		try {
+			while( (last = readByte()) != 10 )
+				buf.addChar( last );
+			s = buf.toString();
+			if( s.charCodeAt(s.length-1) == 13 ) s = s.substr(0,-1);
+		} catch( e : Eof ) {
+			s = buf.toString();
+			if( s.length == 0 )
+				#if neko neko.Lib.rethrow #else throw #end (e);
+		}
+		return s;
+	}
+
+	public function readFloat() : Float {
+		#if neko
+			return _float_of_bytes(untyped read(4).b,bigEndian);
+		#elseif cpp
+			return _float_of_bytes(read(4).getData(),bigEndian);
+		#elseif php
+			var a = untyped __call__('unpack', 'f', readString(4));
+			return a[1];
+		#elseif cs
+			if (helper == null) helper = new cs.NativeArray(8);
+
+			var helper = helper;
+			if (bigEndian == !cs.system.BitConverter.IsLittleEndian)
+			{
+				helper[0] = readByte();
+				helper[1] = readByte();
+				helper[2] = readByte();
+				helper[3] = readByte();
+			} else {
+				helper[3] = readByte();
+				helper[2] = readByte();
+				helper[1] = readByte();
+				helper[0] = readByte();
+			}
+
+			return cs.system.BitConverter.ToSingle(helper, 0);
+		#elseif java
+			if (helper == null) helper = java.nio.ByteBuffer.allocateDirect(8);
+			var helper = helper;
+			helper.order(bigEndian ? java.nio.ByteOrder.BIG_ENDIAN : java.nio.ByteOrder.LITTLE_ENDIAN);
+
+			helper.put(0, cast readByte());
+			helper.put(1, cast readByte());
+			helper.put(2, cast readByte());
+			helper.put(3, cast readByte());
+
+			return helper.getFloat(0);
+		#else
+			var bytes = [];
+			bytes.push(cast readByte());
+			bytes.push(cast readByte());
+			bytes.push(cast readByte());
+			bytes.push(cast readByte());
+			if (!bigEndian)
+				bytes.reverse();
+			var sign = 1 - ((bytes[0] >> 7) << 1);
+			var exp = (((bytes[0] << 1) & 0xFF) | (bytes[1] >> 7)) - 127;
+			var sig = ((bytes[1] & 0x7F) << 16) | (bytes[2] << 8) | bytes[3];
+			if (sig == 0 && exp == -127)
+				return 0.0;
+			return sign*(1 + Math.pow(2, -23)*sig) * Math.pow(2, exp);
+		#end
+	}
+
+	public function readDouble() : Float {
+		#if neko
+			return _double_of_bytes(untyped read(8).b,bigEndian);
+		#elseif cpp
+			return _double_of_bytes(read(8).getData(),bigEndian);
+		#elseif php
+			var a = untyped __call__('unpack', 'd', readString(8));
+			return a[1];
+		#elseif (flash || js)
+		var bytes = [];
+		bytes.push(readByte());
+		bytes.push(readByte());
+		bytes.push(readByte());
+		bytes.push(readByte());
+		bytes.push(readByte());
+		bytes.push(readByte());
+		bytes.push(readByte());
+		bytes.push(readByte());
+		if (!bigEndian)
+			bytes.reverse();
+
+		var sign = 1 - ((bytes[0] >> 7) << 1); // sign = bit 0
+		var exp = (((bytes[0] << 4) & 0x7FF) | (bytes[1] >> 4)) - 1023; // exponent = bits 1..11
+		var sig = getDoubleSig(bytes);
+		if (sig == 0 && exp == -1023)
+			return 0.0;
+		return sign * (1.0 + Math.pow(2, -52) * sig) * Math.pow(2, exp);
+		#elseif cs
+		if (helper == null) helper = new cs.NativeArray(8);
+
+		var helper = helper;
+		if (bigEndian == !cs.system.BitConverter.IsLittleEndian)
+		{
+			helper[0] = readByte();
+			helper[1] = readByte();
+			helper[2] = readByte();
+			helper[3] = readByte();
+			helper[4] = readByte();
+			helper[5] = readByte();
+			helper[6] = readByte();
+			helper[7] = readByte();
+		} else {
+			helper[7] = readByte();
+			helper[6] = readByte();
+			helper[5] = readByte();
+			helper[4] = readByte();
+			helper[3] = readByte();
+			helper[2] = readByte();
+			helper[1] = readByte();
+			helper[0] = readByte();
+		}
+
+		return cs.system.BitConverter.ToDouble(helper, 0);
+		#elseif java
+		if (helper == null) helper = java.nio.ByteBuffer.allocateDirect(8);
+		var helper = helper;
+		helper.order(bigEndian ? java.nio.ByteOrder.BIG_ENDIAN : java.nio.ByteOrder.LITTLE_ENDIAN);
+
+		helper.put(0, cast readByte());
+		helper.put(1, cast readByte());
+		helper.put(2, cast readByte());
+		helper.put(3, cast readByte());
+		helper.put(4, cast readByte());
+		helper.put(5, cast readByte());
+		helper.put(6, cast readByte());
+		helper.put(7, cast readByte());
+
+		return helper.getDouble(0);
+		#else
+		return throw "not implemented";
+		#end
+	}
+
+	public function readInt8() {
+		var n = readByte();
+		if( n >= 128 )
+			return n - 256;
+		return n;
+	}
+
+	public function readInt16() {
+		var ch1 = readByte();
+		var ch2 = readByte();
+		var n = bigEndian ? ch2 | (ch1 << 8) : ch1 | (ch2 << 8);
+		if( n & 0x8000 != 0 )
+			return n - 0x10000;
+		return n;
+	}
+
+	public function readUInt16() {
+		var ch1 = readByte();
+		var ch2 = readByte();
+		return bigEndian ? ch2 | (ch1 << 8) : ch1 | (ch2 << 8);
+	}
+
+	public function readInt24() {
+		var ch1 = readByte();
+		var ch2 = readByte();
+		var ch3 = readByte();
+		var n = bigEndian ? ch3 | (ch2 << 8) | (ch1 << 16) : ch1 | (ch2 << 8) | (ch3 << 16);
+		if( n & 0x800000 != 0 )
+			return n - 0x1000000;
+		return n;
+	}
+
+	public function readUInt24() {
+		var ch1 = readByte();
+		var ch2 = readByte();
+		var ch3 = readByte();
+		return bigEndian ? ch3 | (ch2 << 8) | (ch1 << 16) : ch1 | (ch2 << 8) | (ch3 << 16);
+	}
+
+	public function readInt32() {
+		var ch1 = readByte();
+		var ch2 = readByte();
+		var ch3 = readByte();
+		var ch4 = readByte();
+#if (php || python)
+        // php will overflow integers.  Convert them back to signed 32-bit ints.
+        var n = bigEndian ? ch4 | (ch3 << 8) | (ch2 << 16) | (ch1 << 24) : ch1 | (ch2 << 8) | (ch3 << 16) | (ch4 << 24);
+        if (n & 0x80000000 != 0)
+            return ( n | 0x80000000);
+        else return n;
+#else
+		return bigEndian ? ch4 | (ch3 << 8) | (ch2 << 16) | (ch1 << 24) : ch1 | (ch2 << 8) | (ch3 << 16) | (ch4 << 24);
+#end
+	}
+
+	public function readString( len : Int ) : String {
+		var b = Bytes.alloc(len);
+		readFullBytes(b,0,len);
+		#if neko
+		return neko.Lib.stringReference(b);
+		#else
+		return b.toString();
+		#end
+	}
+
+#if neko
+	static var _float_of_bytes = neko.Lib.load("std","float_of_bytes",2);
+	static var _double_of_bytes = neko.Lib.load("std","double_of_bytes",2);
+	static function __init__() untyped {
+		Input.prototype.bigEndian = false;
+	}
+#elseif cpp
+	static var _float_of_bytes = cpp.Lib.load("std","float_of_bytes",2);
+	static var _double_of_bytes = cpp.Lib.load("std","double_of_bytes",2);
+#end
+
+#if (flash || js)
+	function getDoubleSig(bytes:Array<Int>)
+    {
+        return (((bytes[1]&0xF) << 16) | (bytes[2] << 8) | bytes[3] ) * 4294967296. +
+            (bytes[4] >> 7) * 2147483648 +
+            (((bytes[4]&0x7F) << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7]);
+    }
+#end
+
+}

+ 71 - 0
std/python/_std/haxe/rtti/Meta.hx

@@ -0,0 +1,71 @@
+/*
+ * 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.rtti;
+
+/**
+	An api to access classes and enums metadata at runtime.
+**/
+class Meta {
+
+	/**
+		Returns the metadata that were declared for the given type (class or enum)
+	**/
+	public static function getType( t : Dynamic ) : Dynamic<Array<Dynamic>> {
+		#if (python)
+		var meta : Dynamic = Reflect.field(t, "_hx_meta");
+		#elseif (java || cs)
+		var meta : Dynamic = Reflect.field(t, "__meta__");
+		#else
+		var meta : Dynamic = untyped t.__meta__;
+		#end
+		return (meta == null || meta.obj == null) ? {} : meta.obj;
+	}
+
+	/**
+		Returns the metadata that were declared for the given class static fields
+	**/	
+	public static function getStatics( t : Dynamic ) : Dynamic<Dynamic<Array<Dynamic>>> {
+		#if (python)
+		var meta : Dynamic = Reflect.field(t, "_hx_meta");
+		#elseif (java || cs)
+		var meta : Dynamic = Reflect.field(t, "__meta__");
+		#else
+		var meta : Dynamic = untyped t.__meta__;
+		#end
+		return (meta == null || meta.statics == null) ? {} : meta.statics;
+	}
+
+	/**
+		Returns the metadata that were declared for the given class fields or enum constructors
+	**/
+	public static function getFields( t : Dynamic ) : Dynamic<Dynamic<Array<Dynamic>>> {
+		#if (python)
+		var meta : Dynamic = Reflect.field(t, "_hx_meta");
+		#elseif (java || cs)
+		var meta : Dynamic = Reflect.field(t, "__meta__");
+		#else
+		var meta : Dynamic = untyped t.__meta__;
+		#end
+		return (meta == null || meta.fields == null) ? {} : meta.fields;
+	}
+
+}

+ 175 - 0
std/python/internal/ArrayImpl.hx

@@ -0,0 +1,175 @@
+package python.internal;
+
+/*
+ * 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.
+ */
+
+import python.lib.FuncTools;
+import python.lib.Builtin;
+
+@:allow(Array)
+class ArrayImpl {
+
+
+	public static inline function get_length <T>(x:Array<T>):Int return python.lib.Builtin.len(x);
+	
+
+	public static inline function concat<T>( a1:Array<T>, a2 : Array<T>) : Array<T> 
+	{
+		return untyped (untyped a1) + (untyped a2);
+	}
+
+	public static inline function copy<T>(x:Array<T>) : Array<T> 
+	{
+		return Builtin.list(x);
+	}
+
+	@:keep public static inline function iterator<T>(x:Array<T>) : Iterator<T> 
+	{
+		return python.Lib.toHaxeIterator(x.__iter__());
+	}
+
+	//public static function insert( pos : Int, x : T ) : Void;
+
+
+	public static function indexOf<T>(a:Array<T>, x : T, ?fromIndex:Int) : Int {
+		var l = 
+			if (fromIndex == null) 0
+			else if (fromIndex < 0) a.length + fromIndex 
+			else fromIndex;
+		if (l < 0) l = 0;
+		for (i in l...a.length) {
+			if (a[i] == x) return i;
+		}
+		return -1;
+	}
+
+	public static function lastIndexOf<T>(a:Array<T>, x : T, ?fromIndex:Int) : Int {
+		var l = 
+			if (fromIndex == null) a.length 
+			else if (fromIndex < 0) a.length + fromIndex + 1
+			else fromIndex+1;
+		if (l > a.length) l = a.length;
+		while (--l > -1) {
+			if (a[l] == x) return l;
+		}
+		return -1;
+	}
+
+	public static inline function join<T>(x:Array<T>, sep : String ) : String {
+		return untyped sep.join(x.map(Std.string));
+	}
+
+	public static inline function toString<T>(x:Array<T>) : String {
+		return "[" + x.join(",") + "]";
+	}
+
+	public static inline function pop<T>(x:Array<T>) : Null<T> {
+		return if (x.length == 0) null else untyped __field__(x, "pop")();
+	}
+
+	public static inline function push<T>(x:Array<T>, e:T) : Int {
+		untyped x.append(e);
+		
+		return get_length(x);
+	}
+
+	public static inline function unshift<T>(x:Array<T>,e : T) : Void {
+		return x.insert(0,e);
+	}
+
+	@:keep public static function remove<T>(x:Array<T>,e : T) : Bool {
+		try {
+			untyped __field__(x, "remove")(e);
+			return true;
+		} catch (e:Dynamic) {
+			return false;
+		}
+	}
+
+	// public static function reverse<T>(x:Array<T>) : Void;
+
+	public static inline function shift<T>(x:Array<T>) : Null<T> {
+		if (x.length == 0) return null;
+		return untyped __field__(x, "pop")(0);
+	}
+
+	public static inline function slice<T>(x:Array<T>, pos : Int, ?end : Int ) : Array<T> {
+		return untyped __python_array_get__(x, pos, end);
+	}
+
+	public static inline function sort<T>(x:Array<T>, f:T->T->Int) : Void {
+		return untyped __field__(x, "sort")( (untyped __named_arg__)("key", python.lib.FuncTools.cmp_to_key(f)));
+	}
+	/*
+	b = [i0, i1, i3, i0, i2];
+	a = b.splice( -2, 2);
+	b == [i0, i1, i3];
+	trace(a);
+	a == [i0, i2];
+	*/
+	public static inline function splice<T>(x:Array<T>, pos : Int, len : Int ) : Array<T> {
+		if (pos < 0) pos = x.length+pos;
+		if (pos < 0) pos = 0;
+		var res = untyped __python_array_get__(x, pos, pos+len);
+		untyped __python_del__(untyped __python_array_get__(x, pos, pos+len));
+		return res;
+	}
+
+	@:keep public static inline function map<S,T>(x:Array<T>, f : T -> S ) : Array<S> {
+		return Builtin.list(Builtin.map(f,x));
+	}
+
+	@:keep public static inline function filter<T>(x:Array<T>, f : T -> Bool ) : Array<T> {
+		return Builtin.list(Builtin.filter(f, x));
+	}
+
+
+	
+	@:keep private static inline function __get<T>(x:Array<T>, idx:Int):T
+	{
+		var _hx_a = x;
+		if (idx >= _hx_a.length || idx < 0)
+			return null;
+		else 
+			return x[idx];
+	}
+
+	@:keep private static inline function __set<T>(x:Array<T>, idx:Int, v:T):T
+	{
+		var _hx_a = x;
+
+		_hx_a[idx] = v;
+		return v;
+	}
+
+	@:keep private static inline function __unsafe_get<T>(x:Array<T>,idx:Int):T
+	{
+		return x[idx];
+	}
+
+	@:keep private static inline function __unsafe_set<T>(x:Array<T>,idx:Int, val:T):T
+	{
+		x[idx] = val;
+		return val;
+	}
+	
+}

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

@@ -0,0 +1,38 @@
+
+package python.internal;
+
+import haxe.ds.StringMap;
+
+using Lambda;
+
+
+
+class KeywordHandler {
+
+	static var keywords:StringMap<Bool> = [
+		"and" => true,       "del" => true,       "from" => true,      "not" => true,       "while" => true,
+		"as" => true,        "elif" => true,      "global" => true,    "or" => true,        "with" => true,
+		"assert" => true,    "else" => true,      "if" => true,        "pass" => true,      "yield" => true,
+		"break" => true,     "except" => true,    "import" => true,    "print" => true,		"float" => true,
+		"class" => true,     "exec" => true,      "in" => true,        "raise" => true,
+		"continue" => true,  "finally" => true,   "is" => true,        "return" => true,
+		"def" => true,       "for" => true,       "lambda" => true,    "try" => true, "None" => true
+	];
+
+	public static inline function handleKeywords(name:String)
+    {
+        if(keywords.exists(name))
+            return "_hx_" + name;
+        return name;
+    }
+
+    public static function unhandleKeywords(name:String)
+    {
+    	if (name.substr(0,4) == "_hx_") {
+    		var real = name.substr(4);
+    		if (keywords.exists(real)) return real;
+    	}
+    	return name;
+    }
+
+}

+ 41 - 0
std/python/internal/StringImpl.hx

@@ -0,0 +1,41 @@
+
+package python.internal;
+
+import python.lib.Builtin;
+
+class StringImpl {
+
+	public static function split (s:String, d:String) {
+		return if (d == "") Builtin.list(s) else (s:Dynamic).split(d);
+	}
+
+	public static function charCodeAt(s:String, index:Int) {
+		return if (s == null || s.length == 0 || index < 0 || index >= s.length) null else untyped ord(untyped __python_array_get__(s, index));
+	}
+	public static inline function charAt(s:String, index:Int) {
+		return if (index < 0 || index >= s.length) "" else untyped __python_array_get__(s,index);
+	}
+	public static inline function lastIndexOf(s:String, str:String, ?startIndex:Int):Int {
+		if (startIndex == null) {
+			return (untyped s.rfind)(str, 0, s.length);
+		} else {
+
+			var i = (untyped s.rfind)(str, 0, startIndex+1);
+			var startLeft = i == -1 ? Math.max(0,startIndex+1-str.length) : i+1;
+			var check = (untyped s.find)(str, startLeft, s.length);
+			if (check > i && check <= startIndex) {
+				return check;
+			} else {
+				return i;
+			}
+		}
+
+		
+	}
+
+	public static inline function fromCharCode( code : Int ) : String {
+		var c = code;
+		return untyped (''.join)(Builtin.map(Builtin.chr, [c]));
+	}
+	
+}

+ 19 - 0
std/python/lib/ArrayTools.hx

@@ -0,0 +1,19 @@
+
+package python.lib;
+
+class ArrayTools {
+
+	public static inline function extend <T>(a:Array<T>, x:Array<T>):Void {
+		untyped __field__(a, "extend")(x);
+	}
+
+	public static inline function append <T>(a:Array<T>, x:T):Void {
+		untyped __field__(a, "append")(x);
+	}
+
+	public static inline function contains <T>(a:Array<T>, x:T):Bool 
+	{
+		return untyped __python_in__(x,a);
+	}
+
+}

+ 146 - 0
std/python/lib/Builtin.hx

@@ -0,0 +1,146 @@
+
+package python.lib;
+
+
+import python.lib.io.TextIOBase;
+import python.lib.Types;
+
+
+
+
+@:native("_hx_builtin")
+extern class Builtin {
+
+	
+
+	@:overload(function (f:Int):Int {})
+	public static function abs(x:Float):Float;
+	public static function all(i:Iterable<Bool>):Bool;
+	public static function any(i:Iterable<Bool>):Bool;
+
+	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;
+
+
+	
+
+	@:overload(function (obj:Dynamic, f:Tuple<Dynamic>):Bool {})
+	public static function isinstance(obj:Dynamic, cl:Class<Dynamic>):Bool;
+
+	public static function hasattr(obj:Dynamic, attr:String):Bool;
+	public static function getattr(obj:Dynamic, attr:String):Dynamic;
+	
+	@:overload(function (f:Set<Dynamic>):Int {})
+	@:overload(function (f:StringBuf):Int {})
+	@:overload(function (f:Array<Dynamic>):Int {})
+	@:overload(function (f:Dict<Dynamic, Dynamic>):Int {})
+	@:overload(function (f:Bytes):Int {})
+	@:overload(function (f:DictView<Dynamic>):Int {})
+	@:overload(function (f:Tuple<Dynamic>):Int {})
+	public static function len(x:String):Int;
+
+	public static function open(file:String, mode:String, ?encoding:String = null, ?errors : String, ?newline:String, ?closefd:Bool, ?opener:String->Int->FileDescriptor):TextIOBase;
+
+	//public static function divmod():Void;
+	//public static function input():Void;
+	
+	//public static function staticmethod():Void;
+	//public static function enumerate():Void;
+
+	public static function int(x:Dynamic):Int;
+	//public static function ord():Void;
+	public static inline function str(o:Dynamic):String {
+		return untyped __field__(Builtin, "str")(o);
+	}
+	//public static function eval():Void;
+	
+	//public static function pow():Void;
+	//public static function sum():Void;
+	//public static function basestring():Void;
+	//public static function execfile():Void;
+	
+	public static inline function print(o:Dynamic):Void {
+		return untyped __field__(Builtin, "print")(o);
+	}
+	
+	//public static function super():Void;
+	//public static function bin():Void;
+	//public static function file():Void;
+	public static function iter<X>(d:DictView<X>):PyIterator<X>;
+	//public static function property():Void;
+	
+
+
+	@:overload(function <X>():Tuple<X> {})
+	public static function tuple<X>(a:Array<X>):Tuple<X>;
+
+	
+	
+	
+	//public static function range():Void;
+	//public static function type():Void;
+	//public static function bytearray():Void;
+	//public static function float():Void;
+	
+
+	@:overload(function (f:String):Array<String> {})
+	@:overload(function <G>(f:Tuple<G>):Array<G> {})
+	public static function list<T>(i:PyIterable<T>):Array<T>;
+
+	public static function filter<A>(f:A->Bool, i:Choice<Array<A>, PyIterable<A>>):PyIterator<A>;
+	//public static function raw_input():Void;
+	//public static function unichr():Void;
+	
+	//public static function format():Void;
+	//public static function locals():Void;
+	//public static function reduce():Void;
+	//public static function unicode():Void;
+	public static function chr(c:Int):String;
+	//public static function frozenset():Void;
+	//public static function long():Void;
+	//public static function reload():Void;
+	//public static function vars():Void;
+	//public static function classmethod():Void;
+	
+	public static function map<A,B>(fn:A->B, it:PyIterable<A>):PyIterator<B>;
+	//public static function repr():Void;
+	//public static function xrange():Void;
+	//public static function cmp():Void;
+	//public static function globals():Void;
+	@: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 reversed():Void;
+	//public static function zip():Void;
+	//public static function compile():Void;
+	
+	//public static function memoryview():Void;
+	public static function round(f:Float):Int;
+	//public static function __import__():Void;
+	//public static function complex():Void;
+	//public static function hash():Void;
+	@: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;
+	//public static function set():Void;
+	//public static function apply():Void;
+	public static function delattr(o:Dynamic, attr:String):Void;
+	//public static function help():Void;
+	//public static function next():Void;
+	public static function setattr(o:Dynamic, attr:String, val:Dynamic):Void;
+	//public static function buffer():Void;
+	//public static function dict():Void;
+	//public static function hex():Void;
+	//public static function object():Void;
+	//public static function slice():Void;
+	//public static function coerce():Void;
+	//public static function dir():Void;
+	public static function id(x:{}):Int;
+	//public static function oct():Void;
+	//public static function sorted():Void;
+	//public static function intern():Void;
+	static function __init__ ():Void {
+		python.Macros.importAs("builtins", "python.lib.Builtin");
+	}
+
+}

+ 53 - 0
std/python/lib/Codecs.hx

@@ -0,0 +1,53 @@
+
+package python.lib;
+
+import python.lib.io.IOBase;
+import python.lib.io.RawIOBase;
+import python.lib.io.TextIOBase;
+import python.lib.Types.Bytes;
+import python.lib.Types.FileObject;
+import python.lib.Types.Tup2;
+
+extern interface Codec {
+	public function encode(input:Dynamic, ?errors:String = "strict"):Tup2<String, Int>;
+	public function decode(input:Dynamic, ?errors:String = "strict"):Tup2<Bytes, Int>;
+}
+
+extern interface StreamReader extends Codec {
+	public function read(?size:Int, ?chars:Int, ?firstline:Bool):String;
+	public function readline(?size:Int, ?keepsend:Bool = false):String;
+	public function readlines(?sizehint:Int, ?keepsend:Bool = false):Array<String>;
+	public function reset():Void;
+
+}
+
+extern interface StreamWriter extends Codec {
+	public function write(object:Dynamic):Void;
+	public function writelines(list:Array<String>):Void;
+	public function reset():Void;
+}
+
+extern class StreamReaderWriterText implements StreamReader implements StreamWriter  {
+	public function read(?size:Int, ?chars:Int, ?firstline:Bool):String;
+	public function readline(?size:Int, ?keepsend:Bool = false):String;
+	public function readlines(?sizehint:Int, ?keepsend:Bool = false):Array<String>;
+	public function reset():Void;
+
+	public function write(object:Dynamic):Void;
+	public function writelines(list:Array<String>):Void;
+	
+	public function close():Void;
+
+	public function encode(input:Dynamic, ?errors:String = "strict"):Tup2<String, Int>;
+	public function decode(input:Dynamic, ?errors:String = "strict"):Tup2<Bytes, Int>;
+}
+
+
+extern class Codecs {
+
+	public static function open(filename:String, mode:String, ?encoding:String, ?errors:String, ?buffering:Bool):StreamReaderWriterText;
+
+	static function __init__ ():Void {
+		Macros.importAs("codecs", "python.lib.Codecs");
+	}
+}

+ 10 - 0
std/python/lib/FuncTools.hx

@@ -0,0 +1,10 @@
+
+package python.lib;
+
+
+@:native("_hx_functools")
+extern class FuncTools {
+
+	public static function cmp_to_key<A>(f:A->A->Int):Dynamic;
+
+}

+ 18 - 0
std/python/lib/Glob.hx

@@ -0,0 +1,18 @@
+
+package python.lib;
+
+import python.lib.Types;
+
+extern class Glob {
+
+	public static function glob (pathname:String):Array<String>;
+	public static function iglob (pathname:String):PyIterator<String>;
+
+	
+
+	static function __init__ ():Void 
+	{
+		Macros.importAs("glob", "python.lib.Glob");
+	}
+
+}

+ 20 - 0
std/python/lib/Inspect.hx

@@ -0,0 +1,20 @@
+
+package python.lib;
+
+import python.Macros;
+
+extern class Inspect {
+
+	static function __init__ ():Void 
+	{
+		python.Macros.importAs("inspect", "python.lib.Inspect");
+	}
+
+	static function getmembers (value:Dynamic, ?filter:Dynamic->Bool):Bool;
+	static function ismethod (value:Dynamic):Bool;
+	static function isclass (value:Dynamic):Bool;
+
+	static function isfunction(value:Dynamic):Bool;
+
+	
+}

+ 15 - 0
std/python/lib/Json.hx

@@ -0,0 +1,15 @@
+
+package python.lib;
+
+import python.lib.Types.Dict;
+
+extern class Json {
+
+	
+	public static function loads (s:String):Dict<String, Dynamic>;
+
+	static function __init__ ():Void 
+	{
+		python.Macros.importAs("json", "python.lib.Json");
+	}
+}

+ 73 - 0
std/python/lib/Os.hx

@@ -0,0 +1,73 @@
+
+package python.lib;
+
+
+import python.lib.Types;
+
+extern class Stat {
+	public var st_mode:Int;
+	public var st_ino:Int;
+	public var st_dev:Int;
+	public var st_nlink:Int;
+	public var st_uid:Int;
+	public var st_gid:Int;
+	public var st_size:Int;
+	public var st_atime:Int;
+	public var st_mtime:Int;
+	public var st_ctime:Int;
+
+	@:optional public var st_blocks:Int;
+	@:optional public var st_blksize:Int;
+	@:optional public var st_rdev:Int;
+	@:optional public var st_flags:Int;
+
+	@:optional public var st_gen:Int;
+	@:optional public var st_birthtime:Int;
+
+	@:optional public var st_rsize:Int;
+	@:optional public var st_creator:Int;
+	@:optional public var st_type:Int;
+}
+
+extern class Os {
+
+	public static var environ : Dict<String, String>;
+
+	public static function chdir (path:String):Void;
+
+	public static function unlink (path:String):Void;
+	public static function remove (path:String):Void;
+
+	public static function getcwdb():Bytes;
+
+	public static function removedirs (path:String):Void;
+
+	public static function rename (src:String, dest:String):Void;
+
+	public static function renames (oldName:String, newName:String):Void;
+
+	public static function rmdir (path:String):Void;
+
+	public static function stat (path:String):Stat;
+
+	public static function fchdir (fd:FileDescriptor):Void;
+
+	public static function listdir (path:String = "."):Array<String>;
+
+	public static function walk (top:String, topdown:Bool = true, onerror:OSError->Void = null, followlinks:Bool = false):Tup3<String, Array<String>, Array<String>>;
+
+	//public static inline function environ ():Dict<String, String>;
+
+	public static var sep(default, null) : String;
+	public static var pathsep(default, null):String;
+	
+	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;
+
+	static function __init__ ():Void 
+	{
+		python.Macros.importAs("os", "python.lib.Os");
+	}
+
+}

+ 15 - 0
std/python/lib/PPrint.hx

@@ -0,0 +1,15 @@
+
+package python.lib;
+
+extern class PPrint {
+
+	
+	public static function pprint (x:Dynamic):Void;
+
+	public static function pformat(object:Dynamic, indent:Int=1, width:Int=80, depth:Int=null):String;
+
+	static function __init__ ():Void {
+		python.Macros.importAs("pprint", "python.lib.PPrint");
+	}
+
+}

+ 14 - 0
std/python/lib/Random.hx

@@ -0,0 +1,14 @@
+
+package python.lib;
+
+
+
+extern class Random {
+
+	public static function random ():Float;
+
+	static function __init__ ():Void {
+		Macros.importAs("random", "python.lib.Random");
+	}
+
+}

+ 179 - 0
std/python/lib/Re.hx

@@ -0,0 +1,179 @@
+
+package python.lib;
+
+import python.lib.Types;
+
+
+
+typedef TODO = Dynamic;
+
+typedef Pattern = Choice<String, Regex>;
+
+typedef Repl = Choice<String, MatchObject->String>;
+
+
+
+
+extern class MatchObject 
+{
+	
+	public var pos(default, null):Int;	
+	public var endpos(default, null):Int;
+	public var lastindex(default, null):Int;
+	public var lastgroup(default, null):Int;
+	public var re(default, null):Regex;
+	public var string(default, null):String;
+
+	public function expand(template:String):String;
+	public function group(?i:Int = 0):String;
+	public function groups(defaultVal:String = null):Tuple<String>;
+	public function groupdict(defaultVal:Dict<String, String> = null):Dict<String, String>;
+
+	public function start (?i:Int = 0):Int;
+	public function end (?i:Int = 0):Int;
+
+	public function span (?i:Int):Tup2<Int, Int>;
+
+
+	public inline function groupById(s:String):String {
+		return group(untyped s);
+	}
+
+	public inline function startById(s:String):Int {
+		return start(untyped s);	
+	}
+
+	public inline function endById(s:String):Int {
+		return end(untyped s);	
+	}
+
+}
+
+private class RegexHelper {
+	public static function findallDynamic(r:Regex, string:String, ?pos:Int, ?endpos:Int):Array<Dynamic>
+	{
+		if (endpos == null) {
+			if (pos == null) {
+				return untyped __field__(r, "findall")(string);
+			} else {
+				return untyped __field__(r, "findall")(string, pos);
+			}
+		} else {
+			return untyped __field__(r, "findall")(string, pos, endpos);
+		}
+		
+	}	
+}
+
+extern class Regex 
+{
+	public function search(string:String, pos:Int = 0, ?endpos:Int):Null<MatchObject>;
+	public function match(string:String, pos:Int = 0, ?endpos:Int):Null<MatchObject>;
+	
+	public function split(string:String, maxsplit:Int=0):Array<String>;
+
+	public inline function findallString(string:String, ?pos:Int, ?endpos:Int):Array<String>
+	{
+		return cast this.findallDynamic(string, pos, endpos);
+	}
+
+
+	public inline function findallDynamic(string:String, ?pos:Int, ?endpos:Int):Array<Dynamic>
+	{
+		return RegexHelper.findallDynamic(this, string, pos, endpos);
+	}
+
+	public inline function findallTuple(string:String, ?pos:Int, ?endpos:Int):Array<Tuple<String>> {
+
+		return cast this.findallDynamic(string, pos, endpos);
+	}
+
+	public inline function findallArray(string:String, ?pos:Int, ?endpos:Int):Array<Array<String>>
+	{
+		return findallTuple(string, pos, endpos).map(function (t) return t.toArray());
+	}
+
+	public function finditer(string:String, ?pos:Int, ?endpos:Int):PyIterator<MatchObject>;
+	
+	public function sub(repl:Repl, string:String, count:Int=0):String;
+	public function subn(repl:Repl, string:String, count:Int=0):String;
+	
+	public var flags(default, null):Int;
+	public var groups(default, null):Int;
+	public var groupindex(default, null):Dict<String, Int>;
+	public var pattern(default, null):String;
+}
+
+
+
+extern class Re 
+{
+
+	public static var A:Int;
+	public static var ASCII:Int;
+	public static var DEBUG:Int;
+	public static var I:Int;
+	public static var IGNORECASE:Int;
+
+	public static var L:Int;
+	public static var LOCALE:Int;
+
+	public static var M:Int;
+	public static var MULTILINE:Int;
+
+	public static var S:Int;
+	public static var DOTALL:Int;
+
+	public static var X:Int;
+	public static var VERBOSE:Int;
+
+	public static var U:Int;
+	public static var UNICODE:Int;
+
+	
+	
+	public static function compile (pattern:String, ?flags:Int = 0):Regex;
+
+	public static function match (pattern:Pattern, string:String, flags:Int = 0):Null<MatchObject>;
+
+	public static function search (pattern:Pattern, string:String, flags:Int = 0):Null<MatchObject>;	
+
+	public static function split(pattern:Pattern, string:String, 	   maxsplit:Int=0, flags:Int=0):Array<String>;
+
+	public static inline function findallDynamic(pattern:Pattern, string:String,    flags:Int=0):Array<Dynamic>
+	{
+		return untyped __field__(pattern, "findall")(string, flags);
+	}
+	
+
+	public static inline function findallString(pattern:Pattern, string:String,    flags:Int=0):Array<String>
+	{
+		return untyped __field__(pattern, "findall")(string, flags);
+	}
+
+	public static inline function findallTuple(pattern:Pattern, string:String,    flags:Int=0):Array<Tuple<String>>
+	{
+		return untyped __field__(pattern, "findall")(string, flags);
+	}
+
+	public static inline function findallArray(pattern:Pattern, string:String,    flags:Int=0):Array<Array<String>>
+	{
+		return findallTuple(pattern, string,flags).map(function (t) return t.toArray());
+	}
+
+	public static function finditer(pattern:Pattern, string:String,   flags:Int=0):PyIterator<MatchObject>;
+
+	
+	@:overload(function (pattern:Pattern, repl:String, string:String,  ?count:Int=0, ?flags:Int=0):String {})
+	public static function sub(pattern:Pattern, repl:MatchObject->String, string:String,  ?count:Int=0, ?flags:Int=0):String;
+
+	public static function subn(pattern:Pattern, repl:Repl, string:String, count:Int=0, flags:Int=0):String;
+
+	public static function escape(string:String):TODO;
+
+	public static function purge():Void;
+
+	static function __init__ ():Void {
+		python.Macros.importAs("re", "python.lib.Re");
+	}
+}

+ 13 - 0
std/python/lib/ShUtil.hx

@@ -0,0 +1,13 @@
+
+package python.lib;
+
+import python.lib.Types.BaseException;
+
+extern class ShUtil {
+
+	public static function rmtree(path:String, ?ignore_errors:Bool=false, ?onerror:BaseException->Void):Void;
+
+	static function __init__ ():Void {
+		Macros.importAs("shutil", "python.lib.ShUtil");
+	}
+}

+ 32 - 0
std/python/lib/StringTools.hx

@@ -0,0 +1,32 @@
+
+package python.lib;
+
+import python.lib.Types.Bytes;
+import python.lib.Types.Tup3;
+
+class StringTools {
+
+	public static function format (s:String, args:Array<Dynamic>):String 
+	{
+		return untyped __field__(s, "format")(untyped __python_varargs__(args));
+	}
+
+	public static function encode(s:String, encoding:String="utf-8", errors:String="strict"):Bytes {
+		return untyped __field__(s, "encode")(encoding, errors);
+	}
+
+	public static inline function contains(s:String, e:String):Bool {
+		return untyped __python_in__(e,s);
+	}
+
+	public static inline function strip(s:String, ?chars:String):String 
+	{
+		return untyped __field__(s, "strip")(chars);
+	}
+
+	public static inline function rpartition (s:String, sep:String):Tup3<String, String, String>
+	{
+		return untyped __field__(s, "rpartition")(sep);	
+	}
+
+}

+ 34 - 0
std/python/lib/Subprocess.hx

@@ -0,0 +1,34 @@
+
+package python.lib;
+
+extern class StartupInfo {
+	public var dwFlags : Int;
+
+	public var wShowWindow:Int;
+
+}
+
+extern class Subprocess {
+
+	public static function STARTUPINFO():StartupInfo;
+
+	public static var STD_INPUT_HANDLE:Int;
+	public static var STD_OUTPUT_HANDLE:Int;
+	public static var STD_ERROR_HANDLE:Int;
+	public static var SW_HIDE:Int;
+	public static var STARTF_USESTDHANDLES:Int;
+	public static var STARTF_USESHOWWINDOW:Int;
+
+	//public static var CREATE_NEW_CONSOLE;
+
+	//public static var CREATE_NEW_PROCESS_GROUP;
+
+	public static var PIPE:Dynamic;
+
+	public static var STDOUT:Dynamic;	
+
+	static function __init__ ():Void 
+	{
+		python.Macros.importAs("subprocess", "python.lib.Subprocess");
+	}
+}

+ 32 - 0
std/python/lib/Sys.hx

@@ -0,0 +1,32 @@
+
+package python.lib;
+
+import python.lib.io.RawIOBase;
+import python.lib.io.TextIOBase;
+import python.lib.Types;
+
+
+
+
+
+extern class Sys {
+
+	public static function exit (x:Int):Void;
+
+	public static function getfilesystemencoding():String;
+
+	public static var version:String;
+
+	public static var stdout(default, never):TextIOBase;
+	
+
+	public static function getsizeof (t:Dynamic):Int;
+
+	public static var maxsize:Int;
+	
+	static function __init__ ():Void 
+	{
+		python.Macros.importAs("sys", "python.lib.Sys");
+	}
+	
+}

+ 11 - 0
std/python/lib/Tempfile.hx

@@ -0,0 +1,11 @@
+
+package python.lib;
+
+extern class Tempfile {
+
+	public static function gettempdir():String;
+	static function __init__ ():Void {
+		Macros.importAs("tempfile", "python.lib.Tempfile");
+	}
+
+}

+ 17 - 0
std/python/lib/ThreadLowLevel.hx

@@ -0,0 +1,17 @@
+
+package python.lib;
+
+import python.lib.Types.Tuple;
+
+private typedef TODO = Dynamic;
+
+extern class ThreadLowLevel {
+	
+	public static function start_new_thread(f:Void->Void, args:Tuple<Dynamic>):TODO;
+
+	static function __init__ ():Void 
+	{
+		python.Macros.importAs("_thread", "python.lib.ThreadLowLevel");
+	}
+
+}

+ 12 - 0
std/python/lib/Time.hx

@@ -0,0 +1,12 @@
+
+package python.lib;
+
+extern class Time {
+
+	public static function time ():Int;
+	public static function sleep (t:Float):Void;
+	static function __init__ ():Void 
+	{
+		python.Macros.importAs("time", "python.lib.Time");
+	}
+}

+ 667 - 0
std/python/lib/Types.hx

@@ -0,0 +1,667 @@
+
+package python.lib;
+
+
+import python.Lib;
+import python.lib.Builtin;
+import python.lib.io.IOBase;
+
+abstract Choice <A,B>(Dynamic) {
+	@:from public static inline function fromA <A,B>(x:A):Choice<A,B> return cast x;
+	@:from public static inline function fromB <A,B>(x:B):Choice<A,B> return cast x;
+}
+
+abstract KwArgs (Dict<String, Dynamic>) to Dict<String, Dynamic> from Dict<String, Dynamic> 
+{
+	
+	public function get <V>(key:String, def:V):V 
+	{
+		return this.get(key, def);
+	}
+}
+
+abstract VarArgs (Array<Dynamic>) to Array<Dynamic> from Array<Dynamic> 
+{
+	
+}
+
+
+extern class ByteArray {
+	public function decode(encoding:String="utf-8", errors:String="strict"):String;
+}
+
+extern class Bytes {
+	public var length(get, null):Int;
+	public inline function get_length ():Int return Builtin.len(this);
+	public function decode(encoding:String="utf-8", errors:String="strict"):String;
+
+	static function __init__ ():Void 
+	{
+		Macros.importFromAs("builtins", "bytes", "python.lib.Bytes");
+	}
+
+
+}
+
+typedef Variant<A,B> = Dynamic; 
+typedef Variant3<A,B,C> = Dynamic;
+typedef Variant4<A,B,C,D> = Dynamic;
+
+abstract PyIterator <T>(NativeIterator<T>) to NativeIterator<T> to PyIterable<T> {
+	public inline function new (p:NativeIterator<T>) this = p;
+	@:to public static inline function toHaxeIterator <T>(p:NativeIterator<T>):HaxeIterator<T> return python.Lib.toHaxeIterator(p);
+	@:to public static inline function toPyIterable <T>(p:NativeIterator<T>):PyIterable<T> return p;
+	public function getNativeIterator <T>():NativeIterator<T> return this;
+}
+
+abstract PyIterable <T>(NativeIterable<T>) to NativeIterable<T> from NativeIterable<T> {
+	@:to public static inline function toHaxeIterable <T>(p:NativeIterable<T>):HaxeIterable<T> return python.Lib.toHaxeIterable(p);
+	
+	//@:from public static inline function fromArray <T>(p:Array<T>):PyIterable<T> return cast p;
+
+	public inline function iterator <T>() return IterHelper.iterableToIterator(this);
+	public function getNativeIterable <T>():NativeIterable<T> return this;
+	public function getNativeIterator <T>():NativeIterator<T> return this.__iter__();
+	
+}
+
+class IterHelper {
+	public static inline function iterableToIterator <T>(it:PyIterable<T>):Iterator<T>
+	{
+		return it.toHaxeIterable().iterator();
+	}
+}
+
+typedef NativeIterator<T> = {
+	function __next__ ():T;
+	function __iter__ ():PyIterator<T>;
+}
+
+typedef NativeIterable<T> = {
+	function __iter__():PyIterator<T>;
+	
+}
+
+typedef List<T> = Array<T>;
+
+
+
+typedef Hashable = {
+	public function __hash__():Int;
+}
+
+typedef Equal = {
+	public function __eq__(other:Dynamic):Int;
+}
+
+typedef Comparable = {
+	
+	public function __cmp__(other:Dynamic):Int;
+}
+
+typedef FileObject = IOBase;
+
+extern class FileDescriptor {
+
+}
+
+
+//typedef DictKey<T> = {
+//	function __hash__():Int;
+//	function __eq__(other:Dynamic):Int;
+//	function __cmp__(other:Dynamic):Int;
+//}
+
+//@:native("set")
+extern class Set <T> 
+{
+
+	@:overload(function (?array:Array<T>):Void {})
+	public function new (?iterable:python.lib.Types.PyIterable<T>):Void;
+
+	public inline function length ():Int 
+	{
+		return python.lib.Builtin.len(this);
+	}
+
+
+	public inline function minus (other:Set<T>):Set<T>
+	{
+		return untyped __python_binop__(this, "-", other);
+	}
+	public inline function plus (other:Set<T>):Set<T>
+	{
+		return untyped __python_binop__(this, "+", other);
+	}
+
+	static function __init__ ():Void 
+	{
+		Macros.importFromAs("builtins", "set", "python.lib.Set");
+	}
+
+	function __iter__ ():PyIterator<T>;
+
+	public inline function iterator ():Iterator<T>
+	{
+		return __iter__();
+	}
+}
+
+extern class DictView<T> {
+	public inline function iter ():PyIterator<T> 
+	{
+		return Builtin.iter(this);
+	}
+	public inline function length ():Int 
+	{
+		return Builtin.len(this);
+	}
+}
+
+
+//@:native("dict")
+extern class Dict <K, V>
+{
+	public function new ():Void;
+
+	public inline function length ():Int 
+	{
+		return python.lib.Builtin.len(this);
+	}
+
+	public inline function hasKey (k:K):Bool {
+		return DictImpl.hasKey(this,k);
+	}
+
+	public function clear ():Void;
+	public function copy ():Dict<K,V>;
+	public function get (key:K, def:V):V;
+
+	public function update (d:Dict<K,V>):Void;
+
+	public function keys ():DictView<K>;
+	public function values ():DictView<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 {
+		DictImpl.set(this, key, val);	
+	}
+	
+	public inline function remove (key:K):Void 
+	{
+		DictImpl.remove(this, key);
+	}
+
+	public inline function iterator ():Iterator<V>
+	{
+		return values().iter();
+	}
+
+	static function __init__ ():Void 
+	{
+		Macros.importFromAs("builtins", "dict", "python.lib.Dict");
+	}
+
+}
+
+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) {
+		return untyped __python_in__(key, d);
+	}
+
+	public static inline function remove <X>(d:Dict<X, Dynamic>, key:X) {
+		untyped __python_del__(untyped __python_array_get__(d, key));
+	}
+
+	public static inline function set <K,V>(d:Dict<K, V>, key:K, val:V) {
+		untyped __python_array_set__(d, key, val);
+	}
+}
+
+
+
+extern class Tuple<X> implements ArrayAccess<X> {
+
+	public static inline function empty<X>():Tuple<X> {
+		return Builtin.tuple();
+	}
+
+	
+
+	public static inline function fromArray<X>(a:Array<X>):Tuple<X> {
+		return Builtin.tuple(a);
+	}
+
+	public var length(get_length, null):Int;
+
+	inline function get_length():Int {
+		return Builtin.len(this);
+	}
+
+	public inline function at (i:Int):X {
+		return untyped __python_array_get__(this, i);
+	}
+
+	public inline function toArray ():Array<X>
+	{
+		return Builtin.list(this);
+	}
+
+}
+
+extern class Tup2 <A,B> extends Tuple<Dynamic>
+{
+	public static inline function create <A,B>(a:A, b:B):Tup2<A,B> return untyped __python_tuple__(a,b);
+	public var _1(get, null):A;
+	public inline function get__1():A return untyped __python_array_get__(this, 0);
+	public var _2(get, null):B;
+	public inline function get__2():B return untyped __python_array_get__(this, 1);
+}
+
+extern class Tup3 <A,B,C> extends Tuple<Dynamic>
+{
+	public static inline function create <A,B,C>(a:A, b:B,c:C):Tup3<A,B,C> return untyped __python_tuple__(a,b,c);
+	public var _1(get, null):A;
+	public inline function get__1():A return untyped __python_array_get__(this, 0);
+	public var _2(get, null):B;
+	public inline function get__2():B return untyped __python_array_get__(this, 1);
+	public var _3(get, null):C;
+	public inline function get__3():C return untyped __python_array_get__(this, 2);
+}
+
+extern class Tup4 <A,B,C,D> extends Tuple<Dynamic>
+{
+	public static inline function create <A,B,C,D>(a:A, b:B,c:C,d:D):Tup4<A,B,C,D> return untyped __python_tuple__(a,b,c,d);
+	public var _1(get, null):A;
+	public inline function get__1():A return untyped __python_array_get__(this, 0);
+	public var _2(get, null):B;
+	public inline function get__2():B return untyped __python_array_get__(this, 1);
+	public var _3(get, null):C;
+	public inline function get__3():C return untyped __python_array_get__(this, 2);
+	public var _4(get, null):D;
+	public inline function get__4():D return untyped __python_array_get__(this, 3);
+}
+
+extern class Tup5 <A,B,C,D,E> extends Tuple<Dynamic>
+{
+	public static inline function create <A,B,C,D,E>(a:A, b:B,c:C,d:D,e:E):Tup5<A,B,C,D,E> return untyped __python_tuple__(a,b,c,d,e);
+	public var _1(get, null):A;
+	public inline function get__1():A return untyped __python_array_get__(this, 0);
+	public var _2(get, null):B;
+	public inline function get__2():B return untyped __python_array_get__(this, 1);
+	public var _3(get, null):C;
+	public inline function get__3():C return untyped __python_array_get__(this, 2);
+	public var _4(get, null):D;
+	public inline function get__4():D return untyped __python_array_get__(this, 3);
+	public var _5(get, null):E;
+	public inline function get__5():E return untyped __python_array_get__(this, 4);
+}
+
+
+@:native("BaseException")
+extern class BaseException 
+{
+	public function new (msg:String):Void;
+}
+
+
+
+@:native("BufferError")
+extern class BufferError extends BaseException
+{
+	
+}
+
+@:native("GeneratorExit")
+extern class GeneratorExit extends BaseException
+{
+	
+}
+
+@:native("KeyboardInterrupt")
+extern class KeyboardInterrupt extends BaseException
+{
+	
+}
+
+@:native("Exception")
+extern class Exception extends BaseException 
+{
+
+}
+
+@:native("SyntaxError")
+extern class SyntaxError extends Exception
+{
+	
+}
+
+@:native("StopIteration")
+extern class StopIteration extends Exception
+{
+	public function new (?message:String);
+}
+
+@:native("RuntimeError")
+extern class RuntimeError extends Exception
+{
+	
+}
+
+@:native("NotImplementedError")
+extern class NotImplementedError extends RuntimeError
+{
+	
+}
+
+@:native("IndentationError")
+extern class IndentationError extends SyntaxError
+{
+	
+}
+
+@:native("EnvironmentError")
+extern class EnvironmentError extends Exception
+{
+	
+}
+
+@:native("OSError")
+extern class OSError extends EnvironmentError
+{
+	
+}
+
+@:native("BlockingIOError")
+extern class BlockingIOError extends OSError
+{
+	
+}
+
+@:native("ChildProcessError")
+extern class ChildProcessError extends OSError
+{
+	
+}
+
+@:native("ConnectionError")
+extern class ConnectionError extends OSError
+{
+	
+}
+
+@:native("BrokenPipeError")
+extern class BrokenPipeError extends ConnectionError
+{
+	
+}
+
+@:native("ConnectionAbortedError")
+extern class ConnectionAbortedError extends ConnectionError 
+{
+
+}
+@:native("ConnectionRefusedError")
+extern class ConnectionRefusedError extends ConnectionError 
+{
+
+}
+@:native("ConnectionResetError")
+extern class ConnectionResetError extends ConnectionError 
+{
+
+}
+
+@:native("FileExistsError")
+extern class FileExistsError extends OSError
+{
+
+}
+@:native("FileNotFoundError")
+extern class FileNotFoundError extends OSError
+{
+
+}
+@:native("InterruptedError")
+extern class InterruptedError extends OSError
+{
+
+}
+@:native("IsADirectoryError")
+extern class IsADirectoryError extends OSError
+{
+
+}
+@:native("NotADirectoryError")
+extern class NotADirectoryError extends OSError
+{
+
+}
+@:native("PermissionError")
+extern class PermissionError extends OSError
+{
+
+}
+@:native("ProcessLookupError")
+extern class ProcessLookupError extends OSError
+{
+
+}
+@:native("TimeoutError")
+extern class TimeoutError extends OSError
+{
+
+}
+
+
+@:native("NameError")
+extern class NameError extends Exception
+{
+	
+}
+
+@:native("UnboundLocalError")
+extern class UnboundLocalError extends NameError
+{
+	
+}
+
+@:native("MemoryError")
+extern class MemoryError extends Exception
+{
+	
+}
+
+@:native("AssertionError")
+extern class AssertionError extends Exception
+{
+	
+}
+
+@:native("AttributeError")
+extern class AttributeError extends Exception
+{
+	
+}
+
+@:native("EOFError")
+extern class EOFError extends Exception
+{
+	
+}
+
+@:native("ArithmeticError")
+extern class ArithmeticError extends Exception
+{
+	
+}
+
+
+
+@:native("FloatingPointError")
+extern class FloatingPointError extends ArithmeticError
+{
+	
+}
+
+@:native("OverflowError")
+extern class OverflowError extends ArithmeticError
+{
+	
+}
+
+
+@:native("ZeroDivisionError")
+extern class ZeroDivisionError extends ArithmeticError
+{
+	
+}
+
+
+
+@:native("ImportError")
+extern class ImportError extends Exception
+{
+	
+}
+
+@:native("LookupError")
+extern class LookupError extends Exception
+{
+	
+}
+
+@:native("IndexError")
+extern class IndexError extends LookupError
+{
+	
+}
+
+@:native("KeyError")
+extern class KeyError extends LookupError
+{
+	
+}
+
+
+
+
+
+
+
+@:native("IOError")
+extern class IOError extends EnvironmentError
+{
+	
+}
+
+@:native("VMSError")
+extern class VMSError extends OSError
+{
+	
+}
+
+@:native("WindowsError")
+extern class WindowsError extends OSError
+{
+	
+}
+
+
+
+
+
+
+@:native("ValueError")
+extern class ValueError extends Exception
+{
+	
+}
+
+@:native("UnicodeError")
+extern class UnicodeError extends ValueError
+{
+
+}
+@:native("UnicodeDecodeError")
+extern class UnicodeDecodeError extends UnicodeError
+{
+
+}
+@:native("UnicodeEncodeError")
+extern class UnicodeEncodeError extends UnicodeError
+{
+
+}
+@:native("UnicodeTranslateError")
+extern class UnicodeTranslateError extends UnicodeError
+{
+
+}
+
+@:native("Warning")
+extern class Warning extends Exception
+{
+
+}
+
+@:native("DeprecationWarning")
+extern class DeprecationWarning extends Warning 
+{
+
+}
+@:native("PendingDeprecationWarning")
+extern class PendingDeprecationWarning extends Warning 
+{
+
+}
+@:native("RuntimeWarning")
+extern class RuntimeWarning extends Warning 
+{
+
+}
+@:native("SyntaxWarning")
+extern class SyntaxWarning extends Warning 
+{
+
+}
+@:native("UserWarning")
+extern class UserWarning extends Warning 
+{
+
+}
+@:native("FutureWarning")
+extern class FutureWarning extends Warning 
+{
+
+}
+@:native("ImportWarning")
+extern class ImportWarning extends Warning 
+{
+
+}
+@:native("UnicodeWarning")
+extern class UnicodeWarning extends Warning 
+{
+
+}
+@:native("BytesWarning")
+extern class BytesWarning extends Warning 
+{
+
+}
+@:native("ResourceWarning")
+extern class ResourceWarning extends Warning 
+{
+
+}

+ 45 - 0
std/python/lib/datetime/DateTime.hx

@@ -0,0 +1,45 @@
+
+package python.lib.datetime;
+
+
+extern class DateTime {
+
+	public function new (year:Int, month:Int, day:Int, hour:Int=0, minute:Int=0, second:Int=0, microsecond:Int=0, tzinfo:TzInfo=null);
+
+	public static var min : DateTime;
+	public static var max : DateTime;
+	public static var resolution : TimeDelta;
+
+	public var year : Int;
+	public var month : Int;
+	public var day : Int;
+	public var hour : Int;
+	public var minute : Int;
+	public var second : Int;
+	public var microsecond : Int;
+	public var tzinfo : TzInfo;
+
+	
+
+	public static function today ():DateTime;
+	public static function now (?tzinfo:TzInfo):DateTime;
+	public static function utcnow ():DateTime;
+	public static function fromtimestamp (timestamp:Float):DateTime;
+	public static function utcfromtimestamp (timestamp:Int):DateTime;
+	public static function fromordinal (ordinal:Int):DateTime;
+
+	public function strftime (format:String):String;
+	public function replace (?year:Int = 1970, ?month:Int = 1, ?day:Int = 1, ?hour:Int = 0, ?minute:Int = 0, ?second:Int, ?microsecond:Int, ?tzinfo:TzInfo):DateTime;
+	/* 0-6 */
+	public function weekday():Int;
+	/* 1-7 */
+	public function isoweekday():Int;
+
+	// python 3.3
+	public function timestamp ():Float;
+
+	static function __init__ ():Void 
+	{
+		python.Macros.importFromAs("datetime", "datetime", "python.lib.datetime.DateTime");
+	}
+}

+ 21 - 0
std/python/lib/datetime/TimeDelta.hx

@@ -0,0 +1,21 @@
+
+package python.lib.datetime;
+
+extern class TimeDelta {
+
+	public static var min : TimeDelta;
+	public static var max : TimeDelta;
+	public static var resolution : TimeDelta;
+
+	
+	var days : Int;
+	
+	var seconds : Int;
+	var microseconds : Int;
+	
+
+	static function __init__ ():Void 
+	{
+		python.Macros.importFromAs("datetime", "timedelta", "python.lib.datetime.TimeDelta");
+	}
+}

+ 11 - 0
std/python/lib/datetime/Timezone.hx

@@ -0,0 +1,11 @@
+
+package python.lib.datetime;
+
+extern class Timezone extends TzInfo {
+
+	public static var utc(default, never):TzInfo;
+	static function __init__ ():Void 
+	{
+		python.Macros.importFromAs("datetime", "timezone", "python.lib.datetime.Timezone");
+	}
+}

+ 11 - 0
std/python/lib/datetime/TzInfo.hx

@@ -0,0 +1,11 @@
+
+package python.lib.datetime;
+
+extern class TzInfo {
+
+	
+	static function __init__ ():Void 
+	{
+		python.Macros.importFromAs("datetime", "tzinfo", "python.lib.datetime.TzInfo");
+	}
+}

+ 8 - 0
std/python/lib/io/BufferedRWPair.hx

@@ -0,0 +1,8 @@
+
+package python.lib.io;
+
+extern class BufferedRWPair {
+
+	
+
+}

+ 8 - 0
std/python/lib/io/BufferedRandom.hx

@@ -0,0 +1,8 @@
+
+package python.lib.io;
+
+extern class BufferedRandom {
+
+	
+
+}

+ 8 - 0
std/python/lib/io/BufferedWriter.hx

@@ -0,0 +1,8 @@
+
+package python.lib.io;
+
+extern class BufferedWriter {
+
+	
+
+}

+ 8 - 0
std/python/lib/io/BytesIO.hx

@@ -0,0 +1,8 @@
+
+package python.lib.io;
+
+extern class BytesIO {
+
+	
+
+}

+ 10 - 0
std/python/lib/io/FileIO.hx

@@ -0,0 +1,10 @@
+
+package python.lib.io;
+
+import python.lib.io.RawIOBase;
+
+extern class FileIO extends RawIOBase{
+
+	
+
+}

+ 16 - 0
std/python/lib/io/IOBase.hx

@@ -0,0 +1,16 @@
+
+package python.lib.io;
+
+extern class IOBase {
+
+	public function close():Void;
+	public function flush():Void;
+	public function readline(limit:Int = -1):String;
+	public function readable():Bool;
+	public var closed(default, null):Bool;
+	public function readlines(hint:Int=-1):Array<String>;
+	public function tell():Int;
+	public function writable():Bool;
+	public function seekable():Bool;
+
+}

+ 14 - 0
std/python/lib/io/RawIOBase.hx

@@ -0,0 +1,14 @@
+
+package python.lib.io;
+
+import python.lib.io.FileIO;
+import python.lib.io.IOBase;
+import python.lib.Types.Bytes;
+
+extern class RawIOBase extends IOBase{
+
+	public function readall():Bytes;
+	public function read(n:Int=-1):Null<Bytes>;
+	public function write(b:Bytes):Null<Int>;
+
+}

+ 17 - 0
std/python/lib/io/StringIO.hx

@@ -0,0 +1,17 @@
+
+package python.lib.io;
+
+import python.lib.io.TextIOBase;
+import python.Macros;
+
+extern class StringIO extends TextIOBase 
+{
+	public function new (?s:String):Void;
+	public function getvalue():String;
+
+
+
+	static function __init__ ():Void {
+		Macros.importFromAs("io", "StringIO", "python.lib.io.StringIO");
+	}
+}

+ 11 - 0
std/python/lib/io/TextIOBase.hx

@@ -0,0 +1,11 @@
+
+package python.lib.io;
+
+import python.lib.io.IOBase;
+
+extern class TextIOBase extends IOBase {
+
+	public var encoding:String;
+
+	public function write (s:String):Int;
+}

+ 68 - 0
std/python/lib/os/Path.hx

@@ -0,0 +1,68 @@
+
+package python.lib.os;
+
+import python.lib.Types;
+
+extern class Path {
+
+	public static var sep : String;
+	public static function exists (path:String):Bool;
+
+	public static function abspath (path:String):String;
+
+	public static function basename (path:String):String;
+
+	public static function commonprefix (paths:Array<String>):String;
+
+	public static function lexists (path:String):Bool;
+
+	public static function expanduser (path:String):String;
+
+	public static function expandvars (path:String):String;
+
+	public static function getmtime (path:String):Float;
+
+	public static function getatime (path:String):Float;
+
+	public static function getctime (path:String):Float;
+
+	public static function getsize (path:String):Int;
+
+	public static function isabs (path:String):Bool;
+
+	public static function isfile (path:String):Bool;
+
+	public static function isdir (path:String):Bool;
+
+	public static function dirname (path:String):String;
+
+	
+
+	public static function islink (path:String):Bool;
+
+	public static function ismount (path:String):Bool;
+
+	public static function join (path1:String, ?path2:String, ?path3:String, ?path4:String):String;
+
+	public static function normpath (path:String):String;
+
+	public static function realpath (path:String):String;
+
+	public static function relpath (path:String):String;
+
+	public static function samefile (path1:String, path2:String):String;
+
+	public static function split (path:String):Tup2<String, String>;
+
+	public static function splitdrive (path:String):Tup2<String, String>;
+
+	public static function splitext (path:String):Tup2<String, String>;
+
+	public static function supports_unicode_filenames ():Bool;
+
+
+	static function __init__ ():Void 
+	{
+		python.Macros.importFromAs("os", "path", "python.lib.os.Path");
+	}
+}

+ 66 - 0
std/python/lib/subprocess/Popen.hx

@@ -0,0 +1,66 @@
+
+package python.lib.subprocess;
+
+import python.lib.io.TextIOBase;
+import python.lib.Subprocess.StartupInfo;
+import python.lib.Types;
+
+typedef PopenOptions = {
+	?bufsize : Int,
+	?executable  : String,
+	?stdin  : TextIOBase,
+	?stdout  : TextIOBase,
+	?stderr : TextIOBase,
+	?preexec_fn : Void->Void,
+	?close_fds : Bool,
+	?shell : Bool,
+	?cwd : String,
+	?env : Dict<String, String>,
+	?universal_newlines : Bool,
+	?startupinfo : StartupInfo,
+	?creationflags : Int,
+}
+
+extern class Popen {
+
+	public static inline function create (args:Array<String>, o:PopenOptions):Popen {
+
+		o.bufsize = if (Reflect.hasField(o, "bufsize")) o.bufsize else 0;
+		o.executable = if (Reflect.hasField(o, "executable")) o.executable else null;
+		o.stdin = if (Reflect.hasField(o, "stdin")) o.stdin else null;
+		o.stdout = if (Reflect.hasField(o, "stdout")) o.stdout else null;
+		o.stderr = if (Reflect.hasField(o, "stderr")) o.stderr else null;
+		o.preexec_fn = if (Reflect.hasField(o, "preexec_fn")) o.preexec_fn else null;
+		o.close_fds = if (Reflect.hasField(o, "close_fds")) o.close_fds else null;
+		o.shell = if (Reflect.hasField(o, "shell")) o.shell else null;
+		o.cwd = if (Reflect.hasField(o, "cwd")) o.cwd else null;
+		o.env = if (Reflect.hasField(o, "env")) o.env else null;
+		o.universal_newlines = if (Reflect.hasField(o, "universal_newlines")) o.universal_newlines else null;
+		o.startupinfo = if (Reflect.hasField(o, "startupinfo")) o.startupinfo else null;
+		o.creationflags = if (Reflect.hasField(o, "creationflags")) o.creationflags else 0;
+
+		return new Popen(args, o.bufsize, o.executable, o.stdin, o.stdout, o.stderr, o.preexec_fn,
+			o.close_fds, o.shell, o.cwd, o.env, o.universal_newlines, o.startupinfo, o.creationflags);
+	}
+
+	public function new (args:Array<String>, bufsize:Int=0, executable:String = null, 
+			stdin:FileObject = null, stdout:FileObject = null, stderr:FileObject=null, preexec_fn:Void->Void=null, 
+			close_fds:Bool=false, shell:Bool=false, cwd:String=null, env:Dict<String,String>=null, 
+			universal_newlines:Bool=false, startupinfo:StartupInfo=null, creationflags:Int=0):Void;
+
+
+	public var stdin:TextIOBase;
+
+	public function kill ():Void;
+	public function wait (?timeout:Null<Int>):Null<Int>;
+	public function poll ():Null<Int>;
+	public function terminate ():Void;
+
+	public function communicate (input:Bytes = null, timeout:Null<Int> = null):Tup2<Bytes, Bytes>;
+
+	static function __init__ ():Void 
+	{
+		python.Macros.importFromAs("subprocess", "Popen", "python.lib.subprocess.Popen");
+	}
+
+}

+ 11 - 0
std/python/lib/threading/Thread.hx

@@ -0,0 +1,11 @@
+
+package python.lib.threading;
+
+extern class Thread {
+
+	static function __init__ ():Void 
+	{
+		python.Macros.importFromAs("threading","Thread", "python.lib.thrading.Thread");
+	}
+
+}

+ 10 - 0
std/python/lib/types/ClassType.hx

@@ -0,0 +1,10 @@
+
+package python.lib.types;
+
+extern class ClassType {
+
+	static function __init__ ():Void {
+		Macros.importFromAs("types", "ClassType", "python.lib.types.ClassType");
+	}
+
+}

+ 57 - 0
std/python/lib/xml/etree/ElementTree.hx

@@ -0,0 +1,57 @@
+
+package python.lib.xml.etree;
+
+import python.lib.Types.Tup2;
+
+import python.lib.Types;
+
+extern class XMLParser {
+
+}
+
+extern class Element {
+	public function getroot ():ElementTree;
+	public var tag:String;
+	public var attrib : Dict<String, String>;
+	public var text:Null<String>;
+
+
+	public function get <T>(key:String, def:T = null):T;
+	public function set (key:String, val:String):Void;
+
+	public function copy ():Element;
+
+	public function keys ():Array<String>;	
+	public function items ():Array<Tup2<String, String>>;
+
+	public function iter (tag:String):PyIterable<Element>;
+	public function iterfind (tag:String, namespaces:Dict<String,String> = null):PyIterator<Element>;
+	public function find (match:String, namespaces:Dict<String,String> = null):Null<Element>;
+	public function findall (match:String, namespaces:Dict<String,String> = null):Array<Element>;
+
+	static function __init__ ():Void 
+	{
+		Macros.importFromAs("xml.etree.ElementTree", "Element", "python.lib.xml.etree.Element");
+	}
+}
+
+extern class ElementTree {
+
+
+
+	public static function XML(text:String, ?parser:XMLParser):Element;
+	public static function parse(xml:String):ElementTree;
+
+	public function iter (tag:String):PyIterable<Element>;
+	public function find (match:String, namespaces:Dict<String,String> = null):Null<Element>;
+	public function getroot ():Element;
+
+
+
+
+	static function __init__ ():Void 
+	{
+		Macros.importAs("xml.etree.ElementTree", "python.lib.xml.etree.ElementTree");
+	}
+
+}