Skip to content

Instantly share code, notes, and snippets.

@Lerc
Last active August 29, 2015 14:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Lerc/6056075268a46050b232 to your computer and use it in GitHub Desktop.
Save Lerc/6056075268a46050b232 to your computer and use it in GitHub Desktop.
A Haxe Macro example. Allows class properties to be added that map to an array entry. I made this for a project using JavaScript typed arrays for speed.
(function () { "use strict";
var RegTest = function() {
this.ram = new Uint8Array(65536);
};
RegTest.main = function() {
var foo = new RegTest();
foo.whatIsR0();
};
RegTest.prototype = {
whatIsR0: function() {
console.log("r0 is " + this.ram[123]);
}
,get_r0: function() {
return this.ram[123];
}
,set_r0: function(value) {
return this.ram[123] = value;
}
};
RegTest.main();
})();
package ;
import haxe.macro.Context;
import haxe.macro.Expr;
class RegisterMacro
{
macro static public function memoryMappedRegister(fieldName:String,index :Int):Array<Field> {
var fields = Context.getBuildFields();
var getterName = "get_" + fieldName;
var setterName = "set_" + fieldName;
var propertyFromMacro = macro : {
var $fieldName(get, set) : Int;
inline function $getterName() : Int {
return ram[ $v{index} ];
}
inline function $setterName(value:Int) : Int {
return ram[$v{index}]=value;
}
};
switch (propertyFromMacro) {
case TAnonymous(getterFields):
fields=fields.concat(getterFields);
default:
throw 'unreachable';
}
return fields;
}
}
import js.html.Uint8Array;
@:build( RegisterMacro.memoryMappedRegister("r0",123) )
class RegTest
{
var ram : Uint8Array;
public function new() {
ram = new Uint8Array(65536);
}
public function whatIsR0() {
trace("r0 is "+r0);
}
static function main() {
var foo = new RegTest();
foo.whatIsR0();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment