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 MaterializedExpression(Expression),
737 BorrowMutableReference(SingleLocationExpression),
738}
739
740impl ArgumentExpression {
741 #[must_use]
742 pub fn ty(&self) -> TypeRef {
743 match self {
744 Self::Expression(expr) => expr.ty.clone(),
745 Self::MaterializedExpression(expr) => expr.ty.clone(),
746 Self::BorrowMutableReference(location) => location.ty.clone(),
747 }
748 }
749
750 pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
751 match self {
752 Self::Expression(expr) => Ok(expr),
753 Self::MaterializedExpression(expr) => Ok(expr),
754 Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
755 }
756 }
757
758 pub const fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
759 match &self {
760 Self::Expression(expr) => Ok(expr),
761 Self::MaterializedExpression(expr) => Ok(expr),
762 Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
763 }
764 }
765
766 #[must_use]
767 pub const fn is_mutable_reference(&self) -> bool {
768 matches!(self, Self::BorrowMutableReference(_))
769 }
770
771 #[must_use]
772 pub const fn node(&self) -> &Node {
773 match &self {
774 Self::Expression(expr) => &expr.node,
775 Self::MaterializedExpression(expr) => &expr.node,
776 Self::BorrowMutableReference(loc) => &loc.node,
777 }
778 }
779}
780
781#[derive(Clone)]
782pub struct Expression {
783 pub ty: TypeRef,
784 pub node: Node,
785 pub kind: ExpressionKind,
786}
787
788impl Expression {
789 #[must_use]
790 pub fn debug_last_expression(&self) -> &Self {
791 match &self.kind {
792 ExpressionKind::ConstantAccess(a) => a.expr.debug_last_expression(),
793 ExpressionKind::BinaryOp(binary) => binary.right.debug_last_expression(),
794 ExpressionKind::UnaryOp(a) => a.left.debug_last_expression(),
795 ExpressionKind::ForLoop(_, _, a) => a.debug_last_expression(),
796 ExpressionKind::WhileLoop(_, a) => a.debug_last_expression(),
797 ExpressionKind::Block(block) => block.last().unwrap_or(self),
798 ExpressionKind::Match(a) => a.arms.last().unwrap().expression.debug_last_expression(),
799 ExpressionKind::Guard(g) => g.last().unwrap().result.debug_last_expression(),
800 ExpressionKind::If(_, a, _) => a.debug_last_expression(),
801 ExpressionKind::When(_, b, _a) => b,
802 ExpressionKind::TupleDestructuring(_, _, x) => x,
803 ExpressionKind::Lambda(_, a) => a.debug_last_expression(),
804 _ => self,
805 }
806 }
807}
808
809impl Debug for Expression {
810 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
811 write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
812 }
813}
814
815#[derive(Debug, Clone)]
816pub struct WhenBinding {
817 pub variable: VariableRef,
818 pub expr: Expression,
819}
820
821impl WhenBinding {
822 #[must_use]
823 pub const fn has_expression(&self) -> bool {
824 !matches!(self.expr.kind, ExpressionKind::VariableAccess(_))
825 }
826}
827
828#[derive(Debug, Clone)]
829pub enum StartOfChainKind {
830 Expression(Box<Expression>),
831 Variable(VariableRef),
832}
833
834#[derive(Debug, Clone)]
835pub struct StartOfChain {
836 pub kind: StartOfChainKind,
837 pub node: Node,
838}
839
840impl StartOfChain {}
841
842impl StartOfChainKind {
843 #[must_use]
844 pub fn ty(&self) -> TypeRef {
845 match self {
846 Self::Expression(expr) => expr.ty.clone(),
847 Self::Variable(var) => var.resolved_type.clone(),
848 }
849 }
850
851 #[must_use]
852 pub fn is_mutable(&self) -> bool {
853 match self {
854 Self::Expression(_call) => {
855 false
857 }
858 Self::Variable(var) => var.is_mutable(),
859 }
860 }
861}
862
863#[derive(Debug, Clone)]
864pub enum ExpressionKind {
865 ConstantAccess(ConstantRef),
867 VariableAccess(VariableRef),
868
869 BinaryOp(BinaryOperator),
873 UnaryOp(UnaryOperator),
874 PostfixChain(StartOfChain, Vec<Postfix>),
875
876 CoerceOptionToBool(Box<Expression>),
879 CoerceIntToChar(Box<Expression>),
880 CoerceIntToByte(Box<Expression>),
881 CoerceToAny(Box<Expression>),
882
883 IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpression>),
885 InternalCall(InternalFunctionDefinitionRef, Vec<ArgumentExpression>),
886 HostCall(ExternalFunctionDefinitionRef, Vec<ArgumentExpression>),
887
888 VariableDefinition(VariableRef, Box<Expression>), VariableDefinitionLValue(VariableRef, SingleLocationExpression), VariableReassignment(VariableRef, Box<Expression>),
892
893 Assignment(Box<TargetAssignmentLocation>, Box<Expression>),
894 CompoundAssignment(
895 TargetAssignmentLocation,
896 CompoundOperatorKind,
897 Box<Expression>,
898 ),
899
900 AnonymousStructLiteral(AnonymousStructLiteral),
901 NamedStructLiteral(Box<Expression>),
902
903 FloatLiteral(Fp),
904 NoneLiteral,
905 IntLiteral(i32),
906 ByteLiteral(u8),
907 StringLiteral(String),
908 BoolLiteral(bool),
909 EnumVariantLiteral(EnumVariantType, EnumLiteralExpressions), TupleLiteral(Vec<Expression>),
911
912 InitializerList(TypeRef, Vec<Expression>),
913 InitializerPairList(TypeRef, Vec<(Expression, Expression)>),
914
915 Option(Option<Box<Expression>>), ForLoop(ForPattern, Iterable, Box<Expression>),
919 WhileLoop(BooleanExpression, Box<Expression>),
920
921 Block(Vec<Expression>),
922
923 Match(Match),
925 Guard(Vec<Guard>),
926 If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
927 When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
928
929 TupleDestructuring(Vec<VariableRef>, TypeRef, Box<Expression>),
930
931 Lambda(Vec<VariableRef>, Box<Expression>),
932 BorrowMutRef(Box<SingleLocationExpression>),
933 Error(ErrorKind),
934}
935
936impl Display for ExpressionKind {
937 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
938 match self {
939 Self::ConstantAccess(_) => {
940 write!(f, "constant")
941 }
942 Self::VariableAccess(_) => {
943 write!(f, "varaccess")
944 }
945 Self::BinaryOp(_) => {
946 write!(f, "binaryop")
947 }
948 Self::UnaryOp(_) => {
949 write!(f, "unaryop")
950 }
951 Self::PostfixChain(_, _) => {
952 write!(f, "prefix")
953 }
954 Self::CoerceOptionToBool(_) => {
955 write!(f, "byte")
956 }
957 Self::CoerceIntToChar(_) => {
958 write!(f, "byte")
959 }
960 Self::CoerceIntToByte(_) => {
961 write!(f, "byte")
962 }
963 Self::CoerceToAny(_) => {
964 write!(f, "byte")
965 }
966 Self::IntrinsicCallEx(_, _) => {
967 write!(f, "byte")
968 }
969 Self::InternalCall(_, _) => {
970 write!(f, "byte")
971 }
972 Self::HostCall(_, _) => {
973 write!(f, "byte")
974 }
975 Self::VariableDefinition(a, b) => {
976 write!(f, "vardef {a:?} {}", b.kind)
977 }
978 Self::VariableDefinitionLValue(a, b) => {
979 write!(f, "vardefl {a:?}")
980 }
981 Self::VariableReassignment(_, _) => {
982 write!(f, "var reassignment")
983 }
984 Self::Assignment(_, _) => {
985 write!(f, "byte")
986 }
987 Self::CompoundAssignment(_, _, _) => {
988 write!(f, "byte")
989 }
990 Self::AnonymousStructLiteral(_) => {
991 write!(f, "byte")
992 }
993 Self::NamedStructLiteral(_) => {
994 write!(f, "byte")
995 }
996 Self::FloatLiteral(_) => {
997 write!(f, "byte")
998 }
999 Self::NoneLiteral => {
1000 write!(f, "byte")
1001 }
1002 Self::IntLiteral(_) => {
1003 write!(f, "byte")
1004 }
1005 Self::ByteLiteral(_) => {
1006 write!(f, "byte")
1007 }
1008 Self::StringLiteral(_) => {
1009 write!(f, "byte")
1010 }
1011 Self::BoolLiteral(_) => {
1012 write!(f, "byte")
1013 }
1014 Self::EnumVariantLiteral(_, _) => {
1015 write!(f, "byte")
1016 }
1017 Self::TupleLiteral(_) => {
1018 write!(f, "byte")
1019 }
1020 Self::InitializerList(_, _) => {
1021 write!(f, "byte")
1022 }
1023 Self::InitializerPairList(_, _) => {
1024 write!(f, "byte")
1025 }
1026 Self::Option(_) => {
1027 write!(f, "byte")
1028 }
1029 Self::ForLoop(_, _, _) => {
1030 write!(f, "byte")
1031 }
1032 Self::WhileLoop(_, _) => {
1033 write!(f, "byte")
1034 }
1035 Self::Block(_) => {
1036 write!(f, "byte")
1037 }
1038 Self::Match(_) => {
1039 write!(f, "byte")
1040 }
1041 Self::Guard(_) => {
1042 write!(f, "byte")
1043 }
1044 Self::If(_, _, _) => {
1045 write!(f, "byte")
1046 }
1047 Self::When(_, _, _) => {
1048 write!(f, "byte")
1049 }
1050 Self::TupleDestructuring(_, _, _) => {
1051 write!(f, "byte")
1052 }
1053 Self::Lambda(_, _) => {
1054 write!(f, "byte")
1055 }
1056 Self::BorrowMutRef(_) => {
1057 write!(f, "byte")
1058 }
1059 Self::Error(_) => {
1060 write!(f, "byte")
1061 }
1062 }
1063 }
1064}
1065
1066#[derive(Debug, Clone)]
1067pub struct StringConst(pub Node);
1068
1069#[derive(Debug, Clone)]
1070pub struct ArrayInstantiation {
1071 pub expressions: Vec<Expression>,
1072 pub item_type: TypeRef,
1073 pub array_type: TypeRef,
1074 pub array_type_ref: TypeRef,
1075}
1076
1077#[derive(Debug, Clone)]
1078pub enum ForPattern {
1079 Single(VariableRef),
1080 Pair(VariableRef, VariableRef),
1081}
1082
1083impl ForPattern {
1084 #[must_use]
1085 pub fn is_mutable(&self) -> bool {
1086 match self {
1087 Self::Single(variable) => variable.is_mutable(),
1088 Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
1089 }
1090 }
1091}
1092
1093impl Display for ForPattern {
1094 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1095 write!(f, "resolved_for_pattern")
1096 }
1097}
1098
1099#[derive(Debug, Eq, PartialEq)]
1100pub struct ModulePathItem(pub Node);
1101
1102#[derive(Debug, Clone, Eq, PartialEq)]
1103pub struct LocalTypeIdentifier(pub Node);
1104
1105#[derive(Debug, Clone)]
1106pub struct Constant {
1107 pub symbol_id: TopLevelSymbolId,
1108 pub name: Node,
1109 pub assigned_name: String,
1110 pub id: ConstantId,
1111 pub expr: Expression,
1112 pub resolved_type: TypeRef,
1113 pub function_scope_state: VariableScopes,
1114}
1115pub type ConstantRef = Rc<Constant>;
1116
1117pub type OptionTypeRef = Rc<OptionType>;
1118
1119#[derive(Debug, Clone)]
1120pub struct OptionType {
1121 pub item_type: TypeRef,
1122}
1123
1124#[derive(Debug, Clone)]
1141pub struct ImplMember {}
1142
1143#[derive(Debug, Clone)]
1144pub enum UseItem {
1145 Identifier(Node),
1146 TypeIdentifier(Node),
1147}
1148
1149#[derive(Debug, Clone)]
1150pub struct Use {
1151 pub path: Vec<Node>,
1152 pub items: Vec<UseItem>,
1153}
1154
1155#[derive(Debug, Clone)]
1156pub struct ImplFunctions {
1157 pub functions: SeqMap<String, FunctionRef>,
1158}
1159
1160impl Default for ImplFunctions {
1161 fn default() -> Self {
1162 Self::new()
1163 }
1164}
1165
1166impl ImplFunctions {
1167 #[must_use]
1168 pub fn new() -> Self {
1169 Self {
1170 functions: SeqMap::default(),
1171 }
1172 }
1173}
1174
1175#[derive(Debug, Clone)]
1176pub struct AssociatedImpls {
1177 pub functions: SeqMap<TypeRef, ImplFunctions>,
1178}
1179
1180impl AssociatedImpls {}
1181
1182impl AssociatedImpls {}
1183
1184impl AssociatedImpls {}
1185
1186impl Default for AssociatedImpls {
1187 fn default() -> Self {
1188 Self::new()
1189 }
1190}
1191
1192impl AssociatedImpls {
1193 #[must_use]
1194 pub fn new() -> Self {
1195 Self {
1196 functions: SeqMap::default(),
1197 }
1198 }
1199}
1200
1201impl AssociatedImpls {
1202 pub fn prepare(&mut self, ty: &TypeRef) {
1203 self.functions
1204 .insert(ty.clone(), ImplFunctions::new())
1205 .unwrap_or_else(|_| panic!("should work {ty:?}"));
1206 }
1207
1208 #[must_use]
1209 pub fn is_prepared(&self, ty: &TypeRef) -> bool {
1210 self.functions.contains_key(ty)
1211 }
1212 #[must_use]
1213 pub fn get_member_function(&self, ty: &TypeRef, function_name: &str) -> Option<&FunctionRef> {
1214 let maybe_found_impl = self.functions.get(ty);
1215 if let Some(found_impl) = maybe_found_impl
1216 && let Some(func) = found_impl.functions.get(&function_name.to_string())
1217 {
1218 return Some(func);
1219 }
1220 None
1221 }
1222
1223 fn has_internal_member_function(&self, ty: &TypeRef, function_name: &str) -> bool {
1224 let maybe_found_impl = self.functions.get(ty);
1225 if let Some(found_impl) = maybe_found_impl
1226 && let Some(_func) = found_impl.functions.get(&function_name.to_string())
1227 {
1228 return true;
1229 }
1230 false
1231 }
1232
1233 #[must_use]
1234 pub fn api_get_external_function(
1235 &self,
1236 ty: &TypeRef,
1237 function_name: &str,
1238 ) -> Option<&ExternalFunctionDefinitionRef> {
1239 if let Some(found) = self.get_member_function(ty, function_name)
1240 && let Function::External(ext_fn) = &**found
1241 {
1242 return Some(ext_fn);
1243 }
1244 None
1245 }
1246
1247 #[must_use]
1248 pub fn get_internal_member_function(
1249 &self,
1250 ty: &TypeRef,
1251 function_name: &str,
1252 ) -> Option<&InternalFunctionDefinitionRef> {
1253 if let Some(found) = self.get_member_function(ty, function_name)
1254 && let Function::Internal(int_fn) = &**found
1255 {
1256 return Some(int_fn);
1257 }
1258 None
1259 }
1260
1261 pub fn remove_internal_function_if_exists(
1262 &mut self,
1263 ty: &TypeRef,
1264 function_name: &str,
1265 ) -> bool {
1266 if self.has_internal_member_function(ty, function_name) {
1267 let functions = self.functions.get_mut(ty).unwrap();
1268
1269 functions.functions.remove(&function_name.to_string());
1270 true
1271 } else {
1272 false
1273 }
1274 }
1275
1276 pub fn add_member_function(
1277 &mut self,
1278 ty: &TypeRef,
1279 name: &str,
1280 func: FunctionRef,
1281 ) -> Result<(), SemanticError> {
1282 let maybe_found_impl = self.functions.get_mut(ty);
1283
1284 if let Some(found_impl) = maybe_found_impl {
1285 found_impl
1286 .functions
1287 .insert(name.to_string(), func)
1288 .unwrap_or_else(|_| panic!("already had key {name}"));
1289 Ok(())
1290 } else {
1291 error!(%ty, ?name, "wasn't prepared");
1292 Err(SemanticError::UnknownImplOnType)
1293 }
1294 }
1295
1296 pub fn add_internal_function(
1297 &mut self,
1298 ty: &TypeRef,
1299 func: InternalFunctionDefinition,
1300 ) -> Result<(), SemanticError> {
1301 self.add_member_function(
1303 ty,
1304 &func.assigned_name.clone(),
1305 Function::Internal(func.into()).into(),
1306 )
1307 }
1308
1309 pub fn add_external_member_function(
1310 &mut self,
1311 ty: &TypeRef,
1312 func: ExternalFunctionDefinition,
1313 ) -> Result<(), SemanticError> {
1314 self.add_member_function(
1315 ty,
1316 &func.assigned_name.clone(),
1317 Function::External(func.into()).into(),
1318 )
1319 }
1320
1321 pub fn add_external_struct_member_function(
1322 &mut self,
1323 named_struct_type: TypeRef,
1324 func: Function,
1325 ) -> Result<(), SemanticError> {
1326 self.add_member_function(&named_struct_type, &func.name(), func.into())
1327 }
1328
1329 pub fn add_external_struct_member_function_external(
1330 &mut self,
1331 named_struct_type: TypeRef,
1332 func: ExternalFunctionDefinition,
1333 ) -> Result<(), SemanticError> {
1334 self.add_member_function(
1335 &named_struct_type,
1336 &func.assigned_name.clone(),
1337 Function::External(func.into()).into(),
1338 )
1339 }
1340
1341 pub fn add_external_struct_member_function_external_ref(
1342 &mut self,
1343 named_struct_type: TypeRef,
1344 func: ExternalFunctionDefinitionRef,
1345 ) -> Result<(), SemanticError> {
1346 self.add_member_function(
1347 &named_struct_type,
1348 &func.assigned_name.clone(),
1349 Function::External(func).into(),
1350 )
1351 }
1352}
1353
1354#[derive(Debug, Clone)]
1356pub struct ProgramState {
1357 pub internal_function_id_allocator: InternalFunctionIdAllocator,
1358 pub symbol_id_allocator: SymbolIdAllocator,
1359 pub symbols: Symbols,
1360 pub refs: ReferenceTracker,
1361 pub constants_in_dependency_order: Vec<ConstantRef>,
1365 pub associated_impls: AssociatedImpls,
1366 pub types: TypeCache,
1367 pub errors: Vec<Error>,
1368 pub hints: Vec<Error>,
1369 pub infos: Vec<Error>,
1370}
1371
1372impl ProgramState {
1373 #[must_use]
1374 pub const fn errors(&self) -> &Vec<Error> {
1375 &self.errors
1376 }
1377}
1378
1379impl Default for ProgramState {
1380 fn default() -> Self {
1381 Self::new()
1382 }
1383}
1384
1385#[derive(Debug, Clone)]
1386pub struct InternalFunctionIdAllocator {
1387 pub internal_function_number: InternalFunctionId,
1388}
1389
1390impl Default for InternalFunctionIdAllocator {
1391 fn default() -> Self {
1392 Self::new()
1393 }
1394}
1395
1396impl InternalFunctionIdAllocator {
1397 #[must_use]
1398 pub const fn new() -> Self {
1399 Self {
1400 internal_function_number: 0,
1401 }
1402 }
1403 pub const fn alloc(&mut self) -> InternalFunctionId {
1404 self.internal_function_number += 1;
1405 self.internal_function_number
1406 }
1407}
1408
1409impl ProgramState {
1410 #[must_use]
1411 pub fn new() -> Self {
1412 Self {
1413 symbol_id_allocator: SymbolIdAllocator::new(),
1414 symbols: Symbols::new(),
1415 refs: ReferenceTracker::new(),
1416 internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1417 constants_in_dependency_order: Vec::new(),
1418 associated_impls: AssociatedImpls::new(),
1419 types: TypeCache::new(),
1420 errors: vec![],
1421 hints: vec![],
1422 infos: vec![],
1423 }
1424 }
1425 pub const fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1426 self.internal_function_id_allocator.alloc()
1427 }
1428}
1429
1430#[derive(Clone)]
1431pub enum EnumLiteralExpressions {
1432 Nothing,
1433 Tuple(Vec<Expression>),
1434 Struct(Vec<(usize, Option<Node>, Expression)>),
1435}
1436
1437impl Debug for EnumLiteralExpressions {
1438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1439 match self {
1440 Self::Nothing => Ok(()),
1441 Self::Tuple(x) => write!(f, "{x:?}"),
1442 Self::Struct(s) => write!(f, "{s:?}"),
1443 }
1444 }
1445}