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,41 @@
/*
* 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 lua;
/**
Externs for the "bit" class that is required for Haxe lua
**/
@:native("_hx_bit")
extern class Bit {
static function bnot(x:Float):Int;
static function band(a:Float, b:Float):Int;
static function bor(a:Float, b:Float):Int;
static function bxor(a:Float, b:Float):Int;
static function lshift(x:Float, places:Int):Int;
static function rshift(x:Float, places:Int):Int;
static function arshift(x:Float, places:Int):Int;
static function mod(numerator:Float, denominator:Float):Int;
static function __init__():Void {
untyped _hx_bit = __define_feature__("use._bitop", _hx_bit);
}
}

View File

@ -0,0 +1,314 @@
/*
* 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 lua;
import haxe.SysTools;
@:dox(hide)
class Boot {
// Used temporarily for bind()
static var _:Dynamic;
static var _fid = 0;
static var Max_Int32 = 2147483647;
static var Min_Int32 = -2147483648;
// A max stack size to respect for unpack operations
public static var MAXSTACKSIZE(default, null) = 1000;
public static var platformBigEndian = NativeStringTools.byte(NativeStringTools.dump(function() {}), 7) > 0;
static var hiddenFields:Table<String, Bool> = untyped __lua__("{__id__=true, hx__closures=true, super=true, prototype=true, __fields__=true, __ifields__=true, __class__=true, __properties__=true}");
static function __unhtml(s:String)
return s.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;");
/**
Indicates if the given object is a class.
**/
static inline public function isClass(o:Dynamic):Bool {
if (Lua.type(o) != "table")
return false;
else
return untyped __define_feature__("lua.Boot.isClass", o.__name__);
}
/**
Indicates if the given object is a enum.
**/
static inline public function isEnum(e:Dynamic):Bool {
if (Lua.type(e) != "table")
return false;
else
return untyped __define_feature__("lua.Boot.isEnum", e.__ename__);
}
/**
Returns the class of a given object, and defines the getClass feature
for the given class.
**/
static inline public function getClass(o:Dynamic):Class<Dynamic> {
if (Std.isOfType(o, Array))
return Array;
else if (Std.isOfType(o, String))
return String;
else {
var cl = untyped __define_feature__("lua.Boot.getClass", o.__class__);
if (cl != null)
return cl;
else
return null;
}
}
/**
Indicates if the given object is an instance of the given Type
**/
@:ifFeature("typed_catch")
private static function __instanceof(o:Dynamic, cl:Dynamic) {
if (cl == null)
return false;
switch (cl) {
case Int:
return (Lua.type(o) == "number" && clampInt32(o) == o);
case Float:
return Lua.type(o) == "number";
case Bool:
return Lua.type(o) == "boolean";
case String:
return Lua.type(o) == "string";
case Thread:
return Lua.type(o) == "thread";
case UserData:
return Lua.type(o) == "userdata";
case Array:
return isArray(o);
case Table:
return Lua.type(o) == "table";
case Dynamic:
return o != null;
default:
{
if (o != null && Lua.type(o) == "table" && Lua.type(cl) == "table") {
if (extendsOrImplements(getClass(o), cl))
return true;
// We've exhausted standard inheritance checks. Check for simple Class/Enum eqauality
// Also, do not use isClass/isEnum here, perform raw checks
untyped __feature__("Class.*", if (cl == Class && o.__name__ != null) return true);
untyped __feature__("Enum.*", if (cl == Enum && o.__ename__ != null) return true);
// last chance, is it an enum instance?
return o.__enum__ == cl;
} else {
return false;
}
}
}
}
static function isArray(o:Dynamic):Bool {
return Lua.type(o) == "table"
&& untyped o.__enum__ == null && Lua.getmetatable(o) != null && Lua.getmetatable(o).__index == untyped Array.prototype;
}
/**
Indicates if the given object inherits from the given class
**/
static function inheritsFrom(o:Dynamic, cl:Class<Dynamic>):Bool {
while (Lua.getmetatable(o) != null && Lua.getmetatable(o).__index != null) {
if (Lua.getmetatable(o).__index == untyped cl.prototype)
return true;
o = Lua.getmetatable(o).__index;
}
return false;
}
@:ifFeature("typed_cast")
private static function __cast(o:Dynamic, t:Dynamic) {
if (o == null || __instanceof(o, t))
return o;
else
throw "Cannot cast " + Std.string(o) + " to " + Std.string(t);
}
/**
Define an array from the given table
**/
public inline static function defArray<T>(tab:Table<Int, T>, ?length:Int):Array<T> {
if (length == null) {
length = TableTools.maxn(tab);
if (length > 0) {
var head = tab[1];
Table.remove(tab, 1);
tab[0] = head;
return untyped _hx_tab_array(tab, length);
} else {
return [];
}
} else {
return untyped _hx_tab_array(tab, length);
}
}
/**
Create a Haxe object from the given table structure
**/
public inline static function tableToObject<T>(t:Table<String, T>):Dynamic<T> {
return untyped _hx_o(t);
}
/**
Get Date object as string representation
**/
public static function dateStr(date:std.Date):String {
var m = date.getMonth() + 1;
var d = date.getDate();
var h = date.getHours();
var mi = date.getMinutes();
var s = date.getSeconds();
return date.getFullYear() + "-" + (if (m < 10) "0" + m else "" + m) + "-" + (if (d < 10) "0" + d else "" + d) + " "
+ (if (h < 10) "0" + h else "" + h) + ":" + (if (mi < 10) "0" + mi else "" + mi) + ":" + (if (s < 10) "0" + s else "" + s);
}
/**
A 32 bit clamp function for numbers
**/
public inline static function clampInt32(x:Float) {
return untyped _hx_bit_clamp(x);
}
/**
Create a standard date object from a lua string representation
**/
public static function strDate(s:String):std.Date {
switch (s.length) {
case 8: // hh:mm:ss
var k = s.split(":");
return std.Date.fromTime(Lua.tonumber(k[0]) * 3600000. + Lua.tonumber(k[1]) * 60000. + Lua.tonumber(k[2]) * 1000.);
case 10: // YYYY-MM-DD
var k = s.split("-");
return new std.Date(Lua.tonumber(k[0]), Lua.tonumber(k[1]) - 1, Lua.tonumber(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 std.Date(Lua.tonumber(y[0]), Lua.tonumber(y[1]) - 1, Lua.tonumber(y[2]), Lua.tonumber(t[0]), Lua.tonumber(t[1]), Lua.tonumber(t[2]));
default:
throw "Invalid date format : " + s;
}
}
/**
Helper method to determine if class cl1 extends, implements, or otherwise equals cl2
**/
public static function extendsOrImplements(cl1:Class<Dynamic>, cl2:Class<Dynamic>):Bool {
if (cl1 == null || cl2 == null)
return false;
else if (cl1 == cl2)
return true;
else if (untyped cl1.__interfaces__ != null) {
var intf = untyped cl1.__interfaces__;
for (i in 1...(TableTools.maxn(intf) + 1)) {
// check each interface, including extended interfaces
if (extendsOrImplements(intf[i], cl2))
return true;
}
}
// check standard inheritance
return extendsOrImplements(untyped cl1.__super__, cl2);
}
/**
Returns a shell escaped version of "cmd" along with any args
**/
public static function shellEscapeCmd(cmd:String, ?args:Array<String>) {
if (args != null) {
switch (Sys.systemName()) {
case "Windows":
cmd = [
for (a in [StringTools.replace(cmd, "/", "\\")].concat(args))
SysTools.quoteWinArg(a, true)
].join(" ");
case _:
cmd = [cmd].concat(args).map(SysTools.quoteUnixArg).join(" ");
}
}
return cmd;
}
/**
Returns a temp file path that can be used for reading and writing
**/
public static function tempFile():String {
switch (Sys.systemName()) {
case "Windows":
return haxe.io.Path.join([Os.getenv("TMP"), Os.tmpname()]);
default:
return Os.tmpname();
}
}
static var os_patterns(get,default):Map<String,Array<String>>;
static function get_os_patterns():Map<String,Array<String>> {
if(os_patterns == null) {
os_patterns = [
'Windows' => ['windows', '^mingw', '^cygwin'],
'Linux' => ['linux'],
'Mac' => ['mac', 'darwin', 'osx'],
'BSD' => ['bsd$'],
'Solaris' => ['SunOS']
];
}
return os_patterns;
}
public static function systemName():String {
var os:String = null;
if (untyped jit != null && untyped jit.os != null) {
os = untyped jit.os;
os = os.toLowerCase();
} else {
var popen_status:Bool = false;
var popen_result:lua.FileHandle = null;
untyped __lua__("popen_status, popen_result = pcall(_G.io.popen, '')");
if (popen_status) {
popen_result.close();
os = lua.Io.popen('uname -s', 'r').read('*l').toLowerCase();
} else {
os = lua.Os.getenv('OS').toLowerCase();
}
}
for (k in os_patterns.keys()) {
for (p in os_patterns.get(k)) {
if (lua.NativeStringTools.match(os, p) != null) {
return k;
}
}
}
return null;
}
}

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 lua;
import haxe.extern.Rest;
import haxe.Constraints.Function;
/**
Externs for native Lua coroutines.
**/
@:native("_G.coroutine")
extern class Coroutine<T:Function> extends Thread {
/**
Creates a new coroutine, with body `f`. `f` must be a Lua function.
**/
static function create<T:Function>(f:T):Coroutine<T>;
/**
Returns the running coroutine plus a boolean, true when the running coroutine is the main one.
**/
static function running():CoroutineRunning;
/**
Returns the status of coroutine.
**/
static function status(c:Coroutine<Dynamic>):CoroutineState;
/**
Starts or continues the execution of coroutine.
The first time you resume a coroutine, it starts running its body.
The values `args` are passed as the arguments to the body function.
If the coroutine has yielded, `resume` restarts it;
the values `args` are passed as the results from the yield.
If the coroutine runs without any errors, `resume` returns `true` plus any
values passed to `yield` (if the coroutine yields) or any values returned
by the body function (if the coroutine terminates). If there is any error,
`resume` returns `false` plus the error message.
**/
static function resume<A, B>(c:Coroutine<Dynamic>, args:Rest<A>):CoroutineResume<B>;
/**
Suspends the execution of the calling coroutine.
The coroutine cannot be running a C function, a metamethod, or an iterator.
Any arguments to `yield` are passed as extra results to `resume`.
**/
static function yield<T>(args:Rest<Dynamic>):T;
/**
Creates a new coroutine, with body `f`.
Returns a function that resumes the coroutine each time it is called.
Any arguments passed to the function behave as the extra arguments to `resume`.
Returns the same values returned by `resume`, except the first boolean.
In case of error, propagates the error.
**/
static function wrap<T:Function>(f:T):T;
}
/**
A enumerator that describes the output of `Coroutine.status()`.
**/
enum abstract CoroutineState(String) {
/**
If the coroutine is suspended in a call to yield, or if it has not started
running yet.
**/
var Suspended = "suspended";
/**
If the coroutine is running.
**/
var Running = "running";
/**
If the coroutine is active but not running. That is, it has resumed another
coroutine.
**/
var Normal = "normal";
/**
If the coroutine has finished its body function or if it has stopped with
an error.
**/
var Dead = "dead";
}
@:multiReturn
extern class CoroutineResume<T> {
var success:Bool;
var result:T;
}
@:multiReturn
extern class CoroutineRunning {
var coroutine:Coroutine<Dynamic>;
var status:Bool;
}

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.
*/
package lua;
/**
Externs for the "debug" class for Haxe lua
**/
import haxe.Constraints.Function;
import lua.Table.AnyTable;
@:native("debug")
extern class Debug {
/**
This function returns the name and the value of the local variable with
index local of the function at level level of the stack.
**/
static function getlocal(stackLevel:Int, idx:Int):Dynamic;
/**
This function assigns the value value to the local variable with index
local of the function at level level of the stack.
Call `getinfo` to check whether the level is valid.
**/
static function setlocal(stackLevel:Int, varName:String, value:Dynamic):Void;
/**
Returns a table with information about a function.
**/
static function getinfo(stackLevel:Int):DebugInfo;
/**
Sets the given function as a hook.
When called without arguments, `Debug.sethook` turns off the hook.
**/
static function sethook(?fun:Function, ?monitor:String):Void;
/**
Enters an interactive mode with the user, running each string that the user enters.
Using simple commands and other debug facilities, the user can inspect
global and local variables, change their values, evaluate expressions,
and so on. A line containing only the word `cont` finishes this function,
so that the caller continues its execution.
Note that commands for `Debug.debug` are not lexically nested within any
function, and so have no direct access to local variables.
**/
static function debug():Void;
/**
Returns the current hook settings of the thread, as three values:
the current hook function, the current hook mask, and the current hook count
(as set by the `Debug.sethook` function).
**/
static function gethook(thread:Thread):Function;
/**
Returns the registry table.
**/
static function getregistry():AnyTable;
/**
Returns the metatable of the given `value` or `null` if it does not have a metatable.
**/
static function getmetatable(value:AnyTable):AnyTable;
/**
Sets the metatable for the given `value` to the given `table` (can be `null`).
**/
static function setmetatable(value:AnyTable, table:AnyTable):Void;
/**
This function returns the name and the value of the upvalue with index `up`
of the function `f`. The function returns `null` if there is no upvalue with
the given index.
**/
static function getupvalue(f:Function, up:Int):Dynamic;
/**
This function assigns the value value to the upvalue with index up of
the function `f`. The function returns `null` if there is no upvalue with
the given index. Otherwise, it returns the name of the upvalue.
**/
static function setupvalue(f:Function, up:Int, val:Dynamic):Void;
/**
Returns the Lua value associated to `val`.
If `val` is not a `UserData`, returns `null`.
**/
static function getuservalue(val:Dynamic):Dynamic;
/**
Sets the given value as the Lua value associated to the given udata.
`udata` must be a full `UserData`.
**/
static function setuservalue(udata:Dynamic, val:Dynamic):Void;
/**
Returns a string with a traceback of the call stack.
@param message (optional) is appended at the beginning of the traceback.
@param level (optional) tells at which level to start the traceback.
default is `1`, the function calling traceback.
**/
static function traceback(?thread:Thread, ?message:String, ?level:Int):String;
/**
Returns a unique identifier (as a light userdata) for the upvalue numbered
`n` from the given function `f`.
**/
static function upvalueid(f:Function, n:Int):Dynamic;
/**
Make the `n1`-th upvalue of the Lua closure `f1` refer to the `n2`-th
upvalue of the Lua closure `f2`.
**/
static function upvaluejoin(f1:Function, n1:Int, f2:Function, n2:Int):Void;
}
/**
A enumerator that describes the output of `Debug.getinfo()`.
**/
typedef DebugInfo = {
currentline:Int,
func:Function,
istailcall:Bool,
isvararg:Bool,
lastlinedefined:Int,
linedefined:Int,
name:String,
namewhat:String,
nparams:Int,
nups:Int,
short_src:String,
source:String,
what:String
}

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 lua;
import haxe.Constraints.Function;
import lua.Table;
#if lua_jit
@:luaRequire("ffi")
extern class Ffi {
function new(type:String, arg:Dynamic);
// Declaring and accessing external symbols
static function cdef(def:String):Void;
static var C:Dynamic;
static function gc(cdata:Dynamic, finalizer:Function):Void;
static function load(name:String, ?global:Bool):Dynamic;
static function metatype<T>(ct:Ctype<T>, metatable:Table<Dynamic, Dynamic>):Ctype<T>;
static function typeof(str:String):Ctype<Dynamic>;
// C Type functionality
static function alignof<T>(ct:Ctype<T>):Int;
static function istype<T>(ct:Ctype<T>, obj:Dynamic):Bool;
static function offsetof<T>(ct:Ctype<T>, field:String):Int;
static function sizeof<T>(ct:Ctype<T>, ?nelem:Int):Int;
// Utility functionality
static function errno(?newerr:Int):Int;
static function fill(dst:Dynamic, len:Int, c:Int):Void;
static function string(ptr:Dynamic, ?len:Int):String;
@:overload(function(dst:Dynamic, str:String):Dynamic {})
static function copy(dst:Dynamic, src:Dynamic, len:Int):String;
// Target specific functionality
static var os:String;
static var arch:String;
static function abi(param:String):Bool;
}
extern class Ctype<T> {}
// TODO FFI callback type (gc methods)
#end

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 lua;
import haxe.extern.EitherType;
import haxe.extern.Rest;
import sys.io.FileInput;
extern class FileHandle extends UserData {
function flush():Void;
function read(arg:Rest<EitherType<String, Int>>):String;
function close():Void;
function write(str:String):Void;
@:overload(function():Int {})
@:overload(function(arg:String):Int {})
function seek(arg:String, pos:Int):Void;
}

View File

@ -0,0 +1,46 @@
/*
* 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 lua;
/**
An implementation of the Haxe iterator data structure needed for identical
lua iterator behavior.
**/
class HaxeIterator<T> {
var state:T;
var f:Void->T;
public function new(f:Void->T) {
this.f = f;
this.state = f();
}
public function next() {
var ret = this.state;
this.state = this.f();
return ret;
}
public function hasNext()
return this.state != null;
}

View File

@ -0,0 +1,129 @@
/*
* 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 lua;
import haxe.extern.Rest;
/**
Input and Output Facilities
**/
@:native("_G.io")
extern class Io {
static var stdin:FileHandle;
static var stderr:FileHandle;
static var stdout:FileHandle;
/**
Function to close regular files.
**/
static function close(?file:FileHandle):Void;
/**
Saves any written data to file.
**/
static function flush():Void;
/**
When called with a file name, it opens the named file (in text mode),
and sets its handle as the default input file. When called with a file handle,
it simply sets this file handle as the default input file.
When called without parameters, it returns the current default input file.
In case of errors this function raises the error, instead of returning an
error code.
**/
@:overload(function(file:String):Void {})
static function input(file:FileHandle):Void;
/**
Opens the given file name in read mode and returns an iterator function that,
each time it is called, returns a new line from the file.
**/
static function lines(?file:String):NativeIterator<String>;
/**
This function opens a file, in the mode specified in the string mode.
It returns a new file handle, or, in case of errors, `null` plus an error message.
The mode string can be any of the following:
* `"r"`: read mode (the default)
* `"w"`: write mode
* `"a"`: append mode
* `"r+"`: update mode, all previous data is preserved
* `"w+"`: update mode, all previous data is erased
* `"a+"`: append update mode, previous data is preserved, writing is only
allowed at the end of file
The mode string can also have a `b` at the end, which is needed in some systems
to open the file in binary mode. This string is exactly what is used in the
standard C function fopen.
**/
static function open(filename:String, ?mode:String):FileHandle;
/**
Starts program `command` in a separated process and returns a file handle that
you can use to read data from this program (if mode is `"r"`, the default)
or to write data to this program (if mode is `"w"`).
This function is system dependent and is not available on all platforms.
**/
static function popen(command:String, ?mode:String):FileHandle;
@:overload(function(?count:Int):String {})
static function read(?filename:String):String;
/**
Writes the value of each of its arguments to the file. The arguments must
be strings or numbers.
To write other values, use `Lua.tostring` or `NativeStringTools.format`
before write.
**/
static function write(v:Rest<String>):Void;
static function output(?file:String):FileHandle;
/**
Returns a handle for a temporary file. This file is opened in update mode
and it is automatically removed when the program ends.
**/
static function tmpfile():FileHandle;
/**
Checks whether `obj` is a valid file handle.
**/
static function type(obj:FileHandle):IoType;
}
/**
A enumerator that describes the output of `Io.type()`.
**/
enum abstract IoType(String) {
var File = "file";
var ClosedFile = "closed file";
var NotAFile = null;
@:to public function toString() {
return this;
}
}

View File

@ -0,0 +1,19 @@
package lua;
import haxe.Constraints.Function;
#if lua_jit
@:native("_G.jit")
extern class Jit {
static function on(?f:Function, ?recursive:Bool):Void;
static function off(?f:Function, ?recursive:Bool):Void;
static function flush(?f:Function, ?recursive:Bool):Void;
static function status():Bool;
static var version:String;
static var version_num:Int;
static var os:String;
static var arch:String;
static var opt:{start:Function};
static var util:Dynamic;
}
#end

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 lua;
import lua.Lua;
import lua.Io;
/**
Platform-specific Lua Library. Provides some platform-specific functions
for the Lua target, such as conversion from Haxe types to native types
and vice-versa.
**/
class Lib {
/**
Print the specified value on the default output followed by a newline character.
**/
public static inline function println(v:Dynamic):Void {
Lua.print(Std.string(v));
}
/**
Print the specified value on the default output.
**/
public static inline function print(v:Dynamic):Void {
Io.write(Std.string(v));
Io.flush();
}
/**
Perform Lua-style pattern quoting on a given string.
**/
public inline static function patternQuote(str:String):String {
return NativeStringTools.gsub(str, "[%(%)%.%%%+%-%*%?%[%]%^%$]", function(c:String) {
return "%" + c;
});
}
/**
Fills an array with the result of a simple iterator.
**/
public static function fillArray<T>(itr:Void->T):Array<T> {
var i:T = null;
var ret:Array<T> = [];
while ({
i = itr();
i != null;
}) {
ret.push(i);
}
return ret;
}
/**
Simple test for the presence of an available shell.
**/
public static function isShellAvailable():Bool {
var ret:Dynamic = Os.execute();
if (Lua.type(ret) == "bool") {
return ret;
} else {
return ret != 0;
}
}
}

View File

@ -0,0 +1,32 @@
/*
* 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 lua;
enum abstract LocaleCategory(String) {
var All = "all";
var Collate = "collate";
var Ctype = "ctype";
var Monetary = "monetary";
var Numeric = "numeric";
var Time = "time";
}

View File

@ -0,0 +1,242 @@
/*
* 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 lua;
import haxe.extern.Rest;
import haxe.Constraints.Function;
import haxe.extern.Rest;
/**
These are all global static methods within Lua.
**/
@:native("_G")
extern class Lua {
/**
A global variable that holds a string containing the current interpreter
version.
**/
static var _VERSION:String;
static var arg:Table<Int, String>;
/**
Pushes onto the stack the metatable in the registry.
**/
static function getmetatable(tbl:Table<Dynamic, Dynamic>):Table<Dynamic, Dynamic>;
/**
Pops a table from the stack and sets it as the new metatable for the value
at the given acceptable index.
**/
static function setmetatable(tbl:Table<Dynamic, Dynamic>, mtbl:Table<Dynamic, Dynamic>):Table<Dynamic, Dynamic>;
/**
Pops a table from the stack and sets it as the new environment for the value
at the given index. If the value at the given index is neither a function nor
a thread nor a userdata, lua_setfenv returns `0`.
Otherwise it returns `1`.
**/
static function setfenv(i:Int, tbl:Table<Dynamic, Dynamic>):Void;
/**
Allows a program to traverse all fields of a table.
Its first argument is a table and its second argument is an index in this
table. `next` returns the next index of the table and its associated value.
When `i` is `null`, `next` returns an initial index and its associated value.
When called with the last index, or with `null` in an empty table, `next`
returns `null`. In particular, you can use `next(t)` to check whether a
table is empty.
The order in which the indices are enumerated is not specified, even for
numeric indices. (To traverse a table in numeric order, use a numerical for
or the `ipairs` function).
The behavior of next is undefined if, during the traversal, any value
to a non-existent field in the table is assigned. Existing fields may
however be modified. In particular, existing fields may be cleared.
**/
static function next<K, V>(k:Table<K, V>, ?i:K):NextResult<K, V>;
/**
Receives an argument of any type and converts it to a string in a reasonable
format.
For complete control of how numbers are converted, use`NativeStringTools.format`.
**/
static function tostring(v:Dynamic):String;
static function ipairs<K, V>(t:Table<K, V>):IPairsResult<K, V>;
static function pairs<K, V>(t:Table<K, V>):PairsResult<K, V>;
static function require(module:String):Dynamic;
/**
Converts the Lua value at the given acceptable base to `Int`.
The Lua value must be a number or a string convertible to a number,
otherwise `tonumber` returns `0`.
**/
static function tonumber(str:String, ?base:Int):Int;
/**
Returns the Lua type of its only argument as a string.
The possible results of this function are:
* `"nil"` (a string, not the Lua value nil),
* `"number"`
* `"string"`
* `"boolean"`
* `"table"`
* `"function"`
* `"thread"`
* `"userdata"`
**/
static function type(v:Dynamic):String;
/**
Receives any number of arguments, and prints their values to stdout,
using the tostring function to convert them to strings.
`print` is not intended for formatted output, but only as a quick way to show
a value, typically for debugging.
For complete control of how numbers are converted, use `NativeStringTools.format`.
**/
static function print(v:haxe.extern.Rest<Dynamic>):Void;
/**
If `n` is a number, returns all arguments after argument number `n`.
Otherwise, `n` must be the string `"#"`, and select returns the total
number of extra arguments it received.
**/
static function select(n:Dynamic, rest:Rest<Dynamic>):Dynamic;
/**
Gets the real value of `table[index]`, without invoking any metamethod.
**/
static function rawget<K, V>(t:Table<K, V>, k:K):V;
/**
Sets the real value of `table[index]` to value, without invoking any metamethod.
**/
static function rawset<K, V>(t:Table<K, V>, k:K, v:V):Void;
/**
This function is a generic interface to the garbage collector.
It performs different functions according to its first argument.
**/
static function collectgarbage(opt:CollectGarbageOption, ?arg:Int):Int;
/**
Issues an error when the value of its argument `v` is `false` (i.e., `null`
or `false`) otherwise, returns all its arguments. message is an error message.
when absent, it defaults to "assertion failed!"
**/
static function assert<T>(v:T, ?message:String):T;
/**
Loads and runs the given file.
**/
static function dofile(filename:String):Void;
/**
Generates a Lua error. The error message (which can actually be a Lua value
of any type) must be on the stack top. This function does a long jump,
and therefore never returns.
**/
static function error(message:String, ?level:Int):Void;
/**
Calls a function in protected mode.
**/
static function pcall(f:Function, rest:Rest<Dynamic>):PCallResult;
/**
Returns `true` if the two values in acceptable indices `v1` and `v2` are
primitively equal (that is, without calling metamethods).
Otherwise returns `false`.
Also returns `false` if any of the indices are non valid.
**/
static function rawequal(v1:Dynamic, v2:Dynamic):Bool;
/**
This function is similar to pcall, except that you can set a new error
handler.
**/
static function xpcall(f:Function, msgh:Function, rest:Rest<Dynamic>):PCallResult;
/**
Loads the chunk from file filename or from the standard input if no filename
is given.
**/
static function loadfile(filename:String):LoadResult;
/**
Loads the chunk from given string.
**/
static function load(code:haxe.extern.EitherType<String, Void->String>):LoadResult;
}
/**
Enum for describing garbage collection options
**/
enum abstract CollectGarbageOption(String) {
var Stop = "stop";
var Restart = "restart";
var Collect = "collect";
var Count = "count";
var Step = "step";
var SetPause = "setpause";
var SetStepMul = "setstepmul";
}
@:multiReturn
extern class PCallResult {
var status:Bool;
var value:Dynamic;
}
@:multiReturn
extern class NextResult<K, V> {
var index:K;
var value:V;
}
@:multiReturn
extern class IPairsResult<K, V> {
var next:Table<K, V>->Int->NextResult<Int, V>;
var table:Table<K, V>;
var index:Int;
}
@:multiReturn
extern class PairsResult<K, V> {
var next:Table<K, V>->K->NextResult<K, V>;
var table:Table<K, V>;
var index:K;
}
@:multiReturn
extern class LoadResult {
var func:Function;
var message:String;
}

View File

@ -0,0 +1,195 @@
/*
* 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 lua;
import haxe.extern.Rest;
/**
Mathematical Functions
**/
@:native("_G.math")
extern class Math {
/**
The value of pi.
**/
static var pi(default, never):Float;
/**
The value HUGE_VAL, a value larger than or equal to any other numerical value.
**/
static var huge(default, never):Float;
/**
Returns the absolute value of x.
**/
static function abs(x:Float):Float;
/**
Returns the smallest integer larger than or equal to x.
**/
static function ceil(x:Float):Int;
/**
Returns the largest integer smaller than or equal to x.
**/
static function floor(x:Float):Int;
/**
Returns the arc cosine of x (in radians).
**/
static function acos(x:Float):Float;
/**
Returns the arc sine of x (in radians).
**/
static function asin(x:Float):Float;
/**
Returns the arc tangent of x (in radians).
**/
static function atan(x:Float):Float;
/**
Returns the arc tangent of y/x (in radians), but uses the signs of both parameters to find the quadrant of the result.
(It also handles correctly the case of x being zero.)
**/
static function atan2(y:Float, x:Float):Float;
/**
Returns the cosine of x (assumed to be in radians).
**/
static function cos(x:Float):Float;
/**
Returns the hyperbolic cosine of x.
**/
static function cosh(x:Float):Float;
/**
Returns the sine of x (assumed to be in radians).
**/
static function sin(x:Float):Float;
/**
Returns the hyperbolic sine of x.
**/
static function sinh(x:Float):Float;
/**
Returns the tangent of x (assumed to be in radians)
**/
static function tan(x:Float):Float;
/**
Returns the hyperbolic tangent of x.
**/
static function tanh(x:Float):Float;
/**
Returns the angle x (given in degrees) in radians.
**/
static function rad(x:Float):Float;
/**
Returns two numbers, the integral part of x and the fractional part of x.
**/
static function modf(x:Float):Float;
/**
Returns the remainder of the division of x by y that rounds the quotient towards zero.
**/
static function fmod(x:Float):Float;
/**
Returns y-th power of x.
**/
static function pow(x:Float, y:Float):Float;
/**
Returns the square root of x.
**/
static function sqrt(x:Float):Float;
/**
Returns the value e^x.
**/
static function exp(x:Float):Float;
/**
Returns m and e such that x = m2^e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero).
**/
static function frexp(x:Float):MathFrexpResult;
/**
Returns m2^e (e should be an integer).
**/
static function ldexp(m:Float, e:Int):Float;
/**
Returns the natural logarithm of x.
**/
static function log(x:Float):Float;
/**
Returns the base-10 logarithm of x.
**/
static function log10(x:Float):Float;
/**
Returns the maximum value among its arguments.
**/
static function max(x:Float, numbers:Rest<Float>):Float;
/**
Returns the minimum value among its arguments.
**/
static function min(x:Float, numbers:Rest<Float>):Float;
/**
Returns the angle x (given in radians) in degrees.
**/
static function deg(x:Float):Float;
/**
This function is an interface to the simple pseudo-random generator function rand provided by ANSI C.
(No guarantees can be given for its statistical properties.)
When called without arguments, returns a uniform pseudo-random real number in the range [0,1).
When called with an integer number `m`, returns a uniform pseudo-random integer in the range [1, m].
When called with two integer numbers `m` and `n`, returns a uniform pseudo-random integer in the range [m, n].
**/
static function random(?m:Float, ?n:Float):Float;
/**
Sets `x` as the "seed" for the pseudo-random generator: equal seeds produce equal sequences of numbers.
**/
static function randomseed(x:Float):Float;
}
/**
The return value of `Math.frexp`.
**/
@:multiReturn extern class MathFrexpResult {
var m:Float;
var e:Int;
}

View File

@ -0,0 +1,45 @@
/*
* 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 lua;
/**
This abstract enables easy conversion from basic lua iterators
(i.e., a function that is called until it returns null), and
Haxe iterators, which provide a next/hasNext interface.
**/
@:callable
abstract NativeIterator<T>(Void->T) {
public function new(f:Void->T) {
this = f;
}
@:from
public static function fromF<T>(f:Void->T) {
return new NativeIterator(f);
}
@:to
public function toIterator():Iterator<T> {
return new HaxeIterator(this);
}
}

View File

@ -0,0 +1,170 @@
/*
* 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 lua;
/**
These are all externs for the base Lua "string" class, which functions
as an additional set of string tools.
Note that all relevant indexes are "1" based.
**/
@:native("_G.string")
extern class NativeStringTools {
/**
Receives a string and returns its length. The empty string `""` has
length `0`. Embedded zeros are counted, so `"a\000bc\000"` has length `5`.
**/
static function len(str:String):Int;
/**
Receives zero or more integers. Returns a string with length equal to the
number of arguments, in which each character has the internal numerical
code equal to its corresponding argument.
Note that numerical codes are not necessarily portable across platforms.
**/
static function char(codes:haxe.extern.Rest<Int>):String;
// TODO: make a note about handling matched groups with multireturn
/**
Returns the substring of `str` that starts at `start` and continues until `end`;
`start` and `end` can be negative. If `end` is absent, then it is assumed to be
equal to `-1` (which is the same as the string length).
In particular, the call `sub(str,1,end)` returns a prefix of `str`
with length `end`, and `sub(str, -end)` returns a suffix of `str` with
length `start`.
**/
static function sub(str:String, start:Int, ?end:Int):StringSub;
/**
Looks for the first match of pattern in the string `str`.
If it finds a match, then `find` returns the indices of `str` where this
occurrence starts and ends.
@param target If the target has captures, then in a successful match the
captured values are also returned, after the two indices.
@param start specifies where to start the search; its default value is `1`
and can be negative.
@param plain turns off the pattern matching facilities, so the function does
a plain "find substring" operation, with no characters in pattern
being considered "magic". Note that if plain is given, then `start` must be given as well.
**/
static function find(str:String, target:String, ?start:Int, ?plain:Bool):StringFind;
/**
Returns the internal numerical codes of the characters `str[index]`.
Note that numerical codes are not necessarily portable across platforms.
**/
static function byte(str:String, ?index:Int):Int;
/**
Returns a formatted version of its variable number of arguments following
the description given in its first argument (which must be a string).
The format string follows the same rules as the printf family of standard C
functions. The only differences are that the options/modifiers
`*`, `l`, `L`, `n`, `p`, and `h` are not supported and that there is an
extra option, `q`. The `q` option formats a string in a form suitable to be
safely read back by the Lua interpreter: the string is written between
double quotes, and all double quotes, newlines, embedded zeros,
and backslashes in the string are correctly escaped when written.
For instance, the call
`string.format('%q', 'a string with "quotes" and \n new line')`
will produce the string:
`"a string with \"quotes\" and \
new line"`
The options `c`, `d` `E`, `e`, `f`, `g`, `G`, `i`, `o`, `u, `X-, and `x` all
expect a number as argument, whereas `q` and `s` expect a string.
This function does not accept string values containing embedded zeros,
except as arguments to the `q` option.
**/
static function format(str:String, ?e1:Dynamic, ?e2:Dynamic, ?e3:Dynamic, ?e4:Dynamic):String;
/**
**/
@:overload(function(str:String, pattern:String, replace:String->Void, ?n:Int):String {})
@:overload(function(str:String, pattern:String, replace:String->String, ?n:Int):String {})
static function gsub(str:String, pattern:String, replace:String, ?n:Int):String;
/**
Returns an iterator function that, each time it is called, returns the next
captures from pattern over string `str`. If `pattern` specifies no captures,
then the whole match is produced in each call.
**/
@:overload(function(str:String, pattern:String, match:Void->String, ?n:Int):String->Void {})
static function gmatch(str:String, pattern:String):Void->String;
/**
Looks for the first match of pattern in the string s. If it finds one,
then match returns the captures from the pattern; otherwise it returns `null`.
If pattern specifies no captures, then the whole match is returned.
The optional argument `n` specifies where to start the search;
its default value is `1` and can be negative.
**/
static function match(str:String, pattern:String, ?n:Int):String;
/**
Receives a string and returns a copy of this string with all lowercase
letters changed to uppercase. All other characters are left unchanged.
The definition of what a lowercase letter is depends on the current locale.
**/
static function upper(str:String):String;
/**
Receives a string and returns a copy of this string with all uppercase
letters changed to lowercase. All other characters are left unchanged.
The definition of what an uppercase letter is depends on the current locale.
**/
static function lower(str:String):String;
/**
Returns a string containing a binary representation of the given function,
so that a later loadstring on this string returns a copy of the function.
function must be a Lua function without upvalues.
**/
static function dump(d:Dynamic):Dynamic;
/**
Returns a string that is the concatenation of n copies of
the string s separated by the string sep. The default value
for sep is the empty string (that is, no separator).
Returns the empty string if n is not positive. (Note that
it is very easy to exhaust the memory of your machine with
a single call to this function.)
**/
static function rep(s:String, n : Int, ?sep : String) : String;
}
@:multiReturn extern class StringFind {
var begin:Int;
var end:Int;
}
@:multiReturn extern class StringSub {
var match:String;
var count:Int;
}

View File

@ -0,0 +1,150 @@
/*
* 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 lua;
/**
Operating System Facilities.
**/
@:native("_G.os")
extern class Os {
/**
Returns an approximation of the amount in seconds of CPU time used by the
program.
**/
static function clock():Float;
@:overload(function(format:String, time:Time):DateType {})
@:overload(function(format:String):DateType {})
static function date():DateType;
/**
Returns the number of seconds from time `t1` to time `t2`.
In POSIX, Windows, and some other systems, this value is exactly `t2-t1`.
**/
static function difftime(t2:Time, t1:Time):Float;
// TODO: multi-return
/**
This function is equivalent to the C function system. It passes command to
be executed by an operating system shell. It returns a status code,
which is system-dependent. If command is absent, then it returns
nonzero if a shell is available and zero otherwise.
**/
#if (lua_ver < 5.2)
static function execute(?command:String):Int;
#elseif (lua_ver >= 5.2)
static function execute(?command:String):OsExecute;
#else
static function execute(?command:String):Dynamic;
#end
/**
Calls the C function exit, with an optional code, to terminate the host program.
The default value for code is the success code.
**/
static function exit(code:Int):Int;
/**
Returns the value of the process environment variable `varname`, or `null`
if the variable is not defined.
**/
static function getenv(varname:String):String;
/**
Deletes the file or directory with the given name.
Directories must be empty to be removed.
**/
static function remove(filename:String):OsSuccess;
/**
Renames file or directory named `oldname` to `newname`.
**/
static function rename(oldname:String, newname:String):OsSuccess;
/**
Sets the current locale of the program.
**/
static function setlocale(locale:String, ?category:LocaleCategory):String;
/**
Returns the current time when called without arguments, or a time
representing the date and time specified by the given table.
The returned value is a number, whose meaning depends on your system.
In POSIX, Windows, and some other systems, this number counts the number
of seconds since some given start time (the "epoch").
In other systems, the meaning is not specified, and the number returned
by time can be used only as an argument to date and difftime.
**/
static function time(?arg:TimeParam):Time;
/**
Returns a string with a file name that can be used for a temporary file.
The file must be explicitly opened before its use and explicitly removed
when no longer needed.
When possible, you may prefer to use `Io.tmpfile`, which automatically
removes the file when the program ends.
**/
static function tmpname():String;
}
/**
A typedef that matches the date parameter `Os.time()` will accept.
**/
typedef TimeParam = {
year:Int,
month:Int,
day:Int,
?hour:Int,
?min:Int,
?sec:Int,
?isdst:Bool
}
/**
A typedef that describes the output of `Os.date()`.
**/
typedef DateType = {
hour:Int,
min:Int,
sec:Int,
isdst:Bool,
year:Int,
month:Int,
wday:Int,
yday:Int,
day:Int,
}
@:multiReturn extern class OsExecute {
var success:Bool;
var output:String;
var status:Int;
}
@:multiReturn extern class OsSuccess {
var success:Bool;
var message:String;
}

View File

@ -0,0 +1,71 @@
/*
* 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 lua;
/**
Externs for lua package handling
**/
@:native("_G.package")
extern class Package {
/**
A string describing some compile-time configurations for packages.
**/
static var config:String;
/**
The path used by require to search for a Lua loader.
**/
static var path:String;
/**
The path used by require to search for a C loader.
**/
static var cpath:String;
/**
A table used by require to control which modules are already loaded.
**/
static var loaded:Table<String, Bool>;
/**
A table to store loaders for specific modules.
**/
static var preload:Table<String, Bool>;
/**
A table used by require to control how to load modules.
Each entry in this table is a searcher function.
**/
static var searchers:Table<Int, Void->Null<String>>;
/**
Searches for the given `libname` in the given path `funcname`.
A path is a string containing a sequence of templates separated by semicolons.
**/
static function searchpath(name:String, path:String, ?sep:String, ?rep:String):Null<String>;
/**
Dynamically links the host program with the C library `libname`.
**/
static function loadlib(libname:String, funcname:String):Dynamic;
}

View File

@ -0,0 +1,124 @@
/*
* 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 lua;
/**
A set of utility methods for working with the Lua table extern.
**/
class PairTools {
public static function ipairsEach<T>(table:Table<Dynamic, T>, func:Int->T->Void):Void {
untyped __lua__("for i,v in _G.ipairs(table) do func(i,v) end");
}
public static function pairsEach<A, B>(table:Table<A, B>, func:A->B->Void):Void {
untyped __lua__("for k,v in _G.pairs(table) do func(k,v) end");
}
public static function ipairsMap<A, B>(table:Table<Dynamic, A>, func:Int->A->B):Table<Int, B> {
var ret:Table<Int, B> = Table.create();
untyped __lua__("for i,v in _G.ipairs(table) do ret[i] = func(i,v) end");
return ret;
}
public static function pairsMap<A, B, C>(table:Table<A, B>, func:A->B->C->C):Table<A, C> {
var ret:Table<A, C> = Table.create();
untyped __lua__("for k,v in _G.pairs(table) do ret[k] = func(k,v) end");
return ret;
}
public static function ipairsFold<A, B>(table:Table<Int, A>, func:Int->A->B->B, seed:B):B {
untyped __lua__("for i,v in _G.ipairs(table) do seed = func(i,v,seed) end");
return untyped __lua__("seed");
}
public static function pairsFold<A, B, C>(table:Table<A, B>, func:A->B->C->C, seed:C):C {
untyped __lua__("for k,v in _G.pairs(table) do seed = func(k,v,seed) end");
return untyped __lua__("seed");
}
public static function ipairsConcat<T>(table1:Table<Int, T>, table2:Table<Int, T>) {
var ret:Table<Int, T> = Table.create();
ipairsFold(table1, function(a, b, c:Table<Int, T>) {
c[a] = b;
return c;
}, ret);
var size = lua.TableTools.maxn(ret);
ipairsFold(table2, function(a, b, c:Table<Int, T>) {
c[a + size] = b;
return c;
}, ret);
return ret;
}
public static function pairsMerge<A, B>(table1:Table<A, B>, table2:Table<A, B>) {
var ret = copy(table1);
pairsEach(table2, function(a, b:B) ret[cast a] = b);
return ret;
}
public static function ipairsExist<T>(table:Table<Int, T>, func:Int->T->Bool) {
untyped __lua__("for k,v in _G.ipairs(table) do if func(k,v) then return true end end");
}
public static function pairsExist<A, B>(table:Table<A, B>, func:A->B->Bool) {
untyped __lua__("for k,v in _G.pairs(table) do if func(k,v) then return true end end");
}
public static function copy<A, B>(table1:Table<A, B>):Table<A, B> {
var ret:Table<A, B> = Table.create();
untyped __lua__("for k,v in _G.pairs(table1) do ret[k] = v end");
return ret;
}
public static function pairsIterator<A, B>(table:Table<A, B>):Iterator<{index:A, value:B}> {
var p = Lua.pairs(table);
var next = p.next;
var i = p.index;
return {
next: function() {
var res = next(table, i);
i = res.index;
return {index: res.index, value: res.value};
},
hasNext: function() {
return Lua.next(table, i).value != null;
}
}
}
public static function ipairsIterator<A, B>(table:Table<A, B>):Iterator<{index:Int, value:B}> {
var p = Lua.ipairs(table);
var next = p.next;
var i = p.index;
return {
next: function() {
var res = next(table, i);
i = res.index;
return {index: res.index, value: res.value};
},
hasNext: function() {
return next(table, i).value != null;
}
}
}
}

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 lua;
@:multiReturn extern class Result<T> {
var result:T;
var message:String;
}

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 lua;
import lua.PairTools;
import haxe.ds.ObjectMap;
/**
This library provides generic functions for table manipulation.
**/
@:native("_G.table")
extern class Table<A, B> implements ArrayAccess<B> implements Dynamic<B> {
@:pure static function create<A, B>(?arr:Array<B>, ?hsh:Dynamic):Table<A, B>;
inline static function fromArray<T>(arr:Array<T>):Table<Int, T> {
var ret = Table.create();
for (idx in 0...arr.length) {
ret[idx + 1] = arr[idx];
}
return ret;
}
inline static function fromMap<A, B>(map:Map<A, B>):Table<A, B> {
var ret = Table.create();
for (k in map.keys()) {
ret[untyped k] = map.get(k);
}
return ret;
}
inline static function fromDynamic<A, B>(dyn:Dynamic):Table<A, B> {
var ret = Table.create();
for (f in Reflect.fields(dyn)) {
ret[untyped f] = Reflect.field(dyn, f);
}
return ret;
}
inline static function toMap<A,B>(tbl : Table<A,B>) : Map<A,B> {
var obj = new ObjectMap();
PairTools.pairsFold(tbl, (k,v,m) ->{
obj.set(k,v);
return obj;
}, obj);
return cast obj;
}
/**
Copies the table argument and converts it to an Object.
**/
inline static function toObject<T>(t:Table<String, T>):Dynamic<T> {
return Boot.tableToObject(PairTools.copy(t));
}
inline static function toArray<T>(tbl : Table<Int,T>, ?length:Int) : Array<T> {
return Boot.defArray(PairTools.copy(tbl), length);
}
@:overload(function<A, B>(table:Table<A, B>):Void {})
static function concat<A, B>(table:Table<A, B>, ?sep:String, ?i:Int, ?j:Int):String;
#if (lua_ver == 5.1)
static function foreach<A, B>(table:Table<A, B>, f:A->B->Void):Void;
static function foreachi<A, B>(table:Table<A, B>, f:A->B->Int->Void):Void;
#end
static function sort<A, B>(table:Table<A, B>, ?order:A->A->Bool):Void;
@:overload(function<B>(table:Table<Int, B>, value:B):Void {})
static function insert<B>(table:Table<Int, B>, pos:Int, value:B):Void;
@:overload(function<B>(table:Table<Int, B>):Void {})
static function remove<B>(table:Table<Int, B>, ?pos:Int):Void;
#if (lua_ver >= 5.2)
static function pack<T>(args:haxe.extern.Rest<T>):Table<Int, T>;
static function unpack<Int, V>(args:lua.Table<Int, V>, ?min:Int, ?max:Int):Dynamic;
#end
}
typedef AnyTable = Table<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 lua;
import lua.Table.AnyTable;
/**
This library is an extern for a polyfill library of common lua table
methods.
**/
@:native("_hx_table")
extern class TableTools {
static function pack<T>(args:haxe.extern.Rest<T>):Table<Int, T>;
static function unpack<Int, V>(args:lua.Table<Int, V>, ?min:Int, ?max:Int):Dynamic;
static function maxn(t:AnyTable):Int;
static function __init__():Void {
untyped __define_feature__("use._hx_table", null);
}
}

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 lua;
/**
The sole purpose of this extern is to provide a concrete type for
basic reflection purposes.
**/
class Thread {}

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 lua;
/*
Note: Lua timestamps are usually ints. Platform differences can produce
Floats in certain cases.
*/
typedef Time = Float;

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 lua;
class UserData {}

View File

@ -0,0 +1,48 @@
local function _hx_obj_newindex(t,k,v)
t.__fields__[k] = true
rawset(t,k,v)
end
local _hx_obj_mt = {__newindex=_hx_obj_newindex, __tostring=_hx_tostring}
local function _hx_a(...)
local __fields__ = {};
local ret = {__fields__ = __fields__};
local max = select('#',...);
local tab = {...};
local cur = 1;
while cur < max do
local v = tab[cur];
__fields__[v] = true;
ret[v] = tab[cur+1];
cur = cur + 2
end
return setmetatable(ret, _hx_obj_mt)
end
local function _hx_e()
return setmetatable({__fields__ = {}}, _hx_obj_mt)
end
local function _hx_o(obj)
return setmetatable(obj, _hx_obj_mt)
end
local function _hx_new(prototype)
return setmetatable({__fields__ = {}}, {__newindex=_hx_obj_newindex, __index=prototype, __tostring=_hx_tostring})
end
function _hx_field_arr(obj)
res = {}
idx = 0
if obj.__fields__ ~= nil then
obj = obj.__fields__
end
for k,v in pairs(obj) do
if _hx_hidden[k] == nil then
res[idx] = k
idx = idx + 1
end
end
return _hx_tab_array(res, idx)
end

View File

@ -0,0 +1,3 @@
_hx_apply_self = function(self, f, ...)
return self[f](self,...)
end

View File

@ -0,0 +1,14 @@
_hx_bind = function(o,m)
if m == nil then return nil end;
local f;
if o._hx__closures == nil then
_G.rawset(o, '_hx__closures', {});
else
f = o._hx__closures[m];
end
if (f == nil) then
f = function(...) return m(o, ...) end;
o._hx__closures[m] = f;
end
return f;
end

View File

@ -0,0 +1,16 @@
-- require this for lua 5.1
pcall(require, 'bit')
if bit then
_hx_bit_raw = bit
_hx_bit = setmetatable({}, { __index = _hx_bit_raw });
else
_hx_bit_raw = _G.require('bit32')
_hx_bit = setmetatable({}, { __index = _hx_bit_raw });
-- lua 5.2 weirdness
_hx_bit.bnot = function(...) return _hx_bit_clamp(_hx_bit_raw.bnot(...)) end;
_hx_bit.bxor = function(...) return _hx_bit_clamp(_hx_bit_raw.bxor(...)) end;
end
-- see https://github.com/HaxeFoundation/haxe/issues/8849
_hx_bit.bor = function(...) return _hx_bit_clamp(_hx_bit_raw.bor(...)) end;
_hx_bit.band = function(...) return _hx_bit_clamp(_hx_bit_raw.band(...)) end;
_hx_bit.arshift = function(...) return _hx_bit_clamp(_hx_bit_raw.arshift(...)) end;

View File

@ -0,0 +1,26 @@
if _hx_bit_raw then
_hx_bit_clamp = function(v)
if v <= 2147483647 and v >= -2147483648 then
if v > 0 then return _G.math.floor(v)
else return _G.math.ceil(v)
end
end
if v > 2251798999999999 then v = v*2 end;
if (v ~= v or math.abs(v) == _G.math.huge) then return nil end
return _hx_bit_raw.band(v, 2147483647 ) - math.abs(_hx_bit_raw.band(v, 2147483648))
end
else
_hx_bit_clamp = function(v)
if v < -2147483648 then
return -2147483648
elseif v > 2147483647 then
return 2147483647
elseif v > 0 then
return _G.math.floor(v)
else
return _G.math.ceil(v)
end
end
end;

View File

@ -0,0 +1,7 @@
_hx_box_mr = function(x,nt)
res = _hx_o({__fields__={}})
for i,v in ipairs(nt) do
res[v] = x[i]
end
return res
end

View File

@ -0,0 +1,7 @@
local _hxClasses = {}
local Int = _hx_e();
local Dynamic = _hx_e();
local Float = _hx_e();
local Bool = _hx_e();
local Class = _hx_e();
local Enum = _hx_e();

View File

@ -0,0 +1,7 @@
_hx_dyn_add = function(a,b)
if (_G.type(a) == 'string' or _G.type(b) == 'string') then
return Std.string(a)..Std.string(b)
else
return a + b;
end;
end;

View File

@ -0,0 +1,9 @@
_hx_funcToField = function(f)
if type(f) == 'function' then
return function(self,...)
return f(...)
end
else
return f
end
end

View File

@ -0,0 +1 @@
_hx_print = print or (function() end)

View File

@ -0,0 +1 @@
_G.math.randomseed(_G.os.time());

View File

@ -0,0 +1,13 @@
_hx_staticToInstance = function (tab)
return setmetatable({}, {
__index = function(t,k)
if type(rawget(tab,k)) == 'function' then
return function(self,...)
return rawget(tab,k)(...)
end
else
return rawget(tab,k)
end
end
})
end

View File

@ -0,0 +1,23 @@
local _hx_hidden = {__id__=true, hx__closures=true, super=true, prototype=true, __fields__=true, __ifields__=true, __class__=true, __properties__=true, __fields__=true, __name__=true}
_hx_array_mt = {
__newindex = function(t,k,v)
local len = t.length
t.length = k >= len and (k + 1) or len
rawset(t,k,v)
end
}
function _hx_is_array(o)
return type(o) == "table"
and o.__enum__ == nil
and getmetatable(o) == _hx_array_mt
end
function _hx_tab_array(tab, length)
tab.length = length
return setmetatable(tab, _hx_array_mt)
end

View File

@ -0,0 +1,12 @@
_hx_table = {}
_hx_table.pack = _G.table.pack or function(...)
return {...}
end
_hx_table.unpack = _G.table.unpack or _G.unpack
_hx_table.maxn = _G.table.maxn or function(t)
local maxn=0;
for i in pairs(t) do
maxn=type(i)=='number'and i>maxn and i or maxn
end
return maxn
end;

View File

@ -0,0 +1,114 @@
function _hx_print_class(obj, depth)
local first = true
local result = ''
for k,v in pairs(obj) do
if _hx_hidden[k] == nil then
if first then
first = false
else
result = result .. ', '
end
if _hx_hidden[k] == nil then
result = result .. k .. ':' .. _hx_tostring(v, depth+1)
end
end
end
return '{ ' .. result .. ' }'
end
function _hx_print_enum(o, depth)
if o.length == 2 then
return o[0]
else
local str = o[0] .. "("
for i = 2, (o.length-1) do
if i ~= 2 then
str = str .. "," .. _hx_tostring(o[i], depth+1)
else
str = str .. _hx_tostring(o[i], depth+1)
end
end
return str .. ")"
end
end
function _hx_tostring(obj, depth)
if depth == nil then
depth = 0
elseif depth > 5 then
return "<...>"
end
local tstr = _G.type(obj)
if tstr == "string" then return obj
elseif tstr == "nil" then return "null"
elseif tstr == "number" then
if obj == _G.math.POSITIVE_INFINITY then return "Infinity"
elseif obj == _G.math.NEGATIVE_INFINITY then return "-Infinity"
elseif obj == 0 then return "0"
elseif obj ~= obj then return "NaN"
else return _G.tostring(obj)
end
elseif tstr == "boolean" then return _G.tostring(obj)
elseif tstr == "userdata" then
local mt = _G.getmetatable(obj)
if mt ~= nil and mt.__tostring ~= nil then
return _G.tostring(obj)
else
return "<userdata>"
end
elseif tstr == "function" then return "<function>"
elseif tstr == "thread" then return "<thread>"
elseif tstr == "table" then
if obj.__enum__ ~= nil then
return _hx_print_enum(obj, depth)
elseif obj.toString ~= nil and not _hx_is_array(obj) then return obj:toString()
elseif _hx_is_array(obj) then
if obj.length > 5 then
return "[...]"
else
local str = ""
for i=0, (obj.length-1) do
if i == 0 then
str = str .. _hx_tostring(obj[i], depth+1)
else
str = str .. "," .. _hx_tostring(obj[i], depth+1)
end
end
return "[" .. str .. "]"
end
elseif obj.__class__ ~= nil then
return _hx_print_class(obj, depth)
else
local buffer = {}
local ref = obj
if obj.__fields__ ~= nil then
ref = obj.__fields__
end
for k,v in pairs(ref) do
if _hx_hidden[k] == nil then
_G.table.insert(buffer, _hx_tostring(k, depth+1) .. ' : ' .. _hx_tostring(obj[k], depth+1))
end
end
return "{ " .. table.concat(buffer, ", ") .. " }"
end
else
_G.error("Unknown Lua type", 0)
return ""
end
end
function _hx_error(obj)
if obj.value then
_G.print("runtime error:\n " .. _hx_tostring(obj.value));
else
_G.print("runtime error:\n " .. tostring(obj));
end
if _G.debug and _G.debug.traceback then
_G.print(debug.traceback());
end
end

View File

@ -0,0 +1,11 @@
_hx_wrap_if_string_field = function(o, fld)
if _G.type(o) == 'string' then
if fld == 'length' then
return _G.string.len(o)
else
return String.prototype[fld]
end
else
return o[fld]
end
end

View File

@ -0,0 +1,267 @@
/*
* 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 haxe.iterators.ArrayKeyValueIterator;
@:coreApi
class Array<T> {
public var length(default, null):Int;
public function new():Void {
untyped _hx_tab_array(this, 0);
}
public function concat(a:Array<T>):Array<T> {
var ret = this.copy();
for (i in a)
ret.push(i);
return ret;
}
public function join(sep:String):String {
var tbl:lua.Table<Int, String> = lua.Table.create();
for (i in iterator()) {
lua.Table.insert(tbl, Std.string(i));
}
return lua.Table.concat(tbl, sep);
}
public function pop():Null<T> {
if (length == 0)
return null;
var ret = this[length - 1];
this[length - 1] = null;
length--;
return ret;
}
public function push(x:T):Int {
this[this.length] = x;
return length;
}
public function reverse():Void {
var tmp:T;
var i = 0;
while (i < Std.int(this.length / 2)) {
tmp = this[i];
this[i] = this[this.length - i - 1];
this[this.length - i - 1] = tmp;
i++;
}
}
public function shift():Null<T> {
if (this.length == 0)
return null;
var ret = this[0];
if (this.length == 1) {
this[0] = null;
} else if (this.length > 1) {
this[0] = this[1];
lua.Table.remove(untyped this, 1);
}
this.length -= 1;
return ret;
}
public function slice(pos:Int, ?end:Int):Array<T> {
if (end == null || end > length)
end = length;
else if (end < 0)
end = (length - (-end % length)) % length; // negative pos needs to be wrapped from the end, and mod according to array length
if (pos < 0)
pos = (length - (-pos % length)) % length; // and here
if (pos > end || pos > length)
return [];
var ret = [];
for (i in pos...end) {
ret.push(this[i]);
}
return ret;
}
// TODO: copied from neko Array.sort, move to general util library?
public function sort(f:T->T->Int):Void {
var i = 0;
var l = this.length;
while (i < l) {
var swap = false;
var j = 0;
var max = l - i - 1;
while (j < max) {
if (f(this[j], this[j + 1]) > 0) {
var tmp = this[j + 1];
this[j + 1] = this[j];
this[j] = tmp;
swap = true;
}
j += 1;
}
if (!swap)
break;
i += 1;
}
}
public function splice(pos:Int, len:Int):Array<T> {
if (len < 0 || pos > length)
return [];
else if (pos < 0)
pos = length - (-pos % length);
len = cast Math.min(len, this.length - pos);
var ret = [];
for (i in pos...(pos + len)) {
ret.push(this[i]);
this[i] = this[i + len];
}
for (i in (pos + len)...length) {
this[i] = this[i + len];
}
this.length -= len;
return ret;
}
public function toString():String {
var tbl:lua.Table<Int, String> = lua.Table.create();
lua.Table.insert(tbl, '[');
lua.Table.insert(tbl, join(","));
lua.Table.insert(tbl, ']');
return lua.Table.concat(tbl, "");
}
public function unshift(x:T):Void {
var len = length;
for (i in 0...len)
this[len - i] = this[len - i - 1];
this[0] = x;
}
public inline function insert(pos:Int, x:T):Void {
if (pos > length)
pos = length;
if (pos < 0) {
pos = (length + pos);
if (pos < 0)
pos = 0;
}
var cur_len = length;
while (cur_len > pos) {
this[cur_len] = this[cur_len - 1];
cur_len -= 1;
}
this[pos] = x;
}
public function remove(x:T):Bool {
for (i in 0...length) {
if (this[i] == x) {
for (j in i...length - 1) {
this[j] = this[j + 1];
}
// We need to decrement the length variable, and set its
// value to null to avoid hanging on to a reference in the
// underlying lua table.
this[length - 1] = null;
// Do this in two steps to avoid re-updating the __index metamethod
length--;
return true;
}
}
return false;
}
public function contains(x:T):Bool {
for (i in 0...length) {
if (this[i] == x)
return true;
}
return false;
}
public function indexOf(x:T, ?fromIndex:Int):Int {
var end = length;
if (fromIndex == null)
fromIndex = 0;
else if (fromIndex < 0) {
fromIndex = length + fromIndex;
if (fromIndex < 0)
fromIndex = 0;
}
for (i in fromIndex...end) {
if (x == this[i])
return i;
}
return -1;
}
public function lastIndexOf(x:T, ?fromIndex:Int):Int {
if (fromIndex == null || fromIndex >= length)
fromIndex = length - 1;
else if (fromIndex < 0) {
fromIndex = length + fromIndex;
if (fromIndex < 0)
return -1;
}
var i = fromIndex;
while (i >= 0) {
if (this[i] == x)
return i;
else
i--;
}
return -1;
}
public inline function copy():Array<T> {
return [for (i in this) i];
}
public inline function map<S>(f:T->S):Array<S> {
return [for (i in this) f(i)];
}
public inline function filter(f:T->Bool):Array<T> {
return [for (i in this) if (f(i)) i];
}
public inline function iterator():haxe.iterators.ArrayIterator<T> {
return new haxe.iterators.ArrayIterator(this);
}
public inline function keyValueIterator():ArrayKeyValueIterator<T> {
return new ArrayKeyValueIterator(this);
}
public function resize(len:Int):Void {
if (length < len) {
this.length = len;
} else if (length > len) {
for (i in len...length) {
this[i] = null;
}
this.length = len;
}
}
}

View File

@ -0,0 +1,112 @@
/*
* 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.
*/
@:coreApi class Date {
var d:lua.Os.DateType;
var dUTC:lua.Os.DateType;
var t:lua.Time;
public function new(year:Int, month:Int, day:Int, hour:Int, min:Int, sec:Int) {
t = lua.Os.time({
year: year,
month: month + 1,
day: day,
hour: hour,
min: min,
sec: sec
});
d = lua.Os.date("*t", t);
dUTC = lua.Os.date("!*t", t);
};
public function getTime():Float
return cast t * 1000;
public function getHours():Int
return d.hour;
public function getMinutes():Int
return d.min;
public function getSeconds():Int
return d.sec;
public function getFullYear():Int
return d.year;
public function getMonth():Int
return d.month - 1;
public function getDate():Int
return d.day;
public function getDay():Int
return d.wday - 1;
public function getUTCHours():Int
return dUTC.hour;
public function getUTCMinutes():Int
return dUTC.min;
public function getUTCSeconds():Int
return dUTC.sec;
public function getUTCFullYear():Int
return dUTC.year;
public function getUTCMonth():Int
return dUTC.month - 1;
public function getUTCDate():Int
return dUTC.day;
public function getUTCDay():Int
return dUTC.wday - 1;
public function getTimezoneOffset():Int {
var tUTC = lua.Os.time(dUTC);
return Std.int((tUTC - t) / 60);
}
public inline function toString():String {
return lua.Boot.dateStr(this);
}
public static inline function now():Date {
return fromTime(lua.Os.time() * 1000);
}
public static inline function fromTime(t:Float):Date {
var d:Dynamic = {}
untyped {
lua.Lua.setmetatable(d, untyped {__index: Date.prototype});
d.t = t / 1000;
d.d = lua.Os.date("*t", Std.int(d.t));
d.dUTC = lua.Os.date("!*t", Std.int(d.t));
}
return d;
}
public static inline function fromString(s:String):Date {
return lua.Boot.strDate(s);
}
}

View File

@ -0,0 +1,214 @@
/*
* 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 lua.Table;
import lua.Lib;
import lua.lib.lrexlib.Rex;
// Note - lrexlib gives ascii-based offsets. Use native string tools.
import lua.NativeStringTools.*;
@:coreApi
class EReg {
var r:Rex; // the Rex extern instance.
var global:Bool; // whether the regex is in global mode.
var s:String; // the last matched string
var m:Table<Int, Int>; // the [start:Int, end:Int, and submatches:String (matched groups)] as a single table.
static var FLAGS:Table<String, Int> = Rex.flags();
public function new(r:String, opt:String):Void {
var ropt = 0;
for (i in 0...opt.length) {
switch (opt.charAt(i)) {
case "i":
ropt |= FLAGS.CASELESS;
case "m":
ropt |= FLAGS.MULTILINE;
case "s":
ropt |= FLAGS.DOTALL;
case "g":
global = true;
default:
null;
}
}
ropt |= FLAGS.UTF8; // always check validity of utf8 string
ropt |= FLAGS.UCP; // always enable utf8 character properties
if (global == null)
global = false;
this.r = Rex.create(r, ropt);
}
public function match(s:String):Bool {
return matchFromByte(s, 1);
}
inline function matchFromByte(s:String, offset:Int):Bool {
if (s == null)
return false;
this.m = lua.TableTools.pack(r.exec(s, offset));
this.s = s;
return m[1] != null;
}
public function matched(n:Int):String {
if (m[1] == null || n < 0)
throw "EReg::matched";
else if (n == 0) {
var k = sub(s, m[1], m[2]).match;
return k;
} else if (Std.isOfType(m[3], lua.Table)) {
var mn = 2 * (n - 1);
if (Std.isOfType(untyped m[3][mn + 1], Bool))
return null;
return sub(s, untyped m[3][mn + 1], untyped m[3][mn + 2]).match;
} else {
throw "EReg:matched";
}
}
public function matchedLeft():String {
if (m[1] == null)
throw "No string matched";
return sub(s, 1, m[1] - 1).match;
}
public function matchedRight():String {
if (m[1] == null)
throw "No string matched";
return sub(s, m[2] + 1).match;
}
public function matchedPos():{pos:Int, len:Int} {
var left = matchedLeft();
var matched = matched(0);
if (m[1] == null)
throw "No string matched";
return {
pos: left.length,
len: matched.length
}
}
public function matchSub(s:String, pos:Int, len:Int = -1):Bool {
var ss = s.substr(0, len < 0 ? s.length : pos + len);
if (global) {
m = lua.TableTools.pack(r.exec(ss, pos + 1));
var b = m[1] != null;
if (b) {
this.s = s;
}
return b;
} else {
m = lua.TableTools.pack(r.exec(ss, pos + 1));
var b = m[1] != null;
if (b) {
this.s = s;
}
return b;
}
}
public function split(s:String):Array<String> {
if (global) {
return Lib.fillArray(Rex.split(s, r));
} else {
// we can't use directly Rex.split because it's ignoring the 'g' flag
var d = "#__delim__#";
return Lib.fillArray(Rex.split(replace(s, d), d));
}
}
public function replace(s:String, by:String):String {
var chunks = by.split("$$");
chunks = [for (chunk in chunks) Rex.gsub(chunk, "\\$(\\d)", "%%%1", 1)];
by = chunks.join("$");
return Rex.gsub(s, r, by, global ? null : 1);
}
public function map(s:String, f:EReg->String):String {
var bytesOffset = 1;
var buf = new StringBuf();
do {
if (bytesOffset > len(s)) {
break;
} else if (!matchFromByte(s, bytesOffset)) {
buf.add(sub(s, bytesOffset).match);
break;
}
var pos = m[1];
var length = m[2] - m[1];
buf.add(sub(s, bytesOffset, pos - 1).match);
buf.add(f(this));
if (length < 0) {
var charBytes = len(sub(s, pos).match.charAt(0));
buf.add(sub(s, pos, pos + charBytes - 1).match);
bytesOffset = pos + charBytes;
} else {
bytesOffset = m[2] + 1;
}
} while (global);
if (!global && bytesOffset > 1 && bytesOffset - 1 < len(s))
buf.add(sub(s, bytesOffset).match);
return buf.toString();
}
function map_old(s:String, f:EReg->String):String {
var offset = 0;
var buf = new StringBuf();
do {
if (offset >= s.length) {
break;
} else if (!matchSub(s, offset)) {
buf.add(s.substr(offset));
break;
}
var p = matchedPos();
buf.add(s.substr(offset, p.pos - offset));
buf.add(f(this));
if (p.len == 0) {
buf.add(s.substr(p.pos, 1));
offset = p.pos + 1;
} else
offset = p.pos + p.len;
} while (global);
if (!global && offset > 0 && offset < s.length)
buf.add(s.substr(offset));
return buf.toString();
}
public static function escape(s:String):String {
return escapeRegExpRe.map(s, function(r) return "\\" + r.matched(0));
}
static var escapeRegExpRe = ~/[\[\]{}()*+?.\\\^$|]/g;
static function __init__():Void {
if (Rex == null) {
throw "Rex is missing. Please install lrexlib-pcre.";
}
}
}

View File

@ -0,0 +1,119 @@
/*
* 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;
class Math {
public static var PI(get, null):Float;
static inline function get_PI():Float
return lua.Math.pi;
public static var NEGATIVE_INFINITY(get, null):Float;
static inline function get_NEGATIVE_INFINITY():Float
return -lua.Math.huge;
public static var POSITIVE_INFINITY(get, null):Float;
static inline function get_POSITIVE_INFINITY():Float
return lua.Math.huge;
public static var NaN(get, null):Float;
// Note: this has to be an untyped literal, otherwise the compiler tries
// to unify it to an Int, which defeats useful numeric reflection behavior.
static inline function get_NaN():Float
return untyped __lua__("(0/0)");
public static function isNaN(f:Float):Bool
return (f != f);
public static function isFinite(f:Float):Bool {
return (f > Math.NEGATIVE_INFINITY && f < Math.POSITIVE_INFINITY);
}
public static inline function abs(v:Float):Float
return lua.Math.abs(v);
public static inline function acos(v:Float):Float
return lua.Math.acos(v);
public static inline function asin(v:Float):Float
return lua.Math.asin(v);
public static inline function atan(v:Float):Float
return lua.Math.atan(v);
public static inline function ceil(v:Float):Int
return lua.Math.ceil(v);
public static inline function cos(v:Float):Float
return lua.Math.cos(v);
public static inline function exp(v:Float):Float
return lua.Math.exp(v);
public static inline function sin(v:Float):Float
return lua.Math.sin(v);
public static inline function sqrt(v:Float):Float
return lua.Math.sqrt(v);
public static inline function tan(v:Float):Float
return lua.Math.tan(v);
public static inline function floor(v:Float):Int
return lua.Math.floor(v);
public static inline function log(v:Float):Float
return lua.Math.log(v);
public static inline function random():Float
return untyped __define_feature__("Math.random", lua.Math.random());
public static inline function atan2(y:Float, x:Float):Float
return lua.Math.atan2(y, x);
public static function max(a:Float, b:Float):Float {
return Math.isNaN(a) || Math.isNaN(b) ? Math.NaN : lua.Math.max(a, b);
}
public static function min(a:Float, b:Float):Float {
return Math.isNaN(a) || Math.isNaN(b) ? Math.NaN : lua.Math.min(a, b);
}
public static inline function pow(v:Float, exp:Float):Float
return lua.Math.pow(v, exp);
public static inline function round(v:Float):Int
return Math.floor(v + 0.5);
public static inline function ffloor(v:Float):Float
return floor(v);
public static inline function fceil(v:Float):Float
return ceil(v);
public static inline function fround(v:Float):Float
return round(v);
}

View File

@ -0,0 +1,166 @@
/*
* 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 lua.Lua;
import lua.TableTools;
import lua.Boot;
@:coreApi class Reflect {
public inline static function hasField(o:Dynamic, field:String):Bool {
if (Lua.type(o) == "string" && (untyped String.prototype[field] != null || field == "length")) {
return true;
} else
return untyped o.__fields__ != null ? o.__fields__[field] != null : o[field] != null;
}
public static function field(o:Dynamic, field:String):Dynamic
untyped {
if (Lua.type(o) == "string") {
if (field == "length") {
return cast(o : String).length;
} else
return untyped String.prototype[field];
} else {
return try o[field] catch (e:Dynamic) null;
}
}
public inline static function setField(o:Dynamic, field:String, value:Dynamic):Void
untyped {
o[field] = value;
}
public static function getProperty(o:Dynamic, field:String):Dynamic {
return if (o == null) {
untyped __define_feature__("Reflect.getProperty", null);
} else if (o.__properties__ != null && Reflect.field(o, "get_" + field) != null) {
callMethod(o, Reflect.field(o, "get_" + field), []);
} else {
Reflect.field(o, field);
}
}
public static function setProperty(o:Dynamic, field:String, value:Dynamic):Void
untyped {
if (o.__properties__ != null && o.__properties__["set_" + field]) {
var tmp:String = o.__properties__["set_" + field];
callMethod(o, Reflect.field(o, tmp), [value]);
} else {
o[field] = __define_feature__("Reflect.setProperty", value);
}
}
public static function callMethod(o:Dynamic, func:haxe.Constraints.Function, args:Array<Dynamic>):Dynamic {
if (args == null || args.length == 0) {
return func(o);
} else {
var self_arg = false;
if (o != null && o.__name__ == null) {
self_arg = true;
}
return if (self_arg) {
func(o, lua.TableTools.unpack(cast args, 0, args.length - 1));
} else {
func(lua.TableTools.unpack(cast args, 0, args.length - 1));
}
}
}
public static function fields(o:Dynamic):Array<String> {
if (lua.Lua.type(o) == "string") {
return Reflect.fields(untyped String.prototype);
} else {
return untyped _hx_field_arr(o);
}
}
public static function isFunction(f:Dynamic):Bool {
return Lua.type(f) == "function" && !(Boot.isClass(f) || Boot.isEnum(f));
}
public static function compare<T>(a:T, b:T):Int {
if (a == b)
return 0
else if (a == null)
return -1
else if (b == null)
return 1
else
return (cast a) > (cast b) ? 1 : -1;
}
public static function compareMethods(f1:Dynamic, f2:Dynamic):Bool {
return f1 == f2;
}
public static function isObject(v:Dynamic):Bool
untyped {
if (v == null)
return false;
var t = __lua__("type(v)");
return (t == "string" || (t == "table" && v.__enum__ == null))
|| (t == "function" && (lua.Boot.isClass(v) || lua.Boot.isEnum(v)) != null);
}
public static function isEnumValue(v:Dynamic):Bool {
return v != null && Std.isOfType(v, lua.Table) && v.__enum__ != null;
}
public static function deleteField(o:Dynamic, field:String):Bool
untyped {
if (!hasField(o, field))
return false;
o[field] = null;
o.__fields__[field] = null;
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 {
/*
- Convert var arg to table
- Set indexing from zero
- Extract real table length
- Recreate as dynamic array
- Return function called with this array
*/
return untyped __lua__("function(...)
local a = {...}
local b = {}
local l = 0
for k, v in pairs(a) do
b[k-1] = v
l = math.max(k,l)
end
return f(_hx_tab_array(b, l))
end");
}
}

View File

@ -0,0 +1,110 @@
/*
* 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 lua.Boot;
import lua.NativeStringTools;
@:keepInit
@:coreApi class Std {
@:deprecated('Std.is is deprecated. Use Std.isOfType instead.')
public static inline function is(v:Dynamic, t:Dynamic):Bool {
return isOfType(v, t);
}
public static inline function isOfType(v:Dynamic, t:Dynamic):Bool {
return untyped lua.Boot.__instanceof(v, t);
}
public static inline function downcast<T:{}, S:T>(value:T, c:Class<S>):S {
return untyped lua.Boot.__instanceof(value, c) ? cast value : 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);
}
@:keep
public static function string(s:Dynamic) : String {
return untyped _hx_tostring(s, 0);
}
public static function int(x:Float):Int {
if (!Math.isFinite(x) || Math.isNaN(x))
return 0;
else
return lua.Boot.clampInt32(x);
}
public static function parseInt(x:String):Null<Int> {
if (x == null)
return null;
var hexMatch = NativeStringTools.match(x, "^[ \t\r\n]*([%-+]*0[xX][%da-fA-F]*)");
if (hexMatch != null) {
var sign = switch StringTools.fastCodeAt(hexMatch, 0) {
case '-'.code: -1;
case '+'.code: 1;
case _: 0;
}
return (sign == -1 ? -1 : 1) * lua.Lua.tonumber(hexMatch.substr(sign == 0 ? 2 : 3), 16);
} else {
var intMatch = NativeStringTools.match(x, "^ *[%-+]?%d*");
if (intMatch != null) {
return lua.Lua.tonumber(intMatch);
} else {
return null;
}
}
}
public static function parseFloat(x:String):Float {
if (x == null || x == "")
return Math.NaN;
var digitMatch = NativeStringTools.match(x, "^ *[%.%-+]?[0-9]%d*");
if (digitMatch == null) {
return Math.NaN;
}
x = x.substr(digitMatch.length);
var decimalMatch = NativeStringTools.match(x, "^%.%d*");
if (decimalMatch == null)
decimalMatch = "";
x = x.substr(decimalMatch.length);
var eMatch = NativeStringTools.match(x, "^[eE][+%-]?%d+");
if (eMatch == null)
eMatch = "";
var result = lua.Lua.tonumber(digitMatch + decimalMatch + eMatch);
return result != null ? result : Math.NaN;
}
public static function random(x:Int):Int {
return untyped x <= 0 ? 0 : Math.floor(Math.random() * x);
}
static function __init__():Void
untyped {
__feature__("lua.Boot.isClass", String.__name__ = __feature__("Type.getClassName", "String", true));
__feature__("Type.resolveClass", _hxClasses["Array"] = Array);
__feature__("lua.Boot.isClass", Array.__name__ = __feature__("Type.getClassName", "Array", true));
}
}

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 lua.Lua;
import lua.Table;
import lua.Boot;
#if lua_vanilla
private typedef BaseString = lua.NativeStringTools;
#else
private typedef BaseString = lua.lib.luautf8.Utf8;
#end
@:coreApi
class String {
static var __oldindex:String->String->Dynamic;
public var length(default, null):Int;
public inline function new(string:String)
untyped {}
@:keep
static function __index(s:Dynamic, k:Dynamic):Dynamic {
if (k == "length")
return BaseString.len(s);
else if (Reflect.hasField(untyped String.prototype, k))
return untyped String.prototype[k];
else if (__oldindex != null) {
if (Lua.type(__oldindex) == "function") {
return __oldindex(s, k);
} else if (Lua.type(__oldindex) == "table") {
return untyped __oldindex[k];
}
return null;
} else
return null;
}
public inline function toUpperCase():String
return BaseString.upper(this);
public inline function toLowerCase():String
return BaseString.lower(this);
public inline function indexOf(str:String, ?startIndex:Int):Int {
if (startIndex == null)
startIndex = 1;
else
startIndex += 1;
if (str == "") {
return indexOfEmpty(this, startIndex - 1);
}
var r = BaseString.find(this, str, startIndex, true).begin;
if (r != null && r > 0)
return r - 1;
else
return -1;
}
static function indexOfEmpty(s:String, startIndex:Int):Int {
var length = BaseString.len(s);
if(startIndex < 0) {
startIndex = length + startIndex;
if(startIndex < 0) startIndex = 0;
}
return startIndex > length ? length : startIndex;
}
public inline function lastIndexOf(str:String, ?startIndex:Int):Int {
var ret = -1;
if (startIndex == null)
startIndex = length;
while (true) {
var p = indexOf(str, ret + 1);
if (p == -1 || p > startIndex || p == ret)
break;
ret = p;
}
return ret;
}
public inline function split(delimiter:String):Array<String> {
var idx = 1;
var ret = [];
while (idx != null) {
var newidx = 0;
if (delimiter.length > 0) {
newidx = BaseString.find(this, delimiter, idx, true).begin;
} else if (idx >= this.length) {
newidx = null;
} else {
newidx = idx + 1;
}
if (newidx != null) {
var match = BaseString.sub(this, idx, newidx - 1).match;
ret.push(match);
idx = newidx + delimiter.length;
} else {
ret.push(BaseString.sub(this, idx, this.length).match);
idx = null;
}
}
return ret;
}
public inline function toString():String {
return this;
}
public inline function substring(startIndex:Int, ?endIndex:Int):String {
if (endIndex == null)
endIndex = this.length;
if (endIndex < 0)
endIndex = 0;
if (startIndex < 0)
startIndex = 0;
if (endIndex < startIndex) {
// swap the index positions
return BaseString.sub(this, endIndex + 1, startIndex).match;
} else {
return BaseString.sub(this, startIndex + 1, endIndex).match;
}
}
public inline function charAt(index:Int):String {
return BaseString.sub(this, index + 1, index + 1).match;
}
public inline function charCodeAt(index:Int):Null<Int> {
return BaseString.byte(this, index + 1);
}
public inline function substr(pos:Int, ?len:Int):String {
if (len == null || len > pos + this.length)
len = this.length;
else if (len < 0)
len = length + len;
if (pos < 0)
pos = length + pos;
if (pos < 0)
pos = 0;
return BaseString.sub(this, pos + 1, pos + len).match;
}
public inline static function fromCharCode(code:Int):String {
return BaseString.char(code);
}
}

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.
*/
import lua.Table;
class StringBuf {
var b:Table<Int, String>;
public var length(get, null):Int;
public inline function new() {
b = Table.create();
this.length = 0;
}
inline function get_length():Int {
return length;
}
public inline function add<T>(x:T):Void {
var str = Std.string(x);
Table.insert(b, str);
length += str.length;
}
public inline function addChar(c:Int):Void {
Table.insert(b, String.fromCharCode(c));
length += 1;
}
public inline function addSub(s:String, pos:Int, ?len:Int):Void {
var part = len == null ? s.substr(pos) : s.substr(pos, len);
Table.insert(b, part);
length += part.length;
}
public inline function toString():String {
return Table.concat(b);
}
}

