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

Update to support prettier 3.0 #2157

Merged
merged 30 commits into from
Aug 4, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
6055a9a
Update to support prettier 3.0.0
timotheeguerin Jul 7, 2023
2f15150
.
timotheeguerin Jul 7, 2023
0cd428c
Fix perf issue
timotheeguerin Jul 7, 2023
0875f97
.
timotheeguerin Jul 7, 2023
d5acc9d
format
timotheeguerin Jul 7, 2023
14cbea3
Fix tests
timotheeguerin Jul 7, 2023
896e464
.
timotheeguerin Jul 7, 2023
ebe2b5c
Fix broken ide
timotheeguerin Jul 7, 2023
aac2398
Merge branch 'main' into prettier-3.0.0
timotheeguerin Jul 7, 2023
e42d28d
tweaks
timotheeguerin Jul 7, 2023
aae7a34
Merge
timotheeguerin Jul 7, 2023
2e59d71
Add test to make sure it works with prettier 2.0
timotheeguerin Jul 7, 2023
0323455
.
timotheeguerin Jul 7, 2023
f4e1c98
wip
timotheeguerin Jul 8, 2023
846a239
wip
timotheeguerin Jul 8, 2023
2c2f0e2
works now
timotheeguerin Jul 8, 2023
df53192
regen third party
timotheeguerin Jul 8, 2023
6a50639
fix migration package
timotheeguerin Jul 10, 2023
2a01160
Deal with crlf in licenses
timotheeguerin Jul 10, 2023
9e9f989
Merge branch 'main' into prettier-3.0.0
timotheeguerin Jul 10, 2023
0d4841a
Merge with main
timotheeguerin Jul 24, 2023
76762ac
Merge branch 'main' of https://github.com/Microsoft/typespec into pre…
timotheeguerin Jul 24, 2023
7ab5a60
Changelog
timotheeguerin Jul 24, 2023
8cee8e8
Merge branch 'main' into prettier-3.0.0
timotheeguerin Jul 27, 2023
9ca4a58
Merge branch 'main' into prettier-3.0.0
timotheeguerin Jul 31, 2023
cfd1491
Merge with main
timotheeguerin Aug 3, 2023
9241dc6
update to 3.0.1 and remove temp types
timotheeguerin Aug 3, 2023
e31df68
format
timotheeguerin Aug 3, 2023
a1b1fb8
Fix eslint
timotheeguerin Aug 3, 2023
fb7ef1a
Changelog
timotheeguerin Aug 3, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 25 additions & 19 deletions common/config/rush/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/compiler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
"globby": "~13.1.1",
"js-yaml": "~4.1.0",
"mustache": "~4.2.0",
"prettier": "~2.8.7",
"prettier": "~3.0.0",
"prompts": "~2.4.1",
"vscode-languageserver": "~8.1.0",
"vscode-languageserver-textdocument": "~1.0.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler/src/core/formatter-fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export async function findUnformattedTypeSpecFiles(
export async function formatTypeSpecFile(filename: string) {
const content = await readFile(filename, "utf-8");
const prettierConfig = await prettier.resolveConfig(filename);
const formattedContent = formatTypeSpec(content, prettierConfig ?? {});
const formattedContent = await formatTypeSpec(content, prettierConfig ?? {});
await writeFile(filename, formattedContent);
}

Expand Down
4 changes: 2 additions & 2 deletions packages/compiler/src/core/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import prettier from "prettier";
import * as typespecPrettierPlugin from "../formatter/index.js";
export { printId as formatIdentifier } from "../formatter/print/printer.js";

