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