1pub mod err;
6pub mod intr;
7pub mod prelude;
8use crate::err::{Error, ErrorKind};
9use crate::intr::IntrinsicFunction;
10use crate::prelude::IntrinsicFunctionDefinitionRef;
11pub use fixed32::Fp;
12use seq_map::SeqMap;
13use source_map_node::Node;
14use std::cmp::PartialEq;
15use std::fmt;
16use std::fmt::{Debug, Display, Formatter};
17use std::rc::Rc;
18use swamp_attributes::Attributes;
19use swamp_types::prelude::*;
20use swamp_types::{Type, TypeRef};
21use tracing::error;
22
23#[derive(Debug, Clone)]
24pub struct TypeWithMut {
25 pub resolved_type: TypeRef,
26 pub is_mutable: bool,
27}
28
29#[derive(Debug, Clone)]
30pub enum SemanticError {
31 CouldNotInsertStruct,
32 DuplicateTypeAlias(String),
33 CanOnlyUseStructForMemberFunctions,
34 ResolveNotStruct,
35 DuplicateStructName(String),
36 DuplicateEnumType(String),
37 DuplicateEnumVariantType(String, String),
38 DuplicateFieldName(String),
39 DuplicateExternalFunction(String),
40 DuplicateRustType(String),
41 DuplicateConstName(String),
42 CircularConstantDependency(Vec<ConstantId>),
43 DuplicateConstantId(ConstantId),
44 IncompatibleTypes,
45 WasNotImmutable,
46 WasNotMutable,
47 DuplicateSymbolName(String),
48 DuplicateNamespaceLink(String),
49 MismatchedTypes {
50 expected: TypeRef,
51 found: Vec<TypeRef>,
52 },
53 UnknownImplOnType,
54 UnknownTypeVariable,
55 DuplicateDefinition(String),
56}
57
58#[derive(Debug, Eq, PartialEq)]
59pub struct LocalIdentifier(pub Node);
60
61#[derive(Debug)]
62pub struct InternalMainExpression {
63 pub expression: Expression,
64 pub scopes: VariableScopes,
65 pub program_unique_id: InternalFunctionId,
66}
67
68pub fn formal_function_name(internal_fn_def: &InternalFunctionDefinition) -> String {
69 let prefix = internal_fn_def
70 .associated_with_type
71 .as_ref()
72 .map_or_else(String::new, |associated_with_type| {
73 format!("{associated_with_type}::")
74 });
75 format!(
76 "{}::{}{}",
77 formal_module_name(&internal_fn_def.defined_in_module_path),
78 prefix,
79 internal_fn_def.assigned_name
80 )
81}
82
83pub struct InternalFunctionDefinition {
85 pub body: Expression,
86 pub name: LocalIdentifier,
87 pub assigned_name: String,
88 pub associated_with_type: Option<TypeRef>,
89 pub defined_in_module_path: Vec<String>,
90 pub signature: Signature,
91 pub function_variables: VariableScopes,
92 pub program_unique_id: InternalFunctionId,
93 pub attributes: Attributes,
94}
95
96impl Default for InternalFunctionDefinition {
97 fn default() -> Self {
98 Self {
99 body: Expression {
100 ty: Rc::new(Type {
101 id: TypeId::new(0),
102 flags: TypeFlags::default(),
103 kind: Rc::new(TypeKind::Byte),
104 }),
105 node: Node::default(),
106 kind: ExpressionKind::NoneLiteral,
107 },
108 name: LocalIdentifier(Node::default()),
109 assigned_name: String::new(),
110 associated_with_type: None,
111 defined_in_module_path: vec![],
112 signature: Signature {
113 parameters: vec![],
114 return_type: Rc::new(Type {
115 id: TypeId::new(0),
116 flags: TypeFlags::default(),
117 kind: Rc::new(TypeKind::Byte),
118 }),
119 },
120 function_variables: VariableScopes::default(),
121 program_unique_id: 0,
122 attributes: Attributes::default(),
123 }
124 }
125}
126
127impl InternalFunctionDefinition {}
128
129impl Debug for InternalFunctionDefinition {
130 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
131 write!(f, "{:?}\n{:?}", self.signature, self.body)
132 }
133}
134
135impl PartialEq<Self> for InternalFunctionDefinition {
136 fn eq(&self, other: &Self) -> bool {
137 self.name == other.name
138 }
139}
140
141impl Eq for InternalFunctionDefinition {}
142
143pub type InternalFunctionDefinitionRef = Rc<InternalFunctionDefinition>;
144
145pub type ExternalFunctionId = u32;
146
147pub type InternalFunctionId = u16;
148
149pub type ConstantId = u32;
150
151#[must_use]
152pub fn pretty_module_name(parts: &[String]) -> String {
153 if parts[0] == "crate" {
154 parts[1..].join("::")
155 } else {
156 parts.join("::")
157 }
158}
159
160#[must_use]
161pub fn formal_module_name(parts: &[String]) -> String {
162 parts.join("::")
163}
164
165#[derive(Eq, PartialEq)]
166pub struct ExternalFunctionDefinition {
167 pub name: Option<Node>,
168 pub assigned_name: String,
169 pub signature: Signature,
170 pub id: ExternalFunctionId,
171}
172
173impl Debug for ExternalFunctionDefinition {
174 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
175 write!(f, "external fn")
176 }
177}
178
179pub type ExternalFunctionDefinitionRef = Rc<crate::ExternalFunctionDefinition>;
180
181#[derive(Debug, Eq, Clone, PartialEq)]
182pub enum BlockScopeMode {
183 Open,
184 Closed,
185 Lambda,
186}
187
188#[derive(Debug, Clone)]
189pub struct BlockScope {
190 pub mode: BlockScopeMode,
191 pub lookup: SeqMap<String, VariableRef>,
192 pub variables: SeqMap<usize, VariableRef>,
193 pub register_watermark: usize,
194}
195
196impl Display for BlockScope {
197 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
198 writeln!(f, "-- scope {:?}", self.mode)?;
199
200 for (index, (name, var)) in self.variables.iter().enumerate() {
201 writeln!(f, " var({index}): {name}:{var:?}")?;
202 }
203 Ok(())
204 }
205}
206
207impl Default for BlockScope {
208 fn default() -> Self {
209 Self::new()
210 }
211}
212
213impl BlockScope {
214 #[must_use]
215 pub fn new() -> Self {
216 Self {
217 mode: BlockScopeMode::Open,
218 variables: SeqMap::new(),
219 lookup: SeqMap::new(),
220 register_watermark: 0,
221 }
222 }
223}
224
225#[derive(Debug, Clone)]
226pub struct VariableScope {
227 pub mode: BlockScopeMode,
228 pub variables: SeqMap<usize, VariableRef>,
229}
230
231#[derive(Clone, Debug)]
232pub struct VariableScopes {
233 pub current_register: usize,
235 pub highest_virtual_register: usize,
236 pub all_variables: Vec<VariableRef>,
237}
238
239impl VariableScopes {
240 #[must_use]
241 pub const fn new() -> Self {
242 Self {
243 current_register: 0,
245 all_variables: vec![],
246 highest_virtual_register: 0,
247 }
248 }
249
250 pub const fn finalize(&mut self) {
251 self.highest_virtual_register = self.current_register;
252 }
253}
254impl Default for VariableScopes {
255 fn default() -> Self {
256 Self::new()
257 }
258}
259
260#[derive(Clone, Debug)]
261pub struct FunctionScopeState {
262 pub block_scope_stack: Vec<BlockScope>,
263 pub variable_index: usize,
264}
265
266#[derive(Clone, Debug)]
267pub struct ScopeInfo {
268 pub active_scope: FunctionScopeState,
269 pub total_scopes: VariableScopes,
270}
271
272impl ScopeInfo {
273 #[must_use]
274 pub fn new() -> Self {
275 Self {
276 active_scope: FunctionScopeState::default(),
277 total_scopes: VariableScopes::default(),
278 }
279 }
280}
281
282impl Default for ScopeInfo {
283 fn default() -> Self {
284 Self::new()
285 }
286}
287
288impl Display for FunctionScopeState {
289 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
290 for (index, scope) in self.block_scope_stack.iter().enumerate() {
291 writeln!(f, "block({index}):\n{scope}")?;
292 }
293 Ok(())
294 }
295}
296
297impl FunctionScopeState {
298 pub const fn emit_variable_index(&mut self) -> usize {
299 self.variable_index += 1;
300
301 self.variable_index
302 }
303}
304
305impl Default for FunctionScopeState {
306 fn default() -> Self {
307 Self::new()
308 }
309}
310
311impl FunctionScopeState {
312 #[must_use]
313 pub fn new() -> Self {
314 Self {
315 block_scope_stack: vec![BlockScope::new()],
316 variable_index: 0,
318 }
319 }
320}
321
322#[derive(Debug, Clone)]
323pub enum VariableType {
324 Local,
325 Parameter,
326}
327
328#[derive(Debug, Clone)]
329pub struct Variable {
330 pub name: Node,
331 pub assigned_name: String,
332 pub resolved_type: TypeRef,
333 pub mutable_node: Option<Node>,
334 pub variable_type: VariableType,
335
336 pub scope_index: usize,
337 pub variable_index: usize,
338 pub unique_id_within_function: usize,
339 pub virtual_register: u8,
340
341 pub is_unused: bool,
342}
343
344impl Variable {
345 #[must_use]
346 pub fn create_err(unit_type: TypeRef) -> Self {
347 Self {
348 name: Node::default(),
349 assigned_name: "err".to_string(),
350 resolved_type: unit_type,
351 mutable_node: None,
352 variable_type: VariableType::Local,
353 scope_index: 0,
354 variable_index: 0,
355 virtual_register: 0,
356 unique_id_within_function: 0,
357 is_unused: false,
358 }
359 }
360}
361
362impl Variable {
363 #[must_use]
364 pub const fn is_mutable(&self) -> bool {
365 self.mutable_node.is_some()
366 }
367
368 #[must_use]
369 pub const fn is_immutable(&self) -> bool {
370 !self.is_mutable()
371 }
372}
373
374pub type VariableRef = Rc<Variable>;
375
376#[derive(Debug, Clone)]
377pub struct MutVariable {
378 pub variable_ref: VariableRef,
379}
380
381#[derive(Debug, Clone)]
384pub enum BinaryOperatorKind {
385 Add,
386 Subtract,
387 Multiply,
388 Divide,
389 Modulo,
390 LogicalOr,
391 LogicalAnd,
392 Equal,
393 NotEqual,
394 LessThan,
395 LessEqual,
396 GreaterThan,
397 GreaterEqual,
398 NoneCoalesce,
399}
400
401#[derive(Debug, Clone)]
402pub struct BinaryOperator {
403 pub left: Box<Expression>,
404 pub right: Box<Expression>,
405 pub kind: BinaryOperatorKind,
406 pub node: Node,
407}
408
409#[derive(Debug, Clone)]
410pub enum UnaryOperatorKind {
411 Not,
412 Negate,
413}
414#[derive(Debug, Clone)]
415pub struct UnaryOperator {
416 pub left: Box<Expression>,
417 pub kind: UnaryOperatorKind,
418 pub node: Node,
419}
420
421#[derive()]
422pub struct InternalFunctionCall {
423 pub arguments: Vec<ArgumentExpression>,
424
425 pub function_definition: InternalFunctionDefinitionRef,
426 pub function_expression: Box<Expression>,
427}
428
429impl Debug for InternalFunctionCall {
430 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
431 write!(
432 f,
433 "InFuncCall({:?} {:?})",
434 self.function_expression, self.arguments
435 )
436 }
437}
438
439#[derive(Debug, Clone)]
440pub struct ExternalFunctionCall {
441 pub arguments: Vec<ArgumentExpression>,
442 pub function_definition: ExternalFunctionDefinitionRef,
443 pub function_expression: Box<Expression>,
444}
445
446pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
447 let mut result = String::new();
448 for (i, (key, value)) in values.iter().enumerate() {
449 if i > 0 {
450 result.push_str(", ");
451 }
452 result.push_str(format!("{key}: {value}").as_str());
453 }
454 result
455}
456
457#[derive(Debug, Clone)]
458pub struct MemberCall {
459 pub function: FunctionRef,
460 pub arguments: Vec<ArgumentExpression>,
461}
462
463#[derive(Debug, Clone)]
464pub struct ArrayItem {
465 pub item_type: Rc<TypeRef>,
466 pub int_expression: Expression,
467 pub array_expression: Expression,
468 pub array_type: Rc<TypeRef>,
469}
470
471pub type ArrayItemRef = Rc<ArrayItem>;
472
473#[derive(Debug, Clone)]
474pub enum PrecisionType {
475 Float,
476 String,
477}
478
479#[derive(Debug, Clone)]
480pub enum FormatSpecifierKind {
481 LowerHex, UpperHex, Binary, Float, Precision(u32, Node, PrecisionType), }
487
488#[derive(Debug, Clone)]
489pub struct FormatSpecifier {
490 pub node: Node,
491 pub kind: FormatSpecifierKind,
492}
493
494pub type FunctionRef = Rc<Function>;
495
496#[derive(Debug, Eq, Clone, PartialEq)]
497pub enum Function {
498 Internal(InternalFunctionDefinitionRef),
499 External(ExternalFunctionDefinitionRef),
500 Intrinsic(IntrinsicFunctionDefinitionRef),
501}
502
503impl Function {
504 #[must_use]
505 pub fn name(&self) -> String {
506 match self {
507 Self::Internal(x) => x.assigned_name.clone(),
508 Self::External(y) => y.assigned_name.clone(),
509 Self::Intrinsic(i) => i.name.clone(),
510 }
511 }
512
513 #[must_use]
514 pub fn maybe_node(&self) -> Option<&Node> {
515 match self {
516 Self::Internal(x) => Some(&x.name.0),
517 Self::External(y) => y.name.as_ref(),
518 Self::Intrinsic(_i) => None,
519 }
520 }
521
522 #[must_use]
523 pub fn node(&self) -> Node {
524 match self {
525 Self::Internal(x) => x.name.0.clone(),
526 Self::External(_y) => Node::new_unknown(),
527 Self::Intrinsic(_i) => Node::new_unknown(),
528 }
529 }
530
531 #[must_use]
532 pub fn signature(&self) -> &Signature {
533 match self {
534 Self::Internal(internal) => &internal.signature,
535 Self::External(external) => &external.signature,
536 Self::Intrinsic(i) => &i.signature,
537 }
538 }
539}
540
541#[derive(Debug, Clone)]
542pub struct BooleanExpression {
543 #[allow(unused)]
544 pub expression: Box<Expression>,
545}
546
547#[derive(Debug, Clone)]
549pub struct Match {
550 pub arms: Vec<MatchArm>,
551 pub expression: Box<Expression>,
552}
553
554impl Match {
555 #[must_use]
556 pub fn contains_wildcard(&self) -> bool {
557 for arm in &self.arms {
558 if let Pattern::Wildcard(_) = arm.pattern {
559 return true;
560 }
561 }
562 false
563 }
564}
565
566#[derive(Debug, Clone)]
567pub struct MatchArm {
568 #[allow(unused)]
569 pub pattern: Pattern,
570 pub expression: Box<Expression>,
571 pub expression_type: TypeRef,
572}
573
574#[derive(Debug, Clone)]
575pub enum Pattern {
576 Normal(NormalPattern, Option<BooleanExpression>),
577 Wildcard(Node),
578}
579
580#[derive(Debug, Clone)]
581pub enum NormalPattern {
582 PatternList(Vec<PatternElement>),
583 EnumPattern(EnumVariantType, Option<Vec<PatternElement>>),
584 Literal(Expression),
585}
586
587#[derive(Debug, Clone)]
588pub enum PatternElement {
589 Variable(VariableRef),
590 VariableWithFieldIndex(VariableRef, usize),
591 Wildcard(Node),
592}
593
594#[derive(Debug, Clone)]
595pub struct Iterable {
596 pub key_type: Option<TypeRef>, pub value_type: TypeRef,
598
599 pub resolved_expression: Box<Expression>,
600}
601
602#[derive(Debug, Clone)]
603pub struct AnonymousStructLiteral {
604 pub source_order_expressions: Vec<(usize, Option<Node>, Expression)>,
605 pub struct_like_type: TypeRef,
606}
607
608#[derive(Debug, Clone, Eq, PartialEq)]
609pub enum CompoundOperatorKind {
610 Add,
611 Sub,
612 Mul,
613 Div,
614 Modulo,
615}
616
617#[derive(Debug, Clone)]
618pub struct CompoundOperator {
619 pub node: Node,
620 pub kind: CompoundOperatorKind,
621}
622
623#[derive(Debug, Clone)]
624pub struct VariableCompoundAssignment {
625 pub variable_ref: VariableRef, pub expression: Box<Expression>,
627 pub compound_operator: CompoundOperator,
628}
629
630#[derive(Debug, Clone)]
631pub struct Guard {
632 pub condition: Option<BooleanExpression>,
633 pub result: Expression,
634}
635
636#[derive(Debug, Clone)]
637pub struct Postfix {
638 pub node: Node,
639 pub ty: TypeRef,
640 pub kind: PostfixKind,
641}
642
643#[derive(Debug, Clone)]
644pub struct SliceViewType {
645 pub element: TypeRef,
646}
647
648#[derive(Debug, Clone)]
649pub struct VecType {
650 pub element: TypeRef,
651}
652
653#[derive(Debug, Clone)]
654pub struct GridType {
655 pub element: TypeRef,
656}
657
658#[derive(Debug, Clone)]
659pub struct SparseType {
660 pub element: TypeRef,
661}
662
663#[derive(Debug, Clone)]
664pub struct MapType {
665 pub key: TypeRef,
666 pub value: TypeRef,
667}
668
669#[derive(Debug, Clone)]
670pub enum PostfixKind {
671 StructField(TypeRef, usize),
672 MemberCall(FunctionRef, Vec<ArgumentExpression>),
673 OptionalChainingOperator, VecSubscript(VecType, Expression),
676 VecSubscriptRange(VecType, Expression),
677 SparseSubscript(SparseType, Expression),
678 MapSubscript(MapType, Expression),
679 GridSubscript(GridType, Expression, Expression),
680}
681
682#[derive(Debug, Clone)]
683pub enum LocationAccessKind {
684 FieldIndex(AnonymousStructType, usize),
685 SliceViewSubscript(SliceViewType, Expression),
686 MapSubscriptCreateIfNeeded(MapType, Expression),
687 MapSubscriptMustExist(MapType, Expression),
688 SparseSubscript(SparseType, Expression),
689 GridSubscript(GridType, Expression, Expression),
690}
691
692#[derive(Debug, Clone)]
693pub struct LocationAccess {
694 pub node: Node,
695 pub ty: TypeRef,
696 pub kind: LocationAccessKind,
697}
698
699#[derive(Debug, Clone)]
700pub struct SingleLocationExpression {
701 pub kind: MutableReferenceKind,
702 pub node: Node,
703 pub ty: TypeRef,
704
705 pub starting_variable: VariableRef,
706 pub access_chain: Vec<LocationAccess>,
707}
708
709#[derive(Debug, Clone)]
710pub struct TargetAssignmentLocation(pub SingleLocationExpression);
711
712#[derive(Debug, Clone)]
713pub enum MutableReferenceKind {
714 MutVariableRef,
715 MutStructFieldRef(AnonymousStructType, usize),
716}
717
718#[derive(Debug, Clone)]
719pub enum ArgumentExpression {
720 Expression(Expression),
721 BorrowMutableReference(SingleLocationExpression),
722}
723
724impl ArgumentExpression {
725 #[must_use]
726 pub fn ty(&self) -> TypeRef {
727 match self {
728 Self::Expression(expr) => expr.ty.clone(),
729 Self::BorrowMutableReference(location) => location.ty.clone(),
730 }
731 }
732
733 pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
734 match self {
735 Self::Expression(expr) => Ok(expr),
736 Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
737 }
738 }
739
740 pub const fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
741 match &self {
742 Self::Expression(expr) => Ok(expr),
743 Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
744 }
745 }
746
747 #[must_use]
748 pub const fn is_mutable_reference(&self) -> bool {
749 matches!(self, Self::BorrowMutableReference(_))
750 }
751
752 #[must_use]
753 pub const fn node(&self) -> &Node {
754 match &self {
755 Self::Expression(expr) => &expr.node,
756 Self::BorrowMutableReference(loc) => &loc.node,
757 }
758 }
759}
760
761#[derive(Clone)]
762pub struct Expression {
763 pub ty: TypeRef,
764 pub node: Node,
765 pub kind: ExpressionKind,
766}
767
768impl Expression {
769 #[must_use]
770 pub fn debug_last_expression(&self) -> &Self {
771 match &self.kind {
772 ExpressionKind::ConstantAccess(a) => a.expr.debug_last_expression(),
773 ExpressionKind::BinaryOp(binary) => binary.right.debug_last_expression(),
774 ExpressionKind::UnaryOp(a) => a.left.debug_last_expression(),
775 ExpressionKind::ForLoop(_, _, a) => a.debug_last_expression(),
776 ExpressionKind::WhileLoop(_, a) => a.debug_last_expression(),
777 ExpressionKind::Block(block) => block.last().unwrap_or(self),
778 ExpressionKind::Match(a) => a.arms.last().unwrap().expression.debug_last_expression(),
779 ExpressionKind::Guard(g) => g.last().unwrap().result.debug_last_expression(),
780 ExpressionKind::If(_, a, _) => a.debug_last_expression(),
781 ExpressionKind::When(_, b, _a) => b,
782 ExpressionKind::TupleDestructuring(_, _, x) => x,
783 ExpressionKind::Lambda(_, a) => a.debug_last_expression(),
784 _ => self,
785 }
786 }
787}
788
789impl Debug for Expression {
790 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
791 write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
792 }
793}
794
795#[derive(Debug, Clone)]
796pub struct WhenBinding {
797 pub variable: VariableRef,
798 pub expr: Expression,
799}
800
801impl WhenBinding {
802 #[must_use]
803 pub const fn has_expression(&self) -> bool {
804 !matches!(self.expr.kind, ExpressionKind::VariableAccess(_))
805 }
806}
807
808#[derive(Debug, Clone)]
809pub enum StartOfChainKind {
810 Expression(Box<Expression>),
811 Variable(VariableRef),
812}
813
814#[derive(Debug, Clone)]
815pub struct StartOfChain {
816 pub kind: StartOfChainKind,
817 pub node: Node,
818}
819
820impl StartOfChain {}
821
822impl StartOfChainKind {
823 #[must_use]
824 pub fn ty(&self) -> TypeRef {
825 match self {
826 Self::Expression(expr) => expr.ty.clone(),
827 Self::Variable(var) => var.resolved_type.clone(),
828 }
829 }
830
831 #[must_use]
832 pub fn is_mutable(&self) -> bool {
833 match self {
834 Self::Expression(_call) => {
835 false
837 }
838 Self::Variable(var) => var.is_mutable(),
839 }
840 }
841}
842
843#[derive(Debug, Clone)]
844pub enum ExpressionKind {
845 ConstantAccess(ConstantRef),
847 VariableAccess(VariableRef),
848
849 BinaryOp(BinaryOperator),
853 UnaryOp(UnaryOperator),
854 PostfixChain(StartOfChain, Vec<Postfix>),
855
856 CoerceOptionToBool(Box<Expression>),
859 CoerceIntToChar(Box<Expression>),
860
861 IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpression>),
863 InternalCall(InternalFunctionDefinitionRef, Vec<ArgumentExpression>),
864 HostCall(ExternalFunctionDefinitionRef, Vec<ArgumentExpression>),
865
866 VariableDefinition(VariableRef, Box<Expression>), VariableDefinitionLValue(VariableRef, SingleLocationExpression), VariableReassignment(VariableRef, Box<Expression>),
870
871 Assignment(Box<TargetAssignmentLocation>, Box<Expression>),
872 CompoundAssignment(
873 TargetAssignmentLocation,
874 CompoundOperatorKind,
875 Box<Expression>,
876 ),
877
878 AnonymousStructLiteral(AnonymousStructLiteral),
879
880 FloatLiteral(Fp),
881 NoneLiteral,
882 IntLiteral(i32),
883 StringLiteral(String),
884 BoolLiteral(bool),
885 EnumVariantLiteral(EnumVariantType, EnumLiteralExpressions), TupleLiteral(Vec<Expression>),
887
888 InitializerList(TypeRef, Vec<Expression>),
889 InitializerPairList(TypeRef, Vec<(Expression, Expression)>),
890
891 Option(Option<Box<Expression>>), ForLoop(ForPattern, Iterable, Box<Expression>),
895 WhileLoop(BooleanExpression, Box<Expression>),
896
897 Block(Vec<Expression>),
898
899 Match(Match),
901 Guard(Vec<Guard>),
902 If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
903 When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
904
905 TupleDestructuring(Vec<VariableRef>, TypeRef, Box<Expression>),
906
907 Lambda(Vec<VariableRef>, Box<Expression>),
908 BorrowMutRef(Box<SingleLocationExpression>),
909 Error(ErrorKind),
910}
911
912#[derive(Debug, Clone)]
913pub struct StringConst(pub Node);
914
915#[derive(Debug, Clone)]
916pub struct ArrayInstantiation {
917 pub expressions: Vec<Expression>,
918 pub item_type: TypeRef,
919 pub array_type: TypeRef,
920 pub array_type_ref: TypeRef,
921}
922
923#[derive(Debug, Clone)]
924pub enum ForPattern {
925 Single(VariableRef),
926 Pair(VariableRef, VariableRef),
927}
928
929impl ForPattern {
930 #[must_use]
931 pub fn is_mutable(&self) -> bool {
932 match self {
933 Self::Single(variable) => variable.is_mutable(),
934 Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
935 }
936 }
937}
938
939impl Display for ForPattern {
940 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
941 write!(f, "resolved_for_pattern")
942 }
943}
944
945#[derive(Debug, Eq, PartialEq)]
946pub struct ModulePathItem(pub Node);
947
948#[derive(Debug, Clone, Eq, PartialEq)]
949pub struct LocalTypeIdentifier(pub Node);
950
951#[derive(Debug, Clone)]
952pub struct Constant {
953 pub name: Node,
954 pub assigned_name: String,
955 pub id: ConstantId,
956 pub expr: Expression,
957 pub resolved_type: TypeRef,
958 pub function_scope_state: VariableScopes,
959}
960pub type ConstantRef = Rc<Constant>;
961
962pub type OptionTypeRef = Rc<OptionType>;
963
964#[derive(Debug, Clone)]
965pub struct OptionType {
966 pub item_type: TypeRef,
967}
968
969#[derive(Debug, Clone)]
986pub struct ImplMember {}
987
988#[derive(Debug, Clone)]
989pub enum UseItem {
990 Identifier(Node),
991 TypeIdentifier(Node),
992}
993
994#[derive(Debug, Clone)]
995pub struct Use {
996 pub path: Vec<Node>,
997 pub items: Vec<UseItem>,
998}
999
1000#[derive(Debug, Clone)]
1001pub struct ImplFunctions {
1002 pub functions: SeqMap<String, FunctionRef>,
1003}
1004
1005impl Default for ImplFunctions {
1006 fn default() -> Self {
1007 Self::new()
1008 }
1009}
1010
1011impl ImplFunctions {
1012 #[must_use]
1013 pub fn new() -> Self {
1014 Self {
1015 functions: SeqMap::default(),
1016 }
1017 }
1018}
1019
1020#[derive(Debug, Clone)]
1021pub struct AssociatedImpls {
1022 pub functions: SeqMap<TypeRef, ImplFunctions>,
1023}
1024
1025impl AssociatedImpls {}
1026
1027impl AssociatedImpls {}
1028
1029impl AssociatedImpls {}
1030
1031impl Default for AssociatedImpls {
1032 fn default() -> Self {
1033 Self::new()
1034 }
1035}
1036
1037impl AssociatedImpls {
1038 #[must_use]
1039 pub fn new() -> Self {
1040 Self {
1041 functions: SeqMap::default(),
1042 }
1043 }
1044}
1045
1046impl AssociatedImpls {
1047 pub fn prepare(&mut self, ty: &TypeRef) {
1048 self.functions
1049 .insert(ty.clone(), ImplFunctions::new())
1050 .unwrap_or_else(|_| panic!("should work {ty:?}"));
1051 }
1052
1053 #[must_use]
1054 pub fn is_prepared(&self, ty: &TypeRef) -> bool {
1055 self.functions.contains_key(ty)
1056 }
1057 #[must_use]
1058 pub fn get_member_function(&self, ty: &TypeRef, function_name: &str) -> Option<&FunctionRef> {
1059 let maybe_found_impl = self.functions.get(ty);
1060 if let Some(found_impl) = maybe_found_impl {
1061 if let Some(func) = found_impl.functions.get(&function_name.to_string()) {
1062 return Some(func);
1063 }
1064 }
1065 None
1066 }
1067
1068 fn has_internal_member_function(&self, ty: &TypeRef, function_name: &str) -> bool {
1069 let maybe_found_impl = self.functions.get(ty);
1070 if let Some(found_impl) = maybe_found_impl {
1071 if let Some(_func) = found_impl.functions.get(&function_name.to_string()) {
1072 return true;
1073 }
1074 }
1075 false
1076 }
1077
1078 #[must_use]
1079 pub fn api_get_external_function(
1080 &self,
1081 ty: &TypeRef,
1082 function_name: &str,
1083 ) -> Option<&ExternalFunctionDefinitionRef> {
1084 if let Some(found) = self.get_member_function(ty, function_name) {
1085 if let Function::External(ext_fn) = &**found {
1086 return Some(ext_fn);
1087 }
1088 }
1089 None
1090 }
1091
1092 #[must_use]
1093 pub fn get_internal_member_function(
1094 &self,
1095 ty: &TypeRef,
1096 function_name: &str,
1097 ) -> Option<&InternalFunctionDefinitionRef> {
1098 if let Some(found) = self.get_member_function(ty, function_name) {
1099 if let Function::Internal(int_fn) = &**found {
1100 return Some(int_fn);
1101 }
1102 }
1103 None
1104 }
1105
1106 pub fn remove_internal_function_if_exists(
1107 &mut self,
1108 ty: &TypeRef,
1109 function_name: &str,
1110 ) -> bool {
1111 if self.has_internal_member_function(ty, function_name) {
1112 let functions = self.functions.get_mut(ty).unwrap();
1113
1114 functions.functions.remove(&function_name.to_string());
1115 true
1116 } else {
1117 false
1118 }
1119 }
1120
1121 pub fn add_member_function(
1122 &mut self,
1123 ty: &TypeRef,
1124 name: &str,
1125 func: FunctionRef,
1126 ) -> Result<(), SemanticError> {
1127 let maybe_found_impl = self.functions.get_mut(ty);
1128
1129 if let Some(found_impl) = maybe_found_impl {
1130 found_impl
1131 .functions
1132 .insert(name.to_string(), func)
1133 .expect("todo");
1134 Ok(())
1135 } else {
1136 error!(%ty, ?name, "wasn't prepared");
1137 Err(SemanticError::UnknownImplOnType)
1138 }
1139 }
1140
1141 pub fn add_internal_function(
1142 &mut self,
1143 ty: &TypeRef,
1144 func: InternalFunctionDefinition,
1145 ) -> Result<(), SemanticError> {
1146 self.add_member_function(
1148 ty,
1149 &func.assigned_name.clone(),
1150 Function::Internal(func.into()).into(),
1151 )
1152 }
1153
1154 pub fn add_external_member_function(
1155 &mut self,
1156 ty: &TypeRef,
1157 func: ExternalFunctionDefinition,
1158 ) -> Result<(), SemanticError> {
1159 self.add_member_function(
1160 ty,
1161 &func.assigned_name.clone(),
1162 Function::External(func.into()).into(),
1163 )
1164 }
1165
1166 pub fn add_external_struct_member_function(
1167 &mut self,
1168 named_struct_type: TypeRef,
1169 func: Function,
1170 ) -> Result<(), SemanticError> {
1171 self.add_member_function(&named_struct_type, &func.name(), func.into())
1172 }
1173
1174 pub fn add_external_struct_member_function_external(
1175 &mut self,
1176 named_struct_type: TypeRef,
1177 func: ExternalFunctionDefinition,
1178 ) -> Result<(), SemanticError> {
1179 self.add_member_function(
1180 &named_struct_type,
1181 &func.assigned_name.clone(),
1182 Function::External(func.into()).into(),
1183 )
1184 }
1185
1186 pub fn add_external_struct_member_function_external_ref(
1187 &mut self,
1188 named_struct_type: TypeRef,
1189 func: ExternalFunctionDefinitionRef,
1190 ) -> Result<(), SemanticError> {
1191 self.add_member_function(
1192 &named_struct_type,
1193 &func.assigned_name.clone(),
1194 Function::External(func).into(),
1195 )
1196 }
1197}
1198
1199#[derive(Debug, Clone)]
1201pub struct ProgramState {
1202 pub internal_function_id_allocator: InternalFunctionIdAllocator,
1203 pub constants_in_dependency_order: Vec<ConstantRef>,
1207 pub associated_impls: AssociatedImpls,
1208 pub types: TypeCache,
1209 pub errors: Vec<Error>,
1210 pub hints: Vec<Error>,
1211 pub infos: Vec<Error>,
1212}
1213
1214impl ProgramState {
1215 #[must_use]
1216 pub const fn errors(&self) -> &Vec<Error> {
1217 &self.errors
1218 }
1219}
1220
1221impl Default for ProgramState {
1222 fn default() -> Self {
1223 Self::new()
1224 }
1225}
1226
1227#[derive(Debug, Clone)]
1228pub struct InternalFunctionIdAllocator {
1229 pub internal_function_number: InternalFunctionId,
1230}
1231
1232impl Default for InternalFunctionIdAllocator {
1233 fn default() -> Self {
1234 Self::new()
1235 }
1236}
1237
1238impl InternalFunctionIdAllocator {
1239 #[must_use]
1240 pub const fn new() -> Self {
1241 Self {
1242 internal_function_number: 0,
1243 }
1244 }
1245 pub const fn alloc(&mut self) -> InternalFunctionId {
1246 self.internal_function_number += 1;
1247 self.internal_function_number
1248 }
1249}
1250
1251impl ProgramState {
1252 #[must_use]
1253 pub fn new() -> Self {
1254 Self {
1255 internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1256 constants_in_dependency_order: Vec::new(),
1257 associated_impls: AssociatedImpls::new(),
1258 types: TypeCache::new(),
1259 errors: vec![],
1260 hints: vec![],
1261 infos: vec![],
1262 }
1263 }
1264 pub const fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1265 self.internal_function_id_allocator.alloc()
1266 }
1267}
1268
1269#[derive(Clone)]
1270pub enum EnumLiteralExpressions {
1271 Nothing,
1272 Tuple(Vec<Expression>),
1273 Struct(Vec<(usize, Option<Node>, Expression)>),
1274}
1275
1276impl Debug for EnumLiteralExpressions {
1277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1278 match self {
1279 Self::Nothing => Ok(()),
1280 Self::Tuple(x) => write!(f, "{x:?}"),
1281 Self::Struct(s) => write!(f, "{s:?}"),
1282 }
1283 }
1284}