View File

@ -0,0 +1,126 @@
/*
* 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 lua.Boot;
import lua.Io;
import lua.Lua;
import lua.lib.luv.Os;
import lua.lib.luv.Misc;
import sys.io.FileInput;
import sys.io.FileOutput;
@:coreApi
class Sys {
static var _system_name:String;
public static inline function print(v:Dynamic):Void {
return lua.Lib.print(v);
}
public static inline function println(v:Dynamic):Void {
return lua.Lib.println(v);
}
public inline static function args():Array<String> {
var targs = lua.PairTools.copy(Lua.arg);
var args = lua.Table.toArray(targs);
return args;
}
public static function command(cmd:String, ?args:Array<String>):Int {
var p = new sys.io.Process(cmd, args);
var code = p.exitCode();
p.close();
return code;
}
public inline static function cpuTime():Float {
return lua.Os.clock();
}
public inline static function exit(code:Int):Void {
lua.Os.exit(code);
}
public inline static function getChar(echo:Bool):Int {
return lua.Io.read().charCodeAt(0);
}
static function getSystemName():String {
return lua.Boot.systemName();
}
public static function systemName():String {
if (_system_name == null)
_system_name = getSystemName();
return _system_name;
}
public static function environment():Map<String, String> {
var env = lua.lib.luv.Os.environ();
return lua.Table.toMap(env);
}
@:deprecated("Use programPath instead") public static function executablePath():String {
return Misc.exepath();
}
public inline static function programPath():String {
return haxe.io.Path.join([getCwd(), Lua.arg[0]]);
}
public inline static function getCwd():String
return Misc.cwd();
public inline static function setCwd(s:String):Void
Misc.chdir(s);
public inline static function getEnv(s:String):String {
return Os.getenv(s);
}
public inline static function putEnv(s:String, v:String):Void {
Os.setenv(s, v);
}
public inline static function setTimeLocale(loc:String):Bool {
// TODO Verify
return lua.Os.setlocale(loc) != null;
}
public static function sleep(seconds:Float):Void
lua.lib.luv.Thread.sleep(Math.floor(seconds * 1000));
public inline static function stderr():haxe.io.Output
return @:privateAccess new FileOutput(Io.stderr);
public inline static function stdin():haxe.io.Input
return @:privateAccess new FileInput(Io.stdin);
public inline static function stdout():haxe.io.Output
return @:privateAccess new FileOutput(Io.stdout);
public static function time():Float {
var stamp = lua.lib.luv.Misc.gettimeofday();
return stamp.seconds + (stamp.microseconds / 1000000);
}
}

View File

@ -0,0 +1,220 @@
/*
* 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 lua.Lua;
import lua.Table;
enum ValueType {
TNull;
TInt;
TFloat;
TBool;
TObject;
TFunction;
TClass(c:Class<Dynamic>);
TEnum(e:Enum<Dynamic>);
TUnknown;
}
@:coreApi class Type {
public static function getClass<T>(o:T):Class<T>
untyped {
if (o == null)
return null;
return lua.Boot.getClass(o);
}
public static function getEnum(o:EnumValue):Enum<Dynamic>
untyped {
if (o == null)
return null;
return o.__enum__;
}
public static function getSuperClass(c:Class<Dynamic>):Class<Dynamic>
untyped {
return c.__super__;
}
public static inline function getClassName(c:Class<Dynamic>):String {
return untyped __define_feature__("Type.getClassName", c.__name__);
}
public static function getEnumName(e:Enum<Dynamic>):String {
if (untyped e.__ename__ == null)
return null;
return untyped e.__ename__;
}
public static function resolveClass(name:String):Class<Dynamic>
untyped {
// TODO: better tmp name for _hxClasses
var cl:Class<Dynamic> = _hxClasses[name];
// ensure that this is a class
if (cl == null || !lua.Boot.isClass(cl))
return null;
return cl;
}
public static function resolveEnum(name:String):Enum<Dynamic>
untyped {
// TODO: better tmp name for _hxClasses
var e:Dynamic = _hxClasses[name];
// ensure that this is an enum
if (e == null || !lua.Boot.isEnum(e))
return null;
return e;
}
public static function createInstance<T>(cl:Class<T>, args:Array<Dynamic>):T
untyped {
return __new__(cl, lua.TableTools.unpack(cast args, 0));
}
public static function createEmptyInstance<T>(cl:Class<T>):T
untyped {
var ret = __lua_table__();
Lua.setmetatable(ret, untyped {__index: cl.prototype});
return ret;
}
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(null, f, params);
}
if (params != null && params.length != 0)
throw "Constructor " + constr + " does not need parameters";
return f;
}
public static function createEnumIndex<T>(e:Enum<T>, index:Int, ?params:Array<Dynamic>):T {
var c:String = (untyped e.__constructs__)[index];
if (c == null)
throw index + " is not a valid enum constructor index";
return createEnum(e, c, params);
}
public static function getInstanceFields(c:Class<Dynamic>):Array<String> {
var p:Dynamic = untyped c.prototype;
var a:Array<String> = [];
while (p != null) {
for (f in Reflect.fields(p)) {
if (!Lambda.has(a, f))
a.push(f);
}
var mt = lua.Lua.getmetatable(p);
if (mt != null && mt.__index != null)
p = mt.__index;
else
p = null;
}
return a;
}
public static function getClassFields(c:Class<Dynamic>):Array<String> {
var a = Reflect.fields(c);
a.remove("__name__");
a.remove("__interfaces__");
a.remove("__properties__");
a.remove("__super__");
a.remove("__meta__");
a.remove("prototype");
a.remove("new");
return a;
}
public static function getEnumConstructs(e:Enum<Dynamic>):Array<String> {
var a:Array<String> = untyped e.__constructs__;
return a.copy();
}
public static function typeof(v:Dynamic):ValueType {
switch (Lua.type(v)) {
case "boolean":
return TBool;
case "string":
return TClass(String);
case "number":
// this should handle all cases : NaN, +/-Inf and Floats outside range
if (Math.ceil(v) == v % 2147483648.0)
return TInt;
return TFloat;
case "table":
var e = v.__enum__;
if (e != null)
return TEnum(e);
var c = lua.Boot.getClass(v);
if (c != null)
return TClass(c);
return TObject;
case "function":
if (lua.Boot.isClass(v) || lua.Boot.isEnum(v))
return TObject;
return TFunction;
case "nil":
return TNull;
default:
return TUnknown;
}
}
public static function enumEq<T>(a:T, b:T):Bool
untyped {
if (a == b)
return true;
try {
if (a[0] != b[0])
return false;
for (i in 2...a.length)
if (!enumEq(a[i], b[i]))
return false;
var e = a.__enum__;
if (e != b.__enum__ || e == null)
return false;
} catch (e:Dynamic) {
return false;
}
return true;
}
public inline static function enumConstructor(e:EnumValue):String {
return untyped e[0];
}
public inline static function enumParameters(e:EnumValue):Array<Dynamic> {
return (cast e : Array<Dynamic>).slice(2);
}
public inline static function enumIndex(e:EnumValue):Int {
return untyped e[1];
}
public static function allEnums<T>(e:Enum<T>):Array<T> {
return ((cast e).__empty_constructs__ : Array<T>).copy();
}
}

View File

@ -0,0 +1,85 @@
package haxe;
@:coreApi
class Exception {
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 __exceptionMessage:String;
@:noCompletion var __exceptionStack:Null<CallStack>;
@:noCompletion var __nativeStack:Array<String>;
@:noCompletion @:ifFeature("haxe.Exception.get_stack") var __skipStack:Int = 0;
@:noCompletion var __nativeException:Any;
@:noCompletion var __previousException:Null<Exception>;
static function caught(value:Any):Exception {
if(Std.isOfType(value, Exception)) {
return value;
} else {
return new ValueException(value, null, value);
}
}
static function thrown(value:Any):Any {
if(Std.isOfType(value, Exception)) {
return (value:Exception).native;
} else {
var e = new ValueException(value);
e.__shiftStack();
return e;
}
}
public function new(message:String, ?previous:Exception, ?native:Any) {
__exceptionMessage = message;
__previousException = previous;
if(native != null) {
__nativeException = native;
__nativeStack = NativeStackTrace.exceptionStack();
} else {
__nativeException = this;
__nativeStack = NativeStackTrace.callStack();
__skipStack = 1;
}
}
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 __exceptionMessage;
}
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,34 @@
/*
* 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;
@:coreApi
class Json {
public static function parse(text:String):Dynamic {
return haxe.format.JsonParser.parse(text);
}
public static 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,54 @@
package haxe;
import haxe.CallStack.StackItem;
/**
Do not use manually.
**/
@:dox(hide)
@:noCompletion
class NativeStackTrace {
@:ifFeature('haxe.NativeStackTrace.exceptionStack')
static public inline function saveStack(exception:Any):Void {
}
static public function callStack():Array<String> {
return switch lua.Debug.traceback() {
case null: [];
case s: s.split('\n').slice(3);
}
}
static public function exceptionStack():Array<String> {
return []; //Not implemented. Maybe try xpcal instead of pcal in genlua.
}
static public function toHaxe(native:Array<String>, skip:Int = 0):Array<StackItem> {
var stack = [];
var cnt = -1;
for (item in native) {
var parts = item.substr(1).split(":"); //`substr` to skip a tab at the beginning of a line
var file = parts[0];
if(file == '[C]') {
continue;
}
++cnt;
if(skip > cnt) {
continue;
}
var line = parts[1];
var method = if(parts.length <= 2) {
null;
} else {
var methodPos = parts[2].indexOf("'");
if(methodPos < 0) {
null;
} else {
Method(null, parts[2].substring(methodPos + 1, parts[2].length - 1));
}
}
stack.push(FilePos(method, file, Std.parseInt(line)));
}
return stack;
}
}

