1pub mod modules;
6pub mod ns;
7pub mod prelude;
8
9pub use fixed32::Fp;
10use seq_fmt::comma;
11use seq_map::{SeqMap, SeqMapError};
12use seq_set::SeqSet;
13use std::cell::RefCell;
14use std::cmp::PartialEq;
15use std::fmt;
16use std::fmt::{Debug, Display, Formatter};
17use std::hash::Hash;
18use std::rc::Rc;
19use tracing::{error, info};
20
21#[derive(Clone, Eq, PartialEq, Default)]
22pub struct ResolvedNode {
23 pub span: Span,
24}
25
26impl Spanned for ResolvedNode {
27 fn span(&self) -> Span {
28 self.span.clone()
29 }
30}
31
32impl Debug for ResolvedNode {
33 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
34 if self.span.file_id == 0xffff {
35 write!(f, "<{}:{}>", self.span.offset, self.span.length)
36 } else {
37 write!(
38 f,
39 "<{}:{} ({})>",
40 self.span.offset, self.span.length, self.span.file_id
41 )
42 }
43 }
44}
45
46pub type FileId = u16;
47
48#[derive(PartialEq, Eq, Hash, Default, Clone)]
49pub struct Span {
50 pub file_id: FileId,
51 pub offset: u32,
52 pub length: u16,
53}
54
55impl Span {
56 pub fn merge(&self, other: &Span) -> Span {
57 if other.file_id == 0xffff {
58 return self.clone();
59 }
60 if other.file_id == 0 {
61 return self.clone();
62 }
63 if self.file_id == 0xffff {
64 return self.clone();
65 }
66 if self.file_id == 0 {
67 return self.clone();
68 }
69
70 assert_eq!(
71 self.file_id, other.file_id,
72 "file_id must be the same when merging"
73 );
74 if self.offset <= other.offset {
75 let end = other.offset + other.length as u32;
77 let my_end = self.offset + self.length as u32;
78 let final_end = end.max(my_end);
79
80 Span {
81 offset: self.offset,
82 length: (final_end - self.offset) as u16,
83 file_id: self.file_id,
84 }
85 } else {
86 other.merge(self) }
89 }
90
91 pub fn merge_opt<S: Spanned>(&self, other: Option<&S>) -> Span {
92 match other {
93 Some(spanned) => self.merge(&spanned.span()),
94 None => self.clone(),
95 }
96 }
97
98 pub fn merge_spanned<S: Spanned>(&self, other: &S) -> Span {
99 self.merge(&other.span())
100 }
101
102 pub fn merge_opt_span(&self, other: Option<Span>) -> Span {
103 match other {
104 Some(span) => self.merge(&span),
105 None => self.clone(),
106 }
107 }
108
109 pub fn dummy() -> Self {
110 Span {
111 offset: 0,
112 length: 0,
113 file_id: 0xffff,
114 }
115 }
116
117 pub fn end(&self) -> u32 {
119 self.offset + self.length as u32
120 }
121
122 pub fn merge_all<'a, I, S>(iter: I) -> Option<Span>
124 where
125 I: IntoIterator<Item = &'a S>,
126 S: Spanned + 'a,
127 {
128 iter.into_iter()
129 .map(|s| s.span())
130 .reduce(|acc, span| acc.merge(&span))
131 }
132
133 pub fn merge_iter<'a, I, S>(&self, iter: I) -> Span
135 where
136 I: IntoIterator<Item = &'a S>,
137 S: Spanned + 'a,
138 {
139 iter.into_iter()
140 .fold(self.clone(), |acc, item| acc.merge(&item.span()))
141 }
142
143 pub fn merge_opt_iter<'a, I, S>(&self, iter: I) -> Span
145 where
146 I: IntoIterator<Item = &'a Option<S>>,
147 S: Spanned + 'a,
148 {
149 iter.into_iter()
150 .filter_map(|opt| opt.as_ref())
151 .fold(self.clone(), |acc, item| acc.merge(&item.span()))
152 }
153}
154
155impl Debug for Span {
156 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
157 write!(f, "<{}:{} ({})>", self.offset, self.length, self.file_id)
158 }
159}
160
161#[derive(Clone, Eq, PartialEq)]
162pub struct ResolvedParameterNode {
163 pub name: ResolvedNode,
164 pub is_mutable: Option<ResolvedNode>,
165}
166
167impl Debug for ResolvedParameterNode {
168 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
169 write!(f, "ResolvedParameter")
170 }
171}
172
173impl ResolvedParameterNode {
174 #[inline]
175 #[must_use]
176 pub const fn is_mutable(&self) -> bool {
177 self.is_mutable.is_some()
178 }
179}
180
181#[derive(Debug, Clone, Eq, PartialEq)]
182pub struct FunctionTypeSignature {
183 pub first_parameter_is_self: bool,
184 pub parameters: Vec<ResolvedTypeForParameter>,
185 pub return_type: Box<ResolvedType>,
186}
187
188impl Display for FunctionTypeSignature {
189 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
190 write!(f, "({})->{}", comma(&self.parameters), self.return_type)
191 }
192}
193
194impl FunctionTypeSignature {
195 pub fn same_type(&self, other: &FunctionTypeSignature) -> bool {
196 if self.first_parameter_is_self != other.first_parameter_is_self
197 || self.parameters.len() != other.parameters.len()
198 || !self.return_type.same_type(&other.return_type)
199 {
200 return false;
201 }
202
203 for (param, other_param) in self.parameters.iter().zip(other.parameters.clone()) {
204 if !param.resolved_type.same_type(&other_param.resolved_type) {
205 return false;
206 }
207
208 if param.is_mutable != other_param.is_mutable {
209 return false;
210 }
211 }
212
213 true
214 }
215}
216
217#[derive(Debug, Clone, Eq, PartialEq)]
218pub struct ResolvedRustType {
219 pub type_name: String, pub number: u32, }
222
223impl Spanned for ResolvedRustType {
224 fn span(&self) -> Span {
225 Span::dummy()
226 }
227}
228
229pub type ResolvedRustTypeRef = Rc<ResolvedRustType>;
230
231#[derive(Debug, Clone)]
232pub struct LocalTypeName(pub ResolvedNode);
233
234impl Spanned for LocalTypeName {
235 fn span(&self) -> Span {
236 todo!()
237 }
238}
239
240#[derive(Debug, Clone)]
241pub struct ResolvedTypeForParameter {
242 pub name: String,
243 pub resolved_type: ResolvedType,
244 pub is_mutable: bool,
245 pub node: Option<ResolvedParameterNode>,
246}
247
248impl Display for ResolvedTypeForParameter {
249 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
250 write!(
251 f,
252 "{}{}: {}",
253 if self.is_mutable { "mut " } else { "" },
254 self.name,
255 self.resolved_type
256 )
257 }
258}
259
260impl Eq for ResolvedTypeForParameter {}
261
262impl PartialEq for ResolvedTypeForParameter {
263 fn eq(&self, other: &Self) -> bool {
264 self.resolved_type.same_type(&other.resolved_type) && self.is_mutable == other.is_mutable
266 }
267}
268
269#[derive(Clone, Eq, PartialEq)]
270pub enum ResolvedType {
271 Int,
273 Float,
274 String,
275 Bool,
276 Unit,
277
278 Array(ResolvedArrayTypeRef),
280 Tuple(ResolvedTupleTypeRef),
281 Struct(ResolvedStructTypeRef),
282 Map(ResolvedMapTypeRef),
283
284 Enum(ResolvedEnumTypeRef),
285 Generic(Box<ResolvedType>, Vec<ResolvedType>),
287
288 Function(FunctionTypeSignature),
289 Iterable(Box<ResolvedType>),
290
291 Optional(Box<ResolvedType>),
292 RustType(ResolvedRustTypeRef),
293
294 Any,
295}
296
297impl Debug for ResolvedType {
298 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
299 match self {
300 Self::Int => write!(f, "Int"),
301 Self::Float => write!(f, "Float"),
302 Self::String => write!(f, "String"),
303 Self::Bool => write!(f, "Bool"),
304 Self::Unit => write!(f, "()"),
305 Self::Array(array_type_ref) => write!(f, "[{:?}]", array_type_ref.item_type),
306 Self::Tuple(tuple_type_ref) => write!(f, "( {:?} )", tuple_type_ref.0),
307 Self::Struct(struct_type_ref) => {
308 write!(f, "{}", struct_type_ref.borrow().assigned_name)
309 }
310 Self::Map(map_type_ref) => write!(
311 f,
312 "[{:?}:{:?}]",
313 map_type_ref.key_type, map_type_ref.value_type
314 ),
315 Self::Generic(base, parameters) => write!(f, "{:?}<{:?}>", base, parameters),
316 Self::Enum(enum_type_ref) => write!(f, "{:?}", enum_type_ref.borrow().assigned_name),
317 Self::Function(function_type_signature) => {
321 write!(f, "{:?}", function_type_signature)
322 }
323 Self::Iterable(type_generated) => write!(f, "Iterable<{type_generated:?}>"),
324 Self::Optional(base_type) => write!(f, "{:?}?", base_type),
325 Self::RustType(rust_type) => write!(f, "{:?}?", rust_type.type_name),
326 Self::Any => write!(f, "Any"),
327 }
328 }
329}
330
331impl Display for ResolvedType {
332 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
333 match self {
334 Self::Int => write!(f, "Int"),
335 Self::Float => write!(f, "Float"),
336 Self::String => write!(f, "String"),
337 Self::Bool => write!(f, "Bool"),
338 Self::Unit => write!(f, "()"),
339 Self::Array(array_ref) => write!(f, "[{}]", &array_ref.item_type.to_string()),
340 Self::Tuple(tuple) => write!(f, "({})", comma(&tuple.0)),
341 Self::Struct(struct_ref) => write!(f, "{}", struct_ref.borrow().assigned_name),
342 Self::Map(map_ref) => write!(f, "[{}:{}]", map_ref.key_type, map_ref.value_type),
343 Self::Generic(base_type, params) => write!(f, "{base_type}<{}>", comma(params)),
344 Self::Enum(enum_type) => write!(f, "{}", enum_type.borrow().assigned_name),
345 Self::Function(signature) => write!(f, "function {signature}"),
351 Self::Iterable(generating_type) => write!(f, "Iterable<{generating_type}>"),
352 Self::Optional(base_type) => write!(f, "{base_type}?"),
353 Self::RustType(rust_type) => write!(f, "RustType {}", rust_type.type_name),
354 Self::Any => write!(f, "ANY"),
355 }
356 }
357}
358
359impl Spanned for ResolvedType {
360 fn span(&self) -> Span {
361 match self {
362 Self::Int => Span::dummy(),
364 Self::Float => Span::dummy(),
365 Self::String => Span::dummy(),
366 Self::Bool => Span::dummy(),
367 Self::Unit => todo!(),
368
369 Self::Array(type_ref) => type_ref.item_type.span(),
371 Self::Tuple(tuple_ref) => tuple_ref.0[0].span(),
372 Self::Struct(type_ref) => type_ref.borrow().name.span.clone(),
373 Self::Map(type_ref) => type_ref.key_type.span(),
374
375 Self::Generic(base_type, type_params) => base_type.span().merge_iter(type_params),
377
378 Self::Enum(_type_ref) => todo!(),
380 Self::Function(_signature) => todo!(),
384
385 Self::Iterable(_type_ref) => todo!(),
387
388 Self::Optional(inner_type) => inner_type.span(),
390
391 Self::RustType(type_ref) => type_ref.span(),
393
394 Self::Any => Span::dummy(),
396 }
397 }
398}
399
400#[derive(Debug)]
401pub enum SemanticError {
402 CouldNotInsertStruct,
403 DuplicateTypeAlias(String),
404 CanOnlyUseStructForMemberFunctions,
405 ResolveNotStruct,
406 DuplicateStructName(String),
407 DuplicateEnumType(String),
408 DuplicateEnumVariantType(String, String),
409 DuplicateFieldName(String),
410 DuplicateExternalFunction(String),
411 DuplicateRustType(String),
412 DuplicateConstName(String),
413 CircularConstantDependency(Vec<ConstantId>),
414 DuplicateConstantId(ConstantId),
415 IncompatibleTypes,
416}
417
418impl ResolvedType {
419 pub fn expect_struct_type(&self) -> Result<ResolvedStructTypeRef, SemanticError> {
420 match self {
421 ResolvedType::Struct(struct_type_ref) => Ok(struct_type_ref.clone()),
422 _ => Err(SemanticError::ResolveNotStruct),
423 }
424 }
425
426 pub fn assignable_type(&self, other: &ResolvedType) -> bool {
427 if self.same_type(other) {
428 true
429 } else if let Self::Optional(inner_type) = self {
430 inner_type.same_type(other)
431 } else {
432 false
433 }
434 }
435 pub fn same_type(&self, other: &ResolvedType) -> bool {
436 match (self, other) {
437 (Self::Any, _) => true,
438 (_, Self::Any) => true,
439 (Self::Function(a), Self::Function(b)) => a.same_type(b),
440 (Self::Int, Self::Int) => true,
441 (Self::Float, Self::Float) => true,
442 (Self::String, Self::String) => true,
443 (Self::Bool, Self::Bool) => true,
444 (Self::Unit, Self::Unit) => true,
445 (Self::Array(_), Self::Array(_)) => true,
446 (Self::Map(a), Self::Map(b)) => {
447 a.key_type.same_type(&b.key_type) && a.value_type.same_type(&b.value_type)
448 }
449 (Self::Struct(a), Self::Struct(b)) => compare_struct_types(a, b),
450 (Self::Tuple(a), Self::Tuple(b)) => {
451 if a.0.len() != b.0.len() {
452 return false;
453 }
454 a.0.iter().zip(b.0.iter()).all(|(a, b)| a.same_type(b))
455 }
456 (Self::Enum(_), Self::Enum(_)) => true,
457 (Self::Iterable(a), Self::Iterable(b)) => a.same_type(b),
458 (Self::Optional(inner_type_a), Self::Optional(inner_type_b)) => {
460 inner_type_a.same_type(inner_type_b)
461 }
462 (Self::RustType(type_ref_a), Self::RustType(type_ref_b)) => {
463 type_ref_a.number == type_ref_b.number
464 }
465
466 (Self::Generic(base_a, params_a), Self::Generic(base_b, params_b)) => {
467 if !base_a.same_type(base_b) {
468 return false;
469 }
470
471 if params_a.len() != params_b.len() {
472 return false;
473 }
474
475 for (param_a, param_b) in params_a.iter().zip(params_b) {
476 if !param_a.same_type(param_b) {
477 return false;
478 }
479 }
480 true
481 }
482 _ => false,
483 }
484 }
485}
486
487fn compare_struct_types(a: &ResolvedStructTypeRef, b: &ResolvedStructTypeRef) -> bool {
488 let a_borrow = a.borrow();
489 let b_borrow = b.borrow();
490 if a_borrow.assigned_name != b_borrow.assigned_name {
491 return false;
492 }
493
494 if a_borrow.anon_struct_type.defined_fields.len()
495 != b_borrow.anon_struct_type.defined_fields.len()
496 {
497 return false;
498 }
499
500 for ((a_name, a_type), (b_name, b_type)) in a_borrow
501 .anon_struct_type
502 .defined_fields
503 .iter()
504 .zip(b_borrow.anon_struct_type.defined_fields.clone())
505 {
506 if *a_name != b_name {
507 return false;
508 }
509
510 if !a_type.field_type.same_type(&b_type.field_type) {
511 return false;
512 }
513 }
514
515 true
516}
517
518impl ResolvedNode {
519 pub fn new_unknown() -> Self {
520 Self {
521 span: Span {
522 file_id: 0xffff,
523 offset: 0,
524 length: 0,
525 },
526 }
527 }
528}
529
530#[derive(Debug, Eq, PartialEq)]
531pub struct ResolvedLocalIdentifier(pub ResolvedNode);
532
533pub struct ResolvedInternalFunctionDefinition {
535 pub body: ResolvedExpression,
536 pub name: ResolvedLocalIdentifier,
537 pub signature: FunctionTypeSignature,
538}
539
540impl Debug for ResolvedInternalFunctionDefinition {
541 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
542 write!(f, "{:?}\n{:?}", self.signature, self.body)
543 }
544}
545
546impl PartialEq<Self> for ResolvedInternalFunctionDefinition {
547 fn eq(&self, other: &Self) -> bool {
548 self.name == other.name
549 }
550}
551
552impl Eq for ResolvedInternalFunctionDefinition {}
553
554impl Spanned for ResolvedInternalFunctionDefinition {
555 fn span(&self) -> Span {
556 self.name.0.span.clone()
557 }
558}
559
560pub type ResolvedInternalFunctionDefinitionRef = Rc<ResolvedInternalFunctionDefinition>;
561
562pub type ExternalFunctionId = u32;
563
564pub type ConstantId = u32;
565
566pub struct ResolvedExternalFunctionDefinition {
567 pub name: Option<ResolvedNode>,
568 pub assigned_name: String,
569 pub signature: FunctionTypeSignature,
570 pub id: ExternalFunctionId,
571}
572
573impl PartialEq<Self> for ResolvedExternalFunctionDefinition {
574 fn eq(&self, other: &Self) -> bool {
575 self.id == other.id
576 }
577}
578
579impl Eq for ResolvedExternalFunctionDefinition {}
580
581impl Debug for ResolvedExternalFunctionDefinition {
582 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
583 write!(f, "external fn")
584 }
585}
586
587impl Spanned for ResolvedExternalFunctionDefinition {
588 fn span(&self) -> Span {
589 Span::default()
590 }
591}
592
593pub type ResolvedExternalFunctionDefinitionRef = Rc<crate::ResolvedExternalFunctionDefinition>;
594
595#[derive(Debug)]
596pub struct ResolvedVariable {
597 pub name: ResolvedNode,
598 pub resolved_type: ResolvedType,
599 pub mutable_node: Option<ResolvedNode>,
600
601 pub scope_index: usize,
602 pub variable_index: usize,
603}
604
605impl Spanned for ResolvedVariable {
606 fn span(&self) -> Span {
607 self.name.span.merge_opt(self.mutable_node.as_ref())
608 }
609}
610
611impl ResolvedVariable {
612 #[must_use]
613 pub const fn is_mutable(&self) -> bool {
614 self.mutable_node.is_some()
615 }
616}
617
618pub type ResolvedVariableRef = Rc<ResolvedVariable>;
619
620#[derive(Debug)]
621pub struct ResolvedMutVariable {
622 pub variable_ref: ResolvedVariableRef,
623}
624impl Spanned for ResolvedMutVariable {
625 fn span(&self) -> Span {
626 self.variable_ref.span()
627 }
628}
629
630type ResolvedMutVariableRef = Rc<ResolvedMutVariable>;
631
632#[derive(Debug)]
633pub enum ResolvedBinaryOperatorKind {
634 Add,
635 Subtract,
636 Multiply,
637 Divide,
638 Modulo,
639 LogicalOr,
640 LogicalAnd,
641 Equal,
642 NotEqual,
643 LessThan,
644 LessEqual,
645 GreaterThan,
646 GreaterEqual,
647 RangeExclusive,
648}
649
650#[derive(Debug)]
651pub struct ResolvedBinaryOperator {
652 pub left: Box<ResolvedExpression>,
653 pub right: Box<ResolvedExpression>,
654 pub kind: ResolvedBinaryOperatorKind,
655 pub node: ResolvedNode,
656 pub resolved_type: ResolvedType,
657}
658
659impl Spanned for ResolvedBinaryOperator {
660 fn span(&self) -> Span {
661 self.node.span.clone()
662 }
663}
664
665#[derive(Debug)]
666pub enum ResolvedUnaryOperatorKind {
667 Not,
668 Negate,
669}
670#[derive(Debug)]
671pub struct ResolvedUnaryOperator {
672 pub left: Box<ResolvedExpression>,
673 pub kind: ResolvedUnaryOperatorKind,
674 pub resolved_type: ResolvedType,
675 pub node: ResolvedNode,
676}
677
678impl Spanned for ResolvedUnaryOperator {
679 fn span(&self) -> Span {
680 self.node.span.clone()
681 }
682}
683
684#[derive(Debug)]
685pub enum ResolvedPostfixOperatorKind {
686 Unwrap,
687}
688#[derive(Debug)]
689pub struct ResolvedPostfixOperator {
690 pub left: Box<ResolvedExpression>,
691 pub kind: ResolvedPostfixOperatorKind,
692 pub resolved_type: ResolvedType,
693 pub node: ResolvedNode,
694}
695
696impl Spanned for ResolvedPostfixOperator {
697 fn span(&self) -> Span {
698 self.node.span.clone()
699 }
700}
701
702#[derive()]
703pub struct ResolvedInternalFunctionCall {
704 pub arguments: Vec<ResolvedExpression>,
705
706 pub function_definition: ResolvedInternalFunctionDefinitionRef,
707 pub function_expression: Box<ResolvedExpression>,
708}
709
710impl Debug for ResolvedInternalFunctionCall {
711 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
712 write!(
713 f,
714 "InFuncCall({:?} {:?})",
715 self.function_expression, self.arguments
716 )
717 }
718}
719
720#[derive(Debug)]
721pub struct ResolvedStaticCall {
722 pub function: Rc<ResolvedFunction>,
723 pub arguments: Vec<ResolvedExpression>,
724}
725
726impl Spanned for ResolvedStaticCall {
727 fn span(&self) -> Span {
728 self.function.span()
729 }
730}
731
732#[derive(Debug)]
733pub struct ResolvedExternalFunctionCall {
734 pub arguments: Vec<ResolvedExpression>,
735 pub function_definition: ResolvedExternalFunctionDefinitionRef,
736 pub function_expression: Box<ResolvedExpression>,
737}
738
739#[must_use]
740pub fn comma_seq<K: Clone + Hash + Eq + Display, V: Display>(values: &SeqMap<K, V>) -> String {
741 let mut result = String::new();
742 for (i, (key, value)) in values.iter().enumerate() {
743 if i > 0 {
744 result.push_str(", ");
745 }
746 result.push_str(format!("{key}: {value}").as_str());
747 }
748 result
749}
750
751pub fn comma_seq_nl<K: Clone + Hash + Eq + Display, V: Display>(
752 values: &SeqMap<K, V>,
753 prefix: &str,
754) -> String {
755 let mut result = String::new();
756 for (key, value) in values.iter() {
757 result.push_str(format!("{}{}: {}\n", prefix, key, value).as_str());
758 }
759 result
760}
761
762pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
763 let mut result = String::new();
764 for (i, (key, value)) in values.iter().enumerate() {
765 if i > 0 {
766 result.push_str(", ");
767 }
768 result.push_str(format!("{}: {}", key, value).as_str());
769 }
770 result
771}
772
773#[derive(Debug)]
774pub struct ResolvedMemberCall {
775 pub function: ResolvedFunctionRef,
776 pub arguments: Vec<ResolvedExpression>,
777 pub self_expression: Box<ResolvedExpression>,
778 pub self_is_mutable: bool,
779}
780
781#[derive(Debug)]
782pub enum ResolvedAccess {
783 FieldIndex(ResolvedNode, usize),
784 ArrayIndex(ResolvedExpression),
785 MapIndex(ResolvedExpression),
786}
787
788impl Spanned for ResolvedAccess {
789 fn span(&self) -> Span {
790 match self {
791 Self::FieldIndex(node, _) => node.span.clone(),
792 Self::ArrayIndex(expr) => expr.span(),
793 Self::MapIndex(expr) => expr.span(),
794 }
795 }
796}
797
798pub type ResolvedMutStructTypeFieldRef = Rc<ResolvedMutStructTypeField>;
799#[derive(Debug)]
800pub struct ResolvedMutStructTypeField {
801 pub inner: ResolvedStructTypeFieldRef,
802}
803
804pub type ResolvedMutTupleFieldRef = Rc<ResolvedMutTupleField>;
805
806#[derive(Debug)]
807pub struct ResolvedStructTypeField {
808 pub struct_type_ref: ResolvedStructTypeRef,
809 pub field_name: ResolvedLocalIdentifier,
810 pub resolved_type: ResolvedType,
811 pub index: usize,
812}
813
814impl Spanned for ResolvedStructTypeField {
815 fn span(&self) -> Span {
816 self.field_name.0.span.merge_spanned(&self.resolved_type)
817 }
818}
819
820#[derive(Debug, Clone, Eq, PartialEq)]
821pub struct ResolvedAnonymousStructFieldType {
822 pub identifier: Option<ResolvedNode>,
823
824 pub field_type: ResolvedType,
825}
826
827pub type ResolvedStructTypeFieldRef = Rc<ResolvedStructTypeField>;
828
829pub type ResolvedArrayRef = Rc<ResolvedArray>;
830
831#[derive(Debug)]
832pub struct ResolvedArray {}
833#[derive(Debug)]
834pub struct ResolvedMutArray {
835 pub expression: Box<ResolvedExpression>,
836 pub array_type_ref: ResolvedArrayTypeRef,
837}
838
839#[derive(Debug)]
840pub struct ResolvedMutMap {
841 pub expression: Box<ResolvedExpression>,
842 pub map_type_ref: ResolvedMapTypeRef,
843}
844
845#[derive(Debug)]
846pub struct ResolvedMapIndexLookup {
847 pub map_type: ResolvedType,
848 pub item_type: ResolvedType,
849 pub map_type_ref: ResolvedMapTypeRef,
850 pub index_expression: Box<ResolvedExpression>,
851 pub map_expression: Box<ResolvedExpression>,
852}
853
854impl Spanned for ResolvedMapIndexLookup {
855 fn span(&self) -> Span {
856 todo!()
857 }
858}
859
860#[derive(Debug)]
861pub struct ResolvedArrayItem {
862 pub item_type: ResolvedType,
863 pub int_expression: ResolvedExpression,
864 pub array_expression: ResolvedExpression,
865 pub array_type: ResolvedType,
866}
867
868impl Spanned for ResolvedArrayItem {
869 fn span(&self) -> Span {
870 todo!()
871 }
872}
873
874pub type ResolvedArrayItemRef = Rc<ResolvedArrayItem>;
875
876#[derive(Debug)]
877pub struct ResolvedIndexType {
878 pub expression: Box<ResolvedExpression>,
879 pub resolved_type: ResolvedType,
880}
881
882#[derive(Debug)]
883pub enum ResolvedPrecisionType {
884 Float,
885 String,
886}
887
888#[derive(Debug)]
889pub enum ResolvedFormatSpecifierKind {
890 LowerHex, UpperHex, Binary, Float, Precision(u32, ResolvedNode, ResolvedPrecisionType), }
896
897#[derive(Debug)]
898pub struct ResolvedFormatSpecifier {
899 pub node: ResolvedNode,
900 pub kind: ResolvedFormatSpecifierKind,
901}
902
903#[derive(Debug)]
904pub enum ResolvedStringPart {
905 Literal(ResolvedNode, String),
906 Interpolation(ResolvedExpression, Option<ResolvedFormatSpecifier>),
907}
908
909impl Spanned for ResolvedStringPart {
910 fn span(&self) -> Span {
911 match self {
912 Self::Literal(node, _) => node.span.clone(),
913 Self::Interpolation(expr, _) => expr.span(),
914 }
915 }
916}
917
918#[derive(Debug)]
919pub struct ResolvedMutTupleField {
920 #[allow(unused)]
921 ast: ResolvedExpression,
922}
923
924pub type ResolvedFunctionRef = Rc<ResolvedFunction>;
925
926#[derive(Debug, Eq, PartialEq)]
927pub enum ResolvedFunction {
928 Internal(ResolvedInternalFunctionDefinitionRef),
929 External(ResolvedExternalFunctionDefinitionRef),
930}
931
932impl ResolvedFunction {
933 pub fn name(&self) -> Option<&ResolvedNode> {
934 match self {
935 Self::Internal(x) => Some(&x.name.0),
936 Self::External(y) => y.name.as_ref(),
937 }
938 }
939
940 #[must_use]
941 pub fn signature(&self) -> &FunctionTypeSignature {
942 match self {
943 Self::Internal(internal) => &internal.signature,
944 Self::External(external) => &external.signature,
945 }
946 }
947}
948
949impl Spanned for ResolvedFunction {
950 fn span(&self) -> Span {
951 match self {
952 Self::Internal(def) => def.span(),
953 Self::External(def) => def.span(),
954 }
955 }
956}
957
958pub type MutMemberRef = Rc<MutMember>;
959
960#[derive(Debug)]
961pub struct MutMember {
962 #[allow(unused)]
963 expression: ResolvedExpression,
964}
965
966pub type MemberRef = Rc<Member>;
967
968#[derive(Debug)]
969pub struct Member {
970 #[allow(unused)]
971 expression: ResolvedExpression,
972}
973
974#[derive(Debug)]
975pub struct ResolvedBooleanExpression {
976 #[allow(unused)]
977 pub expression: Box<ResolvedExpression>,
978}
979
980#[derive(Debug)]
981pub struct ResolvedMatch {
982 pub arms: Vec<ResolvedMatchArm>,
983 pub expression: Box<ResolvedExpression>,
984}
985
986#[derive(Debug)]
987pub struct ResolvedMatchArm {
988 #[allow(unused)]
989 pub pattern: ResolvedPattern,
990 pub expression: Box<ResolvedExpression>,
991 pub expression_type: ResolvedType,
992}
993
994#[derive(Debug)]
995pub enum ResolvedPattern {
996 Normal(ResolvedNormalPattern, Option<ResolvedBooleanExpression>),
997 Wildcard(ResolvedNode),
998}
999
1000#[derive(Debug)]
1001pub enum ResolvedNormalPattern {
1002 PatternList(Vec<ResolvedPatternElement>),
1003 EnumPattern(
1004 ResolvedEnumVariantTypeRef,
1005 Option<Vec<ResolvedPatternElement>>,
1006 ),
1007 Literal(ResolvedLiteral),
1008}
1009
1010#[derive(Debug)]
1011pub enum ResolvedPatternElement {
1012 Variable(ResolvedVariableRef),
1013 VariableWithFieldIndex(ResolvedVariableRef, usize),
1014 Wildcard(ResolvedNode),
1015}
1016
1017#[derive(Debug)]
1018pub struct ResolvedIterator {
1019 pub key_type: Option<ResolvedType>, pub value_type: ResolvedType,
1021 pub resolved_expression: Box<ResolvedExpression>,
1022}
1023
1024#[derive(Debug)]
1025pub struct ResolvedStructInstantiation {
1026 pub source_order_expressions: Vec<(usize, ResolvedExpression)>,
1027 pub struct_type_ref: ResolvedStructTypeRef,
1028}
1029
1030#[derive(Debug)]
1031pub struct ResolvedVariableAssignment {
1032 pub variable_refs: ResolvedVariableRef,
1033 pub expression: Box<ResolvedExpression>,
1034}
1035impl Spanned for ResolvedVariableAssignment {
1036 fn span(&self) -> Span {
1037 self.variable_refs.span()
1038 }
1039}
1040
1041#[derive(Debug)]
1042pub enum ResolvedCompoundOperatorKind {
1043 Add,
1044 Sub,
1045 Mul,
1046 Div,
1047 Modulo,
1048}
1049
1050#[derive(Debug)]
1051pub struct ResolvedCompoundOperator {
1052 pub node: ResolvedNode,
1053 pub kind: ResolvedCompoundOperatorKind,
1054}
1055
1056impl Spanned for ResolvedCompoundOperator {
1057 fn span(&self) -> Span {
1058 self.node.span.clone()
1059 }
1060}
1061
1062#[derive(Debug)]
1063pub struct ResolvedVariableCompoundAssignment {
1064 pub variable_ref: ResolvedVariableRef, pub expression: Box<ResolvedExpression>,
1066 pub compound_operator: ResolvedCompoundOperator,
1067}
1068
1069impl Spanned for ResolvedVariableCompoundAssignment {
1070 fn span(&self) -> Span {
1071 todo!()
1072 }
1073}
1074
1075pub fn create_rust_type(name: &str, type_number: TypeNumber) -> ResolvedRustTypeRef {
1076 let rust_type = ResolvedRustType {
1077 type_name: name.to_string(),
1078 number: type_number,
1079 };
1080 Rc::new(rust_type)
1081}
1082
1083#[derive(Debug)]
1084pub struct ResolvedGuard {
1085 pub condition: ResolvedBooleanExpression,
1086 pub result: ResolvedExpression,
1087}
1088
1089#[derive(Debug, Clone, Eq, PartialEq)]
1090pub enum ResolvedRangeMode {
1091 Inclusive,
1092 Exclusive,
1093}
1094
1095#[derive(Debug)]
1096pub enum ResolvedExpression {
1097 VariableAccess(ResolvedVariableRef),
1099 ConstantAccess(ResolvedConstantRef),
1100 FieldAccess(
1101 Box<ResolvedExpression>,
1102 ResolvedStructTypeFieldRef,
1103 Vec<ResolvedAccess>,
1104 ),
1105
1106 ArrayAccess(
1107 Box<ResolvedExpression>,
1108 ResolvedArrayTypeRef,
1109 Vec<ResolvedAccess>,
1110 ), MapIndexAccess(ResolvedMapIndexLookup),
1113 MapRemove(
1114 Box<ResolvedExpression>,
1115 Box<ResolvedExpression>,
1116 ResolvedMapTypeRef,
1117 ),
1118 MapHas(Box<ResolvedExpression>, Box<ResolvedExpression>),
1119
1120 InternalFunctionAccess(ResolvedInternalFunctionDefinitionRef),
1121
1122 ExternalFunctionAccess(ResolvedExternalFunctionDefinitionRef),
1123
1124 MutVariableRef(ResolvedMutVariableRef), MutStructFieldRef(Box<ResolvedExpression>, ResolvedType, Vec<ResolvedAccess>),
1127 MutArrayIndexRef(
1128 Box<ResolvedExpression>,
1129 ResolvedArrayTypeRef,
1130 Vec<ResolvedAccess>,
1131 ),
1132 MutMapIndexRef(
1133 Box<ResolvedExpression>,
1134 ResolvedMapTypeRef,
1135 Box<ResolvedExpression>,
1136 ),
1137 MutRustTypeIndexRef(
1138 Box<ResolvedExpression>,
1139 ResolvedRustTypeRef,
1140 ResolvedType,
1141 Box<ResolvedExpression>,
1142 ),
1143
1144 Option(Option<Box<ResolvedExpression>>),
1145 NoneCoalesceOperator(Box<ResolvedExpression>, Box<ResolvedExpression>),
1146
1147 InitializeVariable(ResolvedVariableAssignment), ReassignVariable(ResolvedVariableAssignment), VariableCompoundAssignment(ResolvedVariableCompoundAssignment),
1153
1154 ArrayExtend(ResolvedVariableRef, Box<ResolvedExpression>), ArrayPush(ResolvedVariableRef, Box<ResolvedExpression>), ArrayAssignment(ResolvedMutArray, ResolvedIndexType, Box<ResolvedExpression>), MapAssignment(ResolvedMutMap, ResolvedIndexType, Box<ResolvedExpression>),
1161 StructFieldAssignment(
1162 Box<ResolvedExpression>,
1163 Vec<ResolvedAccess>,
1164 Box<ResolvedExpression>,
1165 ),
1166
1167 FieldCompoundAssignment(
1168 Box<ResolvedExpression>,
1169 Vec<ResolvedAccess>,
1170 ResolvedCompoundOperator,
1171 Box<ResolvedExpression>,
1172 ),
1173
1174 BinaryOp(ResolvedBinaryOperator),
1176 UnaryOp(ResolvedUnaryOperator),
1177 PostfixOp(ResolvedPostfixOperator),
1178
1179 CoerceOptionToBool(Box<ResolvedExpression>),
1180
1181 FunctionCall(
1185 FunctionTypeSignature,
1186 Box<ResolvedExpression>,
1187 Vec<ResolvedExpression>,
1188 ),
1189
1190 StaticCall(ResolvedStaticCall),
1191 StaticCallGeneric(ResolvedStaticCallGeneric),
1192
1193 FunctionInternalCall(ResolvedInternalFunctionCall),
1194 FunctionExternalCall(ResolvedExternalFunctionCall),
1195
1196 MemberCall(ResolvedMemberCall),
1197 InterpolatedString(Vec<ResolvedStringPart>),
1198
1199 StructInstantiation(ResolvedStructInstantiation),
1201 Array(ResolvedArrayInstantiation),
1202 Tuple(Vec<ResolvedExpression>),
1203 Literal(ResolvedLiteral),
1204 ExclusiveRange(Box<ResolvedExpression>, Box<ResolvedExpression>),
1205
1206 InclusiveRange(Box<ResolvedExpression>, Box<ResolvedExpression>),
1207
1208 IfElseOnlyVariable {
1210 variable: ResolvedVariableRef,
1211 optional_expr: Box<ResolvedExpression>,
1212 true_block: Box<ResolvedExpression>,
1213 false_block: Box<ResolvedExpression>,
1214 },
1215
1216 IfElseAssignExpression {
1217 variable: ResolvedVariableRef,
1218 optional_expr: Box<ResolvedExpression>,
1219 true_block: Box<ResolvedExpression>,
1220 false_block: Box<ResolvedExpression>,
1221 },
1222
1223 Match(ResolvedMatch),
1224 Guard(
1225 Vec<ResolvedGuard>,
1226 Option<Box<ResolvedExpression>>,
1227 ResolvedType,
1228 ),
1229 LetVar(ResolvedVariableRef, Box<ResolvedExpression>),
1230 ArrayRemoveIndex(ResolvedVariableRef, Box<ResolvedExpression>),
1231 ArrayClear(ResolvedVariableRef),
1232
1233 IntAbs(Box<ResolvedExpression>),
1235 IntRnd(Box<ResolvedExpression>),
1236 IntToFloat(Box<ResolvedExpression>),
1237 IntClamp(
1238 Box<ResolvedExpression>,
1239 Box<ResolvedExpression>,
1240 Box<ResolvedExpression>,
1241 ),
1242 IntMin(Box<ResolvedExpression>, Box<ResolvedExpression>),
1243 IntMax(Box<ResolvedExpression>, Box<ResolvedExpression>),
1244
1245 FloatRound(Box<ResolvedExpression>),
1247 FloatFloor(Box<ResolvedExpression>),
1248 FloatSign(Box<ResolvedExpression>),
1249 FloatAbs(Box<ResolvedExpression>),
1250 FloatRnd(Box<ResolvedExpression>),
1251 FloatCos(Box<ResolvedExpression>),
1252 FloatSin(Box<ResolvedExpression>),
1253 FloatAcos(Box<ResolvedExpression>),
1254 FloatAsin(Box<ResolvedExpression>),
1255 FloatAtan2(Box<ResolvedExpression>, Box<ResolvedExpression>),
1256 FloatSqrt(Box<ResolvedExpression>),
1257 FloatClamp(
1258 Box<ResolvedExpression>,
1259 Box<ResolvedExpression>,
1260 Box<ResolvedExpression>,
1261 ),
1262 FloatMin(Box<ResolvedExpression>, Box<ResolvedExpression>),
1263 FloatMax(Box<ResolvedExpression>, Box<ResolvedExpression>),
1264
1265 StringLen(Box<ResolvedExpression>),
1267
1268 Tuple2FloatMagnitude(Box<ResolvedExpression>),
1270
1271 SparseAdd(
1274 Box<ResolvedExpression>,
1275 Box<ResolvedExpression>,
1276 ResolvedType,
1277 ),
1278 SparseRemove(
1279 Box<ResolvedExpression>,
1280 Box<ResolvedExpression>,
1281 ResolvedType,
1282 ),
1283 SparseNew(Span, ResolvedRustTypeRef, ResolvedType, ResolvedType),
1284 SparseAccess(
1285 Box<ResolvedExpression>,
1286 Box<ResolvedExpression>,
1287 ResolvedType,
1288 ),
1289
1290 ForLoop(
1291 ResolvedForPattern,
1292 ResolvedIterator,
1293 Box<ResolvedExpression>,
1294 ),
1295 WhileLoop(ResolvedBooleanExpression, Box<ResolvedExpression>),
1296 Return(Option<Box<ResolvedExpression>>),
1297 Break(ResolvedNode),
1298 Continue(ResolvedNode), Block(Vec<ResolvedExpression>),
1300 If(
1301 ResolvedBooleanExpression,
1302 Box<ResolvedExpression>,
1303 Option<Box<ResolvedExpression>>,
1304 ),
1305
1306 IfOnlyVariable {
1308 variable: ResolvedVariableRef,
1309 optional_expr: Box<ResolvedExpression>,
1310 true_block: Box<ResolvedExpression>,
1311 false_block: Option<Box<ResolvedExpression>>,
1312 },
1313 IfAssignExpression {
1314 variable: ResolvedVariableRef,
1315 optional_expr: Box<ResolvedExpression>,
1316 true_block: Box<ResolvedExpression>,
1317 false_block: Option<Box<ResolvedExpression>>,
1318 },
1319
1320 TupleDestructuring(
1321 Vec<ResolvedVariableRef>,
1322 ResolvedTupleTypeRef,
1323 Box<ResolvedExpression>,
1324 ),
1325 ArrayRangeAccess(
1326 Box<ResolvedExpression>,
1327 ResolvedArrayTypeRef,
1328 Box<ResolvedExpression>,
1329 Box<ResolvedExpression>,
1330 ResolvedRangeMode,
1331 ),
1332 StringRangeAccess(
1333 Box<ResolvedExpression>,
1334 Box<ResolvedExpression>,
1335 Box<ResolvedExpression>,
1336 ResolvedRangeMode,
1337 ),
1338 AssignArrayRange(
1339 Box<ResolvedExpression>,
1340 ResolvedArrayTypeRef,
1341 Box<ResolvedExpression>,
1342 Box<ResolvedExpression>,
1343 ResolvedRangeMode,
1344 Box<ResolvedExpression>,
1345 ),
1346 AssignStringRange(
1347 Box<ResolvedExpression>,
1348 Box<ResolvedExpression>,
1349 Box<ResolvedExpression>,
1350 ResolvedRangeMode,
1351 Box<ResolvedExpression>,
1352 ),
1353}
1354
1355impl ResolvedExpression {
1356 #[must_use]
1357 pub fn is_coerce_to_mutable(&self) -> bool {
1358 info!(?self, "checking mutable");
1359 match self {
1360 Self::VariableAccess(var_access) => var_access.is_mutable(),
1361 Self::FieldAccess(expr, ..) => expr.is_coerce_to_mutable(),
1362 _ => matches!(
1363 self,
1364 Self::MutArrayIndexRef(_, _, _)
1365 | Self::MutVariableRef(_)
1366 | Self::MutStructFieldRef(_, _, _)
1367 | Self::MutMapIndexRef(_, _, _),
1368 ),
1369 }
1370 }
1371
1372 #[allow(clippy::too_many_lines)]
1373 pub fn collect_constant_dependencies(&self, deps: &mut SeqSet<ConstantId>) {
1374 match self {
1375 Self::ConstantAccess(const_ref) => {
1376 deps.insert(const_ref.id);
1377 }
1378 Self::FieldAccess(expr, _, _accesses) => {
1379 expr.collect_constant_dependencies(deps);
1380 }
1381 Self::ArrayAccess(expr, _, _accesses) => {
1382 expr.collect_constant_dependencies(deps);
1383 }
1384 Self::ArrayRangeAccess(base_expr, _, min_expr, max_expr, _mode) => {
1385 base_expr.collect_constant_dependencies(deps);
1386 min_expr.collect_constant_dependencies(deps);
1387 max_expr.collect_constant_dependencies(deps);
1388 }
1389 Self::StringRangeAccess(base_expr, min_expr, max_expr, _mode) => {
1390 base_expr.collect_constant_dependencies(deps);
1391 min_expr.collect_constant_dependencies(deps);
1392 max_expr.collect_constant_dependencies(deps);
1393 }
1394 Self::MapIndexAccess(map_index) => {
1395 map_index.map_expression.collect_constant_dependencies(deps);
1396 }
1397 Self::InternalFunctionAccess(_func_def_ref) => {}
1398 Self::ExternalFunctionAccess(_func_def_ref) => {}
1399 Self::MutVariableRef(_mut_var_ref) => {}
1400 Self::MutStructFieldRef(expr, _, _accesses) => {
1401 expr.collect_constant_dependencies(deps);
1402 }
1403 Self::MutArrayIndexRef(expr, _resolved_type, _accesses) => {
1404 expr.collect_constant_dependencies(deps);
1405 }
1406 Self::MutMapIndexRef(expr, _resolved_type, _accesses) => {
1407 expr.collect_constant_dependencies(deps);
1408 }
1409 Self::MutRustTypeIndexRef(expr, _resolved_type, _value_type, _accesses) => {
1410 expr.collect_constant_dependencies(deps);
1411 }
1412 Self::Option(opt_expr) => {
1413 if let Some(expr) = opt_expr {
1414 expr.collect_constant_dependencies(deps);
1415 }
1416 }
1417 Self::NoneCoalesceOperator(base_expr, default_expr) => {
1418 base_expr.collect_constant_dependencies(deps);
1419 default_expr.collect_constant_dependencies(deps);
1420 }
1421 Self::InitializeVariable(assign) | Self::ReassignVariable(assign) => {
1422 assign.expression.collect_constant_dependencies(deps);
1423 }
1424 Self::VariableCompoundAssignment(compound_assign) => {
1425 compound_assign
1426 .expression
1427 .collect_constant_dependencies(deps);
1428 }
1429 Self::ArrayExtend(_var_ref, expr) | Self::ArrayPush(_var_ref, expr) => {
1430 expr.collect_constant_dependencies(deps);
1431 }
1432 Self::ArrayAssignment(_mut_array, _, expr) => {
1433 expr.collect_constant_dependencies(deps);
1434 }
1435 Self::MapAssignment(_mut_map, _, expr) => {
1436 expr.collect_constant_dependencies(deps);
1437 }
1438 Self::MapRemove(expr, expr2, _) => {
1439 expr.collect_constant_dependencies(deps);
1440 expr2.collect_constant_dependencies(deps);
1441 }
1442
1443 Self::AssignArrayRange(expr, _array_type, start_expr, end_expr, _mode, assign) => {
1444 expr.collect_constant_dependencies(deps);
1445 start_expr.collect_constant_dependencies(deps);
1446 end_expr.collect_constant_dependencies(deps);
1447 assign.collect_constant_dependencies(deps);
1448 }
1449 Self::AssignStringRange(expr, start_expr, end_expr, _mode, assign) => {
1450 expr.collect_constant_dependencies(deps);
1451 start_expr.collect_constant_dependencies(deps);
1452 end_expr.collect_constant_dependencies(deps);
1453 assign.collect_constant_dependencies(deps);
1454 }
1455
1456 Self::MapHas(expr, expr2) => {
1457 expr.collect_constant_dependencies(deps);
1458 expr2.collect_constant_dependencies(deps);
1459 }
1460 Self::StructFieldAssignment(expr, _accesses, source_expr) => {
1461 expr.collect_constant_dependencies(deps);
1462 source_expr.collect_constant_dependencies(deps);
1463 }
1464 Self::FieldCompoundAssignment(expr, _accesses, _, source_expr) => {
1465 expr.collect_constant_dependencies(deps);
1466 source_expr.collect_constant_dependencies(deps);
1467 }
1468 Self::BinaryOp(bin_op) => {
1469 bin_op.left.collect_constant_dependencies(deps);
1470 bin_op.right.collect_constant_dependencies(deps);
1471 }
1472 Self::UnaryOp(unary_op) => {
1473 unary_op.left.collect_constant_dependencies(deps);
1474 }
1475 Self::PostfixOp(postfix_op) => {
1476 postfix_op.left.collect_constant_dependencies(deps);
1477 }
1478 Self::CoerceOptionToBool(expr) => {
1479 expr.collect_constant_dependencies(deps);
1480 }
1481 Self::FunctionCall(_func_type, _func_expr, arguments) => {
1482 for arg in arguments {
1483 arg.collect_constant_dependencies(deps);
1484 }
1485 }
1486 Self::FunctionInternalCall(func_call) => {
1487 for arg in &func_call.arguments {
1488 arg.collect_constant_dependencies(deps);
1489 }
1490 }
1491 Self::FunctionExternalCall(func_call) => {
1492 for arg in &func_call.arguments {
1493 arg.collect_constant_dependencies(deps);
1494 }
1495 }
1496 Self::StaticCall(static_call) => {
1497 for arg in &static_call.arguments {
1498 arg.collect_constant_dependencies(deps);
1499 }
1500 }
1501 Self::StaticCallGeneric(static_call) => {
1502 for arg in &static_call.arguments {
1503 arg.collect_constant_dependencies(deps);
1504 }
1505 }
1506 Self::MemberCall(member_call) => {
1507 for arg in &member_call.arguments {
1508 arg.collect_constant_dependencies(deps);
1509 }
1510 }
1511
1512 Self::InterpolatedString(parts) => {
1513 for part in parts {
1514 match part {
1515 ResolvedStringPart::Literal(_, _) => {}
1516 ResolvedStringPart::Interpolation(expr, _) => {
1517 expr.collect_constant_dependencies(deps);
1518 }
1519 }
1520 }
1521 }
1522 Self::StructInstantiation(struct_inst) => {
1523 for (_index, expr) in &struct_inst.source_order_expressions {
1524 expr.collect_constant_dependencies(deps);
1525 }
1526 }
1527 Self::Array(array_inst) => {
1528 for expr in &array_inst.expressions {
1529 expr.collect_constant_dependencies(deps);
1530 }
1531 }
1532 Self::Tuple(tuple_exprs) => {
1533 for expr in tuple_exprs {
1534 expr.collect_constant_dependencies(deps);
1535 }
1536 }
1537 Self::Literal(_) => {}
1538 Self::ExclusiveRange(start_expr, end_expr) => {
1539 start_expr.collect_constant_dependencies(deps);
1540 end_expr.collect_constant_dependencies(deps);
1541 }
1542 Self::InclusiveRange(start_expr, end_expr) => {
1543 start_expr.collect_constant_dependencies(deps);
1544 end_expr.collect_constant_dependencies(deps);
1545 }
1546 Self::IfElseOnlyVariable {
1547 optional_expr,
1548 true_block,
1549 false_block,
1550 ..
1551 } => {
1552 optional_expr.collect_constant_dependencies(deps);
1553 true_block.collect_constant_dependencies(deps);
1554 false_block.collect_constant_dependencies(deps);
1555 }
1556 Self::IfElseAssignExpression {
1557 optional_expr,
1558 true_block,
1559 false_block,
1560 ..
1561 } => {
1562 optional_expr.collect_constant_dependencies(deps);
1563 true_block.collect_constant_dependencies(deps);
1564 false_block.collect_constant_dependencies(deps);
1565 }
1566 Self::Match(resolved_match) => {
1567 resolved_match
1568 .expression
1569 .collect_constant_dependencies(deps);
1570 }
1571
1572 Self::Guard(guards, wildcard, _resolved_type) => {
1573 for guard in guards {
1574 guard
1575 .condition
1576 .expression
1577 .collect_constant_dependencies(deps);
1578 guard.result.collect_constant_dependencies(deps);
1579 }
1580 if let Some(found_wildcard) = wildcard {
1581 found_wildcard.collect_constant_dependencies(deps);
1582 }
1583 }
1584 Self::LetVar(_var_ref, expr) => {
1585 expr.collect_constant_dependencies(deps);
1586 }
1587 Self::ArrayRemoveIndex(_var_ref, expr) => {
1588 expr.collect_constant_dependencies(deps);
1589 }
1590 Self::ArrayClear(_var_ref) => {
1591 }
1593 Self::FloatRound(expr)
1594 | Self::FloatFloor(expr)
1595 | Self::FloatSign(expr)
1596 | Self::FloatAbs(expr)
1597 | Self::FloatAcos(expr)
1598 | Self::FloatCos(expr)
1599 | Self::FloatSqrt(expr)
1600 | Self::FloatClamp(expr, _, _)
1601 | Self::FloatMin(expr, _)
1602 | Self::FloatMax(expr, _)
1603 | Self::FloatSin(expr)
1604 | Self::FloatAsin(expr)
1605 | Self::FloatAtan2(expr, _) => {
1606 expr.collect_constant_dependencies(deps);
1607 }
1608
1609 Self::StringLen(expr) => {
1610 expr.collect_constant_dependencies(deps);
1611 }
1612
1613 Self::Tuple2FloatMagnitude(expr) => {
1614 expr.collect_constant_dependencies(deps);
1615 }
1616 Self::SparseAdd(expr1, expr2, _) | Self::SparseRemove(expr1, expr2, _) => {
1617 expr1.collect_constant_dependencies(deps);
1618 expr2.collect_constant_dependencies(deps);
1619 }
1620 Self::SparseNew(_, _, _, _) => {}
1621 Self::SparseAccess(expr, expr2, _) => {
1622 expr.collect_constant_dependencies(deps);
1623 expr2.collect_constant_dependencies(deps);
1624 }
1625
1626 Self::ForLoop(_, _, expr) => {
1627 expr.collect_constant_dependencies(deps);
1628 }
1629 Self::WhileLoop(_, expr) => {
1630 expr.collect_constant_dependencies(deps);
1631 }
1632 Self::Return(expr_opt) => {
1633 if let Some(expr) = expr_opt {
1634 expr.collect_constant_dependencies(deps);
1635 }
1636 }
1637 Self::Break(_) | Self::Continue(_) => {}
1638 Self::Block(expressions) => {
1639 for expr in expressions {
1640 expr.collect_constant_dependencies(deps);
1641 }
1642 }
1643
1644 Self::If(cond, true_block, false_block) => {
1645 cond.expression.collect_constant_dependencies(deps);
1646 true_block.collect_constant_dependencies(deps);
1647 if let Some(false_block) = false_block {
1648 false_block.collect_constant_dependencies(deps);
1649 }
1650 }
1651 Self::IfOnlyVariable {
1652 true_block,
1654 false_block,
1655 ..
1656 } => {
1657 true_block.collect_constant_dependencies(deps);
1658 if let Some(false_block) = false_block {
1659 false_block.collect_constant_dependencies(deps);
1660 }
1661 }
1662 Self::IfAssignExpression {
1663 optional_expr,
1664 true_block,
1665 false_block,
1666 ..
1667 } => {
1668 optional_expr.collect_constant_dependencies(deps);
1669 true_block.collect_constant_dependencies(deps);
1670 if let Some(false_block) = false_block {
1671 false_block.collect_constant_dependencies(deps);
1672 }
1673 }
1674 Self::TupleDestructuring(_vars, _, expr) => {
1675 expr.collect_constant_dependencies(deps);
1676 }
1677 Self::VariableAccess(_) => {}
1678 Self::IntAbs(_)
1679 | Self::IntRnd(_)
1680 | Self::FloatRnd(_)
1681 | Self::IntClamp(_, _, _)
1682 | Self::IntMin(_, _)
1683 | Self::IntMax(_, _) => {}
1684 Self::IntToFloat(_) => {}
1685 }
1686 }
1687
1688 pub fn resolution_maybe_expecting_type(
1691 &self,
1692 expecting_type: Option<ResolvedType>,
1693 ) -> Result<ResolvedType, SemanticError> {
1694 expecting_type.map_or_else(
1695 || Ok(self.resolution()),
1696 |found_expecting_type| self.resolution_expecting_type(&found_expecting_type),
1697 )
1698 }
1699
1700 pub fn resolution_expecting_type(
1703 &self,
1704 expecting_type: &ResolvedType,
1705 ) -> Result<ResolvedType, SemanticError> {
1706 let detected_type = self.resolution();
1707 if expecting_type.assignable_type(&detected_type) {
1708 Ok(detected_type)
1709 } else {
1710 error!(?detected_type, ?expecting_type, "incompatible");
1711 Err(SemanticError::IncompatibleTypes)
1712 }
1713 }
1714
1715 #[must_use]
1716 #[allow(clippy::too_many_lines, clippy::match_same_arms)]
1717 pub fn resolution(&self) -> ResolvedType {
1718 let resolution_expression = match self {
1719 Self::FieldAccess(_expr, struct_field_ref, _lookups) => {
1721 struct_field_ref.resolved_type.clone()
1722 }
1723 Self::VariableAccess(variable_ref) => variable_ref.resolved_type.clone(),
1724 Self::ConstantAccess(constant_ref) => constant_ref.resolved_type.clone(),
1725
1726 Self::InternalFunctionAccess(internal_function_def) => {
1727 ResolvedType::Function(internal_function_def.signature.clone())
1728 }
1729 Self::ExternalFunctionAccess(external_function_def) => {
1730 ResolvedType::Function(external_function_def.signature.clone())
1731 }
1732
1733 Self::ArrayAccess(_, array_item_ref, _) => array_item_ref.item_type.clone(),
1735 Self::MapIndexAccess(map_item) => {
1736 ResolvedType::Optional(Box::new(map_item.item_type.clone()))
1737 }
1738 Self::MapRemove(_, _, map_type_ref) => map_type_ref.value_type.clone(),
1739 Self::MapHas(_, _) => ResolvedType::Bool,
1740
1741 Self::ArrayRangeAccess(_base_expr, array_type_ref, _min, _max, _mode) => {
1742 ResolvedType::Array(array_type_ref.clone())
1743 }
1744 Self::StringRangeAccess(_base_expr, _min, _max, _mode) => ResolvedType::String,
1745
1746 Self::MutVariableRef(mut_var_ref) => mut_var_ref.variable_ref.resolved_type.clone(),
1748 Self::MutStructFieldRef(_base_expr, resulting_type, _access_chain) => {
1749 resulting_type.clone()
1750 }
1751 Self::MutRustTypeIndexRef(_, _rust_type, value_type, _x) => {
1752 ResolvedType::Optional(Box::new(value_type.clone()))
1753 }
1754 Self::MutArrayIndexRef(_base, resolved_array_type_ref, _index) => {
1755 resolved_array_type_ref.item_type.clone()
1756 }
1757 Self::MutMapIndexRef(_base, map_type, _index) => {
1758 ResolvedType::Optional(Box::new(map_type.value_type.clone()))
1759 }
1760
1761 Self::InitializeVariable(_variable_assignment) => ResolvedType::Unit,
1763 Self::ReassignVariable(_variable_assignments) => ResolvedType::Unit,
1764 Self::VariableCompoundAssignment(_var_compound_assignment) => ResolvedType::Unit,
1765
1766 Self::ArrayAssignment(_, _, _) => ResolvedType::Unit,
1768 Self::MapAssignment(_c, _a, _d) => ResolvedType::Unit,
1769 Self::StructFieldAssignment(_struct_field, _lookups, _source_resolution) => {
1770 ResolvedType::Unit
1771 }
1772 Self::FieldCompoundAssignment(
1773 _resolved_expression,
1774 _access,
1775 _op_,
1776 _source_resolution,
1777 ) => ResolvedType::Unit,
1778
1779 Self::AssignArrayRange(
1780 _base_expr,
1781 _resolved_array_type_ref,
1782 _start_expr,
1783 _end_expr,
1784 _mode,
1785 _,
1786 ) => ResolvedType::Unit,
1787
1788 Self::AssignStringRange(_base, _start_expr, _end_expr, _mode, _) => ResolvedType::Unit,
1789
1790 Self::BinaryOp(binary_op) => binary_op.resolved_type.clone(),
1792 Self::UnaryOp(unary_op) => unary_op.resolved_type.clone(),
1793 Self::PostfixOp(postfix_op) => postfix_op.resolved_type.clone(),
1794
1795 Self::FunctionCall(signature, _fn_expr, _arguments) => *signature.return_type.clone(),
1797 Self::MemberCall(call) => *call.function.signature().return_type.clone().clone(),
1798 Self::FunctionInternalCall(internal_fn_call) => *internal_fn_call
1799 .function_definition
1800 .signature
1801 .return_type
1802 .clone(),
1803 Self::FunctionExternalCall(external_fn_call) => *external_fn_call
1804 .function_definition
1805 .signature
1806 .return_type
1807 .clone(),
1808 Self::StaticCall(static_call) => *static_call.function.signature().return_type.clone(),
1809 Self::StaticCallGeneric(static_call_generic) => {
1810 *static_call_generic.function.signature().return_type.clone()
1811 }
1812 Self::InterpolatedString(_parts) => ResolvedType::String,
1813
1814 Self::StructInstantiation(struct_instantiation) => {
1816 ResolvedType::Struct(struct_instantiation.struct_type_ref.clone())
1817 }
1818 Self::Array(array_instantiation) => array_instantiation.array_type.clone(),
1819 Self::Tuple(_) => todo!(),
1820 Self::ExclusiveRange(_, _) => ResolvedType::Iterable(Box::new(ResolvedType::Int)),
1821 Self::InclusiveRange(_, _) => ResolvedType::Iterable(Box::new(ResolvedType::Int)),
1822
1823 Self::Option(inner_opt) => inner_opt.as_ref().map_or_else(
1825 || todo!("Handle None type inference"),
1826 |inner_expr| {
1827 let inner_type = inner_expr.resolution();
1828 ResolvedType::Optional(Box::new(inner_type))
1829 },
1830 ),
1831
1832 Self::NoneCoalesceOperator(_base_expr, default_expr) => default_expr.resolution(),
1833
1834 Self::IfElseOnlyVariable { true_block, .. } => true_block.resolution(),
1835 Self::IfElseAssignExpression { true_block, .. } => true_block.resolution(),
1836 Self::IfOnlyVariable { true_block, .. } => true_block.resolution(),
1837 Self::IfAssignExpression { true_block, .. } => true_block.resolution(),
1838
1839 Self::LetVar(_, _) => todo!(),
1840
1841 Self::Literal(literal) => match literal {
1843 ResolvedLiteral::BoolLiteral(_value, _node) => ResolvedType::Bool,
1844 ResolvedLiteral::FloatLiteral(_float_value, _node) => ResolvedType::Float,
1845 ResolvedLiteral::IntLiteral(_int_value, _node) => ResolvedType::Int,
1846 ResolvedLiteral::StringLiteral(_string_value, _node) => ResolvedType::String,
1847 ResolvedLiteral::UnitLiteral(_unit_literal) => ResolvedType::Unit,
1848 ResolvedLiteral::EnumVariantLiteral(variant_ref, _data) => {
1849 ResolvedType::Enum(variant_ref.owner.clone())
1850 }
1851 ResolvedLiteral::TupleLiteral(tuple_type_ref, _data) => {
1852 ResolvedType::Tuple(tuple_type_ref.clone())
1853 }
1854 ResolvedLiteral::Array(array_type_ref, _data, _node) => {
1855 ResolvedType::Array(array_type_ref.clone())
1856 }
1857 ResolvedLiteral::Map(map_type_ref, _data) => {
1858 ResolvedType::Map(map_type_ref.clone())
1859 }
1860 ResolvedLiteral::NoneLiteral(_) => ResolvedType::Any, },
1862
1863 Self::ArrayExtend(variable_ref, _) => variable_ref.resolved_type.clone(),
1865 Self::ArrayPush(variable_ref, _) => variable_ref.resolved_type.clone(),
1866 Self::ArrayRemoveIndex(variable_ref, _) => variable_ref.resolved_type.clone(),
1867 Self::ArrayClear(variable_ref) => variable_ref.resolved_type.clone(),
1868
1869 Self::SparseAdd(_, _, return_type) => return_type.clone(),
1871 Self::SparseRemove(_, _, return_type) => return_type.clone(),
1872 Self::SparseNew(_span, _rust_type_ref, _item_type, generic_type) => {
1873 generic_type.clone()
1874 }
1875 Self::SparseAccess(_sparse_expression, _key_expression, expected_type) => {
1876 expected_type.clone()
1877 }
1878 Self::CoerceOptionToBool(_) => ResolvedType::Bool,
1879
1880 Self::FloatFloor(_) => ResolvedType::Int,
1882 Self::FloatRound(_) => ResolvedType::Int,
1883 Self::FloatSign(_) => ResolvedType::Float,
1884 Self::FloatAbs(_)
1885 | Self::FloatCos(_)
1886 | Self::FloatSin(_)
1887 | Self::FloatAsin(_)
1888 | Self::FloatAcos(_)
1889 | Self::FloatMin(_, _)
1890 | Self::FloatAtan2(_, _)
1891 | Self::FloatSqrt(_)
1892 | Self::FloatClamp(_, _, _)
1893 | Self::FloatMax(_, _) => ResolvedType::Float,
1894
1895 Self::FloatRnd(_) => ResolvedType::Int,
1896
1897 Self::IntAbs(_) | Self::IntClamp(_, _, _) | Self::IntMin(_, _) | Self::IntMax(_, _) => {
1899 ResolvedType::Int
1900 }
1901 Self::IntRnd(_) => ResolvedType::Int,
1902 Self::IntToFloat(_) => ResolvedType::Float,
1903
1904 Self::StringLen(_) => ResolvedType::Int,
1906 Self::Tuple2FloatMagnitude(_) => ResolvedType::Float,
1907
1908 Self::ForLoop(_pattern, _iterator_expr, expr) => expr.resolution(),
1910 Self::WhileLoop(_condition, expr) => expr.resolution(),
1911
1912 Self::Return(ref maybe_expr) => maybe_expr
1914 .as_ref()
1915 .map_or(ResolvedType::Unit, |expr| expr.resolution()),
1916 Self::Break(_) => ResolvedType::Unit,
1917 Self::Continue(_) => ResolvedType::Unit,
1918
1919 Self::Block(expressions) => expressions
1920 .last()
1921 .map_or_else(|| ResolvedType::Unit, Self::resolution),
1922
1923 Self::Match(resolved_match) => resolved_match.arms[0].expression_type.clone(),
1925
1926 Self::Guard(_guards, _wildcard, resolved_type) => resolved_type.clone(),
1927
1928 Self::If(_, true_expr, _) => true_expr.resolution(),
1929
1930 Self::TupleDestructuring(_, _tuple_type, _expr) => ResolvedType::Unit,
1932 };
1933
1934 resolution_expression
1935 }
1936}
1937
1938pub trait Spanned {
1939 fn span(&self) -> Span;
1940}
1941
1942#[allow(clippy::too_many_lines, clippy::match_same_arms)]
1943impl Spanned for ResolvedExpression {
1944 fn span(&self) -> Span {
1945 match self {
1946 Self::VariableAccess(var_ref) => var_ref.span(),
1947 Self::ConstantAccess(constant_ref) => constant_ref.span(),
1948 Self::FieldAccess(base, _field, accesses) => {
1949 let mut span = base.span();
1950 for access in accesses {
1951 span = span.merge(&access.span());
1952 }
1953 span
1954 }
1955 Self::ArrayAccess(_, _arr_ref, _access) => todo!(),
1956 Self::MapIndexAccess(lookup) => lookup.span(),
1957
1958 Self::InternalFunctionAccess(func) => func.span(),
1959 Self::ExternalFunctionAccess(func) => func.span(),
1960 Self::MutVariableRef(var_ref) => var_ref.span(),
1961 Self::Option(opt_expr) => opt_expr
1962 .as_ref()
1963 .map_or_else(Span::dummy, |expr| expr.span()),
1964
1965 Self::InitializeVariable(assign) => assign.span(),
1967 Self::ReassignVariable(assign) => assign.span(),
1968 Self::VariableCompoundAssignment(assign) => assign.span(),
1969 Self::ArrayExtend(var_ref, expr) => var_ref.span().merge(&expr.span()),
1970 Self::ArrayPush(var_ref, expr) => var_ref.span().merge(&expr.span()),
1971 Self::ArrayAssignment(_array, _index, _expr) => {
1972 todo!()
1973 }
1974 Self::MapAssignment(_map, _key, _value) => {
1975 todo!()
1976 }
1977 Self::StructFieldAssignment(base, accesses, value) => {
1978 let mut span = base.span();
1979 for access in accesses {
1980 span = span.merge(&access.span());
1981 }
1982 span.merge(&value.span())
1983 }
1984 Self::FieldCompoundAssignment(base, accesses, op, value) => {
1985 let mut span = base.span();
1986 for access in accesses {
1987 span = span.merge(&access.span());
1988 }
1989 span.merge(&op.span()).merge(&value.span())
1990 }
1991
1992 Self::BinaryOp(op) => op.span(),
1994 Self::UnaryOp(op) => op.span(),
1995 Self::PostfixOp(op) => op.span(),
1996 Self::CoerceOptionToBool(expr) => expr.span(),
1997
1998 Self::FunctionCall(_func_type, expr, _arg) => expr.span(),
2000 Self::FunctionInternalCall(_call) => todo!(),
2001 Self::FunctionExternalCall(call) => call.arguments[0].span(),
2002 Self::StaticCall(call) => call.span(),
2003 Self::StaticCallGeneric(_call) => todo!(),
2004 Self::MemberCall(call) => call.function.span(),
2005
2006 Self::Block(statements) => statements
2008 .first()
2009 .map(|first| {
2010 statements
2011 .last()
2012 .map(|last| first.span().merge(&last.span()))
2013 .unwrap_or_else(|| first.span())
2014 })
2015 .unwrap_or_else(Span::dummy),
2016 Self::InterpolatedString(parts) => parts[0].span(),
2017
2018 Self::StructInstantiation(struct_inst) => {
2020 struct_inst.source_order_expressions[0].1.span()
2021 }
2022 Self::Array(array_inst) => array_inst.span(),
2023 Self::Tuple(exprs) => exprs
2024 .first()
2025 .map(|first| {
2026 exprs
2027 .last()
2028 .map(|last| first.span().merge(&last.span()))
2029 .unwrap_or_else(|| first.span())
2030 })
2031 .unwrap_or_else(Span::dummy),
2032 Self::Literal(lit) => lit.span(),
2033 Self::ExclusiveRange(start, end) => start.span().merge(&end.span()),
2034
2035 Self::IfElseOnlyVariable {
2037 variable,
2038 optional_expr,
2039 true_block,
2040 false_block,
2041 } => variable
2042 .span()
2043 .merge(&optional_expr.span())
2044 .merge(&true_block.span())
2045 .merge(&false_block.span()),
2046 Self::IfElseAssignExpression {
2047 variable,
2048 optional_expr,
2049 true_block,
2050 false_block,
2051 } => variable
2052 .span()
2053 .merge(&optional_expr.span())
2054 .merge(&true_block.span())
2055 .merge(&false_block.span()),
2056 Self::Match(_match_expr) => todo!(),
2057 Self::LetVar(var_ref, expr) => var_ref.span().merge(&expr.span()),
2058
2059 Self::ArrayRemoveIndex(var_ref, index) => var_ref.span().merge(&index.span()),
2061 Self::ArrayClear(var_ref) => var_ref.span(),
2062
2063 Self::FloatRound(expr) => expr.span(),
2065 Self::FloatFloor(expr) => expr.span(),
2066 Self::FloatSign(expr) => expr.span(),
2067 Self::FloatAbs(expr) => expr.span(),
2068 Self::FloatRnd(float_expr) => float_expr.span(),
2069
2070 Self::IntAbs(int_expr) => int_expr.span(),
2072 Self::IntRnd(int_expr) => int_expr.span(),
2073 Self::IntToFloat(int_expr) => int_expr.span(),
2074
2075 Self::SparseAdd(expr1, expr2, _) => expr1.span().merge(&expr2.span()),
2077 Self::SparseRemove(expr1, expr2, _) => expr1.span().merge(&expr2.span()),
2078 Self::SparseNew(span, _rust_type_ref, _resolved_type, _generic_type) => span.clone(),
2079 Self::ForLoop(_pattern, _iterator, statements) => statements.span(),
2080 Self::WhileLoop(_condition, _expression) => todo!(),
2081 Self::Return(_maybe_expr) => todo!(),
2082 Self::Break(node) => node.span(),
2083 Self::Continue(node) => node.span(),
2084 Self::If(_condition, _true_expr, _false_expr) => todo!(),
2085 Self::IfOnlyVariable { .. } => todo!(),
2086 Self::IfAssignExpression { .. } => todo!(),
2087 Self::MutStructFieldRef(a, _b, _access_chain) => a.span(),
2088 Self::MutArrayIndexRef(_, _, _) => todo!(),
2089 Self::TupleDestructuring(_, _, _) => todo!(),
2090 _ => todo!(),
2091 }
2092 }
2093}
2094
2095#[derive(Debug)]
2096pub struct ResolvedStringConst(pub ResolvedNode);
2097
2098#[derive(Debug)]
2099pub enum ResolvedLiteral {
2100 FloatLiteral(Fp, ResolvedNode),
2101 UnitLiteral(ResolvedNode),
2102 NoneLiteral(ResolvedNode),
2103 IntLiteral(i32, ResolvedNode),
2104 StringLiteral(String, ResolvedNode),
2105 BoolLiteral(bool, ResolvedNode),
2106
2107 EnumVariantLiteral(ResolvedEnumVariantTypeRef, ResolvedEnumLiteralData),
2108 TupleLiteral(ResolvedTupleTypeRef, Vec<ResolvedExpression>),
2109 Array(ResolvedArrayTypeRef, Vec<ResolvedExpression>, ResolvedNode),
2110 Map(
2111 ResolvedMapTypeRef,
2112 Vec<(ResolvedExpression, ResolvedExpression)>,
2113 ),
2114}
2115
2116impl Spanned for ResolvedLiteral {
2117 fn span(&self) -> Span {
2118 match self {
2119 Self::FloatLiteral(_v, node) => node.span.clone(),
2120 Self::UnitLiteral(_) => Span::dummy(), Self::NoneLiteral(node) => node.span.clone(),
2122 Self::IntLiteral(_, node) => node.span.clone(),
2123 Self::StringLiteral(_, node) => node.span.clone(),
2124 Self::BoolLiteral(_, node) => node.span.clone(),
2125 Self::EnumVariantLiteral(variant_type_ref, _) => variant_type_ref.name.0.span.clone(),
2126 Self::TupleLiteral(_tuple_type_ref, _tuples) => {
2127 todo!()
2128 }
2129 Self::Array(_array_type_ref, _expressions, node) => node.span.clone(),
2130 Self::Map(_, _) => todo!(),
2131 }
2132 }
2133}
2134
2135#[derive(Debug)]
2136pub struct ResolvedArrayInstantiation {
2137 pub expressions: Vec<ResolvedExpression>,
2138 pub item_type: ResolvedType,
2139 pub array_type: ResolvedType,
2140 pub array_type_ref: ResolvedArrayTypeRef,
2141}
2142
2143impl Spanned for ResolvedArrayInstantiation {
2144 fn span(&self) -> Span {
2145 todo!()
2146 }
2147}
2148
2149#[derive(Debug)]
2150pub enum ResolvedForPattern {
2151 Single(ResolvedVariableRef),
2152 Pair(ResolvedVariableRef, ResolvedVariableRef),
2153}
2154
2155impl ResolvedForPattern {
2156 #[must_use]
2157 pub fn is_mutable(&self) -> bool {
2158 match self {
2159 Self::Single(variable) => variable.is_mutable(),
2160 Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
2161 }
2162 }
2163}
2164
2165impl Display for ResolvedForPattern {
2166 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
2167 write!(f, "resolved_for_pattern")
2168 }
2169}
2170
2171#[derive(Debug, Eq, PartialEq)]
2172pub struct ResolvedModulePathItem(pub ResolvedNode);
2173#[derive(Debug, Eq, PartialEq)]
2174pub struct ResolvedModulePath(pub Vec<ResolvedModulePathItem>);
2175
2176pub type ResolvedStructTypeRef = Rc<RefCell<ResolvedStructType>>;
2177
2178pub type TypeNumber = u32;
2179
2180#[derive(Debug)]
2181pub struct ResolvedIdentifierName(pub ResolvedNode);
2182
2183#[derive(Debug, Eq, PartialEq)]
2184pub struct ResolvedLocalTypeIdentifier(pub ResolvedNode);
2185
2186pub type ResolvedModulePathRef = Rc<ResolvedModulePath>;
2187
2188#[derive(Debug)]
2189pub struct ResolvedConstant {
2190 pub name: ResolvedNode,
2191 pub assigned_name: String,
2192 pub id: ConstantId,
2193 pub expr: ResolvedExpression,
2194 pub resolved_type: ResolvedType,
2195}
2196pub type ResolvedConstantRef = Rc<ResolvedConstant>;
2197
2198impl Spanned for ResolvedConstant {
2199 fn span(&self) -> Span {
2200 self.name.span.clone()
2201 }
2202}
2203
2204#[derive(Eq, PartialEq)]
2205pub struct ResolvedStructType {
2206 pub name: ResolvedNode,
2207 pub assigned_name: String,
2208 pub anon_struct_type: ResolvedAnonymousStructType,
2209
2210 pub functions: SeqMap<String, ResolvedFunctionRef>,
2212}
2213
2214impl Debug for ResolvedStructType {
2215 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
2216 write!(f, "struct {:?}", self.assigned_name)
2217 }
2218}
2219
2220impl ResolvedStructType {
2221 pub fn new(
2222 name: ResolvedNode,
2223 assigned_name: &str,
2224 anon_struct_type: ResolvedAnonymousStructType,
2225 ) -> Self {
2226 Self {
2227 anon_struct_type,
2229 name,
2230 assigned_name: assigned_name.to_string(),
2231 functions: SeqMap::default(),
2232 }
2233 }
2234
2235 pub fn field_index(&self, field_name: &str) -> Option<usize> {
2236 self.anon_struct_type
2237 .defined_fields
2238 .get_index(&field_name.to_string())
2239 }
2240
2241 pub fn name(&self) -> &ResolvedNode {
2242 &self.name
2243 }
2244
2245 pub fn add_external_member_function(
2246 &mut self,
2247 external_func: ResolvedExternalFunctionDefinitionRef,
2248 ) -> Result<(), SeqMapError> {
2249 let name = external_func.assigned_name.clone();
2250 let func = ResolvedFunction::External(external_func);
2251 self.functions.insert(name, func.into())?;
2252 Ok(())
2253 }
2254
2255 pub fn get_member_function(&self, function_name: &str) -> Option<&ResolvedFunctionRef> {
2256 self.functions.get(&function_name.to_string())
2257 }
2258
2259 pub fn get_internal_member_function(
2260 &self,
2261 function_name: &str,
2262 ) -> Option<ResolvedInternalFunctionDefinitionRef> {
2263 let func = self.functions.get(&function_name.to_string())?;
2264 match &**func {
2265 ResolvedFunction::Internal(fn_def) => Some(fn_def.clone()),
2266 _ => None,
2267 }
2268 }
2269}
2270
2271#[derive(Debug, PartialEq, Eq, Hash)]
2272pub struct ResolvedUnitType;
2273pub type ResolvedUnitTypeRef = Rc<ResolvedUnitType>;
2274
2275#[derive(Debug, PartialEq, Eq, Hash)]
2276pub struct ResolvedNoneType;
2277pub type ResolvedNoneTypeRef = Rc<ResolvedNoneType>;
2278
2279#[derive(Debug, PartialEq, Eq, Hash)]
2280pub struct ResolvedIntType;
2281pub type ResolvedIntTypeRef = Rc<ResolvedIntType>;
2282
2283#[derive(Debug, PartialEq, Eq, Hash)]
2284pub struct ResolvedFloatType;
2285
2286pub type ResolvedFloatTypeRef = Rc<ResolvedFloatType>;
2287
2288#[derive(Debug, PartialEq, Eq, Hash)]
2289pub struct ResolvedBoolType;
2290pub type ResolvedBoolTypeRef = Rc<ResolvedBoolType>;
2291
2292#[derive(Debug, PartialEq, Eq, Hash)]
2293pub struct ResolvedStringType;
2294pub type ResolvedStringTypeRef = Rc<ResolvedStringType>;
2295
2296#[derive(Debug, PartialEq, Eq, Hash)]
2297pub struct ResolvedExclusiveRangeType;
2298pub type ResolvedExclusiveRangeTypeRef = Rc<ResolvedExclusiveRangeType>;
2299
2300pub type ResolvedOptionTypeRef = Rc<crate::ResolvedOptionType>;
2301
2302#[derive(Debug)]
2303pub struct ResolvedOptionType {
2304 pub item_type: ResolvedType,
2305}
2306
2307pub type ResolvedArrayTypeRef = Rc<ResolvedArrayType>;
2308
2309#[derive(Debug, Eq, PartialEq)]
2310pub struct ResolvedArrayType {
2311 pub item_type: ResolvedType,
2312}
2313
2314pub type ResolvedMapTypeRef = Rc<ResolvedMapType>;
2315
2316#[derive(Debug, Eq, PartialEq)]
2317pub struct ResolvedMapType {
2318 pub key_type: ResolvedType,
2319 pub value_type: ResolvedType,
2320}
2321
2322pub type ResolvedEnumVariantStructTypeRef = Rc<ResolvedEnumVariantStructType>;
2323
2324#[derive(Debug, Eq, PartialEq)]
2325pub struct CommonEnumVariantType {
2326 pub number: TypeNumber,
2327 pub container_index: u8,
2328 pub module_path: ResolvedModulePath,
2329 pub variant_name: ResolvedLocalTypeIdentifier,
2330 pub assigned_name: String,
2331 pub enum_ref: ResolvedEnumTypeRef,
2332}
2333
2334#[derive(Debug, Clone, Eq, PartialEq)]
2335pub struct ResolvedAnonymousStructType {
2336 pub defined_fields: SeqMap<String, ResolvedAnonymousStructFieldType>,
2337}
2338
2339#[derive(Debug, Eq, PartialEq)]
2340pub struct ResolvedEnumVariantStructType {
2341 pub common: CommonEnumVariantType,
2342
2343 pub anon_struct: ResolvedAnonymousStructType,
2344}
2345
2346pub type ResolvedEnumVariantTupleTypeRef = Rc<ResolvedEnumVariantTupleType>;
2347
2348#[derive(Debug, Eq, PartialEq)]
2349pub struct ResolvedEnumVariantTupleType {
2350 pub common: CommonEnumVariantType,
2351
2352 pub fields_in_order: Vec<ResolvedType>,
2353}
2354
2355pub type ResolvedTupleTypeRef = Rc<ResolvedTupleType>;
2356
2357#[derive(Debug, Eq, PartialEq)]
2358pub struct ResolvedTupleType(pub Vec<ResolvedType>);
2359
2360impl ResolvedTupleType {
2361 pub fn new(types: Vec<ResolvedType>) -> Self {
2362 Self(types)
2363 }
2364}
2365
2366pub type ResolvedEnumTypeRef = Rc<RefCell<ResolvedEnumType>>;
2367
2368#[derive(Debug, Eq, PartialEq)]
2369pub struct ResolvedEnumType {
2370 pub name: ResolvedLocalTypeIdentifier,
2371 pub assigned_name: String,
2372 pub module_path: Vec<String>,
2373 pub number: TypeNumber,
2374
2375 pub variants: SeqMap<String, ResolvedEnumVariantTypeRef>,
2376}
2377
2378impl ResolvedEnumType {
2379 pub fn new(
2380 name: ResolvedLocalTypeIdentifier,
2381 assigned_name: &str,
2382 module_path: Vec<String>,
2383 number: TypeNumber,
2384 ) -> Self {
2385 Self {
2386 name,
2387 assigned_name: assigned_name.to_string(),
2388 module_path,
2389 number,
2390 variants: SeqMap::new(),
2391 }
2392 }
2393
2394 pub fn name(&self) -> &ResolvedLocalTypeIdentifier {
2395 &self.name
2396 }
2397
2398 pub fn get_variant(&self, name: &str) -> Option<&ResolvedEnumVariantTypeRef> {
2399 self.variants.get(&name.to_string())
2400 }
2401
2402 pub fn get_variant_from_index(&self, index: usize) -> Option<&ResolvedEnumVariantTypeRef> {
2403 Some(self.variants.values().collect::<Vec<_>>()[index])
2404 }
2405}
2406
2407pub type ResolvedEnumVariantTypeRef = Rc<ResolvedEnumVariantType>;
2408
2409#[derive(Debug, Eq, PartialEq)]
2410pub struct ResolvedEnumVariantType {
2411 pub owner: ResolvedEnumTypeRef,
2412 pub data: ResolvedEnumVariantContainerType,
2413 pub name: ResolvedLocalTypeIdentifier,
2414 pub assigned_name: String,
2415 pub number: TypeNumber,
2416 pub container_index: u8,
2417}
2418
2419pub type ResolvedEnumVariantStructFieldTypeRef = Rc<ResolvedEnumVariantStructFieldType>;
2420
2421#[derive(Debug)]
2422pub struct ResolvedEnumVariantStructFieldType {
2423 pub name: ResolvedLocalIdentifier,
2424 pub enum_variant: ResolvedEnumVariantTypeRef,
2425 pub resolved_type: ResolvedType,
2426
2427 pub field_index: usize,
2428}
2429
2430pub type ResolvedEnumVariantTupleFieldTypeRef = Rc<ResolvedEnumVariantTupleFieldType>;
2431
2432#[derive(Debug)]
2433pub struct ResolvedEnumVariantTupleFieldType {
2434 pub name: ResolvedLocalIdentifier,
2435 pub enum_variant: ResolvedEnumVariantTypeRef,
2436 pub resolved_type: ResolvedType,
2437
2438 pub field_index: usize,
2439}
2440
2441impl ResolvedEnumVariantType {
2442 pub fn new(
2443 owner: ResolvedEnumTypeRef,
2444 name: ResolvedLocalTypeIdentifier,
2445 assigned_name: &str,
2446 data: ResolvedEnumVariantContainerType,
2447 number: TypeNumber,
2448 container_index: u8,
2449 ) -> Self {
2450 Self {
2451 owner,
2452 data,
2453 name,
2454 assigned_name: assigned_name.to_string(),
2455 number,
2456 container_index,
2457 }
2458 }
2459
2460 pub fn container(&self) -> &ResolvedEnumVariantContainerType {
2461 &self.data
2462 }
2463
2464 pub fn name(&self) -> &ResolvedLocalTypeIdentifier {
2465 &self.name
2466 }
2467}
2468
2469#[derive(Debug, Clone, Eq, PartialEq)]
2470pub enum ResolvedEnumVariantContainerType {
2471 Struct(ResolvedEnumVariantStructTypeRef),
2472 Tuple(ResolvedEnumVariantTupleTypeRef),
2473 Nothing,
2474}
2475
2476#[derive(Debug)]
2477pub struct ResolvedImplMember {}
2478
2479#[derive(Debug)]
2480pub struct ImplType {
2481 pub members: SeqMap<String, ResolvedImplMember>,
2482 pub associated_with_struct_type: ResolvedStructTypeRef,
2483}
2484
2485impl ImplType {
2486 pub fn new(
2487 members: SeqMap<String, ResolvedImplMember>,
2488 associated_with_struct_type: ResolvedStructTypeRef,
2489 ) -> Self {
2490 Self {
2491 members,
2492 associated_with_struct_type,
2493 }
2494 }
2495}
2496
2497#[derive(Debug)]
2498pub enum ResolvedUseItem {
2499 Identifier(ResolvedNode),
2500 TypeIdentifier(ResolvedNode),
2501}
2502
2503#[derive(Debug)]
2504pub struct ResolvedUse {
2505 pub path: Vec<ResolvedNode>,
2506 pub items: Vec<ResolvedUseItem>,
2507}
2508
2509#[derive(Debug)]
2510pub enum ResolvedDefinition {
2511 StructType(ResolvedStructTypeRef),
2512 EnumType(ResolvedEnumTypeRef),
2513 Function(),
2514 ExternalFunction(),
2515 ImplType(ResolvedType),
2516 FunctionDef(ResolvedFunction),
2517 Alias(ResolvedType),
2518 Comment(ResolvedNode),
2519 Use(ResolvedUse),
2520 Constant(ResolvedNode, ResolvedConstantRef),
2521}
2522
2523#[derive(Debug)]
2525pub struct ResolvedProgramState {
2526 pub array_types: Vec<ResolvedArrayTypeRef>,
2527 pub number: TypeNumber,
2528 pub external_function_number: ExternalFunctionId,
2529}
2530
2531impl ResolvedProgramState {
2532 pub fn new() -> Self {
2533 Self {
2534 array_types: Vec::new(),
2535 number: 0,
2536 external_function_number: 0,
2537 }
2538 }
2539
2540 pub fn allocate_number(&mut self) -> TypeNumber {
2541 self.number += 1;
2542 self.number
2543 }
2544
2545 pub fn allocate_external_function_id(&mut self) -> ExternalFunctionId {
2546 self.external_function_number += 1;
2547 self.external_function_number
2548 }
2549}
2550
2551#[derive(Debug)]
2552pub enum ResolvedEnumLiteralData {
2553 Nothing,
2554 Tuple(Vec<ResolvedExpression>),
2555 Struct(Vec<(usize, ResolvedExpression)>),
2556}
2557
2558#[derive(Debug)]
2559pub struct ResolvedStaticCallGeneric {
2560 pub function: Rc<ResolvedFunction>,
2561 pub arguments: Vec<ResolvedExpression>,
2562 pub generic_types: Vec<ResolvedType>,
2563}