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