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_refs::ReferenceTracker;
20use swamp_symbol::{ScopedSymbolId, SymbolIdAllocator, Symbols, TopLevelSymbolId};
21use swamp_types::prelude::*;
22use swamp_types::{Type, TypeRef};
23use tracing::error;
24
25#[derive(Debug, Clone)]
26pub struct TypeWithMut {
27 pub resolved_type: TypeRef,
28 pub is_mutable: bool,
29}
30
31#[derive(Debug, Clone)]
32pub enum SemanticError {
33 CouldNotInsertStruct,
34 DuplicateTypeAlias(String),
35 CanOnlyUseStructForMemberFunctions,
36 ResolveNotStruct,
37 DuplicateStructName(String),
38 DuplicateEnumType(String),
39 DuplicateEnumVariantType(String, String),
40 DuplicateFieldName(String),
41 DuplicateExternalFunction(String),
42 DuplicateRustType(String),
43 DuplicateConstName(String),
44 CircularConstantDependency(Vec<ConstantId>),
45 DuplicateConstantId(ConstantId),
46 IncompatibleTypes,
47 WasNotImmutable,
48 WasNotMutable,
49 DuplicateSymbolName(String),
50 DuplicateNamespaceLink(String),
51 MismatchedTypes {
52 expected: TypeRef,
53 found: Vec<TypeRef>,
54 },
55 UnknownImplOnType,
56 UnknownTypeVariable,
57 DuplicateDefinition(String),
58}
59
60#[derive(Debug, Eq, PartialEq)]
61pub struct LocalIdentifier(pub Node);
62
63#[derive(Debug)]
64pub struct InternalMainExpression {
65 pub expression: Expression,
66 pub scopes: VariableScopes,
67 pub program_unique_id: InternalFunctionId,
68}
69
70pub fn formal_function_name(internal_fn_def: &InternalFunctionDefinition) -> String {
71 let prefix = internal_fn_def
72 .associated_with_type
73 .as_ref()
74 .map_or_else(String::new, |associated_with_type| {
75 format!("{associated_with_type}::")
76 });
77 format!(
78 "{}::{}{}",
79 formal_module_name(&internal_fn_def.defined_in_module_path),
80 prefix,
81 internal_fn_def.assigned_name
82 )
83}
84
85pub struct InternalFunctionDefinition {
87 pub symbol_id: TopLevelSymbolId,
88 pub body: Expression,
89 pub name: LocalIdentifier,
90 pub assigned_name: String,
91 pub associated_with_type: Option<TypeRef>,
92 pub defined_in_module_path: Vec<String>,
93 pub signature: Signature,
94 pub function_variables: VariableScopes,
95 pub program_unique_id: InternalFunctionId,
96 pub attributes: Attributes,
97}
98
99impl Default for InternalFunctionDefinition {
100 fn default() -> Self {
101 Self {
102 body: Expression {
103 ty: Rc::new(Type {
104 id: TypeId::new(0),
105 flags: TypeFlags::default(),
106 kind: Rc::new(TypeKind::Byte),
107 }),
108 node: Node::default(),
109 kind: ExpressionKind::NoneLiteral,
110 },
111 name: LocalIdentifier(Node::default()),
112 assigned_name: String::new(),
113 associated_with_type: None,
114 defined_in_module_path: vec![],
115 signature: Signature {
116 parameters: vec![],
117 return_type: Rc::new(Type {
118 id: TypeId::new(0),
119 flags: TypeFlags::default(),
120 kind: Rc::new(TypeKind::Byte),
121 }),
122 },
123 function_variables: VariableScopes::default(),
124 symbol_id: TopLevelSymbolId::new_illegal(),
125 program_unique_id: 0,
126 attributes: Attributes::default(),
127 }
128 }
129}
130
131impl InternalFunctionDefinition {}
132
133impl Debug for InternalFunctionDefinition {
134 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
135 write!(f, "{:?}\n{:?}", self.signature, self.body)
136 }
137}
138
139impl PartialEq<Self> for InternalFunctionDefinition {
140 fn eq(&self, other: &Self) -> bool {
141 self.name == other.name
142 }
143}
144
145impl Eq for InternalFunctionDefinition {}
146
147pub type InternalFunctionDefinitionRef = Rc<InternalFunctionDefinition>;
148
149pub type ExternalFunctionId = u32;
150
151pub type InternalFunctionId = u16;
152
153pub type ConstantId = u32;
154
155#[must_use]
156pub fn pretty_module_name(parts: &[String]) -> String {
157 if parts[0] == "crate" {
158 parts[1..].join("::")
159 } else {
160 parts.join("::")
161 }
162}
163
164#[must_use]
165pub fn formal_module_name(parts: &[String]) -> String {
166 parts.join("::")
167}
168
169#[derive(Eq, PartialEq)]
170pub struct ExternalFunctionDefinition {
171 pub name: Node,
172 pub assigned_name: String,
173 pub signature: Signature,
174 pub id: ExternalFunctionId,
175}
176
177impl Debug for ExternalFunctionDefinition {
178 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
179 write!(f, "external fn")
180 }
181}
182
183pub type ExternalFunctionDefinitionRef = Rc<crate::ExternalFunctionDefinition>;
184
185#[derive(Debug, Eq, Clone, PartialEq)]
186pub enum BlockScopeMode {
187 Open,
188 Closed,
189 Lambda,
190}
191
192#[derive(Debug, Clone)]
193pub struct BlockScope {
194 pub mode: BlockScopeMode,
195 pub lookup: SeqMap<String, VariableRef>,
196 pub variables: SeqMap<usize, VariableRef>,
197 pub register_watermark: usize,
198}
199
200impl Display for BlockScope {
201 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
202 writeln!(f, "-- scope {:?}", self.mode)?;
203
204 for (index, (name, var)) in self.variables.iter().enumerate() {
205 writeln!(f, " var({index}): {name}:{var:?}")?;
206 }
207 Ok(())
208 }
209}
210
211impl Default for BlockScope {
212 fn default() -> Self {
213 Self::new()
214 }
215}
216
217impl BlockScope {
218 #[must_use]
219 pub fn new() -> Self {
220 Self {
221 mode: BlockScopeMode::Open,
222 variables: SeqMap::new(),
223 lookup: SeqMap::new(),
224 register_watermark: 0,
225 }
226 }
227}
228
229#[derive(Debug, Clone)]
230pub struct VariableScope {
231 pub mode: BlockScopeMode,
232 pub variables: SeqMap<usize, VariableRef>,
233}
234
235#[derive(Clone, Debug)]
236pub struct VariableScopes {
237 pub current_register: usize,
239 pub highest_virtual_register: usize,
240 pub all_variables: Vec<VariableRef>,
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 pub const fn finalize(&mut self) {
255 self.highest_virtual_register = self.current_register;
256 }
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 symbol_id: ScopedSymbolId,
336 pub name: Node,
337 pub assigned_name: String,
338 pub resolved_type: TypeRef,
339 pub mutable_node: Option<Node>,
340 pub variable_type: VariableType,
341
342 pub scope_index: usize,
343 pub variable_index: usize,
344 pub unique_id_within_function: usize,
345 pub virtual_register: u8,
346
347 pub is_unused: bool,
348}
349
350impl Variable {
351 #[must_use]
352 pub fn create_err(unit_type: TypeRef) -> Self {
353 Self {
354 symbol_id: ScopedSymbolId::new_illegal(),
355 name: Node::default(),
356 assigned_name: "err".to_string(),
357 resolved_type: unit_type,
358 mutable_node: None,
359 variable_type: VariableType::Local,
360 scope_index: 0,
361 variable_index: 0,
362 virtual_register: 0,
363 unique_id_within_function: 0,
364 is_unused: false,
365 }
366 }
367}
368
369impl Variable {
370 #[must_use]
371 pub const fn is_mutable(&self) -> bool {
372 self.mutable_node.is_some()
373 }
374
375 #[must_use]
376 pub const fn is_immutable(&self) -> bool {
377 !self.is_mutable()
378 }
379}
380
381pub type VariableRef = Rc<Variable>;
382
383#[derive(Debug, Clone)]
384pub struct MutVariable {
385 pub variable_ref: VariableRef,
386}
387
388#[derive(Debug, Clone)]
391pub enum BinaryOperatorKind {
392 Add,
393 Subtract,
394 Multiply,
395 Divide,
396 Modulo,
397 LogicalOr,
398 LogicalAnd,
399 Equal,
400 NotEqual,
401 LessThan,
402 LessEqual,
403 GreaterThan,
404 GreaterEqual,
405 NoneCoalesce,
406}
407
408#[derive(Debug, Clone)]
409pub struct BinaryOperator {
410 pub left: Box<Expression>,
411 pub right: Box<Expression>,
412 pub kind: BinaryOperatorKind,
413 pub node: Node,
414}
415
416#[derive(Debug, Clone)]
417pub enum UnaryOperatorKind {
418 Not,
419 Negate,
420}
421#[derive(Debug, Clone)]
422pub struct UnaryOperator {
423 pub left: Box<Expression>,
424 pub kind: UnaryOperatorKind,
425 pub node: Node,
426}
427
428#[derive()]
429pub struct InternalFunctionCall {
430 pub arguments: Vec<ArgumentExpression>,
431
432 pub function_definition: InternalFunctionDefinitionRef,
433 pub function_expression: Box<Expression>,
434}
435
436impl Debug for InternalFunctionCall {
437 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
438 write!(
439 f,
440 "InFuncCall({:?} {:?})",
441 self.function_expression, self.arguments
442 )
443 }
444}
445
446#[derive(Debug, Clone)]
447pub struct ExternalFunctionCall {
448 pub arguments: Vec<ArgumentExpression>,
449 pub function_definition: ExternalFunctionDefinitionRef,
450 pub function_expression: Box<Expression>,
451}
452
453pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
454 let mut result = String::new();
455 for (i, (key, value)) in values.iter().enumerate() {
456 if i > 0 {
457 result.push_str(", ");
458 }
459 result.push_str(format!("{key}: {value}").as_str());
460 }
461 result
462}
463
464#[derive(Debug, Clone)]
465pub struct MemberCall {
466 pub function: FunctionRef,
467 pub arguments: Vec<ArgumentExpression>,
468}
469
470#[derive(Debug, Clone)]
471pub struct ArrayItem {
472 pub item_type: Rc<TypeRef>,
473 pub int_expression: Expression,
474 pub array_expression: Expression,
475 pub array_type: Rc<TypeRef>,
476}
477
478pub type ArrayItemRef = Rc<ArrayItem>;
479
480#[derive(Debug, Clone)]
481pub enum PrecisionType {
482 Float,
483 String,
484}
485
486#[derive(Debug, Clone)]
487pub enum FormatSpecifierKind {
488 LowerHex, UpperHex, Binary, Float, Precision(u32, Node, PrecisionType), }
494
495#[derive(Debug, Clone)]
496pub struct FormatSpecifier {
497 pub node: Node,
498 pub kind: FormatSpecifierKind,
499}
500
501pub type FunctionRef = Rc<Function>;
502
503#[derive(Debug, Eq, Clone, PartialEq)]
504pub enum Function {
505 Internal(InternalFunctionDefinitionRef),
506 External(ExternalFunctionDefinitionRef),
507 Intrinsic(IntrinsicFunctionDefinitionRef),
508}
509
510impl Function {
511 #[must_use]
512 pub fn name(&self) -> String {
513 match self {
514 Self::Internal(x) => x.assigned_name.clone(),
515 Self::External(y) => y.assigned_name.clone(),
516 Self::Intrinsic(i) => i.name.clone(),
517 }
518 }
519
520 #[must_use]
521 pub fn symbol_id(&self) -> TopLevelSymbolId {
522 match self {
523 Self::Internal(x) => x.symbol_id,
524 Self::External(y) => TopLevelSymbolId::new_illegal(),
525 Self::Intrinsic(i) => TopLevelSymbolId::new_illegal(),
526 }
527 }
528
529 #[must_use]
530 pub fn maybe_node(&self) -> Option<&Node> {
531 match self {
532 Self::Internal(x) => Some(&x.name.0),
533 Self::External(y) => Some(&y.name),
534 Self::Intrinsic(_i) => None,
535 }
536 }
537
538 #[must_use]
539 pub fn node(&self) -> Node {
540 match self {
541 Self::Internal(x) => x.name.0.clone(),
542 Self::External(_y) => Node::new_unknown(),
543 Self::Intrinsic(_i) => Node::new_unknown(),
544 }
545 }
546
547 #[must_use]
548 pub fn signature(&self) -> &Signature {
549 match self {
550 Self::Internal(internal) => &internal.signature,
551 Self::External(external) => &external.signature,
552 Self::Intrinsic(i) => &i.signature,
553 }
554 }
555}
556
557#[derive(Debug, Clone)]
558pub struct BooleanExpression {
559 #[allow(unused)]
560 pub expression: Box<Expression>,
561}
562
563#[derive(Debug, Clone)]
565pub struct Match {
566 pub arms: Vec<MatchArm>,
567 pub expression: Box<Expression>,
568}
569
570impl Match {
571 #[must_use]
572 pub fn contains_wildcard(&self) -> bool {
573 for arm in &self.arms {
574 if let Pattern::Wildcard(_) = arm.pattern {
575 return true;
576 }
577 }
578 false
579 }
580}
581
582#[derive(Debug, Clone)]
583pub struct MatchArm {
584 #[allow(unused)]
585 pub pattern: Pattern,
586 pub expression: Box<Expression>,
587 pub expression_type: TypeRef,
588}
589
590#[derive(Debug, Clone)]
591pub enum Pattern {
592 Normal(NormalPattern, Option<BooleanExpression>),
593 Wildcard(Node),
594}
595
596#[derive(Debug, Clone)]
597pub enum NormalPattern {
598 PatternList(Vec<PatternElement>),
599 EnumPattern(EnumVariantType, Option<Vec<PatternElement>>),
600 Literal(Expression),
601}
602
603#[derive(Debug, Clone)]
604pub enum PatternElement {
605 Variable(VariableRef),
606 VariableWithFieldIndex(VariableRef, usize),
607 Wildcard(Node),
608}
609
610#[derive(Debug, Clone)]
611pub struct Iterable {
612 pub key_type: Option<TypeRef>, pub value_type: TypeRef,
614
615 pub resolved_expression: Box<Expression>,
616}
617
618#[derive(Debug, Clone)]
619pub struct AnonymousStructLiteral {
620 pub source_order_expressions: Vec<(usize, Option<Node>, Expression)>,
621 pub struct_like_type: TypeRef,
622}
623
624#[derive(Debug, Clone, Eq, PartialEq)]
625pub enum CompoundOperatorKind {
626 Add,
627 Sub,
628 Mul,
629 Div,
630 Modulo,
631}
632
633#[derive(Debug, Clone)]
634pub struct CompoundOperator {
635 pub node: Node,
636 pub kind: CompoundOperatorKind,
637}
638
639#[derive(Debug, Clone)]
640pub struct VariableCompoundAssignment {
641 pub variable_ref: VariableRef, pub expression: Box<Expression>,
643 pub compound_operator: CompoundOperator,
644}
645
646#[derive(Debug, Clone)]
647pub struct Guard {
648 pub condition: Option<BooleanExpression>,
649 pub result: Expression,
650}
651
652#[derive(Debug, Clone)]
653pub struct Postfix {
654 pub node: Node,
655 pub ty: TypeRef,
656 pub kind: PostfixKind,
657}
658
659#[derive(Debug, Clone)]
660pub struct SliceViewType {
661 pub element: TypeRef,
662}
663
664#[derive(Debug, Clone)]
665pub struct VecType {
666 pub element: TypeRef,
667}
668
669#[derive(Debug, Clone)]
670pub struct GridType {
671 pub element: TypeRef,
672}
673
674#[derive(Debug, Clone)]
675pub struct SparseType {
676 pub element: TypeRef,
677}
678
679#[derive(Debug, Clone)]
680pub struct MapType {
681 pub key: TypeRef,
682 pub value: TypeRef,
683}
684
685#[derive(Debug, Clone)]
686pub enum PostfixKind {
687 StructField(TypeRef, usize),
688 MemberCall(FunctionRef, Vec<ArgumentExpression>),
689 OptionalChainingOperator, VecSubscript(VecType, Expression),
692 VecSubscriptRange(VecType, Expression),
693 SparseSubscript(SparseType, Expression),
694 MapSubscript(MapType, Expression),
695 GridSubscript(GridType, Expression, Expression),
696}
697
698#[derive(Debug, Clone)]
699pub enum LocationAccessKind {
700 FieldIndex(AnonymousStructType, usize),
701 SliceViewSubscript(SliceViewType, Expression),
702 MapSubscriptCreateIfNeeded(MapType, Expression),
703 MapSubscriptMustExist(MapType, Expression),
704 SparseSubscript(SparseType, Expression),
705 GridSubscript(GridType, Expression, Expression),
706}
707
708#[derive(Debug, Clone)]
709pub struct LocationAccess {
710 pub node: Node,
711 pub ty: TypeRef,
712 pub kind: LocationAccessKind,
713}
714
715#[derive(Debug, Clone)]
716pub struct SingleLocationExpression {
717 pub kind: MutableReferenceKind,
718 pub node: Node,
719 pub ty: TypeRef,
720
721 pub starting_variable: VariableRef,
722 pub access_chain: Vec<LocationAccess>,
723}
724
725#[derive(Debug, Clone)]
726pub struct TargetAssignmentLocation(pub SingleLocationExpression);
727
728#[derive(Debug, Clone)]
729pub enum MutableReferenceKind {
730 MutVariableRef,
731 MutStructFieldRef(AnonymousStructType, usize),
732}
733
734#[derive(Debug, Clone)]
735pub enum ArgumentExpression {
736 Expression(Expression),
737 MaterializedExpression(Expression),
738 BorrowMutableReference(SingleLocationExpression),
739}
740
741impl ArgumentExpression {
742 #[must_use]
743 pub fn ty(&self) -> TypeRef {
744 match self {
745 Self::Expression(expr) => expr.ty.clone(),
746 Self::MaterializedExpression(expr) => expr.ty.clone(),
747 Self::BorrowMutableReference(location) => location.ty.clone(),
748 }
749 }
750
751 pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
752 match self {
753 Self::Expression(expr) => Ok(expr),
754 Self::MaterializedExpression(expr) => Ok(expr),
755 Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
756 }
757 }
758
759 pub const fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
760 match &self {
761 Self::Expression(expr) => Ok(expr),
762 Self::MaterializedExpression(expr) => Ok(expr),
763 Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
764 }
765 }
766
767 #[must_use]
768 pub const fn is_mutable_reference(&self) -> bool {
769 matches!(self, Self::BorrowMutableReference(_))
770 }
771
772 #[must_use]
773 pub const fn node(&self) -> &Node {
774 match &self {
775 Self::Expression(expr) => &expr.node,
776 Self::MaterializedExpression(expr) => &expr.node,
777 Self::BorrowMutableReference(loc) => &loc.node,
778 }
779 }
780}
781
782#[derive(Clone)]
783pub struct Expression {
784 pub ty: TypeRef,
785 pub node: Node,
786 pub kind: ExpressionKind,
787}
788
789impl Expression {
790 #[must_use]
791 pub fn debug_last_expression(&self) -> &Self {
792 match &self.kind {
793 ExpressionKind::ConstantAccess(a) => a.expr.debug_last_expression(),
794 ExpressionKind::BinaryOp(binary) => binary.right.debug_last_expression(),
795 ExpressionKind::UnaryOp(a) => a.left.debug_last_expression(),
796 ExpressionKind::ForLoop(_, _, a) => a.debug_last_expression(),
797 ExpressionKind::WhileLoop(_, a) => a.debug_last_expression(),
798 ExpressionKind::Block(block) => block.last().unwrap_or(self),
799 ExpressionKind::Match(a) => a.arms.last().unwrap().expression.debug_last_expression(),
800 ExpressionKind::Guard(g) => g.last().unwrap().result.debug_last_expression(),
801 ExpressionKind::If(_, a, _) => a.debug_last_expression(),
802 ExpressionKind::When(_, b, _a) => b,
803 ExpressionKind::TupleDestructuring(_, _, x) => x,
804 ExpressionKind::Lambda(_, a) => a.debug_last_expression(),
805 _ => self,
806 }
807 }
808}
809
810impl Debug for Expression {
811 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
812 write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
813 }
814}
815
816#[derive(Debug, Clone)]
817pub struct WhenBinding {
818 pub variable: VariableRef,
819 pub expr: Expression,
820}
821
822impl WhenBinding {
823 #[must_use]
824 pub const fn has_expression(&self) -> bool {
825 !matches!(self.expr.kind, ExpressionKind::VariableAccess(_))
826 }
827}
828
829#[derive(Debug, Clone)]
830pub enum StartOfChainKind {
831 Expression(Box<Expression>),
832 Variable(VariableRef),
833}
834
835#[derive(Debug, Clone)]
836pub struct StartOfChain {
837 pub kind: StartOfChainKind,
838 pub node: Node,
839}
840
841impl StartOfChain {}
842
843impl StartOfChainKind {
844 #[must_use]
845 pub fn ty(&self) -> TypeRef {
846 match self {
847 Self::Expression(expr) => expr.ty.clone(),
848 Self::Variable(var) => var.resolved_type.clone(),
849 }
850 }
851
852 #[must_use]
853 pub fn is_mutable(&self) -> bool {
854 match self {
855 Self::Expression(_call) => {
856 false
858 }
859 Self::Variable(var) => var.is_mutable(),
860 }
861 }
862}
863
864#[derive(Debug, Clone)]
865pub enum ExpressionKind {
866 ConstantAccess(ConstantRef),
868 VariableAccess(VariableRef),
869
870 BinaryOp(BinaryOperator),
874 UnaryOp(UnaryOperator),
875 PostfixChain(StartOfChain, Vec<Postfix>),
876
877 CoerceOptionToBool(Box<Expression>),
880 CoerceIntToChar(Box<Expression>),
881 CoerceIntToByte(Box<Expression>),
882 CoerceToAny(Box<Expression>),
883
884 IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpression>),
886 InternalCall(InternalFunctionDefinitionRef, Vec<ArgumentExpression>),
887 HostCall(ExternalFunctionDefinitionRef, Vec<ArgumentExpression>),
888
889 VariableDefinition(VariableRef, Box<Expression>), VariableDefinitionLValue(VariableRef, SingleLocationExpression), VariableReassignment(VariableRef, Box<Expression>),
893
894 Assignment(Box<TargetAssignmentLocation>, Box<Expression>),
895 CompoundAssignment(
896 TargetAssignmentLocation,
897 CompoundOperatorKind,
898 Box<Expression>,
899 ),
900
901 AnonymousStructLiteral(AnonymousStructLiteral),
902 NamedStructLiteral(Box<Expression>),
903
904 FloatLiteral(Fp),
905 NoneLiteral,
906 IntLiteral(i32),
907 ByteLiteral(u8),
908 StringLiteral(String),
909 BoolLiteral(bool),
910 EnumVariantLiteral(EnumVariantType, EnumLiteralExpressions), TupleLiteral(Vec<Expression>),
912
913 InitializerList(TypeRef, Vec<Expression>),
914 InitializerPairList(TypeRef, Vec<(Expression, Expression)>),
915
916 Option(Option<Box<Expression>>), ForLoop(ForPattern, Iterable, Box<Expression>),
920 WhileLoop(BooleanExpression, Box<Expression>),
921
922 Block(Vec<Expression>),
923
924 Match(Match),
926 Guard(Vec<Guard>),
927 If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
928 When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
929
930 TupleDestructuring(Vec<VariableRef>, TypeRef, Box<Expression>),
931
932 Lambda(Vec<VariableRef>, Box<Expression>),
933 BorrowMutRef(Box<SingleLocationExpression>),
934 Error(ErrorKind),
935}
936
937impl Display for ExpressionKind {
938 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
939 match self {
940 Self::ConstantAccess(_) => {
941 write!(f, "constant")
942 }
943 Self::VariableAccess(_) => {
944 write!(f, "varaccess")
945 }
946 Self::BinaryOp(_) => {
947 write!(f, "binaryop")
948 }
949 Self::UnaryOp(_) => {
950 write!(f, "unaryop")
951 }
952 Self::PostfixChain(_, _) => {
953 write!(f, "prefix")
954 }
955 Self::CoerceOptionToBool(_) => {
956 write!(f, "byte")
957 }
958 Self::CoerceIntToChar(_) => {
959 write!(f, "byte")
960 }
961 Self::CoerceIntToByte(_) => {
962 write!(f, "byte")
963 }
964 Self::CoerceToAny(_) => {
965 write!(f, "byte")
966 }
967 Self::IntrinsicCallEx(_, _) => {
968 write!(f, "byte")
969 }
970 Self::InternalCall(_, _) => {
971 write!(f, "byte")
972 }
973 Self::HostCall(_, _) => {
974 write!(f, "byte")
975 }
976 Self::VariableDefinition(a, b) => {
977 write!(f, "vardef {a:?} {}", b.kind)
978 }
979 Self::VariableDefinitionLValue(a, b) => {
980 write!(f, "vardefl {a:?}")
981 }
982 Self::VariableReassignment(_, _) => {
983 write!(f, "var reassignment")
984 }
985 Self::Assignment(_, _) => {
986 write!(f, "byte")
987 }
988 Self::CompoundAssignment(_, _, _) => {
989 write!(f, "byte")
990 }
991 Self::AnonymousStructLiteral(_) => {
992 write!(f, "byte")
993 }
994 Self::NamedStructLiteral(_) => {
995 write!(f, "byte")
996 }
997 Self::FloatLiteral(_) => {
998 write!(f, "byte")
999 }
1000 Self::NoneLiteral => {
1001 write!(f, "byte")
1002 }
1003 Self::IntLiteral(_) => {
1004 write!(f, "byte")
1005 }
1006 Self::ByteLiteral(_) => {
1007 write!(f, "byte")
1008 }
1009 Self::StringLiteral(_) => {
1010 write!(f, "byte")
1011 }
1012 Self::BoolLiteral(_) => {
1013 write!(f, "byte")
1014 }
1015 Self::EnumVariantLiteral(_, _) => {
1016 write!(f, "byte")
1017 }
1018 Self::TupleLiteral(_) => {
1019 write!(f, "byte")
1020 }
1021 Self::InitializerList(_, _) => {
1022 write!(f, "byte")
1023 }
1024 Self::InitializerPairList(_, _) => {
1025 write!(f, "byte")
1026 }
1027 Self::Option(_) => {
1028 write!(f, "byte")
1029 }
1030 Self::ForLoop(_, _, _) => {
1031 write!(f, "byte")
1032 }
1033 Self::WhileLoop(_, _) => {
1034 write!(f, "byte")
1035 }
1036 Self::Block(_) => {
1037 write!(f, "byte")
1038 }
1039 Self::Match(_) => {
1040 write!(f, "byte")
1041 }
1042 Self::Guard(_) => {
1043 write!(f, "byte")
1044 }
1045 Self::If(_, _, _) => {
1046 write!(f, "byte")
1047 }
1048 Self::When(_, _, _) => {
1049 write!(f, "byte")
1050 }
1051 Self::TupleDestructuring(_, _, _) => {
1052 write!(f, "byte")
1053 }
1054 Self::Lambda(_, _) => {
1055 write!(f, "byte")
1056 }
1057 Self::BorrowMutRef(_) => {
1058 write!(f, "byte")
1059 }
1060 Self::Error(_) => {
1061 write!(f, "byte")
1062 }
1063 }
1064 }
1065}
1066
1067#[derive(Debug, Clone)]
1068pub struct StringConst(pub Node);
1069
1070#[derive(Debug, Clone)]
1071pub struct ArrayInstantiation {
1072 pub expressions: Vec<Expression>,
1073 pub item_type: TypeRef,
1074 pub array_type: TypeRef,
1075 pub array_type_ref: TypeRef,
1076}
1077
1078#[derive(Debug, Clone)]
1079pub enum ForPattern {
1080 Single(VariableRef),
1081 Pair(VariableRef, VariableRef),
1082}
1083
1084impl ForPattern {
1085 #[must_use]
1086 pub fn is_mutable(&self) -> bool {
1087 match self {
1088 Self::Single(variable) => variable.is_mutable(),
1089 Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
1090 }
1091 }
1092}
1093
1094impl Display for ForPattern {
1095 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1096 write!(f, "resolved_for_pattern")
1097 }
1098}
1099
1100#[derive(Debug, Eq, PartialEq)]
1101pub struct ModulePathItem(pub Node);
1102
1103#[derive(Debug, Clone, Eq, PartialEq)]
1104pub struct LocalTypeIdentifier(pub Node);
1105
1106#[derive(Debug, Clone)]
1107pub struct Constant {
1108 pub symbol_id: TopLevelSymbolId,
1109 pub name: Node,
1110 pub assigned_name: String,
1111 pub id: ConstantId,
1112 pub expr: Expression,
1113 pub resolved_type: TypeRef,
1114 pub function_scope_state: VariableScopes,
1115}
1116pub type ConstantRef = Rc<Constant>;
1117
1118pub type OptionTypeRef = Rc<OptionType>;
1119
1120#[derive(Debug, Clone)]
1121pub struct OptionType {
1122 pub item_type: TypeRef,
1123}
1124
1125#[derive(Debug, Clone)]
1142pub struct ImplMember {}
1143
1144#[derive(Debug, Clone)]
1145pub enum UseItem {
1146 Identifier(Node),
1147 TypeIdentifier(Node),
1148}
1149
1150#[derive(Debug, Clone)]
1151pub struct Use {
1152 pub path: Vec<Node>,
1153 pub items: Vec<UseItem>,
1154}
1155
1156#[derive(Debug, Clone)]
1157pub struct ImplFunctions {
1158 pub functions: SeqMap<String, FunctionRef>,
1159}
1160
1161impl Default for ImplFunctions {
1162 fn default() -> Self {
1163 Self::new()
1164 }
1165}
1166
1167impl ImplFunctions {
1168 #[must_use]
1169 pub fn new() -> Self {
1170 Self {
1171 functions: SeqMap::default(),
1172 }
1173 }
1174}
1175
1176#[derive(Debug, Clone)]
1177pub struct AssociatedImpls {
1178 pub functions: SeqMap<TypeRef, ImplFunctions>,
1179}
1180
1181impl AssociatedImpls {}
1182
1183impl AssociatedImpls {}
1184
1185impl AssociatedImpls {}
1186
1187impl Default for AssociatedImpls {
1188 fn default() -> Self {
1189 Self::new()
1190 }
1191}
1192
1193impl AssociatedImpls {
1194 #[must_use]
1195 pub fn new() -> Self {
1196 Self {
1197 functions: SeqMap::default(),
1198 }
1199 }
1200}
1201
1202impl AssociatedImpls {
1203 pub fn prepare(&mut self, ty: &TypeRef) {
1204 self.functions
1205 .insert(ty.clone(), ImplFunctions::new())
1206 .unwrap_or_else(|_| panic!("should work {ty:?}"));
1207 }
1208
1209 #[must_use]
1210 pub fn is_prepared(&self, ty: &TypeRef) -> bool {
1211 self.functions.contains_key(ty)
1212 }
1213 #[must_use]
1214 pub fn get_member_function(&self, ty: &TypeRef, function_name: &str) -> Option<&FunctionRef> {
1215 let maybe_found_impl = self.functions.get(ty);
1216 if let Some(found_impl) = maybe_found_impl
1217 && let Some(func) = found_impl.functions.get(&function_name.to_string())
1218 {
1219 return Some(func);
1220 }
1221 None
1222 }
1223
1224 fn has_internal_member_function(&self, ty: &TypeRef, function_name: &str) -> bool {
1225 let maybe_found_impl = self.functions.get(ty);
1226 if let Some(found_impl) = maybe_found_impl
1227 && let Some(_func) = found_impl.functions.get(&function_name.to_string())
1228 {
1229 return true;
1230 }
1231 false
1232 }
1233
1234 #[must_use]
1235 pub fn api_get_external_function(
1236 &self,
1237 ty: &TypeRef,
1238 function_name: &str,
1239 ) -> Option<&ExternalFunctionDefinitionRef> {
1240 if let Some(found) = self.get_member_function(ty, function_name)
1241 && let Function::External(ext_fn) = &**found
1242 {
1243 return Some(ext_fn);
1244 }
1245 None
1246 }
1247
1248 #[must_use]
1249 pub fn get_internal_member_function(
1250 &self,
1251 ty: &TypeRef,
1252 function_name: &str,
1253 ) -> Option<&InternalFunctionDefinitionRef> {
1254 if let Some(found) = self.get_member_function(ty, function_name)
1255 && let Function::Internal(int_fn) = &**found
1256 {
1257 return Some(int_fn);
1258 }
1259 None
1260 }
1261
1262 pub fn remove_internal_function_if_exists(
1263 &mut self,
1264 ty: &TypeRef,
1265 function_name: &str,
1266 ) -> bool {
1267 if self.has_internal_member_function(ty, function_name) {
1268 let functions = self.functions.get_mut(ty).unwrap();
1269
1270 functions.functions.remove(&function_name.to_string());
1271 true
1272 } else {
1273 false
1274 }
1275 }
1276
1277 pub fn add_member_function(
1278 &mut self,
1279 ty: &TypeRef,
1280 name: &str,
1281 func: FunctionRef,
1282 ) -> Result<(), SemanticError> {
1283 let maybe_found_impl = self.functions.get_mut(ty);
1284
1285 if let Some(found_impl) = maybe_found_impl {
1286 found_impl
1287 .functions
1288 .insert(name.to_string(), func)
1289 .unwrap_or_else(|_| panic!("already had key {name}"));
1290 Ok(())
1291 } else {
1292 error!(%ty, ?name, "wasn't prepared");
1293 Err(SemanticError::UnknownImplOnType)
1294 }
1295 }
1296
1297 pub fn add_internal_function(
1298 &mut self,
1299 ty: &TypeRef,
1300 func: InternalFunctionDefinition,
1301 ) -> Result<(), SemanticError> {
1302 self.add_member_function(
1304 ty,
1305 &func.assigned_name.clone(),
1306 Function::Internal(func.into()).into(),
1307 )
1308 }
1309
1310 pub fn add_external_member_function(
1311 &mut self,
1312 ty: &TypeRef,
1313 func: ExternalFunctionDefinition,
1314 ) -> Result<(), SemanticError> {
1315 self.add_member_function(
1316 ty,
1317 &func.assigned_name.clone(),
1318 Function::External(func.into()).into(),
1319 )
1320 }
1321
1322 pub fn add_external_struct_member_function(
1323 &mut self,
1324 named_struct_type: TypeRef,
1325 func: Function,
1326 ) -> Result<(), SemanticError> {
1327 self.add_member_function(&named_struct_type, &func.name(), func.into())
1328 }
1329
1330 pub fn add_external_struct_member_function_external(
1331 &mut self,
1332 named_struct_type: TypeRef,
1333 func: ExternalFunctionDefinition,
1334 ) -> Result<(), SemanticError> {
1335 self.add_member_function(
1336 &named_struct_type,
1337 &func.assigned_name.clone(),
1338 Function::External(func.into()).into(),
1339 )
1340 }
1341
1342 pub fn add_external_struct_member_function_external_ref(
1343 &mut self,
1344 named_struct_type: TypeRef,
1345 func: ExternalFunctionDefinitionRef,
1346 ) -> Result<(), SemanticError> {
1347 self.add_member_function(
1348 &named_struct_type,
1349 &func.assigned_name.clone(),
1350 Function::External(func).into(),
1351 )
1352 }
1353}
1354
1355#[derive(Debug, Clone)]
1357pub struct ProgramState {
1358 pub internal_function_id_allocator: InternalFunctionIdAllocator,
1359 pub symbol_id_allocator: SymbolIdAllocator,
1360 pub symbols: Symbols,
1361 pub refs: ReferenceTracker,
1362 pub constants_in_dependency_order: Vec<ConstantRef>,
1366 pub associated_impls: AssociatedImpls,
1367 pub types: TypeCache,
1368 pub errors: Vec<Error>,
1369 pub hints: Vec<Error>,
1370 pub infos: Vec<Error>,
1371}
1372
1373impl ProgramState {
1374 #[must_use]
1375 pub const fn errors(&self) -> &Vec<Error> {
1376 &self.errors
1377 }
1378}
1379
1380impl Default for ProgramState {
1381 fn default() -> Self {
1382 Self::new()
1383 }
1384}
1385
1386#[derive(Debug, Clone)]
1387pub struct InternalFunctionIdAllocator {
1388 pub internal_function_number: InternalFunctionId,
1389}
1390
1391impl Default for InternalFunctionIdAllocator {
1392 fn default() -> Self {
1393 Self::new()
1394 }
1395}
1396
1397impl InternalFunctionIdAllocator {
1398 #[must_use]
1399 pub const fn new() -> Self {
1400 Self {
1401 internal_function_number: 0,
1402 }
1403 }
1404 pub const fn alloc(&mut self) -> InternalFunctionId {
1405 self.internal_function_number += 1;
1406 self.internal_function_number
1407 }
1408}
1409
1410impl ProgramState {
1411 #[must_use]
1412 pub fn new() -> Self {
1413 Self {
1414 symbol_id_allocator: SymbolIdAllocator::new(),
1415 symbols: Symbols::new(),
1416 refs: ReferenceTracker::new(),
1417 internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1418 constants_in_dependency_order: Vec::new(),
1419 associated_impls: AssociatedImpls::new(),
1420 types: TypeCache::new(),
1421 errors: vec![],
1422 hints: vec![],
1423 infos: vec![],
1424 }
1425 }
1426 pub const fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1427 self.internal_function_id_allocator.alloc()
1428 }
1429}
1430
1431#[derive(Clone)]
1432pub enum EnumLiteralExpressions {
1433 Nothing,
1434 Tuple(Vec<Expression>),
1435 Struct(Vec<(usize, Option<Node>, Expression)>),
1436}
1437
1438impl Debug for EnumLiteralExpressions {
1439 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1440 match self {
1441 Self::Nothing => Ok(()),
1442 Self::Tuple(x) => write!(f, "{x:?}"),
1443 Self::Struct(s) => write!(f, "{s:?}"),
1444 }
1445 }
1446}