Skip to main content

lisette_syntax/
ast.rs

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