1use ecow::EcoString;
2
3use crate::program::{CalleeName, DotAccessResolution, MethodName};
4use crate::types;
5use crate::types::{Symbol, Type};
6use fmt::Formatter;
7use std::borrow::Cow;
8use std::fmt;
9use std::fmt::Display;
10use std::iter;
11use std::mem;
12use std::ops::Deref;
13use std::ops::DerefMut;
14use std::ops::Index;
15use std::ptr;
16use std::slice::Iter;
17use std::slice::IterMut;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum DeadCodeCause {
21 Return,
22 Break,
23 Continue,
24 DivergingIf,
25 DivergingMatch,
26 InfiniteLoop,
27 DivergingCall,
28}
29
30#[derive(Clone, PartialEq)]
31pub struct Binding {
32 pub pattern: Pattern,
33 pub annotation: Option<Annotation>,
34 pub ty: Type,
35 pub mut_span: Option<Span>,
36}
37
38impl Binding {
39 pub fn is_mutable(&self) -> bool {
40 self.mut_span.is_some()
41 }
42}
43
44impl fmt::Debug for Binding {
45 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
46 let mut s = f.debug_struct("Binding");
47 s.field("pattern", &self.pattern);
48 s.field("annotation", &self.annotation);
49 s.field("ty", &self.ty);
50 if self.mut_span.is_some() {
51 s.field("mut_span", &self.mut_span);
52 }
53 s.finish()
54 }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
58#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
59#[cfg_attr(feature = "serde", serde(transparent))]
60pub struct BindingId(u32);
61
62impl BindingId {
63 pub const fn new(index: u32) -> Self {
64 Self(index)
65 }
66
67 pub const fn index(self) -> u32 {
68 self.0
69 }
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum IdentifierResolution {
74 Unresolved,
75 Binding(BindingId),
76 Definition {
77 name: Symbol,
78 instantiation: types::SubstitutionMap,
79 },
80 Method {
81 method: MethodName,
82 instantiation: types::SubstitutionMap,
83 },
84}
85
86impl IdentifierResolution {
87 pub fn binding_id(&self) -> Option<BindingId> {
88 match self {
89 Self::Binding(id) => Some(*id),
90 Self::Unresolved | Self::Definition { .. } | Self::Method { .. } => None,
91 }
92 }
93
94 pub fn definition(&self) -> Option<&str> {
95 match self {
96 Self::Definition { name, .. } => Some(name),
97 Self::Unresolved | Self::Binding(_) | Self::Method { .. } => None,
98 }
99 }
100
101 pub fn method(&self) -> Option<&MethodName> {
102 match self {
103 Self::Method { method, .. } => Some(method),
104 Self::Unresolved | Self::Binding(_) | Self::Definition { .. } => None,
105 }
106 }
107
108 pub fn callee_name(&self) -> Option<CalleeName> {
109 match self {
110 Self::Definition { name, .. } => Some(CalleeName::Definition(name.clone())),
111 Self::Method { method, .. } => Some(CalleeName::Method(method.clone())),
112 Self::Unresolved | Self::Binding(_) => None,
113 }
114 }
115
116 pub fn instantiation(&self) -> Option<&types::SubstitutionMap> {
117 match self {
118 Self::Definition { instantiation, .. } | Self::Method { instantiation, .. } => {
119 Some(instantiation)
120 }
121 Self::Unresolved | Self::Binding(_) => None,
122 }
123 }
124}
125
126#[derive(Debug, Clone, PartialEq)]
127pub enum LetMode {
128 Plain,
129 Assert,
130 Else {
131 block: Box<Expression>,
132 else_span: Span,
133 },
134 InvalidAssertElse {
136 block: Box<Expression>,
137 else_span: Span,
138 },
139}
140
141impl LetMode {
142 pub fn is_assert(&self) -> bool {
143 matches!(self, Self::Assert | Self::InvalidAssertElse { .. })
144 }
145
146 pub fn else_block(&self) -> Option<&Expression> {
147 match self {
148 Self::Else { block, .. } | Self::InvalidAssertElse { block, .. } => Some(block),
149 Self::Plain | Self::Assert => None,
150 }
151 }
152
153 pub fn else_block_mut(&mut self) -> Option<&mut Expression> {
154 match self {
155 Self::Else { block, .. } | Self::InvalidAssertElse { block, .. } => Some(block),
156 Self::Plain | Self::Assert => None,
157 }
158 }
159
160 pub fn map_else(self, map: impl FnOnce(Expression, Span) -> Expression) -> Self {
161 match self {
162 Self::Else { block, else_span } => Self::Else {
163 block: Box::new(map(*block, else_span)),
164 else_span,
165 },
166 Self::InvalidAssertElse { block, else_span } => Self::InvalidAssertElse {
167 block: Box::new(map(*block, else_span)),
168 else_span,
169 },
170 Self::Plain => Self::Plain,
171 Self::Assert => Self::Assert,
172 }
173 }
174}
175
176#[derive(Debug, Clone, PartialEq)]
177pub enum FunctionBody {
178 Declaration,
179 Definition(Box<Expression>),
180}
181
182impl FunctionBody {
183 pub fn definition(&self) -> Option<&Expression> {
184 match self {
185 Self::Declaration => None,
186 Self::Definition(body) => Some(body),
187 }
188 }
189
190 pub fn definition_mut(&mut self) -> Option<&mut Expression> {
191 match self {
192 Self::Declaration => None,
193 Self::Definition(body) => Some(body),
194 }
195 }
196
197 pub fn map_definition(self, map: impl FnOnce(Expression) -> Expression) -> Self {
198 match self {
199 Self::Declaration => Self::Declaration,
200 Self::Definition(body) => Self::Definition(Box::new(map(*body))),
201 }
202 }
203}
204
205#[derive(Debug, Clone, PartialEq)]
206pub enum ConstInitializer {
207 Declaration,
208 Value(Box<Expression>),
209}
210
211#[derive(Debug, Clone, PartialEq)]
212pub enum IfLetAlternative {
213 Absent,
214 Present {
215 expression: Box<Expression>,
216 else_span: Span,
217 },
218}
219
220impl IfLetAlternative {
221 pub fn expression(&self) -> Option<&Expression> {
222 match self {
223 Self::Absent => None,
224 Self::Present { expression, .. } => Some(expression),
225 }
226 }
227
228 pub fn expression_mut(&mut self) -> Option<&mut Expression> {
229 match self {
230 Self::Absent => None,
231 Self::Present { expression, .. } => Some(expression),
232 }
233 }
234
235 pub fn else_span(&self) -> Option<Span> {
236 match self {
237 Self::Absent => None,
238 Self::Present { else_span, .. } => Some(*else_span),
239 }
240 }
241}
242
243impl ConstInitializer {
244 pub fn value(&self) -> Option<&Expression> {
245 match self {
246 Self::Declaration => None,
247 Self::Value(value) => Some(value),
248 }
249 }
250
251 pub fn value_mut(&mut self) -> Option<&mut Expression> {
252 match self {
253 Self::Declaration => None,
254 Self::Value(value) => Some(value),
255 }
256 }
257
258 pub fn map_value(self, map: impl FnOnce(Expression) -> Expression) -> Self {
259 match self {
260 Self::Declaration => Self::Declaration,
261 Self::Value(value) => Self::Value(Box::new(map(*value))),
262 }
263 }
264}
265
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub enum BindingKind {
268 Const,
269 Let { mutable: bool },
270 Parameter,
271 MatchArm,
272 IfLet,
273 WhileLet,
274}
275
276impl BindingKind {
277 pub fn is_mutable(&self) -> bool {
278 matches!(self, BindingKind::Let { mutable: true })
279 }
280
281 pub fn is_param(&self) -> bool {
282 matches!(self, BindingKind::Parameter)
283 }
284
285 pub fn is_match_arm(&self) -> bool {
286 matches!(self, BindingKind::MatchArm)
287 }
288
289 pub fn is_pattern_position(&self) -> bool {
290 matches!(
291 self,
292 BindingKind::MatchArm | BindingKind::IfLet | BindingKind::WhileLet
293 )
294 }
295}
296
297#[derive(Clone, PartialEq)]
298pub struct MatchArm {
299 pub pattern: Pattern,
300 pub guard: Option<Box<Expression>>,
301 pub expression: Box<Expression>,
302}
303
304impl MatchArm {
305 pub fn has_guard(&self) -> bool {
306 self.guard.is_some()
307 }
308
309 fn pattern_site(&self) -> PatternSite {
310 PatternSite::MatchArm {
311 has_guard: self.has_guard(),
312 }
313 }
314}
315
316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
317pub enum PatternSite {
318 Parameter,
319 Binding,
320 MatchArm { has_guard: bool },
321}
322
323impl fmt::Debug for MatchArm {
324 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
325 let mut s = f.debug_struct("MatchArm");
326 s.field("pattern", &self.pattern);
327 if self.guard.is_some() {
328 s.field("guard", &self.guard);
329 }
330 s.field("expression", &self.expression);
331 s.finish()
332 }
333}
334
335#[derive(Debug, Clone, PartialEq)]
336pub enum SelectArm {
337 Receive {
338 binding: Box<Pattern>,
339 receive_expression: Box<Expression>,
340 body: Box<Expression>,
341 },
342 Send {
343 send_expression: Box<Expression>,
344 body: Box<Expression>,
345 },
346 MatchReceive {
347 receive_expression: Box<Expression>,
348 arms: Vec<MatchArm>,
349 },
350 WildCard {
351 span: Span,
352 body: Box<Expression>,
353 },
354}
355
356#[derive(Debug, Clone, PartialEq)]
357pub enum RestPattern {
358 Absent,
359 Discard(Span),
360 Bind {
361 name: EcoString,
362 span: Span,
363 binding: Option<BindingId>,
365 },
366}
367
368impl RestPattern {
369 pub fn binding_id(&self) -> Option<BindingId> {
370 match self {
371 Self::Bind { binding, .. } => *binding,
372 Self::Absent | Self::Discard(_) => None,
373 }
374 }
375}
376
377#[derive(Debug, Clone, PartialEq)]
378pub enum ConstructorPatternResolution {
379 Unresolved,
380 Const {
381 qualified_name: Symbol,
382 },
383 ConstValue {
384 qualified_name: Symbol,
385 value: Literal,
386 },
387 EnumVariant {
388 enum_name: Symbol,
389 variant_name: EcoString,
390 },
391}
392
393#[derive(Debug, Clone, PartialEq)]
394pub enum RecordPatternResolution {
395 Unresolved,
396 Struct {
397 struct_name: EcoString,
398 },
399 EnumVariant {
400 enum_name: Symbol,
401 variant_name: EcoString,
402 },
403}
404
405#[derive(Debug, Clone, PartialEq)]
406pub enum SequencePatternResolution {
407 Unresolved,
408 Slice { element_type: Type },
409 Array { element_type: Type, length: u64 },
410}
411
412impl RestPattern {
413 pub fn is_present(&self) -> bool {
414 !matches!(self, RestPattern::Absent)
415 }
416}
417
418#[derive(Debug, Clone, PartialEq)]
419pub enum Pattern {
420 Literal {
421 literal: Literal,
422 ty: Type,
423 span: Span,
424 },
425 Unit {
426 ty: Type,
427 span: Span,
428 },
429 EnumVariant {
430 identifier: EcoString,
431 fields: Vec<Self>,
432 rest: bool,
433 resolution: ConstructorPatternResolution,
434 ty: Type,
435 span: Span,
436 },
437 Struct {
438 identifier: EcoString,
439 fields: Vec<StructFieldPattern>,
440 rest: bool,
441 resolution: RecordPatternResolution,
442 ty: Type,
443 span: Span,
444 },
445 Tuple {
446 elements: Vec<Self>,
447 span: Span,
448 },
449 WildCard {
450 span: Span,
451 },
452 Identifier {
453 identifier: EcoString,
454 span: Span,
455 binding: Option<BindingId>,
457 },
458 Slice {
459 prefix: Vec<Self>,
460 rest: RestPattern,
461 resolution: SequencePatternResolution,
462 span: Span,
463 },
464 Or {
465 patterns: Vec<Self>,
466 span: Span,
467 },
468 AsBinding {
469 pattern: Box<Self>,
470 name: EcoString,
471 name_span: Span,
472 span: Span,
473 binding: Option<BindingId>,
475 },
476}
477
478pub fn collect_pattern_bindings(pattern: &Pattern) -> Vec<(String, Span)> {
480 match pattern {
481 Pattern::Identifier {
482 identifier, span, ..
483 } => vec![(identifier.to_string(), *span)],
484 Pattern::Tuple { elements, .. } => {
485 elements.iter().flat_map(collect_pattern_bindings).collect()
486 }
487 Pattern::EnumVariant { fields, .. } => {
488 fields.iter().flat_map(collect_pattern_bindings).collect()
489 }
490 Pattern::Struct { fields, .. } => fields
491 .iter()
492 .flat_map(|f| collect_pattern_bindings(&f.value))
493 .collect(),
494 Pattern::Slice { prefix, rest, .. } => {
495 let mut bindings: Vec<_> = prefix.iter().flat_map(collect_pattern_bindings).collect();
496 if let RestPattern::Bind { name, span, .. } = rest {
497 bindings.push((name.to_string(), *span));
498 }
499 bindings
500 }
501 Pattern::Or { patterns, .. } => patterns
502 .first()
503 .map(collect_pattern_bindings)
504 .unwrap_or_default(),
505 Pattern::AsBinding {
506 pattern,
507 name,
508 name_span,
509 ..
510 } => {
511 let mut bindings = collect_pattern_bindings(pattern);
512 bindings.push((name.to_string(), *name_span));
513 bindings
514 }
515 Pattern::WildCard { .. } | Pattern::Literal { .. } | Pattern::Unit { .. } => vec![],
516 }
517}
518
519pub fn outermost_or_patterns(pattern: &Pattern) -> Vec<&Pattern> {
520 match pattern {
521 Pattern::Or { .. } => vec![pattern],
522 Pattern::Tuple {
523 elements: patterns, ..
524 }
525 | Pattern::EnumVariant {
526 fields: patterns, ..
527 }
528 | Pattern::Slice {
529 prefix: patterns, ..
530 } => patterns.iter().flat_map(outermost_or_patterns).collect(),
531 Pattern::Struct { fields, .. } => fields
532 .iter()
533 .flat_map(|field| outermost_or_patterns(&field.value))
534 .collect(),
535 Pattern::AsBinding { pattern, .. } => outermost_or_patterns(pattern),
536 Pattern::Identifier { .. }
537 | Pattern::WildCard { .. }
538 | Pattern::Literal { .. }
539 | Pattern::Unit { .. } => vec![],
540 }
541}
542
543#[derive(Debug, Clone)]
544pub struct OrExpansion<'a> {
545 pub pattern: Cow<'a, Pattern>,
546 pub choices: Vec<OrChoice>,
547}
548
549#[derive(Debug, Clone, Copy, PartialEq, Eq)]
550pub struct OrChoice {
551 pub or_span: Span,
552 pub alternative_span: Span,
553}
554
555pub fn expand_or_patterns<'a>(
557 pattern: &'a Pattern,
558 split: &impl Fn(&Pattern) -> bool,
559) -> Vec<OrExpansion<'a>> {
560 match pattern {
561 Pattern::Or { patterns, span } if split(pattern) => patterns
562 .iter()
563 .flat_map(|alternative| {
564 let choice = OrChoice {
565 or_span: *span,
566 alternative_span: alternative.get_span(),
567 };
568 expand_or_patterns(alternative, split)
569 .into_iter()
570 .map(move |mut expansion| {
571 expansion.choices.insert(0, choice);
572 expansion
573 })
574 })
575 .collect(),
576 Pattern::AsBinding {
577 pattern: inner,
578 name,
579 name_span,
580 span,
581 binding,
582 } => expand_children(pattern, iter::once(inner.as_ref()), split, |mut inner| {
583 Pattern::AsBinding {
584 pattern: Box::new(inner.remove(0)),
585 name: name.clone(),
586 name_span: *name_span,
587 span: *span,
588 binding: *binding,
589 }
590 }),
591 Pattern::Tuple { elements, span } => {
592 expand_children(pattern, elements.iter(), split, |elements| Pattern::Tuple {
593 elements,
594 span: *span,
595 })
596 }
597 Pattern::EnumVariant {
598 identifier,
599 fields,
600 rest,
601 resolution,
602 ty,
603 span,
604 } => expand_children(pattern, fields.iter(), split, |fields| {
605 Pattern::EnumVariant {
606 identifier: identifier.clone(),
607 fields,
608 rest: *rest,
609 resolution: resolution.clone(),
610 ty: ty.clone(),
611 span: *span,
612 }
613 }),
614 Pattern::Struct {
615 identifier,
616 fields,
617 rest,
618 resolution,
619 ty,
620 span,
621 } => expand_children(
622 pattern,
623 fields.iter().map(|field| &field.value),
624 split,
625 |values| Pattern::Struct {
626 identifier: identifier.clone(),
627 fields: fields
628 .iter()
629 .zip(values)
630 .map(|(field, value)| StructFieldPattern {
631 name: field.name.clone(),
632 name_span: field.name_span,
633 value,
634 })
635 .collect(),
636 rest: *rest,
637 resolution: resolution.clone(),
638 ty: ty.clone(),
639 span: *span,
640 },
641 ),
642 Pattern::Slice {
643 prefix,
644 rest,
645 resolution,
646 span,
647 } => expand_children(pattern, prefix.iter(), split, |prefix| Pattern::Slice {
648 prefix,
649 rest: rest.clone(),
650 resolution: resolution.clone(),
651 span: *span,
652 }),
653 Pattern::Or { .. }
654 | Pattern::Identifier { .. }
655 | Pattern::WildCard { .. }
656 | Pattern::Literal { .. }
657 | Pattern::Unit { .. } => unexpanded(pattern),
658 }
659}
660
661fn unexpanded(pattern: &Pattern) -> Vec<OrExpansion<'_>> {
662 vec![OrExpansion {
663 pattern: Cow::Borrowed(pattern),
664 choices: vec![],
665 }]
666}
667
668fn expand_children<'a>(
669 pattern: &'a Pattern,
670 children: impl Iterator<Item = &'a Pattern>,
671 split: &impl Fn(&Pattern) -> bool,
672 rebuild: impl Fn(Vec<Pattern>) -> Pattern,
673) -> Vec<OrExpansion<'a>> {
674 let child_expansions: Vec<Vec<OrExpansion<'a>>> = children
675 .map(|child| expand_or_patterns(child, split))
676 .collect();
677 if child_expansions
678 .iter()
679 .flatten()
680 .all(|expansion| expansion.choices.is_empty())
681 {
682 return unexpanded(pattern);
683 }
684
685 let mut combinations: Vec<(Vec<Pattern>, Vec<OrChoice>)> = vec![(vec![], vec![])];
686 for expansions in &child_expansions {
687 combinations = combinations
688 .into_iter()
689 .flat_map(|(children, choices)| {
690 expansions.iter().map(move |expansion| {
691 let mut children = children.clone();
692 children.push(expansion.pattern.as_ref().clone());
693 let mut choices = choices.clone();
694 choices.extend_from_slice(&expansion.choices);
695 (children, choices)
696 })
697 })
698 .collect();
699 }
700
701 combinations
702 .into_iter()
703 .map(|(children, choices)| OrExpansion {
704 pattern: Cow::Owned(rebuild(children)),
705 choices,
706 })
707 .collect()
708}
709
710impl Pattern {
711 pub fn get_span(&self) -> Span {
712 match self {
713 Pattern::Identifier { span, .. } => *span,
714 Pattern::Literal { span, .. } => *span,
715 Pattern::EnumVariant { span, .. } => *span,
716 Pattern::Struct { span, .. } => *span,
717 Pattern::WildCard { span } => *span,
718 Pattern::Unit { span, .. } => *span,
719 Pattern::Tuple { span, .. } => *span,
720 Pattern::Slice { span, .. } => *span,
721 Pattern::Or { span, .. } => *span,
722 Pattern::AsBinding { span, .. } => *span,
723 }
724 }
725
726 pub fn get_type(&self) -> Option<Type> {
727 match self {
728 Pattern::Identifier { .. } => None,
729 Pattern::Literal { ty, .. } => Some(ty.clone()),
730 Pattern::EnumVariant { ty, .. } => Some(ty.clone()),
731 Pattern::Struct { ty, .. } => Some(ty.clone()),
732 Pattern::WildCard { .. } => None,
733 Pattern::Unit { ty, .. } => Some(ty.clone()),
734 Pattern::Tuple { .. } => None,
735 Pattern::Slice { .. } => None,
736 Pattern::Or { .. } => None,
737 Pattern::AsBinding { pattern, .. } => pattern.get_type(),
738 }
739 }
740
741 pub fn is_identifier(&self) -> bool {
742 matches!(self, Pattern::Identifier { .. } | Pattern::AsBinding { .. })
743 }
744
745 pub fn binding_id(&self) -> Option<BindingId> {
746 match self {
747 Pattern::Identifier { binding, .. } | Pattern::AsBinding { binding, .. } => *binding,
748 _ => None,
749 }
750 }
751
752 pub fn get_identifier(&self) -> Option<EcoString> {
753 match self {
754 Pattern::Identifier { identifier, .. } => Some(identifier.clone()),
755 Pattern::AsBinding { name, .. } => Some(name.clone()),
756 _ => None,
757 }
758 }
759}
760
761#[derive(Debug, Clone, PartialEq)]
762pub struct StructFieldPattern {
763 pub name: EcoString,
764 pub name_span: Span,
765 pub value: Pattern,
766}
767
768impl StructFieldPattern {
769 pub fn is_shorthand(&self) -> bool {
771 matches!(&self.value, Pattern::Identifier { identifier, .. } if identifier == &self.name)
772 }
773}
774
775#[derive(Clone, Copy)]
776pub struct FunctionDefinitionView<'a> {
777 pub name: &'a EcoString,
778 pub name_span: Span,
779 pub generics: &'a [Generic],
780 pub params: &'a [Binding],
781 pub body: Option<&'a Expression>,
782 pub return_type: &'a Type,
783 pub annotation: &'a Annotation,
784}
785
786#[derive(Debug, Clone, PartialEq)]
787#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
788pub enum VariantFields {
789 Unit,
790 Tuple(Vec<EnumFieldDefinition>),
791 Struct(Vec<EnumFieldDefinition>),
792}
793
794impl VariantFields {
795 pub fn is_empty(&self) -> bool {
796 match self {
797 VariantFields::Unit => true,
798 VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.is_empty(),
799 }
800 }
801
802 pub fn len(&self) -> usize {
803 match self {
804 VariantFields::Unit => 0,
805 VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.len(),
806 }
807 }
808
809 pub fn as_slice(&self) -> &[EnumFieldDefinition] {
810 match self {
811 VariantFields::Unit => &[],
812 VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields,
813 }
814 }
815
816 pub fn iter(&self) -> Iter<'_, EnumFieldDefinition> {
817 self.as_slice().iter()
818 }
819
820 pub fn is_struct(&self) -> bool {
821 matches!(self, VariantFields::Struct(_))
822 }
823}
824
825impl<'a> IntoIterator for &'a VariantFields {
826 type Item = &'a EnumFieldDefinition;
827 type IntoIter = Iter<'a, EnumFieldDefinition>;
828
829 fn into_iter(self) -> Self::IntoIter {
830 self.iter()
831 }
832}
833
834#[derive(Debug, Clone, PartialEq)]
835#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
836pub struct EnumVariant {
837 pub doc: Option<String>,
838 pub attributes: Vec<Attribute>,
839 pub name: EcoString,
840 pub name_span: Span,
841 pub fields: VariantFields,
842}
843
844#[derive(Debug, Clone, PartialEq)]
845#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
846pub struct EnumFieldDefinition {
847 pub name: EcoString,
848 pub name_span: Span,
849 pub annotation: Annotation,
850 pub ty: Type,
851}
852
853#[derive(Debug, Clone, PartialEq)]
854#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
855pub struct Attribute {
856 pub name: String,
857 pub args: Vec<AttributeArg>,
858 pub span: Span,
859}
860
861#[derive(Debug, Clone, PartialEq)]
862#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
863pub enum AttributeArg {
864 Flag(String),
866 NegatedFlag(String),
868 String(String),
870 Raw(String),
872}
873
874#[derive(Debug, Clone, Copy, PartialEq)]
875#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
876pub enum StructKind {
877 Record,
878 Tuple,
879}
880
881#[derive(Debug, Clone, PartialEq)]
884#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
885pub enum StructFields {
886 Record(Vec<StructFieldDefinition>),
887 Tuple(Vec<StructFieldDefinition>),
888}
889
890impl StructFields {
891 pub fn kind(&self) -> StructKind {
892 match self {
893 Self::Record(_) => StructKind::Record,
894 Self::Tuple(_) => StructKind::Tuple,
895 }
896 }
897
898 pub fn as_slice(&self) -> &[StructFieldDefinition] {
899 match self {
900 Self::Record(fields) | Self::Tuple(fields) => fields,
901 }
902 }
903}
904
905pub fn tuple_field_name(index: usize) -> EcoString {
907 format!("_{index}").into()
908}
909
910impl Deref for StructFields {
911 type Target = [StructFieldDefinition];
912
913 fn deref(&self) -> &Self::Target {
914 self.as_slice()
915 }
916}
917
918impl DerefMut for StructFields {
919 fn deref_mut(&mut self) -> &mut Self::Target {
920 match self {
921 Self::Record(fields) | Self::Tuple(fields) => fields,
922 }
923 }
924}
925
926impl<'a> IntoIterator for &'a StructFields {
927 type Item = &'a StructFieldDefinition;
928 type IntoIter = Iter<'a, StructFieldDefinition>;
929
930 fn into_iter(self) -> Self::IntoIter {
931 self.as_slice().iter()
932 }
933}
934
935impl<'a> IntoIterator for &'a mut StructFields {
936 type Item = &'a mut StructFieldDefinition;
937 type IntoIter = IterMut<'a, StructFieldDefinition>;
938
939 fn into_iter(self) -> Self::IntoIter {
940 match self {
941 StructFields::Record(fields) | StructFields::Tuple(fields) => fields.iter_mut(),
942 }
943 }
944}
945
946#[derive(Debug, Clone, PartialEq)]
947#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
948pub struct StructFieldDefinition {
949 pub doc: Option<String>,
950 pub name: EcoString,
951 pub name_span: Span,
952 pub annotation: Annotation,
953 pub visibility: Visibility,
954 pub ty: Type,
955 pub kind: StructFieldKind,
956}
957
958#[derive(Debug, Clone, PartialEq)]
959#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
960pub enum StructFieldKind {
961 Named { attributes: Vec<Attribute> },
962 Embedded,
963}
964
965impl StructFieldDefinition {
966 pub fn attributes(&self) -> &[Attribute] {
967 match &self.kind {
968 StructFieldKind::Named { attributes } => attributes,
969 StructFieldKind::Embedded => &[],
970 }
971 }
972
973 pub fn is_embedded(&self) -> bool {
974 matches!(self.kind, StructFieldKind::Embedded)
975 }
976}
977
978#[derive(Debug, Clone, PartialEq)]
979pub struct StructFieldAssignment {
980 pub name: EcoString,
981 pub name_span: Span,
982 pub value: Box<Expression>,
983}
984
985#[derive(Debug, Clone, PartialEq)]
986pub enum StructSpread {
987 None,
988 From(Box<Expression>),
989 Autofill { span: Span },
990}
991
992impl StructSpread {
993 pub fn is_none(&self) -> bool {
994 matches!(self, Self::None)
995 }
996
997 pub(crate) fn is_some(&self) -> bool {
998 !self.is_none()
999 }
1000
1001 pub fn span(&self) -> Option<Span> {
1002 match self {
1003 Self::None => None,
1004 Self::From(e) => Some(e.get_span()),
1005 Self::Autofill { span } => Some(*span),
1006 }
1007 }
1008
1009 pub fn as_expression(&self) -> Option<&Expression> {
1010 match self {
1011 Self::From(e) => Some(e),
1012 Self::None | Self::Autofill { .. } => None,
1013 }
1014 }
1015
1016 pub fn as_expression_mut(&mut self) -> Option<&mut Expression> {
1017 match self {
1018 Self::From(e) => Some(e),
1019 Self::None | Self::Autofill { .. } => None,
1020 }
1021 }
1022}
1023
1024#[derive(Clone, PartialEq)]
1025pub struct CallTypeArguments(CallTypeArgumentState);
1026
1027#[derive(Clone, PartialEq)]
1028enum CallTypeArgumentState {
1029 None,
1030 Unresolved(Vec<Annotation>),
1031 Resolved(Vec<ResolvedCallTypeArgument>),
1032 CheckedWithoutTypes(Vec<Annotation>),
1033}
1034
1035#[derive(Debug, Clone, PartialEq)]
1036#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1037struct ResolvedCallTypeArgument {
1038 annotation: Annotation,
1039 ty: Type,
1040}
1041
1042#[derive(Debug, Clone, Copy, PartialEq)]
1043pub struct ResolvedCallTypeArguments<'a> {
1044 arguments: &'a [ResolvedCallTypeArgument],
1045}
1046
1047impl<'a> ResolvedCallTypeArguments<'a> {
1048 pub fn len(self) -> usize {
1049 self.arguments.len()
1050 }
1051
1052 pub fn is_empty(self) -> bool {
1053 self.arguments.is_empty()
1054 }
1055
1056 pub fn first(self) -> Option<&'a Type> {
1057 self.arguments.first().map(|argument| &argument.ty)
1058 }
1059
1060 pub fn get(self, index: usize) -> Option<&'a Type> {
1061 self.arguments.get(index).map(|argument| &argument.ty)
1062 }
1063
1064 pub fn iter(self) -> impl ExactSizeIterator<Item = &'a Type> + Clone {
1065 self.arguments.iter().map(|argument| &argument.ty)
1066 }
1067}
1068
1069impl Index<usize> for ResolvedCallTypeArguments<'_> {
1070 type Output = Type;
1071
1072 fn index(&self, index: usize) -> &Self::Output {
1073 &self.arguments[index].ty
1074 }
1075}
1076
1077impl fmt::Debug for CallTypeArguments {
1078 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1079 match &self.0 {
1080 CallTypeArgumentState::None => f.write_str("None"),
1081 CallTypeArgumentState::Unresolved(annotations) => {
1082 f.debug_tuple("Unresolved").field(annotations).finish()
1083 }
1084 CallTypeArgumentState::Resolved(arguments) => {
1085 let annotations = arguments
1086 .iter()
1087 .map(|argument| &argument.annotation)
1088 .collect::<Vec<_>>();
1089 let types = arguments
1090 .iter()
1091 .map(|argument| &argument.ty)
1092 .collect::<Vec<_>>();
1093 f.debug_struct("Resolved")
1094 .field("annotations", &annotations)
1095 .field("types", &types)
1096 .finish()
1097 }
1098 CallTypeArgumentState::CheckedWithoutTypes(annotations) => f
1099 .debug_struct("Resolved")
1100 .field("annotations", annotations)
1101 .field("types", &Vec::<Type>::new())
1102 .finish(),
1103 }
1104 }
1105}
1106
1107impl CallTypeArguments {
1108 pub const fn none() -> Self {
1109 Self(CallTypeArgumentState::None)
1110 }
1111
1112 pub fn unresolved(annotations: Vec<Annotation>) -> Self {
1113 if annotations.is_empty() {
1114 Self::none()
1115 } else {
1116 Self(CallTypeArgumentState::Unresolved(annotations))
1117 }
1118 }
1119
1120 pub fn resolved(arguments: impl IntoIterator<Item = (Annotation, Type)>) -> Self {
1121 let arguments = arguments
1122 .into_iter()
1123 .map(|(annotation, ty)| ResolvedCallTypeArgument { annotation, ty })
1124 .collect::<Vec<_>>();
1125 if arguments.is_empty() {
1126 Self::none()
1127 } else {
1128 Self(CallTypeArgumentState::Resolved(arguments))
1129 }
1130 }
1131
1132 pub fn checked_without_types(annotations: Vec<Annotation>) -> Self {
1133 if annotations.is_empty() {
1134 Self::none()
1135 } else {
1136 Self(CallTypeArgumentState::CheckedWithoutTypes(annotations))
1137 }
1138 }
1139
1140 pub fn annotations(
1141 &self,
1142 ) -> impl ExactSizeIterator<Item = &Annotation> + DoubleEndedIterator + Clone {
1143 let len = match &self.0 {
1144 CallTypeArgumentState::None => 0,
1145 CallTypeArgumentState::Unresolved(annotations)
1146 | CallTypeArgumentState::CheckedWithoutTypes(annotations) => annotations.len(),
1147 CallTypeArgumentState::Resolved(arguments) => arguments.len(),
1148 };
1149 (0..len).map(move |index| match &self.0 {
1150 CallTypeArgumentState::None => unreachable!(),
1151 CallTypeArgumentState::Unresolved(annotations)
1152 | CallTypeArgumentState::CheckedWithoutTypes(annotations) => &annotations[index],
1153 CallTypeArgumentState::Resolved(arguments) => &arguments[index].annotation,
1154 })
1155 }
1156
1157 pub fn resolved_types(&self) -> Option<ResolvedCallTypeArguments<'_>> {
1158 let arguments: &[ResolvedCallTypeArgument] = match &self.0 {
1159 CallTypeArgumentState::None | CallTypeArgumentState::CheckedWithoutTypes(_) => &[],
1160 CallTypeArgumentState::Unresolved(_) => return None,
1161 CallTypeArgumentState::Resolved(arguments) => arguments,
1162 };
1163 Some(ResolvedCallTypeArguments { arguments })
1164 }
1165
1166 pub fn into_annotations(self) -> Vec<Annotation> {
1167 match self.0 {
1168 CallTypeArgumentState::None => Vec::new(),
1169 CallTypeArgumentState::Unresolved(annotations)
1170 | CallTypeArgumentState::CheckedWithoutTypes(annotations) => annotations,
1171 CallTypeArgumentState::Resolved(arguments) => arguments
1172 .into_iter()
1173 .map(|argument| argument.annotation)
1174 .collect(),
1175 }
1176 }
1177
1178 pub fn is_empty(&self) -> bool {
1179 matches!(self.0, CallTypeArgumentState::None)
1180 }
1181}
1182
1183impl Default for CallTypeArguments {
1184 fn default() -> Self {
1185 Self::none()
1186 }
1187}
1188
1189#[derive(Clone, PartialEq)]
1190#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1191pub enum Annotation {
1192 Constructor {
1193 name: EcoString,
1194 params: Vec<Self>,
1195 writable: bool,
1196 mut_span: Option<Span>,
1197 span: Span,
1198 },
1199 Function {
1200 params: Vec<Self>,
1201 return_type: Box<Self>,
1202 span: Span,
1203 },
1204 Tuple {
1205 elements: Vec<Self>,
1206 span: Span,
1207 },
1208 Unknown,
1209 Opaque {
1210 span: Span,
1211 },
1212 Constant {
1215 value: u64,
1216 text: Option<String>,
1217 span: Span,
1218 },
1219}
1220
1221impl fmt::Debug for Annotation {
1222 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1223 match self {
1224 Self::Constructor {
1225 name,
1226 params,
1227 writable,
1228 mut_span: _,
1229 span,
1230 } => {
1231 let mut s = f.debug_struct("Constructor");
1232 s.field("name", name).field("params", params);
1233 if *writable {
1234 s.field("writable", writable);
1235 }
1236 s.field("span", span).finish()
1237 }
1238 Self::Function {
1239 params,
1240 return_type,
1241 span,
1242 } => f
1243 .debug_struct("Function")
1244 .field("params", params)
1245 .field("return_type", return_type)
1246 .field("span", span)
1247 .finish(),
1248 Self::Tuple { elements, span } => f
1249 .debug_struct("Tuple")
1250 .field("elements", elements)
1251 .field("span", span)
1252 .finish(),
1253 Self::Unknown => write!(f, "Unknown"),
1254 Self::Opaque { span } => f.debug_struct("Opaque").field("span", span).finish(),
1255 Self::Constant { value, text, span } => f
1256 .debug_struct("Constant")
1257 .field("value", value)
1258 .field("text", text)
1259 .field("span", span)
1260 .finish(),
1261 }
1262 }
1263}
1264
1265impl Annotation {
1266 pub(crate) fn unit() -> Self {
1267 Self::Constructor {
1268 name: "Unit".into(),
1269 params: vec![],
1270 writable: false,
1271 mut_span: None,
1272 span: Span::dummy(),
1273 }
1274 }
1275
1276 pub fn get_span(&self) -> Span {
1277 match self {
1278 Self::Constructor { span, .. } => *span,
1279 Self::Function { span, .. } => *span,
1280 Self::Tuple { span, .. } => *span,
1281 Self::Opaque { span } => *span,
1282 Self::Constant { span, .. } => *span,
1283 Self::Unknown => Span::dummy(),
1284 }
1285 }
1286
1287 pub fn get_name(&self) -> Option<String> {
1288 match self {
1289 Self::Constructor { name, .. } => Some(name.to_string()),
1290 _ => None,
1291 }
1292 }
1293
1294 pub fn is_unknown(&self) -> bool {
1295 matches!(self, Self::Unknown)
1296 }
1297
1298 pub fn is_opaque(&self) -> bool {
1299 matches!(self, Self::Opaque { .. })
1300 }
1301}
1302
1303#[derive(Clone, PartialEq)]
1304#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1305pub struct Generic {
1306 pub name: EcoString,
1307 bounds: GenericBounds,
1308 pub span: Span,
1309}
1310
1311impl fmt::Debug for Generic {
1312 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1313 let bounds = self.bounds().collect::<Vec<_>>();
1314 let resolved_bounds = self
1315 .resolved_bounds()
1316 .into_iter()
1317 .flatten()
1318 .collect::<Vec<_>>();
1319
1320 f.debug_struct("Generic")
1321 .field("name", &self.name)
1322 .field("bounds", &bounds)
1323 .field("resolved_bounds", &resolved_bounds)
1324 .field("span", &self.span)
1325 .finish()
1326 }
1327}
1328
1329#[derive(Debug, Clone, PartialEq)]
1330#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1331enum GenericBounds {
1332 Unresolved(Vec<Annotation>),
1333 Resolved(Vec<ResolvedGenericBound>),
1334}
1335
1336#[derive(Debug, Clone, PartialEq)]
1337#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1338struct ResolvedGenericBound {
1339 annotation: Annotation,
1340 ty: Type,
1341}
1342
1343impl Generic {
1344 pub fn new(name: impl Into<EcoString>, bounds: Vec<Annotation>, span: Span) -> Self {
1345 let bounds = if bounds.is_empty() {
1346 GenericBounds::Resolved(Vec::new())
1347 } else {
1348 GenericBounds::Unresolved(bounds)
1349 };
1350 Self {
1351 name: name.into(),
1352 bounds,
1353 span,
1354 }
1355 }
1356
1357 pub fn resolved(
1363 name: impl Into<EcoString>,
1364 bounds: impl IntoIterator<Item = (Annotation, Type)>,
1365 span: Span,
1366 ) -> Self {
1367 Self {
1368 name: name.into(),
1369 bounds: GenericBounds::Resolved(
1370 bounds
1371 .into_iter()
1372 .map(|(annotation, ty)| ResolvedGenericBound { annotation, ty })
1373 .collect(),
1374 ),
1375 span,
1376 }
1377 }
1378
1379 pub fn bounds(&self) -> impl Iterator<Item = &Annotation> + Clone {
1380 let unresolved = match &self.bounds {
1381 GenericBounds::Unresolved(bounds) => Some(bounds.as_slice()),
1382 GenericBounds::Resolved(_) => None,
1383 };
1384 let resolved = match &self.bounds {
1385 GenericBounds::Unresolved(_) => None,
1386 GenericBounds::Resolved(bounds) => Some(bounds.as_slice()),
1387 };
1388 unresolved.into_iter().flatten().chain(
1389 resolved
1390 .into_iter()
1391 .flatten()
1392 .map(|bound| &bound.annotation),
1393 )
1394 }
1395
1396 pub fn bound_count(&self) -> usize {
1397 match &self.bounds {
1398 GenericBounds::Unresolved(bounds) => bounds.len(),
1399 GenericBounds::Resolved(bounds) => bounds.len(),
1400 }
1401 }
1402
1403 pub fn bounds_are_resolved(&self) -> bool {
1404 matches!(self.bounds, GenericBounds::Resolved(_))
1405 }
1406
1407 pub fn resolved_bounds(&self) -> Option<impl Iterator<Item = &Type> + Clone> {
1408 let GenericBounds::Resolved(bounds) = &self.bounds else {
1409 return None;
1410 };
1411 Some(bounds.iter().map(|bound| &bound.ty))
1412 }
1413
1414 pub fn for_each_bound_annotation_mut(&mut self, mut visit: impl FnMut(&mut Annotation)) {
1415 match &mut self.bounds {
1416 GenericBounds::Unresolved(annotations) => annotations.iter_mut().for_each(visit),
1417 GenericBounds::Resolved(bounds) => {
1418 bounds
1419 .iter_mut()
1420 .for_each(|bound| visit(&mut bound.annotation));
1421 }
1422 }
1423 }
1424
1425 pub fn resolve_bounds_with(&mut self, mut resolve: impl FnMut(&Annotation) -> Type) {
1426 let resolved = match &mut self.bounds {
1427 GenericBounds::Unresolved(annotations) => annotations
1428 .drain(..)
1429 .map(|annotation| {
1430 let ty = resolve(&annotation);
1431 ResolvedGenericBound { annotation, ty }
1432 })
1433 .collect(),
1434 GenericBounds::Resolved(bounds) => {
1435 for bound in bounds {
1436 bound.ty = resolve(&bound.annotation);
1437 }
1438 return;
1439 }
1440 };
1441 self.bounds = GenericBounds::Resolved(resolved);
1442 }
1443}
1444
1445#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1446#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1447pub struct Span {
1448 pub file_id: u32,
1449 pub byte_offset: u32,
1450 pub byte_length: u32,
1451}
1452
1453impl Span {
1454 pub fn new(file_id: u32, byte_offset: u32, byte_length: u32) -> Self {
1455 Span {
1456 file_id,
1457 byte_offset,
1458 byte_length,
1459 }
1460 }
1461
1462 pub fn dummy() -> Self {
1463 Span {
1464 file_id: u32::MAX,
1465 byte_offset: 0,
1466 byte_length: 0,
1467 }
1468 }
1469
1470 pub fn is_dummy(&self) -> bool {
1471 self.file_id == u32::MAX
1472 }
1473
1474 pub fn end(&self) -> u32 {
1475 self.byte_offset + self.byte_length
1476 }
1477
1478 pub fn contains(&self, inner: &Span) -> bool {
1479 self.file_id == inner.file_id
1480 && self.byte_offset <= inner.byte_offset
1481 && inner.end() <= self.end()
1482 }
1483
1484 pub fn merge(self, other: Span) -> Span {
1485 assert_eq!(
1486 self.file_id, other.file_id,
1487 "cannot merge spans from different files"
1488 );
1489 let start = self.byte_offset.min(other.byte_offset);
1490 let end = self.end().max(other.end());
1491 Span::new(self.file_id, start, end - start)
1492 }
1493
1494 pub fn after(self, prefix: Span) -> Span {
1495 Span::new(self.file_id, prefix.end(), self.end() - prefix.end())
1496 }
1497
1498 pub fn trailing(self, length: u32) -> Span {
1499 let length = length.min(self.byte_length);
1500 Span::new(self.file_id, self.end() - length, length)
1501 }
1502
1503 pub fn trailing_name(self, source: &str, name: &str) -> Option<Span> {
1504 let text = source.get(self.byte_offset as usize..self.end() as usize)?;
1505 let trimmed = text.trim_end_matches(|c: char| c.is_whitespace() || c == ')');
1506 let before = trimmed.strip_suffix(name)?;
1507 if before.ends_with(|c: char| c.is_alphanumeric() || c == '_') {
1508 return None;
1509 }
1510 Some(Span::new(
1511 self.file_id,
1512 self.byte_offset + before.len() as u32,
1513 name.len() as u32,
1514 ))
1515 }
1516
1517 pub fn name_segments(self, source: &str, name: &str) -> Option<Vec<Span>> {
1518 let mut remaining = source.get(self.byte_offset as usize..self.end() as usize)?;
1519 let mut offset = self.byte_offset as usize;
1520 let mut segments = Vec::new();
1521 for (index, segment) in name.split('.').enumerate() {
1522 if index > 0 {
1523 let trimmed = remaining.trim_start();
1524 offset += remaining.len() - trimmed.len();
1525 remaining = trimmed.strip_prefix('.')?;
1526 offset += 1;
1527 }
1528 let trimmed = if index == 0 {
1529 remaining.trim_start_matches(|c: char| c.is_whitespace() || c == '(')
1530 } else {
1531 remaining.trim_start()
1532 };
1533 offset += remaining.len() - trimmed.len();
1534 remaining = trimmed.strip_prefix(segment)?;
1535 if remaining.starts_with(|c: char| c.is_alphanumeric() || c == '_') {
1536 return None;
1537 }
1538 segments.push(Span::new(self.file_id, offset as u32, segment.len() as u32));
1539 offset += segment.len();
1540 }
1541 Some(segments)
1542 }
1543}
1544
1545#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
1547pub struct ExpressionId {
1548 file_id: u32,
1549 index: u32,
1550}
1551
1552impl ExpressionId {
1553 pub fn file_id(&self) -> u32 {
1554 self.file_id
1555 }
1556
1557 pub fn parsed(file_id: u32, index: u32) -> Self {
1559 Self { file_id, index }
1560 }
1561
1562 pub fn generated(file_id: u32, index: u32) -> Self {
1564 Self {
1565 file_id,
1566 index: u32::MAX - index,
1567 }
1568 }
1569}
1570
1571impl fmt::Debug for ExpressionId {
1572 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1573 write!(formatter, "ExpressionId({}:{})", self.file_id, self.index)
1574 }
1575}
1576
1577#[derive(Debug, Clone, PartialEq)]
1578pub enum Expression {
1579 Literal {
1580 literal: Literal,
1581 ty: Type,
1582 span: Span,
1583 id: ExpressionId,
1584 },
1585 Function {
1586 doc: Option<String>,
1587 attributes: Vec<Attribute>,
1588 name: EcoString,
1589 name_span: Span,
1590 generics: Vec<Generic>,
1591 params: Vec<Binding>,
1592 return_annotation: Annotation,
1593 return_type: Type,
1594 visibility: Visibility,
1595 body: FunctionBody,
1596 ty: Type,
1597 span: Span,
1598 id: ExpressionId,
1599 },
1600 Lambda {
1601 params: Vec<Binding>,
1602 return_annotation: Annotation,
1603 body: Box<Expression>,
1604 ty: Type,
1605 span: Span,
1606 id: ExpressionId,
1607 },
1608 Block {
1609 items: Vec<Expression>,
1610 ty: Type,
1611 span: Span,
1612 id: ExpressionId,
1613 },
1614 Let {
1615 binding: Box<Binding>,
1616 value: Box<Expression>,
1617 mode: LetMode,
1618 ty: Type,
1619 span: Span,
1620 id: ExpressionId,
1621 },
1622 Identifier {
1623 value: EcoString,
1624 ty: Type,
1625 span: Span,
1626 resolution: IdentifierResolution,
1627 id: ExpressionId,
1628 },
1629 Call {
1630 expression: Box<Expression>,
1631 args: Vec<Expression>,
1632 spread: Option<Box<Expression>>,
1633 type_arguments: CallTypeArguments,
1634 ty: Type,
1635 span: Span,
1636 id: ExpressionId,
1637 },
1638 If {
1639 condition: Box<Expression>,
1640 consequence: Box<Expression>,
1641 alternative: Option<Box<Expression>>,
1642 ty: Type,
1643 span: Span,
1644 id: ExpressionId,
1645 },
1646 IfLet {
1647 pattern: Pattern,
1648 scrutinee: Box<Expression>,
1649 consequence: Box<Expression>,
1650 alternative: IfLetAlternative,
1651 ty: Type,
1652 span: Span,
1653 id: ExpressionId,
1654 },
1655 Match {
1656 subject: Box<Expression>,
1657 arms: Vec<MatchArm>,
1658 ty: Type,
1659 span: Span,
1660 id: ExpressionId,
1661 },
1662 Tuple {
1663 elements: Vec<Expression>,
1664 ty: Type,
1665 span: Span,
1666 id: ExpressionId,
1667 },
1668 StructCall {
1669 name: EcoString,
1670 field_assignments: Vec<StructFieldAssignment>,
1671 spread: StructSpread,
1672 ty: Type,
1673 span: Span,
1674 id: ExpressionId,
1675 },
1676 DotAccess {
1677 expression: Box<Expression>,
1678 member: EcoString,
1679 ty: Type,
1680 span: Span,
1681 resolution: DotAccessResolution,
1682 id: ExpressionId,
1683 },
1684 Assignment {
1685 target: Box<Expression>,
1686 value: Box<Expression>,
1687 compound_operator: Option<BinaryOperator>,
1688 span: Span,
1689 id: ExpressionId,
1690 },
1691 Return {
1692 expression: Box<Expression>,
1693 ty: Type,
1694 span: Span,
1695 id: ExpressionId,
1696 },
1697 Propagate {
1698 expression: Box<Expression>,
1699 ty: Type,
1700 span: Span,
1701 id: ExpressionId,
1702 },
1703 TryBlock {
1704 items: Vec<Expression>,
1705 ty: Type,
1706 try_keyword_span: Span,
1707 span: Span,
1708 id: ExpressionId,
1709 },
1710 RecoverBlock {
1711 items: Vec<Expression>,
1712 ty: Type,
1713 recover_keyword_span: Span,
1714 span: Span,
1715 id: ExpressionId,
1716 },
1717 ImplBlock {
1718 annotation: Annotation,
1719 receiver_name: EcoString,
1720 methods: Vec<Expression>,
1721 generics: Vec<Generic>,
1722 ty: Type,
1723 span: Span,
1724 id: ExpressionId,
1725 },
1726 Binary {
1727 operator: BinaryOperator,
1728 left: Box<Expression>,
1729 right: Box<Expression>,
1730 ty: Type,
1731 span: Span,
1732 id: ExpressionId,
1733 },
1734 Unary {
1735 operator: UnaryOperator,
1736 expression: Box<Expression>,
1737 ty: Type,
1738 span: Span,
1739 id: ExpressionId,
1740 },
1741 Paren {
1742 expression: Box<Expression>,
1743 ty: Type,
1744 span: Span,
1745 id: ExpressionId,
1746 },
1747 Const {
1748 binding: Option<BindingId>,
1749 doc: Option<String>,
1750 identifier: EcoString,
1751 identifier_span: Span,
1752 annotation: Option<Annotation>,
1753 expression: ConstInitializer,
1754 visibility: Visibility,
1755 ty: Type,
1756 span: Span,
1757 id: ExpressionId,
1758 },
1759 VariableDeclaration {
1760 doc: Option<String>,
1761 attributes: Vec<Attribute>,
1762 name: EcoString,
1763 name_span: Span,
1764 annotation: Annotation,
1765 visibility: Visibility,
1766 ty: Type,
1767 span: Span,
1768 id: ExpressionId,
1769 },
1770 Loop {
1771 body: Box<Expression>,
1772 ty: Type,
1773 span: Span,
1774 id: ExpressionId,
1775 },
1776 While {
1777 condition: Box<Expression>,
1778 body: Box<Expression>,
1779 span: Span,
1780 id: ExpressionId,
1781 },
1782 WhileLet {
1783 pattern: Pattern,
1784 scrutinee: Box<Expression>,
1785 body: Box<Expression>,
1786 span: Span,
1787 id: ExpressionId,
1788 },
1789 For {
1790 binding: Box<Binding>,
1791 iterable: Box<Expression>,
1792 body: Box<Expression>,
1793 span: Span,
1794 id: ExpressionId,
1795 },
1796 Break {
1797 value: Option<Box<Expression>>,
1798 span: Span,
1799 id: ExpressionId,
1800 },
1801 Continue {
1802 span: Span,
1803 id: ExpressionId,
1804 },
1805 Enum {
1806 doc: Option<String>,
1807 attributes: Vec<Attribute>,
1808 name: EcoString,
1809 name_span: Span,
1810 generics: Vec<Generic>,
1811 variants: Vec<EnumVariant>,
1812 visibility: Visibility,
1813 span: Span,
1814 id: ExpressionId,
1815 },
1816 Struct {
1817 doc: Option<String>,
1818 attributes: Vec<Attribute>,
1819 name: EcoString,
1820 name_span: Span,
1821 generics: Vec<Generic>,
1822 fields: StructFields,
1823 visibility: Visibility,
1824 span: Span,
1825 id: ExpressionId,
1826 },
1827 TypeAlias {
1828 doc: Option<String>,
1829 attributes: Vec<Attribute>,
1830 name: EcoString,
1831 name_span: Span,
1832 generics: Vec<Generic>,
1833 annotation: Annotation,
1834 ty: Type,
1835 visibility: Visibility,
1836 span: Span,
1837 id: ExpressionId,
1838 },
1839 PackageImport {
1840 name: EcoString,
1841 name_span: Span,
1842 alias: Option<ImportAlias>,
1843 span: Span,
1844 id: ExpressionId,
1845 },
1846 Reference {
1847 expression: Box<Expression>,
1848 ty: Type,
1849 span: Span,
1850 id: ExpressionId,
1851 },
1852 Interface {
1853 doc: Option<String>,
1854 attributes: Vec<Attribute>,
1855 name: EcoString,
1856 name_span: Span,
1857 generics: Vec<Generic>,
1858 parents: Vec<ParentInterface>,
1859 method_signatures: Vec<Expression>,
1860 visibility: Visibility,
1861 span: Span,
1862 id: ExpressionId,
1863 },
1864 IndexedAccess {
1865 expression: Box<Expression>,
1866 index: Box<Expression>,
1867 ty: Type,
1868 span: Span,
1869 from_colon_syntax: bool,
1870 id: ExpressionId,
1871 },
1872 Task {
1873 expression: Box<Expression>,
1874 ty: Type,
1875 span: Span,
1876 id: ExpressionId,
1877 },
1878 Defer {
1879 expression: Box<Expression>,
1880 ty: Type,
1881 span: Span,
1882 id: ExpressionId,
1883 },
1884 Assert {
1885 expression: Box<Expression>,
1886 ty: Type,
1887 span: Span,
1888 id: ExpressionId,
1889 },
1890 Select {
1891 arms: Vec<SelectArm>,
1892 ty: Type,
1893 span: Span,
1894 id: ExpressionId,
1895 },
1896 Unit {
1897 ty: Type,
1898 span: Span,
1899 id: ExpressionId,
1900 },
1901 Range {
1902 start: Option<Box<Expression>>,
1903 end: Option<Box<Expression>>,
1904 inclusive: bool,
1905 ty: Type,
1906 span: Span,
1907 id: ExpressionId,
1908 },
1909 Cast {
1910 expression: Box<Expression>,
1911 target_type: Annotation,
1912 ty: Type,
1913 span: Span,
1914 id: ExpressionId,
1915 },
1916}
1917
1918impl Expression {
1919 pub fn imaginary_coefficient(&self) -> Option<f64> {
1920 match self.unwrap_parens() {
1921 Expression::Literal {
1922 literal: Literal::Imaginary(coefficient),
1923 ..
1924 } => Some(*coefficient),
1925 _ => None,
1926 }
1927 }
1928
1929 pub fn id(&self) -> ExpressionId {
1931 match self {
1932 Self::Literal { id, .. }
1933 | Self::Function { id, .. }
1934 | Self::Lambda { id, .. }
1935 | Self::Block { id, .. }
1936 | Self::Let { id, .. }
1937 | Self::Identifier { id, .. }
1938 | Self::Call { id, .. }
1939 | Self::If { id, .. }
1940 | Self::IfLet { id, .. }
1941 | Self::Match { id, .. }
1942 | Self::Tuple { id, .. }
1943 | Self::StructCall { id, .. }
1944 | Self::DotAccess { id, .. }
1945 | Self::Assignment { id, .. }
1946 | Self::Return { id, .. }
1947 | Self::Propagate { id, .. }
1948 | Self::TryBlock { id, .. }
1949 | Self::RecoverBlock { id, .. }
1950 | Self::ImplBlock { id, .. }
1951 | Self::Binary { id, .. }
1952 | Self::Unary { id, .. }
1953 | Self::Paren { id, .. }
1954 | Self::Const { id, .. }
1955 | Self::VariableDeclaration { id, .. }
1956 | Self::Loop { id, .. }
1957 | Self::While { id, .. }
1958 | Self::WhileLet { id, .. }
1959 | Self::For { id, .. }
1960 | Self::Break { id, .. }
1961 | Self::Continue { id, .. }
1962 | Self::Enum { id, .. }
1963 | Self::Struct { id, .. }
1964 | Self::TypeAlias { id, .. }
1965 | Self::PackageImport { id, .. }
1966 | Self::Reference { id, .. }
1967 | Self::Interface { id, .. }
1968 | Self::IndexedAccess { id, .. }
1969 | Self::Task { id, .. }
1970 | Self::Defer { id, .. }
1971 | Self::Assert { id, .. }
1972 | Self::Select { id, .. }
1973 | Self::Unit { id, .. }
1974 | Self::Range { id, .. }
1975 | Self::Cast { id, .. } => *id,
1976 }
1977 }
1978
1979 pub(crate) fn is_block(&self) -> bool {
1980 matches!(self, Expression::Block { .. })
1981 }
1982
1983 pub fn is_range(&self) -> bool {
1984 matches!(self, Expression::Range { .. })
1985 }
1986
1987 pub fn is_conditional(&self) -> bool {
1988 matches!(self, Expression::If { .. } | Expression::IfLet { .. })
1989 }
1990
1991 pub fn is_control_flow(&self) -> bool {
1992 matches!(
1993 self,
1994 Expression::If { .. }
1995 | Expression::IfLet { .. }
1996 | Expression::Match { .. }
1997 | Expression::Select { .. }
1998 | Expression::For { .. }
1999 | Expression::While { .. }
2000 | Expression::WhileLet { .. }
2001 | Expression::Loop { .. }
2002 )
2003 }
2004
2005 pub fn is_temp_producing(&self) -> bool {
2006 matches!(
2007 self.unwrap_parens(),
2008 Expression::If { .. }
2009 | Expression::IfLet { .. }
2010 | Expression::Match { .. }
2011 | Expression::Block { .. }
2012 | Expression::Loop { .. }
2013 | Expression::Select { .. }
2014 | Expression::TryBlock { .. }
2015 | Expression::RecoverBlock { .. }
2016 )
2017 }
2018
2019 pub fn function_definition_view(&self) -> FunctionDefinitionView<'_> {
2020 match self {
2021 Expression::Function {
2022 name,
2023 name_span,
2024 generics,
2025 params,
2026 return_annotation,
2027 return_type,
2028 body,
2029 ..
2030 } => FunctionDefinitionView {
2031 name,
2032 name_span: *name_span,
2033 generics,
2034 params,
2035 body: body.definition(),
2036 return_type,
2037 annotation: return_annotation,
2038 },
2039 _ => panic!("function_definition_view called on non-Function expression"),
2040 }
2041 }
2042
2043 pub fn get_type(&self) -> Type {
2044 self.value_type().unwrap_or_else(Type::unit)
2045 }
2046
2047 pub fn value_type(&self) -> Option<Type> {
2048 self.type_ref().cloned().or_else(|| {
2049 matches!(self, Self::Break { .. } | Self::Continue { .. }).then(Type::never)
2050 })
2051 }
2052
2053 pub fn type_ref(&self) -> Option<&Type> {
2054 match self {
2055 Self::Literal { ty, .. }
2056 | Self::Function { ty, .. }
2057 | Self::Lambda { ty, .. }
2058 | Self::Block { ty, .. }
2059 | Self::Let { ty, .. }
2060 | Self::Identifier { ty, .. }
2061 | Self::Call { ty, .. }
2062 | Self::If { ty, .. }
2063 | Self::IfLet { ty, .. }
2064 | Self::Match { ty, .. }
2065 | Self::Tuple { ty, .. }
2066 | Self::StructCall { ty, .. }
2067 | Self::DotAccess { ty, .. }
2068 | Self::Return { ty, .. }
2069 | Self::Propagate { ty, .. }
2070 | Self::TryBlock { ty, .. }
2071 | Self::RecoverBlock { ty, .. }
2072 | Self::Binary { ty, .. }
2073 | Self::Paren { ty, .. }
2074 | Self::Unary { ty, .. }
2075 | Self::Const { ty, .. }
2076 | Self::VariableDeclaration { ty, .. }
2077 | Self::Defer { ty, .. }
2078 | Self::Assert { ty, .. }
2079 | Self::Reference { ty, .. }
2080 | Self::IndexedAccess { ty, .. }
2081 | Self::Task { ty, .. }
2082 | Self::Select { ty, .. }
2083 | Self::Unit { ty, .. }
2084 | Self::Loop { ty, .. }
2085 | Self::Range { ty, .. }
2086 | Self::Cast { ty, .. } => Some(ty),
2087 Self::Enum { .. }
2088 | Self::Struct { .. }
2089 | Self::Assignment { .. }
2090 | Self::ImplBlock { .. }
2091 | Self::TypeAlias { .. }
2092 | Self::PackageImport { .. }
2093 | Self::Interface { .. }
2094 | Self::While { .. }
2095 | Self::WhileLet { .. }
2096 | Self::For { .. } => None,
2097 Self::Break { .. } | Self::Continue { .. } => None,
2098 }
2099 }
2100
2101 pub fn get_span(&self) -> Span {
2102 match self {
2103 Self::Literal { span, .. }
2104 | Self::Function { span, .. }
2105 | Self::Lambda { span, .. }
2106 | Self::Block { span, .. }
2107 | Self::Let { span, .. }
2108 | Self::Identifier { span, .. }
2109 | Self::Call { span, .. }
2110 | Self::If { span, .. }
2111 | Self::IfLet { span, .. }
2112 | Self::Match { span, .. }
2113 | Self::Tuple { span, .. }
2114 | Self::Enum { span, .. }
2115 | Self::Struct { span, .. }
2116 | Self::StructCall { span, .. }
2117 | Self::DotAccess { span, .. }
2118 | Self::Assignment { span, .. }
2119 | Self::Return { span, .. }
2120 | Self::Propagate { span, .. }
2121 | Self::TryBlock { span, .. }
2122 | Self::RecoverBlock { span, .. }
2123 | Self::ImplBlock { span, .. }
2124 | Self::Binary { span, .. }
2125 | Self::Paren { span, .. }
2126 | Self::Unary { span, .. }
2127 | Self::Const { span, .. }
2128 | Self::VariableDeclaration { span, .. }
2129 | Self::Defer { span, .. }
2130 | Self::Assert { span, .. }
2131 | Self::Reference { span, .. }
2132 | Self::IndexedAccess { span, .. }
2133 | Self::Task { span, .. }
2134 | Self::Select { span, .. }
2135 | Self::Loop { span, .. }
2136 | Self::TypeAlias { span, .. }
2137 | Self::PackageImport { span, .. }
2138 | Self::Interface { span, .. }
2139 | Self::Unit { span, .. }
2140 | Self::While { span, .. }
2141 | Self::WhileLet { span, .. }
2142 | Self::For { span, .. }
2143 | Self::Break { span, .. }
2144 | Self::Continue { span, .. }
2145 | Self::Range { span, .. }
2146 | Self::Cast { span, .. } => *span,
2147 }
2148 }
2149
2150 pub fn set_span(&mut self, new_span: Span) {
2151 match self {
2152 Self::Literal { span, .. }
2153 | Self::Function { span, .. }
2154 | Self::Lambda { span, .. }
2155 | Self::Block { span, .. }
2156 | Self::Let { span, .. }
2157 | Self::Identifier { span, .. }
2158 | Self::Call { span, .. }
2159 | Self::If { span, .. }
2160 | Self::IfLet { span, .. }
2161 | Self::Match { span, .. }
2162 | Self::Tuple { span, .. }
2163 | Self::Enum { span, .. }
2164 | Self::Struct { span, .. }
2165 | Self::StructCall { span, .. }
2166 | Self::DotAccess { span, .. }
2167 | Self::Assignment { span, .. }
2168 | Self::Return { span, .. }
2169 | Self::Propagate { span, .. }
2170 | Self::TryBlock { span, .. }
2171 | Self::RecoverBlock { span, .. }
2172 | Self::ImplBlock { span, .. }
2173 | Self::Binary { span, .. }
2174 | Self::Paren { span, .. }
2175 | Self::Unary { span, .. }
2176 | Self::Const { span, .. }
2177 | Self::VariableDeclaration { span, .. }
2178 | Self::Defer { span, .. }
2179 | Self::Assert { span, .. }
2180 | Self::Reference { span, .. }
2181 | Self::IndexedAccess { span, .. }
2182 | Self::Task { span, .. }
2183 | Self::Select { span, .. }
2184 | Self::Loop { span, .. }
2185 | Self::TypeAlias { span, .. }
2186 | Self::PackageImport { span, .. }
2187 | Self::Interface { span, .. }
2188 | Self::Unit { span, .. }
2189 | Self::While { span, .. }
2190 | Self::WhileLet { span, .. }
2191 | Self::For { span, .. }
2192 | Self::Break { span, .. }
2193 | Self::Continue { span, .. }
2194 | Self::Range { span, .. }
2195 | Self::Cast { span, .. } => *span = new_span,
2196 }
2197 }
2198
2199 pub fn contains_break(&self) -> bool {
2200 match self {
2201 Expression::Break { .. } => true,
2202
2203 Expression::Loop { .. }
2204 | Expression::While { .. }
2205 | Expression::WhileLet { .. }
2206 | Expression::For { .. } => false,
2207
2208 Expression::Block { items, .. } => items.iter().any(Self::contains_break),
2209
2210 Expression::TryBlock { items, .. } => items.iter().any(Self::contains_break),
2211 Expression::RecoverBlock { items, .. } => items.iter().any(Self::contains_break),
2212
2213 Expression::If {
2214 condition,
2215 consequence,
2216 alternative,
2217 ..
2218 } => {
2219 condition.contains_break()
2220 || consequence.contains_break()
2221 || alternative.as_deref().is_some_and(Self::contains_break)
2222 }
2223
2224 Expression::IfLet {
2225 scrutinee,
2226 consequence,
2227 alternative,
2228 ..
2229 } => {
2230 scrutinee.contains_break()
2231 || consequence.contains_break()
2232 || alternative.expression().is_some_and(Self::contains_break)
2233 }
2234
2235 Expression::Match { subject, arms, .. } => {
2236 subject.contains_break() || arms.iter().any(|arm| arm.expression.contains_break())
2237 }
2238
2239 Expression::Paren { expression, .. } => expression.contains_break(),
2240
2241 Expression::Binary { left, right, .. } => {
2242 left.contains_break() || right.contains_break()
2243 }
2244
2245 Expression::Unary { expression, .. } => expression.contains_break(),
2246
2247 Expression::Call {
2248 expression,
2249 args,
2250 spread,
2251 ..
2252 } => {
2253 expression.contains_break()
2254 || args.iter().any(Self::contains_break)
2255 || spread.as_deref().is_some_and(Self::contains_break)
2256 }
2257
2258 Expression::Function { .. } | Expression::Lambda { .. } => false,
2259
2260 Expression::Select { arms, .. } => arms.iter().any(|arm| match arm {
2261 SelectArm::Receive { body, .. } => body.contains_break(),
2262 SelectArm::Send { body, .. } => body.contains_break(),
2263 SelectArm::MatchReceive { arms, .. } => {
2264 arms.iter().any(|a| a.expression.contains_break())
2265 }
2266 SelectArm::WildCard { body, .. } => body.contains_break(),
2267 }),
2268
2269 Expression::Cast { expression, .. } => expression.contains_break(),
2270
2271 Expression::Let { value, mode, .. } => {
2272 value.contains_break() || mode.else_block().is_some_and(Self::contains_break)
2273 }
2274
2275 Expression::Assignment { value, .. } => value.contains_break(),
2276
2277 _ => false,
2278 }
2279 }
2280
2281 pub fn diverges(&self) -> Option<DeadCodeCause> {
2282 match self {
2283 Expression::Return { .. } => Some(DeadCodeCause::Return),
2284 Expression::Break { .. } => Some(DeadCodeCause::Break),
2285 Expression::Continue { .. } => Some(DeadCodeCause::Continue),
2286
2287 Expression::If {
2288 consequence,
2289 alternative,
2290 ..
2291 } => {
2292 if consequence.diverges().is_some()
2293 && alternative
2294 .as_deref()
2295 .is_some_and(|alternative| alternative.diverges().is_some())
2296 {
2297 Some(DeadCodeCause::DivergingIf)
2298 } else {
2299 None
2300 }
2301 }
2302
2303 Expression::IfLet {
2304 consequence,
2305 alternative,
2306 ..
2307 } => {
2308 if consequence.diverges().is_some()
2309 && alternative
2310 .expression()
2311 .is_some_and(|alternative| alternative.diverges().is_some())
2312 {
2313 Some(DeadCodeCause::DivergingIf)
2314 } else {
2315 None
2316 }
2317 }
2318
2319 Expression::Match { arms, .. } => {
2320 if !arms.is_empty() && arms.iter().all(|arm| arm.expression.diverges().is_some()) {
2321 Some(DeadCodeCause::DivergingMatch)
2322 } else {
2323 None
2324 }
2325 }
2326
2327 Expression::Block { items, .. } => {
2328 for item in items {
2329 if let Some(cause) = item.diverges() {
2330 return Some(cause);
2331 }
2332 }
2333 None
2334 }
2335
2336 Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
2337 for item in items {
2338 if let Some(cause) = item.diverges() {
2339 return Some(cause);
2340 }
2341 }
2342 None
2343 }
2344
2345 Expression::Paren { expression, .. } | Expression::Cast { expression, .. } => {
2346 expression.diverges()
2347 }
2348
2349 Expression::Loop { body, .. } => {
2350 if !body.contains_break() {
2351 Some(DeadCodeCause::InfiniteLoop)
2352 } else {
2353 None
2354 }
2355 }
2356
2357 Expression::Call { ty, .. } if ty.is_never() => Some(DeadCodeCause::DivergingCall),
2358
2359 _ => None,
2360 }
2361 }
2362
2363 pub fn evaluation_children(&self) -> Vec<&Expression> {
2364 match self {
2365 Self::Function { .. } | Self::Lambda { .. } | Self::Task { .. } => Vec::new(),
2366 _ => self.children(),
2367 }
2368 }
2369
2370 pub fn propagation_children(&self) -> Vec<&Expression> {
2371 match self {
2372 Self::TryBlock { .. } | Self::RecoverBlock { .. } => Vec::new(),
2373 _ => self.evaluation_children(),
2374 }
2375 }
2376
2377 pub fn children(&self) -> Vec<&Expression> {
2382 let mut children = Vec::new();
2383 self.for_each_child(|child| children.push(child));
2384 children
2385 }
2386
2387 pub fn for_each_child<'a>(&'a self, mut f: impl FnMut(&'a Expression)) {
2388 match self {
2389 Expression::Literal { literal, .. } => match literal {
2390 Literal::Slice(elements) => elements.iter().for_each(f),
2391 Literal::FormatString(parts) => {
2392 for part in parts {
2393 if let FormatStringPart::Expression(e) = part {
2394 f(e);
2395 }
2396 }
2397 }
2398 _ => {}
2399 },
2400 Expression::Function { body, .. } => body.definition().into_iter().for_each(f),
2401 Expression::Lambda { body, .. } => f(body),
2402 Expression::Block { items, .. } => items.iter().for_each(f),
2403 Expression::Let { value, mode, .. } => {
2404 f(value);
2405 if let Some(else_block) = mode.else_block() {
2406 f(else_block);
2407 }
2408 }
2409 Expression::Identifier { .. } => {}
2410 Expression::Call {
2411 expression,
2412 args,
2413 spread,
2414 ..
2415 } => {
2416 f(expression);
2417 args.iter().for_each(&mut f);
2418 if let Some(spread) = spread.as_ref() {
2419 f(spread);
2420 }
2421 }
2422 Expression::If {
2423 condition,
2424 consequence,
2425 alternative,
2426 ..
2427 } => {
2428 f(condition);
2429 f(consequence);
2430 if let Some(alternative) = alternative {
2431 f(alternative);
2432 }
2433 }
2434 Expression::IfLet {
2435 scrutinee,
2436 consequence,
2437 alternative,
2438 ..
2439 } => {
2440 f(scrutinee);
2441 f(consequence);
2442 if let Some(alternative) = alternative.expression() {
2443 f(alternative);
2444 }
2445 }
2446 Expression::Match { subject, arms, .. } => {
2447 f(subject);
2448 for arm in arms {
2449 if let Some(guard) = &arm.guard {
2450 f(guard);
2451 }
2452 f(&arm.expression);
2453 }
2454 }
2455 Expression::Tuple { elements, .. } => elements.iter().for_each(f),
2456 Expression::StructCall {
2457 field_assignments,
2458 spread,
2459 ..
2460 } => {
2461 for field in field_assignments {
2462 f(&field.value);
2463 }
2464 if let Some(spread) = spread.as_expression() {
2465 f(spread);
2466 }
2467 }
2468 Expression::DotAccess { expression, .. }
2469 | Expression::Return { expression, .. }
2470 | Expression::Propagate { expression, .. }
2471 | Expression::Unary { expression, .. }
2472 | Expression::Paren { expression, .. }
2473 | Expression::Reference { expression, .. }
2474 | Expression::Task { expression, .. }
2475 | Expression::Defer { expression, .. }
2476 | Expression::Assert { expression, .. }
2477 | Expression::Cast { expression, .. } => f(expression),
2478 Expression::Assignment { target, value, .. } => {
2479 f(target);
2480 f(value);
2481 }
2482 Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
2483 items.iter().for_each(f)
2484 }
2485 Expression::ImplBlock { methods, .. } => methods.iter().for_each(f),
2486 Expression::Binary { left, right, .. } => {
2487 f(left);
2488 f(right);
2489 }
2490 Expression::Const { expression, .. } => expression.value().into_iter().for_each(f),
2491 Expression::Loop { body, .. } => f(body),
2492 Expression::While {
2493 condition, body, ..
2494 } => {
2495 f(condition);
2496 f(body);
2497 }
2498 Expression::WhileLet {
2499 scrutinee, body, ..
2500 } => {
2501 f(scrutinee);
2502 f(body);
2503 }
2504 Expression::For { iterable, body, .. } => {
2505 f(iterable);
2506 f(body);
2507 }
2508 Expression::Break { value, .. } => {
2509 if let Some(value) = value {
2510 f(value);
2511 }
2512 }
2513 Expression::IndexedAccess {
2514 expression, index, ..
2515 } => {
2516 f(expression);
2517 f(index);
2518 }
2519 Expression::Select { arms, .. } => {
2520 for arm in arms {
2521 match arm {
2522 SelectArm::Receive {
2523 receive_expression,
2524 body,
2525 ..
2526 } => {
2527 f(receive_expression);
2528 f(body);
2529 }
2530 SelectArm::Send {
2531 send_expression,
2532 body,
2533 } => {
2534 f(send_expression);
2535 f(body);
2536 }
2537 SelectArm::MatchReceive {
2538 receive_expression,
2539 arms: match_arms,
2540 } => {
2541 f(receive_expression);
2542 for match_arm in match_arms {
2543 match_arm.guard.as_deref().into_iter().for_each(&mut f);
2544 f(&match_arm.expression);
2545 }
2546 }
2547 SelectArm::WildCard { body, .. } => f(body),
2548 }
2549 }
2550 }
2551 Expression::Range { start, end, .. } => {
2552 if let Some(start) = start {
2553 f(start);
2554 }
2555 if let Some(end) = end {
2556 f(end);
2557 }
2558 }
2559 Expression::Interface {
2560 method_signatures, ..
2561 } => method_signatures.iter().for_each(f),
2562 Expression::Unit { .. }
2563 | Expression::Continue { .. }
2564 | Expression::Enum { .. }
2565 | Expression::Struct { .. }
2566 | Expression::TypeAlias { .. }
2567 | Expression::VariableDeclaration { .. }
2568 | Expression::PackageImport { .. } => {}
2569 }
2570 }
2571
2572 pub fn introduced_patterns<'a>(&'a self, mut f: impl FnMut(&'a Pattern, PatternSite)) {
2573 match self {
2574 Expression::Function { params, .. } | Expression::Lambda { params, .. } => {
2575 for param in params {
2576 f(¶m.pattern, PatternSite::Parameter);
2577 }
2578 }
2579 Expression::Let { binding, .. } | Expression::For { binding, .. } => {
2580 f(&binding.pattern, PatternSite::Binding);
2581 }
2582 Expression::IfLet { pattern, .. } | Expression::WhileLet { pattern, .. } => {
2583 f(pattern, PatternSite::Binding);
2584 }
2585 Expression::Match { arms, .. } => {
2586 for arm in arms {
2587 f(&arm.pattern, arm.pattern_site());
2588 }
2589 }
2590 Expression::Select { arms, .. } => {
2591 for select_arm in arms {
2592 match select_arm {
2593 SelectArm::Receive { binding, .. } => f(binding, PatternSite::Binding),
2594 SelectArm::MatchReceive { arms, .. } => arms
2595 .iter()
2596 .for_each(|arm| f(&arm.pattern, arm.pattern_site())),
2597 SelectArm::Send { .. } | SelectArm::WildCard { .. } => {}
2598 }
2599 }
2600 }
2601 _ => {}
2602 }
2603 }
2604
2605 pub fn for_each_child_mut<'a>(&'a mut self, mut f: impl FnMut(&'a mut Expression)) {
2606 match self {
2607 Expression::Literal { literal, .. } => match literal {
2608 Literal::Slice(elements) => elements.iter_mut().for_each(f),
2609 Literal::FormatString(parts) => {
2610 for part in parts {
2611 if let FormatStringPart::Expression(e) = part {
2612 f(e);
2613 }
2614 }
2615 }
2616 _ => {}
2617 },
2618 Expression::Function { body, .. } => body.definition_mut().into_iter().for_each(f),
2619 Expression::Lambda { body, .. } => f(body),
2620 Expression::Block { items, .. } => items.iter_mut().for_each(f),
2621 Expression::Let { value, mode, .. } => {
2622 f(value);
2623 if let Some(else_block) = mode.else_block_mut() {
2624 f(else_block);
2625 }
2626 }
2627 Expression::Identifier { .. } => {}
2628 Expression::Call {
2629 expression,
2630 args,
2631 spread,
2632 ..
2633 } => {
2634 f(expression);
2635 args.iter_mut().for_each(&mut f);
2636 if let Some(spread) = spread.as_mut() {
2637 f(spread);
2638 }
2639 }
2640 Expression::If {
2641 condition,
2642 consequence,
2643 alternative,
2644 ..
2645 } => {
2646 f(condition);
2647 f(consequence);
2648 if let Some(alternative) = alternative {
2649 f(alternative);
2650 }
2651 }
2652 Expression::IfLet {
2653 scrutinee,
2654 consequence,
2655 alternative,
2656 ..
2657 } => {
2658 f(scrutinee);
2659 f(consequence);
2660 if let Some(alternative) = alternative.expression_mut() {
2661 f(alternative);
2662 }
2663 }
2664 Expression::Match { subject, arms, .. } => {
2665 f(subject);
2666 for arm in arms {
2667 if let Some(guard) = &mut arm.guard {
2668 f(guard);
2669 }
2670 f(&mut arm.expression);
2671 }
2672 }
2673 Expression::Tuple { elements, .. } => elements.iter_mut().for_each(f),
2674 Expression::StructCall {
2675 field_assignments,
2676 spread,
2677 ..
2678 } => {
2679 for field in field_assignments {
2680 f(&mut field.value);
2681 }
2682 if let Some(spread) = spread.as_expression_mut() {
2683 f(spread);
2684 }
2685 }
2686 Expression::DotAccess { expression, .. }
2687 | Expression::Return { expression, .. }
2688 | Expression::Propagate { expression, .. }
2689 | Expression::Unary { expression, .. }
2690 | Expression::Paren { expression, .. }
2691 | Expression::Reference { expression, .. }
2692 | Expression::Task { expression, .. }
2693 | Expression::Defer { expression, .. }
2694 | Expression::Assert { expression, .. }
2695 | Expression::Cast { expression, .. } => f(expression),
2696 Expression::Assignment { target, value, .. } => {
2697 f(target);
2698 f(value);
2699 }
2700 Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
2701 items.iter_mut().for_each(f)
2702 }
2703 Expression::ImplBlock { methods, .. } => methods.iter_mut().for_each(f),
2704 Expression::Binary { left, right, .. } => {
2705 f(left);
2706 f(right);
2707 }
2708 Expression::Const { expression, .. } => expression.value_mut().into_iter().for_each(f),
2709 Expression::Loop { body, .. } => f(body),
2710 Expression::While {
2711 condition, body, ..
2712 } => {
2713 f(condition);
2714 f(body);
2715 }
2716 Expression::WhileLet {
2717 scrutinee, body, ..
2718 } => {
2719 f(scrutinee);
2720 f(body);
2721 }
2722 Expression::For { iterable, body, .. } => {
2723 f(iterable);
2724 f(body);
2725 }
2726 Expression::Break { value, .. } => {
2727 if let Some(value) = value {
2728 f(value);
2729 }
2730 }
2731 Expression::IndexedAccess {
2732 expression, index, ..
2733 } => {
2734 f(expression);
2735 f(index);
2736 }
2737 Expression::Select { arms, .. } => {
2738 for arm in arms {
2739 match arm {
2740 SelectArm::Receive {
2741 receive_expression,
2742 body,
2743 ..
2744 } => {
2745 f(receive_expression);
2746 f(body);
2747 }
2748 SelectArm::Send {
2749 send_expression,
2750 body,
2751 } => {
2752 f(send_expression);
2753 f(body);
2754 }
2755 SelectArm::MatchReceive {
2756 receive_expression,
2757 arms: match_arms,
2758 } => {
2759 f(receive_expression);
2760 for match_arm in match_arms {
2761 match_arm.guard.as_deref_mut().into_iter().for_each(&mut f);
2762 f(&mut match_arm.expression);
2763 }
2764 }
2765 SelectArm::WildCard { body, .. } => f(body),
2766 }
2767 }
2768 }
2769 Expression::Range { start, end, .. } => {
2770 if let Some(start) = start {
2771 f(start);
2772 }
2773 if let Some(end) = end {
2774 f(end);
2775 }
2776 }
2777 Expression::Interface {
2778 method_signatures, ..
2779 } => method_signatures.iter_mut().for_each(f),
2780 Expression::Unit { .. }
2781 | Expression::Continue { .. }
2782 | Expression::Enum { .. }
2783 | Expression::Struct { .. }
2784 | Expression::TypeAlias { .. }
2785 | Expression::VariableDeclaration { .. }
2786 | Expression::PackageImport { .. } => {}
2787 }
2788 }
2789
2790 pub fn strip_wrappers(&mut self) {
2791 self.peel_wrappers(None);
2792 self.strip_child_wrappers();
2793 }
2794
2795 fn strip_child_wrappers(&mut self) {
2796 let slots = self.block_slots();
2797 let keeps_block: Vec<bool> = if slots.is_empty() {
2798 Vec::new()
2799 } else {
2800 self.children()
2801 .into_iter()
2802 .map(|child| slots.iter().any(|slot| ptr::eq(*slot, child)))
2803 .collect()
2804 };
2805 let is_statement_list = self.is_block();
2806 let mut index = 0;
2807 self.for_each_child_mut(|child| {
2808 let keeps_block = keeps_block.get(index).copied().unwrap_or(false);
2809 index += 1;
2810 child.peel_wrappers((!keeps_block).then_some(is_statement_list));
2811 child.strip_child_wrappers();
2812 });
2813 }
2814
2815 pub fn contains_wrapper(&self) -> bool {
2816 let slots = self.block_slots();
2817 let is_statement_list = self.is_block();
2818 self.reads_reference_once()
2819 || self.children().into_iter().any(|child| {
2820 let keeps_block = slots.iter().any(|slot| ptr::eq(*slot, child));
2821 (!keeps_block && child.removable_block(is_statement_list))
2822 || child.contains_wrapper()
2823 })
2824 }
2825
2826 fn removable_block(&self, is_statement: bool) -> bool {
2827 match self {
2828 Expression::Block { items, .. } => match items.as_slice() {
2829 [item] => item.is_plain_block_item() && (is_statement || item.is_value_form()),
2830 _ => false,
2831 },
2832 _ => false,
2833 }
2834 }
2835
2836 fn peel_wrappers(&mut self, blocks: Option<bool>) {
2837 loop {
2838 let removes_block =
2839 blocks.is_some_and(|is_statement| self.removable_block(is_statement));
2840 let inner = match self {
2841 Expression::Block { items, .. } if removes_block => &mut items[0],
2842 _ => return,
2843 };
2844 let placeholder = Expression::Unit {
2845 ty: Type::unit(),
2846 span: inner.get_span(),
2847 id: inner.id(),
2848 };
2849 *self = mem::replace(inner, placeholder);
2850 }
2851 }
2852
2853 fn is_plain_block_item(&self) -> bool {
2854 !matches!(
2855 self,
2856 Expression::Let { .. }
2857 | Expression::Const { .. }
2858 | Expression::Function { .. }
2859 | Expression::Struct { .. }
2860 | Expression::Enum { .. }
2861 | Expression::Interface { .. }
2862 | Expression::TypeAlias { .. }
2863 | Expression::ImplBlock { .. }
2864 | Expression::VariableDeclaration { .. }
2865 | Expression::PackageImport { .. }
2866 | Expression::Defer { .. }
2867 )
2868 }
2869
2870 fn is_value_form(&self) -> bool {
2871 !matches!(
2872 self,
2873 Expression::For { .. }
2874 | Expression::While { .. }
2875 | Expression::WhileLet { .. }
2876 | Expression::Assignment { .. }
2877 | Expression::Return { .. }
2878 | Expression::Break { .. }
2879 | Expression::Continue { .. }
2880 | Expression::Task { .. }
2881 | Expression::Assert { .. }
2882 | Expression::Select { .. }
2883 )
2884 }
2885
2886 fn block_slots(&self) -> Vec<&Expression> {
2887 match self {
2888 Expression::Function { body, .. } => body.definition().into_iter().collect(),
2889 Expression::If {
2890 consequence,
2891 alternative,
2892 ..
2893 } => {
2894 let mut slots = vec![consequence.as_ref()];
2895 slots.extend(alternative.as_deref());
2896 slots
2897 }
2898 Expression::IfLet {
2899 consequence,
2900 alternative,
2901 ..
2902 } => {
2903 let mut slots = vec![consequence.as_ref()];
2904 slots.extend(alternative.expression());
2905 slots
2906 }
2907 Expression::Let { mode, .. } => mode.else_block().into_iter().collect(),
2908 Expression::Loop { body, .. }
2909 | Expression::While { body, .. }
2910 | Expression::WhileLet { body, .. }
2911 | Expression::For { body, .. } => vec![body],
2912 Expression::Task { expression, .. } | Expression::Defer { expression, .. } => {
2913 vec![expression]
2914 }
2915 Expression::Select { .. } => self.children(),
2916 _ => Vec::new(),
2917 }
2918 }
2919
2920 pub fn reads_reference_once(&self) -> bool {
2921 match self {
2922 Expression::Reference { expression, ty, .. } => *ty == expression.get_type(),
2923 Expression::Unary {
2924 operator: UnaryOperator::Deref,
2925 expression,
2926 ..
2927 } => matches!(expression.unwrap_parens(), Expression::Reference { .. }),
2928 Expression::DotAccess {
2929 expression,
2930 resolution,
2931 ..
2932 } => resolution.reads_receiver() && expression.is_reference_receiver(),
2933 _ => false,
2934 }
2935 }
2936
2937 pub fn is_reference_receiver(&self) -> bool {
2938 matches!(
2939 self.unwrap_parens(),
2940 Expression::Reference { expression, .. } if !expression.is_fresh_value()
2941 )
2942 }
2943
2944 pub fn is_fresh_reference(&self) -> bool {
2945 matches!(
2946 self.unwrap_parens(),
2947 Expression::Reference { expression, .. } if expression.is_fresh_value()
2948 )
2949 }
2950
2951 fn is_fresh_value(&self) -> bool {
2952 matches!(
2953 self.unwrap_parens(),
2954 Expression::Call { .. } | Expression::StructCall { .. }
2955 )
2956 }
2957
2958 pub fn unwrap_parens(&self) -> &Expression {
2959 match self {
2960 Expression::Paren { expression, .. } => expression.unwrap_parens(),
2961 other => other,
2962 }
2963 }
2964
2965 pub fn unwrap_value_wrappers(&self) -> &Expression {
2966 match self {
2967 Expression::Paren { expression, .. } => expression.unwrap_value_wrappers(),
2968 Expression::Block { items, .. } if self.removable_block(false) => {
2969 items[0].unwrap_value_wrappers()
2970 }
2971 other => other,
2972 }
2973 }
2974
2975 pub fn is_piped_call(&self) -> bool {
2976 let Expression::Call {
2977 expression: callee,
2978 args,
2979 spread,
2980 ..
2981 } = self
2982 else {
2983 return false;
2984 };
2985 let callee_start = callee.get_span().byte_offset;
2986 args.iter()
2987 .chain(spread.as_deref())
2988 .any(|arg| arg.get_span().byte_offset < callee_start)
2989 }
2990
2991 pub fn binding_id(&self) -> Option<BindingId> {
2992 match self.unwrap_parens() {
2993 Expression::Identifier { resolution, .. } => resolution.binding_id(),
2994 _ => None,
2995 }
2996 }
2997
2998 pub fn as_integer(&self) -> Option<u64> {
2999 match self.unwrap_parens() {
3000 Expression::Literal {
3001 literal: Literal::Integer { value, .. },
3002 ..
3003 } => Some(*value),
3004 _ => None,
3005 }
3006 }
3007
3008 #[inline]
3010 pub fn deref_inner(&self) -> Option<&Expression> {
3011 match self.unwrap_parens() {
3012 Expression::Unary {
3013 operator: UnaryOperator::Deref,
3014 expression,
3015 ..
3016 } => Some(expression),
3017 _ => None,
3018 }
3019 }
3020
3021 pub fn as_dotted_path(&self) -> Option<String> {
3022 match self {
3023 Expression::Identifier { value, .. } => Some(value.to_string()),
3024 Expression::DotAccess {
3025 expression, member, ..
3026 } => Some(format!("{}.{}", expression.as_dotted_path()?, member)),
3027 _ => None,
3028 }
3029 }
3030
3031 pub fn root_identifier(&self) -> Option<&str> {
3032 match self {
3033 Expression::Identifier { value, .. } => Some(value),
3034 Expression::DotAccess { expression, .. } => expression.root_identifier(),
3035 _ => None,
3036 }
3037 }
3038
3039 pub fn root_binding_id(&self) -> Option<BindingId> {
3040 match self.unwrap_parens() {
3041 Expression::Identifier {
3042 resolution: IdentifierResolution::Binding(id),
3043 ..
3044 } => Some(*id),
3045 Expression::DotAccess { expression, .. }
3046 | Expression::IndexedAccess { expression, .. } => expression.root_binding_id(),
3047 _ => None,
3048 }
3049 }
3050
3051 pub fn is_empty_collection(&self) -> bool {
3052 matches!(
3053 self.unwrap_parens(),
3054 Expression::Literal {
3055 literal: Literal::Slice(elements),
3056 ..
3057 } if elements.is_empty()
3058 )
3059 }
3060
3061 pub fn is_all_literals(&self) -> bool {
3062 match self.unwrap_parens() {
3063 Expression::Literal { literal, .. } => match literal {
3064 Literal::Slice(elements) => elements.iter().all(|e| e.is_all_literals()),
3065 Literal::FormatString(parts) => parts.iter().all(|p| match p {
3066 FormatStringPart::Text(_) => true,
3067 FormatStringPart::Expression(e) => e.is_all_literals(),
3068 }),
3069 _ => true,
3070 },
3071 Expression::Tuple { elements, .. } => elements.iter().all(|e| e.is_all_literals()),
3072 Expression::Unit { .. } => true,
3073 _ => false,
3074 }
3075 }
3076
3077 pub fn get_var_name(&self) -> Option<String> {
3078 match self {
3079 Expression::Identifier { value, .. } => Some(value.to_string()),
3080 Expression::DotAccess { expression, .. } => expression.get_var_name(),
3081 Expression::Assignment { target, .. } => target.get_var_name(),
3082 Expression::IndexedAccess { expression, .. } => expression.get_var_name(),
3083 Expression::Paren { expression, .. } => expression.get_var_name(),
3084 Expression::Reference { expression, .. } => expression.get_var_name(),
3085 Expression::Unary {
3086 operator,
3087 expression,
3088 ..
3089 } => {
3090 if operator == &UnaryOperator::Deref {
3091 expression.get_var_name()
3092 } else {
3093 None
3094 }
3095 }
3096 _ => None,
3097 }
3098 }
3099
3100 pub(crate) fn set_public(mut self) -> Self {
3101 match &mut self {
3102 Expression::Struct {
3103 fields, visibility, ..
3104 } => {
3105 if let StructFields::Tuple(fields) = fields {
3106 for field in fields {
3107 field.visibility = Visibility::Public;
3108 }
3109 }
3110 *visibility = Visibility::Public;
3111 }
3112 Expression::Enum { visibility, .. }
3113 | Expression::Function { visibility, .. }
3114 | Expression::Const { visibility, .. }
3115 | Expression::VariableDeclaration { visibility, .. }
3116 | Expression::TypeAlias { visibility, .. }
3117 | Expression::Interface { visibility, .. } => *visibility = Visibility::Public,
3118 _ => {}
3119 }
3120 self
3121 }
3122
3123 pub fn has_else(&self) -> bool {
3124 match self {
3125 Self::Block { items, .. } if items.is_empty() => false,
3126 Self::Unit { .. } => false,
3127 Self::If { alternative, .. } => alternative.as_deref().is_some_and(Self::has_else),
3128 Self::IfLet { alternative, .. } => alternative.expression().is_some_and(Self::has_else),
3129 _ => true,
3130 }
3131 }
3132}
3133
3134#[derive(Debug, Clone, PartialEq)]
3135pub enum Literal {
3136 Integer {
3137 value: u64,
3138 text: Option<String>,
3139 },
3140 Float {
3141 value: f64,
3142 text: Option<String>,
3143 },
3144 Imaginary(f64),
3146 Boolean(bool),
3147 String {
3148 value: String,
3149 raw: bool,
3150 },
3151 FormatString(Vec<FormatStringPart>),
3152 Char(String),
3153 Slice(Vec<Expression>),
3154}
3155
3156impl Literal {
3157 pub fn diagnostic_text(&self) -> String {
3159 match self {
3160 Literal::Integer { text, value } => text.as_ref().unwrap_or(&value.to_string()).clone(),
3161 Literal::Float { text, value } => text.as_ref().unwrap_or(&value.to_string()).clone(),
3162 Literal::Imaginary(v) => format!("{}i", v),
3163 Literal::Boolean(b) => b.to_string(),
3164 Literal::String { value, raw: true } => format!("r\"{}\"", value),
3165 Literal::String { value, raw: false } => format!("\"{}\"", value),
3166 Literal::Char(c) => format!("'{}'", c),
3167 Literal::FormatString(_) => "f\"...\"".to_string(),
3168 Literal::Slice(_) => "[...]".to_string(),
3169 }
3170 }
3171}
3172
3173#[derive(Debug, Clone, PartialEq)]
3174pub enum FormatStringPart {
3175 Text(String),
3176 Expression(Box<Expression>),
3177}
3178
3179#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3180pub enum UnaryOperator {
3181 Negative,
3182 Not,
3183 BitwiseNot,
3184 Deref,
3185}
3186
3187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3188pub enum BinaryOperator {
3189 Addition,
3190 Subtraction,
3191 Multiplication,
3192 Division,
3193 BitwiseAnd,
3194 BitwiseOr,
3195 BitwiseXor,
3196 BitwiseAndNot,
3197 ShiftLeft,
3198 ShiftRight,
3199 LessThan,
3200 LessThanOrEqual,
3201 GreaterThan,
3202 GreaterThanOrEqual,
3203 Remainder,
3204 Equal,
3205 NotEqual,
3206 And,
3207 Or,
3208 Pipeline,
3209}
3210
3211impl BinaryOperator {
3212 pub fn compound_assignment_symbol(&self) -> Option<&'static str> {
3216 match self {
3217 BinaryOperator::Addition => Some("+="),
3218 BinaryOperator::Subtraction => Some("-="),
3219 BinaryOperator::Multiplication => Some("*="),
3220 BinaryOperator::Division => Some("/="),
3221 BinaryOperator::Remainder => Some("%="),
3222 BinaryOperator::BitwiseAnd => Some("&="),
3223 BinaryOperator::BitwiseOr => Some("|="),
3224 BinaryOperator::BitwiseXor => Some("^="),
3225 BinaryOperator::BitwiseAndNot => Some("&^="),
3226 BinaryOperator::ShiftLeft => Some("<<="),
3227 BinaryOperator::ShiftRight => Some(">>="),
3228 _ => None,
3229 }
3230 }
3231
3232 pub fn is_comparison(&self) -> bool {
3233 matches!(
3234 self,
3235 BinaryOperator::Equal
3236 | BinaryOperator::NotEqual
3237 | BinaryOperator::LessThan
3238 | BinaryOperator::LessThanOrEqual
3239 | BinaryOperator::GreaterThan
3240 | BinaryOperator::GreaterThanOrEqual
3241 )
3242 }
3243}
3244
3245impl Display for BinaryOperator {
3246 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3247 let symbol = match self {
3248 BinaryOperator::Addition => "+",
3249 BinaryOperator::Subtraction => "-",
3250 BinaryOperator::Multiplication => "*",
3251 BinaryOperator::Division => "/",
3252 BinaryOperator::Remainder => "%",
3253 BinaryOperator::BitwiseAnd => "&",
3254 BinaryOperator::BitwiseOr => "|",
3255 BinaryOperator::BitwiseXor => "^",
3256 BinaryOperator::BitwiseAndNot => "&^",
3257 BinaryOperator::ShiftLeft => "<<",
3258 BinaryOperator::ShiftRight => ">>",
3259 BinaryOperator::Equal => "==",
3260 BinaryOperator::NotEqual => "!=",
3261 BinaryOperator::LessThan => "<",
3262 BinaryOperator::LessThanOrEqual => "<=",
3263 BinaryOperator::GreaterThan => ">",
3264 BinaryOperator::GreaterThanOrEqual => ">=",
3265 BinaryOperator::And => "&&",
3266 BinaryOperator::Or => "||",
3267 BinaryOperator::Pipeline => "|>",
3268 };
3269 write!(f, "{}", symbol)
3270 }
3271}
3272
3273#[derive(Debug, Clone, PartialEq)]
3274pub struct ParentInterface {
3275 pub annotation: Annotation,
3276 pub ty: Type,
3277 pub span: Span,
3278}
3279
3280#[derive(Debug, Clone, Copy, PartialEq)]
3281#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
3282pub enum Visibility {
3283 Public,
3284 Private,
3285 Local,
3286}
3287
3288impl Visibility {
3289 pub fn is_public(&self) -> bool {
3290 matches!(self, Visibility::Public)
3291 }
3292}
3293
3294#[derive(Debug, Clone, PartialEq)]
3295pub enum ImportAlias {
3296 Named(EcoString, Span),
3297 Blank(Span),
3298}