1 // Copyright 2006-2008 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // The infrastructure used for (localized) message reporting in V8.
6 //
7 // Note: there's a big unresolved issue about ownership of the data
8 // structures used by this framework.
9 
10 #ifndef V8_MESSAGES_H_
11 #define V8_MESSAGES_H_
12 
13 #include <memory>
14 
15 #include "src/handles.h"
16 
17 namespace v8 {
18 namespace internal {
19 namespace wasm {
20 class WasmCode;
21 }
22 
23 // Forward declarations.
24 class AbstractCode;
25 class FrameArray;
26 class JSMessageObject;
27 class LookupIterator;
28 class SharedFunctionInfo;
29 class SourceInfo;
30 class WasmInstanceObject;
31 
32 class MessageLocation {
33  public:
34   MessageLocation(Handle<Script> script, int start_pos, int end_pos);
35   MessageLocation(Handle<Script> script, int start_pos, int end_pos,
36                   Handle<SharedFunctionInfo> shared);
37   MessageLocation();
38 
script()39   Handle<Script> script() const { return script_; }
start_pos()40   int start_pos() const { return start_pos_; }
end_pos()41   int end_pos() const { return end_pos_; }
shared()42   Handle<SharedFunctionInfo> shared() const { return shared_; }
43 
44  private:
45   Handle<Script> script_;
46   int start_pos_;
47   int end_pos_;
48   Handle<SharedFunctionInfo> shared_;
49 };
50 
51 class StackFrameBase {
52  public:
~StackFrameBase()53   virtual ~StackFrameBase() {}
54 
55   virtual Handle<Object> GetReceiver() const = 0;
56   virtual Handle<Object> GetFunction() const = 0;
57 
58   virtual Handle<Object> GetFileName() = 0;
59   virtual Handle<Object> GetFunctionName() = 0;
60   virtual Handle<Object> GetScriptNameOrSourceUrl() = 0;
61   virtual Handle<Object> GetMethodName() = 0;
62   virtual Handle<Object> GetTypeName() = 0;
63   virtual Handle<Object> GetEvalOrigin();
64 
65   virtual int GetPosition() const = 0;
66   // Return 1-based line number, including line offset.
67   virtual int GetLineNumber() = 0;
68   // Return 1-based column number, including column offset if first line.
69   virtual int GetColumnNumber() = 0;
70 
71   virtual bool IsNative() = 0;
72   virtual bool IsToplevel() = 0;
73   virtual bool IsEval();
74   virtual bool IsConstructor() = 0;
75   virtual bool IsStrict() const = 0;
76 
77   virtual MaybeHandle<String> ToString() = 0;
78 
79  protected:
StackFrameBase()80   StackFrameBase() {}
StackFrameBase(Isolate * isolate)81   explicit StackFrameBase(Isolate* isolate) : isolate_(isolate) {}
82   Isolate* isolate_;
83 
84  private:
85   virtual bool HasScript() const = 0;
86   virtual Handle<Script> GetScript() const = 0;
87 };
88 
89 class JSStackFrame : public StackFrameBase {
90  public:
91   JSStackFrame(Isolate* isolate, Handle<Object> receiver,
92                Handle<JSFunction> function, Handle<AbstractCode> code,
93                int offset);
~JSStackFrame()94   virtual ~JSStackFrame() {}
95 
GetReceiver()96   Handle<Object> GetReceiver() const override { return receiver_; }
97   Handle<Object> GetFunction() const override;
98 
99   Handle<Object> GetFileName() override;
100   Handle<Object> GetFunctionName() override;
101   Handle<Object> GetScriptNameOrSourceUrl() override;
102   Handle<Object> GetMethodName() override;
103   Handle<Object> GetTypeName() override;
104 
105   int GetPosition() const override;
106   int GetLineNumber() override;
107   int GetColumnNumber() override;
108 
109   bool IsNative() override;
110   bool IsToplevel() override;
IsConstructor()111   bool IsConstructor() override { return is_constructor_; }
IsStrict()112   bool IsStrict() const override { return is_strict_; }
113 
114   MaybeHandle<String> ToString() override;
115 
116  private:
117   JSStackFrame();
118   void FromFrameArray(Isolate* isolate, Handle<FrameArray> array, int frame_ix);
119 
120   bool HasScript() const override;
121   Handle<Script> GetScript() const override;
122 
123   Handle<Object> receiver_;
124   Handle<JSFunction> function_;
125   Handle<AbstractCode> code_;
126   int offset_;
127 
128   bool is_constructor_;
129   bool is_strict_;
130 
131   friend class FrameArrayIterator;
132 };
133 
134 class WasmStackFrame : public StackFrameBase {
135  public:
~WasmStackFrame()136   virtual ~WasmStackFrame() {}
137 
138   Handle<Object> GetReceiver() const override;
139   Handle<Object> GetFunction() const override;
140 
GetFileName()141   Handle<Object> GetFileName() override { return Null(); }
142   Handle<Object> GetFunctionName() override;
GetScriptNameOrSourceUrl()143   Handle<Object> GetScriptNameOrSourceUrl() override { return Null(); }
GetMethodName()144   Handle<Object> GetMethodName() override { return Null(); }
GetTypeName()145   Handle<Object> GetTypeName() override { return Null(); }
146 
147   int GetPosition() const override;
GetLineNumber()148   int GetLineNumber() override { return wasm_func_index_; }
GetColumnNumber()149   int GetColumnNumber() override { return -1; }
150 
IsNative()151   bool IsNative() override { return false; }
IsToplevel()152   bool IsToplevel() override { return false; }
IsConstructor()153   bool IsConstructor() override { return false; }
IsStrict()154   bool IsStrict() const override { return false; }
IsInterpreted()155   bool IsInterpreted() const { return code_ == nullptr; }
156 
157   MaybeHandle<String> ToString() override;
158 
159  protected:
160   Handle<Object> Null() const;
161 
162   bool HasScript() const override;
163   Handle<Script> GetScript() const override;
164 
165   Handle<WasmInstanceObject> wasm_instance_;
166   uint32_t wasm_func_index_;
167   wasm::WasmCode* code_;  // null for interpreted frames.
168   int offset_;
169 
170  private:
171   WasmStackFrame();
172   void FromFrameArray(Isolate* isolate, Handle<FrameArray> array, int frame_ix);
173 
174   friend class FrameArrayIterator;
175   friend class AsmJsWasmStackFrame;
176 };
177 
178 class AsmJsWasmStackFrame : public WasmStackFrame {
179  public:
~AsmJsWasmStackFrame()180   virtual ~AsmJsWasmStackFrame() {}
181 
182   Handle<Object> GetReceiver() const override;
183   Handle<Object> GetFunction() const override;
184 
185   Handle<Object> GetFileName() override;
186   Handle<Object> GetScriptNameOrSourceUrl() override;
187 
188   int GetPosition() const override;
189   int GetLineNumber() override;
190   int GetColumnNumber() override;
191 
192   MaybeHandle<String> ToString() override;
193 
194  private:
195   friend class FrameArrayIterator;
196   AsmJsWasmStackFrame();
197   void FromFrameArray(Isolate* isolate, Handle<FrameArray> array, int frame_ix);
198 
199   bool is_at_number_conversion_;
200 };
201 
202 class FrameArrayIterator {
203  public:
204   FrameArrayIterator(Isolate* isolate, Handle<FrameArray> array,
205                      int frame_ix = 0);
206 
207   StackFrameBase* Frame();
208 
209   bool HasNext() const;
210   void Next();
211 
212  private:
213   Isolate* isolate_;
214 
215   Handle<FrameArray> array_;
216   int next_frame_ix_;
217 
218   WasmStackFrame wasm_frame_;
219   AsmJsWasmStackFrame asm_wasm_frame_;
220   JSStackFrame js_frame_;
221 };
222 
223 // Determines how stack trace collection skips frames.
224 enum FrameSkipMode {
225   // Unconditionally skips the first frame. Used e.g. when the Error constructor
226   // is called, in which case the first frame is always a BUILTIN_EXIT frame.
227   SKIP_FIRST,
228   // Skip all frames until a specified caller function is seen.
229   SKIP_UNTIL_SEEN,
230   SKIP_NONE,
231 };
232 
233 class ErrorUtils : public AllStatic {
234  public:
235   static MaybeHandle<Object> Construct(
236       Isolate* isolate, Handle<JSFunction> target, Handle<Object> new_target,
237       Handle<Object> message, FrameSkipMode mode, Handle<Object> caller,
238       bool suppress_detailed_trace);
239 
240   static MaybeHandle<String> ToString(Isolate* isolate, Handle<Object> recv);
241 
242   static MaybeHandle<Object> MakeGenericError(
243       Isolate* isolate, Handle<JSFunction> constructor, int template_index,
244       Handle<Object> arg0, Handle<Object> arg1, Handle<Object> arg2,
245       FrameSkipMode mode);
246 
247   // Formats a textual stack trace from the given structured stack trace.
248   // Note that this can call arbitrary JS code through Error.prepareStackTrace.
249   static MaybeHandle<Object> FormatStackTrace(Isolate* isolate,
250                                               Handle<JSObject> error,
251                                               Handle<Object> stack_trace);
252 };
253 
254 #define MESSAGE_TEMPLATES(T)                                                   \
255   /* Error */                                                                  \
256   T(None, "")                                                                  \
257   T(CyclicProto, "Cyclic __proto__ value")                                     \
258   T(Debugger, "Debugger: %")                                                   \
259   T(DebuggerLoading, "Error loading debugger")                                 \
260   T(DefaultOptionsMissing, "Internal % error. Default options are missing.")   \
261   T(DeletePrivateField, "Private fields can not be deleted")                   \
262   T(UncaughtException, "Uncaught %")                                           \
263   T(Unsupported, "Not supported")                                              \
264   T(WrongServiceType, "Internal error, wrong service type: %")                 \
265   T(WrongValueType, "Internal error. Wrong value type.")                       \
266   T(IcuError, "Internal error. Icu error.")                                    \
267   /* TypeError */                                                              \
268   T(ApplyNonFunction,                                                          \
269     "Function.prototype.apply was called on %, which is a % and not a "        \
270     "function")                                                                \
271   T(ArgumentsDisallowedInInitializer,                                          \
272     "'arguments' is not allowed in class field initializer")                   \
273   T(ArrayBufferTooShort,                                                       \
274     "Derived ArrayBuffer constructor created a buffer which was too small")    \
275   T(ArrayBufferSpeciesThis,                                                    \
276     "ArrayBuffer subclass returned this from species constructor")             \
277   T(ArrayItemNotType, "array %[%] is not type %")                              \
278   T(AwaitNotInAsyncFunction, "await is only valid in async function")          \
279   T(AtomicsWaitNotAllowed, "Atomics.wait cannot be called in this context")    \
280   T(BadSortComparisonFunction,                                                 \
281     "The comparison function must be either a function or undefined")          \
282   T(BigIntFromNumber,                                                          \
283     "The number % cannot be converted to a BigInt because it is not an "       \
284     "integer")                                                                 \
285   T(BigIntFromObject, "Cannot convert % to a BigInt")                          \
286   T(BigIntMixedTypes,                                                          \
287     "Cannot mix BigInt and other types, use explicit conversions")             \
288   T(BigIntSerializeJSON, "Do not know how to serialize a BigInt")              \
289   T(BigIntShr, "BigInts have no unsigned right shift, use >> instead")         \
290   T(BigIntToNumber, "Cannot convert a BigInt value to a number")               \
291   T(CalledNonCallable, "% is not a function")                                  \
292   T(CalledOnNonObject, "% called on non-object")                               \
293   T(CalledOnNullOrUndefined, "% called on null or undefined")                  \
294   T(CallSiteExpectsFunction,                                                   \
295     "CallSite expects wasm object as first or function as second argument, "   \
296     "got <%, %>")                                                              \
297   T(CallSiteMethod, "CallSite method % expects CallSite as receiver")          \
298   T(CannotConvertToPrimitive, "Cannot convert object to primitive value")      \
299   T(CannotPreventExt, "Cannot prevent extensions")                             \
300   T(CannotFreeze, "Cannot freeze")                                             \
301   T(CannotFreezeArrayBufferView,                                               \
302     "Cannot freeze array buffer views with elements")                          \
303   T(CannotSeal, "Cannot seal")                                                 \
304   T(CircularStructure, "Converting circular structure to JSON")                \
305   T(ConstructAbstractClass, "Abstract class % not directly constructable")     \
306   T(ConstAssign, "Assignment to constant variable.")                           \
307   T(ConstructorClassField, "Classes may not have a field named 'constructor'") \
308   T(ConstructorNonCallable,                                                    \
309     "Class constructor % cannot be invoked without 'new'")                     \
310   T(ConstructorNotFunction, "Constructor % requires 'new'")                    \
311   T(ConstructorNotReceiver, "The .constructor property is not an object")      \
312   T(CurrencyCode, "Currency code is required with currency style.")            \
313   T(CyclicModuleDependency, "Detected cycle while resolving name '%' in '%'")  \
314   T(DataViewNotArrayBuffer,                                                    \
315     "First argument to DataView constructor must be an ArrayBuffer")           \
316   T(DateType, "this is not a Date object.")                                    \
317   T(DebuggerFrame, "Debugger: Invalid frame index.")                           \
318   T(DebuggerType, "Debugger: Parameters have wrong types.")                    \
319   T(DeclarationMissingInitializer, "Missing initializer in % declaration")     \
320   T(DefineDisallowed, "Cannot define property %, object is not extensible")    \
321   T(DetachedOperation, "Cannot perform % on a detached ArrayBuffer")           \
322   T(DuplicateTemplateProperty, "Object template has duplicate property '%'")   \
323   T(ExtendsValueNotConstructor,                                                \
324     "Class extends value % is not a constructor or null")                      \
325   T(FirstArgumentNotRegExp,                                                    \
326     "First argument to % must not be a regular expression")                    \
327   T(FunctionBind, "Bind must be called on a function")                         \
328   T(GeneratorRunning, "Generator is already running")                          \
329   T(IllegalInvocation, "Illegal invocation")                                   \
330   T(ImmutablePrototypeSet,                                                     \
331     "Immutable prototype object '%' cannot have their prototype set")          \
332   T(ImportCallNotNewExpression, "Cannot use new with import")                  \
333   T(ImportMetaOutsideModule, "Cannot use 'import.meta' outside a module")      \
334   T(ImportMissingSpecifier, "import() requires a specifier")                   \
335   T(IncompatibleMethodReceiver, "Method % called on incompatible receiver %")  \
336   T(InstanceofNonobjectProto,                                                  \
337     "Function has non-object prototype '%' in instanceof check")               \
338   T(InvalidArgument, "invalid_argument")                                       \
339   T(InvalidInOperatorUse, "Cannot use 'in' operator to search for '%' in %")   \
340   T(InvalidRegExpExecResult,                                                   \
341     "RegExp exec method returned something other than an Object or null")      \
342   T(InvalidUnit, "Invalid unit argument for %() '%'")                          \
343   T(IteratorResultNotAnObject, "Iterator result % is not an object")           \
344   T(IteratorSymbolNonCallable, "Found non-callable @@iterator")                \
345   T(IteratorValueNotAnObject, "Iterator value % is not an entry object")       \
346   T(LanguageID, "Language ID should be string or object.")                     \
347   T(LocaleNotEmpty,                                                            \
348     "First argument to Intl.Locale constructor can't be empty or missing")     \
349   T(LocaleBadParameters, "Incorrect locale information provided")              \
350   T(ListFormatBadParameters, "Incorrect ListFormat information provided")      \
351   T(MapperFunctionNonCallable, "flatMap mapper function is not callable")      \
352   T(MethodCalledOnWrongObject,                                                 \
353     "Method % called on a non-object or on a wrong type of object.")           \
354   T(MethodInvokedOnNullOrUndefined,                                            \
355     "Method invoked on undefined or null value.")                              \
356   T(MethodInvokedOnWrongType, "Method invoked on an object that is not %.")    \
357   T(NoAccess, "no access")                                                     \
358   T(NonCallableInInstanceOfCheck,                                              \
359     "Right-hand side of 'instanceof' is not callable")                         \
360   T(NonCoercible, "Cannot destructure 'undefined' or 'null'.")                 \
361   T(NonCoercibleWithProperty,                                                  \
362     "Cannot destructure property `%` of 'undefined' or 'null'.")               \
363   T(NonExtensibleProto, "% is not extensible")                                 \
364   T(NonObjectInInstanceOfCheck,                                                \
365     "Right-hand side of 'instanceof' is not an object")                        \
366   T(NonObjectPropertyLoad, "Cannot read property '%' of %")                    \
367   T(NonObjectPropertyStore, "Cannot set property '%' of %")                    \
368   T(NoSetterInCallback, "Cannot set property % of % which has only a getter")  \
369   T(NotAnIterator, "% is not an iterator")                                     \
370   T(NotAPromise, "% is not a promise")                                         \
371   T(NotConstructor, "% is not a constructor")                                  \
372   T(NotDateObject, "this is not a Date object.")                               \
373   T(NotGeneric, "% requires that 'this' be a %")                               \
374   T(NotCallableOrIterable,                                                     \
375     "% is not a function or its return value is not iterable")                 \
376   T(NotCallableOrAsyncIterable,                                                \
377     "% is not a function or its return value is not async iterable")           \
378   T(NotFiniteNumber, "Value need to be finite number for %()")                 \
379   T(NotIterable, "% is not iterable")                                          \
380   T(NotAsyncIterable, "% is not async iterable")                               \
381   T(NotPropertyName, "% is not a valid property name")                         \
382   T(NotTypedArray, "this is not a typed array.")                               \
383   T(NotSuperConstructor, "Super constructor % of % is not a constructor")      \
384   T(NotSuperConstructorAnonymousClass,                                         \
385     "Super constructor % of anonymous class is not a constructor")             \
386   T(NotIntegerSharedTypedArray, "% is not an integer shared typed array.")     \
387   T(NotInt32SharedTypedArray, "% is not an int32 shared typed array.")         \
388   T(ObjectGetterExpectingFunction,                                             \
389     "Object.prototype.__defineGetter__: Expecting function")                   \
390   T(ObjectGetterCallable, "Getter must be a function: %")                      \
391   T(ObjectNotExtensible, "Cannot add property %, object is not extensible")    \
392   T(ObjectSetterExpectingFunction,                                             \
393     "Object.prototype.__defineSetter__: Expecting function")                   \
394   T(ObjectSetterCallable, "Setter must be a function: %")                      \
395   T(OrdinaryFunctionCalledAsConstructor,                                       \
396     "Function object that's not a constructor was created with new")           \
397   T(PromiseCyclic, "Chaining cycle detected for promise %")                    \
398   T(PromiseExecutorAlreadyInvoked,                                             \
399     "Promise executor has already been invoked with non-undefined arguments")  \
400   T(PromiseNonCallable, "Promise resolve or reject function is not callable")  \
401   T(PropertyDescObject, "Property description must be an object: %")           \
402   T(PropertyNotFunction,                                                       \
403     "'%' returned for property '%' of object '%' is not a function")           \
404   T(ProtoObjectOrNull, "Object prototype may only be an Object or null: %")    \
405   T(PrototypeParentNotAnObject,                                                \
406     "Class extends value does not have valid prototype property %")            \
407   T(ProxyConstructNonObject,                                                   \
408     "'construct' on proxy: trap returned non-object ('%')")                    \
409   T(ProxyDefinePropertyNonConfigurable,                                        \
410     "'defineProperty' on proxy: trap returned truish for defining "            \
411     "non-configurable property '%' which is either non-existant or "           \
412     "configurable in the proxy target")                                        \
413   T(ProxyDefinePropertyNonExtensible,                                          \
414     "'defineProperty' on proxy: trap returned truish for adding property '%' " \
415     " to the non-extensible proxy target")                                     \
416   T(ProxyDefinePropertyIncompatible,                                           \
417     "'defineProperty' on proxy: trap returned truish for adding property '%' " \
418     " that is incompatible with the existing property in the proxy target")    \
419   T(ProxyDeletePropertyNonConfigurable,                                        \
420     "'deleteProperty' on proxy: trap returned truish for property '%' which "  \
421     "is non-configurable in the proxy target")                                 \
422   T(ProxyGetNonConfigurableData,                                               \
423     "'get' on proxy: property '%' is a read-only and "                         \
424     "non-configurable data property on the proxy target but the proxy "        \
425     "did not return its actual value (expected '%' but got '%')")              \
426   T(ProxyGetNonConfigurableAccessor,                                           \
427     "'get' on proxy: property '%' is a non-configurable accessor "             \
428     "property on the proxy target and does not have a getter function, but "   \
429     "the trap did not return 'undefined' (got '%')")                           \
430   T(ProxyGetOwnPropertyDescriptorIncompatible,                                 \
431     "'getOwnPropertyDescriptor' on proxy: trap returned descriptor for "       \
432     "property '%' that is incompatible with the existing property in the "     \
433     "proxy target")                                                            \
434   T(ProxyGetOwnPropertyDescriptorInvalid,                                      \
435     "'getOwnPropertyDescriptor' on proxy: trap returned neither object nor "   \
436     "undefined for property '%'")                                              \
437   T(ProxyGetOwnPropertyDescriptorNonConfigurable,                              \
438     "'getOwnPropertyDescriptor' on proxy: trap reported non-configurability "  \
439     "for property '%' which is either non-existant or configurable in the "    \
440     "proxy target")                                                            \
441   T(ProxyGetOwnPropertyDescriptorNonExtensible,                                \
442     "'getOwnPropertyDescriptor' on proxy: trap returned undefined for "        \
443     "property '%' which exists in the non-extensible proxy target")            \
444   T(ProxyGetOwnPropertyDescriptorUndefined,                                    \
445     "'getOwnPropertyDescriptor' on proxy: trap returned undefined for "        \
446     "property '%' which is non-configurable in the proxy target")              \
447   T(ProxyGetPrototypeOfInvalid,                                                \
448     "'getPrototypeOf' on proxy: trap returned neither object nor null")        \
449   T(ProxyGetPrototypeOfNonExtensible,                                          \
450     "'getPrototypeOf' on proxy: proxy target is non-extensible but the "       \
451     "trap did not return its actual prototype")                                \
452   T(ProxyHandlerOrTargetRevoked,                                               \
453     "Cannot create proxy with a revoked proxy as target or handler")           \
454   T(ProxyHasNonConfigurable,                                                   \
455     "'has' on proxy: trap returned falsish for property '%' which exists in "  \
456     "the proxy target as non-configurable")                                    \
457   T(ProxyHasNonExtensible,                                                     \
458     "'has' on proxy: trap returned falsish for property '%' but the proxy "    \
459     "target is not extensible")                                                \
460   T(ProxyIsExtensibleInconsistent,                                             \
461     "'isExtensible' on proxy: trap result does not reflect extensibility of "  \
462     "proxy target (which is '%')")                                             \
463   T(ProxyNonObject,                                                            \
464     "Cannot create proxy with a non-object as target or handler")              \
465   T(ProxyOwnKeysMissing,                                                       \
466     "'ownKeys' on proxy: trap result did not include '%'")                     \
467   T(ProxyOwnKeysNonExtensible,                                                 \
468     "'ownKeys' on proxy: trap returned extra keys but proxy target is "        \
469     "non-extensible")                                                          \
470   T(ProxyPreventExtensionsExtensible,                                          \
471     "'preventExtensions' on proxy: trap returned truish but the proxy target " \
472     "is extensible")                                                           \
473   T(ProxyPrivate, "Cannot pass private property name to proxy trap")           \
474   T(ProxyRevoked, "Cannot perform '%' on a proxy that has been revoked")       \
475   T(ProxySetFrozenData,                                                        \
476     "'set' on proxy: trap returned truish for property '%' which exists in "   \
477     "the proxy target as a non-configurable and non-writable data property "   \
478     "with a different value")                                                  \
479   T(ProxySetFrozenAccessor,                                                    \
480     "'set' on proxy: trap returned truish for property '%' which exists in "   \
481     "the proxy target as a non-configurable and non-writable accessor "        \
482     "property without a setter")                                               \
483   T(ProxySetPrototypeOfNonExtensible,                                          \
484     "'setPrototypeOf' on proxy: trap returned truish for setting a new "       \
485     "prototype on the non-extensible proxy target")                            \
486   T(ProxyTrapReturnedFalsish, "'%' on proxy: trap returned falsish")           \
487   T(ProxyTrapReturnedFalsishFor,                                               \
488     "'%' on proxy: trap returned falsish for property '%'")                    \
489   T(RedefineDisallowed, "Cannot redefine property: %")                         \
490   T(RedefineExternalArray,                                                     \
491     "Cannot redefine a property of an object with external array elements")    \
492   T(ReduceNoInitial, "Reduce of empty array with no initial value")            \
493   T(RegExpFlags,                                                               \
494     "Cannot supply flags when constructing one RegExp from another")           \
495   T(RegExpNonObject, "% getter called on non-object %")                        \
496   T(RegExpNonRegExp, "% getter called on non-RegExp object")                   \
497   T(RelativeDateTimeFormatterBadParameters,                                    \
498     "Incorrect RelativeDateTimeFormatter provided")                            \
499   T(ResolverNotAFunction, "Promise resolver % is not a function")              \
500   T(ReturnMethodNotCallable, "The iterator's 'return' method is not callable") \
501   T(SharedArrayBufferTooShort,                                                 \
502     "Derived SharedArrayBuffer constructor created a buffer which was too "    \
503     "small")                                                                   \
504   T(SharedArrayBufferSpeciesThis,                                              \
505     "SharedArrayBuffer subclass returned this from species constructor")       \
506   T(StaticPrototype,                                                           \
507     "Classes may not have a static property named 'prototype'")                \
508   T(StrictDeleteProperty, "Cannot delete property '%' of %")                   \
509   T(StrictPoisonPill,                                                          \
510     "'caller', 'callee', and 'arguments' properties may not be accessed on "   \
511     "strict mode functions or the arguments objects for calls to them")        \
512   T(StrictReadOnlyProperty,                                                    \
513     "Cannot assign to read only property '%' of % '%'")                        \
514   T(StrictCannotCreateProperty, "Cannot create property '%' on % '%'")         \
515   T(SymbolIteratorInvalid,                                                     \
516     "Result of the Symbol.iterator method is not an object")                   \
517   T(SymbolAsyncIteratorInvalid,                                                \
518     "Result of the Symbol.asyncIterator method is not an object")              \
519   T(SymbolKeyFor, "% is not a symbol")                                         \
520   T(SymbolToNumber, "Cannot convert a Symbol value to a number")               \
521   T(SymbolToString, "Cannot convert a Symbol value to a string")               \
522   T(ThrowMethodMissing, "The iterator does not provide a 'throw' method.")     \
523   T(UndefinedOrNullToObject, "Cannot convert undefined or null to object")     \
524   T(ValueAndAccessor,                                                          \
525     "Invalid property descriptor. Cannot both specify accessors and a value "  \
526     "or writable attribute, %")                                                \
527   T(VarRedeclaration, "Identifier '%' has already been declared")              \
528   T(WrongArgs, "%: Arguments list has wrong type")                             \
529   /* ReferenceError */                                                         \
530   T(NotDefined, "% is not defined")                                            \
531   T(SuperAlreadyCalled, "Super constructor may only be called once")           \
532   T(UnsupportedSuper, "Unsupported reference to 'super'")                      \
533   /* RangeError */                                                             \
534   T(BigIntDivZero, "Division by zero")                                         \
535   T(BigIntNegativeExponent, "Exponent must be positive")                       \
536   T(BigIntTooBig, "Maximum BigInt size exceeded")                              \
537   T(DateRange, "Provided date is not in valid range.")                         \
538   T(ExpectedLocation,                                                          \
539     "Expected letters optionally connected with underscores or hyphens for "   \
540     "a location, got %")                                                       \
541   T(InvalidArrayBufferLength, "Invalid array buffer length")                   \
542   T(ArrayBufferAllocationFailed, "Array buffer allocation failed")             \
543   T(InvalidArrayLength, "Invalid array length")                                \
544   T(InvalidAtomicAccessIndex, "Invalid atomic access index")                   \
545   T(InvalidCodePoint, "Invalid code point %")                                  \
546   T(InvalidCountValue, "Invalid count value")                                  \
547   T(InvalidCurrencyCode, "Invalid currency code: %")                           \
548   T(InvalidDataViewAccessorOffset,                                             \
549     "Offset is outside the bounds of the DataView")                            \
550   T(InvalidDataViewLength, "Invalid DataView length %")                        \
551   T(InvalidOffset, "Start offset % is outside the bounds of the buffer")       \
552   T(InvalidHint, "Invalid hint: %")                                            \
553   T(InvalidIndex, "Invalid value: not (convertible to) a safe integer")        \
554   T(InvalidLanguageTag, "Invalid language tag: %")                             \
555   T(InvalidWeakMapKey, "Invalid value used as weak map key")                   \
556   T(InvalidWeakSetValue, "Invalid value used in weak set")                     \
557   T(InvalidStringLength, "Invalid string length")                              \
558   T(InvalidTimeValue, "Invalid time value")                                    \
559   T(InvalidTimeZone, "Invalid time zone specified: %")                         \
560   T(InvalidTypedArrayAlignment, "% of % should be a multiple of %")            \
561   T(InvalidTypedArrayIndex, "Invalid typed array index")                       \
562   T(InvalidTypedArrayLength, "Invalid typed array length: %")                  \
563   T(LetInLexicalBinding, "let is disallowed as a lexically bound name")        \
564   T(LocaleMatcher, "Illegal value for localeMatcher:%")                        \
565   T(NormalizationForm, "The normalization form should be one of %.")           \
566   T(ZeroDigitNumericSeparator,                                                 \
567     "Numeric separator can not be used after leading 0.")                      \
568   T(NumberFormatRange, "% argument must be between 0 and 100")                 \
569   T(TrailingNumericSeparator,                                                  \
570     "Numeric separators are not allowed at the end of numeric literals")       \
571   T(ContinuousNumericSeparator,                                                \
572     "Only one underscore is allowed as numeric separator")                     \
573   T(PropertyValueOutOfRange, "% value is out of range.")                       \
574   T(StackOverflow, "Maximum call stack size exceeded")                         \
575   T(ToPrecisionFormatRange,                                                    \
576     "toPrecision() argument must be between 1 and 100")                        \
577   T(ToRadixFormatRange, "toString() radix argument must be between 2 and 36")  \
578   T(TypedArraySetOffsetOutOfBounds, "offset is out of bounds")                 \
579   T(TypedArraySetSourceTooLarge, "Source is too large")                        \
580   T(ValueOutOfRange, "Value % out of range for % options property %")          \
581   /* SyntaxError */                                                            \
582   T(AmbiguousExport,                                                           \
583     "The requested module '%' contains conflicting star exports for name '%'") \
584   T(BadGetterArity, "Getter must not have any formal parameters.")             \
585   T(BadSetterArity, "Setter must have exactly one formal parameter.")          \
586   T(BigIntInvalidString, "Invalid BigInt string")                              \
587   T(ConstructorIsAccessor, "Class constructor may not be an accessor")         \
588   T(ConstructorIsGenerator, "Class constructor may not be a generator")        \
589   T(ConstructorIsAsync, "Class constructor may not be an async method")        \
590   T(DerivedConstructorReturnedNonObject,                                       \
591     "Derived constructors may only return object or undefined")                \
592   T(DuplicateConstructor, "A class may only have one constructor")             \
593   T(DuplicateExport, "Duplicate export of '%'")                                \
594   T(DuplicateProto,                                                            \
595     "Duplicate __proto__ fields are not allowed in object literals")           \
596   T(ForInOfLoopInitializer,                                                    \
597     "% loop variable declaration may not have an initializer.")                \
598   T(ForInOfLoopMultiBindings,                                                  \
599     "Invalid left-hand side in % loop: Must have a single binding.")           \
600   T(GeneratorInSingleStatementContext,                                         \
601     "Generators can only be declared at the top level or inside a block.")     \
602   T(AsyncFunctionInSingleStatementContext,                                     \
603     "Async functions can only be declared at the top level or inside a "       \
604     "block.")                                                                  \
605   T(IllegalBreak, "Illegal break statement")                                   \
606   T(NoIterationStatement,                                                      \
607     "Illegal continue statement: no surrounding iteration statement")          \
608   T(IllegalContinue,                                                           \
609     "Illegal continue statement: '%' does not denote an iteration statement")  \
610   T(IllegalLanguageModeDirective,                                              \
611     "Illegal '%' directive in function with non-simple parameter list")        \
612   T(IllegalReturn, "Illegal return statement")                                 \
613   T(IntrinsicWithSpread, "Intrinsic calls do not support spread arguments")    \
614   T(InvalidRestBindingPattern,                                                 \
615     "`...` must be followed by an identifier in declaration contexts")         \
616   T(InvalidRestAssignmentPattern,                                              \
617     "`...` must be followed by an assignable reference in assignment "         \
618     "contexts")                                                                \
619   T(InvalidEscapedReservedWord, "Keyword must not contain escaped characters") \
620   T(InvalidEscapedMetaProperty, "'%' must not contain escaped characters")     \
621   T(InvalidLhsInAssignment, "Invalid left-hand side in assignment")            \
622   T(InvalidCoverInitializedName, "Invalid shorthand property initializer")     \
623   T(InvalidDestructuringTarget, "Invalid destructuring assignment target")     \
624   T(InvalidLhsInFor, "Invalid left-hand side in for-loop")                     \
625   T(InvalidLhsInPostfixOp,                                                     \
626     "Invalid left-hand side expression in postfix operation")                  \
627   T(InvalidLhsInPrefixOp,                                                      \
628     "Invalid left-hand side expression in prefix operation")                   \
629   T(InvalidRegExpFlags, "Invalid flags supplied to RegExp constructor '%'")    \
630   T(InvalidOrUnexpectedToken, "Invalid or unexpected token")                   \
631   T(InvalidPrivateFieldAccess, "Invalid private field '%'")                    \
632   T(JsonParseUnexpectedEOS, "Unexpected end of JSON input")                    \
633   T(JsonParseUnexpectedToken, "Unexpected token % in JSON at position %")      \
634   T(JsonParseUnexpectedTokenNumber, "Unexpected number in JSON at position %") \
635   T(JsonParseUnexpectedTokenString, "Unexpected string in JSON at position %") \
636   T(LabelRedeclaration, "Label '%' has already been declared")                 \
637   T(LabelledFunctionDeclaration,                                               \
638     "Labelled function declaration not allowed as the body of a control flow " \
639     "structure")                                                               \
640   T(MalformedArrowFunParamList, "Malformed arrow function parameter list")     \
641   T(MalformedRegExp, "Invalid regular expression: /%/: %")                     \
642   T(MalformedRegExpFlags, "Invalid regular expression flags")                  \
643   T(ModuleExportUndefined, "Export '%' is not defined in module")              \
644   T(HtmlCommentInModule, "HTML comments are not allowed in modules")           \
645   T(MultipleDefaultsInSwitch,                                                  \
646     "More than one default clause in switch statement")                        \
647   T(NewlineAfterThrow, "Illegal newline after throw")                          \
648   T(NoCatchOrFinally, "Missing catch or finally after try")                    \
649   T(NotIsvar, "builtin %%IS_VAR: not a variable")                              \
650   T(ParamAfterRest, "Rest parameter must be last formal parameter")            \
651   T(FlattenPastSafeLength,                                                     \
652     "Flattening % elements on an array-like of length % "                      \
653     "is disallowed, as the total surpasses 2**53-1")                           \
654   T(PushPastSafeLength,                                                        \
655     "Pushing % elements on an array-like of length % "                         \
656     "is disallowed, as the total surpasses 2**53-1")                           \
657   T(ElementAfterRest, "Rest element must be last element")                     \
658   T(BadSetterRestParameter,                                                    \
659     "Setter function argument must not be a rest parameter")                   \
660   T(ParamDupe, "Duplicate parameter name not allowed in this context")         \
661   T(ParenthesisInArgString, "Function arg string contains parenthesis")        \
662   T(ArgStringTerminatesParametersEarly,                                        \
663     "Arg string terminates parameters early")                                  \
664   T(UnexpectedEndOfArgString, "Unexpected end of arg string")                  \
665   T(RestDefaultInitializer,                                                    \
666     "Rest parameter may not have a default initializer")                       \
667   T(RuntimeWrongNumArgs, "Runtime function given wrong number of arguments")   \
668   T(SuperNotCalled,                                                            \
669     "Must call super constructor in derived class before accessing 'this' or " \
670     "returning from derived constructor")                                      \
671   T(SingleFunctionLiteral, "Single function literal required")                 \
672   T(SloppyFunction,                                                            \
673     "In non-strict mode code, functions can only be declared at top level, "   \
674     "inside a block, or as the body of an if statement.")                      \
675   T(SpeciesNotConstructor,                                                     \
676     "object.constructor[Symbol.species] is not a constructor")                 \
677   T(StrictDelete, "Delete of an unqualified identifier in strict mode.")       \
678   T(StrictEvalArguments, "Unexpected eval or arguments in strict mode")        \
679   T(StrictFunction,                                                            \
680     "In strict mode code, functions can only be declared at top level or "     \
681     "inside a block.")                                                         \
682   T(StrictOctalLiteral, "Octal literals are not allowed in strict mode.")      \
683   T(StrictDecimalWithLeadingZero,                                              \
684     "Decimals with leading zeros are not allowed in strict mode.")             \
685   T(StrictOctalEscape,                                                         \
686     "Octal escape sequences are not allowed in strict mode.")                  \
687   T(StrictWith, "Strict mode code may not include a with statement")           \
688   T(TemplateOctalLiteral,                                                      \
689     "Octal escape sequences are not allowed in template strings.")             \
690   T(ThisFormalParameter, "'this' is not a valid formal parameter name")        \
691   T(AwaitBindingIdentifier,                                                    \
692     "'await' is not a valid identifier name in an async function")             \
693   T(AwaitExpressionFormalParameter,                                            \
694     "Illegal await-expression in formal parameters of async function")         \
695   T(TooManyArguments,                                                          \
696     "Too many arguments in function call (only 65535 allowed)")                \
697   T(TooManyParameters,                                                         \
698     "Too many parameters in function definition (only 65535 allowed)")         \
699   T(TooManySpreads,                                                            \
700     "Literal containing too many nested spreads (up to 65534 allowed)")        \
701   T(TooManyVariables, "Too many variables declared (only 4194303 allowed)")    \
702   T(TooManyElementsInPromiseAll, "Too many elements passed to Promise.all")    \
703   T(TypedArrayTooShort,                                                        \
704     "Derived TypedArray constructor created an array which was too small")     \
705   T(UnexpectedEOS, "Unexpected end of input")                                  \
706   T(UnexpectedReserved, "Unexpected reserved word")                            \
707   T(UnexpectedStrictReserved, "Unexpected strict mode reserved word")          \
708   T(UnexpectedSuper, "'super' keyword unexpected here")                        \
709   T(UnexpectedNewTarget, "new.target expression is not allowed here")          \
710   T(UnexpectedTemplateString, "Unexpected template string")                    \
711   T(UnexpectedToken, "Unexpected token %")                                     \
712   T(UnexpectedTokenIdentifier, "Unexpected identifier")                        \
713   T(UnexpectedTokenNumber, "Unexpected number")                                \
714   T(UnexpectedTokenString, "Unexpected string")                                \
715   T(UnexpectedTokenRegExp, "Unexpected regular expression")                    \
716   T(UnexpectedLexicalDeclaration,                                              \
717     "Lexical declaration cannot appear in a single-statement context")         \
718   T(UnknownLabel, "Undefined label '%'")                                       \
719   T(UnresolvableExport,                                                        \
720     "The requested module '%' does not provide an export named '%'")           \
721   T(UnterminatedArgList, "missing ) after argument list")                      \
722   T(UnterminatedRegExp, "Invalid regular expression: missing /")               \
723   T(UnterminatedTemplate, "Unterminated template literal")                     \
724   T(UnterminatedTemplateExpr, "Missing } in template expression")              \
725   T(FoundNonCallableHasInstance, "Found non-callable @@hasInstance")           \
726   T(InvalidHexEscapeSequence, "Invalid hexadecimal escape sequence")           \
727   T(InvalidUnicodeEscapeSequence, "Invalid Unicode escape sequence")           \
728   T(UndefinedUnicodeCodePoint, "Undefined Unicode code-point")                 \
729   T(YieldInParameter, "Yield expression not allowed in formal parameter")      \
730   /* EvalError */                                                              \
731   T(CodeGenFromStrings, "%")                                                   \
732   T(NoSideEffectDebugEvaluate, "Possible side-effect in debug-evaluate")       \
733   /* URIError */                                                               \
734   T(URIMalformed, "URI malformed")                                             \
735   /* Wasm errors (currently Error) */                                          \
736   T(WasmTrapUnreachable, "unreachable")                                        \
737   T(WasmTrapMemOutOfBounds, "memory access out of bounds")                     \
738   T(WasmTrapUnalignedAccess, "operation does not support unaligned accesses")  \
739   T(WasmTrapDivByZero, "divide by zero")                                       \
740   T(WasmTrapDivUnrepresentable, "divide result unrepresentable")               \
741   T(WasmTrapRemByZero, "remainder by zero")                                    \
742   T(WasmTrapFloatUnrepresentable, "float unrepresentable in integer range")    \
743   T(WasmTrapFuncInvalid, "invalid index into function table")                  \
744   T(WasmTrapFuncSigMismatch, "function signature mismatch")                    \
745   T(WasmTrapTypeError, "wasm function signature contains illegal type")        \
746   T(WasmExceptionError, "wasm exception")                                      \
747   /* Asm.js validation related */                                              \
748   T(AsmJsInvalid, "Invalid asm.js: %")                                         \
749   T(AsmJsCompiled, "Converted asm.js to WebAssembly: %")                       \
750   T(AsmJsInstantiated, "Instantiated asm.js: %")                               \
751   T(AsmJsLinkingFailed, "Linking failure in asm.js: %")                        \
752   /* DataCloneError messages */                                                \
753   T(DataCloneError, "% could not be cloned.")                                  \
754   T(DataCloneErrorOutOfMemory, "Data cannot be cloned, out of memory.")        \
755   T(DataCloneErrorNeuteredArrayBuffer,                                         \
756     "An ArrayBuffer is neutered and could not be cloned.")                     \
757   T(DataCloneErrorSharedArrayBufferTransferred,                                \
758     "A SharedArrayBuffer could not be cloned. SharedArrayBuffer must not be "  \
759     "transferred.")                                                            \
760   T(DataCloneDeserializationError, "Unable to deserialize cloned data.")       \
761   T(DataCloneDeserializationVersionError,                                      \
762     "Unable to deserialize cloned data due to invalid or unsupported "         \
763     "version.")                                                                \
764   /* Builtins-Trace Errors */                                                  \
765   T(TraceEventCategoryError, "Trace event category must be a string.")         \
766   T(TraceEventNameError, "Trace event name must be a string.")                 \
767   T(TraceEventNameLengthError,                                                 \
768     "Trace event name must not be an empty string.")                           \
769   T(TraceEventPhaseError, "Trace event phase must be a number.")               \
770   T(TraceEventIDError, "Trace event id must be a number.")
771 
772 class MessageTemplate {
773  public:
774   enum Template {
775 #define TEMPLATE(NAME, STRING) k##NAME,
776     MESSAGE_TEMPLATES(TEMPLATE)
777 #undef TEMPLATE
778         kLastMessage
779   };
780 
781   static const char* TemplateString(int template_index);
782 
783   static MaybeHandle<String> FormatMessage(Isolate* isolate, int template_index,
784                                            Handle<String> arg0,
785                                            Handle<String> arg1,
786                                            Handle<String> arg2);
787 
788   static Handle<String> FormatMessage(Isolate* isolate, int template_index,
789                                       Handle<Object> arg);
790 };
791 
792 
793 // A message handler is a convenience interface for accessing the list
794 // of message listeners registered in an environment
795 class MessageHandler {
796  public:
797   // Returns a message object for the API to use.
798   static Handle<JSMessageObject> MakeMessageObject(
799       Isolate* isolate, MessageTemplate::Template type,
800       const MessageLocation* location, Handle<Object> argument,
801       Handle<FixedArray> stack_frames);
802 
803   // Report a formatted message (needs JS allocation).
804   static void ReportMessage(Isolate* isolate, const MessageLocation* loc,
805                             Handle<JSMessageObject> message);
806 
807   static void DefaultMessageReport(Isolate* isolate, const MessageLocation* loc,
808                                    Handle<Object> message_obj);
809   static Handle<String> GetMessage(Isolate* isolate, Handle<Object> data);
810   static std::unique_ptr<char[]> GetLocalizedMessage(Isolate* isolate,
811                                                      Handle<Object> data);
812 
813  private:
814   static void ReportMessageNoExceptions(Isolate* isolate,
815                                         const MessageLocation* loc,
816                                         Handle<Object> message_obj,
817                                         v8::Local<v8::Value> api_exception_obj);
818 };
819 
820 
821 }  // namespace internal
822 }  // namespace v8
823 
824 #endif  // V8_MESSAGES_H_
825