Update Files

This commit is contained in:
2025-01-22 16:18:30 +01:00
parent ed4603cf95
commit a36294b518
16718 changed files with 2960346 additions and 0 deletions

View File

@ -0,0 +1,477 @@
/*
* Copyright (C)2005-2019 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 python;
import python.internal.MethodClosure;
import python.internal.ArrayImpl;
import python.internal.Internal;
import python.internal.StringImpl;
import python.internal.EnumImpl;
import python.internal.HxOverrides;
import python.internal.AnonObject;
import python.internal.UBuiltins;
import python.lib.Inspect;
import python.Syntax;
@:dox(hide)
class Boot {
static var keywords:Set<String> = new Set([
"and", "del", "from", "not", "with", "as", "elif", "global", "or", "yield", "assert", "else", "if", "pass", "None", "break", "except", "import",
"raise", "True", "class", "exec", "in", "return", "False", "continue", "finally", "is", "try", "def", "for", "lambda", "while",
]);
inline static function arrayJoin<T>(x:Array<T>, sep:String):String {
return Syntax.field(sep, "join")(Syntax.code("[{0}(x1,'') for x1 in {1}]", python.Boot.toString1, x));
}
inline static function safeJoin(x:Array<String>, sep:String):String {
return Syntax.field(sep, "join")(Syntax.code("[x1 for x1 in {0}]", x));
}
inline static function isPyBool(o:Dynamic):Bool {
return UBuiltins.isinstance(o, UBuiltins.bool);
}
inline static function isPyInt(o:Dynamic):Bool {
// for historic reasons bool extends int
return UBuiltins.isinstance(o, UBuiltins.int) && !isPyBool(o);
}
inline static function isPyFloat(o:Dynamic):Bool {
return UBuiltins.isinstance(o, UBuiltins.float);
}
static inline function isClass(o:Dynamic):Bool {
return o != null && (o == String || Inspect.isclass(o));
}
static inline function isAnonObject(o:Dynamic) {
return UBuiltins.isinstance(o, AnonObject);
}
@:ifFeature("add_dynamic") private static function _add_dynamic(a:Dynamic, b:Dynamic):Dynamic {
if (UBuiltins.isinstance(a, String) && UBuiltins.isinstance(b, String)) {
return Syntax.binop(a, "+", b);
}
if (UBuiltins.isinstance(a, String) || UBuiltins.isinstance(b, String)) {
return Syntax.binop(toString1(a, ""), "+", toString1(b, ""));
}
return Syntax.binop(a, "+", b);
}
static inline function toString(o:Dynamic) {
return toString1(o, "");
}
private static function toString1(o:Dynamic, s:String):String {
if (o == null)
return "null";
if (isString(o))
return o;
if (s == null)
s = "";
if (s.length >= 5)
return "<...>"; // too much deep recursion
if (isPyBool(o)) {
if ((o : Bool))
return "true"
else
return "false";
}
if (isPyInt(o)) {
return UBuiltins.str(o);
}
// 1.0 should be printed as 1
if (isPyFloat(o)) {
try {
if ((o : Float) == UBuiltins.int(o)) {
return UBuiltins.str(Math.round(o));
} else {
return UBuiltins.str(o);
}
} catch (e:Dynamic) {
return UBuiltins.str(o);
}
}
if (isArray(o)) {
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 + toString1(o1[i], s);
}
st += "]";
return st;
}
try {
if (UBuiltins.hasattr(o, "toString"))
return Syntax.callField(o, "toString");
} catch (e:Dynamic) {}
if (UBuiltins.hasattr(o, "__class__")) {
if (isAnonObject(o)) {
var toStr = null;
try {
var fields = fields(o);
var fieldsStr = [for (f in fields) '$f : ${toString1(simpleField(o, f), s + "\t")}'];
toStr = "{ " + safeJoin(fieldsStr, ", ") + " }";
} catch (e:Dynamic) {
return "{ ... }";
}
if (toStr == null) {
return "{ ... }";
} else {
return toStr;
}
}
if (UBuiltins.isinstance(o, Enum)) {
var o:EnumImpl = (o : EnumImpl);
var l = UBuiltins.len(o.params);
var hasParams = l > 0;
if (hasParams) {
var paramsStr = "";
for (i in 0...l) {
var prefix = "";
if (i > 0) {
prefix = ",";
}
paramsStr += prefix + toString1(o.params[i], s);
}
return o.tag + "(" + paramsStr + ")";
} else {
return o.tag;
}
}
if (Internal.hasClassName(o)) {
if (Syntax.field(Syntax.field(o, "__class__"), "__name__") != "type") {
var fields = getInstanceFields(o);
var fieldsStr = [for (f in fields) '$f : ${toString1(simpleField(o, f), s + "\t")}'];
var toStr = (Internal.fieldClassName(o) : String) + "( " + safeJoin(fieldsStr, ", ") + " )";
return toStr;
} else {
var fields = getClassFields(o);
var fieldsStr = [for (f in fields) '$f : ${toString1(simpleField(o, f), s + "\t")}'];
var toStr = "#" + (Internal.fieldClassName(o) : String) + "( " + safeJoin(fieldsStr, ", ") + " )";
return toStr;
}
}
if (isMetaType(o, String)) {
return "#String";
}
if (isMetaType(o, Array)) {
return "#Array";
}
if (UBuiltins.callable(o)) {
return "function";
}
try {
if (UBuiltins.hasattr(o, "__repr__")) {
return Syntax.callField(o, "__repr__");
}
} catch (e:Dynamic) {}
if (UBuiltins.hasattr(o, "__str__")) {
return Syntax.callField(o, "__str__", []);
}
if (UBuiltins.hasattr(o, "__name__")) {
return Syntax.field(o, "__name__");
}
return "???";
} else {
return UBuiltins.str(o);
}
}
static inline function isMetaType(v:Dynamic, t:Dynamic):Bool {
return Syntax.binop(Syntax.binop(Syntax.call(UBuiltins.type, [v]), "==", UBuiltins.type), "and", Syntax.binop(v, "==", t));
}
@:analyzer(no_local_dce)
static function fields(o:Dynamic) {
var a = [];
if (o != null) {
if (Internal.hasFields(o)) {
var fields = Internal.fieldFields(o);
if (fields != null) {
return (fields : Array<String>).copy();
}
}
if (isAnonObject(o)) {
var d = Syntax.field(o, "__dict__");
var keys = Syntax.callField(d, "keys");
var handler = unhandleKeywords;
Syntax.code("for k in keys:");
Syntax.code(" if (k != '_hx_disable_getattr'):");
Syntax.code(" a.append(handler(k))");
} else if (UBuiltins.hasattr(o, "__dict__")) {
var a = [];
var d = Syntax.field(o, "__dict__");
var keys1 = Syntax.callField(d, "keys");
Syntax.code("for k in keys1:");
Syntax.code(" a.append(k)");
}
}
return a;
}
static inline function isString(o:Dynamic):Bool {
return UBuiltins.isinstance(o, UBuiltins.str);
}
static inline function isArray(o:Dynamic):Bool {
return UBuiltins.isinstance(o, UBuiltins.list);
}
static function simpleField(o:Dynamic, field:String):Dynamic {
if (field == null)
return null;
var field = handleKeywords(field);
return if (UBuiltins.hasattr(o, field)) UBuiltins.getattr(o, field) else null;
}
@:ifFeature("closure_Array", "closure_String")
static inline function createClosure(obj:Dynamic, func:Dynamic):Dynamic {
return new MethodClosure(obj, func);
}
static function hasField(o:Dynamic, field:String):Bool {
if (isAnonObject(o)) {
return Syntax.code('{0}._hx_hasattr({1})', o, field);
}
return UBuiltins.hasattr(o, handleKeywords(field));
}
static function field(o:Dynamic, field:String):Dynamic {
if (field == null)
return null;
inline function def() {
var field = handleKeywords(field);
return if (UBuiltins.hasattr(o, field)) UBuiltins.getattr(o, field) else null;
}
return if (isString(o)) {
switch (field) {
case "length":
StringImpl.get_length(o);
case "toLowerCase":
createClosure(o, StringImpl.toLowerCase);
case "toUpperCase":
createClosure(o, StringImpl.toUpperCase);
case "charAt":
createClosure(o, StringImpl.charAt);
case "charCodeAt":
createClosure(o, StringImpl.charCodeAt);
case "indexOf":
createClosure(o, StringImpl.indexOf);
case "lastIndexOf":
createClosure(o, StringImpl.lastIndexOf);
case "split":
createClosure(o, StringImpl.split);
case "substr":
createClosure(o, StringImpl.substr);
case "substring":
createClosure(o, StringImpl.substring);
case "toString":
createClosure(o, StringImpl.toString);
default:
def();
}
} else if (isArray(o)) {
switch (field) {
case "length":
ArrayImpl.get_length(o);
case "map":
createClosure(o, ArrayImpl.map);
case "filter":
createClosure(o, ArrayImpl.filter);
case "concat":
createClosure(o, ArrayImpl.concat);
case "copy":
createClosure(o, ArrayImpl.copy);
case "iterator":
createClosure(o, ArrayImpl.iterator);
case "keyValueIterator":
createClosure(o, ArrayImpl.keyValueIterator);
case "insert":
createClosure(o, ArrayImpl.insert);
case "join":
createClosure(o, ArrayImpl.join);
case "toString":
createClosure(o, ArrayImpl.toString);
case "pop":
createClosure(o, ArrayImpl.pop);
case "push":
createClosure(o, ArrayImpl.push);
case "unshift":
createClosure(o, ArrayImpl.unshift);
case "indexOf":
createClosure(o, ArrayImpl.indexOf);
case "lastIndexOf":
createClosure(o, ArrayImpl.lastIndexOf);
case "contains":
createClosure(o, ArrayImpl.contains);
case "remove":
createClosure(o, ArrayImpl.remove);
case "reverse":
createClosure(o, ArrayImpl.reverse);
case "shift":
createClosure(o, ArrayImpl.shift);
case "slice":
createClosure(o, ArrayImpl.slice);
case "sort":
createClosure(o, ArrayImpl.sort);
case "splice":
createClosure(o, ArrayImpl.splice);
default:
def();
}
} else {
def();
}
}
static function getInstanceFields(c:Class<Dynamic>):Array<String> {
var f = if (Internal.hasFields(c)) (Internal.fieldFields(c) : Array<String>).copy() else [];
if (Internal.hasMethods(c))
f = f.concat(Internal.fieldMethods(c));
var sc = getSuperClass(c);
if (sc == null) {
return f;
} else {
var scArr = getInstanceFields(sc);
var scMap = new Set(scArr);
for (f1 in f) {
if (!scMap.has(f1)) {
scArr.push(f1);
}
}
return scArr;
}
}
static function getSuperClass(c:Class<Dynamic>):Class<Dynamic> {
if (c == null)
return null;
try {
if (Internal.hasSuper(c)) {
return Internal.fieldSuper(c);
}
return null;
} catch (e:Dynamic) {}
return null;
}
static function getClassFields(c:Class<Dynamic>):Array<String> {
if (Internal.hasStatics(c)) {
var x:Array<String> = Internal.fieldStatics(c);
return x.copy();
} else {
return [];
}
}
static inline function unsafeFastCodeAt(s:String, index:Int) {
return UBuiltins.ord(python.Syntax.arrayAccess(s, index));
}
static inline function handleKeywords(name:String):String {
return if (keywords.has(name)) {
Internal.getPrefixed(name);
} else if (name.length > 2
&& unsafeFastCodeAt(name, 0) == "_".code
&& unsafeFastCodeAt(name, 1) == "_".code
&& unsafeFastCodeAt(name, name.length - 1) != "_".code) {
Internal.getPrefixed(name);
} else
name;
}
static var prefixLength = Internal.prefix().length;
static function unhandleKeywords(name:String):String {
if (name.substr(0, prefixLength) == Internal.prefix()) {
var real = name.substr(prefixLength);
if (keywords.has(real))
return real;
}
return name;
}
static inline function implementsInterface(value:Dynamic, cls:Class<Dynamic>):Bool {
function loop(intf) {
var f:Array<Dynamic> = if (Internal.hasInterfaces(intf)) Internal.fieldInterfaces(intf) else [];
if (f != null) {
for (i in f) {
if (i == cls) {
return true;
} else {
var l = loop(i);
if (l) {
return true;
}
}
}
return false;
} else {
return false;
}
}
var currentClass = Syntax.field(value, "__class__");
var result = false;
while (currentClass != null) {
if (loop(currentClass)) {
result = true;
break;
}
currentClass = getSuperClass(currentClass);
}
return result;
}
}

View File

@ -0,0 +1,55 @@
/*
* Copyright (C)2005-2019 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 python;
import python.Syntax;
@:native("bytearray")
extern class Bytearray implements ArrayAccess<Int> {
var length(get, never):Int;
@:overload(function():Void {})
@:overload(function(it:Array<Int>):Void {})
@:overload(function(it:NativeIterable<Int>):Void {})
@:overload(function(size:Int):Void {})
function new(source:String, encoding:String, ?errors:Dynamic):Void;
private inline function get_length():Int {
return python.internal.UBuiltins.len(this);
}
function append(x:Int):Void;
function extend(t:Bytearray):Void;
inline function get(i:Int):Int {
return Syntax.arrayAccess(this, i);
}
inline function set(i:Int, v:Int):Void {
this.__setitem__(i, v);
}
function __setitem__(i:Int, v:Int):Void;
function decode(encoding:String = "utf-8", errors:String = "strict"):String;
}

View File

@ -0,0 +1,30 @@
/*
* Copyright (C)2005-2019 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 python;
import python.Bytearray;
@:native("bytes")
extern class Bytes extends Bytearray {
// function decode(encoding:String="utf-8", errors:String="strict"):String;
}

View File

@ -0,0 +1,93 @@
/*
* Copyright (C)2005-2019 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 python;
import python.internal.UBuiltins;
import python.Tuple;
import python.NativeIterator;
import python.Syntax;
@:native("dict")
extern class Dict<K, V> {
function new():Void;
var length(get, never):Int;
private inline function get_length():Int {
return UBuiltins.len(this);
}
function get(key:K, ?def:V):V;
inline function getSafe(key:K):V {
return Syntax.arrayAccess(this, key);
}
inline function set(key:K, val:V):Void {
Syntax.arraySet(this, key, val);
}
inline function remove(key:K):Void {
Syntax.delete(python.Syntax.arrayAccess(this, key));
}
inline function hasKey(k:K):Bool {
return Syntax.isIn(k, this);
}
function clear():Void;
function copy():Dict<K, V>;
function items():DictView<Tuple2<K, V>>;
function keys():DictView<K>;
function pop(key:K, ?def:V):V;
function popitem():Tuple2<K, V>;
function setdefault(key:K, ?def:V):V;
function update(d:Dict<K, V>):Void;
function values():DictView<V>;
inline function iter():NativeIterator<K> {
return UBuiltins.iter(this);
}
inline function iterator():Iterator<V> {
return values().iter();
}
private function __iter__():NativeIterator<K>;
}
extern class DictView<T> {
var length(get, never):Int;
private inline function get_length():Int {
return UBuiltins.len(this);
}
inline function iter():NativeIterator<T> {
return UBuiltins.iter(this);
}
inline function iterator():Iterator<T> {
return iter();
}
private function __iter__():NativeIterator<T>;
}

View File

@ -0,0 +1,207 @@
/*
* Copyright (C)2005-2019 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 python;
import haxe.extern.Rest;
@:native("BaseException")
extern class BaseException {
function new(args:Rest<Dynamic>):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 {}
@: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 {}

View File

@ -0,0 +1,37 @@
/*
* Copyright (C)2005-2019 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 python;
import python.NativeIterable.NativeIterableRaw;
class HaxeIterable<T> {
var x:NativeIterableRaw<T>;
public inline function new(x:NativeIterableRaw<T>) {
this.x = x;
}
public inline function iterator():HaxeIterator<T> {
return new HaxeIterator(x.__iter__());
}
}

View File

@ -0,0 +1,58 @@
/*
* Copyright (C)2005-2019 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 python;
import python.Exceptions.StopIteration;
import python.NativeIterator;
class HaxeIterator<T> {
var it:NativeIteratorRaw<T>;
var x:Null<T> = null;
var has = false;
var checked = false;
public function new(it:NativeIteratorRaw<T>) {
this.it = it;
}
public inline function next():T {
if (!checked)
hasNext();
checked = false;
return x;
}
public function hasNext():Bool {
if (!checked) {
try {
x = it.__next__();
has = true;
} catch (s:StopIteration) {
has = false;
x = null;
}
checked = true;
}
return has;
}
}

View File

@ -0,0 +1,69 @@
/*
* Copyright (C)2005-2019 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 python;
import python.Dict;
/**
This type represents python `**kwargs` feature, supporting
passing named arguments to a function.
Example:
```haxe
function f(kwargs:KwArgs<{a:Int}>) {}
f({a: 10});
```
**/
abstract KwArgs<T:{}>(Dict<String, Dynamic>) {
inline function new(d:Dict<String, Dynamic>) {
this = d;
}
@:to public inline function toDict():Dict<String, Dynamic> {
// pass null, it's just to have the type information available in genpy
return toDictHelper(null);
}
// this is a helper method (hack) which is matched in genpy to extract the type information for reverse mapping
// of keyword fields.
function toDictHelper(x:T):Dict<String, Dynamic> {
return this;
}
@:from static inline function fromDict(d:Dict<String, Dynamic>):KwArgs<Dynamic> {
return new KwArgs(d);
}
@:from static function fromT<T:{}>(d:T):KwArgs<T> {
return new KwArgs(Lib.anonAsDict(d));
}
public inline function typed():T {
return Lib.dictAsAnon(toDict());
}
public inline function get<V>(key:String, def:V):V {
return this.get(key, def);
}
}

View File

