SourceCode.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Utf8View.h>
  7. #include <LibJS/SourceCode.h>
  8. #include <LibJS/SourceRange.h>
  9. #include <LibJS/Token.h>
  10. namespace JS {
  11. NonnullRefPtr<SourceCode> SourceCode::create(String filename, String code)
  12. {
  13. return adopt_ref(*new SourceCode(move(filename), move(code)));
  14. }
  15. SourceCode::SourceCode(String filename, String code)
  16. : m_filename(move(filename))
  17. , m_code(move(code))
  18. {
  19. }
  20. String const& SourceCode::filename() const
  21. {
  22. return m_filename;
  23. }
  24. String const& SourceCode::code() const
  25. {
  26. return m_code;
  27. }
  28. SourceRange SourceCode::range_from_offsets(u32 start_offset, u32 end_offset) const
  29. {
  30. Position start;
  31. Position end;
  32. size_t line = 1;
  33. size_t column = 1;
  34. bool previous_code_point_was_carriage_return = false;
  35. Utf8View view(m_code);
  36. for (auto it = view.begin(); it != view.end(); ++it) {
  37. if (start_offset == view.byte_offset_of(it)) {
  38. start = Position {
  39. .line = line,
  40. .column = column,
  41. .offset = start_offset,
  42. };
  43. }
  44. if (end_offset == view.byte_offset_of(it)) {
  45. end = Position {
  46. .line = line,
  47. .column = column,
  48. .offset = end_offset,
  49. };
  50. break;
  51. }
  52. u32 code_point = *it;
  53. bool is_line_terminator = code_point == '\r' || (code_point == '\n' && !previous_code_point_was_carriage_return) || code_point == LINE_SEPARATOR || code_point == PARAGRAPH_SEPARATOR;
  54. previous_code_point_was_carriage_return = code_point == '\r';
  55. if (is_line_terminator) {
  56. ++line;
  57. column = 1;
  58. continue;
  59. }
  60. ++column;
  61. }
  62. return SourceRange { *this, start, end };
  63. }
  64. }