Skip to content

Commit

Permalink
Basic Object Comprehension Support
Browse files Browse the repository at this point in the history
Parses and transpiles object comprehension syntax proposed in issue DanielXMoore#439

Tested only in limited contexts, of the 4 tests added one is failing
  • Loading branch information
peey committed Nov 2, 2024
1 parent b1297f8 commit ca2577d
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
14 changes: 14 additions & 0 deletions source/parser.hera
Original file line number Diff line number Diff line change
Expand Up @@ -3284,6 +3284,20 @@ ObjectLiteral
BracedObjectLiteral
NestedImplicitObjectLiteral
InlineObjectLiteral
ObjectComprehension

ObjectComprehension
OpenBrace __ "for" _ Identifier:id _ "of" _ Expression:exp __ ObjectComprehensionProps:props __ CloseBrace ->
return ["(()=>{const _results = {};\n",
"for (const ", id, " of ", exp, ") {\n",
"Object.assign(_results, {\n",
props, "\n",
"})}; return _results})()"
]

ObjectComprehensionProps
(ComputedPropertyName __ ":" __ Expression __)+ ->
return $0.map(entry => entry.concat([","]))

BracedObjectLiteral
OpenBrace:open AllowAll ( BracedObjectLiteralContent __ CloseBrace )? RestoreAll ->
Expand Down
72 changes: 72 additions & 0 deletions test/object-comprehensions.civet
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
{ testCase } from ./helper.civet

describe "object comprehensions", ->
testCase """
1
---
{
for x of [1, 2, 3]
[x]: 2 * x
[x * 2]: 4 * x
}
---
(()=>{const _results = {};
for (const x of [1, 2, 3]) {
Object.assign(_results, {
[x]: 2 * x
,[x * 2]: 4 * x
,
})}; return _results})()
"""

testCase """
scoping
---
{
for _results of [1]
[_results]: 2 * _results
[_results * 2]: 4 * _results
}
---
(()=>{const _results = {};
for (const _results of [1]) {
Object.assign(_results, {
[_results]: 2 * _results
,[_results * 2]: 4 * _results
,
})}; return _results})()
"""

testCase """
spacing 1
---
{ for x of [1]
[x]: 2 * x
[x * 2]: 4 * x
}
---
(()=>{const _results = {};
for (const x of [1]) {
Object.assign(_results, {
[x]: 2 * x
,[x * 2]: 4 * x
,
})}; return _results})()
"""

testCase """
spacing 2: indentation
---
{ for x of [1]
[x]: 2 * x
[x * 2]: 4 * x
}
---
(()=>{const _results = {};
for (const x of [1]) {
Object.assign(_results, {
[x]: 2 * x
,[x * 2]: 4 * x
,
})}; return _results})()
"""

0 comments on commit ca2577d

Please sign in to comment.