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