From 324ca06cf92ea25032108a94cfef96a98862b833 Mon Sep 17 00:00:00 2001 From: maxine Date: Tue, 24 Jun 2025 13:43:03 -0400 Subject: [PATCH] Start JSON exception handling --- include/error_handling.hpp | 62 ++++++++++++++++++++++++++++++++++++++ src/lexer.cpp | 4 ++- 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/include/error_handling.hpp b/include/error_handling.hpp index ceb040d..a801f04 100644 --- a/include/error_handling.hpp +++ b/include/error_handling.hpp @@ -1,7 +1,69 @@ #pragma once +#include +#include +#include + namespace json { + class Exception : public std::exception { + private: + std::string whatstr; + public: + Exception(std::string base, std::string source, int index) { + //std::ostringstream s; + int counter = 0; + int line = 1; + int column = 0; + std::string lastline = ""; + std::string whitespace = ""; + + for (auto c: source) { + if (counter == index) { + break; + } + + if (c == '\n') { + line++; + column = 0; + lastline = ""; + whitespace = ""; + } else if (c == '\t') { + column++; + lastline += " "; + whitespace += " "; + } else { + column++; + lastline += c; + whitespace += " "; + } + counter++; + } + while (counter < source.size()) { + auto c = source[counter]; + if (c == '\n') { + break; + } + lastline += c; + counter++; + } + + // TODO: Migrate the below code bits to std::format + + /* + s << base << " at line " << line << ", column " << column << std::endl; + s << lastline << std::endl; + s << whitespace << "^";*/ + whatstr = std::format("{} at line {}, column {}\n{}\n{}^", + base, line, column, + lastline, + whitespace); + }; + virtual const char* what() const throw() { + return whatstr.c_str(); + } + }; + class file_error : public std::runtime_error { diff --git a/src/lexer.cpp b/src/lexer.cpp index 04c6e48..eca3ebe 100644 --- a/src/lexer.cpp +++ b/src/lexer.cpp @@ -2,6 +2,7 @@ #include #include #include +#include namespace json { int lexers::lex_whitespace(std::string raw_json, int index) @@ -43,7 +44,8 @@ namespace json { // TODO: handle nested quotes while (c = raw_json[index], c != '"') { if (index == raw_json.length()) { - return {token, index, format_error("Unexpected EOF while lexing string", raw_json, index)}; + //return {token, index, format_error("Unexpected EOF while lexing string", raw_json, index)}; + throw Exception("Unexpected EOF while lexing string", raw_json, index); } token.value += c;