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 source_map_node::Node;
16use std::cmp::PartialEq;
17use std::fmt;
18use std::fmt::{Debug, Display, Formatter};
19use std::rc::Rc;
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(),
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 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() -> Self {
204 Self {
205 block_scope_stack: vec![BlockScope::new()],
206 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 BorrowMutRef,
273}
274#[derive(Debug, Clone)]
275pub struct UnaryOperator {
276 pub left: Box<Expression>,
277 pub kind: UnaryOperatorKind,
278 pub node: Node,
279}
280
281#[derive()]
282pub struct InternalFunctionCall {
283 pub arguments: Vec<MutRefOrImmutableExpression>,
284
285 pub function_definition: InternalFunctionDefinitionRef,
286 pub function_expression: Box<Expression>,
287}
288
289impl Debug for InternalFunctionCall {
290 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
291 write!(
292 f,
293 "InFuncCall({:?} {:?})",
294 self.function_expression, self.arguments
295 )
296 }
297}
298
299#[derive(Debug, Clone)]
300pub struct ExternalFunctionCall {
301 pub arguments: Vec<MutRefOrImmutableExpression>,
302 pub function_definition: ExternalFunctionDefinitionRef,
303 pub function_expression: Box<Expression>,
304}
305
306pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
307 let mut result = String::new();
308 for (i, (key, value)) in values.iter().enumerate() {
309 if i > 0 {
310 result.push_str(", ");
311 }
312 result.push_str(format!("{key}: {value}").as_str());
313 }
314 result
315}
316
317#[derive(Debug, Clone)]
318pub struct MemberCall {
319 pub function: FunctionRef,
320 pub arguments: Vec<MutRefOrImmutableExpression>,
321}
322
323#[derive(Debug, Clone)]
324pub struct ArrayItem {
325 pub item_type: Type,
326 pub int_expression: Expression,
327 pub array_expression: Expression,
328 pub array_type: Type,
329}
330
331pub type ArrayItemRef = Rc<ArrayItem>;
332
333#[derive(Debug, Clone)]
334pub enum PrecisionType {
335 Float,
336 String,
337}
338
339#[derive(Debug, Clone)]
340pub enum FormatSpecifierKind {
341 LowerHex, UpperHex, Binary, Float, Precision(u32, Node, PrecisionType), }
347
348#[derive(Debug, Clone)]
349pub struct FormatSpecifier {
350 pub node: Node,
351 pub kind: FormatSpecifierKind,
352}
353
354#[derive(Debug, Clone)]
355pub enum StringPart {
356 Literal(Node, String),
357 Interpolation(Expression, Option<FormatSpecifier>),
358}
359
360pub type FunctionRef = Rc<Function>;
361
362#[derive(Debug, Eq, Clone, PartialEq)]
363pub enum Function {
364 Internal(InternalFunctionDefinitionRef),
365 External(ExternalFunctionDefinitionRef),
366}
367
368impl Function {
369 #[must_use]
370 pub fn name(&self) -> String {
371 match self {
372 Self::Internal(x) => x.assigned_name.clone(),
373 Self::External(y) => y.assigned_name.clone(),
374 }
375 }
376
377 #[must_use]
378 pub fn maybe_node(&self) -> Option<&Node> {
379 match self {
380 Self::Internal(x) => Some(&x.name.0),
381 Self::External(y) => y.name.as_ref(),
382 }
383 }
384
385 #[must_use]
386 pub fn node(&self) -> Node {
387 match self {
388 Self::Internal(x) => x.name.0.clone(),
389 Self::External(_y) => Node::new_unknown(),
390 }
391 }
392
393 #[must_use]
394 pub fn signature(&self) -> &Signature {
395 match self {
396 Self::Internal(internal) => &internal.signature.signature,
397 Self::External(external) => &external.signature,
398 }
399 }
400
401 #[must_use]
402 pub fn signatures(&self) -> (Option<&GenericAwareSignature>, &Signature) {
403 match self {
404 Self::Internal(internal) => (Some(&internal.signature), &internal.signature.signature),
405 Self::External(external) => (None, &external.signature),
406 }
407 }
408}
409
410#[derive(Debug, Clone)]
411pub struct BooleanExpression {
412 #[allow(unused)]
413 pub expression: Box<Expression>,
414}
415
416#[derive(Debug, Clone)]
418pub struct Match {
419 pub arms: Vec<MatchArm>,
420 pub expression: Box<MutRefOrImmutableExpression>,
421}
422
423impl Match {
424 #[must_use]
425 pub fn contains_wildcard(&self) -> bool {
426 for arm in &self.arms {
427 if let Pattern::Wildcard(_) = arm.pattern {
428 return true;
429 }
430 }
431 false
432 }
433}
434
435#[derive(Debug, Clone)]
436pub struct MatchArm {
437 #[allow(unused)]
438 pub pattern: Pattern,
439 pub expression: Box<Expression>,
440 pub expression_type: Type,
441}
442
443#[derive(Debug, Clone)]
444pub enum Pattern {
445 Normal(NormalPattern, Option<BooleanExpression>),
446 Wildcard(Node),
447}
448
449#[derive(Debug, Clone)]
450pub enum NormalPattern {
451 PatternList(Vec<PatternElement>),
452 EnumPattern(EnumVariantType, Option<Vec<PatternElement>>),
453 Literal(Literal),
454}
455
456#[derive(Debug, Clone)]
457pub enum PatternElement {
458 Variable(VariableRef),
459 VariableWithFieldIndex(VariableRef, usize),
460 Wildcard(Node),
461}
462
463#[derive(Debug, Clone)]
464pub struct Iterable {
465 pub key_type: Option<Type>, pub value_type: Type,
467
468 pub resolved_expression: Box<MutRefOrImmutableExpression>,
469}
470
471#[derive(Debug, Clone)]
472pub struct StructInstantiation {
473 pub source_order_expressions: Vec<(usize, Expression)>,
474 pub struct_type_ref: NamedStructType,
475}
476
477#[derive(Debug, Clone)]
478pub struct AnonymousStructLiteral {
479 pub source_order_expressions: Vec<(usize, Expression)>,
480 pub anonymous_struct_type: AnonymousStructType,
481}
482
483#[derive(Debug, Clone, Eq, PartialEq)]
484pub enum CompoundOperatorKind {
485 Add,
486 Sub,
487 Mul,
488 Div,
489 Modulo,
490}
491
492#[derive(Debug, Clone)]
493pub struct CompoundOperator {
494 pub node: Node,
495 pub kind: CompoundOperatorKind,
496}
497
498#[derive(Debug, Clone)]
499pub struct VariableCompoundAssignment {
500 pub variable_ref: VariableRef, pub expression: Box<Expression>,
502 pub compound_operator: CompoundOperator,
503}
504
505#[must_use]
506pub fn create_rust_type(name: &str, external_number: u32) -> ExternalType {
507 ExternalType {
508 type_name: name.to_string(),
509 number: external_number,
510 }
511}
512
513#[derive(Debug, Clone)]
514pub struct Guard {
515 pub condition: Option<BooleanExpression>,
516 pub result: Expression,
517}
518
519#[derive(Debug, Clone)]
520pub struct Postfix {
521 pub node: Node,
522 pub ty: Type,
523 pub kind: PostfixKind,
524}
525
526#[derive(Debug, Clone)]
527pub enum PostfixKind {
528 StructField(AnonymousStructType, usize),
529 MemberCall(FunctionRef, Vec<MutRefOrImmutableExpression>),
530 FunctionCall(Vec<MutRefOrImmutableExpression>),
531 OptionalChainingOperator, NoneCoalescingOperator(Expression), }
534
535#[derive(Debug, Clone)]
536pub enum LocationAccessKind {
537 FieldIndex(AnonymousStructType, usize),
538 IntrinsicCallMut(IntrinsicFunction, Vec<Expression>),
539}
540
541#[derive(Debug, Clone)]
542pub struct LocationAccess {
543 pub node: Node,
544 pub ty: Type,
545 pub kind: LocationAccessKind,
546}
547
548#[derive(Debug, Clone)]
549pub struct SingleLocationExpression {
550 pub kind: MutableReferenceKind,
551 pub node: Node,
552 pub ty: Type,
553
554 pub starting_variable: VariableRef,
555 pub access_chain: Vec<LocationAccess>,
556}
557
558#[derive(Debug, Clone)]
559pub struct TargetAssignmentLocation(pub SingleLocationExpression);
560
561#[derive(Debug, Clone)]
562pub enum MutableReferenceKind {
563 MutVariableRef,
564 MutStructFieldRef(NamedStructType, usize),
565}
566
567#[derive(Debug, Clone)]
568pub enum MutRefOrImmutableExpression {
569 Expression(Expression),
570 Location(SingleLocationExpression),
571}
572
573impl MutRefOrImmutableExpression {
574 #[must_use]
575 pub fn ty(&self) -> Type {
576 match self {
577 Self::Expression(expr) => expr.ty.clone(),
578 Self::Location(location) => location.ty.clone(),
579 }
580 }
581
582 pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
583 match self {
584 Self::Expression(expr) => Ok(expr),
585 Self::Location(_) => Err(SemanticError::WasNotImmutable),
586 }
587 }
588
589 pub const fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
590 match &self {
591 Self::Expression(expr) => Ok(expr),
592 Self::Location(_) => Err(SemanticError::WasNotImmutable),
593 }
594 }
595
596 pub const fn is_mutable_reference(&self) -> bool {
597 matches!(self, Self::Location(_))
598 }
599
600 #[must_use]
601 pub const fn node(&self) -> &Node {
602 match &self {
603 Self::Expression(expr) => &expr.node,
604 Self::Location(loc) => &loc.node,
605 }
606 }
607}
608
609#[derive(Clone)]
610pub struct Expression {
611 pub ty: Type,
612 pub node: Node,
613 pub kind: ExpressionKind,
614}
615
616impl Debug for Expression {
617 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
618 write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
619 }
620}
621
622#[derive(Debug, Clone)]
623pub struct WhenBinding {
624 pub variable: VariableRef,
625 pub expr: MutRefOrImmutableExpression,
626}
627
628impl WhenBinding {
629 #[must_use]
630 pub const fn has_expression(&self) -> bool {
631 match &self.expr {
632 MutRefOrImmutableExpression::Expression(expr) => {
633 !matches!(expr.kind, ExpressionKind::VariableAccess(_))
634 }
635 MutRefOrImmutableExpression::Location(_) => true,
636 }
637 }
638}
639
640#[derive(Debug, Clone)]
641pub enum ExpressionKind {
642 ConstantAccess(ConstantRef),
644 VariableAccess(VariableRef),
645
646 IntrinsicFunctionAccess(IntrinsicFunctionDefinitionRef),
648 InternalFunctionAccess(InternalFunctionDefinitionRef),
649 ExternalFunctionAccess(ExternalFunctionDefinitionRef),
650
651 BinaryOp(BinaryOperator),
653 UnaryOp(UnaryOperator),
654 PostfixChain(Box<Expression>, Vec<Postfix>),
655
656 CoerceOptionToBool(Box<Expression>),
659
660 FunctionValueCall(Signature, Box<Expression>, Vec<MutRefOrImmutableExpression>),
664
665 InterpolatedString(Vec<StringPart>),
666
667 VariableDefinition(VariableRef, Box<Expression>), VariableReassignment(VariableRef, Box<Expression>),
670 VariableBinding(VariableRef, Box<MutRefOrImmutableExpression>),
671 Assignment(Box<TargetAssignmentLocation>, Box<Expression>),
672 CompoundAssignment(
673 TargetAssignmentLocation,
674 CompoundOperatorKind,
675 Box<Expression>,
676 ),
677
678 StructInstantiation(StructInstantiation),
679 AnonymousStructLiteral(AnonymousStructLiteral),
680 Literal(Literal),
681 Option(Option<Box<Expression>>), ForLoop(ForPattern, Iterable, Box<Expression>),
685 WhileLoop(BooleanExpression, Box<Expression>),
686
687 Block(Vec<Expression>),
688
689 Match(Match),
691 Guard(Vec<Guard>),
692 If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
693 When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
694
695 TupleDestructuring(Vec<VariableRef>, Vec<Type>, Box<Expression>),
696
697 IntrinsicCallEx(IntrinsicFunction, Vec<MutRefOrImmutableExpression>),
701 Lambda(Vec<VariableRef>, Box<Expression>),
711}
712
713#[derive(Debug, Clone)]
714pub struct StringConst(pub Node);
715
716#[derive(Debug, Clone)]
717pub enum Literal {
718 FloatLiteral(Fp),
719 NoneLiteral,
720 IntLiteral(i32),
721 StringLiteral(String),
722 BoolLiteral(bool),
723
724 EnumVariantLiteral(EnumType, EnumVariantType, EnumLiteralData),
725 TupleLiteral(Vec<Type>, Vec<Expression>),
726
727 Slice(Type, Vec<Expression>),
728 SlicePair(Type, Vec<(Expression, Expression)>),
729}
730
731#[derive(Debug, Clone)]
732pub struct ArrayInstantiation {
733 pub expressions: Vec<Expression>,
734 pub item_type: Type,
735 pub array_type: Type,
736 pub array_type_ref: Type,
737}
738
739#[derive(Debug, Clone)]
740pub enum ForPattern {
741 Single(VariableRef),
742 Pair(VariableRef, VariableRef),
743}
744
745impl ForPattern {
746 #[must_use]
747 pub fn is_mutable(&self) -> bool {
748 match self {
749 Self::Single(variable) => variable.is_mutable(),
750 Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
751 }
752 }
753}
754
755impl Display for ForPattern {
756 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
757 write!(f, "resolved_for_pattern")
758 }
759}
760
761#[derive(Debug, Eq, PartialEq)]
762pub struct ModulePathItem(pub Node);
763
764#[derive(Debug, Clone, Eq, PartialEq)]
765pub struct LocalTypeIdentifier(pub Node);
766
767#[derive(Debug, Clone)]
768pub struct Constant {
769 pub name: Node,
770 pub assigned_name: String,
771 pub id: ConstantId,
772 pub expr: Expression,
773 pub resolved_type: Type,
774}
775pub type ConstantRef = Rc<Constant>;
776
777pub type OptionTypeRef = Rc<crate::OptionType>;
778
779#[derive(Debug, Clone)]
780pub struct OptionType {
781 pub item_type: Type,
782}
783
784#[derive(Debug, Clone)]
801pub struct ImplMember {}
802
803#[derive(Debug, Clone)]
804pub enum UseItem {
805 Identifier(Node),
806 TypeIdentifier(Node),
807}
808
809#[derive(Debug, Clone)]
810pub struct Use {
811 pub path: Vec<Node>,
812 pub items: Vec<UseItem>,
813}
814
815#[derive(Debug, Clone)]
816pub struct ImplFunctions {
817 pub functions: SeqMap<String, FunctionRef>,
818}
819
820impl Default for ImplFunctions {
821 fn default() -> Self {
822 Self::new()
823 }
824}
825
826impl ImplFunctions {
827 #[must_use]
828 pub fn new() -> Self {
829 Self {
830 functions: SeqMap::default(),
831 }
832 }
833}
834
835#[derive(Debug, Clone)]
836pub struct AssociatedImpls {
837 pub functions: SeqMap<Type, ImplFunctions>,
838}
839
840impl Default for AssociatedImpls {
841 fn default() -> Self {
842 Self::new()
843 }
844}
845
846impl AssociatedImpls {
847 #[must_use]
848 pub fn new() -> Self {
849 Self {
850 functions: SeqMap::default(),
851 }
852 }
853}
854
855impl AssociatedImpls {
856 pub fn prepare(&mut self, ty: &Type) {
857 self.functions
858 .insert(ty.clone(), ImplFunctions::new())
859 .expect("should work");
860 }
861 #[must_use]
862 pub fn get_member_function(&self, ty: &Type, function_name: &str) -> Option<&FunctionRef> {
863 let maybe_found_impl = self.functions.get(ty);
864 if let Some(found_impl) = maybe_found_impl {
865 if let Some(func) = found_impl.functions.get(&function_name.to_string()) {
866 return Some(func);
867 }
868 }
869 None
870 }
871
872 #[must_use]
873 pub fn api_get_external_function(
874 &self,
875 ty: &Type,
876 function_name: &str,
877 ) -> Option<&ExternalFunctionDefinitionRef> {
878 if let Some(found) = self.get_member_function(ty, function_name) {
879 if let Function::External(ext_fn) = &**found {
880 return Some(ext_fn);
881 }
882 }
883 None
884 }
885
886 #[must_use]
887 pub fn api_fetch_external_function_id(
888 &self,
889 ty: &Type,
890 function_name: &str,
891 ) -> ExternalFunctionId {
892 self.api_get_external_function(ty, function_name)
893 .unwrap()
894 .id
895 }
896
897 #[must_use]
898 pub fn get_internal_member_function(
899 &self,
900 ty: &Type,
901 function_name: &str,
902 ) -> Option<&InternalFunctionDefinitionRef> {
903 if let Some(found) = self.get_member_function(ty, function_name) {
904 if let Function::Internal(int_fn) = &**found {
905 return Some(int_fn);
906 }
907 }
908 None
909 }
910
911 pub fn add_member_function(
912 &mut self,
913 ty: &Type,
914 name: &str,
915 func: FunctionRef,
916 ) -> Result<(), SemanticError> {
917 let maybe_found_impl = self.functions.get_mut(ty);
918
919 if let Some(found_impl) = maybe_found_impl {
920 found_impl
921 .functions
922 .insert(name.to_string(), func)
923 .expect("todo");
924 Ok(())
925 } else {
926 error!(%ty, ?name, "wasn't prepared");
927 Err(SemanticError::UnknownImplOnType)
928 }
929 }
930
931 pub fn add_external_member_function(
932 &mut self,
933 ty: &Type,
934 func: ExternalFunctionDefinition,
935 ) -> Result<(), SemanticError> {
936 self.add_member_function(
937 ty,
938 &func.assigned_name.clone(),
939 Function::External(func.into()).into(),
940 )
941 }
942
943 pub fn add_external_struct_member_function(
944 &mut self,
945 named_struct_type: &NamedStructType,
946 func: Function,
947 ) -> Result<(), SemanticError> {
948 self.add_member_function(
949 &Type::NamedStruct(named_struct_type.clone()),
950 &func.name(),
951 func.into(),
952 )
953 }
954
955 pub fn add_external_struct_member_function_external(
956 &mut self,
957 named_struct_type: NamedStructType,
958 func: ExternalFunctionDefinition,
959 ) -> Result<(), SemanticError> {
960 self.add_member_function(
961 &Type::NamedStruct(named_struct_type),
962 &func.assigned_name.clone(),
963 Function::External(func.into()).into(),
964 )
965 }
966
967 pub fn add_external_struct_member_function_external_ref(
968 &mut self,
969 named_struct_type: NamedStructType,
970 func: ExternalFunctionDefinitionRef,
971 ) -> Result<(), SemanticError> {
972 self.add_member_function(
973 &Type::NamedStruct(named_struct_type),
974 &func.assigned_name.clone(),
975 Function::External(func).into(),
976 )
977 }
978}
979
980#[derive(Debug, Clone)]
982pub struct ProgramState {
983 pub external_function_number: ExternalFunctionId,
984 pub internal_function_id_allocator: InternalFunctionIdAllocator,
985 pub constants_in_dependency_order: Vec<ConstantRef>,
989 pub instantiator: Instantiator,
990}
991
992impl Default for ProgramState {
993 fn default() -> Self {
994 Self::new()
995 }
996}
997
998#[derive(Debug, Clone)]
999pub struct InternalFunctionIdAllocator {
1000 pub internal_function_number: InternalFunctionId,
1001}
1002
1003impl Default for InternalFunctionIdAllocator {
1004 fn default() -> Self {
1005 Self::new()
1006 }
1007}
1008
1009impl InternalFunctionIdAllocator {
1010 #[must_use]
1011 pub const fn new() -> Self {
1012 Self {
1013 internal_function_number: 0,
1014 }
1015 }
1016 pub fn alloc(&mut self) -> InternalFunctionId {
1017 self.internal_function_number += 1;
1018 self.internal_function_number
1019 }
1020}
1021
1022impl ProgramState {
1023 #[must_use]
1024 pub fn new() -> Self {
1025 Self {
1026 external_function_number: 0,
1027 internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1028 constants_in_dependency_order: Vec::new(),
1029 instantiator: Instantiator::new(),
1030 }
1031 }
1032
1033 pub fn allocate_external_function_id(&mut self) -> ExternalFunctionId {
1034 self.external_function_number += 1;
1035 self.external_function_number
1036 }
1037
1038 pub fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1039 self.internal_function_id_allocator.alloc()
1040 }
1041}
1042
1043#[derive(Clone)]
1044pub enum EnumLiteralData {
1045 Nothing,
1046 Tuple(Vec<Expression>),
1047 Struct(Vec<(usize, Expression)>),
1048}
1049
1050impl Debug for EnumLiteralData {
1051 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1052 match self {
1053 Self::Nothing => Ok(()),
1054 Self::Tuple(x) => write!(f, "{x:?}"),
1055 Self::Struct(s) => write!(f, "{s:?}"),
1056 }
1057 }
1058}