Error.cpp 8.5 KB

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