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,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;
}