Skip to content

Instantly share code, notes, and snippets.

@elsassph
Last active November 26, 2017 18:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elsassph/319e1eade1978f08e221 to your computer and use it in GitHub Desktop.
Save elsassph/319e1eade1978f08e221 to your computer and use it in GitHub Desktop.
Haxe macro for: custom, automatic, getter/setter generation
/*
We want to generate:
- getMyProperty / setMyProperty
- getAnotherProperty
- getYetAnotherProperty / setYetAnotherProperty
*/
class Test implements Proxied
{
public var MyPoperty(default, default):Int;
public var anotherProperty(default, null):String;
public var yetAnotherProperty(get, set):Int;
private var FYetAnotherProperty:Int;
public function new()
{
MyPoperty = 0;
anotherProperty = "";
FYetAnotherProperty = 0;
}
public function get_yetAnotherProperty():Int
{
return FYetAnotherProperty;
}
public function set_yetAnotherProperty(value:Int):Int
{
return FYetAnotherProperty = value;
}
}
/*
Implementing this interface will trigger the automatic functions creation macro
*/
@:remove
@:autoBuild(ProxyGenerator.build())
interface Proxied {
}
import haxe.macro.Context;
import haxe.macro.Expr;
class ProxyGenerator
{
macro public static function build():Array<Field>
{
var fields = Context.getBuildFields();
var append = [];
for (field in fields)
{
switch (field.kind)
{
case FProp(_, pset, _, _):
var name = formatName(field.name);
// assume there is always a getter
append.push({
name: 'get' + name,
kind: FieldType.FFun({
args: [],
expr: macro return $i{field.name},
ret: null
}),
pos: Context.currentPos()
});
// only generate setters if the property is writable
if (pset != 'null' && pset != 'never')
{
append.push({
name: 'set' + name,
kind: FieldType.FFun({
args: [{ name:'value', type:null } ],
expr: macro return $i{field.name} = value,
ret: null
}),
pos: Context.currentPos()
});
}
default:
}
}
return fields.concat(append);
}
static function formatName(name:String)
{
return name.charAt(0).toUpperCase() + name.substr(1);
}
}
@Glidias
Copy link

Glidias commented Dec 18, 2016

https://gist.github.com/elsassph/319e1eade1978f08e221#file-2_proxygenerator-hx-L35 How do you define the ComplexType using the given field for "type" and "ret" respectively??

You can do it like this:

case FProp(_, pset, fieldType, _):
  //....
          args: [{ name:'value', type:fieldType } ], 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment