Compare commits

...
102 Commits
Author SHA1 Message Date
FrakitsandGitHub 48ec0f4b01 Update haxelib.json 2025-08-15 13:42:15 +03:00
Ne_Eo 49c90e6434 Fix typo 2025-01-19 20:09:38 +01:00
Ne_Eo bb46d45d56 Import Redirects 2024-11-15 15:25:04 +01:00
Redar13andGitHub 3a5c4f2164 Fix ending in with #end in the file (#5)
* Update Parser.hx

* Update Parser.hx
2024-11-06 16:39:09 +01:00
Ne_Eo f18c7a2210 Small optimization 2024-08-02 23:50:16 +02:00
Ne_Eo 123a7de64a Fix Trigraph bug 2024-07-26 04:24:37 +02:00
Ne_Eo e0e1436930 Fix bug oops :3 2024-06-03 19:00:40 +02:00
b96e6c8149 Fix import extend class (#4)
* Fix import extend class

yea

* Update Interp.hx

* Fix issues with compiling

* Improved extend Errors

---------

Co-authored-by: NeeEoo <NeeEoo@users.noreply.github.com>
2024-04-23 00:01:43 +02:00
NeeEoo f6402ac638 Improve Auto Complete Performance 2024-04-13 18:32:13 +02:00
Ne_EoandGitHub 1e55d0200b Update README.md 2024-02-15 19:43:11 +01:00
NeeEoo 1725dfd1ea Merge branch 'master' into custom-classes 2024-02-15 19:35:31 +01:00
NeeEoo a8cc0ccc86 Restructuring + KeyValueItherators + is + fixes 2023-09-23 21:23:31 +02:00
LeerandGitHub 7dd868aac7 fix compilation errors and make setVar public (#1)
* fix 1

* fix 2

* make setVar public
2023-09-23 20:32:31 +02:00
NeeEoo 220e5ce007 Merge branch 'custom-classes' 2023-08-17 09:55:12 +02:00
NeeEoo 80f6ea4502 Oops 2023-08-17 09:54:56 +02:00
NeeEoo eb820aaf6a Improved ?. 2023-08-17 09:51:43 +02:00
NeeEoo a754c162d9 Fix private class bug 2023-08-13 19:29:08 +02:00
NeeEoo de18ceb887 Fixed Type not found error 2023-08-13 19:24:08 +02:00
NeeEoo 51188173bb Merge To Main 2023-08-13 11:59:13 +02:00
NeeEoo d0797ad5d8 Fixed bug with redirects 2023-08-07 13:54:19 +02:00
NeeEoo 9b37bd532e Oops forgot this 2023-07-06 11:59:12 +02:00
NeeEoo 333352edcf Fix bug + bypassAccessor on assign on scriptObject 2023-07-06 00:40:21 +02:00
NeeEoo 05783773af Added support for sub class imports 2023-06-15 14:36:28 +02:00
NeeEoo 59ee20ee7a WIP Super Class Support 2023-06-15 14:21:18 +02:00
NeeEoo 87f2c1b062 Added import as and switch or and def null 2023-06-15 11:08:08 +02:00
NeeEoo b85cefea56 Cleanup 2023-04-19 13:37:08 +02:00
Yoshman29 2e28f863f3 some fixes & stuff 2023-04-19 01:46:48 +02:00
NeeEoo ddaa4d1741 Added support for dots in preprocessors 2023-04-10 15:08:16 +02:00
NeeEoo 732bd1520a Improved Custom Classes (getting fields outside of the class) 2023-04-10 14:14:16 +02:00
NeeEoo 1d67946f3f Outside variables now in classes (no more import in class) 2023-04-10 03:36:50 +02:00
Yoshman29 fab6d7e662 Merge branch 'custom-classes' of https://github.com/YoshiCrafter29/hscript-improved into custom-classes 2023-04-10 02:56:20 +02:00
NeeEoo 6e20578a81 Improved static variables 2023-04-10 02:37:41 +02:00
NeeEoo dc5282c32e Added finals 2023-04-10 02:10:46 +02:00
lunarcleint 812abae6e5 ??= op 2023-04-09 16:51:04 -07:00
NeeEoo b3b512d027 Added support for ?. 2023-04-10 00:09:50 +02:00
NeeEoo ed296c4c7f Merge branch 'master' into custom-classes 2023-04-09 23:28:45 +02:00
lunarcleint 595bb47249 ?? and .? syntax (only ?? is functional) 2023-04-09 14:09:58 -07:00
NeeEoo daad1a4fa8 Added underscore support to numbers + binary 2023-04-08 00:08:49 +02:00
Yoshman29 daef1ac198 Merge branch 'custom-classes' of https://github.com/YoshiCrafter29/hscript-improved into custom-classes 2023-04-07 16:40:23 +02:00
Yoshman29 3b9d88b252 Update Interp.hx 2023-04-07 16:40:22 +02:00
NeeEoo 809f8229b4 Implemented Super 2023-04-02 18:22:02 +02:00
Yoshman29 ffb1ee2523 Update CustomClassHandler.hx 2023-04-02 03:39:21 +02:00
Yoshman29 0903718314 removed all unnecessary traces 2023-04-01 22:46:02 +02:00
Yoshman29 e0cb883ae4 Update ClassExtendMacro.hx 2023-04-01 18:31:39 +02:00
Yoshman29 17449dd9d5 oopsie 2023-04-01 17:15:01 +02:00
Yoshman29 7963631a1d Update ClassExtendMacro.hx 2023-04-01 15:30:46 +02:00
Yoshman29 77d88f4b34 Update ClassExtendMacro.hx 2023-04-01 15:12:36 +02:00
Yoshman29 c5e3ab1162 custom classes 2023-04-01 15:02:36 +02:00
Yoshman29 75041c1db9 possible working code????? huh??? 2023-04-01 14:38:13 +02:00
Yoshman29 558a4c0782 Tried some fuckery 2023-04-01 02:23:07 +02:00
NeeEoo 995c3b9c8e 2023-03-31 22:11:48 +02:00
Yoshman29 0a64bca9ce custom class progress 2023-03-31 21:41:34 +02:00
NeeEoo b7b12b6cbb WIP Classes 2023-03-31 20:16:30 +02:00
NeeEoo 5684ca8671 WIP Class Parsing 2023-03-31 18:12:50 +02:00
NeeEoo 3c81360dc2 Merge branch 'master' into custom-classes 2023-03-31 17:03:00 +02:00
NeeEoo fc50ebdf90 Small Fix 2023-03-31 00:12:54 +02:00
Yoshman29 4d6e8db5ff helpers 2023-03-30 17:34:50 +02:00
NeeEoo 938ffac57e Custom classes, 2/? finished the macro 2023-03-19 17:57:37 +01:00
NeeEoo 50aaffb101 Custom classes, 1/? started with macros 2023-03-19 05:30:06 +01:00
NeeEoo 4f9b449c6e Added inferred map types and bypassAccessor 2023-03-19 05:26:27 +01:00
Yoshman29 c1a36a3f4b improve deez nuts 2023-01-07 22:22:05 +01:00
Yoshman29 4ca6e2a680 Fixed weird erroring with an error handling 2022-12-26 22:17:08 +01:00
Yoshman29 11db805c34 improve deez nuts 2022-12-24 13:07:02 +01:00
Yoshman29 f1f700ab69 Update UsingHandler.hx 2022-12-22 21:17:47 +01:00
Yoshman29 9eeb8ddb80 that macro took me 3 hours 2022-12-22 21:09:11 +01:00
Yoshman29 95de26a6d0 fuck 2022-12-09 23:09:28 +01:00
Yoshman29 88c2e28dbc crap 2022-12-07 23:51:03 +01:00
Yoshman29 30b7a9e4d4 Update Checker.hx 2022-12-07 23:47:37 +01:00
Yoshman29 37542065d6 bug fix (now it works as intended) 2022-11-04 20:10:35 +01:00
Yoshman29 c9608f7760 Update Interp.hx 2022-11-04 19:54:57 +01:00
Yoshman29 6ba54b0e77 static and public 2022-11-04 19:33:04 +01:00
Yoshman29 f9bb3105c8 new interface 2022-11-02 14:36:36 +01:00
Yoshman29 4b5baa9b5f Revert "thing that needs to be reverted"
This reverts commit 6dedd87260.
2022-10-13 23:18:54 +02:00
Yoshman29 6dedd87260 thing that needs to be reverted 2022-10-13 23:18:47 +02:00
Yoshman29 91317222fb Update Interp.hx 2022-08-13 03:00:11 +02:00
Yoshman29 494953a8cc Added interp.importEnabled 2022-08-12 23:40:55 +02:00
Yoshman29 ae4d8be50c more error handling + variables fix 2022-08-10 17:21:15 +02:00
Yoshman29 d34790e05c fix 2022-07-19 02:44:22 +02:00
Yoshman29 b77e15c6d6 forgot to push smh 2022-07-11 11:32:45 +02:00
Yoshman29 54195d5811 hscript updates 2022-07-02 18:21:43 +02:00
Yoshman29 9c7907f91a fixes 2022-06-30 02:03:07 +02:00
Yoshman29 0601b8def6 natural import & static access from vars for YCE 2022-06-29 00:53:51 +02:00
YoshiCrafter29 841261f199 Added import support 2022-06-08 20:10:40 +02:00
Nicolas Cannasse 7124b6c4ce fix for latest haxe 2022-04-11 17:14:38 +02:00
Nicolas Cannasse ad7beec559 fix for async idents and local functions 2022-04-01 14:43:03 +02:00
Nicolas Cannasse bd4fc51392 renamed test script 2022-04-01 10:27:20 +02:00
Nicolas Cannasse 54d994a879 added asyncIdents support 2022-03-24 15:26:50 +01:00
Nicolas Cannasse 891a085f2b fixed declared vars leak when return (close #111) 2022-01-30 11:26:32 +01:00
Nicolas Cannasse e7ccd2e72d another {} unify fix 2021-05-14 18:22:16 +02:00
Nicolas Cannasse 459a39e65d fix unification with {} 2021-05-14 18:18:55 +02:00
Jens FischerandGitHub 36eb0fca8b Fix Std.is() deprecation warnings with Haxe 4.2 (#101) 2021-03-15 19:49:07 +01:00
Nicolas Cannasse 53b9e22f26 fix for haxe 4.2 2021-02-11 12:07:30 +01:00
Nicolas Cannasse 8ff3f5e351 fixed getFields (apply params, handle interfaces) and getField (handle interface inheritance) 2020-12-18 15:58:21 +01:00
Nicolas Cannasse e6a2c443cb added support for interfaces type checking 2020-12-04 17:08:41 +01:00
Nicolas Cannasse 4f25ab162d added inheritance on setGlobals 2020-08-26 15:51:27 +02:00
Nicolas Cannasse 0520d9f187 added setVar (allow to define globals set behavior) 2020-07-30 10:22:48 +02:00
Nicolas Cannasse cc3c21b7e3 fixed unop priority overriding binop one (close #94) 2020-07-14 12:49:24 +02:00
Nicolas Cannasse ae9560124e fixed () -> e short lambda parsing (close #93) 2020-05-07 10:24:04 +02:00
Nicolas Cannasse 085f4ec37e fixed comments parsing was broken by previous fix 2020-04-27 11:19:46 +02:00
Nicolas Cannasse 476c3a9cc9 fixed parser with concat binop/unop such as a<-b or a<++b (close #92) 2020-04-26 15:10:00 +02:00
Mark KnolandGitHub 1bc5ac8768 Update haxelib.json (#83) 2020-04-12 21:32:39 +02:00
Nicolas Cannasse 4bdff11b87 removed 2020-04-10 12:21:54 +02:00
23 changed files with 2844 additions and 1062 deletions
+2
View File
@@ -1,2 +1,4 @@
/hscript.swf
/release.zip
tests/bin/*
+14 -4
View File
@@ -1,8 +1,18 @@
hscript
hscript-improved
=======
[![TravisCI Build Status](https://travis-ci.org/HaxeFoundation/hscript.svg?branch=master)](https://travis-ci.org/HaxeFoundation/hscript)
[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/HaxeFoundation/hscript?branch=master&svg=true)](https://ci.appveyor.com/project/HaxeFoundation/hscript)
How to install
```
haxelib git hscript-improved https://github.com/FNF-CNE-Devs/hscript-improved.git
```
To enable custom classes support you have to do this in project.xml
```xml
<define name="CUSTOM_CLASSES" />
```
Warning: custom classes are sometimes broken, would like help to fix them. You can only override functions from the current class, not from the extended part, like you cant override update in FlxText because FlxText doesnt have a update function overriden
-----------
Parse and evalutate Haxe expressions.
@@ -100,4 +110,4 @@ Some other optional files :
- `hscript.Macro` : convert Haxe macro into hscript Expr
- `hscript.Printer` : convert hscript Expr to String
- `hscript.Tools` : utility functions (map/iter)
+5 -2
View File
@@ -7,7 +7,7 @@ import hscript.Printer;
import hscript.Checker;
import haxe.unit.*;
class Test extends TestCase {
class TestHScript extends TestCase {
function assertScript(x,v:Dynamic,?vars : Dynamic, allowTypes=false, ?pos:haxe.PosInfos) {
var p = new hscript.Parser();
p.allowTypes = allowTypes;
@@ -101,6 +101,7 @@ class Test extends TestCase {
assertScript("/**/0", 0);
assertScript("x=1;x*=-2", -2);
assertScript("var f = x -> x + 1; f(3)", 4);
assertScript("var f = () -> 55; f()", 55);
assertScript("var f = (x) -> x + 1; f(3)", 4);
assertScript("var f = (x:Int) -> x + 1; f(3)", 4);
assertScript("var f = (x,y) -> x + y; f(3,1)", 4);
@@ -110,6 +111,8 @@ class Test extends TestCase {
assertScript("var f:(x:Int, y:Int)->Int = (x:Int,y:Int) -> x + y; f(3,1)", 4, null, true);
assertScript("var f:(x:Int)->(y:Int, z:Int)->Int = (x:Int) -> (y:Int, z:Int) -> x + y + z; f(3)(1, 2)", 6, null, true);
assertScript("var f:(x:Int)->(Int, Int)->Int = (x:Int) -> (y:Int, z:Int) -> x + y + z; f(3)(1, 2)", 6, null, true);
assertScript("var a = 10; var b = 5; a - -b", 15);
assertScript("var a = 10; var b = 5; a - b / 2", 7.5);
}
function testMap():Void {
@@ -170,7 +173,7 @@ class Test extends TestCase {
#end
var runner = new TestRunner();
runner.add(new Test());
runner.add(new TestHScript());
var succeed = runner.run();
#if sys
+1 -1
View File
@@ -1,3 +1,3 @@
-main Test
-main TestHScript
-dce no
-lib hx3compat
+3 -1
View File
@@ -1 +1,3 @@
--macro keep('IntIterator')
--macro keep('IntIterator')
--macro hscript.macros.UsingHandler.init()
--macro hscript.macros.ClassExtendMacro.init()
+9 -9
View File
@@ -1,9 +1,9 @@
{
"name": "hscript",
"url": "https://github.com/HaxeFoundation/hscript",
"license": "MIT",
"description": "Haxe Script is a scripting engine for a subset of the Haxe language",
"version": "2.4.0",
"releasenote": "Haxe 4.0 final + type checking/completion (hscript.Checker)",
"contributors": ["ncannasse"]
}
{
"name": "hscript-improved",
"url": "https://github.com/HaxeFoundation/hscript",
"license": "MIT",
"description": "Haxe Script is a scripting engine for a subset of the Haxe language",
"version": "2.4.0",
"releasenote": "Haxe 4.0 final + type checking/completion (hscript.Checker)",
"contributors": ["ncannasse","HaxeFoundation"]
}
-65
View File
@@ -1,65 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<project version="2">
<!-- Output SWF options -->
<output>
<movie outputType="Application" />
<movie input="" />
<movie path="hscript.swf" />
<movie fps="30" />
<movie width="800" />
<movie height="600" />
<movie version="9" />
<movie minorVersion="0" />
<movie platform="Flash Player" />
<movie background="#FFFFFF" />
</output>
<!-- Other classes to be compiled into your SWF -->
<classpaths>
<!-- example: <class path="..." /> -->
</classpaths>
<!-- Build options -->
<build>
<option directives="" />
<option flashStrict="True" />
<option noInlineOnDebug="False" />
<option mainClass="Test" />
<option enabledebug="False" />
<option additional="-dce no" />
</build>
<!-- haxelib libraries -->
<haxelib>
<!-- example: <library name="..." /> -->
</haxelib>
<!-- Class files to compile (other referenced classes will automatically be included) -->
<compileTargets>
<!-- example: <compile path="..." /> -->
</compileTargets>
<!-- Assets to embed into the output SWF -->
<library>
<!-- example: <asset path="..." id="..." update="..." glyphs="..." mode="..." place="..." sharepoint="..." /> -->
</library>
<!-- Paths to exclude from the Project Explorer tree -->
<hiddenPaths>
<hidden path="haxelib.xml" />
<hidden path="hscript.hxml" />
<hidden path="hscript.js" />
<hidden path="hscript.n" />
<hidden path="hscript.swf" />
<hidden path="hscript9.swf" />
<hidden path="release.bat" />
<hidden path="release.zip" />
<hidden path="obj" />
</hiddenPaths>
<!-- Executed before build -->
<preBuildCommand />
<!-- Executed after build -->
<postBuildCommand alwaysRun="False" />
<!-- Other project options -->
<options>
<option showHiddenPaths="False" />
<option testMovie="Default" />
<option testMovieCommand="" />
</options>
<!-- Plugin storage -->
<storage />
</project>
+8 -1
View File
@@ -36,6 +36,7 @@ class Async {
var currentLoop : Expr;
var currentBreak : Expr -> Expr;
var uid = 0;
public var asyncIdents : Map<String,Bool>;
static var nullExpr : Expr = #if hscriptPos { e : null, pmin : 0, pmax : 0, origin : "<null>", line : 0 } #else null #end;
static var nullId = mk(EIdent("null"), nullExpr);
@@ -207,11 +208,17 @@ class Async {
return syncFlag;
}
inline function isAsyncIdent( id : String ) {
return asyncIdents == null || asyncIdents.exists(id);
}
function checkSync( e : Expr ) {
if( !syncFlag )
return;
switch( expr(e) ) {
case ECall(_):
case ECall(expr(_) => EIdent(i),_) if( isAsyncIdent(i) || vars.get(i) == Defined ):
syncFlag = false;
case ECall(expr(_) => EField(_,i),_) if( isAsyncIdent(i) ):
syncFlag = false;
case EFunction(_,_,name,_) if( name != null ):
syncFlag = false;
+4
View File
@@ -140,6 +140,10 @@ class Bytes {
#end
bout.addByte(Type.enumIndex(e));
switch( e ) {
case EImport(c):
// TODO
case EClass(_, _, _, _):
// TODO
case EConst(c):
doEncodeConst(c);
case EIdent(v):
+76 -18
View File
@@ -48,6 +48,8 @@ typedef CNamedType = {
typedef CClass = {> CNamedType,
@:optional var superClass : TType;
@:optional var constructor : CField;
@:optional var interfaces : Array<TType>;
@:optional var isInterface : Bool;
var fields : Map<String,CField>;
var statics : Map<String,CField>;
}
@@ -121,12 +123,19 @@ class CheckerTypes {
fields : new Map(),
statics : new Map(),
};
if( c.isInterface )
cl.isInterface = true;
for( p in c.params )
cl.params.push(TParam(p));
todo.push(function() {
localParams = [for( t in cl.params ) c.path+"."+Checker.typeStr(t) => t];
if( c.superClass != null )
cl.superClass = getType(c.superClass.path, [for( t in c.superClass.params ) makeXmlType(t)]);
if( c.interfaces != null ) {
cl.interfaces = [];
for( i in c.interfaces )
cl.interfaces.push(getType(i.path, [for( t in i.params ) makeXmlType(t)]));
}
var pkeys = [];
for( f in c.fields ) {
if( f.isOverride || f.name.substr(0,4) == "get_" || f.name.substr(0,4) == "set_" ) continue;
@@ -295,9 +304,17 @@ class Checker {
}
public function setGlobals( cl : CClass ) {
for( f in cl.fields )
if( f.isPublic )
setGlobal(f.name, f.params.length == 0 ? f.t : TLazy(function() return apply(f.t,f.params,[for( i in 0...f.params.length) makeMono()])));
while( true ) {
for( f in cl.fields )
if( f.isPublic )
setGlobal(f.name, f.params.length == 0 ? f.t : TLazy(function() return apply(f.t,f.params,[for( i in 0...f.params.length) makeMono()])));
if( cl.superClass == null )
break;
cl = switch( cl.superClass ) {
case TInst(c,_): c;
default: throw "assert";
}
}
}
public function removeGlobal( name : String ) {
@@ -580,6 +597,8 @@ class Checker {
case [TDynamic, _]:
return true;
case [TAnon(a1),TAnon(a2)]:
if( a2.length == 0 ) // always unify with {}
return true;
var m = new Map();
for( f in a1 )
m.set(f.name, f);
@@ -595,6 +614,18 @@ class Checker {
return true;
case [TInst(cl1,pl1), TInst(cl2,pl2)]:
while( cl1 != cl2 ) {
if( cl1.interfaces != null ) {
for( i in cl1.interfaces ) {
switch( i ) {
case TInst(cli, args):
var i = TInst(cli, [for( a in args ) apply(a, cl1.params, pl1)]);
if( tryUnify(i, t2) )
return true;
default:
throw "assert";
}
}
}
switch( cl1.superClass ) {
case null: return false;
case TInst(c, args):
@@ -693,23 +724,42 @@ class Checker {
}
}
public function getFields( t : TType ) {
public function getFields( t : TType ) : Array<{ name : String, t : TType }> {
var fields = [];
while( t != null ) {
t = follow(t);
switch( t ) {
case TInst(c, args):
switch( follow(t) ) {
case TInst(c, args):
var map = (t) -> apply(t,c.params,args);
while( c != null ) {
for( fname in c.fields.keys() ) {
var f = c.fields.get(fname);
fields.push({ name : f.name, t : f.t });
if( !f.isPublic || !f.complete ) continue;
var name = f.name, t = map(f.t);
if( allowAsync && StringTools.startsWith(name,"a_") ) {
t = unasync(t);
name = name.substr(2);
}
fields.push({ name : name, t : t });
}
if( c.isInterface && c.interfaces != null ) {
for( i in c.interfaces ) {
for( f in getFields(i) )
fields.push({ name : f.name, t : map(f.t) });
}
}
if( c.superClass == null ) break;
switch( c.superClass ) {
case TInst(csup,args):
var curMap = map;
map = (t) -> curMap(apply(t,csup.params,args));
c = csup;
default:
break;
}
t = c.superClass;
case TAnon(fl):
for( f in fl )
fields.push({ name : f.name, t : f.t });
break;
default:
}
case TAnon(fl):
for( f in fl )
fields.push({ name : f.name, t : f.t });
default:
}
return fields;
}
@@ -726,6 +776,13 @@ class Checker {
if( cf.t == null ) cf = null;
}
}
if( cf == null && c.isInterface && c.interfaces != null ) {
for( i in c.interfaces ) {
var ft = getField(i, f, e, forWrite);
if( ft != null )
return apply(ft, c.params, args);
}
}
if( cf == null ) {
if( c.superClass == null ) return null;
var ft = getField(c.superClass, f, e, forWrite);
@@ -917,7 +974,7 @@ class Checker {
return TVoid;
case EObject(fl):
switch( withType ) {
case WithType(follow(_) => TAnon(tfields)):
case WithType(follow(_) => TAnon(tfields)) if( tfields.length > 0 ):
var map = [for( f in tfields ) f.name => f];
return TAnon([for( f in fl ) {
var ft = map.get(f.name);
@@ -930,7 +987,7 @@ class Checker {
default:
return TAnon([for( f in fl ) { t : typeExpr(f.e, Value), opt : false, name : f.name }]);
}
case EBreak, EContinue:
case EBreak, EContinue, EImport(_):
return TVoid;
case EReturn(v):
var et = v == null ? TVoid : typeExpr(v, allowReturn == null ? Value : WithType(allowReturn));
@@ -1176,9 +1233,10 @@ class Checker {
mergeType( typeExpr(defaultExpr, withType), defaultExpr);
return withType == NoValue ? TVoid : tmin == null ? makeMono() : tmin;
case ENew(cl, params):
default:
}
error("Don't know how to type "+edef(expr).getName(), expr);
return TDynamic;
}
}
}
+24
View File
@@ -0,0 +1,24 @@
package hscript;
class Config {
// Runs support for custom classes in these
public static final ALLOWED_CUSTOM_CLASSES = [
"flixel",
];
// Runs support for abstract support in these
public static final ALLOWED_ABSTRACT_AND_ENUM = [
"flixel",
"openfl.display.BlendMode",
];
// Incase any of your files fail
// These are the module names
public static final DISALLOW_CUSTOM_CLASSES = [
];
public static final DISALLOW_ABSTRACT_AND_ENUM = [
];
}
+104
View File
@@ -0,0 +1,104 @@
package hscript;
using StringTools;
class CustomClassHandler implements IHScriptCustomConstructor {
public static var staticHandler = new StaticHandler();
public var ogInterp:Interp;
public var name:String;
public var fields:Array<Expr>;
public var extend:String;
public var interfaces:Array<String>;
public function new(ogInterp:Interp, name:String, fields:Array<Expr>, ?extend:String, ?interfaces:Array<String>) {
this.ogInterp = ogInterp;
this.name = name;
this.fields = fields;
this.extend = extend;
this.interfaces = interfaces;
}
public function hnew(args:Array<Dynamic>):Dynamic {
var interp = new Interp();
interp.errorHandler = ogInterp.errorHandler;
var cl = extend == null ? TemplateClass : Type.resolveClass('${extend}_HSX');
if(cl == null)
ogInterp.error(EInvalidClass(extend));
var _class = Type.createInstance(cl, args);
var __capturedLocals = ogInterp.duplicate(ogInterp.locals);
var capturedLocals:Map<String, {r:Dynamic, depth:Int}> = [];
for(k=>e in __capturedLocals)
if (e != null && e.depth <= 0)
capturedLocals.set(k, e);
var disallowCopy = Type.getInstanceFields(cl);
for (key => value in capturedLocals) {
if(!disallowCopy.contains(key)) {
interp.locals.set(key, {r: value, depth: -1});
}
}
for (key => value in ogInterp.variables) {
if(!disallowCopy.contains(key)) {
interp.variables.set(key, value);
}
}
for(expr in fields) {
@:privateAccess
interp.exprReturn(expr);
}
interp.variables.set("super", staticHandler);
_class.__interp = interp;
interp.scriptObject = _class;
var newFunc = interp.variables.get("new");
if(newFunc != null) {
Reflect.callMethod(null, newFunc, args);
}
for(variable => value in interp.variables) {
if(variable == "this") continue;
}
return _class;
}
public function toString():String {
return name;
}
}
class TemplateClass implements IHScriptCustomBehaviour {
public var __interp:Interp;
public function hset(name:String, val:Dynamic):Dynamic {
if(this.__interp.variables.exists("set_" + name)) {
return this.__interp.variables.get("set_" + name)(val); // TODO: Prevent recursion from setting it in the function
}
if (this.__interp.variables.exists(name)) {
this.__interp.variables.set(name, val);
return val;
}
Reflect.setProperty(this, name, val);
return Reflect.field(this, name);
}
public function hget(name:String):Dynamic {
if(this.__interp.variables.exists("get_" + name))
return this.__interp.variables.get("get_" + name)();
if (this.__interp.variables.exists(name))
return this.__interp.variables.get(name);
return Reflect.getProperty(this, name);
}
}
class StaticHandler {
public function new() {}
}
+11 -6
View File
@@ -45,31 +45,34 @@ enum Expr {
#end
EConst( c : Const );
EIdent( v : String );
EVar( n : String, ?t : CType, ?e : Expr );
EVar( n : String, ?t : CType, ?e : Expr, ?isPublic : Bool, ?isStatic : Bool );
EParent( e : Expr );
EBlock( e : Array<Expr> );
EField( e : Expr, f : String );
EField( e : Expr, f : String , ?safe : Bool );
EBinop( op : String, e1 : Expr, e2 : Expr );
EUnop( op : String, prefix : Bool, e : Expr );
ECall( e : Expr, params : Array<Expr> );
EIf( cond : Expr, e1 : Expr, ?e2 : Expr );
EWhile( cond : Expr, e : Expr );
EFor( v : String, it : Expr, e : Expr );
EFor( v : String, it : Expr, e : Expr, ?ithv: String);
EBreak;
EContinue;
EFunction( args : Array<Argument>, e : Expr, ?name : String, ?ret : CType );
EFunction( args : Array<Argument>, e : Expr, ?name : String, ?ret : CType, ?isPublic : Bool, ?isStatic : Bool, ?isOverride : Bool );
EReturn( ?e : Expr );
EArray( e : Expr, index : Expr );
EArrayDecl( e : Array<Expr> );
EArrayDecl( e : Array<Expr>, ?wantedType: CType );
ENew( cl : String, params : Array<Expr> );
EThrow( e : Expr );
ETry( e : Expr, v : String, t : Null<CType>, ecatch : Expr );
EObject( fl : Array<{ name : String, e : Expr }> );
ETernary( cond : Expr, e1 : Expr, e2 : Expr );
ESwitch( e : Expr, cases : Array<{ values : Array<Expr>, expr : Expr }>, ?defaultExpr : Expr);
ESwitch( e : Expr, cases : Array<{ values : Array<Expr>, expr : Expr }>, ?defaultExpr : Expr );
EDoWhile( cond : Expr, e : Expr);
EMeta( name : String, args : Array<Expr>, e : Expr );
ECheckType( e : Expr, t : CType );
EImport( c : String, ?asname:String );
EClass( name:String, fields:Array<Expr>, ?extend:String, interfaces:Array<String> );
}
typedef Argument = { name : String, ?t : CType, ?opt : Bool, ?value : Expr };
@@ -117,6 +120,8 @@ enum Error {
EInvalidOp( op : String );
EInvalidAccess( f : String );
ECustom( msg : String );
EInvalidClass( className : String);
EAlreadyExistingClass( className : String);
}
+6
View File
@@ -0,0 +1,6 @@
package hscript;
interface IHScriptCustomBehaviour {
public function hset(name:String, val:Dynamic):Dynamic;
public function hget(name:String):Dynamic;
}
+5
View File
@@ -0,0 +1,5 @@
package hscript;
interface IHScriptCustomConstructor {
public function hnew(args:Array<Dynamic>):Dynamic;
}
+854 -463
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -79,6 +79,8 @@ class Macro {
#if (haxe_ver >= 4)
case OpIn: "in";
#end
default:
continue;
};
binops.set(str, op);
if( assign )
@@ -92,6 +94,9 @@ class Macro {
case OpNegBits: "~";
case OpIncrement: "++";
case OpDecrement: "--";
#if (haxe_ver >= 4.2)
case OpSpread: continue;
#end
}
unops.set(str, op);
}
@@ -247,6 +252,8 @@ class Macro {
EMeta({ name : m, params : params == null ? [] : [for( p in params ) convert(p)], pos : mpos }, convert(esub));
case ECheckType(e, t):
ECheckType(convert(e), convertType(t));
default:
null;
}, pos : #if hscriptPos { file : p.file, min : e.pmin, max : e.pmax } #else p #end }
}
+868 -484
View File
File diff suppressed because it is too large Load Diff
+32 -8
View File
@@ -114,6 +114,25 @@ class Printer {
return;
}
switch( #if hscriptPos e.e #else e #end ) {
case EImport(c, n):
add("import " + c);
if(n != null)
add(' as $n');
case EClass(name, fields, extend, interfaces):
add('class $name');
if (extend != null)
add(' extends $extend');
for(_interface in interfaces) {
add(' implements $_interface');
}
add(' {\n');
tabs += "\t";
//for(field in fields) {
// expr(field);
//}
tabs = tabs.substr(1);
add("}");
case EConst(c):
switch( c ) {
case CInt(i): add(i);
@@ -122,7 +141,7 @@ class Printer {
}
case EIdent(v):
add(v);
case EVar(n, t, e):
case EVar(n, t, e): // TODO: static, public, override
add("var " + n);
addType(t);
if( e != null ) {
@@ -145,9 +164,9 @@ class Printer {
tabs = tabs.substr(1);
add("}");
}
case EField(e, f):
case EField(e, f, s):
expr(e);
add("." + f);
add((s == true ? "?." : ".") + f);
case EBinop(op, e1, e2):
expr(e1);
add(" " + op + " ");
@@ -198,8 +217,11 @@ class Printer {
add(" while ( ");
expr(cond);
add(" )");
case EFor(v, it, e):
add("for( "+v+" in ");
case EFor(v, it, e, ithv):
if(ithv != null)
add("for( "+ithv+" => "+v+" in ");
else
add("for( "+v+" in ");
expr(it);
add(" ) ");
expr(e);
@@ -207,7 +229,7 @@ class Printer {
add("break");
case EContinue:
add("continue");
case EFunction(params, e, name, ret):
case EFunction(params, e, name, ret): // TODO: static, public, override
add("function");
if( name != null )
add(" " + name);
@@ -234,7 +256,7 @@ class Printer {
add("[");
expr(index);
add("]");
case EArrayDecl(el):
case EArrayDecl(el, _):
add("[");
var first = true;
for( e in el ) {
@@ -331,7 +353,7 @@ class Printer {
public static function errorToString( e : Expr.Error ) {
var message = switch( #if hscriptPos e.e #else e #end ) {
case EInvalidChar(c): "Invalid character: '"+(StringTools.isEof(c) ? "EOF" : String.fromCharCode(c))+"' ("+c+")";
case EInvalidChar(c): "Invalid character: '"+(StringTools.isEof(c) ? "EOF (End Of File)" : String.fromCharCode(c))+"' ("+c+")";
case EUnexpected(s): "Unexpected token: \""+s+"\"";
case EUnterminatedString: "Unterminated string";
case EUnterminatedComment: "Unterminated comment";
@@ -341,6 +363,8 @@ class Printer {
case EInvalidOp(op): "Invalid operator: "+op;
case EInvalidAccess(f): "Invalid access to field " + f;
case ECustom(msg): msg;
case EInvalidClass(cla): "Invalid class: " + cla + " was not found.";
case EAlreadyExistingClass(cla): 'Custom Class named $cla already exists.';
};
#if hscriptPos
return e.origin + ":" + e.line + ": " + message;
+5
View File
@@ -27,6 +27,8 @@ class Tools {
public static function iter( e : Expr, f : Expr -> Void ) {
switch( expr(e) ) {
case EConst(_), EIdent(_):
case EImport(c): f(e);
case EClass(_, e, _, _): for( a in e ) f(a);
case EVar(_, _, e): if( e != null ) f(e);
case EParent(e): f(e);
case EBlock(el): for( e in el ) f(e);
@@ -57,6 +59,7 @@ class Tools {
if( def != null ) f(def);
case EMeta(name, args, e): if( args != null ) for( a in args ) f(a); f(e);
case ECheckType(e,_): f(e);
}
}
@@ -86,6 +89,8 @@ class Tools {
case ESwitch(e, cases, def): ESwitch(f(e), [for( c in cases ) { values : [for( v in c.values ) f(v)], expr : f(c.expr) } ], def == null ? null : f(def));
case EMeta(name, args, e): EMeta(name, args == null ? null : [for( a in args ) f(a)], f(e));
case ECheckType(e,t): ECheckType(f(e), t);
case EImport(c): EImport(c);
case EClass(name, el, extend, interfaces): EClass(name, [for( e in el ) f(e)], extend, interfaces);
}
return mk(edef, e);
}
+437
View File
@@ -0,0 +1,437 @@
package hscript.macros;
#if macro
import haxe.macro.Type.ClassType;
import Type.ValueType;
import haxe.macro.Expr.Function;
import haxe.macro.Expr;
import haxe.macro.Type.MetaAccess;
import haxe.macro.Type.FieldKind;
import haxe.macro.Type.ClassField;
import haxe.macro.Type.VarAccess;
import haxe.macro.*;
import Sys;
using StringTools;
class ClassExtendMacro {
public static inline final FUNC_PREFIX = "_HX_SUPER__";
public static inline final CLASS_SUFFIX = "_HSX";
public static var unallowedMetas:Array<String> = [":bitmap", ":noCustomClass", ":generic"];
public static var modifiedClasses:Array<String> = [];
public static function init() {
#if !display
#if CUSTOM_CLASSES
if(Context.defined("display")) return;
for(apply in Config.ALLOWED_CUSTOM_CLASSES) {
Compiler.addGlobalMetadata(apply, "@:build(hscript.macros.ClassExtendMacro.build())");
}
#end
#end
}
public static function build():Array<Field> {
var fields = Context.getBuildFields();
var clRef = Context.getLocalClass();
if (clRef == null) return fields;
var cl = clRef.get();
if (cl.isAbstract || cl.isExtern || cl.isFinal || cl.isInterface) return fields;
if (!cl.name.endsWith("_Impl_") && !cl.name.endsWith(CLASS_SUFFIX) && !cl.name.endsWith("_HSC")) {
var metas = cl.meta.get();
for(m in metas)
if (unallowedMetas.contains(m.name))
return fields;
if(cl.params.length > 0)
return fields;
var key = cl.module;
var fkey = cl.module + "." + cl.name;
if(key == "sys.thread.FixedThreadPool") return fields; // Error: Type name sys.thread.Worker_HSX is redefined from module sys.thread.FixedThreadPool
if(key == "StdTypes") return fields; // Error: Cant extend basic class
if(key == "Xml") return fields; // Error: Cant extend basic class
if(key == "Date") return fields; // Error: Cant extend basic class
if(key == "away3d.tools.commands.Mirror") return fields; // Error: Unknown identifier
if(key == "away3d.tools.commands.SphereMaker") return fields; // Error: Unknown identifier
if(key == "away3d.tools.commands.Weld") return fields; // Error: Unknown identifier
if(fkey == "hscript.CustomClassHandler.TemplateClass") return fields; // Error: Redefined
if(key == "sys.thread.EventLoop") return fields; // Error: cant override force inlined
if(Config.DISALLOW_CUSTOM_CLASSES.contains(cl.module) || Config.DISALLOW_CUSTOM_CLASSES.contains(fkey)) return fields;
if(cl.module.contains("_")) return fields; // Weird issue, sorry
var superFields = [];
if(cl.superClass != null) {
var _superFields = cl.superClass.t.get().fields.get();
_superFields = []; // Comment to enable super support, (broken)
for(field in _superFields) {
if(!field.kind.match(FMethod(_))) // only catch methods
continue;
try {
var nfield = @:privateAccess TypeTools.toField(field);
switch ([field.kind, field.type]) {
case [FMethod(kind), TFun(args, ret)]:
if(kind == MethInline)
nfield.access.push(AInline);
if(kind == MethDynamic)
nfield.access.push(ADynamic);
default:
}
switch(nfield.kind) {
case FFun(fun):
if (fun.params != null && fun.params.length > 0)
continue;
fun.ret = Utils.fixStdTypes(fun.ret);
var metas = nfield.meta;
var defaultValues:Map<String, Dynamic> = [];
var defaultEntry = null;
var isGeneric = false;
for(m in metas) {
if(m.name == ":value") {
defaultEntry = m;
switch(m.params[0].expr) {
case EObjectDecl(fields):
for(fil in fields)
defaultValues[fil.field] = fil.expr;
default:
}
}
if(m.name == ":generic")
isGeneric = true;
}
if(isGeneric) continue;
if(defaultEntry != null)
metas.remove(defaultEntry);
for(arg in fun.args) {
var opt = false;
if(defaultValues.exists(arg.name)) {
arg.value = defaultValues[arg.name];
arg.opt = false;
}
arg.type = Utils.fixStdTypes(arg.type);
if(arg.opt) {
if(arg.type.getParameters()[0].name != "Null")
arg.type = TPath({name: "Null", params: [TPType(arg.type)], pack: []});//macro {Null<Dynamic>};
}
}
default:
}
superFields.push(nfield);
} catch(e) {
}
}
//superFields = [];
}
var shadowClass = macro class {
};
var definedFields:Array<String> = [];
//trace(getModuleName(cl));
var hasNew = false;
for(_field in [fields.copy(), superFields.copy()])
for(f in _field) {
if (f == null)
continue;
if (f.name == "new") {
hasNew = true;
continue;
}
if (f.name.startsWith(FUNC_PREFIX))
continue;
if (f.access.contains(ADynamic) || f.access.contains(AStatic) || f.access.contains(AExtern) || f.access.contains(AInline))
continue;
if(f.name == "hget" || f.name == "hset") continue; // sorry, no overwriting the hget and hset in custom classes, yet
if(definedFields.contains(f.name)) continue; // no duplicate fields
for(m in f.meta)
if (unallowedMetas.contains(m.name))
continue;
switch(f.kind) {
case FFun(fun):
if (fun == null)
continue;
if (fun.params != null && fun.params.length > 0) // TODO: Support for this maybe?
continue;
if(fun.params == null)
fun.params = [];
var overrideExpr:Expr;
var returns:Bool = !fun.ret.match(TPath({name: "Void"}));
var name = f.name;
var arguments = fun.args == null ? [] : [for(a in fun.args) macro $i{a.name}];
if (returns) {
overrideExpr = macro {
var name:String = $v{name};
if (__interp != null) {
var v:Dynamic = null;
if (__interp.variables.exists(name) && Reflect.isFunction(v = __interp.variables.get(name))) {
return v($a{arguments});
}
}
return super.$name($a{arguments});
};
} else {
overrideExpr = macro {
var name:String = $v{name};
if (__interp != null) {
var v:Dynamic = null;
if (__interp != null && __interp.variables.exists(name) && Reflect.isFunction(v = __interp.variables.get(name))) {
v($a{arguments});
return;
}
}
super.$name($a{arguments});
};
}
var superFuncExpr:Expr = returns ? {
macro return super.$name($a{arguments});
} : {
macro super.$name($a{arguments});
};
var func:Function = {
ret: fun.ret,
params: fun.params.copy(),
expr: overrideExpr,
args: fun.args.copy()
};
var overrideField:Field = {
name: f.name,
access: f.access.copy(),
kind: FFun(func),
pos: Context.currentPos(),
doc: f.doc,
meta: f.meta.copy()
};
if (!overrideField.access.contains(AOverride))
overrideField.access.push(AOverride);
var superField:Field = {
name: '$FUNC_PREFIX${f.name}',
pos: Context.currentPos(),
kind: FFun({
ret: fun.ret,
params: fun.params.copy(),
expr: superFuncExpr,
args: fun.args.copy()
}),
access: f.access.copy()
};
if (superField.access.contains(AOverride))
superField.access.remove(AOverride);
shadowClass.fields.push(overrideField);
shadowClass.fields.push(superField);
definedFields.push(f.name);
default:
// fuck off >:(
}
}
var totalFields = definedFields.length;
if(totalFields == 0 && !hasNew) {
//Sys.println(cl.pack.join(".") + "." + cl.name + ", " + totalFields);
return fields;
}
shadowClass.kind = TDClass({
pack: cl.pack.copy(),
name: cl.name
}, [
{name: "IHScriptCustomBehaviour", pack: ["hscript"]}
], false, true, false);
shadowClass.name = '${cl.name}$CLASS_SUFFIX';
var imports = Context.getLocalImports().copy();
Utils.setupMetas(shadowClass, imports);
// Adding hscript getters and setters
shadowClass.fields.push({
name: "__interp",
pos: Context.currentPos(),
kind: FVar(TPath({
pack: ['hscript'],
name: 'Interp'
}))
});
// Todo: make it possible to override
if(cl.name == "FunkinShader" || cl.name == "CustomShader" || cl.name == "MultiThreadedScript") {
Context.defineModule(cl.module, [shadowClass], imports);
return fields;
}
var hasHgetInSuper = false;
var hasHsetInSuper = false;
if(cl.name == "CustomShader") {
hasHgetInSuper = hasHsetInSuper = true;
}
// TODO: somehow check the super super class
for(_field in [fields.copy(), superFields.copy()])
for(f in _field) {
if (f.name == "new")
continue;
if (f.name.startsWith(FUNC_PREFIX))
continue;
if (f.access.contains(ADynamic) || f.access.contains(AStatic) || f.access.contains(AExtern))
continue;
switch(f.kind) {
case FFun(fun):
if (fun.params != null && fun.params.length > 0)
continue;
if(!hasHgetInSuper)
hasHgetInSuper = f.name == "hget";
if(!hasHsetInSuper)
hasHsetInSuper = f.name == "hset";
if(hasHgetInSuper && hasHsetInSuper)
break;
default:
}
}
var hgetField = if(hasHgetInSuper) {
macro {
if(this.__interp.variables.exists("get_" + name))
return this.__interp.variables.get("get_" + name)();
if (this.__interp.variables.exists(name))
return this.__interp.variables.get(name);
return super.hget(name);
}
} else {
macro {
if(this.__interp.variables.exists("get_" + name))
return this.__interp.variables.get("get_" + name)();
if (this.__interp.variables.exists(name))
return this.__interp.variables.get(name);
return Reflect.getProperty(this, name);
}
}
var hsetField = if(hasHsetInSuper) {
macro {
if(this.__interp.variables.exists("set_" + name)) {
return this.__interp.variables.get("set_" + name)(val); // TODO: Prevent recursion from setting it in the function
}
if (this.__interp.variables.exists(name)) {
this.__interp.variables.set(name, val);
return val;
}
return super.hset(name, val);
}
} else {
macro {
if(this.__interp.variables.exists("set_" + name)) {
return this.__interp.variables.get("set_" + name)(val); // TODO: Prevent recursion from setting it in the function
}
if (this.__interp.variables.exists(name)) {
this.__interp.variables.set(name, val);
return val;
}
Reflect.setProperty(this, name, val);
return Reflect.field(this, name);
}
}
//if(hasHsetInSuper || hasHgetInSuper) return fields;
//trace(cl.name);
shadowClass.fields.push({
name: "hset",
pos: Context.currentPos(),
access: hasHsetInSuper ? [AOverride, APublic] : [APublic],
kind: FFun({
ret: TPath({name: 'Dynamic', pack: []}),
params: [],
expr: hsetField,
args: [
{
name: "name",
opt: false,
meta: [],
type: TPath({name: "String", pack: []})
},
{
name: "val",
opt: false,
meta: [],
type: TPath({name: "Dynamic", pack: []})
}
]
})
});
shadowClass.fields.push({
name: "hget",
pos: Context.currentPos(),
access: hasHgetInSuper ? [AOverride, APublic] : [APublic],
kind: FFun({
ret: TPath({name: 'Dynamic', pack: []}),
params: [],
expr: hgetField,
args: [
{
name: "name",
opt: false,
meta: [],
type: TPath({name: "String", pack: []})
}
]
})
});
/*var p = new Printer();
var aa = p.printTypeDefinition(shadowClass);
if(aa.length < 5024)
trace(aa);
if(aa.indexOf("pack") >= 0)
if(cl.name == "FunkinShader")*/
Context.defineModule(cl.module, [shadowClass], imports);
}
return fields;
}
}
#else
class ClassExtendMacro {
public var usedClass:Class<Dynamic>;
public var className:String;
}
#end
+160
View File
@@ -0,0 +1,160 @@
package hscript.macros;
#if macro
import Type.ValueType;
import haxe.macro.ComplexTypeTools;
import haxe.macro.Expr;
import haxe.macro.Context;
import haxe.macro.Printer;
import haxe.macro.Compiler;
using StringTools;
class UsingHandler {
public static function init() {
#if !display
if(Context.defined("display")) return;
for(apply in Config.ALLOWED_ABSTRACT_AND_ENUM) {
Compiler.addGlobalMetadata(apply, '@:build(hscript.macros.UsingHandler.build())');
}
#end
}
public static function build():Array<Field> {
var fields = Context.getBuildFields();
var clRef = Context.getLocalClass();
if (clRef == null) return fields;
var cl = clRef.get();
if (/* cl.name.startsWith("Flx") && */ cl.name.endsWith("_Impl_") && cl.params.length <= 0 && !cl.meta.has(":multiType") && !cl.name.contains("_HSC")) {
var metas = cl.meta.get();
var trimEnum = cl.name.substr(0, cl.name.length - 6);
var key = cl.module;
var fkey = cl.module + "." + trimEnum;
if(key == "lime.system.Locale") return fields; // Error: Unknown identifier : currentLocale, Due to Func
if(key == "cpp.Function") return fields; // Error: Unknown identifier : nativeGetProcAddress, Due to Func
if(key == "haxe.ds.Vector") return fields; // Error: haxe.ds._Vector.VectorData<blit.T> has no field blit, Due to Func
if(key == "haxe.display.Display") return fields; // Error: haxe.display.DisplayItemKind<haxe.display.DisplayLiteral<Dynamic>> has no field Null, Due to Func
if(key == "cpp.Callable") return fields; // Error: cpp.Function.fromStaticFunction must be called on static function, Due to Func
if(key == "haxe.display.JsonAnonStatusKind") return fields; // Error: cannot initialize a variable of type 'char *' with an rvalue of type 'const char *', Due to Func
if(key == "cpp.CharStar") return fields; // Error: cannot initialize a variable of type 'char *' with an rvalue of type 'const char *', Due to Func
if(Config.DISALLOW_ABSTRACT_AND_ENUM.contains(cl.module) || Config.DISALLOW_ABSTRACT_AND_ENUM.contains(fkey)) return fields;
if(cl.module.contains("_")) return fields; // Weird issue, sorry
var shadowClass = macro class {
};
shadowClass.kind = TDClass();
shadowClass.params = switch(cl.params.length) {
case 0:
null;
case 1:
[{
name: "T",
}];
default:
[for(k=>e in cl.params) {
name: "T" + Std.int(k+1)
}];
};
shadowClass.name = '${cl.name.substr(0, cl.name.length - 6)}_HSC';
var imports = Context.getLocalImports().copy();
Utils.setupMetas(shadowClass, imports);
//trace(cl.module);
for(f in fields)
switch(f.kind) {
case FFun(fun):
if (f.access.contains(AStatic)) {
if (fun.expr != null) {
fun.expr = macro @:privateAccess $e{fun.expr};
shadowClass.fields.push(f);
/*var trimEnum = cl.name.substr(0, cl.name.length - 6);
var returns:Bool = !fun.ret.match(TPath({name: "Void"}));
var name = f.name;
var arguments = fun.args == null ? [] : [for(a in fun.args) macro $i{a.name}];
var expr:Expr = Context.parse('${returns?"return " : ""} $trimEnum.$name(${[for(a in fun.args) a.name].join(", ")})', f.pos);
var func:Function = {
ret: fun.ret,
params: fun.params.copy(),
expr: expr,
args: fun.args.copy()
};
var field:Field = {
pos: f.pos,
name: f.name,
meta: f.meta,
kind: FFun(func),
doc: null,//f.doc,
access: [APublic, AStatic]
}
shadowClass.fields.push(field);*/
}
}
case FProp(get, set, t, e):
if (get == "default" && (set == "never" || set == "null")) {
shadowClass.fields.push(f);
}
case FVar(t, e):
if (f.access.contains(AStatic) || cl.meta.has(":enum") || f.name.toUpperCase() == f.name) {
var name:String = f.name;
var enumType:String = cl.name;
var pack = cl.module.split(".");
//trace(pack, cl.name, name, cl.module);
if(pack[pack.length - 1] == trimEnum)
pack.pop();
var complexType:ComplexType = t;
if(complexType == null && e != null) {
complexType = switch(e.expr) {
case EConst(CRegexp(_)): TPath({ name: "EReg", pack: [] });
default: null;
}
}
if(complexType == null) {
complexType = TPath({
name: trimEnum,
pack: [],//pack
});
}
var code = Context.parse('@:privateAccess ($trimEnum.$name)', f.pos); // '${pack.join(".")}.${trimEnum}.$name'
var field:Field = {
pos: f.pos,
name: f.name,
meta: f.meta,
kind: FVar(null, code),
doc: f.doc,
access: [APublic, AStatic]
}
shadowClass.fields.push(field);
}
default:
}
//var printer = new Printer();
//for(field in shadowClass.fields)
// trace(printer.printField(field));
Context.defineModule(cl.module, [shadowClass], imports);
}
return fields;
}
}
#end
+209
View File
@@ -0,0 +1,209 @@
package hscript.macros;
#if macro
import haxe.macro.Type.ClassType;
import Type.ValueType;
import haxe.macro.Expr.Function;
import haxe.macro.Expr;
import haxe.macro.Type.MetaAccess;
import haxe.macro.Type.FieldKind;
import haxe.macro.Type.ClassField;
import haxe.macro.Type.VarAccess;
import haxe.macro.*;
using StringTools;
class Utils {
public static function fixStdTypes(type:ComplexType) {
switch(type) {
case TPath({name: "StdTypes"}):
var a:TypePath = type.getParameters()[0];
a.name = a.sub;
a.sub = null;
default:
}
return type;
}
public static function setupMetas(shadowClass:TypeDefinition, imports) {
shadowClass.meta = [];
shadowClass.meta.push({name: ":dox", params: [macro hide], pos: Context.currentPos()});
shadowClass.meta.push({name: ":noCompletion", params: [], pos: Context.currentPos()});
var module = Context.getModule(Context.getLocalModule());
for(t in module) {
switch(t) {
case TInst(t, params):
if (t != null) {
var e = t.get();
processModule(shadowClass, e.module, e.name);
processImport(imports, e.module, e.name);
}
case TEnum(t, params):
if (t != null) {
var e = t.get();
processModule(shadowClass, e.module, e.name);
processImport(imports, e.module, e.name);
}
case TType(t, params):
if (t != null) {
var e = t.get();
processModule(shadowClass, e.module, e.name);
processImport(imports, e.module, e.name);
}
case TAbstract(t, params):
if (t != null) {
var e = t.get();
processModule(shadowClass, e.module, e.name);
processImport(imports, e.module, e.name);
}
default:
// not needed?
}
}
}
public static function processModule(shadowClass:TypeDefinition, module:String, n:String) {
if (n.endsWith("_Impl_"))
n = n.substr(0, n.length - 6);
if (module.endsWith("_Impl_"))
module = module.substr(0, module.length - 6);
shadowClass.meta.push(
{
name: ':access',
params: [
Context.parse(fixModuleName(module.endsWith('.${n}') ? module : '${module}.${n}'), Context.currentPos())
],
pos: Context.currentPos()
}
);
}
/*public static function getModuleName(path:Type) {
switch(path) {
case TPath(name, pack):// | TDClass(name, pack):
var str = "";
for(p in pack) {
str += p + ".";
}
str += name;
return str;
default:
}
return "INVALID";
}*/
public static function fixModuleName(name:String) {
return [for(s in name.split(".")) if (s.charAt(0) == "_") s.substr(1) else s].join(".");
}
public static function processImport(imports:Array<ImportExpr>, module:String, n:String) {
if (n.endsWith("_Impl_"))
n = n.substr(0, n.length - 6);
module = fixModuleName(module);
if (module.endsWith("_Impl_"))
module = module.substr(0, module.length - 6);
imports.push({
path: [for(m in module.split(".")) {
name: m,
pos: Context.currentPos()
}],
mode: INormal
});
}
public static function cleanExpr(expr:Expr, oldFunc:String, newFunc:String) {
if (expr == null) return;
if (expr.expr == null) return;
switch(expr.expr) {
case EConst(c):
switch(c) {
case CIdent(s):
if (s == oldFunc)
expr.expr = EConst(CIdent(newFunc));
case CString(s, b):
if (s == oldFunc)
expr.expr = EConst(CString(s, b));
default:
// nothing
}
case EField(e, field):
if (field == oldFunc && e != null) {
switch(e.expr) {
case EConst(c):
switch(c) {
case CIdent(s):
if (s == "super")
expr.expr = EField(e, newFunc);
default:
}
default:
}
}
case EParenthesis(e):
cleanExpr(e, oldFunc, newFunc);
case EObjectDecl(fields):
for(f in fields) {
cleanExpr(f.expr, oldFunc, newFunc);
}
case EArrayDecl(values):
for(a in values) {
cleanExpr(a, oldFunc, newFunc);
}
case ECall(e, params):
cleanExpr(e, oldFunc, newFunc);
case EBlock(exprs):
for(e in exprs)
cleanExpr(e, oldFunc, newFunc);
case EFor(it, expr):
cleanExpr(it, oldFunc, newFunc);
cleanExpr(expr, oldFunc, newFunc);
case EIf(econd, eif, eelse):
cleanExpr(econd, oldFunc, newFunc);
cleanExpr(eif, oldFunc, newFunc);
cleanExpr(eelse, oldFunc, newFunc);
case EWhile(econd, e, normalWhile):
cleanExpr(econd, oldFunc, newFunc);
cleanExpr(e, oldFunc, newFunc);
case ECast(e, t):
cleanExpr(e, oldFunc, newFunc);
case ECheckType(e, t):
cleanExpr(e, oldFunc, newFunc);
case ETry(e, catches):
cleanExpr(e, oldFunc, newFunc);
for(c in catches) {
cleanExpr(c.expr, oldFunc, newFunc);
}
case EThrow(e):
cleanExpr(e, oldFunc, newFunc);
case ETernary(econd, eif, eelse):
cleanExpr(econd, oldFunc, newFunc);
cleanExpr(eif, oldFunc, newFunc);
cleanExpr(eelse, oldFunc, newFunc);
case ESwitch(e, cases, edef):
cleanExpr(e, oldFunc, newFunc);
for(c in cases) {
cleanExpr(c.expr, oldFunc, newFunc);
}
cleanExpr(edef, oldFunc, newFunc);
case EReturn(e):
cleanExpr(e, oldFunc, newFunc);
case EIs(e, t):
cleanExpr(e, oldFunc, newFunc);
case EVars(vars):
for(v in vars) {
cleanExpr(v.expr, oldFunc, newFunc);
}
case ENew(t, params):
for(p in params) {
cleanExpr(p, oldFunc, newFunc);
}
default:
}
}
}
#end