Skip to content

Instantly share code, notes, and snippets.

@markknol
Last active October 27, 2015 09:14
Show Gist options
  • Save markknol/b0fc79fa82d596a398e6 to your computer and use it in GitHub Desktop.
Save markknol/b0fc79fa82d596a398e6 to your computer and use it in GitHub Desktop.
Macro Field build handbook

Build property with inline getter

Virtually adds this property to a class:

public function myVar(get, null):Float;
private inline function get_myVar():Float {
	return 1.5;
}

Build macro:

#if (display || macro)
import haxe.macro.Context;
import haxe.macro.Expr;
public static function build():Array<Field> {
	var fields = Context.getBuildFields();
	
	var value = 1.5;
	var pos = Context.currentPos();
	var fieldName = "myVar";
	
	var myFunc:Function = { 
		expr: macro return $v{value},  // actual value
		ret: (macro:Float), // ret = return type
		args:[] // no arguments here
	}
	
	// create: `public var $fieldName(get,null)`
	var propertyField:Field = {
		name:  fieldName,
		access: [Access.APublic],
		kind: FieldType.FProp("get", "null", myFunc.ret), 
		pos: pos,
	};
	
	// create: `private inline function get_$fieldName() return $value`
	var getterField:Field = {
		name: "get_" + fieldName,
		access: [Access.APrivate, Access.AInline],
		kind: FieldType.FFun(myFunc),
		pos: pos,
	};
	
	// append both fields
	fields.push(propertyField);
	fields.push(getterField);
	
	return fields;
}
#end

working with Position

Position from context

Context.getCurrentPos();

Custom position

var pos = Context.makePosition({ 
	file: myFile,
	min:1, 
	max:2 
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment