diff --git a/src/util/json/job.cpp b/src/util/json/job.cpp new file mode 100644 index 0000000..0b72626 --- /dev/null +++ b/src/util/json/job.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2022 Riyyi + * + * SPDX-License-Identifier: MIT + */ + +#include // istringstream +#include // getline + +#include "util/json/job.h" + +namespace Json { + +Job::Job(const std::string& input) + : m_input(input) +{ +} + +Job::~Job() +{ +} + +// ------------------------------------------ + +void Job::printErrorLine(Token token, const char* message) +{ + // Error message + std::string errorFormat = "\033[;1m" // Bold + "JSON:%zu:%zu: " + "\033[31;1m" // Bold red + "error: " + "\033[0m" // Reset + "%s" + "\n"; + printf(errorFormat.c_str(), + token.line, + token.column, + message); + + // Get the JSON line that caused the error + std::istringstream input(m_input); + std::string line; + size_t count = 0; + while (std::getline(input, line)) { + count++; + if (count == token.line) { + break; + } + } + + // JSON line + std::string lineFormat = " %" + + std::to_string(m_lineNumbersWidth) + + "zu | " + "%s" + "\033[31;1m" // Bold red + "%s" + "\033[0m" // Reset + "\n"; + printf(lineFormat.c_str(), + token.line, + line.substr(0, token.column - 1).c_str(), + line.substr(token.column - 1).c_str()); + + // Arrow pointer + std::string arrowFormat = " %s | " + "\033[31;1m" // Bold red + "%s^%s" + "\033[0m" // Reset + "\n"; + printf(arrowFormat.c_str(), + std::string(m_lineNumbersWidth, ' ').c_str(), + std::string(token.column - 1, ' ').c_str(), + std::string(line.length() - token.column, '~').c_str()); +} + +} // namespace Json diff --git a/src/util/json/job.h b/src/util/json/job.h new file mode 100644 index 0000000..e35405b --- /dev/null +++ b/src/util/json/job.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2022 Riyyi + * + * SPDX-License-Identifier: MIT + */ + +#ifndef JSON_JOB_H +#define JSON_JOB_H + +#include // size_t +#include + +#include "util/json/lexer.h" + +namespace Json { + +class Job { +public: + Job(const std::string& input); + virtual ~Job(); + + enum class Color { + None, + Info, + Warn, + Danger, + Success, + Comment, + }; + + void printErrorLine(Token token, const char* message); + + void setLineNumbersWidth(size_t width) { m_lineNumbersWidth = width; } + + const std::string& input() { return m_input; } + +private: + std::string m_input; + size_t m_lineNumbersWidth { 0 }; +}; + +} // namespace Json + +#endif // JSON_JOB_H