diff --git a/assets/InstanceExprArgMacro.hx b/assets/InstanceExprArgMacro.hx new file mode 100644 index 00000000..add97720 --- /dev/null +++ b/assets/InstanceExprArgMacro.hx @@ -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 +} diff --git a/assets/InstanceExprArgUsage.hx b/assets/InstanceExprArgUsage.hx new file mode 100644 index 00000000..3f038335 --- /dev/null +++ b/assets/InstanceExprArgUsage.hx @@ -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); + } +} diff --git a/content/09-macro.md b/content/09-macro.md index f6f45bf6..6f8bcfed 100644 --- a/content/09-macro.md +++ b/content/09-macro.md @@ -90,6 +90,23 @@ If the final argument of a macro is of type `Array`, the macro accepts an + +#### 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] +``` +