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