1pub mod intr;
6pub mod modules;
7pub mod ns;
8pub mod prelude;
9pub mod symtbl;
10
11use crate::intr::IntrinsicFunction;
12pub use fixed32::Fp;
13use seq_fmt::comma;
14use seq_map::{SeqMap, SeqMapError};
15use std::cell::RefCell;
16use std::cmp::PartialEq;
17use std::fmt;
18use std::fmt::{Debug, Display, Formatter};
19use std::hash::Hash;
20use std::rc::Rc;
21
22#[derive(Clone, Eq, PartialEq, Default)]
23pub struct Node {
24 pub span: Span,
25}
26
27impl Debug for Node {
28 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
29 if self.span.file_id == 0xffff {
30 write!(f, "<{}:{}>", self.span.offset, self.span.length)
31 } else {
32 write!(
33 f,
34 "<{}:{} ({})>",
35 self.span.offset, self.span.length, self.span.file_id
36 )
37 }
38 }
39}
40
41pub type FileId = u16;
42
43#[derive(PartialEq, Eq, Hash, Default, Clone)]
44pub struct Span {
45 pub file_id: FileId,
46 pub offset: u32,
47 pub length: u16,
48}
49
50impl Span {
51 pub fn dummy() -> Self {
52 Span {
53 offset: 0,
54 length: 0,
55 file_id: 0xffff,
56 }
57 }
58
59 pub fn end(&self) -> u32 {
61 self.offset + self.length as u32
62 }
63}
64
65impl Debug for Span {
66 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
67 write!(f, "<{}:{} ({})>", self.offset, self.length, self.file_id)
68 }
69}
70
71#[derive(Clone, Eq, PartialEq)]
72pub struct ParameterNode {
73 pub name: Node,
74 pub is_mutable: Option<Node>,
75}
76
77impl Debug for ParameterNode {
78 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
79 write!(f, "Parameter")
80 }
81}
82
83impl ParameterNode {
84 #[inline]
85 #[must_use]
86 pub const fn is_mutable(&self) -> bool {
87 self.is_mutable.is_some()
88 }
89}
90
91#[derive(Debug, Clone, Eq, PartialEq)]
92pub struct Signature {
93 pub parameters: Vec<TypeForParameter>,
94 pub return_type: Box<Type>,
95}
96
97impl Display for Signature {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
99 write!(f, "({})->{}", comma(&self.parameters), self.return_type)
100 }
101}
102
103impl Signature {
104 pub fn same_type(&self, other: &Signature) -> bool {
105 if self.parameters.len() != other.parameters.len()
106 || !self.return_type.compatible_with(&other.return_type)
107 {
108 return false;
109 }
110
111 for (param, other_param) in self.parameters.iter().zip(other.parameters.clone()) {
112 if !¶m
113 .resolved_type
114 .compatible_with(&other_param.resolved_type)
115 {
116 return false;
117 }
118
119 if param.is_mutable != other_param.is_mutable {
120 return false;
121 }
122 }
123
124 true
125 }
126}
127
128#[derive(Debug, Clone, Eq, PartialEq)]
129pub struct ExternalType {
130 pub type_name: String, pub number: u32, }
133
134pub type ExternalTypeRef = Rc<ExternalType>;
135
136#[derive(Debug, Clone)]
137pub struct TypeWithMut {
138 pub resolved_type: Type,
139 pub is_mutable: bool,
140}
141
142#[derive(Debug, Clone)]
143pub struct TypeForParameter {
144 pub name: String,
145 pub resolved_type: Type,
146 pub is_mutable: bool,
147 pub node: Option<ParameterNode>,
148}
149
150impl Display for TypeForParameter {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
152 write!(
153 f,
154 "{}{}: {:?}",
155 if self.is_mutable { "mut " } else { "" },
156 self.name,
157 self.resolved_type
158 )
159 }
160}
161
162impl Eq for TypeForParameter {}
163
164impl PartialEq for TypeForParameter {
165 fn eq(&self, other: &Self) -> bool {
166 let types_equal = self.resolved_type.compatible_with(&other.resolved_type);
167
168 types_equal && (self.is_mutable == other.is_mutable)
169 }
170}
171
172#[derive(Clone, Eq, PartialEq)]
173pub enum Type {
174 Int,
176 Float,
177 String,
178 Bool,
179
180 Unit, Never, Array(ArrayTypeRef),
185 Tuple(TupleTypeRef),
186 NamedStruct(StructTypeRef),
187 AnonymousStruct(AnonymousStructType),
188 Map(MapTypeRef),
189
190 Enum(EnumTypeRef),
191 Generic(Box<Type>, Vec<Type>),
192
193 Function(Signature),
194 Iterable(Box<Type>),
195
196 Optional(Box<Type>),
197 External(ExternalTypeRef),
198}
199
200impl Type {
201 #[must_use]
202 pub const fn is_concrete(&self) -> bool {
203 !matches!(self, Self::Unit | Self::Never)
204 }
205}
206
207impl Debug for Type {
208 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
209 match self {
210 Self::Int => write!(f, "Int"),
211 Self::Float => write!(f, "Float"),
212 Self::String => write!(f, "String"),
213 Self::Bool => write!(f, "Bool"),
214 Self::Unit => write!(f, "Unit"),
215 Self::Never => write!(f, "!"),
216 Self::Array(array_type_ref) => write!(f, "[{:?}]", array_type_ref.item_type),
217 Self::Tuple(tuple_type_ref) => write!(f, "( {:?} )", tuple_type_ref.0),
218 Self::NamedStruct(struct_type_ref) => {
219 write!(f, "{}", struct_type_ref.borrow().assigned_name)
220 }
221 Self::AnonymousStruct(anonymous_struct_type) => {
222 write!(f, "{:?}", anonymous_struct_type)
223 }
224 Self::Map(map_type_ref) => write!(
225 f,
226 "[{:?}:{:?}]",
227 map_type_ref.key_type, map_type_ref.value_type
228 ),
229 Self::Generic(base, parameters) => write!(f, "{base:?}<{parameters:?}>"),
230 Self::Enum(enum_type_ref) => write!(f, "{:?}", enum_type_ref.borrow().assigned_name),
231 Self::Function(function_type_signature) => {
232 write!(f, "{:?}", function_type_signature)
233 }
234 Self::Iterable(type_generated) => write!(f, "Iterable<{type_generated:?}>"),
235 Self::Optional(base_type) => write!(f, "{base_type:?}?"),
236 Self::External(rust_type) => write!(f, "{:?}?", rust_type.type_name),
237 }
238 }
239}
240
241impl Display for Type {
242 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
243 match self {
244 Self::Int => write!(f, "Int"),
245 Self::Float => write!(f, "Float"),
246 Self::String => write!(f, "String"),
247 Self::Bool => write!(f, "Bool"),
248 Self::Unit => write!(f, "Unit"),
249 Self::Never => write!(f, "!"),
250 Self::Array(array_ref) => write!(f, "[{}]", &array_ref.item_type.to_string()),
251 Self::Tuple(tuple) => write!(f, "({})", comma(&tuple.0)),
252 Self::NamedStruct(struct_ref) => write!(f, "{}", struct_ref.borrow().assigned_name),
253 Self::AnonymousStruct(struct_ref) => write!(f, "{:?}", struct_ref),
254 Self::Map(map_ref) => write!(f, "[{}:{}]", map_ref.key_type, map_ref.value_type),
255 Self::Generic(base_type, params) => write!(f, "{base_type}<{}>", comma(params)),
256 Self::Enum(enum_type) => write!(f, "{}", enum_type.borrow().assigned_name),
257 Self::Function(signature) => write!(f, "function {signature}"),
258 Self::Iterable(generating_type) => write!(f, "Iterable<{generating_type}>"),
259 Self::Optional(base_type) => write!(f, "{base_type}?"),
260 Self::External(rust_type) => write!(f, "RustType {}", rust_type.type_name),
261 }
262 }
263}
264
265#[derive(Debug)]
266pub enum SemanticError {
267 CouldNotInsertStruct,
268 DuplicateTypeAlias(String),
269 CanOnlyUseStructForMemberFunctions,
270 ResolveNotStruct,
271 DuplicateStructName(String),
272 DuplicateEnumType(String),
273 DuplicateEnumVariantType(String, String),
274 DuplicateFieldName(String),
275 DuplicateExternalFunction(String),
276 DuplicateRustType(String),
277 DuplicateConstName(String),
278 CircularConstantDependency(Vec<ConstantId>),
279 DuplicateConstantId(ConstantId),
280 IncompatibleTypes,
281 WasNotImmutable,
282 WasNotMutable,
283 DuplicateSymbolName,
284 DuplicateNamespaceLink(String),
285 MismatchedTypes { expected: Type, found: Vec<Type> },
286}
287
288impl Type {
289 pub fn expect_struct_type(&self) -> Result<StructTypeRef, SemanticError> {
290 match self {
291 Type::NamedStruct(struct_type_ref) => Ok(struct_type_ref.clone()),
292 _ => Err(SemanticError::ResolveNotStruct),
293 }
294 }
295
296 pub fn assignable_type(&self, other: &Type) -> bool {
297 if self.compatible_with(other) {
298 true
299 } else if let Self::Optional(inner_type) = self {
300 inner_type.compatible_with(other)
301 } else {
302 false
303 }
304 }
305
306 #[must_use]
307 pub fn compatible_with(&self, other: &Type) -> bool {
308 match (self, other) {
309 (Self::Function(a), Self::Function(b)) => a.same_type(b),
310 (_, Self::Never) => true,
311 (Self::Int, Self::Int) => true,
312 (Self::Float, Self::Float) => true,
313 (Self::String, Self::String) => true,
314 (Self::Bool, Self::Bool) => true,
315 (Self::Unit, Self::Unit) => true,
316 (Self::Array(_), Self::Array(_)) => true,
317 (Self::Map(a), Self::Map(b)) => {
318 a.key_type.compatible_with(&b.key_type)
319 && a.value_type.compatible_with(&b.value_type)
320 }
321 (Self::NamedStruct(a), Self::NamedStruct(b)) => compare_struct_types(a, b),
322 (Self::AnonymousStruct(a), Self::AnonymousStruct(b)) => {
323 compare_anonymous_struct_types(a, b)
324 }
325 (Self::Tuple(a), Self::Tuple(b)) => {
326 if a.0.len() != b.0.len() {
327 return false;
328 }
329 a.0.iter()
330 .zip(b.0.iter())
331 .all(|(a, b)| a.compatible_with(b))
332 }
333 (Self::Enum(_), Self::Enum(_)) => true,
334 (Self::Iterable(a), Self::Iterable(b)) => a.compatible_with(b),
335 (Self::Optional(inner_type_a), Self::Optional(inner_type_b)) => {
337 inner_type_a.compatible_with(inner_type_b)
338 }
339 (Self::External(type_ref_a), Self::External(type_ref_b)) => {
340 type_ref_a.number == type_ref_b.number
341 }
342
343 (Self::Generic(base_a, params_a), Self::Generic(base_b, params_b)) => {
344 if !base_a.compatible_with(base_b) {
345 return false;
346 }
347
348 if params_a.len() != params_b.len() {
349 return false;
350 }
351
352 for (param_a, param_b) in params_a.iter().zip(params_b) {
353 if !param_a.compatible_with(param_b) {
354 return false;
355 }
356 }
357 true
358 }
359 _ => false,
360 }
361 }
362}
363
364fn compare_struct_types(a: &StructTypeRef, b: &StructTypeRef) -> bool {
365 let a_borrow = a.borrow();
366 let b_borrow = b.borrow();
367 if a_borrow.assigned_name != b_borrow.assigned_name {
368 return false;
369 }
370
371 compare_anonymous_struct_types(&a_borrow.anon_struct_type, &b_borrow.anon_struct_type)
372}
373
374fn compare_anonymous_struct_types(a: &AnonymousStructType, b: &AnonymousStructType) -> bool {
375 if a.field_name_sorted_fields.len() != b.field_name_sorted_fields.len() {
376 return false;
377 }
378
379 for ((a_name, a_type), (b_name, b_type)) in a
380 .field_name_sorted_fields
381 .iter()
382 .zip(b.field_name_sorted_fields.clone())
383 {
384 if *a_name != b_name {
385 return false;
386 }
387
388 if !a_type.field_type.compatible_with(&b_type.field_type) {
389 return false;
390 }
391 }
392
393 true
394}
395
396#[must_use]
397pub fn check_assignable_anonymous_struct_types(
398 a: &AnonymousStructType,
399 b: &AnonymousStructType,
400) -> bool {
401 if a.field_name_sorted_fields.len() != b.field_name_sorted_fields.len() {
402 return false;
403 }
404
405 for (name, field) in &a.field_name_sorted_fields {
406 if let Some(found_field) = b.field_name_sorted_fields.get(name) {
407 if !found_field.field_type.compatible_with(&field.field_type) {
408 return false;
409 }
410 } else {
411 return false;
412 }
413 }
414
415 true
416}
417
418impl Node {
419 pub fn new_unknown() -> Self {
420 Self {
421 span: Span {
422 file_id: 0xffff,
423 offset: 0,
424 length: 0,
425 },
426 }
427 }
428}
429
430#[derive(Debug, Eq, PartialEq)]
431pub struct LocalIdentifier(pub Node);
432
433pub struct InternalFunctionDefinition {
435 pub body: Expression,
436 pub name: LocalIdentifier,
437 pub signature: Signature,
438}
439
440impl Debug for InternalFunctionDefinition {
441 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
442 write!(f, "{:?}\n{:?}", self.signature, self.body)
443 }
444}
445
446impl PartialEq<Self> for InternalFunctionDefinition {
447 fn eq(&self, other: &Self) -> bool {
448 self.name == other.name
449 }
450}
451
452impl Eq for InternalFunctionDefinition {}
453
454pub type InternalFunctionDefinitionRef = Rc<InternalFunctionDefinition>;
455
456pub type ExternalFunctionId = u32;
457
458pub type ConstantId = u32;
459
460pub struct ExternalFunctionDefinition {
461 pub name: Option<Node>,
462 pub assigned_name: String,
463 pub signature: Signature,
464 pub id: ExternalFunctionId,
465}
466
467impl PartialEq<Self> for ExternalFunctionDefinition {
468 fn eq(&self, other: &Self) -> bool {
469 self.id == other.id
470 }
471}
472
473impl Eq for ExternalFunctionDefinition {}
474
475impl Debug for ExternalFunctionDefinition {
476 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
477 write!(f, "external fn")
478 }
479}
480
481pub type ExternalFunctionDefinitionRef = Rc<crate::ExternalFunctionDefinition>;
482
483#[derive(Debug)]
484pub struct Variable {
485 pub name: Node,
486 pub resolved_type: Type,
487 pub mutable_node: Option<Node>,
488
489 pub scope_index: usize,
490 pub variable_index: usize,
491}
492
493impl Variable {
494 #[must_use]
495 pub const fn is_mutable(&self) -> bool {
496 self.mutable_node.is_some()
497 }
498}
499
500pub type VariableRef = Rc<Variable>;
501
502#[derive(Debug)]
503pub struct MutVariable {
504 pub variable_ref: VariableRef,
505}
506
507#[derive(Debug)]
510pub enum BinaryOperatorKind {
511 Add,
512 Subtract,
513 Multiply,
514 Divide,
515 Modulo,
516 LogicalOr,
517 LogicalAnd,
518 Equal,
519 NotEqual,
520 LessThan,
521 LessEqual,
522 GreaterThan,
523 GreaterEqual,
524 RangeExclusive,
525}
526
527#[derive(Debug)]
528pub struct BinaryOperator {
529 pub left: Box<Expression>,
530 pub right: Box<Expression>,
531 pub kind: BinaryOperatorKind,
532 pub node: Node,
533}
534
535#[derive(Debug)]
536pub enum UnaryOperatorKind {
537 Not,
538 Negate,
539}
540#[derive(Debug)]
541pub struct UnaryOperator {
542 pub left: Box<Expression>,
543 pub kind: UnaryOperatorKind,
544 pub node: Node,
545}
546
547#[derive()]
548pub struct InternalFunctionCall {
549 pub arguments: Vec<ArgumentExpressionOrLocation>,
550
551 pub function_definition: InternalFunctionDefinitionRef,
552 pub function_expression: Box<Expression>,
553}
554
555impl Debug for InternalFunctionCall {
556 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
557 write!(
558 f,
559 "InFuncCall({:?} {:?})",
560 self.function_expression, self.arguments
561 )
562 }
563}
564
565#[derive(Debug)]
566pub struct ExternalFunctionCall {
567 pub arguments: Vec<ArgumentExpressionOrLocation>,
568 pub function_definition: ExternalFunctionDefinitionRef,
569 pub function_expression: Box<Expression>,
570}
571
572#[must_use]
573pub fn comma_seq<K: Clone + Hash + Eq + Display, V: Display>(values: &SeqMap<K, V>) -> String {
574 let mut result = String::new();
575 for (i, (key, value)) in values.iter().enumerate() {
576 if i > 0 {
577 result.push_str(", ");
578 }
579 result.push_str(format!("{key}: {value}").as_str());
580 }
581 result
582}
583
584pub fn comma_seq_nl<K: Clone + Hash + Eq + Display, V: Display>(
585 values: &SeqMap<K, V>,
586 prefix: &str,
587) -> String {
588 let mut result = String::new();
589 for (key, value) in values.iter() {
590 result.push_str(format!("{}{}: {}\n", prefix, key, value).as_str());
591 }
592 result
593}
594
595pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
596 let mut result = String::new();
597 for (i, (key, value)) in values.iter().enumerate() {
598 if i > 0 {
599 result.push_str(", ");
600 }
601 result.push_str(format!("{}: {}", key, value).as_str());
602 }
603 result
604}
605
606#[derive(Debug)]
607pub struct MemberCall {
608 pub function: FunctionRef,
609 pub arguments: Vec<ArgumentExpressionOrLocation>,
610}
611
612#[derive(Debug, Eq, PartialEq, Clone)]
613pub struct StructTypeField {
614 pub identifier: Option<Node>,
615 pub field_type: Type,
616}
617
618impl Display for StructTypeField {
619 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
620 write!(f, "{:?}:{}", self.identifier, self.field_type)
621 }
622}
623
624#[derive(Debug)]
625pub struct MapIndexLookup {
626 pub map_type: Type,
627 pub item_type: Type,
628 pub map_type_ref: MapTypeRef,
629 pub index_expression: Box<Expression>,
630 pub map_expression: Box<Expression>,
631}
632
633#[derive(Debug)]
634pub struct ArrayItem {
635 pub item_type: Type,
636 pub int_expression: Expression,
637 pub array_expression: Expression,
638 pub array_type: Type,
639}
640
641pub type ArrayItemRef = Rc<ArrayItem>;
642
643#[derive(Debug)]
644pub enum PrecisionType {
645 Float,
646 String,
647}
648
649#[derive(Debug)]
650pub enum FormatSpecifierKind {
651 LowerHex, UpperHex, Binary, Float, Precision(u32, Node, PrecisionType), }
657
658#[derive(Debug)]
659pub struct FormatSpecifier {
660 pub node: Node,
661 pub kind: FormatSpecifierKind,
662}
663
664#[derive(Debug)]
665pub enum StringPart {
666 Literal(Node, String),
667 Interpolation(Expression, Option<FormatSpecifier>),
668}
669
670pub type FunctionRef = Rc<Function>;
671
672#[derive(Debug, Eq, PartialEq)]
673pub enum Function {
674 Internal(InternalFunctionDefinitionRef),
675 External(ExternalFunctionDefinitionRef),
676}
677
678impl Function {
679 #[must_use]
680 pub fn name(&self) -> Option<&Node> {
681 match self {
682 Self::Internal(x) => Some(&x.name.0),
683 Self::External(y) => y.name.as_ref(),
684 }
685 }
686
687 #[must_use]
688 pub fn node(&self) -> Node {
689 match self {
690 Self::Internal(x) => x.name.0.clone(),
691 Self::External(_y) => Node::new_unknown(),
692 }
693 }
694
695 #[must_use]
696 pub fn signature(&self) -> &Signature {
697 match self {
698 Self::Internal(internal) => &internal.signature,
699 Self::External(external) => &external.signature,
700 }
701 }
702}
703
704#[derive(Debug)]
705pub struct BooleanExpression {
706 #[allow(unused)]
707 pub expression: Box<Expression>,
708}
709
710#[derive(Debug)]
711pub struct Match {
712 pub arms: Vec<MatchArm>,
713 pub expression: Box<MutOrImmutableExpression>,
714}
715
716#[derive(Debug)]
717pub struct MatchArm {
718 #[allow(unused)]
719 pub pattern: Pattern,
720 pub expression: Box<Expression>,
721 pub expression_type: Type,
722}
723
724#[derive(Debug)]
725pub enum Pattern {
726 Normal(NormalPattern, Option<BooleanExpression>),
727 Wildcard(Node),
728}
729
730#[derive(Debug)]
731pub enum NormalPattern {
732 PatternList(Vec<PatternElement>),
733 EnumPattern(EnumVariantTypeRef, Option<Vec<PatternElement>>),
734 Literal(Literal),
735}
736
737#[derive(Debug)]
738pub enum PatternElement {
739 Variable(VariableRef),
740 VariableWithFieldIndex(VariableRef, usize),
741 Wildcard(Node),
742}
743
744#[derive(Debug)]
745pub struct Iterable {
746 pub key_type: Option<Type>, pub value_type: Type,
748
749 pub resolved_expression: Box<MutOrImmutableExpression>,
750}
751
752#[derive(Debug)]
753pub struct StructInstantiation {
754 pub source_order_expressions: Vec<(usize, Expression)>,
755 pub struct_type_ref: StructTypeRef,
756}
757
758#[derive(Debug)]
759pub struct AnonymousStructLiteral {
760 pub source_order_expressions: Vec<(usize, Expression)>,
761 pub anonymous_struct_type: AnonymousStructType,
762}
763
764#[derive(Debug, Eq, PartialEq)]
765pub enum CompoundOperatorKind {
766 Add,
767 Sub,
768 Mul,
769 Div,
770 Modulo,
771}
772
773#[derive(Debug)]
774pub struct CompoundOperator {
775 pub node: Node,
776 pub kind: CompoundOperatorKind,
777}
778
779#[derive(Debug)]
780pub struct VariableCompoundAssignment {
781 pub variable_ref: VariableRef, pub expression: Box<Expression>,
783 pub compound_operator: CompoundOperator,
784}
785
786pub fn create_rust_type(name: &str, type_number: TypeNumber) -> ExternalTypeRef {
787 let rust_type = ExternalType {
788 type_name: name.to_string(),
789 number: type_number,
790 };
791 Rc::new(rust_type)
792}
793
794#[derive(Debug)]
795pub struct Guard {
796 pub condition: Option<BooleanExpression>,
797 pub result: Expression,
798}
799
800#[derive(Debug, Clone, Eq, PartialEq)]
801pub enum RangeMode {
802 Inclusive,
803 Exclusive,
804}
805
806#[derive(Debug)]
807pub struct Postfix {
808 pub node: Node,
809 pub ty: Type,
810 pub kind: PostfixKind,
811}
812
813#[derive(Debug)]
814pub struct Range {
815 pub min: Expression,
816 pub max: Expression,
817 pub mode: RangeMode,
818}
819
820#[derive(Debug)]
821pub enum PostfixKind {
822 StructField(AnonymousStructType, usize),
823 ArrayIndex(ArrayTypeRef, Expression),
824 ArrayRangeIndex(ArrayTypeRef, Range),
825 StringIndex(Expression),
826 StringRangeIndex(Range),
827 MapIndex(MapTypeRef, Expression),
828 ExternalTypeIndexRef(ExternalTypeRef, Expression),
829 MemberCall(FunctionRef, Vec<ArgumentExpressionOrLocation>),
830 FunctionCall(Vec<ArgumentExpressionOrLocation>),
831 OptionUnwrap, NoneCoalesce(Expression),
833
834 IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpressionOrLocation>),
835 IntrinsicCall(IntrinsicFunction, Vec<Expression>),
836}
837
838#[derive(Debug)]
839pub enum LocationAccessKind {
840 FieldIndex(AnonymousStructType, usize),
841 ArrayIndex(ArrayTypeRef, Expression),
842 ArrayRange(ArrayTypeRef, Range),
843 StringIndex(Expression),
844 StringRange(Range),
845 MapIndex(MapTypeRef, Expression),
846 MapIndexInsertIfNonExisting(MapTypeRef, Expression),
847 ExternalTypeIndex(ExternalTypeRef, Expression),
848}
849
850#[derive(Debug)]
851pub struct LocationAccess {
852 pub node: Node,
853 pub ty: Type,
854 pub kind: LocationAccessKind,
855}
856
857#[derive(Debug)]
858pub struct SingleLocationExpression {
859 pub kind: SingleLocationExpressionKind,
860 pub node: Node,
861 pub ty: Type,
862
863 pub starting_variable: VariableRef,
864 pub access_chain: Vec<LocationAccess>,
865}
866
867#[derive(Debug)]
868pub struct SingleMutLocationExpression(pub SingleLocationExpression);
869
870#[derive(Debug)]
871pub enum SingleLocationExpressionKind {
872 MutVariableRef,
873 MutStructFieldRef(StructTypeRef, usize),
874 MutArrayIndexRef(ArrayTypeRef),
875 MutMapIndexRef(MapTypeRef),
876 MutExternalTypeIndexRef(ExternalTypeRef),
877}
878
879#[derive(Debug)]
880pub struct SliceLocationExpression {
881 pub start: Box<Expression>,
882 pub range_start: Box<Expression>,
883 pub range_end: Box<Expression>,
884 pub mode: RangeMode,
885 pub ty: Type,
886}
887
888#[derive(Debug)]
889pub struct MutOrImmutableExpression {
890 pub expression_or_location: ArgumentExpressionOrLocation,
891 pub is_mutable: Option<Node>,
892}
893
894impl MutOrImmutableExpression {}
895
896impl MutOrImmutableExpression {
897 pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
898 match self.expression_or_location {
899 ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
900 ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
901 }
902 }
903
904 pub fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
905 match &self.expression_or_location {
906 ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
907 ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
908 }
909 }
910
911 pub fn ty(&self) -> &Type {
912 match &self.expression_or_location {
913 ArgumentExpressionOrLocation::Expression(expr) => &expr.ty,
914 ArgumentExpressionOrLocation::Location(loc) => &loc.ty,
915 }
916 }
917}
918
919#[derive(Debug)]
920pub enum ArgumentExpressionOrLocation {
921 Expression(Expression),
922 Location(SingleLocationExpression),
923}
924
925#[derive()]
926pub struct Expression {
927 pub ty: Type,
928 pub node: Node,
929 pub kind: ExpressionKind,
930}
931
932impl Debug for Expression {
933 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
934 write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
935 }
936}
937
938#[derive(Debug)]
939pub struct WhenBinding {
940 pub variable: VariableRef,
941 pub expr: MutOrImmutableExpression,
942}
943
944#[derive(Debug)]
945pub enum ExpressionKind {
946 ConstantAccess(ConstantRef),
948 VariableAccess(VariableRef),
949 FieldAccess(Box<Expression>, usize),
950 ArrayAccess(
951 Box<Expression>,
952 ArrayTypeRef,
953 Box<Expression>, ), MapIndexAccess(Box<Expression>, MapTypeRef, Box<Expression>),
956 StringRangeAccess(Box<Expression>, Box<Range>),
957 ArrayRangeAccess(Box<Expression>, Box<Range>),
958
959 InternalFunctionAccess(InternalFunctionDefinitionRef),
961 ExternalFunctionAccess(ExternalFunctionDefinitionRef),
962
963 MapAssignment(
965 Box<SingleMutLocationExpression>,
966 Box<Expression>,
967 Box<Expression>,
968 ), BinaryOp(BinaryOperator),
972 UnaryOp(UnaryOperator),
973 PostfixChain(Box<Expression>, Vec<Postfix>),
974
975 CoerceOptionToBool(Box<Expression>),
979
980 FunctionCall(
984 Signature,
985 Box<Expression>,
986 Vec<ArgumentExpressionOrLocation>,
987 ),
988
989 MemberCall(MemberCall),
990 InterpolatedString(Vec<StringPart>),
991
992 VariableDefinition(VariableRef, Box<MutOrImmutableExpression>), VariableReassignment(VariableRef, Box<MutOrImmutableExpression>),
995
996 StructInstantiation(StructInstantiation),
997 AnonymousStructLiteral(AnonymousStructLiteral),
998 Array(ArrayInstantiation),
999 Tuple(Vec<Expression>),
1000 Literal(Literal),
1001 Option(Option<Box<Expression>>), Range(Box<Expression>, Box<Expression>, RangeMode),
1003
1004 ForLoop(ForPattern, Iterable, Box<Expression>),
1006 WhileLoop(BooleanExpression, Box<Expression>),
1007 Return(Option<Box<Expression>>),
1008 Break,
1009 Continue, Block(Vec<Expression>),
1012
1013 Match(Match),
1015 Guard(Vec<Guard>),
1016 If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
1017
1018 When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
1019
1020 TupleDestructuring(Vec<VariableRef>, TupleTypeRef, Box<Expression>),
1021
1022 Assignment(Box<SingleMutLocationExpression>, Box<Expression>),
1023 AssignmentSlice(Box<SliceLocationExpression>, Box<Expression>),
1024 CompoundAssignment(
1025 SingleMutLocationExpression,
1026 CompoundOperatorKind,
1027 Box<Expression>,
1028 ),
1029
1030 IntrinsicCallMut(
1034 IntrinsicFunction,
1035 SingleMutLocationExpression,
1036 Vec<Expression>,
1037 ),
1038
1039 SparseNew(ExternalTypeRef, Type), }
1042
1043#[derive(Debug)]
1044pub struct StringConst(pub Node);
1045
1046#[derive(Debug)]
1047pub enum Literal {
1048 FloatLiteral(Fp),
1049 NoneLiteral,
1050 IntLiteral(i32),
1051 StringLiteral(String),
1052 BoolLiteral(bool),
1053
1054 EnumVariantLiteral(EnumVariantTypeRef, EnumLiteralData),
1055 TupleLiteral(TupleTypeRef, Vec<Expression>),
1056 Array(ArrayTypeRef, Vec<Expression>),
1057 Map(MapTypeRef, Vec<(Expression, Expression)>),
1058}
1059
1060#[derive(Debug)]
1061pub struct ArrayInstantiation {
1062 pub expressions: Vec<Expression>,
1063 pub item_type: Type,
1064 pub array_type: Type,
1065 pub array_type_ref: ArrayTypeRef,
1066}
1067
1068#[derive(Debug)]
1069pub enum ForPattern {
1070 Single(VariableRef),
1071 Pair(VariableRef, VariableRef),
1072}
1073
1074impl ForPattern {
1075 #[must_use]
1076 pub fn is_mutable(&self) -> bool {
1077 match self {
1078 Self::Single(variable) => variable.is_mutable(),
1079 Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
1080 }
1081 }
1082}
1083
1084impl Display for ForPattern {
1085 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1086 write!(f, "resolved_for_pattern")
1087 }
1088}
1089
1090#[derive(Debug, Eq, PartialEq)]
1091pub struct ModulePathItem(pub Node);
1092
1093pub type StructTypeRef = Rc<RefCell<NamedStructType>>;
1094
1095pub fn same_anon_struct_ref(a: &AnonymousStructType, b: &AnonymousStructType) -> bool {
1096 compare_anonymous_struct_types(a, b)
1097}
1098
1099pub fn same_named_struct_ref(a: &StructTypeRef, b: &StructTypeRef) -> bool {
1100 Rc::ptr_eq(a, b)
1101}
1102
1103pub type TypeNumber = u32;
1104
1105#[derive(Debug, Clone, Eq, PartialEq)]
1106pub struct LocalTypeIdentifier(pub Node);
1107
1108#[derive(Debug)]
1109pub struct Constant {
1110 pub name: Node,
1111 pub assigned_name: String,
1112 pub id: ConstantId,
1113 pub expr: Expression,
1114 pub resolved_type: Type,
1115}
1116pub type ConstantRef = Rc<Constant>;
1117
1118#[derive(Debug)]
1119pub struct AliasType {
1120 pub name: Node,
1121 pub assigned_name: String,
1122 pub referenced_type: Type,
1123}
1124pub type AliasTypeRef = Rc<AliasType>;
1125
1126#[derive(Eq, PartialEq)]
1127pub struct NamedStructType {
1128 pub name: Node,
1129 pub assigned_name: String,
1130 pub anon_struct_type: AnonymousStructType,
1131
1132 pub functions: SeqMap<String, FunctionRef>,
1134}
1135
1136impl Debug for NamedStructType {
1137 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1138 write!(f, "struct {:?}", self.assigned_name)
1139 }
1140}
1141
1142impl NamedStructType {
1143 pub fn new(name: Node, assigned_name: &str, anon_struct_type: AnonymousStructType) -> Self {
1144 Self {
1145 anon_struct_type,
1147 name,
1148 assigned_name: assigned_name.to_string(),
1149 functions: SeqMap::default(),
1150 }
1151 }
1152
1153 pub fn field_index(&self, field_name: &str) -> Option<usize> {
1154 self.anon_struct_type
1155 .field_name_sorted_fields
1156 .get_index(&field_name.to_string())
1157 }
1158
1159 pub fn name(&self) -> &Node {
1160 &self.name
1161 }
1162
1163 pub fn add_external_member_function(
1164 &mut self,
1165 external_func: ExternalFunctionDefinitionRef,
1166 ) -> Result<(), SeqMapError> {
1167 let name = external_func.assigned_name.clone();
1168 let func = Function::External(external_func);
1169 self.functions.insert(name, func.into())?;
1170 Ok(())
1171 }
1172
1173 pub fn get_member_function(&self, function_name: &str) -> Option<&FunctionRef> {
1174 self.functions.get(&function_name.to_string())
1175 }
1176
1177 pub fn get_internal_member_function(
1178 &self,
1179 function_name: &str,
1180 ) -> Option<InternalFunctionDefinitionRef> {
1181 let func = self.functions.get(&function_name.to_string())?;
1182 match &**func {
1183 Function::Internal(fn_def) => Some(fn_def.clone()),
1184 _ => None,
1185 }
1186 }
1187}
1188
1189pub type OptionTypeRef = Rc<crate::OptionType>;
1190
1191#[derive(Debug)]
1192pub struct OptionType {
1193 pub item_type: Type,
1194}
1195
1196pub type ArrayTypeRef = Rc<ArrayType>;
1197
1198pub fn same_array_ref(a: &ArrayTypeRef, b: &ArrayTypeRef) -> bool {
1199 Rc::ptr_eq(a, b)
1200}
1201
1202#[derive(Debug, Eq, PartialEq)]
1203pub struct ArrayType {
1204 pub item_type: Type,
1205}
1206
1207pub type MapTypeRef = Rc<MapType>;
1208
1209#[derive(Debug, Eq, PartialEq)]
1210pub struct MapType {
1211 pub key_type: Type,
1212 pub value_type: Type,
1213}
1214
1215pub type EnumVariantStructTypeRef = Rc<EnumVariantStructType>;
1216
1217pub fn sort_struct_fields2(
1235 unordered_seq_map: &SeqMap<String, StructTypeField>,
1236) -> SeqMap<String, StructTypeField> {
1237 let mut sorted_pairs: Vec<(&String, &StructTypeField)> = unordered_seq_map.iter().collect();
1238 sorted_pairs.sort_by(|a, b| a.0.cmp(b.0));
1239
1240 sorted_pairs
1241 .into_iter()
1242 .map(|(name, field)| (name.clone(), field.clone()))
1243 .collect()
1244}
1245
1246#[derive(Clone, Eq, PartialEq)]
1247pub struct AnonymousStructType {
1248 pub field_name_sorted_fields: SeqMap<String, StructTypeField>,
1250}
1251
1252impl Debug for AnonymousStructType {
1253 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1254 write!(f, "{}", comma_seq(&self.field_name_sorted_fields))
1255 }
1256}
1257
1258impl AnonymousStructType {
1259 pub fn new_and_sort_fields(source_ordered_fields: SeqMap<String, StructTypeField>) -> Self {
1260 Self {
1261 field_name_sorted_fields: sort_struct_fields2(&source_ordered_fields),
1262 }
1263 }
1264
1265 pub fn new(defined_order: SeqMap<String, StructTypeField>) -> Self {
1266 Self {
1267 field_name_sorted_fields: defined_order,
1268 }
1269 }
1270}
1271
1272#[derive(Debug, Eq, PartialEq)]
1273pub struct EnumVariantStructType {
1274 pub common: EnumVariantCommon,
1275 pub anon_struct: AnonymousStructType,
1276}
1277
1278pub type EnumVariantTupleTypeRef = Rc<EnumVariantTupleType>;
1279
1280#[derive(Debug, Eq, PartialEq)]
1281pub struct EnumVariantTupleType {
1282 pub common: EnumVariantCommon,
1283 pub fields_in_order: Vec<Type>,
1284}
1285
1286pub type TupleTypeRef = Rc<TupleType>;
1287
1288#[derive(Debug, Eq, PartialEq)]
1289pub struct TupleType(pub Vec<Type>);
1290
1291impl TupleType {
1292 pub fn new(types: Vec<Type>) -> Self {
1293 Self(types)
1294 }
1295}
1296
1297pub type EnumTypeRef = Rc<RefCell<EnumType>>;
1298
1299#[derive(Eq, PartialEq)]
1300pub struct EnumType {
1301 pub name: LocalTypeIdentifier,
1302 pub assigned_name: String,
1303 pub module_path: Vec<String>,
1304 pub number: TypeNumber,
1305
1306 pub variants: SeqMap<String, EnumVariantTypeRef>,
1307}
1308
1309impl Debug for EnumType {
1310 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1311 write!(f, "{}", self.assigned_name)?;
1312 let s = comma(
1313 &self
1314 .variants
1315 .iter()
1316 .map(|(name, _variant)| name)
1317 .collect::<Vec<&String>>(),
1318 );
1319 write!(f, "{{ {s} }}")
1320 }
1321}
1322
1323impl EnumType {
1324 #[must_use]
1325 pub fn new(
1326 name: LocalTypeIdentifier,
1327 assigned_name: &str,
1328 module_path: Vec<String>,
1329 number: TypeNumber,
1330 ) -> Self {
1331 Self {
1332 name,
1333 assigned_name: assigned_name.to_string(),
1334 module_path,
1335 number,
1336 variants: SeqMap::new(),
1337 }
1338 }
1339
1340 #[must_use]
1341 pub const fn name(&self) -> &LocalTypeIdentifier {
1342 &self.name
1343 }
1344
1345 pub fn get_variant(&self, name: &str) -> Option<&EnumVariantTypeRef> {
1346 self.variants.get(&name.to_string())
1347 }
1348
1349 pub fn get_variant_from_index(&self, index: usize) -> Option<&EnumVariantTypeRef> {
1350 Some(self.variants.values().collect::<Vec<_>>()[index])
1351 }
1352}
1353
1354pub type EnumVariantTypeRef = Rc<EnumVariantType>;
1355
1356#[derive(Eq, PartialEq, Clone)]
1357pub struct EnumVariantCommon {
1358 pub name: LocalTypeIdentifier,
1359 pub assigned_name: String,
1360 pub number: TypeNumber,
1361 pub container_index: u8,
1362 pub owner: EnumTypeRef,
1363}
1364
1365impl Debug for EnumVariantCommon {
1366 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
1367 write!(
1368 f,
1369 "<{}>{}::{}",
1370 self.number,
1371 self.owner.borrow().assigned_name,
1372 self.assigned_name
1373 )
1374 }
1375}
1376
1377pub type EnumVariantStructFieldTypeRef = Rc<EnumVariantStructFieldType>;
1378
1379#[derive(Debug)]
1380pub struct EnumVariantStructFieldType {
1381 pub name: LocalIdentifier,
1382 pub enum_variant: EnumVariantTypeRef,
1383 pub resolved_type: Type,
1384
1385 pub field_index: usize,
1386}
1387
1388pub type EnumVariantTupleFieldTypeRef = Rc<EnumVariantTupleFieldType>;
1389
1390#[derive(Debug, Eq, PartialEq)]
1391pub struct EnumVariantTupleFieldType {
1392 pub name: LocalIdentifier,
1393 pub enum_variant: EnumVariantTypeRef,
1394 pub resolved_type: Type,
1395
1396 pub field_index: usize,
1397}
1398
1399#[derive(Debug, Clone, Eq, PartialEq)]
1400pub struct EnumVariantSimpleType {
1401 pub common: EnumVariantCommon,
1402}
1403
1404pub type EnumVariantSimpleTypeRef = Rc<EnumVariantSimpleType>;
1405
1406#[derive(Clone, Eq, PartialEq)]
1407pub enum EnumVariantType {
1408 Struct(EnumVariantStructTypeRef),
1409 Tuple(EnumVariantTupleTypeRef),
1410 Nothing(EnumVariantSimpleTypeRef),
1411}
1412impl EnumVariantType {
1413 pub fn common(&self) -> &EnumVariantCommon {
1414 match self {
1415 Self::Tuple(tuple) => &tuple.common,
1416 Self::Struct(c) => &c.common,
1417 Self::Nothing(c) => &c.common,
1418 }
1419 }
1420}
1421
1422impl Debug for EnumVariantType {
1423 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1424 match self {
1425 Self::Struct(x) => write!(f, "{{ {x:?} }}"),
1426 Self::Tuple(x) => write!(f, "({x:?})"),
1427 Self::Nothing(_x) => Ok(()),
1428 }
1429 }
1430}
1431
1432#[derive(Debug)]
1433pub struct ImplMember {}
1434
1435#[derive(Debug)]
1436pub enum UseItem {
1437 Identifier(Node),
1438 TypeIdentifier(Node),
1439}
1440
1441#[derive(Debug)]
1442pub struct Use {
1443 pub path: Vec<Node>,
1444 pub items: Vec<UseItem>,
1445}
1446
1447#[derive(Debug)]
1449pub struct ProgramState {
1450 pub array_types: Vec<ArrayTypeRef>,
1451 pub number: TypeNumber,
1452 pub external_function_number: ExternalFunctionId,
1453 pub constants_in_dependency_order: Vec<ConstantRef>,
1457}
1458
1459impl ProgramState {
1460 pub fn new() -> Self {
1461 Self {
1462 array_types: Vec::new(),
1463 number: 0,
1464 external_function_number: 0,
1465 constants_in_dependency_order: Vec::new(),
1466 }
1467 }
1468
1469 pub fn allocate_number(&mut self) -> TypeNumber {
1470 self.number += 1;
1471 self.number
1472 }
1473
1474 pub fn allocate_external_function_id(&mut self) -> ExternalFunctionId {
1475 self.external_function_number += 1;
1476 self.external_function_number
1477 }
1478}
1479
1480#[derive()]
1481pub enum EnumLiteralData {
1482 Nothing,
1483 Tuple(Vec<Expression>),
1484 Struct(Vec<(usize, Expression)>),
1485}
1486
1487impl Debug for EnumLiteralData {
1488 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1489 match self {
1490 Self::Nothing => Ok(()),
1491 Self::Tuple(x) => write!(f, "{x:?}"),
1492 Self::Struct(s) => write!(f, "{s:?}"),
1493 }
1494 }
1495}