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(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
496#[must_use]
497pub fn create_rust_type(name: &str, external_number: u32) -> ExternalType {
498 ExternalType {
499 type_name: name.to_string(),
500 number: external_number,
501 }
502}
503
504#[derive(Debug, Clone)]
505pub struct Guard {
506 pub condition: Option<BooleanExpression>,
507 pub result: Expression,
508}
509
510#[derive(Debug, Clone)]
511pub struct Postfix {
512 pub node: Node,
513 pub ty: Type,
514 pub kind: PostfixKind,
515}
516
517#[derive(Debug, Clone)]
518pub enum PostfixKind {
519 StructField(AnonymousStructType, usize),
520 MemberCall(FunctionRef, Vec<ArgumentExpressionOrLocation>),
521 FunctionCall(Vec<ArgumentExpressionOrLocation>),
522 OptionalChainingOperator, NoneCoalescingOperator(Expression), }
525
526#[derive(Debug, Clone)]
527pub enum LocationAccessKind {
528 FieldIndex(AnonymousStructType, usize),
529 IntrinsicCallMut(IntrinsicFunction, Vec<Expression>),
530}
531
532#[derive(Debug, Clone)]
533pub struct LocationAccess {
534 pub node: Node,
535 pub ty: Type,
536 pub kind: LocationAccessKind,
537}
538
539#[derive(Debug, Clone)]
540pub struct SingleLocationExpression {
541 pub kind: SingleLocationExpressionKind,
542 pub node: Node,
543 pub ty: Type,
544
545 pub starting_variable: VariableRef,
546 pub access_chain: Vec<LocationAccess>,
547}
548
549#[derive(Debug, Clone)]
550pub struct SingleMutLocationExpression(pub SingleLocationExpression);
551
552#[derive(Debug, Clone)]
553pub enum SingleLocationExpressionKind {
554 MutVariableRef,
555 MutStructFieldRef(NamedStructType, usize),
556}
557
558#[derive(Debug, Clone)]
559pub struct MutOrImmutableExpression {
560 pub expression_or_location: ArgumentExpressionOrLocation,
561 pub is_mutable: Option<Node>,
562}
563
564impl MutOrImmutableExpression {
565 pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
566 match self.expression_or_location {
567 ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
568 ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
569 }
570 }
571
572 pub const fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
573 match &self.expression_or_location {
574 ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
575 ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
576 }
577 }
578
579 #[must_use]
580 pub const fn ty(&self) -> &Type {
581 match &self.expression_or_location {
582 ArgumentExpressionOrLocation::Expression(expr) => &expr.ty,
583 ArgumentExpressionOrLocation::Location(loc) => &loc.ty,
584 }
585 }
586
587 #[must_use]
588 pub const fn node(&self) -> &Node {
589 match &self.expression_or_location {
590 ArgumentExpressionOrLocation::Expression(expr) => &expr.node,
591 ArgumentExpressionOrLocation::Location(loc) => &loc.node,
592 }
593 }
594}
595
596#[derive(Debug, Clone)]
597pub enum ArgumentExpressionOrLocation {
598 Expression(Expression),
599 Location(SingleLocationExpression),
600}
601
602impl ArgumentExpressionOrLocation {
603 #[must_use]
604 pub fn ty(&self) -> Type {
605 match self {
606 Self::Expression(expr) => expr.ty.clone(),
607 Self::Location(location) => location.ty.clone(),
608 }
609 }
610}
611
612#[derive(Clone)]
613pub struct Expression {
614 pub ty: Type,
615 pub node: Node,
616 pub kind: ExpressionKind,
617}
618
619impl Debug for Expression {
620 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
621 write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
622 }
623}
624
625#[derive(Debug, Clone)]
626pub struct WhenBinding {
627 pub variable: VariableRef,
628 pub expr: MutOrImmutableExpression,
629}
630
631impl WhenBinding {
632 #[must_use]
633 pub const fn has_expression(&self) -> bool {
634 match &self.expr.expression_or_location {
635 ArgumentExpressionOrLocation::Expression(expr) => {
636 !matches!(expr.kind, ExpressionKind::VariableAccess(_))
637 }
638 ArgumentExpressionOrLocation::Location(_) => true,
639 }
640 }
641}
642
643#[derive(Debug, Clone)]
644pub enum ExpressionKind {
645 ConstantAccess(ConstantRef),
647 VariableAccess(VariableRef),
648
649 IntrinsicFunctionAccess(IntrinsicFunctionDefinitionRef),
651 InternalFunctionAccess(InternalFunctionDefinitionRef),
652 ExternalFunctionAccess(ExternalFunctionDefinitionRef),
653
654 BinaryOp(BinaryOperator),
656 UnaryOp(UnaryOperator),
657 PostfixChain(Box<Expression>, Vec<Postfix>),
658
659 CoerceOptionToBool(Box<Expression>),
662
663 FunctionValueCall(
667 Signature,
668 Box<Expression>,
669 Vec<ArgumentExpressionOrLocation>,
670 ),
671
672 InterpolatedString(Vec<StringPart>),
673
674 VariableDefinition(VariableRef, Box<MutOrImmutableExpression>), VariableReassignment(VariableRef, Box<MutOrImmutableExpression>),
677 Assignment(Box<SingleMutLocationExpression>, Box<Expression>),
678 CompoundAssignment(
679 SingleMutLocationExpression,
680 CompoundOperatorKind,
681 Box<Expression>,
682 ),
683
684 StructInstantiation(StructInstantiation),
685 AnonymousStructLiteral(AnonymousStructLiteral),
686 Literal(Literal),
687 Option(Option<Box<Expression>>), ForLoop(ForPattern, Iterable, Box<Expression>),
691 WhileLoop(BooleanExpression, Box<Expression>),
692
693 Block(Vec<Expression>),
694
695 Match(Match),
697 Guard(Vec<Guard>),
698 If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
699 When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
700
701 TupleDestructuring(Vec<VariableRef>, Vec<Type>, Box<Expression>),
702
703 IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpressionOrLocation>),
707 Lambda(Vec<VariableRef>, Box<Expression>),
717}
718
719#[derive(Debug, Clone)]
720pub struct StringConst(pub Node);
721
722#[derive(Debug, Clone)]
723pub enum Literal {
724 FloatLiteral(Fp),
725 NoneLiteral,
726 IntLiteral(i32),
727 StringLiteral(String),
728 BoolLiteral(bool),
729
730 EnumVariantLiteral(EnumType, EnumVariantType, EnumLiteralData),
731 TupleLiteral(Vec<Type>, Vec<Expression>),
732
733 Slice(Type, Vec<Expression>),
734 SlicePair(Type, Vec<(Expression, Expression)>),
735}
736
737#[derive(Debug, Clone)]
738pub struct ArrayInstantiation {
739 pub expressions: Vec<Expression>,
740 pub item_type: Type,
741 pub array_type: Type,
742 pub array_type_ref: Type,
743}
744
745#[derive(Debug, Clone)]
746pub enum ForPattern {
747 Single(VariableRef),
748 Pair(VariableRef, VariableRef),
749}
750
751impl ForPattern {
752 #[must_use]
753 pub fn is_mutable(&self) -> bool {
754 match self {
755 Self::Single(variable) => variable.is_mutable(),
756 Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
757 }
758 }
759}
760
761impl Display for ForPattern {
762 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
763 write!(f, "resolved_for_pattern")
764 }
765}
766
767#[derive(Debug, Eq, PartialEq)]
768pub struct ModulePathItem(pub Node);
769
770#[derive(Debug, Clone, Eq, PartialEq)]
771pub struct LocalTypeIdentifier(pub Node);
772
773#[derive(Debug, Clone)]
774pub struct Constant {
775 pub name: Node,
776 pub assigned_name: String,
777 pub id: ConstantId,
778 pub expr: Expression,
779 pub resolved_type: Type,
780}
781pub type ConstantRef = Rc<Constant>;
782
783pub type OptionTypeRef = Rc<crate::OptionType>;
784
785#[derive(Debug, Clone)]
786pub struct OptionType {
787 pub item_type: Type,
788}
789
790#[derive(Debug, Clone)]
807pub struct ImplMember {}
808
809#[derive(Debug, Clone)]
810pub enum UseItem {
811 Identifier(Node),
812 TypeIdentifier(Node),
813}
814
815#[derive(Debug, Clone)]
816pub struct Use {
817 pub path: Vec<Node>,
818 pub items: Vec<UseItem>,
819}
820
821#[derive(Debug, Clone)]
822pub struct ImplFunctions {
823 pub functions: SeqMap<String, FunctionRef>,
824}
825
826impl Default for ImplFunctions {
827 fn default() -> Self {
828 Self::new()
829 }
830}
831
832impl ImplFunctions {
833 #[must_use]
834 pub fn new() -> Self {
835 Self {
836 functions: SeqMap::default(),
837 }
838 }
839}
840
841#[derive(Debug, Clone)]
842pub struct AssociatedImpls {
843 pub functions: SeqMap<Type, ImplFunctions>,
844}
845
846impl Default for AssociatedImpls {
847 fn default() -> Self {
848 Self::new()
849 }
850}
851
852impl AssociatedImpls {
853 #[must_use]
854 pub fn new() -> Self {
855 Self {
856 functions: SeqMap::default(),
857 }
858 }
859}
860
861impl AssociatedImpls {
862 pub fn prepare(&mut self, ty: &Type) {
863 self.functions
864 .insert(ty.clone(), ImplFunctions::new())
865 .expect("should work");
866 }
867 #[must_use]
868 pub fn get_member_function(&self, ty: &Type, function_name: &str) -> Option<&FunctionRef> {
869 let maybe_found_impl = self.functions.get(ty);
870 if let Some(found_impl) = maybe_found_impl {
871 if let Some(func) = found_impl.functions.get(&function_name.to_string()) {
872 return Some(func);
873 }
874 }
875 None
876 }
877
878 #[must_use]
879 pub fn api_get_external_function(
880 &self,
881 ty: &Type,
882 function_name: &str,
883 ) -> Option<&ExternalFunctionDefinitionRef> {
884 if let Some(found) = self.get_member_function(ty, function_name) {
885 if let Function::External(ext_fn) = &**found {
886 return Some(ext_fn);
887 }
888 }
889 None
890 }
891
892 #[must_use]
893 pub fn api_fetch_external_function_id(
894 &self,
895 ty: &Type,
896 function_name: &str,
897 ) -> ExternalFunctionId {
898 self.api_get_external_function(ty, function_name)
899 .unwrap()
900 .id
901 }
902
903 #[must_use]
904 pub fn get_internal_member_function(
905 &self,
906 ty: &Type,
907 function_name: &str,
908 ) -> Option<&InternalFunctionDefinitionRef> {
909 if let Some(found) = self.get_member_function(ty, function_name) {
910 if let Function::Internal(int_fn) = &**found {
911 return Some(int_fn);
912 }
913 }
914 None
915 }
916
917 pub fn add_member_function(
918 &mut self,
919 ty: &Type,
920 name: &str,
921 func: FunctionRef,
922 ) -> Result<(), SemanticError> {
923 let maybe_found_impl = self.functions.get_mut(ty);
924
925 if let Some(found_impl) = maybe_found_impl {
926 found_impl
927 .functions
928 .insert(name.to_string(), func)
929 .expect("todo");
930 Ok(())
931 } else {
932 error!(%ty, ?name, "wasn't prepared");
933 Err(SemanticError::UnknownImplOnType)
934 }
935 }
936
937 pub fn add_external_member_function(
938 &mut self,
939 ty: &Type,
940 func: ExternalFunctionDefinition,
941 ) -> Result<(), SemanticError> {
942 self.add_member_function(
943 ty,
944 &func.assigned_name.clone(),
945 Function::External(func.into()).into(),
946 )
947 }
948
949 pub fn add_external_struct_member_function(
950 &mut self,
951 named_struct_type: &NamedStructType,
952 func: Function,
953 ) -> Result<(), SemanticError> {
954 self.add_member_function(
955 &Type::NamedStruct(named_struct_type.clone()),
956 &func.name(),
957 func.into(),
958 )
959 }
960
961 pub fn add_external_struct_member_function_external(
962 &mut self,
963 named_struct_type: NamedStructType,
964 func: ExternalFunctionDefinition,
965 ) -> Result<(), SemanticError> {
966 self.add_member_function(
967 &Type::NamedStruct(named_struct_type),
968 &func.assigned_name.clone(),
969 Function::External(func.into()).into(),
970 )
971 }
972
973 pub fn add_external_struct_member_function_external_ref(
974 &mut self,
975 named_struct_type: NamedStructType,
976 func: ExternalFunctionDefinitionRef,
977 ) -> Result<(), SemanticError> {
978 self.add_member_function(
979 &Type::NamedStruct(named_struct_type),
980 &func.assigned_name.clone(),
981 Function::External(func).into(),
982 )
983 }
984}
985
986#[derive(Debug, Clone)]
988pub struct ProgramState {
989 pub external_function_number: ExternalFunctionId,
990 pub internal_function_id_allocator: InternalFunctionIdAllocator,
991 pub constants_in_dependency_order: Vec<ConstantRef>,
995 pub instantiator: Instantiator,
996}
997
998impl Default for ProgramState {
999 fn default() -> Self {
1000 Self::new()
1001 }
1002}
1003
1004#[derive(Debug, Clone)]
1005pub struct InternalFunctionIdAllocator {
1006 pub internal_function_number: InternalFunctionId,
1007}
1008
1009impl Default for InternalFunctionIdAllocator {
1010 fn default() -> Self {
1011 Self::new()
1012 }
1013}
1014
1015impl InternalFunctionIdAllocator {
1016 #[must_use]
1017 pub const fn new() -> Self {
1018 Self {
1019 internal_function_number: 0,
1020 }
1021 }
1022 pub fn alloc(&mut self) -> InternalFunctionId {
1023 self.internal_function_number += 1;
1024 self.internal_function_number
1025 }
1026}
1027
1028impl ProgramState {
1029 #[must_use]
1030 pub fn new() -> Self {
1031 Self {
1032 external_function_number: 0,
1033 internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1034 constants_in_dependency_order: Vec::new(),
1035 instantiator: Instantiator::new(),
1036 }
1037 }
1038
1039 pub fn allocate_external_function_id(&mut self) -> ExternalFunctionId {
1040 self.external_function_number += 1;
1041 self.external_function_number
1042 }
1043
1044 pub fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1045 self.internal_function_id_allocator.alloc()
1046 }
1047}
1048
1049#[derive(Clone)]
1050pub enum EnumLiteralData {
1051 Nothing,
1052 Tuple(Vec<Expression>),
1053 Struct(Vec<(usize, Expression)>),
1054}
1055
1056impl Debug for EnumLiteralData {
1057 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1058 match self {
1059 Self::Nothing => Ok(()),
1060 Self::Tuple(x) => write!(f, "{x:?}"),
1061 Self::Struct(s) => write!(f, "{s:?}"),
1062 }
1063 }
1064}