Skip to content

Instantly share code, notes, and snippets.

@alecmce
Last active December 19, 2015 21:58
Show Gist options
  • Save alecmce/6023959 to your computer and use it in GitHub Desktop.
Save alecmce/6023959 to your computer and use it in GitHub Desktop.
Interesting Macro error: if you define Example here in the same file as Main.hx then you get the error "Cannot access static field [field] from a class instance", but it's lying. Extract Example.hx to a different file and it compiles (and outputs "hello world", as you would expect).
package;
#if macro
import haxe.macro.Expr;
import haxe.macro.Expr.ExprOf;
import haxe.macro.Context;
import haxe.macro.Type;
#end
class Main
{
public static function main()
new Main();
public function new()
{
var instance = new Example();
instance.write("hello world");
trace(instance.read());
}
}
class Example
{
var map:Map<Int, String>;
public function new()
{
map = new Map<Int, String>();
}
macro public function write(self:ExprOf<Example>, value:Expr):Expr
{
return macro (untyped $self.hiddenWrite)(1, $value);
}
function hiddenWrite(id:Int, value:String)
{
map.set(id, value);
}
public function read():String
{
return map.get(1);
}
}
// openfl test flash.nmml flash
// src/Main.hx:20: characters 8-22 : Cannot access static field write from a class instance
@alecmce
Copy link
Author

alecmce commented Jul 20, 2013

FYI from Matthew Spencer (@m22spencer on Twitter) - "Separating classes fixes since you are no longer compiling cls Main in macro context"

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