Skip to main content

lisette_syntax/
ast.rs

1use ecow::EcoString;
2
3use crate::program::{CallKind, DotAccessResolution};
4use crate::types::Type;
5
6macro_rules! children {
7    () => { Vec::new() };
8    ($($expression:expr),+ $(,)?) => {{
9        let __children: Vec<&Expression> = vec![$($expression),+];
10        __children
11    }};
12}
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum DeadCodeCause {
16    Return,
17    Break,
18    Continue,
19    DivergingIf,
20    DivergingMatch,
21    InfiniteLoop,
22    DivergingCall,
23}
24
25#[derive(Clone, PartialEq)]
26pub struct Binding {
27    pub pattern: Pattern,
28    pub annotation: Option<Annotation>,
29    pub ty: Type,
30    pub mut_span: Option<Span>,
31}
32
33impl Binding {
34    pub fn is_mutable(&self) -> bool {
35        self.mut_span.is_some()
36    }
37}
38
39impl std::fmt::Debug for Binding {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        let mut s = f.debug_struct("Binding");
42        s.field("pattern", &self.pattern);
43        s.field("annotation", &self.annotation);
44        s.field("ty", &self.ty);
45        if self.mut_span.is_some() {
46            s.field("mut_span", &self.mut_span);
47        }
48        s.finish()
49    }
50}
51
52pub type BindingId = u32;
53
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum IdentifierResolution {
56    Unresolved,
57    Binding(BindingId),
58    Definition(EcoString),
59}
60
61impl IdentifierResolution {
62    pub fn binding_id(&self) -> Option<BindingId> {
63        match self {
64            Self::Binding(id) => Some(*id),
65            Self::Unresolved | Self::Definition(_) => None,
66        }
67    }
68
69    pub fn definition(&self) -> Option<&str> {
70        match self {
71            Self::Definition(definition) => Some(definition),
72            Self::Unresolved | Self::Binding(_) => None,
73        }
74    }
75}
76
77#[derive(Debug, Clone, PartialEq)]
78pub enum LetMode {
79    Plain,
80    Assert,
81    Else {
82        block: Box<Expression>,
83        else_span: Span,
84    },
85    /// Parser recovery for the invalid combination `let assert ... else ...`.
86    InvalidAssertElse {
87        block: Box<Expression>,
88        else_span: Span,
89    },
90}
91
92impl LetMode {
93    pub fn is_assert(&self) -> bool {
94        matches!(self, Self::Assert | Self::InvalidAssertElse { .. })
95    }
96
97    pub fn else_block(&self) -> Option<&Expression> {
98        match self {
99            Self::Else { block, .. } | Self::InvalidAssertElse { block, .. } => Some(block),
100            Self::Plain | Self::Assert => None,
101        }
102    }
103
104    pub fn else_block_mut(&mut self) -> Option<&mut Expression> {
105        match self {
106            Self::Else { block, .. } | Self::InvalidAssertElse { block, .. } => Some(block),
107            Self::Plain | Self::Assert => None,
108        }
109    }
110
111    pub fn map_else(self, map: impl FnOnce(Expression, Span) -> Expression) -> Self {
112        match self {
113            Self::Else { block, else_span } => Self::Else {
114                block: Box::new(map(*block, else_span)),
115                else_span,
116            },
117            Self::InvalidAssertElse { block, else_span } => Self::InvalidAssertElse {
118                block: Box::new(map(*block, else_span)),
119                else_span,
120            },
121            Self::Plain => Self::Plain,
122            Self::Assert => Self::Assert,
123        }
124    }
125}
126
127#[derive(Debug, Clone, PartialEq)]
128pub enum FunctionBody {
129    Declaration,
130    Definition(Box<Expression>),
131}
132
133impl FunctionBody {
134    pub fn definition(&self) -> Option<&Expression> {
135        match self {
136            Self::Declaration => None,
137            Self::Definition(body) => Some(body),
138        }
139    }
140
141    pub fn definition_mut(&mut self) -> Option<&mut Expression> {
142        match self {
143            Self::Declaration => None,
144            Self::Definition(body) => Some(body),
145        }
146    }
147
148    pub fn map_definition(self, map: impl FnOnce(Expression) -> Expression) -> Self {
149        match self {
150            Self::Declaration => Self::Declaration,
151            Self::Definition(body) => Self::Definition(Box::new(map(*body))),
152        }
153    }
154}
155
156#[derive(Debug, Clone, PartialEq)]
157pub enum ConstInitializer {
158    Declaration,
159    Value(Box<Expression>),
160}
161
162#[derive(Debug, Clone, PartialEq)]
163pub enum IfLetAlternative {
164    Absent,
165    Present {
166        expression: Box<Expression>,
167        else_span: Span,
168    },
169}
170
171impl IfLetAlternative {
172    pub fn expression(&self) -> Option<&Expression> {
173        match self {
174            Self::Absent => None,
175            Self::Present { expression, .. } => Some(expression),
176        }
177    }
178
179    pub fn expression_mut(&mut self) -> Option<&mut Expression> {
180        match self {
181            Self::Absent => None,
182            Self::Present { expression, .. } => Some(expression),
183        }
184    }
185
186    pub fn else_span(&self) -> Option<Span> {
187        match self {
188            Self::Absent => None,
189            Self::Present { else_span, .. } => Some(*else_span),
190        }
191    }
192}
193
194impl ConstInitializer {
195    pub fn value(&self) -> Option<&Expression> {
196        match self {
197            Self::Declaration => None,
198            Self::Value(value) => Some(value),
199        }
200    }
201
202    pub fn value_mut(&mut self) -> Option<&mut Expression> {
203        match self {
204            Self::Declaration => None,
205            Self::Value(value) => Some(value),
206        }
207    }
208
209    pub fn map_value(self, map: impl FnOnce(Expression) -> Expression) -> Self {
210        match self {
211            Self::Declaration => Self::Declaration,
212            Self::Value(value) => Self::Value(Box::new(map(*value))),
213        }
214    }
215}
216
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum BindingKind {
219    Let { mutable: bool },
220    Parameter { mutable: bool },
221    MatchArm,
222    IfLet,
223    WhileLet,
224}
225
226impl BindingKind {
227    pub fn is_mutable(&self) -> bool {
228        matches!(
229            self,
230            BindingKind::Let { mutable: true } | BindingKind::Parameter { mutable: true }
231        )
232    }
233
234    pub fn is_param(&self) -> bool {
235        matches!(self, BindingKind::Parameter { .. })
236    }
237
238    pub fn is_match_arm(&self) -> bool {
239        matches!(self, BindingKind::MatchArm)
240    }
241
242    pub fn is_pattern_position(&self) -> bool {
243        matches!(
244            self,
245            BindingKind::MatchArm | BindingKind::IfLet | BindingKind::WhileLet
246        )
247    }
248}
249
250#[derive(Clone, PartialEq)]
251pub struct MatchArm {
252    pub pattern: Pattern,
253    pub guard: Option<Box<Expression>>,
254    pub expression: Box<Expression>,
255}
256
257impl MatchArm {
258    pub fn has_guard(&self) -> bool {
259        self.guard.is_some()
260    }
261}
262
263impl std::fmt::Debug for MatchArm {
264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265        let mut s = f.debug_struct("MatchArm");
266        s.field("pattern", &self.pattern);
267        if self.guard.is_some() {
268            s.field("guard", &self.guard);
269        }
270        s.field("expression", &self.expression);
271        s.finish()
272    }
273}
274
275#[derive(Debug, Clone, PartialEq)]
276pub enum SelectArm {
277    Receive {
278        binding: Box<Pattern>,
279        receive_expression: Box<Expression>,
280        body: Box<Expression>,
281    },
282    Send {
283        send_expression: Box<Expression>,
284        body: Box<Expression>,
285    },
286    MatchReceive {
287        receive_expression: Box<Expression>,
288        arms: Vec<MatchArm>,
289    },
290    WildCard {
291        body: Box<Expression>,
292    },
293}
294
295#[derive(Debug, Clone, PartialEq)]
296pub enum RestPattern {
297    Absent,
298    Discard(Span),
299    Bind { name: EcoString, span: Span },
300}
301
302#[derive(Debug, Clone, PartialEq)]
303pub enum ConstructorPatternResolution {
304    Unresolved,
305    Const {
306        qualified_name: EcoString,
307    },
308    ConstValue {
309        qualified_name: EcoString,
310        value: Literal,
311    },
312    EnumVariant {
313        enum_name: EcoString,
314        variant_name: EcoString,
315    },
316}
317
318#[derive(Debug, Clone, PartialEq)]
319pub enum RecordPatternResolution {
320    Unresolved,
321    Struct {
322        struct_name: EcoString,
323    },
324    EnumVariant {
325        enum_name: EcoString,
326        variant_name: EcoString,
327    },
328}
329
330#[derive(Debug, Clone, PartialEq)]
331pub enum SequencePatternResolution {
332    Unresolved,
333    Slice { element_type: Type },
334    Array { element_type: Type, length: u64 },
335}
336
337impl RestPattern {
338    pub fn is_present(&self) -> bool {
339        !matches!(self, RestPattern::Absent)
340    }
341}
342
343#[derive(Debug, Clone, PartialEq)]
344pub enum Pattern {
345    Literal {
346        literal: Literal,
347        ty: Type,
348        span: Span,
349    },
350    Unit {
351        ty: Type,
352        span: Span,
353    },
354    EnumVariant {
355        identifier: EcoString,
356        fields: Vec<Self>,
357        rest: bool,
358        resolution: ConstructorPatternResolution,
359        ty: Type,
360        span: Span,
361    },
362    Struct {
363        identifier: EcoString,
364        fields: Vec<StructFieldPattern>,
365        rest: bool,
366        resolution: RecordPatternResolution,
367        ty: Type,
368        span: Span,
369    },
370    Tuple {
371        elements: Vec<Self>,
372        span: Span,
373    },
374    WildCard {
375        span: Span,
376    },
377    Identifier {
378        identifier: EcoString,
379        span: Span,
380    },
381    Slice {
382        prefix: Vec<Self>,
383        rest: RestPattern,
384        resolution: SequencePatternResolution,
385        span: Span,
386    },
387    Or {
388        patterns: Vec<Self>,
389        span: Span,
390    },
391    AsBinding {
392        pattern: Box<Self>,
393        name: EcoString,
394        name_span: Span,
395        span: Span,
396    },
397}
398
399/// Binding names introduced by a pattern, paired with their spans, in source order.
400pub fn collect_pattern_bindings(pattern: &Pattern) -> Vec<(String, Span)> {
401    match pattern {
402        Pattern::Identifier { identifier, span } => vec![(identifier.to_string(), *span)],
403        Pattern::Tuple { elements, .. } => {
404            elements.iter().flat_map(collect_pattern_bindings).collect()
405        }
406        Pattern::EnumVariant { fields, .. } => {
407            fields.iter().flat_map(collect_pattern_bindings).collect()
408        }
409        Pattern::Struct { fields, .. } => fields
410            .iter()
411            .flat_map(|f| collect_pattern_bindings(&f.value))
412            .collect(),
413        Pattern::Slice { prefix, rest, .. } => {
414            let mut bindings: Vec<_> = prefix.iter().flat_map(collect_pattern_bindings).collect();
415            if let RestPattern::Bind { name, span } = rest {
416                bindings.push((name.to_string(), *span));
417            }
418            bindings
419        }
420        Pattern::Or { patterns, .. } => patterns
421            .first()
422            .map(collect_pattern_bindings)
423            .unwrap_or_default(),
424        Pattern::AsBinding {
425            pattern,
426            name,
427            name_span,
428            ..
429        } => {
430            let mut bindings = collect_pattern_bindings(pattern);
431            bindings.push((name.to_string(), *name_span));
432            bindings
433        }
434        Pattern::WildCard { .. } | Pattern::Literal { .. } | Pattern::Unit { .. } => vec![],
435    }
436}
437
438impl Pattern {
439    pub fn get_span(&self) -> Span {
440        match self {
441            Pattern::Identifier { span, .. } => *span,
442            Pattern::Literal { span, .. } => *span,
443            Pattern::EnumVariant { span, .. } => *span,
444            Pattern::Struct { span, .. } => *span,
445            Pattern::WildCard { span } => *span,
446            Pattern::Unit { span, .. } => *span,
447            Pattern::Tuple { span, .. } => *span,
448            Pattern::Slice { span, .. } => *span,
449            Pattern::Or { span, .. } => *span,
450            Pattern::AsBinding { span, .. } => *span,
451        }
452    }
453
454    pub fn get_type(&self) -> Option<Type> {
455        match self {
456            Pattern::Identifier { .. } => None,
457            Pattern::Literal { ty, .. } => Some(ty.clone()),
458            Pattern::EnumVariant { ty, .. } => Some(ty.clone()),
459            Pattern::Struct { ty, .. } => Some(ty.clone()),
460            Pattern::WildCard { .. } => None,
461            Pattern::Unit { ty, .. } => Some(ty.clone()),
462            Pattern::Tuple { .. } => None,
463            Pattern::Slice { .. } => None,
464            Pattern::Or { .. } => None,
465            Pattern::AsBinding { pattern, .. } => pattern.get_type(),
466        }
467    }
468
469    pub fn is_identifier(&self) -> bool {
470        matches!(self, Pattern::Identifier { .. } | Pattern::AsBinding { .. })
471    }
472
473    pub fn get_identifier(&self) -> Option<EcoString> {
474        match self {
475            Pattern::Identifier { identifier, .. } => Some(identifier.clone()),
476            Pattern::AsBinding { name, .. } => Some(name.clone()),
477            _ => None,
478        }
479    }
480
481    pub fn is_some_pattern(&self) -> bool {
482        let peeled = match self {
483            Pattern::AsBinding { pattern, .. } => pattern.as_ref(),
484            p => p,
485        };
486        matches!(peeled, Pattern::EnumVariant { identifier, fields, .. }
487            if crate::types::unqualified_name(identifier) == "Some" && fields.len() == 1)
488    }
489}
490
491#[derive(Debug, Clone, PartialEq)]
492pub struct StructFieldPattern {
493    pub name: EcoString,
494    pub value: Pattern,
495}
496
497#[derive(Clone, Copy)]
498pub struct FunctionDefinitionView<'a> {
499    pub name: &'a EcoString,
500    pub name_span: Span,
501    pub generics: &'a [Generic],
502    pub params: &'a [Binding],
503    pub body: Option<&'a Expression>,
504    pub return_type: &'a Type,
505    pub annotation: &'a Annotation,
506}
507
508#[derive(Debug, Clone, PartialEq)]
509pub enum VariantFields {
510    Unit,
511    Tuple(Vec<EnumFieldDefinition>),
512    Struct(Vec<EnumFieldDefinition>),
513}
514
515impl VariantFields {
516    pub fn is_empty(&self) -> bool {
517        match self {
518            VariantFields::Unit => true,
519            VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.is_empty(),
520        }
521    }
522
523    pub fn len(&self) -> usize {
524        match self {
525            VariantFields::Unit => 0,
526            VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.len(),
527        }
528    }
529
530    pub fn as_slice(&self) -> &[EnumFieldDefinition] {
531        match self {
532            VariantFields::Unit => &[],
533            VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields,
534        }
535    }
536
537    pub fn iter(&self) -> std::slice::Iter<'_, EnumFieldDefinition> {
538        self.as_slice().iter()
539    }
540
541    pub fn is_struct(&self) -> bool {
542        matches!(self, VariantFields::Struct(_))
543    }
544}
545
546impl<'a> IntoIterator for &'a VariantFields {
547    type Item = &'a EnumFieldDefinition;
548    type IntoIter = std::slice::Iter<'a, EnumFieldDefinition>;
549
550    fn into_iter(self) -> Self::IntoIter {
551        self.iter()
552    }
553}
554
555#[derive(Debug, Clone, PartialEq)]
556pub struct EnumVariant {
557    pub doc: Option<String>,
558    pub name: EcoString,
559    pub name_span: Span,
560    pub fields: VariantFields,
561}
562
563#[derive(Debug, Clone, PartialEq)]
564pub struct EnumFieldDefinition {
565    pub name: EcoString,
566    pub name_span: Span,
567    pub annotation: Annotation,
568    pub ty: Type,
569}
570
571#[derive(Debug, Clone, PartialEq)]
572pub struct Attribute {
573    pub name: String,
574    pub args: Vec<AttributeArg>,
575    pub span: Span,
576}
577
578#[derive(Debug, Clone, PartialEq)]
579#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
580pub enum AttributeArg {
581    /// A flag option, e.g., `omitempty`, `skip`, `snake_case`
582    Flag(String),
583    /// A negated flag, e.g., `!omitempty`
584    NegatedFlag(String),
585    /// A quoted string, e.g., `"custom_name"` (name override)
586    String(String),
587    /// A raw backtick literal, e.g., `json:"name,string"`
588    Raw(String),
589}
590
591#[derive(Debug, Clone, Copy, PartialEq)]
592#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
593pub enum StructKind {
594    Record,
595    Tuple,
596}
597
598/// The field collection carries the struct's shape so it cannot disagree with
599/// the fields it describes.
600#[derive(Debug, Clone, PartialEq)]
601pub enum StructFields {
602    Record(Vec<StructFieldDefinition>),
603    Tuple(Vec<StructFieldDefinition>),
604}
605
606impl StructFields {
607    pub fn kind(&self) -> StructKind {
608        match self {
609            Self::Record(_) => StructKind::Record,
610            Self::Tuple(_) => StructKind::Tuple,
611        }
612    }
613
614    pub fn as_slice(&self) -> &[StructFieldDefinition] {
615        match self {
616            Self::Record(fields) | Self::Tuple(fields) => fields,
617        }
618    }
619}
620
621impl std::ops::Deref for StructFields {
622    type Target = [StructFieldDefinition];
623
624    fn deref(&self) -> &Self::Target {
625        self.as_slice()
626    }
627}
628
629impl std::ops::DerefMut for StructFields {
630    fn deref_mut(&mut self) -> &mut Self::Target {
631        match self {
632            Self::Record(fields) | Self::Tuple(fields) => fields,
633        }
634    }
635}
636
637impl<'a> IntoIterator for &'a StructFields {
638    type Item = &'a StructFieldDefinition;
639    type IntoIter = std::slice::Iter<'a, StructFieldDefinition>;
640
641    fn into_iter(self) -> Self::IntoIter {
642        self.as_slice().iter()
643    }
644}
645
646impl<'a> IntoIterator for &'a mut StructFields {
647    type Item = &'a mut StructFieldDefinition;
648    type IntoIter = std::slice::IterMut<'a, StructFieldDefinition>;
649
650    fn into_iter(self) -> Self::IntoIter {
651        match self {
652            StructFields::Record(fields) | StructFields::Tuple(fields) => fields.iter_mut(),
653        }
654    }
655}
656
657#[derive(Debug, Clone, PartialEq)]
658pub struct StructFieldDefinition {
659    pub doc: Option<String>,
660    pub name: EcoString,
661    pub name_span: Span,
662    pub annotation: Annotation,
663    pub visibility: Visibility,
664    pub ty: Type,
665    pub kind: StructFieldKind,
666}
667
668#[derive(Debug, Clone, PartialEq)]
669pub enum StructFieldKind {
670    Named { attributes: Vec<Attribute> },
671    Embedded,
672}
673
674impl StructFieldDefinition {
675    pub fn attributes(&self) -> &[Attribute] {
676        match &self.kind {
677            StructFieldKind::Named { attributes } => attributes,
678            StructFieldKind::Embedded => &[],
679        }
680    }
681
682    pub fn is_embedded(&self) -> bool {
683        matches!(self.kind, StructFieldKind::Embedded)
684    }
685}
686
687#[derive(Debug, Clone, PartialEq)]
688pub struct StructFieldAssignment {
689    pub name: EcoString,
690    pub name_span: Span,
691    pub value: Box<Expression>,
692}
693
694#[derive(Debug, Clone, PartialEq)]
695pub enum StructSpread {
696    None,
697    From(Box<Expression>),
698    Autofill { span: Span },
699}
700
701impl StructSpread {
702    pub fn is_none(&self) -> bool {
703        matches!(self, Self::None)
704    }
705
706    pub(crate) fn is_some(&self) -> bool {
707        !self.is_none()
708    }
709
710    pub fn span(&self) -> Option<Span> {
711        match self {
712            Self::None => None,
713            Self::From(e) => Some(e.get_span()),
714            Self::Autofill { span } => Some(*span),
715        }
716    }
717
718    pub fn as_expression(&self) -> Option<&Expression> {
719        match self {
720            Self::From(e) => Some(e),
721            Self::None | Self::Autofill { .. } => None,
722        }
723    }
724}
725
726#[derive(Debug, Clone, PartialEq)]
727#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
728pub struct FunctionAnnotationParameter {
729    pub annotation: Annotation,
730    pub mutable: bool,
731}
732
733#[derive(Clone, PartialEq)]
734pub struct CallTypeArguments(CallTypeArgumentState);
735
736#[derive(Clone, PartialEq)]
737enum CallTypeArgumentState {
738    None,
739    Unresolved(Vec<Annotation>),
740    Resolved(Vec<ResolvedCallTypeArgument>),
741    CheckedWithoutTypes(Vec<Annotation>),
742}
743
744#[derive(Debug, Clone, PartialEq)]
745#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
746struct ResolvedCallTypeArgument {
747    annotation: Annotation,
748    ty: Type,
749}
750
751#[derive(Debug, Clone, Copy, PartialEq)]
752pub struct ResolvedCallTypeArguments<'a> {
753    arguments: &'a [ResolvedCallTypeArgument],
754}
755
756impl<'a> ResolvedCallTypeArguments<'a> {
757    pub fn len(self) -> usize {
758        self.arguments.len()
759    }
760
761    pub fn is_empty(self) -> bool {
762        self.arguments.is_empty()
763    }
764
765    pub fn first(self) -> Option<&'a Type> {
766        self.arguments.first().map(|argument| &argument.ty)
767    }
768
769    pub fn get(self, index: usize) -> Option<&'a Type> {
770        self.arguments.get(index).map(|argument| &argument.ty)
771    }
772
773    pub fn iter(self) -> impl ExactSizeIterator<Item = &'a Type> + Clone {
774        self.arguments.iter().map(|argument| &argument.ty)
775    }
776}
777
778impl std::ops::Index<usize> for ResolvedCallTypeArguments<'_> {
779    type Output = Type;
780
781    fn index(&self, index: usize) -> &Self::Output {
782        &self.arguments[index].ty
783    }
784}
785
786impl std::fmt::Debug for CallTypeArguments {
787    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
788        match &self.0 {
789            CallTypeArgumentState::None => f.write_str("None"),
790            CallTypeArgumentState::Unresolved(annotations) => {
791                f.debug_tuple("Unresolved").field(annotations).finish()
792            }
793            CallTypeArgumentState::Resolved(arguments) => {
794                let annotations = arguments
795                    .iter()
796                    .map(|argument| &argument.annotation)
797                    .collect::<Vec<_>>();
798                let types = arguments
799                    .iter()
800                    .map(|argument| &argument.ty)
801                    .collect::<Vec<_>>();
802                f.debug_struct("Resolved")
803                    .field("annotations", &annotations)
804                    .field("types", &types)
805                    .finish()
806            }
807            CallTypeArgumentState::CheckedWithoutTypes(annotations) => f
808                .debug_struct("Resolved")
809                .field("annotations", annotations)
810                .field("types", &Vec::<Type>::new())
811                .finish(),
812        }
813    }
814}
815
816impl CallTypeArguments {
817    pub const fn none() -> Self {
818        Self(CallTypeArgumentState::None)
819    }
820
821    pub fn unresolved(annotations: Vec<Annotation>) -> Self {
822        if annotations.is_empty() {
823            Self::none()
824        } else {
825            Self(CallTypeArgumentState::Unresolved(annotations))
826        }
827    }
828
829    pub fn resolved(arguments: impl IntoIterator<Item = (Annotation, Type)>) -> Self {
830        let arguments = arguments
831            .into_iter()
832            .map(|(annotation, ty)| ResolvedCallTypeArgument { annotation, ty })
833            .collect::<Vec<_>>();
834        if arguments.is_empty() {
835            Self::none()
836        } else {
837            Self(CallTypeArgumentState::Resolved(arguments))
838        }
839    }
840
841    pub fn checked_without_types(annotations: Vec<Annotation>) -> Self {
842        if annotations.is_empty() {
843            Self::none()
844        } else {
845            Self(CallTypeArgumentState::CheckedWithoutTypes(annotations))
846        }
847    }
848
849    pub fn annotations(
850        &self,
851    ) -> impl ExactSizeIterator<Item = &Annotation> + DoubleEndedIterator + Clone {
852        let len = match &self.0 {
853            CallTypeArgumentState::None => 0,
854            CallTypeArgumentState::Unresolved(annotations)
855            | CallTypeArgumentState::CheckedWithoutTypes(annotations) => annotations.len(),
856            CallTypeArgumentState::Resolved(arguments) => arguments.len(),
857        };
858        (0..len).map(move |index| match &self.0 {
859            CallTypeArgumentState::None => unreachable!(),
860            CallTypeArgumentState::Unresolved(annotations)
861            | CallTypeArgumentState::CheckedWithoutTypes(annotations) => &annotations[index],
862            CallTypeArgumentState::Resolved(arguments) => &arguments[index].annotation,
863        })
864    }
865
866    pub fn resolved_types(&self) -> Option<ResolvedCallTypeArguments<'_>> {
867        let arguments: &[ResolvedCallTypeArgument] = match &self.0 {
868            CallTypeArgumentState::None | CallTypeArgumentState::CheckedWithoutTypes(_) => &[],
869            CallTypeArgumentState::Unresolved(_) => return None,
870            CallTypeArgumentState::Resolved(arguments) => arguments,
871        };
872        Some(ResolvedCallTypeArguments { arguments })
873    }
874
875    pub fn into_annotations(self) -> Vec<Annotation> {
876        match self.0 {
877            CallTypeArgumentState::None => Vec::new(),
878            CallTypeArgumentState::Unresolved(annotations)
879            | CallTypeArgumentState::CheckedWithoutTypes(annotations) => annotations,
880            CallTypeArgumentState::Resolved(arguments) => arguments
881                .into_iter()
882                .map(|argument| argument.annotation)
883                .collect(),
884        }
885    }
886
887    pub fn is_empty(&self) -> bool {
888        matches!(self.0, CallTypeArgumentState::None)
889    }
890}
891
892impl Default for CallTypeArguments {
893    fn default() -> Self {
894        Self::none()
895    }
896}
897
898#[derive(Debug, Clone, PartialEq)]
899#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
900pub enum Annotation {
901    Constructor {
902        name: EcoString,
903        params: Vec<Self>,
904        span: Span,
905    },
906    Function {
907        params: Vec<FunctionAnnotationParameter>,
908        return_type: Box<Self>,
909        span: Span,
910    },
911    Tuple {
912        elements: Vec<Self>,
913        span: Span,
914    },
915    Unknown,
916    Opaque {
917        span: Span,
918    },
919    /// An integer literal in type-argument position, e.g. the `3` in
920    /// `Array<int, 3>`. Valid only as an `Array` size, rejected elsewhere.
921    Constant {
922        value: u64,
923        text: Option<String>,
924        span: Span,
925    },
926}
927
928impl Annotation {
929    pub(crate) fn unit() -> Self {
930        Self::Constructor {
931            name: "Unit".into(),
932            params: vec![],
933            span: Span::dummy(),
934        }
935    }
936
937    pub fn get_span(&self) -> Span {
938        match self {
939            Self::Constructor { span, .. } => *span,
940            Self::Function { span, .. } => *span,
941            Self::Tuple { span, .. } => *span,
942            Self::Opaque { span } => *span,
943            Self::Constant { span, .. } => *span,
944            Self::Unknown => Span::dummy(),
945        }
946    }
947
948    pub fn get_name(&self) -> Option<String> {
949        match self {
950            Self::Constructor { name, .. } => Some(name.to_string()),
951            _ => None,
952        }
953    }
954
955    pub fn is_unknown(&self) -> bool {
956        matches!(self, Self::Unknown)
957    }
958
959    pub fn is_opaque(&self) -> bool {
960        matches!(self, Self::Opaque { .. })
961    }
962}
963
964#[derive(Clone, PartialEq)]
965pub struct Generic {
966    pub name: EcoString,
967    bounds: GenericBounds,
968    pub span: Span,
969}
970
971impl std::fmt::Debug for Generic {
972    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
973        let bounds = self.bounds().collect::<Vec<_>>();
974        let resolved_bounds = self
975            .resolved_bounds()
976            .into_iter()
977            .flatten()
978            .collect::<Vec<_>>();
979
980        f.debug_struct("Generic")
981            .field("name", &self.name)
982            .field("bounds", &bounds)
983            .field("resolved_bounds", &resolved_bounds)
984            .field("span", &self.span)
985            .finish()
986    }
987}
988
989#[derive(Debug, Clone, PartialEq)]
990enum GenericBounds {
991    Unresolved(Vec<Annotation>),
992    Resolved(Vec<ResolvedGenericBound>),
993}
994
995#[derive(Debug, Clone, PartialEq)]
996struct ResolvedGenericBound {
997    annotation: Annotation,
998    ty: Type,
999}
1000
1001impl Generic {
1002    pub fn new(name: impl Into<EcoString>, bounds: Vec<Annotation>, span: Span) -> Self {
1003        let bounds = if bounds.is_empty() {
1004            GenericBounds::Resolved(Vec::new())
1005        } else {
1006            GenericBounds::Unresolved(bounds)
1007        };
1008        Self {
1009            name: name.into(),
1010            bounds,
1011            span,
1012        }
1013    }
1014
1015    pub fn bounds(&self) -> impl Iterator<Item = &Annotation> + Clone {
1016        let unresolved = match &self.bounds {
1017            GenericBounds::Unresolved(bounds) => Some(bounds.as_slice()),
1018            GenericBounds::Resolved(_) => None,
1019        };
1020        let resolved = match &self.bounds {
1021            GenericBounds::Unresolved(_) => None,
1022            GenericBounds::Resolved(bounds) => Some(bounds.as_slice()),
1023        };
1024        unresolved.into_iter().flatten().chain(
1025            resolved
1026                .into_iter()
1027                .flatten()
1028                .map(|bound| &bound.annotation),
1029        )
1030    }
1031
1032    pub fn bound_count(&self) -> usize {
1033        match &self.bounds {
1034            GenericBounds::Unresolved(bounds) => bounds.len(),
1035            GenericBounds::Resolved(bounds) => bounds.len(),
1036        }
1037    }
1038
1039    pub fn bounds_are_resolved(&self) -> bool {
1040        matches!(self.bounds, GenericBounds::Resolved(_))
1041    }
1042
1043    pub fn resolved_bounds(&self) -> Option<impl Iterator<Item = &Type> + Clone> {
1044        let GenericBounds::Resolved(bounds) = &self.bounds else {
1045            return None;
1046        };
1047        Some(bounds.iter().map(|bound| &bound.ty))
1048    }
1049
1050    pub fn resolve_bounds_with(&mut self, mut resolve: impl FnMut(&Annotation) -> Type) {
1051        let resolved = match &mut self.bounds {
1052            GenericBounds::Unresolved(annotations) => annotations
1053                .drain(..)
1054                .map(|annotation| {
1055                    let ty = resolve(&annotation);
1056                    ResolvedGenericBound { annotation, ty }
1057                })
1058                .collect(),
1059            GenericBounds::Resolved(bounds) => {
1060                for bound in bounds {
1061                    bound.ty = resolve(&bound.annotation);
1062                }
1063                return;
1064            }
1065        };
1066        self.bounds = GenericBounds::Resolved(resolved);
1067    }
1068
1069    pub fn retain_bounds(&mut self, mut keep: impl FnMut(&Annotation) -> bool) {
1070        match &mut self.bounds {
1071            GenericBounds::Unresolved(bounds) => bounds.retain(&mut keep),
1072            GenericBounds::Resolved(bounds) => bounds.retain(|bound| keep(&bound.annotation)),
1073        }
1074    }
1075}
1076
1077#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1078#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1079pub struct Span {
1080    pub file_id: u32,
1081    pub byte_offset: u32,
1082    pub byte_length: u32,
1083}
1084
1085impl Span {
1086    pub fn new(file_id: u32, byte_offset: u32, byte_length: u32) -> Self {
1087        Span {
1088            file_id,
1089            byte_offset,
1090            byte_length,
1091        }
1092    }
1093
1094    pub fn dummy() -> Self {
1095        Span {
1096            file_id: u32::MAX,
1097            byte_offset: 0,
1098            byte_length: 0,
1099        }
1100    }
1101
1102    pub fn is_dummy(&self) -> bool {
1103        self.file_id == u32::MAX
1104    }
1105
1106    pub fn end(&self) -> u32 {
1107        self.byte_offset + self.byte_length
1108    }
1109
1110    pub fn merge(self, other: Span) -> Span {
1111        assert_eq!(
1112            self.file_id, other.file_id,
1113            "cannot merge spans from different files"
1114        );
1115        let start = self.byte_offset.min(other.byte_offset);
1116        let end = self.end().max(other.end());
1117        Span::new(self.file_id, start, end - start)
1118    }
1119}
1120
1121#[derive(Debug, Clone, PartialEq)]
1122#[allow(clippy::large_enum_variant)]
1123pub enum Expression {
1124    Literal {
1125        literal: Literal,
1126        ty: Type,
1127        span: Span,
1128    },
1129    Function {
1130        doc: Option<String>,
1131        attributes: Vec<Attribute>,
1132        name: EcoString,
1133        name_span: Span,
1134        generics: Vec<Generic>,
1135        params: Vec<Binding>,
1136        return_annotation: Annotation,
1137        return_type: Type,
1138        visibility: Visibility,
1139        body: FunctionBody,
1140        ty: Type,
1141        span: Span,
1142    },
1143    Lambda {
1144        params: Vec<Binding>,
1145        return_annotation: Annotation,
1146        body: Box<Expression>,
1147        ty: Type,
1148        span: Span,
1149    },
1150    Block {
1151        items: Vec<Expression>,
1152        ty: Type,
1153        span: Span,
1154    },
1155    Let {
1156        binding: Box<Binding>,
1157        value: Box<Expression>,
1158        mode: LetMode,
1159        ty: Type,
1160        span: Span,
1161    },
1162    Identifier {
1163        value: EcoString,
1164        ty: Type,
1165        span: Span,
1166        resolution: IdentifierResolution,
1167    },
1168    Call {
1169        expression: Box<Expression>,
1170        args: Vec<Expression>,
1171        spread: Option<Box<Expression>>,
1172        type_arguments: CallTypeArguments,
1173        ty: Type,
1174        span: Span,
1175        call_kind: CallKind,
1176    },
1177    If {
1178        condition: Box<Expression>,
1179        consequence: Box<Expression>,
1180        alternative: Option<Box<Expression>>,
1181        ty: Type,
1182        span: Span,
1183    },
1184    IfLet {
1185        pattern: Pattern,
1186        scrutinee: Box<Expression>,
1187        consequence: Box<Expression>,
1188        alternative: IfLetAlternative,
1189        ty: Type,
1190        span: Span,
1191    },
1192    Match {
1193        subject: Box<Expression>,
1194        arms: Vec<MatchArm>,
1195        ty: Type,
1196        span: Span,
1197    },
1198    Tuple {
1199        elements: Vec<Expression>,
1200        ty: Type,
1201        span: Span,
1202    },
1203    StructCall {
1204        name: EcoString,
1205        field_assignments: Vec<StructFieldAssignment>,
1206        spread: StructSpread,
1207        ty: Type,
1208        span: Span,
1209    },
1210    DotAccess {
1211        expression: Box<Expression>,
1212        member: EcoString,
1213        ty: Type,
1214        span: Span,
1215        resolution: DotAccessResolution,
1216    },
1217    Assignment {
1218        target: Box<Expression>,
1219        value: Box<Expression>,
1220        compound_operator: Option<BinaryOperator>,
1221        span: Span,
1222    },
1223    Return {
1224        expression: Box<Expression>,
1225        ty: Type,
1226        span: Span,
1227    },
1228    Propagate {
1229        expression: Box<Expression>,
1230        ty: Type,
1231        span: Span,
1232    },
1233    TryBlock {
1234        items: Vec<Expression>,
1235        ty: Type,
1236        try_keyword_span: Span,
1237        span: Span,
1238    },
1239    RecoverBlock {
1240        items: Vec<Expression>,
1241        ty: Type,
1242        recover_keyword_span: Span,
1243        span: Span,
1244    },
1245    ImplBlock {
1246        annotation: Annotation,
1247        receiver_name: EcoString,
1248        methods: Vec<Expression>,
1249        generics: Vec<Generic>,
1250        ty: Type,
1251        span: Span,
1252    },
1253    Binary {
1254        operator: BinaryOperator,
1255        left: Box<Expression>,
1256        right: Box<Expression>,
1257        ty: Type,
1258        span: Span,
1259    },
1260    Unary {
1261        operator: UnaryOperator,
1262        expression: Box<Expression>,
1263        ty: Type,
1264        span: Span,
1265    },
1266    Paren {
1267        expression: Box<Expression>,
1268        ty: Type,
1269        span: Span,
1270    },
1271    Const {
1272        doc: Option<String>,
1273        identifier: EcoString,
1274        identifier_span: Span,
1275        annotation: Option<Annotation>,
1276        expression: ConstInitializer,
1277        visibility: Visibility,
1278        ty: Type,
1279        span: Span,
1280    },
1281    VariableDeclaration {
1282        doc: Option<String>,
1283        name: EcoString,
1284        name_span: Span,
1285        annotation: Annotation,
1286        visibility: Visibility,
1287        ty: Type,
1288        span: Span,
1289    },
1290    RawGo {
1291        text: String,
1292    },
1293    Loop {
1294        body: Box<Expression>,
1295        ty: Type,
1296        span: Span,
1297    },
1298    While {
1299        condition: Box<Expression>,
1300        body: Box<Expression>,
1301        span: Span,
1302    },
1303    WhileLet {
1304        pattern: Pattern,
1305        scrutinee: Box<Expression>,
1306        body: Box<Expression>,
1307        span: Span,
1308    },
1309    For {
1310        binding: Box<Binding>,
1311        iterable: Box<Expression>,
1312        body: Box<Expression>,
1313        span: Span,
1314    },
1315    Break {
1316        value: Option<Box<Expression>>,
1317        span: Span,
1318    },
1319    Continue {
1320        span: Span,
1321    },
1322    Enum {
1323        doc: Option<String>,
1324        attributes: Vec<Attribute>,
1325        name: EcoString,
1326        name_span: Span,
1327        generics: Vec<Generic>,
1328        variants: Vec<EnumVariant>,
1329        visibility: Visibility,
1330        span: Span,
1331    },
1332    Struct {
1333        doc: Option<String>,
1334        attributes: Vec<Attribute>,
1335        name: EcoString,
1336        name_span: Span,
1337        generics: Vec<Generic>,
1338        fields: StructFields,
1339        visibility: Visibility,
1340        span: Span,
1341    },
1342    TypeAlias {
1343        doc: Option<String>,
1344        attributes: Vec<Attribute>,
1345        name: EcoString,
1346        name_span: Span,
1347        generics: Vec<Generic>,
1348        annotation: Annotation,
1349        ty: Type,
1350        visibility: Visibility,
1351        span: Span,
1352    },
1353    ModuleImport {
1354        name: EcoString,
1355        name_span: Span,
1356        alias: Option<ImportAlias>,
1357        span: Span,
1358    },
1359    Reference {
1360        expression: Box<Expression>,
1361        ty: Type,
1362        span: Span,
1363    },
1364    Interface {
1365        doc: Option<String>,
1366        name: EcoString,
1367        name_span: Span,
1368        generics: Vec<Generic>,
1369        parents: Vec<ParentInterface>,
1370        method_signatures: Vec<Expression>,
1371        visibility: Visibility,
1372        span: Span,
1373    },
1374    IndexedAccess {
1375        expression: Box<Expression>,
1376        index: Box<Expression>,
1377        ty: Type,
1378        span: Span,
1379        from_colon_syntax: bool,
1380    },
1381    Task {
1382        expression: Box<Expression>,
1383        ty: Type,
1384        span: Span,
1385    },
1386    Defer {
1387        expression: Box<Expression>,
1388        ty: Type,
1389        span: Span,
1390    },
1391    Assert {
1392        expression: Box<Expression>,
1393        ty: Type,
1394        span: Span,
1395    },
1396    Select {
1397        arms: Vec<SelectArm>,
1398        ty: Type,
1399        span: Span,
1400    },
1401    Unit {
1402        ty: Type,
1403        span: Span,
1404    },
1405    Range {
1406        start: Option<Box<Expression>>,
1407        end: Option<Box<Expression>>,
1408        inclusive: bool,
1409        ty: Type,
1410        span: Span,
1411    },
1412    Cast {
1413        expression: Box<Expression>,
1414        target_type: Annotation,
1415        ty: Type,
1416        span: Span,
1417    },
1418}
1419
1420impl Expression {
1421    pub(crate) fn is_block(&self) -> bool {
1422        matches!(self, Expression::Block { .. })
1423    }
1424
1425    pub fn is_range(&self) -> bool {
1426        matches!(self, Expression::Range { .. })
1427    }
1428
1429    pub fn is_conditional(&self) -> bool {
1430        matches!(self, Expression::If { .. } | Expression::IfLet { .. })
1431    }
1432
1433    pub fn is_control_flow(&self) -> bool {
1434        matches!(
1435            self,
1436            Expression::If { .. }
1437                | Expression::IfLet { .. }
1438                | Expression::Match { .. }
1439                | Expression::Select { .. }
1440                | Expression::For { .. }
1441                | Expression::While { .. }
1442                | Expression::WhileLet { .. }
1443                | Expression::Loop { .. }
1444        )
1445    }
1446
1447    pub fn is_temp_producing(&self) -> bool {
1448        matches!(
1449            self.unwrap_parens(),
1450            Expression::If { .. }
1451                | Expression::IfLet { .. }
1452                | Expression::Match { .. }
1453                | Expression::Block { .. }
1454                | Expression::Loop { .. }
1455                | Expression::Select { .. }
1456                | Expression::TryBlock { .. }
1457                | Expression::RecoverBlock { .. }
1458        )
1459    }
1460
1461    pub fn function_definition_view(&self) -> FunctionDefinitionView<'_> {
1462        match self {
1463            Expression::Function {
1464                name,
1465                name_span,
1466                generics,
1467                params,
1468                return_annotation,
1469                return_type,
1470                body,
1471                ..
1472            } => FunctionDefinitionView {
1473                name,
1474                name_span: *name_span,
1475                generics,
1476                params,
1477                body: body.definition(),
1478                return_type,
1479                annotation: return_annotation,
1480            },
1481            _ => panic!("function_definition_view called on non-Function expression"),
1482        }
1483    }
1484
1485    pub fn as_option_constructor(&self) -> Option<std::result::Result<(), ()>> {
1486        let variant = match self {
1487            Expression::Identifier { value, .. } => Some(value.as_str()),
1488            _ => None,
1489        }?;
1490
1491        match variant {
1492            "Option.Some" | "Some" => Some(Ok(())),
1493            "Option.None" | "None" => Some(Err(())),
1494            _ => None,
1495        }
1496    }
1497
1498    pub fn is_none_literal(&self) -> bool {
1499        matches!(self.as_option_constructor(), Some(Err(())))
1500    }
1501
1502    pub fn as_result_constructor(&self) -> Option<std::result::Result<(), ()>> {
1503        let variant = match self {
1504            Expression::Identifier { value, .. } => Some(value.as_str()),
1505            _ => None,
1506        }?;
1507
1508        match variant {
1509            "Result.Ok" | "Ok" => Some(Ok(())),
1510            "Result.Err" | "Err" => Some(Err(())),
1511            _ => None,
1512        }
1513    }
1514
1515    pub fn as_partial_constructor(&self) -> Option<&'static str> {
1516        let variant = match self {
1517            Expression::Identifier { value, .. } => Some(value.as_str()),
1518            _ => None,
1519        }?;
1520
1521        match variant {
1522            "Partial.Ok" => Some("Ok"),
1523            "Partial.Err" => Some("Err"),
1524            "Partial.Both" => Some("Both"),
1525            _ => None,
1526        }
1527    }
1528
1529    pub fn get_type(&self) -> Type {
1530        match self {
1531            Self::Literal { ty, .. }
1532            | Self::Function { ty, .. }
1533            | Self::Lambda { ty, .. }
1534            | Self::Block { ty, .. }
1535            | Self::Let { ty, .. }
1536            | Self::Identifier { ty, .. }
1537            | Self::Call { ty, .. }
1538            | Self::If { ty, .. }
1539            | Self::IfLet { ty, .. }
1540            | Self::Match { ty, .. }
1541            | Self::Tuple { ty, .. }
1542            | Self::StructCall { ty, .. }
1543            | Self::DotAccess { ty, .. }
1544            | Self::Return { ty, .. }
1545            | Self::Propagate { ty, .. }
1546            | Self::TryBlock { ty, .. }
1547            | Self::RecoverBlock { ty, .. }
1548            | Self::Binary { ty, .. }
1549            | Self::Paren { ty, .. }
1550            | Self::Unary { ty, .. }
1551            | Self::Const { ty, .. }
1552            | Self::VariableDeclaration { ty, .. }
1553            | Self::Defer { ty, .. }
1554            | Self::Assert { ty, .. }
1555            | Self::Reference { ty, .. }
1556            | Self::IndexedAccess { ty, .. }
1557            | Self::Task { ty, .. }
1558            | Self::Select { ty, .. }
1559            | Self::Unit { ty, .. }
1560            | Self::Loop { ty, .. }
1561            | Self::Range { ty, .. }
1562            | Self::Cast { ty, .. } => ty.clone(),
1563            Self::Enum { .. }
1564            | Self::Struct { .. }
1565            | Self::Assignment { .. }
1566            | Self::ImplBlock { .. }
1567            | Self::TypeAlias { .. }
1568            | Self::ModuleImport { .. }
1569            | Self::Interface { .. }
1570            | Self::RawGo { .. }
1571            | Self::While { .. }
1572            | Self::WhileLet { .. }
1573            | Self::For { .. } => Type::ignored(),
1574            Self::Break { .. } | Self::Continue { .. } => Type::Never,
1575        }
1576    }
1577
1578    pub fn get_span(&self) -> Span {
1579        match self {
1580            Self::Literal { span, .. }
1581            | Self::Function { span, .. }
1582            | Self::Lambda { span, .. }
1583            | Self::Block { span, .. }
1584            | Self::Let { span, .. }
1585            | Self::Identifier { span, .. }
1586            | Self::Call { span, .. }
1587            | Self::If { span, .. }
1588            | Self::IfLet { span, .. }
1589            | Self::Match { span, .. }
1590            | Self::Tuple { span, .. }
1591            | Self::Enum { span, .. }
1592            | Self::Struct { span, .. }
1593            | Self::StructCall { span, .. }
1594            | Self::DotAccess { span, .. }
1595            | Self::Assignment { span, .. }
1596            | Self::Return { span, .. }
1597            | Self::Propagate { span, .. }
1598            | Self::TryBlock { span, .. }
1599            | Self::RecoverBlock { span, .. }
1600            | Self::ImplBlock { span, .. }
1601            | Self::Binary { span, .. }
1602            | Self::Paren { span, .. }
1603            | Self::Unary { span, .. }
1604            | Self::Const { span, .. }
1605            | Self::VariableDeclaration { span, .. }
1606            | Self::Defer { span, .. }
1607            | Self::Assert { span, .. }
1608            | Self::Reference { span, .. }
1609            | Self::IndexedAccess { span, .. }
1610            | Self::Task { span, .. }
1611            | Self::Select { span, .. }
1612            | Self::Loop { span, .. }
1613            | Self::TypeAlias { span, .. }
1614            | Self::ModuleImport { span, .. }
1615            | Self::Interface { span, .. }
1616            | Self::Unit { span, .. }
1617            | Self::While { span, .. }
1618            | Self::WhileLet { span, .. }
1619            | Self::For { span, .. }
1620            | Self::Break { span, .. }
1621            | Self::Continue { span, .. }
1622            | Self::Range { span, .. }
1623            | Self::Cast { span, .. } => *span,
1624            Self::RawGo { .. } => Span::dummy(),
1625        }
1626    }
1627
1628    pub fn contains_break(&self) -> bool {
1629        match self {
1630            Expression::Break { .. } => true,
1631
1632            Expression::Loop { .. }
1633            | Expression::While { .. }
1634            | Expression::WhileLet { .. }
1635            | Expression::For { .. } => false,
1636
1637            Expression::Block { items, .. } => items.iter().any(Self::contains_break),
1638
1639            Expression::TryBlock { items, .. } => items.iter().any(Self::contains_break),
1640            Expression::RecoverBlock { items, .. } => items.iter().any(Self::contains_break),
1641
1642            Expression::If {
1643                condition,
1644                consequence,
1645                alternative,
1646                ..
1647            } => {
1648                condition.contains_break()
1649                    || consequence.contains_break()
1650                    || alternative.as_deref().is_some_and(Self::contains_break)
1651            }
1652
1653            Expression::IfLet {
1654                scrutinee,
1655                consequence,
1656                alternative,
1657                ..
1658            } => {
1659                scrutinee.contains_break()
1660                    || consequence.contains_break()
1661                    || alternative.expression().is_some_and(Self::contains_break)
1662            }
1663
1664            Expression::Match { subject, arms, .. } => {
1665                subject.contains_break() || arms.iter().any(|arm| arm.expression.contains_break())
1666            }
1667
1668            Expression::Paren { expression, .. } => expression.contains_break(),
1669
1670            Expression::Binary { left, right, .. } => {
1671                left.contains_break() || right.contains_break()
1672            }
1673
1674            Expression::Unary { expression, .. } => expression.contains_break(),
1675
1676            Expression::Call {
1677                expression,
1678                args,
1679                spread,
1680                ..
1681            } => {
1682                expression.contains_break()
1683                    || args.iter().any(Self::contains_break)
1684                    || spread.as_deref().is_some_and(Self::contains_break)
1685            }
1686
1687            Expression::Function { .. } | Expression::Lambda { .. } => false,
1688
1689            Expression::Select { arms, .. } => arms.iter().any(|arm| match arm {
1690                SelectArm::Receive { body, .. } => body.contains_break(),
1691                SelectArm::Send { body, .. } => body.contains_break(),
1692                SelectArm::MatchReceive { arms, .. } => {
1693                    arms.iter().any(|a| a.expression.contains_break())
1694                }
1695                SelectArm::WildCard { body } => body.contains_break(),
1696            }),
1697
1698            Expression::Cast { expression, .. } => expression.contains_break(),
1699
1700            Expression::Let { value, mode, .. } => {
1701                value.contains_break() || mode.else_block().is_some_and(Self::contains_break)
1702            }
1703
1704            Expression::Assignment { value, .. } => value.contains_break(),
1705
1706            _ => false,
1707        }
1708    }
1709
1710    pub fn diverges(&self) -> Option<DeadCodeCause> {
1711        match self {
1712            Expression::Return { .. } => Some(DeadCodeCause::Return),
1713            Expression::Break { .. } => Some(DeadCodeCause::Break),
1714            Expression::Continue { .. } => Some(DeadCodeCause::Continue),
1715
1716            Expression::If {
1717                consequence,
1718                alternative,
1719                ..
1720            } => {
1721                if consequence.diverges().is_some()
1722                    && alternative
1723                        .as_deref()
1724                        .is_some_and(|alternative| alternative.diverges().is_some())
1725                {
1726                    Some(DeadCodeCause::DivergingIf)
1727                } else {
1728                    None
1729                }
1730            }
1731
1732            Expression::IfLet {
1733                consequence,
1734                alternative,
1735                ..
1736            } => {
1737                if consequence.diverges().is_some()
1738                    && alternative
1739                        .expression()
1740                        .is_some_and(|alternative| alternative.diverges().is_some())
1741                {
1742                    Some(DeadCodeCause::DivergingIf)
1743                } else {
1744                    None
1745                }
1746            }
1747
1748            Expression::Match { arms, .. } => {
1749                if !arms.is_empty() && arms.iter().all(|arm| arm.expression.diverges().is_some()) {
1750                    Some(DeadCodeCause::DivergingMatch)
1751                } else {
1752                    None
1753                }
1754            }
1755
1756            Expression::Block { items, .. } => {
1757                for item in items {
1758                    if let Some(cause) = item.diverges() {
1759                        return Some(cause);
1760                    }
1761                }
1762                None
1763            }
1764
1765            Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
1766                for item in items {
1767                    if let Some(cause) = item.diverges() {
1768                        return Some(cause);
1769                    }
1770                }
1771                None
1772            }
1773
1774            Expression::Paren { expression, .. } | Expression::Cast { expression, .. } => {
1775                expression.diverges()
1776            }
1777
1778            Expression::Loop { body, .. } => {
1779                if !body.contains_break() {
1780                    Some(DeadCodeCause::InfiniteLoop)
1781                } else {
1782                    None
1783                }
1784            }
1785
1786            Expression::Call { ty, .. } if ty.is_never() => Some(DeadCodeCause::DivergingCall),
1787
1788            _ => None,
1789        }
1790    }
1791
1792    /// Returns references to all direct child expressions.
1793    ///
1794    /// This is the single source of truth for expression tree recursion. Use this
1795    /// instead of writing per-variant match arms when you need to walk an expression tree.
1796    pub fn children(&self) -> Vec<&Expression> {
1797        match self {
1798            Expression::Literal { literal, .. } => match literal {
1799                Literal::Slice(elements) => elements.iter().collect(),
1800                Literal::FormatString(parts) => parts
1801                    .iter()
1802                    .filter_map(|p| match p {
1803                        FormatStringPart::Expression(e) => Some(e.as_ref()),
1804                        FormatStringPart::Text(_) => None,
1805                    })
1806                    .collect(),
1807                _ => Vec::new(),
1808            },
1809            Expression::Function { body, .. } => body.definition().into_iter().collect(),
1810            Expression::Lambda { body, .. } => children![body],
1811            Expression::Block { items, .. } => items.iter().collect(),
1812            Expression::Let { value, mode, .. } => {
1813                let mut c = children![value.as_ref()];
1814                if let Some(eb) = mode.else_block() {
1815                    c.push(eb);
1816                }
1817                c
1818            }
1819            Expression::Identifier { .. } => Vec::new(),
1820            Expression::Call {
1821                expression,
1822                args,
1823                spread,
1824                ..
1825            } => {
1826                let mut c = children![expression.as_ref()];
1827                c.extend(args);
1828                if let Some(s) = spread.as_ref() {
1829                    c.push(s);
1830                }
1831                c
1832            }
1833            Expression::If {
1834                condition,
1835                consequence,
1836                alternative,
1837                ..
1838            } => {
1839                let mut c = children![condition, consequence];
1840                if let Some(alternative) = alternative {
1841                    c.push(alternative);
1842                }
1843                c
1844            }
1845            Expression::IfLet {
1846                scrutinee,
1847                consequence,
1848                alternative,
1849                ..
1850            } => {
1851                let mut c = children![scrutinee, consequence];
1852                if let Some(alternative) = alternative.expression() {
1853                    c.push(alternative);
1854                }
1855                c
1856            }
1857            Expression::Match { subject, arms, .. } => {
1858                let mut c = children![subject.as_ref()];
1859                for arm in arms {
1860                    if let Some(guard) = &arm.guard {
1861                        c.push(guard);
1862                    }
1863                    c.push(&arm.expression);
1864                }
1865                c
1866            }
1867            Expression::Tuple { elements, .. } => elements.iter().collect(),
1868            Expression::StructCall {
1869                field_assignments,
1870                spread,
1871                ..
1872            } => {
1873                let mut c: Vec<&Expression> =
1874                    field_assignments.iter().map(|f| f.value.as_ref()).collect();
1875                if let Some(s) = spread.as_expression() {
1876                    c.push(s);
1877                }
1878                c
1879            }
1880            Expression::DotAccess { expression, .. } => children![expression],
1881            Expression::Assignment { target, value, .. } => children![target, value],
1882            Expression::Return { expression, .. } => children![expression],
1883            Expression::Propagate { expression, .. } => children![expression],
1884            Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
1885                items.iter().collect()
1886            }
1887            Expression::ImplBlock { methods, .. } => methods.iter().collect(),
1888            Expression::Binary { left, right, .. } => children![left, right],
1889            Expression::Unary { expression, .. } => children![expression],
1890            Expression::Paren { expression, .. } => children![expression],
1891            Expression::Const { expression, .. } => expression.value().into_iter().collect(),
1892            Expression::Loop { body, .. } => children![body],
1893            Expression::While {
1894                condition, body, ..
1895            } => children![condition, body],
1896            Expression::WhileLet {
1897                scrutinee, body, ..
1898            } => children![scrutinee, body],
1899            Expression::For { iterable, body, .. } => children![iterable, body],
1900            Expression::Break { value, .. } => value
1901                .as_ref()
1902                .map(|v| children![v.as_ref()])
1903                .unwrap_or_default(),
1904            Expression::Reference { expression, .. } => children![expression],
1905            Expression::IndexedAccess {
1906                expression, index, ..
1907            } => children![expression, index],
1908            Expression::Task { expression, .. } => children![expression],
1909            Expression::Defer { expression, .. } => children![expression],
1910            Expression::Assert { expression, .. } => children![expression],
1911            Expression::Select { arms, .. } => {
1912                let mut c = Vec::new();
1913                for arm in arms {
1914                    match arm {
1915                        SelectArm::Receive {
1916                            receive_expression,
1917                            body,
1918                            ..
1919                        } => {
1920                            c.push(receive_expression.as_ref());
1921                            c.push(body.as_ref());
1922                        }
1923                        SelectArm::Send {
1924                            send_expression,
1925                            body,
1926                        } => {
1927                            c.push(send_expression.as_ref());
1928                            c.push(body.as_ref());
1929                        }
1930                        SelectArm::MatchReceive {
1931                            receive_expression,
1932                            arms: match_arms,
1933                        } => {
1934                            c.push(receive_expression.as_ref());
1935                            for ma in match_arms {
1936                                if let Some(guard) = &ma.guard {
1937                                    c.push(guard);
1938                                }
1939                                c.push(&ma.expression);
1940                            }
1941                        }
1942                        SelectArm::WildCard { body } => {
1943                            c.push(body.as_ref());
1944                        }
1945                    }
1946                }
1947                c
1948            }
1949            Expression::Range { start, end, .. } => {
1950                let mut c = Vec::new();
1951                if let Some(s) = start {
1952                    c.push(s.as_ref());
1953                }
1954                if let Some(e) = end {
1955                    c.push(e.as_ref());
1956                }
1957                c
1958            }
1959            Expression::Cast { expression, .. } => children![expression],
1960            Expression::Interface {
1961                method_signatures, ..
1962            } => method_signatures.iter().collect(),
1963            Expression::Unit { .. }
1964            | Expression::Continue { .. }
1965            | Expression::Enum { .. }
1966            | Expression::Struct { .. }
1967            | Expression::TypeAlias { .. }
1968            | Expression::VariableDeclaration { .. }
1969            | Expression::ModuleImport { .. }
1970            | Expression::RawGo { .. } => Vec::new(),
1971        }
1972    }
1973
1974    pub fn unwrap_parens(&self) -> &Expression {
1975        match self {
1976            Expression::Paren { expression, .. } => expression.unwrap_parens(),
1977            other => other,
1978        }
1979    }
1980
1981    pub fn binding_id(&self) -> Option<BindingId> {
1982        match self.unwrap_parens() {
1983            Expression::Identifier { resolution, .. } => resolution.binding_id(),
1984            _ => None,
1985        }
1986    }
1987
1988    pub fn as_integer(&self) -> Option<u64> {
1989        match self.unwrap_parens() {
1990            Expression::Literal {
1991                literal: Literal::Integer { value, .. },
1992                ..
1993            } => Some(*value),
1994            _ => None,
1995        }
1996    }
1997
1998    /// Inner expression of an explicit `x.*` deref, or `None` for anything else.
1999    #[inline]
2000    pub fn deref_inner(&self) -> Option<&Expression> {
2001        match self {
2002            Expression::Unary {
2003                operator: UnaryOperator::Deref,
2004                expression,
2005                ..
2006            } => Some(expression),
2007            _ => None,
2008        }
2009    }
2010
2011    pub fn as_dotted_path(&self) -> Option<String> {
2012        match self {
2013            Expression::Identifier { value, .. } => Some(value.to_string()),
2014            Expression::DotAccess {
2015                expression, member, ..
2016            } => Some(format!("{}.{}", expression.as_dotted_path()?, member)),
2017            _ => None,
2018        }
2019    }
2020
2021    pub fn root_identifier(&self) -> Option<&str> {
2022        match self {
2023            Expression::Identifier { value, .. } => Some(value),
2024            Expression::DotAccess { expression, .. } => expression.root_identifier(),
2025            _ => None,
2026        }
2027    }
2028
2029    pub fn is_empty_collection(&self) -> bool {
2030        matches!(
2031            self,
2032            Expression::Literal {
2033                literal: Literal::Slice(elements),
2034                ..
2035            } if elements.is_empty()
2036        )
2037    }
2038
2039    pub fn is_all_literals(&self) -> bool {
2040        match self.unwrap_parens() {
2041            Expression::Literal { literal, .. } => match literal {
2042                Literal::Slice(elements) => elements.iter().all(|e| e.is_all_literals()),
2043                Literal::FormatString(parts) => parts.iter().all(|p| match p {
2044                    FormatStringPart::Text(_) => true,
2045                    FormatStringPart::Expression(e) => e.is_all_literals(),
2046                }),
2047                _ => true,
2048            },
2049            Expression::Tuple { elements, .. } => elements.iter().all(|e| e.is_all_literals()),
2050            Expression::Unit { .. } => true,
2051            _ => false,
2052        }
2053    }
2054
2055    pub fn get_var_name(&self) -> Option<String> {
2056        match self {
2057            Expression::Identifier { value, .. } => Some(value.to_string()),
2058            Expression::DotAccess { expression, .. } => expression.get_var_name(),
2059            Expression::Assignment { target, .. } => target.get_var_name(),
2060            Expression::IndexedAccess { expression, .. } => expression.get_var_name(),
2061            Expression::Paren { expression, .. } => expression.get_var_name(),
2062            Expression::Reference { expression, .. } => expression.get_var_name(),
2063            Expression::Unary {
2064                operator,
2065                expression,
2066                ..
2067            } => {
2068                if operator == &UnaryOperator::Deref {
2069                    expression.get_var_name()
2070                } else {
2071                    None
2072                }
2073            }
2074            _ => None,
2075        }
2076    }
2077
2078    pub(crate) fn set_public(self) -> Self {
2079        match self {
2080            Expression::Enum {
2081                doc,
2082                attributes,
2083                name,
2084                name_span,
2085                generics,
2086                variants,
2087                span,
2088                ..
2089            } => Expression::Enum {
2090                doc,
2091                attributes,
2092                name,
2093                name_span,
2094                generics,
2095                variants,
2096                visibility: Visibility::Public,
2097                span,
2098            },
2099            Expression::Struct {
2100                doc,
2101                attributes,
2102                name,
2103                name_span,
2104                generics,
2105                fields,
2106                span,
2107                ..
2108            } => {
2109                let fields = match fields {
2110                    StructFields::Tuple(fields) => StructFields::Tuple(
2111                        fields
2112                            .into_iter()
2113                            .map(|f| StructFieldDefinition {
2114                                visibility: Visibility::Public,
2115                                ..f
2116                            })
2117                            .collect(),
2118                    ),
2119                    StructFields::Record(fields) => StructFields::Record(fields),
2120                };
2121                Expression::Struct {
2122                    doc,
2123                    attributes,
2124                    name,
2125                    name_span,
2126                    generics,
2127                    fields,
2128                    visibility: Visibility::Public,
2129                    span,
2130                }
2131            }
2132            Expression::Function {
2133                doc,
2134                attributes,
2135                name,
2136                name_span,
2137                generics,
2138                params,
2139                return_annotation,
2140                return_type,
2141                body,
2142                ty,
2143                span,
2144                ..
2145            } => Expression::Function {
2146                doc,
2147                attributes,
2148                name,
2149                name_span,
2150                generics,
2151                params,
2152                return_annotation,
2153                return_type,
2154                visibility: Visibility::Public,
2155                body,
2156                ty,
2157                span,
2158            },
2159            Expression::Const {
2160                doc,
2161                identifier,
2162                identifier_span,
2163                annotation,
2164                expression,
2165                ty,
2166                span,
2167                ..
2168            } => Expression::Const {
2169                doc,
2170                identifier,
2171                identifier_span,
2172                annotation,
2173                expression,
2174                visibility: Visibility::Public,
2175                ty,
2176                span,
2177            },
2178            Expression::VariableDeclaration {
2179                doc,
2180                name,
2181                name_span,
2182                annotation,
2183                ty,
2184                span,
2185                ..
2186            } => Expression::VariableDeclaration {
2187                doc,
2188                name,
2189                name_span,
2190                annotation,
2191                visibility: Visibility::Public,
2192                ty,
2193                span,
2194            },
2195            Expression::TypeAlias {
2196                doc,
2197                attributes,
2198                name,
2199                name_span,
2200                generics,
2201                annotation,
2202                ty,
2203                span,
2204                ..
2205            } => Expression::TypeAlias {
2206                doc,
2207                attributes,
2208                name,
2209                name_span,
2210                generics,
2211                annotation,
2212                ty,
2213                visibility: Visibility::Public,
2214                span,
2215            },
2216            Expression::Interface {
2217                doc,
2218                name,
2219                name_span,
2220                generics,
2221                parents,
2222                method_signatures,
2223                span,
2224                ..
2225            } => Expression::Interface {
2226                doc,
2227                name,
2228                name_span,
2229                generics,
2230                parents,
2231                method_signatures,
2232                visibility: Visibility::Public,
2233                span,
2234            },
2235            expression => expression,
2236        }
2237    }
2238
2239    pub fn has_else(&self) -> bool {
2240        match self {
2241            Self::Block { items, .. } if items.is_empty() => false,
2242            Self::Unit { .. } => false,
2243            Self::If { alternative, .. } => alternative.as_deref().is_some_and(Self::has_else),
2244            Self::IfLet { alternative, .. } => alternative.expression().is_some_and(Self::has_else),
2245            _ => true,
2246        }
2247    }
2248}
2249
2250#[derive(Debug, Clone, PartialEq)]
2251pub enum Literal {
2252    Integer {
2253        value: u64,
2254        text: Option<String>,
2255    },
2256    Float {
2257        value: f64,
2258        text: Option<String>,
2259    },
2260    /// Imaginary coefficient, e.g. `4i` stores `4.0`
2261    Imaginary(f64),
2262    Boolean(bool),
2263    String {
2264        value: String,
2265        raw: bool,
2266    },
2267    FormatString(Vec<FormatStringPart>),
2268    Char(String),
2269    Slice(Vec<Expression>),
2270}
2271
2272#[derive(Debug, Clone, PartialEq)]
2273pub enum FormatStringPart {
2274    Text(String),
2275    Expression(Box<Expression>),
2276}
2277
2278#[derive(Debug, Clone, PartialEq)]
2279pub enum UnaryOperator {
2280    Negative,
2281    Not,
2282    BitwiseNot,
2283    Deref,
2284}
2285
2286#[derive(Debug, Clone, Copy, PartialEq)]
2287pub enum BinaryOperator {
2288    Addition,
2289    Subtraction,
2290    Multiplication,
2291    Division,
2292    BitwiseAnd,
2293    BitwiseOr,
2294    BitwiseXor,
2295    BitwiseAndNot,
2296    ShiftLeft,
2297    ShiftRight,
2298    LessThan,
2299    LessThanOrEqual,
2300    GreaterThan,
2301    GreaterThanOrEqual,
2302    Remainder,
2303    Equal,
2304    NotEqual,
2305    And,
2306    Or,
2307    Pipeline,
2308}
2309
2310impl BinaryOperator {
2311    /// The compound-assignment form (`+=`, `<<=`, ...) for operators that have
2312    /// one. Comparison, logical, and pipeline operators return `None`. Mirrors
2313    /// the compound-assignment tokens accepted by `parse_assignment`.
2314    pub fn compound_assignment_symbol(&self) -> Option<&'static str> {
2315        match self {
2316            BinaryOperator::Addition => Some("+="),
2317            BinaryOperator::Subtraction => Some("-="),
2318            BinaryOperator::Multiplication => Some("*="),
2319            BinaryOperator::Division => Some("/="),
2320            BinaryOperator::Remainder => Some("%="),
2321            BinaryOperator::BitwiseAnd => Some("&="),
2322            BinaryOperator::BitwiseOr => Some("|="),
2323            BinaryOperator::BitwiseXor => Some("^="),
2324            BinaryOperator::BitwiseAndNot => Some("&^="),
2325            BinaryOperator::ShiftLeft => Some("<<="),
2326            BinaryOperator::ShiftRight => Some(">>="),
2327            _ => None,
2328        }
2329    }
2330}
2331
2332impl std::fmt::Display for BinaryOperator {
2333    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2334        let symbol = match self {
2335            BinaryOperator::Addition => "+",
2336            BinaryOperator::Subtraction => "-",
2337            BinaryOperator::Multiplication => "*",
2338            BinaryOperator::Division => "/",
2339            BinaryOperator::Remainder => "%",
2340            BinaryOperator::BitwiseAnd => "&",
2341            BinaryOperator::BitwiseOr => "|",
2342            BinaryOperator::BitwiseXor => "^",
2343            BinaryOperator::BitwiseAndNot => "&^",
2344            BinaryOperator::ShiftLeft => "<<",
2345            BinaryOperator::ShiftRight => ">>",
2346            BinaryOperator::Equal => "==",
2347            BinaryOperator::NotEqual => "!=",
2348            BinaryOperator::LessThan => "<",
2349            BinaryOperator::LessThanOrEqual => "<=",
2350            BinaryOperator::GreaterThan => ">",
2351            BinaryOperator::GreaterThanOrEqual => ">=",
2352            BinaryOperator::And => "&&",
2353            BinaryOperator::Or => "||",
2354            BinaryOperator::Pipeline => "|>",
2355        };
2356        write!(f, "{}", symbol)
2357    }
2358}
2359
2360#[derive(Debug, Clone, PartialEq)]
2361pub struct ParentInterface {
2362    pub annotation: Annotation,
2363    pub ty: Type,
2364    pub span: Span,
2365}
2366
2367#[derive(Debug, Clone, Copy, PartialEq)]
2368#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2369pub enum Visibility {
2370    Public,
2371    Private,
2372}
2373
2374impl Visibility {
2375    pub fn is_public(&self) -> bool {
2376        matches!(self, Visibility::Public)
2377    }
2378}
2379
2380#[derive(Debug, Clone, PartialEq)]
2381pub enum ImportAlias {
2382    Named(EcoString, Span),
2383    Blank(Span),
2384}