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 }
257}
258impl Default for VariableScopes {
259 fn default() -> Self {
260 Self::new()
261 }
262}
263
264#[derive(Clone, Debug)]
265pub struct FunctionScopeState {
266 pub block_scope_stack: Vec<BlockScope>,
267 pub variable_index: usize,
268}
269
270#[derive(Clone, Debug)]
271pub struct ScopeInfo {
272 pub active_scope: FunctionScopeState,
273 pub total_scopes: VariableScopes,
274}
275
276impl ScopeInfo {
277 #[must_use]
278 pub fn new() -> Self {
279 Self {
280 active_scope: FunctionScopeState::default(),
281 total_scopes: VariableScopes::default(),
282 }
283 }
284}
285
286impl Default for ScopeInfo {
287 fn default() -> Self {
288 Self::new()
289 }
290}
291
292impl Display for FunctionScopeState {
293 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
294 for (index, scope) in self.block_scope_stack.iter().enumerate() {
295 writeln!(f, "block({index}):\n{scope}")?;
296 }
297 Ok(())
298 }
299}
300
301impl FunctionScopeState {
302 pub const fn emit_variable_index(&mut self) -> usize {
303 self.variable_index += 1;
304
305 self.variable_index
306 }
307}
308
309impl Default for FunctionScopeState {
310 fn default() -> Self {
311 Self::new()
312 }
313}
314
315impl FunctionScopeState {
316 #[must_use]
317 pub fn new() -> Self {
318 Self {
319 block_scope_stack: vec![BlockScope::new()],
320 variable_index: 0,
322 }
323 }
324}
325
326#[derive(Debug, Clone)]
327pub enum VariableType {
328 Local,
329 Parameter,
330}
331
332#[derive(Debug, Clone)]
333pub struct Variable {
334 pub symbol_id: ScopedSymbolId,
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 symbol_id: ScopedSymbolId::new_illegal(),
354 name: Node::default(),
355 assigned_name: "err".to_string(),
356 resolved_type: unit_type,
357 mutable_node: None,
358 variable_type: VariableType::Local,
359 scope_index: 0,
360 variable_index: 0,
361 virtual_register: 0,
362 unique_id_within_function: 0,
363 is_unused: false,
364 }
365 }
366}
367
368impl Variable {
369 #[must_use]
370 pub const fn is_mutable(&self) -> bool {
371 self.mutable_node.is_some()
372 }
373
374 #[must_use]
375 pub const fn is_immutable(&self) -> bool {
376 !self.is_mutable()
377 }
378}
379
380pub type VariableRef = Rc<Variable>;
381
382#[derive(Debug, Clone)]
383pub struct MutVariable {
384 pub variable_ref: VariableRef,
385}
386
387#[derive(Debug, Clone)]
390pub enum BinaryOperatorKind {
391 Add,
392 Subtract,
393 Multiply,
394 Divide,
395 Modulo,
396 LogicalOr,
397 LogicalAnd,
398 Equal,
399 NotEqual,
400 LessThan,
401 LessEqual,
402 GreaterThan,
403 GreaterEqual,
404 NoneCoalesce,
405}
406
407#[derive(Debug, Clone)]
408pub struct BinaryOperator {
409 pub left: Box<Expression>,
410 pub right: Box<Expression>,
411 pub kind: BinaryOperatorKind,
412 pub node: Node,
413}
414
415#[derive(Debug, Clone)]
416pub enum UnaryOperatorKind {
417 Not,
418 Negate,
419}
420#[derive(Debug, Clone)]
421pub struct UnaryOperator {
422 pub left: Box<Expression>,
423 pub kind: UnaryOperatorKind,
424 pub node: Node,
425}
426
427#[derive()]
428pub struct InternalFunctionCall {
429 pub arguments: Vec<ArgumentExpression>,
430
431 pub function_definition: InternalFunctionDefinitionRef,
432 pub function_expression: Box<Expression>,
433}
434
435impl Debug for InternalFunctionCall {
436 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
437 write!(
438 f,
439 "InFuncCall({:?} {:?})",
440 self.function_expression, self.arguments
441 )
442 }
443}
444
445#[derive(Debug, Clone)]
446pub struct ExternalFunctionCall {
447 pub arguments: Vec<ArgumentExpression>,
448 pub function_definition: ExternalFunctionDefinitionRef,
449 pub function_expression: Box<Expression>,
450}
451
452pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
453 let mut result = String::new();
454 for (i, (key, value)) in values.iter().enumerate() {
455 if i > 0 {
456 result.push_str(", ");
457 }
458 result.push_str(format!("{key}: {value}").as_str());
459 }
460 result
461}
462
463#[derive(Debug, Clone)]
464pub struct MemberCall {
465 pub function: FunctionRef,
466 pub arguments: Vec<ArgumentExpression>,
467}
468
469#[derive(Debug, Clone)]
470pub struct ArrayItem {
471 pub item_type: Rc<TypeRef>,
472 pub int_expression: Expression,
473 pub array_expression: Expression,
474 pub array_type: Rc<TypeRef>,
475}
476
477pub type ArrayItemRef = Rc<ArrayItem>;
478
479#[derive(Debug, Clone)]
480pub enum PrecisionType {
481 Float,
482 String,
483}
484
485#[derive(Debug, Clone)]
486pub enum FormatSpecifierKind {
487 LowerHex, UpperHex, Binary, Float, Precision(u32, Node, PrecisionType), }
493
494#[derive(Debug, Clone)]
495pub struct FormatSpecifier {
496 pub node: Node,
497 pub kind: FormatSpecifierKind,
498}
499
500pub type FunctionRef = Rc<Function>;
501
502#[derive(Debug, Eq, Clone, PartialEq)]
503pub enum Function {
504 Internal(InternalFunctionDefinitionRef),
505 External(ExternalFunctionDefinitionRef),
506 Intrinsic(IntrinsicFunctionDefinitionRef),
507}
508
509impl Function {
510 #[must_use]
511 pub fn name(&self) -> String {
512 match self {
513 Self::Internal(x) => x.assigned_name.clone(),
514 Self::External(y) => y.assigned_name.clone(),
515 Self::Intrinsic(i) => i.name.clone(),
516 }
517 }
518
519 #[must_use]
520 pub fn symbol_id(&self) -> TopLevelSymbolId {
521 match self {
522 Self::Internal(x) => x.symbol_id,
523 Self::External(y) => TopLevelSymbolId::new_illegal(),
524 Self::Intrinsic(i) => TopLevelSymbolId::new_illegal(),
525 }
526 }
527
528 #[must_use]
529 pub fn maybe_node(&self) -> Option<&Node> {
530 match self {
531 Self::Internal(x) => Some(&x.name.0),
532 Self::External(y) => Some(&y.name),
533 Self::Intrinsic(_i) => None,
534 }
535 }
536
537 #[must_use]
538 pub fn node(&self) -> Node {
539 match self {
540 Self::Internal(x) => x.name.0.clone(),
541 Self::External(_y) => Node::new_unknown(),
542 Self::Intrinsic(_i) => Node::new_unknown(),
543 }
544 }
545
546 #[must_use]
547 pub fn signature(&self) -> &Signature {
548 match self {
549 Self::Internal(internal) => &internal.signature,
550 Self::External(external) => &external.signature,
551 Self::Intrinsic(i) => &i.signature,
552 }
553 }
554}
555
556#[derive(Debug, Clone)]
557pub struct BooleanExpression {
558 #[allow(unused)]
559 pub expression: Box<Expression>,
560}
561
562#[derive(Debug, Clone)]
564pub struct Match {
565 pub arms: Vec<MatchArm>,
566 pub expression: Box<Expression>,
567}
568
569impl Match {
570 #[must_use]
571 pub fn contains_wildcard(&self) -> bool {
572 for arm in &self.arms {
573 if let Pattern::Wildcard(_) = arm.pattern {
574 return true;
575 }
576 }
577 false
578 }
579}
580
581#[derive(Debug, Clone)]
582pub struct MatchArm {
583 #[allow(unused)]
584 pub pattern: Pattern,
585 pub expression: Box<Expression>,
586 pub expression_type: TypeRef,
587}
588
589#[derive(Debug, Clone)]
590pub enum Pattern {
591 Normal(NormalPattern, Option<BooleanExpression>),
592 Wildcard(Node),
593}
594
595#[derive(Debug, Clone)]
596pub enum NormalPattern {
597 PatternList(Vec<PatternElement>),
598 EnumPattern(EnumVariantType, Option<Vec<PatternElement>>),
599 Literal(Expression),
600}
601
602#[derive(Debug, Clone)]
603pub enum PatternElement {
604 Variable(VariableRef),
605 VariableWithFieldIndex(VariableRef, usize),
606 Wildcard(Node),
607}
608
609#[derive(Debug, Clone)]
610pub struct Iterable {
611 pub key_type: Option<TypeRef>, pub value_type: TypeRef,
613
614 pub resolved_expression: Box<Expression>,
615}
616
617#[derive(Debug, Clone)]
618pub struct AnonymousStructLiteral {
619 pub source_order_expressions: Vec<(usize, Option<Node>, Expression)>,
620 pub struct_like_type: TypeRef,
621}
622
623#[derive(Debug, Clone, Eq, PartialEq)]
624pub enum CompoundOperatorKind {
625 Add,
626 Sub,
627 Mul,
628 Div,
629 Modulo,
630}
631
632#[derive(Debug, Clone)]
633pub struct CompoundOperator {
634 pub node: Node,
635 pub kind: CompoundOperatorKind,
636}
637
638#[derive(Debug, Clone)]
639pub struct VariableCompoundAssignment {
640 pub variable_ref: VariableRef, pub expression: Box<Expression>,
642 pub compound_operator: CompoundOperator,
643}
644
645#[derive(Debug, Clone)]
646pub struct Guard {
647 pub condition: Option<BooleanExpression>,
648 pub result: Expression,
649}
650
651#[derive(Debug, Clone)]
652pub struct Postfix {
653 pub node: Node,
654 pub ty: TypeRef,
655 pub kind: PostfixKind,
656}
657
658#[derive(Debug, Clone)]
659pub struct SliceViewType {
660 pub element: TypeRef,
661}
662
663#[derive(Debug, Clone)]
664pub struct VecType {
665 pub element: TypeRef,
666}
667
668#[derive(Debug, Clone)]
669pub struct GridType {
670 pub element: TypeRef,
671}
672
673#[derive(Debug, Clone)]
674pub struct SparseType {
675 pub element: TypeRef,
676}
677
678#[derive(Debug, Clone)]
679pub struct MapType {
680 pub key: TypeRef,
681 pub value: TypeRef,
682}
683
684#[derive(Debug, Clone)]
685pub enum PostfixKind {
686 StructField(TypeRef, usize),
687 MemberCall(FunctionRef, Vec<ArgumentExpression>),
688 OptionalChainingOperator, VecSubscript(VecType, Expression),
691 VecSubscriptRange(VecType, Expression),
692 SparseSubscript(SparseType, Expression),
693 MapSubscript(MapType, Expression),
694 GridSubscript(GridType, Expression, Expression),
695}
696
697#[derive(Debug, Clone)]
698pub enum LocationAccessKind {
699 FieldIndex(AnonymousStructType, usize),
700 SliceViewSubscript(SliceViewType, Expression),
701 MapSubscriptCreateIfNeeded(MapType, Expression),
702 MapSubscriptMustExist(MapType, Expression),
703 SparseSubscript(SparseType, Expression),
704 GridSubscript(GridType, Expression, Expression),
705}
706
707#[derive(Debug, Clone)]
708pub struct LocationAccess {
709 pub node: Node,
710 pub ty: TypeRef,
711 pub kind: LocationAccessKind,
712}
713
714#[derive(Debug, Clone)]
715pub struct SingleLocationExpression {
716 pub kind: MutableReferenceKind,
717 pub node: Node,
718 pub ty: TypeRef,
719
720 pub starting_variable: VariableRef,
721 pub access_chain: Vec<LocationAccess>,
722}
723
724#[derive(Debug, Clone)]
725pub struct TargetAssignmentLocation(pub SingleLocationExpression);
726
727#[derive(Debug, Clone)]
728pub enum MutableReferenceKind {
729 MutVariableRef,
730 MutStructFieldRef(AnonymousStructType, usize),
731}
732
733#[derive(Debug, Clone)]
734pub enum ArgumentExpression {
735 Expression(Expression),
736 BorrowMutableReference(SingleLocationExpression),
737}
738
739impl ArgumentExpression {
740 #[must_use]
741 pub fn ty(&self) -> TypeRef {
742 match self {
743 Self::Expression(expr) => expr.ty.clone(),
744 Self::BorrowMutableReference(location) => location.ty.clone(),
745 }
746 }
747
748 pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
749 match self {
750 Self::Expression(expr) => Ok(expr),
751 Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
752 }
753 }
754
755 pub const fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
756 match &self {
757 Self::Expression(expr) => Ok(expr),
758 Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
759 }
760 }
761
762 #[must_use]
763 pub const fn is_mutable_reference(&self) -> bool {
764 matches!(self, Self::BorrowMutableReference(_))
765 }
766
767 #[must_use]
768 pub const fn node(&self) -> &Node {
769 match &self {
770 Self::Expression(expr) => &expr.node,
771 Self::BorrowMutableReference(loc) => &loc.node,
772 }
773 }
774}
775
776#[derive(Clone)]
777pub struct Expression {
778 pub ty: TypeRef,
779 pub node: Node,
780 pub kind: ExpressionKind,
781}
782
783impl Expression {
784 #[must_use]
785 pub fn debug_last_expression(&self) -> &Self {
786 match &self.kind {
787 ExpressionKind::ConstantAccess(a) => a.expr.debug_last_expression(),
788 ExpressionKind::BinaryOp(binary) => binary.right.debug_last_expression(),
789 ExpressionKind::UnaryOp(a) => a.left.debug_last_expression(),
790 ExpressionKind::ForLoop(_, _, a) => a.debug_last_expression(),
791 ExpressionKind::WhileLoop(_, a) => a.debug_last_expression(),
792 ExpressionKind::Block(block) => block.last().unwrap_or(self),
793 ExpressionKind::Match(a) => a.arms.last().unwrap().expression.debug_last_expression(),
794 ExpressionKind::Guard(g) => g.last().unwrap().result.debug_last_expression(),
795 ExpressionKind::If(_, a, _) => a.debug_last_expression(),
796 ExpressionKind::When(_, b, _a) => b,
797 ExpressionKind::TupleDestructuring(_, _, x) => x,
798 ExpressionKind::Lambda(_, a) => a.debug_last_expression(),
799 _ => self,
800 }
801 }
802}
803
804impl Debug for Expression {
805 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
806 write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
807 }
808}
809
810#[derive(Debug, Clone)]
811pub struct WhenBinding {
812 pub variable: VariableRef,
813 pub expr: Expression,
814}
815
816impl WhenBinding {
817 #[must_use]
818 pub const fn has_expression(&self) -> bool {
819 !matches!(self.expr.kind, ExpressionKind::VariableAccess(_))
820 }
821}
822
823#[derive(Debug, Clone)]
824pub enum StartOfChainKind {
825 Expression(Box<Expression>),
826 Variable(VariableRef),
827}
828
829#[derive(Debug, Clone)]
830pub struct StartOfChain {
831 pub kind: StartOfChainKind,
832 pub node: Node,
833}
834
835impl StartOfChain {}
836
837impl StartOfChainKind {
838 #[must_use]
839 pub fn ty(&self) -> TypeRef {
840 match self {
841 Self::Expression(expr) => expr.ty.clone(),
842 Self::Variable(var) => var.resolved_type.clone(),
843 }
844 }
845
846 #[must_use]
847 pub fn is_mutable(&self) -> bool {
848 match self {
849 Self::Expression(_call) => {
850 false
852 }
853 Self::Variable(var) => var.is_mutable(),
854 }
855 }
856}
857
858#[derive(Debug, Clone)]
859pub enum ExpressionKind {
860 ConstantAccess(ConstantRef),
862 VariableAccess(VariableRef),
863
864 BinaryOp(BinaryOperator),
868 UnaryOp(UnaryOperator),
869 PostfixChain(StartOfChain, Vec<Postfix>),
870
871 CoerceOptionToBool(Box<Expression>),
874 CoerceIntToChar(Box<Expression>),
875 CoerceIntToByte(Box<Expression>),
876 CoerceToAny(Box<Expression>),
877
878 IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpression>),
880 InternalCall(InternalFunctionDefinitionRef, Vec<ArgumentExpression>),
881 HostCall(ExternalFunctionDefinitionRef, Vec<ArgumentExpression>),
882
883 VariableDefinition(VariableRef, Box<Expression>), VariableDefinitionLValue(VariableRef, SingleLocationExpression), VariableReassignment(VariableRef, Box<Expression>),
887
888 Assignment(Box<TargetAssignmentLocation>, Box<Expression>),
889 CompoundAssignment(
890 TargetAssignmentLocation,
891 CompoundOperatorKind,
892 Box<Expression>,
893 ),
894
895 AnonymousStructLiteral(AnonymousStructLiteral),
896 NamedStructLiteral(Box<Expression>),
897
898 FloatLiteral(Fp),
899 NoneLiteral,
900 IntLiteral(i32),
901 ByteLiteral(u8),
902 StringLiteral(String),
903 BoolLiteral(bool),
904 EnumVariantLiteral(EnumVariantType, EnumLiteralExpressions), TupleLiteral(Vec<Expression>),
906
907 InitializerList(TypeRef, Vec<Expression>),
908 InitializerPairList(TypeRef, Vec<(Expression, Expression)>),
909
910 Option(Option<Box<Expression>>), ForLoop(ForPattern, Iterable, Box<Expression>),
914 WhileLoop(BooleanExpression, Box<Expression>),
915
916 Block(Vec<Expression>),
917
918 Match(Match),
920 Guard(Vec<Guard>),
921 If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
922 When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
923
924 TupleDestructuring(Vec<VariableRef>, TypeRef, Box<Expression>),
925
926 Lambda(Vec<VariableRef>, Box<Expression>),
927 BorrowMutRef(Box<SingleLocationExpression>),
928 Error(ErrorKind),
929}
930
931#[derive(Debug, Clone)]
932pub struct StringConst(pub Node);
933
934#[derive(Debug, Clone)]
935pub struct ArrayInstantiation {
936 pub expressions: Vec<Expression>,
937 pub item_type: TypeRef,
938 pub array_type: TypeRef,
939 pub array_type_ref: TypeRef,
940}
941
942#[derive(Debug, Clone)]
943pub enum ForPattern {
944 Single(VariableRef),
945 Pair(VariableRef, VariableRef),
946}
947
948impl ForPattern {
949 #[must_use]
950 pub fn is_mutable(&self) -> bool {
951 match self {
952 Self::Single(variable) => variable.is_mutable(),
953 Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
954 }
955 }
956}
957
958impl Display for ForPattern {
959 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
960 write!(f, "resolved_for_pattern")
961 }
962}
963
964#[derive(Debug, Eq, PartialEq)]
965pub struct ModulePathItem(pub Node);
966
967#[derive(Debug, Clone, Eq, PartialEq)]
968pub struct LocalTypeIdentifier(pub Node);
969
970#[derive(Debug, Clone)]
971pub struct Constant {
972 pub symbol_id: TopLevelSymbolId,
973 pub name: Node,
974 pub assigned_name: String,
975 pub id: ConstantId,
976 pub expr: Expression,
977 pub resolved_type: TypeRef,
978 pub function_scope_state: VariableScopes,
979}
980pub type ConstantRef = Rc<Constant>;
981
982pub type OptionTypeRef = Rc<OptionType>;
983
984#[derive(Debug, Clone)]
985pub struct OptionType {
986 pub item_type: TypeRef,
987}
988
989#[derive(Debug, Clone)]
1006pub struct ImplMember {}
1007
1008#[derive(Debug, Clone)]
1009pub enum UseItem {
1010 Identifier(Node),
1011 TypeIdentifier(Node),
1012}
1013
1014#[derive(Debug, Clone)]
1015pub struct Use {
1016 pub path: Vec<Node>,
1017 pub items: Vec<UseItem>,
1018}
1019
1020#[derive(Debug, Clone)]
1021pub struct ImplFunctions {
1022 pub functions: SeqMap<String, FunctionRef>,
1023}
1024
1025impl Default for ImplFunctions {
1026 fn default() -> Self {
1027 Self::new()
1028 }
1029}
1030
1031impl ImplFunctions {
1032 #[must_use]
1033 pub fn new() -> Self {
1034 Self {
1035 functions: SeqMap::default(),
1036 }
1037 }
1038}
1039
1040#[derive(Debug, Clone)]
1041pub struct AssociatedImpls {
1042 pub functions: SeqMap<TypeRef, ImplFunctions>,
1043}
1044
1045impl AssociatedImpls {}
1046
1047impl AssociatedImpls {}
1048
1049impl AssociatedImpls {}
1050
1051impl Default for AssociatedImpls {
1052 fn default() -> Self {
1053 Self::new()
1054 }
1055}
1056
1057impl AssociatedImpls {
1058 #[must_use]
1059 pub fn new() -> Self {
1060 Self {
1061 functions: SeqMap::default(),
1062 }
1063 }
1064}
1065
1066impl AssociatedImpls {
1067 pub fn prepare(&mut self, ty: &TypeRef) {
1068 self.functions
1069 .insert(ty.clone(), ImplFunctions::new())
1070 .unwrap_or_else(|_| panic!("should work {ty:?}"));
1071 }
1072
1073 #[must_use]
1074 pub fn is_prepared(&self, ty: &TypeRef) -> bool {
1075 self.functions.contains_key(ty)
1076 }
1077 #[must_use]
1078 pub fn get_member_function(&self, ty: &TypeRef, function_name: &str) -> Option<&FunctionRef> {
1079 let maybe_found_impl = self.functions.get(ty);
1080 if let Some(found_impl) = maybe_found_impl
1081 && let Some(func) = found_impl.functions.get(&function_name.to_string())
1082 {
1083 return Some(func);
1084 }
1085 None
1086 }
1087
1088 fn has_internal_member_function(&self, ty: &TypeRef, function_name: &str) -> bool {
1089 let maybe_found_impl = self.functions.get(ty);
1090 if let Some(found_impl) = maybe_found_impl
1091 && let Some(_func) = found_impl.functions.get(&function_name.to_string())
1092 {
1093 return true;
1094 }
1095 false
1096 }
1097
1098 #[must_use]
1099 pub fn api_get_external_function(
1100 &self,
1101 ty: &TypeRef,
1102 function_name: &str,
1103 ) -> Option<&ExternalFunctionDefinitionRef> {
1104 if let Some(found) = self.get_member_function(ty, function_name)
1105 && let Function::External(ext_fn) = &**found
1106 {
1107 return Some(ext_fn);
1108 }
1109 None
1110 }
1111
1112 #[must_use]
1113 pub fn get_internal_member_function(
1114 &self,
1115 ty: &TypeRef,
1116 function_name: &str,
1117 ) -> Option<&InternalFunctionDefinitionRef> {
1118 if let Some(found) = self.get_member_function(ty, function_name)
1119 && let Function::Internal(int_fn) = &**found
1120 {
1121 return Some(int_fn);
1122 }
1123 None
1124 }
1125
1126 pub fn remove_internal_function_if_exists(
1127 &mut self,
1128 ty: &TypeRef,
1129 function_name: &str,
1130 ) -> bool {
1131 if self.has_internal_member_function(ty, function_name) {
1132 let functions = self.functions.get_mut(ty).unwrap();
1133
1134 functions.functions.remove(&function_name.to_string());
1135 true
1136 } else {
1137 false
1138 }
1139 }
1140
1141 pub fn add_member_function(
1142 &mut self,
1143 ty: &TypeRef,
1144 name: &str,
1145 func: FunctionRef,
1146 ) -> Result<(), SemanticError> {
1147 let maybe_found_impl = self.functions.get_mut(ty);
1148
1149 if let Some(found_impl) = maybe_found_impl {
1150 found_impl
1151 .functions
1152 .insert(name.to_string(), func)
1153 .unwrap_or_else(|_| panic!("already had key {name}"));
1154 Ok(())
1155 } else {
1156 error!(%ty, ?name, "wasn't prepared");
1157 Err(SemanticError::UnknownImplOnType)
1158 }
1159 }
1160
1161 pub fn add_internal_function(
1162 &mut self,
1163 ty: &TypeRef,
1164 func: InternalFunctionDefinition,
1165 ) -> Result<(), SemanticError> {
1166 self.add_member_function(
1168 ty,
1169 &func.assigned_name.clone(),
1170 Function::Internal(func.into()).into(),
1171 )
1172 }
1173
1174 pub fn add_external_member_function(
1175 &mut self,
1176 ty: &TypeRef,
1177 func: ExternalFunctionDefinition,
1178 ) -> Result<(), SemanticError> {
1179 self.add_member_function(
1180 ty,
1181 &func.assigned_name.clone(),
1182 Function::External(func.into()).into(),
1183 )
1184 }
1185
1186 pub fn add_external_struct_member_function(
1187 &mut self,
1188 named_struct_type: TypeRef,
1189 func: Function,
1190 ) -> Result<(), SemanticError> {
1191 self.add_member_function(&named_struct_type, &func.name(), func.into())
1192 }
1193
1194 pub fn add_external_struct_member_function_external(
1195 &mut self,
1196 named_struct_type: TypeRef,
1197 func: ExternalFunctionDefinition,
1198 ) -> Result<(), SemanticError> {
1199 self.add_member_function(
1200 &named_struct_type,
1201 &func.assigned_name.clone(),
1202 Function::External(func.into()).into(),
1203 )
1204 }
1205
1206 pub fn add_external_struct_member_function_external_ref(
1207 &mut self,
1208 named_struct_type: TypeRef,
1209 func: ExternalFunctionDefinitionRef,
1210 ) -> Result<(), SemanticError> {
1211 self.add_member_function(
1212 &named_struct_type,
1213 &func.assigned_name.clone(),
1214 Function::External(func).into(),
1215 )
1216 }
1217}
1218
1219#[derive(Debug, Clone)]
1221pub struct ProgramState {
1222 pub internal_function_id_allocator: InternalFunctionIdAllocator,
1223 pub symbol_id_allocator: SymbolIdAllocator,
1224 pub symbols: Symbols,
1225 pub refs: ReferenceTracker,
1226 pub constants_in_dependency_order: Vec<ConstantRef>,
1230 pub associated_impls: AssociatedImpls,
1231 pub types: TypeCache,
1232 pub errors: Vec<Error>,
1233 pub hints: Vec<Error>,
1234 pub infos: Vec<Error>,
1235}
1236
1237impl ProgramState {
1238 #[must_use]
1239 pub const fn errors(&self) -> &Vec<Error> {
1240 &self.errors
1241 }
1242}
1243
1244impl Default for ProgramState {
1245 fn default() -> Self {
1246 Self::new()
1247 }
1248}
1249
1250#[derive(Debug, Clone)]
1251pub struct InternalFunctionIdAllocator {
1252 pub internal_function_number: InternalFunctionId,
1253}
1254
1255impl Default for InternalFunctionIdAllocator {
1256 fn default() -> Self {
1257 Self::new()
1258 }
1259}
1260
1261impl InternalFunctionIdAllocator {
1262 #[must_use]
1263 pub const fn new() -> Self {
1264 Self {
1265 internal_function_number: 0,
1266 }
1267 }
1268 pub const fn alloc(&mut self) -> InternalFunctionId {
1269 self.internal_function_number += 1;
1270 self.internal_function_number
1271 }
1272}
1273
1274impl ProgramState {
1275 #[must_use]
1276 pub fn new() -> Self {
1277 Self {
1278 symbol_id_allocator: SymbolIdAllocator::new(),
1279 symbols: Symbols::new(),
1280 refs: ReferenceTracker::new(),
1281 internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1282 constants_in_dependency_order: Vec::new(),
1283 associated_impls: AssociatedImpls::new(),
1284 types: TypeCache::new(),
1285 errors: vec![],
1286 hints: vec![],
1287 infos: vec![],
1288 }
1289 }
1290 pub const fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1291 self.internal_function_id_allocator.alloc()
1292 }
1293}
1294
1295#[derive(Clone)]
1296pub enum EnumLiteralExpressions {
1297 Nothing,
1298 Tuple(Vec<Expression>),
1299 Struct(Vec<(usize, Option<Node>, Expression)>),
1300}
1301
1302impl Debug for EnumLiteralExpressions {
1303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1304 match self {
1305 Self::Nothing => Ok(()),
1306 Self::Tuple(x) => write!(f, "{x:?}"),
1307 Self::Struct(s) => write!(f, "{s:?}"),
1308 }
1309 }
1310}