ParserError.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. ErrorOr<String> ParserError::to_string() const
  13. {
  14. if (!position.has_value())
  15. return String::from_deprecated_string(message);
  16. return String::formatted("{} (line: {}, column: {})", message, position.value().line, position.value().column);
  17. }
  18. DeprecatedString ParserError::to_deprecated_string() const
  19. {
  20. if (!position.has_value())
  21. return message;
  22. return DeprecatedString::formatted("{} (line: {}, column: {})", message, position.value().line, position.value().column);
  23. }
  24. DeprecatedString ParserError::source_location_hint(StringView source, char const spacer, char const indicator) const
  25. {
  26. if (!position.has_value())
  27. return {};
  28. // We need to modify the source to match what the lexer considers one line - normalizing
  29. // line terminators to \n is easier than splitting using all different LT characters.
  30. DeprecatedString 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);
  31. StringBuilder builder;
  32. builder.append(source_string.split_view('\n', SplitBehavior::KeepEmpty)[position.value().line - 1]);
  33. builder.append('\n');
  34. for (size_t i = 0; i < position.value().column - 1; ++i)
  35. builder.append(spacer);
  36. builder.append(indicator);
  37. return builder.to_deprecated_string();
  38. }
  39. }