1use ecow::EcoString;
2
3use crate::program::{CallKind, DotAccessKind, ReceiverCoercion};
4use crate::types::Type;
5
6const CHILDREN_INLINE_CAP: usize = 4;
7
8pub struct Children<'a> {
9 inline: [Option<&'a Expression>; CHILDREN_INLINE_CAP],
10 inline_len: usize,
11 heap: Vec<&'a Expression>,
12}
13
14impl<'a> Children<'a> {
15 pub fn new() -> Self {
16 Children {
17 inline: [None; CHILDREN_INLINE_CAP],
18 inline_len: 0,
19 heap: Vec::new(),
20 }
21 }
22
23 pub fn push(&mut self, expression: &'a Expression) {
24 if self.heap.is_empty() && self.inline_len < CHILDREN_INLINE_CAP {
25 self.inline[self.inline_len] = Some(expression);
26 self.inline_len += 1;
27 } else {
28 self.heap.push(expression);
29 }
30 }
31
32 pub fn iter(&self) -> impl Iterator<Item = &'a Expression> + '_ {
33 self.inline[..self.inline_len]
34 .iter()
35 .filter_map(|slot| *slot)
36 .chain(self.heap.iter().copied())
37 }
38}
39
40impl Default for Children<'_> {
41 fn default() -> Self {
42 Children::new()
43 }
44}
45
46impl<'a> Extend<&'a Expression> for Children<'a> {
47 fn extend<T: IntoIterator<Item = &'a Expression>>(&mut self, iter: T) {
48 for expression in iter {
49 self.push(expression);
50 }
51 }
52}
53
54impl<'a> FromIterator<&'a Expression> for Children<'a> {
55 fn from_iter<T: IntoIterator<Item = &'a Expression>>(iter: T) -> Self {
56 let mut children = Children::new();
57 children.extend(iter);
58 children
59 }
60}
61
62pub struct ChildrenIntoIter<'a> {
63 inline: [Option<&'a Expression>; CHILDREN_INLINE_CAP],
64 pos: usize,
65 inline_len: usize,
66 heap: std::vec::IntoIter<&'a Expression>,
67}
68
69impl<'a> Iterator for ChildrenIntoIter<'a> {
70 type Item = &'a Expression;
71
72 fn next(&mut self) -> Option<&'a Expression> {
73 if self.pos < self.inline_len {
74 let item = self.inline[self.pos];
75 self.pos += 1;
76 item
77 } else {
78 self.heap.next()
79 }
80 }
81}
82
83impl<'a> IntoIterator for Children<'a> {
84 type Item = &'a Expression;
85 type IntoIter = ChildrenIntoIter<'a>;
86
87 fn into_iter(self) -> ChildrenIntoIter<'a> {
88 ChildrenIntoIter {
89 inline: self.inline,
90 pos: 0,
91 inline_len: self.inline_len,
92 heap: self.heap.into_iter(),
93 }
94 }
95}
96
97macro_rules! children {
98 () => { Children::new() };
99 ($($expression:expr),+ $(,)?) => {{
100 let mut __children = Children::new();
101 $( __children.push($expression); )+
102 __children
103 }};
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum DeadCodeCause {
108 Return,
109 Break,
110 Continue,
111 DivergingIf,
112 DivergingMatch,
113 InfiniteLoop,
114 DivergingCall,
115}
116
117#[derive(Clone, PartialEq)]
118pub struct Binding {
119 pub pattern: Pattern,
120 pub annotation: Option<Annotation>,
121 pub typed_pattern: Option<TypedPattern>,
122 pub ty: Type,
123 pub mutable: bool,
124}
125
126impl std::fmt::Debug for Binding {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128 let mut s = f.debug_struct("Binding");
129 s.field("pattern", &self.pattern);
130 s.field("annotation", &self.annotation);
131 s.field("typed_pattern", &self.typed_pattern);
132 s.field("ty", &self.ty);
133 if self.mutable {
134 s.field("mutable", &self.mutable);
135 }
136 s.finish()
137 }
138}
139
140pub type BindingId = u32;
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum BindingKind {
144 Let { mutable: bool },
145 Parameter { mutable: bool },
146 MatchArm,
147 IfLet,
148 WhileLet,
149}
150
151impl BindingKind {
152 pub fn is_mutable(&self) -> bool {
153 matches!(
154 self,
155 BindingKind::Let { mutable: true } | BindingKind::Parameter { mutable: true }
156 )
157 }
158
159 pub fn is_param(&self) -> bool {
160 matches!(self, BindingKind::Parameter { .. })
161 }
162
163 pub fn is_match_arm(&self) -> bool {
164 matches!(self, BindingKind::MatchArm)
165 }
166
167 pub fn is_pattern_position(&self) -> bool {
168 matches!(
169 self,
170 BindingKind::MatchArm | BindingKind::IfLet | BindingKind::WhileLet
171 )
172 }
173}
174
175#[derive(Clone, PartialEq)]
176pub struct MatchArm {
177 pub pattern: Pattern,
178 pub guard: Option<Box<Expression>>,
179 pub typed_pattern: Option<TypedPattern>,
180 pub expression: Box<Expression>,
181}
182
183impl MatchArm {
184 pub fn has_guard(&self) -> bool {
185 self.guard.is_some()
186 }
187}
188
189impl std::fmt::Debug for MatchArm {
190 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191 let mut s = f.debug_struct("MatchArm");
192 s.field("pattern", &self.pattern);
193 if self.guard.is_some() {
194 s.field("guard", &self.guard);
195 }
196 s.field("expression", &self.expression);
197 s.finish()
198 }
199}
200
201#[derive(Debug, Clone, PartialEq)]
202pub struct SelectArm {
203 pub pattern: SelectArmPattern,
204}
205
206#[derive(Debug, Clone, PartialEq)]
207pub enum SelectArmPattern {
208 Receive {
209 binding: Box<Pattern>,
210 typed_pattern: Option<TypedPattern>,
211 receive_expression: Box<Expression>,
212 body: Box<Expression>,
213 },
214 Send {
215 send_expression: Box<Expression>,
216 body: Box<Expression>,
217 },
218 MatchReceive {
219 receive_expression: Box<Expression>,
220 arms: Vec<MatchArm>,
221 },
222 WildCard {
223 body: Box<Expression>,
224 },
225}
226
227#[derive(Debug, Clone, PartialEq)]
228pub enum RestPattern {
229 Absent,
230 Discard(Span),
231 Bind { name: EcoString, span: Span },
232}
233
234impl RestPattern {
235 pub fn is_present(&self) -> bool {
236 !matches!(self, RestPattern::Absent)
237 }
238}
239
240#[derive(Debug, Clone, PartialEq)]
241pub enum Pattern {
242 Literal {
243 literal: Literal,
244 ty: Type,
245 span: Span,
246 },
247 Unit {
248 ty: Type,
249 span: Span,
250 },
251 EnumVariant {
252 identifier: EcoString,
253 fields: Vec<Self>,
254 rest: bool,
255 ty: Type,
256 span: Span,
257 },
258 Struct {
259 identifier: EcoString,
260 fields: Vec<StructFieldPattern>,
261 rest: bool,
262 ty: Type,
263 span: Span,
264 },
265 Tuple {
266 elements: Vec<Self>,
267 span: Span,
268 },
269 WildCard {
270 span: Span,
271 },
272 Identifier {
273 identifier: EcoString,
274 span: Span,
275 },
276 Slice {
277 prefix: Vec<Self>,
278 rest: RestPattern,
279 element_ty: Type,
280 span: Span,
281 },
282 Or {
283 patterns: Vec<Self>,
284 span: Span,
285 },
286 AsBinding {
287 pattern: Box<Self>,
288 name: EcoString,
289 span: Span,
290 },
291}
292
293pub fn collect_pattern_bindings(pattern: &Pattern) -> Vec<(String, Span)> {
295 match pattern {
296 Pattern::Identifier { identifier, span } => vec![(identifier.to_string(), *span)],
297 Pattern::Tuple { elements, .. } => {
298 elements.iter().flat_map(collect_pattern_bindings).collect()
299 }
300 Pattern::EnumVariant { fields, .. } => {
301 fields.iter().flat_map(collect_pattern_bindings).collect()
302 }
303 Pattern::Struct { fields, .. } => fields
304 .iter()
305 .flat_map(|f| collect_pattern_bindings(&f.value))
306 .collect(),
307 Pattern::Slice { prefix, rest, .. } => {
308 let mut bindings: Vec<_> = prefix.iter().flat_map(collect_pattern_bindings).collect();
309 if let RestPattern::Bind { name, span } = rest {
310 bindings.push((name.to_string(), *span));
311 }
312 bindings
313 }
314 Pattern::Or { patterns, .. } => patterns
315 .first()
316 .map(collect_pattern_bindings)
317 .unwrap_or_default(),
318 Pattern::AsBinding {
319 pattern,
320 name,
321 span,
322 } => {
323 let mut bindings = collect_pattern_bindings(pattern);
324 bindings.push((name.to_string(), *span));
325 bindings
326 }
327 Pattern::WildCard { .. } | Pattern::Literal { .. } | Pattern::Unit { .. } => vec![],
328 }
329}
330
331#[derive(Clone, Copy)]
333pub enum PatternKind {
334 Literal,
335 Unit,
336 EnumVariant,
337 Struct,
338 Tuple,
339 WildCard,
340 Identifier,
341 Slice,
342 Or,
343 AsBinding,
344}
345
346impl PatternKind {
347 pub const COUNT: usize = PatternKind::AsBinding as usize + 1;
349}
350
351impl Pattern {
352 pub fn kind(&self) -> PatternKind {
353 match self {
354 Pattern::Literal { .. } => PatternKind::Literal,
355 Pattern::Unit { .. } => PatternKind::Unit,
356 Pattern::EnumVariant { .. } => PatternKind::EnumVariant,
357 Pattern::Struct { .. } => PatternKind::Struct,
358 Pattern::Tuple { .. } => PatternKind::Tuple,
359 Pattern::WildCard { .. } => PatternKind::WildCard,
360 Pattern::Identifier { .. } => PatternKind::Identifier,
361 Pattern::Slice { .. } => PatternKind::Slice,
362 Pattern::Or { .. } => PatternKind::Or,
363 Pattern::AsBinding { .. } => PatternKind::AsBinding,
364 }
365 }
366
367 pub fn get_span(&self) -> Span {
368 match self {
369 Pattern::Identifier { span, .. } => *span,
370 Pattern::Literal { span, .. } => *span,
371 Pattern::EnumVariant { span, .. } => *span,
372 Pattern::Struct { span, .. } => *span,
373 Pattern::WildCard { span } => *span,
374 Pattern::Unit { span, .. } => *span,
375 Pattern::Tuple { span, .. } => *span,
376 Pattern::Slice { span, .. } => *span,
377 Pattern::Or { span, .. } => *span,
378 Pattern::AsBinding { span, .. } => *span,
379 }
380 }
381
382 pub fn get_type(&self) -> Option<Type> {
383 match self {
384 Pattern::Identifier { .. } => None,
385 Pattern::Literal { ty, .. } => Some(ty.clone()),
386 Pattern::EnumVariant { ty, .. } => Some(ty.clone()),
387 Pattern::Struct { ty, .. } => Some(ty.clone()),
388 Pattern::WildCard { .. } => None,
389 Pattern::Unit { ty, .. } => Some(ty.clone()),
390 Pattern::Tuple { .. } => None,
391 Pattern::Slice { .. } => None,
392 Pattern::Or { .. } => None,
393 Pattern::AsBinding { pattern, .. } => pattern.get_type(),
394 }
395 }
396
397 pub fn is_identifier(&self) -> bool {
398 matches!(self, Pattern::Identifier { .. } | Pattern::AsBinding { .. })
399 }
400
401 pub fn get_identifier(&self) -> Option<EcoString> {
402 match self {
403 Pattern::Identifier { identifier, .. } => Some(identifier.clone()),
404 Pattern::AsBinding { name, .. } => Some(name.clone()),
405 _ => None,
406 }
407 }
408}
409
410#[derive(Debug, Clone, PartialEq)]
411pub struct StructFieldPattern {
412 pub name: EcoString,
413 pub value: Pattern,
414}
415
416#[derive(Debug, Clone, PartialEq)]
417pub enum TypedPattern {
418 Wildcard,
419 Literal(Literal),
420 Const {
424 qualified_name: EcoString,
425 ty: Type,
426 value: Option<Literal>,
427 },
428 EnumVariant {
429 enum_name: EcoString,
430 variant_name: EcoString,
431 variant_fields: Vec<EnumFieldDefinition>,
432 fields: Vec<TypedPattern>,
433 type_args: Vec<Type>,
434 field_types: Box<[Type]>,
435 },
436 EnumStructVariant {
437 enum_name: EcoString,
438 variant_name: EcoString,
439 variant_fields: Vec<EnumFieldDefinition>,
440 pattern_fields: Vec<(EcoString, TypedPattern)>,
441 type_args: Vec<Type>,
442 },
443 Struct {
444 struct_name: EcoString,
445 struct_fields: Vec<StructFieldDefinition>,
446 pattern_fields: Vec<(EcoString, TypedPattern)>,
447 type_args: Vec<Type>,
448 },
449 Slice {
450 prefix: Vec<TypedPattern>,
451 has_rest: bool,
452 element_type: Type,
453 },
454 Tuple {
455 arity: usize,
456 elements: Vec<TypedPattern>,
457 },
458 Or {
459 alternatives: Vec<TypedPattern>,
460 },
461}
462
463#[derive(Debug, Clone, PartialEq)]
464pub struct FunctionDefinition {
465 pub name: EcoString,
466 pub name_span: Span,
467 pub generics: Vec<Generic>,
468 pub params: Vec<Binding>,
469 pub body: Box<Expression>,
470 pub return_type: Type,
471 pub annotation: Annotation,
472 pub ty: Type,
473}
474
475#[derive(Clone, Copy)]
476pub struct FunctionDefinitionView<'a> {
477 pub name: &'a EcoString,
478 pub name_span: Span,
479 pub generics: &'a [Generic],
480 pub params: &'a [Binding],
481 pub body: &'a Expression,
482 pub return_type: &'a Type,
483}
484
485#[derive(Debug, Clone, PartialEq)]
486pub enum VariantFields {
487 Unit,
488 Tuple(Vec<EnumFieldDefinition>),
489 Struct(Vec<EnumFieldDefinition>),
490}
491
492impl VariantFields {
493 pub fn is_empty(&self) -> bool {
494 match self {
495 VariantFields::Unit => true,
496 VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.is_empty(),
497 }
498 }
499
500 pub fn len(&self) -> usize {
501 match self {
502 VariantFields::Unit => 0,
503 VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.len(),
504 }
505 }
506
507 pub fn iter(&self) -> std::slice::Iter<'_, EnumFieldDefinition> {
508 match self {
509 VariantFields::Unit => [].iter(),
510 VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.iter(),
511 }
512 }
513
514 pub fn is_struct(&self) -> bool {
515 matches!(self, VariantFields::Struct(_))
516 }
517}
518
519impl<'a> IntoIterator for &'a VariantFields {
520 type Item = &'a EnumFieldDefinition;
521 type IntoIter = std::slice::Iter<'a, EnumFieldDefinition>;
522
523 fn into_iter(self) -> Self::IntoIter {
524 self.iter()
525 }
526}
527
528#[derive(Debug, Clone, PartialEq)]
529pub struct EnumVariant {
530 pub doc: Option<String>,
531 pub name: EcoString,
532 pub name_span: Span,
533 pub fields: VariantFields,
534}
535
536#[derive(Debug, Clone, PartialEq)]
537pub struct EnumFieldDefinition {
538 pub name: EcoString,
539 pub name_span: Span,
540 pub annotation: Annotation,
541 pub ty: Type,
542}
543
544#[derive(Debug, Clone, PartialEq)]
545pub struct Attribute {
546 pub name: String,
547 pub args: Vec<AttributeArg>,
548 pub span: Span,
549}
550
551#[derive(Debug, Clone, PartialEq)]
552#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
553pub enum AttributeArg {
554 Flag(String),
556 NegatedFlag(String),
558 String(String),
560 Raw(String),
562}
563
564#[derive(Debug, Clone, Copy, PartialEq)]
565#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
566pub enum StructKind {
567 Record,
568 Tuple,
569}
570
571#[derive(Debug, Clone, PartialEq)]
572pub struct StructFieldDefinition {
573 pub doc: Option<String>,
574 pub attributes: Vec<Attribute>,
575 pub name: EcoString,
576 pub name_span: Span,
577 pub annotation: Annotation,
578 pub visibility: Visibility,
579 pub ty: Type,
580 pub embedded: bool,
581}
582
583#[derive(Debug, Clone, PartialEq)]
584pub struct StructFieldAssignment {
585 pub name: EcoString,
586 pub name_span: Span,
587 pub value: Box<Expression>,
588}
589
590#[derive(Debug, Clone, PartialEq)]
591pub enum StructSpread {
592 None,
593 From(Box<Expression>),
594 ZeroFill { span: Span },
595}
596
597impl StructSpread {
598 pub fn is_none(&self) -> bool {
599 matches!(self, Self::None)
600 }
601
602 pub fn is_some(&self) -> bool {
603 !self.is_none()
604 }
605
606 pub fn span(&self) -> Option<Span> {
607 match self {
608 Self::None => None,
609 Self::From(e) => Some(e.get_span()),
610 Self::ZeroFill { span } => Some(*span),
611 }
612 }
613
614 pub fn as_expression(&self) -> Option<&Expression> {
615 match self {
616 Self::From(e) => Some(e),
617 Self::None | Self::ZeroFill { .. } => None,
618 }
619 }
620}
621
622#[derive(Debug, Clone, PartialEq)]
623#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
624pub enum Annotation {
625 Constructor {
626 name: EcoString,
627 params: Vec<Self>,
628 span: Span,
629 },
630 Function {
631 params: Vec<Self>,
632 return_type: Box<Self>,
633 span: Span,
634 },
635 Tuple {
636 elements: Vec<Self>,
637 span: Span,
638 },
639 Unknown,
640 Opaque {
641 span: Span,
642 },
643}
644
645impl Annotation {
646 pub fn unit() -> Self {
647 Self::Constructor {
648 name: "Unit".into(),
649 params: vec![],
650 span: Span::dummy(),
651 }
652 }
653
654 pub fn get_span(&self) -> Span {
655 match self {
656 Self::Constructor { span, .. } => *span,
657 Self::Function { span, .. } => *span,
658 Self::Tuple { span, .. } => *span,
659 Self::Opaque { span } => *span,
660 Self::Unknown => Span::dummy(),
661 }
662 }
663
664 pub fn get_name(&self) -> Option<String> {
665 match self {
666 Self::Constructor { name, .. } => Some(name.to_string()),
667 _ => None,
668 }
669 }
670
671 pub fn is_unit(&self) -> bool {
672 matches!(self, Self::Constructor { name, params, .. } if name == "Unit" && params.is_empty())
673 }
674
675 pub fn is_unknown(&self) -> bool {
676 matches!(self, Self::Unknown)
677 }
678
679 pub fn is_opaque(&self) -> bool {
680 matches!(self, Self::Opaque { .. })
681 }
682}
683
684#[derive(Debug, Clone, PartialEq)]
685pub struct Generic {
686 pub name: EcoString,
687 pub bounds: Vec<Annotation>,
688 pub span: Span,
689}
690
691#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
692#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
693pub struct Span {
694 pub file_id: u32,
695 pub byte_offset: u32,
696 pub byte_length: u32,
697}
698
699impl Span {
700 pub fn new(file_id: u32, byte_offset: u32, byte_length: u32) -> Self {
701 Span {
702 file_id,
703 byte_offset,
704 byte_length,
705 }
706 }
707
708 pub fn dummy() -> Self {
709 Span {
710 file_id: 0,
711 byte_offset: 0,
712 byte_length: 0,
713 }
714 }
715
716 pub fn is_dummy(&self) -> bool {
717 self.byte_length == 0
718 }
719
720 pub fn end(&self) -> u32 {
721 self.byte_offset + self.byte_length
722 }
723
724 pub fn merge(self, other: Span) -> Span {
725 Span::new(
726 self.file_id,
727 self.byte_offset,
728 other.end() - self.byte_offset,
729 )
730 }
731}
732
733#[derive(Debug, Clone, PartialEq)]
734#[allow(clippy::large_enum_variant)]
735pub enum Expression {
736 Literal {
737 literal: Literal,
738 ty: Type,
739 span: Span,
740 },
741 Function {
742 doc: Option<String>,
743 attributes: Vec<Attribute>,
744 name: EcoString,
745 name_span: Span,
746 generics: Vec<Generic>,
747 params: Vec<Binding>,
748 return_annotation: Annotation,
749 return_type: Type,
750 visibility: Visibility,
751 body: Box<Expression>,
752 ty: Type,
753 span: Span,
754 },
755 Lambda {
756 params: Vec<Binding>,
757 return_annotation: Annotation,
758 body: Box<Expression>,
759 ty: Type,
760 span: Span,
761 },
762 Block {
763 items: Vec<Expression>,
764 ty: Type,
765 span: Span,
766 },
767 Let {
768 binding: Box<Binding>,
769 value: Box<Expression>,
770 mutable: bool,
771 mut_span: Option<Span>,
772 else_block: Option<Box<Expression>>,
773 else_span: Option<Span>,
774 assert: bool,
775 typed_pattern: Option<TypedPattern>,
776 ty: Type,
777 span: Span,
778 },
779 Identifier {
780 value: EcoString,
781 ty: Type,
782 span: Span,
783 binding_id: Option<BindingId>,
784 qualified: Option<EcoString>,
785 },
786 Call {
787 expression: Box<Expression>,
788 args: Vec<Expression>,
789 spread: Box<Option<Expression>>,
790 raw_type_args: Vec<Annotation>,
793 resolved_type_args: Vec<Type>,
797 ty: Type,
798 span: Span,
799 call_kind: Option<CallKind>,
800 },
801 If {
802 condition: Box<Expression>,
803 consequence: Box<Expression>,
804 alternative: Box<Expression>,
805 ty: Type,
806 span: Span,
807 },
808 IfLet {
809 pattern: Pattern,
810 scrutinee: Box<Expression>,
811 consequence: Box<Expression>,
812 alternative: Box<Expression>,
813 typed_pattern: Option<TypedPattern>,
814 else_span: Option<Span>,
815 ty: Type,
816 span: Span,
817 },
818 Match {
819 subject: Box<Expression>,
820 arms: Vec<MatchArm>,
821 ty: Type,
822 span: Span,
823 },
824 Tuple {
825 elements: Vec<Expression>,
826 ty: Type,
827 span: Span,
828 },
829 StructCall {
830 name: EcoString,
831 field_assignments: Vec<StructFieldAssignment>,
832 spread: StructSpread,
833 ty: Type,
834 span: Span,
835 },
836 DotAccess {
837 expression: Box<Expression>,
838 member: EcoString,
839 ty: Type,
840 span: Span,
841 dot_access_kind: Option<DotAccessKind>,
842 receiver_coercion: Option<ReceiverCoercion>,
843 },
844 Assignment {
845 target: Box<Expression>,
846 value: Box<Expression>,
847 compound_operator: Option<BinaryOperator>,
848 span: Span,
849 },
850 Return {
851 expression: Box<Expression>,
852 ty: Type,
853 span: Span,
854 },
855 Propagate {
856 expression: Box<Expression>,
857 ty: Type,
858 span: Span,
859 },
860 TryBlock {
861 items: Vec<Expression>,
862 ty: Type,
863 try_keyword_span: Span,
864 span: Span,
865 },
866 RecoverBlock {
867 items: Vec<Expression>,
868 ty: Type,
869 recover_keyword_span: Span,
870 span: Span,
871 },
872 ImplBlock {
873 annotation: Annotation,
874 receiver_name: EcoString,
875 methods: Vec<Expression>,
876 generics: Vec<Generic>,
877 ty: Type,
878 span: Span,
879 },
880 Binary {
881 operator: BinaryOperator,
882 left: Box<Expression>,
883 right: Box<Expression>,
884 ty: Type,
885 span: Span,
886 },
887 Unary {
888 operator: UnaryOperator,
889 expression: Box<Expression>,
890 ty: Type,
891 span: Span,
892 },
893 Paren {
894 expression: Box<Expression>,
895 ty: Type,
896 span: Span,
897 },
898 Const {
899 doc: Option<String>,
900 identifier: EcoString,
901 identifier_span: Span,
902 annotation: Option<Annotation>,
903 expression: Box<Expression>,
904 visibility: Visibility,
905 ty: Type,
906 span: Span,
907 },
908 VariableDeclaration {
909 doc: Option<String>,
910 name: EcoString,
911 name_span: Span,
912 annotation: Annotation,
913 visibility: Visibility,
914 ty: Type,
915 span: Span,
916 },
917 RawGo {
918 text: String,
919 },
920 Loop {
921 body: Box<Expression>,
922 ty: Type,
923 span: Span,
924 needs_label: bool,
925 },
926 While {
927 condition: Box<Expression>,
928 body: Box<Expression>,
929 span: Span,
930 needs_label: bool,
931 },
932 WhileLet {
933 pattern: Pattern,
934 scrutinee: Box<Expression>,
935 body: Box<Expression>,
936 typed_pattern: Option<TypedPattern>,
937 span: Span,
938 needs_label: bool,
939 },
940 For {
941 binding: Box<Binding>,
942 iterable: Box<Expression>,
943 body: Box<Expression>,
944 span: Span,
945 needs_label: bool,
946 binding_id: Option<BindingId>,
947 },
948 Break {
949 value: Option<Box<Expression>>,
950 span: Span,
951 },
952 Continue {
953 span: Span,
954 },
955 Enum {
956 doc: Option<String>,
957 attributes: Vec<Attribute>,
958 name: EcoString,
959 name_span: Span,
960 generics: Vec<Generic>,
961 variants: Vec<EnumVariant>,
962 visibility: Visibility,
963 span: Span,
964 },
965 Struct {
966 doc: Option<String>,
967 attributes: Vec<Attribute>,
968 name: EcoString,
969 name_span: Span,
970 generics: Vec<Generic>,
971 fields: Vec<StructFieldDefinition>,
972 kind: StructKind,
973 visibility: Visibility,
974 span: Span,
975 },
976 TypeAlias {
977 doc: Option<String>,
978 attributes: Vec<Attribute>,
979 name: EcoString,
980 name_span: Span,
981 generics: Vec<Generic>,
982 annotation: Annotation,
983 ty: Type,
984 visibility: Visibility,
985 span: Span,
986 },
987 ModuleImport {
988 name: EcoString,
989 name_span: Span,
990 alias: Option<ImportAlias>,
991 span: Span,
992 },
993 Reference {
994 expression: Box<Expression>,
995 ty: Type,
996 span: Span,
997 },
998 Interface {
999 doc: Option<String>,
1000 name: EcoString,
1001 name_span: Span,
1002 generics: Vec<Generic>,
1003 parents: Vec<ParentInterface>,
1004 method_signatures: Vec<Expression>,
1005 visibility: Visibility,
1006 span: Span,
1007 },
1008 IndexedAccess {
1009 expression: Box<Expression>,
1010 index: Box<Expression>,
1011 ty: Type,
1012 span: Span,
1013 from_colon_syntax: bool,
1014 },
1015 Task {
1016 expression: Box<Expression>,
1017 ty: Type,
1018 span: Span,
1019 },
1020 Defer {
1021 expression: Box<Expression>,
1022 ty: Type,
1023 span: Span,
1024 },
1025 Assert {
1026 expression: Box<Expression>,
1027 ty: Type,
1028 span: Span,
1029 },
1030 Select {
1031 arms: Vec<SelectArm>,
1032 ty: Type,
1033 span: Span,
1034 },
1035 Unit {
1036 ty: Type,
1037 span: Span,
1038 },
1039 Range {
1040 start: Option<Box<Expression>>,
1041 end: Option<Box<Expression>>,
1042 inclusive: bool,
1043 ty: Type,
1044 span: Span,
1045 },
1046 Cast {
1047 expression: Box<Expression>,
1048 target_type: Annotation,
1049 ty: Type,
1050 span: Span,
1051 },
1052 NoOp,
1053}
1054
1055#[derive(Clone, Copy)]
1057pub enum ExpressionKind {
1058 Literal,
1059 Function,
1060 Lambda,
1061 Block,
1062 Let,
1063 Identifier,
1064 Call,
1065 If,
1066 IfLet,
1067 Match,
1068 Tuple,
1069 StructCall,
1070 DotAccess,
1071 Assignment,
1072 Return,
1073 Propagate,
1074 TryBlock,
1075 RecoverBlock,
1076 ImplBlock,
1077 Binary,
1078 Unary,
1079 Paren,
1080 Const,
1081 VariableDeclaration,
1082 RawGo,
1083 Loop,
1084 While,
1085 WhileLet,
1086 For,
1087 Break,
1088 Continue,
1089 Enum,
1090 Struct,
1091 TypeAlias,
1092 ModuleImport,
1093 Reference,
1094 Interface,
1095 IndexedAccess,
1096 Task,
1097 Defer,
1098 Assert,
1099 Select,
1100 Unit,
1101 Range,
1102 Cast,
1103 NoOp,
1104}
1105
1106impl ExpressionKind {
1107 pub const COUNT: usize = ExpressionKind::NoOp as usize + 1;
1109}
1110
1111impl Expression {
1112 pub fn kind(&self) -> ExpressionKind {
1113 match self {
1114 Expression::Literal { .. } => ExpressionKind::Literal,
1115 Expression::Function { .. } => ExpressionKind::Function,
1116 Expression::Lambda { .. } => ExpressionKind::Lambda,
1117 Expression::Block { .. } => ExpressionKind::Block,
1118 Expression::Let { .. } => ExpressionKind::Let,
1119 Expression::Identifier { .. } => ExpressionKind::Identifier,
1120 Expression::Call { .. } => ExpressionKind::Call,
1121 Expression::If { .. } => ExpressionKind::If,
1122 Expression::IfLet { .. } => ExpressionKind::IfLet,
1123 Expression::Match { .. } => ExpressionKind::Match,
1124 Expression::Tuple { .. } => ExpressionKind::Tuple,
1125 Expression::StructCall { .. } => ExpressionKind::StructCall,
1126 Expression::DotAccess { .. } => ExpressionKind::DotAccess,
1127 Expression::Assignment { .. } => ExpressionKind::Assignment,
1128 Expression::Return { .. } => ExpressionKind::Return,
1129 Expression::Propagate { .. } => ExpressionKind::Propagate,
1130 Expression::TryBlock { .. } => ExpressionKind::TryBlock,
1131 Expression::RecoverBlock { .. } => ExpressionKind::RecoverBlock,
1132 Expression::ImplBlock { .. } => ExpressionKind::ImplBlock,
1133 Expression::Binary { .. } => ExpressionKind::Binary,
1134 Expression::Unary { .. } => ExpressionKind::Unary,
1135 Expression::Paren { .. } => ExpressionKind::Paren,
1136 Expression::Const { .. } => ExpressionKind::Const,
1137 Expression::VariableDeclaration { .. } => ExpressionKind::VariableDeclaration,
1138 Expression::RawGo { .. } => ExpressionKind::RawGo,
1139 Expression::Loop { .. } => ExpressionKind::Loop,
1140 Expression::While { .. } => ExpressionKind::While,
1141 Expression::WhileLet { .. } => ExpressionKind::WhileLet,
1142 Expression::For { .. } => ExpressionKind::For,
1143 Expression::Break { .. } => ExpressionKind::Break,
1144 Expression::Continue { .. } => ExpressionKind::Continue,
1145 Expression::Enum { .. } => ExpressionKind::Enum,
1146 Expression::Struct { .. } => ExpressionKind::Struct,
1147 Expression::TypeAlias { .. } => ExpressionKind::TypeAlias,
1148 Expression::ModuleImport { .. } => ExpressionKind::ModuleImport,
1149 Expression::Reference { .. } => ExpressionKind::Reference,
1150 Expression::Interface { .. } => ExpressionKind::Interface,
1151 Expression::IndexedAccess { .. } => ExpressionKind::IndexedAccess,
1152 Expression::Task { .. } => ExpressionKind::Task,
1153 Expression::Defer { .. } => ExpressionKind::Defer,
1154 Expression::Assert { .. } => ExpressionKind::Assert,
1155 Expression::Select { .. } => ExpressionKind::Select,
1156 Expression::Unit { .. } => ExpressionKind::Unit,
1157 Expression::Range { .. } => ExpressionKind::Range,
1158 Expression::Cast { .. } => ExpressionKind::Cast,
1159 Expression::NoOp => ExpressionKind::NoOp,
1160 }
1161 }
1162
1163 pub fn is_noop(&self) -> bool {
1164 matches!(self, Expression::NoOp)
1165 }
1166
1167 pub fn is_block(&self) -> bool {
1168 matches!(self, Expression::Block { .. })
1169 }
1170
1171 pub fn is_range(&self) -> bool {
1172 matches!(self, Expression::Range { .. })
1173 }
1174
1175 pub fn is_conditional(&self) -> bool {
1176 matches!(self, Expression::If { .. } | Expression::IfLet { .. })
1177 }
1178
1179 pub fn is_control_flow(&self) -> bool {
1180 matches!(
1181 self,
1182 Expression::If { .. }
1183 | Expression::IfLet { .. }
1184 | Expression::Match { .. }
1185 | Expression::Select { .. }
1186 | Expression::For { .. }
1187 | Expression::While { .. }
1188 | Expression::WhileLet { .. }
1189 | Expression::Loop { .. }
1190 )
1191 }
1192
1193 pub fn is_temp_producing(&self) -> bool {
1194 matches!(
1195 self.unwrap_parens(),
1196 Expression::If { .. }
1197 | Expression::IfLet { .. }
1198 | Expression::Match { .. }
1199 | Expression::Block { .. }
1200 | Expression::Loop { .. }
1201 | Expression::Select { .. }
1202 | Expression::TryBlock { .. }
1203 | Expression::RecoverBlock { .. }
1204 )
1205 }
1206
1207 pub fn callee_name(&self) -> Option<String> {
1208 let Expression::Call { expression, .. } = self else {
1209 return None;
1210 };
1211 match expression.as_ref() {
1212 Expression::Identifier { value, .. } => Some(value.to_string()),
1213 Expression::DotAccess {
1214 expression: base,
1215 member,
1216 ..
1217 } => {
1218 if let Expression::Identifier { value, .. } = base.as_ref() {
1219 Some(format!("{}.{}", value, member))
1220 } else {
1221 None
1222 }
1223 }
1224 _ => None,
1225 }
1226 }
1227
1228 pub fn to_function_signature(&self) -> FunctionDefinition {
1229 match self {
1230 Expression::Function {
1231 name,
1232 name_span,
1233 generics,
1234 params,
1235 return_annotation,
1236 return_type,
1237 ty,
1238 ..
1239 } => FunctionDefinition {
1240 name: name.clone(),
1241 name_span: *name_span,
1242 generics: generics.clone(),
1243 params: params.clone(),
1244 body: Box::new(Expression::NoOp),
1245 return_type: return_type.clone(),
1246 annotation: return_annotation.clone(),
1247 ty: ty.clone(),
1248 },
1249 _ => panic!("to_function_signature called on non-Function expression"),
1250 }
1251 }
1252
1253 pub fn function_definition_view(&self) -> FunctionDefinitionView<'_> {
1254 match self {
1255 Expression::Function {
1256 name,
1257 name_span,
1258 generics,
1259 params,
1260 return_type,
1261 body,
1262 ..
1263 } => FunctionDefinitionView {
1264 name,
1265 name_span: *name_span,
1266 generics,
1267 params,
1268 body,
1269 return_type,
1270 },
1271 _ => panic!("function_definition_view called on non-Function expression"),
1272 }
1273 }
1274
1275 pub fn as_option_constructor(&self) -> Option<std::result::Result<(), ()>> {
1276 let variant = match self {
1277 Expression::Identifier { value, .. } => Some(value.as_str()),
1278 _ => None,
1279 }?;
1280
1281 match variant {
1282 "Option.Some" | "Some" => Some(Ok(())),
1283 "Option.None" | "None" => Some(Err(())),
1284 _ => None,
1285 }
1286 }
1287
1288 pub fn is_none_literal(&self) -> bool {
1289 matches!(self.as_option_constructor(), Some(Err(())))
1290 }
1291
1292 pub fn as_result_constructor(&self) -> Option<std::result::Result<(), ()>> {
1293 let variant = match self {
1294 Expression::Identifier { value, .. } => Some(value.as_str()),
1295 _ => None,
1296 }?;
1297
1298 match variant {
1299 "Result.Ok" | "Ok" => Some(Ok(())),
1300 "Result.Err" | "Err" => Some(Err(())),
1301 _ => None,
1302 }
1303 }
1304
1305 pub fn as_partial_constructor(&self) -> Option<&'static str> {
1306 let variant = match self {
1307 Expression::Identifier { value, .. } => Some(value.as_str()),
1308 _ => None,
1309 }?;
1310
1311 match variant {
1312 "Partial.Ok" => Some("Ok"),
1313 "Partial.Err" => Some("Err"),
1314 "Partial.Both" => Some("Both"),
1315 _ => None,
1316 }
1317 }
1318
1319 pub fn get_type(&self) -> Type {
1320 match self {
1321 Self::Literal { ty, .. }
1322 | Self::Function { ty, .. }
1323 | Self::Lambda { ty, .. }
1324 | Self::Block { ty, .. }
1325 | Self::Let { ty, .. }
1326 | Self::Identifier { ty, .. }
1327 | Self::Call { ty, .. }
1328 | Self::If { ty, .. }
1329 | Self::IfLet { ty, .. }
1330 | Self::Match { ty, .. }
1331 | Self::Tuple { ty, .. }
1332 | Self::StructCall { ty, .. }
1333 | Self::DotAccess { ty, .. }
1334 | Self::Return { ty, .. }
1335 | Self::Propagate { ty, .. }
1336 | Self::TryBlock { ty, .. }
1337 | Self::RecoverBlock { ty, .. }
1338 | Self::Binary { ty, .. }
1339 | Self::Paren { ty, .. }
1340 | Self::Unary { ty, .. }
1341 | Self::Const { ty, .. }
1342 | Self::VariableDeclaration { ty, .. }
1343 | Self::Defer { ty, .. }
1344 | Self::Assert { ty, .. }
1345 | Self::Reference { ty, .. }
1346 | Self::IndexedAccess { ty, .. }
1347 | Self::Task { ty, .. }
1348 | Self::Select { ty, .. }
1349 | Self::Unit { ty, .. }
1350 | Self::Loop { ty, .. }
1351 | Self::Range { ty, .. }
1352 | Self::Cast { ty, .. } => ty.clone(),
1353 Self::Enum { .. }
1354 | Self::Struct { .. }
1355 | Self::Assignment { .. }
1356 | Self::ImplBlock { .. }
1357 | Self::TypeAlias { .. }
1358 | Self::ModuleImport { .. }
1359 | Self::Interface { .. }
1360 | Self::NoOp
1361 | Self::RawGo { .. }
1362 | Self::While { .. }
1363 | Self::WhileLet { .. }
1364 | Self::For { .. } => Type::ignored(),
1365 Self::Break { .. } | Self::Continue { .. } => Type::Never,
1366 }
1367 }
1368
1369 pub fn get_span(&self) -> Span {
1370 match self {
1371 Self::Literal { span, .. }
1372 | Self::Function { span, .. }
1373 | Self::Lambda { span, .. }
1374 | Self::Block { span, .. }
1375 | Self::Let { span, .. }
1376 | Self::Identifier { span, .. }
1377 | Self::Call { span, .. }
1378 | Self::If { span, .. }
1379 | Self::IfLet { span, .. }
1380 | Self::Match { span, .. }
1381 | Self::Tuple { span, .. }
1382 | Self::Enum { span, .. }
1383 | Self::Struct { span, .. }
1384 | Self::StructCall { span, .. }
1385 | Self::DotAccess { span, .. }
1386 | Self::Assignment { span, .. }
1387 | Self::Return { span, .. }
1388 | Self::Propagate { span, .. }
1389 | Self::TryBlock { span, .. }
1390 | Self::RecoverBlock { span, .. }
1391 | Self::ImplBlock { span, .. }
1392 | Self::Binary { span, .. }
1393 | Self::Paren { span, .. }
1394 | Self::Unary { span, .. }
1395 | Self::Const { span, .. }
1396 | Self::VariableDeclaration { span, .. }
1397 | Self::Defer { span, .. }
1398 | Self::Assert { span, .. }
1399 | Self::Reference { span, .. }
1400 | Self::IndexedAccess { span, .. }
1401 | Self::Task { span, .. }
1402 | Self::Select { span, .. }
1403 | Self::Loop { span, .. }
1404 | Self::TypeAlias { span, .. }
1405 | Self::ModuleImport { span, .. }
1406 | Self::Interface { span, .. }
1407 | Self::Unit { span, .. }
1408 | Self::While { span, .. }
1409 | Self::WhileLet { span, .. }
1410 | Self::For { span, .. }
1411 | Self::Break { span, .. }
1412 | Self::Continue { span, .. }
1413 | Self::Range { span, .. }
1414 | Self::Cast { span, .. } => *span,
1415 Self::NoOp | Self::RawGo { .. } => Span::dummy(),
1416 }
1417 }
1418
1419 pub fn contains_break(&self) -> bool {
1420 match self {
1421 Expression::Break { .. } => true,
1422
1423 Expression::Loop { .. }
1424 | Expression::While { .. }
1425 | Expression::WhileLet { .. }
1426 | Expression::For { .. } => false,
1427
1428 Expression::Block { items, .. } => items.iter().any(Self::contains_break),
1429
1430 Expression::TryBlock { items, .. } => items.iter().any(Self::contains_break),
1431 Expression::RecoverBlock { items, .. } => items.iter().any(Self::contains_break),
1432
1433 Expression::If {
1434 condition,
1435 consequence,
1436 alternative,
1437 ..
1438 } => {
1439 condition.contains_break()
1440 || consequence.contains_break()
1441 || alternative.contains_break()
1442 }
1443
1444 Expression::IfLet {
1445 scrutinee,
1446 consequence,
1447 alternative,
1448 ..
1449 } => {
1450 scrutinee.contains_break()
1451 || consequence.contains_break()
1452 || alternative.contains_break()
1453 }
1454
1455 Expression::Match { subject, arms, .. } => {
1456 subject.contains_break() || arms.iter().any(|arm| arm.expression.contains_break())
1457 }
1458
1459 Expression::Paren { expression, .. } => expression.contains_break(),
1460
1461 Expression::Binary { left, right, .. } => {
1462 left.contains_break() || right.contains_break()
1463 }
1464
1465 Expression::Unary { expression, .. } => expression.contains_break(),
1466
1467 Expression::Call {
1468 expression,
1469 args,
1470 spread,
1471 ..
1472 } => {
1473 expression.contains_break()
1474 || args.iter().any(Self::contains_break)
1475 || spread.as_ref().as_ref().is_some_and(Self::contains_break)
1476 }
1477
1478 Expression::Function { .. } | Expression::Lambda { .. } => false,
1479
1480 Expression::Select { arms, .. } => arms.iter().any(|arm| match &arm.pattern {
1481 SelectArmPattern::Receive { body, .. } => body.contains_break(),
1482 SelectArmPattern::Send { body, .. } => body.contains_break(),
1483 SelectArmPattern::MatchReceive { arms, .. } => {
1484 arms.iter().any(|a| a.expression.contains_break())
1485 }
1486 SelectArmPattern::WildCard { body } => body.contains_break(),
1487 }),
1488
1489 Expression::Cast { expression, .. } => expression.contains_break(),
1490
1491 Expression::Let {
1492 value, else_block, ..
1493 } => value.contains_break() || else_block.as_ref().is_some_and(|e| e.contains_break()),
1494
1495 Expression::Assignment { value, .. } => value.contains_break(),
1496
1497 _ => false,
1498 }
1499 }
1500
1501 pub fn diverges(&self) -> Option<DeadCodeCause> {
1502 match self {
1503 Expression::Return { .. } => Some(DeadCodeCause::Return),
1504 Expression::Break { .. } => Some(DeadCodeCause::Break),
1505 Expression::Continue { .. } => Some(DeadCodeCause::Continue),
1506
1507 Expression::If {
1508 consequence,
1509 alternative,
1510 ..
1511 } => {
1512 if consequence.diverges().is_some() && alternative.diverges().is_some() {
1513 Some(DeadCodeCause::DivergingIf)
1514 } else {
1515 None
1516 }
1517 }
1518
1519 Expression::IfLet {
1520 consequence,
1521 alternative,
1522 ..
1523 } => {
1524 if consequence.diverges().is_some() && alternative.diverges().is_some() {
1525 Some(DeadCodeCause::DivergingIf)
1526 } else {
1527 None
1528 }
1529 }
1530
1531 Expression::Match { arms, .. } => {
1532 if !arms.is_empty() && arms.iter().all(|arm| arm.expression.diverges().is_some()) {
1533 Some(DeadCodeCause::DivergingMatch)
1534 } else {
1535 None
1536 }
1537 }
1538
1539 Expression::Block { items, .. } => {
1540 for item in items {
1541 if let Some(cause) = item.diverges() {
1542 return Some(cause);
1543 }
1544 }
1545 None
1546 }
1547
1548 Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
1549 for item in items {
1550 if let Some(cause) = item.diverges() {
1551 return Some(cause);
1552 }
1553 }
1554 None
1555 }
1556
1557 Expression::Paren { expression, .. } | Expression::Cast { expression, .. } => {
1558 expression.diverges()
1559 }
1560
1561 Expression::Loop { body, .. } => {
1562 if !body.contains_break() {
1563 Some(DeadCodeCause::InfiniteLoop)
1564 } else {
1565 None
1566 }
1567 }
1568
1569 Expression::Call { ty, .. } if ty.is_never() => Some(DeadCodeCause::DivergingCall),
1570
1571 _ => None,
1572 }
1573 }
1574
1575 pub fn children(&self) -> Children<'_> {
1580 match self {
1581 Expression::Literal { literal, .. } => match literal {
1582 Literal::Slice(elements) => elements.iter().collect(),
1583 Literal::FormatString(parts) => parts
1584 .iter()
1585 .filter_map(|p| match p {
1586 FormatStringPart::Expression(e) => Some(e.as_ref()),
1587 FormatStringPart::Text(_) => None,
1588 })
1589 .collect(),
1590 _ => Children::new(),
1591 },
1592 Expression::Function { body, .. } => children![body],
1593 Expression::Lambda { body, .. } => children![body],
1594 Expression::Block { items, .. } => items.iter().collect(),
1595 Expression::Let {
1596 value, else_block, ..
1597 } => {
1598 let mut c = children![value.as_ref()];
1599 if let Some(eb) = else_block {
1600 c.push(eb);
1601 }
1602 c
1603 }
1604 Expression::Identifier { .. } => Children::new(),
1605 Expression::Call {
1606 expression,
1607 args,
1608 spread,
1609 ..
1610 } => {
1611 let mut c = children![expression.as_ref()];
1612 c.extend(args);
1613 if let Some(s) = spread.as_ref() {
1614 c.push(s);
1615 }
1616 c
1617 }
1618 Expression::If {
1619 condition,
1620 consequence,
1621 alternative,
1622 ..
1623 } => children![condition, consequence, alternative],
1624 Expression::IfLet {
1625 scrutinee,
1626 consequence,
1627 alternative,
1628 ..
1629 } => children![scrutinee, consequence, alternative],
1630 Expression::Match { subject, arms, .. } => {
1631 let mut c = children![subject.as_ref()];
1632 for arm in arms {
1633 if let Some(guard) = &arm.guard {
1634 c.push(guard);
1635 }
1636 c.push(&arm.expression);
1637 }
1638 c
1639 }
1640 Expression::Tuple { elements, .. } => elements.iter().collect(),
1641 Expression::StructCall {
1642 field_assignments,
1643 spread,
1644 ..
1645 } => {
1646 let mut c: Children = field_assignments.iter().map(|f| f.value.as_ref()).collect();
1647 if let Some(s) = spread.as_expression() {
1648 c.push(s);
1649 }
1650 c
1651 }
1652 Expression::DotAccess { expression, .. } => children![expression],
1653 Expression::Assignment { target, value, .. } => children![target, value],
1654 Expression::Return { expression, .. } => children![expression],
1655 Expression::Propagate { expression, .. } => children![expression],
1656 Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
1657 items.iter().collect()
1658 }
1659 Expression::ImplBlock { methods, .. } => methods.iter().collect(),
1660 Expression::Binary { left, right, .. } => children![left, right],
1661 Expression::Unary { expression, .. } => children![expression],
1662 Expression::Paren { expression, .. } => children![expression],
1663 Expression::Const { expression, .. } => children![expression],
1664 Expression::Loop { body, .. } => children![body],
1665 Expression::While {
1666 condition, body, ..
1667 } => children![condition, body],
1668 Expression::WhileLet {
1669 scrutinee, body, ..
1670 } => children![scrutinee, body],
1671 Expression::For { iterable, body, .. } => children![iterable, body],
1672 Expression::Break { value, .. } => value
1673 .as_ref()
1674 .map(|v| children![v.as_ref()])
1675 .unwrap_or_default(),
1676 Expression::Reference { expression, .. } => children![expression],
1677 Expression::IndexedAccess {
1678 expression, index, ..
1679 } => children![expression, index],
1680 Expression::Task { expression, .. } => children![expression],
1681 Expression::Defer { expression, .. } => children![expression],
1682 Expression::Assert { expression, .. } => children![expression],
1683 Expression::Select { arms, .. } => {
1684 let mut c = Children::new();
1685 for arm in arms {
1686 match &arm.pattern {
1687 SelectArmPattern::Receive {
1688 receive_expression,
1689 body,
1690 ..
1691 } => {
1692 c.push(receive_expression.as_ref());
1693 c.push(body.as_ref());
1694 }
1695 SelectArmPattern::Send {
1696 send_expression,
1697 body,
1698 } => {
1699 c.push(send_expression.as_ref());
1700 c.push(body.as_ref());
1701 }
1702 SelectArmPattern::MatchReceive {
1703 receive_expression,
1704 arms: match_arms,
1705 } => {
1706 c.push(receive_expression.as_ref());
1707 for ma in match_arms {
1708 if let Some(guard) = &ma.guard {
1709 c.push(guard);
1710 }
1711 c.push(&ma.expression);
1712 }
1713 }
1714 SelectArmPattern::WildCard { body } => {
1715 c.push(body.as_ref());
1716 }
1717 }
1718 }
1719 c
1720 }
1721 Expression::Range { start, end, .. } => {
1722 let mut c = Children::new();
1723 if let Some(s) = start {
1724 c.push(s.as_ref());
1725 }
1726 if let Some(e) = end {
1727 c.push(e.as_ref());
1728 }
1729 c
1730 }
1731 Expression::Cast { expression, .. } => children![expression],
1732 Expression::Interface {
1733 method_signatures, ..
1734 } => method_signatures.iter().collect(),
1735 Expression::Unit { .. }
1736 | Expression::Continue { .. }
1737 | Expression::Enum { .. }
1738 | Expression::Struct { .. }
1739 | Expression::TypeAlias { .. }
1740 | Expression::VariableDeclaration { .. }
1741 | Expression::ModuleImport { .. }
1742 | Expression::RawGo { .. }
1743 | Expression::NoOp => Children::new(),
1744 }
1745 }
1746
1747 pub fn unwrap_parens(&self) -> &Expression {
1748 match self {
1749 Expression::Paren { expression, .. } => expression.unwrap_parens(),
1750 other => other,
1751 }
1752 }
1753
1754 pub fn binding_id(&self) -> Option<BindingId> {
1755 match self.unwrap_parens() {
1756 Expression::Identifier { binding_id, .. } => *binding_id,
1757 _ => None,
1758 }
1759 }
1760
1761 pub fn as_integer(&self) -> Option<u64> {
1762 match self.unwrap_parens() {
1763 Expression::Literal {
1764 literal: Literal::Integer { value, .. },
1765 ..
1766 } => Some(*value),
1767 _ => None,
1768 }
1769 }
1770
1771 #[inline]
1773 pub fn deref_inner(&self) -> Option<&Expression> {
1774 match self {
1775 Expression::Unary {
1776 operator: UnaryOperator::Deref,
1777 expression,
1778 ..
1779 } => Some(expression),
1780 _ => None,
1781 }
1782 }
1783
1784 pub fn as_dotted_path(&self) -> Option<String> {
1785 match self {
1786 Expression::Identifier { value, .. } => Some(value.to_string()),
1787 Expression::DotAccess {
1788 expression, member, ..
1789 } => Some(format!("{}.{}", expression.as_dotted_path()?, member)),
1790 _ => None,
1791 }
1792 }
1793
1794 pub fn root_identifier(&self) -> Option<&str> {
1795 match self {
1796 Expression::Identifier { value, .. } => Some(value),
1797 Expression::DotAccess { expression, .. } => expression.root_identifier(),
1798 _ => None,
1799 }
1800 }
1801
1802 pub fn is_empty_collection(&self) -> bool {
1803 matches!(
1804 self,
1805 Expression::Literal {
1806 literal: Literal::Slice(elements),
1807 ..
1808 } if elements.is_empty()
1809 )
1810 }
1811
1812 pub fn is_all_literals(&self) -> bool {
1813 match self.unwrap_parens() {
1814 Expression::Literal { literal, .. } => match literal {
1815 Literal::Slice(elements) => elements.iter().all(|e| e.is_all_literals()),
1816 Literal::FormatString(parts) => parts.iter().all(|p| match p {
1817 FormatStringPart::Text(_) => true,
1818 FormatStringPart::Expression(e) => e.is_all_literals(),
1819 }),
1820 _ => true,
1821 },
1822 Expression::Tuple { elements, .. } => elements.iter().all(|e| e.is_all_literals()),
1823 Expression::Unit { .. } => true,
1824 _ => false,
1825 }
1826 }
1827
1828 pub fn get_var_name(&self) -> Option<String> {
1829 match self {
1830 Expression::Identifier { value, .. } => Some(value.to_string()),
1831 Expression::DotAccess { expression, .. } => expression.get_var_name(),
1832 Expression::Assignment { target, .. } => target.get_var_name(),
1833 Expression::IndexedAccess { expression, .. } => expression.get_var_name(),
1834 Expression::Paren { expression, .. } => expression.get_var_name(),
1835 Expression::Reference { expression, .. } => expression.get_var_name(),
1836 Expression::Unary {
1837 operator,
1838 expression,
1839 ..
1840 } => {
1841 if operator == &UnaryOperator::Deref {
1842 expression.get_var_name()
1843 } else {
1844 None
1845 }
1846 }
1847 _ => None,
1848 }
1849 }
1850
1851 pub fn is_function(&self) -> bool {
1852 matches!(self, Expression::Function { .. })
1853 }
1854
1855 pub fn set_public(self) -> Self {
1856 match self {
1857 Expression::Enum {
1858 doc,
1859 attributes,
1860 name,
1861 name_span,
1862 generics,
1863 variants,
1864 span,
1865 ..
1866 } => Expression::Enum {
1867 doc,
1868 attributes,
1869 name,
1870 name_span,
1871 generics,
1872 variants,
1873 visibility: Visibility::Public,
1874 span,
1875 },
1876 Expression::Struct {
1877 doc,
1878 attributes,
1879 name,
1880 name_span,
1881 generics,
1882 fields,
1883 kind,
1884 span,
1885 ..
1886 } => {
1887 let fields = if kind == StructKind::Tuple {
1888 fields
1889 .into_iter()
1890 .map(|f| StructFieldDefinition {
1891 visibility: Visibility::Public,
1892 ..f
1893 })
1894 .collect()
1895 } else {
1896 fields
1897 };
1898 Expression::Struct {
1899 doc,
1900 attributes,
1901 name,
1902 name_span,
1903 generics,
1904 fields,
1905 kind,
1906 visibility: Visibility::Public,
1907 span,
1908 }
1909 }
1910 Expression::Function {
1911 doc,
1912 attributes,
1913 name,
1914 name_span,
1915 generics,
1916 params,
1917 return_annotation,
1918 return_type,
1919 body,
1920 ty,
1921 span,
1922 ..
1923 } => Expression::Function {
1924 doc,
1925 attributes,
1926 name,
1927 name_span,
1928 generics,
1929 params,
1930 return_annotation,
1931 return_type,
1932 visibility: Visibility::Public,
1933 body,
1934 ty,
1935 span,
1936 },
1937 Expression::Const {
1938 doc,
1939 identifier,
1940 identifier_span,
1941 annotation,
1942 expression,
1943 ty,
1944 span,
1945 ..
1946 } => Expression::Const {
1947 doc,
1948 identifier,
1949 identifier_span,
1950 annotation,
1951 expression,
1952 visibility: Visibility::Public,
1953 ty,
1954 span,
1955 },
1956 Expression::VariableDeclaration {
1957 doc,
1958 name,
1959 name_span,
1960 annotation,
1961 ty,
1962 span,
1963 ..
1964 } => Expression::VariableDeclaration {
1965 doc,
1966 name,
1967 name_span,
1968 annotation,
1969 visibility: Visibility::Public,
1970 ty,
1971 span,
1972 },
1973 Expression::TypeAlias {
1974 doc,
1975 attributes,
1976 name,
1977 name_span,
1978 generics,
1979 annotation,
1980 ty,
1981 span,
1982 ..
1983 } => Expression::TypeAlias {
1984 doc,
1985 attributes,
1986 name,
1987 name_span,
1988 generics,
1989 annotation,
1990 ty,
1991 visibility: Visibility::Public,
1992 span,
1993 },
1994 Expression::Interface {
1995 doc,
1996 name,
1997 name_span,
1998 generics,
1999 parents,
2000 method_signatures,
2001 span,
2002 ..
2003 } => Expression::Interface {
2004 doc,
2005 name,
2006 name_span,
2007 generics,
2008 parents,
2009 method_signatures,
2010 visibility: Visibility::Public,
2011 span,
2012 },
2013 expression => expression,
2014 }
2015 }
2016
2017 pub fn has_else(&self) -> bool {
2018 match self {
2019 Self::Block { items, .. } if items.is_empty() => false,
2020 Self::Unit { .. } => false,
2021 Self::If { alternative, .. } | Self::IfLet { alternative, .. } => {
2022 alternative.has_else()
2023 }
2024 _ => true,
2025 }
2026 }
2027}
2028
2029#[derive(Debug, Clone, PartialEq)]
2030pub enum Literal {
2031 Integer {
2032 value: u64,
2033 text: Option<String>,
2034 },
2035 Float {
2036 value: f64,
2037 text: Option<String>,
2038 },
2039 Imaginary(f64),
2041 Boolean(bool),
2042 String {
2043 value: String,
2044 raw: bool,
2045 },
2046 FormatString(Vec<FormatStringPart>),
2047 Char(String),
2048 Slice(Vec<Expression>),
2049}
2050
2051#[derive(Debug, Clone, PartialEq)]
2052pub enum FormatStringPart {
2053 Text(String),
2054 Expression(Box<Expression>),
2055}
2056
2057#[derive(Debug, Clone, PartialEq)]
2058pub enum UnaryOperator {
2059 Negative,
2060 Not,
2061 BitwiseNot,
2062 Deref,
2063}
2064
2065#[derive(Debug, Clone, Copy, PartialEq)]
2066pub enum BinaryOperator {
2067 Addition,
2068 Subtraction,
2069 Multiplication,
2070 Division,
2071 BitwiseAnd,
2072 BitwiseOr,
2073 BitwiseXor,
2074 BitwiseAndNot,
2075 ShiftLeft,
2076 ShiftRight,
2077 LessThan,
2078 LessThanOrEqual,
2079 GreaterThan,
2080 GreaterThanOrEqual,
2081 Remainder,
2082 Equal,
2083 NotEqual,
2084 And,
2085 Or,
2086 Pipeline,
2087}
2088
2089impl BinaryOperator {
2090 pub fn compound_assignment_symbol(&self) -> Option<&'static str> {
2094 match self {
2095 BinaryOperator::Addition => Some("+="),
2096 BinaryOperator::Subtraction => Some("-="),
2097 BinaryOperator::Multiplication => Some("*="),
2098 BinaryOperator::Division => Some("/="),
2099 BinaryOperator::Remainder => Some("%="),
2100 BinaryOperator::BitwiseAnd => Some("&="),
2101 BinaryOperator::BitwiseOr => Some("|="),
2102 BinaryOperator::BitwiseXor => Some("^="),
2103 BinaryOperator::BitwiseAndNot => Some("&^="),
2104 BinaryOperator::ShiftLeft => Some("<<="),
2105 BinaryOperator::ShiftRight => Some(">>="),
2106 _ => None,
2107 }
2108 }
2109}
2110
2111impl std::fmt::Display for BinaryOperator {
2112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2113 let symbol = match self {
2114 BinaryOperator::Addition => "+",
2115 BinaryOperator::Subtraction => "-",
2116 BinaryOperator::Multiplication => "*",
2117 BinaryOperator::Division => "/",
2118 BinaryOperator::Remainder => "%",
2119 BinaryOperator::BitwiseAnd => "&",
2120 BinaryOperator::BitwiseOr => "|",
2121 BinaryOperator::BitwiseXor => "^",
2122 BinaryOperator::BitwiseAndNot => "&^",
2123 BinaryOperator::ShiftLeft => "<<",
2124 BinaryOperator::ShiftRight => ">>",
2125 BinaryOperator::Equal => "==",
2126 BinaryOperator::NotEqual => "!=",
2127 BinaryOperator::LessThan => "<",
2128 BinaryOperator::LessThanOrEqual => "<=",
2129 BinaryOperator::GreaterThan => ">",
2130 BinaryOperator::GreaterThanOrEqual => ">=",
2131 BinaryOperator::And => "&&",
2132 BinaryOperator::Or => "||",
2133 BinaryOperator::Pipeline => "|>",
2134 };
2135 write!(f, "{}", symbol)
2136 }
2137}
2138
2139#[derive(Debug, Clone, PartialEq)]
2140pub struct ParentInterface {
2141 pub annotation: Annotation,
2142 pub ty: Type,
2143 pub span: Span,
2144}
2145
2146#[derive(Debug, Clone, Copy, PartialEq)]
2147#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2148pub enum Visibility {
2149 Public,
2150 Private,
2151}
2152
2153impl Visibility {
2154 pub fn is_public(&self) -> bool {
2155 matches!(self, Visibility::Public)
2156 }
2157}
2158
2159#[derive(Debug, Clone, PartialEq)]
2160pub enum ImportAlias {
2161 Named(EcoString, Span),
2162 Blank(Span),
2163}