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