@ -0,0 +1,135 @@
/*
* Copyright (C)2005-2019 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 python;
import python.internal.AnonObject;
import python.Dict;
import python.NativeStringTools;
typedef PySys = python.lib.Sys;
/**
Platform-specific Python Library. Provides some platform-specific functions
for the Python target, such as conversion from Haxe types to native types
and vice-versa.
**/
class Lib {
static var lineEnd:String = Sys.systemName() == "Windows" ? "\r\n" : "\n";
static public var __name__(get, never):String;
static inline function get___name__():String
return python.Syntax.code('__name__');
/**
Print the specified value on the default output.
**/
public static inline function print(v:Dynamic):Void {
printString(Std.string(v));
}
private static function printString(str:String):Void {
PySys.stdout.buffer.write(NativeStringTools.encode(str, "utf-8"));
PySys.stdout.flush();
}
/**
Print the specified value on the default output followed by a newline character.
**/
public static inline function println(v:Dynamic):Void {
var str = Std.string(v);
printString('$str$lineEnd');
}
/**
Returns an anonymous Object which holds the same data as the Dictionary `v`.
**/
public static function dictToAnon(v:Dict<String, Dynamic>):Dynamic {
return new AnonObject(v.copy());
}
/**
Returns a flat copy of the underlying Dictionary of `o`.
**/
@:access(python.Boot.isAnonObject)
public static function anonToDict(o:{}):Dict<String, Dynamic> {
return if (Boot.isAnonObject(o)) {
(Syntax.field(o, "__dict__") : Dict<String, Dynamic>).copy();
} else null;
}
/**
Returns the underlying Dictionary of the anonymous object `o`.
Modifications to this dictionary are reflected in the anonymous Object too.
**/
@:access(python.Boot.isAnonObject)
public static function anonAsDict(o:{}):Dict<String, Dynamic> {
return if (Boot.isAnonObject(o)) {
(Syntax.field(o, "__dict__") : Dict<String, Dynamic>);
} else null;
}
/**
Returns the Dictionary `d` as an anonymous Object.
Modifications to the object are reflected in the Dictionary too.
**/
public static inline function dictAsAnon(d:Dict<String, Dynamic>):Dynamic {
return new AnonObject(d);
}
/**
Return Python native iterable from Haxe iterable.
**/
public static function toPythonIterable<T>(it:Iterable<T>):python.NativeIterable<T> {
return {
__iter__: function() {
var it1 = it.iterator();
var self:NativeIterator<T> = null;
self = new NativeIterator({
__next__: function():T {
if (it1.hasNext()) {
return it1.next();
} else {
throw new python.Exceptions.StopIteration();
}
},
__iter__: function() return self
});
return self;
}
}
}
/**
Return Haxe iterable from Python native iterable.
**/
public static inline function toHaxeIterable<T>(it:NativeIterable<T>):HaxeIterable<T> {
return new HaxeIterable(it);
}
/**
Return Haxe iterator instance from Python native iterable.
**/
public static inline function toHaxeIterator<T>(it:NativeIterator<T>):HaxeIterator<T> {
return new HaxeIterator(it);
}
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (C)2005-2019 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 python;
class NativeArrayTools {
public static inline function extend<T>(a:Array<T>, x:Array<T>):Void {
python.Syntax.field(a, "extend")(x);
}
public static inline function append<T>(a:Array<T>, x:T):Void {
python.Syntax.field(a, "append")(x);
}
public static inline function contains<T>(a:Array<T>, x:T):Bool {
return python.Syntax.isIn(x, a);
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright (C)2005-2019 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 python;
import python.HaxeIterable;
import python.NativeIterator;
/**
This type represents native Python iterables (objects that implement `__iter__()` method).
It supports Haxe iteration and conversion to `Iterable` by creating wrapper objects.
**/
abstract NativeIterable<T>(NativeIterableRaw<T>) to NativeIterableRaw<T> from NativeIterableRaw<T> {
/**
Return Haxe `Iterable` object wrapping `this` native iterable.
**/
@:to public inline function toHaxeIterable():HaxeIterable<T>
return new HaxeIterable(this);
/**
Return Haxe `Iterator` object by wrapping `this.__iter__()` native iterator.
**/
public inline function iterator():HaxeIterator<T>
return new HaxeIterator(this.__iter__());
}
/**
Native Python iterable protocol.
**/
typedef NativeIterableRaw<T> = {
private function __iter__():NativeIterator<T>;
}

View File

@ -0,0 +1,47 @@
/*
* Copyright (C)2005-2019 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 python;
import python.NativeIterable.NativeIterableRaw;
/**
This type represents native Python iterators.
It supports automatic conversion to Haxe `Iterator` by creating wrapper object.
**/
abstract NativeIterator<T>(NativeIteratorRaw<T>) to NativeIteratorRaw<T> to NativeIterable<T> {
public inline function new(p:NativeIteratorRaw<T>)
this = p;
/**
Return Haxe `Iterator` object by wrapping `this` native iterator.
**/
@:to public inline function toHaxeIterator():HaxeIterator<T>
return new HaxeIterator(this);
}
/**
Native Python iterator protocol.
**/
typedef NativeIteratorRaw<T> = NativeIterableRaw<T> & {
function __next__():T;
}

View File

@ -0,0 +1,56 @@
/*
* Copyright (C)2005-2019 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 python;
import python.Bytes;
import python.Tuple;
class NativeStringTools {
public static function format(s:String, args:Array<Dynamic>):String {
return python.Syntax.field(s, "format")(python.Syntax.varArgs(args));
}
public static inline function encode(s:String, encoding:String = "utf-8", errors:String = "strict"):Bytes {
return (python.Syntax.callField(s, "encode", encoding, errors) : Bytes);
}
public static inline function contains(s:String, e:String):Bool {
return python.Syntax.isIn(e, s);
}
public static inline function strip(s:String, ?chars:String):String {
return python.Syntax.field(s, "strip")(chars);
}
public static inline function rpartition(s:String, sep:String):Tuple3<String, String, String> {
return python.Syntax.field(s, "rpartition")(sep);
}
public static inline function startswith(s:String, prefix:String):Bool {
return python.Syntax.field(s, "startswith")(prefix);
}
public static inline function endswith(s:String, suffix:String):Bool {
return python.Syntax.field(s, "endswith")(suffix);
}
}

View File

@ -0,0 +1,80 @@
/*
* Copyright (C)2005-2019 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 python;
import haxe.extern.Rest;
import python.internal.UBuiltins;
import python.NativeIterator;
import python.NativeIterable;
import python.Syntax;
@:native("set")
extern class Set<T> {
@:overload(function(?array:Array<T>):Void {})
function new(?iterable:NativeIterable<T>):Void;
var length(get, never):Int;
private inline function get_length():Int {
return UBuiltins.len(this);
}
inline function has(v:T):Bool {
return Syntax.isIn(v, this);
}
function isdisjoint(other:Set<T>):Bool;
function issubset(other:Set<T>):Bool;
inline function issubset_proper(other:Set<T>):Bool {
return Syntax.binop(this, "<", other);
}
function issuperset(other:Set<T>):Bool;
inline function issuperset_proper(other:Set<T>):Bool {
return Syntax.binop(this, ">", other);
}
function union(other:Set<T>, others:Rest<Set<T>>):Set<T>;
function intersection(other:Set<T>, others:Rest<Set<T>>):Set<T>;
function difference(other:Set<T>, others:Rest<Set<T>>):Set<T>;
function symmetric_difference(other:Set<T>):Set<T>;
function copy():Set<T>;
function update(other:Set<T>, others:Rest<Set<T>>):Set<T>;
function intersection_update(other:Set<T>, others:Rest<Set<T>>):Set<T>;
function difference_update(other:Set<T>, others:Rest<Set<T>>):Set<T>;
function symmetric_difference_update(other:Set<T>):Set<T>;
function add(elem:T):Void;
function remove(elem:T):Void;
function discard(elem:T):Void;
function pop():T;
function clear():Void;
inline function iter():NativeIterator<T> {
return UBuiltins.iter(this);
}
inline function iterator():Iterator<T> {
return iter();
}
private function __iter__():NativeIterator<T>;
}

View File

@ -0,0 +1,104 @@
/*
* Copyright (C)2005-2019 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 python;
import haxe.extern.Rest;
@:noPackageRestrict
@:noClosure
extern class Syntax {
@:noUsing macro public static function importModule(module:String):haxe.macro.Expr;
@:noUsing macro public static function importAs(module:String, className:String):haxe.macro.Expr;
@:overload(function(className:String, args:Rest<Dynamic>):Dynamic {})
static function construct<T>(cls:Class<T>, args:Rest<Dynamic>):T;
@:noUsing
@:deprecated("python.Syntax.newInstance() is deprecated. Use python.Syntax.construct() instead.")
macro public static function newInstance(c:haxe.macro.Expr, params:Array<haxe.macro.Expr>):haxe.macro.Expr;
extern static function _newInstance(c:Dynamic, args:Array<Dynamic>):Dynamic;
@:noUsing
extern static function isIn(a:Dynamic, b:Dynamic):Bool;
@:noUsing
extern static function delete(a:Dynamic):Void;
@:noUsing
extern static function binop(a:Dynamic, op:String, b:Dynamic):Dynamic;
@:noUsing
extern static function assign(a:Dynamic, b:Dynamic):Void;
static function code(code:String, args:Rest<Dynamic>):Dynamic;
@:noUsing
@:deprecated("python.Syntax.pythonCode() is deprecated. Use python.Syntax.code() instead.")
macro public static function pythonCode(b:ExprOf<String>, rest:Array<haxe.macro.Expr>):haxe.macro.Expr;
@:noUsing
static function _pythonCode<T>(b:String, args:Array<Dynamic>):T;
@:noUsing
macro public static function arrayAccess(x:haxe.macro.Expr, rest:Array<haxe.macro.Expr>):haxe.macro.Expr.ExprOf<Dynamic>;
@:noUsing
macro public static function arrayAccessWithTrailingColon(x:haxe.macro.Expr, rest:Array<haxe.macro.Expr>):haxe.macro.Expr.ExprOf<Dynamic>;
extern static function _arrayAccess(a:Dynamic, args:Array<Dynamic>, ?trailingColon:Bool = false):Dynamic;
@:noUsing
extern static function arraySet(a:Dynamic, i:Dynamic, v:Dynamic):Dynamic;
extern static function _foreach(id:Dynamic, it:Dynamic, block:Dynamic):Dynamic;
@:noUsing
macro public static function foreach<T>(v:haxe.macro.Expr, it:haxe.macro.Expr, b:haxe.macro.Expr):haxe.macro.Expr;
@:noUsing macro public static function importFromAs(from:String, module:String, className:String):haxe.macro.Expr;
@:noUsing
macro public static function callField(o:haxe.macro.Expr, field:haxe.macro.Expr.ExprOf<String>, params:Array<haxe.macro.Expr>):haxe.macro.Expr;
extern static function call(e:Dynamic, args:Array<Dynamic>):Dynamic;
@:noUsing
extern static function field(o:Dynamic, field:String):Dynamic;
@:noUsing
macro public static function tuple(args:Array<haxe.macro.Expr>):haxe.macro.Expr;
extern static function _tuple(args:Array<Dynamic>):Dynamic;
@:noUsing
extern static function varArgs(args:Array<Dynamic>):Dynamic;
macro public static function callNamedUntyped(e:haxe.macro.Expr, args:haxe.macro.Expr):haxe.macro.Expr;
extern static function _callNamedUntyped(e:Dynamic, args:Dynamic):Dynamic;
extern static function opPow(a:Int, b:Int):Int;
}

View File

@ -0,0 +1,113 @@
/*
* Copyright (C)2005-2019 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 python;
import haxe.macro.Expr;
import haxe.macro.Context;
import haxe.macro.ExprTools;
@:noPackageRestrict
@:noClosure
class Syntax {
@:noUsing
macro public static function importModule(module:String):Expr {
return macro python.Syntax.code($v{"import " + module});
}
@:noUsing
macro public static function importAs(module:String, className:String):ExprOf<Void> {
var n = className.split(".").join("_");
var e = "import " + module + " as " + n;
return macro python.Syntax.code($v{e});
}
@:noUsing
@:deprecated("python.Syntax.newInstance() is deprecated. Use python.Syntax.construct() instead.")
macro public static function newInstance(c:Expr, params:Array<Expr>):Expr {
return macro python.Syntax._newInstance($c, $a{params});
}
@:noUsing
@:deprecated("python.Syntax.pythonCode() is deprecated. Use python.Syntax.code() instead.")
macro public static function pythonCode(b:ExprOf<String>, rest:Array<Expr>):Expr {
if (rest == null)
rest = [];
return macro @:pos(Context.currentPos()) untyped python.Syntax._pythonCode($b, $a{rest});
}
@:noUsing
macro public static function arrayAccess(x:Expr, rest:Array<Expr>):ExprOf<Dynamic> {
return macro python.Syntax._arrayAccess($x, $a{rest});
}
@:noUsing
macro public static function arrayAccessWithTrailingColon(x:Expr, rest:Array<Expr>):ExprOf<Dynamic> {
return macro python.Syntax._arrayAccess($x, $a{rest}, true);
}
@:noUsing
macro public static function foreach<T>(v:Expr, it:Expr, b:Expr):Expr {
var id = switch (v.expr) {
case EConst(CIdent(x)): x;
case _: Context.error("unexpected " + ExprTools.toString(v) + ": const ident expected", v.pos);
}
var iter = try {
var it = macro($it.__iter__() : python.NativeIterator.NativeIteratorRaw<T>);
Context.typeof(it);
it;
} catch (e:Dynamic) {
macro($it : python.NativeIterable.NativeIterableRaw<T>);
}
return macro {
var $id = null;
python.Syntax._foreach($v, $it, cast $b);
}
}
@:noUsing
macro public static function importFromAs(from:String, module:String, className:String):ExprOf<Void> {
var n = className.split(".").join("_");
var e = "from " + from + " import " + module + " as " + n;
return macro python.Syntax.code($v{e});
}
@:noUsing
macro public static function callField(o:Expr, field:ExprOf<String>, params:Array<Expr>):Expr {
return macro @:pos(o.pos) python.Syntax.call(python.Syntax.field($o, $field), $a{params});
}
@:noUsing
macro public static function tuple(args:Array<Expr>):Dynamic {
var args = macro $a{args};
return macro python.Syntax._tuple($args);
}
macro public static function callNamedUntyped(e:Expr, args:Expr):Expr {
return macro @:pos(e.pos) python.Syntax._callNamedUntyped($e, $args);
}
}

View File

@ -0,0 +1,117 @@
/*
* Copyright (C)2005-2019 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 python;
import python.internal.UBuiltins;
import python.Syntax;
@:native("tuple")
extern class Tuple<X> implements ArrayAccess<X> {
@:overload(function():Void {})
function new(a:Array<X>):Void;
var length(get, never):Int;
inline function get_length():Int {
return UBuiltins.len(this);
}
inline function toArray():Array<X> {
return UBuiltins.list(this);
}
}
@:native("tuple")
extern class Tuple1<A> extends Tuple<Dynamic> {
static inline function make<A>(a:A):Tuple1<A>
return Syntax.tuple(a);
var _1(get, null):A;
inline function get__1():A
return this[0];
}
@:native("tuple")
extern class Tuple2<A, B> extends Tuple<Dynamic> {
static inline function make<A, B>(a:A, b:B):Tuple2<A, B>
return Syntax.tuple(a, b);
var _1(get, null):A;
inline function get__1():A
return this[0];
var _2(get, null):B;
inline function get__2():B
return this[1];
}
@:native("tuple")
extern class Tuple3<A, B, C> extends Tuple<Dynamic> {
static inline function make<A, B, C>(a:A, b:B, c:C):Tuple3<A, B, C>
return Syntax.tuple(a, b, c);
var _1(get, null):A;
inline function get__1():A
return this[0];
var _2(get, null):B;
inline function get__2():B
return this[1];
var _3(get, null):C;
inline function get__3():C
return this[2];
}
@:native("tuple")
extern class Tuple4<A, B, C, D> extends Tuple<Dynamic> {
static inline function make<A, B, C, D>(a:A, b:B, c:C, d:D):Tuple4<A, B, C, D>
return Syntax.tuple(a, b, c, d);
var _1(get, null):A;
inline function get__1():A
return this[0];
var _2(get, null):B;
inline function get__2():B
return this[1];
var _3(get, null):C;
inline function get__3():C
return this[2];
var _4(get, null):D;
inline function get__4():D
return this[3];
}
@:native("tuple")
extern class Tuple5<A, B, C, D, E> extends Tuple<Dynamic> {
static inline function make<A, B, C, D, E>(a:A, b:B, c:C, d:D, e:E):Tuple5<A, B, C, D, E>
return Syntax.tuple(a, b, c, d, e);
var _1(get, null):A;
inline function get__1():A
return this[0];
var _2(get, null):B;
inline function get__2():B
return this[1];
var _3(get, null):C;
inline function get__3():C
return this[2];
var _4(get, null):D;
inline function get__4():D
return this[3];
var _5(get, null):E;
inline function get__5():E
return this[4];
}

View File

@ -0,0 +1,55 @@
/*
* Copyright (C)2005-2019 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 python;
import python.internal.UBuiltins.list;
/**
This type represents python `*args` feature, supporting
passing arbitrary number of arguments to a function.
Example:
```haxe
function f(args:VarArgs<Int>) {}
f([1, 2, 3]);
```
**/
@:analyzer(no_simplification)
abstract VarArgs<T>(Dynamic) {
inline function new(d:Array<T>) {
this = d;
}
inline function raw():Dynamic {
return this;
}
@:to public inline function toArray():Array<T> {
return if (!Std.isOfType(raw(), Array)) list(raw()) else (raw() : Array<T>);
}
@:from static inline function fromArray<T>(d:Array<T>):VarArgs<T> {
return new VarArgs(d);
}
}

View File

@ -0,0 +1,141 @@
/*
* Copyright (C)2005-2019 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.
*/
#if !macro
import python.internal.ArrayImpl;
import python.NativeIterator;
#end
import haxe.iterators.ArrayKeyValueIterator;
@:native("list")
@:coreApi
extern class Array<T> implements ArrayAccess<T> {
var length(default, null):Int;
function new():Void;
inline function concat(a:Array<T>):Array<T> {
return ArrayImpl.concat(this, a);
}
inline function copy():Array<T> {
return ArrayImpl.copy(this);
}
@:runtime inline function iterator():haxe.iterators.ArrayIterator<T> {
return new haxe.iterators.ArrayIterator(this);
}
@:runtime inline public function keyValueIterator():ArrayKeyValueIterator<T> {
return new ArrayKeyValueIterator(this);
}
inline function insert(pos:Int, x:T):Void {
ArrayImpl.insert(this, pos, x);
}
@:runtime inline function join(sep:String):String {
return ArrayImpl.join(this, sep);
}
inline function toString():String {
return ArrayImpl.toString(this);
}
@:runtime inline function pop():Null<T> {
return ArrayImpl.pop(this);
}
@:runtime inline function push(x:T):Int {
return ArrayImpl.push(this, x);
}
inline function unshift(x:T):Void {
ArrayImpl.unshift(this, x);
}
inline function indexOf(x:T, ?fromIndex:Int):Int {
return ArrayImpl.indexOf(this, x, fromIndex);
}
inline function lastIndexOf(x:T, ?fromIndex:Int):Int {
return ArrayImpl.lastIndexOf(this, x, fromIndex);
}
inline function remove(x:T):Bool {
return ArrayImpl.remove(this, x);
}
inline function contains(x:T):Bool {
return ArrayImpl.contains(this,x);
}
inline function reverse():Void {
ArrayImpl.reverse(this);
}
@:runtime inline function shift():Null<T> {
return ArrayImpl.shift(this);
}
inline function slice(pos:Int, ?end:Int):Array<T> {
return ArrayImpl.slice(this, pos, end);
}
inline function sort(f:T->T->Int):Void {
ArrayImpl.sort(this, f);
}
inline function splice(pos:Int, len:Int):Array<T> {
return ArrayImpl.splice(this, pos, len);
}
@:runtime inline function map<S>(f:T->S):Array<S> {
return ArrayImpl.map(this, f);
}
@:runtime inline function filter(f:T->Bool):Array<T> {
return ArrayImpl.filter(this, f);
}
inline function resize(len:Int):Void {
ArrayImpl.resize(this, len);
}
@: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 unsafeGet(idx:Int):T {
return ArrayImpl.unsafeGet(this, idx);
}
@:keep private inline function unsafeSet(idx:Int, val:T):T {
return ArrayImpl.unsafeSet(this, idx, val);
}
@:noCompletion private function __iter__():NativeIterator<T>;
}

View File

@ -0,0 +1,155 @@
/*
* Copyright (C)2005-2019 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.datetime.Datetime;
import python.lib.datetime.Timedelta;
import python.lib.datetime.Timezone;
import python.Syntax;
@:coreApi class Date {
private var date:Datetime;
private var dateUTC: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 = makeLocal(new Datetime(year, month + 1, day, hour, min, sec, 0));
dateUTC = date.astimezone(Timezone.utc);
}
public inline function getTime():Float {
return date.timestamp() * 1000;
}
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() % 7;
}
public inline function getUTCHours():Int {
return dateUTC.hour;
}
public inline function getUTCMinutes():Int {
return dateUTC.minute;
}
public inline function getUTCSeconds():Int {
return dateUTC.second;
}
public inline function getUTCFullYear():Int {
return dateUTC.year;
}
public inline function getUTCMonth():Int {
return dateUTC.month - 1;
}
public inline function getUTCDate():Int {
return dateUTC.day;
}
public inline function getUTCDay():Int {
return dateUTC.isoweekday() % 7;
}
public function getTimezoneOffset():Int {
return -Std.int(Syntax.binop(date.utcoffset(), "/", new Timedelta(0, 60)));
}
public function toString():String {
return date.strftime("%Y-%m-%d %H:%M:%S");
}
static public function now():Date {
var d = new Date(2000, 0, 1, 0, 0, 0);
d.date = makeLocal(Datetime.now());
d.dateUTC = d.date.astimezone(Timezone.utc);
return d;
}
static public function fromTime(t:Float):Date {
var d = new Date(2000, 0, 1, 0, 0, 0);
d.date = makeLocal(Datetime.fromtimestamp(t / 1000.0));
d.dateUTC = d.date.astimezone(Timezone.utc);
return d;
}
static function makeLocal(date:Datetime):Datetime {
try {
return date.astimezone();
} catch (e:Dynamic) {
// No way in vanilla Python <=3.5 to get the local timezone
// Additionally dates close to the epoch <86400 will throw on astimezone
var tzinfo = Datetime.now(Timezone.utc).astimezone().tzinfo;
return date.replace({tzinfo: tzinfo});
}
}
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;
}
static public function fromString(s:String):Date {
switch (s.length) {
case 8: // hh:mm:ss
var k = s.split(":");
return Date.fromTime(Std.parseInt(k[0]) * 3600000. + Std.parseInt(k[1]) * 60000. + Std.parseInt(k[2]) * 1000.);
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;
}
}
}

View File

@ -0,0 +1,167 @@
/*
* Copyright (C)2005-2019 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.internal.UBuiltins;
import python.lib.Re;
import python.lib.Re.MatchObject;
import python.lib.Re.Pattern;
@:coreApi
class EReg {
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);
}
public inline function match(s:String):Bool {
matchObj = Re.search(pattern, s);
return matchObj != null;
}
public inline function matched(n:Int):String {
return matchObj.group(n);
}
public inline function matchedLeft():String {
return matchObj.string.substr(0, matchObj.start());
}
public inline function matchedRight():String {
return matchObj.string.substr(matchObj.end());
}
public inline function matchedPos():{pos:Int, len:Int} {
return {pos: matchObj.start(), len: matchObj.end() - matchObj.start()};
}
public function matchSub(s:String, pos:Int, len:Int = -1):Bool {
if (len != -1) {
matchObj = pattern.search(s, pos, pos + len);
} else {
matchObj = pattern.search(s, pos);
}
return this.matchObj != null;
}
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));
ret;
} else {
this.match(s);
if (matchObj == null) {
[s];
} else {
[s.substring(0, matchObj.start()), s.substr(matchObj.end())];
}
}
}
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) {
var gs = g[i];
if (gs == null)
continue;
res = res.split("$" + UBuiltins.str(i + 1)).join(gs);
}
res = res.split("_hx_#repl#__").join("$");
return res;
}
return Re.sub(pattern, replace, s, global ? 0 : 1);
}
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();
}
public static inline function escape(s:String):String {
return Re.escape(s);
}
}

View File

@ -0,0 +1,131 @@
/*
* Copyright (C)2005-2019 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.internal.UBuiltins;
@:pythonImport("math")
@:coreApi
extern class Math {
static var PI(default, null):Float;
static var NEGATIVE_INFINITY(default, null):Float;
static var POSITIVE_INFINITY(default, null):Float;
static var NaN(default, null):Float;
static inline function abs(v:Float):Float {
return (Math : Dynamic).fabs(v);
}
static inline function min(a:Float, b:Float):Float {
return if (isNaN(a)) a else if (isNaN(b)) b else UBuiltins.min(a, b);
}
static inline function max(a:Float, b:Float):Float {
return if (isNaN(a)) a else if (isNaN(b)) b else UBuiltins.max(a, b);
}
static inline function sin(v:Float):Float {
return if (v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY) NaN else python.lib.Math.sin(v);
}
static inline function cos(v:Float):Float {
return if (v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY) NaN else python.lib.Math.cos(v);
}
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;
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);
}
}
static inline function log(v:Float):Float {
return if (v == 0.0) NEGATIVE_INFINITY else if (v < 0.0) NaN else python.lib.Math.log(v);
}
static function pow(v:Float, exp:Float):Float;
static inline function sqrt(v:Float):Float {
return if (v < 0) NaN else python.lib.Math.sqrt(v);
}
static inline function round(v:Float):Int {
return Math.floor(v + 0.5);
}
static function floor(v:Float):Int;
static function ceil(v:Float):Int;
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);
}
static inline function isFinite(f:Float):Bool
return f != POSITIVE_INFINITY && f != NEGATIVE_INFINITY && !isNaN(f);
static inline function isNaN(f:Float):Bool {
return python.lib.Math.isnan(f);
}
static function __init__():Void {
NEGATIVE_INFINITY = UBuiltins.float('-inf');
POSITIVE_INFINITY = UBuiltins.float('inf');
NaN = UBuiltins.float("nan");
PI = python.lib.Math.pi;
}
}

View File

@ -0,0 +1,145 @@
/*
* Copyright (C)2005-2019 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.internal.AnonObject;
import python.internal.StringImpl;
import python.internal.ArrayImpl;
import python.internal.UBuiltins;
import python.internal.MethodClosure;
import python.lib.Inspect;
import python.Syntax;
import python.VarArgs;
import python.Boot;
import python.Boot.handleKeywords;
@:access(python.Boot)
@:coreApi
class Reflect {
public static inline function hasField(o:Dynamic, field:String):Bool {
return Boot.hasField(o, field);
}
@:ifFeature("dynamic_read", "anon_optional_read")
public static function field(o:Dynamic, field:String):Dynamic {
return Boot.field(o, field);
}
@:ifFeature("dynamic_write", "anon_optional_write")
public static inline function setField(o:Dynamic, field:String, value:Dynamic):Void {
UBuiltins.setattr(o, handleKeywords(field), value);
}
public static function getProperty(o:Dynamic, field:String):Dynamic {
if (o == null)
return null;
field = handleKeywords(field);
if (Boot.isAnonObject(o))
return Reflect.field(o, field);
var tmp = Reflect.field(o, "get_" + field);
if (tmp != null && UBuiltins.callable(tmp))
return tmp();
else
return Reflect.field(o, field);
}
public static function setProperty(o:Dynamic, field:String, value:Dynamic):Void {
var field = handleKeywords(field);
if (Boot.isAnonObject(o))
UBuiltins.setattr(o, field, value);
else if (UBuiltins.hasattr(o, "set_" + field))
UBuiltins.getattr(o, "set_" + field)(value);
else
UBuiltins.setattr(o, field, value);
}
public static function callMethod(o:Dynamic, func:haxe.Constraints.Function, args:Array<Dynamic>):Dynamic {
return if (UBuiltins.callable(func)) func(python.Syntax.varArgs(args)) else null;
}
public static inline function fields(o:Dynamic):Array<String> {
return python.Boot.fields(o);
}
public static function isFunction(f:Dynamic):Bool {
return Inspect.isfunction(f) || Inspect.ismethod(f) || Boot.hasField(f, "func_code");
}
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);
}
static inline function isClosure(v:Dynamic):Bool {
return UBuiltins.isinstance(v, MethodClosure);
}
public static function compareMethods(f1:Dynamic, f2:Dynamic):Bool {
if (f1 == f2)
return true;
if (isClosure(f1) && isClosure(f2)) {
var m1 = (f1 : MethodClosure);
var m2 = (f2 : MethodClosure);
return m1.obj == m2.obj && m1.func == m2.func;
}
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 && UBuiltins.isinstance(v, cast Enum);
}
public static function deleteField(o:Dynamic, field:String):Bool {
field = handleKeywords(field);
if (!hasField(o, field))
return false;
Syntax.callField(o, "__delattr__", field);
return true;
}
public static function copy<T>(o:Null<T>):Null<T> {
if (o == null)
return null;
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 function(v:VarArgs<Dynamic>) {
return f(v);
}
}
}

View File

@ -0,0 +1,217 @@
/*
* Copyright (C)2005-2019 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.internal.Internal;
import python.internal.UBuiltins;
import python.lib.Inspect;
import python.Boot;
import python.Syntax;
@:keepInit
@:coreApi class Std {
@:access(python.Boot)
public static function downcast<T:{}, S:T>(value:T, c:Class<S>):S {
try {
return UBuiltins.isinstance(value, c) || (Inspect.isInterface(c) && Boot.implementsInterface(value, c)) ? cast value : null;
} catch (e:Dynamic) {
return null;
}
}
@:deprecated('Std.instance() is deprecated. Use Std.downcast() instead.')
public static inline function instance<T:{}, S:T>(value:T, c:Class<S>):S {
return downcast(value, c);
}
@:access(python.Boot)
static inline function isMetaType(v:Dynamic, t:Dynamic):Bool {
return Boot.isMetaType(v, t);
}
@:ifFeature("typed_cast")
@:deprecated('Std.is is deprecated. Use Std.isOfType instead.')
public static inline function is(v:Dynamic, t:Dynamic):Bool {
return isOfType(v, t);
}
@:access(python.Boot)
@:ifFeature("typed_cast")
public static function isOfType(v:Dynamic, t:Dynamic):Bool {
if (v == null && t == null) {
return false;
}
if (t == null) {
return false;
}
if (isMetaType(t, Dynamic)) {
return v != null;
}
var isBool = UBuiltins.isinstance(v, UBuiltins.bool);
if (isMetaType(t, Bool) && isBool) {
return true;
}
if (!isBool && !isMetaType(t, Bool) && isMetaType(t, Int) && UBuiltins.isinstance(v, UBuiltins.int)) {
return true;
}
var vIsFloat = UBuiltins.isinstance(v, UBuiltins.float);
if (!isBool && vIsFloat && isMetaType(t, Int) && Math.isFinite(v) && v == Std.int(v) && v <= 2147483647 && v >= -2147483648) {
return true;
}
if (!isBool && isMetaType(t, Float) && (UBuiltins.isinstance(v, python.Syntax.tuple(UBuiltins.float, UBuiltins.int)))) {
return true;
}
if (isMetaType(t, UBuiltins.str)) {
return UBuiltins.isinstance(v, String);
}
var isEnumType = isMetaType(t, Enum);
if (isEnumType && Inspect.isclass(v) && Internal.hasConstructs(v))
return true;
if (isEnumType)
return false;
var isClassType = isMetaType(t, Class);
if (isClassType
&& !UBuiltins.isinstance(v, Enum)
&& Inspect.isclass(v)
&& Internal.hasClassName(v)
&& !Internal.hasConstructs(v))
return true;
if (isClassType)
return false;
if (try UBuiltins.isinstance(v, t) catch (e:Dynamic) false) {
return true;
}
if (Inspect.isclass(t)) {
return Boot.implementsInterface(v, t);
} else {
return false;
}
}
@:access(python.Boot)
public static function string(s:Dynamic):String {
return python.Boot.toString(s);
}
public static inline function int(x:Float):Int {
try {
return UBuiltins.int(x);
} catch (e:Dynamic) {
return null;
}
}
public static function parseInt(x:String):Null<Int> {
if (x == null)
return null;
try {
return UBuiltins.int(x);
} catch (e:Dynamic) {
var base = 10;
var len = x.length;
var foundCount = 0;
var sign = 0;
var firstDigitIndex = 0;
var lastDigitIndex = -1;
var previous = 0;
for(i in 0...len) {
var c = StringTools.fastCodeAt(x, i);
switch c {
case _ if((c > 8 && c < 14) || c == 32):
if(foundCount > 0) {
return null;
}
continue;
case '-'.code if(foundCount == 0):
sign = -1;
case '+'.code if(foundCount == 0):
sign = 1;
case '0'.code if(foundCount == 0 || (foundCount == 1 && sign != 0)):
case 'x'.code | 'X'.code if(previous == '0'.code && ((foundCount == 1 && sign == 0) || (foundCount == 2 && sign != 0))):
base = 16;
case _ if('0'.code <= c && c <= '9'.code):
case _ if(base == 16 && (('a'.code <= c && c <= 'z'.code) || ('A'.code <= c && c <= 'Z'.code))):
case _:
break;
}
if((foundCount == 0 && sign == 0) || (foundCount == 1 && sign != 0)) {
firstDigitIndex = i;
}
foundCount++;
lastDigitIndex = i;
previous = c;
}
if(firstDigitIndex <= lastDigitIndex) {
var digits = x.substring(firstDigitIndex, lastDigitIndex + 1);
return try {
(sign == -1 ? -1 : 1) * UBuiltins.int(digits, base);
} catch(e:Dynamic) {
null;
}
}
return null;
}
}
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 UBuiltins.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 {
return if (x <= 0) 0 else python.internal.UBuiltins.int(Math.random() * x);
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (C)2005-2019 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.
*/
#if !macro
import python.internal.StringImpl;
#end
@:coreApi
@:native("str")
extern class String {
var length(default, null):Int;
function new(string:String):Void;
@:runtime inline function toUpperCase():String {
return StringImpl.toUpperCase(this);
}
@:runtime inline function toLowerCase():String {
return StringImpl.toLowerCase(this);
}
inline function charAt(index:Int):String {
return StringImpl.charAt(this, index);
}
inline function charCodeAt(index:Int):Null<Int> {
return StringImpl.charCodeAt(this, index);
}
inline function indexOf(str:String, ?startIndex:Int):Int {
return StringImpl.indexOf(this, str, startIndex);
}
inline function lastIndexOf(str:String, ?startIndex:Int):Int {
return StringImpl.lastIndexOf(this, str, startIndex);
}
@:runtime inline function split(delimiter:String):Array<String> {
return StringImpl.split(this, delimiter);
}
inline function substr(pos:Int, ?len:Int):String {
return StringImpl.substr(this, pos, len);
}
inline function substring(startIndex:Int, ?endIndex:Int):String {
return StringImpl.substring(this, startIndex, endIndex);
}
inline function toString():String
return StringImpl.toString(this);
static inline function fromCharCode(code:Int):String {
return StringImpl.fromCharCode(code);
}
}

View File

@ -0,0 +1,63 @@
/*
* Copyright (C)2005-2019 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.io.IOBase.SeekSet;
import python.lib.io.StringIO;
@:coreApi
class StringBuf {
private var b:StringIO;
public inline function new():Void {
this.b = new StringIO();
}
public var length(get, never):Int;
function get_length():Int {
var pos = b.tell();
b.seek(0, SeekEnd);
var len = b.tell();
b.seek(pos, SeekSet);
return len;
}
public inline function add<T>(x:T):Void {
add1(Std.string(x));
}
inline function add1(s:String):Void {
b.write(s);
}
public inline function addChar(c:Int):Void {
add1(String.fromCharCode(c));
}
public inline function addSub(s:String, pos:Int, ?len:Int):Void {
add1((len == null ? s.substr(pos) : s.substr(pos, len)));
}
public inline function toString():String {
return b.getvalue();
}
}

View File

@ -0,0 +1,169 @@
/*
* Copyright (C)2005-2019 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.Time;
import python.lib.Os;
import sys.io.FileInput;
import sys.io.FileOutput;
import haxe.ds.StringMap;
@:coreApi
class Sys {
static var environ(get,default):StringMap<String>;
static function get_environ():StringMap<String> {
return switch environ {
case null:
var environ = new StringMap();
var env = Os.environ;
for (key in env.keys()) {
environ.set(key, env.get(key, null));
}
Sys.environ = environ;
case env: env;
}
}
public static inline function time():Float {
return Time.time();
}
public static function exit(code:Int):Void {
python.lib.Sys.exit(code);
}
public static inline function print(v:Dynamic):Void {
python.Lib.print(v);
}
public static inline function println(v:Dynamic):Void {
python.Lib.println(v);
}
public static function args():Array<String> {
var argv = python.lib.Sys.argv;
return argv.slice(1);
}
public static function getEnv(s:String):String {
return environ.get(s);
}
public static function putEnv(s:String, v:String):Void {
python.lib.Os.putenv(s, v);
environ.set(s, v);
}
public static function environment():Map<String, String> {
return environ;
}
public static function sleep(seconds:Float):Void {
python.lib.Time.sleep(seconds);
}
public static function setTimeLocale(loc:String):Bool {
return false;
}
public static function getCwd():String {
return python.lib.Os.getcwd();
}
public static function setCwd(s:String):Void {
python.lib.Os.chdir(s);
}
public static function systemName():String {
return switch (python.lib.Sys.platform) {
case var x if (StringTools.startsWith(x, "linux")):
"Linux";
case "darwin": "Mac";
case "win32" | "cygwin": "Windows";
case _:
throw "not supported platform";
}
}
public static function command(cmd:String, ?args:Array<String>):Int {
return if (args == null)
python.lib.Subprocess.call(cmd, {shell: true});
else
python.lib.Subprocess.call([cmd].concat(args));
}
public static inline function cpuTime():Float {
return python.lib.Timeit.default_timer();
}
@:deprecated("Use programPath instead") public static function executablePath():String {
return python.lib.Sys.argv[0];
}
// It has to be initialized before any call to Sys.setCwd()...
static var _programPath = sys.FileSystem.fullPath(python.lib.Inspect.getsourcefile(Sys));
public static function programPath():String {
return _programPath;
}
public static function getChar(echo:Bool):Int {
var ch = switch (systemName()) {
case "Linux" | "Mac":
var fd = python.lib.Sys.stdin.fileno();
var old = python.lib.Termios.tcgetattr(fd);
var restore = python.lib.Termios.tcsetattr.bind(fd, python.lib.Termios.TCSADRAIN, old);
try {
python.lib.Tty.setraw(fd);
var x = python.lib.Sys.stdin.read(1);
restore();
x.charCodeAt(0);
} catch (e:Dynamic) {
restore();
throw e;
}
case "Windows":
// python.lib.Msvcrt.getch().decode("utf-8").charCodeAt(0);
python.lib.Msvcrt.getwch().charCodeAt(0);
case var x:
throw "platform " + x + " not supported";
}
if (echo) {
python.Lib.print(String.fromCharCode(ch));
}
return ch;
}
public static function stdin():haxe.io.Input {
return python.io.IoTools.createFileInputFromText(python.lib.Sys.stdin);
}
public static function stdout():haxe.io.Output {
return python.io.IoTools.createFileOutputFromText(python.lib.Sys.stdout);
}
public static function stderr():haxe.io.Output {
return python.io.IoTools.createFileOutputFromText(python.lib.Sys.stderr);
}
}

View File

@ -0,0 +1,257 @@
/*
* Copyright (C)2005-2019 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.internal.AnonObject;
import python.internal.EnumImpl;
import python.internal.Internal;
import python.internal.UBuiltins;
import python.Syntax;
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 (Internal.hasClass(o)) {
return Internal.fieldClass(o);
}
if (UBuiltins.hasattr(o, "__class__")) {
return Syntax.field(o, "__class__");
} else {
return null;
}
}
public static function getEnum(o:EnumValue):Enum<Dynamic> {
if (o == null)
return null;
return Syntax.field(o, "__class__");
}
public static function getSuperClass(c:Class<Dynamic>):Class<Dynamic> {
return python.Boot.getSuperClass(c);
}
public static function getClassName(c:Class<Dynamic>):String {
if (Internal.hasClassName(c)) {
return Internal.fieldClassName(c);
} else {
// it's not a Haxe class
if (c == Array)
return "Array";
if (c == Math)
return "Math";
if (c == String)
return "String";
try {
return Syntax.field(c, "__name__");
} catch (e:Dynamic) {
return null;
}
}
}
public static function getEnumName(e:Enum<Dynamic>):String {
return Internal.fieldClassName(e);
}
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> = Internal.classRegistry().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 (Internal.hasConstructs(o)) cast o else null;
}
public static inline function createInstance<T>(cl:Class<T>, args:Array<Dynamic>):T {
return Syntax.construct(cl, Syntax.varArgs(args));
}
public static function createEmptyInstance<T>(cl:Class<T>):T {
var i = Syntax.callField(cl, "__new__", cl);
function callInit(cl) {
var sc = getSuperClass(cl);
if (sc != null) {
callInit(sc);
}
if (Internal.hasEmptyInit(cl)) {
Internal.callEmptyInit(cl, i);
}
}
callInit(cl);
return i;
}
public static function createEnum<T>(e:Enum<T>, constr:String, ?params:Array<Dynamic>):T {
var f:Dynamic = 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 = Internal.fieldConstructs(e)[index];
if (c == null)
throw index + " is not a valid enum constructor index";
return createEnum(e, c, params);
}
public static inline function getInstanceFields(c:Class<Dynamic>):Array<String> {
return python.Boot.getInstanceFields(c);
}
public static inline function getClassFields(c:Class<Dynamic>):Array<String> {
return python.Boot.getClassFields(c);
}
public static function getEnumConstructs(e:Enum<Dynamic>):Array<String> {
if (UBuiltins.hasattr(e, Internal.constructsVal())) {
var x:Array<String> = Internal.fieldConstructs(e);
return x.copy();
} else {
return [];
}
}
public static function typeof(v:Dynamic):ValueType {
if (v == null) {
return TNull;
} else if (UBuiltins.isinstance(v, UBuiltins.bool)) {
return TBool;
} else if (UBuiltins.isinstance(v, UBuiltins.int)) {
return TInt;
} else if (UBuiltins.isinstance(v, UBuiltins.float)) {
return TFloat;
} else if (UBuiltins.isinstance(v, String)) {
return TClass(String);
} else if (UBuiltins.isinstance(v, Array)) {
return TClass(Array);
} else if (UBuiltins.isinstance(v, AnonObject) || python.lib.Inspect.isclass(v)) {
return TObject;
} else if (UBuiltins.isinstance(v, Enum)) {
return TEnum(Syntax.field(v, "__class__"));
} else if (UBuiltins.isinstance(v, UBuiltins.type) || Internal.hasClass(v)) {
return TClass(Syntax.field(v, "__class__"));
} else if (UBuiltins.callable(v)) {
return TFunction;
} else {
return TUnknown;
}
}
static inline function asEnumImpl(x:Dynamic):EnumImpl {
return (cast x : EnumImpl);
}
public static function enumEq<T>(a:T, b:T):Bool {
if (a == b)
return true;
try {
if (b == null && a != b)
return false;
if (asEnumImpl(a).tag != asEnumImpl(b).tag)
return false;
var p1 = asEnumImpl(a).params;
var p2 = asEnumImpl(b).params;
if (p1.length != p2.length)
return false;
for (i in 0...p1.length)
if (!enumEq(p1[i], p2[i]))
return false;
if (Internal.fieldClass(a) != Internal.fieldClass(b))
return false;
} catch (e:Dynamic) {
return false;
}
return true;
}
public static inline function enumConstructor(e:EnumValue):String {
return asEnumImpl(e).tag;
}
public static inline function enumParameters(e:EnumValue):Array<Dynamic> {
return asEnumImpl(e).params.toArray();
}
public static inline function enumIndex(e:EnumValue):Int {
return asEnumImpl(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.isOfType(v, e))
ret.push(v);
}
return ret;
}
}

View File

@ -0,0 +1,94 @@
package haxe;
import python.Exceptions.BaseException;
import python.Exceptions.Exception in PyException;
import python.lib.Traceback;
import python.internal.UBuiltins;
private typedef PyStackItem = python.Tuple.Tuple4<String, Int, String, String>;
@:coreApi
class Exception extends PyException {
public var message(get,never):String;
public var stack(get,never):CallStack;
public var previous(get,never):Null<Exception>;
public var native(get,never):Any;
@:noCompletion var __exceptionStack:Null<CallStack>;
@:noCompletion var __nativeStack:Array<PyStackItem>;
@:noCompletion @:ifFeature("haxe.Exception.get_stack") var __skipStack:Int = 0;
@:noCompletion var __nativeException:BaseException;
@:noCompletion var __previousException:Null<Exception>;
static function caught(value:Any):Exception {
if(Std.isOfType(value, Exception)) {
return value;
} else if(Std.isOfType(value, BaseException)) {
return new Exception(UBuiltins.str(value), null, value);
} else {
return new ValueException(value, null, value);
}
}
static function thrown(value:Any):Any {
if(Std.isOfType(value, Exception)) {
return (value:Exception).native;
} else if(Std.isOfType(value, BaseException)) {
return value;
} else {
var e = new ValueException(value);
e.__shiftStack();
return e;
}
}
public function new(message:String, ?previous:Exception, ?native:Any) {
super(message);
this.__previousException = previous;
if(native != null && Std.isOfType(native, BaseException)) {
__nativeException = native;
__nativeStack = NativeStackTrace.exceptionStack();
} else {
__nativeException = cast this;
__nativeStack = NativeStackTrace.callStack();
}
}
function unwrap():Any {
return __nativeException;
}
public function toString():String {
return message;
}
public function details():String {
return inline CallStack.exceptionToString(this);
}
@:noCompletion
@:ifFeature("haxe.Exception.get_stack")
inline function __shiftStack():Void {
__skipStack++;
}
function get_message():String {
return UBuiltins.str(this);
}
function get_previous():Null<Exception> {
return __previousException;
}
final function get_native():Any {
return __nativeException;
}
function get_stack():CallStack {
return switch __exceptionStack {
case null:
__exceptionStack = NativeStackTrace.toHaxe(__nativeStack, __skipStack);
case s: s;
}
}
}

View File

@ -0,0 +1,35 @@
/*
* Copyright (C)2005-2019 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;
import python.Syntax;
class Json {
public static inline function parse(text:String):Dynamic {
return python.lib.Json.loads(text, {object_hook: python.Lib.dictToAnon});
}
public static inline function stringify(value:Dynamic, ?replacer:(key:Dynamic, value:Dynamic) -> Dynamic, ?space:String):String {
return haxe.format.JsonPrinter.print(value, replacer, space);
}
}

View File

@ -0,0 +1,46 @@
package haxe;
import haxe.CallStack.StackItem;
private typedef NativeTrace = Array<python.Tuple.Tuple4<String, Int, String, String>>;
/**
Do not use manually.
**/
@:dox(hide)
@:noCompletion
class NativeStackTrace {
@:ifFeature('haxe.NativeStackTrace.exceptionStack')
static public inline function saveStack(exception:Any):Void {
}
static public inline function callStack():NativeTrace {
var infos = python.lib.Traceback.extract_stack();
infos.pop();
infos.reverse();
return infos;
}
static public function exceptionStack():NativeTrace {
var exc = python.lib.Sys.exc_info();
if (exc._3 != null) {
var infos = python.lib.Traceback.extract_tb(exc._3);
infos.reverse();
return infos;
} else {
return [];
}
}
static public function toHaxe(native:NativeTrace, skip:Int = 0):Array<StackItem> {
var stack = [];
for(i in 0...native.length) {
if(skip > i) {
continue;
}
var elem = native[i];
stack.push(FilePos(Method(null, elem._3), elem._1, elem._2));
}
return stack;
}
}

View File

@ -0,0 +1,54 @@
/*
* Copyright (C)2005-2019 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;
import haxe.io.Bytes;
import haxe.io.BytesData;
@:coreApi class Resource {
static var content:python.Dict<String, BytesData>;
static function getContent():python.Dict<String, BytesData> {
if (content == null)
content = untyped _hx_resources__();
return content;
}
public static inline function listNames():Array<String> {
return python.internal.UBuiltins.list(getContent().keys());
}
public static function getString(name:String):String {
var bytes = getBytes(name);
if (bytes != null)
return bytes.toString();
return null;
}
public static function getBytes(name:String):haxe.io.Bytes {
var data = getContent().get(name, null);
if (data == null)
return null;
return Bytes.ofData(data);
}
}

View File

@ -0,0 +1,91 @@
/*
* Copyright (C)2005-2019 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;
import python.Dict;
import python.Syntax;
class IntMap<T> implements haxe.Constraints.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;
Syntax.delete(Syntax.arrayAccess(h, key));
return true;
}
public function keys():Iterator<Int> {
return h.keys().iter();
}
public function iterator():Iterator<T> {
return h.values().iter();
}
@:runtime public inline function keyValueIterator():KeyValueIterator<Int, T> {
return new haxe.iterators.MapKeyValueIterator(this);
}
public function copy():IntMap<T> {
var copied = new IntMap();
for (key in keys())
copied.set(key, get(key));
return copied;
}
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();
}
public inline function clear():Void {
h.clear();
}
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (C)2005-2019 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;
import python.Dict;
class ObjectMap<K:{}, V> implements haxe.Constraints.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();
}
@:runtime public inline function keyValueIterator():KeyValueIterator<K, V> {
return new haxe.iterators.MapKeyValueIterator(this);
}
public function copy():ObjectMap<K, V> {
var copied = new ObjectMap();
for (key in keys())
copied.set(key, get(key));
return copied;
}
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();
}
public inline function clear():Void {
h.clear();
}
}

View File

@ -0,0 +1,92 @@
/*
* Copyright (C)2005-2019 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;
import python.Syntax;
import python.Dict;
class StringMap<T> implements haxe.Constraints.IMap<String, T> {
private var h:Dict<String, T>;
public function new():Void {
h = new Dict();
}
public inline function set(key:String, value:T):Void {
h.set(key, value);
}
public inline function get(key:String):Null<T> {
return h.get(key, null);
}
public inline function exists(key:String):Bool {
return h.hasKey(key);
}
public function remove(key:String):Bool {
var has = h.hasKey(key);
if (has)
h.remove(key);
return has;
}
public function keys():Iterator<String> {
return h.keys().iter();
}
public function iterator():Iterator<T> {
return h.values().iter();
}
@:runtime public inline function keyValueIterator():KeyValueIterator<String, T> {
return new haxe.iterators.MapKeyValueIterator(this);
}
public function copy():StringMap<T> {
var copied = new StringMap();
for (key in keys())
copied.set(key, get(key));
return copied;
}
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();
}
public inline function clear():Void {
h.clear();
}
}

View File

@ -0,0 +1,84 @@
/*
* Copyright (C)2005-2019 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 sys;
import python.lib.Os;
import python.lib.os.Path;
@:coreApi
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(1000 * s.st_atime),
mtime: Date.fromTime(1000 * s.st_mtime),
ctime: Date.fromTime(1000 * s.st_ctime),
size: s.st_size,
dev: s.st_dev,
ino: s.st_ino,
nlink: s.st_nlink,
rdev: python.internal.UBuiltins.getattr(s, "st_rdev", 0), // st_rdev is not available on Windows
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.realpath(relPath);
}
public static function absolutePath(relPath:String):String {
if (haxe.io.Path.isAbsolute(relPath))
return relPath;
return haxe.io.Path.join([Sys.getCwd(), relPath]);
}
public static function isDirectory(path:String):Bool {
return Path.isdir(path);
}
public static function createDirectory(path:String):Void {
Os.makedirs(path, 511, true);
}
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);
}
}

View File

@ -0,0 +1,92 @@
/*
* Copyright (C)2005-2019 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 sys.io;
import python.io.IoTools;
import sys.io.FileInput;
@:coreApi
class File {
public static function getContent(path:String):String {
var f:python.lib.io.TextIOBase = cast python.lib.Builtins.open(path, "r", -1, "utf-8", null, "");
var content = f.read(-1);
f.close();
return content;
}
public static function saveContent(path:String, content:String):Void {
var f:python.lib.io.TextIOBase = cast python.lib.Builtins.open(path, "w", -1, "utf-8", null, "");
f.write(content);
f.close();
}
public static function getBytes(path:String):haxe.io.Bytes {
var f:python.lib.io.RawIOBase = cast python.lib.Builtins.open(path, "rb", -1);
var size = f.read(-1);
var b = haxe.io.Bytes.ofData(size);
f.close();
return b;
}
public static function saveBytes(path:String, bytes:haxe.io.Bytes):Void {
var f:python.lib.io.RawIOBase = cast python.lib.Builtins.open(path, "wb", -1);
f.write(bytes.getData());
f.close();
}
public static function read(path:String, binary:Bool = true):FileInput {
var mode = if (binary) "rb" else "r";
var f = python.lib.Builtins.open(path, mode, -1, null, null, binary ? null : "");
return if (binary) IoTools.createFileInputFromBytes(cast f) else IoTools.createFileInputFromText(cast f);
}
public static function write(path:String, binary:Bool = true):FileOutput {
var mode = if (binary) "wb" else "w";
var f = python.lib.Builtins.open(path, mode, -1, null, null, binary ? null : "");
return if (binary) IoTools.createFileOutputFromBytes(cast f) else IoTools.createFileOutputFromText(cast f);
}
public static function append(path:String, binary:Bool = true):FileOutput {
var mode = if (binary) "ab" else "a";
var f = python.lib.Builtins.open(path, mode, -1, null, null, binary ? null : "");
return if (binary) IoTools.createFileOutputFromBytes(cast f) else IoTools.createFileOutputFromText(cast f);
}
public static function update(path:String, binary:Bool = true):FileOutput {
if (!FileSystem.exists(path)) {
write(path).close();
}
var mode = if (binary) "rb+" else "r+";
var f = python.lib.Builtins.open(path, mode, -1, null, null, binary ? null : "");
return if (binary) IoTools.createFileOutputFromBytes(cast f) else IoTools.createFileOutputFromText(cast f);
}
public static function copy(srcPath:String, dstPath:String):Void {
return python.lib.Shutil.copy(srcPath, dstPath);
}
}

View File

@ -0,0 +1,120 @@
/*
* Copyright (C)2005-2019 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 sys.io;
import haxe.io.Bytes;
import haxe.io.Encoding;
import haxe.io.Input;
import python.io.IFileInput;
class FileInput extends Input {
var impl:IFileInput;
function new(impl:IFileInput) {
this.impl = impl;
}
override public function set_bigEndian(b:Bool) {
return impl.bigEndian = b;
}
public function seek(p:Int, pos:FileSeek):Void {
return impl.seek(p, pos);
}
public function tell():Int {
return impl.tell();
}
public function eof():Bool {
return impl.eof();
}
override public function readByte():Int {
return impl.readByte();
}
override public function readBytes(s:Bytes, pos:Int, len:Int):Int {
return impl.readBytes(s, pos, len);
}
override public function close():Void {
impl.close();
}
override public function readAll(?bufsize:Int):Bytes {
return impl.readAll(bufsize);
}
override public function readFullBytes(s:Bytes, pos:Int, len:Int):Void {
impl.readFullBytes(s, pos, len);
}
override public function read(nbytes:Int):Bytes {
return impl.read(nbytes);
}
override public function readUntil(end:Int):String {
return impl.readUntil(end);
}
override public function readLine():String {
return impl.readLine();
}
override public function readFloat():Float {
return impl.readFloat();
}
override public function readDouble():Float {
return impl.readDouble();
}
override public function readInt8():Int {
return impl.readInt8();
}
override public function readInt16():Int {
return impl.readInt16();
}
override public function readUInt16():Int {
return impl.readUInt16();
}
override public function readInt24():Int {
return impl.readInt24();
}
override public function readUInt24():Int {
return impl.readUInt24();
}
override public function readInt32():Int {
return impl.readInt32();
}
override public function readString(len:Int, ?encoding:Encoding):String {
return impl.readString(len);
}
}

View File

@ -0,0 +1,117 @@
/*
* Copyright (C)2005-2019 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 sys.io;
import haxe.io.Bytes;
import haxe.io.Encoding;
import haxe.io.Input;
import haxe.io.Output;
import python.io.IFileOutput;
class FileOutput extends Output {
var impl:IFileOutput;
function new(impl:IFileOutput) {
this.impl = impl;
}
public function seek(p:Int, pos:FileSeek):Void {
return impl.seek(p, pos);
}
public function tell():Int {
return impl.tell();
}
override public function set_bigEndian(b:Bool) {
return impl.bigEndian = b;
}
override public function writeByte(c:Int):Void {
impl.writeByte(c);
}
override public function writeBytes(s:Bytes, pos:Int, len:Int):Int {
return impl.writeBytes(s, pos, len);
}
override public function flush():Void {
impl.flush();
}
override public function close():Void {
impl.close();
}
override public function write(s:Bytes):Void {
impl.write(s);
}
override public function writeFullBytes(s:Bytes, pos:Int, len:Int):Void {
impl.writeFullBytes(s, pos, len);
}
override public function writeFloat(x:Float):Void {
impl.writeFloat(x);
}
override public function writeDouble(x:Float):Void {
impl.writeDouble(x);
}
override public function writeInt8(x:Int):Void {
impl.writeInt8(x);
}
override public function writeInt16(x:Int):Void {
impl.writeInt16(x);
}
override public function writeUInt16(x:Int):Void {
impl.writeUInt16(x);
}
override public function writeInt24(x:Int):Void {
impl.writeInt24(x);
}
override public function writeUInt24(x:Int):Void {
impl.writeUInt24(x);
}
override public function writeInt32(x:Int):Void {
impl.writeInt32(x);
}
override public function prepare(nbytes:Int):Void {
impl.prepare(nbytes);
}
override public function writeInput(i:Input, ?bufsize:Int):Void {
impl.writeInput(i, bufsize);
}
override public function writeString(s:String, ?encoding:Encoding):Void {
impl.writeString(s);
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright (C)2005-2019 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 sys.io;
import python.io.IoTools;
import python.lib.io.BufferedReader;
import python.lib.io.BufferedWriter;
import python.lib.io.TextIOWrapper;
import python.lib.Subprocess;
import python.lib.subprocess.Popen;
class Process {
public var stdout(default, null):haxe.io.Input;
public var stderr(default, null):haxe.io.Input;
public var stdin(default, null):haxe.io.Output;
var p:Popen;
public function new(cmd:String, ?args:Array<String>, ?detached:Bool):Void {
if (detached)
throw "Detached process is not supported on this platform";
p = Popen.create(args == null ? cmd : [cmd].concat(args), {
shell: args == null,
stdin: Subprocess.PIPE,
stdout: Subprocess.PIPE,
stderr: Subprocess.PIPE
});
this.stdout = IoTools.createFileInputFromText(new TextIOWrapper(new BufferedReader(p.stdout)));
this.stderr = IoTools.createFileInputFromText(new TextIOWrapper(new BufferedReader(p.stderr)));
this.stdin = IoTools.createFileOutputFromText(new TextIOWrapper(new BufferedWriter(p.stdin)));
}
public function getPid():Int {
return p.pid;
}
public function exitCode(block:Bool = true):Null<Int> {
if (block == false)
return p.poll();
return p.wait();
}
public function close():Void {
var ver = python.lib.Sys.version_info;
if (ver[0] > 3 || (ver[0] == 3 && ver[1] >= 3)) // >= 3.3
try {
p.terminate();
} catch (e:python.Exceptions.ProcessLookupError) {
// it has already terminated
}
else
try {
p.terminate();
} catch (e:python.Exceptions.OSError) {
// it has already terminated
}
}
public function kill():Void {
p.kill();
}
}

View File

@ -0,0 +1,47 @@
/*
* Copyright (C)2005-2019 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 sys.net;
class Host {
public var host(default, null):String;
public var ip(default, null):Int;
var name:String;
public function new(name:String):Void {
host = name;
this.name = name;
}
public function toString():String {
return name;
}
public function reverse():String {
return "";
}
public static function localhost():String {
return "";
}
}

View File

@ -0,0 +1,201 @@
/*
* Copyright (C)2005-2019 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 sys.net;
import haxe.io.Error;
import haxe.io.Bytes;
import haxe.io.BytesData;
import python.Exceptions;
import python.Tuple;
import python.lib.socket.Socket in PSocket;
import python.lib.Socket in PSocketModule;
import python.lib.socket.Address in PAddress;
import python.lib.Select;
private class SocketInput extends haxe.io.Input {
var __s:PSocket;
public function new(s) {
__s = s;
}
public override function readByte():Int {
var r:BytesData;
try {
r = __s.recv(1, 0);
} catch (e:BlockingIOError) {
throw Blocked;
}
if (r.length == 0)
throw new haxe.io.Eof();
return python.Syntax.code("r[0]");
}
public override function readBytes(buf:haxe.io.Bytes, pos:Int, len:Int):Int {
var r;
var data = buf.getData();
try {
r = __s.recv(len, 0);
for (i in pos...(pos + r.length)) {
data.set(i, r[i - pos]);
}
} catch (e:BlockingIOError) {
throw Blocked;
}
if (r.length == 0)
throw new haxe.io.Eof();
return r.length;
}
public override function close() {
super.close();
if (__s != null)
__s.close();
}
}
private class SocketOutput extends haxe.io.Output {
var __s:PSocket;
public function new(s) {
__s = s;
}
public override function writeByte(c:Int) {
try {
__s.send(python.Syntax.code('bytes([c])'), 0);
} catch (e:BlockingIOError) {
throw Blocked;
}
}
public override function writeBytes(buf:haxe.io.Bytes, pos:Int, len:Int):Int {
try {
var data = buf.getData();
var payload = python.Syntax.code("{0}[{1}:{1}+{2}]", data, pos, len);
var r = __s.send(payload, 0);
return r;
} catch (e:BlockingIOError) {
throw Blocked;
}
}
public override function close() {
super.close();
if (__s != null)
__s.close();
}
}
@:coreApi class Socket {
var __s:PSocket;
public var input(default, null):haxe.io.Input;
public var output(default, null):haxe.io.Output;
public var custom:Dynamic;
public function new():Void {
__initSocket();
input = new SocketInput(__s);
output = new SocketOutput(__s);
}
function __initSocket():Void {
__s = new PSocket();
}
public function close():Void {
__s.close();
}
public function read():String {
return input.readAll().toString();
}
public function write(content:String):Void {
output.writeString(content);
}
public function connect(host:Host, port:Int):Void {
var host_str = host.toString();
__s.connect(Tuple2.make(host_str, port));
}
public function listen(connections:Int):Void {
__s.listen(connections);
}
public function shutdown(read:Bool, write:Bool):Void
__s.shutdown((read && write) ? PSocketModule.SHUT_RDWR : read ? PSocketModule.SHUT_RD : PSocketModule.SHUT_WR);
public function bind(host:Host, port:Int):Void {
var host_str = host.toString();
__s.bind(Tuple2.make(host_str, port));
}
public function accept():Socket {
var tp2:Tuple2<PSocket, PAddress> = __s.accept();
var s = new Socket();
s.__s = tp2._1;
s.input = new SocketInput(s.__s);
s.output = new SocketOutput(s.__s);
return s;
}
public function peer():{host:Host, port:Int} {
var pn = __s.getpeername();
return {host: new Host(pn._1), port: pn._2}
}
public function host():{host:Host, port:Int} {
var pn = __s.getsockname();
return {host: new Host(pn._1), port: pn._2};
}
public function setTimeout(timeout:Float):Void {
__s.settimeout(timeout);
}
public function waitForRead():Void {
Select.select([this], [], []);
}
public function setBlocking(b:Bool):Void {
__s.setblocking(b);
}
public function setFastSend(b:Bool):Void {
__s.setsockopt(PSocketModule.SOL_TCP, PSocketModule.TCP_NODELAY, b);
}
@:keep function fileno():Int
return __s.fileno();
public static function select(read:Array<Socket>, write:Array<Socket>, others:Array<Socket>,
?timeout:Float):{read:Array<Socket>, write:Array<Socket>, others:Array<Socket>} {
var t3 = Select.select(read, write, others, timeout);
return {read: t3._1, write: t3._2, others: t3._3};
}
}

View File

@ -0,0 +1,83 @@
/*
* Copyright (C)2005-2019 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 sys.thread;
using python.internal.UBuiltins;
class Deque<T> {
var deque:NativeDeque<T>;
var lock:NativeCondition;
public function new() {
deque = new NativeDeque<T>();
lock = new NativeCondition();
}
public function add(i:T) {
lock.acquire();
deque.append(i);
lock.notify();
lock.release();
}
public function push(i:T) {
lock.acquire();
deque.appendleft(i);
lock.notify();
lock.release();
}
public function pop(block:Bool):Null<T> {
var ret = null;
lock.acquire();
if (block) {
lock.wait_for(() -> deque.bool());
ret = deque.popleft();
} else if (deque.bool()) {
ret = deque.popleft();
}
lock.release();
return ret;
}
}
@:pythonImport("collections", "deque")
@:native("deque")
extern class NativeDeque<T> {
function new();
function append(x:T):Void;
function appendleft(x:T):Void;
function popleft():T;
}
@:pythonImport("threading", "Condition")
@:native("Condition")
private extern class NativeCondition {
function new(?lock:Dynamic);
function acquire(blocking:Bool = true, timeout:Float = -1):Bool;
function release():Void;
function wait(?timeout:Float):Bool;
function wait_for(predicate:()->Bool, ?timeout:Float):Bool;
function notify(n:Int = 1):Void;
function notify_all():Void;
}

View File

@ -0,0 +1,48 @@
/*
* Copyright (C)2005-2019 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 sys.thread;
@:coreApi
class Lock {
final semaphore:NativeSemaphore;
public inline function new() {
semaphore = new NativeSemaphore(0);
}
public inline function wait(?timeout:Float):Bool {
return semaphore.acquire(true, timeout);
}
public inline function release():Void {
semaphore.release();
}
}
@:pythonImport("threading", "Semaphore")
@:native("Lock")
private extern class NativeSemaphore {
function new(value:Int);
function acquire(blocking:Bool = true, ?timeout:Float):Bool;
function release():Void;
}

View File

@ -0,0 +1,51 @@
/*
* Copyright (C)2005-2019 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 sys.thread;
@:coreApi
class Mutex {
final lock:NativeRLock;
inline public function new():Void {
lock = new NativeRLock();
}
inline public function acquire():Void {
lock.acquire(true);
}
inline public function tryAcquire():Bool {
return lock.acquire(false);
}
inline public function release():Void {
lock.release();
}
}
@:pythonImport("threading", "RLock")
private extern class NativeRLock {
function new():Void;
function acquire(blocking:Bool):Bool;
function release():Void;
}

View File

@ -0,0 +1,175 @@
/*
* Copyright (C)2005-2019 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 sys.thread;
import haxe.ds.ObjectMap;
private typedef ThreadImpl = HxThread;
abstract Thread(ThreadImpl) from ThreadImpl {
public var events(get,never):EventLoop;
public static inline function current():Thread {
return HxThread.current();
}
public static inline function create(callb:Void->Void):Thread {
return HxThread.create(callb, false);
}
public static inline function runWithEventLoop(job:()->Void):Void {
HxThread.runWithEventLoop(job);
}
public static inline function createWithEventLoop(job:()->Void):Thread {
return HxThread.create(job, true);
}
public static inline function readMessage(block:Bool):Dynamic {
return HxThread.readMessage(block);
}
public inline function sendMessage(msg:Dynamic):Void {
this.sendMessage(msg);
}
function get_events():EventLoop {
if(this.events == null)
throw new NoEventLoopException();
return this.events;
}
@:keep
static public function processEvents() {
HxThread.current().events.loop();
}
}
private class HxThread {
public var events(default,null):Null<EventLoop>;
final nativeThread:NativeThread;
final messages = new Deque<Dynamic>();
static var threads:ObjectMap<NativeThread, HxThread>;
static var threadsMutex:Mutex;
static var mainThread:HxThread;
static function __init__() {
threads = new ObjectMap();
threadsMutex = new Mutex();
mainThread = new HxThread(PyThreadingAPI.current_thread());
mainThread.events = new EventLoop();
}
private function new(t:NativeThread) {
nativeThread = t;
}
public function sendMessage(msg:Dynamic):Void {
messages.add(msg);
}
public static function current():HxThread {
threadsMutex.acquire();
var ct = PyThreadingAPI.current_thread();
if (ct == PyThreadingAPI.main_thread()) {
threadsMutex.release();
return mainThread;
}
// If the current thread was not created via the haxe API, it can still be wrapped
if (!threads.exists(ct)) {
threads.set(ct, new HxThread(ct));
}
var t = threads.get(ct);
threadsMutex.release();
return t;
}
public static function create(callb:Void->Void, withEventLoop:Bool):HxThread {
var nt:NativeThread = null;
var t:HxThread = null;
// Wrap the callback so it will clear the thread reference once the thread is finished
var wrappedCallB = () -> {
try {
callb();
if(withEventLoop)
t.events.loop();
} catch(e) {
dropThread(nt);
throw e;
}
dropThread(nt);
}
nt = new NativeThread(null, wrappedCallB);
t = new HxThread(nt);
if(withEventLoop)
t.events = new EventLoop();
threadsMutex.acquire();
threads.set(nt, t);
threadsMutex.release();
nt.start();
return t;
}
public static function runWithEventLoop(job:()->Void):Void {
var thread = current();
if(thread.events == null) {
thread.events = new EventLoop();
try {
job();
thread.events.loop();
thread.events = null;
} catch(e) {
thread.events = null;
throw e;
}
} else {
job();
}
}
static inline function dropThread(nt:NativeThread) {
threadsMutex.acquire();
threads.remove(nt);
threadsMutex.release();
}
public static function readMessage(block:Bool):Dynamic {
return current().messages.pop(block);
}
}
@:pythonImport("threading", "Thread")
@:native("Thread")
private extern class NativeThread {
function new(group:Dynamic, target:Void->Void);
function start():Void;
}
@:pythonImport("threading")
@:native("threading")
private extern class PyThreadingAPI {
static function current_thread():NativeThread;
static function main_thread():NativeThread;
}

View File

@ -0,0 +1,30 @@
/*
* Copyright (C)2005-2019 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 sys.thread;
@:pythonImport("threading", "local")
@:native("local")
extern class Tls<T> {
function new():Void;
var value(default, default):T;
}

View File

@ -0,0 +1,28 @@
/*
* Copyright (C)2005-2019 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 python.internal;
@:native("_hx_AnonObject")
class AnonObject {
public function new(fields:python.Dict<String, Dynamic>) {}
}

View File

@ -0,0 +1,206 @@
/*
* Copyright (C)2005-2019 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 python.internal;
import python.lib.Functools;
@:allow(Array)
class ArrayImpl {
@:ifFeature("dynamic_read.length", "anon_optional_read.length", "python.internal.ArrayImpl.length")
public static inline function get_length<T>(x:Array<T>):Int
return UBuiltins.len(x);
@:ifFeature("dynamic_read.concat", "anon_optional_read.concat", "python.internal.ArrayImpl.concat")
public static inline function concat<T>(a1:Array<T>, a2:Array<T>):Array<T> {
return Syntax.binop(a1, "+", a2);
}
@:ifFeature("dynamic_read.copy", "anon_optional_read.copy", "python.internal.ArrayImpl.copy")
public static inline function copy<T>(x:Array<T>):Array<T> {
return UBuiltins.list(x);
}
@:ifFeature("dynamic_read.iterator", "anon_optional_read.iterator", "python.internal.ArrayImpl.iterator")
public static inline function iterator<T>(x:Array<T>):Iterator<T> {
return new HaxeIterator(Syntax.callField(x, "__iter__"));
}
@:ifFeature("dynamic_read.keyValueIterator", "anon_optional_read.keyValueIterator", "python.internal.ArrayImpl.keyValueIterator")
public static inline function keyValueIterator<T>(x:Array<T>) : KeyValueIterator<Int, T> {
return new haxe.iterators.ArrayKeyValueIterator(x);
}
@:ifFeature("dynamic_read.indexOf", "anon_optional_read.indexOf", "python.internal.ArrayImpl.indexOf")
public static function indexOf<T>(a:Array<T>, x:T, ?fromIndex:Int):Int {
var len = a.length;
var l = if (fromIndex == null) 0 else if (fromIndex < 0) len + fromIndex else fromIndex;
if (l < 0)
l = 0;
for (i in l...len) {
if (unsafeGet(a, i) == x)
return i;
}
return -1;
}
@:ifFeature("dynamic_read.lastIndexOf", "anon_optional_read.lastIndexOf", "python.internal.ArrayImpl.lastIndexOf")
public static function lastIndexOf<T>(a:Array<T>, x:T, ?fromIndex:Int):Int {
var len = a.length;
var l = if (fromIndex == null) len else if (fromIndex < 0) len + fromIndex + 1 else fromIndex + 1;
if (l > len)
l = len;
while (--l > -1) {
if (unsafeGet(a, l) == x)
return l;
}
return -1;
}
@:access(python.Boot)
@:ifFeature("dynamic_read.join", "anon_optional_read.join", "python.internal.ArrayImpl.join")
public static inline function join<T>(x:Array<T>, sep:String):String {
return Boot.arrayJoin(x, sep);
}
@:ifFeature("dynamic_read.toString", "anon_optional_read.toString", "python.internal.ArrayImpl.toString")
public static inline function toString<T>(x:Array<T>):String {
return "[" + join(x, ",") + "]";
}
@:ifFeature("dynamic_read.pop", "anon_optional_read.pop", "python.internal.ArrayImpl.pop")
public static inline function pop<T>(x:Array<T>):Null<T> {
return if (x.length == 0) null else Syntax.callField(x, "pop");
}
@:ifFeature("dynamic_read.push", "anon_optional_read.push", "python.internal.ArrayImpl.push")
public static inline function push<T>(x:Array<T>, e:T):Int {
Syntax.callField(x, "append", e);
return x.length;
}
@:ifFeature("dynamic_read.unshift", "anon_optional_read.unshift", "python.internal.ArrayImpl.unshift")
public static inline function unshift<T>(x:Array<T>, e:T):Void {
x.insert(0, e);
}
@:ifFeature("dynamic_read.remove", "anon_optional_read.remove", "python.internal.ArrayImpl.remove")
public static function remove<T>(x:Array<T>, e:T):Bool {
try {
Syntax.callField(x, "remove", e);
return true;
} catch (e:Dynamic) {
return false;
}
}
@:ifFeature("dynamic_read.contains", "anon_optional_read.contains", "python.internal.ArrayImpl.contains")
public static inline function contains<T>(x:Array<T>,e : T) : Bool {
return Syntax.isIn(e, x);
}
@:ifFeature("dynamic_read.shift", "anon_optional_read.shift", "python.internal.ArrayImpl.shift")
public static inline function shift<T>(x:Array<T>):Null<T> {
if (x.length == 0)
return null;
return Syntax.callField(x, "pop", 0);
}
@:ifFeature("dynamic_read.slice", "anon_optional_read.slice", "python.internal.ArrayImpl.slice")
public static inline function slice<T>(x:Array<T>, pos:Int, ?end:Int):Array<T> {
return Syntax.arrayAccess(x, pos, end);
}
@:ifFeature("dynamic_read.sort", "anon_optional_read.sort", "python.internal.ArrayImpl.sort")
public static inline function sort<T>(x:Array<T>, f:T->T->Int):Void {
Syntax.callNamedUntyped(Syntax.field(x, "sort"), {key: Functools.cmp_to_key(f)});
}
@:ifFeature("dynamic_read.splice", "anon_optional_read.splice", "python.internal.ArrayImpl.splice")
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 = Syntax.arrayAccess(x, pos, pos + len);
Syntax.delete((Syntax.arrayAccess(x, pos, pos + len)));
return res;
}
@:ifFeature("dynamic_read.map", "anon_optional_read.map", "python.internal.ArrayImpl.map")
public static inline function map<S, T>(x:Array<T>, f:T->S):Array<S> {
return UBuiltins.list(UBuiltins.map(f, cast x));
}
@:ifFeature("dynamic_read.filter", "anon_optional_read.filter", "python.internal.ArrayImpl.filter")
public static inline function filter<T>(x:Array<T>, f:T->Bool):Array<T> {
return UBuiltins.list(UBuiltins.filter(f, cast x));
}
@:ifFeature("dynamic_read.insert", "anon_optional_read.insert", "python.internal.ArrayImpl.insert")
public static inline function insert<T>(a:Array<T>, pos:Int, x:T):Void {
Syntax.callField(a, "insert", pos, x);
}
@:ifFeature("dynamic_read.reverse", "anon_optional_read.reverse", "python.internal.ArrayImpl.reverse")
public static inline function reverse<T>(a:Array<T>):Void {
Syntax.callField(a, "reverse");
}
@:ifFeature("array_read")
private static inline function _get<T>(x:Array<T>, idx:Int):T {
return if (idx > -1 && idx < x.length) unsafeGet(x, idx) else null;
}
@:ifFeature("array_write")
private static inline function _set<T>(x:Array<T>, idx:Int, v:T):T {
var l = x.length;
while (l < idx) {
x.push(null);
l += 1;
}
if (l == idx) {
x.push(v);
} else {
Syntax.assign(Syntax.arrayAccess(x, idx), v);
}
return v;
}
public static inline function unsafeGet<T>(x:Array<T>, idx:Int):T {
return Syntax.arrayAccess(x, idx);
}
public static inline function unsafeSet<T>(x:Array<T>, idx:Int, val:T):T {
Syntax.assign(Syntax.arrayAccess(x, idx), val);
return val;
}
public static inline function resize<T>(x:Array<T>, len:Int):Void {
var l = x.length;
if (l < len) {
_set(x, len - 1, null);
} else if (l > len) {
splice(x, len, l - len);
}
}
}

View File

@ -0,0 +1,52 @@
/*
* Copyright (C)2005-2019 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 python.internal;
@:ifFeature("has_enum", "Enum.*")
@:native("Enum")
class EnumImpl {
@:ifFeature("has_enum", "Enum.*")
public var tag:String;
@:ifFeature("has_enum", "Enum.*")
public var index:Int;
@:ifFeature("has_enum", "Enum.*")
public var params:Tuple<Dynamic>;
@:ifFeature("has_enum", "Enum.*")
public function new(tag, index, params) {
this.tag = tag;
this.index = index;
this.params = params;
}
@:ifFeature("has_enum", "Enum.*")
function __str__() {
return if (params == null) {
tag;
} else {
python.Syntax.code("{0} + '(' + (', '.join(str(v) for v in {1})) + ')'", tag, params);
}
}
}

View File

@ -0,0 +1,229 @@
/*
* Copyright (C)2005-2019 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 python.internal;
import python.Syntax;
import python.Syntax.code in py;
@:noDoc
@:native("HxOverrides")
@:access(python.internal.ArrayImpl)
@:access(python.Boot)
class HxOverrides {
// this two cases iterator and shift are like all methods in String and Array and are already handled in Reflect
// we need to modify the transformer to call Reflect directly
@:ifFeature("dynamic_read.iterator", "anon_optional_read.iterator", "anon_read.iterator")
static public function iterator(x) {
if (Boot.isArray(x)) {
return (x : Array<Dynamic>).iterator();
}
return Syntax.callField(x, "iterator");
}
@:ifFeature("dynamic_read.keyValueIterator", "anon_optional_read.keyValueIterator", "anon_read.keyValueIterator")
static public function keyValueIterator(x) {
if (Boot.isArray(x)) {
return (x:Array<Dynamic>).keyValueIterator();
}
return Syntax.callField(x, "keyValueIterator");
}
@:ifFeature("dynamic_binop_==", "dynamic_binop_!=", "type_param_binop_==", "type_param_binop_!=")
static function eq(a:Dynamic, b:Dynamic):Bool {
if (Boot.isArray(a) || Boot.isArray(b)) {
return Syntax.code('a is b');
}
return Syntax.binop(a, "==", b);
}
@:ifFeature("unsafe_string_concat")
static function stringOrNull(s:String):String {
return if (s == null) "null" else s;
}
@:ifFeature("dynamic_read.shift", "anon_optional_read.shift", "anon_read.shift")
static public function shift(x) {
if (Boot.isArray(x)) {
return (x : Array<Dynamic>).shift();
}
return Syntax.callField(x, "shift");
}
@:ifFeature("dynamic_read.pop", "anon_optional_read.pop", "anon_read.pop")
static public function pop(x) {
if (Boot.isArray(x)) {
return (x : Array<Dynamic>).pop();
}
return Syntax.callField(x, "pop");
}
@:ifFeature("dynamic_read.push", "anon_optional_read.push", "anon_read.push")
static public function push(x:Dynamic, e:Dynamic) {
if (Boot.isArray(x)) {
return (x : Array<Dynamic>).push(e);
}
return Syntax.callField(x, "push", e);
}
@:ifFeature("dynamic_read.join", "anon_optional_read.join", "anon_read.join")
static public function join(x, sep) {
if (Boot.isArray(x)) {
return (x : Array<Dynamic>).join(sep);
}
return Syntax.callField(x, "join", sep);
}
@:ifFeature("dynamic_read.filter", "anon_optional_read.filter", "anon_read.filter")
static public function filter(x, f) {
if (Boot.isArray(x)) {
return (x : Array<Dynamic>).filter(f);
}
return Syntax.callField(x, "filter", f);
}
@:ifFeature("dynamic_read.map", "anon_optional_read.map", "anon_read.map")
static public function map(x:Dynamic, f:Dynamic) {
if (Boot.isArray(x)) {
return (x : Array<Dynamic>).map(f);
}
return Syntax.callField(x, "map", f);
}
@:ifFeature("dynamic_read.toUpperCase", "anon_optional_read.toUpperCase", "anon_read.toUpperCase")
static public function toUpperCase(x) {
if (Boot.isString(x)) {
return (x : String).toUpperCase();
}
return Syntax.callField(x, "toUpperCase");
}
@:ifFeature("dynamic_read.toLowerCase", "anon_optional_read.toLowerCase", "anon_read.toLowerCase")
static public function toLowerCase(x) {
if (Boot.isString(x)) {
return (x : String).toLowerCase();
}
return Syntax.callField(x, "toLowerCase");
}
@:ifFeature("dynamic_read.split", "anon_optional_read.split", "anon_read.split")
static public function split(x:Dynamic, delimiter:String) {
if (Boot.isString(x)) {
return (x : String).split(delimiter);
}
return Syntax.callField(x, "split", delimiter);
}
@:ifFeature("dynamic_read.length", "anon_optional_read.length", "anon_read.length")
static public function length(x:Dynamic) {
if (Boot.isString(x)) {
return (x : String).length;
} else if (Boot.isArray(x)) {
return (x : Array<Dynamic>).length;
}
return Syntax.field(x, "length");
}
@:ifFeature("binop_>>>")
static public function rshift(val:Int, n:Int) {
return Syntax.binop(Syntax.binop(val, "%", Syntax.code("0x100000000")), ">>", n);
}
@:ifFeature("binop_%")
static public function modf(a:Float, b:Float) {
if(b == 0.0) {
return Syntax.code("float('nan')");
} else if(a < 0) {
if(b < 0) {
return Syntax.code("-(-{0} % (-{1}))", a, b);
} else {
return Syntax.code("-(-{0} % {1})", a, b);
}
} else if(b < 0) {
return Syntax.code("{0} % (-{1})", a, b);
} else {
return Syntax.code("{0} % {1}", a, b);
}
}
@:ifFeature("binop_%")
static public function mod(a:Int, b:Int) {
if(a < 0) {
if(b < 0) {
return Syntax.code("-(-{0} % (-{1}))", a, b);
} else {
return Syntax.code("-(-{0} % {1})", a, b);
}
} else if(b < 0) {
return Syntax.code("{0} % (-{1})", a, b);
} else {
return Syntax.code("{0} % {1}", a, b);
}
}
@:ifFeature("dynamic_array_read")
static public function arrayGet<T>(a:Dynamic, i:Int):Dynamic {
if (Boot.isArray(a)) {
return ArrayImpl._get(a, i);
} else {
return Syntax.arrayAccess(a, i);
}
}
@:ifFeature("dynamic_array_write")
static public function arraySet(a:Dynamic, i:Int, v:Dynamic) {
if (Boot.isArray(a)) {
return ArrayImpl._set(a, i, v);
} else {
Syntax.assign(Syntax.arrayAccess(a, i), v);
return v;
}
}
@:ifFeature("python._KwArgs.KwArgs_Impl_.fromT")
static public function mapKwArgs(a:{}, v:Dict<String, String>) {
var a = python.Lib.dictAsAnon(python.Lib.anonToDict(a));
for (k in v.keys()) {
var val = v.get(k);
if (Syntax.code('{0}._hx_hasattr({1})', a, k)) {
var x = UBuiltins.getattr(a, k);
UBuiltins.setattr(a, val, x);
UBuiltins.delattr(a, k);
}
}
return a;
}
@:ifFeature("python._KwArgs.KwArgs_Impl_.toDictHelper")
static public function reverseMapKwArgs(a:Dict<String, Dynamic>, v:Dict<String, String>) {
var a = a.copy();
for (k in v.keys()) {
var val = v.get(k);
if (a.hasKey(val)) {
var x = a.get(val, null);
a.set(k, x);
a.remove(val);
}
}
return a;
}
}

View File

@ -0,0 +1,222 @@
/*
* Copyright (C)2005-2019 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 python.internal;
#if macro
import haxe.macro.Context;
import haxe.macro.Expr;
#end
@:noPackageRestrict
class Internal {
#if macro
static var _prefix = "_hx_";
static var _className = _prefix + "class_name";
static var _class = _prefix + "class";
static var _fields = _prefix + "fields";
static var _super = _prefix + "super";
static var _methods = _prefix + "methods";
static var _statics = _prefix + "statics";
static var _interfaces = _prefix + "interfaces";
static var _emptyInit = _prefix + "empty_init";
static var _constructs = _prefix + "constructs";
static var _classes = _prefix + "classes";
static var _dict = "__dict__";
static function _getPrefixed(x:Expr):Expr {
return switch (x.expr) {
case EConst(CString(x)): macro @:pos(Context.currentPos()) $v{_prefix + x};
case _: macro @:pos(Context.currentPos()) (python.Syntax.binop($v{_prefix}, "+", $x) : String);
}
}
static function withPos(x:String):Expr {
return macro @:pos(Context.currentPos()) $v{x};
}
static function fieldWithPos(o:Expr, x:String):Expr {
return macro @:pos(Context.currentPos()) (untyped __define_feature__($v{"python." + x}, python.Syntax.field($o, $v{x})));
}
static function has(o:Expr, field:String):Expr {
return macro(untyped __define_feature__($v{"python." + field}, python.internal.UBuiltins.hasattr($o, $v{field})) : Bool);
}
#end
macro public static function getPrefixed(x:ExprOf<String>):Expr {
return switch (x.expr) {
case EConst(CString(x)): macro @:pos(Context.currentPos()) $v{_prefix + x};
case _: macro @:pos(Context.currentPos()) (python.Syntax.binop($v{_prefix}, "+", $x) : String);
}
}
macro public static function classRegistry():Expr {
return macro(untyped __define_feature__($v{"python." + _classes}, python.Syntax.code($v{_classes})) : python.Dict<String, Class<Dynamic>>);
}
macro public static function callFieldPrefixed(o:Expr, x:String, params:Array<Expr>):Expr {
var args = [o, macro @:pos(Context.currentPos()) $v{_prefix + x}].concat(params);
return macro @:pos(Context.currentPos()) python.Syntax.callField($a{args});
}
macro public static function fieldPrefixed(o:Expr, x:String):Expr {
var args = [o, macro @:pos(Context.currentPos()) $v{_prefix + x}];
return macro @:pos(Context.currentPos()) python.Syntax.field($a{args});
}
macro public static function hasAttrPrefixed(o:Expr, x:String):Expr {
var args = [o, macro @:pos(Context.currentPos()) $v{_prefix + x}];
return macro @:pos(Context.currentPos()) python.Syntax.field($a{args});
}
macro public static function importAsPrefixed(o:String, x:String) {
return macro @:pos(Context.currentPos()) python.Syntax.importAs($v{o}, $v{_prefix + x});
}
macro public static function prefix():Expr {
return macro @:pos(Context.currentPos()) $v{_prefix};
}
macro public static function pythonCodePrefixed(x:String):Expr {
return macro python.Syntax.code($v{_prefix + x});
}
macro public static function hasClassName(o:Expr):Expr {
return has(o, _className);
}
macro public static function hasInterfaces(o:Expr):Expr {
return has(o, _interfaces);
}
macro public static function hasClass(o:Expr):Expr {
return has(o, _class);
}
macro public static function hasConstructs(o:Expr):Expr {
return has(o, _constructs);
}
macro public static function hasEmptyInit(o:Expr):Expr {
return has(o, _emptyInit);
}
macro public static function hasMethods(o:Expr):Expr {
return has(o, _methods);
}
macro public static function hasFields(o:Expr):Expr {
return has(o, _fields);
}
macro public static function hasSuper(o:Expr):Expr {
return has(o, _super);
}
macro public static function hasStatics(o:Expr):Expr {
return has(o, _statics);
}
macro public static function classNameVal():Expr {
return withPos(_className);
}
macro public static function methodsVal():Expr {
return withPos(_methods);
}
macro public static function classVal():Expr {
return withPos(_className);
}
macro public static function superVal():Expr {
return withPos(_super);
}
macro public static function interfacesVal():Expr {
return withPos(_interfaces);
}
macro public static function fieldsVal():Expr {
return withPos(_fields);
}
macro public static function staticsVal():Expr {
return withPos(_statics);
}
macro public static function constructsVal():Expr {
return withPos(_constructs);
}
macro public static function emptyInitVal():Expr {
return withPos(_emptyInit);
}
macro public static function fieldClassName(o:Expr):Expr {
return fieldWithPos(o, _className);
}
macro public static function fieldInterfaces(o:Expr):Expr {
return fieldWithPos(o, _interfaces);
}
macro public static function fieldClass(o:Expr):Expr {
return fieldWithPos(o, _class);
}
macro public static function fieldSuper(o:Expr):Expr {
return fieldWithPos(o, _super);
}
macro public static function fieldStatics(o:Expr):Expr {
return fieldWithPos(o, _statics);
}
macro public static function fieldMethods(o:Expr):Expr {
return fieldWithPos(o, _methods);
}
macro public static function fieldFields(o:Expr):Expr {
return fieldWithPos(o, _fields);
}
macro public static function fieldConstructs(o:Expr):Expr {
return fieldWithPos(o, _constructs);
}
macro public static function fieldDict(o:Expr):Expr {
return macro @:pos(Context.currentPos()) python.Syntax.field($o, $v{_dict});
}
macro public static function fieldEmptyInit(o:Expr):Expr {
return fieldWithPos(o, _emptyInit);
}
macro public static function callEmptyInit(o:Expr, instance:Expr):Expr {
return macro @:pos(Context.currentPos()) python.Syntax.callField($o, $v{_emptyInit}, $instance);
}
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (C)2005-2019 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 python.internal;
class MethodClosure {
@:allow(Reflect) var obj:Dynamic;
@:allow(Reflect) var func:haxe.Constraints.Function;
public function new(obj:Dynamic, func:haxe.Constraints.Function) {
this.obj = obj;
this.func = func;
}
@:keep public function __call__(args:VarArgs<Dynamic>) {
return this.func(this.obj, args);
}
}

View File

@ -0,0 +1,148 @@
/*
* Copyright (C)2005-2019 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 python.internal;
import python.internal.Internal;
@:native("HxString")
class StringImpl {
@:ifFeature("dynamic_read.split", "anon_optional_read.split", "python.internal.StringImpl.split")
public static inline function split(s:String, d:String) {
return if (d == "") UBuiltins.list(s) else Syntax.callField(s, "split", d);
}
@:ifFeature("dynamic_read.charCodeAt", "anon_optional_read.charCodeAt", "python.internal.StringImpl.charCodeAt")
public static function charCodeAt(s:String, index:Int) {
return if (s == null || s.length == 0 || index < 0 || index >= s.length) null else UBuiltins.ord(Syntax.arrayAccess(s, index));
}
@:ifFeature("dynamic_read.charAt", "anon_optional_read.charAt", "python.internal.StringImpl.charAt")
public static inline function charAt(s:String, index:Int) {
return if (index < 0 || index >= s.length) "" else Syntax.arrayAccess(s, index);
}
@:ifFeature("dynamic_read.lastIndexOf", "anon_optional_read.lastIndexOf", "python.internal.StringImpl.lastIndexOf")
public static inline function lastIndexOf(s:String, str:String, ?startIndex:Int):Int {
if (startIndex == null) {
return Syntax.callField(s, "rfind", str, 0, s.length);
} else if(str == "") {
var length = s.length;
if(startIndex < 0) {
startIndex = length + startIndex;
if(startIndex < 0) startIndex = 0;
}
return startIndex > length ? length : startIndex;
} else {
var i = Syntax.callField(s, "rfind", str, 0, startIndex + 1);
var startLeft = i == -1 ? UBuiltins.max(0, startIndex + 1 - str.length) : i + 1;
var check = Syntax.callField(s, "find", str, startLeft, s.length);
if (check > i && check <= startIndex) {
return check;
} else {
return i;
}
}
}
@:ifFeature("dynamic_read.toUpperCase", "anon_optional_read.toUpperCase", "python.internal.StringImpl.toUpperCase")
public static inline function toUpperCase(s:String) {
return Syntax.callField(s, "upper");
}
@:ifFeature("dynamic_read.toLowerCase", "anon_optional_read.toLowerCase", "python.internal.StringImpl.toLowerCase")
public static inline function toLowerCase(s:String) {
return Syntax.callField(s, "lower");
}
@:ifFeature("dynamic_read.indexOf", "anon_optional_read.indexOf", "python.internal.StringImpl.indexOf")
public static inline function indexOf(s:String, str:String, ?startIndex:Int) {
if (startIndex == null)
return Syntax.callField(s, "find", str);
else
return indexOfImpl(s, str, startIndex);
}
static function indexOfImpl(s:String, str:String, startIndex:Int) {
if(str == "") {
var length = s.length;
if(startIndex < 0) {
startIndex = length + startIndex;
if(startIndex < 0) startIndex = 0;
}
return startIndex > length ? length : startIndex;
}
return Syntax.callField(s, "find", str, startIndex);
}
@:ifFeature("dynamic_read.toString", "anon_optional_read.toString", "python.internal.StringImpl.toString")
public static inline function toString(s:String) {
return s;
}
@:ifFeature("dynamic_read.length", "anon_optional_read.length", "python.internal.StringImpl.length")
public static inline function get_length(s:String) {
return UBuiltins.len(s);
}
@:ifFeature("dynamic_read.fromCharCode", "anon_optional_read.fromCharCode", "python.internal.StringImpl.fromCharCode")
public static inline function fromCharCode(code:Int):String {
#if doc_gen
return "";
#else
return Syntax.callField('', "join", UBuiltins.map(UBuiltins.chr, cast [code])); // TODO: check cast
#end
}
@:ifFeature("dynamic_read.substring", "anon_optional_read.substring", "python.internal.StringImpl.substring")
public static function substring(s:String, startIndex:Int, ?endIndex:Int):String {
if (startIndex < 0)
startIndex = 0;
if (endIndex == null) {
return Syntax.arrayAccessWithTrailingColon(s, startIndex);
} else {
if (endIndex < 0)
endIndex = 0;
if (endIndex < startIndex) {
return Syntax.arrayAccess(s, endIndex, startIndex);
} else {
return Syntax.arrayAccess(s, startIndex, endIndex);
}
}
}
@:ifFeature("dynamic_read.substr", "anon_optional_read.substr", "python.internal.StringImpl.substr")
public static function substr(s:String, startIndex:Int, ?len:Int):String {
if (len == null) {
return Syntax.arrayAccessWithTrailingColon(s, startIndex);
} else {
if (len == 0)
return "";
if (startIndex < 0) {
startIndex = s.length + startIndex;
if (startIndex < 0)
startIndex = 0;
}
return Syntax.arrayAccess(s, startIndex, startIndex + len);
}
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright (C)2005-2019 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 python.internal;
/**
This class provides unqualified access to python builtins that are safe to use in haxe/python code.
Fields listed here must be synchronized with genpy's KeywordHandler.kwds2 list to be properly escaped.
**/
extern class UBuiltins {
static function id(x:Dynamic):String;
static function len(x:Dynamic):Int;
static function isinstance(o:Dynamic, c:Dynamic):Bool;
static function str(o:Dynamic):String;
static function bool(o:Dynamic):Bool;
static function float(o:Dynamic):Float;
static function int(o:Dynamic, ?base:Int):Int;
static function list<T>(o:Dynamic):Array<T>;
static function min<T>(a:T, b:T):T;
static function max<T>(a:T, b:T):T;
static function hasattr(o:Dynamic, a:String):Bool;
static function getattr(o:Dynamic, a:String, ?def:Dynamic):Dynamic;
static function setattr(o:Dynamic, a:String, v:Dynamic):Void;
static function delattr(o:Dynamic, attr:String):Void;
static function callable(x:Dynamic):Bool;
static function type(o:Dynamic):Dynamic;
static function ord(s:String):Int;
static function chr(c:Int):String;
static function map<T, S>(f:T->S, a:Array<T>):Array<S>;
static function filter<T>(f:T->Bool, a:Array<T>):Array<T>;
static function iter<T>(o:python.NativeIterable<T>):python.NativeIterator<T>;
}

View File

@ -0,0 +1,35 @@
/*
* Copyright (C)2005-2019 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 python.io;
import python.io.NativeBytesInput;
import python.io.NativeTextInput;
import python.lib.io.RawIOBase;
import python.lib.io.IOBase.SeekSet;
import python.lib.io.TextIOBase;
class FileBytesInput extends NativeBytesInput implements IFileInput {
public function new(stream:RawIOBase) {
super(stream);
}
}

View File

@ -0,0 +1,33 @@
/*
* Copyright (C)2005-2019 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 python.io;
import python.io.IFileOutput;
import python.io.NativeBytesOutput;
import python.lib.io.RawIOBase;
class FileBytesOutput extends NativeBytesOutput implements IFileOutput {
public function new(stream:RawIOBase) {
super(stream);
}
}

View File

@ -0,0 +1,35 @@
/*
* Copyright (C)2005-2019 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 python.io;
import python.io.NativeBytesInput;
import python.io.NativeTextInput;
import python.lib.io.RawIOBase;
import python.lib.io.IOBase.SeekSet;
import python.lib.io.TextIOBase;
class FileTextInput extends NativeTextInput implements IFileInput {
public function new(stream:TextIOBase) {
super(stream);
}
}

View File

@ -0,0 +1,33 @@
/*
* Copyright (C)2005-2019 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 python.io;
import python.io.IFileOutput;
import python.io.NativeBytesOutput;
import python.lib.io.TextIOBase;
class FileTextOutput extends NativeTextOutput implements IFileOutput {
public function new(stream:TextIOBase) {
super(stream);
}
}

View File

@ -0,0 +1,33 @@
/*
* Copyright (C)2005-2019 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 python.io;
import python.io.IInput;
import sys.io.FileSeek;
interface IFileInput extends IInput {
public function seek(p:Int, pos:FileSeek):Void;
public function tell():Int;
public function eof():Bool;
}

View File

@ -0,0 +1,31 @@
/*
* Copyright (C)2005-2019 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 python.io;
import python.io.IOutput;
import sys.io.FileSeek;
interface IFileOutput extends IOutput {
public function seek(p:Int, pos:FileSeek):Void;
public function tell():Int;
}

View File

@ -0,0 +1,64 @@
/*
* Copyright (C)2005-2019 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 python.io;
import haxe.io.Bytes;
import haxe.io.Encoding;
interface IInput {
public var bigEndian(default, set):Bool;
public function readByte():Int;
public function readBytes(s:Bytes, pos:Int, len:Int):Int;
public function close():Void;
public function readAll(?bufsize:Int):Bytes;
public function readFullBytes(s:Bytes, pos:Int, len:Int):Void;
public function read(nbytes:Int):Bytes;
public function readUntil(end:Int):String;
public function readLine():String;
public function readFloat():Float;
public function readDouble():Float;
public function readInt8():Int;
public function readInt16():Int;
public function readUInt16():Int;
public function readInt24():Int;
public function readUInt24():Int;
public function readInt32():Int;
public function readString(len:Int, ?encoding:Encoding):String;
}

View File

@ -0,0 +1,65 @@
/*
* Copyright (C)2005-2019 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 python.io;
import haxe.io.Bytes;
import haxe.io.Encoding;
import haxe.io.Input;
interface IOutput {
public var bigEndian(default, set):Bool;
public function writeByte(c:Int):Void;
public function writeBytes(s:Bytes, pos:Int, len:Int):Int;
public function flush():Void;
public function close():Void;
public function write(s:Bytes):Void;
public function writeFullBytes(s:Bytes, pos:Int, len:Int):Void;
public function writeFloat(x:Float):Void;
public function writeDouble(x:Float):Void;
public function writeInt8(x:Int):Void;
public function writeInt16(x:Int):Void;
public function writeUInt16(x:Int):Void;
public function writeInt24(x:Int):Void;
public function writeUInt24(x:Int):Void;
public function writeInt32(x:Int):Void;
public function prepare(nbytes:Int):Void;
public function writeInput(i:Input, ?bufsize:Int):Void;
public function writeString(s:String, ?encoding:Encoding):Void;
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (C)2005-2019 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 python.io;
import python.io.FileBytesInput;
import python.io.FileTextInput;
import python.io.FileTextOutput;
import python.io.FileBytesOutput;
import python.lib.io.RawIOBase;
import python.lib.io.TextIOBase;
import sys.io.FileInput;
import sys.io.FileOutput;
import python.lib.io.IOBase.SeekSet;
class IoTools {
public static function createFileInputFromText(t:TextIOBase) {
return @:privateAccess new FileInput(new FileTextInput(t));
}
public static function createFileInputFromBytes(t:RawIOBase) {
return @:privateAccess new FileInput(new FileBytesInput(t));
}
public static function createFileOutputFromText(t:TextIOBase) {
return @:privateAccess new FileOutput(new FileTextOutput(t));
}
public static function createFileOutputFromBytes(t:RawIOBase) {
return @:privateAccess new FileOutput(new FileBytesOutput(t));
}
public static function seekInTextMode(stream:TextIOBase, tell:Void->Int, p:Int, pos:sys.io.FileSeek) {
var pos = switch (pos) {
case SeekBegin:
SeekSet;
case SeekCur:
p = tell() + p;
SeekSet;
case SeekEnd:
stream.seek(0, SeekEnd);
p = tell() + p;
SeekSet;
}
stream.seek(p, pos);
}
public static function seekInBinaryMode(stream:RawIOBase, p:Int, pos:sys.io.FileSeek) {
var pos = switch (pos) {
case SeekBegin: SeekSet;
case SeekCur: SeekCur;
case SeekEnd: SeekEnd;
};
stream.seek(p, pos);
}
}

View File

@ -0,0 +1,55 @@
/*
* Copyright (C)2005-2019 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 python.io;
import haxe.io.Eof;
import haxe.io.Input;
import python.io.IInput;
import python.io.IoTools;
import python.Bytearray;
import python.lib.io.RawIOBase;
import python.lib.io.IOBase.SeekSet;
class NativeBytesInput extends NativeInput<RawIOBase> implements IInput {
public function new(stream:RawIOBase) {
super(stream);
}
override public function readByte():Int {
var ret = stream.read(1);
if (ret.length == 0)
throwEof();
return ret.get(0);
}
override public function seek(p:Int, pos:sys.io.FileSeek):Void {
wasEof = false;
return IoTools.seekInBinaryMode(stream, p, pos);
}
override function readinto(b:Bytearray):Int {
return stream.readinto(b);
}
}

View File

@ -0,0 +1,50 @@
/*
* Copyright (C)2005-2019 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 python.io;
import haxe.io.Output;
import python.Bytearray;
import python.lib.io.IOBase;
import python.lib.io.RawIOBase;
class NativeBytesOutput extends NativeOutput<RawIOBase> {
public function new(stream:RawIOBase) {
super(stream);
}
public function seek(p:Int, pos:sys.io.FileSeek):Void {
return IoTools.seekInBinaryMode(stream, p, pos);
}
override public function prepare(nbytes:Int):Void {
stream.truncate(nbytes);
}
override public function writeByte(c:Int):Void {
stream.write(new Bytearray([c]));
}
override function writeBytes(s:haxe.io.Bytes, pos:Int, len:Int):Int {
return stream.write(python.Syntax.code("{0}[{1}:{2}]", s.getData(), pos, pos + len));
}
}

View File

@ -0,0 +1,84 @@
/*
* Copyright (C)2005-2019 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 python.io;
import haxe.io.Eof;
import haxe.io.Input;
import python.Bytearray;
import python.lib.io.IOBase;
import python.lib.io.RawIOBase;
class NativeInput<T:IOBase> extends Input {
var stream:T;
var wasEof:Bool;
function new(s:T) {
this.stream = s;
this.bigEndian = false;
wasEof = false;
if (!stream.readable())
throw "Write-only stream";
}
public var canSeek(get, never):Bool;
inline function get_canSeek():Bool
return stream.seekable();
override public function close():Void {
stream.close();
}
public function tell():Int {
return stream.tell();
}
function throwEof() {
wasEof = true;
throw new Eof();
}
public function eof() {
return wasEof;
}
function readinto(b:Bytearray):Int {
throw "abstract method, should be overridden";
}
function seek(p:Int, mode:sys.io.FileSeek) {
throw "abstract method, should be overridden";
}
override public function readBytes(s:haxe.io.Bytes, pos:Int, len:Int):Int {
if (pos < 0 || len < 0 || pos + len > s.length)
throw haxe.io.Error.OutsideBounds;
var ba = new Bytearray(len);
var ret = readinto(ba);
if (ret == 0)
throwEof();
s.blit(pos, haxe.io.Bytes.ofData(ba), 0, len);
return ret;
}
}

View File

@ -0,0 +1,59 @@
/*
* Copyright (C)2005-2019 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 python.io;
import haxe.io.Output;
import python.lib.io.IOBase;
import python.lib.io.RawIOBase;
class NativeOutput<T:IOBase> extends Output {
var stream:T;
public var canSeek(get, never):Bool;
inline function get_canSeek():Bool
return stream.seekable();
public function new(stream:T) {
this.bigEndian = false;
this.stream = stream;
if (!stream.writable())
throw "Read only stream";
}
override public function close():Void {
stream.close();
}
override public function prepare(nbytes:Int):Void {
stream.truncate(nbytes);
}
override public function flush():Void {
stream.flush();
}
public function tell():Int {
return stream.tell();
}
}

View File

@ -0,0 +1,57 @@
/*
* Copyright (C)2005-2019 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 python.io;
import haxe.io.Eof;
import haxe.io.Input;
import python.io.IInput;
import python.io.IoTools;
import python.io.NativeInput;
import python.Bytearray;
import python.lib.io.RawIOBase;
import python.lib.io.IOBase.SeekSet;
import python.lib.io.TextIOBase;
class NativeTextInput extends NativeInput<TextIOBase> implements IInput {
public function new(stream:TextIOBase) {
super(stream);
}
override public function readByte():Int {
var ret = stream.buffer.read(1);
if (ret.length == 0)
throwEof();
return ret[0];
}
override public function seek(p:Int, pos:sys.io.FileSeek):Void {
wasEof = false;
IoTools.seekInTextMode(stream, tell, p, pos);
}
override function readinto(b:Bytearray):Int {
return stream.buffer.readinto(b);
}
}

View File

@ -0,0 +1,49 @@
/*
* Copyright (C)2005-2019 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 python.io;
import haxe.io.Output;
import python.io.IoTools;
import python.lib.io.IOBase;
import python.lib.io.RawIOBase;
import python.lib.io.TextIOBase;
class NativeTextOutput extends NativeOutput<TextIOBase> {
public function new(stream:TextIOBase) {
super(stream);
if (!stream.writable())
throw "Read only stream";
}
public function seek(p:Int, pos:sys.io.FileSeek):Void {
IoTools.seekInTextMode(stream, tell, p, pos);
}
override public function writeBytes(s:haxe.io.Bytes, pos:Int, len:Int):Int {
return stream.buffer.write(python.Syntax.arrayAccess(@:privateAccess s.b, pos, pos + len));
}
override public function writeByte(c:Int):Void {
stream.write(String.fromCharCode(c));
}
}

View File

@ -0,0 +1,156 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import haxe.extern.Rest;
import python.lib.io.FileIO;
import python.Dict;
import python.lib.io.IOBase;
import python.NativeIterable;
import python.NativeIterator;
@:pythonImport("builtins")
extern class Builtins {
@:overload(function(f:Int):Int {})
static function abs(x:Float):Float;
static function all(i:Iterable<Bool>):Bool;
static function any(i:Iterable<Bool>):Bool;
static function bool(x:Dynamic):Bool;
static function issubclass(x:Class<Dynamic>, from:Class<Dynamic>):Bool;
static function callable(x:Dynamic):Bool;
@:overload(function(obj:Dynamic, f:Tuple<Dynamic>):Bool {})
static function isinstance(obj:Dynamic, cl:Dynamic):Bool;
static function hasattr(obj:Dynamic, attr:String):Bool;
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:Bytearray):Int {})
@:overload(function(f:Tuple<Dynamic>):Int {})
static function len(x:String):Int;
static function open(file:String, mode:String, ?buffering:Int = -1, ?encoding:String = null, ?errors:String, ?newline:String, ?closefd:Bool,
?opener:String->Int->FileDescriptor):IOBase;
// static function divmod():Void;
// static function input():Void;
// static function staticmethod():Void;
// static function enumerate():Void;
@:overload(function(x:Dynamic, base:Int):Int {})
static function int(x:Dynamic):Int;
static function ord(s:String):Int;
static function str(o:Dynamic):String;
// static function eval():Void;
// static function pow():Void;
// static function sum():Void;
// static function basestring():Void;
// static function execfile():Void;
static function print(o:Dynamic):Void;
// static function super():Void;
// static function bin():Void;
// static function file():Void;
static function iter<X>(d:DictView<X>):NativeIterator<X>;
// static function property():Void;
/*
@:overload(function <X>():Tuple<X> {})
static function tuple<X>(a:Array<X>):Tuple<X>;
*/
// static function range():Void;
static function type():Void;
/*
@:overload(function (it:Array<Int>):python.Bytearray {})
@:overload(function (it:NativeIterable<Int>):python.Bytearray {})
@:overload(function (size:Int):python.Bytearray {})
static function bytearray(source:String,encoding:String,?errors:Dynamic):python.Bytearray;
*/
static function float(x:Dynamic):Float;
@:overload(function<T>(f:Array<T>):Array<T> {})
@:overload(function<T>(f:Tuple<T>):Array<T> {})
@:overload(function<T>(f:Dict.DictView<T>):Array<T> {})
@:overload(function(f:String):Array<String> {})
static function list<T>(i:NativeIterable<T>):Array<T>;
@:overload(function<A>(f:A->Bool, i:NativeIterable<A>):NativeIterator<A> {})
static function filter<A>(f:A->Bool, i:Array<A>):NativeIterator<A>;
// static function raw_input():Void;
// static function unichr():Void;
// static function format():Void;
// static function locals():Void;
// static function reduce():Void;
// static function unicode():Void;
static function chr(c:Int):String;
// static function frozenset():Void;
// static function long():Void;
// static function reload():Void;
// static function vars():Void;
// static function classmethod():Void;
static function map<A, B>(fn:A->B, it:NativeIterable<A>):NativeIterator<B>;
static function repr(o:Dynamic):String;
// static function xrange():Void;
// static function cmp():Void;
// static function globals():Void;
@:overload(function(a1:Float, a2:Float, rest:Rest<Float>):Float {})
static function max(a1:Int, a2:Int, rest:Rest<Int>):Int;
// static function reversed():Void;
// static function zip():Void;
// static function compile():Void;
// static function memoryview():Void;
static function round(f:Float):Int;
// static function __import__():Void;
// static function complex():Void;
// static function hash():Void;
@:overload(function(a1:Float, a2:Float, rest:Rest<Float>):Float {})
static function min(a1:Int, a2:Int, rest:Rest<Int>):Int;
// static function set():Void;
// static function apply():Void;
static function delattr(o:Dynamic, attr:String):Void;
// static function help():Void;
// static function next():Void;
static function setattr(o:Dynamic, attr:String, val:Dynamic):Void;
// static function buffer():Void;
// static function dict():Void;
// static function hex():Void;
// static function object():Void;
// static function slice():Void;
// static function coerce():Void;
// static function dir():Void;
static function id(x:{}):Int;
// static function oct():Void;
// static function sorted():Void;
// static function intern():Void;
}

View File

@ -0,0 +1,33 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.Bytes;
import python.lib.codecs.StreamReaderWriter;
@:pythonImport("codecs")
extern class Codecs {
static function open(filename:String, mode:String, ?encoding:String, ?errors:String, ?buffering:Bool):StreamReaderWriter;
static function encode(obj:String, ?encoding:String = "utf-8", errors:String = "strict"):Bytes;
static function decode(obj:Bytes, ?encoding:String = "utf-8", errors:String = "strict"):String;
}

View File

@ -0,0 +1,25 @@
/*
* Copyright (C)2005-2019 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 python.lib;
extern class FileDescriptor {}

View File

@ -0,0 +1,27 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.lib.io.IOBase;
typedef FileObject = IOBase;

View File

@ -0,0 +1,28 @@
/*
* Copyright (C)2005-2019 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 python.lib;
@:pythonImport("functools")
extern class Functools {
static function cmp_to_key<A>(f:A->A->Int):Dynamic;
}

View File

@ -0,0 +1,31 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.NativeIterator;
@:pythonImport("glob")
extern class Glob {
static function glob(pathname:String):Array<String>;
static function iglob(pathname:String):NativeIterator<String>;
}

View File

@ -0,0 +1,106 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.Bytes;
import python.Set;
@:pythonImport("hashlib")
extern class Hashlib {
/**
A set containing the names of the hash algorithms guaranteed to be supported by this module on all platforms.
Note that md5 is in this list despite some upstream vendors offering an odd “FIPS compliant” Python build that excludes it.
**/
static var algorithms_guaranteed(default, null):Set<String>;
/**
A set containing the names of the hash algorithms that are available in the running Python interpreter.
These names will be recognized when passed to new(). algorithms_guaranteed will always be a subset.
The same algorithm may appear multiple times in this set under different names (thanks to OpenSSL).
**/
static var algorithms_available(default, null):Set<String>;
/**
A generic constructor that takes the string name of the desired algorithm as its first parameter.
It also exists to allow access to the above listed hashes as well as any other algorithms that your OpenSSL library may offer.
The named constructors are much faster than new() and should be preferred.
**/
@:native("new")
static function new_(name:String, ?data:Bytes):HashlibHash;
static function sha1():HashlibHash;
static function sha224():HashlibHash;
static function sha256():HashlibHash;
static function sha384():HashlibHash;
static function sha512():HashlibHash;
static function blake2b():HashlibHash;
static function blake2s():HashlibHash;
static function md5():HashlibHash;
static function sha3_224():HashlibHash;
static function sha3_256():HashlibHash;
static function sha3_384():HashlibHash;
static function sha3_512():HashlibHash;
static function shake_128():HashlibHash;
static function shake_256():HashlibHash;
}
extern class HashlibHash {
/**
The size of the resulting hash in bytes.
**/
var digest_size(default, null):Int;
/**
The internal block size of the hash algorithm in bytes.
**/
var block_size(default, null):Int;
/**
The canonical name of this hash, always lowercase and always suitable as a parameter to new() to create another hash of this type.
**/
var name:String;
/**
Update the hash object with the object arg, which must be interpretable as a buffer of bytes.
Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a+b).
**/
function update(a:Bytes):Void;
/**
Return the digest of the data passed to the update() method so far.
This is a bytes object of size digest_size which may contain bytes in the whole range from 0 to 255.
**/
function digest():Bytes;
/**
Like digest() except the digest is returned as a string object of double length, containing only hexadecimal digits.
This may be used to exchange the value safely in email or other non-binary environments.
**/
function hexdigest():String;
/**
Return a copy (“clone”) of the hash object.
This can be used to efficiently compute the digests of data sharing a common initial substring.
**/
function copy():HashlibHash;
}

View File

@ -0,0 +1,38 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.Tuple.Tuple2;
@:pythonImport("inspect")
extern class Inspect {
static function getmembers(object:Dynamic, ?predicate:Dynamic->Bool):Array<Tuple2<String, Dynamic>>;
static function ismethod(object:Dynamic):Bool;
static function isclass(object:Dynamic):Bool;
static function isfunction(object:Dynamic):Bool;
static function getsourcefile(object:Dynamic):String;
static inline function isInterface(cls:Class<Dynamic>):Bool {
return untyped __define_feature__("python._hx_is_interface", c._hx_is_interface);
}
}

View File

@ -0,0 +1,33 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.lib.io.IOBase;
@:pythonImport("io")
extern class Io {
static var DEFAULT_BUFFER_SIZE:Int;
static function open(file:String, mode:String, ?buffering:Int = -1, ?encoding:String = null, ?errors:String, ?newline:String, ?closefd:Bool,
?opener:String->Int->FileDescriptor):IOBase;
}

View File

@ -0,0 +1,52 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.KwArgs;
import python.Dict;
import python.lib.json.JSONEncoder;
import python.Tuple.Tuple2;
typedef JsonDumpsOptions = {
var ?skipkeys:Bool;
var ?ensure_ascii:Bool;
var ?check_circular:Bool;
var ?allow_nan:Bool;
var ?cls:Dynamic;
var ?indent:String;
var ?separators:Tuple2<String, String>;
@:native("default") var ?def:Dynamic->String;
var ?sort_keys:Bool;
}
typedef JsonLoadsOptions = {
var ?encoding:String;
var ?cls:Dynamic;
var ?object_hook:Dict<String, Dynamic>->Dynamic;
}
@:pythonImport("json")
extern class Json {
static function loads(s:String, ?options:KwArgs<JsonLoadsOptions>):Dict<String, Dynamic>;
static function dumps(x:Dynamic, ?options:KwArgs<JsonDumpsOptions>):String;
}

View File

@ -0,0 +1,40 @@
/*
* Copyright (C)2005-2019 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 python.lib;
@:pythonImport("math")
extern class Math {
static function isnan(f:Float):Bool;
static var pi:Float;
static function sqrt(f:Float):Float;
static function log(f:Float):Float;
static function cos(f:Float):Float;
static function sin(f:Float):Float;
static function tan(f: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;
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C)2005-2019 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 python.lib;
@:pythonImport("msvcrt", ignoreError = true)
extern class Msvcrt {
static function getch():python.Bytes;
static function getwch():String;
}

View File

@ -0,0 +1,92 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.Exceptions.OSError;
import python.Tuple;
import python.Dict;
extern class Stat {
var st_mode:Int;
var st_ino:Int;
var st_dev:Int;
var st_nlink:Int;
var st_uid:Int;
var st_gid:Int;
var st_size:Int;
var st_atime:Int;
var st_mtime:Int;
var st_ctime:Int;
@:optional var st_blocks:Int;
@:optional var st_blksize:Int;
@:optional var st_rdev:Int;
@:optional var st_flags:Int;
@:optional var st_gen:Int;
@:optional var st_birthtime:Int;
@:optional var st_rsize:Int;
@:optional var st_creator:Int;
@:optional var st_type:Int;
}
@:pythonImport("os")
extern class Os {
static var environ:Dict<String, String>;
static function putenv(name:String, value:String):Void;
static function chdir(path:String):Void;
static function unlink(path:String):Void;
static function remove(path:String):Void;
static function getcwd():String;
static function getcwdb():Bytes;
static function removedirs(path:String):Void;
static function rename(src:String, dest:String):Void;
static function renames(oldName:String, newName:String):Void;
static function rmdir(path:String):Void;
static function stat(path:String):Stat;
static function fchdir(fd:FileDescriptor):Void;
static function listdir(path:String = "."):Array<String>;
static function walk(top:String, topdown:Bool = true, onerror:OSError->Void = null,
followlinks:Bool = false):Tuple3<String, Array<String>, Array<String>>;
static var sep(default, null):String;
static var pathsep(default, null):String;
static function makedirs(path:String, mode:Int = 511 /* Oktal 777 */, exist_ok:Bool = false):Void;
static function mkdir(path:String, mode:Int = 511 /* Oktal 777 */):Void;
}

