Created
May 5, 2014 12:51
-
-
Save nadako/ceaf986c006c5796fce7 to your computer and use it in GitHub Desktop.
Typed hasField check 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
using TypedFieldMacro; | |
typedef A = {?f:Int} | |
class Main | |
{ | |
static function main() | |
{ | |
var a:A = {f:1}; | |
if (a.f.exists()) trace(a.f); | |
} | |
} |
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
import haxe.macro.Context; | |
import haxe.macro.Expr; | |
using haxe.macro.Tools; | |
class TypedFieldMacro | |
{ | |
public static macro function exists(field:Expr):ExprOf<Bool> | |
{ | |
var tfield = Context.typeExpr(field); | |
switch (tfield.expr) | |
{ | |
case TField(e, FAnon(_.get() => f)): | |
if (!f.meta.has(":optional")) | |
Context.warning('TypedFieldMacro.exists is used for non-optional field ${f.name} of type ${e.t.toString()}', field.pos); | |
var eobj = Context.getTypedExpr(e); | |
return macro Reflect.hasField($eobj, $v{f.name}); | |
default: | |
var e = Context.getTypedExpr(tfield); | |
throw new Error('Unsupported expression ${e.toString()}. Only anonymous structure fields are supported!', field.pos); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment