Skip to content

Instantly share code, notes, and snippets.

@nadako
Created November 18, 2014 13:27
Show Gist options
  • Save nadako/bcb6f547b52b3afbd908 to your computer and use it in GitHub Desktop.
Save nadako/bcb6f547b52b3afbd908 to your computer and use it in GitHub Desktop.
Type params syntax sugar.
class Main {
static function main() {
var event:MapChangeEvent<Map<String,Int>>;
$type(event.key); // String
$type(event.value); // Int
}
}
@:genericBuild(MapChangeEventMacro.build())
class MapChangeEvent<MapType> {}
class MapChangeEventImpl<TSource, TKey, TValue> {
public var source:TSource;
public var key:TKey;
public var value:TValue;
}
import haxe.macro.Expr;
import haxe.macro.Context;
import haxe.macro.Type;
using haxe.macro.Tools;
class MapChangeEventMacro {
static function build():ComplexType {
return switch (Context.getLocalType()) {
case TInst(_, [mapType]):
switch (mapType.follow()) {
case TAbstract(_.get() => {pack: [], name: "Map"}, [keyType, valueType]):
return TPath({
pack: [],
name: "MapChangeEvent",
sub: "MapChangeEventImpl",
params: [
TPType(mapType.toComplexType()),
TPType(keyType.toComplexType()),
TPType(valueType.toComplexType()),
],
});
default:
throw false;
}
default:
throw false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment