Skip to content

Commit e2a8ce3

Browse files
committed
Allow multiple patterns to be specified
1 parent fb62407 commit e2a8ce3

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

spec/e2e/match/valid.lit

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
11
fn number_as_word do match it {
22
2 then "two"
33
1 then "one"
4+
3, 4 then "three or four"
45
_ then "too big"
56
}
67

78
debug(number_as_word(1)) # expect: "one"
89
debug(number_as_word(2)) # expect: "two"
9-
debug(number_as_word(3)) # expect: "too big"
10+
debug(number_as_word(3)) # expect: "three or four"
11+
debug(number_as_word(4)) # expect: "three or four"
12+
debug(number_as_word(5)) # expect: "too big"
1013

1114
fn word_to_number do match it {
15+
"zero",
16+
"none", then 0
1217
"one" then 1
1318
"two" then 2
14-
_ then 0
19+
_ then -1
1520
}
1621
debug(word_to_number("one")) # expect: 1
1722
debug(word_to_number("two")) # expect: 2
18-
debug(word_to_number("other")) # expect: 0
23+
debug(word_to_number("zero")) # expect: 0
24+
debug(word_to_number("none")) # expect: 0
25+
debug(word_to_number("other")) # expect: -1
1926

2027
fn is_empty do match it {
2128
[] then true

src/lit/parser.cr

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -326,10 +326,18 @@ module Lit
326326
branches = [] of Tuple(Expr, Expr)
327327

328328
until check(TokenType::RIGHT_BRACE) || at_end?
329-
pattern = expression
329+
patterns = [expression] of Expr
330+
while match?(TokenType::COMMA)
331+
ignore_newlines
332+
# Allow trailing comma by checking if we're at the end of the match block
333+
break if check(TokenType::THEN)
334+
patterns << expression
335+
end
336+
330337
consume(TokenType::THEN, "I was expecting 'then' after the match pattern.")
331338

332-
branches << {pattern, expression}
339+
body = expression
340+
branches += patterns.map { |p| {p, body}.as(Tuple(Expr, Expr)) }
333341
consume_line("I was expecting a newline after the match case.")
334342

335343
ignore_newlines

0 commit comments

Comments
 (0)