asserts.js 13 KB

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