Error.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/StringBuilder.h>
  8. #include <LibJS/AST.h>
  9. #include <LibJS/Runtime/Completion.h>
  10. #include <LibJS/Runtime/Error.h>
  11. #include <LibJS/Runtime/ExecutionContext.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. #include <LibJS/SourceRange.h>
  14. namespace JS {
  15. JS_DEFINE_ALLOCATOR(Error);
  16. static SourceRange dummy_source_range { SourceCode::create(String {}, String {}), {}, {} };
  17. SourceRange const& TracebackFrame::source_range() const
  18. {
  19. if (!cached_source_range)
  20. return dummy_source_range;
  21. if (auto* unrealized = cached_source_range->source_range.get_pointer<UnrealizedSourceRange>()) {
  22. auto source_range = [&] {
  23. if (!unrealized->source_code)
  24. return dummy_source_range;
  25. return unrealized->realize();
  26. }();
  27. cached_source_range->source_range = move(source_range);
  28. }
  29. return cached_source_range->source_range.get<SourceRange>();
  30. }
  31. NonnullGCPtr<Error> Error::create(Realm& realm)
  32. {
  33. return realm.create<Error>(realm.intrinsics().error_prototype());
  34. }
  35. NonnullGCPtr<Error> Error::create(Realm& realm, String message)
  36. {
  37. auto& vm = realm.vm();
  38. auto error = Error::create(realm);
  39. u8 attr = Attribute::Writable | Attribute::Configurable;
  40. error->define_direct_property(vm.names.message, PrimitiveString::create(vm, move(message)), attr);
  41. return error;
  42. }
  43. NonnullGCPtr<Error> Error::create(Realm& realm, StringView message)
  44. {
  45. return create(realm, MUST(String::from_utf8(message)));
  46. }
  47. Error::Error(Object& prototype)
  48. : Object(ConstructWithPrototypeTag::Tag, prototype)
  49. {
  50. populate_stack();
  51. }
  52. // 20.5.8.1 InstallErrorCause ( O, options ), https://tc39.es/ecma262/#sec-installerrorcause
  53. ThrowCompletionOr<void> Error::install_error_cause(Value options)
  54. {
  55. auto& vm = this->vm();
  56. // 1. If Type(options) is Object and ? HasProperty(options, "cause") is true, then
  57. if (options.is_object() && TRY(options.as_object().has_property(vm.names.cause))) {
  58. // a. Let cause be ? Get(options, "cause").
  59. auto cause = TRY(options.as_object().get(vm.names.cause));
  60. // b. Perform CreateNonEnumerableDataPropertyOrThrow(O, "cause", cause).
  61. create_non_enumerable_data_property_or_throw(vm.names.cause, cause);
  62. }
  63. // 2. Return unused.
  64. return {};
  65. }
  66. void Error::populate_stack()
  67. {
  68. auto stack_trace = vm().stack_trace();
  69. m_traceback.ensure_capacity(stack_trace.size());
  70. for (auto& element : stack_trace) {
  71. auto* context = element.execution_context;
  72. TracebackFrame frame {
  73. .function_name = context->function_name ? context->function_name->byte_string() : "",
  74. .cached_source_range = element.source_range,
  75. };
  76. m_traceback.append(move(frame));
  77. }
  78. }
  79. String Error::stack_string(CompactTraceback compact) const
  80. {
  81. if (m_traceback.is_empty())
  82. return {};
  83. StringBuilder stack_string_builder;
  84. // Note: We roughly follow V8's formatting
  85. auto append_frame = [&](TracebackFrame const& frame) {
  86. auto function_name = frame.function_name;
  87. auto source_range = frame.source_range();
  88. // Note: Since we don't know whether we have a valid SourceRange here we just check for some default values.
  89. if (!source_range.filename().is_empty() || source_range.start.offset != 0 || source_range.end.offset != 0) {
  90. if (function_name.is_empty())
  91. stack_string_builder.appendff(" at {}:{}:{}\n", source_range.filename(), source_range.start.line, source_range.start.column);
  92. else
  93. stack_string_builder.appendff(" at {} ({}:{}:{})\n", function_name, source_range.filename(), source_range.start.line, source_range.start.column);
  94. } else {
  95. stack_string_builder.appendff(" at {}\n", function_name.is_empty() ? "<unknown>"sv : function_name.view());
  96. }
  97. };
  98. auto is_same_frame = [](TracebackFrame const& a, TracebackFrame const& b) {
  99. if (a.function_name.is_empty() && b.function_name.is_empty()) {
  100. auto source_range_a = a.source_range();
  101. auto source_range_b = b.source_range();
  102. return source_range_a.filename() == source_range_b.filename() && source_range_a.start.line == source_range_b.start.line;
  103. }
  104. return a.function_name == b.function_name;
  105. };
  106. // Note: We don't want to capture the global execution context, so we omit the last frame
  107. // Note: The error's name and message get prepended by ErrorPrototype::stack
  108. // FIXME: We generate a stack-frame for the Errors constructor, other engines do not
  109. unsigned repetitions = 0;
  110. size_t used_frames = m_traceback.size() - 1;
  111. for (size_t i = 0; i < used_frames; ++i) {
  112. auto const& frame = m_traceback[i];
  113. if (compact == CompactTraceback::Yes && i + 1 < used_frames) {
  114. auto const& next_traceback_frame = m_traceback[i + 1];
  115. if (is_same_frame(frame, next_traceback_frame)) {
  116. repetitions++;
  117. continue;
  118. }
  119. }
  120. if (repetitions > 4) {
  121. // If more than 5 (1 + >4) consecutive function calls with the same name, print
  122. // the name only once and show the number of repetitions instead. This prevents
  123. // printing ridiculously large call stacks of recursive functions.
  124. append_frame(frame);
  125. stack_string_builder.appendff(" {} more calls\n", repetitions);
  126. } else {
  127. for (size_t j = 0; j < repetitions + 1; j++)
  128. append_frame(frame);
  129. }
  130. repetitions = 0;
  131. }
  132. for (size_t j = 0; j < repetitions; j++)
  133. append_frame(m_traceback[used_frames - 1]);
  134. return MUST(stack_string_builder.to_string());
  135. }
  136. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  137. JS_DEFINE_ALLOCATOR(ClassName); \
  138. NonnullGCPtr<ClassName> ClassName::create(Realm& realm) \
  139. { \
  140. return realm.create<ClassName>(realm.intrinsics().snake_name##_prototype()); \
  141. } \
  142. \
  143. NonnullGCPtr<ClassName> ClassName::create(Realm& realm, String message) \
  144. { \
  145. auto& vm = realm.vm(); \
  146. auto error = ClassName::create(realm); \
  147. u8 attr = Attribute::Writable | Attribute::Configurable; \
  148. error->define_direct_property(vm.names.message, PrimitiveString::create(vm, move(message)), attr); \
  149. return error; \
  150. } \
  151. \
  152. NonnullGCPtr<ClassName> ClassName::create(Realm& realm, StringView message) \
  153. { \
  154. return create(realm, MUST(String::from_utf8(message))); \
  155. } \
  156. \
  157. ClassName::ClassName(Object& prototype) \
  158. : Error(prototype) \
  159. { \
  160. }
  161. JS_ENUMERATE_NATIVE_ERRORS
  162. #undef __JS_ENUMERATE
  163. }