From 2689faa67c5f3279def7206e100a8fef77e8625c Mon Sep 17 00:00:00 2001 From: Bob Polis Date: Mon, 21 Sep 2020 16:37:40 +0200 Subject: [PATCH] fixed line numbers for syntax errors by considering removed source lines: labels, comments --- interpreter.cpp | 15 +++++++++++---- interpreter.hpp | 1 + 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/interpreter.cpp b/interpreter.cpp index 1a340db..ef3f50e 100644 --- a/interpreter.cpp +++ b/interpreter.cpp @@ -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 ----------------------------------------------------- diff --git a/interpreter.hpp b/interpreter.hpp index 01a3abd..f9ace33 100644 --- a/interpreter.hpp +++ b/interpreter.hpp @@ -38,6 +38,7 @@ class interpreter { std::map _vars; std::vector _calls; std::vector::size_type _pc {0}; + std::vector _pc_offsets; void reset(); void exec_instruction(const std::string& code, bool& done);