Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion TestHScript.hx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@ class TestHScript extends TestCase {
for( v in Reflect.fields(vars) )
interp.variables.set(v,Reflect.field(vars,v));
var ret : Dynamic = interp.execute(program);
assertEquals(v, ret, pos);
if(Reflect.isEnumValue(v) && Reflect.isEnumValue(ret)) {
if(!Type.enumEq(v, ret)) {
assertEquals(Std.string(v), Std.string(ret), pos);
} else {
assertTrue(true, pos);
}
} else assertEquals(v, ret, pos);
assertPos.lineNumber += 1;
}

Expand Down Expand Up @@ -332,6 +338,14 @@ class TestHScript extends TestCase {
assertScript('import StringTools.contains; contains("hscript", "hscript")', true);
// scripted class field import
assertScript('class M {public static function double(val:Float){return val * 2;}} import M.double; double(10)', 20, null, true);
#if !hscriptNoWildcardImports
// wildcard imports
assertScript("import haxe.ds.*; StringMap", haxe.ds.StringMap);
final script = "import haxe.ds.*; var a = new StringMap(); a.set('hiii', 0xF0); a.get('hiii')";
assertScript(script, 0xF0);
assertScript(script+"; StringTools.trim(' hello ')","hello");
assertScript("import haxe.ds.*; Option.Some(123)", haxe.ds.Option.Some(123));
#end
}

