ParserError.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/StringView.h>
  8. #include <AK/Vector.h>
  9. #include <LibJS/ParserError.h>
  10. #include <LibJS/Token.h>
  11. namespace JS {
  12. String ParserError::to_string() const
  13. {
  14. if (!position.has_value())
  15. return message;
  16. return String::formatted("{} (line: {}, column: {})", message, position.value().line, position.value().column);
  17. }
  18. String ParserError::source_location_hint(StringView source, char const spacer, char const indicator) const
  19. {
  20. if (!position.has_value())
  21. return {};
  22. // We need to modify the source to match what the lexer considers one line - normalizing
  23. // line terminators to \n is easier than splitting using all different LT characters.
  24. String source_string = source.replace("\r\n"sv, "\n"sv, ReplaceMode::All).replace("\r"sv, "\n"sv, ReplaceMode::All).replace(LINE_SEPARATOR_STRING, "\n"sv, ReplaceMode::All).replace(PARAGRAPH_SEPARATOR_STRING, "\n"sv, ReplaceMode::All);
  25. StringBuilder builder;
  26. builder.append(source_string.split_view('\n', SplitBehavior::KeepEmpty)[position.value().line - 1]);
  27. builder.append('\n');
  28. for (size_t i = 0; i < position.value().column - 1; ++i)
  29. builder.append(spacer);
  30. builder.append(indicator);
  31. return builder.build();
  32. }
  33. }