Skip to content

Commit

Permalink
Fix for key: T, value in loop to define value using typed key
Browse files Browse the repository at this point in the history
Helps with #1562
  • Loading branch information
edemaine committed Nov 2, 2024
1 parent b1297f8 commit e9c2959
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
5 changes: 2 additions & 3 deletions civet.dev/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1758,9 +1758,8 @@ for own key in object
You can add types to the declarations (unlike TypeScript):
<Playground>
for var key: string, value: unknown in object
console.log key, JSON.stringify value
key ?= "no last key"
for key: keyof typeof object, value in object
process key, value
</Playground>
### Loop Expressions
Expand Down
14 changes: 10 additions & 4 deletions source/parser/for.civet
Original file line number Diff line number Diff line change
Expand Up @@ -338,17 +338,18 @@ function processForInOf($0: [
children: [declaration, " = ", itemRef]
names: declaration.names
}, ";"]
pattern = itemRef
declaration =
type: "ForDeclaration"
binding: {
type: "Binding"
pattern
children: [ pattern ]
pattern: itemRef
children: [ itemRef ]
names: []
}
children: ["const ", itemRef]
names: []
unless pattern.type is "Identifier"
pattern = itemRef

unless declaration2 or own
return {
Expand Down Expand Up @@ -392,7 +393,12 @@ function processForInOf($0: [
if decl2
blockPrefix.push ["", {
type: "Declaration"
children: [trimFirstSpace(ws2), decl2, " = ", trimFirstSpace(expRef), "[", trimFirstSpace(pattern), "]"]
children: [
trimFirstSpace(ws2), decl2, " = "
trimFirstSpace(expRef)
"[", trimFirstSpace(pattern), "]"
]
decl: decl2
names: decl2.names
}, ";"]

Expand Down
13 changes: 12 additions & 1 deletion test/types/for.civet
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,22 @@ describe "[TS] for", ->
for x: T, y in z
console.log x, y
---
for (const key in z) {const x: T = key;const y = z[key];
for (const key in z) {const x: T = key;const y = z[x];
console.log(x, y)
}
"""

testCase """
destructuring for..in with two declarations
---
for [a, b]: T, value in z
console.log x
---
for (const key in z) {const [a, b]: T = key;const value = z[key];
console.log(x)
}
"""

testCase """
parenthesized
---
Expand Down

0 comments on commit e9c2959

Please sign in to comment.