You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: derive/README.md
+142Lines changed: 142 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -369,3 +369,145 @@ The `default` attribute generates code that:
369
369
3. If parsing fails with other errors, propagates the error
370
370
371
371
This provides a clean, type-safe way to handle optional grammar elements while keeping your AST representation simple and avoiding the complexity of `Option<T>` handling.
372
+
373
+
## Advanced Patterns: Enums, Nested Choices, and Repetitions
374
+
375
+
For more complex grammars involving operators and expression parsing, pest-ast provides patterns for handling:
376
+
377
+
1.**Parsing into enums** - representing grammar alternatives
378
+
2.**Nested choices** - patterns like `(plus | minus)`
379
+
3.**Repetitions of anonymous sequences** - patterns like `(operator ~ operand)*`
380
+
381
+
### Parsing into Enums
382
+
383
+
When your grammar has alternatives (using `|`), you can use enums to represent them.
384
+
385
+
**Example Grammar:**
386
+
```pest
387
+
abc = { a | b | c }
388
+
a = { "a" }
389
+
b = { "b" }
390
+
c = { "c" }
391
+
```
392
+
393
+
**Rust AST:**
394
+
```rust
395
+
#[derive(FromPest)]
396
+
#[pest_ast(rule(Rule::a))]
397
+
structA;
398
+
399
+
#[derive(FromPest)]
400
+
#[pest_ast(rule(Rule::b))]
401
+
structB;
402
+
403
+
#[derive(FromPest)]
404
+
#[pest_ast(rule(Rule::c))]
405
+
structC;
406
+
407
+
// Enum uses the parent rule that contains the choice
408
+
#[derive(FromPest)]
409
+
#[pest_ast(rule(Rule::abc))]
410
+
enumAbc {
411
+
A(A),
412
+
B(B),
413
+
C(C),
414
+
}
415
+
```
416
+
417
+
See `derive/examples/simple_enum_derives.rs` for a complete example.
418
+
419
+
### Nested Choices with Manual FromPest
420
+
421
+
For patterns like `arith_expr = { term ~ ((plus | minus) ~ term)* }`, the `(plus | minus)` choice
422
+
doesn't have its own grammar rule. You can handle this by implementing `FromPest` manually:
0 commit comments