Skip to content

Commit

Permalink
Merge pull request #1592 from DanielXMoore/range-assign
Browse files Browse the repository at this point in the history
Fix range `for` loop with complex left-hand side
  • Loading branch information
edemaine authored Nov 11, 2024
2 parents 8eb4aaf + 5722bc8 commit 86f2b30
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
20 changes: 9 additions & 11 deletions source/parser/for.civet
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type {
AssignmentExpression
ASTNode
ASTNodeObject
ASTLeaf
Expand Down Expand Up @@ -184,23 +185,20 @@ function forRange(
ascDec = [", ", ascRef, " = ", startRef, " <= ", endRef]

let varAssign: ASTNode[] = [], varLetAssign = varAssign, varLet = varAssign, blockPrefix
let names: string[] = forDeclaration?.names
if forDeclaration?.decl // var/let/const declaration of variable
if forDeclaration.decl is "let"
let names: string[] = forDeclaration?.names ?? []
if forDeclaration?
if forDeclaration.type is "AssignmentExpression" // Coffee-style for loop
varAssign = varLetAssign = [forDeclaration, " = "]
names = [] // assigned but not declared
else if forDeclaration.decl is "let" // let: declare within loop
varName := forDeclaration.children.splice(1) // strip let
varAssign = [...trimFirstSpace(varName), " = "]
varAssign = [...trimFirstSpace(varName) as ASTNode[], " = "]
varLet = [",", ...varName, " = ", counterRef]
else // const or var: put inside loop
// TODO: missing indentation
else // const or var or assignment like `for x[y] of z`: put inside loop
value := "StringLiteral" is start.subtype ? ["String.fromCharCode(", counterRef, ")"] : counterRef
blockPrefix = [
["", [forDeclaration, " = ", value], ";"]
]
else if forDeclaration // Coffee-style for loop
assert.equal forDeclaration.type, "AssignmentExpression",
"Internal error: Coffee-style for loop must be an assignment expression"
varAssign = varLetAssign = [forDeclaration, " = "]
names = [] // assigned but not declared

declaration := {
type: "Declaration"
Expand Down
8 changes: 8 additions & 0 deletions test/for.civet
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,14 @@ describe "for", ->
}
"""

testCase """
range with access assignment
---
for chosen[i] of [0...10]
---
for (let i1 = 0; i1 < 10; ++i1) {chosen[i] = i1;;}
"""

testCase """
infinite range
---
Expand Down

0 comments on commit 86f2b30

Please sign in to comment.