Skip to content

Instantly share code, notes, and snippets.

@binki
Last active January 6, 2017 17:13
Show Gist options
  • Save binki/58baa68b6311f7ee474df6f1651dacf1 to your computer and use it in GitHub Desktop.
Save binki/58baa68b6311f7ee474df6f1651dacf1 to your computer and use it in GitHub Desktop.
Haxe: how to expand arbitrary interpolated strings in macros
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;
}
}
$ 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