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