Skip to content

Commit

Permalink
Support multidimensional subscripts
Browse files Browse the repository at this point in the history
This change allows commas inside subscripts.

```cpp
auto x = a[1, 2, 3];
```

From C++23, array subscripts work like arguments to `operator[]` as an n-ary
function.

Before C++23, `operator[]` must be a unary function, but before C++20, it's
possible to use the comma operator inside subscript expressions - and this is
done in libraries that use expression templates to achieve multidimensional
array syntax.

Use of the comma operator in subscript expressions was deprecated in C++20 to
make way for the C++23 change to n-ary `operator[]`.
  • Loading branch information
elbeno committed Aug 6, 2023
1 parent f88bf81 commit 472002f
Show file tree
Hide file tree
Showing 5 changed files with 318,112 additions and 316,202 deletions.
9 changes: 6 additions & 3 deletions grammar.js
Original file line number Diff line number Diff line change
Expand Up @@ -880,11 +880,14 @@ module.exports = grammar(C, {

subscript_expression: $ => prec(PREC.SUBSCRIPT, seq(
field('argument', $._expression),
'[',
field('index', choice($._expression, $.initializer_list)),
']',
field('indices', $.subscript_argument_list),
)),

subscript_argument_list: $ => seq(
'[',
commaSep(choice($._expression, $.initializer_list)),
']',
),

call_expression: ($, original) => choice(original, seq(
field('function', $.primitive_type),
Expand Down
87 changes: 67 additions & 20 deletions src/grammar.json
Original file line number Diff line number Diff line change
Expand Up @@ -6860,30 +6860,13 @@
"name": "_expression"
}
},
{
"type": "STRING",
"value": "["
},
{
"type": "FIELD",
"name": "index",
"name": "indices",
"content": {
"type": "CHOICE",
"members": [
{
"type": "SYMBOL",
"name": "_expression"
},
{
"type": "SYMBOL",
"name": "initializer_list"
}
]
"type": "SYMBOL",
"name": "subscript_argument_list"
}
},
{
"type": "STRING",
"value": "]"
}
]
}
Expand Down Expand Up @@ -11439,6 +11422,70 @@
}
]
},
"subscript_argument_list": {
"type": "SEQ",
"members": [
{
"type": "STRING",
"value": "["
},
{
"type": "CHOICE",
"members": [
{
"type": "SEQ",
"members": [
{
"type": "CHOICE",
"members": [
{
"type": "SYMBOL",
"name": "_expression"
},
{
"type": "SYMBOL",
"name": "initializer_list"
}
]
},
{
"type": "REPEAT",
"content": {
"type": "SEQ",
"members": [
{
"type": "STRING",
"value": ","
},
{
"type": "CHOICE",
"members": [
{
"type": "SYMBOL",
"name": "_expression"
},
{
"type": "SYMBOL",
"name": "initializer_list"
}
]
}
]
}
}
]
},
{
"type": "BLANK"
}
]
},
{
"type": "STRING",
"value": "]"
}
]
},
"co_await_expression": {
"type": "PREC_LEFT",
"value": 14,
Expand Down
Loading

0 comments on commit 472002f

Please sign in to comment.