Allow 'for (const i in [1,2,3])' which failed with 'can't write const' error before

This commit is contained in:
Gordon Williams 2022-05-26 13:00:29 +01:00
parent 6130edfa35
commit 2645dcb7c7
2 changed files with 36 additions and 0 deletions

View File

@ -2535,6 +2535,7 @@ NO_INLINE JsVar *jspeStatementFor() {
JsVar *oldBlockScope = jspeBlockStart();
// initialisation
JsVar *forStatement = 0;
bool startsWithConst = lex->tk==LEX_R_CONST;
// we could have 'for (;;)' - so don't munch up our semicolon if that's all we have
if (lex->tk != ';')
forStatement = jspeStatement();
@ -2606,8 +2607,11 @@ NO_INLINE JsVar *jspeStatementFor() {
assert(jsvGetRefs(iteratorValue)==0);
}
if (isForOf || iteratorValue) { // could be out of memory
// Now write the value to our iterator
assert(!jsvIsName(iteratorValue));
if (startsWithConst) forStatement->flags &= ~JSV_CONSTANT; // for (const i in [1,2,3]) has to work
jsvReplaceWithOrAddToRoot(forStatement, iteratorValue);
if (startsWithConst) forStatement->flags |= JSV_CONSTANT;
if (iteratorValue!=loopIndexVar) jsvUnLock(iteratorValue);
jslSeekToP(&forBodyStart);

32
tests/test_const.js Normal file
View File

@ -0,0 +1,32 @@
var results = [];
const x = 42;
try {
x = 43;
results.push(false);
} catch (e) {
results.push(true);
}
const y = 42;
try {
y += 1;
results.push(false);
} catch (e) {
results.push(true);
}
// Normal FOR loops fail
try {
for (const z=0;z<5;z++);
results.push(false);
} catch (e) {
results.push(true);
}
// FOR..IN loops are ok
for (const w in [1,2,3]) ;
print(results);
result = results.every(x=>x);