Skip to main content

lisette_syntax/
ast.rs

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