View File

@ -0,0 +1,30 @@
/*
* Copyright (C)2005-2019 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 python.lib;
@:pythonImport("pprint")
extern class Pprint {
static function pprint(x:Dynamic):Void;
static function pformat(object:Dynamic, indent:Int = 1, width:Int = 80, depth:Int = null):String;
}

View File

@ -0,0 +1,153 @@
/*
* Copyright (C)2005-2019 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 python.lib;
@:pythonImport("random")
extern class Random {
/**
Initialize the random number generator.
If `a` is omitted or `null`, the current system time is used.
If randomness sources are provided by the operating system,
they are used instead of the system time (see the os.urandom()
function for details on availability).
If `a` is an int, it is used directly.
With `version` 2 (the default), a str, bytes, or bytearray object
gets converted to an int and all of its bits are used.
With version 1, the hash() of a is used instead.
**/
static function seed(?a:Int, ?version:Int):Float;
/**
Return an object capturing the current internal state of the generator.
This object can be passed to setstate() to restore the state.
**/
static function getstate():RandomState;
/**
`state` should have been obtained from a previous call to `getstate`(),
and `setstate`() restores the internal state of the generator to what
it was at the time `getstate`() was called.
**/
static function setstate(state:RandomState):Void;
/**
Returns a Python integer with `k` random bits.
This method is supplied with the `MersenneTwister` generator and
some other generators may also provide it as an optional part of the API.
When available, `getrandbits`() enables `randrange`() to handle arbitrarily large ranges.
**/
static function getrandbits(k:Int):Int;
/**
Return a randomly selected element from `range(start, stop, step)`.
This is equivalent to `choice(range(start, stop, step))`,
but doesnt actually build a range object.
**/
@:overload(function(stop:Int):Int {})
static function randrange(start:Int, stop:Int, ?step:Int):Int;
/**
Return a random integer N such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
**/
static function randint(a:Int, b:Int):Int;
/**
Return the next random floating point number in the range [0.0, 1.0).
**/
static function random():Float;
/**
Return a random floating point number N such that
`a <= N <= b` for `a <= b` and `b <= N <= a` for `b < a`.
**/
static function uniform(a:Float, b:Float):Float;
/**
Return a random floating point number N such that
`low <= N <= high` and with the specified `mode` between those bounds.
The `low` and `high` bounds default to zero and one.
The `mode` argument defaults to the midpoint between the bounds,
giving a symmetric distribution.
**/
static function triangular(?low:Float, ?high:Float, ?mode:Float):Float;
/**
Beta distribution. Conditions on the parameters are `alpha > 0` and `beta > 0`.
Returned values range between 0 and 1.
**/
static function betavariate(alpha:Float, beta:Float):Float;
/**
Exponential distribution. `lambd` is 1.0 divided by the desired mean.
It should be nonzero. Returned values range from 0 to positive infinity if `lambd` is positive,
and from negative infinity to 0 if `lambd` is negative.
**/
static function expovariate(lambd:Float):Float;
/**
Gamma distribution. (Not the gamma function!)
Conditions on the parameters are `alpha > 0` and `beta > 0`.
**/
static function gammavariate(alpha:Float, beta:Float):Float;
/**
Gaussian distribution. `mu` is the mean, and `sigma` is the standard deviation.
This is slightly faster than the `normalvariate` function defined below.
**/
static function gauss(mu:Float, sigma:Float):Float;
/**
Log normal distribution. If you take the natural logarithm of this distribution,
youll get a normal distribution with mean `mu` and standard deviation `sigma`.
`mu` can have any value, and `sigma` must be greater than zero.
**/
static function lognormvariate(mu:Float, sigma:Float):Float;
/**
Normal distribution. `mu` is the mean, and `sigma` is the standard deviation.
**/
static function normalvariate(mu:Float, sigma:Float):Float;
/**
`mu` is the mean angle, expressed in radians between 0 and 2*pi,
and `kappa` is the concentration parameter, which must be greater than or equal to zero.
If `kappa` is equal to zero, this distribution reduces to a uniform random angle
over the range 0 to 2*pi.
**/
static function vonmisesvariate(mu:Float, kappa:Float):Float;
/**
Pareto distribution. alpha is the `shape` parameter.
**/
static function paretovariate(alpha:Float):Float;
/**
Weibull distribution. `alpha` is the scale parameter and `beta` is the shape parameter.
**/
static function weibullvariate(alpha:Float, beta:Float):Float;
}
abstract RandomState({}) {}

