Path: blob/trunk/third_party/closure/goog/asserts/asserts.js
2868 views
// Copyright 2008 The Closure Library Authors. All Rights Reserved.1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS-IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314/**15* @fileoverview Utilities to check the preconditions, postconditions and16* invariants runtime.17*18* Methods in this package should be given special treatment by the compiler19* for type-inference. For example, <code>goog.asserts.assert(foo)</code>20* will restrict <code>foo</code> to a truthy value.21*22* The compiler has an option to disable asserts. So code like:23* <code>24* var x = goog.asserts.assert(foo()); goog.asserts.assert(bar());25* </code>26* will be transformed into:27* <code>28* var x = foo();29* </code>30* The compiler will leave in foo() (because its return value is used),31* but it will remove bar() because it assumes it does not have side-effects.32*33* @author [email protected] (Andrew Grieve)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) {60messageArgs.unshift(messagePattern);61goog.debug.Error.call(this, goog.string.subs.apply(null, messageArgs));62// Remove the messagePattern afterwards to avoid permanently modifying the63// passed in array.64messageArgs.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*/71this.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) {85throw e;86};878889/**90* The handler responsible for throwing or logging assertion errors.91* @private {function(!goog.asserts.AssertionError)}92*/93goog.asserts.errorHandler_ = goog.asserts.DEFAULT_ERROR_HANDLER;949596/**97* Throws an exception with the given message and "Assertion failed" prefixed98* onto it.99* @param {string} defaultMessage The message to use if givenMessage is empty.100* @param {Array<*>} defaultArgs The substitution arguments for defaultMessage.101* @param {string|undefined} givenMessage Message supplied by the caller.102* @param {Array<*>} givenArgs The substitution arguments for givenMessage.103* @throws {goog.asserts.AssertionError} When the value is not a number.104* @private105*/106goog.asserts.doAssertFailure_ = function(107defaultMessage, defaultArgs, givenMessage, givenArgs) {108var message = 'Assertion failed';109if (givenMessage) {110message += ': ' + givenMessage;111var args = givenArgs;112} else if (defaultMessage) {113message += ': ' + defaultMessage;114args = defaultArgs;115}116// The '' + works around an Opera 10 bug in the unit tests. Without it,117// a stack trace is added to var message above. With this, a stack trace is118// not added until this line (it causes the extra garbage to be added after119// the assertion message instead of in the middle of it).120var e = new goog.asserts.AssertionError('' + message, args || []);121goog.asserts.errorHandler_(e);122};123124125/**126* Sets a custom error handler that can be used to customize the behavior of127* assertion failures, for example by turning all assertion failures into log128* messages.129* @param {function(!goog.asserts.AssertionError)} errorHandler130*/131goog.asserts.setErrorHandler = function(errorHandler) {132if (goog.asserts.ENABLE_ASSERTS) {133goog.asserts.errorHandler_ = errorHandler;134}135};136137138/**139* Checks if the condition evaluates to true if goog.asserts.ENABLE_ASSERTS is140* true.141* @template T142* @param {T} condition The condition to check.143* @param {string=} opt_message Error message in case of failure.144* @param {...*} var_args The items to substitute into the failure message.145* @return {T} The value of the condition.146* @throws {goog.asserts.AssertionError} When the condition evaluates to false.147*/148goog.asserts.assert = function(condition, opt_message, var_args) {149if (goog.asserts.ENABLE_ASSERTS && !condition) {150goog.asserts.doAssertFailure_(151'', null, opt_message, Array.prototype.slice.call(arguments, 2));152}153return condition;154};155156157/**158* Fails if goog.asserts.ENABLE_ASSERTS is true. This function is useful in case159* when we want to add a check in the unreachable area like switch-case160* statement:161*162* <pre>163* switch(type) {164* case FOO: doSomething(); break;165* case BAR: doSomethingElse(); break;166* default: goog.asserts.fail('Unrecognized type: ' + type);167* // We have only 2 types - "default:" section is unreachable code.168* }169* </pre>170*171* @param {string=} opt_message Error message in case of failure.172* @param {...*} var_args The items to substitute into the failure message.173* @throws {goog.asserts.AssertionError} Failure.174*/175goog.asserts.fail = function(opt_message, var_args) {176if (goog.asserts.ENABLE_ASSERTS) {177goog.asserts.errorHandler_(178new goog.asserts.AssertionError(179'Failure' + (opt_message ? ': ' + opt_message : ''),180Array.prototype.slice.call(arguments, 1)));181}182};183184185/**186* Checks if the value is a number if goog.asserts.ENABLE_ASSERTS is true.187* @param {*} 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 {number} The value, guaranteed to be a number when asserts enabled.191* @throws {goog.asserts.AssertionError} When the value is not a number.192*/193goog.asserts.assertNumber = function(value, opt_message, var_args) {194if (goog.asserts.ENABLE_ASSERTS && !goog.isNumber(value)) {195goog.asserts.doAssertFailure_(196'Expected number but got %s: %s.', [goog.typeOf(value), value],197opt_message, Array.prototype.slice.call(arguments, 2));198}199return /** @type {number} */ (value);200};201202203/**204* Checks if the value is a string if goog.asserts.ENABLE_ASSERTS is true.205* @param {*} value The value to check.206* @param {string=} opt_message Error message in case of failure.207* @param {...*} var_args The items to substitute into the failure message.208* @return {string} The value, guaranteed to be a string when asserts enabled.209* @throws {goog.asserts.AssertionError} When the value is not a string.210*/211goog.asserts.assertString = function(value, opt_message, var_args) {212if (goog.asserts.ENABLE_ASSERTS && !goog.isString(value)) {213goog.asserts.doAssertFailure_(214'Expected string but got %s: %s.', [goog.typeOf(value), value],215opt_message, Array.prototype.slice.call(arguments, 2));216}217return /** @type {string} */ (value);218};219220221/**222* Checks if the value is a function if goog.asserts.ENABLE_ASSERTS is true.223* @param {*} value The value to check.224* @param {string=} opt_message Error message in case of failure.225* @param {...*} var_args The items to substitute into the failure message.226* @return {!Function} The value, guaranteed to be a function when asserts227* enabled.228* @throws {goog.asserts.AssertionError} When the value is not a function.229*/230goog.asserts.assertFunction = function(value, opt_message, var_args) {231if (goog.asserts.ENABLE_ASSERTS && !goog.isFunction(value)) {232goog.asserts.doAssertFailure_(233'Expected function but got %s: %s.', [goog.typeOf(value), value],234opt_message, Array.prototype.slice.call(arguments, 2));235}236return /** @type {!Function} */ (value);237};238239240/**241* Checks if the value is an Object if goog.asserts.ENABLE_ASSERTS is true.242* @param {*} value The value to check.243* @param {string=} opt_message Error message in case of failure.244* @param {...*} var_args The items to substitute into the failure message.245* @return {!Object} The value, guaranteed to be a non-null object.246* @throws {goog.asserts.AssertionError} When the value is not an object.247*/248goog.asserts.assertObject = function(value, opt_message, var_args) {249if (goog.asserts.ENABLE_ASSERTS && !goog.isObject(value)) {250goog.asserts.doAssertFailure_(251'Expected object but got %s: %s.', [goog.typeOf(value), value],252opt_message, Array.prototype.slice.call(arguments, 2));253}254return /** @type {!Object} */ (value);255};256257258/**259* Checks if the value is an Array if goog.asserts.ENABLE_ASSERTS is true.260* @param {*} value The value to check.261* @param {string=} opt_message Error message in case of failure.262* @param {...*} var_args The items to substitute into the failure message.263* @return {!Array<?>} The value, guaranteed to be a non-null array.264* @throws {goog.asserts.AssertionError} When the value is not an array.265*/266goog.asserts.assertArray = function(value, opt_message, var_args) {267if (goog.asserts.ENABLE_ASSERTS && !goog.isArray(value)) {268goog.asserts.doAssertFailure_(269'Expected array but got %s: %s.', [goog.typeOf(value), value],270opt_message, Array.prototype.slice.call(arguments, 2));271}272return /** @type {!Array<?>} */ (value);273};274275276/**277* Checks if the value is a boolean if goog.asserts.ENABLE_ASSERTS is true.278* @param {*} value The value to check.279* @param {string=} opt_message Error message in case of failure.280* @param {...*} var_args The items to substitute into the failure message.281* @return {boolean} The value, guaranteed to be a boolean when asserts are282* enabled.283* @throws {goog.asserts.AssertionError} When the value is not a boolean.284*/285goog.asserts.assertBoolean = function(value, opt_message, var_args) {286if (goog.asserts.ENABLE_ASSERTS && !goog.isBoolean(value)) {287goog.asserts.doAssertFailure_(288'Expected boolean but got %s: %s.', [goog.typeOf(value), value],289opt_message, Array.prototype.slice.call(arguments, 2));290}291return /** @type {boolean} */ (value);292};293294295/**296* Checks if the value is a DOM Element if goog.asserts.ENABLE_ASSERTS is true.297* @param {*} value The value to check.298* @param {string=} opt_message Error message in case of failure.299* @param {...*} var_args The items to substitute into the failure message.300* @return {!Element} The value, likely to be a DOM Element when asserts are301* enabled.302* @throws {goog.asserts.AssertionError} When the value is not an Element.303*/304goog.asserts.assertElement = function(value, opt_message, var_args) {305if (goog.asserts.ENABLE_ASSERTS &&306(!goog.isObject(value) || value.nodeType != goog.dom.NodeType.ELEMENT)) {307goog.asserts.doAssertFailure_(308'Expected Element but got %s: %s.', [goog.typeOf(value), value],309opt_message, Array.prototype.slice.call(arguments, 2));310}311return /** @type {!Element} */ (value);312};313314315/**316* Checks if the value is an instance of the user-defined type if317* goog.asserts.ENABLE_ASSERTS is true.318*319* The compiler may tighten the type returned by this function.320*321* @param {?} value The value to check.322* @param {function(new: T, ...)} type A user-defined constructor.323* @param {string=} opt_message Error message in case of failure.324* @param {...*} var_args The items to substitute into the failure message.325* @throws {goog.asserts.AssertionError} When the value is not an instance of326* type.327* @return {T}328* @template T329*/330goog.asserts.assertInstanceof = function(value, type, opt_message, var_args) {331if (goog.asserts.ENABLE_ASSERTS && !(value instanceof type)) {332goog.asserts.doAssertFailure_(333'Expected instanceof %s but got %s.',334[goog.asserts.getType_(type), goog.asserts.getType_(value)],335opt_message, Array.prototype.slice.call(arguments, 3));336}337return value;338};339340341/**342* Checks that no enumerable keys are present in Object.prototype. Such keys343* would break most code that use {@code for (var ... in ...)} loops.344*/345goog.asserts.assertObjectPrototypeIsIntact = function() {346for (var key in Object.prototype) {347goog.asserts.fail(key + ' should not be enumerable in Object.prototype.');348}349};350351352/**353* Returns the type of a value. If a constructor is passed, and a suitable354* string cannot be found, 'unknown type name' will be returned.355* @param {*} value A constructor, object, or primitive.356* @return {string} The best display name for the value, or 'unknown type name'.357* @private358*/359goog.asserts.getType_ = function(value) {360if (value instanceof Function) {361return value.displayName || value.name || 'unknown type name';362} else if (value instanceof Object) {363return value.constructor.displayName || value.constructor.name ||364Object.prototype.toString.call(value);365} else {366return value === null ? 'null' : typeof value;367}368};369370371