From d4f35305393c27968e9499c8b97d0787b3ccaaa4 Mon Sep 17 00:00:00 2001 From: Stephan Hadinger Date: Mon, 29 Aug 2022 19:27:06 +0200 Subject: [PATCH] Berry stricter strict mode --- lib/libesp32/berry/src/be_parser.c | 7 ++++++- lib/libesp32/berry/src/be_var.c | 15 +++++++++++++++ lib/libesp32/berry/src/be_var.h | 1 + 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/lib/libesp32/berry/src/be_parser.c b/lib/libesp32/berry/src/be_parser.c index 3f2fc20d0..f9267d5cc 100644 --- a/lib/libesp32/berry/src/be_parser.c +++ b/lib/libesp32/berry/src/be_parser.c @@ -469,6 +469,12 @@ static int new_upval(bvm *vm, bfuncinfo *finfo, bstring *name, bexpdesc *var) static void new_var(bparser *parser, bstring *name, bexpdesc *var) { bfuncinfo *finfo = parser->finfo; + if (comp_is_strict(parser->vm)) { + /* check if we are masking a builtin */ + if (be_builtin_class_find(parser->vm, name) >= 0) { + push_error(parser, "strict: redefinition of builtin '%s'", str(name)); + } + } if (finfo->prev || finfo->binfo->prev || parser->islocal) { init_exp(var, ETLOCAL, 0); var->v.idx = new_localvar(parser, name); /* if local, contains the index in current local var list */ @@ -982,7 +988,6 @@ static void compound_assign(bparser *parser, int op, bexpdesc *l, bexpdesc *r) /* A new implicit local variable is created if no global has the same name (excluding builtins) */ /* This means that you can override a builtin silently */ /* This also means that a function cannot create a global, they must preexist or create with `global` module */ -/* TODO add warning in strict mode */ static int check_newvar(bparser *parser, bexpdesc *e) { if (e->type == ETGLOBAL) { diff --git a/lib/libesp32/berry/src/be_var.c b/lib/libesp32/berry/src/be_var.c index 1a8e5b18c..cf4ffa95b 100644 --- a/lib/libesp32/berry/src/be_var.c +++ b/lib/libesp32/berry/src/be_var.c @@ -132,6 +132,21 @@ int be_builtin_find(bvm *vm, bstring *name) return -1; /* not found */ } +/* find in the list of builtins or classes - used by strict to avoid accidental change of those */ +int be_builtin_class_find(bvm *vm, bstring *name) +{ + bvalue *res = be_map_findstr(vm, builtin(vm).vtab, name); + if (res) { + return var_toidx(res); + } else { + int idx = global_native_class_find(vm, name); + if (idx >= 0) { + return idx; + } + } + return -1; /* not found */ +} + bstring* be_builtin_name(bvm *vm, int index) { bmap *map = builtin(vm).vtab; diff --git a/lib/libesp32/berry/src/be_var.h b/lib/libesp32/berry/src/be_var.h index 6b9908a6b..565e587e3 100644 --- a/lib/libesp32/berry/src/be_var.h +++ b/lib/libesp32/berry/src/be_var.h @@ -23,6 +23,7 @@ int be_global_new(bvm *vm, bstring *name); bvalue* be_global_var(bvm *vm, int index); void be_global_release_space(bvm *vm); int be_builtin_find(bvm *vm, bstring *name); +int be_builtin_class_find(bvm *vm, bstring *name); bstring* be_builtin_name(bvm *vm, int index); int be_builtin_new(bvm *vm, bstring *name); void be_bulitin_release_space(bvm *vm);