# 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 at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // 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 and
13 | // limitations under the License.
14 |
15 | /**
16 | * @fileoverview Utilities to check the preconditions, postconditions and
17 | * invariants runtime.
18 | *
19 | * Methods in this package should be given special treatment by the compiler
20 | * 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 | * @author agrieve@google.com (Andrew Grieve)
35 | */
36 |
37 | goog.provide('goog.asserts');
38 | goog.provide('goog.asserts.AssertionError');
39 |
40 | goog.require('goog.debug.Error');
41 | goog.require('goog.dom.NodeType');
42 | goog.require('goog.string');
43 |
44 |
45 | /**
46 | * @define {boolean} Whether to strip out asserts or to leave them in.
47 | */
48 | goog.define('goog.asserts.ENABLE_ASSERTS', goog.DEBUG);
49 |
50 |
51 |
52 | /**
53 | * Error object for failed assertions.
54 | * @param {string} messagePattern The pattern that was used to form message.
55 | * @param {!Array<*>} messageArgs The items to substitute into the pattern.
56 | * @constructor
57 | * @extends {goog.debug.Error}
58 | * @final
59 | */
60 | goog.asserts.AssertionError = function(messagePattern, messageArgs) {
61 | messageArgs.unshift(messagePattern);
62 | goog.debug.Error.call(this, goog.string.subs.apply(null, messageArgs));
63 | // Remove the messagePattern afterwards to avoid permenantly modifying the
64 | // passed in array.
65 | messageArgs.shift();
66 |
67 | /**
68 | * The message pattern used to format the error message. Error handlers can
69 | * use this to uniquely identify the assertion.
70 | * @type {string}
71 | */
72 | this.messagePattern = messagePattern;
73 | };
74 | goog.inherits(goog.asserts.AssertionError, goog.debug.Error);
75 |
76 |
77 | /** @override */
78 | goog.asserts.AssertionError.prototype.name = 'AssertionError';
79 |
80 |
81 | /**
82 | * The default error handler.
83 | * @param {!goog.asserts.AssertionError} e The exception to be handled.
84 | */
85 | goog.asserts.DEFAULT_ERROR_HANDLER = function(e) { throw e; };
86 |
87 |
88 | /**
89 | * The handler responsible for throwing or logging assertion errors.
90 | * @private {function(!goog.asserts.AssertionError)}
91 | */
92 | goog.asserts.errorHandler_ = goog.asserts.DEFAULT_ERROR_HANDLER;
93 |
94 |
95 | /**
96 | * Throws an exception with the given message and "Assertion failed" prefixed
97 | * onto it.
98 | * @param {string} defaultMessage The message to use if givenMessage is empty.
99 | * @param {Array<*>} defaultArgs The substitution arguments for defaultMessage.
100 | * @param {string|undefined} givenMessage Message supplied by the caller.
101 | * @param {Array<*>} givenArgs The substitution arguments for givenMessage.
102 | * @throws {goog.asserts.AssertionError} When the value is not a number.
103 | * @private
104 | */
105 | goog.asserts.doAssertFailure_ =
106 | function(defaultMessage, defaultArgs, givenMessage, givenArgs) {
107 | var message = 'Assertion failed';
108 | if (givenMessage) {
109 | message += ': ' + givenMessage;
110 | var args = givenArgs;
111 | } else if (defaultMessage) {
112 | message += ': ' + defaultMessage;
113 | args = defaultArgs;
114 | }
115 | // The '' + works around an Opera 10 bug in the unit tests. Without it,
116 | // a stack trace is added to var message above. With this, a stack trace is
117 | // not added until this line (it causes the extra garbage to be added after
118 | // the assertion message instead of in the middle of it).
119 | var e = new goog.asserts.AssertionError('' + message, args || []);
120 | goog.asserts.errorHandler_(e);
121 | };
122 |
123 |
124 | /**
125 | * Sets a custom error handler that can be used to customize the behavior of
126 | * assertion failures, for example by turning all assertion failures into log
127 | * messages.
128 | * @param {function(goog.asserts.AssertionError)} errorHandler
129 | */
130 | goog.asserts.setErrorHandler = function(errorHandler) {
131 | if (goog.asserts.ENABLE_ASSERTS) {
132 | goog.asserts.errorHandler_ = errorHandler;
133 | }
134 | };
135 |
136 |
137 | /**
138 | * Checks if the condition evaluates to true if goog.asserts.ENABLE_ASSERTS is
139 | * true.
140 | * @template T
141 | * @param {T} condition The condition to check.
142 | * @param {string=} opt_message Error message in case of failure.
143 | * @param {...*} var_args The items to substitute into the failure message.
144 | * @return {!T} The value of the condition.
145 | * @throws {goog.asserts.AssertionError} When the condition evaluates to false.
146 | */
147 | goog.asserts.assert = function(condition, opt_message, var_args) {
148 | if (goog.asserts.ENABLE_ASSERTS && !condition) {
149 | goog.asserts.doAssertFailure_('', null, opt_message,
150 | Array.prototype.slice.call(arguments, 2));
151 | }
152 | return condition;
153 | };
154 |
155 |
156 | /**
157 | * Fails if goog.asserts.ENABLE_ASSERTS is true. This function is useful in case
158 | * when we want to add a check in the unreachable area like switch-case
159 | * statement:
160 | *
161 | * <pre>
162 | * switch(type) {
163 | * case FOO: doSomething(); break;
164 | * case BAR: doSomethingElse(); break;
165 | * default: goog.assert.fail('Unrecognized type: ' + type);
166 | * // We have only 2 types - "default:" section is unreachable code.
167 | * }
168 | * </pre>
169 | *
170 | * @param {string=} opt_message Error message in case of failure.
171 | * @param {...*} var_args The items to substitute into the failure message.
172 | * @throws {goog.asserts.AssertionError} Failure.
173 | */
174 | goog.asserts.fail = function(opt_message, var_args) {
175 | if (goog.asserts.ENABLE_ASSERTS) {
176 | goog.asserts.errorHandler_(new goog.asserts.AssertionError(
177 | 'Failure' + (opt_message ? ': ' + opt_message : ''),
178 | Array.prototype.slice.call(arguments, 1)));
179 | }
180 | };
181 |
182 |
183 | /**
184 | * Checks if the value is a number if goog.asserts.ENABLE_ASSERTS is true.
185 | * @param {*} value The value to check.
186 | * @param {string=} opt_message Error message in case of failure.
187 | * @param {...*} var_args The items to substitute into the failure message.
188 | * @return {number} The value, guaranteed to be a number when asserts enabled.
189 | * @throws {goog.asserts.AssertionError} When the value is not a number.
190 | */
191 | goog.asserts.assertNumber = function(value, opt_message, var_args) {
192 | if (goog.asserts.ENABLE_ASSERTS && !goog.isNumber(value)) {
193 | goog.asserts.doAssertFailure_('Expected number but got %s: %s.',
194 | [goog.typeOf(value), value], opt_message,
195 | Array.prototype.slice.call(arguments, 2));
196 | }
197 | return /** @type {number} */ (value);
198 | };
199 |
200 |
201 | /**
202 | * Checks if the value is a string if goog.asserts.ENABLE_ASSERTS is true.
203 | * @param {*} value The value to check.
204 | * @param {string=} opt_message Error message in case of failure.
205 | * @param {...*} var_args The items to substitute into the failure message.
206 | * @return {string} The value, guaranteed to be a string when asserts enabled.
207 | * @throws {goog.asserts.AssertionError} When the value is not a string.
208 | */
209 | goog.asserts.assertString = function(value, opt_message, var_args) {
210 | if (goog.asserts.ENABLE_ASSERTS && !goog.isString(value)) {
211 | goog.asserts.doAssertFailure_('Expected string but got %s: %s.',
212 | [goog.typeOf(value), value], opt_message,
213 | Array.prototype.slice.call(arguments, 2));
214 | }
215 | return /** @type {string} */ (value);
216 | };
217 |
218 |
219 | /**
220 | * Checks if the value is a function if goog.asserts.ENABLE_ASSERTS is true.
221 | * @param {*} value The value to check.
222 | * @param {string=} opt_message Error message in case of failure.
223 | * @param {...*} var_args The items to substitute into the failure message.
224 | * @return {!Function} The value, guaranteed to be a function when asserts
225 | * enabled.
226 | * @throws {goog.asserts.AssertionError} When the value is not a function.
227 | */
228 | goog.asserts.assertFunction = function(value, opt_message, var_args) {
229 | if (goog.asserts.ENABLE_ASSERTS && !goog.isFunction(value)) {
230 | goog.asserts.doAssertFailure_('Expected function but got %s: %s.',
231 | [goog.typeOf(value), value], opt_message,
232 | Array.prototype.slice.call(arguments, 2));
233 | }
234 | return /** @type {!Function} */ (value);
235 | };
236 |
237 |
238 | /**
239 | * Checks if the value is an Object if goog.asserts.ENABLE_ASSERTS is true.
240 | * @param {*} value The value to check.
241 | * @param {string=} opt_message Error message in case of failure.
242 | * @param {...*} var_args The items to substitute into the failure message.
243 | * @return {!Object} The value, guaranteed to be a non-null object.
244 | * @throws {goog.asserts.AssertionError} When the value is not an object.
245 | */
246 | goog.asserts.assertObject = function(value, opt_message, var_args) {
247 | if (goog.asserts.ENABLE_ASSERTS && !goog.isObject(value)) {
248 | goog.asserts.doAssertFailure_('Expected object but got %s: %s.',
249 | [goog.typeOf(value), value],
250 | opt_message, Array.prototype.slice.call(arguments, 2));
251 | }
252 | return /** @type {!Object} */ (value);
253 | };
254 |
255 |
256 | /**
257 | * Checks if the value is an Array if goog.asserts.ENABLE_ASSERTS is true.
258 | * @param {*} value The value to check.
259 | * @param {string=} opt_message Error message in case of failure.
260 | * @param {...*} var_args The items to substitute into the failure message.
261 | * @return {!Array<?>} The value, guaranteed to be a non-null array.
262 | * @throws {goog.asserts.AssertionError} When the value is not an array.
263 | */
264 | goog.asserts.assertArray = function(value, opt_message, var_args) {
265 | if (goog.asserts.ENABLE_ASSERTS && !goog.isArray(value)) {
266 | goog.asserts.doAssertFailure_('Expected array but got %s: %s.',
267 | [goog.typeOf(value), value], opt_message,
268 | Array.prototype.slice.call(arguments, 2));
269 | }
270 | return /** @type {!Array<?>} */ (value);
271 | };
272 |
273 |
274 | /**
275 | * Checks if the value is a boolean if goog.asserts.ENABLE_ASSERTS is true.
276 | * @param {*} value The value to check.
277 | * @param {string=} opt_message Error message in case of failure.
278 | * @param {...*} var_args The items to substitute into the failure message.
279 | * @return {boolean} The value, guaranteed to be a boolean when asserts are
280 | * enabled.
281 | * @throws {goog.asserts.AssertionError} When the value is not a boolean.
282 | */
283 | goog.asserts.assertBoolean = function(value, opt_message, var_args) {
284 | if (goog.asserts.ENABLE_ASSERTS && !goog.isBoolean(value)) {
285 | goog.asserts.doAssertFailure_('Expected boolean but got %s: %s.',
286 | [goog.typeOf(value), value], opt_message,
287 | Array.prototype.slice.call(arguments, 2));
288 | }
289 | return /** @type {boolean} */ (value);
290 | };
291 |
292 |
293 | /**
294 | * Checks if the value is a DOM Element if goog.asserts.ENABLE_ASSERTS is true.
295 | * @param {*} value The value to check.
296 | * @param {string=} opt_message Error message in case of failure.
297 | * @param {...*} var_args The items to substitute into the failure message.
298 | * @return {!Element} The value, likely to be a DOM Element when asserts are
299 | * enabled.
300 | * @throws {goog.asserts.AssertionError} When the value is not a boolean.
301 | */
302 | goog.asserts.assertElement = function(value, opt_message, var_args) {
303 | if (goog.asserts.ENABLE_ASSERTS && (!goog.isObject(value) ||
304 | value.nodeType != goog.dom.NodeType.ELEMENT)) {
305 | goog.asserts.doAssertFailure_('Expected Element but got %s: %s.',
306 | [goog.typeOf(value), value], opt_message,
307 | Array.prototype.slice.call(arguments, 2));
308 | }
309 | return /** @type {!Element} */ (value);
310 | };
311 |
312 |
313 | /**
314 | * Checks if the value is an instance of the user-defined type if
315 | * goog.asserts.ENABLE_ASSERTS is true.
316 | *
317 | * The compiler may tighten the type returned by this function.
318 | *
319 | * @param {*} value The value to check.
320 | * @param {function(new: T, ...)} type A user-defined constructor.
321 | * @param {string=} opt_message Error message in case of failure.
322 | * @param {...*} var_args The items to substitute into the failure message.
323 | * @throws {goog.asserts.AssertionError} When the value is not an instance of
324 | * type.
325 | * @return {!T}
326 | * @template T
327 | */
328 | goog.asserts.assertInstanceof = function(value, type, opt_message, var_args) {
329 | if (goog.asserts.ENABLE_ASSERTS && !(value instanceof type)) {
330 | goog.asserts.doAssertFailure_('Expected instanceof %s but got %s.',
331 | [goog.asserts.getType_(type), goog.asserts.getType_(value)],
332 | opt_message, Array.prototype.slice.call(arguments, 3));
333 | }
334 | return value;
335 | };
336 |
337 |
338 | /**
339 | * Checks that no enumerable keys are present in Object.prototype. Such keys
340 | * would break most code that use {@code for (var ... in ...)} loops.
341 | */
342 | goog.asserts.assertObjectPrototypeIsIntact = function() {
343 | for (var key in Object.prototype) {
344 | goog.asserts.fail(key + ' should not be enumerable in Object.prototype.');
345 | }
346 | };
347 |
348 |
349 | /**
350 | * Returns the type of a value. If a constructor is passed, and a suitable
351 | * string cannot be found, 'unknown type name' will be returned.
352 | * @param {*} value A constructor, object, or primitive.
353 | * @return {string} The best display name for the value, or 'unknown type name'.
354 | * @private
355 | */
356 | goog.asserts.getType_ = function(value) {
357 | if (value instanceof Function) {
358 | return value.displayName || value.name || 'unknown type name';
359 | } else if (value instanceof Object) {
360 | return value.constructor.displayName || value.constructor.name ||
361 | Object.prototype.toString.call(value);
362 | } else {
363 | return value === null ? 'null' : typeof value;
364 | }
365 | };