-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathambiguity.ts
More file actions
50 lines (46 loc) · 1.5 KB
/
ambiguity.ts
File metadata and controls
50 lines (46 loc) · 1.5 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
import type { Node } from '@babel/types';
import type { AstPath, doc, Printer } from 'prettier';
import { printers as estreePrinters } from 'prettier/plugins/estree.js';
import type { Options } from '../options.js';
import { flattenDoc } from '../utils/doc.js';
const estreePrinter = estreePrinters['estree'] as Printer<Node | undefined>;
/**
* Search next non EmptyStatement node and set current print, so we can fix it
* later if its ambiguous
*/
export function saveCurrentPrintOnSiblingNode(
path: AstPath<Node | undefined>,
printed: doc.builders.Doc[],
): void {
const { index, siblings } = path;
if (index !== null) {
const nextNode = siblings
?.slice(index + 1)
.find((n) => n?.type !== 'EmptyStatement');
if (nextNode) {
nextNode.extra = nextNode.extra || {};
nextNode.extra['prevTemplatePrinted'] = printed;
}
}
}
/** HACK to fix ASI semi-colons. */
export function fixPreviousPrint(
previousTemplatePrinted: doc.builders.Doc[],
path: AstPath<Node | undefined>,
options: Options,
print: (path: AstPath<Node | undefined>) => doc.builders.Doc,
args: unknown,
): void {
const printedSemiFalse = estreePrinter.print(
path,
{ ...options, semi: false },
print,
args,
);
console.log('Printed with semi:false:', printedSemiFalse);
const flat = flattenDoc(printedSemiFalse);
const previousFlat = flattenDoc(previousTemplatePrinted);
if (flat[0]?.startsWith(';') && previousFlat.at(-1) !== ';') {
previousTemplatePrinted.push(';');
}
}