View File

@ -0,0 +1,179 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.Tuple;
private 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;
}
typedef Pattern = Choice<String, Regex>;
typedef Repl = Choice<String, MatchObject->String>;
extern class MatchObject {
var pos(default, null):Int;
var endpos(default, null):Int;
var lastindex(default, null):Int;
var lastgroup(default, null):Int;
var re(default, null):Regex;
var string(default, null):String;
function expand(template:String):String;
@:overload(function(x:String):String {})
function group(?i:Int = 0):String;
function groups(defaultVal:String = null):Tuple<String>;
function groupdict(defaultVal:Dict<String, String> = null):Dict<String, String>;
@:overload(function(x:String):Int {})
function start(?i:Int = 0):Int;
@:overload(function(x:String):Int {})
function end(?i:Int = 0):Int;
function span(?i:Int):Tuple2<Int, Int>;
inline function groupById(s:String):String {
return group(s);
}
inline function startById(s:String):Int {
return start(s);
}
inline function endById(s:String):Int {
return end(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 python.Syntax.field(r, "findall")(string);
} else {
return python.Syntax.field(r, "findall")(string, pos);
}
} else {
return python.Syntax.field(r, "findall")(string, pos, endpos);
}
}
}
extern class Regex {
function search(string:String, pos:Int = 0, ?endpos:Int):Null<MatchObject>;
function match(string:String, pos:Int = 0, ?endpos:Int):Null<MatchObject>;
function split(string:String, maxsplit:Int = 0):Array<String>;
inline function findallString(string:String, ?pos:Int, ?endpos:Int):Array<String> {
return cast this.findallDynamic(string, pos, endpos);
}
inline function findallDynamic(string:String, ?pos:Int, ?endpos:Int):Array<Dynamic> {
return RegexHelper.findallDynamic(this, string, pos, endpos);
}
inline function findallTuple(string:String, ?pos:Int, ?endpos:Int):Array<Tuple<String>> {
return cast this.findallDynamic(string, pos, endpos);
}
inline function findallArray(string:String, ?pos:Int, ?endpos:Int):Array<Array<String>> {
return findallTuple(string, pos, endpos).map(function(t) return t.toArray());
}
function finditer(string:String, ?pos:Int, ?endpos:Int):NativeIterator<MatchObject>;
function sub(repl:Repl, string:String, count:Int = 0):String;
function subn(repl:Repl, string:String, count:Int = 0):String;
var flags(default, null):Int;
var groups(default, null):Int;
var groupindex(default, null):Dict<String, Int>;
var pattern(default, null):String;
}
@:pythonImport("re")
extern class Re {
static var A:Int;
static var ASCII:Int;
static var DEBUG:Int;
static var I:Int;
static var IGNORECASE:Int;
static var L:Int;
static var LOCALE:Int;
static var M:Int;
static var MULTILINE:Int;
static var S:Int;
static var DOTALL:Int;
static var X:Int;
static var VERBOSE:Int;
static var U:Int;
static var UNICODE:Int;
static function compile(pattern:String, ?flags:Int = 0):Regex;
static function match(pattern:Pattern, string:String, flags:Int = 0):Null<MatchObject>;
static function search(pattern:Pattern, string:String, flags:Int = 0):Null<MatchObject>;
static function split(pattern:Pattern, string:String, maxsplit:Int = 0, flags:Int = 0):Array<String>;
static inline function findallDynamic(pattern:Pattern, string:String, flags:Int = 0):Array<Dynamic> {
return python.Syntax.field(pattern, "findall")(string, flags);
}
static inline function findallString(pattern:Pattern, string:String, flags:Int = 0):Array<String> {
return python.Syntax.field(pattern, "findall")(string, flags);
}
static inline function findallTuple(pattern:Pattern, string:String, flags:Int = 0):Array<Tuple<String>> {
return python.Syntax.field(pattern, "findall")(string, flags);
}
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());
}
static function finditer(pattern:Pattern, string:String, flags:Int = 0):NativeIterator<MatchObject>;
@:overload(function(pattern:Pattern, repl:String, string:String, ?count:Int = 0, ?flags:Int = 0):String {})
static function sub(pattern:Pattern, repl:MatchObject->String, string:String, ?count:Int = 0, ?flags:Int = 0):String;
static function subn(pattern:Pattern, repl:Repl, string:String, count:Int = 0, flags:Int = 0):String;
static function escape(string:String):String;
static function purge():Void;
}

