diff --git a/src/lparser.cpp b/src/lparser.cpp index 130e13cc6..1613ef615 100644 --- a/src/lparser.cpp +++ b/src/lparser.cpp @@ -3121,6 +3121,31 @@ static void expsuffix (LexState *ls, expdesc *v, int line, int flags, TypeHint * } +static int cond (LexState *ls, bool for_while_loop = false); +static void ifexpr (LexState *ls, expdesc *v) { + throw_warn(ls, "'if a then b else c' is deprecated", "use 'a ? b : c' instead", WT_DEPRECATED); + /* + ** 'if' expressions are based on a patch published by by Ryota Hirose. + */ + FuncState *fs = ls->fs; + int condition; + int escape = NO_JUMP; + int reg; + luaX_next(ls); + condition = cond(ls); + checknext(ls, TK_THEN); + expr(ls, v); + reg = luaK_exp2anyreg(fs, v); + luaK_concat(fs, &escape, luaK_jump(fs)); + luaK_patchtohere(fs, condition); + checknext(ls, TK_ELSE); + expr(ls, v); + checknext(ls, TK_END); + luaK_exp2reg(fs, v, reg); + luaK_patchtohere(fs, escape); +} + + static void newexpr (LexState *ls, expdesc *v) { FuncState *fs = ls->fs; @@ -3638,6 +3663,7 @@ static BinOpr subexpr (LexState *ls, expdesc *v, int limit, TypeHint *prop, int subexpr(ls, v, UNARY_PRIORITY, nullptr, flags); luaK_prefix(ls->fs, uop, v, line); } + else if (ls->t.token == TK_IF) ifexpr(ls, v); else if (ls->t.token == '+') { int line = ls->getLineNumber(); luaX_next(ls); /* skip '+' */ @@ -3948,7 +3974,7 @@ static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) { luaK_storevar(ls->fs, &lh->v, &e); } -static int cond (LexState *ls, bool for_while_loop = false) { +static int cond (LexState *ls, bool for_while_loop) { /* cond -> exp */ expdesc v; ls->used_walrus = false; diff --git a/testes/pluto/basic.pluto b/testes/pluto/basic.pluto index 97b988deb..d584cb8ca 100644 --- a/testes/pluto/basic.pluto +++ b/testes/pluto/basic.pluto @@ -773,6 +773,13 @@ do } assert(true ? (t:t()) : false) + -- Longhand: 'if' expression + assert(if a == 3 then + "yes" + else + "no" + end == "yes") + -- @pluto_warnings: enable-unreachable-code end