Skip to content

Instantly share code, notes, and snippets.

@YellowAfterlife
Created September 17, 2014 11:51
Show Gist options
  • Save YellowAfterlife/f5148c542d8a1bb89815 to your computer and use it in GitHub Desktop.
Save YellowAfterlife/f5148c542d8a1bb89815 to your computer and use it in GitHub Desktop.
function printTry(e1:haxe.macro.TypedExpr, catches: Array<{ v : haxe.macro.TVar, expr : haxe.macro.TypedExpr }>)
{
// TODO catch other types of exceptions
// getting last (e:Dynamic) catch:
var _dynCatch = catches.pop(), _tabs;
// try-block:
var s = 'local try, catch = pcall(function ()';
_tabs = tabs; tabs += tabString;
var tryBlock = printExpr(e1);
s += '\n${tabs}${tryBlock}';
var hasReturns = (tryBlock.indexOf("return") >= 0);
var alwaysReturns = false;
if (hasReturns) {
switch (e1.expr) {
case TBlock(m):
switch (m[m.length - 1].expr) {
case TReturn(_): alwaysReturns = true;
default:
}
case TReturn(_): alwaysReturns = true;
default:
}
if (!alwaysReturns) s += '\n${tabs}return undefined';
}
tabs = _tabs;
s += '\n${tabs}end);';
// catch-block:
if (_dynCatch.expr != null) switch (_dynCatch.expr.expr) {
case TBlock([]): // empty catch-block
if (hasReturns) {
if (!alwaysReturns) {
s += '\n${tabs}if try and (catch ~= undefined) then return catch end';
} else s += '\n${tabs}if try then return catch end';
}
default: // print block only if it's non-empty.
s += '\n${tabs}if (try == false) then';
tabs += "\t";
s += '\n${tabs}local ${_dynCatch.v.name} = catch;';
s += '\n${tabs}${printExpr(_dynCatch.expr)}';
tabs = _tabs;
s += '\n${tabs}';
if (hasReturns) {
if (!alwaysReturns) {
s += 'elseif (catch ~= undefined) then return catch end';
} else s += 'else return catch end';
} else s += 'end';
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment