Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mapDocInPlace to modify the doc without creating unnecessary copies #6622

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/doc/doc-utils.js
Expand Up @@ -72,6 +72,21 @@ function mapDoc(doc, cb) {
return cb(doc);
}

function mapDocInPlace(doc, cb) {
if (doc.type === "concat" || doc.type === "fill") {
for (let partIndex = 0; partIndex < doc.parts.length; ++partIndex) {
doc.parts[partIndex] = mapDocInPlace(doc.parts[partIndex], cb);
}
} else if (doc.type === "if-break") {
doc.breakContents =
doc.breakContents && mapDocInPlace(doc.breakContents, cb);
doc.flatContents = doc.flatContents && mapDocInPlace(doc.flatContents, cb);
} else if (doc.contents) {
doc.contents = mapDocInPlace(doc.contents, cb);
}
return cb(doc);
}

function findInDoc(doc, fn, defaultValue) {
let result = defaultValue;
let hasStopped = false;
Expand Down Expand Up @@ -212,6 +227,7 @@ module.exports = {
traverseDoc,
findInDoc,
mapDoc,
mapDocInPlace,
propagateBreaks,
removeLines,
stripTrailingHardline
Expand Down
6 changes: 4 additions & 2 deletions src/language-js/embed.js
Expand Up @@ -13,7 +13,7 @@ const {
group,
dedentToRoot
},
utils: { mapDoc, stripTrailingHardline }
utils: { mapDoc, mapDocInPlace, stripTrailingHardline }
} = require("../doc");

function embed(path, print, textToDoc, options) {
Expand Down Expand Up @@ -207,8 +207,10 @@ function uncook(cookedValue) {
return cookedValue.replace(/([\\`]|\$\{)/g, "\\$1");
}

// Note that this uses mapDocInPlace, and so modifies the
// original doc object.
function escapeTemplateCharacters(doc, raw) {
return mapDoc(doc, currentDoc => {
return mapDocInPlace(doc, currentDoc => {
if (!currentDoc.parts) {
return currentDoc;
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/core.js
Expand Up @@ -14,7 +14,7 @@ const {
const rangeUtil = require("./range-util");
const privateUtil = require("../common/util");
const {
utils: { mapDoc },
utils: { mapDocInPlace },
printer: { printDocToString },
debug: { printDocToDebug }
} = require("../doc");
Expand Down Expand Up @@ -89,7 +89,7 @@ function coreFormat(text, opts, addAlignmentSize) {
const result = printDocToString(
opts.endOfLine === "lf"
? doc
: mapDoc(doc, currentDoc =>
: mapDocInPlace(doc, currentDoc =>
typeof currentDoc === "string" && currentDoc.indexOf("\n") !== -1
? currentDoc.replace(/\n/g, eol)
: currentDoc
Expand Down