Last active
January 6, 2017 17:13
-
-
Save binki/58baa68b6311f7ee474df6f1651dacf1 to your computer and use it in GitHub Desktop.
Haxe: how to expand arbitrary interpolated strings in macros
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import haxe.macro.Expr; | |
import haxe.macro.MacroStringTools; | |
import haxe.macro.Printer; | |
class MoreLiteral { | |
static function main() { | |
var x = 2; | |
trace(Util.xpand(34)); | |
} | |
static function otherFunction() return 43; | |
} | |
class Util { | |
macro static public function xpand(e:Expr) { | |
// This is cool. We can expand arbitrary expressions in other | |
// contexts. | |
var result = MacroStringTools.formatString("${x * 3 + otherFunction()}", e.pos); | |
trace(result); | |
trace(new Printer().printExpr(result)); | |
return result; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ haxe --run MoreLiteral | |
MoreLiteral.hx:19: { expr => EBinop(OpAdd,{ expr => EConst(CString()), pos => #pos(MoreLiteral.hx:8: character 26) },{ expr => EBinop(OpAdd,{ expr => EBinop(OpMult,{ expr => EConst(CIdent(x)), pos => #pos(MoreLiteral.hx:8: characters 28-29) },{ expr => EConst(CInt(3)), pos => #pos(MoreLiteral.hx:9: characters 0-1) }), pos => #pos(MoreLiteral.hx:8: lines 8-9) },{ expr => ECall({ expr => EConst(CIdent(otherFunction)), pos => #pos(MoreLiteral.hx:9: lines 9-11) },[]), pos => #pos(MoreLiteral.hx:9: lines 9-11) }), pos => #pos(MoreLiteral.hx:8: lines 8-11) }), pos => #pos(MoreLiteral.hx:8: lines 8-11) } | |
MoreLiteral.hx:20: "" + x * 3 + otherFunction() | |
MoreLiteral.hx:8: 49 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment