messages.h 47.6 KB
Newer Older
1
// Copyright 2006-2008 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4 5 6 7 8 9 10 11 12

// The infrastructure used for (localized) message reporting in V8.
//
// Note: there's a big unresolved issue about ownership of the data
// structures used by this framework.

#ifndef V8_MESSAGES_H_
#define V8_MESSAGES_H_

13 14
#include <memory>

15
#include "src/handles.h"
16

17 18
namespace v8 {
namespace internal {
19

20
// Forward declarations.
21 22
class AbstractCode;
class FrameArray;
23 24
class JSMessageObject;
class LookupIterator;
25
class SharedFunctionInfo;
26
class SourceInfo;
27
class WasmInstanceObject;
28 29 30

class MessageLocation {
 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 36 37 38

  Handle<Script> script() const { return script_; }
  int start_pos() const { return start_pos_; }
  int end_pos() const { return end_pos_; }
39
  Handle<SharedFunctionInfo> shared() const { return shared_; }
40 41 42 43 44

 private:
  Handle<Script> script_;
  int start_pos_;
  int end_pos_;
45
  Handle<SharedFunctionInfo> shared_;
46 47
};

48
class StackFrameBase {
49
 public:
50 51 52 53 54 55 56 57 58 59
  virtual ~StackFrameBase() {}

  virtual Handle<Object> GetReceiver() const = 0;
  virtual Handle<Object> GetFunction() const = 0;

  virtual Handle<Object> GetFileName() = 0;
  virtual Handle<Object> GetFunctionName() = 0;
  virtual Handle<Object> GetScriptNameOrSourceUrl() = 0;
  virtual Handle<Object> GetMethodName() = 0;
  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 67 68 69
  virtual int GetColumnNumber() = 0;

  virtual bool IsNative() = 0;
  virtual bool IsToplevel() = 0;
70
  virtual bool IsEval();
71 72 73 74
  virtual bool IsConstructor() = 0;
  virtual bool IsStrict() const = 0;

  virtual MaybeHandle<String> ToString() = 0;
75 76 77 78 79 80 81 82 83

 protected:
  StackFrameBase() {}
  explicit StackFrameBase(Isolate* isolate) : isolate_(isolate) {}
  Isolate* isolate_;

 private:
  virtual bool HasScript() const = 0;
  virtual Handle<Script> GetScript() const = 0;
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
};

class JSStackFrame : public StackFrameBase {
 public:
  JSStackFrame(Isolate* isolate, Handle<Object> receiver,
               Handle<JSFunction> function, Handle<AbstractCode> code,
               int offset);
  virtual ~JSStackFrame() {}

  Handle<Object> GetReceiver() const override { return receiver_; }
  Handle<Object> GetFunction() const override;

  Handle<Object> GetFileName() override;
  Handle<Object> GetFunctionName() override;
  Handle<Object> GetScriptNameOrSourceUrl() override;
  Handle<Object> GetMethodName() override;
  Handle<Object> GetTypeName() override;

  int GetPosition() const override;
  int GetLineNumber() override;
  int GetColumnNumber() override;
105

106 107
  bool IsNative() override;
  bool IsToplevel() override;
108
  bool IsConstructor() override { return is_constructor_; }
109
  bool IsStrict() const override { return is_strict_; }
110

111
  MaybeHandle<String> ToString() override;
112 113

 private:
114 115 116
  JSStackFrame();
  void FromFrameArray(Isolate* isolate, Handle<FrameArray> array, int frame_ix);

117 118
  bool HasScript() const override;
  Handle<Script> GetScript() const override;
119

120
  Handle<Object> receiver_;
121 122 123 124
  Handle<JSFunction> function_;
  Handle<AbstractCode> code_;
  int offset_;

125
  bool is_constructor_;
126 127 128 129 130 131 132 133 134
  bool is_strict_;

  friend class FrameArrayIterator;
};

class WasmStackFrame : public StackFrameBase {
 public:
  virtual ~WasmStackFrame() {}

135
  Handle<Object> GetReceiver() const override;
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
  Handle<Object> GetFunction() const override;

  Handle<Object> GetFileName() override { return Null(); }
  Handle<Object> GetFunctionName() override;
  Handle<Object> GetScriptNameOrSourceUrl() override { return Null(); }
  Handle<Object> GetMethodName() override { return Null(); }
  Handle<Object> GetTypeName() override { return Null(); }

  int GetPosition() const override;
  int GetLineNumber() override { return wasm_func_index_; }
  int GetColumnNumber() override { return -1; }

  bool IsNative() override { return false; }
  bool IsToplevel() override { return false; }
  bool IsConstructor() override { return false; }
  bool IsStrict() const override { return false; }
152
  bool IsInterpreted() const { return code_.is_null(); }
153 154 155

  MaybeHandle<String> ToString() override;

156
 protected:
157 158
  Handle<Object> Null() const;

159 160
  bool HasScript() const override;
  Handle<Script> GetScript() const override;
161

162
  Handle<WasmInstanceObject> wasm_instance_;
163
  uint32_t wasm_func_index_;
164
  Handle<AbstractCode> code_;  // null handle for interpreted frames.
165 166
  int offset_;

167
 private:
168
  WasmStackFrame();
169 170
  void FromFrameArray(Isolate* isolate, Handle<FrameArray> array, int frame_ix);

171
  friend class FrameArrayIterator;
172
  friend class AsmJsWasmStackFrame;
173 174
};

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
class AsmJsWasmStackFrame : public WasmStackFrame {
 public:
  virtual ~AsmJsWasmStackFrame() {}

  Handle<Object> GetReceiver() const override;
  Handle<Object> GetFunction() const override;

  Handle<Object> GetFileName() override;
  Handle<Object> GetScriptNameOrSourceUrl() override;

  int GetPosition() const override;
  int GetLineNumber() override;
  int GetColumnNumber() override;

  MaybeHandle<String> ToString() override;
190 191 192

 private:
  friend class FrameArrayIterator;
193
  AsmJsWasmStackFrame();
194 195 196
  void FromFrameArray(Isolate* isolate, Handle<FrameArray> array, int frame_ix);

  bool is_at_number_conversion_;
197 198
};

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
class FrameArrayIterator {
 public:
  FrameArrayIterator(Isolate* isolate, Handle<FrameArray> array,
                     int frame_ix = 0);

  StackFrameBase* Frame();

  bool HasNext() const;
  void Next();

 private:
  Isolate* isolate_;

  Handle<FrameArray> array_;
  int next_frame_ix_;

  WasmStackFrame wasm_frame_;
216
  AsmJsWasmStackFrame asm_wasm_frame_;
217
  JSStackFrame js_frame_;
218 219
};

220 221 222 223 224 225 226 227 228 229
// Determines how stack trace collection skips frames.
enum FrameSkipMode {
  // Unconditionally skips the first frame. Used e.g. when the Error constructor
  // is called, in which case the first frame is always a BUILTIN_EXIT frame.
  SKIP_FIRST,
  // Skip all frames until a specified caller function is seen.
  SKIP_UNTIL_SEEN,
  SKIP_NONE,
};

jgruber's avatar
jgruber committed
230 231 232 233
class ErrorUtils : public AllStatic {
 public:
  static MaybeHandle<Object> Construct(
      Isolate* isolate, Handle<JSFunction> target, Handle<Object> new_target,
234 235
      Handle<Object> message, FrameSkipMode mode, Handle<Object> caller,
      bool suppress_detailed_trace);
jgruber's avatar
jgruber committed
236 237

  static MaybeHandle<String> ToString(Isolate* isolate, Handle<Object> recv);
238 239 240 241 242

  static MaybeHandle<Object> MakeGenericError(
      Isolate* isolate, Handle<JSFunction> constructor, int template_index,
      Handle<Object> arg0, Handle<Object> arg1, Handle<Object> arg2,
      FrameSkipMode mode);
243 244 245 246 247 248

  // Formats a textual stack trace from the given structured stack trace.
  // Note that this can call arbitrary JS code through Error.prepareStackTrace.
  static MaybeHandle<Object> FormatStackTrace(Isolate* isolate,
                                              Handle<JSObject> error,
                                              Handle<Object> stack_trace);
jgruber's avatar
jgruber committed
249 250
};

251 252
#define MESSAGE_TEMPLATES(T)                                                   \
  /* 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 260 261
  T(Unsupported, "Not supported")                                              \
  T(WrongServiceType, "Internal error, wrong service type: %")                 \
  T(WrongValueType, "Internal error. Wrong value type.")                       \
262 263 264 265
  /* TypeError */                                                              \
  T(ApplyNonFunction,                                                          \
    "Function.prototype.apply was called on %, which is a % and not a "        \
    "function")                                                                \
266 267 268 269
  T(ArrayBufferTooShort,                                                       \
    "Derived ArrayBuffer constructor created a buffer which was too small")    \
  T(ArrayBufferSpeciesThis,                                                    \
    "ArrayBuffer subclass returned this from species constructor")             \
270 271
  T(ArrayFunctionsOnFrozen, "Cannot modify frozen array elements")             \
  T(ArrayFunctionsOnSealed, "Cannot add/remove sealed array elements")         \
272
  T(AwaitNotInAsyncFunction, "await is only valid in async function")          \
273
  T(AtomicsWaitNotAllowed, "Atomics.wait cannot be called in this context")    \
274 275
  T(BadSortComparisonFunction,                                                 \
    "The comparison function must be either a function or undefined")          \
276 277 278 279
  T(BigIntFromNumber,                                                          \
    "The number % is not a safe integer and thus cannot be converted to a "    \
    "BigInt")                                                                  \
  T(BigIntFromObject, "Cannot convert % to a BigInt")                          \
280 281
  T(BigIntMixedTypes,                                                          \
    "Cannot mix BigInt and other types, use explicit conversions")             \
282
  T(BigIntSerializeJSON, "Do not know how to serialize a BigInt")              \
283
  T(BigIntShr, "BigInts have no unsigned right shift, use >> instead")         \
284
  T(BigIntToNumber, "Cannot convert a BigInt value to a number")               \
285 286
  T(CalledNonCallable, "% is not a function")                                  \
  T(CalledOnNonObject, "% called on non-object")                               \
287
  T(CalledOnNullOrUndefined, "% called on null or undefined")                  \
288
  T(CallSiteExpectsFunction,                                                   \
289 290
    "CallSite expects wasm object as first or function as second argument, "   \
    "got <%, %>")                                                              \
291
  T(CallSiteMethod, "CallSite method % expects CallSite as receiver")          \
292
  T(CannotConvertToPrimitive, "Cannot convert object to primitive value")      \
293
  T(CannotPreventExt, "Cannot prevent extensions")                             \
294
  T(CannotFreeze, "Cannot freeze")                                             \
295 296
  T(CannotFreezeArrayBufferView,                                               \
    "Cannot freeze array buffer views with elements")                          \
297
  T(CannotSeal, "Cannot seal")                                                 \
298
  T(CircularStructure, "Converting circular structure to JSON")                \
299
  T(ConstructAbstractClass, "Abstract class % not directly constructable")     \
300
  T(ConstAssign, "Assignment to constant variable.")                           \
301
  T(ConstructorNonCallable,                                                    \
302
    "Class constructor % cannot be invoked without 'new'")                     \
303
  T(ConstructorNotFunction, "Constructor % requires 'new'")                    \
304
  T(ConstructorNotReceiver, "The .constructor property is not an object")      \
305
  T(CurrencyCode, "Currency code is required with currency style.")            \
306
  T(CyclicModuleDependency, "Detected cycle while resolving name '%'")         \
307 308
  T(DataViewNotArrayBuffer,                                                    \
    "First argument to DataView constructor must be an ArrayBuffer")           \
309
  T(DateType, "this is not a Date object.")                                    \
310 311
  T(DebuggerFrame, "Debugger: Invalid frame index.")                           \
  T(DebuggerType, "Debugger: Parameters have wrong types.")                    \
312
  T(DeclarationMissingInitializer, "Missing initializer in % declaration")     \
vabr's avatar
vabr committed
313
  T(DefineDisallowed, "Cannot define property %, object is not extensible")    \
314
  T(DetachedOperation, "Cannot perform % on a detached ArrayBuffer")           \
315
  T(DuplicateTemplateProperty, "Object template has duplicate property '%'")   \
316 317
  T(ExtendsValueNotConstructor,                                                \
    "Class extends value % is not a constructor or null")                      \
318 319
  T(FirstArgumentNotRegExp,                                                    \
    "First argument to % must not be a regular expression")                    \
320
  T(FunctionBind, "Bind must be called on a function")                         \
321
  T(GeneratorRunning, "Generator is already running")                          \
322
  T(IllegalInvocation, "Illegal invocation")                                   \
323 324
  T(ImmutablePrototypeSet,                                                     \
    "Immutable prototype object '%' cannot have their prototype set")          \
325
  T(ImportCallNotNewExpression, "Cannot use new with import")                  \
326
  T(ImportMetaOutsideModule, "Cannot use 'import.meta' outside a module")      \
327
  T(ImportMissingSpecifier, "import() requires a specifier")                   \
328 329 330
  T(IncompatibleMethodReceiver, "Method % called on incompatible receiver %")  \
  T(InstanceofNonobjectProto,                                                  \
    "Function has non-object prototype '%' in instanceof check")               \
331
  T(InvalidArgument, "invalid_argument")                                       \
332
  T(InvalidInOperatorUse, "Cannot use 'in' operator to search for '%' in %")   \
333 334
  T(InvalidRegExpExecResult,                                                   \
    "RegExp exec method returned something other than an Object or null")      \
335 336
  T(IteratorResultNotAnObject, "Iterator result % is not an object")           \
  T(IteratorValueNotAnObject, "Iterator value % is not an entry object")       \
337 338 339 340 341 342
  T(LanguageID, "Language ID should be string or object.")                     \
  T(MethodCalledOnWrongObject,                                                 \
    "Method % called on a non-object or on a wrong type of object.")           \
  T(MethodInvokedOnNullOrUndefined,                                            \
    "Method invoked on undefined or null value.")                              \
  T(MethodInvokedOnWrongType, "Method invoked on an object that is not %.")    \
343
  T(NoAccess, "no access")                                                     \
344 345
  T(NonCallableInInstanceOfCheck,                                              \
    "Right-hand side of 'instanceof' is not callable")                         \
346 347 348
  T(NonCoercible, "Cannot destructure 'undefined' or 'null'.")                 \
  T(NonCoercibleWithProperty,                                                  \
    "Cannot destructure property `%` of 'undefined' or 'null'.")               \
349
  T(NonExtensibleProto, "% is not extensible")                                 \
350 351
  T(NonObjectInInstanceOfCheck,                                                \
    "Right-hand side of 'instanceof' is not an object")                        \
352 353 354
  T(NonObjectPropertyLoad, "Cannot read property '%' of %")                    \
  T(NonObjectPropertyStore, "Cannot set property '%' of %")                    \
  T(NoSetterInCallback, "Cannot set property % of % which has only a getter")  \
355
  T(NotAnIterator, "% is not an iterator")                                     \
356
  T(NotAPromise, "% is not a promise")                                         \
357
  T(NotConstructor, "% is not a constructor")                                  \
358
  T(NotDateObject, "this is not a Date object.")                               \
359
  T(NotGeneric, "% requires that 'this' be a %")                               \
360 361 362 363
  T(NotCallableOrIterable,                                                     \
    "% is not a function or its return value is not iterable")                 \
  T(NotCallableOrAsyncIterable,                                                \
    "% is not a function or its return value is not async iterable")           \
364
  T(NotIterable, "% is not iterable")                                          \
365
  T(NotAsyncIterable, "% is not async iterable")                               \
366
  T(NotPropertyName, "% is not a valid property name")                         \
367
  T(NotTypedArray, "this is not a typed array.")                               \
368 369 370
  T(NotSuperConstructor, "Super constructor % of % is not a constructor")      \
  T(NotSuperConstructorAnonymousClass,                                         \
    "Super constructor % of anonymous class is not a constructor")             \
binji's avatar
binji committed
371
  T(NotIntegerSharedTypedArray, "% is not an integer shared typed array.")     \
binji's avatar
binji committed
372
  T(NotInt32SharedTypedArray, "% is not an int32 shared typed array.")         \
373 374 375
  T(ObjectGetterExpectingFunction,                                             \
    "Object.prototype.__defineGetter__: Expecting function")                   \
  T(ObjectGetterCallable, "Getter must be a function: %")                      \
vabr's avatar
vabr committed
376
  T(ObjectNotExtensible, "Cannot add property %, object is not extensible")    \
377 378 379
  T(ObjectSetterExpectingFunction,                                             \
    "Object.prototype.__defineSetter__: Expecting function")                   \
  T(ObjectSetterCallable, "Setter must be a function: %")                      \
380 381
  T(OrdinaryFunctionCalledAsConstructor,                                       \
    "Function object that's not a constructor was created with new")           \
382
  T(PromiseCyclic, "Chaining cycle detected for promise %")                    \
383 384
  T(PromiseExecutorAlreadyInvoked,                                             \
    "Promise executor has already been invoked with non-undefined arguments")  \
385
  T(PromiseNonCallable, "Promise resolve or reject function is not callable")  \
386
  T(PropertyDescObject, "Property description must be an object: %")           \
387 388
  T(PropertyNotFunction,                                                       \
    "'%' returned for property '%' of object '%' is not a function")           \
389
  T(ProtoObjectOrNull, "Object prototype may only be an Object or null: %")    \
390 391
  T(PrototypeParentNotAnObject,                                                \
    "Class extends value does not have valid prototype property %")            \
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
  T(ProxyConstructNonObject,                                                   \
    "'construct' on proxy: trap returned non-object ('%')")                    \
  T(ProxyDefinePropertyNonConfigurable,                                        \
    "'defineProperty' on proxy: trap returned truish for defining "            \
    "non-configurable property '%' which is either non-existant or "           \
    "configurable in the proxy target")                                        \
  T(ProxyDefinePropertyNonExtensible,                                          \
    "'defineProperty' on proxy: trap returned truish for adding property '%' " \
    " to the non-extensible proxy target")                                     \
  T(ProxyDefinePropertyIncompatible,                                           \
    "'defineProperty' on proxy: trap returned truish for adding property '%' " \
    " that is incompatible with the existing property in the proxy target")    \
  T(ProxyDeletePropertyNonConfigurable,                                        \
    "'deleteProperty' on proxy: trap returned truish for property '%' which "  \
    "is non-configurable in the proxy target")                                 \
  T(ProxyGetNonConfigurableData,                                               \
    "'get' on proxy: property '%' is a read-only and "                         \
    "non-configurable data property on the proxy target but the proxy "        \
    "did not return its actual value (expected '%' but got '%')")              \
  T(ProxyGetNonConfigurableAccessor,                                           \
    "'get' on proxy: property '%' is a non-configurable accessor "             \
    "property on the proxy target and does not have a getter function, but "   \
    "the trap did not return 'undefined' (got '%')")                           \
  T(ProxyGetOwnPropertyDescriptorIncompatible,                                 \
    "'getOwnPropertyDescriptor' on proxy: trap returned descriptor for "       \
    "property '%' that is incompatible with the existing property in the "     \
    "proxy target")                                                            \
  T(ProxyGetOwnPropertyDescriptorInvalid,                                      \
    "'getOwnPropertyDescriptor' on proxy: trap returned neither object nor "   \
    "undefined for property '%'")                                              \
  T(ProxyGetOwnPropertyDescriptorNonConfigurable,                              \
    "'getOwnPropertyDescriptor' on proxy: trap reported non-configurability "  \
    "for property '%' which is either non-existant or configurable in the "    \
    "proxy target")                                                            \
  T(ProxyGetOwnPropertyDescriptorNonExtensible,                                \
    "'getOwnPropertyDescriptor' on proxy: trap returned undefined for "        \
    "property '%' which exists in the non-extensible proxy target")            \
  T(ProxyGetOwnPropertyDescriptorUndefined,                                    \
    "'getOwnPropertyDescriptor' on proxy: trap returned undefined for "        \
    "property '%' which is non-configurable in the proxy target")              \
  T(ProxyGetPrototypeOfInvalid,                                                \
    "'getPrototypeOf' on proxy: trap returned neither object nor null")        \
  T(ProxyGetPrototypeOfNonExtensible,                                          \
    "'getPrototypeOf' on proxy: proxy target is non-extensible but the "       \
    "trap did not return its actual prototype")                                \
437
  T(ProxyHandlerOrTargetRevoked,                                               \
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    "Cannot create proxy with a revoked proxy as target or handler")           \
  T(ProxyHasNonConfigurable,                                                   \
    "'has' on proxy: trap returned falsish for property '%' which exists in "  \
    "the proxy target as non-configurable")                                    \
  T(ProxyHasNonExtensible,                                                     \
    "'has' on proxy: trap returned falsish for property '%' but the proxy "    \
    "target is not extensible")                                                \
  T(ProxyIsExtensibleInconsistent,                                             \
    "'isExtensible' on proxy: trap result does not reflect extensibility of "  \
    "proxy target (which is '%')")                                             \
  T(ProxyNonObject,                                                            \
    "Cannot create proxy with a non-object as target or handler")              \
  T(ProxyOwnKeysMissing,                                                       \
    "'ownKeys' on proxy: trap result did not include '%'")                     \
  T(ProxyOwnKeysNonExtensible,                                                 \
    "'ownKeys' on proxy: trap returned extra keys but proxy target is "        \
    "non-extensible")                                                          \
  T(ProxyPreventExtensionsExtensible,                                          \
    "'preventExtensions' on proxy: trap returned truish but the proxy target " \
    "is extensible")                                                           \
458
  T(ProxyPrivate, "Cannot pass private property name to proxy trap")           \
459
  T(ProxyRevoked, "Cannot perform '%' on a proxy that has been revoked")       \
460 461 462 463 464 465 466 467 468 469 470 471 472 473
  T(ProxySetFrozenData,                                                        \
    "'set' on proxy: trap returned truish for property '%' which exists in "   \
    "the proxy target as a non-configurable and non-writable data property "   \
    "with a different value")                                                  \
  T(ProxySetFrozenAccessor,                                                    \
    "'set' on proxy: trap returned truish for property '%' which exists in "   \
    "the proxy target as a non-configurable and non-writable accessor "        \
    "property without a setter")                                               \
  T(ProxySetPrototypeOfNonExtensible,                                          \
    "'setPrototypeOf' on proxy: trap returned truish for setting a new "       \
    "prototype on the non-extensible proxy target")                            \
  T(ProxyTrapReturnedFalsish, "'%' on proxy: trap returned falsish")           \
  T(ProxyTrapReturnedFalsishFor,                                               \
    "'%' on proxy: trap returned falsish for property '%'")                    \
474
  T(RedefineDisallowed, "Cannot redefine property: %")                         \
475 476
  T(RedefineExternalArray,                                                     \
    "Cannot redefine a property of an object with external array elements")    \
477
  T(ReduceNoInitial, "Reduce of empty array with no initial value")            \
478 479
  T(RegExpFlags,                                                               \
    "Cannot supply flags when constructing one RegExp from another")           \
480
  T(RegExpNonObject, "% getter called on non-object %")                        \
481
  T(RegExpNonRegExp, "% getter called on non-RegExp object")                   \
482
  T(ResolverNotAFunction, "Promise resolver % is not a function")              \
483
  T(ReturnMethodNotCallable, "The iterator's 'return' method is not callable") \
484 485 486 487 488
  T(SharedArrayBufferTooShort,                                                 \
    "Derived SharedArrayBuffer constructor created a buffer which was too "    \
    "small")                                                                   \
  T(SharedArrayBufferSpeciesThis,                                              \
    "SharedArrayBuffer subclass returned this from species constructor")       \
489 490 491 492 493
  T(StaticPrototype, "Classes may not have static property named prototype")   \
  T(StrictDeleteProperty, "Cannot delete property '%' of %")                   \
  T(StrictPoisonPill,                                                          \
    "'caller', 'callee', and 'arguments' properties may not be accessed on "   \
    "strict mode functions or the arguments objects for calls to them")        \
494 495 496
  T(StrictReadOnlyProperty,                                                    \
    "Cannot assign to read only property '%' of % '%'")                        \
  T(StrictCannotCreateProperty, "Cannot create property '%' on % '%'")         \
neis's avatar
neis committed
497 498
  T(SymbolIteratorInvalid,                                                     \
    "Result of the Symbol.iterator method is not an object")                   \
499 500
  T(SymbolAsyncIteratorInvalid,                                                \
    "Result of the Symbol.asyncIterator method is not an object")              \
501
  T(SymbolKeyFor, "% is not a symbol")                                         \
502 503
  T(SymbolToNumber, "Cannot convert a Symbol value to a number")               \
  T(SymbolToString, "Cannot convert a Symbol value to a string")               \
neis's avatar
neis committed
504
  T(ThrowMethodMissing, "The iterator does not provide a 'throw' method.")     \
505 506
  T(UndefinedOrNullToObject, "Cannot convert undefined or null to object")     \
  T(ValueAndAccessor,                                                          \
507 508
    "Invalid property descriptor. Cannot both specify accessors and a value "  \
    "or writable attribute, %")                                                \
509
  T(VarRedeclaration, "Identifier '%' has already been declared")              \
510
  T(WrongArgs, "%: Arguments list has wrong type")                             \
511 512
  /* ReferenceError */                                                         \
  T(NotDefined, "% is not defined")                                            \
513
  T(SuperAlreadyCalled, "Super constructor may only be called once")           \
514
  T(UnsupportedSuper, "Unsupported reference to 'super'")                      \
515
  /* RangeError */                                                             \
516
  T(BigIntDivZero, "Division by zero")                                         \
517
  T(BigIntTooBig, "Maximum BigInt size exceeded")                              \
518
  T(DateRange, "Provided date is not in valid range.")                         \
jshin's avatar
jshin committed
519 520 521 522 523
  T(ExpectedTimezoneID,                                                        \
    "Expected Area/Location(/Location)* for time zone, got %")                 \
  T(ExpectedLocation,                                                          \
    "Expected letters optionally connected with underscores or hyphens for "   \
    "a location, got %")                                                       \
524
  T(InvalidArrayBufferLength, "Invalid array buffer length")                   \
525
  T(ArrayBufferAllocationFailed, "Array buffer allocation failed")             \
526
  T(InvalidArrayLength, "Invalid array length")                                \
527
  T(InvalidAtomicAccessIndex, "Invalid atomic access index")                   \
528 529
  T(InvalidCodePoint, "Invalid code point %")                                  \
  T(InvalidCountValue, "Invalid count value")                                  \
530
  T(InvalidCurrencyCode, "Invalid currency code: %")                           \
531 532
  T(InvalidDataViewAccessorOffset,                                             \
    "Offset is outside the bounds of the DataView")                            \
533
  T(InvalidDataViewLength, "Invalid DataView length %")                        \
534
  T(InvalidOffset, "Start offset % is outside the bounds of the buffer")       \
535
  T(InvalidHint, "Invalid hint: %")                                            \
536
  T(InvalidIndex, "Invalid value: not (convertible to) a safe integer")        \
537
  T(InvalidLanguageTag, "Invalid language tag: %")                             \
538 539
  T(InvalidWeakMapKey, "Invalid value used as weak map key")                   \
  T(InvalidWeakSetValue, "Invalid value used in weak set")                     \
540
  T(InvalidStringLength, "Invalid string length")                              \
541
  T(InvalidTimeValue, "Invalid time value")                                    \
542
  T(InvalidTypedArrayAlignment, "% of % should be a multiple of %")            \
543
  T(InvalidTypedArrayIndex, "Invalid typed array index")                       \
544
  T(InvalidTypedArrayLength, "Invalid typed array length: %")                  \
545
  T(LetInLexicalBinding, "let is disallowed as a lexically bound name")        \
546 547
  T(LocaleMatcher, "Illegal value for localeMatcher:%")                        \
  T(NormalizationForm, "The normalization form should be one of %.")           \
548
  T(NumberFormatRange, "% argument must be between 0 and 100")                 \
549
  T(PropertyValueOutOfRange, "% value is out of range.")                       \
550
  T(StackOverflow, "Maximum call stack size exceeded")                         \
551 552
  T(ToPrecisionFormatRange,                                                    \
    "toPrecision() argument must be between 1 and 100")                        \
553
  T(ToRadixFormatRange, "toString() radix argument must be between 2 and 36")  \
554 555
  T(TypedArraySetNegativeOffset, "Start offset is negative")                   \
  T(TypedArraySetSourceTooLarge, "Source is too large")                        \
556 557
  T(UnsupportedTimeZone, "Unsupported time zone specified %")                  \
  T(ValueOutOfRange, "Value % out of range for % options property %")          \
558
  /* SyntaxError */                                                            \
559 560
  T(AmbiguousExport,                                                           \
    "The requested module contains conflicting star exports for name '%'")     \
561 562
  T(BadGetterArity, "Getter must not have any formal parameters.")             \
  T(BadSetterArity, "Setter must have exactly one formal parameter.")          \
563
  T(BigIntInvalidString, "Invalid BigInt string")                              \
564 565
  T(ConstructorIsAccessor, "Class constructor may not be an accessor")         \
  T(ConstructorIsGenerator, "Class constructor may not be a generator")        \
566
  T(ConstructorIsAsync, "Class constructor may not be an async method")        \
567 568 569
  T(ClassConstructorReturnedNonObject,                                         \
    "Class constructors may only return object or undefined")                  \
  T(DerivedConstructorReturnedNonObject,                                       \
570 571 572 573 574
    "Derived constructors may only return object or undefined")                \
  T(DuplicateConstructor, "A class may only have one constructor")             \
  T(DuplicateExport, "Duplicate export of '%'")                                \
  T(DuplicateProto,                                                            \
    "Duplicate __proto__ fields are not allowed in object literals")           \
575 576
  T(ForInOfLoopInitializer,                                                    \
    "% loop variable declaration may not have an initializer.")                \
577 578
  T(ForInOfLoopMultiBindings,                                                  \
    "Invalid left-hand side in % loop: Must have a single binding.")           \
579 580 581 582 583
  T(GeneratorInSingleStatementContext,                                         \
    "Generators can only be declared at the top level or inside a block.")     \
  T(AsyncFunctionInSingleStatementContext,                                     \
    "Async functions can only be declared at the top level or inside a "       \
    "block.")                                                                  \
584
  T(IllegalBreak, "Illegal break statement")                                   \
585 586 587 588
  T(NoIterationStatement,                                                      \
    "Illegal continue statement: no surrounding iteration statement")          \
  T(IllegalContinue,                                                           \
    "Illegal continue statement: '%' does not denote an iteration statement")  \
589 590
  T(IllegalLanguageModeDirective,                                              \
    "Illegal '%' directive in function with non-simple parameter list")        \
591
  T(IllegalReturn, "Illegal return statement")                                 \
592 593 594 595 596
  T(InvalidRestBindingPattern,                                                 \
    "`...` must be followed by an identifier in declaration contexts")         \
  T(InvalidRestAssignmentPattern,                                              \
    "`...` must be followed by an assignable reference in assignment "         \
    "contexts")                                                                \
597
  T(InvalidEscapedReservedWord, "Keyword must not contain escaped characters") \
598
  T(InvalidEscapedMetaProperty, "'%' must not contain escaped characters")     \
599
  T(InvalidLhsInAssignment, "Invalid left-hand side in assignment")            \
600 601
  T(InvalidCoverInitializedName, "Invalid shorthand property initializer")     \
  T(InvalidDestructuringTarget, "Invalid destructuring assignment target")     \
602 603 604 605 606
  T(InvalidLhsInFor, "Invalid left-hand side in for-loop")                     \
  T(InvalidLhsInPostfixOp,                                                     \
    "Invalid left-hand side expression in postfix operation")                  \
  T(InvalidLhsInPrefixOp,                                                      \
    "Invalid left-hand side expression in prefix operation")                   \
607
  T(InvalidRegExpFlags, "Invalid flags supplied to RegExp constructor '%'")    \
608
  T(InvalidOrUnexpectedToken, "Invalid or unexpected token")                   \
609 610 611 612
  T(JsonParseUnexpectedEOS, "Unexpected end of JSON input")                    \
  T(JsonParseUnexpectedToken, "Unexpected token % in JSON at position %")      \
  T(JsonParseUnexpectedTokenNumber, "Unexpected number in JSON at position %") \
  T(JsonParseUnexpectedTokenString, "Unexpected string in JSON at position %") \
613
  T(LabelRedeclaration, "Label '%' has already been declared")                 \
614 615 616
  T(LabelledFunctionDeclaration,                                               \
    "Labelled function declaration not allowed as the body of a control flow " \
    "structure")                                                               \
617
  T(MalformedArrowFunParamList, "Malformed arrow function parameter list")     \
618
  T(MalformedRegExp, "Invalid regular expression: /%/: %")                     \
619 620
  T(MalformedRegExpFlags, "Invalid regular expression flags")                  \
  T(ModuleExportUndefined, "Export '%' is not defined in module")              \
621
  T(HtmlCommentInModule, "HTML comments are not allowed in modules")           \
622 623 624 625 626 627
  T(MultipleDefaultsInSwitch,                                                  \
    "More than one default clause in switch statement")                        \
  T(NewlineAfterThrow, "Illegal newline after throw")                          \
  T(NoCatchOrFinally, "Missing catch or finally after try")                    \
  T(NotIsvar, "builtin %%IS_VAR: not a variable")                              \
  T(ParamAfterRest, "Rest parameter must be last formal parameter")            \
628 629 630
  T(PushPastSafeLength,                                                        \
    "Pushing % elements on an array-like of length % "                         \
    "is disallowed, as the total surpasses 2**53-1")                           \
631
  T(ElementAfterRest, "Rest element must be last element")                     \
632 633
  T(BadSetterRestParameter,                                                    \
    "Setter function argument must not be a rest parameter")                   \
634
  T(ParamDupe, "Duplicate parameter name not allowed in this context")         \
635
  T(ParenthesisInArgString, "Function arg string contains parenthesis")        \
636 637 638
  T(ArgStringTerminatesParametersEarly,                                        \
    "Arg string terminates parameters early")                                  \
  T(UnexpectedEndOfArgString, "Unexpected end of arg string")                  \
639 640
  T(RestDefaultInitializer,                                                    \
    "Rest parameter may not have a default initializer")                       \
641
  T(RuntimeWrongNumArgs, "Runtime function given wrong number of arguments")   \
642 643 644
  T(SuperNotCalled,                                                            \
    "Must call super constructor in derived class before accessing 'this' or " \
    "returning from derived constructor")                                      \
645
  T(SingleFunctionLiteral, "Single function literal required")                 \
646 647 648
  T(SloppyFunction,                                                            \
    "In non-strict mode code, functions can only be declared at top level, "   \
    "inside a block, or as the body of an if statement.")                      \
649 650
  T(SpeciesNotConstructor,                                                     \
    "object.constructor[Symbol.species] is not a constructor")                 \
651 652 653 654
  T(StrictDelete, "Delete of an unqualified identifier in strict mode.")       \
  T(StrictEvalArguments, "Unexpected eval or arguments in strict mode")        \
  T(StrictFunction,                                                            \
    "In strict mode code, functions can only be declared at top level or "     \
655
    "inside a block.")                                                         \
656
  T(StrictOctalLiteral, "Octal literals are not allowed in strict mode.")      \
657 658
  T(StrictDecimalWithLeadingZero,                                              \
    "Decimals with leading zeros are not allowed in strict mode.")             \
659 660
  T(StrictOctalEscape,                                                         \
    "Octal escape sequences are not allowed in strict mode.")                  \
661 662
  T(StrictWith, "Strict mode code may not include a with statement")           \
  T(TemplateOctalLiteral,                                                      \
663
    "Octal escape sequences are not allowed in template strings.")             \
664
  T(ThisFormalParameter, "'this' is not a valid formal parameter name")        \
665 666 667 668
  T(AwaitBindingIdentifier,                                                    \
    "'await' is not a valid identifier name in an async function")             \
  T(AwaitExpressionFormalParameter,                                            \
    "Illegal await-expression in formal parameters of async function")         \
669 670 671 672
  T(TooManyArguments,                                                          \
    "Too many arguments in function call (only 65535 allowed)")                \
  T(TooManyParameters,                                                         \
    "Too many parameters in function definition (only 65535 allowed)")         \
673 674
  T(TooManySpreads,                                                            \
    "Literal containing too many nested spreads (up to 65534 allowed)")        \
675
  T(TooManyVariables, "Too many variables declared (only 4194303 allowed)")    \
676 677
  T(TypedArrayTooShort,                                                        \
    "Derived TypedArray constructor created an array which was too small")     \
678
  T(UnexpectedEOS, "Unexpected end of input")                                  \
679 680
  T(UnexpectedFunctionSent,                                                    \
    "function.sent expression is not allowed outside a generator")             \
681 682 683
  T(UnexpectedReserved, "Unexpected reserved word")                            \
  T(UnexpectedStrictReserved, "Unexpected strict mode reserved word")          \
  T(UnexpectedSuper, "'super' keyword unexpected here")                        \
684
  T(UnexpectedNewTarget, "new.target expression is not allowed here")          \
685
  T(UnexpectedTemplateString, "Unexpected template string")                    \
686
  T(UnexpectedToken, "Unexpected token %")                                     \
687
  T(UnexpectedTokenIdentifier, "Unexpected identifier")                        \
688 689
  T(UnexpectedTokenNumber, "Unexpected number")                                \
  T(UnexpectedTokenString, "Unexpected string")                                \
690
  T(UnexpectedTokenRegExp, "Unexpected regular expression")                    \
691 692
  T(UnexpectedLexicalDeclaration,                                              \
    "Lexical declaration cannot appear in a single-statement context")         \
693
  T(UnknownLabel, "Undefined label '%'")                                       \
694 695
  T(UnresolvableExport,                                                        \
    "The requested module does not provide an export named '%'")               \
696 697 698 699
  T(UnterminatedArgList, "missing ) after argument list")                      \
  T(UnterminatedRegExp, "Invalid regular expression: missing /")               \
  T(UnterminatedTemplate, "Unterminated template literal")                     \
  T(UnterminatedTemplateExpr, "Missing } in template expression")              \
700
  T(FoundNonCallableHasInstance, "Found non-callable @@hasInstance")           \
701 702 703
  T(InvalidHexEscapeSequence, "Invalid hexadecimal escape sequence")           \
  T(InvalidUnicodeEscapeSequence, "Invalid Unicode escape sequence")           \
  T(UndefinedUnicodeCodePoint, "Undefined Unicode code-point")                 \
704
  T(YieldInParameter, "Yield expression not allowed in formal parameter")      \
705
  /* EvalError */                                                              \
706
  T(CodeGenFromStrings, "%")                                                   \
707
  T(NoSideEffectDebugEvaluate, "Possible side-effect in debug-evaluate")       \
708
  /* URIError */                                                               \
709 710 711 712 713 714 715 716 717
  T(URIMalformed, "URI malformed")                                             \
  /* Wasm errors (currently Error) */                                          \
  T(WasmTrapUnreachable, "unreachable")                                        \
  T(WasmTrapMemOutOfBounds, "memory access out of bounds")                     \
  T(WasmTrapDivByZero, "divide by zero")                                       \
  T(WasmTrapDivUnrepresentable, "divide result unrepresentable")               \
  T(WasmTrapRemByZero, "remainder by zero")                                    \
  T(WasmTrapFloatUnrepresentable, "integer result unrepresentable")            \
  T(WasmTrapFuncInvalid, "invalid function")                                   \
718
  T(WasmTrapFuncSigMismatch, "function signature mismatch")                    \
719
  T(WasmTrapInvalidIndex, "invalid index into function table")                 \
720
  T(WasmTrapTypeError, "invalid type")                                         \
721
  T(WasmExceptionError, "wasm exception")                                      \
722
  /* Asm.js validation related */                                              \
723
  T(AsmJsInvalid, "Invalid asm.js: %")                                         \
724 725
  T(AsmJsCompiled, "Converted asm.js to WebAssembly: %")                       \
  T(AsmJsInstantiated, "Instantiated asm.js: %")                               \
726
  T(AsmJsLinkingFailed, "Linking failure in asm.js: %")                        \
727 728
  /* DataCloneError messages */                                                \
  T(DataCloneError, "% could not be cloned.")                                  \
729
  T(DataCloneErrorOutOfMemory, "Data cannot be cloned, out of memory.")        \
730 731
  T(DataCloneErrorNeuteredArrayBuffer,                                         \
    "An ArrayBuffer is neutered and could not be cloned.")                     \
732 733
  T(DataCloneErrorSharedArrayBufferTransferred,                                \
    "A SharedArrayBuffer could not be cloned. SharedArrayBuffer must not be "  \
734 735 736 737 738
    "transferred.")                                                            \
  T(DataCloneDeserializationError, "Unable to deserialize cloned data.")       \
  T(DataCloneDeserializationVersionError,                                      \
    "Unable to deserialize cloned data due to invalid or unsupported "         \
    "version.")
739 740 741

class MessageTemplate {
 public:
742
  enum Template {
743 744 745 746 747 748
#define TEMPLATE(NAME, STRING) k##NAME,
    MESSAGE_TEMPLATES(TEMPLATE)
#undef TEMPLATE
        kLastMessage
  };

749 750
  static const char* TemplateString(int template_index);

751 752 753 754
  static MaybeHandle<String> FormatMessage(int template_index,
                                           Handle<String> arg0,
                                           Handle<String> arg1,
                                           Handle<String> arg2);
755 756 757 758 759 760 761 762 763 764 765 766

  static Handle<String> FormatMessage(Isolate* isolate, int template_index,
                                      Handle<Object> arg);
};


// A message handler is a convenience interface for accessing the list
// of message listeners registered in an environment
class MessageHandler {
 public:
  // Returns a message object for the API to use.
  static Handle<JSMessageObject> MakeMessageObject(
767
      Isolate* isolate, MessageTemplate::Template type,
768
      const MessageLocation* location, Handle<Object> argument,
769
      Handle<FixedArray> stack_frames);
770 771

  // Report a formatted message (needs JS allocation).
772
  static void ReportMessage(Isolate* isolate, const MessageLocation* loc,
773
                            Handle<JSMessageObject> message);
774 775 776 777

  static void DefaultMessageReport(Isolate* isolate, const MessageLocation* loc,
                                   Handle<Object> message_obj);
  static Handle<String> GetMessage(Isolate* isolate, Handle<Object> data);
778 779
  static std::unique_ptr<char[]> GetLocalizedMessage(Isolate* isolate,
                                                     Handle<Object> data);
780 781 782 783 784 785

 private:
  static void ReportMessageNoExceptions(Isolate* isolate,
                                        const MessageLocation* loc,
                                        Handle<Object> message_obj,
                                        v8::Local<v8::Value> api_exception_obj);
786
};
787 788


789 790
}  // namespace internal
}  // namespace v8
791 792

#endif  // V8_MESSAGES_H_