1pub mod err;
6pub mod intr;
7pub mod prelude;
8use crate::err::{Error, ErrorKind};
9use crate::intr::IntrinsicFunction;
10use crate::prelude::IntrinsicFunctionDefinitionRef;
11pub use fixed32::Fp;
12use seq_map::SeqMap;
13use source_map_node::Node;
14use std::cmp::PartialEq;
15use std::fmt;
16use std::fmt::{Debug, Display, Formatter};
17use std::rc::Rc;
18use swamp_attributes::Attributes;
19use swamp_types::prelude::*;
20use swamp_types::{Type, TypeRef};
21use tracing::error;
22
23
24#[derive(Debug, Clone)]
25pub struct TypeWithMut {
26 pub resolved_type: TypeRef,
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 {
51 expected: TypeRef,
52 found: Vec<TypeRef>,
53 },
54 UnknownImplOnType,
55 UnknownTypeVariable,
56 DuplicateDefinition(String),
57}
58
59#[derive(Debug, Eq, PartialEq)]
60pub struct LocalIdentifier(pub Node);
61
62#[derive(Debug)]
63pub struct InternalMainExpression {
64 pub expression: Expression,
65 pub scopes: VariableScopes,
66 pub program_unique_id: InternalFunctionId,
67}
68
69pub fn formal_function_name(internal_fn_def: &InternalFunctionDefinition) -> String {
70 let prefix = internal_fn_def
71 .associated_with_type
72 .as_ref()
73 .map_or_else(String::new, |associated_with_type| {
74 format!("{associated_with_type}::")
75 });
76 format!(
77 "{}::{}{}",
78 formal_module_name(&internal_fn_def.defined_in_module_path),
79 prefix,
80 internal_fn_def.assigned_name
81 )
82}
83
84pub struct InternalFunctionDefinition {
86 pub body: Expression,
87 pub name: LocalIdentifier,
88 pub assigned_name: String,
89 pub associated_with_type: Option<TypeRef>,
90 pub defined_in_module_path: Vec<String>,
91 pub signature: Signature,
92 pub function_variables: VariableScopes,
93 pub program_unique_id: InternalFunctionId,
94 pub attributes: Attributes,
95}
96
97impl Default for InternalFunctionDefinition {
98 fn default() -> Self {
99 Self {
100 body: Expression {
101 ty: Rc::new(Type {
102 id: TypeId::new(0),
103 flags: TypeFlags::default(),
104 kind: Rc::new(TypeKind::Byte),
105 }),
106 node: Node::default(),
107 kind: ExpressionKind::NoneLiteral,
108 },
109 name: LocalIdentifier(Node::default()),
110 assigned_name: String::new(),
111 associated_with_type: None,
112 defined_in_module_path: vec![],
113 signature: Signature {
114 parameters: vec![],
115 return_type: Rc::new(Type {
116 id: TypeId::new(0),
117 flags: TypeFlags::default(),
118 kind: Rc::new(TypeKind::Byte),
119 }),
120 },
121 function_variables: VariableScopes::default(),
122 program_unique_id: 0,
123 attributes: Attributes::default(),
124 }
125 }
126}
127
128impl InternalFunctionDefinition {}
129
130impl Debug for InternalFunctionDefinition {
131 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
132 write!(f, "{:?}\n{:?}", self.signature, self.body)
133 }
134}
135
136impl PartialEq<Self> for InternalFunctionDefinition {
137 fn eq(&self, other: &Self) -> bool {
138 self.name == other.name
139 }
140}
141
142impl Eq for InternalFunctionDefinition {}
143
144pub type InternalFunctionDefinitionRef = Rc<InternalFunctionDefinition>;
145
146pub type ExternalFunctionId = u32;
147
148pub type InternalFunctionId = u16;
149
150pub type ConstantId = u32;
151
152#[must_use]
153pub fn pretty_module_name(parts: &[String]) -> String {
154 if parts[0] == "crate" {
155 parts[1..].join("::")
156 } else {
157 parts.join("::")
158 }
159}
160
161#[must_use]
162pub fn formal_module_name(parts: &[String]) -> String {
163 parts.join("::")
164}
165
166#[derive(Eq, PartialEq)]
167pub struct ExternalFunctionDefinition {
168 pub name: Option<Node>,
169 pub assigned_name: String,
170 pub signature: Signature,
171 pub id: ExternalFunctionId,
172}
173
174impl Debug for ExternalFunctionDefinition {
175 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
176 write!(f, "external fn")
177 }
178}
179
180pub type ExternalFunctionDefinitionRef = Rc<crate::ExternalFunctionDefinition>;
181
182#[derive(Debug, Eq, Clone, PartialEq)]
183pub enum BlockScopeMode {
184 Open,
185 Closed,
186 Lambda,
187}
188
189#[derive(Debug, Clone)]
190pub struct BlockScope {
191 pub mode: BlockScopeMode,
192 pub lookup: SeqMap<String, VariableRef>,
193 pub variables: SeqMap<usize, VariableRef>,
194 pub register_watermark: usize,
195
196}
197
198impl Display for BlockScope {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
200 writeln!(f, "-- scope {:?}", self.mode)?;
201
202 for (index, (name, var)) in self.variables.iter().enumerate() {
203 writeln!(f, " var({index}): {name}:{var:?}")?;
204 }
205 Ok(())
206 }
207}
208
209impl Default for BlockScope {
210 fn default() -> Self {
211 Self::new()
212 }
213}
214
215impl BlockScope {
216 #[must_use]
217 pub fn new() -> Self {
218 Self {
219 mode: BlockScopeMode::Open,
220 variables: SeqMap::new(),
221 lookup: SeqMap::new(),
222 register_watermark: 0,
223
224 }
225 }
226}
227
228#[derive(Debug, Clone)]
229pub struct VariableScope {
230 pub mode: BlockScopeMode,
231 pub variables: SeqMap<usize, VariableRef>,
232}
233
234#[derive(Clone, Debug)]
235pub struct VariableScopes {
236 pub current_register: usize,
238 pub highest_virtual_register: usize,
239 pub all_variables: Vec<VariableRef>,
240
241}
242
243impl VariableScopes {
244 #[must_use]
245 pub const fn new() -> Self {
246 Self {
247 current_register: 0,
249 all_variables: vec![],
250 highest_virtual_register: 0,
251
252 }
253 }
254
255 pub const fn finalize(&mut self) {
256 self.highest_virtual_register = self.current_register;
257 }
258}
259impl Default for VariableScopes {
260 fn default() -> Self {
261 Self::new()
262 }
263}
264
265#[derive(Clone, Debug)]
266pub struct FunctionScopeState {
267 pub block_scope_stack: Vec<BlockScope>,
268 pub variable_index: usize,
269}
270
271#[derive(Clone, Debug)]
272pub struct ScopeInfo {
273 pub active_scope: FunctionScopeState,
274 pub total_scopes: VariableScopes,
275}
276
277impl ScopeInfo {
278 #[must_use]
279 pub fn new() -> Self {
280 Self {
281 active_scope: FunctionScopeState::default(),
282 total_scopes: VariableScopes::default(),
283 }
284 }
285}
286
287impl Default for ScopeInfo {
288 fn default() -> Self {
289 Self::new()
290 }
291}
292
293impl Display for FunctionScopeState {
294 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
295 for (index, scope) in self.block_scope_stack.iter().enumerate() {
296 writeln!(f, "block({index}):\n{scope}")?;
297 }
298 Ok(())
299 }
300}
301
302impl FunctionScopeState {
303 pub const fn emit_variable_index(&mut self) -> usize {
304 self.variable_index += 1;
305
306 self.variable_index
307 }
308}
309
310impl Default for FunctionScopeState {
311 fn default() -> Self {
312 Self::new()
313 }
314}
315
316impl FunctionScopeState {
317 #[must_use]
318 pub fn new() -> Self {
319 Self {
320 block_scope_stack: vec![BlockScope::new()],
321 variable_index: 0,
323 }
324 }
325}
326
327#[derive(Debug, Clone)]
328pub enum VariableType {
329 Local,
330 Parameter,
331}
332
333#[derive(Debug, Clone)]
334pub struct Variable {
335 pub name: Node,
336 pub assigned_name: String,
337 pub resolved_type: TypeRef,
338 pub mutable_node: Option<Node>,
339 pub variable_type: VariableType,
340
341 pub scope_index: usize,
342 pub variable_index: usize,
343 pub unique_id_within_function: usize,
344 pub virtual_register: u8,
345
346 pub is_unused: bool,
347}
348
349impl Variable {
350 #[must_use]
351 pub fn create_err(unit_type: TypeRef) -> Self {
352 Self {
353 name: Node::default(),
354 assigned_name: "err".to_string(),
355 resolved_type: unit_type,
356 mutable_node: None,
357 variable_type: VariableType::Local,
358 scope_index: 0,
359 variable_index: 0,
360 virtual_register: 0,
361 unique_id_within_function: 0,
362 is_unused: false,
363 }
364 }
365}
366
367impl Variable {
368 #[must_use]
369 pub const fn is_mutable(&self) -> bool {
370 self.mutable_node.is_some()
371 }
372
373 #[must_use]
374 pub const fn is_immutable(&self) -> bool {
375 !self.is_mutable()
376 }
377}
378
379pub type VariableRef = Rc<Variable>;
380
381#[derive(Debug, Clone)]
382pub struct MutVariable {
383 pub variable_ref: VariableRef,
384}
385
386#[derive(Debug, Clone)]
389pub enum BinaryOperatorKind {
390 Add,
391 Subtract,
392 Multiply,
393 Divide,
394 Modulo,
395 LogicalOr,
396 LogicalAnd,
397 Equal,
398 NotEqual,
399 LessThan,
400 LessEqual,
401 GreaterThan,
402 GreaterEqual,
403 NoneCoalesce,
404}
405
406#[derive(Debug, Clone)]
407pub struct BinaryOperator {
408 pub left: Box<Expression>,
409 pub right: Box<Expression>,
410 pub kind: BinaryOperatorKind,
411 pub node: Node,
412}
413
414#[derive(Debug, Clone)]
415pub enum UnaryOperatorKind {
416 Not,
417 Negate,
418}
419#[derive(Debug, Clone)]
420pub struct UnaryOperator {
421 pub left: Box<Expression>,
422 pub kind: UnaryOperatorKind,
423 pub node: Node,
424}
425
426#[derive()]
427pub struct InternalFunctionCall {
428 pub arguments: Vec<ArgumentExpression>,
429
430 pub function_definition: InternalFunctionDefinitionRef,
431 pub function_expression: Box<Expression>,
432}
433
434impl Debug for InternalFunctionCall {
435 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
436 write!(
437 f,
438 "InFuncCall({:?} {:?})",
439 self.function_expression, self.arguments
440 )
441 }
442}
443
444#[derive(Debug, Clone)]
445pub struct ExternalFunctionCall {
446 pub arguments: Vec<ArgumentExpression>,
447 pub function_definition: ExternalFunctionDefinitionRef,
448 pub function_expression: Box<Expression>,
449}
450
451pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
452 let mut result = String::new();
453 for (i, (key, value)) in values.iter().enumerate() {
454 if i > 0 {
455 result.push_str(", ");
456 }
457 result.push_str(format!("{key}: {value}").as_str());
458 }
459 result
460}
461
462#[derive(Debug, Clone)]
463pub struct MemberCall {
464 pub function: FunctionRef,
465 pub arguments: Vec<ArgumentExpression>,
466}
467
468#[derive(Debug, Clone)]
469pub struct ArrayItem {
470 pub item_type: Rc<TypeRef>,
471 pub int_expression: Expression,
472 pub array_expression: Expression,
473 pub array_type: Rc<TypeRef>,
474}
475
476pub type ArrayItemRef = Rc<ArrayItem>;
477
478#[derive(Debug, Clone)]
479pub enum PrecisionType {
480 Float,
481 String,
482}
483
484#[derive(Debug, Clone)]
485pub enum FormatSpecifierKind {
486 LowerHex, UpperHex, Binary, Float, Precision(u32, Node, PrecisionType), }
492
493#[derive(Debug, Clone)]
494pub struct FormatSpecifier {
495 pub node: Node,
496 pub kind: FormatSpecifierKind,
497}
498
499pub type FunctionRef = Rc<Function>;
500
501#[derive(Debug, Eq, Clone, PartialEq)]
502pub enum Function {
503 Internal(InternalFunctionDefinitionRef),
504 External(ExternalFunctionDefinitionRef),
505 Intrinsic(IntrinsicFunctionDefinitionRef),
506}
507
508impl Function {
509 #[must_use]
510 pub fn name(&self) -> String {
511 match self {
512 Self::Internal(x) => x.assigned_name.clone(),
513 Self::External(y) => y.assigned_name.clone(),
514 Self::Intrinsic(i) => i.name.clone(),
515 }
516 }
517
518 #[must_use]
519 pub fn maybe_node(&self) -> Option<&Node> {
520 match self {
521 Self::Internal(x) => Some(&x.name.0),
522 Self::External(y) => y.name.as_ref(),
523 Self::Intrinsic(_i) => None,
524 }
525 }
526
527 #[must_use]
528 pub fn node(&self) -> Node {
529 match self {
530 Self::Internal(x) => x.name.0.clone(),
531 Self::External(_y) => Node::new_unknown(),
532 Self::Intrinsic(_i) => Node::new_unknown(),
533 }
534 }
535
536 #[must_use]
537 pub fn signature(&self) -> &Signature {
538 match self {
539 Self::Internal(internal) => &internal.signature,
540 Self::External(external) => &external.signature,
541 Self::Intrinsic(i) => &i.signature,
542 }
543 }
544}
545
546#[derive(Debug, Clone)]
547pub struct BooleanExpression {
548 #[allow(unused)]
549 pub expression: Box<Expression>,
550}
551
552#[derive(Debug, Clone)]
554pub struct Match {
555 pub arms: Vec<MatchArm>,
556 pub expression: Box<Expression>,
557}
558
559impl Match {
560 #[must_use]
561 pub fn contains_wildcard(&self) -> bool {
562 for arm in &self.arms {
563 if let Pattern::Wildcard(_) = arm.pattern {
564 return true;
565 }
566 }
567 false
568 }
569}
570
571#[derive(Debug, Clone)]
572pub struct MatchArm {
573 #[allow(unused)]
574 pub pattern: Pattern,
575 pub expression: Box<Expression>,
576 pub expression_type: TypeRef,
577}
578
579#[derive(Debug, Clone)]
580pub enum Pattern {
581 Normal(NormalPattern, Option<BooleanExpression>),
582 Wildcard(Node),
583}
584
585#[derive(Debug, Clone)]
586pub enum NormalPattern {
587 PatternList(Vec<PatternElement>),
588 EnumPattern(EnumVariantType, Option<Vec<PatternElement>>),
589 Literal(Expression),
590}
591
592#[derive(Debug, Clone)]
593pub enum PatternElement {
594 Variable(VariableRef),
595 VariableWithFieldIndex(VariableRef, usize),
596 Wildcard(Node),
597}
598
599#[derive(Debug, Clone)]
600pub struct Iterable {
601 pub key_type: Option<TypeRef>, pub value_type: TypeRef,
603
604 pub resolved_expression: Box<Expression>,
605}
606
607#[derive(Debug, Clone)]
608pub struct AnonymousStructLiteral {
609 pub source_order_expressions: Vec<(usize, Option<Node>, Expression)>,
610 pub struct_like_type: TypeRef,
611}
612
613#[derive(Debug, Clone, Eq, PartialEq)]
614pub enum CompoundOperatorKind {
615 Add,
616 Sub,
617 Mul,
618 Div,
619 Modulo,
620}
621
622#[derive(Debug, Clone)]
623pub struct CompoundOperator {
624 pub node: Node,
625 pub kind: CompoundOperatorKind,
626}
627
628#[derive(Debug, Clone)]
629pub struct VariableCompoundAssignment {
630 pub variable_ref: VariableRef, pub expression: Box<Expression>,
632 pub compound_operator: CompoundOperator,
633}
634
635#[derive(Debug, Clone)]
636pub struct Guard {
637 pub condition: Option<BooleanExpression>,
638 pub result: Expression,
639}
640
641#[derive(Debug, Clone)]
642pub struct Postfix {
643 pub node: Node,
644 pub ty: TypeRef,
645 pub kind: PostfixKind,
646}
647
648#[derive(Debug, Clone)]
649pub struct SliceViewType {
650 pub element: TypeRef,
651}
652
653#[derive(Debug, Clone)]
654pub struct VecType {
655 pub element: TypeRef,
656}
657
658#[derive(Debug, Clone)]
659pub struct GridType {
660 pub element: TypeRef,
661}
662
663#[derive(Debug, Clone)]
664pub struct SparseType {
665 pub element: TypeRef,
666}
667
668#[derive(Debug, Clone)]
669pub struct MapType {
670 pub key: TypeRef,
671 pub value: TypeRef,
672}
673
674#[derive(Debug, Clone)]
675pub enum PostfixKind {
676 StructField(TypeRef, usize),
677 MemberCall(FunctionRef, Vec<ArgumentExpression>),
678 OptionalChainingOperator, VecSubscript(VecType, Expression),
681 VecSubscriptRange(VecType, Expression),
682 SparseSubscript(SparseType, Expression),
683 MapSubscript(MapType, Expression),
684 GridSubscript(GridType, Expression, Expression),
685}
686
687#[derive(Debug, Clone)]
688pub enum LocationAccessKind {
689 FieldIndex(AnonymousStructType, usize),
690 SliceViewSubscript(SliceViewType, Expression),
691 MapSubscriptCreateIfNeeded(MapType, Expression),
692 MapSubscriptMustExist(MapType, Expression),
693 SparseSubscript(SparseType, Expression),
694 GridSubscript(GridType, Expression, Expression),
695}
696
697#[derive(Debug, Clone)]
698pub struct LocationAccess {
699 pub node: Node,
700 pub ty: TypeRef,
701 pub kind: LocationAccessKind,
702}
703
704#[derive(Debug, Clone)]
705pub struct SingleLocationExpression {
706 pub kind: MutableReferenceKind,
707 pub node: Node,
708 pub ty: TypeRef,
709
710 pub starting_variable: VariableRef,
711 pub access_chain: Vec<LocationAccess>,
712}
713
714#[derive(Debug, Clone)]
715pub struct TargetAssignmentLocation(pub SingleLocationExpression);
716
717#[derive(Debug, Clone)]
718pub enum MutableReferenceKind {
719 MutVariableRef,
720 MutStructFieldRef(AnonymousStructType, usize),
721}
722
723#[derive(Debug, Clone)]
724pub enum ArgumentExpression {
725 Expression(Expression),
726 BorrowMutableReference(SingleLocationExpression),
727}
728
729impl ArgumentExpression {
730 #[must_use]
731 pub fn ty(&self) -> TypeRef {
732 match self {
733 Self::Expression(expr) => expr.ty.clone(),
734 Self::BorrowMutableReference(location) => location.ty.clone(),
735 }
736 }
737
738 pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
739 match self {
740 Self::Expression(expr) => Ok(expr),
741 Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
742 }
743 }
744
745 pub const fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
746 match &self {
747 Self::Expression(expr) => Ok(expr),
748 Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
749 }
750 }
751
752 #[must_use]
753 pub const fn is_mutable_reference(&self) -> bool {
754 matches!(self, Self::BorrowMutableReference(_))
755 }
756
757 #[must_use]
758 pub const fn node(&self) -> &Node {
759 match &self {
760 Self::Expression(expr) => &expr.node,
761 Self::BorrowMutableReference(loc) => &loc.node,
762 }
763 }
764}
765
766#[derive(Clone)]
767pub struct Expression {
768 pub ty: TypeRef,
769 pub node: Node,
770 pub kind: ExpressionKind,
771}
772
773impl Expression {
774 #[must_use]
775 pub fn debug_last_expression(&self) -> &Self {
776 match &self.kind {
777 ExpressionKind::ConstantAccess(a) => a.expr.debug_last_expression(),
778 ExpressionKind::BinaryOp(binary) => binary.right.debug_last_expression(),
779 ExpressionKind::UnaryOp(a) => a.left.debug_last_expression(),
780 ExpressionKind::ForLoop(_, _, a) => a.debug_last_expression(),
781 ExpressionKind::WhileLoop(_, a) => a.debug_last_expression(),
782 ExpressionKind::Block(block) => block.last().unwrap_or(self),
783 ExpressionKind::Match(a) => a.arms.last().unwrap().expression.debug_last_expression(),
784 ExpressionKind::Guard(g) => g.last().unwrap().result.debug_last_expression(),
785 ExpressionKind::If(_, a, _) => a.debug_last_expression(),
786 ExpressionKind::When(_, b, _a) => b,
787 ExpressionKind::TupleDestructuring(_, _, x) => x,
788 ExpressionKind::Lambda(_, a) => a.debug_last_expression(),
789 _ => self,
790 }
791 }
792}
793
794impl Debug for Expression {
795 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
796 write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
797 }
798}
799
800#[derive(Debug, Clone)]
801pub struct WhenBinding {
802 pub variable: VariableRef,
803 pub expr: Expression,
804}
805
806impl WhenBinding {
807 #[must_use]
808 pub const fn has_expression(&self) -> bool {
809 !matches!(self.expr.kind, ExpressionKind::VariableAccess(_))
810 }
811}
812
813#[derive(Debug, Clone)]
814pub enum StartOfChainKind {
815 Expression(Box<Expression>),
816 Variable(VariableRef),
817}
818
819#[derive(Debug, Clone)]
820pub struct StartOfChain {
821 pub kind: StartOfChainKind,
822 pub node: Node,
823}
824
825impl StartOfChain {}
826
827impl StartOfChainKind {
828 #[must_use]
829 pub fn ty(&self) -> TypeRef {
830 match self {
831 Self::Expression(expr) => expr.ty.clone(),
832 Self::Variable(var) => var.resolved_type.clone(),
833 }
834 }
835
836 #[must_use]
837 pub fn is_mutable(&self) -> bool {
838 match self {
839 Self::Expression(_call) => {
840 false
842 }
843 Self::Variable(var) => var.is_mutable(),
844 }
845 }
846}
847
848#[derive(Debug, Clone)]
849pub enum ExpressionKind {
850 ConstantAccess(ConstantRef),
852 VariableAccess(VariableRef),
853
854 BinaryOp(BinaryOperator),
858 UnaryOp(UnaryOperator),
859 PostfixChain(StartOfChain, Vec<Postfix>),
860
861 CoerceOptionToBool(Box<Expression>),
864 CoerceIntToChar(Box<Expression>),
865 CoerceIntToByte(Box<Expression>),
866 CoerceToAny(Box<Expression>),
867
868 IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpression>),
870 InternalCall(InternalFunctionDefinitionRef, Vec<ArgumentExpression>),
871 HostCall(ExternalFunctionDefinitionRef, Vec<ArgumentExpression>),
872
873 VariableDefinition(VariableRef, Box<Expression>), VariableDefinitionLValue(VariableRef, SingleLocationExpression), VariableReassignment(VariableRef, Box<Expression>),
877
878 Assignment(Box<TargetAssignmentLocation>, Box<Expression>),
879 CompoundAssignment(
880 TargetAssignmentLocation,
881 CompoundOperatorKind,
882 Box<Expression>,
883 ),
884
885 AnonymousStructLiteral(AnonymousStructLiteral),
886
887 FloatLiteral(Fp),
888 NoneLiteral,
889 IntLiteral(i32),
890 ByteLiteral(u8),
891 StringLiteral(String),
892 BoolLiteral(bool),
893 EnumVariantLiteral(EnumVariantType, EnumLiteralExpressions), TupleLiteral(Vec<Expression>),
895
896 InitializerList(TypeRef, Vec<Expression>),
897 InitializerPairList(TypeRef, Vec<(Expression, Expression)>),
898
899 Option(Option<Box<Expression>>), ForLoop(ForPattern, Iterable, Box<Expression>),
903 WhileLoop(BooleanExpression, Box<Expression>),
904
905 Block(Vec<Expression>),
906
907 Match(Match),
909 Guard(Vec<Guard>),
910 If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
911 When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
912
913 TupleDestructuring(Vec<VariableRef>, TypeRef, Box<Expression>),
914
915 Lambda(Vec<VariableRef>, Box<Expression>),
916 BorrowMutRef(Box<SingleLocationExpression>),
917 Error(ErrorKind),
918}
919
920#[derive(Debug, Clone)]
921pub struct StringConst(pub Node);
922
923#[derive(Debug, Clone)]
924pub struct ArrayInstantiation {
925 pub expressions: Vec<Expression>,
926 pub item_type: TypeRef,
927 pub array_type: TypeRef,
928 pub array_type_ref: TypeRef,
929}
930
931#[derive(Debug, Clone)]
932pub enum ForPattern {
933 Single(VariableRef),
934 Pair(VariableRef, VariableRef),
935}
936
937impl ForPattern {
938 #[must_use]
939 pub fn is_mutable(&self) -> bool {
940 match self {
941 Self::Single(variable) => variable.is_mutable(),
942 Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
943 }
944 }
945}
946
947impl Display for ForPattern {
948 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
949 write!(f, "resolved_for_pattern")
950 }
951}
952
953#[derive(Debug, Eq, PartialEq)]
954pub struct ModulePathItem(pub Node);
955
956#[derive(Debug, Clone, Eq, PartialEq)]
957pub struct LocalTypeIdentifier(pub Node);
958
959#[derive(Debug, Clone)]
960pub struct Constant {
961 pub name: Node,
962 pub assigned_name: String,
963 pub id: ConstantId,
964 pub expr: Expression,
965 pub resolved_type: TypeRef,
966 pub function_scope_state: VariableScopes,
967}
968pub type ConstantRef = Rc<Constant>;
969
970pub type OptionTypeRef = Rc<OptionType>;
971
972#[derive(Debug, Clone)]
973pub struct OptionType {
974 pub item_type: TypeRef,
975}
976
977#[derive(Debug, Clone)]
994pub struct ImplMember {}
995
996#[derive(Debug, Clone)]
997pub enum UseItem {
998 Identifier(Node),
999 TypeIdentifier(Node),
1000}
1001
1002#[derive(Debug, Clone)]
1003pub struct Use {
1004 pub path: Vec<Node>,
1005 pub items: Vec<UseItem>,
1006}
1007
1008#[derive(Debug, Clone)]
1009pub struct ImplFunctions {
1010 pub functions: SeqMap<String, FunctionRef>,
1011}
1012
1013impl Default for ImplFunctions {
1014 fn default() -> Self {
1015 Self::new()
1016 }
1017}
1018
1019impl ImplFunctions {
1020 #[must_use]
1021 pub fn new() -> Self {
1022 Self {
1023 functions: SeqMap::default(),
1024 }
1025 }
1026}
1027
1028#[derive(Debug, Clone)]
1029pub struct AssociatedImpls {
1030 pub functions: SeqMap<TypeRef, ImplFunctions>,
1031}
1032
1033impl AssociatedImpls {}
1034
1035impl AssociatedImpls {}
1036
1037impl AssociatedImpls {}
1038
1039impl Default for AssociatedImpls {
1040 fn default() -> Self {
1041 Self::new()
1042 }
1043}
1044
1045impl AssociatedImpls {
1046 #[must_use]
1047 pub fn new() -> Self {
1048 Self {
1049 functions: SeqMap::default(),
1050 }
1051 }
1052}
1053
1054impl AssociatedImpls {
1055 pub fn prepare(&mut self, ty: &TypeRef) {
1056 self.functions
1057 .insert(ty.clone(), ImplFunctions::new())
1058 .unwrap_or_else(|_| panic!("should work {ty:?}"));
1059 }
1060
1061 #[must_use]
1062 pub fn is_prepared(&self, ty: &TypeRef) -> bool {
1063 self.functions.contains_key(ty)
1064 }
1065 #[must_use]
1066 pub fn get_member_function(&self, ty: &TypeRef, function_name: &str) -> Option<&FunctionRef> {
1067 let maybe_found_impl = self.functions.get(ty);
1068 if let Some(found_impl) = maybe_found_impl
1069 && let Some(func) = found_impl.functions.get(&function_name.to_string()) {
1070 return Some(func);
1071 }
1072 None
1073 }
1074
1075 fn has_internal_member_function(&self, ty: &TypeRef, function_name: &str) -> bool {
1076 let maybe_found_impl = self.functions.get(ty);
1077 if let Some(found_impl) = maybe_found_impl
1078 && let Some(_func) = found_impl.functions.get(&function_name.to_string()) {
1079 return true;
1080 }
1081 false
1082 }
1083
1084 #[must_use]
1085 pub fn api_get_external_function(
1086 &self,
1087 ty: &TypeRef,
1088 function_name: &str,
1089 ) -> Option<&ExternalFunctionDefinitionRef> {
1090 if let Some(found) = self.get_member_function(ty, function_name)
1091 && let Function::External(ext_fn) = &**found {
1092 return Some(ext_fn);
1093 }
1094 None
1095 }
1096
1097 #[must_use]
1098 pub fn get_internal_member_function(
1099 &self,
1100 ty: &TypeRef,
1101 function_name: &str,
1102 ) -> Option<&InternalFunctionDefinitionRef> {
1103 if let Some(found) = self.get_member_function(ty, function_name)
1104 && let Function::Internal(int_fn) = &**found {
1105 return Some(int_fn);
1106 }
1107 None
1108 }
1109
1110 pub fn remove_internal_function_if_exists(
1111 &mut self,
1112 ty: &TypeRef,
1113 function_name: &str,
1114 ) -> bool {
1115 if self.has_internal_member_function(ty, function_name) {
1116 let functions = self.functions.get_mut(ty).unwrap();
1117
1118 functions.functions.remove(&function_name.to_string());
1119 true
1120 } else {
1121 false
1122 }
1123 }
1124
1125 pub fn add_member_function(
1126 &mut self,
1127 ty: &TypeRef,
1128 name: &str,
1129 func: FunctionRef,
1130 ) -> Result<(), SemanticError> {
1131 let maybe_found_impl = self.functions.get_mut(ty);
1132
1133 if let Some(found_impl) = maybe_found_impl {
1134 found_impl
1135 .functions
1136 .insert(name.to_string(), func)
1137 .unwrap_or_else(|_| panic!("already had key {name}"));
1138 Ok(())
1139 } else {
1140 error!(%ty, ?name, "wasn't prepared");
1141 Err(SemanticError::UnknownImplOnType)
1142 }
1143 }
1144
1145 pub fn add_internal_function(
1146 &mut self,
1147 ty: &TypeRef,
1148 func: InternalFunctionDefinition,
1149 ) -> Result<(), SemanticError> {
1150 self.add_member_function(
1152 ty,
1153 &func.assigned_name.clone(),
1154 Function::Internal(func.into()).into(),
1155 )
1156 }
1157
1158 pub fn add_external_member_function(
1159 &mut self,
1160 ty: &TypeRef,
1161 func: ExternalFunctionDefinition,
1162 ) -> Result<(), SemanticError> {
1163 self.add_member_function(
1164 ty,
1165 &func.assigned_name.clone(),
1166 Function::External(func.into()).into(),
1167 )
1168 }
1169
1170 pub fn add_external_struct_member_function(
1171 &mut self,
1172 named_struct_type: TypeRef,
1173 func: Function,
1174 ) -> Result<(), SemanticError> {
1175 self.add_member_function(&named_struct_type, &func.name(), func.into())
1176 }
1177
1178 pub fn add_external_struct_member_function_external(
1179 &mut self,
1180 named_struct_type: TypeRef,
1181 func: ExternalFunctionDefinition,
1182 ) -> Result<(), SemanticError> {
1183 self.add_member_function(
1184 &named_struct_type,
1185 &func.assigned_name.clone(),
1186 Function::External(func.into()).into(),
1187 )
1188 }
1189
1190 pub fn add_external_struct_member_function_external_ref(
1191 &mut self,
1192 named_struct_type: TypeRef,
1193 func: ExternalFunctionDefinitionRef,
1194 ) -> Result<(), SemanticError> {
1195 self.add_member_function(
1196 &named_struct_type,
1197 &func.assigned_name.clone(),
1198 Function::External(func).into(),
1199 )
1200 }
1201}
1202
1203#[derive(Debug, Clone)]
1205pub struct ProgramState {
1206 pub internal_function_id_allocator: InternalFunctionIdAllocator,
1207 pub constants_in_dependency_order: Vec<ConstantRef>,
1211 pub associated_impls: AssociatedImpls,
1212 pub types: TypeCache,
1213 pub errors: Vec<Error>,
1214 pub hints: Vec<Error>,
1215 pub infos: Vec<Error>,
1216}
1217
1218impl ProgramState {
1219 #[must_use]
1220 pub const fn errors(&self) -> &Vec<Error> {
1221 &self.errors
1222 }
1223}
1224
1225impl Default for ProgramState {
1226 fn default() -> Self {
1227 Self::new()
1228 }
1229}
1230
1231#[derive(Debug, Clone)]
1232pub struct InternalFunctionIdAllocator {
1233 pub internal_function_number: InternalFunctionId,
1234}
1235
1236impl Default for InternalFunctionIdAllocator {
1237 fn default() -> Self {
1238 Self::new()
1239 }
1240}
1241
1242impl InternalFunctionIdAllocator {
1243 #[must_use]
1244 pub const fn new() -> Self {
1245 Self {
1246 internal_function_number: 0,
1247 }
1248 }
1249 pub const fn alloc(&mut self) -> InternalFunctionId {
1250 self.internal_function_number += 1;
1251 self.internal_function_number
1252 }
1253}
1254
1255impl ProgramState {
1256 #[must_use]
1257 pub fn new() -> Self {
1258 Self {
1259 internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1260 constants_in_dependency_order: Vec::new(),
1261 associated_impls: AssociatedImpls::new(),
1262 types: TypeCache::new(),
1263 errors: vec![],
1264 hints: vec![],
1265 infos: vec![],
1266 }
1267 }
1268 pub const fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1269 self.internal_function_id_allocator.alloc()
1270 }
1271}
1272
1273#[derive(Clone)]
1274pub enum EnumLiteralExpressions {
1275 Nothing,
1276 Tuple(Vec<Expression>),
1277 Struct(Vec<(usize, Option<Node>, Expression)>),
1278}
1279
1280impl Debug for EnumLiteralExpressions {
1281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1282 match self {
1283 Self::Nothing => Ok(()),
1284 Self::Tuple(x) => write!(f, "{x:?}"),
1285 Self::Struct(s) => write!(f, "{s:?}"),
1286 }
1287 }
1288}