Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add compiler warning/error for duplicate variable declaration in LuaJIT 2.1
--- lj_parse.c
+++ lj_parse.c
@@ -27,6 +27,8 @@
#include "lj_parse.h"
#include "lj_vm.h"
#include "lj_vmevent.h"
+
+#include <stdio.h>
/* -- Parser structures and definitions ----------------------------------- */
@@ -164,6 +166,12 @@
LJ_STATIC_ASSERT((int)BC_MODVV-(int)BC_ADDVV == (int)OPR_MOD-(int)OPR_ADD);
/* -- Error handling ------------------------------------------------------ */
+
+static void parser_warning (LexState *ls, const char *msg) {
+ const char *str = strdata(ls->chunkname);
+ fprintf(stderr, "%s:%d: warning %s\n", (str[0] == '@') ? str+1 : str , ls->linenumber, msg);
+ fflush(stderr);
+}
LJ_NORET LJ_NOINLINE static void err_syntax(LexState *ls, ErrMsg em)
{
@@ -1034,7 +1042,27 @@
{
FuncState *fs = ls->fs;
MSize vtop = ls->vtop;
- checklimit(fs, fs->nactvar+n, LJ_MAX_LOCVAR, "local variables");
+ BCReg i, nactvar_n = fs->nactvar+n;
+
+ if(name && name > ((GCstr*)0xffff)) { /*some names are made from casting ints */
+ /* allow '_' and '(for...' duplicates */
+ const char *str_name = strdata(name);
+ if(!(str_name[0] == '(' || (name->len == 1 && str_name[0] == '_'))) {
+ for (i=0; i < nactvar_n; ++i) {
+ if (name == strref(var_get(ls, fs, i).name)) {
+ if(fs->bl && i < fs->bl->nactvar) {
+ parser_warning(ls, lj_strfmt_pushf(ls->L,
+ "Name [%s] already declared will be shadowed", str_name));
+ }
+ else {
+ lj_lex_error(ls, 0, LJ_ERR_XNAMEDUP, str_name);
+ }
+ }
+ }
+ }
+ }
+
+ checklimit(fs, nactvar_n, LJ_MAX_LOCVAR, "local variables");
if (LJ_UNLIKELY(vtop >= ls->sizevstack)) {
if (ls->sizevstack >= LJ_MAX_VSTACK)
lj_lex_error(ls, 0, LJ_ERR_XLIMC, LJ_MAX_VSTACK);
--- lj_errmsg.h
+++ lj_errmsg.h
@@ -145,6 +145,7 @@
ERRDEF(XLUNDEF, "undefined label " LUA_QS)
ERRDEF(XLDUP, "duplicate label " LUA_QS)
ERRDEF(XGSCOPE, "<goto %s> jumps into the scope of local " LUA_QS)
+ERRDEF(XNAMEDUP, "duplicate name " LUA_QS)
/* Bytecode reader errors. */
ERRDEF(BCFMT, "cannot load incompatible bytecode")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.