Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions assets/InstanceExprArgMacro.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import haxe.macro.Expr;
import haxe.macro.ExprTools;
import haxe.macro.MacroStringTools;

// use this for macros or other classes
class Logger {
public final id:String;
public function new(id:String) {
this.id = id;
}

inline public function log(data:Any, logID:String, ?pos) {
haxe.Log.trace('$id: $logID = [$data]', pos);
}

macro public function logExpr(instance:Expr, data:Expr):Expr {
return eval(instance, data);
}

#if macro
static public function eval(instance:Expr, obj:Expr):Expr {
final id = MacroStringTools.formatString('${ExprTools.toString(obj)}', obj.pos);

return macro {
@:pos(obj.pos)
$instance.log($obj, $id);
};
}
#end
}
12 changes: 12 additions & 0 deletions assets/InstanceExprArgUsage.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Test {
static function main() {
final factLogger = new Logger("Fact");
final lieLogger = new Logger("Lie");

final theory1 = {statement: "Haxe is great!", conclusion: true};
final theory2 = {statement: "7 > 9", conclusion: false};

(theory1.conclusion ? factLogger : lieLogger).logExpr(theory1.statement);
(theory2.conclusion ? factLogger : lieLogger).logExpr(theory2.statement);
}
}
17 changes: 17 additions & 0 deletions content/09-macro.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,23 @@ If the final argument of a macro is of type `Array<Expr>`, the macro accepts an



<!--label:macro-instance-arg-->
#### Instance Argument

If the macro is an instance method, the first arg will be the expression used to reference the instance:

[code asset](assets/InstanceExprArgMacro.hx)

Usage:

[code asset](assets/InstanceExprArgUsage.hx)

This outputs at runtime:
```
Test.hx:9: Fact: theory1.statement = [Haxe is great!]
Test.hx:10: Lie: theory2.statement = [7 > 9]
```



<!--label:macro-reification-->
Expand Down