Skip to content

Commit

Permalink
Fix for empty destructuring patterns
Browse files Browse the repository at this point in the history
  • Loading branch information
wcjohnson committed Jun 20, 2017
1 parent 7f8327e commit 5e36dd3
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 9 deletions.
7 changes: 6 additions & 1 deletion src/destructure.lsc
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ export matchesDestructuringPattern(ref, pattern) ->
| "ArrayPattern": ref~matchesArrayPattern(pattern)
| "ObjectPattern": ref~matchesObjectPattern(pattern)

export isNonEmptyPattern(pattern) ->
match pattern.type:
| "ArrayPattern": pattern.elements?.length > 0
| "ObjectPattern": pattern.properties?.length > 0

////////// Array pattern matching
Bracket(array, i, element) ->
t.memberExpression(
Expand All @@ -23,7 +28,7 @@ Bracket(array, i, element) ->
)~atNode(element)

HasLength(array, min, max, patternNode) ->
args = if max:
args = if max~looseNotEq(null):
[ array, t.numericLiteral(min)~atNode(patternNode), t.numericLiteral(max)~atNode(patternNode) ]
elif min > 0:
[ array, t.numericLiteral(min)~atNode(patternNode) ]
Expand Down
4 changes: 2 additions & 2 deletions src/match.lsc
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import t from './types'
import { toBlockStatement } from './blocks'
import { isa } from './is'
import { undeclaredRef } from './ref'
import { matchesDestructuringPattern, accessors } from './destructure'
import { matchesDestructuringPattern, accessors, isNonEmptyPattern } from './destructure'
import { createAndExpression as And, createOrExpression as Or } from './logical'
import { runtime } from './runtime'
import { checkFalsePositiveReference } from './variables'
Expand Down Expand Up @@ -114,7 +114,7 @@ transformBoundConsequent({discriminantRef}, binding, consequent) ->

transformMatchConsequent(mtch, casePath) ->
{ binding, consequent } = casePath.node
if binding:
if binding and binding~isNonEmptyPattern():
mtch~transformBoundConsequent(binding, consequent)
else:
consequent~toBlockStatement()
Expand Down
8 changes: 4 additions & 4 deletions test/fixtures/match/arr-pattern/exec.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ assert.equal(
"empty"
)
assert.equal(
"empty",
match []:
| with []:
"empty"
"nonempty",
match [1]:
| with []: "empty"
| with [first]: "nonempty"
)
assert.equal(
undefined,
Expand Down
3 changes: 1 addition & 2 deletions test/fixtures/match/arr-pattern/expected.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const _hasLength = require('@oigroup/lightscript-runtime/hasLength');
if (_hasLength(x)) {
const [] = x;
if (_hasLength(x, 0, 0)) {
"empty";
} else if (_hasLength(x, 2, 2)) {
const [a, b] = x;
Expand Down

0 comments on commit 5e36dd3

Please sign in to comment.