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, Copy, PartialEq, Eq)]
202pub enum MatchOrigin {
203 Explicit,
204 IfLet { else_span: Option<Span> },
205}
206
207#[derive(Debug, Clone, PartialEq)]
208pub struct SelectArm {
209 pub pattern: SelectArmPattern,
210}
211
212#[derive(Debug, Clone, PartialEq)]
213pub enum SelectArmPattern {
214 Receive {
215 binding: Box<Pattern>,
216 typed_pattern: Option<TypedPattern>,
217 receive_expression: Box<Expression>,
218 body: Box<Expression>,
219 },
220 Send {
221 send_expression: Box<Expression>,
222 body: Box<Expression>,
223 },
224 MatchReceive {
225 receive_expression: Box<Expression>,
226 arms: Vec<MatchArm>,
227 },
228 WildCard {
229 body: Box<Expression>,
230 },
231}
232
233#[derive(Debug, Clone, PartialEq)]
234pub enum RestPattern {
235 Absent,
236 Discard(Span),
237 Bind { name: EcoString, span: Span },
238}
239
240impl RestPattern {
241 pub fn is_present(&self) -> bool {
242 !matches!(self, RestPattern::Absent)
243 }
244}
245
246#[derive(Debug, Clone, PartialEq)]
247pub enum Pattern {
248 Literal {
249 literal: Literal,
250 ty: Type,
251 span: Span,
252 },
253 Unit {
254 ty: Type,
255 span: Span,
256 },
257 EnumVariant {
258 identifier: EcoString,
259 fields: Vec<Self>,
260 rest: bool,
261 ty: Type,
262 span: Span,
263 },
264 Struct {
265 identifier: EcoString,
266 fields: Vec<StructFieldPattern>,
267 rest: bool,
268 ty: Type,
269 span: Span,
270 },
271 Tuple {
272 elements: Vec<Self>,
273 span: Span,
274 },
275 WildCard {
276 span: Span,
277 },
278 Identifier {
279 identifier: EcoString,
280 span: Span,
281 },
282 Slice {
283 prefix: Vec<Self>,
284 rest: RestPattern,
285 element_ty: Type,
286 span: Span,
287 },
288 Or {
289 patterns: Vec<Self>,
290 span: Span,
291 },
292 AsBinding {
293 pattern: Box<Self>,
294 name: EcoString,
295 span: Span,
296 },
297}
298
299pub fn collect_pattern_bindings(pattern: &Pattern) -> Vec<(String, Span)> {
301 match pattern {
302 Pattern::Identifier { identifier, span } => vec![(identifier.to_string(), *span)],
303 Pattern::Tuple { elements, .. } => {
304 elements.iter().flat_map(collect_pattern_bindings).collect()
305 }
306 Pattern::EnumVariant { fields, .. } => {
307 fields.iter().flat_map(collect_pattern_bindings).collect()
308 }
309 Pattern::Struct { fields, .. } => fields
310 .iter()
311 .flat_map(|f| collect_pattern_bindings(&f.value))
312 .collect(),
313 Pattern::Slice { prefix, rest, .. } => {
314 let mut bindings: Vec<_> = prefix.iter().flat_map(collect_pattern_bindings).collect();
315 if let RestPattern::Bind { name, span } = rest {
316 bindings.push((name.to_string(), *span));
317 }
318 bindings
319 }
320 Pattern::Or { patterns, .. } => patterns
321 .first()
322 .map(collect_pattern_bindings)
323 .unwrap_or_default(),
324 Pattern::AsBinding {
325 pattern,
326 name,
327 span,
328 } => {
329 let mut bindings = collect_pattern_bindings(pattern);
330 bindings.push((name.to_string(), *span));
331 bindings
332 }
333 Pattern::WildCard { .. } | Pattern::Literal { .. } | Pattern::Unit { .. } => vec![],
334 }
335}
336
337#[derive(Clone, Copy)]
339pub enum PatternKind {
340 Literal,
341 Unit,
342 EnumVariant,
343 Struct,
344 Tuple,
345 WildCard,
346 Identifier,
347 Slice,
348 Or,
349 AsBinding,
350}
351
352impl PatternKind {
353 pub const COUNT: usize = PatternKind::AsBinding as usize + 1;
355}
356
357impl Pattern {
358 pub fn kind(&self) -> PatternKind {
359 match self {
360 Pattern::Literal { .. } => PatternKind::Literal,
361 Pattern::Unit { .. } => PatternKind::Unit,
362 Pattern::EnumVariant { .. } => PatternKind::EnumVariant,
363 Pattern::Struct { .. } => PatternKind::Struct,
364 Pattern::Tuple { .. } => PatternKind::Tuple,
365 Pattern::WildCard { .. } => PatternKind::WildCard,
366 Pattern::Identifier { .. } => PatternKind::Identifier,
367 Pattern::Slice { .. } => PatternKind::Slice,
368 Pattern::Or { .. } => PatternKind::Or,
369 Pattern::AsBinding { .. } => PatternKind::AsBinding,
370 }
371 }
372
373 pub fn get_span(&self) -> Span {
374 match self {
375 Pattern::Identifier { span, .. } => *span,
376 Pattern::Literal { span, .. } => *span,
377 Pattern::EnumVariant { span, .. } => *span,
378 Pattern::Struct { span, .. } => *span,
379 Pattern::WildCard { span } => *span,
380 Pattern::Unit { span, .. } => *span,
381 Pattern::Tuple { span, .. } => *span,
382 Pattern::Slice { span, .. } => *span,
383 Pattern::Or { span, .. } => *span,
384 Pattern::AsBinding { span, .. } => *span,
385 }
386 }
387
388 pub fn get_type(&self) -> Option<Type> {
389 match self {
390 Pattern::Identifier { .. } => None,
391 Pattern::Literal { ty, .. } => Some(ty.clone()),
392 Pattern::EnumVariant { ty, .. } => Some(ty.clone()),
393 Pattern::Struct { ty, .. } => Some(ty.clone()),
394 Pattern::WildCard { .. } => None,
395 Pattern::Unit { ty, .. } => Some(ty.clone()),
396 Pattern::Tuple { .. } => None,
397 Pattern::Slice { .. } => None,
398 Pattern::Or { .. } => None,
399 Pattern::AsBinding { pattern, .. } => pattern.get_type(),
400 }
401 }
402
403 pub fn is_identifier(&self) -> bool {
404 matches!(self, Pattern::Identifier { .. } | Pattern::AsBinding { .. })
405 }
406
407 pub fn get_identifier(&self) -> Option<EcoString> {
408 match self {
409 Pattern::Identifier { identifier, .. } => Some(identifier.clone()),
410 Pattern::AsBinding { name, .. } => Some(name.clone()),
411 _ => None,
412 }
413 }
414}
415
416#[derive(Debug, Clone, PartialEq)]
417pub struct StructFieldPattern {
418 pub name: EcoString,
419 pub value: Pattern,
420}
421
422#[derive(Debug, Clone, PartialEq)]
423pub enum TypedPattern {
424 Wildcard,
425 Literal(Literal),
426 Const {
430 qualified_name: EcoString,
431 ty: Type,
432 value: Option<Literal>,
433 },
434 EnumVariant {
435 enum_name: EcoString,
436 variant_name: EcoString,
437 variant_fields: Vec<EnumFieldDefinition>,
438 fields: Vec<TypedPattern>,
439 type_args: Vec<Type>,
440 field_types: Box<[Type]>,
441 },
442 EnumStructVariant {
443 enum_name: EcoString,
444 variant_name: EcoString,
445 variant_fields: Vec<EnumFieldDefinition>,
446 pattern_fields: Vec<(EcoString, TypedPattern)>,
447 type_args: Vec<Type>,
448 },
449 Struct {
450 struct_name: EcoString,
451 struct_fields: Vec<StructFieldDefinition>,
452 pattern_fields: Vec<(EcoString, TypedPattern)>,
453 type_args: Vec<Type>,
454 },
455 Slice {
456 prefix: Vec<TypedPattern>,
457 has_rest: bool,
458 element_type: Type,
459 },
460 Tuple {
461 arity: usize,
462 elements: Vec<TypedPattern>,
463 },
464 Or {
465 alternatives: Vec<TypedPattern>,
466 },
467}
468
469#[derive(Debug, Clone, PartialEq)]
470pub struct FunctionDefinition {
471 pub name: EcoString,
472 pub name_span: Span,
473 pub generics: Vec<Generic>,
474 pub params: Vec<Binding>,
475 pub body: Box<Expression>,
476 pub return_type: Type,
477 pub annotation: Annotation,
478 pub ty: Type,
479}
480
481#[derive(Clone, Copy)]
482pub struct FunctionDefinitionView<'a> {
483 pub name: &'a EcoString,
484 pub name_span: Span,
485 pub generics: &'a [Generic],
486 pub params: &'a [Binding],
487 pub body: &'a Expression,
488 pub return_type: &'a Type,
489}
490
491#[derive(Debug, Clone, PartialEq)]
492pub enum VariantFields {
493 Unit,
494 Tuple(Vec<EnumFieldDefinition>),
495 Struct(Vec<EnumFieldDefinition>),
496}
497
498impl VariantFields {
499 pub fn is_empty(&self) -> bool {
500 match self {
501 VariantFields::Unit => true,
502 VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.is_empty(),
503 }
504 }
505
506 pub fn len(&self) -> usize {
507 match self {
508 VariantFields::Unit => 0,
509 VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.len(),
510 }
511 }
512
513 pub fn iter(&self) -> std::slice::Iter<'_, EnumFieldDefinition> {
514 match self {
515 VariantFields::Unit => [].iter(),
516 VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.iter(),
517 }
518 }
519
520 pub fn is_struct(&self) -> bool {
521 matches!(self, VariantFields::Struct(_))
522 }
523}
524
525impl<'a> IntoIterator for &'a VariantFields {
526 type Item = &'a EnumFieldDefinition;
527 type IntoIter = std::slice::Iter<'a, EnumFieldDefinition>;
528
529 fn into_iter(self) -> Self::IntoIter {
530 self.iter()
531 }
532}
533
534#[derive(Debug, Clone, PartialEq)]
535pub struct EnumVariant {
536 pub doc: Option<String>,
537 pub name: EcoString,
538 pub name_span: Span,
539 pub fields: VariantFields,
540}
541
542#[derive(Debug, Clone, PartialEq)]
543pub struct EnumFieldDefinition {
544 pub name: EcoString,
545 pub name_span: Span,
546 pub annotation: Annotation,
547 pub ty: Type,
548}
549
550#[derive(Debug, Clone, PartialEq)]
551pub struct Attribute {
552 pub name: String,
553 pub args: Vec<AttributeArg>,
554 pub span: Span,
555}
556
557#[derive(Debug, Clone, PartialEq)]
558#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
559pub enum AttributeArg {
560 Flag(String),
562 NegatedFlag(String),
564 String(String),
566 Raw(String),
568}
569
570#[derive(Debug, Clone, Copy, PartialEq)]
571#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
572pub enum StructKind {
573 Record,
574 Tuple,
575}
576
577#[derive(Debug, Clone, PartialEq)]
578pub struct StructFieldDefinition {
579 pub doc: Option<String>,
580 pub attributes: Vec<Attribute>,
581 pub name: EcoString,
582 pub name_span: Span,
583 pub annotation: Annotation,
584 pub visibility: Visibility,
585 pub ty: Type,
586 pub embedded: bool,
587}
588
589#[derive(Debug, Clone, PartialEq)]
590pub struct StructFieldAssignment {
591 pub name: EcoString,
592 pub name_span: Span,
593 pub value: Box<Expression>,
594}
595
596#[derive(Debug, Clone, PartialEq)]
597pub enum StructSpread {
598 None,
599 From(Box<Expression>),
600 ZeroFill { span: Span },
601}
602
603impl StructSpread {
604 pub fn is_none(&self) -> bool {
605 matches!(self, Self::None)
606 }
607
608 pub fn is_some(&self) -> bool {
609 !self.is_none()
610 }
611
612 pub fn span(&self) -> Option<Span> {
613 match self {
614 Self::None => None,
615 Self::From(e) => Some(e.get_span()),
616 Self::ZeroFill { span } => Some(*span),
617 }
618 }
619
620 pub fn as_expression(&self) -> Option<&Expression> {
621 match self {
622 Self::From(e) => Some(e),
623 Self::None | Self::ZeroFill { .. } => None,
624 }
625 }
626}
627
628#[derive(Debug, Clone, PartialEq)]
629#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
630pub enum Annotation {
631 Constructor {
632 name: EcoString,
633 params: Vec<Self>,
634 span: Span,
635 },
636 Function {
637 params: Vec<Self>,
638 return_type: Box<Self>,
639 span: Span,
640 },
641 Tuple {
642 elements: Vec<Self>,
643 span: Span,
644 },
645 Unknown,
646 Opaque {
647 span: Span,
648 },
649}
650
651impl Annotation {
652 pub fn unit() -> Self {
653 Self::Constructor {
654 name: "Unit".into(),
655 params: vec![],
656 span: Span::dummy(),
657 }
658 }
659
660 pub fn get_span(&self) -> Span {
661 match self {
662 Self::Constructor { span, .. } => *span,
663 Self::Function { span, .. } => *span,
664 Self::Tuple { span, .. } => *span,
665 Self::Opaque { span } => *span,
666 Self::Unknown => Span::dummy(),
667 }
668 }
669
670 pub fn get_name(&self) -> Option<String> {
671 match self {
672 Self::Constructor { name, .. } => Some(name.to_string()),
673 _ => None,
674 }
675 }
676
677 pub fn is_unit(&self) -> bool {
678 matches!(self, Self::Constructor { name, params, .. } if name == "Unit" && params.is_empty())
679 }
680
681 pub fn is_unknown(&self) -> bool {
682 matches!(self, Self::Unknown)
683 }
684
685 pub fn is_opaque(&self) -> bool {
686 matches!(self, Self::Opaque { .. })
687 }
688}
689
690#[derive(Debug, Clone, PartialEq)]
691pub struct Generic {
692 pub name: EcoString,
693 pub bounds: Vec<Annotation>,
694 pub span: Span,
695}
696
697#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
698#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
699pub struct Span {
700 pub file_id: u32,
701 pub byte_offset: u32,
702 pub byte_length: u32,
703}
704
705impl Span {
706 pub fn new(file_id: u32, byte_offset: u32, byte_length: u32) -> Self {
707 Span {
708 file_id,
709 byte_offset,
710 byte_length,
711 }
712 }
713
714 pub fn dummy() -> Self {
715 Span {
716 file_id: 0,
717 byte_offset: 0,
718 byte_length: 0,
719 }
720 }
721
722 pub fn is_dummy(&self) -> bool {
723 self.byte_length == 0
724 }
725
726 pub fn end(&self) -> u32 {
727 self.byte_offset + self.byte_length
728 }
729
730 pub fn merge(self, other: Span) -> Span {
731 Span::new(
732 self.file_id,
733 self.byte_offset,
734 other.end() - self.byte_offset,
735 )
736 }
737}
738
739#[derive(Debug, Clone, PartialEq)]
740#[allow(clippy::large_enum_variant)]
741pub enum Expression {
742 Literal {
743 literal: Literal,
744 ty: Type,
745 span: Span,
746 },
747 Function {
748 doc: Option<String>,
749 attributes: Vec<Attribute>,
750 name: EcoString,
751 name_span: Span,
752 generics: Vec<Generic>,
753 params: Vec<Binding>,
754 return_annotation: Annotation,
755 return_type: Type,
756 visibility: Visibility,
757 body: Box<Expression>,
758 ty: Type,
759 span: Span,
760 },
761 Lambda {
762 params: Vec<Binding>,
763 return_annotation: Annotation,
764 body: Box<Expression>,
765 ty: Type,
766 span: Span,
767 },
768 Block {
769 items: Vec<Expression>,
770 ty: Type,
771 span: Span,
772 },
773 Let {
774 binding: Box<Binding>,
775 value: Box<Expression>,
776 mutable: bool,
777 mut_span: Option<Span>,
778 else_block: Option<Box<Expression>>,
779 else_span: Option<Span>,
780 typed_pattern: Option<TypedPattern>,
781 ty: Type,
782 span: Span,
783 },
784 Identifier {
785 value: EcoString,
786 ty: Type,
787 span: Span,
788 binding_id: Option<BindingId>,
789 qualified: Option<EcoString>,
790 },
791 Call {
792 expression: Box<Expression>,
793 args: Vec<Expression>,
794 spread: Box<Option<Expression>>,
795 type_args: Vec<Annotation>,
796 ty: Type,
797 span: Span,
798 call_kind: Option<CallKind>,
799 },
800 If {
801 condition: Box<Expression>,
802 consequence: Box<Expression>,
803 alternative: Box<Expression>,
804 ty: Type,
805 span: Span,
806 },
807 IfLet {
808 pattern: Pattern,
809 scrutinee: Box<Expression>,
810 consequence: Box<Expression>,
811 alternative: Box<Expression>,
812 typed_pattern: Option<TypedPattern>,
813 else_span: Option<Span>,
814 ty: Type,
815 span: Span,
816 },
817 Match {
818 subject: Box<Expression>,
819 arms: Vec<MatchArm>,
820 origin: MatchOrigin,
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 Select {
1026 arms: Vec<SelectArm>,
1027 ty: Type,
1028 span: Span,
1029 },
1030 Unit {
1031 ty: Type,
1032 span: Span,
1033 },
1034 Range {
1035 start: Option<Box<Expression>>,
1036 end: Option<Box<Expression>>,
1037 inclusive: bool,
1038 ty: Type,
1039 span: Span,
1040 },
1041 Cast {
1042 expression: Box<Expression>,
1043 target_type: Annotation,
1044 ty: Type,
1045 span: Span,
1046 },
1047 NoOp,
1048}
1049
1050#[derive(Clone, Copy)]
1052pub enum ExpressionKind {
1053 Literal,
1054 Function,
1055 Lambda,
1056 Block,
1057 Let,
1058 Identifier,
1059 Call,
1060 If,
1061 IfLet,
1062 Match,
1063 Tuple,
1064 StructCall,
1065 DotAccess,
1066 Assignment,
1067 Return,
1068 Propagate,
1069 TryBlock,
1070 RecoverBlock,
1071 ImplBlock,
1072 Binary,
1073 Unary,
1074 Paren,
1075 Const,
1076 VariableDeclaration,
1077 RawGo,
1078 Loop,
1079 While,
1080 WhileLet,
1081 For,
1082 Break,
1083 Continue,
1084 Enum,
1085 Struct,
1086 TypeAlias,
1087 ModuleImport,
1088 Reference,
1089 Interface,
1090 IndexedAccess,
1091 Task,
1092 Defer,
1093 Select,
1094 Unit,
1095 Range,
1096 Cast,
1097 NoOp,
1098}
1099
1100impl ExpressionKind {
1101 pub const COUNT: usize = ExpressionKind::NoOp as usize + 1;
1103}
1104
1105impl Expression {
1106 pub fn kind(&self) -> ExpressionKind {
1107 match self {
1108 Expression::Literal { .. } => ExpressionKind::Literal,
1109 Expression::Function { .. } => ExpressionKind::Function,
1110 Expression::Lambda { .. } => ExpressionKind::Lambda,
1111 Expression::Block { .. } => ExpressionKind::Block,
1112 Expression::Let { .. } => ExpressionKind::Let,
1113 Expression::Identifier { .. } => ExpressionKind::Identifier,
1114 Expression::Call { .. } => ExpressionKind::Call,
1115 Expression::If { .. } => ExpressionKind::If,
1116 Expression::IfLet { .. } => ExpressionKind::IfLet,
1117 Expression::Match { .. } => ExpressionKind::Match,
1118 Expression::Tuple { .. } => ExpressionKind::Tuple,
1119 Expression::StructCall { .. } => ExpressionKind::StructCall,
1120 Expression::DotAccess { .. } => ExpressionKind::DotAccess,
1121 Expression::Assignment { .. } => ExpressionKind::Assignment,
1122 Expression::Return { .. } => ExpressionKind::Return,
1123 Expression::Propagate { .. } => ExpressionKind::Propagate,
1124 Expression::TryBlock { .. } => ExpressionKind::TryBlock,
1125 Expression::RecoverBlock { .. } => ExpressionKind::RecoverBlock,
1126 Expression::ImplBlock { .. } => ExpressionKind::ImplBlock,
1127 Expression::Binary { .. } => ExpressionKind::Binary,
1128 Expression::Unary { .. } => ExpressionKind::Unary,
1129 Expression::Paren { .. } => ExpressionKind::Paren,
1130 Expression::Const { .. } => ExpressionKind::Const,
1131 Expression::VariableDeclaration { .. } => ExpressionKind::VariableDeclaration,
1132 Expression::RawGo { .. } => ExpressionKind::RawGo,
1133 Expression::Loop { .. } => ExpressionKind::Loop,
1134 Expression::While { .. } => ExpressionKind::While,
1135 Expression::WhileLet { .. } => ExpressionKind::WhileLet,
1136 Expression::For { .. } => ExpressionKind::For,
1137 Expression::Break { .. } => ExpressionKind::Break,
1138 Expression::Continue { .. } => ExpressionKind::Continue,
1139 Expression::Enum { .. } => ExpressionKind::Enum,
1140 Expression::Struct { .. } => ExpressionKind::Struct,
1141 Expression::TypeAlias { .. } => ExpressionKind::TypeAlias,
1142 Expression::ModuleImport { .. } => ExpressionKind::ModuleImport,
1143 Expression::Reference { .. } => ExpressionKind::Reference,
1144 Expression::Interface { .. } => ExpressionKind::Interface,
1145 Expression::IndexedAccess { .. } => ExpressionKind::IndexedAccess,
1146 Expression::Task { .. } => ExpressionKind::Task,
1147 Expression::Defer { .. } => ExpressionKind::Defer,
1148 Expression::Select { .. } => ExpressionKind::Select,
1149 Expression::Unit { .. } => ExpressionKind::Unit,
1150 Expression::Range { .. } => ExpressionKind::Range,
1151 Expression::Cast { .. } => ExpressionKind::Cast,
1152 Expression::NoOp => ExpressionKind::NoOp,
1153 }
1154 }
1155
1156 pub fn is_noop(&self) -> bool {
1157 matches!(self, Expression::NoOp)
1158 }
1159
1160 pub fn is_block(&self) -> bool {
1161 matches!(self, Expression::Block { .. })
1162 }
1163
1164 pub fn is_range(&self) -> bool {
1165 matches!(self, Expression::Range { .. })
1166 }
1167
1168 pub fn is_conditional(&self) -> bool {
1169 matches!(
1170 self,
1171 Expression::If { .. }
1172 | Expression::IfLet { .. }
1173 | Expression::Match {
1174 origin: MatchOrigin::IfLet { .. },
1175 ..
1176 }
1177 )
1178 }
1179
1180 pub fn is_control_flow(&self) -> bool {
1181 matches!(
1182 self,
1183 Expression::If { .. }
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::Reference { ty, .. }
1345 | Self::IndexedAccess { ty, .. }
1346 | Self::Task { ty, .. }
1347 | Self::Select { ty, .. }
1348 | Self::Unit { ty, .. }
1349 | Self::Loop { ty, .. }
1350 | Self::Range { ty, .. }
1351 | Self::Cast { ty, .. } => ty.clone(),
1352 Self::Enum { .. }
1353 | Self::Struct { .. }
1354 | Self::Assignment { .. }
1355 | Self::ImplBlock { .. }
1356 | Self::TypeAlias { .. }
1357 | Self::ModuleImport { .. }
1358 | Self::Interface { .. }
1359 | Self::NoOp
1360 | Self::RawGo { .. }
1361 | Self::While { .. }
1362 | Self::WhileLet { .. }
1363 | Self::For { .. } => Type::ignored(),
1364 Self::Break { .. } | Self::Continue { .. } => Type::Never,
1365 }
1366 }
1367
1368 pub fn get_span(&self) -> Span {
1369 match self {
1370 Self::Literal { span, .. }
1371 | Self::Function { span, .. }
1372 | Self::Lambda { span, .. }
1373 | Self::Block { span, .. }
1374 | Self::Let { span, .. }
1375 | Self::Identifier { span, .. }
1376 | Self::Call { span, .. }
1377 | Self::If { span, .. }
1378 | Self::IfLet { span, .. }
1379 | Self::Match { span, .. }
1380 | Self::Tuple { span, .. }
1381 | Self::Enum { span, .. }
1382 | Self::Struct { span, .. }
1383 | Self::StructCall { span, .. }
1384 | Self::DotAccess { span, .. }
1385 | Self::Assignment { span, .. }
1386 | Self::Return { span, .. }
1387 | Self::Propagate { span, .. }
1388 | Self::TryBlock { span, .. }
1389 | Self::RecoverBlock { span, .. }
1390 | Self::ImplBlock { span, .. }
1391 | Self::Binary { span, .. }
1392 | Self::Paren { span, .. }
1393 | Self::Unary { span, .. }
1394 | Self::Const { span, .. }
1395 | Self::VariableDeclaration { span, .. }
1396 | Self::Defer { span, .. }
1397 | Self::Reference { span, .. }
1398 | Self::IndexedAccess { span, .. }
1399 | Self::Task { span, .. }
1400 | Self::Select { span, .. }
1401 | Self::Loop { span, .. }
1402 | Self::TypeAlias { span, .. }
1403 | Self::ModuleImport { span, .. }
1404 | Self::Interface { span, .. }
1405 | Self::Unit { span, .. }
1406 | Self::While { span, .. }
1407 | Self::WhileLet { span, .. }
1408 | Self::For { span, .. }
1409 | Self::Break { span, .. }
1410 | Self::Continue { span, .. }
1411 | Self::Range { span, .. }
1412 | Self::Cast { span, .. } => *span,
1413 Self::NoOp | Self::RawGo { .. } => Span::dummy(),
1414 }
1415 }
1416
1417 pub fn contains_break(&self) -> bool {
1418 match self {
1419 Expression::Break { .. } => true,
1420
1421 Expression::Loop { .. }
1422 | Expression::While { .. }
1423 | Expression::WhileLet { .. }
1424 | Expression::For { .. } => false,
1425
1426 Expression::Block { items, .. } => items.iter().any(Self::contains_break),
1427
1428 Expression::TryBlock { items, .. } => items.iter().any(Self::contains_break),
1429 Expression::RecoverBlock { items, .. } => items.iter().any(Self::contains_break),
1430
1431 Expression::If {
1432 condition,
1433 consequence,
1434 alternative,
1435 ..
1436 } => {
1437 condition.contains_break()
1438 || consequence.contains_break()
1439 || alternative.contains_break()
1440 }
1441
1442 Expression::IfLet {
1443 scrutinee,
1444 consequence,
1445 alternative,
1446 ..
1447 } => {
1448 scrutinee.contains_break()
1449 || consequence.contains_break()
1450 || alternative.contains_break()
1451 }
1452
1453 Expression::Match { subject, arms, .. } => {
1454 subject.contains_break() || arms.iter().any(|arm| arm.expression.contains_break())
1455 }
1456
1457 Expression::Paren { expression, .. } => expression.contains_break(),
1458
1459 Expression::Binary { left, right, .. } => {
1460 left.contains_break() || right.contains_break()
1461 }
1462
1463 Expression::Unary { expression, .. } => expression.contains_break(),
1464
1465 Expression::Call {
1466 expression,
1467 args,
1468 spread,
1469 ..
1470 } => {
1471 expression.contains_break()
1472 || args.iter().any(Self::contains_break)
1473 || spread.as_ref().as_ref().is_some_and(Self::contains_break)
1474 }
1475
1476 Expression::Function { .. } | Expression::Lambda { .. } => false,
1477
1478 Expression::Select { arms, .. } => arms.iter().any(|arm| match &arm.pattern {
1479 SelectArmPattern::Receive { body, .. } => body.contains_break(),
1480 SelectArmPattern::Send { body, .. } => body.contains_break(),
1481 SelectArmPattern::MatchReceive { arms, .. } => {
1482 arms.iter().any(|a| a.expression.contains_break())
1483 }
1484 SelectArmPattern::WildCard { body } => body.contains_break(),
1485 }),
1486
1487 Expression::Cast { expression, .. } => expression.contains_break(),
1488
1489 Expression::Let {
1490 value, else_block, ..
1491 } => value.contains_break() || else_block.as_ref().is_some_and(|e| e.contains_break()),
1492
1493 Expression::Assignment { value, .. } => value.contains_break(),
1494
1495 _ => false,
1496 }
1497 }
1498
1499 pub fn diverges(&self) -> Option<DeadCodeCause> {
1500 match self {
1501 Expression::Return { .. } => Some(DeadCodeCause::Return),
1502 Expression::Break { .. } => Some(DeadCodeCause::Break),
1503 Expression::Continue { .. } => Some(DeadCodeCause::Continue),
1504
1505 Expression::If {
1506 consequence,
1507 alternative,
1508 ..
1509 } => {
1510 if consequence.diverges().is_some() && alternative.diverges().is_some() {
1511 Some(DeadCodeCause::DivergingIf)
1512 } else {
1513 None
1514 }
1515 }
1516
1517 Expression::IfLet {
1518 consequence,
1519 alternative,
1520 ..
1521 } => {
1522 if consequence.diverges().is_some() && alternative.diverges().is_some() {
1523 Some(DeadCodeCause::DivergingIf)
1524 } else {
1525 None
1526 }
1527 }
1528
1529 Expression::Match { arms, .. } => {
1530 if !arms.is_empty() && arms.iter().all(|arm| arm.expression.diverges().is_some()) {
1531 Some(DeadCodeCause::DivergingMatch)
1532 } else {
1533 None
1534 }
1535 }
1536
1537 Expression::Block { items, .. } => {
1538 for item in items {
1539 if let Some(cause) = item.diverges() {
1540 return Some(cause);
1541 }
1542 }
1543 None
1544 }
1545
1546 Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
1547 for item in items {
1548 if let Some(cause) = item.diverges() {
1549 return Some(cause);
1550 }
1551 }
1552 None
1553 }
1554
1555 Expression::Paren { expression, .. } | Expression::Cast { expression, .. } => {
1556 expression.diverges()
1557 }
1558
1559 Expression::Loop { body, .. } => {
1560 if !body.contains_break() {
1561 Some(DeadCodeCause::InfiniteLoop)
1562 } else {
1563 None
1564 }
1565 }
1566
1567 Expression::Call { ty, .. } if ty.is_never() => Some(DeadCodeCause::DivergingCall),
1568
1569 _ => None,
1570 }
1571 }
1572
1573 pub fn children(&self) -> Children<'_> {
1578 match self {
1579 Expression::Literal { literal, .. } => match literal {
1580 Literal::Slice(elements) => elements.iter().collect(),
1581 Literal::FormatString(parts) => parts
1582 .iter()
1583 .filter_map(|p| match p {
1584 FormatStringPart::Expression(e) => Some(e.as_ref()),
1585 FormatStringPart::Text(_) => None,
1586 })
1587 .collect(),
1588 _ => Children::new(),
1589 },
1590 Expression::Function { body, .. } => children![body],
1591 Expression::Lambda { body, .. } => children![body],
1592 Expression::Block { items, .. } => items.iter().collect(),
1593 Expression::Let {
1594 value, else_block, ..
1595 } => {
1596 let mut c = children![value.as_ref()];
1597 if let Some(eb) = else_block {
1598 c.push(eb);
1599 }
1600 c
1601 }
1602 Expression::Identifier { .. } => Children::new(),
1603 Expression::Call {
1604 expression,
1605 args,
1606 spread,
1607 ..
1608 } => {
1609 let mut c = children![expression.as_ref()];
1610 c.extend(args);
1611 if let Some(s) = spread.as_ref() {
1612 c.push(s);
1613 }
1614 c
1615 }
1616 Expression::If {
1617 condition,
1618 consequence,
1619 alternative,
1620 ..
1621 } => children![condition, consequence, alternative],
1622 Expression::IfLet {
1623 scrutinee,
1624 consequence,
1625 alternative,
1626 ..
1627 } => children![scrutinee, consequence, alternative],
1628 Expression::Match { subject, arms, .. } => {
1629 let mut c = children![subject.as_ref()];
1630 for arm in arms {
1631 if let Some(guard) = &arm.guard {
1632 c.push(guard);
1633 }
1634 c.push(&arm.expression);
1635 }
1636 c
1637 }
1638 Expression::Tuple { elements, .. } => elements.iter().collect(),
1639 Expression::StructCall {
1640 field_assignments,
1641 spread,
1642 ..
1643 } => {
1644 let mut c: Children = field_assignments.iter().map(|f| f.value.as_ref()).collect();
1645 if let Some(s) = spread.as_expression() {
1646 c.push(s);
1647 }
1648 c
1649 }
1650 Expression::DotAccess { expression, .. } => children![expression],
1651 Expression::Assignment { target, value, .. } => children![target, value],
1652 Expression::Return { expression, .. } => children![expression],
1653 Expression::Propagate { expression, .. } => children![expression],
1654 Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
1655 items.iter().collect()
1656 }
1657 Expression::ImplBlock { methods, .. } => methods.iter().collect(),
1658 Expression::Binary { left, right, .. } => children![left, right],
1659 Expression::Unary { expression, .. } => children![expression],
1660 Expression::Paren { expression, .. } => children![expression],
1661 Expression::Const { expression, .. } => children![expression],
1662 Expression::Loop { body, .. } => children![body],
1663 Expression::While {
1664 condition, body, ..
1665 } => children![condition, body],
1666 Expression::WhileLet {
1667 scrutinee, body, ..
1668 } => children![scrutinee, body],
1669 Expression::For { iterable, body, .. } => children![iterable, body],
1670 Expression::Break { value, .. } => value
1671 .as_ref()
1672 .map(|v| children![v.as_ref()])
1673 .unwrap_or_default(),
1674 Expression::Reference { expression, .. } => children![expression],
1675 Expression::IndexedAccess {
1676 expression, index, ..
1677 } => children![expression, index],
1678 Expression::Task { expression, .. } => children![expression],
1679 Expression::Defer { expression, .. } => children![expression],
1680 Expression::Select { arms, .. } => {
1681 let mut c = Children::new();
1682 for arm in arms {
1683 match &arm.pattern {
1684 SelectArmPattern::Receive {
1685 receive_expression,
1686 body,
1687 ..
1688 } => {
1689 c.push(receive_expression.as_ref());
1690 c.push(body.as_ref());
1691 }
1692 SelectArmPattern::Send {
1693 send_expression,
1694 body,
1695 } => {
1696 c.push(send_expression.as_ref());
1697 c.push(body.as_ref());
1698 }
1699 SelectArmPattern::MatchReceive {
1700 receive_expression,
1701 arms: match_arms,
1702 } => {
1703 c.push(receive_expression.as_ref());
1704 for ma in match_arms {
1705 if let Some(guard) = &ma.guard {
1706 c.push(guard);
1707 }
1708 c.push(&ma.expression);
1709 }
1710 }
1711 SelectArmPattern::WildCard { body } => {
1712 c.push(body.as_ref());
1713 }
1714 }
1715 }
1716 c
1717 }
1718 Expression::Range { start, end, .. } => {
1719 let mut c = Children::new();
1720 if let Some(s) = start {
1721 c.push(s.as_ref());
1722 }
1723 if let Some(e) = end {
1724 c.push(e.as_ref());
1725 }
1726 c
1727 }
1728 Expression::Cast { expression, .. } => children![expression],
1729 Expression::Interface {
1730 method_signatures, ..
1731 } => method_signatures.iter().collect(),
1732 Expression::Unit { .. }
1733 | Expression::Continue { .. }
1734 | Expression::Enum { .. }
1735 | Expression::Struct { .. }
1736 | Expression::TypeAlias { .. }
1737 | Expression::VariableDeclaration { .. }
1738 | Expression::ModuleImport { .. }
1739 | Expression::RawGo { .. }
1740 | Expression::NoOp => Children::new(),
1741 }
1742 }
1743
1744 pub fn unwrap_parens(&self) -> &Expression {
1745 match self {
1746 Expression::Paren { expression, .. } => expression.unwrap_parens(),
1747 other => other,
1748 }
1749 }
1750
1751 pub fn binding_id(&self) -> Option<BindingId> {
1752 match self.unwrap_parens() {
1753 Expression::Identifier { binding_id, .. } => *binding_id,
1754 _ => None,
1755 }
1756 }
1757
1758 pub fn as_integer(&self) -> Option<u64> {
1759 match self.unwrap_parens() {
1760 Expression::Literal {
1761 literal: Literal::Integer { value, .. },
1762 ..
1763 } => Some(*value),
1764 _ => None,
1765 }
1766 }
1767
1768 #[inline]
1770 pub fn deref_inner(&self) -> Option<&Expression> {
1771 match self {
1772 Expression::Unary {
1773 operator: UnaryOperator::Deref,
1774 expression,
1775 ..
1776 } => Some(expression),
1777 _ => None,
1778 }
1779 }
1780
1781 pub fn as_dotted_path(&self) -> Option<String> {
1782 match self {
1783 Expression::Identifier { value, .. } => Some(value.to_string()),
1784 Expression::DotAccess {
1785 expression, member, ..
1786 } => Some(format!("{}.{}", expression.as_dotted_path()?, member)),
1787 _ => None,
1788 }
1789 }
1790
1791 pub fn root_identifier(&self) -> Option<&str> {
1792 match self {
1793 Expression::Identifier { value, .. } => Some(value),
1794 Expression::DotAccess { expression, .. } => expression.root_identifier(),
1795 _ => None,
1796 }
1797 }
1798
1799 pub fn is_empty_collection(&self) -> bool {
1800 matches!(
1801 self,
1802 Expression::Literal {
1803 literal: Literal::Slice(elements),
1804 ..
1805 } if elements.is_empty()
1806 )
1807 }
1808
1809 pub fn is_all_literals(&self) -> bool {
1810 match self.unwrap_parens() {
1811 Expression::Literal { literal, .. } => match literal {
1812 Literal::Slice(elements) => elements.iter().all(|e| e.is_all_literals()),
1813 Literal::FormatString(parts) => parts.iter().all(|p| match p {
1814 FormatStringPart::Text(_) => true,
1815 FormatStringPart::Expression(e) => e.is_all_literals(),
1816 }),
1817 _ => true,
1818 },
1819 Expression::Tuple { elements, .. } => elements.iter().all(|e| e.is_all_literals()),
1820 Expression::Unit { .. } => true,
1821 _ => false,
1822 }
1823 }
1824
1825 pub fn get_var_name(&self) -> Option<String> {
1826 match self {
1827 Expression::Identifier { value, .. } => Some(value.to_string()),
1828 Expression::DotAccess { expression, .. } => expression.get_var_name(),
1829 Expression::Assignment { target, .. } => target.get_var_name(),
1830 Expression::IndexedAccess { expression, .. } => expression.get_var_name(),
1831 Expression::Paren { expression, .. } => expression.get_var_name(),
1832 Expression::Reference { expression, .. } => expression.get_var_name(),
1833 Expression::Unary {
1834 operator,
1835 expression,
1836 ..
1837 } => {
1838 if operator == &UnaryOperator::Deref {
1839 expression.get_var_name()
1840 } else {
1841 None
1842 }
1843 }
1844 _ => None,
1845 }
1846 }
1847
1848 pub fn is_function(&self) -> bool {
1849 matches!(self, Expression::Function { .. })
1850 }
1851
1852 pub fn set_public(self) -> Self {
1853 match self {
1854 Expression::Enum {
1855 doc,
1856 attributes,
1857 name,
1858 name_span,
1859 generics,
1860 variants,
1861 span,
1862 ..
1863 } => Expression::Enum {
1864 doc,
1865 attributes,
1866 name,
1867 name_span,
1868 generics,
1869 variants,
1870 visibility: Visibility::Public,
1871 span,
1872 },
1873 Expression::Struct {
1874 doc,
1875 attributes,
1876 name,
1877 name_span,
1878 generics,
1879 fields,
1880 kind,
1881 span,
1882 ..
1883 } => {
1884 let fields = if kind == StructKind::Tuple {
1885 fields
1886 .into_iter()
1887 .map(|f| StructFieldDefinition {
1888 visibility: Visibility::Public,
1889 ..f
1890 })
1891 .collect()
1892 } else {
1893 fields
1894 };
1895 Expression::Struct {
1896 doc,
1897 attributes,
1898 name,
1899 name_span,
1900 generics,
1901 fields,
1902 kind,
1903 visibility: Visibility::Public,
1904 span,
1905 }
1906 }
1907 Expression::Function {
1908 doc,
1909 attributes,
1910 name,
1911 name_span,
1912 generics,
1913 params,
1914 return_annotation,
1915 return_type,
1916 body,
1917 ty,
1918 span,
1919 ..
1920 } => Expression::Function {
1921 doc,
1922 attributes,
1923 name,
1924 name_span,
1925 generics,
1926 params,
1927 return_annotation,
1928 return_type,
1929 visibility: Visibility::Public,
1930 body,
1931 ty,
1932 span,
1933 },
1934 Expression::Const {
1935 doc,
1936 identifier,
1937 identifier_span,
1938 annotation,
1939 expression,
1940 ty,
1941 span,
1942 ..
1943 } => Expression::Const {
1944 doc,
1945 identifier,
1946 identifier_span,
1947 annotation,
1948 expression,
1949 visibility: Visibility::Public,
1950 ty,
1951 span,
1952 },
1953 Expression::VariableDeclaration {
1954 doc,
1955 name,
1956 name_span,
1957 annotation,
1958 ty,
1959 span,
1960 ..
1961 } => Expression::VariableDeclaration {
1962 doc,
1963 name,
1964 name_span,
1965 annotation,
1966 visibility: Visibility::Public,
1967 ty,
1968 span,
1969 },
1970 Expression::TypeAlias {
1971 doc,
1972 attributes,
1973 name,
1974 name_span,
1975 generics,
1976 annotation,
1977 ty,
1978 span,
1979 ..
1980 } => Expression::TypeAlias {
1981 doc,
1982 attributes,
1983 name,
1984 name_span,
1985 generics,
1986 annotation,
1987 ty,
1988 visibility: Visibility::Public,
1989 span,
1990 },
1991 Expression::Interface {
1992 doc,
1993 name,
1994 name_span,
1995 generics,
1996 parents,
1997 method_signatures,
1998 span,
1999 ..
2000 } => Expression::Interface {
2001 doc,
2002 name,
2003 name_span,
2004 generics,
2005 parents,
2006 method_signatures,
2007 visibility: Visibility::Public,
2008 span,
2009 },
2010 expression => expression,
2011 }
2012 }
2013
2014 pub fn has_else(&self) -> bool {
2015 match self {
2016 Self::Block { items, .. } if items.is_empty() => false,
2017 Self::Unit { .. } => false,
2018 Self::If { alternative, .. } | Self::IfLet { alternative, .. } => {
2019 alternative.has_else()
2020 }
2021 _ => true,
2022 }
2023 }
2024}
2025
2026#[derive(Debug, Clone, PartialEq)]
2027pub enum Literal {
2028 Integer {
2029 value: u64,
2030 text: Option<String>,
2031 },
2032 Float {
2033 value: f64,
2034 text: Option<String>,
2035 },
2036 Imaginary(f64),
2038 Boolean(bool),
2039 String {
2040 value: String,
2041 raw: bool,
2042 },
2043 FormatString(Vec<FormatStringPart>),
2044 Char(String),
2045 Slice(Vec<Expression>),
2046}
2047
2048#[derive(Debug, Clone, PartialEq)]
2049pub enum FormatStringPart {
2050 Text(String),
2051 Expression(Box<Expression>),
2052}
2053
2054#[derive(Debug, Clone, PartialEq)]
2055pub enum UnaryOperator {
2056 Negative,
2057 Not,
2058 BitwiseNot,
2059 Deref,
2060}
2061
2062#[derive(Debug, Clone, Copy, PartialEq)]
2063pub enum BinaryOperator {
2064 Addition,
2065 Subtraction,
2066 Multiplication,
2067 Division,
2068 BitwiseAnd,
2069 BitwiseOr,
2070 BitwiseXor,
2071 BitwiseAndNot,
2072 ShiftLeft,
2073 ShiftRight,
2074 LessThan,
2075 LessThanOrEqual,
2076 GreaterThan,
2077 GreaterThanOrEqual,
2078 Remainder,
2079 Equal,
2080 NotEqual,
2081 And,
2082 Or,
2083 Pipeline,
2084}
2085
2086impl BinaryOperator {
2087 pub fn compound_assignment_symbol(&self) -> Option<&'static str> {
2091 match self {
2092 BinaryOperator::Addition => Some("+="),
2093 BinaryOperator::Subtraction => Some("-="),
2094 BinaryOperator::Multiplication => Some("*="),
2095 BinaryOperator::Division => Some("/="),
2096 BinaryOperator::Remainder => Some("%="),
2097 BinaryOperator::BitwiseAnd => Some("&="),
2098 BinaryOperator::BitwiseOr => Some("|="),
2099 BinaryOperator::BitwiseXor => Some("^="),
2100 BinaryOperator::BitwiseAndNot => Some("&^="),
2101 BinaryOperator::ShiftLeft => Some("<<="),
2102 BinaryOperator::ShiftRight => Some(">>="),
2103 _ => None,
2104 }
2105 }
2106}
2107
2108impl std::fmt::Display for BinaryOperator {
2109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2110 let symbol = match self {
2111 BinaryOperator::Addition => "+",
2112 BinaryOperator::Subtraction => "-",
2113 BinaryOperator::Multiplication => "*",
2114 BinaryOperator::Division => "/",
2115 BinaryOperator::Remainder => "%",
2116 BinaryOperator::BitwiseAnd => "&",
2117 BinaryOperator::BitwiseOr => "|",
2118 BinaryOperator::BitwiseXor => "^",
2119 BinaryOperator::BitwiseAndNot => "&^",
2120 BinaryOperator::ShiftLeft => "<<",
2121 BinaryOperator::ShiftRight => ">>",
2122 BinaryOperator::Equal => "==",
2123 BinaryOperator::NotEqual => "!=",
2124 BinaryOperator::LessThan => "<",
2125 BinaryOperator::LessThanOrEqual => "<=",
2126 BinaryOperator::GreaterThan => ">",
2127 BinaryOperator::GreaterThanOrEqual => ">=",
2128 BinaryOperator::And => "&&",
2129 BinaryOperator::Or => "||",
2130 BinaryOperator::Pipeline => "|>",
2131 };
2132 write!(f, "{}", symbol)
2133 }
2134}
2135
2136#[derive(Debug, Clone, PartialEq)]
2137pub struct ParentInterface {
2138 pub annotation: Annotation,
2139 pub ty: Type,
2140 pub span: Span,
2141}
2142
2143#[derive(Debug, Clone, Copy, PartialEq)]
2144#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2145pub enum Visibility {
2146 Public,
2147 Private,
2148}
2149
2150impl Visibility {
2151 pub fn is_public(&self) -> bool {
2152 matches!(self, Visibility::Public)
2153 }
2154}
2155
2156#[derive(Debug, Clone, PartialEq)]
2157pub enum ImportAlias {
2158 Named(EcoString, Span),
2159 Blank(Span),
2160}