1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 19:37:35 +00:00

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 :^)
This commit is contained in:
Linus Groh 2020-05-26 12:57:50 +01:00 committed by Andreas Kling
parent bc307f6b1c
commit 2d47b30256

View file

@ -29,6 +29,7 @@
#include "AST.h"
#include "Lexer.h"
#include <AK/NonnullRefPtr.h>
#include <AK/StringBuilder.h>
#include <stdio.h>
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(); }