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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use super::{Evaluator, FlowControl, Scope, ScopeKind};
use crate::{
ast::utils::Value,
ast::source::*,
error::{NbclError, Result, Span},
};
impl Evaluator {
pub(crate) fn execute_stmt(&mut self, stmt: &Stmt) -> Result<Value> {
if let FlowControl::Return(val) = &self.flow {
return Ok(val.clone());
}
let result = match stmt {
Stmt::Expr(expr) => {
// Standalone expressions are evaluated and discarded
self.eval_expr(&expr)?
}
Stmt::Return(maybe_rt, span) => {
// Ensure that we cant return at:
// TopLevel or a Block child of TopLevel
let is_at_root = match self.scopes.as_slice() {
[root] if root.kind == ScopeKind::TopLevel => true,
[root, current]
if root.kind == ScopeKind::TopLevel && current.kind == ScopeKind::Block =>
{
true
}
_ => false,
};
if is_at_root {
return Err(NbclError::Runtime {
message: "cannot return from the top level".to_string(),
hint: Some("Move this logic into a function or component if you need early returns.".to_string()),
span: Some(span.clone()),
});
}
let val = match maybe_rt {
Some(ReturnType::Node(n)) => {
let resolved_nodes = self.resolve_node(n.clone())?;
Value::Nodes(resolved_nodes)
},
Some(ReturnType::Expr(e)) => self.eval_expr(&e)?,
None => Value::Null,
};
self.flow = FlowControl::Return(val.clone());
val
}
// TODO: Use typehint in global and local
Stmt::Global(name, _type_hint, expr) => {
let val = self.eval_expr(&expr)?;
// A 'global' always goes into the very first scope (index 0),
// regardless of how many components or blocks deep we are.
if let Some(global_scope) = self.scopes.first_mut() {
global_scope.variables.insert(name.to_string(), val);
} else {
// Fallback: if somehow scopes is empty (shouldn't happen),
// create a new one.
let mut map = Scope::new(ScopeKind::TopLevel);
map.variables.insert(name.to_string(), val);
self.scopes.push(map);
}
Value::Null
}
Stmt::Local(name, _type_hint, expr) => {
let val = self.eval_expr(&expr)?;
if let Some(current_scope) = self.scopes.last_mut() {
current_scope.variables.insert(name.to_string(), val);
}
Value::Null
}
Stmt::Assign(lhs, assign_op, rhs_expr, span) => {
let new_val = self.eval_expr(&rhs_expr)?;
match &lhs.kind {
ExprKind::Variable(name) => {
let mut found = false;
for scope in self.scopes.iter_mut().rev() {
if let Some(val_ref) = scope.variables.get_mut(name) {
let updated = Self::apply_assign_op(
val_ref.clone(),
&assign_op,
new_val,
Some(span),
)?;
*val_ref = updated;
found = true;
break;
}
}
if !found {
let candidates = self.scopes.iter().flat_map(|s| s.variables.keys());
let suggestion = crate::utils::find_best_match(&name, candidates);
let hint = suggestion.map(|s| format!("Did you mean \"{}\"?", s));
return Err(NbclError::Runtime {
message: format!("variable '{}' doesn't exist", name),
hint,
span: Some(span.clone()),
});
}
}
ExprKind::Field(base, field_name, _is_safe) => {
let mut target_map = self.eval_expr(&base)?;
if let Value::Map(ref mut entries) = target_map {
if let Some(pos) = entries.iter().position(|(k, _)| k == field_name) {
let old_val = entries[pos].1.clone();
entries[pos].1 = Self::apply_assign_op(
old_val,
&assign_op,
new_val,
Some(&span),
)?;
} else {
if assign_op == &AssignOp::Equal {
entries.push((field_name.clone(), new_val));
} else {
return Err(NbclError::Runtime {
message: format!(
"cannot update field '{}' that doesn't exist",
field_name
),
span: Some(span.clone()),
hint: None,
});
}
}
self.reassign_to_lhs(&base, target_map)?;
} else {
return Err(NbclError::Runtime {
message: "cannot set field on non-map".into(),
span: Some(span.clone()),
hint: None,
});
}
}
ExprKind::Index(base, index_expr) => {
let mut target_coll = self.eval_expr(&base)?;
let index_val = self.eval_expr(&index_expr)?;
match (&mut target_coll, index_val) {
(Value::List(items), Value::Int(i)) => {
let idx = i as usize;
if idx < items.len() {
let old_val = items[idx].clone();
items[idx] = Self::apply_assign_op(
old_val,
&assign_op,
new_val,
Some(&span),
)?;
self.reassign_to_lhs(&base, target_coll)?;
} else {
return Err(NbclError::Runtime {
message: format!("index {} out of bounds", i),
span: Some(span.clone()),
hint: None,
});
}
}
_ => {
return Err(NbclError::Runtime {
message: "invalid index operation".into(),
span: Some(span.clone()),
hint: None,
});
}
}
}
_ => {
return Err(NbclError::Runtime {
message: "invalid assignment target".into(),
span: Some(span.clone()),
hint: None,
});
}
}
Value::Null
}
Stmt::For(patterns, iter_expr, body) => {
let iter_val = self.eval_expr(&iter_expr)?;
match iter_val {
Value::Range(start, end) => {
let mut loop_scope = Scope::new(ScopeKind::Block);
// Optimization:
// Create dummy patterns and then only modify
// the value in the loop to avoid allocations.
for pattern in patterns {
loop_scope.variables.insert(pattern.clone(), Value::Null);
}
self.scopes.push(loop_scope);
let scope_idx = self.scopes.len() - 1;
for i in start..end {
if let FlowControl::Return(_) = self.flow {
break;
}
if patterns.len() == 1 {
if let Some(val) =
self.scopes[scope_idx].variables.get_mut(&patterns[0])
{
*val = Value::Int(i);
}
} else if patterns.len() == 2 {
if let Some(val1) =
self.scopes[scope_idx].variables.get_mut(&patterns[0])
{
*val1 = Value::Int(i);
}
if let Some(val2) =
self.scopes[scope_idx].variables.get_mut(&patterns[1])
{
*val2 = Value::Int(i);
}
}
self.execute_block_internal(&body)?;
if let FlowControl::Return(_) = self.flow {
break;
}
}
self.scopes.pop();
}
Value::List(items) => {
let loop_scope = Scope::new(ScopeKind::Block);
self.scopes.push(loop_scope);
let scope_idx = self.scopes.len() - 1;
for (i, item) in items.into_iter().enumerate() {
if let FlowControl::Return(_) = self.flow {
break;
}
// Handle pattern matching (len 1 or len 2)
if patterns.len() == 1 {
self.scopes[scope_idx].variables.insert(patterns[0].clone(), item);
} else if patterns.len() == 2 {
self.scopes[scope_idx]
.variables
.insert(patterns[0].clone(), Value::Int(i as i64));
self.scopes[scope_idx].variables.insert(patterns[1].clone(), item);
}
// Execute the block logic
self.execute_block_internal(&body)?;
if let FlowControl::Return(_) = self.flow {
break;
}
}
self.scopes.pop();
}
// unreachable
_ => {}
}
Value::Null
}
Stmt::While(condition_expr, body) => {
self.scopes.push(Scope::new(ScopeKind::Block));
// Keep looping as long as the condition evaluates to truthy
// and we haven't hit a Return statement.
while self.eval_expr(&condition_expr)?.is_truthy() {
if let FlowControl::Return(_) = self.flow {
break;
}
// Execute the block logic
self.execute_block_internal(&body)?;
if let FlowControl::Return(_) = self.flow {
break;
}
}
self.scopes.pop();
Value::Null
}
};
Ok(result)
}
/// Executes the statements in a block and evaluates the terminator if present.
fn execute_block_internal(&mut self, block: &Block) -> Result<Value> {
// Run all statements
for s in &block.stmts {
self.execute_stmt(s)?;
if let FlowControl::Return(_) = self.flow {
return Ok(Value::Null);
}
}
// Evaluate the implicit return (terminator) if it exists
if let Some(expr) = &block.terminator {
let val = self.eval_expr(expr)?;
return Ok(val);
}
Ok(Value::Null)
}
fn reassign_to_lhs(&mut self, lhs: &Expr, value: Value) -> Result<()> {
match &lhs.kind {
ExprKind::Variable(name) => {
for scope in self.scopes.iter_mut().rev() {
if let Some(val_ref) = scope.variables.get_mut(name) {
*val_ref = value;
return Ok(());
}
}
Err(NbclError::Runtime {
message: "Variable lost during assignment".into(),
hint: None,
span: None,
})
}
ExprKind::Field(base, field, _) => {
let mut parent = self.eval_expr(&base)?;
if let Value::Map(ref mut entries) = parent {
if let Some(pos) = entries.iter().position(|(k, _)| k == field) {
entries[pos].1 = value;
} else {
entries.push((field.clone(), value));
}
self.reassign_to_lhs(&base, parent)
} else {
Ok(())
}
}
ExprKind::Index(base, index_expr) => {
let mut parent = self.eval_expr(&base)?;
let idx_val = self.eval_expr(&index_expr)?;
if let (Value::List(items), Value::Int(i)) = (&mut parent, idx_val) {
let idx = i as usize;
if idx < items.len() {
items[idx] = value;
self.reassign_to_lhs(&base, parent)?;
}
}
Ok(())
}
_ => Ok(()),
}
}
fn apply_assign_op(
current: Value,
op: &AssignOp,
rhs: Value,
span: Option<&Span>,
) -> Result<Value> {
match op {
AssignOp::Equal => Ok(rhs),
AssignOp::PlusEqual => match (current, rhs) {
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a + b)),
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a + b)),
(Value::Str(mut a), Value::Str(b)) => {
a.push_str(&b);
Ok(Value::Str(a))
}
_ => Err(NbclError::Runtime {
message: "type mismatch in '+=' operation".into(),
span: span.cloned(),
hint: Some("Both sides must be the same numeric or string type.".into()),
}),
},
AssignOp::MinEqual => match (current, rhs) {
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a - b)),
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a - b)),
_ => Err(NbclError::Runtime {
message: "type mismatch in '-=' operation".into(),
span: span.cloned(),
hint: Some("Subtraction is only supported for numeric types.".into()),
}),
},
AssignOp::MultEqual => match (current, rhs) {
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a * b)),
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a * b)),
_ => Err(NbclError::Runtime {
message: "type mismatch in '*=' operation".into(),
span: span.cloned(),
hint: Some("Multiplication is only supported for numeric types.".into()),
}),
},
AssignOp::DivEqual => match (current, rhs) {
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a / b)),
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a / b)),
_ => Err(NbclError::Runtime {
message: "type mismatch in '/=' operation".into(),
span: span.cloned(),
hint: Some("Division is only supported for numeric types.".into()),
}),
},
}
}
}