-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluator.h
More file actions
549 lines (480 loc) · 16.8 KB
/
evaluator.h
File metadata and controls
549 lines (480 loc) · 16.8 KB
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
#ifndef EVALUATOR_H
#define EVALUATOR_H
#include "ast.h"
#include "object.h"
#include "builtin.h"
#include <cassert>
#include <cstddef>
#include <memory>
#include <string>
#include <string_view>
#include <typeinfo>
#include <vector>
#include "utils.h"
#include "cleaner.h"
#include <fmt/format.h>
using obj::Error;
using obj::Environment;
using obj::Object;
using obj::ObjectType;
using ast::ASTNode;
using ast::Program;
using ast::ExpressionStatement;
using ast::Prefix;
using ast::Infix;
using ast::Block;
using ast::If;
using ast::ReturnStatement;
using ast::LetStatement;
using ast::Identifier;
using ast::Node;
using ast::AssignStatement;
static constexpr std::string_view WRONG_ARGS = "Cantidad errónea de argumentos para la función cerca de la línea {}, se esperaban {} pero se obtuvo {}";
static constexpr std::string_view NOT_A_FUNCTION = "No es una function: {} cerca de la línea {}";
static constexpr std::string_view TYPE_MISMATCH = "Discrepancia de tipos: {} {} {} cerca de la línea {}";
static constexpr std::string_view UNKNOWN_PREFIX_OPERATION = "Operador desconocido: {}{} cerca de la línea {}";
static constexpr std::string_view UNKNOWN_INFIX_OPERATION = "Operador desconocido: {} {} {} cerca de la línea {}";
const static auto TRUE = std::make_unique<obj::Boolean>(true);
const static auto FALSE = std::make_unique<obj::Boolean>(false);
const static auto _NULL = std::make_unique<obj::Null>();
static Object* evaluate_program(Program*, Environment*);
static Object* to_boolean_object(bool);
static Object* to_boolean_object(const std::string&, Object*, Object*);
static Object* evaluate_prefix_expression(const std::string&, Object*, const int);
static Object* evaluate_infix_expression(const std::string&, Object*, Object*, const int);
static Object* evaluate_if_expression(If*, Environment*);
static Object* evaluate_block_statements(Block*, Environment*);
static Object* evaluate_identifier(Identifier*, Environment*);
static std::vector<Object*> evaluate_expression(const std::vector<Expression*>&, Environment*);
static Object* apply_function(Object*, const std::vector<Object*>&, const int);
static Object* evaluate(ASTNode* node, Environment* env)
{
auto node_type = node->type();
switch (node_type) {
case Node::Program:
return evaluate_program(dynamic_cast<Program*>(node), env);
case Node::ExpressionStatement:
{
auto cast_exp_st = dynamic_cast<ExpressionStatement*>(node);
return evaluate(cast_exp_st->expression, env);
}
case Node::Integer:
{
auto cast_int = dynamic_cast<ast::Integer*>(node);
auto integer = new obj::Integer(cast_int->value);
cleaner.push_back(integer);
return integer;
}
case Node::Boolean:
{
auto cast_bool = dynamic_cast<ast::Boolean*>(node);
return to_boolean_object(cast_bool->value);
}
case Node::Prefix:
{
auto cast_prefix = dynamic_cast<Prefix*>(node);
assert(cast_prefix != nullptr);
auto right = evaluate(cast_prefix->right, env);
assert(right != nullptr);
return evaluate_prefix_expression(cast_prefix->operatr, right, cast_prefix->token.line);
}
case Node::Infix:
{
auto cast_infix = dynamic_cast<Infix*>(node);
assert(cast_infix->left && cast_infix->right);
auto left = evaluate(cast_infix->left, env);
auto right = evaluate(cast_infix->right, env);
assert(left && right);
return evaluate_infix_expression(cast_infix->operatr, left, right, cast_infix->token.line);
}
case Node::Block:
{
auto cast_block = dynamic_cast<Block*>(node);
return evaluate_block_statements(cast_block, env);
}
case Node::If:
{
auto cast_if = dynamic_cast<ast::If*>(node);
return evaluate_if_expression(cast_if, env);
}
case Node::ReturnStatement:
{
auto cast_rtn_st = dynamic_cast<ReturnStatement*>(node);
assert(cast_rtn_st->return_value);
auto value = evaluate(cast_rtn_st->return_value, env);
assert(value);
auto return_val = new obj::Return(value);
cleaner.push_back(return_val);
return return_val;
}
case Node::LetStatement:
{
auto cast_let_st = dynamic_cast<LetStatement*>(node);
assert(cast_let_st->value);
auto value = evaluate(cast_let_st->value, env);
assert(cast_let_st->name);
env->set_item(cast_let_st->name->value, value);
return value;
}
case Node::AssignStatement:
{
auto cast_assign = dynamic_cast<AssignStatement*>(node);
auto value = evaluate(cast_assign->value, env);
env->set_item(cast_assign->name->value, value);
return value;
}
case Node::Identifier:
{
auto cast_ident = dynamic_cast<Identifier*>(node);
assert(cast_ident);
return evaluate_identifier(cast_ident, env);
}
case Node::Function:
{
auto cast_func = dynamic_cast<ast::Function*>(node);
assert(cast_func);
auto func = new obj::Function(cast_func->parameters, cast_func->body, env);
cleaner.push_back(func);
return func;
}
case Node::Call:
{
auto cast_call = dynamic_cast<ast::Call*>(node);
auto function = evaluate(cast_call->function, env);
auto args = evaluate_expression(cast_call->arguments, env);
return apply_function(function, args, cast_call->token.line);
}
case Node::StringLiteral:
{
auto cast_str_lit = dynamic_cast<ast::StringLiteral*>(node);
auto str = new obj::String(cast_str_lit->value);
cleaner.push_back(str);
return str;
}
case Node::Null:
return _NULL.get();
default:
return nullptr;
}
}
static Environment* extend_function_environment(obj::Function* fn, const std::vector<Object*>& args, const int line)
{
if(fn->parameters.size() != args.size())
{
auto error = new Error{
fmt::format(WRONG_ARGS,
line,
fn->parameters.size(),
args.size()
)};
eval_errors.push_back(error);
return nullptr;
}
auto env = new Environment(fn->env);
environments.push_back(env);
for(std::size_t i = 0; i < fn->parameters.size(); i++)
env->set_item(fn->parameters.at(i)->value, args.at(i));
return env;
}
static Object* unwrap_return_value(Object* obj)
{
if(typeid(*obj) == typeid(obj::Return))
return static_cast<obj::Return*>(obj)->value;
return obj;
}
Object* apply_function(Object* fn, const std::vector<Object*>& args, const int line)
{
if(typeid(*fn) == typeid(obj::Function))
{
auto function = static_cast<obj::Function*>(fn);
auto extended_environment = extend_function_environment(function, args, line);
if(!extended_environment)
return eval_errors.at(eval_errors.size() - 1UL);
auto evaluated = evaluate(function->body, extended_environment);
return unwrap_return_value(evaluated);
}
else if(typeid(*fn) == typeid(obj::Builtin))
{
auto function = static_cast<obj::Builtin*>(fn);
return function->fn(args, line);
}
auto error = new Error{
fmt::format(NOT_A_FUNCTION,
fn->type_string(),
line
)};
eval_errors.push_back(error);
return error;
}
Object* evaluate_program(Program* program, Environment* env)
{
Object* result = nullptr;
for(auto s : program->statements)
{
result = evaluate(s, env);
if(typeid(*result) == typeid(obj::Return))
{
auto cast_result = static_cast<obj::Return*>(result);
return cast_result->value;
}
else if (typeid(*result) == typeid(obj::Error))
return result;
}
return result;
}
static bool is_truthy(Object* obj)
{
if(obj == _NULL.get())
return false;
else if(obj == TRUE.get())
return true;
else if(obj == FALSE.get())
return false;
else
return true;
}
Object* evaluate_if_expression(If* if_expression, Environment* env)
{
assert(if_expression->condition);
auto condicion = evaluate(if_expression->condition, env);
assert(condicion);
if(is_truthy(condicion))
{
assert(if_expression->consequence);
return evaluate(if_expression->consequence, env);
}
else if (if_expression->alternative)
return evaluate(if_expression->alternative, env);
else
return _NULL.get();
}
Object* evaluate_block_statements(Block* block, Environment* env)
{
Object* result = nullptr;
for (auto statement : block->statements)
{
result = evaluate(statement, env);
if((result && result->type() == ObjectType::RETURN)
|| result->type() == ObjectType::ERROR)
return result;
}
return result;
}
static Object* evaluate_bang_operator_expression(Object* right)
{
if(right == TRUE.get())
return FALSE.get();
else if(right == FALSE.get())
return TRUE.get();
else if(right == _NULL.get())
return TRUE.get();
else
return FALSE.get();
}
static Object* evaluate_minus_operator_expression(Object* right, const int line)
{
if(typeid(*right).name() != typeid(obj::Integer).name())
{
auto error = new Error{
fmt::format(UNKNOWN_PREFIX_OPERATION,
"-",
right->type_string(),
line
)};
eval_errors.push_back(error);
return error;
}
auto cast_right = dynamic_cast<obj::Integer*>(right);
auto integer = new obj::Integer(-cast_right->value);
cleaner.push_back(integer);
return integer;
}
Object* evaluate_prefix_expression(const std::string& operatr, Object* right, const int line)
{
if(operatr == "!")
return evaluate_bang_operator_expression(right);
else if(operatr == "-")
return evaluate_minus_operator_expression(right, line);
else
{
auto error = new Error{
fmt::format(UNKNOWN_PREFIX_OPERATION,
operatr,
right->type_string(),
line
)};
eval_errors.push_back(error);
return error;
}
}
static Object* evaluate_integer_infix_expression(const std::string& operatr, Object* left, Object* right, const int line)
{
auto left_value = static_cast<obj::Integer*>(left)->value;
auto right_value = static_cast<obj::Integer*>(right)->value;
if (operatr == "+")
{
auto integer = new obj::Integer(left_value + right_value);
cleaner.push_back(integer);
return integer;
}
else if (operatr == "-")
{
auto integer = new obj::Integer(left_value - right_value);
cleaner.push_back(integer);
return integer;
}
else if (operatr == "*")
{
auto integer = new obj::Integer(left_value * right_value);
cleaner.push_back(integer);
return integer;
}
else if (operatr == "/")
{
auto integer = new obj::Integer(left_value / right_value);
cleaner.push_back(integer);
return integer;
}
else if (operatr == "<")
return to_boolean_object(left_value < right_value);
else if (operatr == ">")
return to_boolean_object(left_value > right_value);
else if (operatr == "==")
return to_boolean_object(left_value == right_value);
else if (operatr == "!=")
return to_boolean_object(left_value != right_value);
else
{
auto error = new Error{
fmt::format(UNKNOWN_INFIX_OPERATION,
left->type_string(),
operatr,
right->type_string(),
line
)};
eval_errors.push_back(error);
return error;
}
}
static Object* evaluate_string_infix_expression(const std::string& operatr, Object* left, Object* right, const int line)
{
auto left_value = static_cast<obj::String*>(left)->value;
auto right_value = static_cast<obj::String*>(right)->value;
if(operatr == "+")
{
auto str = new obj::String(left_value + right_value);
cleaner.push_back(str);
return str;
}
else if(operatr == "==")
return to_boolean_object(left_value == right_value);
else if(operatr == "!=")
return to_boolean_object(left_value != right_value);
auto error = new Error{
fmt::format(UNKNOWN_INFIX_OPERATION,
left->type_string(),
operatr,
right->type_string(),
line
)};
eval_errors.push_back(error);
return error;
}
Object* evaluate_infix_expression(const std::string& operatr, Object* left, Object* right, const int line)
{
if(left->type() == ObjectType::INTEGER && right->type() == ObjectType::INTEGER)
return evaluate_integer_infix_expression(operatr, left, right, line);
else if(left->type() == ObjectType::STRING && right->type() == ObjectType::STRING)
return evaluate_string_infix_expression(operatr, left, right, line);
else if(operatr == "==" || operatr == "!=")
return to_boolean_object(operatr, left, right);
else if(left->type() != right->type())
{
auto error = new Error{
fmt::format(TYPE_MISMATCH,
left->type_string(),
operatr,
right->type_string(),
line
)};
eval_errors.push_back(error);
return error;
}
auto error = new Error{
fmt::format(UNKNOWN_INFIX_OPERATION,
left->type_string(),
operatr,
right->type_string(),
line
)};
eval_errors.push_back(error);
return error;
}
Object* evaluate_identifier(Identifier* ident, Environment* env)
{
if(env->item_exist(ident->value))
return env->get_item(ident->value);
else if(BUILTINS.find(ident->value) != BUILTINS.end())
return &BUILTINS.at(ident->value);
else
return _NULL.get();
}
std::vector<Object*> evaluate_expression(const std::vector<Expression*>& expressions, Environment* env)
{
auto result = std::vector<Object*>();
for(auto exp : expressions)
{
auto evaluated = evaluate(exp, env);
if(evaluated)
result.push_back(evaluated);
}
return result;
}
Object* to_boolean_object(bool value)
{
return value ? TRUE.get() : FALSE.get();
}
Object* to_boolean_object(const std::string& operatr, Object* left, Object* right)
{
switch (left->type()) {
case ObjectType::BOOLEAN:
{
if(right->type() == ObjectType::BOOLEAN && operatr == "==") {
auto value = static_cast<obj::Boolean*>(left)->value
== static_cast<obj::Boolean*>(right)->value;
return value ? TRUE.get() : FALSE.get();
}
if(right->type() == ObjectType::BOOLEAN && operatr == "!=") {
auto value = static_cast<obj::Boolean*>(left)->value
!= static_cast<obj::Boolean*>(right)->value;
return value ? TRUE.get() : FALSE.get();
}
if(operatr == "!=")
return TRUE.get();
return FALSE.get();
}
case ObjectType::INTEGER:
{
if(operatr == "!=")
return TRUE.get();
return FALSE.get();
}
case ObjectType::STRING:
{
if(operatr == "!=")
return TRUE.get();
return FALSE.get();
}
case ObjectType::_NULL:
{
if(right->type() == ObjectType::_NULL && operatr == "==")
return TRUE.get();
if(operatr == "!=" && right->type() != ObjectType::_NULL)
return TRUE.get();
return FALSE.get();
}
default:
return FALSE.get();
}
}
#endif // EVALUATOR_H