Skip to main content

lisette_syntax/
ast.rs

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