fast-path.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. var assert = require("assert");
  2. var types = require("./types");
  3. var n = types.namedTypes;
  4. var Node = n.Node;
  5. var isArray = types.builtInTypes.array;
  6. var isNumber = types.builtInTypes.number;
  7. function FastPath(value) {
  8. assert.ok(this instanceof FastPath);
  9. this.stack = [value];
  10. }
  11. var FPp = FastPath.prototype;
  12. module.exports = FastPath;
  13. // Static convenience function for coercing a value to a FastPath.
  14. FastPath.from = function(obj) {
  15. if (obj instanceof FastPath) {
  16. // Return a defensive copy of any existing FastPath instances.
  17. return obj.copy();
  18. }
  19. if (obj instanceof types.NodePath) {
  20. // For backwards compatibility, unroll NodePath instances into
  21. // lightweight FastPath [..., name, value] stacks.
  22. var copy = Object.create(FastPath.prototype);
  23. var stack = [obj.value];
  24. for (var pp; (pp = obj.parentPath); obj = pp)
  25. stack.push(obj.name, pp.value);
  26. copy.stack = stack.reverse();
  27. return copy;
  28. }
  29. // Otherwise use obj as the value of the new FastPath instance.
  30. return new FastPath(obj);
  31. };
  32. FPp.copy = function copy() {
  33. var copy = Object.create(FastPath.prototype);
  34. copy.stack = this.stack.slice(0);
  35. return copy;
  36. };
  37. // The name of the current property is always the penultimate element of
  38. // this.stack, and always a String.
  39. FPp.getName = function getName() {
  40. var s = this.stack;
  41. var len = s.length;
  42. if (len > 1) {
  43. return s[len - 2];
  44. }
  45. // Since the name is always a string, null is a safe sentinel value to
  46. // return if we do not know the name of the (root) value.
  47. return null;
  48. };
  49. // The value of the current property is always the final element of
  50. // this.stack.
  51. FPp.getValue = function getValue() {
  52. var s = this.stack;
  53. return s[s.length - 1];
  54. };
  55. function getNodeHelper(path, count) {
  56. var s = path.stack;
  57. for (var i = s.length - 1; i >= 0; i -= 2) {
  58. var value = s[i];
  59. if (n.Node.check(value) && --count < 0) {
  60. return value;
  61. }
  62. }
  63. return null;
  64. }
  65. FPp.getNode = function getNode(count) {
  66. return getNodeHelper(this, ~~count);
  67. };
  68. FPp.getParentNode = function getParentNode(count) {
  69. return getNodeHelper(this, ~~count + 1);
  70. };
  71. // The length of the stack can be either even or odd, depending on whether
  72. // or not we have a name for the root value. The difference between the
  73. // index of the root value and the index of the final value is always
  74. // even, though, which allows us to return the root value in constant time
  75. // (i.e. without iterating backwards through the stack).
  76. FPp.getRootValue = function getRootValue() {
  77. var s = this.stack;
  78. if (s.length % 2 === 0) {
  79. return s[1];
  80. }
  81. return s[0];
  82. };
  83. // Temporarily push properties named by string arguments given after the
  84. // callback function onto this.stack, then call the callback with a
  85. // reference to this (modified) FastPath object. Note that the stack will
  86. // be restored to its original state after the callback is finished, so it
  87. // is probably a mistake to retain a reference to the path.
  88. FPp.call = function call(callback/*, name1, name2, ... */) {
  89. var s = this.stack;
  90. var origLen = s.length;
  91. var value = s[origLen - 1];
  92. var argc = arguments.length;
  93. for (var i = 1; i < argc; ++i) {
  94. var name = arguments[i];
  95. value = value[name];
  96. s.push(name, value);
  97. }
  98. var result = callback(this);
  99. s.length = origLen;
  100. return result;
  101. };
  102. // Similar to FastPath.prototype.call, except that the value obtained by
  103. // accessing this.getValue()[name1][name2]... should be array-like. The
  104. // callback will be called with a reference to this path object for each
  105. // element of the array.
  106. FPp.each = function each(callback/*, name1, name2, ... */) {
  107. var s = this.stack;
  108. var origLen = s.length;
  109. var value = s[origLen - 1];
  110. var argc = arguments.length;
  111. for (var i = 1; i < argc; ++i) {
  112. var name = arguments[i];
  113. value = value[name];
  114. s.push(name, value);
  115. }
  116. for (var i = 0; i < value.length; ++i) {
  117. if (i in value) {
  118. s.push(i, value[i]);
  119. // If the callback needs to know the value of i, call
  120. // path.getName(), assuming path is the parameter name.
  121. callback(this);
  122. s.length -= 2;
  123. }
  124. }
  125. s.length = origLen;
  126. };
  127. // Similar to FastPath.prototype.each, except that the results of the
  128. // callback function invocations are stored in an array and returned at
  129. // the end of the iteration.
  130. FPp.map = function map(callback/*, name1, name2, ... */) {
  131. var s = this.stack;
  132. var origLen = s.length;
  133. var value = s[origLen - 1];
  134. var argc = arguments.length;
  135. for (var i = 1; i < argc; ++i) {
  136. var name = arguments[i];
  137. value = value[name];
  138. s.push(name, value);
  139. }
  140. var result = new Array(value.length);
  141. for (var i = 0; i < value.length; ++i) {
  142. if (i in value) {
  143. s.push(i, value[i]);
  144. result[i] = callback(this, i);
  145. s.length -= 2;
  146. }
  147. }
  148. s.length = origLen;
  149. return result;
  150. };
  151. // Inspired by require("ast-types").NodePath.prototype.needsParens, but
  152. // more efficient because we're iterating backwards through a stack.
  153. FPp.needsParens = function(assumeExpressionContext) {
  154. var parent = this.getParentNode();
  155. if (!parent) {
  156. return false;
  157. }
  158. var name = this.getName();
  159. var node = this.getNode();
  160. // If the value of this path is some child of a Node and not a Node
  161. // itself, then it doesn't need parentheses. Only Node objects (in
  162. // fact, only Expression nodes) need parentheses.
  163. if (this.getValue() !== node) {
  164. return false;
  165. }
  166. // Only statements don't need parentheses.
  167. if (n.Statement.check(node)) {
  168. return false;
  169. }
  170. // Identifiers never need parentheses.
  171. if (node.type === "Identifier") {
  172. return false;
  173. }
  174. if (parent.type === "ParenthesizedExpression") {
  175. return false;
  176. }
  177. switch (node.type) {
  178. case "UnaryExpression":
  179. case "SpreadElement":
  180. case "SpreadProperty":
  181. return parent.type === "MemberExpression"
  182. && name === "object"
  183. && parent.object === node;
  184. case "BinaryExpression":
  185. case "LogicalExpression":
  186. switch (parent.type) {
  187. case "CallExpression":
  188. return name === "callee"
  189. && parent.callee === node;
  190. case "UnaryExpression":
  191. case "SpreadElement":
  192. case "SpreadProperty":
  193. return true;
  194. case "MemberExpression":
  195. return name === "object"
  196. && parent.object === node;
  197. case "BinaryExpression":
  198. case "LogicalExpression":
  199. var po = parent.operator;
  200. var pp = PRECEDENCE[po];
  201. var no = node.operator;
  202. var np = PRECEDENCE[no];
  203. if (pp > np) {
  204. return true;
  205. }
  206. if (pp === np && name === "right") {
  207. assert.strictEqual(parent.right, node);
  208. return true;
  209. }
  210. default:
  211. return false;
  212. }
  213. case "SequenceExpression":
  214. switch (parent.type) {
  215. case "ReturnStatement":
  216. return false;
  217. case "ForStatement":
  218. // Although parentheses wouldn't hurt around sequence
  219. // expressions in the head of for loops, traditional style
  220. // dictates that e.g. i++, j++ should not be wrapped with
  221. // parentheses.
  222. return false;
  223. case "ExpressionStatement":
  224. return name !== "expression";
  225. default:
  226. // Otherwise err on the side of overparenthesization, adding
  227. // explicit exceptions above if this proves overzealous.
  228. return true;
  229. }
  230. case "YieldExpression":
  231. switch (parent.type) {
  232. case "BinaryExpression":
  233. case "LogicalExpression":
  234. case "UnaryExpression":
  235. case "SpreadElement":
  236. case "SpreadProperty":
  237. case "CallExpression":
  238. case "MemberExpression":
  239. case "NewExpression":
  240. case "ConditionalExpression":
  241. case "YieldExpression":
  242. return true;
  243. default:
  244. return false;
  245. }
  246. case "IntersectionTypeAnnotation":
  247. case "UnionTypeAnnotation":
  248. return parent.type === "NullableTypeAnnotation";
  249. case "Literal":
  250. return parent.type === "MemberExpression"
  251. && isNumber.check(node.value)
  252. && name === "object"
  253. && parent.object === node;
  254. case "AssignmentExpression":
  255. case "ConditionalExpression":
  256. switch (parent.type) {
  257. case "UnaryExpression":
  258. case "SpreadElement":
  259. case "SpreadProperty":
  260. case "BinaryExpression":
  261. case "LogicalExpression":
  262. return true;
  263. case "CallExpression":
  264. return name === "callee"
  265. && parent.callee === node;
  266. case "ConditionalExpression":
  267. return name === "test"
  268. && parent.test === node;
  269. case "MemberExpression":
  270. return name === "object"
  271. && parent.object === node;
  272. default:
  273. return false;
  274. }
  275. case "ArrowFunctionExpression":
  276. if(n.CallExpression.check(parent) && name === 'callee') {
  277. return true;
  278. }
  279. if(n.MemberExpression.check(parent) && name === 'object') {
  280. return true;
  281. }
  282. return isBinary(parent);
  283. case "ObjectExpression":
  284. if (parent.type === "ArrowFunctionExpression" &&
  285. name === "body") {
  286. return true;
  287. }
  288. default:
  289. if (parent.type === "NewExpression" &&
  290. name === "callee" &&
  291. parent.callee === node) {
  292. return containsCallExpression(node);
  293. }
  294. }
  295. if (assumeExpressionContext !== true &&
  296. !this.canBeFirstInStatement() &&
  297. this.firstInStatement())
  298. return true;
  299. return false;
  300. };
  301. function isBinary(node) {
  302. return n.BinaryExpression.check(node)
  303. || n.LogicalExpression.check(node);
  304. }
  305. function isUnaryLike(node) {
  306. return n.UnaryExpression.check(node)
  307. // I considered making SpreadElement and SpreadProperty subtypes
  308. // of UnaryExpression, but they're not really Expression nodes.
  309. || (n.SpreadElement && n.SpreadElement.check(node))
  310. || (n.SpreadProperty && n.SpreadProperty.check(node));
  311. }
  312. var PRECEDENCE = {};
  313. [["||"],
  314. ["&&"],
  315. ["|"],
  316. ["^"],
  317. ["&"],
  318. ["==", "===", "!=", "!=="],
  319. ["<", ">", "<=", ">=", "in", "instanceof"],
  320. [">>", "<<", ">>>"],
  321. ["+", "-"],
  322. ["*", "/", "%", "**"]
  323. ].forEach(function(tier, i) {
  324. tier.forEach(function(op) {
  325. PRECEDENCE[op] = i;
  326. });
  327. });
  328. function containsCallExpression(node) {
  329. if (n.CallExpression.check(node)) {
  330. return true;
  331. }
  332. if (isArray.check(node)) {
  333. return node.some(containsCallExpression);
  334. }
  335. if (n.Node.check(node)) {
  336. return types.someField(node, function(name, child) {
  337. return containsCallExpression(child);
  338. });
  339. }
  340. return false;
  341. }
  342. FPp.canBeFirstInStatement = function() {
  343. var node = this.getNode();
  344. return !n.FunctionExpression.check(node)
  345. && !n.ObjectExpression.check(node);
  346. };
  347. FPp.firstInStatement = function() {
  348. var s = this.stack;
  349. var parentName, parent;
  350. var childName, child;
  351. for (var i = s.length - 1; i >= 0; i -= 2) {
  352. if (n.Node.check(s[i])) {
  353. childName = parentName;
  354. child = parent;
  355. parentName = s[i - 1];
  356. parent = s[i];
  357. }
  358. if (!parent || !child) {
  359. continue;
  360. }
  361. if (n.BlockStatement.check(parent) &&
  362. parentName === "body" &&
  363. childName === 0) {
  364. assert.strictEqual(parent.body[0], child);
  365. return true;
  366. }
  367. if (n.ExpressionStatement.check(parent) &&
  368. childName === "expression") {
  369. assert.strictEqual(parent.expression, child);
  370. return true;
  371. }
  372. if (n.SequenceExpression.check(parent) &&
  373. parentName === "expressions" &&
  374. childName === 0) {
  375. assert.strictEqual(parent.expressions[0], child);
  376. continue;
  377. }
  378. if (n.CallExpression.check(parent) &&
  379. childName === "callee") {
  380. assert.strictEqual(parent.callee, child);
  381. continue;
  382. }
  383. if (n.MemberExpression.check(parent) &&
  384. childName === "object") {
  385. assert.strictEqual(parent.object, child);
  386. continue;
  387. }
  388. if (n.ConditionalExpression.check(parent) &&
  389. childName === "test") {
  390. assert.strictEqual(parent.test, child);
  391. continue;
  392. }
  393. if (isBinary(parent) &&
  394. childName === "left") {
  395. assert.strictEqual(parent.left, child);
  396. continue;
  397. }
  398. if (n.UnaryExpression.check(parent) &&
  399. !parent.prefix &&
  400. childName === "argument") {
  401. assert.strictEqual(parent.argument, child);
  402. continue;
  403. }
  404. return false;
  405. }
  406. return true;
  407. };