Skip to content

Commit

Permalink
Fix len
Browse files Browse the repository at this point in the history
  • Loading branch information
alehander92 committed Dec 6, 2018
1 parent 0689c20 commit 2935f8a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
25 changes: 21 additions & 4 deletions src/gara.nim
Expand Up @@ -132,7 +132,7 @@ proc loadManyPattern(pattern: NimNode, input: NimNode, i: int, capture: int = -1
`test` and `assign`
result = (test, newCode, 0)

proc loadList(pattern: NimNode, input: NimNode, capture: int = -1): (NimNode, NimNode) =
proc loadList(pattern: NimNode, input: NimNode, capture: int = -1, isArray: bool = false): (NimNode, NimNode) =
# sequence or array match: it matches its elements
# generates:
#
Expand Down Expand Up @@ -174,7 +174,17 @@ proc loadList(pattern: NimNode, input: NimNode, capture: int = -1): (NimNode, Ni
t = quote do: `t` and `elementTest`
newCode.add(elementCode)
let minTest = quote do: `input`.len >= `min`
test = quote do: `minTest` and `t`
if not isArray:
test = quote do: `minTest` and `t`
else:
test = quote:
when `minTest`:
`t`
else:
false
newCode = quote:
when `minTest`:
`newCode`

result = (test, newCode)

Expand Down Expand Up @@ -248,7 +258,7 @@ proc load(pattern: NimNode, input: NimNode, capture: int = -1): (NimNode, NimNod
# newCode.add(elementCode)

of nnkBracket:
(test, newCode) = loadList(pattern, input, capture)
(test, newCode) = loadList(pattern, input, capture, isArray=true)

of nnkPrefix:
# @object or ~object
Expand Down Expand Up @@ -550,7 +560,13 @@ proc matchBranch(branch: NimNode, input: NimNode, capture: int = -1): (NimNode,
# echo code.treerepr
assignNames = @[]
var (test, newCode) = load(pattern, input, capture)
newCode = code #.add(code)
if newCode.kind == nnkWhenStmt:
let whenTest = newCode[0][0]
newCode = quote:
when `whenTest`:
`code`
else:
newCode = code
result = (nnkElIfBranch.newTree(test, newCode), false)
else:
# echo branch.treerepr
Expand Down Expand Up @@ -624,6 +640,7 @@ macro maybeMatches*(input: untyped, pattern: untyped): untyped =
else:
tmp = none[(`tupleInit`).type]()
tmp
# echo result.repr

macro match*(input: typed, branches: varargs[untyped]): untyped =
if branches.len == 0:
Expand Down
8 changes: 5 additions & 3 deletions tests/test_gara.nim
Expand Up @@ -247,6 +247,7 @@ suite "match":

match a:
[1, @a, 3, @b, 5]:
echo a
fail()
[1, @a, 3, @b]:
check(a == 2 and b == 4)
Expand All @@ -265,11 +266,12 @@ suite "matches":
test "option":
let a = Rectangle(a: 0, b: 0)

let c = a.maybeMatches((a: @a, b: @b))
# don't use things that clash with env? huh, TODO
let c = a.maybeMatches((a: @a2, b: @b2))
check(c.isSome)
let g = c.get
check(g.a == 0)
check(g.b == 0)
check(g.a2 == 0)
check(g.b2 == 0)


# TODO
Expand Down

0 comments on commit 2935f8a

Please sign in to comment.