View File

@ -0,0 +1,33 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import haxe.io.BytesData;
import python.Tuple;
private typedef Selectable = haxe.extern.EitherType<Int, {function fileno():Int;}>;
@:pythonImport("select")
extern class Select {
static function select<T>(rlist:Array<T>, wlist:Array<T>, xlist:Array<T>, ?timeout:Float):Tuple3<Array<T>, Array<T>, Array<T>>;
}

View File

@ -0,0 +1,33 @@
/*
* Copyright (C)2005-2019 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 python.lib;
@:pythonImport("shutil")
extern class Shutil {
static function rmtree(path:String, ?ignore_errors:Bool = false, ?onerror:python.Exceptions.BaseException->Void):Void;
static function copyfile(src:String, dst:String):Void;
static function copy(src:String, dst:String):Void;
static function copy2(src:String, dst:String):Void;
}

View File

@ -0,0 +1,288 @@
/*
* Copyright (C)2005-2019 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 python.lib;
@:pythonImport("socket")
extern class Socket {
static var AF_APPLETALK:Int;
static var AF_ASH:Int;
static var AF_ATMPVC:Int;
static var AF_ATMSVC:Int;
static var AF_AX25:Int;
static var AF_BLUETOOTH:Int;
static var AF_BRIDGE:Int;
static var AF_CAN:Int;
static var AF_ECONET:Int;
static var AF_INET:Int;
static var AF_INET6:Int;
static var AF_IPX:Int;
static var AF_IRDA:Int;
static var AF_KEY:Int;
static var AF_LLC:Int;
static var AF_NETBEUI:Int;
static var AF_NETLINK:Int;
static var AF_NETROM:Int;
static var AF_PACKET:Int;
static var AF_PPPOX:Int;
static var AF_RDS:Int;
static var AF_ROSE:Int;
static var AF_ROUTE:Int;
static var AF_SECURITY:Int;
static var AF_SNA:Int;
static var AF_TIPC:Int;
static var AF_UNIX:Int;
static var AF_UNSPEC:Int;
static var AF_WANPIPE:Int;
static var AF_X25:Int;
static var AI_ADDRCONFIG:Int;
static var AI_ALL:Int;
static var AI_CANONNAME:Int;
static var AI_NUMERICHOST:Int;
static var AI_NUMERICSERV:Int;
static var AI_PASSIVE:Int;
static var AI_V4MAPPED:Int;
static var BDADDR_ANY:Int;
static var BDADDR_LOCAL:Int;
static var BTPROTO_HCI:Int;
static var BTPROTO_L2CAP:Int;
static var BTPROTO_RFCOMM:Int;
static var BTPROTO_SCO:Int;
static var CAN_EFF_FLAG:Int;
static var CAN_EFF_MASK:Int;
static var CAN_ERR_FLAG:Int;
static var CAN_ERR_MASK:Int;
static var CAN_RAW:Int;
static var CAN_RAW_ERR_FILTER:Int;
static var CAN_RAW_FILTER:Int;
static var CAN_RAW_LOOPBACK:Int;
static var CAN_RAW_RECV_OWN_MSGS:Int;
static var CAN_RTR_FLAG:Int;
static var CAN_SFF_MASK:Int;
static var CAPI:Int;
static var CMSG_LEN:Int;
static var CMSG_SPACE:Int;
static var EAGAIN:Int;
static var EAI_ADDRFAMILY:Int;
static var EAI_AGAIN:Int;
static var EAI_BADFLAGS:Int;
static var EAI_FAIL:Int;
static var EAI_FAMILY:Int;
static var EAI_MEMORY:Int;
static var EAI_NODATA:Int;
static var EAI_NONAME:Int;
static var EAI_OVERFLOW:Int;
static var EAI_SERVICE:Int;
static var EAI_SOCKTYPE:Int;
static var EAI_SYSTEM:Int;
static var EBADF:Int;
static var EWOULDBLOCK:Int;
static var HCI_DATA_DIR:Int;
static var HCI_FILTER:Int;
static var HCI_TIME_STAMP:Int;
static var INADDR_ALLHOSTS_GROUP:Int;
static var INADDR_ANY:Int;
static var INADDR_BROADCAST:Int;
static var INADDR_LOOPBACK:Int;
static var INADDR_MAX_LOCAL_GROUP:Int;
static var INADDR_NONE:Int;
static var INADDR_UNSPEC_GROUP:Int;
static var IPPORT_RESERVED:Int;
static var IPPORT_USERRESERVED:Int;
static var IPPROTO_AH:Int;
static var IPPROTO_DSTOPTS:Int;
static var IPPROTO_EGP:Int;
static var IPPROTO_ESP:Int;
static var IPPROTO_FRAGMENT:Int;
static var IPPROTO_GRE:Int;
static var IPPROTO_HOPOPTS:Int;
static var IPPROTO_ICMP:Int;
static var IPPROTO_ICMPV6:Int;
static var IPPROTO_IDP:Int;
static var IPPROTO_IGMP:Int;
static var IPPROTO_IP:Int;
static var IPPROTO_IPIP:Int;
static var IPPROTO_IPV6:Int;
static var IPPROTO_NONE:Int;
static var IPPROTO_PIM:Int;
static var IPPROTO_PUP:Int;
static var IPPROTO_RAW:Int;
static var IPPROTO_ROUTING:Int;
static var IPPROTO_RSVP:Int;
static var IPPROTO_SCTP:Int;
static var IPPROTO_TCP:Int;
static var IPPROTO_TP:Int;
static var IPPROTO_UDP:Int;
static var IPV6_CHECKSUM:Int;
static var IPV6_DSTOPTS:Int;
static var IPV6_HOPLIMIT:Int;
static var IPV6_HOPOPTS:Int;
static var IPV6_JOIN_GROUP:Int;
static var IPV6_LEAVE_GROUP:Int;
static var IPV6_MULTICAST_HOPS:Int;
static var IPV6_MULTICAST_IF:Int;
static var IPV6_MULTICAST_LOOP:Int;
static var IPV6_NEXTHOP:Int;
static var IPV6_PKTINFO:Int;
static var IPV6_RECVDSTOPTS:Int;
static var IPV6_RECVHOPLIMIT:Int;
static var IPV6_RECVHOPOPTS:Int;
static var IPV6_RECVPKTINFO:Int;
static var IPV6_RECVRTHDR:Int;
static var IPV6_RECVTCLASS:Int;
static var IPV6_RTHDR:Int;
static var IPV6_RTHDRDSTOPTS:Int;
static var IPV6_RTHDR_TYPE_0:Int;
static var IPV6_TCLASS:Int;
static var IPV6_UNICAST_HOPS:Int;
static var IPV6_V6ONLY:Int;
static var IP_ADD_MEMBERSHIP:Int;
static var IP_DEFAULT_MULTICAST_LOOP:Int;
static var IP_DEFAULT_MULTICAST_TTL:Int;
static var IP_DROP_MEMBERSHIP:Int;
static var IP_HDRINCL:Int;
static var IP_MAX_MEMBERSHIPS:Int;
static var IP_MULTICAST_IF:Int;
static var IP_MULTICAST_LOOP:Int;
static var IP_MULTICAST_TTL:Int;
static var IP_OPTIONS:Int;
static var IP_RECVOPTS:Int;
static var IP_RECVRETOPTS:Int;
static var IP_RETOPTS:Int;
static var IP_TOS:Int;
static var IP_TRANSPARENT:Int;
static var IP_TTL:Int;
static var MSG_CMSG_CLOEXEC:Int;
static var MSG_CONFIRM:Int;
static var MSG_CTRUNC:Int;
static var MSG_DONTROUTE:Int;
static var MSG_DONTWAIT:Int;
static var MSG_EOR:Int;
static var MSG_ERRQUEUE:Int;
static var MSG_MORE:Int;
static var MSG_NOSIGNAL:Int;
static var MSG_OOB:Int;
static var MSG_PEEK:Int;
static var MSG_TRUNC:Int;
static var MSG_WAITALL:Int;
static var NETLINK_DNRTMSG:Int;
static var NETLINK_FIREWALL:Int;
static var NETLINK_IP6_FW:Int;
static var NETLINK_NFLOG:Int;
static var NETLINK_ROUTE:Int;
static var NETLINK_USERSOCK:Int;
static var NETLINK_XFRM:Int;
static var NI_DGRAM:Int;
static var NI_MAXHOST:Int;
static var NI_MAXSERV:Int;
static var NI_NAMEREQD:Int;
static var NI_NOFQDN:Int;
static var NI_NUMERICHOST:Int;
static var NI_NUMERICSERV:Int;
static var PACKET_BROADCAST:Int;
static var PACKET_FASTROUTE:Int;
static var PACKET_HOST:Int;
static var PACKET_LOOPBACK:Int;
static var PACKET_MULTICAST:Int;
static var PACKET_OTHERHOST:Int;
static var PACKET_OUTGOING:Int;
static var PF_CAN:Int;
static var PF_PACKET:Int;
static var PF_RDS:Int;
static var SCM_CREDENTIALS:Int;
static var SCM_RIGHTS:Int;
static var SHUT_RD:Int;
static var SHUT_RDWR:Int;
static var SHUT_WR:Int;
static var SOCK_CLOEXEC:Int;
static var SOCK_DGRAM:Int;
static var SOCK_NONBLOCK:Int;
static var SOCK_RAW:Int;
static var SOCK_RDM:Int;
static var SOCK_SEQPACKET:Int;
static var SOCK_STREAM:Int;
static var SOL_CAN_BASE:Int;
static var SOL_CAN_RAW:Int;
static var SOL_HCI:Int;
static var SOL_IP:Int;
static var SOL_SOCKET:Int;
static var SOL_TCP:Int;
static var SOL_TIPC:Int;
static var SOL_UDP:Int;
static var SOMAXCONN:Int;
static var SO_ACCEPTCONN:Int;
static var SO_BINDTODEVICE:Int;
static var SO_BROADCAST:Int;
static var SO_DEBUG:Int;
static var SO_DONTROUTE:Int;
static var SO_ERROR:Int;
static var SO_KEEPALIVE:Int;
static var SO_LINGER:Int;
static var SO_OOBINLINE:Int;
static var SO_PASSCRED:Int;
static var SO_PEERCRED:Int;
static var SO_RCVBUF:Int;
static var SO_RCVLOWAT:Int;
static var SO_RCVTIMEO:Int;
static var SO_REUSEADDR:Int;
static var SO_REUSEPORT:Int;
static var SO_SNDBUF:Int;
static var SO_SNDLOWAT:Int;
static var SO_SNDTIMEO:Int;
static var SO_TYPE:Int;
static var TCP_CORK:Int;
static var TCP_DEFER_ACCEPT:Int;
static var TCP_INFO:Int;
static var TCP_KEEPCNT:Int;
static var TCP_KEEPIDLE:Int;
static var TCP_KEEPINTVL:Int;
static var TCP_LINGER2:Int;
static var TCP_MAXSEG:Int;
static var TCP_NODELAY:Int;
static var TCP_QUICKACK:Int;
static var TCP_SYNCNT:Int;
static var TCP_WINDOW_CLAMP:Int;
static var TIPC_ADDR_ID:Int;
static var TIPC_ADDR_NAME:Int;
static var TIPC_ADDR_NAMESEQ:Int;
static var TIPC_CFG_SRV:Int;
static var TIPC_CLUSTER_SCOPE:Int;
static var TIPC_CONN_TIMEOUT:Int;
static var TIPC_CRITICAL_IMPORTANCE:Int;
static var TIPC_DEST_DROPPABLE:Int;
static var TIPC_HIGH_IMPORTANCE:Int;
static var TIPC_IMPORTANCE:Int;
static var TIPC_LOW_IMPORTANCE:Int;
static var TIPC_MEDIUM_IMPORTANCE:Int;
static var TIPC_NODE_SCOPE:Int;
static var TIPC_PUBLISHED:Int;
static var TIPC_SRC_DROPPABLE:Int;
static var TIPC_SUBSCR_TIMEOUT:Int;
static var TIPC_SUB_CANCEL:Int;
static var TIPC_SUB_PORTS:Int;
static var TIPC_SUB_SERVICE:Int;
static var TIPC_TOP_SRV:Int;
static var TIPC_WAIT_FOREVER:Int;
static var TIPC_WITHDRAWN:Int;
static var TIPC_ZONE_SCOPE:Int;
static var _GLOBAL_DEFAULT_TIMEOUT:Int;
}

View File

@ -0,0 +1,63 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.lib.ssl.SSLContext;
@:pythonImport("ssl")
extern class Ssl {
@:require(python_version >= 3.4)
static function create_default_context(purpose:String):SSLContext;
/**
Prevents a TLSv1 connection. This option is only applicable in conjunction
with PROTOCOL_TLS. It prevents the peers from choosing TLSv1 as the
protocol version.
**/
static var OP_NO_TLSv1:Int;
/**
Prevents a TLSv1.1 connection. This option is only applicable in conjunction
with PROTOCOL_TLS. It prevents the peers from choosing TLSv1.1 as the
protocol version. Available only with openssl version 1.0.1+.
since python 3.4
**/
@:require(python_version >= 3.4)
static var OP_NO_TLSv1_1:Int;
static var OP_NO_SSLv3:Int;
static var OP_NO_SSLv2:Int;
static var OP_NO_COMPRESSION:Int;
#if (python_version >= 3.6)
@:deprecated("deprecated, use PROTOCOL_TLS instead")
#end
static var PROTOCOL_SSLv23:String;
@:require(python_version >= 3.6)
static var PROTOCOL_TLS:String;
static var CERT_REQUIRED:Int;
}

