Skip to content

Commit 67a6457

Browse files
committed
Add symbol-string shorthand syntax for maps
1 parent b6b1236 commit 67a6457

File tree

5 files changed

+26
-6
lines changed

5 files changed

+26
-6
lines changed

CHANGELOG.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
11
## Unreleased - [Full diff](https://github.com/lit-lang/lit/compare/v0.2.0...main)
22

3+
- Add symbol-string shorthand syntax for maps
4+
5+
```lit
6+
let user = {
7+
name: "Alice",
8+
}
9+
10+
# same as { "name": "Alice" }
11+
# or even { :name : "Alice" }
12+
```
13+
314
- Allow break to return a value
415

516
```lit

spec/e2e/map.lit

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,6 @@ m2[1.0] = 3
2727
println(m3) # expect: {"key" : 1, 1.0 : 2}
2828

2929
# merging overwrites same keys
30-
println(m3.merge({"key" : 2})) # expect: {"key" : 2, 1.0 : 2}
30+
println(m3.merge({key: 2})) # expect: {"key" : 2, 1.0 : 2}
3131

3232
m.merge(1) # error: [line 32] Runtime error: I was expecting a Map, but got Integer.

src/lit/parser.cr

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -545,8 +545,12 @@ module Lit
545545

546546
loop do
547547
ignore_newlines
548-
key = expression
549-
consume(TokenType::COLON, "I was expecting a ':' after a map key.")
548+
if match?(TokenType::SYMBOL)
549+
key = Expr::Literal.new(previous.literal)
550+
else
551+
key = expression
552+
consume(TokenType::COLON, "I was expecting a ':' after a map key.")
553+
end
550554
value = expression
551555
ignore_newlines
552556

src/lit/scanner.cr

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -294,9 +294,14 @@ module Lit
294294
end
295295

296296
text = @src[@token_start_pos...@current_pos]
297-
type = keyword_from(text) || TokenType::IDENTIFIER
298297

299-
add_token(type)
298+
if peek == ':' # symbol-like string shortcut for maps
299+
advance
300+
add_token(TokenType::SYMBOL, text)
301+
else
302+
type = keyword_from(text) || TokenType::IDENTIFIER
303+
add_token(type)
304+
end
300305
end
301306

302307
private def peek : Char

src/lit/token_type.cr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ module Lit
1414
PIPE_GREATER
1515

1616
# Literals
17-
NUMBER; STRING; IDENTIFIER; STRING_INTERPOLATION
17+
NUMBER; STRING; IDENTIFIER; STRING_INTERPOLATION; SYMBOL
1818

1919
# Keywords
2020
AND; DO; ELSE; FALSE; FN; IF; VAR; LET; NIL; OR; PRINT; PRINTLN; RETURN; TRUE; TYPE; SELF; WHILE; UNTIL; LOOP; BREAK; NEXT

0 commit comments

Comments
 (0)