swamp_script_analyzer/
variable.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/script
 * Licensed under the MIT License. See LICENSE in the project root for license information.
 */

use crate::err::ResolveError;
use crate::{BlockScopeMode, Resolver};
use std::rc::Rc;
use swamp_script_ast::{CompoundOperator, Expression, Node, Variable};
use swamp_script_semantic::{
    ResolvedCompoundOperatorKind, ResolvedExpression, ResolvedNode, ResolvedType, ResolvedVariable,
    ResolvedVariableAssignment, ResolvedVariableCompoundAssignment, ResolvedVariableRef, Spanned,
};

impl<'a> Resolver<'a> {
    fn try_find_local_variable(&self, node: &ResolvedNode) -> Option<&ResolvedVariableRef> {
        let current_scope = self
            .scope
            .block_scope_stack
            .iter()
            .last()
            .expect("no scope stack available");

        let variable_text = self.get_text_resolved(node).to_string();

        current_scope.variables.get(&variable_text)
    }
    #[allow(unused)]
    pub(crate) fn find_variable(
        &self,
        variable: &Variable,
    ) -> Result<ResolvedVariableRef, ResolveError> {
        self.try_find_variable(&variable.name).map_or_else(
            || Err(ResolveError::UnknownVariable(self.to_node(&variable.name))),
            Ok,
        )
    }

    pub(crate) fn find_variable_from_node(
        &self,
        node: &Node,
    ) -> Result<ResolvedVariableRef, ResolveError> {
        self.try_find_variable(node).map_or_else(
            || Err(ResolveError::UnknownVariable(self.to_node(node))),
            Ok,
        )
    }

    pub(crate) fn try_find_variable(&self, node: &Node) -> Option<ResolvedVariableRef> {
        let variable_text = self.get_text(node);

        for scope in self.scope.block_scope_stack.iter().rev() {
            if let Some(value) = scope.variables.get(&variable_text.to_string()) {
                return Some(value.clone());
            }
            if scope.mode == BlockScopeMode::Closed {
                break;
            }
        }

        None
    }

    fn set_or_overwrite_variable_with_type(
        &mut self,
        variable: &Variable,
        variable_type_ref: &ResolvedType,
    ) -> Result<(ResolvedVariableRef, bool), ResolveError> {
        if let Some(existing_variable) = self.try_find_variable(&variable.name) {
            // Check type compatibility
            if !&existing_variable.resolved_type.same_type(variable_type_ref) {
                return Err(ResolveError::OverwriteVariableWithAnotherType(
                    self.to_node(&variable.name),
                ));
            }

            // For reassignment, check if the EXISTING variable is mutable
            if !existing_variable.is_mutable() {
                return Err(ResolveError::CanOnlyOverwriteVariableWithMut(
                    self.to_node(&variable.name),
                ));
            }

            return Ok((existing_variable, true));
        }

        // For first assignment, create new variable with the mutability from the assignment
        let scope_index = self.scope.block_scope_stack.len() - 1;
        let name = self.to_node(&variable.name);
        let mutable_node = self.to_node_option(&variable.is_mutable);
        let variable_name_str = self.get_text_resolved(&name).to_string();

        let variables = &mut self
            .scope
            .block_scope_stack
            .last_mut()
            .expect("block scope should have at least one scope")
            .variables;
        let variable_index = variables.len();

        let resolved_variable = ResolvedVariable {
            name,
            resolved_type: variable_type_ref.clone(),
            mutable_node,
            scope_index,
            variable_index,
        };

        let variable_ref = Rc::new(resolved_variable);

        {
            variables
                .insert(variable_name_str, variable_ref.clone())
                .expect("should have checked earlier for variable");
        }

        Ok((variable_ref, false))
    }

    pub(crate) fn create_local_variable(
        &mut self,
        variable: &Node,
        is_mutable: &Option<Node>,
        variable_type_ref: &ResolvedType,
    ) -> Result<ResolvedVariableRef, ResolveError> {
        self.create_local_variable_resolved(
            &self.to_node(variable),
            &self.to_node_option(is_mutable),
            variable_type_ref,
        )
    }

    pub(crate) fn create_local_variable_resolved(
        &mut self,
        variable: &ResolvedNode,
        is_mutable: &Option<ResolvedNode>,
        variable_type_ref: &ResolvedType,
    ) -> Result<ResolvedVariableRef, ResolveError> {
        if let Some(_existing_variable) = self.try_find_local_variable(variable) {
            return Err(ResolveError::OverwriteVariableNotAllowedHere(
                variable.clone(),
            ));
        }
        let variable_str = self.get_text_resolved(variable).to_string();

        let scope_index = self.scope.block_scope_stack.len() - 1;

        let variables = &mut self
            .scope
            .block_scope_stack
            .last_mut()
            .expect("block scope should have at least one scope")
            .variables;

        let resolved_variable = ResolvedVariable {
            name: variable.clone(),
            resolved_type: variable_type_ref.clone(),
            mutable_node: is_mutable.clone(),
            scope_index,
            variable_index: variables.len(),
        };

        let variable_ref = Rc::new(resolved_variable);

        variables
            .insert(variable_str, variable_ref.clone())
            .expect("should have checked earlier for variable");

        Ok(variable_ref)
    }

    pub(crate) fn create_local_variable_generated(
        &mut self,
        variable_str: &str,
        is_mutable: bool,
        variable_type_ref: &ResolvedType,
    ) -> Result<ResolvedVariableRef, ResolveError> {
        /*


        if let Some(_existing_variable) = self.try_find_local_variable(variable) {
            return Err(ResolveError::OverwriteVariableNotAllowedHere(
                variable.clone(),
            ));
        }
        let variable_str = self.get_text_resolved(variable).to_string();

         */

        let scope_index = self.scope.block_scope_stack.len() - 1;

        let variables = &mut self
            .scope
            .block_scope_stack
            .last_mut()
            .expect("block scope should have at least one scope")
            .variables;

        let resolved_variable = ResolvedVariable {
            name: ResolvedNode::default(),
            resolved_type: variable_type_ref.clone(),
            mutable_node: if is_mutable {
                Some(ResolvedNode::default())
            } else {
                None
            },
            scope_index,
            variable_index: variables.len(),
        };

        let variable_ref = Rc::new(resolved_variable);

        variables
            .insert(variable_str.to_string(), variable_ref.clone())
            .expect("should have checked earlier for variable");

        Ok(variable_ref)
    }

    pub(crate) fn resolve_compound_assignment_variable(
        &mut self,
        target: &Node,
        operator: &CompoundOperator,
        source: &Expression,
    ) -> Result<ResolvedExpression, ResolveError> {
        let resolved_variable = self.find_variable_from_node(target)?;
        let resolved_source = self.resolve_expression(source)?;
        let source_type = resolved_source.resolution();

        let target_type = &resolved_variable.resolved_type;

        let resolved_compound_operator = self.resolve_compound_operator(operator);

        match &target_type {
            ResolvedType::Int => {
                if source_type != ResolvedType::Int {
                    return Err(ResolveError::IncompatibleTypes(
                        resolved_compound_operator.node.span().clone(),
                        source_type,
                    ));
                }
                let compound_assignment = ResolvedVariableCompoundAssignment {
                    variable_ref: resolved_variable,
                    expression: Box::from(resolved_source),
                    compound_operator: resolved_compound_operator,
                };
                Ok(ResolvedExpression::VariableCompoundAssignment(
                    compound_assignment,
                ))
            }
            ResolvedType::Array(array_type_ref) => {
                match resolved_compound_operator.kind {
                    ResolvedCompoundOperatorKind::Add => {
                        let source_type = resolved_source.resolution();
                        if let ResolvedType::Array(_source_array_type) = &source_type {
                            // Concatenating two arrays
                            if !target_type.same_type(&source_type) {
                                return Err(ResolveError::IncompatibleTypes(
                                    resolved_source.span(),
                                    target_type.clone(),
                                ));
                            }
                            Ok(ResolvedExpression::ArrayExtend(
                                resolved_variable,
                                Box::new(resolved_source),
                            ))
                        } else {
                            // Appending a single item
                            if !source_type.same_type(&array_type_ref.item_type) {
                                return Err(ResolveError::IncompatibleTypes(
                                    resolved_source.span(),
                                    target_type.clone(),
                                ));
                            }
                            Ok(ResolvedExpression::ArrayPush(
                                resolved_variable,
                                Box::new(resolved_source),
                            ))
                        }
                    }
                    _ => Err(ResolveError::InvalidOperatorForArray(
                        self.to_node(&operator.node),
                    )),
                }
            }
            _ => Err(ResolveError::ExpectedArray(target_type.clone())),
        }
    }

