patcher.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. var assert = require("assert");
  2. var linesModule = require("./lines");
  3. var types = require("./types");
  4. var getFieldValue = types.getFieldValue;
  5. var Printable = types.namedTypes.Printable;
  6. var Expression = types.namedTypes.Expression;
  7. var SourceLocation = types.namedTypes.SourceLocation;
  8. var util = require("./util");
  9. var comparePos = util.comparePos;
  10. var FastPath = require("./fast-path");
  11. var isObject = types.builtInTypes.object;
  12. var isArray = types.builtInTypes.array;
  13. var isString = types.builtInTypes.string;
  14. var riskyAdjoiningCharExp = /[0-9a-z_$]/i;
  15. function Patcher(lines) {
  16. assert.ok(this instanceof Patcher);
  17. assert.ok(lines instanceof linesModule.Lines);
  18. var self = this,
  19. replacements = [];
  20. self.replace = function(loc, lines) {
  21. if (isString.check(lines))
  22. lines = linesModule.fromString(lines);
  23. replacements.push({
  24. lines: lines,
  25. start: loc.start,
  26. end: loc.end
  27. });
  28. };
  29. self.get = function(loc) {
  30. // If no location is provided, return the complete Lines object.
  31. loc = loc || {
  32. start: { line: 1, column: 0 },
  33. end: { line: lines.length,
  34. column: lines.getLineLength(lines.length) }
  35. };
  36. var sliceFrom = loc.start,
  37. toConcat = [];
  38. function pushSlice(from, to) {
  39. assert.ok(comparePos(from, to) <= 0);
  40. toConcat.push(lines.slice(from, to));
  41. }
  42. replacements.sort(function(a, b) {
  43. return comparePos(a.start, b.start);
  44. }).forEach(function(rep) {
  45. if (comparePos(sliceFrom, rep.start) > 0) {
  46. // Ignore nested replacement ranges.
  47. } else {
  48. pushSlice(sliceFrom, rep.start);
  49. toConcat.push(rep.lines);
  50. sliceFrom = rep.end;
  51. }
  52. });
  53. pushSlice(sliceFrom, loc.end);
  54. return linesModule.concat(toConcat);
  55. };
  56. }
  57. exports.Patcher = Patcher;
  58. var Pp = Patcher.prototype;
  59. Pp.tryToReprintComments = function(newNode, oldNode, print) {
  60. var patcher = this;
  61. if (!newNode.comments &&
  62. !oldNode.comments) {
  63. // We were (vacuously) able to reprint all the comments!
  64. return true;
  65. }
  66. var newPath = FastPath.from(newNode);
  67. var oldPath = FastPath.from(oldNode);
  68. newPath.stack.push("comments", getSurroundingComments(newNode));
  69. oldPath.stack.push("comments", getSurroundingComments(oldNode));
  70. var reprints = [];
  71. var ableToReprintComments =
  72. findArrayReprints(newPath, oldPath, reprints);
  73. // No need to pop anything from newPath.stack or oldPath.stack, since
  74. // newPath and oldPath are fresh local variables.
  75. if (ableToReprintComments && reprints.length > 0) {
  76. reprints.forEach(function(reprint) {
  77. var oldComment = reprint.oldPath.getValue();
  78. assert.ok(oldComment.leading || oldComment.trailing);
  79. patcher.replace(
  80. oldComment.loc,
  81. // Comments can't have .comments, so it doesn't matter
  82. // whether we print with comments or without.
  83. print(reprint.newPath).indentTail(oldComment.loc.indent)
  84. );
  85. });
  86. }
  87. return ableToReprintComments;
  88. };
  89. // Get all comments that are either leading or trailing, ignoring any
  90. // comments that occur inside node.loc. Returns an empty array for nodes
  91. // with no leading or trailing comments.
  92. function getSurroundingComments(node) {
  93. var result = [];
  94. if (node.comments &&
  95. node.comments.length > 0) {
  96. node.comments.forEach(function(comment) {
  97. if (comment.leading || comment.trailing) {
  98. result.push(comment);
  99. }
  100. });
  101. }
  102. return result;
  103. }
  104. Pp.deleteComments = function(node) {
  105. if (!node.comments) {
  106. return;
  107. }
  108. var patcher = this;
  109. node.comments.forEach(function(comment) {
  110. if (comment.leading) {
  111. // Delete leading comments along with any trailing whitespace
  112. // they might have.
  113. patcher.replace({
  114. start: comment.loc.start,
  115. end: node.loc.lines.skipSpaces(
  116. comment.loc.end, false, false)
  117. }, "");
  118. } else if (comment.trailing) {
  119. // Delete trailing comments along with any leading whitespace
  120. // they might have.
  121. patcher.replace({
  122. start: node.loc.lines.skipSpaces(
  123. comment.loc.start, true, false),
  124. end: comment.loc.end
  125. }, "");
  126. }
  127. });
  128. };
  129. exports.getReprinter = function(path) {
  130. assert.ok(path instanceof FastPath);
  131. // Make sure that this path refers specifically to a Node, rather than
  132. // some non-Node subproperty of a Node.
  133. var node = path.getValue();
  134. if (!Printable.check(node))
  135. return;
  136. var orig = node.original;
  137. var origLoc = orig && orig.loc;
  138. var lines = origLoc && origLoc.lines;
  139. var reprints = [];
  140. if (!lines || !findReprints(path, reprints))
  141. return;
  142. return function(print) {
  143. var patcher = new Patcher(lines);
  144. reprints.forEach(function(reprint) {
  145. var newNode = reprint.newPath.getValue();
  146. var oldNode = reprint.oldPath.getValue();
  147. SourceLocation.assert(oldNode.loc, true);
  148. var needToPrintNewPathWithComments =
  149. !patcher.tryToReprintComments(newNode, oldNode, print)
  150. if (needToPrintNewPathWithComments) {
  151. // Since we were not able to preserve all leading/trailing
  152. // comments, we delete oldNode's comments, print newPath
  153. // with comments, and then patch the resulting lines where
  154. // oldNode used to be.
  155. patcher.deleteComments(oldNode);
  156. }
  157. var newLines = print(
  158. reprint.newPath,
  159. needToPrintNewPathWithComments
  160. ).indentTail(oldNode.loc.indent);
  161. var nls = needsLeadingSpace(lines, oldNode.loc, newLines);
  162. var nts = needsTrailingSpace(lines, oldNode.loc, newLines);
  163. // If we try to replace the argument of a ReturnStatement like
  164. // return"asdf" with e.g. a literal null expression, we run
  165. // the risk of ending up with returnnull, so we need to add an
  166. // extra leading space in situations where that might
  167. // happen. Likewise for "asdf"in obj. See #170.
  168. if (nls || nts) {
  169. var newParts = [];
  170. nls && newParts.push(" ");
  171. newParts.push(newLines);
  172. nts && newParts.push(" ");
  173. newLines = linesModule.concat(newParts);
  174. }
  175. patcher.replace(oldNode.loc, newLines);
  176. });
  177. // Recall that origLoc is the .loc of an ancestor node that is
  178. // guaranteed to contain all the reprinted nodes and comments.
  179. return patcher.get(origLoc).indentTail(-orig.loc.indent);
  180. };
  181. };
  182. // If the last character before oldLoc and the first character of newLines
  183. // are both identifier characters, they must be separated by a space,
  184. // otherwise they will most likely get fused together into a single token.
  185. function needsLeadingSpace(oldLines, oldLoc, newLines) {
  186. var posBeforeOldLoc = util.copyPos(oldLoc.start);
  187. // The character just before the location occupied by oldNode.
  188. var charBeforeOldLoc =
  189. oldLines.prevPos(posBeforeOldLoc) &&
  190. oldLines.charAt(posBeforeOldLoc);
  191. // First character of the reprinted node.
  192. var newFirstChar = newLines.charAt(newLines.firstPos());
  193. return charBeforeOldLoc &&
  194. riskyAdjoiningCharExp.test(charBeforeOldLoc) &&
  195. newFirstChar &&
  196. riskyAdjoiningCharExp.test(newFirstChar);
  197. }
  198. // If the last character of newLines and the first character after oldLoc
  199. // are both identifier characters, they must be separated by a space,
  200. // otherwise they will most likely get fused together into a single token.
  201. function needsTrailingSpace(oldLines, oldLoc, newLines) {
  202. // The character just after the location occupied by oldNode.
  203. var charAfterOldLoc = oldLines.charAt(oldLoc.end);
  204. var newLastPos = newLines.lastPos();
  205. // Last character of the reprinted node.
  206. var newLastChar = newLines.prevPos(newLastPos) &&
  207. newLines.charAt(newLastPos);
  208. return newLastChar &&
  209. riskyAdjoiningCharExp.test(newLastChar) &&
  210. charAfterOldLoc &&
  211. riskyAdjoiningCharExp.test(charAfterOldLoc);
  212. }
  213. function findReprints(newPath, reprints) {
  214. var newNode = newPath.getValue();
  215. Printable.assert(newNode);
  216. var oldNode = newNode.original;
  217. Printable.assert(oldNode);
  218. assert.deepEqual(reprints, []);
  219. if (newNode.type !== oldNode.type) {
  220. return false;
  221. }
  222. var oldPath = new FastPath(oldNode);
  223. var canReprint = findChildReprints(newPath, oldPath, reprints);
  224. if (!canReprint) {
  225. // Make absolutely sure the calling code does not attempt to reprint
  226. // any nodes.
  227. reprints.length = 0;
  228. }
  229. return canReprint;
  230. }
  231. function findAnyReprints(newPath, oldPath, reprints) {
  232. var newNode = newPath.getValue();
  233. var oldNode = oldPath.getValue();
  234. if (newNode === oldNode)
  235. return true;
  236. if (isArray.check(newNode))
  237. return findArrayReprints(newPath, oldPath, reprints);
  238. if (isObject.check(newNode))
  239. return findObjectReprints(newPath, oldPath, reprints);
  240. return false;
  241. }
  242. function findArrayReprints(newPath, oldPath, reprints) {
  243. var newNode = newPath.getValue();
  244. var oldNode = oldPath.getValue();
  245. isArray.assert(newNode);
  246. var len = newNode.length;
  247. if (!(isArray.check(oldNode) &&
  248. oldNode.length === len))
  249. return false;
  250. for (var i = 0; i < len; ++i) {
  251. newPath.stack.push(i, newNode[i]);
  252. oldPath.stack.push(i, oldNode[i]);
  253. var canReprint = findAnyReprints(newPath, oldPath, reprints);
  254. newPath.stack.length -= 2;
  255. oldPath.stack.length -= 2;
  256. if (!canReprint) {
  257. return false;
  258. }
  259. }
  260. return true;
  261. }
  262. function findObjectReprints(newPath, oldPath, reprints) {
  263. var newNode = newPath.getValue();
  264. isObject.assert(newNode);
  265. if (newNode.original === null) {
  266. // If newNode.original node was set to null, reprint the node.
  267. return false;
  268. }
  269. var oldNode = oldPath.getValue();
  270. if (!isObject.check(oldNode))
  271. return false;
  272. if (Printable.check(newNode)) {
  273. if (!Printable.check(oldNode)) {
  274. return false;
  275. }
  276. // Here we need to decide whether the reprinted code for newNode
  277. // is appropriate for patching into the location of oldNode.
  278. if (newNode.type === oldNode.type) {
  279. var childReprints = [];
  280. if (findChildReprints(newPath, oldPath, childReprints)) {
  281. reprints.push.apply(reprints, childReprints);
  282. } else if (oldNode.loc) {
  283. // If we have no .loc information for oldNode, then we
  284. // won't be able to reprint it.
  285. reprints.push({
  286. oldPath: oldPath.copy(),
  287. newPath: newPath.copy()
  288. });
  289. } else {
  290. return false;
  291. }
  292. return true;
  293. }
  294. if (Expression.check(newNode) &&
  295. Expression.check(oldNode) &&
  296. // If we have no .loc information for oldNode, then we won't
  297. // be able to reprint it.
  298. oldNode.loc) {
  299. // If both nodes are subtypes of Expression, then we should be
  300. // able to fill the location occupied by the old node with
  301. // code printed for the new node with no ill consequences.
  302. reprints.push({
  303. oldPath: oldPath.copy(),
  304. newPath: newPath.copy()
  305. });
  306. return true;
  307. }
  308. // The nodes have different types, and at least one of the types
  309. // is not a subtype of the Expression type, so we cannot safely
  310. // assume the nodes are syntactically interchangeable.
  311. return false;
  312. }
  313. return findChildReprints(newPath, oldPath, reprints);
  314. }
  315. // This object is reused in hasOpeningParen and hasClosingParen to avoid
  316. // having to allocate a temporary object.
  317. var reusablePos = { line: 1, column: 0 };
  318. var nonSpaceExp = /\S/;
  319. function hasOpeningParen(oldPath) {
  320. var oldNode = oldPath.getValue();
  321. var loc = oldNode.loc;
  322. var lines = loc && loc.lines;
  323. if (lines) {
  324. var pos = reusablePos;
  325. pos.line = loc.start.line;
  326. pos.column = loc.start.column;
  327. while (lines.prevPos(pos)) {
  328. var ch = lines.charAt(pos);
  329. if (ch === "(") {
  330. // If we found an opening parenthesis but it occurred before
  331. // the start of the original subtree for this reprinting, then
  332. // we must not return true for hasOpeningParen(oldPath).
  333. return comparePos(oldPath.getRootValue().loc.start, pos) <= 0;
  334. }
  335. if (nonSpaceExp.test(ch)) {
  336. return false;
  337. }
  338. }
  339. }
  340. return false;
  341. }
  342. function hasClosingParen(oldPath) {
  343. var oldNode = oldPath.getValue();
  344. var loc = oldNode.loc;
  345. var lines = loc && loc.lines;
  346. if (lines) {
  347. var pos = reusablePos;
  348. pos.line = loc.end.line;
  349. pos.column = loc.end.column;
  350. do {
  351. var ch = lines.charAt(pos);
  352. if (ch === ")") {
  353. // If we found a closing parenthesis but it occurred after the
  354. // end of the original subtree for this reprinting, then we
  355. // must not return true for hasClosingParen(oldPath).
  356. return comparePos(pos, oldPath.getRootValue().loc.end) <= 0;
  357. }
  358. if (nonSpaceExp.test(ch)) {
  359. return false;
  360. }
  361. } while (lines.nextPos(pos));
  362. }
  363. return false;
  364. }
  365. function hasParens(oldPath) {
  366. // This logic can technically be fooled if the node has parentheses
  367. // but there are comments intervening between the parentheses and the
  368. // node. In such cases the node will be harmlessly wrapped in an
  369. // additional layer of parentheses.
  370. return hasOpeningParen(oldPath) && hasClosingParen(oldPath);
  371. }
  372. function findChildReprints(newPath, oldPath, reprints) {
  373. var newNode = newPath.getValue();
  374. var oldNode = oldPath.getValue();
  375. isObject.assert(newNode);
  376. isObject.assert(oldNode);
  377. if (newNode.original === null) {
  378. // If newNode.original node was set to null, reprint the node.
  379. return false;
  380. }
  381. // If this type of node cannot come lexically first in its enclosing
  382. // statement (e.g. a function expression or object literal), and it
  383. // seems to be doing so, then the only way we can ignore this problem
  384. // and save ourselves from falling back to the pretty printer is if an
  385. // opening parenthesis happens to precede the node. For example,
  386. // (function(){ ... }()); does not need to be reprinted, even though
  387. // the FunctionExpression comes lexically first in the enclosing
  388. // ExpressionStatement and fails the hasParens test, because the
  389. // parent CallExpression passes the hasParens test. If we relied on
  390. // the path.needsParens() && !hasParens(oldNode) check below, the
  391. // absence of a closing parenthesis after the FunctionExpression would
  392. // trigger pretty-printing unnecessarily.
  393. if (!newPath.canBeFirstInStatement() &&
  394. newPath.firstInStatement() &&
  395. !hasOpeningParen(oldPath))
  396. return false;
  397. // If this node needs parentheses and will not be wrapped with
  398. // parentheses when reprinted, then return false to skip reprinting
  399. // and let it be printed generically.
  400. if (newPath.needsParens(true) && !hasParens(oldPath)) {
  401. return false;
  402. }
  403. for (var k in util.getUnionOfKeys(newNode, oldNode)) {
  404. if (k === "loc")
  405. continue;
  406. newPath.stack.push(k, types.getFieldValue(newNode, k));
  407. oldPath.stack.push(k, types.getFieldValue(oldNode, k));
  408. var canReprint = findAnyReprints(newPath, oldPath, reprints);
  409. newPath.stack.length -= 2;
  410. oldPath.stack.length -= 2;
  411. if (!canReprint) {
  412. return false;
  413. }
  414. }
  415. return true;
  416. }