Skip to content

Commit fbc1502

Browse files
committed
Merge pull request #841 from rhendric/for-literal-error
add robustness to generated loop code
2 parents 94de1f0 + 4a20718 commit fbc1502

File tree

3 files changed

+23
-7
lines changed

3 files changed

+23
-7
lines changed

lib/ast.js

Lines changed: 8 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/ast.ls

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -199,11 +199,13 @@ SourceNode::to-string = (...args) ->
199199
if once then [sub, ref <<< {+temp}] else [sub, ref, [ref.value]]
200200

201201
# Compiles to a variable/source pair suitable for looping.
202-
compile-loop-reference: (o, name, ret) ->
202+
compile-loop-reference: (o, name, ret, safe-access) ->
203203
if this instanceof Var and o.scope.check @value
204204
or this instanceof Unary and @op in <[ + - ]> and -1/0 < +@it.value < 1/0
205205
or this instanceof Literal and not @is-complex!
206-
return [@compile o] * 2
206+
code = @compile o, LEVEL_PAREN
207+
code = "(#code)" if safe-access and this not instanceof Var
208+
return [code] * 2
207209
asn = Assign Var(tmp = o.scope.temporary name), this
208210
ret or asn.void = true
209211
[tmp; asn.compile o, if ret then LEVEL_CALL else LEVEL_PAREN]
@@ -2352,7 +2354,7 @@ class exports.For extends While
23522354
else
23532355
@item = Var o.scope.temporary \x if @ref
23542356
if @item or @object and @own or @let
2355-
[svar, srcPart] = @source.compile-loop-reference o, \ref, not @object
2357+
[svar, srcPart] = @source.compile-loop-reference o, \ref, not @object, true
23562358
svar is srcPart or temps.push svar
23572359
else
23582360
svar = srcPart = @source.compile o, LEVEL_PAREN

test/loop.ls

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -686,3 +686,13 @@ eq 1, i
686686
o = { [k, -> v] for let k, v of {a: 1, b: 2} }
687687
eq 1 o.a!
688688
eq 2 o.b!
689+
690+
# Certain literals could result in illegal JavaScript if not carefully
691+
# handled. These are all nonsensical use cases and could just as easily
692+
# be LiveScript syntax errors. The thing to avoid is for them to be JavaScript
693+
# syntax errors; lsc should never produce illegal JavaScript on any input,
694+
# silly or otherwise.
695+
deep-equal [] [0 for x in 42]
696+
deep-equal [] [0 for x in -42]
697+
throws "Cannot read property 'length' of null" -> [0 for x in null]
698+
throws "Cannot read property 'length' of undefined" -> [0 for x in void]

0 commit comments

Comments
 (0)