forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitem.rs
More file actions
1266 lines (1148 loc) · 36 KB
/
Copy pathitem.rs
File metadata and controls
1266 lines (1148 loc) · 36 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
use rowan::ast::{AstNode, support};
use super::{TraitRef, TupleType, TypeBoundList, ast_node, use_tree::UsePath};
use crate::{FeLang, SyntaxKind as SK, SyntaxToken};
ast_node! {
/// The top-level node of the AST tree.
pub struct Root,
SK::Root,
}
impl Root {
pub fn items(&self) -> Option<ItemList> {
support::child(self.syntax())
}
}
ast_node! {
/// A list of items in a module.
pub struct ItemList,
SK::ItemList,
IntoIterator<Item=Item>
}
impl ItemList {
pub fn inner_attr_list(&self) -> Option<super::AttrList> {
support::child(self.syntax())
}
}
ast_node! {
/// A single item in a module.
/// Use `[Item::kind]` to get the specific type of item.
pub struct Item,
SK::Item
}
impl Item {
pub fn kind(&self) -> Option<ItemKind> {
support::child(self.syntax())
.map(ItemKind::Mod)
.or_else(|| support::child(self.syntax()).map(ItemKind::Func))
.or_else(|| support::child(self.syntax()).map(ItemKind::Struct))
.or_else(|| support::child(self.syntax()).map(ItemKind::Contract))
.or_else(|| support::child(self.syntax()).map(ItemKind::Msg))
.or_else(|| support::child(self.syntax()).map(ItemKind::Enum))
.or_else(|| support::child(self.syntax()).map(ItemKind::TypeAlias))
.or_else(|| support::child(self.syntax()).map(ItemKind::Impl))
.or_else(|| support::child(self.syntax()).map(ItemKind::Trait))
.or_else(|| support::child(self.syntax()).map(ItemKind::ImplTrait))
.or_else(|| support::child(self.syntax()).map(ItemKind::Const))
.or_else(|| support::child(self.syntax()).map(ItemKind::StaticAssert))
.or_else(|| support::child(self.syntax()).map(ItemKind::Use))
.or_else(|| support::child(self.syntax()).map(ItemKind::Extern))
}
}
ast_node! {
pub struct Mod,
SK::Mod,
}
impl super::AttrListOwner for Mod {}
impl super::ItemModifierOwner for Mod {}
impl Mod {
/// Returns the name of the function.
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the function's parameter list.
pub fn items(&self) -> Option<ItemList> {
support::child(self.syntax())
}
}
ast_node! {
/// `pub fn foo<T, U: Trait>(_ x: T, from u: U) -> T where T: Trait2 { ... }`
pub struct Func,
SK::Func,
}
ast_node! {
/// `foo<T>(a: T) -> T where T: Clone`
pub struct FuncSignature,
SK::FuncSignature,
}
impl super::GenericParamsOwner for FuncSignature {}
impl super::WhereClauseOwner for FuncSignature {}
impl FuncSignature {
/// Returns the name of the function.
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the function's parameter list.
pub fn params(&self) -> Option<super::FuncParamList> {
support::child(self.syntax())
}
/// Returns the function's return type.
pub fn ret_ty(&self) -> Option<super::Type> {
support::child(self.syntax())
}
/// Returns the optional `uses` clause of the function.
pub fn uses_clause(&self) -> Option<super::UsesClause> {
support::child(self.syntax())
}
/// Returns the where clause of the function.
pub fn where_clause(&self) -> Option<super::WhereClause> {
support::child(self.syntax())
}
}
impl super::AttrListOwner for Func {}
impl super::ItemModifierOwner for Func {}
impl Func {
pub fn const_kw(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::ConstKw)
}
/// Returns the function's signature if present in the syntax tree.
/// This is primarily for consumers (like lazy spans) that need to handle
/// malformed code without panicking.
pub fn signature_opt(&self) -> Option<FuncSignature> {
support::child(self.syntax())
}
/// Returns the function's signature.
pub fn sig(&self) -> FuncSignature {
self.signature_opt()
.expect("a function must always contain a signature node")
}
/// Returns the function's body.
pub fn body(&self) -> Option<super::BlockExpr> {
support::child(self.syntax())
}
}
ast_node! {
pub struct Struct,
SK::Struct,
}
impl super::GenericParamsOwner for Struct {}
impl super::WhereClauseOwner for Struct {}
impl super::AttrListOwner for Struct {}
impl super::ItemModifierOwner for Struct {}
impl Struct {
/// Returns the name of the struct.
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the struct's field def list.
pub fn fields(&self) -> Option<RecordFieldDefList> {
support::child(self.syntax())
}
}
ast_node! {
pub struct Contract,
SK::Contract,
}
impl super::AttrListOwner for Contract {}
impl super::ItemModifierOwner for Contract {}
impl Contract {
/// Returns the name of the contract.
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the contract's leading fields section.
pub fn fields(&self) -> Option<ContractFields> {
support::child(self.syntax())
}
/// Returns the optional `uses` clause of the contract.
pub fn uses_clause(&self) -> Option<super::UsesClause> {
support::child(self.syntax())
}
/// Returns the optional `init` block of the contract.
pub fn init_block(&self) -> Option<ContractInit> {
support::child(self.syntax())
}
/// Returns all `recv` blocks declared in the contract.
pub fn recvs(&self) -> rowan::ast::AstChildren<ContractRecv> {
support::children(self.syntax())
}
}
ast_node! {
/// A section containing the leading contract fields.
pub struct ContractFields,
SK::ContractFields,
IntoIterator<Item=RecordFieldDef>
}
ast_node! {
/// The contract initialization block: `init(...) uses (...) { ... }`.
pub struct ContractInit,
SK::ContractInit,
}
impl super::AttrListOwner for ContractInit {}
impl ContractInit {
pub fn params(&self) -> Option<super::FuncParamList> {
support::child(self.syntax())
}
pub fn uses_clause(&self) -> Option<super::UsesClause> {
support::child(self.syntax())
}
pub fn body(&self) -> Option<super::BlockExpr> {
support::child(self.syntax())
}
}
ast_node! {
/// A `recv` block inside a contract. Supports both typed and untyped forms.
pub struct ContractRecv,
SK::ContractRecv,
}
impl super::AttrListOwner for ContractRecv {}
impl ContractRecv {
/// Optional root message type path (`recv Type { ... }`).
pub fn path(&self) -> Option<super::Path> {
support::child(self.syntax())
}
/// The list of arms in this recv block.
pub fn arms(&self) -> Option<RecvArmList> {
support::child(self.syntax())
}
}
ast_node! {
/// List of recv arms inside a recv block.
pub struct RecvArmList,
SK::RecvArmList,
IntoIterator<Item=RecvArm>
}
ast_node! {
/// A single recv arm: `Pattern -> RetTy uses (...) { body }`
pub struct RecvArm,
SK::RecvArm,
}
impl super::AttrListOwner for RecvArm {}
impl RecvArm {
/// The pattern being matched (e.g., `Transfer { to, amount }`).
pub fn pat(&self) -> Option<super::Pat> {
support::child(self.syntax())
}
/// Optional return type.
pub fn ret_ty(&self) -> Option<super::Type> {
support::child(self.syntax())
}
/// Optional uses clause.
pub fn uses_clause(&self) -> Option<super::UsesClause> {
support::child(self.syntax())
}
/// The body block.
pub fn body(&self) -> Option<super::BlockExpr> {
support::child(self.syntax())
}
}
ast_node! {
pub struct Enum,
SK::Enum,
}
impl super::GenericParamsOwner for Enum {}
impl super::WhereClauseOwner for Enum {}
impl super::AttrListOwner for Enum {}
impl super::ItemModifierOwner for Enum {}
impl Enum {
/// Returns the name of the enum.
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the enum's variant def list.
pub fn variants(&self) -> Option<VariantDefList> {
support::child(self.syntax())
}
}
ast_node! {
/// `type Foo<T> = Bar<T>`
pub struct TypeAlias,
SK::TypeAlias,
}
impl super::GenericParamsOwner for TypeAlias {}
impl super::AttrListOwner for TypeAlias {}
impl super::ItemModifierOwner for TypeAlias {}
impl TypeAlias {
/// Returns the name of the type alias.
/// `Foo` in `type Foo<T> = Bar<T>`
pub fn alias(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the type alias's type.
/// `Bar<T>` in `type Foo<T> = Bar<T>`
pub fn ty(&self) -> Option<super::Type> {
support::child(self.syntax())
}
}
ast_node! {
/// `trait Foo<..> where .. { .. }`
pub struct Trait,
SK::Trait,
}
impl super::GenericParamsOwner for Trait {}
impl super::WhereClauseOwner for Trait {}
impl super::AttrListOwner for Trait {}
impl super::ItemModifierOwner for Trait {}
impl Trait {
/// Returns the name of the trait.
/// `Foo` in `trait Foo<..> where .. { .. }`
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the trait's item list.
/// `{ .. }` in `trait Foo<..> where .. { .. }`
pub fn item_list(&self) -> Option<TraitItemList> {
support::child(self.syntax())
}
pub fn super_trait_list(&self) -> Option<SuperTraitList> {
support::child(self.syntax())
}
}
ast_node! {
pub struct SuperTraitList,
SK::SuperTraitList,
IntoIterator<Item=TraitRef>
}
impl SuperTraitList {
pub fn colon(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Colon)
}
}
ast_node! {
/// `type Bar` in trait definition
/// or `type Bar = i32` in trait implementation
pub struct TraitTypeItem,
SK::TraitTypeItem,
}
impl super::AttrListOwner for TraitTypeItem {}
impl TraitTypeItem {
/// Returns the name of the associated type
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
pub fn ty(&self) -> Option<super::Type> {
support::child(self.syntax())
}
pub fn bounds(&self) -> Option<TypeBoundList> {
support::child(self.syntax())
}
}
ast_node! {
/// `const FOO: Ty` in trait definition
/// or `const FOO: Ty = expr` in trait implementation
pub struct TraitConstItem,
SK::TraitConstItem,
}
impl super::AttrListOwner for TraitConstItem {}
impl super::ItemModifierOwner for TraitConstItem {}
impl TraitConstItem {
/// Returns the name of the associated const
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the type of the associated const
pub fn ty(&self) -> Option<super::Type> {
support::child(self.syntax())
}
/// Returns the optional default value of the associated const
pub fn value(&self) -> Option<super::Expr> {
support::child(self.syntax())
}
}
ast_node! {
pub struct TraitItem,
SK::Func | SK::TraitTypeItem | SK::TraitConstItem
}
impl TraitItem {
pub fn kind(&self) -> TraitItemKind {
match self.syntax().kind() {
SK::Func => TraitItemKind::Func(AstNode::cast(self.syntax().clone()).unwrap()),
SK::TraitTypeItem => {
TraitItemKind::Type(TraitTypeItem::cast(self.syntax().clone()).unwrap())
}
SK::TraitConstItem => {
TraitItemKind::Const(TraitConstItem::cast(self.syntax().clone()).unwrap())
}
_ => unreachable!(),
}
}
}
pub enum TraitItemKind {
Func(Func),
Type(TraitTypeItem),
Const(TraitConstItem),
}
ast_node! {
pub struct ImplItem,
SK::Func | SK::TraitConstItem
}
impl ImplItem {
pub fn kind(&self) -> ImplItemKind {
match self.syntax().kind() {
SK::Func => ImplItemKind::Func(AstNode::cast(self.syntax().clone()).unwrap()),
SK::TraitConstItem => {
ImplItemKind::Const(TraitConstItem::cast(self.syntax().clone()).unwrap())
}
_ => unreachable!(),
}
}
}
pub enum ImplItemKind {
Func(Func),
Const(TraitConstItem),
}
ast_node! {
/// `impl Foo::Bar<T> where .. { .. }`
pub struct Impl,
SK::Impl,
}
impl super::GenericParamsOwner for Impl {}
impl super::WhereClauseOwner for Impl {}
impl super::AttrListOwner for Impl {}
impl Impl {
/// Returns the type of the impl.
/// `Foo::Bar<T>` in `impl Foo::Bar<T> where .. { .. }`
pub fn ty(&self) -> Option<super::Type> {
support::child(self.syntax())
}
/// Returns the impl item list.
/// `{ .. }` in `impl Foo::Bar<T> where .. { .. }`
/// Supports `fn` and associated `const` items.
pub fn item_list(&self) -> Option<ImplItemList> {
support::child(self.syntax())
}
}
ast_node! {
/// `impl<T> Foo for Bar<T> { .. }`
pub struct ImplTrait,
SK::ImplTrait,
}
impl super::GenericParamsOwner for ImplTrait {}
impl super::WhereClauseOwner for ImplTrait {}
impl super::AttrListOwner for ImplTrait {}
impl ImplTrait {
/// Returns the trait of the impl.
/// `Foo` in `impl<T> Foo for Bar<T> { .. }`
pub fn trait_ref(&self) -> Option<TraitRef> {
support::child(self.syntax())
}
/// Returns the type of the impl.
/// `Bar<T>` in `impl<T> Foo for Bar<T> { .. }`
pub fn ty(&self) -> Option<super::Type> {
support::child(self.syntax())
}
/// Returns the trait impl item list.
/// `{ .. }` in `impl<T> Foo for Bar<T> { .. }`
pub fn item_list(&self) -> Option<TraitItemList> {
support::child(self.syntax())
}
}
ast_node! {
/// `const FOO: u32 = 42;`
pub struct Const,
SK::Const,
}
impl super::AttrListOwner for Const {}
impl ItemModifierOwner for Const {}
impl Const {
/// Returns the name of the const.
/// `FOO` in `const FOO: u32 = 42;`
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the type of the const.
/// `u32` in `const FOO: u32 = 42;`
pub fn ty(&self) -> Option<super::Type> {
support::child(self.syntax())
}
/// Returns the value of the const.
/// `42` in `const FOO: u32 = 42;`
pub fn value(&self) -> Option<super::Expr> {
support::child(self.syntax())
}
}
ast_node! {
/// `static_assert(expr)`
pub struct StaticAssert,
SK::StaticAssert,
}
impl super::AttrListOwner for StaticAssert {}
impl StaticAssert {
/// Returns the asserted condition.
pub fn condition(&self) -> Option<super::Expr> {
support::child(self.syntax())
}
}
ast_node! {
/// `use foo::{bar, Baz::*}`
pub struct Use,
SK::Use,
}
impl super::AttrListOwner for Use {}
impl ItemModifierOwner for Use {}
impl Use {
/// Returns the use tree.
/// `foo::{bar, Baz::*}` in `use foo::{bar, Baz::*}`
pub fn use_tree(&self) -> Option<super::UseTree> {
support::child(self.syntax())
}
pub fn has_sub_tree(&self) -> bool {
self.use_tree().is_some_and(|it| it.has_subtree())
}
}
ast_node! {
/// `extern { .. }`
pub struct Extern,
SK::Extern,
}
impl super::AttrListOwner for Extern {}
impl Extern {
/// Returns the item list.
/// NOTE: Currently only supports `fn` items.
pub fn extern_block(&self) -> Option<ExternItemList> {
support::child(self.syntax())
}
}
ast_node! {
pub struct RecordFieldDefList,
SK::RecordFieldDefList,
IntoIterator<Item=RecordFieldDef>
}
ast_node! {
pub struct RecordFieldDef,
SK::RecordFieldDef,
}
impl super::AttrListOwner for RecordFieldDef {}
impl RecordFieldDef {
/// Returns the pub keyword if exists.
pub fn pub_kw(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::PubKw)
}
/// Returns the visibility restriction if exists, e.g. `(ingot)` in `pub(ingot)`.
pub fn vis_restriction(&self) -> Option<VisRestriction> {
support::child(self.syntax())
}
/// Returns the mut keyword if exists.
pub fn mut_kw(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::MutKw)
}
/// Returns the name of the field.
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the type of the field.
pub fn ty(&self) -> Option<super::Type> {
support::child(self.syntax())
}
}
ast_node! {
pub struct VariantDefList,
SK::VariantDefList,
IntoIterator<Item=VariantDef>
}
ast_node! {
/// `Foo(i32, u32)`
pub struct VariantDef,
SK::VariantDef,
}
impl super::AttrListOwner for VariantDef {}
impl VariantDef {
/// Returns the name of the variant.
/// `Foo` in `Foo(i32, u32)`
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the kind of the variant.
pub fn kind(&self) -> VariantKind {
support::child(self.syntax())
.map(VariantKind::Tuple)
.or_else(|| support::child(self.syntax()).map(VariantKind::Record))
.unwrap_or(VariantKind::Unit)
}
/// Returns the variant's field def list.
pub fn fields(&self) -> Option<RecordFieldDefList> {
support::child(self.syntax())
}
pub fn tuple_type(&self) -> Option<TupleType> {
support::child(self.syntax())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum VariantKind {
Unit,
Tuple(TupleType),
Record(RecordFieldDefList),
}
ast_node! {
pub struct TraitItemList,
SK::TraitItemList,
IntoIterator<Item=TraitItem>,
}
ast_node! {
pub struct ImplItemList,
SK::ImplItemList,
IntoIterator<Item=ImplItem>,
}
ast_node! {
pub struct ExternItemList,
SK::ExternItemList,
IntoIterator<Item=Func>,
}
ast_node! {
/// `(ingot)`, `(super)`, `(in path::to::module)`
pub struct VisRestriction,
SK::VisRestriction,
}
impl VisRestriction {
pub fn ingot_kw(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::IngotKw)
}
pub fn super_kw(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::SuperKw)
}
pub fn in_kw(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::InKw)
}
pub fn path(&self) -> Option<UsePath> {
support::child(self.syntax())
}
}
pub trait ItemModifierOwner: AstNode<Language = FeLang> {
fn pub_kw(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::PubKw)
}
fn unsafe_kw(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::UnsafeKw)
}
fn vis_restriction(&self) -> Option<VisRestriction> {
support::child(self.syntax())
}
}
ast_node! {
/// `msg Erc20Msg { ... }`
pub struct Msg,
SK::Msg,
}
impl super::AttrListOwner for Msg {}
impl super::ItemModifierOwner for Msg {}
impl Msg {
/// Returns the name of the message interface.
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
/// Returns the message variants.
pub fn variants(&self) -> Option<MsgVariantList> {
support::child(self.syntax())
}
}
ast_node! {
/// A list of message variants.
pub struct MsgVariantList,
SK::MsgVariantList,
IntoIterator<Item=MsgVariant>
}
ast_node! {
/// A single message variant.
/// `Transfer { to: Address, amount: u256 } -> bool`
pub struct MsgVariant,
SK::MsgVariant,
}
impl super::AttrListOwner for MsgVariant {}
impl MsgVariant {
pub fn name(&self) -> Option<SyntaxToken> {
support::token(self.syntax(), SK::Ident)
}
pub fn params(&self) -> Option<MsgVariantParams> {
support::child(self.syntax())
}
pub fn ret_ty(&self) -> Option<super::Type> {
support::child(self.syntax())
}
}
ast_node! {
/// Message variant parameters.
/// `{ to: Address, amount: u256 }`
pub struct MsgVariantParams,
SK::MsgVariantParams,
IntoIterator<Item=RecordFieldDef>
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, derive_more::From, derive_more::TryInto)]
pub enum ItemKind {
Mod(Mod),
Func(Func),
Struct(Struct),
Contract(Contract),
Msg(Msg),
Enum(Enum),
TypeAlias(TypeAlias),
Impl(Impl),
Trait(Trait),
ImplTrait(ImplTrait),
Const(Const),
StaticAssert(StaticAssert),
Use(Use),
Extern(Extern),
}
#[cfg(test)]
mod tests {
use derive_more::TryIntoError;
use tracing::error;
use wasm_bindgen_test::wasm_bindgen_test;
use super::*;
use crate::{
ast::{ExprKind, TypeKind, prelude::*},
lexer::Lexer,
parser::{ItemListScope, Parser, RecoveryMode},
};
fn parse_item<T>(source: &str) -> T
where
T: TryFrom<ItemKind, Error = TryIntoError<ItemKind>>,
{
let _logging = test_utils::setup_test_tracing();
let lexer = Lexer::new(source);
let mut parser = Parser::new(lexer, RecoveryMode::Recover);
let _ = parser.parse(ItemListScope::default());
let (node, errs) = parser.finish_to_node();
for e in errs {
error!("{:?}", e);
}
let item_list = ItemList::cast(node).unwrap();
let mut items = item_list.into_iter().collect::<Vec<_>>();
if items.len() > 1 {
error!("expected one item, got: {:?}", &items);
}
assert_eq!(items.len(), 1);
items.pop().unwrap().kind().unwrap().try_into().unwrap()
}
#[test]
#[wasm_bindgen_test]
fn mod_() {
let source = r"
pub mod foo {
pub fn bar() {}
pub struct Baz
}
";
let mod_: Mod = parse_item(source);
assert_eq!(mod_.name().unwrap().text(), "foo");
let mut i = 0;
for item in mod_.items().unwrap().into_iter() {
match i {
0 => {
assert!(matches!(item.kind().unwrap(), ItemKind::Func(_)));
let func: Func = item.kind().unwrap().try_into().unwrap();
assert_eq!(func.sig().name().unwrap().text(), "bar");
}
1 => {
assert!(matches!(item.kind().unwrap(), ItemKind::Struct(_)));
let struct_: Struct = item.kind().unwrap().try_into().unwrap();
assert_eq!(struct_.name().unwrap().text(), "Baz");
}
_ => panic!(),
}
i += 1;
}
assert_eq!(i, 2);
}
#[test]
#[wasm_bindgen_test]
fn mod_with_inner_attr() {
let source = r"
pub mod foo {
#![arithmetic(unchecked)]
pub fn bar() {}
}
";
let mod_: Mod = parse_item(source);
let item_list = mod_.items().expect("module should have items");
assert_eq!(
item_list
.inner_attr_list()
.expect("module should have inner attrs")
.normal_attrs()
.count(),
1
);
assert_eq!(item_list.into_iter().count(), 1);
}
#[test]
#[wasm_bindgen_test]
fn root_with_inner_attr() {
let source = r"
#![arithmetic(unchecked)]
fn foo() {}
";
let (node, errs) = crate::parse_source_file(source, RecoveryMode::Recover);
assert!(errs.is_empty(), "unexpected parse errors: {errs:?}");
let root = Root::cast(rowan::SyntaxNode::new_root(node)).expect("root");
let item_list = root.items().expect("root should have items");
assert_eq!(
item_list
.inner_attr_list()
.expect("root should have inner attrs")
.normal_attrs()
.count(),
1
);
assert_eq!(item_list.into_iter().count(), 1);
}
#[test]
#[wasm_bindgen_test]
fn func() {
let source = r#"
/// This is doc comment
#[evm]
pub unsafe fn foo<T, U: Trait>(_ x: T, from u: U) -> (T, U) where T: Trait2 { return }
"#;
let func: Func = parse_item(source);
assert_eq!(func.sig().name().unwrap().text(), "foo");
assert_eq!(func.attr_list().unwrap().iter().count(), 2);
assert_eq!(func.sig().generic_params().unwrap().iter().count(), 2);
assert!(func.sig().where_clause().is_some());
assert!(func.body().is_some());
assert!(matches!(
func.sig().ret_ty().unwrap().kind(),
TypeKind::Tuple(_)
));
assert!(func.pub_kw().is_some());
assert!(func.unsafe_kw().is_some());
}
#[test]
#[wasm_bindgen_test]
fn struct_() {
let source = r#"
pub struct Foo<T, U: Trait> where T: Trait2 {
pub x: T,
y: (U, i32),
}
"#;
let s: Struct = parse_item(source);
assert_eq!(s.name().unwrap().text(), "Foo");
let mut count = 0;
for field in s.fields().unwrap() {
match count {
0 => {
assert!(field.pub_kw().is_some());
assert_eq!(field.name().unwrap().text(), "x");
assert!(matches!(field.ty().unwrap().kind(), TypeKind::Path(_)));
}
1 => {
assert!(field.pub_kw().is_none());
assert_eq!(field.name().unwrap().text(), "y");
assert!(matches!(field.ty().unwrap().kind(), TypeKind::Tuple(_)));
}
_ => unreachable!(),
}
count += 1;
}
assert_eq!(count, 2);
}
#[test]
#[wasm_bindgen_test]
fn contract() {
let source = r#"
pub contract Foo {
pub x: u32,
y: (i32, u32),
}
"#;
let c: Contract = parse_item(source);
assert_eq!(c.name().unwrap().text(), "Foo");
let mut count = 0;
for field in c.fields().unwrap() {
match count {
0 => {
assert!(field.pub_kw().is_some());
assert_eq!(field.name().unwrap().text(), "x");
assert!(matches!(field.ty().unwrap().kind(), TypeKind::Path(_)));
}
1 => {
assert!(field.pub_kw().is_none());
assert_eq!(field.name().unwrap().text(), "y");
assert!(matches!(field.ty().unwrap().kind(), TypeKind::Tuple(_)));
}
_ => unreachable!(),
}
count += 1;
}
assert_eq!(count, 2);
}
#[test]
#[wasm_bindgen_test]
fn enum_() {
let source = r#"
pub enum Foo<T, U: Trait> where T: Trait2 {
Bar
Baz(T, U)
Bux {
x: i8
y: i8
}
}
"#;
let e: Enum = parse_item(source);
assert_eq!(e.name().unwrap().text(), "Foo");
let mut count = 0;
for variant in e.variants().unwrap() {
match count {
0 => {
assert_eq!(variant.name().unwrap().text(), "Bar");
assert_eq!(variant.kind(), VariantKind::Unit);
}
1 => {
assert_eq!(variant.name().unwrap().text(), "Baz");
assert!(matches!(variant.kind(), VariantKind::Tuple(_)));
}
2 => {
assert_eq!(variant.name().unwrap().text(), "Bux");