I was playing around with the @:event
metadata yesterday, and I wrote a couple of helper functions for a macro I was working on. I figured I’d share, in case it might help anyone.
The first gets all of the @:event
MetadataEntry
values from a class and its superclasses:
private static function getAllEvents(type:ClassType):Array<MetadataEntry> {
if (type == null) {
return [];
}
var events = type.meta.extract(":event").filter(eventMeta -> eventMeta.params.length == 1);
var superClass = type.superClass;
if (superClass != null) {
for (event in getAllEvents(superClass.t.get())) {
events.push(event);
}
}
return events;
}
The second gets the string value from the referenced event.
private static function getEventName(eventMeta:MetadataEntry):String {
var typedExprDef = Context.typeExpr(eventMeta.params[0]).expr;
return switch (typedExprDef) {
case TCast(e, m):
switch (e.expr) {
case TConst(c):
switch (c) {
case TString(s): s;
default: null;
}
default: null;
}
default: null;
};
}