View File

@ -0,0 +1,52 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import haxe.extern.EitherType;
extern class StartupInfo {
var dwFlags:Int;
var wShowWindow:Int;
}
@:pythonImport("subprocess")
extern class Subprocess {
static function STARTUPINFO():StartupInfo;
static var STD_INPUT_HANDLE:Int;
static var STD_OUTPUT_HANDLE:Int;
static var STD_ERROR_HANDLE:Int;
static var SW_HIDE:Int;
static var STARTF_USESTDHANDLES:Int;
static var STARTF_USESHOWWINDOW:Int;
static var CREATE_NEW_CONSOLE:Int;
static var CREATE_NEW_PROCESS_GROUP:Int;
static var PIPE:Int;
static var STDOUT:Int;
static function call(args:EitherType<String, Array<String>>, ?kwArgs:python.KwArgs<Dynamic>):Int;
}

View File

@ -0,0 +1,58 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.Exceptions.BaseException;
import python.lib.io.FileIO;
import python.lib.io.RawIOBase;
import python.lib.io.TextIOBase;
import python.Tuple;
extern class TB {}
extern class Frame {}
@:pythonImport("sys")
extern class Sys {
static var argv(default, never):Array<String>;
static var executable(default, never):String;
static function exit(x:Int):Void;
static function getfilesystemencoding():String;
static var version:String;
static var platform:String;
static var stdout(default, never):TextIOBase;
static var stdin(default, never):TextIOBase;
static var stderr(default, never):TextIOBase;
static function getsizeof(t:Dynamic):Int;
static var maxsize:Int;
static function exc_info<T:BaseException>():Tuple3<Class<T>, T, TB>;
static var version_info:Tuple5<Int, Int, Int, String, Int>;
}

View File

@ -0,0 +1,28 @@
/*
* Copyright (C)2005-2019 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 python.lib;
@:pythonImport("tempfile")
extern class Tempfile {
static function gettempdir():String;
}

View File

@ -0,0 +1,35 @@
/*
* Copyright (C)2005-2019 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 python.lib;
abstract TermiosSettings(Dynamic) {}
@:pythonImport("termios", ignoreError = true)
extern class Termios {
static var TCSADRAIN:Int;
static var ECHO:Int;
static function tcgetattr(fileNo:Int):TermiosSettings;
static function tcsetattr(fileNo:Int, when:Int, settings:TermiosSettings):Void;
}

View File

@ -0,0 +1,30 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.Tuple;
@:pythonImport("_thread")
extern class ThreadLowLevel {
static function start_new_thread(f:Void->Void, args:Tuple<Dynamic>):Dynamic;
}

View File

@ -0,0 +1,39 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.lib.threading.Thread;
@:pythonImport("threading")
extern class Threading {
static function active_count():Int;
static function current_thread():Thread;
static function get_ident():Int;
static function enumerate():Array<Thread>;
static function main_thread():Thread;
static function settrace(func:Dynamic):Void;
static function setprofile(func:Dynamic):Void;
static function stack_size(?size:Int):Int;
static function local():Dynamic;
static var TIMEOUT_MAX:Float;
}

View File

@ -0,0 +1,33 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.lib.time.StructTime;
@:pythonImport("time")
extern class Time {
static function time():Float;
static function clock():Float;
static function sleep(t:Float):Void;
static function mktime(s:StructTime):Float;
}

View File

@ -0,0 +1,28 @@
/*
* Copyright (C)2005-2019 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 python.lib;
@:pythonImport("timeit")
extern class Timeit {
static function default_timer():Float;
}

View File

@ -0,0 +1,35 @@
/*
* Copyright (C)2005-2019 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 python.lib;
import python.lib.Sys;
import python.lib.Sys.Frame;
import python.Tuple;
@:pythonImport("traceback")
extern class Traceback {
static function extract_stack(?f:Frame, ?limit:Int):Array<StackItem>;
static function extract_tb(tb:Sys.TB, ?limit:Int):Array<StackItem>;
}
private typedef StackItem = Tuple4<String, Int, String, String>;

View File

@ -0,0 +1,28 @@
/*
* Copyright (C)2005-2019 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 python.lib;
@:pythonImport("tty", ignoreError = true)
extern class Tty {
static function setraw(fileNo:Int):Void;
}

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