# lib/goog/asserts/asserts.js

    1// Copyright 2008 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415/**16 * @fileoverview Utilities to check the preconditions, postconditions and17 * invariants runtime.18 *19 * Methods in this package should be given special treatment by the compiler20 * for type-inference. For example, <code>goog.asserts.assert(foo)</code>21 * will restrict <code>foo</code> to a truthy value.22 *23 * The compiler has an option to disable asserts. So code like:24 * <code>25 * var x = goog.asserts.assert(foo()); goog.asserts.assert(bar());26 * </code>27 * will be transformed into:28 * <code>29 * var x = foo();30 * </code>31 * The compiler will leave in foo() (because its return value is used),32 * but it will remove bar() because it assumes it does not have side-effects.33 *34 */3536goog.provide('goog.asserts');37goog.provide('goog.asserts.AssertionError');3839goog.require('goog.debug.Error');40goog.require('goog.dom.NodeType');41goog.require('goog.string');424344/**45 * @define {boolean} Whether to strip out asserts or to leave them in.46 */47goog.define('goog.asserts.ENABLE_ASSERTS', goog.DEBUG);48495051/**52 * Error object for failed assertions.53 * @param {string} messagePattern The pattern that was used to form message.54 * @param {!Array.<*>} messageArgs The items to substitute into the pattern.55 * @constructor56 * @extends {goog.debug.Error}57 * @final58 */59goog.asserts.AssertionError = function(messagePattern, messageArgs) {60  messageArgs.unshift(messagePattern);61  goog.debug.Error.call(this, goog.string.subs.apply(null, messageArgs));62  // Remove the messagePattern afterwards to avoid permenantly modifying the63  // passed in array.64  messageArgs.shift();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   */71  this.messagePattern = messagePattern;72};73goog.inherits(goog.asserts.AssertionError, goog.debug.Error);747576/** @override */77goog.asserts.AssertionError.prototype.name = 'AssertionError';787980/**81 * The default error handler.82 * @param {!goog.asserts.AssertionError} e The exception to be handled.83 */84goog.asserts.DEFAULT_ERROR_HANDLER = function(e) { throw e; };858687/**88 * The handler responsible for throwing or logging assertion errors.89 * @private {function(!goog.asserts.AssertionError)}90 */91goog.asserts.errorHandler_ = goog.asserts.DEFAULT_ERROR_HANDLER;929394/**95 * Throws an exception with the given message and "Assertion failed" prefixed96 * onto it.97 * @param {string} defaultMessage The message to use if givenMessage is empty.98 * @param {Array.<*>} defaultArgs The substitution arguments for defaultMessage.99 * @param {string|undefined} givenMessage Message supplied by the caller.100 * @param {Array.<*>} givenArgs The substitution arguments for givenMessage.101 * @throws {goog.asserts.AssertionError} When the value is not a number.102 * @private103 */104goog.asserts.doAssertFailure_ =105    function(defaultMessage, defaultArgs, givenMessage, givenArgs) {106  var message = 'Assertion failed';107  if (givenMessage) {108    message += ': ' + givenMessage;109    var args = givenArgs;110  } else if (defaultMessage) {111    message += ': ' + defaultMessage;112    args = defaultArgs;113  }114  // The '' + works around an Opera 10 bug in the unit tests. Without it,115  // a stack trace is added to var message above. With this, a stack trace is116  // not added until this line (it causes the extra garbage to be added after117  // the assertion message instead of in the middle of it).118  var e = new goog.asserts.AssertionError('' + message, args || []);119  goog.asserts.errorHandler_(e);120};121122123/**124 * Sets a custom error handler that can be used to customize the behavior of125 * assertion failures, for example by turning all assertion failures into log126 * messages.127 * @param {function(goog.asserts.AssertionError)} errorHandler128 */129goog.asserts.setErrorHandler = function(errorHandler) {130  if (goog.asserts.ENABLE_ASSERTS) {131    goog.asserts.errorHandler_ = errorHandler;132  }133};134135136/**137 * Checks if the condition evaluates to true if goog.asserts.ENABLE_ASSERTS is138 * true.139 * @template T140 * @param {T} condition The condition to check.141 * @param {string=} opt_message Error message in case of failure.142 * @param {...*} var_args The items to substitute into the failure message.143 * @return {T} The value of the condition.144 * @throws {goog.asserts.AssertionError} When the condition evaluates to false.145 */146goog.asserts.assert = function(condition, opt_message, var_args) {147  if (goog.asserts.ENABLE_ASSERTS && !condition) {148    goog.asserts.doAssertFailure_('', null, opt_message,149        Array.prototype.slice.call(arguments, 2));150  }151  return condition;152};153154155/**156 * Fails if goog.asserts.ENABLE_ASSERTS is true. This function is useful in case157 * when we want to add a check in the unreachable area like switch-case158 * statement:159 *160 * <pre>161 *  switch(type) {162 *    case FOO: doSomething(); break;163 *    case BAR: doSomethingElse(); break;164 *    default: goog.assert.fail('Unrecognized type: ' + type);165 *      // We have only 2 types - "default:" section is unreachable code.166 *  }167 * </pre>168 *169 * @param {string=} opt_message Error message in case of failure.170 * @param {...*} var_args The items to substitute into the failure message.171 * @throws {goog.asserts.AssertionError} Failure.172 */173goog.asserts.fail = function(opt_message, var_args) {174  if (goog.asserts.ENABLE_ASSERTS) {175    goog.asserts.errorHandler_(new goog.asserts.AssertionError(176        'Failure' + (opt_message ? ': ' + opt_message : ''),177        Array.prototype.slice.call(arguments, 1)));178  }179};180181182/**183 * Checks if the value is a number if goog.asserts.ENABLE_ASSERTS is true.184 * @param {*} value The value to check.185 * @param {string=} opt_message Error message in case of failure.186 * @param {...*} var_args The items to substitute into the failure message.187 * @return {number} The value, guaranteed to be a number when asserts enabled.188 * @throws {goog.asserts.AssertionError} When the value is not a number.189 */190goog.asserts.assertNumber = function(value, opt_message, var_args) {191  if (goog.asserts.ENABLE_ASSERTS && !goog.isNumber(value)) {192    goog.asserts.doAssertFailure_('Expected number but got %s: %s.',193        [goog.typeOf(value), value], opt_message,194        Array.prototype.slice.call(arguments, 2));195  }196  return /** @type {number} */ (value);197};198199200/**201 * Checks if the value is a string if goog.asserts.ENABLE_ASSERTS is true.202 * @param {*} value The value to check.203 * @param {string=} opt_message Error message in case of failure.204 * @param {...*} var_args The items to substitute into the failure message.205 * @return {string} The value, guaranteed to be a string when asserts enabled.206 * @throws {goog.asserts.AssertionError} When the value is not a string.207 */208goog.asserts.assertString = function(value, opt_message, var_args) {209  if (goog.asserts.ENABLE_ASSERTS && !goog.isString(value)) {210    goog.asserts.doAssertFailure_('Expected string but got %s: %s.',211        [goog.typeOf(value), value], opt_message,212        Array.prototype.slice.call(arguments, 2));213  }214  return /** @type {string} */ (value);215};216217218/**219 * Checks if the value is a function if goog.asserts.ENABLE_ASSERTS is true.220 * @param {*} value The value to check.221 * @param {string=} opt_message Error message in case of failure.222 * @param {...*} var_args The items to substitute into the failure message.223 * @return {!Function} The value, guaranteed to be a function when asserts224 *     enabled.225 * @throws {goog.asserts.AssertionError} When the value is not a function.226 */227goog.asserts.assertFunction = function(value, opt_message, var_args) {228  if (goog.asserts.ENABLE_ASSERTS && !goog.isFunction(value)) {229    goog.asserts.doAssertFailure_('Expected function but got %s: %s.',230        [goog.typeOf(value), value], opt_message,231        Array.prototype.slice.call(arguments, 2));232  }233  return /** @type {!Function} */ (value);234};235236237/**238 * Checks if the value is an Object if goog.asserts.ENABLE_ASSERTS is true.239 * @param {*} value The value to check.240 * @param {string=} opt_message Error message in case of failure.241 * @param {...*} var_args The items to substitute into the failure message.242 * @return {!Object} The value, guaranteed to be a non-null object.243 * @throws {goog.asserts.AssertionError} When the value is not an object.244 */245goog.asserts.assertObject = function(value, opt_message, var_args) {246  if (goog.asserts.ENABLE_ASSERTS && !goog.isObject(value)) {247    goog.asserts.doAssertFailure_('Expected object but got %s: %s.',248        [goog.typeOf(value), value],249        opt_message, Array.prototype.slice.call(arguments, 2));250  }251  return /** @type {!Object} */ (value);252};253254255/**256 * Checks if the value is an Array if goog.asserts.ENABLE_ASSERTS is true.257 * @param {*} value The value to check.258 * @param {string=} opt_message Error message in case of failure.259 * @param {...*} var_args The items to substitute into the failure message.260 * @return {!Array} The value, guaranteed to be a non-null array.261 * @throws {goog.asserts.AssertionError} When the value is not an array.262 */263goog.asserts.assertArray = function(value, opt_message, var_args) {264  if (goog.asserts.ENABLE_ASSERTS && !goog.isArray(value)) {265    goog.asserts.doAssertFailure_('Expected array but got %s: %s.',266        [goog.typeOf(value), value], opt_message,267        Array.prototype.slice.call(arguments, 2));268  }269  return /** @type {!Array} */ (value);270};271272273/**274 * Checks if the value is a boolean if goog.asserts.ENABLE_ASSERTS is true.275 * @param {*} value The value to check.276 * @param {string=} opt_message Error message in case of failure.277 * @param {...*} var_args The items to substitute into the failure message.278 * @return {boolean} The value, guaranteed to be a boolean when asserts are279 *     enabled.280 * @throws {goog.asserts.AssertionError} When the value is not a boolean.281 */282goog.asserts.assertBoolean = function(value, opt_message, var_args) {283  if (goog.asserts.ENABLE_ASSERTS && !goog.isBoolean(value)) {284    goog.asserts.doAssertFailure_('Expected boolean but got %s: %s.',285        [goog.typeOf(value), value], opt_message,286        Array.prototype.slice.call(arguments, 2));287  }288  return /** @type {boolean} */ (value);289};290291292/**293 * Checks if the value is a DOM Element if goog.asserts.ENABLE_ASSERTS is true.294 * @param {*} value The value to check.295 * @param {string=} opt_message Error message in case of failure.296 * @param {...*} var_args The items to substitute into the failure message.297 * @return {!Element} The value, likely to be a DOM Element when asserts are298 *     enabled.299 * @throws {goog.asserts.AssertionError} When the value is not a boolean.300 */301goog.asserts.assertElement = function(value, opt_message, var_args) {302  if (goog.asserts.ENABLE_ASSERTS && (!goog.isObject(value) ||303      value.nodeType != goog.dom.NodeType.ELEMENT)) {304    goog.asserts.doAssertFailure_('Expected Element but got %s: %s.',305        [goog.typeOf(value), value], opt_message,306        Array.prototype.slice.call(arguments, 2));307  }308  return /** @type {!Element} */ (value);309};310311312/**313 * Checks if the value is an instance of the user-defined type if314 * goog.asserts.ENABLE_ASSERTS is true.315 *316 * The compiler may tighten the type returned by this function.317 *318 * @param {*} value The value to check.319 * @param {function(new: T, ...)} type A user-defined constructor.320 * @param {string=} opt_message Error message in case of failure.321 * @param {...*} var_args The items to substitute into the failure message.322 * @throws {goog.asserts.AssertionError} When the value is not an instance of323 *     type.324 * @return {!T}325 * @template T326 */327goog.asserts.assertInstanceof = function(value, type, opt_message, var_args) {328  if (goog.asserts.ENABLE_ASSERTS && !(value instanceof type)) {329    goog.asserts.doAssertFailure_('instanceof check failed.', null,330        opt_message, Array.prototype.slice.call(arguments, 3));331  }332  return value;333};334335336/**337 * Checks that no enumerable keys are present in Object.prototype. Such keys338 * would break most code that use {@code for (var ... in ...)} loops.339 */340goog.asserts.assertObjectPrototypeIsIntact = function() {341  for (var key in Object.prototype) {342    goog.asserts.fail(key + ' should not be enumerable in Object.prototype.');343  }344};