View File

@ -0,0 +1,55 @@
package haxe;
import lua.Lua.select;
import lua.Table;
import lua.PairTools.copy;
import lua.TableTools.maxn;
import lua.TableTools.pack;
import lua.TableTools.unpack;
import haxe.iterators.RestIterator;
import haxe.iterators.RestKeyValueIterator;
private typedef NativeRest<T> = Table<Int,T>;
@:coreApi
abstract Rest<T>(NativeRest<T>) {
public var length(get, never):Int;
inline function get_length():Int
return maxn(this);
@:from static public function of<T>(array:Array<T>):Rest<T> {
return new Rest(Table.fromArray(array));
}
inline function new(table:Table<Int,T>):Void
this = table;
@:arrayAccess inline function get(index:Int):T
return this[index + 1];
@:to public function toArray():Array<T> {
return Table.toArray(this);
}
public inline function iterator():RestIterator<T>
return new RestIterator<T>(this);
public inline function keyValueIterator():RestKeyValueIterator<T>
return new RestKeyValueIterator<T>(this);
public inline function append(item:T):Rest<T> {
var result = copy(this);
Table.insert(result, item);
return new Rest(result);
}
public inline function prepend(item:T):Rest<T> {
var result = copy(this);
Table.insert(result, 1, item);
return new Rest(result);
}
public function toString():String {
return toArray().toString();
}
}

