forked from OKEAMAH/prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.js
More file actions
366 lines (301 loc) · 10.1 KB
/
core.js
File metadata and controls
366 lines (301 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import { diffArrays } from "diff";
import {
convertEndOfLineToChars,
countEndOfLineChars,
guessEndOfLine,
normalizeEndOfLine,
} from "../common/end-of-line.js";
import { addAlignmentToDoc, hardline } from "../document/builders.js";
import { printDocToDebug } from "../document/debug.js";
import { printDocToString as printDocToStringWithoutNormalizeOptions } from "../document/printer.js";
import getAlignmentSize from "../utils/get-alignment-size.js";
import { prepareToPrint, printAstToDoc } from "./ast-to-doc.js";
import getCursorNode from "./get-cursor-node.js";
import massageAst from "./massage-ast.js";
import normalizeFormatOptions from "./normalize-format-options.js";
import parseText from "./parse.js";
import { resolveParser } from "./parser-and-printer.js";
import { calculateRange } from "./range-util.js";
const BOM = "\uFEFF";
const CURSOR = Symbol("cursor");
async function coreFormat(originalText, opts, addAlignmentSize = 0) {
if (!originalText || originalText.trim().length === 0) {
return { formatted: "", cursorOffset: -1, comments: [] };
}
const { ast, text } = await parseText(originalText, opts);
if (opts.cursorOffset >= 0) {
opts.cursorNode = getCursorNode(ast, opts);
}
let doc = await printAstToDoc(ast, opts, addAlignmentSize);
if (addAlignmentSize > 0) {
// Add a hardline to make the indents take effect, it will be removed later
doc = addAlignmentToDoc([hardline, doc], addAlignmentSize, opts.tabWidth);
}
const result = printDocToStringWithoutNormalizeOptions(doc, opts);
// Remove extra leading indentation as well as the added indentation after last newline
if (addAlignmentSize > 0) {
const trimmed = result.formatted.trim();
if (result.cursorNodeStart !== undefined) {
result.cursorNodeStart -= result.formatted.indexOf(trimmed);
}
result.formatted = trimmed + convertEndOfLineToChars(opts.endOfLine);
}
const comments = opts[Symbol.for("comments")];
if (opts.cursorOffset >= 0) {
let oldCursorNodeStart;
let oldCursorNodeText;
let cursorOffsetRelativeToOldCursorNode;
let newCursorNodeStart;
let newCursorNodeText;
if (opts.cursorNode && result.cursorNodeText) {
oldCursorNodeStart = opts.locStart(opts.cursorNode);
oldCursorNodeText = text.slice(
oldCursorNodeStart,
opts.locEnd(opts.cursorNode),
);
cursorOffsetRelativeToOldCursorNode =
opts.cursorOffset - oldCursorNodeStart;
newCursorNodeStart = result.cursorNodeStart;
newCursorNodeText = result.cursorNodeText;
} else {
oldCursorNodeStart = 0;
oldCursorNodeText = text;
cursorOffsetRelativeToOldCursorNode = opts.cursorOffset;
newCursorNodeStart = 0;
newCursorNodeText = result.formatted;
}
if (oldCursorNodeText === newCursorNodeText) {
return {
formatted: result.formatted,
cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode,
comments,
};
}
// diff old and new cursor node texts, with a special cursor
// symbol inserted to find out where it moves to
// eslint-disable-next-line unicorn/prefer-spread
const oldCursorNodeCharArray = oldCursorNodeText.split("");
oldCursorNodeCharArray.splice(
cursorOffsetRelativeToOldCursorNode,
0,
CURSOR,
);
// eslint-disable-next-line unicorn/prefer-spread
const newCursorNodeCharArray = newCursorNodeText.split("");
const cursorNodeDiff = diffArrays(
oldCursorNodeCharArray,
newCursorNodeCharArray,
);
let cursorOffset = newCursorNodeStart;
for (const entry of cursorNodeDiff) {
if (entry.removed) {
if (entry.value.includes(CURSOR)) {
break;
}
} else {
cursorOffset += entry.count;
}
}
return { formatted: result.formatted, cursorOffset, comments };
}
return { formatted: result.formatted, cursorOffset: -1, comments };
}
async function formatRange(originalText, opts) {
const { ast, text } = await parseText(originalText, opts);
const { rangeStart, rangeEnd } = calculateRange(text, opts, ast);
const rangeString = text.slice(rangeStart, rangeEnd);
// Try to extend the range backwards to the beginning of the line.
// This is so we can detect indentation correctly and restore it.
// Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
const rangeStart2 = Math.min(
rangeStart,
text.lastIndexOf("\n", rangeStart) + 1,
);
const indentString = text.slice(rangeStart2, rangeStart).match(/^\s*/u)[0];
const alignmentSize = getAlignmentSize(indentString, opts.tabWidth);
const rangeResult = await coreFormat(
rangeString,
{
...opts,
rangeStart: 0,
rangeEnd: Number.POSITIVE_INFINITY,
// Track the cursor offset only if it's within our range
cursorOffset:
opts.cursorOffset > rangeStart && opts.cursorOffset <= rangeEnd
? opts.cursorOffset - rangeStart
: -1,
// Always use `lf` to format, we'll replace it later
endOfLine: "lf",
},
alignmentSize,
);
// Since the range contracts to avoid trailing whitespace,
// we need to remove the newline that was inserted by the `format` call.
const rangeTrimmed = rangeResult.formatted.trimEnd();
let { cursorOffset } = opts;
if (cursorOffset > rangeEnd) {
// handle the case where the cursor was past the end of the range
cursorOffset += rangeTrimmed.length - rangeString.length;
} else if (rangeResult.cursorOffset >= 0) {
// handle the case where the cursor was in the range
cursorOffset = rangeResult.cursorOffset + rangeStart;
}
// keep the cursor as it was if it was before the start of the range
let formatted =
text.slice(0, rangeStart) + rangeTrimmed + text.slice(rangeEnd);
if (opts.endOfLine !== "lf") {
const eol = convertEndOfLineToChars(opts.endOfLine);
if (cursorOffset >= 0 && eol === "\r\n") {
cursorOffset += countEndOfLineChars(
formatted.slice(0, cursorOffset),
"\n",
);
}
formatted = formatted.replaceAll("\n", eol);
}
return { formatted, cursorOffset, comments: rangeResult.comments };
}
function ensureIndexInText(text, index, defaultValue) {
if (
typeof index !== "number" ||
Number.isNaN(index) ||
index < 0 ||
index > text.length
) {
return defaultValue;
}
return index;
}
function normalizeIndexes(text, options) {
let { cursorOffset, rangeStart, rangeEnd } = options;
cursorOffset = ensureIndexInText(text, cursorOffset, -1);
rangeStart = ensureIndexInText(text, rangeStart, 0);
rangeEnd = ensureIndexInText(text, rangeEnd, text.length);
return { ...options, cursorOffset, rangeStart, rangeEnd };
}
function normalizeInputAndOptions(text, options) {
let { cursorOffset, rangeStart, rangeEnd, endOfLine } = normalizeIndexes(
text,
options,
);
const hasBOM = text.charAt(0) === BOM;
if (hasBOM) {
text = text.slice(1);
cursorOffset--;
rangeStart--;
rangeEnd--;
}
if (endOfLine === "auto") {
endOfLine = guessEndOfLine(text);
}
// get rid of CR/CRLF parsing
if (text.includes("\r")) {
const countCrlfBefore = (index) =>
countEndOfLineChars(text.slice(0, Math.max(index, 0)), "\r\n");
cursorOffset -= countCrlfBefore(cursorOffset);
rangeStart -= countCrlfBefore(rangeStart);
rangeEnd -= countCrlfBefore(rangeEnd);
text = normalizeEndOfLine(text);
}
return {
hasBOM,
text,
options: normalizeIndexes(text, {
...options,
cursorOffset,
rangeStart,
rangeEnd,
endOfLine,
}),
};
}
async function hasPragma(text, options) {
const selectedParser = await resolveParser(options);
return !selectedParser.hasPragma || selectedParser.hasPragma(text);
}
async function formatWithCursor(originalText, originalOptions) {
let { hasBOM, text, options } = normalizeInputAndOptions(
originalText,
await normalizeFormatOptions(originalOptions),
);
if (
(options.rangeStart >= options.rangeEnd && text !== "") ||
(options.requirePragma && !(await hasPragma(text, options)))
) {
return {
formatted: originalText,
cursorOffset: originalOptions.cursorOffset,
comments: [],
};
}
let result;
if (options.rangeStart > 0 || options.rangeEnd < text.length) {
result = await formatRange(text, options);
} else {
if (
!options.requirePragma &&
options.insertPragma &&
options.printer.insertPragma &&
!(await hasPragma(text, options))
) {
text = options.printer.insertPragma(text);
}
result = await coreFormat(text, options);
}
if (hasBOM) {
result.formatted = BOM + result.formatted;
if (result.cursorOffset >= 0) {
result.cursorOffset++;
}
}
return result;
}
async function parse(originalText, originalOptions, devOptions) {
const { text, options } = normalizeInputAndOptions(
originalText,
await normalizeFormatOptions(originalOptions),
);
const parsed = await parseText(text, options);
if (devOptions) {
if (devOptions.preprocessForPrint) {
parsed.ast = await prepareToPrint(parsed.ast, options);
}
if (devOptions.massage) {
parsed.ast = massageAst(parsed.ast, options);
}
}
return parsed;
}
async function formatAst(ast, options) {
options = await normalizeFormatOptions(options);
const doc = await printAstToDoc(ast, options);
return printDocToStringWithoutNormalizeOptions(doc, options);
}
// Doesn't handle shebang for now
async function formatDoc(doc, options) {
const text = printDocToDebug(doc);
const { formatted } = await formatWithCursor(text, {
...options,
parser: "__js_expression",
});
return formatted;
}
async function printToDoc(originalText, options) {
options = await normalizeFormatOptions(options);
const { ast } = await parseText(originalText, options);
return printAstToDoc(ast, options);
}
async function printDocToString(doc, options) {
return printDocToStringWithoutNormalizeOptions(
doc,
await normalizeFormatOptions(options),
);
}
export {
formatAst,
formatDoc,
formatWithCursor,
parse,
printDocToString,
printToDoc,
};