#include #include #include #include "eval.h" static int evaluate_value(const struct Node* node, int64_t* out); static int complain(const struct Node* node, const char* message) { (void)fprintf(stderr, "line %d: %s\n", node->line, message); return 1; } static int evaluate_operands(const struct Node* node, int64_t* left, int64_t* right) { if (evaluate_value(node->first, left)) return 1; return evaluate_value(node->second, right); } static int evaluate_value(const struct Node* node, int64_t* out) { int64_t left = 0; int64_t right = 0; switch (node->kind) { case VALUE_DIFFERENCE: *out = (int64_t)node->first->character - (int64_t)node->second->character; return 0; case VALUE_SUM: if (evaluate_operands(node, &left, &right)) return 1; *out = left + right; return 0; case VALUE_PRODUCT: if (evaluate_operands(node, &left, &right)) return 1; *out = left * right; return 0; case VALUE_QUOTIENT: if (evaluate_operands(node, &left, &right)) return 1; if (right == 0) return complain(node, "division by zero"); *out = left / right; return 0; default: break; } assert(!"the parser handed a non-value where a value goes"); return 1; } static int evaluate_type(const struct Node* node, struct Type* out) { out->kind = KIND_VOID; out->number = 0; switch (node->kind) { case TYPE_DECLTYPE: if (evaluate_value(node->first, &out->number)) return 1; out->kind = KIND_VALUE; return 0; default: break; } assert(!"the parser handed a non-type where a type goes"); return 1; } static enum RunStatus emit(const struct Node* node) { struct Type type; if (evaluate_type(node->first, &type)) return RUN_FAILED; if (type.kind == KIND_VALUE) (void)printf("%" PRId64 "\n", type.number); return RUN_DONE; } static enum RunStatus execute_one(const struct Node* node) { switch (node->kind) { case STMT_EMIT: return emit(node); default: break; } assert(!"the parser handed a non-statement where a statement goes"); return RUN_FAILED; } enum RunStatus execute(const struct Node* statement) { while (statement != NULL) { enum RunStatus status = execute_one(statement); if (status != RUN_DONE) return status; statement = statement->next; } return RUN_DONE; }