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 CoerceIntToByte(Box<Expression>),
861 CoerceToAny(Box<Expression>),
862
863 IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpression>),
865 InternalCall(InternalFunctionDefinitionRef, Vec<ArgumentExpression>),
866 HostCall(ExternalFunctionDefinitionRef, Vec<ArgumentExpression>),
867
868 VariableDefinition(VariableRef, Box<Expression>), VariableDefinitionLValue(VariableRef, SingleLocationExpression), VariableReassignment(VariableRef, Box<Expression>),
872
873 Assignment(Box<TargetAssignmentLocation>, Box<Expression>),
874 CompoundAssignment(
875 TargetAssignmentLocation,
876 CompoundOperatorKind,
877 Box<Expression>,
878 ),
879
880 AnonymousStructLiteral(AnonymousStructLiteral),
881
882 FloatLiteral(Fp),
883 NoneLiteral,
884 IntLiteral(i32),
885 ByteLiteral(u8),
886 StringLiteral(String),
887 BoolLiteral(bool),
888 EnumVariantLiteral(EnumVariantType, EnumLiteralExpressions), TupleLiteral(Vec<Expression>),
890
891 InitializerList(TypeRef, Vec<Expression>),
892 InitializerPairList(TypeRef, Vec<(Expression, Expression)>),
893
894 Option(Option<Box<Expression>>), ForLoop(ForPattern, Iterable, Box<Expression>),
898 WhileLoop(BooleanExpression, Box<Expression>),
899
900 Block(Vec<Expression>),
901
902 Match(Match),
904 Guard(Vec<Guard>),
905 If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
906 When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
907
908 TupleDestructuring(Vec<VariableRef>, TypeRef, Box<Expression>),
909
910 Lambda(Vec<VariableRef>, Box<Expression>),
911 BorrowMutRef(Box<SingleLocationExpression>),
912 Error(ErrorKind),
913}
914
915#[derive(Debug, Clone)]
916pub struct StringConst(pub Node);
917
918#[derive(Debug, Clone)]
919pub struct ArrayInstantiation {
920 pub expressions: Vec<Expression>,
921 pub item_type: TypeRef,
922 pub array_type: TypeRef,
923 pub array_type_ref: TypeRef,
924}
925
926#[derive(Debug, Clone)]
927pub enum ForPattern {
928 Single(VariableRef),
929 Pair(VariableRef, VariableRef),
930}
931
932impl ForPattern {
933 #[must_use]
934 pub fn is_mutable(&self) -> bool {
935 match self {
936 Self::Single(variable) => variable.is_mutable(),
937 Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
938 }
939 }
940}
941
942impl Display for ForPattern {
943 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
944 write!(f, "resolved_for_pattern")
945 }
946}
947
948#[derive(Debug, Eq, PartialEq)]
949pub struct ModulePathItem(pub Node);
950
951#[derive(Debug, Clone, Eq, PartialEq)]
952pub struct LocalTypeIdentifier(pub Node);
953
954#[derive(Debug, Clone)]
955pub struct Constant {
956 pub name: Node,
957 pub assigned_name: String,
958 pub id: ConstantId,
959 pub expr: Expression,
960 pub resolved_type: TypeRef,
961 pub function_scope_state: VariableScopes,
962}
963pub type ConstantRef = Rc<Constant>;
964
965pub type OptionTypeRef = Rc<OptionType>;
966
967#[derive(Debug, Clone)]
968pub struct OptionType {
969 pub item_type: TypeRef,
970}
971
972#[derive(Debug, Clone)]
989pub struct ImplMember {}
990
991#[derive(Debug, Clone)]
992pub enum UseItem {
993 Identifier(Node),
994 TypeIdentifier(Node),
995}
996
997#[derive(Debug, Clone)]
998pub struct Use {
999 pub path: Vec<Node>,
1000 pub items: Vec<UseItem>,
1001}
1002
1003#[derive(Debug, Clone)]
1004pub struct ImplFunctions {
1005 pub functions: SeqMap<String, FunctionRef>,
1006}
1007
1008impl Default for ImplFunctions {
1009 fn default() -> Self {
1010 Self::new()
1011 }
1012}
1013
1014impl ImplFunctions {
1015 #[must_use]
1016 pub fn new() -> Self {
1017 Self {
1018 functions: SeqMap::default(),
1019 }
1020 }
1021}
1022
1023#[derive(Debug, Clone)]
1024pub struct AssociatedImpls {
1025 pub functions: SeqMap<TypeRef, ImplFunctions>,
1026}
1027
1028impl AssociatedImpls {}
1029
1030impl AssociatedImpls {}
1031
1032impl AssociatedImpls {}
1033
1034impl Default for AssociatedImpls {
1035 fn default() -> Self {
1036 Self::new()
1037 }
1038}
1039
1040impl AssociatedImpls {
1041 #[must_use]
1042 pub fn new() -> Self {
1043 Self {
1044 functions: SeqMap::default(),
1045 }
1046 }
1047}
1048
1049impl AssociatedImpls {
1050 pub fn prepare(&mut self, ty: &TypeRef) {
1051 self.functions
1052 .insert(ty.clone(), ImplFunctions::new())
1053 .unwrap_or_else(|_| panic!("should work {ty:?}"));
1054 }
1055
1056 #[must_use]
1057 pub fn is_prepared(&self, ty: &TypeRef) -> bool {
1058 self.functions.contains_key(ty)
1059 }
1060 #[must_use]
1061 pub fn get_member_function(&self, ty: &TypeRef, function_name: &str) -> Option<&FunctionRef> {
1062 let maybe_found_impl = self.functions.get(ty);
1063 if let Some(found_impl) = maybe_found_impl
1064 && let Some(func) = found_impl.functions.get(&function_name.to_string())
1065 {
1066 return Some(func);
1067 }
1068 None
1069 }
1070
1071 fn has_internal_member_function(&self, ty: &TypeRef, function_name: &str) -> bool {
1072 let maybe_found_impl = self.functions.get(ty);
1073 if let Some(found_impl) = maybe_found_impl
1074 && let Some(_func) = found_impl.functions.get(&function_name.to_string())
1075 {
1076 return true;
1077 }
1078 false
1079 }
1080
1081 #[must_use]
1082 pub fn api_get_external_function(
1083 &self,
1084 ty: &TypeRef,
1085 function_name: &str,
1086 ) -> Option<&ExternalFunctionDefinitionRef> {
1087 if let Some(found) = self.get_member_function(ty, function_name)
1088 && let Function::External(ext_fn) = &**found
1089 {
1090 return Some(ext_fn);
1091 }
1092 None
1093 }
1094
1095 #[must_use]
1096 pub fn get_internal_member_function(
1097 &self,
1098 ty: &TypeRef,
1099 function_name: &str,
1100 ) -> Option<&InternalFunctionDefinitionRef> {
1101 if let Some(found) = self.get_member_function(ty, function_name)
1102 && let Function::Internal(int_fn) = &**found
1103 {
1104 return Some(int_fn);
1105 }
1106 None
1107 }
1108
1109 pub fn remove_internal_function_if_exists(
1110 &mut self,
1111 ty: &TypeRef,
1112 function_name: &str,
1113 ) -> bool {
1114 if self.has_internal_member_function(ty, function_name) {
1115 let functions = self.functions.get_mut(ty).unwrap();
1116
1117 functions.functions.remove(&function_name.to_string());
1118 true
1119 } else {
1120 false
1121 }
1122 }
1123
1124 pub fn add_member_function(
1125 &mut self,
1126 ty: &TypeRef,
1127 name: &str,
1128 func: FunctionRef,
1129 ) -> Result<(), SemanticError> {
1130 let maybe_found_impl = self.functions.get_mut(ty);
1131
1132 if let Some(found_impl) = maybe_found_impl {
1133 found_impl
1134 .functions
1135 .insert(name.to_string(), func)
1136 .unwrap_or_else(|_| panic!("already had key {name}"));
1137 Ok(())
1138 } else {
1139 error!(%ty, ?name, "wasn't prepared");
1140 Err(SemanticError::UnknownImplOnType)
1141 }
1142 }
1143
1144 pub fn add_internal_function(
1145 &mut self,
1146 ty: &TypeRef,
1147 func: InternalFunctionDefinition,
1148 ) -> Result<(), SemanticError> {
1149 self.add_member_function(
1151 ty,
1152 &func.assigned_name.clone(),
1153 Function::Internal(func.into()).into(),
1154 )
1155 }
1156
1157 pub fn add_external_member_function(
1158 &mut self,
1159 ty: &TypeRef,
1160 func: ExternalFunctionDefinition,
1161 ) -> Result<(), SemanticError> {
1162 self.add_member_function(
1163 ty,
1164 &func.assigned_name.clone(),
1165 Function::External(func.into()).into(),
1166 )
1167 }
1168
1169 pub fn add_external_struct_member_function(
1170 &mut self,
1171 named_struct_type: TypeRef,
1172 func: Function,
1173 ) -> Result<(), SemanticError> {
1174 self.add_member_function(&named_struct_type, &func.name(), func.into())
1175 }
1176
1177 pub fn add_external_struct_member_function_external(
1178 &mut self,
1179 named_struct_type: TypeRef,
1180 func: ExternalFunctionDefinition,
1181 ) -> Result<(), SemanticError> {
1182 self.add_member_function(
1183 &named_struct_type,
1184 &func.assigned_name.clone(),
1185 Function::External(func.into()).into(),
1186 )
1187 }
1188
1189 pub fn add_external_struct_member_function_external_ref(
1190 &mut self,
1191 named_struct_type: TypeRef,
1192 func: ExternalFunctionDefinitionRef,
1193 ) -> Result<(), SemanticError> {
1194 self.add_member_function(
1195 &named_struct_type,
1196 &func.assigned_name.clone(),
1197 Function::External(func).into(),
1198 )
1199 }
1200}
1201
1202#[derive(Debug, Clone)]
1204pub struct ProgramState {
1205 pub internal_function_id_allocator: InternalFunctionIdAllocator,
1206 pub constants_in_dependency_order: Vec<ConstantRef>,
1210 pub associated_impls: AssociatedImpls,
1211 pub types: TypeCache,
1212 pub errors: Vec<Error>,
1213 pub hints: Vec<Error>,
1214 pub infos: Vec<Error>,
1215}
1216
1217impl ProgramState {
1218 #[must_use]
1219 pub const fn errors(&self) -> &Vec<Error> {
1220 &self.errors
1221 }
1222}
1223
1224impl Default for ProgramState {
1225 fn default() -> Self {
1226 Self::new()
1227 }
1228}
1229
1230#[derive(Debug, Clone)]
1231pub struct InternalFunctionIdAllocator {
1232 pub internal_function_number: InternalFunctionId,
1233}
1234
1235impl Default for InternalFunctionIdAllocator {
1236 fn default() -> Self {
1237 Self::new()
1238 }
1239}
1240
1241impl InternalFunctionIdAllocator {
1242 #[must_use]
1243 pub const fn new() -> Self {
1244 Self {
1245 internal_function_number: 0,
1246 }
1247 }
1248 pub const fn alloc(&mut self) -> InternalFunctionId {
1249 self.internal_function_number += 1;
1250 self.internal_function_number
1251 }
1252}
1253
1254impl ProgramState {
1255 #[must_use]
1256 pub fn new() -> Self {
1257 Self {
1258 internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1259 constants_in_dependency_order: Vec::new(),
1260 associated_impls: AssociatedImpls::new(),
1261 types: TypeCache::new(),
1262 errors: vec![],
1263 hints: vec![],
1264 infos: vec![],
1265 }
1266 }
1267 pub const fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1268 self.internal_function_id_allocator.alloc()
1269 }
1270}
1271
1272#[derive(Clone)]
1273pub enum EnumLiteralExpressions {
1274 Nothing,
1275 Tuple(Vec<Expression>),
1276 Struct(Vec<(usize, Option<Node>, Expression)>),
1277}
1278
1279impl Debug for EnumLiteralExpressions {
1280 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1281 match self {
1282 Self::Nothing => Ok(()),
1283 Self::Tuple(x) => write!(f, "{x:?}"),
1284 Self::Struct(s) => write!(f, "{s:?}"),
1285 }
1286 }
1287}