-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathparse.rs
More file actions
2378 lines (2110 loc) · 76.4 KB
/
parse.rs
File metadata and controls
2378 lines (2110 loc) · 76.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module contains the parsing code to convert the
//! tokens into an AST.
use std::fmt;
use std::num::NonZeroUsize;
use std::str::FromStr;
use std::sync::Arc;
use chumsky::input::{Input, ValueInput};
use chumsky::prelude::{
any, choice, empty, just, nested_delimiters, none_of, one_of, recursive, skip_then_retry_until,
via_parser,
};
use chumsky::{extra, select, IterParser, Parser};
use either::Either;
use miniscript::iter::{Tree, TreeLike};
use crate::error::ErrorCollector;
use crate::error::{Error, RichError, Span};
use crate::impl_eq_hash;
use crate::lexer::Token;
use crate::num::NonZeroPow2Usize;
use crate::pattern::Pattern;
use crate::str::{
AliasName, Binary, Decimal, FunctionName, Hexadecimal, Identifier, JetName, ModuleName,
WitnessName,
};
use crate::types::{AliasedType, BuiltinAlias, TypeConstructible, UIntType};
/// A program is a sequence of items.
#[derive(Clone, Debug)]
pub struct Program {
items: Arc<[Item]>,
span: Span,
}
impl Program {
/// Access the items of the program.
pub fn items(&self) -> &[Item] {
&self.items
}
}
impl_eq_hash!(Program; items);
/// An item is a component of a program.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum Item {
/// A type alias.
TypeAlias(TypeAlias),
/// A function.
Function(Function),
/// A module, which is ignored.
Module,
}
/// Definition of a function.
#[derive(Clone, Debug)]
pub struct Function {
name: FunctionName,
params: Arc<[FunctionParam]>,
ret: Option<AliasedType>,
body: Expression,
span: Span,
}
impl Function {
/// Access the name of the function.
pub fn name(&self) -> &FunctionName {
&self.name
}
/// Access the parameters of the function.
pub fn params(&self) -> &[FunctionParam] {
&self.params
}
/// Access the return type of the function.
///
/// An empty return type means that the function returns the unit value.
pub fn ret(&self) -> Option<&AliasedType> {
self.ret.as_ref()
}
/// Access the body of the function.
pub fn body(&self) -> &Expression {
&self.body
}
/// Access the span of the function.
pub fn span(&self) -> &Span {
&self.span
}
}
impl_eq_hash!(Function; name, params, ret, body);
/// Parameter of a function.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct FunctionParam {
identifier: Identifier,
ty: AliasedType,
}
impl FunctionParam {
/// Access the identifier of the parameter.
pub fn identifier(&self) -> &Identifier {
&self.identifier
}
/// Access the type of the parameter.
pub fn ty(&self) -> &AliasedType {
&self.ty
}
}
/// A statement is a component of a block expression.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum Statement {
/// A declaration of variables inside a pattern.
Assignment(Assignment),
/// An expression that returns nothing (the unit value).
Expression(Expression),
}
/// The output of an expression is assigned to a pattern.
#[derive(Clone, Debug)]
pub struct Assignment {
pattern: Pattern,
ty: AliasedType,
expression: Expression,
span: Span,
}
impl Assignment {
/// Access the pattern of the assignment.
pub fn pattern(&self) -> &Pattern {
&self.pattern
}
/// Access the return type of assigned expression.
pub fn ty(&self) -> &AliasedType {
&self.ty
}
/// Access the assigned expression.
pub fn expression(&self) -> &Expression {
&self.expression
}
/// Access the span of the expression.
pub fn span(&self) -> &Span {
&self.span
}
}
impl_eq_hash!(Assignment; pattern, ty, expression);
/// Call expression.
#[derive(Clone, Debug)]
pub struct Call {
name: CallName,
args: Arc<[Expression]>,
span: Span,
}
impl Call {
/// Access the name of the call.
pub fn name(&self) -> &CallName {
&self.name
}
/// Access the arguments to the call.
pub fn args(&self) -> &[Expression] {
self.args.as_ref()
}
/// Access the span of the call.
pub fn span(&self) -> &Span {
&self.span
}
}
impl_eq_hash!(Call; name, args);
/// Name of a call.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum CallName {
/// Name of a jet.
Jet(JetName),
/// [`Either::unwrap_left`].
UnwrapLeft(AliasedType),
/// [`Either::unwrap_right`].
UnwrapRight(AliasedType),
/// [`Option::unwrap`].
Unwrap,
/// [`Option::is_none`].
IsNone(AliasedType),
/// [`assert!`].
Assert,
/// [`panic!`] without error message.
Panic,
/// [`dbg!`].
Debug,
/// Cast from the given source type.
TypeCast(AliasedType),
/// Name of a custom function.
Custom(FunctionName),
/// Fold of a bounded list with the given function.
Fold(FunctionName, NonZeroPow2Usize),
/// Fold of an array with the given function.
ArrayFold(FunctionName, NonZeroUsize),
/// Loop over the given function a bounded number of times until it returns success.
ForWhile(FunctionName),
}
/// A type alias.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct TypeAlias {
name: AliasName,
ty: AliasedType,
span: Span,
}
impl TypeAlias {
/// Access the name of the alias.
pub fn name(&self) -> &AliasName {
&self.name
}
/// Access the type that the alias resolves to.
///
/// During the parsing stage, the resolved type may include aliases.
/// The compiler will later check if all contained aliases have been declared before.
pub fn ty(&self) -> &AliasedType {
&self.ty
}
/// Access the span of the alias.
pub fn span(&self) -> &Span {
&self.span
}
}
impl_eq_hash!(TypeAlias; name, ty);
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum UIntBound {
Min,
Max,
}
impl UIntBound {
pub const fn as_str(self) -> &'static str {
match self {
Self::Min => "MIN",
Self::Max => "MAX",
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum TypeBound {
UInt(UIntType, UIntBound),
}
/// An expression is something that returns a value.
#[derive(Clone, Debug)]
pub struct Expression {
inner: ExpressionInner,
span: Span,
}
impl Expression {
/// Access the inner expression.
pub fn inner(&self) -> &ExpressionInner {
&self.inner
}
/// Access the span of the expression.
pub fn span(&self) -> &Span {
&self.span
}
/// Convert the expression into a block expression.
#[cfg(feature = "arbitrary")]
fn into_block(self) -> Self {
match self.inner {
ExpressionInner::Single(_) => Expression {
span: self.span,
inner: ExpressionInner::Block(Arc::from([]), Some(Arc::new(self))),
},
_ => self,
}
}
pub fn empty(span: Span) -> Self {
Self {
inner: ExpressionInner::Single(SingleExpression {
inner: SingleExpressionInner::Tuple(Arc::new([])),
span,
}),
span,
}
}
}
impl_eq_hash!(Expression; inner);
/// The kind of expression.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum ExpressionInner {
/// A single expression directly returns a value.
Single(SingleExpression),
/// A block expression first executes a series of statements inside a local scope.
/// Then, the block returns the value of its final expression.
/// The block returns nothing (unit) if there is no final expression.
Block(Arc<[Statement]>, Option<Arc<Expression>>),
}
/// A single expression directly returns a value.
#[derive(Clone, Debug)]
pub struct SingleExpression {
inner: SingleExpressionInner,
span: Span,
}
impl SingleExpression {
/// Access the inner expression.
pub fn inner(&self) -> &SingleExpressionInner {
&self.inner
}
/// Access the span of the expression.
pub fn span(&self) -> &Span {
&self.span
}
}
impl_eq_hash!(SingleExpression; inner);
/// The kind of single expression.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum SingleExpressionInner {
/// Either wrapper expression
Either(Either<Arc<Expression>, Arc<Expression>>),
/// Option wrapper expression
Option(Option<Arc<Expression>>),
/// Boolean literal expression
Boolean(bool),
/// Decimal string literal.
Decimal(Decimal),
/// Binary string literal.
Binary(Binary),
/// Hexadecimal string literal.
Hexadecimal(Hexadecimal),
/// Constants of a type (e.g. MAX, MIN)
TypeBound(TypeBound),
/// Witness value.
Witness(WitnessName),
/// Parameter value.
Parameter(WitnessName),
/// Variable identifier expression
Variable(Identifier),
/// Function call
Call(Call),
/// Expression in parentheses
Expression(Arc<Expression>),
/// Match expression over a sum type
Match(Match),
/// Tuple wrapper expression
Tuple(Arc<[Expression]>),
/// Array wrapper expression
Array(Arc<[Expression]>),
/// List wrapper expression
///
/// The exclusive upper bound on the list size is not known at this point
List(Arc<[Expression]>),
}
/// Match expression.
#[derive(Clone, Debug)]
pub struct Match {
scrutinee: Arc<Expression>,
left: MatchArm,
right: MatchArm,
span: Span,
}
impl Match {
/// Access the expression that is matched.
pub fn scrutinee(&self) -> &Expression {
&self.scrutinee
}
/// Access the match arm for left sum values.
pub fn left(&self) -> &MatchArm {
&self.left
}
/// Access the match arm for right sum values.
pub fn right(&self) -> &MatchArm {
&self.right
}
/// Access the span of the match statement.
pub fn span(&self) -> &Span {
&self.span
}
/// Get the type of the expression that is matched.
pub fn scrutinee_type(&self) -> AliasedType {
match (&self.left.pattern, &self.right.pattern) {
(MatchPattern::Left(_, ty_l), MatchPattern::Right(_, ty_r)) => {
AliasedType::either(ty_l.clone(), ty_r.clone())
}
(MatchPattern::None, MatchPattern::Some(_, ty_r)) => AliasedType::option(ty_r.clone()),
(MatchPattern::False, MatchPattern::True) => AliasedType::boolean(),
_ => unreachable!("Match expressions have valid left and right arms"),
}
}
}
impl_eq_hash!(Match; scrutinee, left, right);
/// Arm of a match expression.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct MatchArm {
pattern: MatchPattern,
expression: Arc<Expression>,
}
impl MatchArm {
/// Access the pattern that guards the match arm.
pub fn pattern(&self) -> &MatchPattern {
&self.pattern
}
/// Access the expression that is executed in the match arm.
pub fn expression(&self) -> &Expression {
&self.expression
}
}
/// Pattern of a match arm.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum MatchPattern {
/// Bind inner value of left value to a pattern.
Left(Pattern, AliasedType),
/// Bind inner value of right value to a pattern.
Right(Pattern, AliasedType),
/// Match none value (no binding).
None,
/// Bind inner value of some value to a pattern.
Some(Pattern, AliasedType),
/// Match false value (no binding).
False,
/// Match true value (no binding).
True,
}
impl MatchPattern {
/// Access the pattern of a match pattern that binds a variables.
pub fn as_pattern(&self) -> Option<&Pattern> {
match self {
MatchPattern::Left(i, _) | MatchPattern::Right(i, _) | MatchPattern::Some(i, _) => {
Some(i)
}
MatchPattern::None | MatchPattern::False | MatchPattern::True => None,
}
}
/// Access the pattern and the type of a match pattern that binds a variables.
pub fn as_typed_pattern(&self) -> Option<(&Pattern, &AliasedType)> {
match self {
MatchPattern::Left(i, ty) | MatchPattern::Right(i, ty) | MatchPattern::Some(i, ty) => {
Some((i, ty))
}
MatchPattern::None | MatchPattern::False | MatchPattern::True => None,
}
}
}
/// Program root when parsing modules.
#[derive(Clone, Debug)]
pub struct ModuleProgram {
items: Arc<[ModuleItem]>,
span: Span,
}
impl ModuleProgram {
/// Access the items of the program.
pub fn items(&self) -> &[ModuleItem] {
&self.items
}
/// Access the span of the program.
pub fn span(&self) -> &Span {
&self.span
}
}
impl_eq_hash!(ModuleProgram; items);
/// Item when parsing modules.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum ModuleItem {
Ignored,
Module(Module),
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct Module {
name: ModuleName,
assignments: Arc<[ModuleAssignment]>,
span: Span,
}
impl Module {
/// Access the name of the module.
pub fn name(&self) -> &ModuleName {
&self.name
}
/// Access the assignments of the module.
pub fn assignments(&self) -> &[ModuleAssignment] {
&self.assignments
}
/// Access the span of the module.
pub fn span(&self) -> &Span {
&self.span
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct ModuleAssignment {
name: WitnessName,
ty: AliasedType,
expression: Expression,
span: Span,
}
impl ModuleAssignment {
/// Access the assigned witness name.
pub fn name(&self) -> &WitnessName {
&self.name
}
/// Access the assigned witness type.
pub fn ty(&self) -> &AliasedType {
&self.ty
}
/// Access the assigned witness expression.
pub fn expression(&self) -> &Expression {
&self.expression
}
}
impl fmt::Display for Program {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for item in self.items() {
writeln!(f, "{item}")?;
}
Ok(())
}
}
impl fmt::Display for Item {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TypeAlias(alias) => write!(f, "{alias}"),
Self::Function(function) => write!(f, "{function}"),
// The parse tree contains no information about the contents of modules.
// We print a random empty module `mod witness {}` here
// so that `from_string(to_string(x)) = x` holds for all trees `x`.
Self::Module => write!(f, "mod witness {{}}"),
}
}
}
impl fmt::Display for TypeAlias {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "type {} = {};", self.name(), self.ty())
}
}
impl fmt::Display for Function {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "fn {}(", self.name())?;
for (i, param) in self.params().iter().enumerate() {
if 0 < i {
write!(f, ", ")?;
}
write!(f, "{param}")?;
}
write!(f, ")")?;
if let Some(ty) = self.ret() {
write!(f, " -> {ty}")?;
}
write!(f, " {}", self.body())
}
}
impl fmt::Display for FunctionParam {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.identifier(), self.ty())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum ExprTree<'a> {
Expression(&'a Expression),
Block(&'a [Statement], &'a Option<Arc<Expression>>),
Statement(&'a Statement),
Assignment(&'a Assignment),
Single(&'a SingleExpression),
Call(&'a Call),
Match(&'a Match),
}
impl TreeLike for ExprTree<'_> {
fn as_node(&self) -> Tree<Self> {
use SingleExpressionInner as S;
match self {
Self::Expression(expr) => match expr.inner() {
ExpressionInner::Block(statements, maybe_expr) => {
Tree::Unary(Self::Block(statements, maybe_expr))
}
ExpressionInner::Single(single) => Tree::Unary(Self::Single(single)),
},
Self::Block(statements, maybe_expr) => Tree::Nary(
statements
.iter()
.map(Self::Statement)
.chain(maybe_expr.iter().map(Arc::as_ref).map(Self::Expression))
.collect(),
),
Self::Statement(statement) => match statement {
Statement::Assignment(assignment) => Tree::Unary(Self::Assignment(assignment)),
Statement::Expression(expression) => Tree::Unary(Self::Expression(expression)),
},
Self::Assignment(assignment) => Tree::Unary(Self::Expression(assignment.expression())),
Self::Single(single) => match single.inner() {
S::Boolean(_)
| S::Binary(_)
| S::Decimal(_)
| S::Hexadecimal(_)
| S::Variable(_)
| S::TypeBound(_) => Tree::Nullary,
S::Witness(_) | S::Parameter(_) | S::Option(None) => Tree::Nullary,
S::Option(Some(l))
| S::Either(Either::Left(l))
| S::Either(Either::Right(l))
| S::Expression(l) => Tree::Unary(Self::Expression(l)),
S::Call(call) => Tree::Unary(Self::Call(call)),
S::Match(match_) => Tree::Unary(Self::Match(match_)),
S::Tuple(elements) | S::Array(elements) | S::List(elements) => {
Tree::Nary(elements.iter().map(Self::Expression).collect())
}
},
Self::Call(call) => Tree::Nary(call.args().iter().map(Self::Expression).collect()),
Self::Match(match_) => Tree::Nary(Arc::new([
Self::Expression(match_.scrutinee()),
Self::Expression(match_.left().expression()),
Self::Expression(match_.right().expression()),
])),
}
}
}
impl fmt::Display for ExprTree<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use SingleExpressionInner as S;
for data in self.verbose_pre_order_iter() {
match &data.node {
Self::Statement(..) if data.is_complete => writeln!(f, ";")?,
Self::Expression(..) | Self::Statement(..) => {}
Self::Block(..) => {
if data.n_children_yielded == 0 {
writeln!(f, "{{")?;
} else if !data.is_complete {
write!(f, " ")?;
}
if data.is_complete {
writeln!(f, "}}")?;
}
}
Self::Assignment(assignment) => match data.n_children_yielded {
0 => write!(f, "let {}: {} = ", assignment.pattern(), assignment.ty())?,
n => debug_assert_eq!(n, 1),
},
Self::Single(single) => match single.inner() {
S::Boolean(bit) => write!(f, "{bit}")?,
S::Binary(binary) => write!(f, "0b{binary}")?,
S::Decimal(decimal) => write!(f, "{decimal}")?,
S::Hexadecimal(hexadecimal) => write!(f, "0x{hexadecimal}")?,
S::Variable(name) => write!(f, "{name}")?,
S::TypeBound(TypeBound::UInt(ty, bound)) => {
write!(f, "{ty}::{}", bound.as_str())?
}
S::Witness(name) => write!(f, "witness::{name}")?,
S::Parameter(name) => write!(f, "param::{name}")?,
S::Option(None) => write!(f, "None")?,
S::Option(Some(_)) => match data.n_children_yielded {
0 => write!(f, "Some(")?,
n => {
debug_assert_eq!(n, 1);
write!(f, ")")?;
}
},
S::Either(Either::Left(_)) => match data.n_children_yielded {
0 => write!(f, "Left(")?,
n => {
debug_assert_eq!(n, 1);
write!(f, ")")?;
}
},
S::Either(Either::Right(_)) => match data.n_children_yielded {
0 => write!(f, "Right(")?,
n => {
debug_assert_eq!(n, 1);
write!(f, ")")?;
}
},
S::Expression(_) => match data.n_children_yielded {
0 => write!(f, "(")?,
n => {
debug_assert_eq!(n, 1);
write!(f, ")")?;
}
},
S::Call(..) | S::Match(..) => {}
S::Tuple(tuple) => {
if data.n_children_yielded == 0 {
write!(f, "(")?;
} else if !data.is_complete || tuple.len() == 1 {
write!(f, ", ")?;
}
if data.is_complete {
write!(f, ")")?;
}
}
S::Array(..) => {
if data.n_children_yielded == 0 {
write!(f, "[")?;
} else if !data.is_complete {
write!(f, ", ")?;
}
if data.is_complete {
write!(f, "]")?;
}
}
S::List(..) => {
if data.n_children_yielded == 0 {
write!(f, "list![")?;
} else if !data.is_complete {
write!(f, ", ")?;
}
if data.is_complete {
write!(f, "]")?;
}
}
},
Self::Call(call) => {
if data.n_children_yielded == 0 {
write!(f, "{}(", call.name())?;
} else if !data.is_complete {
write!(f, ", ")?;
}
if data.is_complete {
write!(f, ")")?;
}
}
Self::Match(match_) => match data.n_children_yielded {
0 => write!(f, "match ")?,
1 => write!(f, "{{\n{} => ", match_.left().pattern())?,
2 => write!(f, ",\n{} => ", match_.right().pattern())?,
n => {
debug_assert_eq!(n, 3);
write!(f, ",\n}}")?;
}
},
}
}
Ok(())
}
}
impl fmt::Display for Expression {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", ExprTree::Expression(self))
}
}
impl fmt::Display for Statement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", ExprTree::Statement(self))
}
}
impl fmt::Display for Assignment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", ExprTree::Assignment(self))
}
}
impl fmt::Display for SingleExpression {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", ExprTree::Single(self))
}
}
impl fmt::Display for Call {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", ExprTree::Call(self))
}
}
impl fmt::Display for CallName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CallName::Jet(jet) => write!(f, "jet::{jet}"),
CallName::UnwrapLeft(ty) => write!(f, "unwrap_left::<{ty}>"),
CallName::UnwrapRight(ty) => write!(f, "unwrap_right::<{ty}>"),
CallName::Unwrap => write!(f, "unwrap"),
CallName::IsNone(ty) => write!(f, "is_none::<{ty}>"),
CallName::Assert => write!(f, "assert!"),
CallName::Panic => write!(f, "panic!"),
CallName::Debug => write!(f, "dbg!"),
CallName::TypeCast(ty) => write!(f, "<{ty}>::into"),
CallName::Custom(name) => write!(f, "{name}"),
CallName::Fold(name, bound) => write!(f, "fold::<{name}, {bound}>"),
CallName::ArrayFold(name, size) => write!(f, "array_fold::<{name}, {size}>"),
CallName::ForWhile(name) => write!(f, "for_while::<{name}>"),
}
}
}
impl fmt::Display for Match {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", ExprTree::Match(self))
}
}
impl fmt::Display for MatchPattern {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MatchPattern::Left(i, ty) => write!(f, "Left({i}: {ty})"),
MatchPattern::Right(i, ty) => write!(f, "Right({i}: {ty})"),
MatchPattern::None => write!(f, "None"),
MatchPattern::Some(i, ty) => write!(f, "Some({i}: {ty})"),
MatchPattern::False => write!(f, "false"),
MatchPattern::True => write!(f, "true"),
}
}
}
macro_rules! impl_parse_wrapped_string {
($wrapper: ident, $label: literal) => {
impl ChumskyParse for $wrapper {
fn parser<'tokens, 'src: 'tokens, I>(
) -> impl Parser<'tokens, I, Self, ParseError<'src>> + Clone
where
I: ValueInput<'tokens, Token = Token<'src>, Span = Span>,
{
select! {
Token::Ident(ident) => Self::from_str_unchecked(ident)
}
.labelled($label)
}
}
};
}
impl_parse_wrapped_string!(FunctionName, "function name");
impl_parse_wrapped_string!(Identifier, "identifier");
impl_parse_wrapped_string!(WitnessName, "witness name");
impl_parse_wrapped_string!(AliasName, "alias name");
impl_parse_wrapped_string!(ModuleName, "module name");
/// Copy of [`FromStr`] that internally uses the `chumsky` parser.
pub trait ParseFromStr: Sized {
/// Parse a value from the string `s`.
fn parse_from_str(s: &str) -> Result<Self, RichError>;
}
/// Trait for parsing with collection of errors.
pub trait ParseFromStrWithErrors: Sized {
/// Parse a value from the string `s` with Errors.
fn parse_from_str_with_errors(s: &str, handler: &mut ErrorCollector) -> Option<Self>;
}
/// Trait for generating parsers of themselves.
///
/// Replacement for previous `PestParse` trait.
pub trait ChumskyParse: Sized {
fn parser<'tokens, 'src: 'tokens, I>() -> impl Parser<'tokens, I, Self, ParseError<'src>> + Clone
where
I: ValueInput<'tokens, Token = Token<'src>, Span = Span>;
}
type ParseError<'src> = extra::Err<RichError>;
/// This implementation only returns first encountered error.
impl<A: ChumskyParse + std::fmt::Debug> ParseFromStr for A {
fn parse_from_str(s: &str) -> Result<Self, RichError> {
let (tokens, mut lex_errs) = crate::lexer::lex(s);
let Some(tokens) = tokens else {
return Err(lex_errs.pop().unwrap_or(RichError::parsing_error(
"Empty token stream without an error.",
)));
};
let (ast, parse_errs) = A::parser()
.map_with(|parsed, _| parsed)
.parse(
tokens
.as_slice()
.map((s.len()..s.len()).into(), |(t, s)| (t, s)),
)
.into_output_errors();
if parse_errs.is_empty() {
Ok(ast.ok_or(RichError::parsing_error("Empty AST without an error."))?)
} else {
let err = parse_errs.first().unwrap().clone();
Err(err)
}
}
}
impl<A: ChumskyParse + std::fmt::Debug> ParseFromStrWithErrors for A {
fn parse_from_str_with_errors(s: &str, handler: &mut ErrorCollector) -> Option<Self> {
let (tokens, lex_errs) = crate::lexer::lex(s);
handler.update(lex_errs);
let tokens = tokens?;
let (ast, parse_errs) = A::parser()
.map_with(|parsed, _| parsed)
.parse(
tokens
.as_slice()
.map((s.len()..s.len()).into(), |(t, s)| (t, s)),
)
.into_output_errors();
handler.update(parse_errs);
// TODO: We should return parsed result if we found errors, but because analyzing in `ast` module
// is not handling poisoned tree right now, we don't return parsed result
if handler.get().is_empty() {
ast
} else {
None
}
}
}
/// Parse a token, and, if not found, place itself in place of missing one.
///
/// Should be only used when we know that this token should be there. For example, type of
/// `List<ty, bound>` would require comma inside angle brackets.
fn parse_token_with_recovery<'tokens, 'src: 'tokens, I>(
tok: Token<'src>,
) -> impl Parser<'tokens, I, Token<'src>, ParseError<'src>> + Clone
where
I: ValueInput<'tokens, Token = Token<'src>, Span = Span>,
{
just(tok.clone()).recover_with(via_parser(empty().to(tok)))
}
/// Parser with error recovery for expressions, which would always contains given delimiters.
///
/// Can track span of open delimiter (if any).
fn delimited_with_recovery<'tokens, 'src: 'tokens, I, P, T, F>(
parser: P,
open: Token<'src>,
close: Token<'src>,
fallback: F,
) -> impl Parser<'tokens, I, T, ParseError<'src>> + Clone
where
I: ValueInput<'tokens, Token = Token<'src>, Span = Span>,
P: Parser<'tokens, I, T, ParseError<'src>> + Clone,
T: Clone + 'tokens,
F: Fn(Span) -> T + Clone + 'tokens,