Skip to content

Instantly share code, notes, and snippets.

@nadako
Created May 5, 2014 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nadako/ceaf986c006c5796fce7 to your computer and use it in GitHub Desktop.
Save nadako/ceaf986c006c5796fce7 to your computer and use it in GitHub Desktop.
Typed hasField check macro
using TypedFieldMacro;
typedef A = {?f:Int}
class Main
{
static function main()
{
var a:A = {f:1};
if (a.f.exists()) trace(a.f);
}
}
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