Skip to content

Instantly share code, notes, and snippets.

@skial
Last active March 20, 2016 13:09
Show Gist options
  • Save skial/c1e35988b853b214da39 to your computer and use it in GitHub Desktop.
Save skial/c1e35988b853b214da39 to your computer and use it in GitHub Desktop.
@:astSource test code, originally for https://github.com/HaxeFoundation/haxe/issues/4959
-cp src
-neko bin/test.n
-main Main
haxe build.hxml
src/Macro.hx:18: new,[@:astSource({
var a = 1;
var b = a * 25;
})]
src/Macro.hx:28: main,[@:astSource({
trace(new Test(10));
})]
package;
import haxe.macro.Type;
import haxe.macro.Context;
import haxe.macro.Printer;
class Macro {
// Runs on class `Test`.
public static function build() {
// Accessing class `Main` _through_ the compiler.
var type = Context.getType( 'Main' );
var print = new Printer();
switch (type) {
case TInst(_.get() => cls, params):
if (cls.constructor != null) {
trace( 'new', [for (m in cls.constructor.get().meta.get()) print.printMetadata( m )] );
}
for (field in cls.fields.get()) {
trace( field.name, [for (m in field.meta.get()) print.printMetadata( m )] );
}
for (field in cls.statics.get()) {
trace( field.name, [for (m in field.meta.get()) print.printMetadata( m )] );
}
case _:
}
return Context.getBuildFields();
}
}
package;
class Main {
@:astSource static function main() {
trace( new Test(10) );
}
@:astSource public function new() {
var a = 1;
var b = a * 25;
}
}
@:build( Macro.build() )
class Test {
public var a:Int = 0;
public var b:Int = 1;
public function new(a:Int, ?b:Int) {
this.a = (a > 5) ? a : this.a;
if (b != null) this.b = b;
}
public function toString():String {
return 'Test::a=>$a,b=>$b';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment