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
|
use std::{cell::RefCell, collections::HashMap, rc::Rc};
use crate::{
interpret::{
operator::ValueOperator,
value::{FnValue, ValueKind},
},
lex::token::Location,
parse::ast::{
expression::{Expression, ExpressionKind},
nodes::{
BinaryOperatorKind as BinOp, BlockExpression, SimpleLiteralKind, StrPartKind,
UnaryOperatorKind as UnOp,
},
statement::{Statement, StatementKind},
Program,
},
types::{bag::TypeBag, TypeKind},
};
use thiserror::Error;
use super::{
operator::{CallError, OperationError},
scope::{ScopeChain, ScopeError},
value::Value,
};
pub struct Walker {
types: TypeBag,
scope: ScopeChain,
}
impl Walker {
// Should preferably be called only once.
pub fn root() -> Self {
Walker {
scope: ScopeChain::new(),
types: TypeBag::new(),
}
}
pub fn new(scope: ScopeChain, types: TypeBag) -> Self {
Walker { scope, types }
}
pub fn walk(&mut self, program: &Program) -> Result<(), WalkerError> {
self.scope.nest();
for statement in program.statements.iter() {
self.walk_statement(statement)?;
}
Ok(())
}
fn walk_statement(&mut self, statement: &Statement) -> Result<Option<Value>, WalkerError> {
let result = match &statement.kind {
StatementKind::Expression(node) => {
self.walk_expression(node)?;
None
}
StatementKind::Print(node) => {
let result = self.walk_expression(node)?;
println!("{}", result);
None
}
StatementKind::Return(node) => {
let returned = match node {
Some(e) => Some(self.walk_expression(e)?),
None => None,
};
// If there's a function running above us it will catch this error.
return Err(WalkerError::new(
statement.at,
WalkerErrorKind::Return(returned),
));
}
StatementKind::Break(node) => {
let returned = if let Some(expression) = node {
Some(self.walk_expression(expression)?)
} else {
None
};
// If there's a loop above us it will catch this error.
return Err(WalkerError::new(
statement.at,
WalkerErrorKind::LoopBreak(returned),
));
}
// Same here.
StatementKind::Continue => {
return Err(WalkerError::new(
statement.at,
WalkerErrorKind::LoopContinue,
));
}
};
Ok(result)
}
pub fn walk_expression(&mut self, node: &Expression) -> Result<Value, WalkerError> {
match &node.kind {
ExpressionKind::Binary { left, op, right } => {
// Assignment
match op.kind {
BinOp::ConstAssign => return self.assing_to_lvalue(left, right, true),
BinOp::Assign => return self.assing_to_lvalue(left, right, false),
_ => {}
}
// Short-circuting operators
if let BinOp::And | BinOp::Or = op.kind {
let left_value = self.walk_expression(left)?;
let is_left_true = match left_value.kind {
ValueKind::Bool(bool) => bool,
_ => {
return Err(WalkerError::new(left.at, WalkerErrorKind::WrongAndOrType))
}
};
if let BinOp::And = op.kind {
if !is_left_true {
return Ok(Value::bool(false, &self.types));
}
} else if is_left_true {
return Ok(Value::bool(true, &self.types));
}
return self.walk_expression(right);
}
let left = self.walk_expression(left)?;
let right = self.walk_expression(right)?;
let exe = ValueOperator::new(&self.types);
// Other operators
match op.kind {
BinOp::Plus => exe.add(left, right),
BinOp::Minus => exe.sub(left, right),
BinOp::Star => exe.mul(left, right),
BinOp::Slash => exe.div(left, right),
BinOp::Dot => todo!("Structures not implemented yet."),
BinOp::Eq => exe.eq(left, right),
BinOp::Neq => exe.neq(left, right),
BinOp::Gt => exe.gt(left, right),
BinOp::Gte => exe.gte(left, right),
BinOp::Lt => exe.gt(right, left),
BinOp::Lte => exe.gte(right, left),
_ => unreachable!(),
}
.map_err(|err| WalkerError::new(op.at, WalkerErrorKind::OperationError(err)))
}
ExpressionKind::Unary { op, right } => {
let value = self.walk_expression(right)?;
let exe = ValueOperator::new(&self.types);
match op.kind {
UnOp::Minus => exe.neg(value),
UnOp::Not => exe.not(value),
}
.map_err(|err| WalkerError::new(op.at, WalkerErrorKind::OperationError(err)))
}
ExpressionKind::Call(node) => {
let called = self.walk_expression(&node.called)?;
let mut argument_values = Vec::new();
for argument_node in node.arguments.iter() {
argument_values.push(self.walk_expression(argument_node)?);
}
let exe = ValueOperator::new(&self.types);
match exe.call(&called, argument_values) {
Ok(value) => Ok(value),
Err(CallError::BeforeCall(op_err)) => Err(WalkerError::new(
node.at,
WalkerErrorKind::OperationError(op_err),
)),
Err(CallError::InsideFunction(err)) => Err(err),
}
}
ExpressionKind::ArrayAccess(node) => {
let array = self.walk_expression(&node.array)?;
let index = self.walk_expression(&node.index)?;
let exe = ValueOperator::new(&self.types);
exe.subscript(array, index)
.map_err(|err| WalkerError::new(node.at, WalkerErrorKind::OperationError(err)))
}
ExpressionKind::MemberAccess(_) => todo!("Structures not implemented yet."),
ExpressionKind::Group(node) => self.walk_expression(node),
ExpressionKind::ArrayLiteral(node) => {
let mut elements = Vec::new();
for expression in &node.elements {
elements.push(self.walk_expression(expression)?);
}
Ok(Value {
kind: ValueKind::Array(Rc::new(RefCell::new(elements))),
// FIXME: Use actual type.
typ: self.types.create_type(TypeKind::Array(self.types.void())),
})
}
ExpressionKind::SimpleLiteral(node) => {
let value = match node.kind {
SimpleLiteralKind::Int(int) => Value::int(int as i64, &self.types),
SimpleLiteralKind::Float(float) => Value::float(float as f64, &self.types),
SimpleLiteralKind::Bool(bool) => Value::bool(bool, &self.types),
};
Ok(value)
}
ExpressionKind::Block(block) => self.walk_block(block.as_ref()),
ExpressionKind::StrLiteral(node) => {
let mut buffer = String::new();
for part in &node.parts {
match &part.kind {
StrPartKind::Literal(literal) => buffer.push_str(literal),
StrPartKind::Embed(embed) => {
buffer.push_str(&self.walk_expression(embed)?.to_string())
}
};
}
Ok(Value::str(buffer, &self.types))
}
ExpressionKind::FnLiteral(node) => Ok(Value {
kind: ValueKind::Fn(Rc::new(RefCell::new(FnValue {
node: node.as_ref().clone(),
scope: self.scope.clone(),
}))),
// FIXME: Use actual type here.
typ: self.types.create_type(TypeKind::Fn {
parameters: HashMap::new(),
returns: self.types.void(),
}),
}),
ExpressionKind::If(if_node) => {
for conditional in &if_node.conditionals {
if let ValueKind::Bool(bool) =
self.walk_expression(&conditional.condition)?.kind
{
if bool {
return self.walk_block(&conditional.block);
}
} else {
return Err(WalkerError::new(
conditional.at,
WalkerErrorKind::WrongIfConditionType,
));
}
}
if let Some(else_conditional) = &if_node.else_block {
self.walk_block(else_conditional)
} else {
Ok(Value::void(&self.types))
}
}
ExpressionKind::Loop(loop_node) => {
loop {
if let Some(condition) = &loop_node.condition {
let condition_value = self.walk_expression(condition)?;
if let ValueKind::Bool(should_repeat) = condition_value.kind {
if !should_repeat {
return Ok(Value::void(&self.types));
}
} else {
return Err(WalkerError::new(
condition.at,
WalkerErrorKind::WrongLoopConditionType,
));
}
}
match self.walk_block(&loop_node.body) {
Err(WalkerError {
kind: WalkerErrorKind::LoopBreak(loop_value),
..
}) => return Ok(loop_value.unwrap_or(Value::void(&self.types))),
// Do nothing for continue and continue looping of course, you dummy.
Err(WalkerError {
kind: WalkerErrorKind::LoopContinue,
..
}) => {}
// This is probably an actual error.
Err(x) => return Err(x),
// Do nothing with values returned from loops for now.
_ => {}
}
}
}
ExpressionKind::Identifier(ident) => self
.scope
.get_var(ident, &self.types)
.map_err(|err| WalkerError::new(node.at, WalkerErrorKind::ScopeError(err))),
}
}
fn walk_block(&mut self, block: &BlockExpression) -> Result<Value, WalkerError> {
self.scope.nest();
for statement in block.statements.iter() {
self.walk_statement(statement)?;
}
let result = if let Some(tail_expression) = &block.tail_expression {
Ok(self.walk_expression(tail_expression)?)
} else {
Ok(Value::void(&self.types))
};
self.scope.unnest();
result
}
pub fn assing_to_lvalue(
&mut self,
lvalue: &Expression,
rvalue: &Expression,
is_constant: bool,
) -> Result<Value, WalkerError> {
// Maybe other expressions could also be l-values, but these are fine for now.
match &lvalue.kind {
ExpressionKind::MemberAccess(_) => todo!("Structures not implemented yet."),
ExpressionKind::ArrayAccess(node) => {
let mut array = self.walk_expression(&node.array)?;
let index = self.walk_expression(&node.index)?;
let value = self.walk_expression(rvalue)?;
let exe = ValueOperator::new(&self.types);
exe.subscript_assign(&mut array, index, value)
.map_err(|err| WalkerError::new(node.at, WalkerErrorKind::OperationError(err)))
}
ExpressionKind::Identifier(ident) => {
let value = self.walk_expression(rvalue)?;
self.scope
.set_var(ident, value.clone(), is_constant)
.map_err(|err| WalkerError::new(lvalue.at, WalkerErrorKind::ScopeError(err)))?;
return Ok(value);
}
_ => Err(WalkerError::new(
lvalue.at,
WalkerErrorKind::NonLValueAssignment,
)),
}
}
}
#[derive(Debug)]
pub struct WalkerError {
pub kind: WalkerErrorKind,
pub at: Location,
}
impl WalkerError {
fn new(at: Location, kind: WalkerErrorKind) -> Self {
WalkerError { at, kind }
}
}
#[derive(Error, Debug)]
pub enum WalkerErrorKind {
#[error("Loop expressions can only take boolean values as conditions.")]
WrongLoopConditionType,
#[error("If and Elif expressions can only take boolean values as conditions.")]
WrongIfConditionType,
#[error("&& and || expressions can only take boolean values as their operands.")]
WrongAndOrType,
#[error("Can only assign to identifiers and member or array access results.")]
NonLValueAssignment,
#[error(transparent)]
ScopeError(ScopeError),
#[error(transparent)]
OperationError(OperationError),
// These are used for loop control flow and are only errors
// if continue and break statements are used outside of loops.
#[error("Continue statements are only valid inside loops.")]
LoopContinue,
#[error("Break statements are only valid inside loops.")]
LoopBreak(Option<Value>),
// Same as with the loop control errors, but for functions.
#[error("Return statements are only valid inside functions.")]
Return(Option<Value>),
}
|