Allow call and unary expressions as map keys.

This commit is contained in:
Bob Nystrom
2015-12-22 16:00:50 -08:00
parent 55beda3ea9
commit 1ebc711c30
3 changed files with 30 additions and 1 deletions

View File

@ -1987,7 +1987,7 @@ static void map(Compiler* compiler, bool allowAssignment)
if (peek(compiler) == TOKEN_RIGHT_BRACE) break;
// The key.
parsePrecedence(compiler, false, PREC_PRIMARY);
parsePrecedence(compiler, false, PREC_UNARY);
consume(compiler, TOKEN_COLON, "Expect ':' after map key.");
ignoreNewlines(compiler);

View File

@ -0,0 +1,3 @@
var map = {
1 + 2: "bad key" // expect error
}

View File

@ -0,0 +1,26 @@
var name = "value"
var map = {
// Primary.
name: name,
1: true,
// Call.
name.count: name.count,
name[0]: name[1],
// Unary.
-1: -2,
~3: !false,
// Allow any expression for a value.
"key": true ? 1 : 2
}
System.print(map[name]) // expect: value
System.print(map[1]) // expect: true
System.print(map[name.count]) // expect: 5
System.print(map[name[0]]) // expect: a
System.print(map[-1]) // expect: -2
System.print(map[~3]) // expect: true
System.print(map["key"]) // expect: 1