View File

@ -0,0 +1,115 @@
/*
* 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 lua.Lua;
class IntMap<T> implements haxe.Constraints.IMap<Int, T> {
private var h:lua.Table<Int, T>;
static var tnull:Dynamic = lua.Table.create();
public inline function new():Void {
h = lua.Table.create();
}
public inline function set(key:Int, value:T):Void {
if (value == null) {
h[key] = tnull;
} else {
h[key] = value;
}
}
public inline function get(key:Int):Null<T> {
var ret = h[key];
if (ret == tnull) {
ret = null;
}
return ret;
}
public inline function exists(key:Int):Bool {
return h[key] != null;
}
public function remove(key:Int):Bool {
if (h[key] == null) {
return false;
} else {
h[key] = null;
return true;
}
}
public function keys():Iterator<Int> {
var next = Lua.next;
var cur = next(h, null).index;
return {
next: function() {
var ret = cur;
cur = next(h, cur).index;
return cast ret;
},
hasNext: function() return cur != null
}
}
public function iterator():Iterator<T> {
var it = keys();
return untyped {
hasNext: function() return it.hasNext(),
next: function() return h[it.next()]
};
}
@: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 = lua.Table.create();
}
}

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 haxe.ds;
class ObjectMap<A, B> implements haxe.Constraints.IMap<A, B> {
static var count = 0;
static inline function assignId(obj:{}):Int {
return untyped obj.__id__ = ++count;
}
static inline function getId(obj:{}):Int {
return untyped obj.__id__;
}
var h:Dynamic;
var k:Dynamic;
public inline function new():Void {
h = lua.Table.create();
k = lua.Table.create();
}
public inline function set(key:A, value:B):Void
untyped {
h[key] = value;
k[key] = true;
}
public inline function get(key:A):Null<B>
untyped {
return h[key];
}
public inline function exists(key:A):Bool
untyped {
return k[key] != null;
}
public function remove(key:A):Bool
untyped {
if (k[key] == null)
return false;
k[key] = null;
h[key] = null;
return true;
}
public function keys():Iterator<A>
untyped {
var cur = next(h, null);
return {
next: function() {
var ret = cur;
cur = untyped next(k, cur);
return ret;
},
hasNext: function() return cur != null
}
}
public function iterator():Iterator<B> {
var itr = keys();
return untyped {
hasNext: itr.hasNext,
next: function() return h[itr.next()]
};
}
@:runtime public inline function keyValueIterator():KeyValueIterator<A, B> {
return new haxe.iterators.MapKeyValueIterator(this);
}
public function copy():ObjectMap<A, B> {
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(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 = lua.Table.create();
k = lua.Table.create();
}
}

View File

@ -0,0 +1,119 @@
/*
* 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 lua.Lua;
class StringMap<T> implements haxe.Constraints.IMap<String, T> {
private var h:lua.Table<String, T>;
static var tnull:Dynamic = lua.Table.create();
public inline function new():Void {
h = lua.Table.create();
}
public inline function set(key:String, value:T):Void
untyped {
if (value == null) {
h[key] = tnull;
} else {
h[key] = value;
}
}
public inline function get(key:String):Null<T>
untyped {
var ret = h[key];
if (ret == tnull) {
ret = null;
}
return ret;
}
public inline function exists(key:String):Bool
untyped {
return h[key] != null;
}
public function remove(key:String):Bool
untyped {
if (h[key] == null) {
return false;
} else {
h[key] = null;
return true;
}
}
public function keys():Iterator<String> {
var next = Lua.next;
var cur = next(h, null).index;
return {
next: function() {
var ret = cur;
cur = next(h, cur).index;
return cast ret;
},
hasNext: function() return cur != null
}
}
public function iterator():Iterator<T> {
var it = keys();
return untyped {
hasNext: function() return it.hasNext(),
next: function() return h[it.next()]
};
}
@: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 = lua.Table.create();
}
}

View File

@ -0,0 +1,292 @@
/*
* 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.format;
/**
An implementation of JSON parser in Haxe.
This class is used by `haxe.Json` when native JSON implementation
is not available.
@see https://haxe.org/manual/std-Json-parsing.html
**/
class JsonParser {
/**
Parses given JSON-encoded `str` and returns the resulting object.
JSON objects are parsed into anonymous structures and JSON arrays
are parsed into `Array<Dynamic>`.
If given `str` is not valid JSON, an exception will be thrown.
If `str` is null, the result is unspecified.
**/
static public inline function parse(str:String):Dynamic {
return lua.lib.hxluasimdjson.Json.parse(str);
}
var str:String;
var pos:Int;
function new(str:String) {
this.str = str;
this.pos = 0;
}
function doParse():Dynamic {
var result = parseRec();
var c;
while (!StringTools.isEof(c = nextChar())) {
switch (c) {
case ' '.code, '\r'.code, '\n'.code, '\t'.code:
// allow trailing whitespace
default:
invalidChar();
}
}
return result;
}
function parseRec():Dynamic {
while (true) {
var c = nextChar();
switch (c) {
case ' '.code, '\r'.code, '\n'.code, '\t'.code:
// loop
case '{'.code:
var obj = {}, field = null, comma:Null<Bool> = null;
while (true) {
var c = nextChar();
switch (c) {
case ' '.code, '\r'.code, '\n'.code, '\t'.code:
// loop
case '}'.code:
if (field != null || comma == false)
invalidChar();
return obj;
case ':'.code:
if (field == null)
invalidChar();
Reflect.setField(obj, field, parseRec());
field = null;
comma = true;
case ','.code:
if (comma) comma = false else invalidChar();
case '"'.code:
if (field != null || comma) invalidChar();
field = parseString();
default:
invalidChar();
}
}
case '['.code:
var arr = [], comma:Null<Bool> = null;
while (true) {
var c = nextChar();
switch (c) {
case ' '.code, '\r'.code, '\n'.code, '\t'.code:
// loop
case ']'.code:
if (comma == false) invalidChar();
return arr;
case ','.code:
if (comma) comma = false else invalidChar();
default:
if (comma) invalidChar();
pos--;
arr.push(parseRec());
comma = true;
}
}
case 't'.code:
var save = pos;
if (nextChar() != 'r'.code || nextChar() != 'u'.code || nextChar() != 'e'.code) {
pos = save;
invalidChar();
}
return true;
case 'f'.code:
var save = pos;
if (nextChar() != 'a'.code || nextChar() != 'l'.code || nextChar() != 's'.code || nextChar() != 'e'.code) {
pos = save;
invalidChar();
}
return false;
case 'n'.code:
var save = pos;
if (nextChar() != 'u'.code || nextChar() != 'l'.code || nextChar() != 'l'.code) {
pos = save;
invalidChar();
}
return null;
case '"'.code:
return parseString();
case '0'.code, '1'.code, '2'.code, '3'.code, '4'.code, '5'.code, '6'.code, '7'.code, '8'.code, '9'.code, '-'.code:
return parseNumber(c);
default:
invalidChar();
}
}
}
function parseString() {
// eq( haxe.format.JsonParser.parse('"\\u00E9"'), "é" );
var start = pos;
var buf:StringBuf = null;
var prev = -1;
inline function cancelSurrogate() {
// invalid high surrogate (not followed by low surrogate)
buf.addChar(0xFFFD);
prev = -1;
}
while (true) {
var c = nextChar();
if (c == '"'.code)
break;
if (c == '\\'.code) {
if (buf == null) {
buf = new StringBuf();
}
buf.addSub(str, start, pos - start - 1);
c = nextChar();
switch (c) {
case "r".code:
buf.addChar("\r".code);
case "n".code:
buf.addChar("\n".code);
case "t".code:
buf.addChar("\t".code);
case "b".code:
buf.addChar(8);
case "f".code:
buf.addChar(12);
case "/".code, '\\'.code, '"'.code:
buf.addChar(c);
case 'u'.code:
var uc:Int = Std.parseInt("0x" + str.substr(pos, 4));
pos += 4;
if (prev != -1) {
if (uc < 0xDC00 || uc > 0xDFFF)
cancelSurrogate();
else {
buf.addChar(((prev - 0xD800) << 10) + (uc - 0xDC00) + 0x10000);
prev = -1;
}
} else if (uc >= 0xD800 && uc <= 0xDBFF)
prev = uc;
else
buf.addChar(uc);
default:
throw "Invalid escape sequence \\" + String.fromCharCode(c) + " at position " + (pos - 1);
}
start = pos;
}
// ensure utf8 chars are not cut
else if (c >= 0x80) {
pos++;
if (c >= 0xFC)
pos += 4;
else if (c >= 0xF8)
pos += 3;
else if (c >= 0xF0)
pos += 2;
else if (c >= 0xE0)
pos++;
}
else if (StringTools.isEof(c))
throw "Unclosed string";
}
if (buf == null) {
return str.substr(start, pos - start - 1);
} else {
buf.addSub(str, start, pos - start - 1);
return buf.toString();
}
}
inline function parseNumber(c:Int):Dynamic {
var start = pos - 1;
var minus = c == '-'.code, digit = !minus, zero = c == '0'.code;
var point = false, e = false, pm = false, end = false;
while (true) {
c = nextChar();
switch (c) {
case '0'.code:
if (zero && !point)
invalidNumber(start);
if (minus) {
minus = false;
zero = true;
}
digit = true;
case '1'.code, '2'.code, '3'.code, '4'.code, '5'.code, '6'.code, '7'.code, '8'.code, '9'.code:
if (zero && !point)
invalidNumber(start);
if (minus)
minus = false;
digit = true;
zero = false;
case '.'.code:
if (minus || point || e)
invalidNumber(start);
digit = false;
point = true;
case 'e'.code, 'E'.code:
if (minus || zero || e)
invalidNumber(start);
digit = false;
e = true;
case '+'.code, '-'.code:
if (!e || pm)
invalidNumber(start);
digit = false;
pm = true;
default:
if (!digit)
invalidNumber(start);
pos--;
end = true;
}
if (end)
break;
}
var f = Std.parseFloat(str.substr(start, pos - start));
var i = Std.int(f);
return if (i == f) i else f;
}
function nextChar() {
pos++;
return lua.NativeStringTools.byte(str, pos);
}
function invalidChar() {
pos--; // rewind
throw "Invalid char " + lua.NativeStringTools.byte(str, pos) + " at position " + pos;
}
function invalidNumber(start:Int) {
throw "Invalid number at position " + start + ": " + str.substr(start, pos - start);
}
}

