Path: blob/trunk/third_party/closure/goog/asserts/asserts.js
4010 views
/**1* @license2* Copyright The Closure Library Authors.3* SPDX-License-Identifier: Apache-2.04*/56/**7* @fileoverview Utilities to check the preconditions, postconditions and8* invariants runtime.9*10* Methods in this package are given special treatment by the compiler11* for type-inference. For example, <code>goog.asserts.assert(foo)</code>12* will make the compiler treat <code>foo</code> as non-nullable. Similarly,13* <code>goog.asserts.assertNumber(foo)</code> informs the compiler about the14* type of <code>foo</code>. Where applicable, such assertions are preferable to15* casts by jsdoc with <code>@type</code>.16*17* The compiler has an option to disable asserts. So code like:18* <code>19* var x = goog.asserts.assert(foo());20* goog.asserts.assert(bar());21* </code>22* will be transformed into:23* <code>24* var x = foo();25* </code>26* The compiler will leave in foo() (because its return value is used),27* but it will remove bar() because it assumes it does not have side-effects.28*29* Additionally, note the compiler will consider the type to be "tightened" for30* all statements <em>after</em> the assertion. For example:31* <code>32* const /** ?Object &#ast;/ value = foo();33* goog.asserts.assert(value);34* // "value" is of type {!Object} at this point.35* </code>36*/3738goog.module('goog.asserts');39goog.module.declareLegacyNamespace();4041const DebugError = goog.require('goog.debug.Error');42const NodeType = goog.require('goog.dom.NodeType');43const utils = goog.require('goog.utils');444546// NOTE: this needs to be exported directly and referenced via the exports47// object because unit tests stub it out.48/**49* @define {boolean} Whether to strip out asserts or to leave them in.50*/51exports.ENABLE_ASSERTS = goog.define('goog.asserts.ENABLE_ASSERTS', goog.DEBUG);52535455/**56* Error object for failed assertions.57* @param {string} messagePattern The pattern that was used to form message.58* @param {!Array<*>} messageArgs The items to substitute into the pattern.59* @constructor60* @extends {DebugError}61* @final62*/63function AssertionError(messagePattern, messageArgs) {64DebugError.call(this, subs(messagePattern, messageArgs));6566/**67* The message pattern used to format the error message. Error handlers can68* use this to uniquely identify the assertion.69* @type {string}70*/71this.messagePattern = messagePattern;72}73utils.inherits(AssertionError, DebugError);74exports.AssertionError = AssertionError;7576/** @override @type {string} */77AssertionError.prototype.name = 'AssertionError';787980/**81* The default error handler.82* @param {!AssertionError} e The exception to be handled.83* @return {void}84*/85exports.DEFAULT_ERROR_HANDLER = function(e) {86throw e;87};888990/**91* The handler responsible for throwing or logging assertion errors.92* @type {function(!AssertionError)}93*/94let errorHandler_ = exports.DEFAULT_ERROR_HANDLER;959697/**98* Does simple python-style string substitution.99* subs("foo%s hot%s", "bar", "dog") becomes "foobar hotdog".100* @param {string} pattern The string containing the pattern.101* @param {!Array<*>} subs The items to substitute into the pattern.102* @return {string} A copy of `str` in which each occurrence of103* `%s` has been replaced an argument from `var_args`.104*/105function subs(pattern, subs) {106const splitParts = pattern.split('%s');107let returnString = '';108109// Replace up to the last split part. We are inserting in the110// positions between split parts.111const subLast = splitParts.length - 1;112for (let i = 0; i < subLast; i++) {113// keep unsupplied as '%s'114const sub = (i < subs.length) ? subs[i] : '%s';115returnString += splitParts[i] + sub;116}117return returnString + splitParts[subLast];118}119120121/**122* Throws an exception with the given message and "Assertion failed" prefixed123* onto it.124* @param {string} defaultMessage The message to use if givenMessage is empty.125* @param {?Array<*>} defaultArgs The substitution arguments for defaultMessage.126* @param {string|undefined} givenMessage Message supplied by the caller.127* @param {!Array<*>} givenArgs The substitution arguments for givenMessage.128* @throws {AssertionError} When the value is not a number.129*/130function doAssertFailure(defaultMessage, defaultArgs, givenMessage, givenArgs) {131let message = 'Assertion failed';132let args;133if (givenMessage) {134message += ': ' + givenMessage;135args = givenArgs;136} else if (defaultMessage) {137message += ': ' + defaultMessage;138args = defaultArgs;139}140// The '' + works around an Opera 10 bug in the unit tests. Without it,141// a stack trace is added to var message above. With this, a stack trace is142// not added until this line (it causes the extra garbage to be added after143// the assertion message instead of in the middle of it).144const e = new AssertionError('' + message, args || []);145errorHandler_(e);146}147148149/**150* Sets a custom error handler that can be used to customize the behavior of151* assertion failures, for example by turning all assertion failures into log152* messages.153* @param {function(!AssertionError)} errorHandler154* @return {void}155*/156exports.setErrorHandler = function(errorHandler) {157if (exports.ENABLE_ASSERTS) {158errorHandler_ = errorHandler;159}160};161162163/**164* Checks if the condition evaluates to true if ENABLE_ASSERTS is165* true.166* @template T167* @param {T} condition The condition to check.168* @param {string=} opt_message Error message in case of failure.169* @param {...*} var_args The items to substitute into the failure message.170* @return {T} The value of the condition.171* @throws {AssertionError} When the condition evaluates to false.172* @closurePrimitive {asserts.truthy}173*/174exports.assert = function(condition, opt_message, var_args) {175if (exports.ENABLE_ASSERTS && !condition) {176doAssertFailure(177'', null, opt_message, Array.prototype.slice.call(arguments, 2));178}179return condition;180};181182183/**184* Checks if `value` is `null` or `undefined` if goog.asserts.ENABLE_ASSERTS is185* true.186*187* @param {T} value The value to check.188* @param {string=} opt_message Error message in case of failure.189* @param {...*} var_args The items to substitute into the failure message.190* @return {R} `value` with its type narrowed to exclude `null` and `undefined`.191*192* @template T193* @template R :=194* mapunion(T, (V) =>195* cond(eq(V, 'null'),196* none(),197* cond(eq(V, 'undefined'),198* none(),199* V)))200* =:201*202* @throws {!AssertionError} When `value` is `null` or `undefined`.203* @closurePrimitive {asserts.matchesReturn}204*/205exports.assertExists = function(value, opt_message, var_args) {206if (exports.ENABLE_ASSERTS && value == null) {207doAssertFailure(208'Expected to exist: %s.', [value], opt_message,209Array.prototype.slice.call(arguments, 2));210}211return value;212};213214215/**216* Fails if goog.asserts.ENABLE_ASSERTS is true. This function is useful in case217* when we want to add a check in the unreachable area like switch-case218* statement:219*220* <pre>221* switch(type) {222* case FOO: doSomething(); break;223* case BAR: doSomethingElse(); break;224* default: goog.asserts.fail('Unrecognized type: ' + type);225* // We have only 2 types - "default:" section is unreachable code.226* }227* </pre>228*229* @param {string=} opt_message Error message in case of failure.230* @param {...*} var_args The items to substitute into the failure message.231* @return {void}232* @throws {AssertionError} Failure.233* @closurePrimitive {asserts.fail}234*/235exports.fail = function(opt_message, var_args) {236if (exports.ENABLE_ASSERTS) {237errorHandler_(new AssertionError(238'Failure' + (opt_message ? ': ' + opt_message : ''),239Array.prototype.slice.call(arguments, 1)));240}241};242243244/**245* Checks if the value is a number if goog.asserts.ENABLE_ASSERTS is true.246* @param {*} value The value to check.247* @param {string=} opt_message Error message in case of failure.248* @param {...*} var_args The items to substitute into the failure message.249* @return {number} The value, guaranteed to be a number when asserts enabled.250* @throws {AssertionError} When the value is not a number.251* @closurePrimitive {asserts.matchesReturn}252*/253exports.assertNumber = function(value, opt_message, var_args) {254if (exports.ENABLE_ASSERTS && typeof value !== 'number') {255doAssertFailure(256'Expected number but got %s: %s.', [utils.typeOf(value), value],257opt_message, Array.prototype.slice.call(arguments, 2));258}259return /** @type {number} */ (value);260};261262263/**264* Checks if the value is a string if goog.asserts.ENABLE_ASSERTS is true.265* @param {*} value The value to check.266* @param {string=} opt_message Error message in case of failure.267* @param {...*} var_args The items to substitute into the failure message.268* @return {string} The value, guaranteed to be a string when asserts enabled.269* @throws {AssertionError} When the value is not a string.270* @closurePrimitive {asserts.matchesReturn}271*/272exports.assertString = function(value, opt_message, var_args) {273if (exports.ENABLE_ASSERTS && typeof value !== 'string') {274doAssertFailure(275'Expected string but got %s: %s.', [utils.typeOf(value), value],276opt_message, Array.prototype.slice.call(arguments, 2));277}278return /** @type {string} */ (value);279};280281282/**283* Checks if the value is a function if goog.asserts.ENABLE_ASSERTS is true.284* @param {*} value The value to check.285* @param {string=} opt_message Error message in case of failure.286* @param {...*} var_args The items to substitute into the failure message.287* @return {!Function} The value, guaranteed to be a function when asserts288* enabled.289* @throws {AssertionError} When the value is not a function.290* @closurePrimitive {asserts.matchesReturn}291*/292exports.assertFunction = function(value, opt_message, var_args) {293if (exports.ENABLE_ASSERTS && typeof value !== 'function') {294doAssertFailure(295'Expected function but got %s: %s.', [utils.typeOf(value), value],296opt_message, Array.prototype.slice.call(arguments, 2));297}298return /** @type {!Function} */ (value);299};300301302/**303* Checks if the value is an Object if goog.asserts.ENABLE_ASSERTS is true.304* @param {*} value The value to check.305* @param {string=} opt_message Error message in case of failure.306* @param {...*} var_args The items to substitute into the failure message.307* @return {!Object} The value, guaranteed to be a non-null object.308* @throws {AssertionError} When the value is not an object.309* @closurePrimitive {asserts.matchesReturn}310*/311exports.assertObject = function(value, opt_message, var_args) {312if (exports.ENABLE_ASSERTS && !utils.isObject(value)) {313doAssertFailure(314'Expected object but got %s: %s.', [utils.typeOf(value), value],315opt_message, Array.prototype.slice.call(arguments, 2));316}317return /** @type {!Object} */ (value);318};319320321/**322* Checks if the value is an Array if ENABLE_ASSERTS is true.323* @param {*} value The value to check.324* @param {string=} opt_message Error message in case of failure.325* @param {...*} var_args The items to substitute into the failure message.326* @return {!Array<?>} The value, guaranteed to be a non-null array.327* @throws {AssertionError} When the value is not an array.328* @closurePrimitive {asserts.matchesReturn}329*/330exports.assertArray = function(value, opt_message, var_args) {331if (exports.ENABLE_ASSERTS && !Array.isArray(value)) {332doAssertFailure(333'Expected array but got %s: %s.', [utils.typeOf(value), value],334opt_message, Array.prototype.slice.call(arguments, 2));335}336return /** @type {!Array<?>} */ (value);337};338339340/**341* Checks if the value is a boolean if goog.asserts.ENABLE_ASSERTS is true.342* @param {*} value The value to check.343* @param {string=} opt_message Error message in case of failure.344* @param {...*} var_args The items to substitute into the failure message.345* @return {boolean} The value, guaranteed to be a boolean when asserts are346* enabled.347* @throws {AssertionError} When the value is not a boolean.348* @closurePrimitive {asserts.matchesReturn}349*/350exports.assertBoolean = function(value, opt_message, var_args) {351if (exports.ENABLE_ASSERTS && typeof value !== 'boolean') {352doAssertFailure(353'Expected boolean but got %s: %s.', [utils.typeOf(value), value],354opt_message, Array.prototype.slice.call(arguments, 2));355}356return /** @type {boolean} */ (value);357};358359360/**361* Checks if the value is a DOM Element if goog.asserts.ENABLE_ASSERTS is true.362* @param {*} value The value to check.363* @param {string=} opt_message Error message in case of failure.364* @param {...*} var_args The items to substitute into the failure message.365* @return {!Element} The value, likely to be a DOM Element when asserts are366* enabled.367* @throws {AssertionError} When the value is not an Element.368* @closurePrimitive {asserts.matchesReturn}369* @deprecated Use goog.asserts.dom.assertIsElement instead.370*/371exports.assertElement = function(value, opt_message, var_args) {372if (exports.ENABLE_ASSERTS &&373(!utils.isObject(value) ||374/** @type {!Node} */ (value).nodeType != NodeType.ELEMENT)) {375doAssertFailure(376'Expected Element but got %s: %s.', [utils.typeOf(value), value],377opt_message, Array.prototype.slice.call(arguments, 2));378}379return /** @type {!Element} */ (value);380};381382383/**384* Checks if the value is an instance of the user-defined type if385* goog.asserts.ENABLE_ASSERTS is true.386*387* The compiler may tighten the type returned by this function.388*389* Do not use this to ensure a value is an HTMLElement or a subclass! Cross-390* document DOM inherits from separate - though identical - browser classes, and391* such a check will unexpectedly fail. Please use the methods in392* goog.asserts.dom for these purposes.393*394* @param {?} value The value to check.395* @param {function(new: T, ...)} type A user-defined constructor.396* @param {string=} opt_message Error message in case of failure.397* @param {...*} var_args The items to substitute into the failure message.398* @throws {AssertionError} When the value is not an instance of399* type.400* @return {T}401* @template T402* @closurePrimitive {asserts.matchesReturn}403*/404exports.assertInstanceof = function(value, type, opt_message, var_args) {405if (exports.ENABLE_ASSERTS && !(value instanceof type)) {406doAssertFailure(407'Expected instanceof %s but got %s.', [getType(type), getType(value)],408opt_message, Array.prototype.slice.call(arguments, 3));409}410return value;411};412413414/**415* Checks whether the value is a finite number, if ENABLE_ASSERTS416* is true.417*418* @param {*} value The value to check.419* @param {string=} opt_message Error message in case of failure.420* @param {...*} var_args The items to substitute into the failure message.421* @throws {AssertionError} When the value is not a number, or is422* a non-finite number such as NaN, Infinity or -Infinity.423* @return {number} The value initially passed in.424*/425exports.assertFinite = function(value, opt_message, var_args) {426if (exports.ENABLE_ASSERTS &&427(typeof value != 'number' || !isFinite(value))) {428doAssertFailure(429'Expected %s to be a finite number but it is not.', [value],430opt_message, Array.prototype.slice.call(arguments, 2));431}432return /** @type {number} */ (value);433};434435/**436* Returns the type of a value. If a constructor is passed, and a suitable437* string cannot be found, 'unknown type name' will be returned.438* @param {*} value A constructor, object, or primitive.439* @return {string} The best display name for the value, or 'unknown type name'.440*/441function getType(value) {442if (value instanceof Function) {443return value.displayName || value.name || 'unknown type name';444} else if (value instanceof Object) {445return /** @type {string} */ (value.constructor.displayName) ||446value.constructor.name || Object.prototype.toString.call(value);447} else {448return value === null ? 'null' : typeof value;449}450}451452453