@tslite/printer 0.5.6 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +55 -0
- package/NOTICE +15 -0
- package/dist/_namespaces/ts.d.ts +4 -0
- package/dist/_namespaces/ts.js +6 -0
- package/dist/emitter.d.ts +2 -0
- package/dist/emitter.js +2751 -0
- package/dist/index.d.ts +1 -64
- package/dist/index.js +4 -1
- package/dist/types.d.ts +197 -0
- package/dist/types.js +65 -0
- package/dist/utilities.d.ts +24 -0
- package/dist/utilities.js +427 -0
- package/package.json +17 -38
- package/dist/index.cjs +0 -1
- package/dist/index.d.cts +0 -64
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
// Modificado de microsoft/TypeScript v3.9.10, src/compiler/utilities.ts e src/compiler/transformer.ts: o namespace virou
|
|
2
|
+
// módulo ES, com os imports explícitos. Os writers do printer — o de texto, o de uma linha só e o que adia o ponto e
|
|
3
|
+
// vírgula final —, a escrita dos comentários e a notificação que não faz nada.
|
|
4
|
+
import { CharacterCodes, NewLineKind, computeLineAndCharacterOfPosition, computeLineStarts, filter, getIndentSize, getIndentString, getLeadingCommentRanges, getLineOfLocalPositionFromLineMap, isPinnedComment, isWhiteSpaceLike, isWhiteSpaceSingleLine, last, noop, skipTrivia, } from "./_namespaces/ts.js";
|
|
5
|
+
const stringWriter = createSingleLineStringWriter();
|
|
6
|
+
function createSingleLineStringWriter() {
|
|
7
|
+
let str = "";
|
|
8
|
+
const writeText = text => str += text;
|
|
9
|
+
return {
|
|
10
|
+
getText: () => str,
|
|
11
|
+
write: writeText,
|
|
12
|
+
rawWrite: writeText,
|
|
13
|
+
writeKeyword: writeText,
|
|
14
|
+
writeOperator: writeText,
|
|
15
|
+
writePunctuation: writeText,
|
|
16
|
+
writeSpace: writeText,
|
|
17
|
+
writeStringLiteral: writeText,
|
|
18
|
+
writeLiteral: writeText,
|
|
19
|
+
writeParameter: writeText,
|
|
20
|
+
writeProperty: writeText,
|
|
21
|
+
writeSymbol: (s, _) => writeText(s),
|
|
22
|
+
writeTrailingSemicolon: writeText,
|
|
23
|
+
writeComment: writeText,
|
|
24
|
+
getTextPos: () => str.length,
|
|
25
|
+
getLine: () => 0,
|
|
26
|
+
getColumn: () => 0,
|
|
27
|
+
getIndent: () => 0,
|
|
28
|
+
isAtStartOfLine: () => false,
|
|
29
|
+
hasTrailingComment: () => false,
|
|
30
|
+
hasTrailingWhitespace: () => !!str.length && isWhiteSpaceLike(str.charCodeAt(str.length - 1)),
|
|
31
|
+
// Completely ignore indentation for string writers. And map newlines to
|
|
32
|
+
// a single space.
|
|
33
|
+
writeLine: () => str += " ",
|
|
34
|
+
increaseIndent: noop,
|
|
35
|
+
decreaseIndent: noop,
|
|
36
|
+
clear: () => str = "",
|
|
37
|
+
trackSymbol: noop,
|
|
38
|
+
reportInaccessibleThisError: noop,
|
|
39
|
+
reportInaccessibleUniqueSymbolError: noop,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export function usingSingleLineStringWriter(action) {
|
|
43
|
+
const oldString = stringWriter.getText();
|
|
44
|
+
try {
|
|
45
|
+
action(stringWriter);
|
|
46
|
+
return stringWriter.getText();
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
stringWriter.clear();
|
|
50
|
+
stringWriter.writeKeyword(oldString);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Returns a value indicating whether a name is unique globally or within the current file.
|
|
55
|
+
* Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`.
|
|
56
|
+
*/
|
|
57
|
+
export function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
|
|
58
|
+
return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
|
|
59
|
+
}
|
|
60
|
+
export function createTextWriter(newLine) {
|
|
61
|
+
let output;
|
|
62
|
+
let indent;
|
|
63
|
+
let lineStart;
|
|
64
|
+
let lineCount;
|
|
65
|
+
let linePos;
|
|
66
|
+
let hasTrailingComment = false;
|
|
67
|
+
function updateLineCountAndPosFor(s) {
|
|
68
|
+
const lineStartsOfS = computeLineStarts(s);
|
|
69
|
+
if (lineStartsOfS.length > 1) {
|
|
70
|
+
lineCount = lineCount + lineStartsOfS.length - 1;
|
|
71
|
+
linePos = output.length - s.length + last(lineStartsOfS);
|
|
72
|
+
lineStart = (linePos - output.length) === 0;
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
lineStart = false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function writeText(s) {
|
|
79
|
+
if (s && s.length) {
|
|
80
|
+
if (lineStart) {
|
|
81
|
+
s = getIndentString(indent) + s;
|
|
82
|
+
lineStart = false;
|
|
83
|
+
}
|
|
84
|
+
output += s;
|
|
85
|
+
updateLineCountAndPosFor(s);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function write(s) {
|
|
89
|
+
if (s)
|
|
90
|
+
hasTrailingComment = false;
|
|
91
|
+
writeText(s);
|
|
92
|
+
}
|
|
93
|
+
function writeComment(s) {
|
|
94
|
+
if (s)
|
|
95
|
+
hasTrailingComment = true;
|
|
96
|
+
writeText(s);
|
|
97
|
+
}
|
|
98
|
+
function reset() {
|
|
99
|
+
output = "";
|
|
100
|
+
indent = 0;
|
|
101
|
+
lineStart = true;
|
|
102
|
+
lineCount = 0;
|
|
103
|
+
linePos = 0;
|
|
104
|
+
hasTrailingComment = false;
|
|
105
|
+
}
|
|
106
|
+
function rawWrite(s) {
|
|
107
|
+
if (s !== undefined) {
|
|
108
|
+
output += s;
|
|
109
|
+
updateLineCountAndPosFor(s);
|
|
110
|
+
hasTrailingComment = false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function writeLiteral(s) {
|
|
114
|
+
if (s && s.length) {
|
|
115
|
+
write(s);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function writeLine(force) {
|
|
119
|
+
if (!lineStart || force) {
|
|
120
|
+
output += newLine;
|
|
121
|
+
lineCount++;
|
|
122
|
+
linePos = output.length;
|
|
123
|
+
lineStart = true;
|
|
124
|
+
hasTrailingComment = false;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function getTextPosWithWriteLine() {
|
|
128
|
+
return lineStart ? output.length : (output.length + newLine.length);
|
|
129
|
+
}
|
|
130
|
+
reset();
|
|
131
|
+
return {
|
|
132
|
+
write,
|
|
133
|
+
rawWrite,
|
|
134
|
+
writeLiteral,
|
|
135
|
+
writeLine,
|
|
136
|
+
increaseIndent: () => { indent++; },
|
|
137
|
+
decreaseIndent: () => { indent--; },
|
|
138
|
+
getIndent: () => indent,
|
|
139
|
+
getTextPos: () => output.length,
|
|
140
|
+
getLine: () => lineCount,
|
|
141
|
+
getColumn: () => lineStart ? indent * getIndentSize() : output.length - linePos,
|
|
142
|
+
getText: () => output,
|
|
143
|
+
isAtStartOfLine: () => lineStart,
|
|
144
|
+
hasTrailingComment: () => hasTrailingComment,
|
|
145
|
+
hasTrailingWhitespace: () => !!output.length && isWhiteSpaceLike(output.charCodeAt(output.length - 1)),
|
|
146
|
+
clear: reset,
|
|
147
|
+
reportInaccessibleThisError: noop,
|
|
148
|
+
reportInaccessibleUniqueSymbolError: noop,
|
|
149
|
+
trackSymbol: noop,
|
|
150
|
+
writeKeyword: write,
|
|
151
|
+
writeOperator: write,
|
|
152
|
+
writeParameter: write,
|
|
153
|
+
writeProperty: write,
|
|
154
|
+
writePunctuation: write,
|
|
155
|
+
writeSpace: write,
|
|
156
|
+
writeStringLiteral: write,
|
|
157
|
+
writeSymbol: (s, _) => write(s),
|
|
158
|
+
writeTrailingSemicolon: write,
|
|
159
|
+
writeComment,
|
|
160
|
+
getTextPosWithWriteLine
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
export function getTrailingSemicolonDeferringWriter(writer) {
|
|
164
|
+
let pendingTrailingSemicolon = false;
|
|
165
|
+
function commitPendingTrailingSemicolon() {
|
|
166
|
+
if (pendingTrailingSemicolon) {
|
|
167
|
+
writer.writeTrailingSemicolon(";");
|
|
168
|
+
pendingTrailingSemicolon = false;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
...writer,
|
|
173
|
+
writeTrailingSemicolon() {
|
|
174
|
+
pendingTrailingSemicolon = true;
|
|
175
|
+
},
|
|
176
|
+
writeLiteral(s) {
|
|
177
|
+
commitPendingTrailingSemicolon();
|
|
178
|
+
writer.writeLiteral(s);
|
|
179
|
+
},
|
|
180
|
+
writeStringLiteral(s) {
|
|
181
|
+
commitPendingTrailingSemicolon();
|
|
182
|
+
writer.writeStringLiteral(s);
|
|
183
|
+
},
|
|
184
|
+
writeSymbol(s, sym) {
|
|
185
|
+
commitPendingTrailingSemicolon();
|
|
186
|
+
writer.writeSymbol(s, sym);
|
|
187
|
+
},
|
|
188
|
+
writePunctuation(s) {
|
|
189
|
+
commitPendingTrailingSemicolon();
|
|
190
|
+
writer.writePunctuation(s);
|
|
191
|
+
},
|
|
192
|
+
writeKeyword(s) {
|
|
193
|
+
commitPendingTrailingSemicolon();
|
|
194
|
+
writer.writeKeyword(s);
|
|
195
|
+
},
|
|
196
|
+
writeOperator(s) {
|
|
197
|
+
commitPendingTrailingSemicolon();
|
|
198
|
+
writer.writeOperator(s);
|
|
199
|
+
},
|
|
200
|
+
writeParameter(s) {
|
|
201
|
+
commitPendingTrailingSemicolon();
|
|
202
|
+
writer.writeParameter(s);
|
|
203
|
+
},
|
|
204
|
+
writeSpace(s) {
|
|
205
|
+
commitPendingTrailingSemicolon();
|
|
206
|
+
writer.writeSpace(s);
|
|
207
|
+
},
|
|
208
|
+
writeProperty(s) {
|
|
209
|
+
commitPendingTrailingSemicolon();
|
|
210
|
+
writer.writeProperty(s);
|
|
211
|
+
},
|
|
212
|
+
writeComment(s) {
|
|
213
|
+
commitPendingTrailingSemicolon();
|
|
214
|
+
writer.writeComment(s);
|
|
215
|
+
},
|
|
216
|
+
writeLine() {
|
|
217
|
+
commitPendingTrailingSemicolon();
|
|
218
|
+
writer.writeLine();
|
|
219
|
+
},
|
|
220
|
+
increaseIndent() {
|
|
221
|
+
commitPendingTrailingSemicolon();
|
|
222
|
+
writer.increaseIndent();
|
|
223
|
+
},
|
|
224
|
+
decreaseIndent() {
|
|
225
|
+
commitPendingTrailingSemicolon();
|
|
226
|
+
writer.decreaseIndent();
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
export function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
|
|
231
|
+
emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
|
|
232
|
+
}
|
|
233
|
+
export function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
|
|
234
|
+
// If the leading comments start on different line than the start of node, write new line
|
|
235
|
+
if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
|
|
236
|
+
getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
|
|
237
|
+
writer.writeLine();
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
export function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
|
|
241
|
+
// If the leading comments start on different line than the start of node, write new line
|
|
242
|
+
if (pos !== commentPos &&
|
|
243
|
+
getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
|
|
244
|
+
writer.writeLine();
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
export function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
|
|
248
|
+
if (comments && comments.length > 0) {
|
|
249
|
+
if (leadingSeparator) {
|
|
250
|
+
writer.writeSpace(" ");
|
|
251
|
+
}
|
|
252
|
+
let emitInterveningSeparator = false;
|
|
253
|
+
for (const comment of comments) {
|
|
254
|
+
if (emitInterveningSeparator) {
|
|
255
|
+
writer.writeSpace(" ");
|
|
256
|
+
emitInterveningSeparator = false;
|
|
257
|
+
}
|
|
258
|
+
writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
|
|
259
|
+
if (comment.hasTrailingNewLine) {
|
|
260
|
+
writer.writeLine();
|
|
261
|
+
}
|
|
262
|
+
else {
|
|
263
|
+
emitInterveningSeparator = true;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
if (emitInterveningSeparator && trailingSeparator) {
|
|
267
|
+
writer.writeSpace(" ");
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Detached comment is a comment at the top of file or function body that is separated from
|
|
273
|
+
* the next statement by space.
|
|
274
|
+
*/
|
|
275
|
+
export function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
|
|
276
|
+
let leadingComments;
|
|
277
|
+
let currentDetachedCommentInfo;
|
|
278
|
+
if (removeComments) {
|
|
279
|
+
// removeComments is true, only reserve pinned comment at the top of file
|
|
280
|
+
// For example:
|
|
281
|
+
// /*! Pinned Comment */
|
|
282
|
+
//
|
|
283
|
+
// var x = 10;
|
|
284
|
+
if (node.pos === 0) {
|
|
285
|
+
leadingComments = filter(getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
// removeComments is false, just get detached as normal and bypass the process to filter comment
|
|
290
|
+
leadingComments = getLeadingCommentRanges(text, node.pos);
|
|
291
|
+
}
|
|
292
|
+
if (leadingComments) {
|
|
293
|
+
const detachedComments = [];
|
|
294
|
+
let lastComment;
|
|
295
|
+
for (const comment of leadingComments) {
|
|
296
|
+
if (lastComment) {
|
|
297
|
+
const lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
|
|
298
|
+
const commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
|
|
299
|
+
if (commentLine >= lastCommentLine + 2) {
|
|
300
|
+
// There was a blank line between the last comment and this comment. This
|
|
301
|
+
// comment is not part of the copyright comments. Return what we have so
|
|
302
|
+
// far.
|
|
303
|
+
break;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
detachedComments.push(comment);
|
|
307
|
+
lastComment = comment;
|
|
308
|
+
}
|
|
309
|
+
if (detachedComments.length) {
|
|
310
|
+
// All comments look like they could have been part of the copyright header. Make
|
|
311
|
+
// sure there is at least one blank line between it and the node. If not, it's not
|
|
312
|
+
// a copyright header.
|
|
313
|
+
const lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, last(detachedComments).end);
|
|
314
|
+
const nodeLine = getLineOfLocalPositionFromLineMap(lineMap, skipTrivia(text, node.pos));
|
|
315
|
+
if (nodeLine >= lastCommentLine + 2) {
|
|
316
|
+
// Valid detachedComments
|
|
317
|
+
emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
|
|
318
|
+
emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
|
|
319
|
+
currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: last(detachedComments).end };
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return currentDetachedCommentInfo;
|
|
324
|
+
function isPinnedCommentLocal(comment) {
|
|
325
|
+
return isPinnedComment(text, comment.pos);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
export function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
|
|
329
|
+
if (text.charCodeAt(commentPos + 1) === CharacterCodes.asterisk) {
|
|
330
|
+
const firstCommentLineAndCharacter = computeLineAndCharacterOfPosition(lineMap, commentPos);
|
|
331
|
+
const lineCount = lineMap.length;
|
|
332
|
+
let firstCommentLineIndent;
|
|
333
|
+
for (let pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
|
|
334
|
+
const nextLineStart = (currentLine + 1) === lineCount
|
|
335
|
+
? text.length + 1
|
|
336
|
+
: lineMap[currentLine + 1];
|
|
337
|
+
if (pos !== commentPos) {
|
|
338
|
+
// If we are not emitting first line, we need to write the spaces to adjust the alignment
|
|
339
|
+
if (firstCommentLineIndent === undefined) {
|
|
340
|
+
firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
|
|
341
|
+
}
|
|
342
|
+
// These are number of spaces writer is going to write at current indent
|
|
343
|
+
const currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
|
|
344
|
+
// Number of spaces we want to be writing
|
|
345
|
+
// eg: Assume writer indent
|
|
346
|
+
// module m {
|
|
347
|
+
// /* starts at character 9 this is line 1
|
|
348
|
+
// * starts at character pos 4 line --1 = 8 - 8 + 3
|
|
349
|
+
// More left indented comment */ --2 = 8 - 8 + 2
|
|
350
|
+
// class c { }
|
|
351
|
+
// }
|
|
352
|
+
// module m {
|
|
353
|
+
// /* this is line 1 -- Assume current writer indent 8
|
|
354
|
+
// * line --3 = 8 - 4 + 5
|
|
355
|
+
// More right indented comment */ --4 = 8 - 4 + 11
|
|
356
|
+
// class c { }
|
|
357
|
+
// }
|
|
358
|
+
const spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
|
|
359
|
+
if (spacesToEmit > 0) {
|
|
360
|
+
let numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
|
|
361
|
+
const indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
|
|
362
|
+
// Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
|
|
363
|
+
writer.rawWrite(indentSizeSpaceString);
|
|
364
|
+
// Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
|
|
365
|
+
while (numberOfSingleSpacesToEmit) {
|
|
366
|
+
writer.rawWrite(" ");
|
|
367
|
+
numberOfSingleSpacesToEmit--;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
else {
|
|
371
|
+
// No spaces to emit write empty string
|
|
372
|
+
writer.rawWrite("");
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
// Write the comment line text
|
|
376
|
+
writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
|
|
377
|
+
pos = nextLineStart;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
else {
|
|
381
|
+
// Single line comment of style //....
|
|
382
|
+
writer.writeComment(text.substring(commentPos, commentEnd));
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
|
|
386
|
+
const end = Math.min(commentEnd, nextLineStart - 1);
|
|
387
|
+
const currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
|
|
388
|
+
if (currentLineText) {
|
|
389
|
+
// trimmed forward and ending spaces text
|
|
390
|
+
writer.writeComment(currentLineText);
|
|
391
|
+
if (end !== commentEnd) {
|
|
392
|
+
writer.writeLine();
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
// Empty string - make sure we write empty line
|
|
397
|
+
writer.rawWrite(newLine);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
function calculateIndent(text, pos, end) {
|
|
401
|
+
let currentLineIndent = 0;
|
|
402
|
+
for (; pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
|
|
403
|
+
if (text.charCodeAt(pos) === CharacterCodes.tab) {
|
|
404
|
+
// Tabs = TabSize = indent size and go to next tabStop
|
|
405
|
+
currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
// Single space
|
|
409
|
+
currentLineIndent++;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
return currentLineIndent;
|
|
413
|
+
}
|
|
414
|
+
const carriageReturnLineFeed = "\r\n";
|
|
415
|
+
const lineFeed = "\n";
|
|
416
|
+
export function getNewLineCharacter(options, getNewLine) {
|
|
417
|
+
switch (options.newLine) {
|
|
418
|
+
case NewLineKind.CarriageReturnLineFeed:
|
|
419
|
+
return carriageReturnLineFeed;
|
|
420
|
+
case NewLineKind.LineFeed:
|
|
421
|
+
return lineFeed;
|
|
422
|
+
}
|
|
423
|
+
return getNewLine ? getNewLine() : carriageReturnLineFeed;
|
|
424
|
+
}
|
|
425
|
+
export function noEmitNotification(hint, node, callback) {
|
|
426
|
+
callback(hint, node);
|
|
427
|
+
}
|
package/package.json
CHANGED
|
@@ -1,60 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tslite/printer",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.12.0",
|
|
4
|
+
"description": "The tsc 3.9.10 printer, copied from the tag and cut down to the TSLite Language: prints a parse tree node, a list or a file as text, with the writers it prints through",
|
|
5
|
+
"author": "Anderson D. Rosa <andersondrosa@outlook.com>",
|
|
6
|
+
"license": "Apache-2.0",
|
|
5
7
|
"type": "module",
|
|
6
|
-
"main": "./dist/index.cjs",
|
|
7
|
-
"module": "./dist/index.js",
|
|
8
|
-
"types": "./dist/index.d.ts",
|
|
9
8
|
"exports": {
|
|
10
9
|
".": {
|
|
11
|
-
"types": "./dist/
|
|
12
|
-
"import": "./dist/
|
|
13
|
-
"require": "./dist/index.cjs"
|
|
10
|
+
"types": "./dist/_namespaces/ts.d.ts",
|
|
11
|
+
"import": "./dist/_namespaces/ts.js"
|
|
14
12
|
}
|
|
15
13
|
},
|
|
16
14
|
"files": [
|
|
17
|
-
"dist"
|
|
15
|
+
"dist",
|
|
16
|
+
"LICENSE",
|
|
17
|
+
"NOTICE"
|
|
18
18
|
],
|
|
19
|
-
"
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"@tslite/parser": "1.12.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@tslite/oracle": "0.1.1"
|
|
22
24
|
},
|
|
23
25
|
"repository": {
|
|
24
26
|
"type": "git",
|
|
25
27
|
"url": "https://github.com/andersondrosa/tslite.git",
|
|
26
28
|
"directory": "packages/printer"
|
|
27
29
|
},
|
|
28
|
-
"keywords": [
|
|
29
|
-
"ast",
|
|
30
|
-
"estree",
|
|
31
|
-
"codegen",
|
|
32
|
-
"printer",
|
|
33
|
-
"emit",
|
|
34
|
-
"code-generation",
|
|
35
|
-
"typescript"
|
|
36
|
-
],
|
|
37
|
-
"author": "Anderson D. Rosa <andersondrosa@outlook.com>",
|
|
38
|
-
"license": "MIT",
|
|
39
30
|
"publishConfig": {
|
|
40
31
|
"access": "public"
|
|
41
32
|
},
|
|
42
|
-
"dependencies": {
|
|
43
|
-
"@tslite/core": "0.10.0",
|
|
44
|
-
"@tslite/sanitize": "0.1.11",
|
|
45
|
-
"@tslite/capability": "0.6.0"
|
|
46
|
-
},
|
|
47
33
|
"scripts": {
|
|
48
|
-
"build": "
|
|
49
|
-
"dev": "tsup --watch",
|
|
50
|
-
"test": "vitest run",
|
|
51
|
-
"test:watch": "vitest",
|
|
52
|
-
"test:coverage": "vitest run --coverage",
|
|
53
|
-
"typecheck": "tsc --noEmit",
|
|
54
|
-
"lint": "eslint src",
|
|
55
|
-
"lint:fix": "eslint src --fix",
|
|
34
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && node ../../scripts/copy-declarations.mjs dist",
|
|
56
35
|
"clean": "rm -rf dist",
|
|
57
|
-
"
|
|
58
|
-
"
|
|
36
|
+
"test": "vitest run",
|
|
37
|
+
"typecheck": "tsc --noEmit -p ."
|
|
59
38
|
}
|
|
60
39
|
}
|
package/dist/index.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var core=require('@tslite/core'),capability=require('@tslite/capability'),sanitize=require('@tslite/sanitize');var L=t=>core.VALID_OBJECT_KEY.test(t);function m(t){let e=n=>{if(typeof n=="string")return `"${n}"`;if(typeof n!="object")return String(n);if(n===null)return "null";if(Array.isArray(n))return `[${n.map(e).join(",")}]`;let s=n;if(core.isExprMarker(s)){let{[core.EXPR_MARKER]:i,...y}=s,N={type:i,...y};return r(N)}return `{ ${Object.entries(s).map(([i,y])=>`${L(i)?i:`"${i}"`}: ${e(y)}`).join(", ")} }`};return e(t)}var u=", ",l=null,r=t=>{if(t==null)return "";if(Array.isArray(t))return t.filter(Boolean).map(r).join(u);if(typeof t!="object")return String(t);if(!t.type)return JSON.stringify(t);if(t.type in T){if(l){let e=capability.nodeViolation(t,l);if(e)throw new core.TSLiteError("node-not-allowed",`'${e}' is not allowed by the active capability profile.`,{type:t.type})}return T[t.type](t)}throw Error("Unknown type: "+t.type)},W=(t,e)=>{t&&typeof t=="object"&&!Array.isArray(t)&&sanitize.assertSafe(t,e.sanitize==="hermetic"?sanitize.HERMETIC_POLICY:void 0);let n=l;l=capability.compileProfile(e);try{return r(t)}finally{l=n;}},c=t=>`(${t})`;function b(t){if(_.has(t.type))return true;if(t.type!=="Literal")return false;let e=t;return !(typeof e.value=="number"||e.bigint!=null)}var _=new Set(["Identifier","ThisExpression","ArrayExpression","MemberExpression","CallExpression","TemplateLiteral"]),x=t=>{if(t.type==="TSAsExpression")return x(t.expression);let e=r(t);return b(t)?e:c(e)},M=t=>`[${r(t.elements)}]`,U=t=>`[${t.elements.map(n=>n?r(n):"").join(", ")}]`,q=t=>{let e=r(t.params),n=r(t.body),s=t.body.type!=="BlockStatement"&&n.startsWith("{"),o=t.body.type=="AssignmentExpression"||t.body.type=="BinaryExpression"||t.body.type=="ObjectExpression"||t.body.type=="JsonExpression"||s?c(n):n;return `${t.async?"async ":""}(${e}) => ${o}`},V=t=>{let e=r(t.left),n=r(t.right);return `${e} ${t.operator} ${n}`},X=t=>"await "+p(t.argument,core.Precedence.Await,false),$=t=>t.type==="TSAsExpression"?$(t.expression):t,w=t=>{let e=$(t);return e.type==="UnaryExpression"||e.type==="AwaitExpression"},A=(t,e)=>{let n=$(e);if(n.type!=="LogicalExpression")return false;let s=n.operator;return t==="??"?s==="||"||s==="&&":t==="||"||t==="&&"?s==="??":false},K=t=>{let e=core.BinaryPrecedence[t.operator]??1/0,n=t.operator==="**",s=p(t.left,e,false,n),o=n&&(w(t.left)||s[0]==="-"||s[0]==="+")?c(s):s,i=p(t.right,e,true,n);return `${o} ${t.operator} ${i}`},z=t=>{let e=t.body.map(E).filter(Boolean).join(" ");return `{ ${e?e+" ":""}}`},Y=t=>t.label?`break ${r(t.label)}`:"break",H=t=>{let e=x(t.callee),n=t.optional?"?.":"";return `${e}${n}(${r(t.arguments)})`},G=t=>r(t.expression),S=t=>t.type==="BinaryExpression"||t.type==="LogicalExpression"?core.BinaryPrecedence[t.operator]??1/0:t.type==="ConditionalExpression"?core.Precedence.Conditional:t.type==="AssignmentExpression"?core.Precedence.Assignment:t.type==="ArrowFunctionExpression"?core.Precedence.ArrowFunction:t.type==="AwaitExpression"?core.Precedence.Await:t.type==="SequenceExpression"?core.Precedence.Sequence:t.type==="TSAsExpression"?S(t.expression):1/0,B=(t,e,n,s=false)=>{let o=S(t);return n?s?o<e:o<=e:s?o<=e:o<e},p=(t,e,n,s=false)=>{let o=r(t);return B(t,e,n,s)?c(o):o},Q=t=>`${p(t.test,core.Precedence.Conditional,false,true)} ? ${r(t.consequent)} : ${r(t.alternate)}`,Z=t=>t.label?`continue ${r(t.label)}`:"continue",d=t=>{let e=r(t.expression);return e[0]==="{"||e.startsWith("function")||e.startsWith("class")?c(e):e},tt=t=>";",et=t=>`do ${r(t.body)} while (${r(t.test)})`,rt=t=>`for (${r(t.left)} in ${r(t.right)}) ${r(t.body)}`,nt=t=>`for${t.await?" await":""} (${r(t.left)} of ${r(t.right)}) ${r(t.body)}`,st=t=>{let e=r(t.init),n=r(t.test),s=r(t.update);return `for (${e};${n?` ${n}`:""};${s?` ${s}`:""}) ${r(t.body)}`},ot=t=>{let e=t.params.map(P).join(u);return `${t.async?"async ":""}function ${r(t.id)}(${e}) ${r(t.body)}`},it=t=>{let e=r(t.params);return `${t.async?"async ":""}function ${r(t.id)}(${e}) ${r(t.body)}`},P=t=>t.name,at=t=>{throw new core.TSLiteError("incomplete-tree","Cannot print a tree with a Placeholder (hole) \u2014 fill the holes first.",{type:t.type})},pt=t=>`if (${r(t.test)}) ${r(t.consequent)}${t.alternate?` else ${r(t.alternate)}`:""}`,ct=t=>m(t.body),lt=t=>t.raw?t.raw:t.value===void 0?"undefined":t.value===null?"null":typeof t.value=="string"?JSON.stringify(t.value):typeof t.value=="boolean"?String(t.value):t.bigint?t.bigint+"n":t.regex?`/${t.regex.pattern}/${t.regex.flags}`:(t.value instanceof RegExp,String(t.value)),ut=t=>{let e=core.BinaryPrecedence[t.operator]??1/0,n=(s,o)=>A(t.operator,s)?c(r(s)):p(s,e,o);return `${n(t.left,false)} ${t.operator} ${n(t.right,true)}`},yt=t=>{let e=[x(t.object)];return t.optional&&e.push(t.computed?"?.":"?"),e.push(t.computed?"[":"."),e.push(r(t.property)),t.computed&&e.push("]"),e.join("")},mt=t=>{let e=t.properties.map(r).join(", ");return e.length==0?"{}":`{ ${e} }`},ft=t=>{let e=t.properties.map(r).join(", ");return e.length==0?"{ }":`{ ${e} }`},xt=new Set(["FunctionDeclaration","IfStatement","ForStatement","ForInStatement","ForOfStatement","WhileStatement","TryStatement","SwitchStatement","ClassDeclaration","BlockStatement"]),E=t=>{let e=r(t);return !e||e===";"?"":xt.has(t.type)?e:e+";"},$t=t=>t.body.map(E).filter(Boolean).join(" "),St=t=>t.shorthand?r(t.value):`${t.computed?`[${r(t.key)}]`:r(t.key)}: ${r(t.value)}`,Et=t=>`${r(t.left)} = ${r(t.right)}`,Tt=t=>"return "+r(t.argument),gt=t=>{let e=t.test?`case ${r(t.test)}:`:"default:",n=t.consequent.map(E).filter(Boolean).join(" ");return n?`${e} ${n}`:e},ht=t=>`switch (${r(t.discriminant)}) { ${t.cases.map(r).join(" ")} }`,bt=t=>t.value.raw,wt=t=>"`"+t.quasis.map((e,n)=>r(e)+(e.tail?"":"${"+r(t.expressions[n])+"}")).join("")+"`",At=t=>"throw "+r(t.argument),Bt=t=>{let e=`try ${r(t.block)}`;if(t.handler){let n=t.handler.param;e+=n?` catch (${r(n)}) ${r(t.handler.body)}`:` catch ${r(t.handler.body)}`;}return e+(t.finalizer?` finally ${r(t.finalizer)}`:"")},Pt=t=>{let e=p(t.argument,core.Precedence.Unary,false),n=t.operator.length>1||(t.operator==="+"||t.operator==="-")&&e[0]===t.operator?" ":"";return t.operator+n+e},It=t=>t.prefix==true?t.operator+r(t.argument):r(t.argument)+t.operator,jt=t=>`${t.kind} ${t.declarations.map(I).join(", ")}`,I=t=>t.init?`${r(t.id)} = ${r(t.init)}`:r(t.id),Ct=t=>`while (${r(t.test)}) ${r(t.body)}`,Nt=t=>{if(t.importKind==="type")return "";let e=r(t.source);if(t.specifiers.length==0)return `import ${e}`;let n=t.specifiers.find(i=>i.type==="ImportDefaultSpecifier"||i.type==="ImportNamespaceSpecifier"),s=t.specifiers.filter(i=>i.type==="ImportSpecifier"&&i.importKind!=="type");if(!n&&s.length===0)return "";let o=[];return n&&o.push(r(n)),s.length&&o.push(`{ ${s.map(j).join(u)} }`),`import ${o.join(u)} from ${e}`},Dt=t=>r(t.local),kt=t=>`* as ${r(t.local)}`,j=t=>t.imported.name===t.local.name?`${r(t.local)}`:`${r(t.imported)} as ${r(t.local)}`,Ft=t=>{if(t.declaration){let n=r(t.declaration);return n?`export ${n}`:""}return `export { ${t.specifiers.map(C).join(u)} }`},Lt=t=>`export default ${r(t.declaration)}`,C=t=>t.local.name===t.exported.name?`${r(t.local)}`:`${r(t.local)} as ${r(t.exported)}`,vt=t=>`...${r(t.argument)}`,Ot=t=>`...${r(t.argument)}`,Jt=()=>"",Rt=t=>r(t.expression),Wt=t=>r(core.desugarJSX(t)),_t=t=>r(core.desugarJSX(t)),T={print:r,JSXElement:Wt,JSXFragment:_t,ArrayExpression:M,ArrayPattern:U,ArrowFunctionExpression:q,AssignmentExpression:V,AssignmentPattern:Et,AwaitExpression:X,BinaryExpression:K,BlockStatement:z,BreakStatement:Y,CallExpression:H,ChainExpression:G,ConditionalExpression:Q,ContinueStatement:Z,DoWhileStatement:et,EmptyStatement:tt,ExpressionStatement:d,ForInStatement:rt,ForOfStatement:nt,ForStatement:st,FunctionDeclaration:ot,FunctionExpression:it,Identifier:P,Placeholder:at,IfStatement:pt,ImportDeclaration:Nt,ImportDefaultSpecifier:Dt,ImportNamespaceSpecifier:kt,ImportSpecifier:j,ExportNamedDeclaration:Ft,ExportDefaultDeclaration:Lt,ExportSpecifier:C,JsonExpression:ct,Literal:lt,LogicalExpression:ut,MemberExpression:yt,ObjectExpression:mt,ObjectPattern:ft,Program:$t,Property:St,ReturnStatement:Tt,SwitchCase:gt,SwitchStatement:ht,TemplateElement:bt,TemplateLiteral:wt,ThrowStatement:At,TryStatement:Bt,UnaryExpression:Pt,UpdateExpression:It,VariableDeclaration:jt,VariableDeclarator:I,WhileStatement:Ct,SpreadElement:vt,RestElement:Ot,TSTypeAliasDeclaration:Jt,TSAsExpression:Rt};exports.getExpressionPrecedence=S;exports.isPrimaryOperand=b;exports.mixesCoalesce=A;exports.needsParens=B;exports.print=r;exports.printJson=m;exports.printWithProfile=W;exports.unaryLike=w;
|
package/dist/index.d.cts
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { BaseNode, TSLite } from '@tslite/core';
|
|
2
|
-
import { CapabilityProfile } from '@tslite/capability';
|
|
3
|
-
|
|
4
|
-
type PrintInput = BaseNode | BaseNode[] | (BaseNode | null)[] | null | undefined;
|
|
5
|
-
declare const print: (node: PrintInput) => string;
|
|
6
|
-
/**
|
|
7
|
-
* Printer **sob-contrato** (D37): emite só o que o `profile` permite e **recusa o
|
|
8
|
-
* resto** (lança `node-not-allowed`). É o limite hard do lado JIT — simétrico ao
|
|
9
|
-
* `evaluate(ast, env, { profile })` do interpret. O `print` padrão (standalone)
|
|
10
|
-
* segue emitindo qualquer nó.
|
|
11
|
-
*/
|
|
12
|
-
declare const printWithProfile: (ast: PrintInput, profile: CapabilityProfile) => string;
|
|
13
|
-
/**
|
|
14
|
-
* Uma expressão é PRIMÁRIA em posição de membro/callee? (isto é: reparsa certo
|
|
15
|
-
* ali, sem parênteses)
|
|
16
|
-
*
|
|
17
|
-
* **Fonte única.** O `@tslite/format` faz a mesma pergunta ao imprimir a callee
|
|
18
|
-
* de uma chamada, e derivá-la duas vezes já custou um defeito: o formatador
|
|
19
|
-
* emitia `() => { … }()`, que o TSLite reparsa mas o **TypeScript recusa** — e a
|
|
20
|
-
* promessa da plataforma é ser um subset PURO de TS.
|
|
21
|
-
*/
|
|
22
|
-
declare function isPrimaryOperand(node: BaseNode): boolean;
|
|
23
|
-
/** Operando que começa com unário/`await` (à esquerda de `**` exige parênteses). */
|
|
24
|
-
declare const unaryLike: (node: BaseNode) => boolean;
|
|
25
|
-
declare const mixesCoalesce: (parentOp: string, child: BaseNode) => boolean;
|
|
26
|
-
/**
|
|
27
|
-
* Returns the operator precedence of an expression node.
|
|
28
|
-
* Higher value = binds tighter. Returns Infinity for atoms (Identifier, Literal, etc).
|
|
29
|
-
*/
|
|
30
|
-
/** A precedência efetiva de uma expressão (erasure de `as`); `Infinity` = primária. */
|
|
31
|
-
declare const getExpressionPrecedence: (node: BaseNode) => number;
|
|
32
|
-
/**
|
|
33
|
-
* Wraps a child node in parentheses when its precedence is lower than
|
|
34
|
-
* the parent's, respecting left/right associativity rules.
|
|
35
|
-
*
|
|
36
|
-
* For left-associative operators (most):
|
|
37
|
-
* - left child: parens when childPrec < parentPrec
|
|
38
|
-
* - right child: parens when childPrec <= parentPrec
|
|
39
|
-
*
|
|
40
|
-
* For right-associative operators (**):
|
|
41
|
-
* - left child: parens when childPrec <= parentPrec
|
|
42
|
-
* - right child: parens when childPrec < parentPrec
|
|
43
|
-
*/
|
|
44
|
-
/**
|
|
45
|
-
* A DECISÃO de parentizar um operando pela precedência — exportada para quem
|
|
46
|
-
* imprime por outra via (o `@tslite/emit` renderiza `Doc`, não texto) tomar a
|
|
47
|
-
* mesma decisão, em vez de manter uma segunda máquina de precedência.
|
|
48
|
-
*/
|
|
49
|
-
declare const needsParens: (node: BaseNode, parentPrec: number, isRight: boolean, rightAssociative?: boolean) => boolean;
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Prints the hybrid JSON form (a value with `#expr` islands) as JS source.
|
|
53
|
-
*
|
|
54
|
-
* Static data is emitted as an object/array literal; each `#expr` island is
|
|
55
|
-
* handed back to `print()` — the same `#expr` boundary the type layer walks.
|
|
56
|
-
*
|
|
57
|
-
* ```ts
|
|
58
|
-
* printJson({ name: "John", init: { "#expr": "CallExpression", ... } })
|
|
59
|
-
* // '{ name: "John", init: setup() }'
|
|
60
|
-
* ```
|
|
61
|
-
*/
|
|
62
|
-
declare function printJson(node: TSLite): string;
|
|
63
|
-
|
|
64
|
-
export { getExpressionPrecedence, isPrimaryOperand, mixesCoalesce, needsParens, print, printJson, printWithProfile, unaryLike };
|