function testClass() {
Expand Down
6 changes: 4 additions & 2 deletions hscript/Bytes.hx
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,11 @@ class Bytes {
switch( e ) {
case EPackage(n):
doEncodeString(n == null ? "" : n);
case EImport(c, asName, isUsing):
case EImport(c, asName, isUsing, isWildcard):
doEncodeBoolean(isUsing ?? false);
doEncodeString(c);
doEncodeString(asName == null ? "" : asName);
doEncodeBoolean(isWildcard ?? false);
case EClass(name, fields, extend, interfaces, isFinal, _):
doEncodeString(name);
doEncodeString(extend == null ? "" : extend);
Expand Down Expand Up @@ -608,7 +609,8 @@ class Bytes {
final isUsing:Bool = doDecodeBoolean();
final cls = doDecodeString();
final asName = doDecodeString();
EImport(cls, asName == "" ? null : asName, isUsing);
final isWildcard:Bool = doDecodeBoolean();
EImport(cls, asName == "" ? null : asName, isUsing, isWildcard);
case BCLASS:
final name:String = doDecodeString();
final extend:String = doDecodeString();
Expand Down
2 changes: 1 addition & 1 deletion hscript/Expr.hx
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ enum Expr {
ECheckType( e : Expr, t : CType );

EPackage( ?n:String );
EImport( c : String, ?asname:String, ?isUsing:Bool );
EImport( c : String, ?asname:String, ?isUsing:Bool, ?isWildcard:Bool );
EClass( name:String, fields:Array<Expr>, ?extend:String, interfaces:Array<String>, ?isFinal:Bool, ?isPrivate:Bool );
EEnum( en:EnumDecl, ?isAbstract:Bool );
ECast(e:Expr, ?t:CType);
Expand Down
47 changes: 43 additions & 4 deletions hscript/Interp.hx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
*/
package hscript;

import hscript.utils.TypeListRegistry;
import haxe.Exception;
import haxe.ds.StringMap;
import haxe.ds.ObjectMap;
Expand Down Expand Up @@ -172,6 +173,9 @@ class Interp {

public var allowStaticVariables:Bool = false;
public var allowPublicVariables:Bool = false;
#if !hscriptNoWildcardImports
public var allowWildcardImports:Bool = true;
#end

@:deprecated("refer to 'hscript.Config.IMPORT_BLACKLIST'")
public var importBlocklist(get, never):Array<String>;
Expand Down Expand Up @@ -875,8 +879,21 @@ class Interp {
/** Handles `import` / `using` statements (extracted from the expr() switch). **/
@:noInline
@:access(hscript.CustomClassHandler)
function exprImport(clsName:String, aliasAs:Null<String>, isUsing:Bool):Void {
function exprImport(clsName:String, aliasAs:Null<String>, isUsing:Bool, isWildCard:Bool):Void {
if(!importEnabled) return;

if (isWildCard) {
#if !hscriptNoWildcardImports
if(!allowWildcardImports) {
error(ECustom('Wildcard imports are disabled'));
}
exprImportWildcard(clsName.trim());
return;
#else
error(ECustom('Wildcard imports are omitted from this build'));
return;
#end
}

var splitClassName:Array<String> = [for (e in clsName.split(".")) e.trim()];
var realClassName = splitClassName.join(".");
Expand Down Expand Up @@ -1002,6 +1019,28 @@ class Interp {
}
}

#if !hscriptNoWildcardImports
/** Handles `*`(wildcard) imports **/
@:noInline // whatever this does
function exprImportWildcard(pkg):Void {
final types = TypeListRegistry.get(pkg);

if(types == null) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This pull request has already been merged, but I have noticed that importFailedCallback is not used here (or anywhere in the pull request), the variable does use only 2 parameters being Array<String>, Null<String>, so it could be changed to include an isWildCard:Bool parameter so that it could fit here (or just make another callback though that's a bit much).
Adding the resolver here would allow for wildcard scripted packages, and making it more consistent with what you'd expect importFailedCallback to do.

This is all really just my thoughts and opinions, as someone who has been messing around with hscript for the last 2 years, so take what I say with a grain of salt.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// copying the invalid class error
error(ECustom('Invalid package: $pkg was not found'));
return;
}

for (type in types) {
final full = pkg + '.'+ type;

if(isBlocked(full)) continue;
if(variables.exists(type) || customClasses.exists(type)) continue;
try exprImport(full, null, false, false) catch(e) {}
}
}
#end

/** Handles `enum` declarations (extracted from the expr() switch). **/
@:noInline
function exprEnum(en:EnumDecl, isAbstract:Bool):Void {
Expand Down Expand Up @@ -1117,8 +1156,8 @@ class Interp {
case EPackage(_):
case EClass(name, fields, extend, interfaces, isFinal):
exprClass(name, fields, extend, interfaces, isFinal);
case EImport(clsName, aliasAs, isUsing):
exprImport(clsName, aliasAs, isUsing);
case EImport(clsName, aliasAs, isUsing, isWildcard):
exprImport(clsName, aliasAs, isUsing, isWildcard);
case EEnum(en, isAbstract):
exprEnum(en, isAbstract);
case ERegex(e, f):
Expand Down Expand Up @@ -1803,7 +1842,7 @@ class Interp {
static function walkHasFunctionLiteral(e:Expr):Bool {
return switch (Tools.expr(e)) {
case EFunction(_, _, _, _, _, _, _, _, _, _): true;
case EConst(_) | EIdent(_) | EBreak | EContinue | EPackage(_) | ERegex(_, _) | EImport(_, _, _): false;
case EConst(_) | EIdent(_) | EBreak | EContinue | EPackage(_) | ERegex(_, _) | EImport(_, _, _, _): false;
case EVar(_, _, ev, _, _, _, _, _, _, _): ev != null && walkHasFunctionLiteral(ev);
case EParent(x) | EUnop(_, _, x) | EThrow(x) | EMeta(_, _, x) | ECast(x, _):
walkHasFunctionLiteral(x);
Expand Down
7 changes: 6 additions & 1 deletion hscript/Parser.hx
Original file line number Diff line number Diff line change
Expand Up @@ -984,6 +984,7 @@ class Parser {
var isUsing = id == "using";
var oldReadPos = readPos;
var tk = token();
var isWildcard = false;
switch( tk ) {
case TPOpen:
if(isUsing) error(ECustom('Expected identifier'),tokenMin,tokenMax);
Expand Down Expand Up @@ -1013,6 +1014,7 @@ class Parser {
if( t != TDot ) {
if(t.match(TId("as"))) {
if(isUsing) error(ECustom('Expected . or ;'),tokenMin,tokenMax);
if(isWildcard) error(ECustom('Expected . or ; or as'),tokenMin,tokenMax);
t = token();
switch( t ) {
case TId(id):
Expand All @@ -1030,14 +1032,17 @@ class Parser {
switch( t ) {
case TId(id):
path.push(id);
case TOp("*") if(!isUsing):
isWildcard = true;
break;
default:
unexpected(t);
}
}
ensure(TSemicolon);
push(TSemicolon);
var p = path.join(".");
mk(EImport(p, asname, isUsing),p1);
mk(EImport(p, asname, isUsing, isWildcard),p1);
default:
unexpected(tk);
null;
Expand Down
3 changes: 2 additions & 1 deletion hscript/Printer.hx
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,11 @@ class Printer {
if(n != null)
add(' $n');
add(';\n');
case EImport(c, n, u):
case EImport(c, n, u, w):
add('${u ? 'using' : 'import'} $c');
if(n != null)
add(' as $n');
if(w==true) add('.*');
case EClass(name, fields, extend, interfaces, fnal):
var isFinal = fnal != null && fnal;
if(isFinal)
Expand Down
81 changes: 81 additions & 0 deletions hscript/macros/WildcardMacro.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package hscript.macros;

#if !hscriptNoWildcardImports
import haxe.ds.StringMap;
import haxe.rtti.Meta;

#if macro
import haxe.macro.Context;
import haxe.macro.Expr;
#end

using StringTools;

/** @author hackx2 **/
@:keep
final class WildcardMacro { // uses rtti to store type names
static final INDEX_META_NAME= "__indexed_types";
static final SEPARATOR = '~';
#if macro
static var __has_gen = false;
#end

public static macro function getTypes() {
#if macro
if(!__has_gen) {
__has_gen = true;
Context.onGenerate(_ -> {
switch Context.getType('hscript.macros.WildcardMacro') {
case TInst(t, _):
final meta = t.get().meta;
if(!meta.has(INDEX_META_NAME)) {
final arr:Array<Expr> = [
macro $v {
[
for(i in Context.getAllModuleTypes()) {
final typeName = switch i {
case TClassDecl(cls):
cls.toString();
case TEnumDecl(enum_):
enum_.toString();
case _: null;
}

if(typeName != null && !typeName.endsWith('_Fields_') && !typeName.endsWith('_Impl_') && !typeName.endsWith(ClassExtendMacro.CLASS_SUFFIX)) {
typeName;
}
}
].join(SEPARATOR)
}
];

meta.add(INDEX_META_NAME, arr,Context.currentPos());
}
case _: // nothin
}
});
}
#end

return macro {
final types = new haxe.ds.StringMap<Array<String>>();

final rttiType = haxe.rtti.Meta.getType(hscript.macros.WildcardMacro);
final raw:Dynamic = Reflect.field(rttiType, $v{INDEX_META_NAME});

if(raw != null) {
for (t in (raw[0] : String).split($v{SEPARATOR})) {
final dot = t.lastIndexOf('.');
final pack = dot == -1 ? '' : t.substr(0, dot);
final name = t.substr(dot + 1);

final type_pack = types.get(pack);
if (type_pack == null) types.set(pack, [name]) else type_pack.push(name);
}
}

types;
}
}
}
#end
14 changes: 14 additions & 0 deletions hscript/utils/TypeListRegistry.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package hscript.utils;

#if !hscriptNoWildcardImports
import haxe.ds.StringMap;
import hscript.macros.WildcardMacro;

class TypeListRegistry {
static var list(default, null):StringMap<Array<String>>;
public static function get(pkg:String) {
final map = list ??= WildcardMacro.getTypes();
return map != null ? map.get(pkg) : null;
}
}
#end