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