OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 /** |
| 6 * @fileoverview Assertion support. |
| 7 */ |
| 8 |
| 9 /** |
| 10 * Verify |condition| is truthy and return |condition| if so. |
| 11 * @template T |
| 12 * @param {T} condition A condition to check for truthiness. Note that this |
| 13 * may be used to test whether a value is defined or not, and we don't want |
| 14 * to force a cast to Boolean. |
| 15 * @param {string=} opt_message A message to show on failure. |
| 16 * @return {T} A non-null |condition|. |
| 17 */ |
| 18 function assert(condition, opt_message) { |
| 19 if (!condition) { |
| 20 var message = 'Assertion failed'; |
| 21 if (opt_message) |
| 22 message = message + ': ' + opt_message; |
| 23 var error = new Error(message); |
| 24 var global = function() { return this; }(); |
| 25 if (global.traceAssertionsForTesting) |
| 26 console.warn(error.stack); |
| 27 throw error; |
| 28 } |
| 29 return condition; |
| 30 } |
| 31 |
| 32 /** |
| 33 * Call this from places in the code that should never be reached. |
| 34 * |
| 35 * For example, handling all the values of enum with a switch() like this: |
| 36 * |
| 37 * function getValueFromEnum(enum) { |
| 38 * switch (enum) { |
| 39 * case ENUM_FIRST_OF_TWO: |
| 40 * return first |
| 41 * case ENUM_LAST_OF_TWO: |
| 42 * return last; |
| 43 * } |
| 44 * assertNotReached(); |
| 45 * return document; |
| 46 * } |
| 47 * |
| 48 * This code should only be hit in the case of serious programmer error or |
| 49 * unexpected input. |
| 50 * |
| 51 * @param {string=} opt_message A message to show when this is hit. |
| 52 */ |
| 53 function assertNotReached(opt_message) { |
| 54 assert(false, opt_message || 'Unreachable code hit'); |
| 55 } |
| 56 |
| 57 /** |
| 58 * @param {*} value The value to check. |
| 59 * @param {function(new: T, ...)} type A user-defined constructor. |
| 60 * @param {string=} opt_message A message to show when this is hit. |
| 61 * @return {T} |
| 62 * @template T |
| 63 */ |
| 64 function assertInstanceof(value, type, opt_message) { |
| 65 // We don't use assert immediately here so that we avoid constructing an error |
| 66 // message if we don't have to. |
| 67 if (!(value instanceof type)) { |
| 68 assertNotReached(opt_message || 'Value ' + value + |
| 69 ' is not a[n] ' + (type.name || typeof type)); |
| 70 } |
| 71 return value; |
| 72 } |
| 73 |
OLD | NEW |