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