Skip to content

Commit 8ab351b

Browse files
committed
docs: add example usage of conflicts
1 parent 7668192 commit 8ab351b

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

docs/src/creating-parsers/3-writing-the-grammar.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,69 @@ This is where `prec.left` and `prec.right` come into use. We want to select the
291291
}
292292
```
293293

294+
## Using Conflicts
295+
296+
Sometimes, conflicts are actually desirable. In our JavaScript grammar, expressions and patterns can create intentional ambiguity.
297+
A construct like `[x, y]` could be legitimately parsed as both an array literal (like in `let a = [x, y]`) or as a destructuring
298+
pattern (like in `let [x, y] = arr`).
299+
300+
```js
301+
module.exports = grammar({
302+
name: "javascript",
303+
304+
rules: {
305+
expression: $ => choice(
306+
$.identifier,
307+
$.array,
308+
$.pattern,
309+
),
310+
311+
array: $ => seq(
312+
"[",
313+
optional(seq(
314+
$.expression, repeat(seq(",", $.expression))
315+
)),
316+
"]"
317+
),
318+
319+
array_pattern: $ => seq(
320+
"[",
321+
optional(seq(
322+
$.pattern, repeat(seq(",", $.pattern))
323+
)),
324+
"]"
325+
),
326+
327+
pattern: $ => choice(
328+
$.identifier,
329+
$.array_pattern,
330+
),
331+
},
332+
})
333+
```
334+
335+
In such cases, we want the parser to explore both possibilities by explicitly declaring this ambiguity:
336+
337+
```js
338+
{
339+
name: "javascript",
340+
341+
conflicts: $ => [
342+
[$.array, $.array_pattern],
343+
],
344+
345+
rules: {
346+
// ...
347+
},
348+
}
349+
```
350+
351+
```admonish note
352+
The example is a bit contrived for the purpose of illustrating the usage of conflicts. The actual JavaScript grammar isn't
353+
structured like that, but this conflict is actually present in the
354+
[Tree-sitter JavaScript grammar](https://github.com/tree-sitter/tree-sitter-javascript/blob/108b2d4d17a04356a340aea809e4dd5b801eb40d/grammar.js#L100).
355+
```
356+
294357
## Hiding Rules
295358

296359
You may have noticed in the above examples that some grammar rule name like `_expression` and `_type` began with an underscore.

0 commit comments

Comments
 (0)