From 2d47b30256f501bd06ff51ee2e7691d51e0386fd Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Tue, 26 May 2020 12:57:50 +0100 Subject: [PATCH] LibJS: Add Error::source_location_hint() This util function on the Error struct will take the source and then returns a string like this based on line and column information it has: foo bar ^ Which can be shown in the repl for syntax errors :^) --- Libraries/LibJS/Parser.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Libraries/LibJS/Parser.h b/Libraries/LibJS/Parser.h index 1b2f5f9056..154f18eb53 100644 --- a/Libraries/LibJS/Parser.h +++ b/Libraries/LibJS/Parser.h @@ -29,6 +29,7 @@ #include "AST.h" #include "Lexer.h" #include +#include #include namespace JS { @@ -89,6 +90,19 @@ public: return message; return String::format("%s (line: %zu, column: %zu)", message.characters(), line, column); } + + String source_location_hint(const StringView& source, const char spacer = ' ', const char indicator = '^') const + { + if (line == 0 || column == 0) + return {}; + StringBuilder builder; + builder.append(source.split_view('\n')[line - 1]); + builder.append('\n'); + for (size_t i = 0; i < column - 1; ++i) + builder.append(spacer); + builder.append(indicator); + return builder.build(); + } }; bool has_errors() const { return m_parser_state.m_errors.size(); }