Skip to content

Commit

Permalink
Re-add ifexpr, but require 'end' to terminate it
Browse files Browse the repository at this point in the history
  • Loading branch information
Sainan authored and well-in-that-case committed Aug 1, 2024
1 parent 4bcd52b commit 3e1ed8b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/lparser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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 '+' */
Expand Down Expand Up @@ -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;
Expand Down
7 changes: 7 additions & 0 deletions testes/pluto/basic.pluto
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 3e1ed8b

Please sign in to comment.