1pub mod inst_cache;
6pub mod instantiator;
7pub mod intr;
8pub mod prelude;
9pub mod type_var_stack;
10use crate::instantiator::Instantiator;
11use crate::intr::IntrinsicFunction;
12use crate::prelude::IntrinsicFunctionDefinitionRef;
13pub use fixed32::Fp;
14use seq_map::SeqMap;
15use std::cmp::PartialEq;
16use std::fmt;
17use std::fmt::{Debug, Display, Formatter};
18use std::rc::Rc;
19use swamp_node::Node;
20use swamp_types::GenericAwareSignature;
21use swamp_types::prelude::*;
22use tracing::error;
23
24#[derive(Debug, Clone)]
25pub struct TypeWithMut {
26 pub resolved_type: Type,
27 pub is_mutable: bool,
28}
29
30#[derive(Debug, Clone)]
31pub enum SemanticError {
32 CouldNotInsertStruct,
33 DuplicateTypeAlias(String),
34 CanOnlyUseStructForMemberFunctions,
35 ResolveNotStruct,
36 DuplicateStructName(String),
37 DuplicateEnumType(String),
38 DuplicateEnumVariantType(String, String),
39 DuplicateFieldName(String),
40 DuplicateExternalFunction(String),
41 DuplicateRustType(String),
42 DuplicateConstName(String),
43 CircularConstantDependency(Vec<ConstantId>),
44 DuplicateConstantId(ConstantId),
45 IncompatibleTypes,
46 WasNotImmutable,
47 WasNotMutable,
48 DuplicateSymbolName(String),
49 DuplicateNamespaceLink(String),
50 MismatchedTypes { expected: Type, found: Vec<Type> },
51 UnknownImplOnType,
52 UnknownTypeVariable,
53}
54
55#[derive(Debug, Eq, PartialEq)]
56pub struct LocalIdentifier(pub Node);
57
58#[derive(Debug)]
59pub struct InternalMainExpression {
60 pub expression: Expression,
61 pub function_scope_state: Vec<VariableRef>,
62 pub program_unique_id: InternalFunctionId,
63}
64
65pub struct InternalFunctionDefinition {
67 pub body: Expression,
68 pub name: LocalIdentifier,
69 pub assigned_name: String,
70 pub signature: GenericAwareSignature,
71 pub variable_scopes: FunctionScopeState,
72 pub function_scope_state: Vec<VariableRef>,
73 pub program_unique_id: InternalFunctionId,
74}
75
76impl Default for InternalFunctionDefinition {
77 fn default() -> Self {
78 Self {
79 body: Expression {
80 ty: Type::Never,
81 node: Node::default(),
82 kind: ExpressionKind::Block(vec![]),
83 },
84 name: LocalIdentifier(Node::default()),
85 assigned_name: String::new(),
86 signature: GenericAwareSignature {
87 signature: Signature {
88 parameters: vec![],
89 return_type: Box::new(Type::Never),
90 },
91 generic_type_variables: vec![],
92 },
93 variable_scopes: FunctionScopeState::new(Type::Unit),
94 function_scope_state: Vec::new(),
95 program_unique_id: 0,
96 }
97 }
98}
99
100impl Debug for InternalFunctionDefinition {
101 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
102 write!(f, "{:?}\n{:?}", self.signature, self.body)
103 }
104}
105
106impl PartialEq<Self> for InternalFunctionDefinition {
107 fn eq(&self, other: &Self) -> bool {
108 self.name == other.name
109 }
110}
111
112impl Eq for InternalFunctionDefinition {}
113
114pub type InternalFunctionDefinitionRef = Rc<InternalFunctionDefinition>;
115
116pub type ExternalFunctionId = u32;
117
118pub type InternalFunctionId = u16;
119
120pub type ConstantId = u32;
121
122#[derive(Eq, PartialEq)]
123pub struct ExternalFunctionDefinition {
124 pub name: Option<Node>,
125 pub assigned_name: String,
126 pub signature: Signature,
127 pub id: ExternalFunctionId,
128}
129
130impl Debug for ExternalFunctionDefinition {
131 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
132 write!(f, "external fn")
133 }
134}
135
136pub type ExternalFunctionDefinitionRef = Rc<crate::ExternalFunctionDefinition>;
137
138#[derive(Debug, Eq, Clone, PartialEq)]
139pub enum BlockScopeMode {
140 Open,
141 Closed,
142}
143
144#[derive(Debug, Clone)]
145pub struct BlockScope {
146 pub mode: BlockScopeMode,
147 pub variables: SeqMap<String, VariableRef>,
148}
149
150impl Display for BlockScope {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
152 writeln!(f, "-- scope {:?}", self.mode)?;
153
154 for (index, (name, var)) in self.variables.iter().enumerate() {
155 writeln!(f, " var({index}): {name}:{var:?}")?;
156 }
157 Ok(())
158 }
159}
160
161impl Default for BlockScope {
162 fn default() -> Self {
163 Self::new()
164 }
165}
166
167impl BlockScope {
168 #[must_use]
169 pub fn new() -> Self {
170 Self {
171 mode: BlockScopeMode::Open,
172 variables: SeqMap::new(),
173 }
174 }
175}
176
177#[derive(Clone)]
178pub struct FunctionScopeState {
179 pub block_scope_stack: Vec<BlockScope>,
180 pub return_type: Type,
181 pub variable_index: usize,
182}
183
184impl Display for FunctionScopeState {
185 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
186 for (index, scope) in self.block_scope_stack.iter().enumerate() {
187 writeln!(f, "block({index}):\n{scope}")?;
188 }
189 Ok(())
190 }
191}
192
193impl FunctionScopeState {
194 pub fn gen_variable_index(&mut self) -> usize {
195 let index = self.variable_index;
196 self.variable_index += 1;
197 index
198 }
199}
200
201impl FunctionScopeState {
202 #[must_use]
203 pub fn new(return_type: Type) -> Self {
204 Self {
205 block_scope_stack: vec![BlockScope::new()],
206 return_type,
207 variable_index: 0,
208 }
209 }
210}
211
212#[derive(Debug, Clone)]
213pub struct Variable {
214 pub name: Node,
215 pub assigned_name: String,
216 pub resolved_type: Type,
217 pub mutable_node: Option<Node>,
218
219 pub scope_index: usize,
220 pub variable_index: usize,
221
222 pub unique_id_within_function: usize,
223 pub is_unused: bool,
224}
225
226impl Variable {
227 #[must_use]
228 pub const fn is_mutable(&self) -> bool {
229 self.mutable_node.is_some()
230 }
231}
232
233pub type VariableRef = Rc<Variable>;
234
235#[derive(Debug, Clone)]
236pub struct MutVariable {
237 pub variable_ref: VariableRef,
238}
239
240#[derive(Debug, Clone)]
243pub enum BinaryOperatorKind {
244 Add,
245 Subtract,
246 Multiply,
247 Divide,
248 Modulo,
249 LogicalOr,
250 LogicalAnd,
251 Equal,
252 NotEqual,
253 LessThan,
254 LessEqual,
255 GreaterThan,
256 GreaterEqual,
257 RangeExclusive,
258}
259
260#[derive(Debug, Clone)]
261pub struct BinaryOperator {
262 pub left: Box<Expression>,
263 pub right: Box<Expression>,
264 pub kind: BinaryOperatorKind,
265 pub node: Node,
266}
267
268#[derive(Debug, Clone)]
269pub enum UnaryOperatorKind {
270 Not,
271 Negate,
272}
273#[derive(Debug, Clone)]
274pub struct UnaryOperator {
275 pub left: Box<Expression>,
276 pub kind: UnaryOperatorKind,
277 pub node: Node,
278}
279
280#[derive()]
281pub struct InternalFunctionCall {
282 pub arguments: Vec<ArgumentExpressionOrLocation>,
283
284 pub function_definition: InternalFunctionDefinitionRef,
285 pub function_expression: Box<Expression>,
286}
287
288impl Debug for InternalFunctionCall {
289 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
290 write!(
291 f,
292 "InFuncCall({:?} {:?})",
293 self.function_expression, self.arguments
294 )
295 }
296}
297
298#[derive(Debug, Clone)]
299pub struct ExternalFunctionCall {
300 pub arguments: Vec<ArgumentExpressionOrLocation>,
301 pub function_definition: ExternalFunctionDefinitionRef,
302 pub function_expression: Box<Expression>,
303}
304
305pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
306 let mut result = String::new();
307 for (i, (key, value)) in values.iter().enumerate() {
308 if i > 0 {
309 result.push_str(", ");
310 }
311 result.push_str(format!("{}: {}", key, value).as_str());
312 }
313 result
314}
315
316#[derive(Debug, Clone)]
317pub struct MemberCall {
318 pub function: FunctionRef,
319 pub arguments: Vec<ArgumentExpressionOrLocation>,
320}
321
322#[derive(Debug, Clone)]
323pub struct ArrayItem {
324 pub item_type: Type,
325 pub int_expression: Expression,
326 pub array_expression: Expression,
327 pub array_type: Type,
328}
329
330pub type ArrayItemRef = Rc<ArrayItem>;
331
332#[derive(Debug, Clone)]
333pub enum PrecisionType {
334 Float,
335 String,
336}
337
338#[derive(Debug, Clone)]
339pub enum FormatSpecifierKind {
340 LowerHex, UpperHex, Binary, Float, Precision(u32, Node, PrecisionType), }
346
347#[derive(Debug, Clone)]
348pub struct FormatSpecifier {
349 pub node: Node,
350 pub kind: FormatSpecifierKind,
351}
352
353#[derive(Debug, Clone)]
354pub enum StringPart {
355 Literal(Node, String),
356 Interpolation(Expression, Option<FormatSpecifier>),
357}
358
359pub type FunctionRef = Rc<Function>;
360
361#[derive(Debug, Eq, Clone, PartialEq)]
362pub enum Function {
363 Internal(InternalFunctionDefinitionRef),
364 External(ExternalFunctionDefinitionRef),
365}
366
367impl Function {
368 #[must_use]
369 pub fn name(&self) -> String {
370 match self {
371 Self::Internal(x) => x.assigned_name.clone(),
372 Self::External(y) => y.assigned_name.clone(),
373 }
374 }
375
376 #[must_use]
377 pub fn maybe_node(&self) -> Option<&Node> {
378 match self {
379 Self::Internal(x) => Some(&x.name.0),
380 Self::External(y) => y.name.as_ref(),
381 }
382 }
383
384 #[must_use]
385 pub fn node(&self) -> Node {
386 match self {
387 Self::Internal(x) => x.name.0.clone(),
388 Self::External(_y) => Node::new_unknown(),
389 }
390 }
391
392 #[must_use]
393 pub fn signature(&self) -> &Signature {
394 match self {
395 Self::Internal(internal) => &internal.signature.signature,
396 Self::External(external) => &external.signature,
397 }
398 }
399}
400
401#[derive(Debug, Clone)]
402pub struct BooleanExpression {
403 #[allow(unused)]
404 pub expression: Box<Expression>,
405}
406
407#[derive(Debug, Clone)]
409pub struct Match {
410 pub arms: Vec<MatchArm>,
411 pub expression: Box<MutOrImmutableExpression>,
412}
413
414impl Match {
415 #[must_use]
416 pub fn contains_wildcard(&self) -> bool {
417 for arm in &self.arms {
418 if let Pattern::Wildcard(_) = arm.pattern {
419 return true;
420 }
421 }
422 false
423 }
424}
425
426#[derive(Debug, Clone)]
427pub struct MatchArm {
428 #[allow(unused)]
429 pub pattern: Pattern,
430 pub expression: Box<Expression>,
431 pub expression_type: Type,
432}
433
434#[derive(Debug, Clone)]
435pub enum Pattern {
436 Normal(NormalPattern, Option<BooleanExpression>),
437 Wildcard(Node),
438}
439
440#[derive(Debug, Clone)]
441pub enum NormalPattern {
442 PatternList(Vec<PatternElement>),
443 EnumPattern(EnumVariantType, Option<Vec<PatternElement>>),
444 Literal(Literal),
445}
446
447#[derive(Debug, Clone)]
448pub enum PatternElement {
449 Variable(VariableRef),
450 VariableWithFieldIndex(VariableRef, usize),
451 Wildcard(Node),
452}
453
454#[derive(Debug, Clone)]
455pub struct Iterable {
456 pub key_type: Option<Type>, pub value_type: Type,
458
459 pub resolved_expression: Box<MutOrImmutableExpression>,
460}
461
462#[derive(Debug, Clone)]
463pub struct StructInstantiation {
464 pub source_order_expressions: Vec<(usize, Expression)>,
465 pub struct_type_ref: NamedStructType,
466}
467
468#[derive(Debug, Clone)]
469pub struct AnonymousStructLiteral {
470 pub source_order_expressions: Vec<(usize, Expression)>,
471 pub anonymous_struct_type: AnonymousStructType,
472}
473
474#[derive(Debug, Clone, Eq, PartialEq)]
475pub enum CompoundOperatorKind {
476 Add,
477 Sub,
478 Mul,
479 Div,
480 Modulo,
481}
482
483#[derive(Debug, Clone)]
484pub struct CompoundOperator {
485 pub node: Node,
486 pub kind: CompoundOperatorKind,
487}
488
489#[derive(Debug, Clone)]
490pub struct VariableCompoundAssignment {
491 pub variable_ref: VariableRef, pub expression: Box<Expression>,
493 pub compound_operator: CompoundOperator,
494}
495
496pub fn create_rust_type(name: &str, external_number: u32) -> ExternalType {
497 ExternalType {
498 type_name: name.to_string(),
499 number: external_number,
500 }
501}
502
503#[derive(Debug, Clone)]
504pub struct Guard {
505 pub condition: Option<BooleanExpression>,
506 pub result: Expression,
507}
508
509#[derive(Debug, Clone)]
510pub struct Postfix {
511 pub node: Node,
512 pub ty: Type,
513 pub kind: PostfixKind,
514}
515
516#[derive(Debug, Clone)]
517pub enum PostfixKind {
518 StructField(AnonymousStructType, usize),
519 MemberCall(FunctionRef, Vec<ArgumentExpressionOrLocation>),
520 FunctionCall(Vec<ArgumentExpressionOrLocation>),
521 OptionalChainingOperator, NoneCoalescingOperator(Expression), }
524
525#[derive(Debug, Clone)]
526pub enum LocationAccessKind {
527 FieldIndex(AnonymousStructType, usize),
528 IntrinsicCallMut(IntrinsicFunction, Vec<Expression>),
529}
530
531#[derive(Debug, Clone)]
532pub struct LocationAccess {
533 pub node: Node,
534 pub ty: Type,
535 pub kind: LocationAccessKind,
536}
537
538#[derive(Debug, Clone)]
539pub struct SingleLocationExpression {
540 pub kind: SingleLocationExpressionKind,
541 pub node: Node,
542 pub ty: Type,
543
544 pub starting_variable: VariableRef,
545 pub access_chain: Vec<LocationAccess>,
546}
547
548#[derive(Debug, Clone)]
549pub struct SingleMutLocationExpression(pub SingleLocationExpression);
550
551#[derive(Debug, Clone)]
552pub enum SingleLocationExpressionKind {
553 MutVariableRef,
554 MutStructFieldRef(NamedStructType, usize),
555}
556
557#[derive(Debug, Clone)]
558pub struct MutOrImmutableExpression {
559 pub expression_or_location: ArgumentExpressionOrLocation,
560 pub is_mutable: Option<Node>,
561}
562
563impl MutOrImmutableExpression {
564 pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
565 match self.expression_or_location {
566 ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
567 ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
568 }
569 }
570
571 pub fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
572 match &self.expression_or_location {
573 ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
574 ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
575 }
576 }
577
578 pub fn ty(&self) -> &Type {
579 match &self.expression_or_location {
580 ArgumentExpressionOrLocation::Expression(expr) => &expr.ty,
581 ArgumentExpressionOrLocation::Location(loc) => &loc.ty,
582 }
583 }
584
585 #[must_use]
586 pub const fn node(&self) -> &Node {
587 match &self.expression_or_location {
588 ArgumentExpressionOrLocation::Expression(expr) => &expr.node,
589 ArgumentExpressionOrLocation::Location(loc) => &loc.node,
590 }
591 }
592}
593
594#[derive(Debug, Clone)]
595pub enum ArgumentExpressionOrLocation {
596 Expression(Expression),
597 Location(SingleLocationExpression),
598}
599
600impl ArgumentExpressionOrLocation {
601 #[must_use]
602 pub fn ty(&self) -> Type {
603 match self {
604 Self::Expression(expr) => expr.ty.clone(),
605 Self::Location(location) => location.ty.clone(),
606 }
607 }
608}
609
610#[derive(Clone)]
611pub struct Expression {
612 pub ty: Type,
613 pub node: Node,
614 pub kind: ExpressionKind,
615}
616
617impl Debug for Expression {
618 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
619 write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
620 }
621}
622
623#[derive(Debug, Clone)]
624pub struct WhenBinding {
625 pub variable: VariableRef,
626 pub expr: MutOrImmutableExpression,
627}
628
629impl WhenBinding {
630 #[must_use]
631 pub const fn has_expression(&self) -> bool {
632 match &self.expr.expression_or_location {
633 ArgumentExpressionOrLocation::Expression(expr) => {
634 !matches!(expr.kind, ExpressionKind::VariableAccess(_))
635 }
636 ArgumentExpressionOrLocation::Location(_) => true,
637 }
638 }
639}
640
641#[derive(Debug, Clone)]
642pub enum ExpressionKind {
643 ConstantAccess(ConstantRef),
645 VariableAccess(VariableRef),
646
647 IntrinsicFunctionAccess(IntrinsicFunctionDefinitionRef),
649 InternalFunctionAccess(InternalFunctionDefinitionRef),
650 ExternalFunctionAccess(ExternalFunctionDefinitionRef),
651
652 BinaryOp(BinaryOperator),
654 UnaryOp(UnaryOperator),
655 PostfixChain(Box<Expression>, Vec<Postfix>),
656
657 CoerceOptionToBool(Box<Expression>),
660
661 FunctionValueCall(
665 Signature,
666 Box<Expression>,
667 Vec<ArgumentExpressionOrLocation>,
668 ),
669
670 InterpolatedString(Vec<StringPart>),
671
672 VariableDefinition(VariableRef, Box<MutOrImmutableExpression>), VariableReassignment(VariableRef, Box<MutOrImmutableExpression>),
675 Assignment(Box<SingleMutLocationExpression>, Box<Expression>),
676 CompoundAssignment(
677 SingleMutLocationExpression,
678 CompoundOperatorKind,
679 Box<Expression>,
680 ),
681
682 StructInstantiation(StructInstantiation),
683 AnonymousStructLiteral(AnonymousStructLiteral),
684 Literal(Literal),
685 Option(Option<Box<Expression>>), ForLoop(ForPattern, Iterable, Box<Expression>),
689 WhileLoop(BooleanExpression, Box<Expression>),
690
691 Block(Vec<Expression>),
692
693 Match(Match),
695 Guard(Vec<Guard>),
696 If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
697 When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
698
699 TupleDestructuring(Vec<VariableRef>, Vec<Type>, Box<Expression>),
700
701 IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpressionOrLocation>),
705 Lambda(Vec<VariableRef>, Box<Expression>),
715}
716
717#[derive(Debug, Clone)]
718pub struct StringConst(pub Node);
719
720#[derive(Debug, Clone)]
721pub enum Literal {
722 FloatLiteral(Fp),
723 NoneLiteral,
724 IntLiteral(i32),
725 StringLiteral(String),
726 BoolLiteral(bool),
727
728 EnumVariantLiteral(EnumType, EnumVariantType, EnumLiteralData),
729 TupleLiteral(Vec<Type>, Vec<Expression>),
730
731 Slice(Type, Vec<Expression>),
732 SlicePair(Type, Vec<(Expression, Expression)>),
733}
734
735#[derive(Debug, Clone)]
736pub struct ArrayInstantiation {
737 pub expressions: Vec<Expression>,
738 pub item_type: Type,
739 pub array_type: Type,
740 pub array_type_ref: Type,
741}
742
743#[derive(Debug, Clone)]
744pub enum ForPattern {
745 Single(VariableRef),
746 Pair(VariableRef, VariableRef),
747}
748
749impl ForPattern {
750 #[must_use]
751 pub fn is_mutable(&self) -> bool {
752 match self {
753 Self::Single(variable) => variable.is_mutable(),
754 Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
755 }
756 }
757}
758
759impl Display for ForPattern {
760 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
761 write!(f, "resolved_for_pattern")
762 }
763}
764
765#[derive(Debug, Eq, PartialEq)]
766pub struct ModulePathItem(pub Node);
767
768#[derive(Debug, Clone, Eq, PartialEq)]
769pub struct LocalTypeIdentifier(pub Node);
770
771#[derive(Debug, Clone)]
772pub struct Constant {
773 pub name: Node,
774 pub assigned_name: String,
775 pub id: ConstantId,
776 pub expr: Expression,
777 pub resolved_type: Type,
778}
779pub type ConstantRef = Rc<Constant>;
780
781pub type OptionTypeRef = Rc<crate::OptionType>;
782
783#[derive(Debug, Clone)]
784pub struct OptionType {
785 pub item_type: Type,
786}
787
788#[derive(Debug, Clone)]
805pub struct ImplMember {}
806
807#[derive(Debug, Clone)]
808pub enum UseItem {
809 Identifier(Node),
810 TypeIdentifier(Node),
811}
812
813#[derive(Debug, Clone)]
814pub struct Use {
815 pub path: Vec<Node>,
816 pub items: Vec<UseItem>,
817}
818
819#[derive(Debug, Clone)]
820pub struct ImplFunctions {
821 pub functions: SeqMap<String, FunctionRef>,
822}
823
824impl Default for ImplFunctions {
825 fn default() -> Self {
826 Self::new()
827 }
828}
829
830impl ImplFunctions {
831 #[must_use]
832 pub fn new() -> Self {
833 Self {
834 functions: SeqMap::default(),
835 }
836 }
837}
838
839#[derive(Debug, Clone)]
840pub struct AssociatedImpls {
841 pub functions: SeqMap<Type, ImplFunctions>,
842}
843
844impl Default for AssociatedImpls {
845 fn default() -> Self {
846 Self::new()
847 }
848}
849
850impl AssociatedImpls {
851 #[must_use]
852 pub fn new() -> Self {
853 Self {
854 functions: SeqMap::default(),
855 }
856 }
857}
858
859impl AssociatedImpls {
860 pub fn prepare(&mut self, ty: &Type) {
861 self.functions
862 .insert(ty.clone(), ImplFunctions::new())
863 .expect("should work");
864 }
865 #[must_use]
866 pub fn get_member_function(&self, ty: &Type, function_name: &str) -> Option<&FunctionRef> {
867 let maybe_found_impl = self.functions.get(&ty);
868 if let Some(found_impl) = maybe_found_impl {
869 if let Some(func) = found_impl.functions.get(&function_name.to_string()) {
870 return Some(func);
871 }
872 }
873 None
874 }
875
876 pub fn api_get_external_function(
877 &self,
878 ty: &Type,
879 function_name: &str,
880 ) -> Option<&ExternalFunctionDefinitionRef> {
881 if let Some(found) = self.get_member_function(ty, function_name) {
882 if let Function::External(ext_fn) = &**found {
883 return Some(ext_fn);
884 }
885 }
886 None
887 }
888
889 pub fn api_fetch_external_function_id(
890 &self,
891 ty: &Type,
892 function_name: &str,
893 ) -> ExternalFunctionId {
894 self.api_get_external_function(ty, function_name)
895 .unwrap()
896 .id
897 }
898
899 pub fn get_internal_member_function(
900 &self,
901 ty: &Type,
902 function_name: &str,
903 ) -> Option<&InternalFunctionDefinitionRef> {
904 if let Some(found) = self.get_member_function(ty, function_name) {
905 if let Function::Internal(int_fn) = &**found {
906 return Some(int_fn);
907 }
908 }
909 None
910 }
911
912 pub fn add_member_function(
913 &mut self,
914 ty: &Type,
915 name: &str,
916 func: FunctionRef,
917 ) -> Result<(), SemanticError> {
918 let maybe_found_impl = self.functions.get_mut(&ty);
919
920 if let Some(found_impl) = maybe_found_impl {
921 found_impl
922 .functions
923 .insert(name.to_string(), func)
924 .expect("todo");
925 Ok(())
926 } else {
927 error!(%ty, ?name, "wasn't prepared");
928 Err(SemanticError::UnknownImplOnType)
929 }
930 }
931
932 pub fn add_external_member_function(
933 &mut self,
934 ty: &Type,
935 func: ExternalFunctionDefinition,
936 ) -> Result<(), SemanticError> {
937 self.add_member_function(
938 ty,
939 &func.assigned_name.clone(),
940 Function::External(func.into()).into(),
941 )
942 }
943
944 pub fn add_external_struct_member_function(
945 &mut self,
946 named_struct_type: &NamedStructType,
947 func: Function,
948 ) -> Result<(), SemanticError> {
949 self.add_member_function(
950 &Type::NamedStruct(named_struct_type.clone()),
951 &func.name().clone(),
952 func.into(),
953 )
954 }
955
956 pub fn add_external_struct_member_function_external(
957 &mut self,
958 named_struct_type: NamedStructType,
959 func: ExternalFunctionDefinition,
960 ) -> Result<(), SemanticError> {
961 self.add_member_function(
962 &Type::NamedStruct(named_struct_type.clone()),
963 &func.assigned_name.clone(),
964 Function::External(func.into()).into(),
965 )
966 }
967
968 pub fn add_external_struct_member_function_external_ref(
969 &mut self,
970 named_struct_type: NamedStructType,
971 func: ExternalFunctionDefinitionRef,
972 ) -> Result<(), SemanticError> {
973 self.add_member_function(
974 &Type::NamedStruct(named_struct_type.clone()),
975 &func.assigned_name.clone(),
976 Function::External(func.into()).into(),
977 )
978 }
979}
980
981#[derive(Debug, Clone)]
983pub struct ProgramState {
984 pub external_function_number: ExternalFunctionId,
985 pub internal_function_id_allocator: InternalFunctionIdAllocator,
986 pub constants_in_dependency_order: Vec<ConstantRef>,
990 pub instantiator: Instantiator,
991}
992
993impl Default for ProgramState {
994 fn default() -> Self {
995 Self::new()
996 }
997}
998
999#[derive(Debug, Clone)]
1000pub struct InternalFunctionIdAllocator {
1001 pub internal_function_number: InternalFunctionId,
1002}
1003
1004impl Default for InternalFunctionIdAllocator {
1005 fn default() -> Self {
1006 Self::new()
1007 }
1008}
1009
1010impl InternalFunctionIdAllocator {
1011 #[must_use]
1012 pub const fn new() -> Self {
1013 Self {
1014 internal_function_number: 0,
1015 }
1016 }
1017 pub fn alloc(&mut self) -> InternalFunctionId {
1018 self.internal_function_number += 1;
1019 self.internal_function_number
1020 }
1021}
1022
1023impl ProgramState {
1024 #[must_use]
1025 pub fn new() -> Self {
1026 Self {
1027 external_function_number: 0,
1028 internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1029 constants_in_dependency_order: Vec::new(),
1030 instantiator: Instantiator::new(),
1031 }
1032 }
1033
1034 pub fn allocate_external_function_id(&mut self) -> ExternalFunctionId {
1035 self.external_function_number += 1;
1036 self.external_function_number
1037 }
1038
1039 pub fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1040 self.internal_function_id_allocator.alloc()
1041 }
1042}
1043
1044#[derive(Clone)]
1045pub enum EnumLiteralData {
1046 Nothing,
1047 Tuple(Vec<Expression>),
1048 Struct(Vec<(usize, Expression)>),
1049}
1050
1051impl Debug for EnumLiteralData {
1052 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1053 match self {
1054 Self::Nothing => Ok(()),
1055 Self::Tuple(x) => write!(f, "{x:?}"),
1056 Self::Struct(s) => write!(f, "{s:?}"),
1057 }
1058 }
1059}