View File

@ -0,0 +1,50 @@
/*
* Copyright (C)2005-2018 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.iterators;
import lua.lib.luautf8.Utf8;
class StringIterator {
var codes : (String, Int)->StringCodePoint;
var codepoint : Int;
var str : String;
var position : Int;
public inline function new(s:String) {
this.codes = Utf8.codes(s);
this.str = s;
var cp = codes(str, 0);
this.codepoint = cp.codepoint;
this.position = cp.position;
}
public inline function hasNext() {
return codepoint != null;
}
public inline function next() {
var ret = codepoint;
var cp = codes(str, position);
codepoint = cp.codepoint;
position = cp.position;
return ret;
}
}

View File

@ -0,0 +1,125 @@
/*
* 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 lua.Io;
import haxe.io.Path;
import lua.lib.luv.fs.FileSystem as LFileSystem;
class FileSystem {
public static function exists(path:String):Bool {
if (path == null)
return false;
else {
var res = LFileSystem.stat(path);
return res.result != null;
}
}
public inline static function rename(path:String, newPath:String):Void {
var ret = lua.Os.rename(path, newPath);
if (!ret.success) {
throw ret.message;
}
}
public inline static function stat(path:String):FileStat {
var ls = LFileSystem.stat(path);
if (ls.result == null)
throw ls.message;
var l = ls.result;
return {
gid: l.gid,
uid: l.uid,
rdev: l.rdev,
size: l.size,
nlink: l.nlink,
mtime: Date.fromTime(l.mtime.sec + l.mtime.nsec / 1000000),
mode: l.mode,
ino: l.ino,
dev: l.dev,
ctime: Date.fromTime(l.ctime.sec + l.ctime.nsec / 1000000),
atime: Date.fromTime(l.atime.sec + l.atime.nsec / 1000000)
};
}
public inline static function fullPath(relPath:String):String {
return LFileSystem.realpath(Path.normalize(absolutePath(relPath)));
}
public inline static function absolutePath(relPath:String):String {
if (haxe.io.Path.isAbsolute(relPath)) {
return relPath;
}
var pwd = lua.lib.luv.Misc.cwd();
if (pwd == null)
return relPath;
return Path.join([pwd, relPath]);
}
public inline static function deleteFile(path:String):Void {
var ret = lua.Os.remove(path);
if (!ret.success) {
throw ret.message;
}
}
public inline static function readDirectory(path:String):Array<String> {
var scandir = LFileSystem.scandir(path);
var itr = function() {
var next = LFileSystem.scandir_next(scandir).name;
return next;
}
return lua.Lib.fillArray(itr);
}
public inline static function isDirectory(path:String):Bool {
var result = LFileSystem.stat(path).result;
if (result == null)
return false;
else
return result.type == "directory";
}
public inline static function deleteDirectory(path:String):Void {
var ret = LFileSystem.rmdir(path);
if (ret.result == null) {
throw ret.message;
}
}
public static function createDirectory(path:String):Void {
var path = haxe.io.Path.addTrailingSlash(path);
var _p = null;
var parts = [];
while (path != (_p = haxe.io.Path.directory(path))) {
parts.unshift(path);
path = _p;
}
for (part in parts) {
if (part.charCodeAt(part.length - 1) != ":".code && !exists(part) && !LFileSystem.mkdir(part, 511).result)
throw "Could not create directory:" + part;
}
}
}

View File

@ -0,0 +1,97 @@
/*
* 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.SysTools;
import lua.Lua;
import lua.Io;
import lua.Os;
import lua.FileHandle;
import lua.Boot;
@:coreApi
class File {
public static function getContent(path:String):String {
var f = Io.open(path, "r");
if (f == null)
throw 'Invalid path : $path';
var s = f.read("*all");
f.close();
return s;
}
public static function append(path:String, binary:Bool = true):FileOutput {
return @:privateAccess new FileOutput(Io.open(path, "a"));
}
public static function update(path:String, binary:Bool = true):FileOutput {
if (!FileSystem.exists(path)) {
write(path).close();
}
return @:privateAccess new FileOutput(Io.open(path, binary ? "r+b" : "r+"));
}
public static function copy(srcPath:String, dstPath:String):Void {
var result = switch (Sys.systemName()) {
case "Windows": Os.execute('copy ${SysTools.quoteWinArg(srcPath, true)} ${SysTools.quoteWinArg(dstPath, true)}');
default: Os.execute('cp ${SysTools.quoteUnixArg(srcPath)} ${SysTools.quoteUnixArg(dstPath)}');
};
if (#if (lua_ver >= 5.2) !result.success #elseif (lua_ver < 5.2) result != 0 #else ((result : Dynamic) != true && (result : Dynamic) != 0) #end
) {
throw 'Failed to copy $srcPath to $dstPath';
}
}
public static function getBytes(path:String):haxe.io.Bytes {
var finput = read(path, true);
var res = finput.readAll();
finput.close();
return res;
}
public static function read(path:String, binary:Bool = true):FileInput {
var fh = Io.open(path, binary ? 'rb' : 'r');
if (fh == null)
throw 'Invalid path : $path';
return @:privateAccess new FileInput(fh);
}
public static function write(path:String, binary:Bool = true):FileOutput {
var fh = Io.open(path, binary ? 'wb' : 'w');
if (fh == null)
throw 'Invalid path : $path';
return @:privateAccess new FileOutput(fh);
}
public static function saveBytes(path:String, bytes:haxe.io.Bytes):Void {
var f = write(path, true);
f.writeBytes(bytes, 0, bytes.length);
f.close();
}
public static function saveContent(path:String, content:String):Void {
var f = write(path, true);
f.writeString(content);
f.close();
}
}

View File

@ -0,0 +1,100 @@
/*
* 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 lua.FileHandle;
import lua.Io;
import lua.NativeStringTools;
import lua.Boot;
import lua.Os;
import haxe.io.Bytes;
import haxe.io.Error;
import haxe.io.Eof;
class FileInput extends haxe.io.Input {
var f:FileHandle;
var _eof:Bool;
function new(f:FileHandle) {
if (f == null)
throw 'Invalid filehandle : $f';
this.bigEndian = Boot.platformBigEndian;
this.f = f;
this._eof = false;
}
inline public function seek(p:Int, pos:FileSeek):Void {
var arg = switch (pos) {
case SeekBegin: "set";
case SeekCur: "cur";
case SeekEnd: "end";
}
_eof = false;
return f.seek(arg, p);
}
inline public function tell():Int {
return f.seek();
}
inline public function eof():Bool {
return _eof;
}
override inline public function readByte():Int {
var byte = f.read(1);
if (byte == null) {
_eof = true;
throw new haxe.io.Eof();
}
return NativeStringTools.byte(byte);
}
override function readBytes(s:Bytes, pos:Int, len:Int):Int {
if (eof())
throw new haxe.io.Eof();
return super.readBytes(s, pos, len);
}
override inline public function close():Void {
f.close();
}
override public function readAll(?bufsize:Int):Bytes {
if (bufsize == null)
bufsize = (1 << 14); // 16 Ko
var buf = Bytes.alloc(bufsize);
var total = new haxe.io.BytesBuffer();
try {
while (true) {
var len = readBytes(buf, 0, bufsize);
if (len == 0)
break;
total.addBytes(buf, 0, len);
}
} catch (e:Eof) {
_eof = true;
}
return total.getBytes();
}
}

View File

@ -0,0 +1,62 @@
/*
* 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 lua.FileHandle;
import haxe.io.Bytes;
class FileOutput extends haxe.io.Output {
var f:FileHandle;
function new(f:FileHandle) {
if (f == null)
throw 'Invalid filehandle : $f';
this.f = f;
}
public inline function seek(p:Int, pos:FileSeek):Void {
var arg = switch (pos) {
case SeekBegin: "set";
case SeekCur: "cur";
case SeekEnd: "end";
}
return f.seek(arg, p);
}
public inline function tell():Int {
return f.seek();
}
override inline public function writeByte(c:Int):Void {
f.write(String.fromCharCode(c));
}
override inline public function writeBytes(s:Bytes, pos:Int, len:Int):Int {
f.write(s.getString(pos, len));
return s.length;
}
override public function close() {
f.close();
}
}

View File

@ -0,0 +1,228 @@
/*
* 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 lua.Io;
import lua.lib.luv.Pipe;
import lua.lib.luv.Signal;
import lua.lib.luv.Loop;
import lua.Boot;
import lua.Table;
import lua.NativeStringTools;
import haxe.SysTools;
import haxe.io.Bytes;
import haxe.io.Error;
import haxe.io.Eof;
@:coreApi
class Process {
var _pid:Int;
var _handle:lua.lib.luv.Process;
var _code:Int;
var closef:Int->Signal->Void;
public var stdout(default, null):haxe.io.Input;
public var stderr(default, null):haxe.io.Input;
public var stdin(default, null):haxe.io.Output;
static var argQuote = Sys.systemName() == "Windows" ? function(x) return SysTools.quoteWinArg(x, true) : SysTools.quoteUnixArg;
static var _shell = Sys.systemName() == "Windows" ? 'cmd.exe' : '/bin/sh';
/**
Sets the args for the shell, which will include the cmd to be executed
by the shell.
**/
static function setArgs(cmd:String, ?args:Array<String>):Table<Int, String> {
var pargs = lua.Table.create();
var idx = 1;
if (sys.FileSystem.exists(cmd))
cmd = '"$cmd"'; // escape simple paths
var all = [cmd];
if (args != null) {
for (a in args) {
all.push(argQuote(a));
}
}
if (Sys.systemName() == "Windows") {
pargs[idx++] = '/s';
pargs[idx++] = '/c';
pargs[idx++] = all.join(" ");
} else {
pargs[idx++] = "-c";
pargs[idx++] = all.join(" ");
}
return pargs;
}
public function new(cmd:String, ?args:Array<String>, ?detached:Bool) {
if (detached)
throw "Detached process is not supported on this platform";
var _stdout = new Pipe(false);
var _stderr = new Pipe(false);
var _stdin = new Pipe(false);
stdout = new ProcessInput(_stdout);
stderr = new ProcessInput(_stderr);
stdin = new ProcessOutput(_stdin);
var stdio = untyped __lua_table__([_stdin, _stdout, _stderr]);
var opt = {args: setArgs(cmd, args), stdio: stdio};
var p = lua.lib.luv.Process.spawn(_shell, opt, function(code:Int, signal:Signal) {
_code = code;
if (!_handle.is_closing()){
_handle.close();
}
_stdin.shutdown(()->_stdin.close());
_stderr.shutdown(()->_stderr.close());
_stdout.shutdown(()->_stdout.close());
});
_handle = p.handle;
if (p.handle == null)
throw p.pid;
_pid = p.pid;
}
public function getPid():Int {
return _pid;
}
public function close():Void {
if (!_handle.is_closing()){
_handle.close();
}
}
public function exitCode(block:Bool = true):Null<Int> {
if (!block)
return _code;
while (_handle.is_active()) {
Loop.run(); // process io until the handle closes (emulate blocking)
}
return _code;
}
public function kill():Void {
_handle.kill("sigterm");
}
}
private class ProcessInput extends haxe.io.Input {
var b:Pipe;
var buf:String;
var idx:Int;
var _eof:Bool;
public function new(pipe:Pipe) {
b = pipe;
_eof = false;
}
inline public function eof():Bool {
return _eof;
}
override function readBytes(s:Bytes, pos:Int, len:Int):Int {
if (eof())
throw new haxe.io.Eof();
return super.readBytes(s, pos, len);
}
override public function readByte() {
var err_str = null;
if (buf == null || idx >= NativeStringTools.len(buf)) {
buf = null;
idx = 0;
var pending = true;
b.read_start(function(err, chunk) {
if (chunk != null) {
if (buf != null) {
buf = buf + chunk;
} else {
buf = chunk;
}
}
if (err != null)
err_str = err;
pending = false;
});
// process io until we read our input (emulate blocking)
while (pending)
Loop.run();
}
if (buf == null) {
_eof = true;
throw new haxe.io.Eof();
}
if (err_str != null)
throw err_str;
var code = NativeStringTools.byte(buf, ++idx);
return code;
}
override public function readAll(?bufsize:Int):Bytes {
if (bufsize == null)
bufsize = (1 << 14); // 16 Ko
var buf = Bytes.alloc(bufsize);
var total = new haxe.io.BytesBuffer();
try {
while (true) {
var len = readBytes(buf, 0, bufsize);
// don't throw blocked error here
if (len != 0)
total.addBytes(buf, 0, len);
if (len < bufsize)
break;
}
} catch (e:Eof) {
_eof = true;
}
return total.getBytes();
}
override public function close() {
b.close();
}
}
private class ProcessOutput extends haxe.io.Output {
var b:Pipe;
public function new(pipe:Pipe) {
b = pipe;
set_bigEndian(Boot.platformBigEndian);
}
override public function writeByte(c:Int):Void {
b.write(NativeStringTools.char(c));
}
override public function close() {
b.close();
}
}