    pub(crate) fn resolve_variable_assignment(
        &mut self,
        ast_variable: &Variable,
        ast_expression: &Expression,
    ) -> Result<ResolvedExpression, ResolveError> {
        let converted_expression = self.resolve_expression(ast_expression)?;
        let expression_type = converted_expression.resolution();
        let (variable_ref, is_reassignment) =
            self.set_or_overwrite_variable_with_type(ast_variable, &expression_type)?;

        let assignment = ResolvedVariableAssignment {
            variable_refs: vec![variable_ref],
            expression: Box::from(converted_expression),
        };

        if is_reassignment {
            Ok(ResolvedExpression::ReassignVariable(assignment))
        } else {
            Ok(ResolvedExpression::InitializeVariable(assignment))
        }
    }

    pub(crate) fn resolve_variable_assignment_resolved(
        &mut self,
        ast_variable: &Variable,
        converted_expression: ResolvedExpression,
    ) -> Result<ResolvedExpression, ResolveError> {
        let expression_type = converted_expression.resolution();
        let (variable_ref, is_reassignment) =
            self.set_or_overwrite_variable_with_type(ast_variable, &expression_type)?;

        let assignment = ResolvedVariableAssignment {
            variable_refs: vec![variable_ref],
            expression: Box::from(converted_expression),
        };

        if is_reassignment {
            Ok(ResolvedExpression::ReassignVariable(assignment))
        } else {
            Ok(ResolvedExpression::InitializeVariable(assignment))
        }
    }

    pub(crate) fn resolve_multi_variable_assignment(
        &mut self,
        ast_variables: &[Variable],
        ast_expression: &Expression,
    ) -> Result<ResolvedExpression, ResolveError> {
        let converted_expression = self.resolve_expression(ast_expression)?;
        let expression_type = converted_expression.resolution();

        let mut variable_refs = Vec::new();
        let mut all_reassignment = true;

        if ast_variables.len() > 1 {
            if let ResolvedType::Tuple(tuple) = expression_type {
                if ast_variables.len() > tuple.0.len() {
                    return Err(ResolveError::TooManyDestructureVariables);
                }
                for (variable_ref, tuple_type) in ast_variables.iter().zip(tuple.0.clone()) {
                    let (variable_ref, _is_reassignment) =
                        self.set_or_overwrite_variable_with_type(&variable_ref, &tuple_type)?;
                    variable_refs.push(variable_ref);
                }
                return Ok(ResolvedExpression::TupleDestructuring(
                    variable_refs,
                    tuple,
                    Box::from(converted_expression),
                ));
            } else {
                return Err(ResolveError::CanNotDestructure(
                    self.to_node(&ast_variables[0].name).span,
                ));
            }
        } else {
            let ast_variable = &ast_variables[0];
            let (variable_ref, is_reassignment) =
                self.set_or_overwrite_variable_with_type(&ast_variable, &expression_type)?;
            variable_refs.push(variable_ref);
            if !is_reassignment {
                all_reassignment = false;
            }
        }

        let assignment = ResolvedVariableAssignment {
            variable_refs,
            expression: Box::from(converted_expression),
        };

        if all_reassignment {
            Ok(ResolvedExpression::ReassignVariable(assignment))
        } else {
            Ok(ResolvedExpression::InitializeVariable(assignment))
        }
    }
}