fast-path.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. var tslib_1 = require("tslib");
  4. var assert_1 = tslib_1.__importDefault(require("assert"));
  5. var types = tslib_1.__importStar(require("ast-types"));
  6. var util = tslib_1.__importStar(require("./util"));
  7. var n = types.namedTypes;
  8. var isArray = types.builtInTypes.array;
  9. var isNumber = types.builtInTypes.number;
  10. var PRECEDENCE = {};
  11. [
  12. ["??"],
  13. ["||"],
  14. ["&&"],
  15. ["|"],
  16. ["^"],
  17. ["&"],
  18. ["==", "===", "!=", "!=="],
  19. ["<", ">", "<=", ">=", "in", "instanceof"],
  20. [">>", "<<", ">>>"],
  21. ["+", "-"],
  22. ["*", "/", "%"],
  23. ["**"],
  24. ].forEach(function (tier, i) {
  25. tier.forEach(function (op) {
  26. PRECEDENCE[op] = i;
  27. });
  28. });
  29. var FastPath = function FastPath(value) {
  30. assert_1.default.ok(this instanceof FastPath);
  31. this.stack = [value];
  32. };
  33. var FPp = FastPath.prototype;
  34. // Static convenience function for coercing a value to a FastPath.
  35. FastPath.from = function (obj) {
  36. if (obj instanceof FastPath) {
  37. // Return a defensive copy of any existing FastPath instances.
  38. return obj.copy();
  39. }
  40. if (obj instanceof types.NodePath) {
  41. // For backwards compatibility, unroll NodePath instances into
  42. // lightweight FastPath [..., name, value] stacks.
  43. var copy = Object.create(FastPath.prototype);
  44. var stack = [obj.value];
  45. for (var pp = void 0; (pp = obj.parentPath); obj = pp)
  46. stack.push(obj.name, pp.value);
  47. copy.stack = stack.reverse();
  48. return copy;
  49. }
  50. // Otherwise use obj as the value of the new FastPath instance.
  51. return new FastPath(obj);
  52. };
  53. FPp.copy = function copy() {
  54. var copy = Object.create(FastPath.prototype);
  55. copy.stack = this.stack.slice(0);
  56. return copy;
  57. };
  58. // The name of the current property is always the penultimate element of
  59. // this.stack, and always a String.
  60. FPp.getName = function getName() {
  61. var s = this.stack;
  62. var len = s.length;
  63. if (len > 1) {
  64. return s[len - 2];
  65. }
  66. // Since the name is always a string, null is a safe sentinel value to
  67. // return if we do not know the name of the (root) value.
  68. return null;
  69. };
  70. // The value of the current property is always the final element of
  71. // this.stack.
  72. FPp.getValue = function getValue() {
  73. var s = this.stack;
  74. return s[s.length - 1];
  75. };
  76. FPp.valueIsDuplicate = function () {
  77. var s = this.stack;
  78. var valueIndex = s.length - 1;
  79. return s.lastIndexOf(s[valueIndex], valueIndex - 1) >= 0;
  80. };
  81. function getNodeHelper(path, count) {
  82. var s = path.stack;
  83. for (var i = s.length - 1; i >= 0; i -= 2) {
  84. var value = s[i];
  85. if (n.Node.check(value) && --count < 0) {
  86. return value;
  87. }
  88. }
  89. return null;
  90. }
  91. FPp.getNode = function getNode(count) {
  92. if (count === void 0) { count = 0; }
  93. return getNodeHelper(this, ~~count);
  94. };
  95. FPp.getParentNode = function getParentNode(count) {
  96. if (count === void 0) { count = 0; }
  97. return getNodeHelper(this, ~~count + 1);
  98. };
  99. // The length of the stack can be either even or odd, depending on whether
  100. // or not we have a name for the root value. The difference between the
  101. // index of the root value and the index of the final value is always
  102. // even, though, which allows us to return the root value in constant time
  103. // (i.e. without iterating backwards through the stack).
  104. FPp.getRootValue = function getRootValue() {
  105. var s = this.stack;
  106. if (s.length % 2 === 0) {
  107. return s[1];
  108. }
  109. return s[0];
  110. };
  111. // Temporarily push properties named by string arguments given after the
  112. // callback function onto this.stack, then call the callback with a
  113. // reference to this (modified) FastPath object. Note that the stack will
  114. // be restored to its original state after the callback is finished, so it
  115. // is probably a mistake to retain a reference to the path.
  116. FPp.call = function call(callback /*, name1, name2, ... */) {
  117. var s = this.stack;
  118. var origLen = s.length;
  119. var value = s[origLen - 1];
  120. var argc = arguments.length;
  121. for (var i = 1; i < argc; ++i) {
  122. var name = arguments[i];
  123. value = value[name];
  124. s.push(name, value);
  125. }
  126. var result = callback(this);
  127. s.length = origLen;
  128. return result;
  129. };
  130. // Similar to FastPath.prototype.call, except that the value obtained by
  131. // accessing this.getValue()[name1][name2]... should be array-like. The
  132. // callback will be called with a reference to this path object for each
  133. // element of the array.
  134. FPp.each = function each(callback /*, name1, name2, ... */) {
  135. var s = this.stack;
  136. var origLen = s.length;
  137. var value = s[origLen - 1];
  138. var argc = arguments.length;
  139. for (var i = 1; i < argc; ++i) {
  140. var name = arguments[i];
  141. value = value[name];
  142. s.push(name, value);
  143. }
  144. for (var i = 0; i < value.length; ++i) {
  145. if (i in value) {
  146. s.push(i, value[i]);
  147. // If the callback needs to know the value of i, call
  148. // path.getName(), assuming path is the parameter name.
  149. callback(this);
  150. s.length -= 2;
  151. }
  152. }
  153. s.length = origLen;
  154. };
  155. // Similar to FastPath.prototype.each, except that the results of the
  156. // callback function invocations are stored in an array and returned at
  157. // the end of the iteration.
  158. FPp.map = function map(callback /*, name1, name2, ... */) {
  159. var s = this.stack;
  160. var origLen = s.length;
  161. var value = s[origLen - 1];
  162. var argc = arguments.length;
  163. for (var i = 1; i < argc; ++i) {
  164. var name = arguments[i];
  165. value = value[name];
  166. s.push(name, value);
  167. }
  168. var result = new Array(value.length);
  169. for (var i = 0; i < value.length; ++i) {
  170. if (i in value) {
  171. s.push(i, value[i]);
  172. result[i] = callback(this, i);
  173. s.length -= 2;
  174. }
  175. }
  176. s.length = origLen;
  177. return result;
  178. };
  179. // Returns true if the node at the tip of the path is wrapped with
  180. // parentheses, OR if the only reason the node needed parentheses was that
  181. // it couldn't be the first expression in the enclosing statement (see
  182. // FastPath#canBeFirstInStatement), and it has an opening `(` character.
  183. // For example, the FunctionExpression in `(function(){}())` appears to
  184. // need parentheses only because it's the first expression in the AST, but
  185. // since it happens to be preceded by a `(` (which is not apparent from
  186. // the AST but can be determined using FastPath#getPrevToken), there is no
  187. // ambiguity about how to parse it, so it counts as having parentheses,
  188. // even though it is not immediately followed by a `)`.
  189. FPp.hasParens = function () {
  190. var node = this.getNode();
  191. var prevToken = this.getPrevToken(node);
  192. if (!prevToken) {
  193. return false;
  194. }
  195. var nextToken = this.getNextToken(node);
  196. if (!nextToken) {
  197. return false;
  198. }
  199. if (prevToken.value === "(") {
  200. if (nextToken.value === ")") {
  201. // If the node preceded by a `(` token and followed by a `)` token,
  202. // then of course it has parentheses.
  203. return true;
  204. }
  205. // If this is one of the few Expression types that can't come first in
  206. // the enclosing statement because of parsing ambiguities (namely,
  207. // FunctionExpression, ObjectExpression, and ClassExpression) and
  208. // this.firstInStatement() returns true, and the node would not need
  209. // parentheses in an expression context because this.needsParens(true)
  210. // returns false, then it just needs an opening parenthesis to resolve
  211. // the parsing ambiguity that made it appear to need parentheses.
  212. var justNeedsOpeningParen = !this.canBeFirstInStatement() &&
  213. this.firstInStatement() &&
  214. !this.needsParens(true);
  215. if (justNeedsOpeningParen) {
  216. return true;
  217. }
  218. }
  219. return false;
  220. };
  221. FPp.getPrevToken = function (node) {
  222. node = node || this.getNode();
  223. var loc = node && node.loc;
  224. var tokens = loc && loc.tokens;
  225. if (tokens && loc.start.token > 0) {
  226. var token = tokens[loc.start.token - 1];
  227. if (token) {
  228. // Do not return tokens that fall outside the root subtree.
  229. var rootLoc = this.getRootValue().loc;
  230. if (util.comparePos(rootLoc.start, token.loc.start) <= 0) {
  231. return token;
  232. }
  233. }
  234. }
  235. return null;
  236. };
  237. FPp.getNextToken = function (node) {
  238. node = node || this.getNode();
  239. var loc = node && node.loc;
  240. var tokens = loc && loc.tokens;
  241. if (tokens && loc.end.token < tokens.length) {
  242. var token = tokens[loc.end.token];
  243. if (token) {
  244. // Do not return tokens that fall outside the root subtree.
  245. var rootLoc = this.getRootValue().loc;
  246. if (util.comparePos(token.loc.end, rootLoc.end) <= 0) {
  247. return token;
  248. }
  249. }
  250. }
  251. return null;
  252. };
  253. // Inspired by require("ast-types").NodePath.prototype.needsParens, but
  254. // more efficient because we're iterating backwards through a stack.
  255. FPp.needsParens = function (assumeExpressionContext) {
  256. var node = this.getNode();
  257. // This needs to come before `if (!parent) { return false }` because
  258. // an object destructuring assignment requires parens for
  259. // correctness even when it's the topmost expression.
  260. if (node.type === "AssignmentExpression" &&
  261. node.left.type === "ObjectPattern") {
  262. return true;
  263. }
  264. var parent = this.getParentNode();
  265. var name = this.getName();
  266. // If the value of this path is some child of a Node and not a Node
  267. // itself, then it doesn't need parentheses. Only Node objects (in fact,
  268. // only Expression nodes) need parentheses.
  269. if (this.getValue() !== node) {
  270. return false;
  271. }
  272. // Only statements don't need parentheses.
  273. if (n.Statement.check(node)) {
  274. return false;
  275. }
  276. // Identifiers never need parentheses.
  277. if (node.type === "Identifier") {
  278. return false;
  279. }
  280. if (parent && parent.type === "ParenthesizedExpression") {
  281. return false;
  282. }
  283. if (node.extra && node.extra.parenthesized) {
  284. return true;
  285. }
  286. if (!parent)
  287. return false;
  288. // Wrap e.g. `-1` in parentheses inside `(-1) ** 2`.
  289. if (node.type === "UnaryExpression" &&
  290. parent.type === "BinaryExpression" &&
  291. name === "left" &&
  292. parent.left === node &&
  293. parent.operator === "**") {
  294. return true;
  295. }
  296. switch (node.type) {
  297. case "UnaryExpression":
  298. case "SpreadElement":
  299. case "SpreadProperty":
  300. return (parent.type === "MemberExpression" &&
  301. name === "object" &&
  302. parent.object === node);
  303. case "BinaryExpression":
  304. case "LogicalExpression":
  305. switch (parent.type) {
  306. case "CallExpression":
  307. return name === "callee" && parent.callee === node;
  308. case "UnaryExpression":
  309. case "SpreadElement":
  310. case "SpreadProperty":
  311. return true;
  312. case "MemberExpression":
  313. return name === "object" && parent.object === node;
  314. case "BinaryExpression":
  315. case "LogicalExpression": {
  316. var po = parent.operator;
  317. var pp = PRECEDENCE[po];
  318. var no = node.operator;
  319. var np = PRECEDENCE[no];
  320. if (pp > np) {
  321. return true;
  322. }
  323. if (pp === np && name === "right") {
  324. assert_1.default.strictEqual(parent.right, node);
  325. return true;
  326. }
  327. break;
  328. }
  329. default:
  330. return false;
  331. }
  332. break;
  333. case "SequenceExpression":
  334. switch (parent.type) {
  335. case "ReturnStatement":
  336. return false;
  337. case "ForStatement":
  338. // Although parentheses wouldn't hurt around sequence expressions in
  339. // the head of for loops, traditional style dictates that e.g. i++,
  340. // j++ should not be wrapped with parentheses.
  341. return false;
  342. case "ExpressionStatement":
  343. return name !== "expression";
  344. default:
  345. // Otherwise err on the side of overparenthesization, adding
  346. // explicit exceptions above if this proves overzealous.
  347. return true;
  348. }
  349. case "OptionalIndexedAccessType":
  350. return node.optional && parent.type === "IndexedAccessType";
  351. case "IntersectionTypeAnnotation":
  352. case "UnionTypeAnnotation":
  353. return parent.type === "NullableTypeAnnotation";
  354. case "Literal":
  355. return (parent.type === "MemberExpression" &&
  356. isNumber.check(node.value) &&
  357. name === "object" &&
  358. parent.object === node);
  359. // Babel 6 Literal split
  360. case "NumericLiteral":
  361. return (parent.type === "MemberExpression" &&
  362. name === "object" &&
  363. parent.object === node);
  364. case "YieldExpression":
  365. case "AwaitExpression":
  366. case "AssignmentExpression":
  367. case "ConditionalExpression":
  368. switch (parent.type) {
  369. case "UnaryExpression":
  370. case "SpreadElement":
  371. case "SpreadProperty":
  372. case "BinaryExpression":
  373. case "LogicalExpression":
  374. return true;
  375. case "CallExpression":
  376. case "NewExpression":
  377. return name === "callee" && parent.callee === node;
  378. case "ConditionalExpression":
  379. return name === "test" && parent.test === node;
  380. case "MemberExpression":
  381. return name === "object" && parent.object === node;
  382. default:
  383. return false;
  384. }
  385. case "ArrowFunctionExpression":
  386. if (n.CallExpression.check(parent) &&
  387. name === "callee" &&
  388. parent.callee === node) {
  389. return true;
  390. }
  391. if (n.MemberExpression.check(parent) &&
  392. name === "object" &&
  393. parent.object === node) {
  394. return true;
  395. }
  396. if (n.TSAsExpression &&
  397. n.TSAsExpression.check(parent) &&
  398. name === "expression" &&
  399. parent.expression === node) {
  400. return true;
  401. }
  402. return isBinary(parent);
  403. case "ObjectExpression":
  404. if (parent.type === "ArrowFunctionExpression" &&
  405. name === "body" &&
  406. parent.body === node) {
  407. return true;
  408. }
  409. break;
  410. case "TSAsExpression":
  411. if (parent.type === "ArrowFunctionExpression" &&
  412. name === "body" &&
  413. parent.body === node &&
  414. node.expression.type === "ObjectExpression") {
  415. return true;
  416. }
  417. break;
  418. case "CallExpression":
  419. if (name === "declaration" &&
  420. n.ExportDefaultDeclaration.check(parent) &&
  421. n.FunctionExpression.check(node.callee)) {
  422. return true;
  423. }
  424. }
  425. if (parent.type === "NewExpression" &&
  426. name === "callee" &&
  427. parent.callee === node) {
  428. return containsCallExpression(node);
  429. }
  430. if (assumeExpressionContext !== true &&
  431. !this.canBeFirstInStatement() &&
  432. this.firstInStatement()) {
  433. return true;
  434. }
  435. return false;
  436. };
  437. function isBinary(node) {
  438. return n.BinaryExpression.check(node) || n.LogicalExpression.check(node);
  439. }
  440. // @ts-ignore 'isUnaryLike' is declared but its value is never read. [6133]
  441. function isUnaryLike(node) {
  442. return (n.UnaryExpression.check(node) ||
  443. // I considered making SpreadElement and SpreadProperty subtypes of
  444. // UnaryExpression, but they're not really Expression nodes.
  445. (n.SpreadElement && n.SpreadElement.check(node)) ||
  446. (n.SpreadProperty && n.SpreadProperty.check(node)));
  447. }
  448. function containsCallExpression(node) {
  449. if (n.CallExpression.check(node)) {
  450. return true;
  451. }
  452. if (isArray.check(node)) {
  453. return node.some(containsCallExpression);
  454. }
  455. if (n.Node.check(node)) {
  456. return types.someField(node, function (_name, child) {
  457. return containsCallExpression(child);
  458. });
  459. }
  460. return false;
  461. }
  462. FPp.canBeFirstInStatement = function () {
  463. var node = this.getNode();
  464. if (n.FunctionExpression.check(node)) {
  465. return false;
  466. }
  467. if (n.ObjectExpression.check(node)) {
  468. return false;
  469. }
  470. if (n.ClassExpression.check(node)) {
  471. return false;
  472. }
  473. return true;
  474. };
  475. FPp.firstInStatement = function () {
  476. var s = this.stack;
  477. var parentName, parent;
  478. var childName, child;
  479. for (var i = s.length - 1; i >= 0; i -= 2) {
  480. if (n.Node.check(s[i])) {
  481. childName = parentName;
  482. child = parent;
  483. parentName = s[i - 1];
  484. parent = s[i];
  485. }
  486. if (!parent || !child) {
  487. continue;
  488. }
  489. if (n.BlockStatement.check(parent) &&
  490. parentName === "body" &&
  491. childName === 0) {
  492. assert_1.default.strictEqual(parent.body[0], child);
  493. return true;
  494. }
  495. if (n.ExpressionStatement.check(parent) && childName === "expression") {
  496. assert_1.default.strictEqual(parent.expression, child);
  497. return true;
  498. }
  499. if (n.AssignmentExpression.check(parent) && childName === "left") {
  500. assert_1.default.strictEqual(parent.left, child);
  501. return true;
  502. }
  503. if (n.ArrowFunctionExpression.check(parent) && childName === "body") {
  504. assert_1.default.strictEqual(parent.body, child);
  505. return true;
  506. }
  507. // s[i + 1] and s[i + 2] represent the array between the parent
  508. // SequenceExpression node and its child nodes
  509. if (n.SequenceExpression.check(parent) &&
  510. s[i + 1] === "expressions" &&
  511. childName === 0) {
  512. assert_1.default.strictEqual(parent.expressions[0], child);
  513. continue;
  514. }
  515. if (n.CallExpression.check(parent) && childName === "callee") {
  516. assert_1.default.strictEqual(parent.callee, child);
  517. continue;
  518. }
  519. if (n.MemberExpression.check(parent) && childName === "object") {
  520. assert_1.default.strictEqual(parent.object, child);
  521. continue;
  522. }
  523. if (n.ConditionalExpression.check(parent) && childName === "test") {
  524. assert_1.default.strictEqual(parent.test, child);
  525. continue;
  526. }
  527. if (isBinary(parent) && childName === "left") {
  528. assert_1.default.strictEqual(parent.left, child);
  529. continue;
  530. }
  531. if (n.UnaryExpression.check(parent) &&
  532. !parent.prefix &&
  533. childName === "argument") {
  534. assert_1.default.strictEqual(parent.argument, child);
  535. continue;
  536. }
  537. return false;
  538. }
  539. return true;
  540. };
  541. exports.default = FastPath;