vkdb
A time series database engine in C++.
Loading...
Searching...
No Matches
vq.cpp
1#include <vkdb/vq.h>
2#include <vkdb/database.h>
3#include <vkdb/lexer.h>
4#include <vkdb/parser.h>
5#include <vkdb/interpreter.h>
6
7namespace vkdb {
8bool VQ::had_error_ = false;
9bool VQ::had_runtime_error_ = false;
10Database VQ::database_{INTERPRETER_DEFAULT_DATABASE};
11const Interpreter VQ::interpreter_{database_, VQ::runtimeError};
12
13void VQ::runFile(const std::filesystem::path path) noexcept {
14 if (path.extension() != ".vq") {
15 std::cerr << "\033[1;32mVQ::runFile(): File extension cannot be "
16 << path.extension() << ", must be .vq.\033[0m\n";
17 return;
18 }
19 std::ifstream file{path};
20 if (!file.is_open()) {
21 std::cerr << "\033[1;32mVQ::runFile(): Unable to open file "
22 << path << ".\033[0m\n";
23 return;
24 }
25 std::stringstream buffer;
26 buffer << file.rdbuf();
27 run(buffer.str());
28}
29
30void VQ::runPrompt() noexcept {
31 std::cout << "\033[1;31mwelcome to the vq repl! :)\033[0m\n";
32 std::cout << "\033[1;31m(on default interpreter database)\033[0m\n";
33 std::string line;
34 while (true) {
35 std::cout << "\033[1;34m(vq) >> \033[0m";
36 if (!std::getline(std::cin, line) || line.empty()) {
37 break;
38 };
39 run(line);
40 had_error_ = false;
41 }
42}
43
44void VQ::run(const std::string& source) noexcept {
45 Lexer lexer{source};
46 auto tokens{lexer.tokenize()};
47
48 Parser parser{tokens, error};
49 auto expr{parser.parse()};
50
51 if (had_error_) {
52 return;
53 }
54
55 interpreter_.interpret(expr.value());
56}
57
58void VQ::error(Token token, const std::string& message) noexcept {
59 if (token.type() == TokenType::END_OF_FILE) {
60 report(token.line(), "at end", message);
61 } else {
62 report(token.line(), "at '" + token.lexeme() + "'", message);
63 }
64}
65
66void VQ::runtimeError(const RuntimeError& error) noexcept {
67 std::cerr << "\033[1;32m[line " << error.token().line();
68 std::cerr << "] Runtime error: " << error.message() << "\033[0m\n";
69 had_runtime_error_ = true;
70}
71
72void VQ::report(
73 size_type line,
74 const std::string& where,
75 const std::string& message
76) noexcept {
77 std::cerr << "\033[1;32m[line " << line << "] Parse error ";
78 std::cerr << where << ": " << message << "\033[0m\n";
79 had_error_ = true;
80}
81} // namespace vkdb
Lexer for vq.
Definition lexer.h:45
Parser for vq.
Definition parser.h:22
Runtime error.
Represents a token.
Definition token.h:81
static void error(Token token, const std::string &message) noexcept
Handle an error.
Definition vq.cpp:58
static void run(const std::string &source) noexcept
Run a source string.
Definition vq.cpp:44
static void runFile(const std::filesystem::path path) noexcept
Run a file.
Definition vq.cpp:13
static void runPrompt() noexcept
Run the prompt.
Definition vq.cpp:30
static void runtimeError(const RuntimeError &error) noexcept
Handle a runtime error.
Definition vq.cpp:66