Last active
June 13, 2021 00:36
-
-
Save Jarrio/2e1249087b24b168bd48c2baae5a52ae to your computer and use it in GitHub Desktop.
Haxe enum destructor macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package; | |
import haxe.macro.Printer; | |
import haxe.macro.Context; | |
#if macro | |
import haxe.macro.Expr; | |
#end | |
using haxe.macro.Tools; | |
class MacroTools { | |
public static macro function extract<T>(data:ExprOf<T>, pattern:Expr) { | |
var enum_name = null; | |
var enum_args = []; | |
var result = null; | |
var obj:Array<ObjectField> = []; | |
switch (pattern.expr) { | |
case EConst(CIdent(s)): | |
try { | |
var type = Context.typeof(data); | |
trace(type); | |
switch (type.follow()) { | |
case TEnum(_.get() => t, params): | |
for (name => value in t.constructs) { | |
if (name == s) { | |
enum_name = Context.makeExpr(EConst(CIdent(name)), data.pos); | |
switch (value.type) { | |
case TFun(args, ret): | |
var expr = null; | |
for (field in args) { | |
expr = {expr: EConst(CIdent(field.name)), pos: data.pos}; | |
obj.push({ | |
field: field.name, | |
expr: expr | |
}); | |
enum_args.push(expr); | |
} | |
default: | |
throw 'Invalid input. Check if the enum has any arguments'; | |
} | |
} | |
} | |
default: | |
} | |
} catch (e) { | |
throw e; | |
} | |
default: | |
} | |
var parse = {expr: EObjectDecl(obj), pos: data.pos}; | |
var res = {expr: ECall(pattern, enum_args), pos: data.pos}; | |
result = macro switch ($data) { | |
case ${res} : $parse; | |
case _: null; | |
} | |
return result; | |
} | |
} | |
//update tab spaces? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment