简体   繁体   中英

How do I create a macro for property extensions

I'd like to write my own macro for creating property like objects in Haxe. This question is not so much about properties but more about writing macros. (probably NME has already a macro for that).

having this class in haxe

class Foo {
    @:property var bar:String;
}

I like this to be expanded into

class Foo {
    private var bar:String;

    public function setBar(_val:String):void {
        this.bar = _val;
    }

    public function getBar():String {
        return this.bar;
    }
 }

I read the corresponding docs but honestly I find them very confusing.

thanks

您可能想看看tinkerbell如何解决相同的问题: https : //github.com/back2dos/tinkerbell/wiki/tink_lang#wiki-accessors

This Type Builder example (pasted below for reference, but there's better description at the link) found in the Haxe Manual is a nice, simple example of adding a function to a Class.

Adding a property would be much the same. I added a trace(field) loop to help get a feel for how they're defined:

Main.hx

@:build(TypeBuildingMacro.build("myFunc"))
class Main {
  static public function main() {
    trace(Main.myFunc); // my default
  }
}

TypeBuildingMacro.hx

import haxe.macro.Context;
import haxe.macro.Expr;

class TypeBuildingMacro {
  macro static public function build(fieldName:String):Array<Field> {
    var fields = Context.getBuildFields();
    for (field in fields) { trace(field); }
    var newField = {
      name: fieldName,
      doc: null,
      meta: [],
      access: [AStatic, APublic],
      kind: FVar(macro : String, macro "my default"),
      pos: Context.currentPos()
    };
    fields.push(newField);
    return fields;
  }
}

Note that Main.hx must invoke the macro with the @:build metadata, so the compiler knows to run the macro (which adds the function) before processing the Main class itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM