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