fast-path.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. FPp.valueIsDuplicate = function () {
  56. var s = this.stack;
  57. var valueIndex = s.length - 1;
  58. return s.lastIndexOf(s[valueIndex], valueIndex - 1) >= 0;
  59. };
  60. function getNodeHelper(path, count) {
  61. var s = path.stack;
  62. for (var i = s.length - 1; i >= 0; i -= 2) {
  63. var value = s[i];
  64. if (n.Node.check(value) && --count < 0) {
  65. return value;
  66. }
  67. }
  68. return null;
  69. }
  70. FPp.getNode = function getNode(count) {
  71. return getNodeHelper(this, ~~count);
  72. };
  73. FPp.getParentNode = function getParentNode(count) {
  74. return getNodeHelper(this, ~~count + 1);
  75. };
  76. // The length of the stack can be either even or odd, depending on whether
  77. // or not we have a name for the root value. The difference between the
  78. // index of the root value and the index of the final value is always
  79. // even, though, which allows us to return the root value in constant time
  80. // (i.e. without iterating backwards through the stack).
  81. FPp.getRootValue = function getRootValue() {
  82. var s = this.stack;
  83. if (s.length % 2 === 0) {
  84. return s[1];
  85. }
  86. return s[0];
  87. };
  88. // Temporarily push properties named by string arguments given after the
  89. // callback function onto this.stack, then call the callback with a
  90. // reference to this (modified) FastPath object. Note that the stack will
  91. // be restored to its original state after the callback is finished, so it
  92. // is probably a mistake to retain a reference to the path.
  93. FPp.call = function call(callback/*, name1, name2, ... */) {
  94. var s = this.stack;
  95. var origLen = s.length;
  96. var value = s[origLen - 1];
  97. var argc = arguments.length;
  98. for (var i = 1; i < argc; ++i) {
  99. var name = arguments[i];
  100. value = value[name];
  101. s.push(name, value);
  102. }
  103. var result = callback(this);
  104. s.length = origLen;
  105. return result;
  106. };
  107. // Similar to FastPath.prototype.call, except that the value obtained by
  108. // accessing this.getValue()[name1][name2]... should be array-like. The
  109. // callback will be called with a reference to this path object for each
  110. // element of the array.
  111. FPp.each = function each(callback/*, name1, name2, ... */) {
  112. var s = this.stack;
  113. var origLen = s.length;
  114. var value = s[origLen - 1];
  115. var argc = arguments.length;
  116. for (var i = 1; i < argc; ++i) {
  117. var name = arguments[i];
  118. value = value[name];
  119. s.push(name, value);
  120. }
  121. for (var i = 0; i < value.length; ++i) {
  122. if (i in value) {
  123. s.push(i, value[i]);
  124. // If the callback needs to know the value of i, call
  125. // path.getName(), assuming path is the parameter name.
  126. callback(this);
  127. s.length -= 2;
  128. }
  129. }
  130. s.length = origLen;
  131. };
  132. // Similar to FastPath.prototype.each, except that the results of the
  133. // callback function invocations are stored in an array and returned at
  134. // the end of the iteration.
  135. FPp.map = function map(callback/*, name1, name2, ... */) {
  136. var s = this.stack;
  137. var origLen = s.length;
  138. var value = s[origLen - 1];
  139. var argc = arguments.length;
  140. for (var i = 1; i < argc; ++i) {
  141. var name = arguments[i];
  142. value = value[name];
  143. s.push(name, value);
  144. }
  145. var result = new Array(value.length);
  146. for (var i = 0; i < value.length; ++i) {
  147. if (i in value) {
  148. s.push(i, value[i]);
  149. result[i] = callback(this, i);
  150. s.length -= 2;
  151. }
  152. }
  153. s.length = origLen;
  154. return result;
  155. };
  156. function expressionStartsWithCurlyBrace(node) {
  157. // TODO detect when node is already wrapped in parentheses to avoid (admittedly harmless) wrapping in extra parentheses.
  158. if(node == null) return false;
  159. switch(node.type) {
  160. // expressions guaranteed to start with a {
  161. case "ObjectExpression":
  162. case "ObjectPattern":
  163. return true;
  164. // All expressions that comprise nested expressions
  165. case "BinaryExpression":
  166. case "AssignmentExpression":
  167. case "LogicalExpression":
  168. return expressionStartsWithCurlyBrace(node.left);
  169. case "MemberExpression":
  170. case "BindExpression":
  171. return expressionStartsWithCurlyBrace(node.object);
  172. case "CallExpression":
  173. return expressionStartsWithCurlyBrace(node.callee);
  174. case "UpdateExpression":
  175. case "UnaryExpression":
  176. return node.prefix === false && expressionStartsWithCurlyBrace(node.argument);
  177. case "TSNonNullExpression":
  178. return expressionStartsWithCurlyBrace(node.expression);
  179. case "ConditionalExpression":
  180. return expressionStartsWithCurlyBrace(node.test);
  181. case "SequenceExpression":
  182. return expressionStartsWithCurlyBrace(node.expressions[0]);
  183. case "TaggedTemplateExpression":
  184. return expressionStartsWithCurlyBrace(node.tag);
  185. default:
  186. false;
  187. }
  188. }
  189. // Inspired by require("ast-types").NodePath.prototype.needsParens, but
  190. // more efficient because we're iterating backwards through a stack.
  191. FPp.needsParens = function(assumeExpressionContext) {
  192. var node = this.getNode();
  193. // This needs to come before `if (!parent) { return false }` because
  194. // an object destructuring assignment requires parens for
  195. // correctness even when it's the topmost expression.
  196. if (node.type === "AssignmentExpression" && node.left.type === 'ObjectPattern') {
  197. return true;
  198. }
  199. var parent = this.getParentNode();
  200. if (!parent) {
  201. return false;
  202. }
  203. var name = this.getName();
  204. // If the value of this path is some child of a Node and not a Node
  205. // itself, then it doesn't need parentheses. Only Node objects (in fact,
  206. // only Expression nodes) need parentheses.
  207. if (this.getValue() !== node) {
  208. return false;
  209. }
  210. // Only statements don't need parentheses.
  211. if (n.Statement.check(node)) {
  212. return false;
  213. }
  214. // Identifiers never need parentheses.
  215. if (node.type === "Identifier") {
  216. return false;
  217. }
  218. if (parent.type === "ParenthesizedExpression") {
  219. return false;
  220. }
  221. if (parent.type === "ArrowFunctionExpression" && name === "body") {
  222. return expressionStartsWithCurlyBrace(node);
  223. }
  224. switch (node.type) {
  225. case "UnaryExpression":
  226. case "SpreadElement":
  227. case "SpreadProperty":
  228. return parent.type === "MemberExpression"
  229. && name === "object"
  230. && parent.object === node;
  231. case "BinaryExpression":
  232. case "LogicalExpression":
  233. switch (parent.type) {
  234. case "CallExpression":
  235. return name === "callee"
  236. && parent.callee === node;
  237. case "UnaryExpression":
  238. case "SpreadElement":
  239. case "SpreadProperty":
  240. return true;
  241. case "MemberExpression":
  242. return name === "object"
  243. && parent.object === node;
  244. case "BinaryExpression":
  245. case "LogicalExpression":
  246. var po = parent.operator;
  247. var pp = PRECEDENCE[po];
  248. var no = node.operator;
  249. var np = PRECEDENCE[no];
  250. if (pp > np) {
  251. return true;
  252. }
  253. if (pp === np && name === "right") {
  254. assert.strictEqual(parent.right, node);
  255. return true;
  256. }
  257. default:
  258. return false;
  259. }
  260. case "SequenceExpression":
  261. switch (parent.type) {
  262. case "ReturnStatement":
  263. return false;
  264. case "ForStatement":
  265. // Although parentheses wouldn't hurt around sequence expressions in
  266. // the head of for loops, traditional style dictates that e.g. i++,
  267. // j++ should not be wrapped with parentheses.
  268. return false;
  269. case "ExpressionStatement":
  270. return name !== "expression";
  271. default:
  272. // Otherwise err on the side of overparenthesization, adding
  273. // explicit exceptions above if this proves overzealous.
  274. return true;
  275. }
  276. case "YieldExpression":
  277. switch (parent.type) {
  278. case "BinaryExpression":
  279. case "LogicalExpression":
  280. case "UnaryExpression":
  281. case "SpreadElement":
  282. case "SpreadProperty":
  283. case "CallExpression":
  284. case "MemberExpression":
  285. case "NewExpression":
  286. case "ConditionalExpression":
  287. case "YieldExpression":
  288. return true;
  289. default:
  290. return false;
  291. }
  292. case "IntersectionTypeAnnotation":
  293. case "UnionTypeAnnotation":
  294. return parent.type === "NullableTypeAnnotation";
  295. case "Literal":
  296. return parent.type === "MemberExpression"
  297. && isNumber.check(node.value)
  298. && name === "object"
  299. && parent.object === node;
  300. // Babel 6 Literal split
  301. case "NumericLiteral":
  302. return parent.type === "MemberExpression"
  303. && name === "object"
  304. && parent.object === node;
  305. case "AssignmentExpression":
  306. case "ConditionalExpression":
  307. switch (parent.type) {
  308. case "UnaryExpression":
  309. case "SpreadElement":
  310. case "SpreadProperty":
  311. case "BinaryExpression":
  312. case "LogicalExpression":
  313. return true;
  314. case "CallExpression":
  315. return name === "callee"
  316. && parent.callee === node;
  317. case "ConditionalExpression":
  318. return name === "test"
  319. && parent.test === node;
  320. case "MemberExpression":
  321. return name === "object"
  322. && parent.object === node;
  323. default:
  324. return false;
  325. }
  326. case "ArrowFunctionExpression":
  327. if(n.CallExpression.check(parent) && name === 'callee') {
  328. return true;
  329. }
  330. if(n.MemberExpression.check(parent) && name === 'object') {
  331. return true;
  332. }
  333. return isBinary(parent);
  334. case "ObjectExpression":
  335. if (parent.type === "ArrowFunctionExpression" &&
  336. name === "body") {
  337. return true;
  338. }
  339. break;
  340. case "CallExpression":
  341. if (name === "declaration" &&
  342. n.ExportDefaultDeclaration.check(parent) &&
  343. n.FunctionExpression.check(node.callee)) {
  344. return true;
  345. }
  346. }
  347. if (parent.type === "NewExpression" &&
  348. name === "callee" &&
  349. parent.callee === node) {
  350. return containsCallExpression(node);
  351. }
  352. if (assumeExpressionContext !== true &&
  353. !this.canBeFirstInStatement() &&
  354. this.firstInStatement()) {
  355. return true;
  356. }
  357. return false;
  358. };
  359. function isBinary(node) {
  360. return n.BinaryExpression.check(node)
  361. || n.LogicalExpression.check(node);
  362. }
  363. function isUnaryLike(node) {
  364. return n.UnaryExpression.check(node)
  365. // I considered making SpreadElement and SpreadProperty subtypes of
  366. // UnaryExpression, but they're not really Expression nodes.
  367. || (n.SpreadElement && n.SpreadElement.check(node))
  368. || (n.SpreadProperty && n.SpreadProperty.check(node));
  369. }
  370. var PRECEDENCE = {};
  371. [["||"],
  372. ["&&"],
  373. ["|"],
  374. ["^"],
  375. ["&"],
  376. ["==", "===", "!=", "!=="],
  377. ["<", ">", "<=", ">=", "in", "instanceof"],
  378. [">>", "<<", ">>>"],
  379. ["+", "-"],
  380. ["*", "/", "%", "**"]
  381. ].forEach(function(tier, i) {
  382. tier.forEach(function(op) {
  383. PRECEDENCE[op] = i;
  384. });
  385. });
  386. function containsCallExpression(node) {
  387. if (n.CallExpression.check(node)) {
  388. return true;
  389. }
  390. if (isArray.check(node)) {
  391. return node.some(containsCallExpression);
  392. }
  393. if (n.Node.check(node)) {
  394. return types.someField(node, function(name, child) {
  395. return containsCallExpression(child);
  396. });
  397. }
  398. return false;
  399. }
  400. FPp.canBeFirstInStatement = function() {
  401. var node = this.getNode();
  402. if (n.FunctionExpression.check(node)) {
  403. return false;
  404. }
  405. if (n.ObjectExpression.check(node)) {
  406. return false;
  407. }
  408. if (n.ClassExpression.check(node)) {
  409. return false;
  410. }
  411. return true;
  412. };
  413. FPp.firstInStatement = function() {
  414. var s = this.stack;
  415. var parentName, parent;
  416. var childName, child;
  417. for (var i = s.length - 1; i >= 0; i -= 2) {
  418. if (n.Node.check(s[i])) {
  419. childName = parentName;
  420. child = parent;
  421. parentName = s[i - 1];
  422. parent = s[i];
  423. }
  424. if (!parent || !child) {
  425. continue;
  426. }
  427. if (n.BlockStatement.check(parent) &&
  428. parentName === "body" &&
  429. childName === 0) {
  430. assert.strictEqual(parent.body[0], child);
  431. return true;
  432. }
  433. if (n.ExpressionStatement.check(parent) &&
  434. childName === "expression") {
  435. assert.strictEqual(parent.expression, child);
  436. return true;
  437. }
  438. if (n.SequenceExpression.check(parent) &&
  439. parentName === "expressions" &&
  440. childName === 0) {
  441. assert.strictEqual(parent.expressions[0], child);
  442. continue;
  443. }
  444. if (n.CallExpression.check(parent) &&
  445. childName === "callee") {
  446. assert.strictEqual(parent.callee, child);
  447. continue;
  448. }
  449. if (n.MemberExpression.check(parent) &&
  450. childName === "object") {
  451. assert.strictEqual(parent.object, child);
  452. continue;
  453. }
  454. if (n.ConditionalExpression.check(parent) &&
  455. childName === "test") {
  456. assert.strictEqual(parent.test, child);
  457. continue;
  458. }
  459. if (isBinary(parent) &&
  460. childName === "left") {
  461. assert.strictEqual(parent.left, child);
  462. continue;
  463. }
  464. if (n.UnaryExpression.check(parent) &&
  465. !parent.prefix &&
  466. childName === "argument") {
  467. assert.strictEqual(parent.argument, child);
  468. continue;
  469. }
  470. return false;
  471. }
  472. return true;
  473. };