1pub mod access;
6pub mod call;
7pub mod constant;
8pub mod def;
9pub mod err;
10pub mod internal;
11pub mod literal;
12pub mod operator;
13pub mod pattern;
14pub mod prelude;
15mod structure;
16pub mod types;
17pub mod variable;
18use crate::err::{Error, ErrorKind};
19use seq_map::SeqMap;
20use std::mem::take;
21use std::num::{ParseFloatError, ParseIntError};
22use std::rc::Rc;
23use swamp_script_semantic::modules::ModuleRef;
24use swamp_script_semantic::prelude::*;
25use swamp_script_semantic::symtbl::{FuncDef, Symbol, SymbolTable, SymbolTableRef};
26use swamp_script_semantic::{
27 AnonymousStructLiteral, ArgumentExpressionOrLocation, LocationAccess, LocationAccessKind,
28 MutOrImmutableExpression, NormalPattern, Postfix, PostfixKind, RangeMode,
29 SingleLocationExpression, SingleLocationExpressionKind, SingleMutLocationExpression,
30 TypeWithMut, WhenBinding, check_assignable_anonymous_struct_types, same_anon_struct_ref,
31};
32use swamp_script_source_map::SourceMap;
33use tracing::error;
34use tracing::info;
35
36#[must_use]
37pub fn convert_range_mode(range_mode: &swamp_script_ast::RangeMode) -> RangeMode {
38 match range_mode {
39 swamp_script_ast::RangeMode::Inclusive => RangeMode::Inclusive,
40 swamp_script_ast::RangeMode::Exclusive => RangeMode::Exclusive,
41 }
42}
43
44#[derive(Copy, Clone, Eq, PartialEq, Debug)]
45pub enum LocationSide {
46 Lhs,
47 Rhs,
48}
49
50#[derive(Debug)]
51pub struct AutoUseModules {
52 pub modules: Vec<SymbolTableRef>,
53}
54
55#[derive(Debug)]
56pub struct Program {
57 pub state: ProgramState,
58 pub modules: Modules,
59 pub auto_use_modules: AutoUseModules,
60}
61
62impl Default for Program {
63 fn default() -> Self {
64 Self::new()
65 }
66}
67
68impl Program {
69 #[must_use]
70 pub fn new() -> Self {
71 Self {
72 state: ProgramState::new(),
73 modules: Modules::new(),
74 auto_use_modules: AutoUseModules {
75 modules: Vec::new(),
76 },
77 }
78 }
79}
80
81#[must_use]
82pub const fn convert_span(without: &swamp_script_ast::SpanWithoutFileId, file_id: FileId) -> Span {
83 Span {
84 file_id,
85 offset: without.offset,
86 length: without.length,
87 }
88}
89
90pub const SPARSE_TYPE_ID: TypeNumber = 999;
91pub const SPARSE_ID_TYPE_ID: TypeNumber = 998;
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum TypeContextScope {
95 InsideFunction, InsideLoop, InsideBothFunctionAndLoop,
100 ArgumentOrOutsideFunction, }
102
103impl TypeContextScope {
104 #[must_use]
106 pub fn allows_return(&self) -> bool {
107 matches!(self, Self::InsideFunction | Self::InsideBothFunctionAndLoop)
108 }
109
110 #[must_use]
112 pub fn allows_break(&self) -> bool {
113 matches!(self, Self::InsideLoop | Self::InsideBothFunctionAndLoop)
114 }
115
116 #[must_use]
118 pub fn allows_continue(&self) -> bool {
119 self.allows_break() }
121
122 #[must_use]
124 pub fn enter_function(&self) -> Self {
125 match self {
126 Self::ArgumentOrOutsideFunction => Self::InsideFunction,
127 Self::InsideLoop => Self::InsideBothFunctionAndLoop,
128 _ => *self,
129 }
130 }
131
132 #[must_use]
134 pub fn enter_loop(&self) -> Self {
135 match self {
136 Self::ArgumentOrOutsideFunction => Self::InsideLoop,
137 Self::InsideFunction => Self::InsideBothFunctionAndLoop,
138 _ => *self,
139 }
140 }
141}
142
143#[derive(Debug, Clone)]
145pub struct TypeContext<'a> {
146 pub expected_type: Option<&'a Type>,
148
149 pub return_type: Option<&'a Type>,
151
152 pub scope: TypeContextScope,
153
154 pub is_in_compare_like: bool,
155}
156
157impl TypeContext<'_> {
158 pub(crate) fn allows_continue(&self) -> bool {
159 self.scope.allows_continue() && self.is_in_compare_like
160 }
161}
162
163impl TypeContext<'_> {
164 pub(crate) fn allows_return(&self) -> bool {
165 self.scope.allows_return() && self.is_in_compare_like
166 }
167}
168
169impl TypeContext<'_> {
170 pub(crate) fn allows_break(&self) -> bool {
171 self.scope.allows_break()
172 }
173}
174
175impl<'a> TypeContext<'a> {
176 #[must_use]
177 pub const fn new(
178 expected_type: Option<&'a Type>,
179 return_type: Option<&'a Type>,
180 scope: TypeContextScope,
181 ) -> Self {
182 Self {
183 expected_type,
184 return_type,
185 scope,
186 is_in_compare_like: false,
187 }
188 }
189
190 pub const fn new_argument(required_type: &'a Type) -> Self {
191 Self {
192 expected_type: Some(required_type),
193 return_type: None,
194 scope: TypeContextScope::ArgumentOrOutsideFunction,
195 is_in_compare_like: false,
196 }
197 }
198
199 #[must_use]
200 pub const fn new_unsure_argument(expected_type: Option<&'a Type>) -> Self {
201 Self {
202 expected_type,
203 return_type: None,
204 scope: TypeContextScope::ArgumentOrOutsideFunction,
205 is_in_compare_like: false,
206 }
207 }
208
209 #[must_use]
210 pub const fn new_anything_argument() -> Self {
211 Self {
212 expected_type: None,
213 return_type: None,
214 scope: TypeContextScope::ArgumentOrOutsideFunction,
215 is_in_compare_like: false,
216 }
217 }
218
219 #[must_use]
220 pub const fn new_function(required_type: &'a Type) -> Self {
221 Self {
222 expected_type: Some(required_type),
223 return_type: Some(required_type),
224 scope: TypeContextScope::InsideFunction,
225 is_in_compare_like: false,
226 }
227 }
228
229 #[must_use]
230 pub const fn with_expected_type(&self, expected_type: Option<&'a Type>) -> Self {
231 Self {
232 expected_type,
233 return_type: self.return_type,
234 scope: self.scope,
235 is_in_compare_like: self.is_in_compare_like,
236 }
237 }
238
239 pub(crate) const fn we_know_expected_type(&self, found_type: &'a Type) -> Self {
240 self.with_expected_type(Some(found_type))
241 }
242
243 #[must_use]
246 pub const fn for_return(&self) -> Self {
247 Self {
248 expected_type: Some(self.return_type.unwrap()),
249 return_type: Some(self.return_type.unwrap()),
250 scope: TypeContextScope::ArgumentOrOutsideFunction,
251 is_in_compare_like: false,
252 }
253 }
254
255 #[must_use]
256 pub fn enter_function(&self, required_type: &'a Type) -> Self {
257 Self {
258 expected_type: Some(required_type),
259 return_type: Some(required_type),
260 scope: self.scope.enter_function(),
261 is_in_compare_like: false,
262 }
263 }
264
265 #[must_use]
267 pub fn enter_loop(&self) -> Self {
268 Self {
269 expected_type: self.expected_type,
270 return_type: self.return_type,
271 scope: self.scope.enter_loop(),
272 is_in_compare_like: self.is_in_compare_like,
273 }
274 }
275
276 #[must_use]
278 pub fn enter_compare(&self) -> Self {
279 Self {
280 expected_type: self.expected_type,
281 return_type: self.return_type,
282 scope: self.scope.enter_loop(),
283 is_in_compare_like: true,
284 }
285 }
286}
287
288#[derive(Debug, Eq, PartialEq)]
289pub enum BlockScopeMode {
290 Open,
291 Closed,
292}
293
294#[derive(Debug)]
295pub struct BlockScope {
296 mode: BlockScopeMode,
297 variables: SeqMap<String, VariableRef>,
298}
299
300impl Default for BlockScope {
301 fn default() -> Self {
302 Self::new()
303 }
304}
305
306impl BlockScope {
307 #[must_use]
308 pub fn new() -> Self {
309 Self {
310 mode: BlockScopeMode::Open,
311 variables: SeqMap::new(),
312 }
313 }
314}
315
316pub struct SharedState<'a> {
317 pub state: &'a mut ProgramState,
318 pub lookup_table: SymbolTable,
319 pub definition_table: SymbolTable,
320 pub modules: &'a Modules,
321 pub source_map: &'a SourceMap,
322 pub file_id: FileId,
323}
324
325impl<'a> SharedState<'a> {
326 #[must_use]
327 pub fn get_symbol_table(&'a self, path: &[String]) -> Option<&'a SymbolTable> {
328 if path.is_empty() {
329 return Some(&self.lookup_table);
330 }
331 self.get_module(path)
332 .map_or(None, |module| Some(&module.namespace.symbol_table))
333 }
334
335 #[must_use]
336 pub fn get_module(&'a self, path: &[String]) -> Option<&'a ModuleRef> {
337 let resolved_path = {
338 self.lookup_table.get_package_version(&path[0]).map_or_else(
339 || path.to_vec(),
340 |found_version| {
341 let mut new_path = path.to_vec();
342 let complete_name = format!("{}-{found_version}", path[0]);
343 info!(path=?path[0], found_version, complete_name, "switched out version");
344 new_path[0] = complete_name;
345 new_path
346 },
347 )
348 };
349
350 if path.len() == 1 {
351 if let Some(module_ref) = self.lookup_table.get_module_link(&path[0]) {
352 return Some(module_ref);
353 }
354 }
355
356 if let Some(x) = self.modules.get(&resolved_path) {
357 return Some(x);
358 }
359
360 None
361 }
362}
363
364pub struct FunctionScopeState {
365 pub block_scope_stack: Vec<BlockScope>,
366 pub return_type: Type,
367}
368
369impl FunctionScopeState {
370 #[must_use]
371 pub fn new(return_type: Type) -> Self {
372 Self {
373 block_scope_stack: vec![BlockScope::new()],
374 return_type,
375 }
376 }
377}
378
379pub struct Analyzer<'a> {
380 pub shared: SharedState<'a>,
381 scope: FunctionScopeState,
382 global: FunctionScopeState,
383}
384
385impl<'a> Analyzer<'a> {
386 pub fn new(
387 state: &'a mut ProgramState,
388 modules: &'a Modules,
389 source_map: &'a SourceMap,
390 file_id: FileId,
391 ) -> Self {
392 let shared = SharedState {
393 state,
394 lookup_table: SymbolTable::default(),
395 definition_table: SymbolTable::default(),
396 modules,
397 source_map,
398 file_id,
399 };
400 Self {
401 scope: FunctionScopeState::new(Type::Unit),
402 global: FunctionScopeState::new(Type::Unit),
403 shared,
404 }
405 }
406
407 fn start_function(&mut self, return_type: Type) {
408 self.global.block_scope_stack = take(&mut self.scope.block_scope_stack);
409 self.scope = FunctionScopeState::new(return_type);
410 }
411
412 fn stop_function(&mut self) {
413 self.scope.block_scope_stack = take(&mut self.global.block_scope_stack);
414 }
415
416 fn analyze_if_expression(
417 &mut self,
418 condition: &swamp_script_ast::Expression,
419 true_expression: &swamp_script_ast::Expression,
420 maybe_false_expression: Option<&swamp_script_ast::Expression>,
421 context: &TypeContext,
422 ) -> Result<Expression, Error> {
423 let resolved_condition = self.analyze_bool_argument_expression(condition)?;
424
425 let branch_context = context.enter_compare();
426
427 let true_expr = self.analyze_expression(true_expression, &branch_context)?;
428 let resolved_true = Box::new(true_expr);
429
430 let mut detected = context.expected_type.cloned();
431 if detected.is_none() && !matches!(resolved_true.ty, Type::Never) {
432 detected = Some(resolved_true.ty.clone());
433 }
434
435 let else_statements = if let Some(false_expression) = maybe_false_expression {
437 let else_context = branch_context.with_expected_type(detected.as_ref());
438 let else_expr = self.analyze_expression(false_expression, &else_context)?;
439 if detected.is_none() && !matches!(else_expr.ty, Type::Never) {
440 detected = Some(else_expr.ty.clone());
441 }
442
443 Some(Box::new(else_expr))
444 } else {
445 None
446 };
447
448 Ok(self.create_expr(
449 ExpressionKind::If(resolved_condition, resolved_true, else_statements),
450 detected.unwrap(),
451 &condition.node,
452 ))
453 }
454
455 fn get_text(&self, ast_node: &swamp_script_ast::Node) -> &str {
456 let span = Span {
457 file_id: self.shared.file_id,
458 offset: ast_node.span.offset,
459 length: ast_node.span.length,
460 };
461 self.shared.source_map.get_span_source(
462 self.shared.file_id,
463 span.offset as usize,
464 span.length as usize,
465 )
466 }
467
468 fn get_text_resolved(&self, resolved_node: &Node) -> &str {
469 let span = Span {
470 file_id: self.shared.file_id,
471 offset: resolved_node.span.offset,
472 length: resolved_node.span.length,
473 };
474 self.shared.source_map.get_span_source(
475 self.shared.file_id,
476 span.offset as usize,
477 span.length as usize,
478 )
479 }
480
481 fn get_path(&self, ident: &swamp_script_ast::QualifiedTypeIdentifier) -> (Vec<String>, String) {
482 let path = ident
483 .module_path
484 .as_ref()
485 .map_or_else(Vec::new, |found_path| {
486 let mut v = Vec::new();
487 for p in &found_path.0 {
488 v.push(self.get_text(p).to_string());
489 }
490 v
491 });
492 (path, self.get_text(&ident.name.0).to_string())
493 }
494
495 fn analyze_return_type(
496 &mut self,
497 function: &swamp_script_ast::Function,
498 ) -> Result<Type, Error> {
499 let ast_return_type = match function {
500 swamp_script_ast::Function::Internal(x) => &x.declaration.return_type,
501 swamp_script_ast::Function::External(x) => &x.return_type,
502 };
503
504 let resolved_return_type = match ast_return_type {
505 None => Type::Unit,
506 Some(x) => self.analyze_type(x)?,
507 };
508
509 Ok(resolved_return_type)
510 }
511
512 fn analyze_function_body_expression(
513 &mut self,
514 expression: &swamp_script_ast::Expression,
515 return_type: &Type,
516 ) -> Result<Expression, Error> {
517 let context = TypeContext::new_function(return_type);
518 let resolved_statement = self.analyze_expression(expression, &context)?;
519
520 Ok(resolved_statement)
521 }
522
523 fn analyze_maybe_type(
524 &mut self,
525 maybe_type: Option<&swamp_script_ast::Type>,
526 ) -> Result<Type, Error> {
527 let found_type = match maybe_type {
528 None => Type::Unit,
529 Some(ast_type) => self.analyze_type(ast_type)?,
530 };
531 Ok(found_type)
532 }
533
534 fn analyze_for_pattern(
535 &mut self,
536 pattern: &swamp_script_ast::ForPattern,
537 key_type: Option<&Type>,
538 value_type: &Type,
539 ) -> Result<ForPattern, Error> {
540 match pattern {
541 swamp_script_ast::ForPattern::Single(var) => {
542 let variable_ref = self.create_local_variable(
543 &var.identifier,
544 Option::from(&var.is_mut),
545 value_type,
546 )?;
547 Ok(ForPattern::Single(variable_ref))
548 }
549 swamp_script_ast::ForPattern::Pair(first, second) => {
550 let found_key = key_type.unwrap();
551 let first_var_ref = self.create_local_variable(
552 &first.identifier,
553 Option::from(&first.is_mut),
554 found_key,
555 )?;
556 let second_var_ref = self.create_local_variable(
557 &second.identifier,
558 Option::from(&second.is_mut),
559 value_type,
560 )?;
561 Ok(ForPattern::Pair(first_var_ref, second_var_ref))
562 }
563 }
564 }
565
566 fn analyze_parameters(
567 &mut self,
568 parameters: &Vec<swamp_script_ast::Parameter>,
569 ) -> Result<Vec<TypeForParameter>, Error> {
570 let mut resolved_parameters = Vec::new();
571 for parameter in parameters {
572 let param_type = self.analyze_type(¶meter.param_type)?;
573 resolved_parameters.push(TypeForParameter {
574 name: self.get_text(¶meter.variable.name).to_string(),
575 resolved_type: param_type,
576 is_mutable: parameter.variable.is_mutable.is_some(),
577 node: Some(ParameterNode {
578 is_mutable: self.to_node_option(Option::from(¶meter.variable.is_mutable)),
579 name: self.to_node(¶meter.variable.name),
580 }),
581 });
582 }
583 Ok(resolved_parameters)
584 }
585
586 pub fn analyze_immutable_argument(
589 &mut self,
590 ast_expression: &swamp_script_ast::Expression,
591 expected_type: &Type,
592 ) -> Result<Expression, Error> {
593 let context = TypeContext::new_argument(expected_type);
594 self.analyze_expression(ast_expression, &context)
595 }
596
597 pub fn analyze_start_chain_expression_get_mutability(
600 &mut self,
601 ast_expression: &swamp_script_ast::Expression,
602 expected_type: Option<&Type>,
603 ) -> Result<(Expression, bool), Error> {
604 let any_parameter_context = TypeContext::new_unsure_argument(expected_type);
605 let resolved = self.analyze_expression(ast_expression, &any_parameter_context)?;
606 let mutability = match resolved.kind {
607 ExpressionKind::VariableAccess(ref resolved_variable) => resolved_variable.is_mutable(),
608 _ => false,
609 };
610
611 Ok((resolved, mutability))
612 }
613
614 #[allow(clippy::too_many_lines)]
617 pub fn analyze_expression(
618 &mut self,
619 ast_expression: &swamp_script_ast::Expression,
620 context: &TypeContext,
621 ) -> Result<Expression, Error> {
622 let expr = self.analyze_expression_internal(ast_expression, context)?;
623
624 let encountered_type = expr.ty.clone();
625
626 if let Some(found_expected_type) = context.expected_type {
627 if found_expected_type.compatible_with(&encountered_type) {
628 return Ok(expr);
629 }
630
631 let result = self.coerce_expression(
632 expr,
633 found_expected_type,
634 &encountered_type,
635 &ast_expression.node,
636 )?;
637
638 return Ok(result);
639 }
640
641 Ok(expr)
642 }
643
644 #[allow(clippy::too_many_lines)]
647 pub fn analyze_expression_internal(
648 &mut self,
649 ast_expression: &swamp_script_ast::Expression,
650 context: &TypeContext,
651 ) -> Result<Expression, Error> {
652 let expression = match &ast_expression.kind {
653 swamp_script_ast::ExpressionKind::Break => {
654 self.analyze_break(context, &ast_expression.node)?
655 }
656 swamp_script_ast::ExpressionKind::Return(optional_expression) => self.analyze_return(
657 context,
658 optional_expression.as_deref(),
659 &ast_expression.node,
660 )?,
661
662 swamp_script_ast::ExpressionKind::Continue => {
663 self.analyze_continue(context, &ast_expression.node)?
664 }
665
666 swamp_script_ast::ExpressionKind::PostfixChain(postfix_chain) => {
668 self.analyze_postfix_chain(postfix_chain)?
669 }
670
671 swamp_script_ast::ExpressionKind::IdentifierReference(variable) => {
672 self.analyze_identifier_reference(&variable.name)?
673 }
674 swamp_script_ast::ExpressionKind::VariableDefinition(
675 variable,
676 coerce_type,
677 source_expression,
678 ) => self.analyze_create_variable(
679 variable,
680 Option::from(coerce_type),
681 source_expression,
682 )?,
683
684 swamp_script_ast::ExpressionKind::VariableAssignment(variable, source_expression) => {
685 self.analyze_variable_assignment(variable, source_expression)?
686 }
687 swamp_script_ast::ExpressionKind::DestructuringAssignment(variables, expression) => {
688 self.analyze_destructuring(&ast_expression.node, variables, expression)?
689 }
690
691 swamp_script_ast::ExpressionKind::StaticFunctionReference(qualified_identifier) => {
692 self.analyze_static_function_access(qualified_identifier)?
693 }
694
695 swamp_script_ast::ExpressionKind::StaticMemberFunctionReference(
696 type_identifier,
697 member_name,
698 ) => self.analyze_static_member_access(type_identifier, member_name)?,
699
700 swamp_script_ast::ExpressionKind::ConstantReference(constant_identifier) => {
701 self.analyze_constant_access(constant_identifier)?
702 }
703
704 swamp_script_ast::ExpressionKind::FunctionReference(qualified_identifier) => {
705 self.analyze_static_function_access(qualified_identifier)?
706 }
707
708 swamp_script_ast::ExpressionKind::Assignment(location, source) => {
709 self.analyze_assignment(location, source)?
710 }
711 swamp_script_ast::ExpressionKind::CompoundAssignment(target, op, source) => {
712 self.analyze_assignment_compound(target, op, source)?
713 }
714
715 swamp_script_ast::ExpressionKind::BinaryOp(resolved_a, operator, resolved_b) => {
717 let (resolved_op, result_type) =
718 self.analyze_binary_op(resolved_a, operator, resolved_b)?;
719
720 self.create_expr(
721 ExpressionKind::BinaryOp(resolved_op),
722 result_type,
723 &ast_expression.node,
724 )
725 }
726 swamp_script_ast::ExpressionKind::UnaryOp(operator, expression) => {
727 let (resolved_op, result_type) = self.analyze_unary_op(operator, expression)?;
728 self.create_expr(
729 ExpressionKind::UnaryOp(resolved_op),
730 result_type,
731 &ast_expression.node,
732 )
733 }
734
735 swamp_script_ast::ExpressionKind::Block(expressions) => {
736 let (block, resulting_type) =
737 self.analyze_block(&ast_expression.node, context, expressions)?;
738 self.create_expr(
739 ExpressionKind::Block(block),
740 resulting_type,
741 &ast_expression.node,
742 )
743 }
744
745 swamp_script_ast::ExpressionKind::With(variable_bindings, expression) => {
746 self.analyze_with_expr(context, variable_bindings, expression)?
747 }
748
749 swamp_script_ast::ExpressionKind::When(variable_bindings, true_expr, else_expr) => {
750 self.analyze_when_expr(context, variable_bindings, true_expr, else_expr.as_deref())?
751 }
752
753 swamp_script_ast::ExpressionKind::InterpolatedString(string_parts) => {
754 let kind = ExpressionKind::InterpolatedString(
755 self.analyze_interpolated_string(string_parts)?,
756 );
757
758 self.create_expr(kind, Type::String, &ast_expression.node)
759 }
760
761 swamp_script_ast::ExpressionKind::StructLiteral(
763 struct_identifier,
764 fields,
765 has_rest,
766 ) => self.analyze_struct_instantiation(struct_identifier, fields, *has_rest)?,
767
768 swamp_script_ast::ExpressionKind::AnonymousStructLiteral(
769 fields,
770 rest_was_specified,
771 ) => self.analyze_anonymous_struct_literal(
772 &ast_expression.node,
773 fields,
774 *rest_was_specified,
775 context,
776 )?,
777
778 swamp_script_ast::ExpressionKind::Range(min_value, max_value, range_mode) => {
779 let range = self.analyze_range(min_value, max_value, range_mode)?;
780 self.create_expr(
781 ExpressionKind::Range(Box::from(range.min), Box::from(range.max), range.mode),
782 Type::Iterable(Box::from(Type::Int)),
783 &ast_expression.node,
784 )
785 }
786
787 swamp_script_ast::ExpressionKind::Literal(literal) => {
788 let (literal, resolved_type) =
789 self.analyze_literal(&ast_expression.node, literal, context)?;
790 self.create_expr(
791 ExpressionKind::Literal(literal),
792 resolved_type,
793 &ast_expression.node,
794 )
795 }
796
797 swamp_script_ast::ExpressionKind::ForLoop(pattern, iterable_expression, statements) => {
798 let resolved_iterator =
799 self.analyze_iterable(pattern.any_mut(), &iterable_expression.expression)?;
800
801 self.push_block_scope("for_loop");
802 let pattern = self.analyze_for_pattern(
803 pattern,
804 resolved_iterator.key_type.as_ref(),
805 &resolved_iterator.value_type,
806 )?;
807 let resolved_statements =
808 self.analyze_expression(statements, &context.enter_loop())?;
809 self.pop_block_scope("for_loop");
810 let resolved_type = resolved_statements.ty.clone();
811 self.create_expr(
812 ExpressionKind::ForLoop(
813 pattern,
814 resolved_iterator,
815 Box::from(resolved_statements),
816 ),
817 resolved_type,
818 &ast_expression.node,
819 )
820 }
821 swamp_script_ast::ExpressionKind::WhileLoop(expression, statements) => {
822 let condition = self.analyze_bool_argument_expression(expression)?;
823 let resolved_statements =
825 self.analyze_expression(statements, &context.enter_loop())?;
826 let resolved_type = resolved_statements.ty.clone();
827 self.create_expr(
830 ExpressionKind::WhileLoop(condition, Box::from(resolved_statements)),
831 resolved_type,
832 &ast_expression.node,
833 )
834 }
835
836 swamp_script_ast::ExpressionKind::If(
837 expression,
838 true_expression,
839 maybe_false_expression,
840 ) => self.analyze_if_expression(
841 expression,
842 true_expression,
843 maybe_false_expression.as_deref(),
844 context,
845 )?,
846
847 swamp_script_ast::ExpressionKind::Match(expression, arms) => {
848 let (match_expr, return_type) = self.analyze_match(expression, context, arms)?;
849 self.create_expr(
850 ExpressionKind::Match(match_expr),
851 return_type,
852 &ast_expression.node,
853 )
854 }
855 swamp_script_ast::ExpressionKind::Guard(guard_expressions) => {
856 self.analyze_guard(&ast_expression.node, context, guard_expressions)?
857 }
858 };
859
860 Ok(expression)
863 }
864
865 fn get_struct_type(
866 &mut self,
867 qualified_type_identifier: &swamp_script_ast::QualifiedTypeIdentifier,
868 ) -> Result<StructTypeRef, Error> {
869 let maybe_struct_type = self.analyze_named_type(qualified_type_identifier)?;
870 match maybe_struct_type {
871 Type::NamedStruct(struct_type) => Ok(struct_type),
872 _ => Err(self.create_err(
873 ErrorKind::UnknownStructTypeReference,
875 &qualified_type_identifier.name.0,
876 )),
877 }
878 }
879
880 #[must_use]
882 pub fn check_built_in_type(s: &str) -> Option<Type> {
883 let found = match s {
884 "Int" => Type::Int,
885 "Float" => Type::Float,
886 "Bool" => Type::Bool,
887 "String" => Type::String,
888 _ => return None,
889 };
890 Some(found)
891 }
892
893 pub(crate) fn analyze_named_type(
894 &mut self,
895 type_name_to_find: &swamp_script_ast::QualifiedTypeIdentifier,
896 ) -> Result<Type, Error> {
897 let (path, name) = self.get_path(type_name_to_find);
898 if let Some(ty) = Self::check_built_in_type(&name) {
900 return Ok(ty);
901 }
902
903 let symbol = {
904 let maybe_symbol_table = self.shared.get_symbol_table(&path);
905 let symbol_table = maybe_symbol_table.ok_or_else(|| {
906 self.create_err(ErrorKind::UnknownSymbol, &type_name_to_find.name.0)
907 })?;
908 symbol_table
909 .get_symbol(&name)
910 .ok_or_else(|| {
911 self.create_err(ErrorKind::UnknownSymbol, &type_name_to_find.name.0)
912 })?
913 .clone()
914 };
915
916 let mut analyzed_types = Vec::new();
917
918 for analyzed_type in &type_name_to_find.generic_params {
919 let ty = self.analyze_type(analyzed_type)?;
920
921 analyzed_types.push(ty);
922 }
923
924 let result_type = match symbol {
925 Symbol::Type(base_type) => base_type,
926 Symbol::Alias(alias_type) => alias_type.referenced_type.clone(),
927 _ => return Err(self.create_err(ErrorKind::UnknownSymbol, &type_name_to_find.name.0)),
928 };
929
930 Ok(result_type)
931 }
932
933 fn create_default_value_for_type(
934 &mut self,
935 node: &swamp_script_ast::Node,
936 field_type: &Type,
937 ) -> Result<Expression, Error> {
938 let kind = match field_type {
939 Type::Bool => ExpressionKind::Literal(Literal::BoolLiteral(false)),
940 Type::Int => ExpressionKind::Literal(Literal::IntLiteral(0)),
941 Type::Float => ExpressionKind::Literal(Literal::FloatLiteral(Fp::zero())),
942 Type::String => ExpressionKind::Literal(Literal::StringLiteral(String::new())),
943 Type::Array(array_type_ref) => {
944 ExpressionKind::Literal(Literal::Array(array_type_ref.clone(), vec![]))
945 }
946 Type::Tuple(tuple_type_ref) => {
947 let mut expressions = Vec::new();
948 for resolved_type in &tuple_type_ref.0 {
949 let expr = self.create_default_value_for_type(node, resolved_type)?;
950 expressions.push(expr);
951 }
952 ExpressionKind::Literal(Literal::TupleLiteral(tuple_type_ref.clone(), expressions))
953 }
954 Type::Map(map_type_ref) => {
955 ExpressionKind::Literal(Literal::Map(map_type_ref.clone(), vec![]))
956 }
957 Type::Optional(_optional_type) => ExpressionKind::Literal(Literal::NoneLiteral),
958
959 Type::NamedStruct(struct_ref) => self.create_default_static_call(node, struct_ref)?,
960 _ => {
961 return Err(
962 self.create_err(ErrorKind::NoDefaultImplemented(field_type.clone()), node)
963 );
964 }
965 };
966
967 let expr = self.create_expr(kind, field_type.clone(), node);
968 Ok(expr)
969 }
970
971 fn create_default_static_call(
972 &mut self,
973 node: &swamp_script_ast::Node,
974 struct_ref_borrow: &StructTypeRef,
975 ) -> Result<ExpressionKind, Error> {
976 struct_ref_borrow
977 .borrow()
978 .functions
979 .get(&"default".to_string())
980 .map_or_else(
981 || {
982 Err(self.create_err(
983 ErrorKind::NoDefaultImplementedForStruct(struct_ref_borrow.clone()),
984 node,
985 ))
986 },
987 |function| {
988 let kind = match &**function {
989 Function::Internal(internal_function) => {
990 ExpressionKind::InternalFunctionAccess(internal_function.clone())
991 }
992 Function::External(external_function) => {
993 ExpressionKind::ExternalFunctionAccess(external_function.clone())
994 }
995 };
996
997 let base_expr =
998 self.create_expr(kind, Type::Function(function.signature().clone()), node);
999
1000 let empty_call_postfix = Postfix {
1001 node: self.to_node(node),
1002 ty: *function.signature().return_type.clone(),
1003 kind: PostfixKind::FunctionCall(vec![]),
1004 };
1005
1006 let kind =
1007 ExpressionKind::PostfixChain(Box::new(base_expr), vec![empty_call_postfix]);
1008
1009 Ok(kind)
1010 },
1011 )
1012 }
1013
1014 fn add_postfix(
1015 &mut self,
1016 vec: &mut Vec<Postfix>,
1017 kind: PostfixKind,
1018 ty: Type,
1019 node: &swamp_script_ast::Node,
1020 ) {
1021 let resolved_node = self.to_node(node);
1022 let postfix = Postfix {
1023 node: resolved_node,
1024 ty,
1025 kind,
1026 };
1027
1028 vec.push(postfix);
1029 }
1030
1031 pub fn analyze_struct_field(
1036 &mut self,
1037 field_name: &swamp_script_ast::Node,
1038 tv: Type,
1039 ) -> Result<(AnonymousStructType, usize, Type), Error> {
1040 let field_name_str = self.get_text(field_name).to_string();
1041
1042 let anon_struct_ref = match &tv {
1043 Type::NamedStruct(struct_type) => struct_type.borrow().anon_struct_type.clone(),
1044 Type::AnonymousStruct(anon_struct) => anon_struct.clone(),
1045 _ => return Err(self.create_err(ErrorKind::UnknownStructField, field_name)),
1046 };
1047
1048 if let Some(found_field) = anon_struct_ref
1049 .field_name_sorted_fields
1050 .get(&field_name_str)
1051 {
1052 let index = anon_struct_ref
1053 .field_name_sorted_fields
1054 .get_index(&field_name_str)
1055 .expect("checked earlier");
1056
1057 return Ok((
1058 anon_struct_ref.clone(),
1059 index,
1060 found_field.field_type.clone(),
1061 ));
1062 }
1063
1064 Err(self.create_err(ErrorKind::UnknownStructField, field_name))
1065 }
1066
1067 #[allow(clippy::too_many_lines)]
1068 fn analyze_postfix_chain(
1069 &mut self,
1070 chain: &swamp_script_ast::PostfixChain,
1071 ) -> Result<Expression, Error> {
1072 if let swamp_script_ast::ExpressionKind::StaticMemberFunctionReference(
1073 qualified_type_reference,
1074 member_name,
1075 ) = &chain.base.kind
1076 {
1077 if let Some(found_expr) =
1078 self.check_for_internal_static_call(qualified_type_reference, member_name, &[])?
1079 {
1080 return Ok(found_expr);
1081 }
1082 }
1083
1084 let (start, is_mutable) =
1085 self.analyze_start_chain_expression_get_mutability(&chain.base, None)?;
1086
1087 let mut tv = TypeWithMut {
1088 resolved_type: start.ty.clone(),
1089 is_mutable,
1090 };
1091
1092 let mut uncertain = false;
1093
1094 let mut suffixes = Vec::new();
1095
1096 for item in &chain.postfixes {
1097 match item {
1098 swamp_script_ast::Postfix::FieldAccess(field_name) => {
1099 let (struct_type_ref, index, return_type) =
1100 self.analyze_struct_field(&field_name.clone(), tv.resolved_type)?;
1101 self.add_postfix(
1102 &mut suffixes,
1103 PostfixKind::StructField(struct_type_ref.clone(), index),
1104 return_type.clone(),
1105 field_name,
1106 );
1107
1108 tv.resolved_type = return_type.clone();
1109 }
1111 swamp_script_ast::Postfix::MemberCall(member_name, ast_arguments) => {
1112 let dereference = ast_arguments
1113 .iter()
1114 .map(|x| &x.expression)
1115 .collect::<Vec<_>>();
1116 if let Some(found_internal) = self.check_for_internal_member_call(
1117 &tv.resolved_type,
1118 tv.is_mutable,
1119 member_name,
1120 &dereference,
1121 )? {
1122 tv.resolved_type = found_internal.ty.clone();
1123 tv.is_mutable = false;
1124 suffixes.push(found_internal);
1125 } else if let Type::NamedStruct(struct_type) = &tv.resolved_type.clone() {
1126 let return_type = self.analyze_postfix_member_call(
1127 struct_type,
1128 tv.is_mutable,
1129 member_name,
1130 ast_arguments,
1131 &mut suffixes,
1132 )?;
1133
1134 tv.resolved_type = return_type.clone();
1136 tv.is_mutable = false;
1137 } else {
1138 return Err(
1139 self.create_err(ErrorKind::NotValidLocationStartingPoint, member_name)
1140 );
1141 }
1142 }
1143 swamp_script_ast::Postfix::FunctionCall(node, arguments) => {
1144 if let Type::Function(signature) = &tv.resolved_type {
1145 let resolved_node = self.to_node(node);
1146 let resolved_arguments = self.analyze_and_verify_parameters(
1147 &resolved_node,
1148 &signature.parameters,
1149 arguments,
1150 )?;
1151 self.add_postfix(
1152 &mut suffixes,
1153 PostfixKind::FunctionCall(resolved_arguments),
1154 *signature.return_type.clone(),
1155 node,
1156 );
1157
1158 tv.resolved_type = *signature.return_type.clone();
1159 tv.is_mutable = false;
1160 };
1161 }
1162
1163 swamp_script_ast::Postfix::Subscript(index_expr) => {
1164 let collection_type = tv.resolved_type.clone();
1165 match &collection_type {
1166 Type::String => {
1167 if let swamp_script_ast::ExpressionKind::Range(min, max, mode) =
1168 &index_expr.kind
1169 {
1170 let range = self.analyze_range(min, max, mode)?;
1171
1172 self.add_postfix(
1173 &mut suffixes,
1174 PostfixKind::StringRangeIndex(range),
1175 collection_type.clone(),
1176 &index_expr.node,
1177 );
1178
1179 tv.resolved_type = Type::String;
1180 } else {
1181 let int_argument_context = TypeContext::new_argument(&Type::Int);
1182 let resolved_index_expr =
1183 self.analyze_expression(index_expr, &int_argument_context)?;
1184 self.add_postfix(
1185 &mut suffixes,
1186 PostfixKind::StringIndex(resolved_index_expr),
1187 Type::String,
1188 &index_expr.node,
1189 );
1190 }
1191 tv.resolved_type = Type::String;
1192 tv.is_mutable = false;
1193 }
1194
1195 Type::Array(array_type_ref) => {
1196 if let swamp_script_ast::ExpressionKind::Range(
1197 min_expr,
1198 max_expr,
1199 mode,
1200 ) = &index_expr.kind
1201 {
1202 let range = self.analyze_range(min_expr, max_expr, mode)?;
1203
1204 self.add_postfix(
1205 &mut suffixes,
1206 PostfixKind::ArrayRangeIndex(array_type_ref.clone(), range),
1207 collection_type.clone(),
1208 &index_expr.node,
1209 );
1210
1211 tv.resolved_type = collection_type.clone();
1212 } else {
1213 let int_argument_context = TypeContext::new_argument(&Type::Int);
1214 let resolved_index_expr =
1215 self.analyze_expression(index_expr, &int_argument_context)?;
1216 self.add_postfix(
1217 &mut suffixes,
1218 PostfixKind::ArrayIndex(
1219 array_type_ref.clone(),
1220 resolved_index_expr,
1221 ),
1222 array_type_ref.item_type.clone(),
1223 &index_expr.node,
1224 );
1225
1226 tv.resolved_type = array_type_ref.item_type.clone();
1227 }
1228
1229 tv.is_mutable = false;
1230 }
1231
1232 Type::Map(map_type_ref) => {
1233 let key_type_context =
1234 TypeContext::new_argument(&map_type_ref.key_type);
1235 let resolved_key_expr =
1236 self.analyze_expression(index_expr, &key_type_context)?;
1237 let return_type =
1238 Type::Optional(Box::from(map_type_ref.value_type.clone()));
1239 self.add_postfix(
1240 &mut suffixes,
1241 PostfixKind::MapIndex(map_type_ref.clone(), resolved_key_expr),
1242 return_type.clone(),
1243 &index_expr.node,
1244 );
1245
1246 tv.resolved_type = return_type;
1247 tv.is_mutable = false;
1248 }
1249
1250 Type::Generic(base, generic_type_parameters) => match &**base {
1251 Type::External(found_rust_type) => {
1252 if found_rust_type.number == SPARSE_TYPE_ID {
1253 let sparse_id = self
1254 .shared
1255 .lookup_table
1256 .get_external_type("SparseId")
1257 .expect("SparseId is missing");
1258 let binding = Type::External(sparse_id.clone());
1259 let sparse_id_context = TypeContext::new_argument(&binding);
1260 let contained_type = &generic_type_parameters[0];
1261 let resolved_key =
1262 self.analyze_expression(index_expr, &sparse_id_context)?;
1263
1264 let return_type =
1265 Type::Optional(Box::new(contained_type.clone()));
1266
1267 self.add_postfix(
1268 &mut suffixes,
1269 PostfixKind::ExternalTypeIndexRef(
1270 found_rust_type.clone(),
1271 resolved_key,
1272 ),
1273 return_type.clone(),
1274 &index_expr.node,
1275 );
1276
1277 tv.resolved_type = return_type;
1278 tv.is_mutable = false;
1279 } else {
1280 panic!("unknown generic type lookup")
1281 }
1282 }
1283 _ => panic!("not supported"),
1284 },
1285 _ => {
1286 return Err(self.create_err(
1287 ErrorKind::ExpectedArray(collection_type),
1288 &index_expr.node,
1289 ));
1290 }
1291 }
1292 }
1293
1294 swamp_script_ast::Postfix::NoneCoalesce(default_expr) => {
1295 let unwrapped_type = if let Type::Optional(unwrapped_type) = &tv.resolved_type {
1296 unwrapped_type
1297 } else if uncertain {
1298 &tv.resolved_type
1299 } else {
1300 return Err(
1301 self.create_err(ErrorKind::CanNotNoneCoalesce, &default_expr.node)
1302 );
1303 };
1304
1305 let unwrapped_type_context = TypeContext::new_argument(unwrapped_type);
1306 let resolved_default_expr =
1307 self.analyze_expression(default_expr, &unwrapped_type_context)?;
1308 self.add_postfix(
1309 &mut suffixes,
1310 PostfixKind::NoneCoalesce(resolved_default_expr),
1311 unwrapped_type.clone(),
1312 &default_expr.node,
1313 );
1314 tv.resolved_type = unwrapped_type.clone();
1315 uncertain = false; }
1317
1318 swamp_script_ast::Postfix::OptionUnwrap(option_node) => {
1319 if let Type::Optional(unwrapped_type) = &tv.resolved_type {
1320 uncertain = true;
1321 self.add_postfix(
1322 &mut suffixes,
1323 PostfixKind::OptionUnwrap,
1324 *unwrapped_type.clone(),
1325 option_node,
1326 );
1327 tv.resolved_type = *unwrapped_type.clone();
1328 } else {
1329 return Err(self.create_err(ErrorKind::ExpectedOptional, option_node));
1330 }
1331 }
1332 }
1333 }
1334
1335 if uncertain {
1336 if let Type::Optional(_) = tv.resolved_type {
1337 } else {
1338 tv.resolved_type = Type::Optional(Box::from(tv.resolved_type.clone()));
1339 }
1340 }
1341
1342 Ok(self.create_expr(
1343 ExpressionKind::PostfixChain(Box::new(start), suffixes),
1344 tv.resolved_type,
1345 &chain.base.node,
1346 ))
1347 }
1348
1349 fn analyze_bool_argument_expression(
1350 &mut self,
1351 expression: &swamp_script_ast::Expression,
1352 ) -> Result<BooleanExpression, Error> {
1353 let bool_context = TypeContext::new_argument(&Type::Bool);
1354 let resolved_expression = self.analyze_expression(expression, &bool_context)?;
1355 let expr_type = resolved_expression.ty.clone();
1356
1357 let bool_expression = match expr_type {
1358 Type::Bool => resolved_expression,
1359 Type::Optional(_) => self.create_expr(
1360 ExpressionKind::CoerceOptionToBool(Box::new(resolved_expression)),
1361 Type::Bool,
1362 &expression.node,
1363 ),
1364 _ => {
1365 return Err(self.create_err(ErrorKind::ExpectedBooleanExpression, &expression.node));
1366 }
1367 };
1368
1369 Ok(BooleanExpression {
1370 expression: Box::from(bool_expression),
1371 })
1372 }
1373
1374 fn analyze_iterable(
1375 &mut self,
1376 force_mut: Option<swamp_script_ast::Node>,
1377 expression: &swamp_script_ast::MutableOrImmutableExpression,
1378 ) -> Result<Iterable, Error> {
1379 let any_context = TypeContext::new_anything_argument();
1380 let resolved_expression: MutOrImmutableExpression = if force_mut.is_some() {
1381 let resolved_node = self.to_node(&force_mut.unwrap());
1382 MutOrImmutableExpression {
1383 expression_or_location: ArgumentExpressionOrLocation::Location(
1384 self.analyze_to_location(
1385 &expression.expression,
1386 &any_context,
1387 LocationSide::Rhs,
1388 )?,
1389 ),
1390 is_mutable: Some(resolved_node),
1391 }
1392 } else {
1393 self.analyze_mut_or_immutable_expression(expression, &any_context, LocationSide::Rhs)?
1394 };
1395
1396 let resolved_type = &resolved_expression.ty().clone();
1397 let (key_type, value_type): (Option<Type>, Type) = match resolved_type {
1398 Type::Array(array_type) => (Some(Type::Int), array_type.item_type.clone()),
1399 Type::Map(map_type_ref) => (
1400 Some(map_type_ref.key_type.clone()),
1401 map_type_ref.value_type.clone(),
1402 ),
1403 Type::String => (Some(Type::Int), Type::String),
1404 Type::Iterable(item_type) => (None, *item_type.clone()),
1405 Type::Generic(_base_type, params) => {
1406 let rust_type_ref_for_id = self
1410 .shared
1411 .lookup_table
1412 .get_external_type("SparseId")
1413 .expect("SparseId was missing");
1414 let rust_id_type = Type::External(rust_type_ref_for_id.clone());
1415 (Some(rust_id_type), params[0].clone())
1416 }
1417 _ => return Err(self.create_err(ErrorKind::NotAnIterator, &expression.expression.node)),
1418 };
1419
1420 Ok(Iterable {
1421 key_type,
1422 value_type,
1423 resolved_expression: Box::new(resolved_expression),
1424 })
1425 }
1426
1427 fn analyze_argument_expressions(
1428 &mut self,
1429 expected_type: Option<&Type>,
1430 ast_expressions: &[swamp_script_ast::Expression],
1431 ) -> Result<Vec<Expression>, Error> {
1432 let mut resolved_expressions = Vec::new();
1433 let argument_expressions_context = TypeContext::new_unsure_argument(expected_type);
1434 for expression in ast_expressions {
1435 resolved_expressions
1436 .push(self.analyze_expression(expression, &argument_expressions_context)?);
1437 }
1438 Ok(resolved_expressions)
1439 }
1440
1441 fn analyze_block(
1442 &mut self,
1443 _node: &swamp_script_ast::Node,
1444 context: &TypeContext,
1445 ast_expressions: &[swamp_script_ast::Expression],
1446 ) -> Result<(Vec<Expression>, Type), Error> {
1447 if ast_expressions.is_empty() {
1448 return Ok((vec![], Type::Unit));
1449 }
1450
1451 self.push_block_scope("block");
1452
1453 let mut resolved_expressions = Vec::with_capacity(ast_expressions.len());
1454
1455 for expression in &ast_expressions[..ast_expressions.len() - 1] {
1456 let stmt_context = context.with_expected_type(Some(&Type::Unit));
1457 let expr = self.analyze_expression(expression, &stmt_context)?;
1458
1459 if matches!(expr.ty, Type::Never) {
1460 resolved_expressions.push(expr);
1461 return Ok((resolved_expressions, Type::Never));
1462 }
1463
1464 resolved_expressions.push(expr);
1465 }
1466
1467 let last_expr =
1469 self.analyze_expression(&ast_expressions[ast_expressions.len() - 1], context)?;
1470 let last_type = last_expr.ty.clone();
1471 resolved_expressions.push(last_expr);
1472
1473 self.pop_block_scope("block");
1474
1475 Ok((resolved_expressions, last_type))
1476 }
1477
1478 fn analyze_interpolated_string(
1479 &mut self,
1480 string_parts: &[swamp_script_ast::StringPart],
1481 ) -> Result<Vec<StringPart>, Error> {
1482 let mut resolved_parts = Vec::new();
1483 for part in string_parts {
1484 let resolved_string_part = match part {
1485 swamp_script_ast::StringPart::Literal(string_node, processed_string) => {
1486 StringPart::Literal(self.to_node(string_node), processed_string.to_string())
1487 }
1488 swamp_script_ast::StringPart::Interpolation(expression, format_specifier) => {
1489 let any_context = TypeContext::new_anything_argument();
1490 let expr = self.analyze_expression(expression, &any_context)?;
1491 let resolved_format_specifier =
1492 self.analyze_format_specifier(Option::from(format_specifier));
1493 StringPart::Interpolation(expr, resolved_format_specifier)
1494 }
1495 };
1496
1497 resolved_parts.push(resolved_string_part);
1498 }
1499
1500 Ok(resolved_parts)
1501 }
1502
1503 pub(crate) fn analyze_static_function_access(
1504 &self,
1505 qualified_func_name: &swamp_script_ast::QualifiedIdentifier,
1506 ) -> Result<Expression, Error> {
1507 let path = self.get_module_path(qualified_func_name.module_path.as_ref());
1508 let function_name = self.get_text(&qualified_func_name.name);
1509
1510 if let Some(found_table) = self.shared.get_symbol_table(&path) {
1511 if let Some(found_func) = found_table.get_function(function_name) {
1512 let (kind, return_type) = match found_func {
1513 FuncDef::Internal(internal_fn) => (
1514 ExpressionKind::InternalFunctionAccess(internal_fn.clone()),
1515 &internal_fn.signature.return_type,
1516 ),
1517 FuncDef::External(external_fn) => (
1518 ExpressionKind::ExternalFunctionAccess(external_fn.clone()),
1519 &external_fn.signature.return_type,
1520 ),
1521 FuncDef::Intrinsic(_) => {
1523 return Err(
1524 self.create_err(ErrorKind::UnknownFunction, &qualified_func_name.name)
1525 );
1526 }
1527 };
1528
1529 return Ok(self.create_expr(kind, *return_type.clone(), &qualified_func_name.name));
1530 }
1531 }
1532 Err(self.create_err(ErrorKind::UnknownFunction, &qualified_func_name.name))
1533 }
1534
1535 fn analyze_identifier_reference(
1537 &self,
1538 var_node: &swamp_script_ast::Node,
1539 ) -> Result<Expression, Error> {
1540 let text = self.get_text(var_node);
1541
1542 if let Some(found_variable) = self.try_find_variable(var_node) {
1545 return Ok(self.create_expr(
1546 ExpressionKind::VariableAccess(found_variable.clone()),
1547 found_variable.resolved_type.clone(),
1548 var_node,
1549 ));
1550 }
1551
1552 if let Some(found_symbol) = self.shared.lookup_table.get_symbol(text) {
1553 let expr = match found_symbol {
1554 Symbol::FunctionDefinition(func) => match func {
1555 FuncDef::External(found_external_function) => self.create_expr(
1556 ExpressionKind::ExternalFunctionAccess(found_external_function.clone()),
1557 Type::Function(found_external_function.signature.clone()),
1558 var_node,
1559 ),
1560 FuncDef::Internal(found_internal_function) => self.create_expr(
1561 ExpressionKind::InternalFunctionAccess(found_internal_function.clone()),
1562 Type::Function(found_internal_function.signature.clone()),
1563 var_node,
1564 ),
1565 FuncDef::Intrinsic(_) => todo!(),
1566 },
1567
1568 _ => {
1569 return Err(self.create_err(ErrorKind::UnknownIdentifier, var_node));
1570 }
1571 };
1572 return Ok(expr);
1573 }
1574
1575 Err(self.create_err(ErrorKind::UnknownIdentifier, var_node))
1576 }
1577 fn analyze_usize_index(
1578 &mut self,
1579 usize_expression: &swamp_script_ast::Expression,
1580 ) -> Result<Expression, Error> {
1581 let int_context = TypeContext::new_argument(&Type::Int);
1582 let lookup_expression = self.analyze_expression(usize_expression, &int_context)?;
1583 let lookup_resolution = lookup_expression.ty.clone();
1584
1585 match &lookup_resolution {
1586 Type::Int => {}
1587 _ => Err(self.create_err(
1588 ErrorKind::ArrayIndexMustBeInt(lookup_resolution),
1589 &usize_expression.node,
1590 ))?,
1591 }
1592
1593 Ok(lookup_expression)
1594 }
1595
1596 fn analyze_array_type_helper(
1597 &mut self,
1598 node: &swamp_script_ast::Node,
1599 items: &[swamp_script_ast::Expression],
1600 expected_type: Option<&Type>,
1601 ) -> Result<(ArrayTypeRef, Vec<Expression>), Error> {
1602 let expressions = self.analyze_argument_expressions(None, items)?;
1603 let item_type = if expressions.is_empty() {
1604 if let Some(found_expected_type) = expected_type {
1605 info!(?found_expected_type, "found array type");
1606 if let Type::Array(found) = found_expected_type {
1607 found.item_type.clone()
1608 } else {
1609 return Err(self.create_err(ErrorKind::NotAnArray, node));
1610 }
1611 } else {
1612 return Err(self.create_err(ErrorKind::NotAnArray, node));
1613 }
1614 } else {
1615 expressions[0].ty.clone()
1616 };
1617
1618 let array_type = ArrayType { item_type };
1619
1620 let array_type_ref = Rc::new(array_type);
1621
1622 Ok((array_type_ref, expressions))
1623 }
1624
1625 fn push_block_scope(&mut self, _debug_str: &str) {
1626 self.scope.block_scope_stack.push(BlockScope {
1627 mode: BlockScopeMode::Open,
1628 variables: SeqMap::default(),
1629 });
1630 }
1631
1632 fn pop_block_scope(&mut self, _debug_str: &str) {
1633 self.scope.block_scope_stack.pop();
1634 }
1635
1636 fn push_closed_block_scope(&mut self) {
1637 self.scope.block_scope_stack.push(BlockScope {
1638 mode: BlockScopeMode::Closed,
1639 variables: SeqMap::default(),
1640 });
1641 }
1642
1643 fn pop_closed_block_scope(&mut self) {
1644 self.scope.block_scope_stack.pop();
1645 }
1646
1647 fn analyze_enum_variant_ref(
1648 &self,
1649 qualified_type_identifier: &swamp_script_ast::QualifiedTypeIdentifier,
1650 variant_name: &swamp_script_ast::LocalTypeIdentifier,
1651 ) -> Result<EnumVariantTypeRef, Error> {
1652 let variant_name_string = self.get_text(&variant_name.0).to_string();
1653 self.get_enum_variant_type(qualified_type_identifier, &variant_name_string)
1654 }
1655
1656 fn analyze_match(
1657 &mut self,
1658 scrutinee: &swamp_script_ast::MutableOrImmutableExpression,
1659 default_context: &TypeContext,
1660 arms: &Vec<swamp_script_ast::MatchArm>,
1661 ) -> Result<(Match, Type), Error> {
1662 let mut known_type = default_context.expected_type.cloned();
1663 let own_context = default_context.clone();
1664 let scrutinee_context = TypeContext::new_anything_argument();
1666 let resolved_scrutinee = self.analyze_mut_or_immutable_expression(
1667 scrutinee,
1668 &scrutinee_context,
1669 LocationSide::Rhs,
1670 )?;
1671 let scrutinee_type = resolved_scrutinee.ty().clone();
1672
1673 if arms.is_empty() {
1675 return Err(self.create_err(ErrorKind::EmptyMatch, &scrutinee.expression.node));
1676 }
1677
1678 let mut resolved_arms = Vec::with_capacity(arms.len());
1679
1680 for arm in arms {
1681 let (resolved_arm, _anyone_wants_mutable) = self.analyze_arm(
1682 arm,
1683 &resolved_scrutinee,
1684 &own_context.with_expected_type(known_type.as_ref()),
1685 &scrutinee_type,
1686 )?;
1687
1688 if known_type.is_none() && !matches!(resolved_arm.expression.ty, Type::Never) {
1689 known_type = Some(resolved_arm.expression.ty.clone());
1690 }
1691 resolved_arms.push(resolved_arm);
1692 }
1693
1694 known_type.map_or_else(
1695 || {
1696 Err(self.create_err(
1697 ErrorKind::MatchArmsMustHaveTypes,
1698 &scrutinee.expression.node,
1699 ))
1700 },
1701 |encountered_type| {
1702 if matches!(encountered_type, Type::Never) {
1703 Err(self.create_err(
1704 ErrorKind::IncompatibleTypes(encountered_type.clone(), encountered_type),
1705 &scrutinee.expression.node,
1706 ))
1707 } else {
1708 Ok((
1709 Match {
1710 expression: Box::new(resolved_scrutinee),
1711 arms: resolved_arms,
1712 },
1713 encountered_type,
1714 ))
1715 }
1716 },
1717 )
1718 }
1719
1720 fn analyze_arm(
1721 &mut self,
1722 arm: &swamp_script_ast::MatchArm,
1723 _expression: &MutOrImmutableExpression,
1724 type_context: &TypeContext,
1725 expected_condition_type: &Type,
1726 ) -> Result<(MatchArm, bool), Error> {
1727 let (resolved_pattern, scope_was_pushed, anyone_wants_mutable) =
1728 self.analyze_pattern(&arm.pattern, expected_condition_type)?;
1729
1730 let resolved_expression = self.analyze_expression(&arm.expression, type_context)?;
1731 if scope_was_pushed {
1732 self.pop_block_scope("analyze_arm");
1733 }
1734
1735 let resolved_type = resolved_expression.ty.clone();
1736
1737 Ok((
1738 MatchArm {
1739 pattern: resolved_pattern,
1740 expression: Box::from(resolved_expression),
1741 expression_type: resolved_type,
1742 },
1743 anyone_wants_mutable,
1744 ))
1745 }
1746
1747 fn str_to_int(text: &str) -> Result<i32, ParseIntError> {
1748 text.parse::<i32>()
1749 }
1750
1751 fn str_to_float(text: &str) -> Result<f32, ParseFloatError> {
1752 text.parse::<f32>()
1753 }
1754
1755 fn analyze_pattern_literal(
1756 &mut self,
1757 node: &swamp_script_ast::Node,
1758 ast_literal: &swamp_script_ast::LiteralKind,
1759 expected_condition_type: &Type,
1760 ) -> Result<NormalPattern, Error> {
1761 let required_condition_type_context = TypeContext::new_argument(expected_condition_type);
1762 let (resolved_literal, literal_type) =
1763 self.analyze_literal(node, ast_literal, &required_condition_type_context)?;
1764
1765 if !literal_type.compatible_with(expected_condition_type) {
1766 return Err(self.create_err(
1767 ErrorKind::IncompatibleTypes(literal_type, expected_condition_type.clone()),
1768 node,
1769 ));
1770 }
1771
1772 Ok(NormalPattern::Literal(resolved_literal))
1773 }
1774
1775 const fn to_node(&self, node: &swamp_script_ast::Node) -> Node {
1776 Node {
1777 span: Span {
1778 file_id: self.shared.file_id,
1779 offset: node.span.offset,
1780 length: node.span.length,
1781 },
1782 }
1783 }
1784
1785 fn get_module_path(&self, module_path: Option<&swamp_script_ast::ModulePath>) -> Vec<String> {
1786 module_path.as_ref().map_or_else(Vec::new, |found| {
1787 let mut strings = Vec::new();
1788 for path_item in &found.0 {
1789 strings.push(self.get_text(path_item).to_string());
1790 }
1791 strings
1792 })
1793 }
1794
1795 fn get_enum_variant_type(
1796 &self,
1797 qualified_type_identifier: &swamp_script_ast::QualifiedTypeIdentifier,
1798 variant_name: &str,
1799 ) -> Result<EnumVariantTypeRef, Error> {
1800 let (symbol_table, enum_name) =
1801 self.get_symbol_table_and_name(qualified_type_identifier)?;
1802 symbol_table
1803 .get_enum_variant_type(&enum_name, variant_name)
1804 .ok_or_else(|| {
1805 self.create_err(
1806 ErrorKind::UnknownEnumVariantType,
1807 &qualified_type_identifier.name.0,
1808 )
1809 })
1810 }
1811
1812 pub(crate) fn get_symbol_table_and_name(
1813 &self,
1814 type_identifier: &swamp_script_ast::QualifiedTypeIdentifier,
1815 ) -> Result<(&SymbolTable, String), Error> {
1816 let path = self.get_module_path(type_identifier.module_path.as_ref());
1817 let name = self.get_text(&type_identifier.name.0).to_string();
1818
1819 let maybe_symbol_table = self.shared.get_symbol_table(&path);
1820 maybe_symbol_table.map_or_else(
1821 || Err(self.create_err(ErrorKind::UnknownModule, &type_identifier.name.0)),
1822 |symbol_table| Ok((symbol_table, name)),
1823 )
1824 }
1825
1826 const fn analyze_compound_operator(
1827 &self,
1828 ast_operator: &swamp_script_ast::CompoundOperator,
1829 ) -> CompoundOperator {
1830 let resolved_node = self.to_node(&ast_operator.node);
1831 let resolved_kind = match ast_operator.kind {
1832 swamp_script_ast::CompoundOperatorKind::Add => CompoundOperatorKind::Add,
1833 swamp_script_ast::CompoundOperatorKind::Sub => CompoundOperatorKind::Sub,
1834 swamp_script_ast::CompoundOperatorKind::Mul => CompoundOperatorKind::Mul,
1835 swamp_script_ast::CompoundOperatorKind::Div => CompoundOperatorKind::Div,
1836 swamp_script_ast::CompoundOperatorKind::Modulo => CompoundOperatorKind::Modulo,
1837 };
1838
1839 CompoundOperator {
1840 node: resolved_node,
1841 kind: resolved_kind,
1842 }
1843 }
1844
1845 const fn to_node_option(&self, maybe_node: Option<&swamp_script_ast::Node>) -> Option<Node> {
1846 match maybe_node {
1847 None => None,
1848 Some(node) => Some(self.to_node(node)),
1849 }
1850 }
1851
1852 const fn analyze_format_specifier(
1853 &self,
1854 ast_format_specifier: Option<&swamp_script_ast::FormatSpecifier>,
1855 ) -> Option<FormatSpecifier> {
1856 let f = match ast_format_specifier {
1857 None => return None,
1858 Some(ast_format) => match ast_format {
1859 swamp_script_ast::FormatSpecifier::LowerHex(node) => FormatSpecifier {
1860 node: self.to_node(node),
1861 kind: FormatSpecifierKind::LowerHex,
1862 },
1863 swamp_script_ast::FormatSpecifier::UpperHex(node) => FormatSpecifier {
1864 node: self.to_node(node),
1865 kind: FormatSpecifierKind::UpperHex,
1866 },
1867 swamp_script_ast::FormatSpecifier::Binary(node) => FormatSpecifier {
1868 node: self.to_node(node),
1869 kind: FormatSpecifierKind::Binary,
1870 },
1871 swamp_script_ast::FormatSpecifier::Float(node) => FormatSpecifier {
1872 node: self.to_node(node),
1873 kind: FormatSpecifierKind::Float,
1874 },
1875 swamp_script_ast::FormatSpecifier::Precision(value, node, x) => {
1876 let (precision_type, precision_node) = match x {
1877 swamp_script_ast::PrecisionType::Float(node) => {
1878 (PrecisionType::Float, self.to_node(node))
1879 }
1880 swamp_script_ast::PrecisionType::String(node) => {
1881 (PrecisionType::String, self.to_node(node))
1882 }
1883 };
1884 FormatSpecifier {
1885 node: self.to_node(node),
1886 kind: FormatSpecifierKind::Precision(
1887 *value,
1888 precision_node,
1889 precision_type,
1890 ),
1891 }
1892 }
1893 },
1894 };
1895
1896 Some(f)
1897 }
1898
1899 fn analyze_with_expr(
1900 &mut self,
1901 context: &TypeContext,
1902 variables: &[swamp_script_ast::VariableBinding],
1903 expression: &swamp_script_ast::Expression,
1904 ) -> Result<Expression, Error> {
1905 let mut variable_expressions = Vec::new();
1906
1907 for variable in variables {
1908 let any_context = TypeContext::new_anything_argument();
1909 let var = self.analyze_mut_or_immutable_expression(
1910 &variable.expression,
1911 &any_context,
1912 LocationSide::Rhs,
1913 )?;
1914 variable_expressions.push(var);
1915 }
1916
1917 self.push_closed_block_scope();
1918 let mut expressions = Vec::new();
1919 for (variable_binding, resolved_expression) in variables.iter().zip(variable_expressions) {
1920 let initialize_variable_expression = self.create_variable_binding_for_with(
1921 &variable_binding.variable,
1922 resolved_expression,
1923 )?;
1924 expressions.push(initialize_variable_expression);
1925 }
1926
1927 let resolved_expression = self.analyze_expression(expression, context)?;
1928 let block_type = resolved_expression.ty.clone();
1929 expressions.push(resolved_expression);
1930
1931 let block_expression_kind = ExpressionKind::Block(expressions);
1932 self.pop_closed_block_scope();
1933
1934 let block_expr = self.create_expr(block_expression_kind, block_type, &expression.node);
1935 Ok(block_expr)
1936 }
1937
1938 fn analyze_when_expr(
1939 &mut self,
1940 context: &TypeContext,
1941 variables: &[swamp_script_ast::WhenBinding],
1942 true_expr: &swamp_script_ast::Expression,
1943 else_expr: Option<&swamp_script_ast::Expression>,
1944 ) -> Result<Expression, Error> {
1945 self.push_block_scope("when");
1947 let mut bindings = Vec::new();
1948 for variable_binding in variables {
1949 let mut_expr = if let Some(found_expr) = &variable_binding.expression {
1950 let any_context = TypeContext::new_anything_argument();
1951 self.analyze_mut_or_immutable_expression(
1952 found_expr,
1953 &any_context,
1954 LocationSide::Rhs,
1955 )?
1956 } else {
1957 let same_var = self.find_variable(&variable_binding.variable)?;
1958
1959 let is_mutable = same_var.mutable_node.clone();
1960 let argument_expression = if same_var.is_mutable() {
1961 let loc = SingleLocationExpression {
1962 kind: SingleLocationExpressionKind::MutVariableRef,
1963 node: self.to_node(&variable_binding.variable.name),
1964 ty: same_var.resolved_type.clone(),
1965 starting_variable: same_var,
1966 access_chain: vec![],
1967 };
1968 ArgumentExpressionOrLocation::Location(loc)
1969 } else {
1970 let generated_expr_kind = ExpressionKind::VariableAccess(same_var.clone());
1971 let generated_expression = self.create_expr(
1972 generated_expr_kind,
1973 same_var.resolved_type.clone(),
1974 &variable_binding.variable.name,
1975 );
1976 ArgumentExpressionOrLocation::Expression(generated_expression)
1977 };
1978
1979 MutOrImmutableExpression {
1980 expression_or_location: argument_expression,
1981 is_mutable,
1982 }
1983 };
1984
1985 let ty = mut_expr.ty();
1986
1987 if let Type::Optional(found_ty) = ty {
1988 let variable_ref = self.create_variable(&variable_binding.variable, found_ty)?;
1989
1990 let binding = WhenBinding {
1991 variable: variable_ref,
1992 expr: mut_expr,
1993 };
1994 bindings.push(binding);
1995 } else {
1996 return Err(self.create_err(ErrorKind::ExpectedOptional, &true_expr.node));
1997 }
1998 }
1999
2000 let resolved_true = self.analyze_expression(true_expr, context)?;
2001 let block_type = resolved_true.ty.clone();
2002
2003 self.pop_block_scope("when");
2004
2005 let maybe_resolved_else = if let Some(found_else) = else_expr {
2006 let block_type_for_true_context = context.we_know_expected_type(&block_type);
2007 Some(Box::new(self.analyze_expression(
2008 found_else,
2009 &block_type_for_true_context,
2010 )?))
2011 } else {
2012 None
2013 };
2014
2015 let when_kind =
2016 ExpressionKind::When(bindings, Box::from(resolved_true), maybe_resolved_else);
2017
2018 let block_expr = self.create_expr(when_kind, block_type, &true_expr.node);
2019 Ok(block_expr)
2020 }
2021
2022 fn analyze_guard(
2023 &mut self,
2024 node: &swamp_script_ast::Node,
2025 context: &TypeContext,
2026 guard_expressions: &Vec<swamp_script_ast::GuardExpr>,
2027 ) -> Result<Expression, Error> {
2028 let mut guards = Vec::new();
2029 let mut found_wildcard = None;
2030 let mut detected_type = context.expected_type.cloned();
2031
2032 for guard in guard_expressions {
2033 let resolved_condition = match &guard.clause {
2034 swamp_script_ast::GuardClause::Wildcard(x) => {
2035 if found_wildcard.is_some() {
2036 return Err(
2037 self.create_err(ErrorKind::GuardCanNotHaveMultipleWildcards, node)
2038 );
2039 }
2040 found_wildcard = Some(x);
2041 None
2042 }
2043 swamp_script_ast::GuardClause::Expression(clause_expr) => {
2044 if found_wildcard.is_some() {
2045 return Err(self.create_err(ErrorKind::WildcardMustBeLastInGuard, node));
2046 }
2047 Some(self.analyze_bool_argument_expression(clause_expr)?)
2048 }
2049 };
2050
2051 let resolved_result = self.analyze_expression(
2052 &guard.result,
2053 &context.with_expected_type(detected_type.as_ref()),
2054 )?;
2055 let ty = resolved_result.ty.clone();
2056 if detected_type.is_none() && !matches!(ty, Type::Never) {
2057 detected_type = Some(ty.clone());
2058 }
2059
2060 guards.push(Guard {
2061 condition: resolved_condition,
2062 result: resolved_result,
2063 });
2064 }
2065
2066 if found_wildcard.is_none() {
2067 return Err(self.create_err(ErrorKind::GuardMustHaveWildcard, node));
2068 }
2069
2070 let kind = ExpressionKind::Guard(guards);
2071
2072 detected_type.map_or_else(
2073 || Err(self.create_err(ErrorKind::GuardHasNoType, node)),
2074 |found_expecting_type| {
2075 let expr = self.create_expr(kind, found_expecting_type, node);
2076 Ok(expr)
2077 },
2078 )
2079 }
2080
2081 pub fn analyze_variable_assignment(
2084 &mut self,
2085 variable: &swamp_script_ast::Variable,
2086 source_expression: &swamp_script_ast::MutableOrImmutableExpression,
2087 ) -> Result<Expression, Error> {
2088 let any_argument_context = TypeContext::new_anything_argument();
2089 let source_expr = self.analyze_mut_or_immutable_expression(
2090 source_expression,
2091 &any_argument_context,
2092 LocationSide::Rhs,
2093 )?;
2094 let ty = source_expr.ty().clone();
2095 if !ty.is_concrete() {
2096 return Err(self.create_err(ErrorKind::VariableTypeMustBeConcrete, &variable.name));
2097 }
2098
2099 let maybe_found_variable = self.try_find_variable(&variable.name);
2100
2101 let kind: ExpressionKind = if let Some(found_var) = maybe_found_variable {
2102 if !found_var.is_mutable() {
2103 return Err(self.create_err(ErrorKind::VariableIsNotMutable, &variable.name));
2104 }
2105 if !found_var.resolved_type.assignable_type(&ty) {
2106 return Err(self.create_err(
2107 ErrorKind::IncompatibleTypes(found_var.resolved_type.clone(), ty.clone()),
2108 &variable.name,
2109 ));
2110 }
2111 ExpressionKind::VariableReassignment(found_var, Box::from(source_expr))
2112 } else {
2113 let new_var = self.create_variable(variable, &ty)?;
2114 ExpressionKind::VariableDefinition(new_var, Box::from(source_expr))
2115 };
2116
2117 Ok(self.create_expr(kind, Type::Unit, &variable.name))
2118 }
2119
2120 fn analyze_create_variable(
2121 &mut self,
2122 var: &swamp_script_ast::Variable,
2123 annotation_type: Option<&swamp_script_ast::Type>,
2124 source_expression: &swamp_script_ast::MutableOrImmutableExpression,
2125 ) -> Result<Expression, Error> {
2126 let ty = if let Some(found_ast_type) = annotation_type {
2127 Some(self.analyze_type(found_ast_type)?)
2128 } else {
2129 None
2130 };
2131
2132 let unsure_arg_context = TypeContext::new_unsure_argument(ty.as_ref());
2133
2134 let resolved_source = self.analyze_mut_or_immutable_expression(
2135 source_expression,
2136 &unsure_arg_context,
2137 LocationSide::Rhs,
2138 )?;
2139
2140 let var_ref = self.create_local_variable(
2141 &var.name,
2142 Option::from(&var.is_mutable),
2143 &resolved_source.ty(),
2144 )?;
2145
2146 let resolved_type = resolved_source.ty().clone();
2147 assert_ne!(resolved_type, Type::Unit);
2148 let kind = ExpressionKind::VariableDefinition(var_ref, Box::from(resolved_source));
2149
2150 let resolved_expr = self.create_expr(kind, Type::Unit, &var.name);
2151
2152 Ok(resolved_expr)
2153 }
2154
2155 fn add_location_item(
2156 &mut self,
2157 vec: &mut Vec<LocationAccess>,
2158 kind: LocationAccessKind,
2159 ty: Type,
2160 ast_node: &swamp_script_ast::Node,
2161 ) {
2162 let resolved_node = self.to_node(ast_node);
2163 let postfix = LocationAccess {
2164 node: resolved_node.clone(),
2165 ty,
2166 kind,
2167 };
2168
2169 vec.push(postfix);
2170 }
2171
2172 #[allow(clippy::too_many_lines)]
2173 fn analyze_chain_to_location(
2174 &mut self,
2175 chain: &swamp_script_ast::PostfixChain,
2176 context: &TypeContext,
2177 location_side: LocationSide,
2178 ) -> Result<SingleLocationExpression, Error> {
2179 let mut items = Vec::new();
2180
2181 let nothing_context =
2182 TypeContext::new(None, None, TypeContextScope::ArgumentOrOutsideFunction);
2183
2184 let base_expr = self.analyze_expression(&chain.base, ¬hing_context)?;
2185 let ExpressionKind::VariableAccess(start_variable) = base_expr.kind else {
2186 return Err(self.create_err(ErrorKind::NotValidLocationStartingPoint, &chain.base.node));
2187 };
2188
2189 if !start_variable.is_mutable() {
2190 return Err(self.create_err(ErrorKind::VariableIsNotMutable, &chain.base.node));
2191 }
2192
2193 let mut ty = start_variable.resolved_type.clone();
2194 for (i, item) in chain.postfixes.iter().enumerate() {
2195 match &item {
2196 swamp_script_ast::Postfix::FieldAccess(field_name_node) => {
2197 let (struct_type_ref, index, return_type) =
2199 self.analyze_struct_field(field_name_node, ty)?;
2200 self.add_location_item(
2201 &mut items,
2202 LocationAccessKind::FieldIndex(struct_type_ref.clone(), index),
2203 return_type.clone(),
2204 field_name_node,
2205 );
2206
2207 ty = return_type.clone();
2208 }
2209 swamp_script_ast::Postfix::Subscript(lookup_expr) => {
2210 let is_range = if let swamp_script_ast::ExpressionKind::Range(min, max, mode) =
2211 &lookup_expr.kind
2212 {
2213 Some(self.analyze_range(min, max, mode)?)
2214 } else {
2215 None
2216 };
2217 match &ty {
2218 Type::String => {
2219 if let Some(range) = is_range {
2220 self.add_location_item(
2221 &mut items,
2222 LocationAccessKind::StringRange(range),
2223 Type::String,
2224 &lookup_expr.node,
2225 );
2226 } else {
2227 let index_expr_context = TypeContext::new_argument(&Type::Int);
2228 let index_expr =
2229 self.analyze_expression(lookup_expr, &index_expr_context)?; self.add_location_item(
2231 &mut items,
2232 LocationAccessKind::StringIndex(index_expr),
2233 Type::String,
2234 &lookup_expr.node,
2235 );
2236 }
2237 ty = Type::String;
2238 }
2239
2240 Type::Array(array_type) => {
2241 let int_argument_context = TypeContext::new_argument(&Type::Int);
2242 let index_expr =
2243 self.analyze_expression(lookup_expr, &int_argument_context)?; self.add_location_item(
2245 &mut items,
2246 LocationAccessKind::ArrayIndex(array_type.clone(), index_expr),
2247 array_type.item_type.clone(),
2248 &lookup_expr.node,
2249 );
2250 ty = array_type.item_type.clone();
2251 }
2252
2253 Type::Map(map_type) => {
2254 let key_type_argument_context =
2255 TypeContext::new_argument(&map_type.key_type);
2256 let key_expr =
2257 self.analyze_expression(lookup_expr, &key_type_argument_context)?;
2258 let is_last = i == chain.postfixes.len() - 1;
2259 let allow_auto_insert = is_last && location_side == LocationSide::Lhs;
2260 let (kind, lookup_type) = if allow_auto_insert {
2261 (
2264 LocationAccessKind::MapIndexInsertIfNonExisting(
2265 map_type.clone(),
2266 key_expr,
2267 ),
2268 map_type.value_type.clone(),
2269 )
2270 } else {
2271 let optional_value_type =
2272 Type::Optional(Box::from(map_type.value_type.clone()));
2273 (
2274 LocationAccessKind::MapIndex(map_type.clone(), key_expr),
2275 optional_value_type,
2276 )
2277 };
2278
2279 self.add_location_item(
2280 &mut items,
2281 kind,
2282 lookup_type.clone(),
2283 &lookup_expr.node,
2284 );
2285 ty = lookup_type;
2286 }
2287
2288 Type::Generic(collection_type, generic_params) => {
2289 if let Type::External(rust_type) = &**collection_type {
2290 let val_type = generic_params[0].clone();
2291 if rust_type.number == SPARSE_TYPE_ID {
2292 let sparse_id_type = self
2293 .shared
2294 .lookup_table
2295 .get_external_type("SparseId")
2296 .expect("should have SparseId");
2297
2298 let key_type = Type::External(sparse_id_type.clone());
2299 let key_type_context = TypeContext::new_argument(&key_type);
2300
2301 let key_expr =
2302 self.analyze_expression(lookup_expr, &key_type_context)?;
2303
2304 self.add_location_item(
2305 &mut items,
2306 LocationAccessKind::ExternalTypeIndex(
2307 rust_type.clone(),
2308 key_expr,
2309 ),
2310 key_type.clone(),
2311 &lookup_expr.node,
2312 );
2313
2314 ty = Type::Optional(Box::from(val_type.clone()));
2315 }
2316 }
2317 }
2318
2319 _ => {
2320 return Err(
2321 self.create_err(ErrorKind::IllegalIndexInChain, &lookup_expr.node)
2322 );
2323 }
2324 }
2325 }
2326
2327 swamp_script_ast::Postfix::MemberCall(node, _) => {
2328 return Err(self.create_err(ErrorKind::CallsCanNotBePartOfChain, node));
2329 }
2330
2331 swamp_script_ast::Postfix::FunctionCall(node, _) => {
2332 return Err(self.create_err(ErrorKind::CallsCanNotBePartOfChain, node));
2333 }
2334 swamp_script_ast::Postfix::OptionUnwrap(node) => {
2335 return Err(self.create_err(ErrorKind::UnwrapCanNotBePartOfChain, node));
2336 }
2337 swamp_script_ast::Postfix::NoneCoalesce(expr) => {
2338 return Err(
2339 self.create_err(ErrorKind::NoneCoalesceCanNotBePartOfChain, &expr.node)
2340 );
2341 }
2342 }
2343 }
2344
2345 if let Some(found_expected_type) = context.expected_type {
2346 if !ty.compatible_with(found_expected_type) {
2347 return Err(self.create_err(
2348 ErrorKind::IncompatibleTypes(ty, found_expected_type.clone()),
2349 &chain.base.node,
2350 ));
2351 }
2352 }
2353
2354 let location = SingleLocationExpression {
2355 kind: SingleLocationExpressionKind::MutVariableRef,
2356 node: self.to_node(&chain.base.node),
2357 ty: ty.clone(),
2358 starting_variable: start_variable,
2359 access_chain: items,
2360 };
2361 Ok(location)
2362 }
2363
2364 fn analyze_to_location(
2365 &mut self,
2366 expr: &swamp_script_ast::Expression,
2367 context: &TypeContext,
2368 location_type: LocationSide,
2369 ) -> Result<SingleLocationExpression, Error> {
2370 match &expr.kind {
2371 swamp_script_ast::ExpressionKind::PostfixChain(chain) => {
2372 self.analyze_chain_to_location(chain, context, location_type)
2373 }
2374 swamp_script_ast::ExpressionKind::IdentifierReference(variable) => {
2375 let var = self.find_variable(variable)?;
2376 if var.is_mutable() {
2377 Ok(SingleLocationExpression {
2378 kind: SingleLocationExpressionKind::MutVariableRef,
2379 node: self.to_node(&variable.name),
2380 ty: var.resolved_type.clone(),
2381 starting_variable: var,
2382 access_chain: vec![],
2383 })
2384 } else {
2385 Err(self.create_err(ErrorKind::VariableIsNotMutable, &expr.node))
2386 }
2387 }
2388 _ => Err(self.create_err(ErrorKind::NotValidLocationStartingPoint, &expr.node)),
2389 }
2390 }
2391
2392 #[allow(clippy::single_match)]
2393 fn check_special_assignment_compound(
2394 &mut self,
2395 target_expression: &swamp_script_ast::Expression,
2396 target_type: &Type,
2397 op: &CompoundOperatorKind,
2398 source: &swamp_script_ast::Expression,
2399 source_type: &Type,
2400 ) -> Result<Option<ExpressionKind>, Error> {
2401 match &target_type {
2402 Type::Array(array_type) => {
2403 let target_type_context = TypeContext::new_argument(target_type);
2404 let source_type_context = TypeContext::new_argument(source_type);
2405 if *op == CompoundOperatorKind::Add
2406 && source_type.compatible_with(&array_type.item_type)
2407 {
2408 let target_location = SingleMutLocationExpression(self.analyze_to_location(
2410 target_expression,
2411 &target_type_context,
2412 LocationSide::Rhs,
2413 )?);
2414 let resolved_source = self.analyze_expression(source, &source_type_context)?;
2415 return Ok(Option::from(ExpressionKind::IntrinsicCallMut(
2416 IntrinsicFunction::VecSelfPush,
2417 target_location,
2418 vec![resolved_source],
2419 )));
2420 } else if *op == CompoundOperatorKind::Add
2421 && source_type.compatible_with(target_type)
2422 {
2423 let target_location = SingleMutLocationExpression(self.analyze_to_location(
2425 target_expression,
2426 &target_type_context,
2427 LocationSide::Rhs,
2428 )?);
2429 let resolved_source = self.analyze_expression(source, &source_type_context)?;
2430 return Ok(Option::from(ExpressionKind::IntrinsicCallMut(
2431 IntrinsicFunction::VecSelfExtend,
2432 target_location,
2433 vec![resolved_source],
2434 )));
2435 }
2436 }
2437 _ => {}
2438 }
2439
2440 Ok(None)
2441 }
2442
2443 fn analyze_assignment_compound(
2444 &mut self,
2445 target_expression: &swamp_script_ast::Expression,
2446 ast_op: &swamp_script_ast::CompoundOperator,
2447 ast_source_expression: &swamp_script_ast::Expression,
2448 ) -> Result<Expression, Error> {
2449 let resolved_op = self.analyze_compound_operator(ast_op);
2450 let any_argument_context = TypeContext::new_anything_argument();
2451 let source_expr = self.analyze_expression(ast_source_expression, &any_argument_context)?;
2452 let source_expr_type_context = TypeContext::new_argument(&source_expr.ty);
2453
2454 let resolved_location = SingleMutLocationExpression(self.analyze_to_location(
2455 target_expression,
2456 &source_expr_type_context,
2457 LocationSide::Rhs,
2458 )?);
2459
2460 let kind = if let Some(found_special) = self.check_special_assignment_compound(
2461 target_expression,
2462 &resolved_location.0.ty,
2463 &resolved_op.kind,
2464 ast_source_expression,
2465 &source_expr.ty,
2466 )? {
2467 found_special
2468 } else {
2469 ExpressionKind::CompoundAssignment(
2470 resolved_location,
2471 resolved_op.kind,
2472 Box::from(source_expr),
2473 )
2474 };
2475
2476 let expr = self.create_expr(kind, Type::Unit, &target_expression.node);
2477
2478 Ok(expr)
2479 }
2480
2481 fn analyze_assignment(
2482 &mut self,
2483 target_location: &swamp_script_ast::Expression,
2484 ast_source_expression: &swamp_script_ast::Expression,
2485 ) -> Result<Expression, Error> {
2486 let any_argument_context = TypeContext::new_anything_argument();
2487 let resolved_location =
2488 self.analyze_to_location(target_location, &any_argument_context, LocationSide::Lhs)?;
2489
2490 let ty = resolved_location.ty.clone();
2491 if ty == Type::Unit {
2492 error!(?ast_source_expression, "unit problem");
2493 }
2494
2495 let lhs_argument_context = TypeContext::new_argument(&ty);
2496 let source_expr = self.analyze_expression(ast_source_expression, &lhs_argument_context)?;
2497
2498 let mut_location = SingleMutLocationExpression(resolved_location);
2499
2500 let kind = ExpressionKind::Assignment(Box::from(mut_location), Box::from(source_expr));
2501
2502 let expr = self.create_expr(kind, Type::Unit, &target_location.node); Ok(expr)
2505 }
2506
2507 #[must_use]
2508 pub fn create_mut_single_location_expr(
2509 &self,
2510 kind: SingleLocationExpressionKind,
2511 ty: Type,
2512 ast_node: &swamp_script_ast::Node,
2513 ) -> SingleMutLocationExpression {
2514 SingleMutLocationExpression(SingleLocationExpression {
2515 kind,
2516 ty,
2517 starting_variable: Rc::new(Variable {
2518 name: Node::default(),
2519 resolved_type: Type::Int,
2520 mutable_node: None,
2521 scope_index: 0,
2522 variable_index: 0,
2523 }),
2524 node: self.to_node(ast_node),
2525 access_chain: vec![],
2526 })
2527 }
2528
2529 #[must_use]
2530 pub fn create_single_location_expr(
2531 &self,
2532 kind: SingleLocationExpressionKind,
2533 ty: Type,
2534 ast_node: &swamp_script_ast::Node,
2535 ) -> SingleLocationExpression {
2536 SingleLocationExpression {
2537 kind,
2538 ty,
2539 starting_variable: Rc::new(Variable {
2540 name: Node::default(),
2541 resolved_type: Type::Int,
2542 mutable_node: None,
2543 scope_index: 0,
2544 variable_index: 0,
2545 }),
2546 node: self.to_node(ast_node),
2547 access_chain: vec![],
2548 }
2549 }
2550
2551 #[must_use]
2552 pub fn create_single_location_expr_resolved(
2553 &self,
2554 kind: SingleLocationExpressionKind,
2555 ty: Type,
2556 node: &Node,
2557 ) -> SingleLocationExpression {
2558 SingleLocationExpression {
2559 kind,
2560 ty,
2561 starting_variable: Rc::new(Variable {
2562 name: Node::default(),
2563 resolved_type: Type::Int,
2564 mutable_node: None,
2565 scope_index: 0,
2566 variable_index: 0,
2567 }),
2568 node: node.clone(),
2569 access_chain: vec![],
2570 }
2571 }
2572 #[must_use]
2573 pub fn create_mut_single_location_expr_resolved(
2574 &self,
2575 kind: SingleLocationExpressionKind,
2576 ty: Type,
2577 node: &Node,
2578 ) -> SingleMutLocationExpression {
2579 SingleMutLocationExpression(SingleLocationExpression {
2580 kind,
2581 ty,
2582 starting_variable: Rc::new(Variable {
2583 name: Node::default(),
2584 resolved_type: Type::Int,
2585 mutable_node: None,
2586 scope_index: 0,
2587 variable_index: 0,
2588 }),
2589 node: node.clone(),
2590 access_chain: vec![],
2591 })
2592 }
2593
2594 #[must_use]
2595 pub const fn create_expr(
2596 &self,
2597 kind: ExpressionKind,
2598 ty: Type,
2599 ast_node: &swamp_script_ast::Node,
2600 ) -> Expression {
2601 Expression {
2603 kind,
2604 ty,
2605 node: self.to_node(ast_node),
2606 }
2607 }
2608
2609 #[must_use]
2610 pub fn create_expr_resolved(
2611 &self,
2612 kind: ExpressionKind,
2613 ty: Type,
2614 ast_node: &Node,
2615 ) -> Expression {
2616 Expression {
2617 kind,
2618 ty,
2619 node: ast_node.clone(),
2620 }
2621 }
2622
2623 fn analyze_destructuring(
2624 &mut self,
2625 node: &swamp_script_ast::Node,
2626 target_ast_variables: &[swamp_script_ast::Variable],
2627 tuple_expression: &swamp_script_ast::Expression,
2628 ) -> Result<Expression, Error> {
2629 let any_context = TypeContext::new_anything_argument();
2630 let tuple_resolved = self.analyze_expression(tuple_expression, &any_context)?;
2631 let tuple_expr_type = &tuple_resolved.ty;
2632
2633 let mut variable_refs = Vec::new();
2634 if let Type::Tuple(tuple) = tuple_expr_type.clone() {
2635 if target_ast_variables.len() > tuple.0.len() {
2636 return Err(self.create_err(ErrorKind::TooManyDestructureVariables, node));
2637 }
2638 for (variable_ref, tuple_type) in target_ast_variables.iter().zip(tuple.0.clone()) {
2639 let (variable_ref, _is_reassignment) =
2640 self.set_or_overwrite_variable_with_type(variable_ref, &tuple_type)?;
2641 variable_refs.push(variable_ref);
2642 }
2643 let expr_kind =
2644 ExpressionKind::TupleDestructuring(variable_refs, tuple, Box::from(tuple_resolved));
2645
2646 Ok(self.create_expr(expr_kind, Type::Unit, node))
2647 } else {
2648 Err(self.create_err(ErrorKind::CanNotDestructure, node))
2649 }
2650 }
2651
2652 fn analyze_postfix_member_func_call(
2653 &mut self,
2654 resolved_node: &Node,
2655 found_function: &FunctionRef,
2656 struct_type: &StructTypeRef,
2657 is_mutable: bool,
2658 arguments: &[swamp_script_ast::MutableOrImmutableExpression],
2659 ) -> Result<Postfix, Error> {
2660 let signature = found_function.signature();
2661
2662 let self_type = &signature.parameters[0];
2663 if !self_type
2664 .resolved_type
2665 .compatible_with(&Type::NamedStruct(struct_type.clone()))
2666 || self_type.is_mutable && !is_mutable
2667 {
2668 return Err(self.create_err_resolved(ErrorKind::SelfNotCorrectType, resolved_node));
2669 }
2670
2671 let resolved_arguments = self.analyze_and_verify_parameters(
2672 resolved_node,
2673 &signature.parameters[1..],
2674 arguments,
2675 )?;
2676
2677 let kind = PostfixKind::MemberCall(found_function.clone(), resolved_arguments);
2678 let postfix = Postfix {
2679 node: resolved_node.clone(),
2680 ty: *signature.return_type.clone(),
2681 kind,
2682 };
2683
2684 Ok(postfix)
2685 }
2686
2687 fn analyze_postfix_field_call(
2688 &mut self,
2689 resolved_node: &Node,
2690 struct_type: &StructTypeRef,
2691 field: &StructTypeField,
2692 index: usize,
2693 signature: &Signature,
2694 arguments: &[swamp_script_ast::MutableOrImmutableExpression],
2695 ) -> Result<Vec<Postfix>, Error> {
2696 let mut suffixes = Vec::new();
2697 let struct_field_kind =
2699 PostfixKind::StructField(struct_type.borrow().anon_struct_type.clone(), index);
2700
2701 let struct_field_postfix = Postfix {
2702 node: resolved_node.clone(),
2703 ty: field.field_type.clone(),
2704 kind: struct_field_kind,
2705 };
2706
2707 suffixes.push(struct_field_postfix);
2708
2709 let resolved_arguments =
2710 self.analyze_and_verify_parameters(resolved_node, &signature.parameters, arguments)?;
2711
2712 let call_kind = PostfixKind::FunctionCall(resolved_arguments);
2713
2714 let call_postfix = Postfix {
2715 node: resolved_node.clone(),
2716 ty: *signature.return_type.clone(),
2717 kind: call_kind,
2718 };
2719 suffixes.push(call_postfix);
2720
2721 Ok(suffixes)
2722 }
2723
2724 fn analyze_postfix_member_call(
2725 &mut self,
2726 struct_type: &StructTypeRef,
2727 is_mutable: bool,
2728 member_name: &swamp_script_ast::Node,
2729 arguments: &[swamp_script_ast::MutableOrImmutableExpression],
2730 suffixes: &mut Vec<Postfix>,
2731 ) -> Result<Type, Error> {
2732 let field_name_str = self.get_text(member_name).to_string();
2733
2734 let resolved_node = self.to_node(member_name);
2735 let binding = struct_type.borrow();
2736 let postfixes = match binding.functions.get(&field_name_str) {
2737 Some(found_function_member) => {
2738 let postfix = self.analyze_postfix_member_func_call(
2739 &resolved_node,
2740 found_function_member,
2741 struct_type,
2742 is_mutable,
2743 arguments,
2744 )?;
2745 vec![postfix]
2746 }
2747 _ => match binding
2748 .anon_struct_type
2749 .field_name_sorted_fields
2750 .get(&field_name_str)
2751 {
2752 Some(found_field) => {
2753 if let Type::Function(signature) = &found_field.field_type {
2754 let index = binding
2755 .anon_struct_type
2756 .field_name_sorted_fields
2757 .get_index(&field_name_str)
2758 .expect("should work");
2759 self.analyze_postfix_field_call(
2760 &resolved_node,
2761 struct_type,
2762 found_field,
2763 index,
2764 signature,
2765 arguments,
2766 )?
2767 } else {
2768 return Err(
2769 self.create_err(ErrorKind::NotValidLocationStartingPoint, member_name)
2770 );
2771 }
2772 }
2773 _ => {
2774 return Err(
2775 self.create_err(ErrorKind::NotValidLocationStartingPoint, member_name)
2776 );
2777 }
2778 },
2779 };
2780
2781 let last_type = postfixes.last().unwrap().ty.clone();
2782 suffixes.extend(postfixes);
2783
2784 Ok(last_type)
2785 }
2786
2787 fn analyze_break(
2803 &self,
2804 context: &TypeContext,
2805 node: &swamp_script_ast::Node,
2806 ) -> Result<Expression, Error> {
2807 if !context.allows_break() {
2808 return Err(self.create_err(ErrorKind::BreakOutsideLoop, node));
2809 }
2810
2811 Ok(Expression {
2812 kind: ExpressionKind::Break,
2813 ty: Type::Never,
2814 node: self.to_node(node),
2815 })
2816 }
2817
2818 fn analyze_return(
2819 &mut self,
2820 context: &TypeContext,
2821 optional_expression: Option<&swamp_script_ast::Expression>,
2822 node: &swamp_script_ast::Node,
2823 ) -> Result<Expression, Error> {
2824 if !context.allows_return() {
2825 return Err(self.create_err(ErrorKind::ReturnOutsideCompare, node));
2826 }
2827
2828 let return_context = context.for_return();
2829 let inner = if let Some(expr) = optional_expression {
2830 Some(Box::new(self.analyze_expression(expr, &return_context)?))
2831 } else {
2832 None
2834 };
2835
2836 Ok(self.create_expr(ExpressionKind::Return(inner), Type::Never, node))
2837 }
2838
2839 fn analyze_continue(
2840 &self,
2841 context: &TypeContext,
2842 node: &swamp_script_ast::Node,
2843 ) -> Result<Expression, Error> {
2844 if !context.allows_continue() {
2845 return Err(self.create_err(ErrorKind::ContinueOutsideLoop, node));
2846 }
2847 Ok(self.create_expr(ExpressionKind::Continue, Type::Never, node))
2848 }
2849
2850 fn coerce_expression(
2851 &self,
2852 expr: Expression,
2853 expected_type: &Type,
2854 encountered_type: &Type,
2855 node: &swamp_script_ast::Node,
2856 ) -> Result<Expression, Error> {
2857 if !matches!(encountered_type, Type::Optional(_)) {
2858 if let Type::Optional(expected_inner_type) = expected_type {
2860 if encountered_type.compatible_with(expected_inner_type) {
2861 let wrapped = self.create_expr(
2862 ExpressionKind::Option(Option::from(Box::new(expr))),
2863 expected_type.clone(),
2864 node,
2865 );
2866 return Ok(wrapped);
2867 }
2868 }
2869 } else if matches!(expected_type, &Type::Bool) {
2870 if let Type::Optional(_inner_type) = encountered_type {
2871 let wrapped = self.create_expr(
2872 ExpressionKind::CoerceOptionToBool(Box::from(expr)),
2873 Type::Bool,
2874 node,
2875 );
2876 return Ok(wrapped);
2877 }
2878 }
2879
2880 error!(?expr, "expr");
2881 error!(?expected_type, ?encountered_type, "incompatible types");
2882
2883 Err(self.create_err(
2884 ErrorKind::IncompatibleTypes(expected_type.clone(), encountered_type.clone()),
2885 node,
2886 ))
2887 }
2888}