fixed line numbers for syntax errors by considering removed source lines: labels, comments

This commit is contained in:
Bob Polis 2020-09-21 16:37:40 +02:00
parent eeeaf894e0
commit 2689faa67c
2 changed files with 12 additions and 4 deletions

View File

@ -34,10 +34,13 @@ std::string interpreter::eval(std::istream& in, bool& done) {
// first pass: read program & resolve labels
for (std::string line; std::getline(in, line); ++_pc) {
if (line[0] == ':') {
_labels.emplace(line.substr(1), _pc--);
if (line[0] == ':') { // check label definition
_labels.emplace(line.substr(1), _pc);
_pc_offsets.push_back(_pc);
_pc--; // we'll lose this line
} else if (line[0] == '#') { // check comment
_pc--;
_pc_offsets.push_back(_pc);
_pc--; // we'll lose this line
} else {
_prog.push_back(line);
}
@ -126,7 +129,11 @@ void interpreter::exec_instruction(const std::string& code, bool& done) {
else if (code == "inp") inp();
else if (code == "out") out();
else if (code == "err") err();
else throw syntax_error {code, _pc + 1};
else {
auto it = std::upper_bound(_pc_offsets.begin(), _pc_offsets.end(), _pc);
size_t lineno {it - _pc_offsets.begin() + _pc + 1};
throw syntax_error {code, lineno};
}
}
// integer operations -----------------------------------------------------

View File

@ -38,6 +38,7 @@ class interpreter {
std::map<std::string, std::string> _vars;
std::vector<int> _calls;
std::vector<std::string>::size_type _pc {0};
std::vector<size_t> _pc_offsets;
void reset();
void exec_instruction(const std::string& code, bool& done);