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