export function formatTypeSpec(code: string, prettierConfig?: prettier.Options): string {
const output = prettier.format(code, {
export async function formatTypeSpec(code: string, prettierConfig?: prettier.Options): Promise<string> {
const output = await prettier.format(code, {
...prettierConfig,
parser: "typespec",
plugins: [typespecPrettierPlugin],
Expand Down
6 changes: 2 additions & 4 deletions packages/compiler/src/formatter/parser.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { Parser, ParserOptions } from "prettier";
import { ParserOptions } from "prettier";
import { getSourceLocation } from "../core/diagnostics.js";
import { parse as typespecParse, visitChildren } from "../core/parser.js";
import { Diagnostic, Node, SyntaxKind, TypeSpecScriptNode } from "../core/types.js";
import { mutate } from "../core/util.js";

export function parse(
text: string,
parsers: { [parserName: string]: Parser },
opts: ParserOptions & { parentParser?: string }
text: string, options: ParserOptions<any>,
): TypeSpecScriptNode {
const result = typespecParse(text, { comments: true, docs: true });

Expand Down
86 changes: 86 additions & 0 deletions packages/compiler/src/formatter/print/prettier-ast-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// --------------------------------------------------
// Unfortunately have to make our own `AstPath` as prettier types have issue with readonly Array.
// --------------------------------------------------
export type AST = any;

// The type of elements that make up the given array T.
type ArrayElement<T> = T extends Array<infer E> ? E : never;


// Effectively performing T[P], except that it's telling TypeScript that it's
// safe to do this for tuples, arrays, or objects.
type IndexValue<T, P> = T extends readonly any[]
? P extends number
? T[P]
: never
: P extends keyof T
? T[P]
: never;


type CallProperties<T> = keyof T;
type IterProperties<T> = keyof T;

type CallCallback<T, U> = (path: AstPath<T>, index: number, value: any) => U;
type EachCallback<T> = (path: AstPath<ArrayElement<T>>, index: number, value: any) => void;
type MapCallback<T, U> = (path: AstPath<ArrayElement<T>>, index: number, value: any) => U;

// https://github.com/prettier/prettier/blob/next/src/common/ast-path.js
export interface AstPath<T = any> {
get key(): string | null;
get index(): number | null;
get node(): T;
get parent(): T | null;
get grandparent(): T | null;
get isInArray(): boolean;
get siblings(): T[] | null;
get next(): T | null;
get previous(): T | null;
get isFirst(): boolean;
get isLast(): boolean;
get isRoot(): boolean;
get root(): T;
get ancestors(): T[];

stack: T[];

callParent<U>(callback: (path: this) => U, count?: number): U;

/**
* @deprecated Please use `AstPath#key` or `AstPath#index`
*/
getName(): PropertyKey | null;

/**
* @deprecated Please use `AstPath#node` or `AstPath#siblings`
*/
getValue(): T;

getNode(count?: number): T | null;

getParentNode(count?: number): T | null;

match(
...predicates: Array<(node: any, name: string | null, number: number | null) => boolean>
): boolean;

// For each of the tree walk functions (call, each, and map) this provides 5
// strict type signatures, along with a fallback at the end if you end up
// calling more than 5 properties deep. This helps a lot with typing because
// for the majority of cases you're calling fewer than 5 properties, so the
// tree walk functions have a clearer understanding of what you're doing.
//
// Note that resolving these types is somewhat complicated, and it wasn't
// even supported until TypeScript 4.2 (before it would just say that the
// type instantiation was excessively deep and possibly infinite).

call<U>(callback: CallCallback<T, U>): U;
call<U, P1 extends CallProperties<T>>(callback: CallCallback<IndexValue<T, P1>, U>, prop1: P1): U;

each(callback: EachCallback<T>): void;
each<P1 extends IterProperties<T>>(callback: EachCallback<IndexValue<T, P1>>, prop1: P1): void;


map<U>(callback: MapCallback<T, U>): U[];
map<U, P1 extends IterProperties<T>>(callback: MapCallback<IndexValue<T, P1>, U>, prop1: P1): U[];
}
25 changes: 15 additions & 10 deletions packages/compiler/src/formatter/print/printer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import prettier, { AstPath, Doc, Printer } from "prettier";
// TODO revisit `getValue` is deprecated.
/* eslint-disable deprecation/deprecation */
import prettier, { Doc, Printer } from "prettier";
import { isIdentifierContinue, isIdentifierStart, utf16CodeUnits } from "../../core/charcode.js";
import { compilerAssert } from "../../core/diagnostics.js";
import { Keywords } from "../../core/scanner.js";
Expand All @@ -13,8 +15,10 @@ import {
DecoratorExpressionNode,
DirectiveExpressionNode,
DocNode,
ProjectionDecoratorReferenceExpressionNode,
EnumMemberNode,
EnumSpreadMemberNode,
UsingStatementNode,
EnumStatementNode,
FunctionDeclarationStatementNode,
FunctionParameterNode,
Expand Down Expand Up @@ -70,12 +74,13 @@ import {
import { FlattenedNamespaceStatementNode } from "../types.js";
import { commentHandler } from "./comment-handler.js";
import { needsParens } from "./needs-parens.js";
import { AstPath } from "./prettier-ast-path.js";
import { DecorableNode, PrettierChildPrint, TypeSpecPrettierOptions } from "./types.js";

const { align, breakParent, group, hardline, ifBreak, indent, join, line, softline } =
prettier.doc.builders;

const { isNextLineEmpty } = prettier.util;
const { isNextLineEmpty } = prettier.util as any;
timotheeguerin marked this conversation as resolved.
Show resolved Hide resolved

/**
* If the decorators for that node should try to be kept inline.
Expand Down Expand Up @@ -135,7 +140,7 @@ export function printNode(
case SyntaxKind.ImportStatement:
return [`import "${node.path.value}";`];
case SyntaxKind.UsingStatement:
return [`using `, path.call(print, "name"), `;`];
return [`using `, (path as AstPath<UsingStatementNode>).call(print, "name"), `;`];
case SyntaxKind.OperationStatement:
return printOperationStatement(path as AstPath<OperationStatementNode>, options, print);
case SyntaxKind.OperationSignatureDeclaration:
Expand Down Expand Up @@ -333,7 +338,7 @@ export function printNode(
case SyntaxKind.ProjectionTupleExpression:
return printTuple(path as AstPath<ProjectionTupleExpressionNode>, options, print);
case SyntaxKind.ProjectionDecoratorReferenceExpression:
return path.call(print, "target");
return (path as AstPath<ProjectionDecoratorReferenceExpressionNode>).call(print, "target");
case SyntaxKind.Return:
return printReturnExpression(path as AstPath<ReturnExpressionNode>, options, print);
case SyntaxKind.Doc:
Expand Down Expand Up @@ -401,9 +406,9 @@ function printTemplateParameters<T extends Node>(

const shouldHug = (args as any).length === 1;
if (shouldHug) {
return ["<", join(", ", path.map(print, propertyName)), ">"];
return ["<", join(", ", path.map(print, propertyName as any)), ">"];
} else {
const body = indent([softline, join([", ", softline], path.map(print, propertyName))]);
const body = indent([softline, join([", ", softline], path.map(print, propertyName as any))]);
return group(["<", body, softline, ">"]);
}
}
Expand Down Expand Up @@ -855,7 +860,7 @@ function printDanglingComments(
return "";
}
path.each((commentPath) => {
const comment = commentPath.getValue();
const comment: any = commentPath.getValue();
if (!comment.leading && !comment.trailing) {
parts.push(printComment(path, options));
}
Expand Down Expand Up @@ -1289,7 +1294,7 @@ export function printStatementSequence<T extends Node>(
parts.push(hardline);
}
}
}, property);
}, property as any);

return parts;
}
Expand Down Expand Up @@ -1558,7 +1563,7 @@ function printProjectionExpressionStatements<T extends Node>(
parts.push(hardline);
}
}
}, key);
}, key as any);
return parts;
}

Expand Down Expand Up @@ -1689,7 +1694,7 @@ function printItemList<T extends Node>(
print: PrettierChildPrint,
key: keyof T
) {
return join(", ", path.map(print, key));
return join(", ", path.map(print, key as any));
}

/**
Expand Down
7 changes: 4 additions & 3 deletions packages/compiler/src/formatter/print/types.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { AstPath, Doc, ParserOptions } from "prettier";
import { DecoratorExpressionNode, Node } from "../../core/types.js";
import { Doc, ParserOptions } from "prettier";
import { DecoratorExpressionNode } from "../../core/types.js";

export interface TypeSpecPrettierOptions extends ParserOptions {}

export type PrettierChildPrint = (path: AstPath<Node>, index?: number) => Doc;
// export type PrettierChildPrint = (path: AstPath<Node>, index?: number) => Doc;
export type PrettierChildPrint = (...args: any) => Doc;

export interface DecorableNode {
decorators: readonly DecoratorExpressionNode[];
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler/src/init/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ async function writeMain(host: CompilerHost, config: ScaffoldingConfig) {
const lines = [...config.libraries.map((x) => `import "${x}";`), ""];
const content = lines.join("\n");

return host.writeFile(joinPaths(config.directory, "main.tsp"), formatTypeSpec(content));
return host.writeFile(joinPaths(config.directory, "main.tsp"), await formatTypeSpec(content));
}

async function writeFiles(host: CompilerHost, config: ScaffoldingConfig) {
Expand Down
Loading