View File

@ -0,0 +1,71 @@
/*
* 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.Bytes;
import haxe.io.BytesInput;
import lua.NativeStringTools.find;
import lua.lib.luv.net.Dns;
import lua.lib.luv.Os;
@:coreapi
class Host {
public var host(default, null):String;
public var ip(default, null):Int;
var _ip:String;
public function new(name:String):Void {
host = name;
if (find(name, "(%d+)%.(%d+)%.(%d+)%.(%d+)").begin != null) {
_ip = name;
} else {
var res = lua.lib.luv.net.Dns.getaddrinfo(name);
if (res.result == null)
throw "Unrecognized node name";
_ip = res.result[1].addr;
if (_ip == "::1")
_ip = "127.0.0.0";
}
var num = 0;
for (a in _ip.split(".")) {
num = num * 256 + lua.Lua.tonumber(a);
}
ip = num;
}
public function toString():String {
return _ip;
}
public function reverse():String {
return Dns.getnameinfo({ip: _ip}).result;
}
static public function localhost():String {
return Os.gethostname();
}
}

View File

@ -0,0 +1,234 @@
/*
* 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 lua.lib.luasocket.Socket as LuaSocket;
import lua.lib.luasocket.socket.*;
import lua.*;
import haxe.io.Bytes;
import haxe.io.Error;
class Socket {
public var input(default, null):haxe.io.Input;
public var output(default, null):haxe.io.Output;
var custom:Dynamic;
var _socket:LuaSocket;
var blocking = false;
var timeout = null;
public function new():Void {}
public function close():Void {
_socket.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 res = LuaSocket.connect(host.host, port);
if (res.message != null)
throw 'Socket Error : ${res.message}';
input = new SocketInput(res.result);
output = new SocketOutput(res.result);
_socket = res.result;
_socket.settimeout(timeout);
}
public function listen(connections:Int):Void {
var res = LuaSocket.tcp();
if (res.message != null)
throw 'Socket Listen Error : ${res.message}';
res.result.listen(connections);
_socket = res.result;
_socket.settimeout(timeout);
}
public function shutdown(read:Bool, write:Bool):Void {
var client:TcpClient = cast _socket;
switch [read, write] {
case [true, true]:
client.shutdown(Both);
case [true, false]:
client.shutdown(Receive);
case [false, true]:
client.shutdown(Send);
default:
null;
}
}
public function bind(host:Host, port:Int):Void {
var res = LuaSocket.bind(host.host, port);
if (res.message != null)
throw 'Socket Bind Error : ${res.message}';
_socket = res.result;
}
public function accept():Socket {
var server:TcpServer = cast _socket;
var res = server.accept();
if (res.message != null)
throw 'Error : ${res.message}';
var sock = new Socket();
sock._socket = res.result;
sock.input = new SocketInput(res.result);
sock.output = new SocketOutput(res.result);
return sock;
}
public function peer():{host:Host, port:Int} {
var client:TcpClient = cast _socket;
var res = client.getpeername();
var host = new Host(res.address);
return {host: host, port: Std.parseInt(res.port)};
}
public function host():{host:Host, port:Int} {
var server:TcpServer = cast _socket;
var res = server.getsockname();
var host = new Host(res.address);
return {host: host, port: Std.parseInt(res.port)};
}
public inline function setTimeout(timeout:Float):Void {
this.timeout = timeout;
if (_socket != null) {
var client:TcpClient = cast _socket;
client.settimeout(timeout);
}
}
public function waitForRead():Void {
select([this], null, null);
}
public function setBlocking(b:Bool):Void {
blocking = b;
}
public function setFastSend(b:Bool):Void {
var client:TcpClient = cast _socket;
client.setoption(TcpNoDelay, true);
}
static public function select(read:Array<Socket>, write:Array<Socket>, others:Array<Socket>,
?timeout:Float):{read:Array<Socket>, write:Array<Socket>, others:Array<Socket>} {
var read_tbl = read == null ? Table.create() : Table.fromArray([for (r in read) cast r._socket]);
var write_tbl = write == null ? Table.create() : Table.fromArray(([for (r in write) cast r._socket]));
var res = LuaSocket.select(read_tbl, write_tbl, timeout);
var convert_socket = function(x:LuaSocket) {
var sock = new Socket();
sock.input = new SocketInput(cast x);
sock.output = new SocketOutput(cast x);
return sock;
}
var read_arr = res.read == null ? [] : Table.toArray(res.read).map(convert_socket);
var write_arr = res.write == null ? [] : Table.toArray(res.write).map(convert_socket);
return {read: read_arr, write: write_arr, others: []};
}
}
private class SocketInput extends haxe.io.Input {
var tcp:TcpClient;
public function new(tcp:TcpClient) {
this.tcp = tcp;
}
override public function readByte():Int {
var res = tcp.receive(1);
if (res.message == "closed"){
throw new haxe.io.Eof();
}
else if (res.message != null)
throw 'Error : ${res.message}';
return res.result.charCodeAt(0);
}
override public function readBytes(s:Bytes, pos:Int, len:Int):Int {
var leftToRead = len;
var b = s.getData();
if (pos < 0 || len < 0 || pos + len > s.length)
throw haxe.io.Error.OutsideBounds;
var readCount = 0;
try {
while (leftToRead > 0) {
b[pos] = cast readByte();
pos++;
readCount++;
leftToRead--;
}
} catch (e:haxe.io.Eof) {
if (readCount == 0) {
throw e;
}
}
return readCount;
}
}
private class SocketOutput extends haxe.io.Output {
var tcp:TcpClient;
public function new(tcp:TcpClient) {
this.tcp = tcp;
}
override public function writeByte(c:Int):Void {
var char = NativeStringTools.char(c);
var res = tcp.send(char);
if (res.message != null){
throw 'Error : Socket writeByte : ${res.message}';
}
}
override public function writeBytes(s:Bytes, pos:Int, len:Int):Int {
if (pos < 0 || len < 0 || pos + len > s.length)
throw Error.OutsideBounds;
var b = s.getData().slice(pos, pos +len).map(function(byte){
return lua.NativeStringTools.char(byte);
});
var encoded = Table.concat(cast b, 0);
var res = tcp.send(encoded);
if (res.message != null){
throw 'Error : Socket writeByte : ${res.message}';
}
return len;
}
}

View File

@ -0,0 +1,5 @@
package lua.lib.hxluasimdjson;
@:luaRequire("hxsimdjson")
extern class Json {
public static function parse(str:String) : Dynamic;
}

View File

@ -0,0 +1,86 @@
/*
* 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 lua.lib.lrexlib;
import haxe.extern.EitherType;
@:luaRequire("rex_pcre")
extern class Rex {
inline static function create(expr:String, flag:EitherType<Int, String>):Rex {
return untyped Rex['new'](expr, flag);
}
/**
The function searches for the first match of the regexp `patt` in the
string `subj`, starting from offset `init`, subject to flags `cf` and `ef`.
@return matched string, or array of strings.
**/
static function match(patt:EitherType<Rex, String>, subj:String, ?init:Int, ?ef:Int):Dynamic;
/**
The function searches for the first match of the regexp patt in the string
`subj`, starting from offset `init`, subject to flags `cf` and `ef`.
**/
static function find(patt:EitherType<Rex, String>, subj:String, ?init:Int, ?ef:Int):Dynamic;
/**
The function is intended for use in the generic for Lua construct. It is
used for splitting a subject string `subj` into parts (sections). The `sep`
parameter is a regular expression pattern representing separators between
the sections.
**/
static function split(subj:String, sep:EitherType<Rex, String>, ?cf:Int, ?ef:Int):Void->String;
/**
This function counts matches of the pattern `patt` in the string `subj`.
**/
static function count(subj:String, patt:EitherType<Rex, String>, cf:Int, ef:Int):Dynamic;
static function flags(?tb:Dynamic):Dynamic;
/**
The function searches for the first match of the regexp in the string
`subj`, starting from offset `init`, subject to execution flags `ef`.
**/
function tfind(subj:String, ?init:Int, ?ef:Int):Dynamic;
/**
This function searches for the first match of the regexp in the string
`subj`, starting from offset `init`, subject to execution flags `ef`.
**/
function exec(subj:String, ?init:Int, ?ef:Int):Dynamic;
/**
The function is intended for use in the generic for Lua construct. It
returns an iterator for repeated matching of the pattern patt in the
string `subj`, subject to flags `cf` and `ef`.
**/
static function gmatch(subj:String, patt:EitherType<Rex, String>, ?cf:Int, ?ef:Int):Void->String;
/**
This function searches for all matches of the pattern `patt` in the string
`subj` and replaces them according to the parameters `repl` and `n`.
**/
static function gsub(subj:String, patt:EitherType<Rex, String>, repl:Dynamic, ?n:Int, ?cf:Int, ?ef:Int):String;
}

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 lua.lib.luasocket;
import lua.lib.luasocket.socket.*;
@:luaRequire("socket")
extern class Socket {
static var _DEBUG:Bool;
static var _VERSION:String;
static function tcp():Result<TcpMaster>;
static function bind(address:String, port:Int, ?backlog:Int):Result<TcpServer>;
static function connect(address:String, port:Int, ?locaddr:String, ?locport:Int):Result<TcpClient>;
static function gettime():Float;
static function select(recvt:Table<Int, Socket>, sendt:Table<Int, Socket>, ?timeout:Float):SelectResult;
function close():Void;
function getsockname():AddrInfo;
function settimeout(value:Float, ?mode:TimeoutMode):Void;
}

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 lua.lib.luasocket.socket;
@:multiReturn extern class AddrInfo {
var address:String;
var port: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 lua.lib.luasocket.socket;
@:luaRequire("socket", "dns")
extern class Dns {
static function gethostname():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 lua.lib.luasocket.socket;
enum abstract ReceivePattern(String) {
var All = "*a";
var Line = "*l";
}

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 lua.lib.luasocket.socket;
@:multiReturn extern class SelectResult {
var read:Table<Int, Socket>;
var write:Table<Int, Socket>;
}

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 lua.lib.luasocket.socket;
enum abstract ShutdownMode(String) {
var Both = "both";
var Send = "send";
var Receive = "receive";
}

View File

@ -0,0 +1,34 @@
/*
* 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 lua.lib.luasocket.socket;
import haxe.extern.EitherType;
extern class TcpClient extends Socket {
function getpeername():AddrInfo;
function receive(pattern:EitherType<ReceivePattern, Int>, ?prefix:String):Result<String>;
function send(data:String, ?i:Int, ?j:Int):Result<Int>;
function shutdown(mode:ShutdownMode):Result<Int>;
function settimeout(value:Float, ?mode:TimeoutMode):Void;
function setoption(option:TcpOption, value:EitherType<Bool, {on:Bool, timeout:Float}>):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 lua.lib.luasocket.socket;
import haxe.extern.EitherType;
extern class TcpMaster extends Socket {
// transforms master to TcpServer
function listen(backlog:Int):Void;
// transforms master to TcpClient
function connect(address:String, port:Int):Void;
function bind(address:String, port:Int):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 lua.lib.luasocket.socket;
enum abstract TcpOption(String) {
var KeepAlive = "keepalive";
var Linger = "linger";
var ReuseAddress = "reuseaddr";
var TcpNoDelay = "tcp-nodelay";
}

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 lua.lib.luasocket.socket;
import lua.*;
extern class TcpServer extends Socket {
function accept():Result<TcpClient>;
function settimeout(value:Int, ?mode:TimeoutMode):Void;
function setoption(option:String, value:TcpOption):Void;
}

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 lua.lib.luasocket.socket;
enum abstract TimeoutMode(String) {
var Block = "b";
var Total = "t";
}

View File

@ -0,0 +1,115 @@
package lua.lib.luautf8;
/**
These are all externs for the lua-utf8 library, which functions
as an additional set of string tools.
Note that all relevant indexes are "1" based.
**/
@:luaRequire('lua-utf8')
extern class Utf8 {
/**
Receives a string and returns its length. The empty string `""` has
length `0`. Embedded zeros are counted, so `"a\000bc\000"` has length `5`.
**/
static function len(str:String):Int;
/**
Receives zero or more integers. Returns a string with length equal to the
number of arguments, in which each character has the internal numerical
code equal to its corresponding argument.
Note that numerical codes are not necessarily portable across platforms.
**/
static function char(codes:haxe.extern.Rest<Int>):String;
/**
Returns the substring of `str` that starts at `start` and continues until `end`;
`start` and `end` can be negative. If `end` is absent, then it is assumed to be
equal to `-1` (which is the same as the string length).
In particular, the call `sub(str,1,end)` returns a prefix of `str`
with length `end`, and `sub(str, -end)` returns a suffix of `str` with
length `start`.
**/
static function sub(str:String, start:Int, ?end:Int):StringSub;
/**
Returns the character code at position `index` of `str`.
**/
static function charCodeAt(str:String, index:Int):Int;
/**
Looks for the first match of pattern in the string `str`.
If it finds a match, then `find` returns the indices of `str` where this
occurrence starts and ends.
@param target If the target has captures, then in a successful match the
captured values are also returned, after the two indices.
@param start specifies where to start the search; its default value is `1`
and can be negative.
@param plain turns off the pattern matching facilities, so the function does
a plain "find substring" operation, with no characters in pattern
being considered "magic". Note that if plain is given, then `start` must be given as well.
**/
static function find(str:String, target:String, ?start:Int, ?plain:Bool):StringFind;
/**
Returns the internal numerical codes of the characters `str[index]`.
Note that numerical codes are not necessarily portable across platforms.
**/
static function byte(str:String, ?index:Int):Int;
/**
**/
@:overload(function(str:String, pattern:String, replace:String->Void, ?n:Int):String {})
@:overload(function(str:String, pattern:String, replace:String->String, ?n:Int):String {})
static function gsub(str:String, pattern:String, replace:String, ?n:Int):String;
/**
Returns an iterator function that, each time it is called, returns the next
captures from pattern over string `str`. If `pattern` specifies no captures,
then the whole match is produced in each call.
**/
@:overload(function(str:String, pattern:String, match:Void->String, ?n:Int):String->Void {})
static function gmatch(str:String, pattern:String):Void->String;
/**
Looks for the first match of pattern in the string s. If it finds one,
then match returns the captures from the pattern; otherwise it returns `null`.
If pattern specifies no captures, then the whole match is returned.
The optional argument `n` specifies where to start the search;
its default value is `1` and can be negative.
**/
static function match(str:String, pattern:String, ?n:Int):String;
/**
Receives a string and returns a copy of this string with all lowercase
letters changed to uppercase. All other characters are left unchanged.
The definition of what a lowercase letter is depends on the current locale.
**/
static function upper(str:String):String;
/**
Receives a string and returns a copy of this string with all uppercase
letters changed to lowercase. All other characters are left unchanged.
The definition of what an uppercase letter is depends on the current locale.
**/
static function lower(str:String):String;
static function codes(str:String):String->Int->StringCodePoint;
}
@:multiReturn extern class StringFind {
var begin:Int;
var end:Int;
}
@:multiReturn extern class StringSub {
var match:String;
var count:Int;
}
@:multiReturn extern class StringCodePoint {
var position:Int;
var codepoint:Int;
}

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 lua.lib.luv;
@:luaRequire("luv")
extern class Async extends Handle {
static function new_async():Async;
@:native("new_async") function new():Void;
function send():Int;
}

View File

@ -0,0 +1,32 @@
/*
* 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 lua.lib.luv;
@:luaRequire("luv")
extern class Check extends Handle {
static function new_check():Check;
@:native("new_check") function new():Void;
function start(handle:Handle):Int;
function stop():Int;
}

View File

@ -0,0 +1,36 @@
/*
* 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 lua.lib.luv;
@:luaRequire("luv")
extern class Handle {
function is_active():Bool;
function is_closing():Bool;
function close():Void;
function ref():Void;
function unref():Void;
function has_ref():Bool;
function send_buffer_size(size:Int):Int;
function recv_buffer_size(size:Int):Int;
function fileno():Int;
}

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 lua.lib.luv;
@:luaRequire("luv")
extern class Idle extends Handle {
static function new_idle():Idle;
@:native("new_idle") function new():Void;
function start(cb:Void->Void):Int;
function stop(cb:Void->Void):Int;
}

View File

@ -0,0 +1,14 @@
package lua.lib.luv;
@:luaRequire("luv")
extern class Loop {
static function loop_close():Bool;
static function run(?mode:String):Bool;
static function loop_alive():Bool;
static function stop():Void;
static function backend_fd():Int;
static function backend_timeout():Int;
static function now():Int;
static function update_time():Void;
static function walk(cb:Handle->Void):Void;
}

View File

@ -0,0 +1,107 @@
/*
* 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 lua.lib.luv;
@:luaRequire("luv")
extern class Misc {
static function chdir(path:String):Bool;
static function cpu_info():Table<Int, CpuInfo>;
static function cwd():String;
static function exepath():String;
static function get_process_title():String;
static function get_total_memory():Int;
static function get_free_memory():Int;
static function getpid():Int;
static function getrusage():ResourceUsage;
static function guess_handle(handle:Int):String;
static function hrtime():Float;
static function gettimeofday() : TimeOfDay;
// TODO: implement this
static function interface_addresses() : Dynamic;
static function loadavg():Float;
static function resident_set_memory():Int;
static function set_process_title(title:String):Bool;
static function uptime():Int;
static function version():Int;
static function version_string():String;
// Windows only
static function getuid():Int;
static function setuid(from:Int, to:Int):String;
static function getgid():Int;
static function setgid(from:Int, to:Int):Void;
// Windows only
static function print_all_handles():Table<Int, String>;
static function print_active_handles():Table<Int, String>;
}
typedef CpuInfo = {
model:String,
times:CpuTimes,
speed:Int
}
typedef CpuTimes = {
sys:Int,
idle:Int,
irq:Int,
user:Int
}
typedef ResourceUsage = {
nivcsw:Int,
maxrss:Int,
msgrcv:Int,
isrss:Int,
inblock:Int,
ixrss:Int,
nvcsw:Int,
nsignals:Int,
minflt:Int,
nswap:Int,
msgsnd:Int,
oublock:Int,
majflt:Int,
stime:MicroTimeStamp,
idrss:Int,
utime:MicroTimeStamp
}
typedef MicroTimeStamp = {
usec:Int,
sec:Int
}
@:multiReturn
extern class TimeOfDay {
var seconds : Int;
var microseconds : Int;
}

View File

@ -0,0 +1,72 @@
/*
* 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 lua.lib.luv;
@:luaRequire("luv")
extern class Os {
@:native("os_homedir")
static function homedir():String;
@:native("os_tmpdir")
static function tmpdir():String;
@:native("os_get_passwd")
static function get_passwd():String;
@:native("os_getenv")
static function getenv(env:String):String;
@:native("os_setenv")
static function setenv(env:String, value:String):Void;
@:native("os_unsetenv")
static function unsetenv(env:String):Void;
@:native("os_gethostname")
static function gethostname():String;
@:native("os_environ")
static function environ():Table<String, String>;
@:native("os_uname")
static function uname():Uname;
@:native("os_getpid")
static function getpid():Int;
@:native("os_getppid")
static function getppid():Int;
@:native("os_getpriority")
static function getpriority(pid:Int):Int;
@:native("os_setpriority")
static function setpriority(pid:Int, priority:Int):Bool;
}
typedef Uname = {
sysname:String,
release:String,
version:String,
machine:String
}

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 lua.lib.luv;
import haxe.extern.EitherType;
@:luaRequire("luv")
extern class Pipe extends Stream {
static function new_pipe(ipc:Bool):Pipe;
@:native("new_pipe") function new(ipc:Bool):Void;
function open(file:EitherType<FileHandle, Handle>):Pipe;
function bind(name:String):Pipe;
function connect(name:String, cb:String->Bool->Void):Int;
function getsockname():String;
function pending_instances(count:Int):Int;
function pending_count():Int;
function pending_type():Int;
}

View File

@ -0,0 +1,32 @@
/*
* 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 lua.lib.luv;
@:luaRequire("luv")
extern class Poll extends Handle {
static function new_poll():Async;
@:native("new_poll") function new():Void;
function start(?type:Int, ?cb:Void->Void):Int;
function stop():Int;
}

View File

@ -0,0 +1,32 @@
/*
* 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 lua.lib.luv;
@:luaRequire("luv")
extern class Prepare extends Handle {
static function new_prepare():Prepare;
@:native("new_prepare") function new():Void;
function start():Int;
function stop():Int;
}

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 lua.lib.luv;
@:luaRequire("luv")
extern class Process extends Handle {
static function disable_stdio_inheritance():Void;
static function spawn(path:String, options:Dynamic, cb:Int->Signal->Void):LuvSpawn;
function kill(sig:String):Int;
}
typedef ProcessOptions = {
args:Table<Int, String>,
stdio:Table<Int, Pipe>
}
@:multiReturn extern class LuvSpawn {
var handle:Process;
var pid: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 lua.lib.luv;
@:luaRequire("luv")
extern class Request {
function cancel():Bool;
}

View File

@ -0,0 +1,32 @@
/*
* 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 lua.lib.luv;
@:luaRequire("luv")
extern class Signal extends Handle {
static function new_signal():Signal;
@:native("new_signal") function new():Void;
function start(sigtype:haxe.extern.EitherType<Int, String>, ?cb:Void->Void):Int;
function stop():Int;
}

View File

@ -0,0 +1,42 @@
/*
* 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 lua.lib.luv;
import lua.lib.luv.net.Tcp;
@:luaRequire("luv")
extern class Stream extends Handle {
function shutdown(?cb:Void->Void):Int;
function listen(backlog:Int, cb:String->String->Void):Int;
function accept(client_stream:Stream):Int;
function read_start(cb:String->String->Void):Int;
function read_stop():Int;
function write(data:StreamData, ?cb:String->Bool->Void):Int;
function write2(data:StreamData, send_handle:Tcp, cb:String->Bool->Void):Int;
function try_write(data:StreamData):Int;
function is_readable():Bool;
function is_writable():Bool;
function set_blocking(blocking:Bool):Int;
}
typedef StreamData = haxe.extern.EitherType<String, Table<Int, String>>;

View File

@ -0,0 +1,34 @@
/*
* 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 lua.lib.luv;
@:luaRequire("luv")
extern class Thread {
static function new_thread():Timer;
@:native("new_thread") function new():Void;
static function self():Thread;
static function sleep(msec:Int):Void;
function equal(t:Thread):Bool;
function join(t:Thread):Bool;
}

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 lua.lib.luv;
@:luaRequire("luv")
extern class Timer extends Handle {
static function new_timer():Timer;
@:native("new_timer") function new():Void;
function start(timeout:Int, repeat:Int, cb:Void->Void):Int;
function stop():Int;
function again():Int;
function set_repeat(repeat:Int):Void;
function get_repeat():Int;
}

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 lua.lib.luv;
@:luaRequire("luv")
extern class Tty extends Stream {
static function new_tty(fd:Int, readable:Bool):Tty;
@:native("new_tty") function new(fd:Int, readable:Bool):Void;
static function reset_mode():Int;
function set_mode(mode:Int):Int;
function get_winsize():WidthHeight;
}
@:multiReturn
extern class WidthHeight {
var width:Int;
var height:Int;
}

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 lua.lib.luv;
@:luaRequire("luv")
extern class Work {
static function new_work():Work;
@:native("new_work") function new():Void;
static function queue_work(work:Work):Bool;
}

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 lua.lib.luv.fs;
typedef FileDescriptor = Int;

View File

@ -0,0 +1,215 @@
/*
* 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 lua.lib.luv.fs;
import lua.lib.luv.fs.Open;
import lua.Result;
@:luaRequire("luv")
extern class FileSystem {
@:native("fs_close")
@:overload(function(file:FileDescriptor, cb:String->Bool->Void):Request {})
static function close(file:FileDescriptor):Result<Bool>;
@:native("fs_open")
@:overload(function(path:String, flags:Open, mode:Int, ?cb:String->FileDescriptor->Void):Request {})
static function open(path:String, flags:Open, mode:Int):Result<FileDescriptor>;
@:native("fs_read")
@:overload(function(file:FileDescriptor, len:Int, offset:Int, ?cb:String->String->Void):Request {})
static function read(file:FileDescriptor, len:Int, offset:Int):Result<String>;
@:native("fs_unlink")
@:overload(function(file:FileDescriptor, ?cb:String->String->Void):Request {})
static function unlink(file:FileDescriptor, content:String):Result<String>;
@:native("fs_write")
@:overload(function(file:FileDescriptor, content:String, offset:Int, ?cb:String->Bool->Void):Int {})
static function write(file:FileDescriptor, content:String, offset:Int):Result<Bool>;
@:native("fs_mkdir")
@:overload(function(path:String, mode:Int, cb:String->Bool->Void):Request {})
static function mkdir(path:String, mode:Int):Result<Bool>;
@:native("fs_mkdtemp")
@:overload(function(data:String, cb:String->Bool->Void):Request {})
static function mkdtemp(data:String):Result<Bool>;
@:native("fs_rmdir")
@:overload(function(path:String, cb:String->Bool->Void):Request {})
static function rmdir(path:String):Result<Int>;
@:native("fs_scandir")
@:overload(function(path:String, cb:String->Bool->Void):Request {})
static function scandir(path:String):ScanDirMarker;
@:native("fs_scandir_next")
static function scandir_next(scandir:ScanDirMarker):ScandirNext;
@:native("fs_stat")
@:overload(function(path:String, cb:String->Stat->Void):Request {})
static function stat(path:String):Result<Stat>;
@:native("fs_fstat")
@:overload(function(descriptor:FileDescriptor, cb:String->Stat->Void):Request {})
static function fstat(descriptor:FileDescriptor):Result<Stat>;
@:native("fs_lstat")
@:overload(function(path:String, cb:String->Stat->Void):Request {})
static function lstat(path:String):Result<Stat>;
@:native("fs_rename")
@:overload(function(path:String, newpath:String, cb:String->Bool->Void):Request {})
static function rename(path:String, newpath:String):Result<Bool>;
@:native("fs_fsync")
@:overload(function(descriptor:FileDescriptor, cb:String->Bool->Void):Request {})
static function fsync(descriptor:FileDescriptor):Result<Bool>;
@:native("fs_fdatasync")
@:overload(function(descriptor:FileDescriptor, cb:String->Bool->Void):Request {})
static function fdatasync(descriptor:FileDescriptor):Result<Bool>;
@:native("fs_ftruncate")
@:overload(function(descriptor:FileDescriptor, offset:Int, cb:String->Bool->Void):Request {})
static function ftruncate(descriptor:FileDescriptor, offset:Int):Result<Bool>;
@:native("fs_sendfile")
@:overload(function(fin:FileDescriptor, fout:FileDescriptor, cb:String->Int->Void):Request {})
static function sendfile(fin:FileDescriptor, fout:FileDescriptor):Result<Int>;
@:native("fs_access")
@:overload(function(path:String, mode:Int, cb:String->Bool->Void):Request {})
static function access(path:String, mode:Int):Result<Bool>;
@:native("fs_chmod")
@:overload(function(path:String, mode:Int, cb:String->Bool->Void):Request {})
static function chmod(path:String, mode:Int):Result<Bool>;
@:native("fs_fchmod")
@:overload(function(descriptor:FileDescriptor, mode:Int, cb:String->Bool->Void):Request {})
static function fchmod(descriptor:FileDescriptor, mode:Int):Result<Bool>;
@:native("fs_futime")
@:overload(function(descriptor:FileDescriptor, actime:Int, modtime:Int, cb:String->Bool->Void):Request {})
static function futime(descriptor:FileDescriptor, actime:Int, modtime:Int):Result<Bool>;
@:native("fs_utime")
@:overload(function(path:String, actime:Int, modtime:Int, cb:String->Bool->Void):Request {})
static function utime(path:String, actime:Int, modtime:Int):Result<Bool>;
@:native("fs_link")
@:overload(function(oldpath:String, newpath:String, cb:String->Bool->Void):Request {})
static function link(oldpath:String, newpath:String):Result<Bool>;
@:native("fs_symlink")
@:overload(function(oldpath:String, newpath:String, flags:Int, cb:String->Bool->Void):Request {})
static function symlink(oldpath:String, newpath:String, flags:Int):Bool;
@:native("fs_readlink")
@:overload(function(path:String, cb:String->String->Void):Request {})
static function readlink(path:String):String;
@:native("fs_realpath")
@:overload(function(path:String, cb:String->String->Void):Request {})
static function realpath(path:String):String;
@:native("fs_chown")
@:overload(function(path:String, uid:Int, gid:Int, cb:String->Bool->Void):Request {})
static function chown(path:String, uid:Int, gid:Int):Bool;
@:native("fs_fchown")
@:overload(function(descriptor:FileDescriptor, uid:Int, gid:Int, cb:String->Bool->Void):Request {})
static function fchown(descriptor:FileDescriptor, uid:Int, gid:Int):Bool;
/**
Not available on windows
**/
@:native("fs_lchown")
@:overload(function(descriptor:FileDescriptor, uid:Int, gid:Int, cb:String->Bool->Void):Request {})
static function lchown(descriptor:FileDescriptor, uid:Int, gid:Int):Bool;
@:native("fs_statfs")
@:overload(function(path:String, cb:StatFs->Bool->Void):Request {})
static function statfs(path:String):StatFs;
@:native("fs_opendir")
@:overload(function(path:String, cb:Handle->Bool->Void):Request {})
static function opendir(path:String):Handle;
@:native("fs_readdir")
@:overload(function(dir:Handle, cb:Table<Int, NameType>->Bool->Void):Request {})
static function readdir(path:String):Table<Int, NameType>;
@:native("fs_closedir")
@:overload(function(dir:Handle, cb:Bool->Void):Request {})
static function closedir(dir:Handle):Bool;
}
extern class ScanDirMarker {}
@:multiReturn
extern class ScandirNext {
var name:String;
var type:String;
}
typedef NameType = {
name:String,
type:String
}
typedef Stat = {
ino:Int,
ctime:TimeStamp,
uid:Int,
dev:Int,
nlink:Int,
mode:Int,
size:Int,
birthtime:TimeStamp,
gid:Int,
type:String,
rdev:Int,
gen:Int,
blocks:Int,
mtime:TimeStamp,
atime:TimeStamp,
blksize:Int,
flags:Int
}
typedef TimeStamp = {
sec:Int,
nsec:Int
}
typedef StatFs = {
type:Int,
bsize:Int,
blocks:Int,
bfree:Int,
bavail:Int,
files:Int,
ffree:Int
}

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