util.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /**
  2. * Copyright (c) 2014, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * https://raw.github.com/facebook/regenerator/master/LICENSE file. An
  7. * additional grant of patent rights can be found in the PATENTS file in
  8. * the same directory.
  9. */
  10. var assert = require("assert");
  11. var types = require("ast-types");
  12. var n = types.namedTypes;
  13. var b = types.builders;
  14. var hasOwn = Object.prototype.hasOwnProperty;
  15. exports.defaults = function(obj) {
  16. var len = arguments.length;
  17. var extension;
  18. for (var i = 1; i < len; ++i) {
  19. if ((extension = arguments[i])) {
  20. for (var key in extension) {
  21. if (hasOwn.call(extension, key) && !hasOwn.call(obj, key)) {
  22. obj[key] = extension[key];
  23. }
  24. }
  25. }
  26. }
  27. return obj;
  28. };
  29. exports.runtimeProperty = function(name) {
  30. return b.memberExpression(
  31. b.identifier("regeneratorRuntime"),
  32. b.identifier(name),
  33. false
  34. );
  35. };
  36. // Inspired by the isReference function from ast-util:
  37. // https://github.com/eventualbuddha/ast-util/blob/9bf91c5ce8/lib/index.js#L466-L506
  38. exports.isReference = function(path, name) {
  39. var node = path.value;
  40. if (!n.Identifier.check(node)) {
  41. return false;
  42. }
  43. if (name && node.name !== name) {
  44. return false;
  45. }
  46. var parent = path.parent.value;
  47. switch (parent.type) {
  48. case "VariableDeclarator":
  49. return path.name === "init";
  50. case "MemberExpression":
  51. return path.name === "object" || (
  52. parent.computed && path.name === "property"
  53. );
  54. case "FunctionExpression":
  55. case "FunctionDeclaration":
  56. case "ArrowFunctionExpression":
  57. if (path.name === "id") {
  58. return false;
  59. }
  60. if (parent.params === path.parentPath &&
  61. parent.params[path.name] === node) {
  62. return false;
  63. }
  64. return true;
  65. case "ClassDeclaration":
  66. case "ClassExpression":
  67. return path.name !== "id";
  68. case "CatchClause":
  69. return path.name !== "param";
  70. case "Property":
  71. case "MethodDefinition":
  72. return path.name !== "key";
  73. case "ImportSpecifier":
  74. case "ImportDefaultSpecifier":
  75. case "ImportNamespaceSpecifier":
  76. case "LabeledStatement":
  77. return false;
  78. default:
  79. return true;
  80. }
  81. };