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

[Not Ready] [typespec-vscode] Typespec vscode localization #5466

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import { isLineBreak, isWhiteSpaceSingleLine } from "../charcode.js";
import { defineCodeFix, getSourceLocation } from "../diagnostics.js";
import type { CodeFixEdit, DiagnosticTarget, SourceLocation } from "../types.js";

export function createTripleQuoteIndentCodeFix(diagnosticTarget: DiagnosticTarget) {
return defineCodeFix({
id: "triple-quote-indent",
label: "Format triple-quote-indent",
fix: (context) => {
const result: CodeFixEdit[] = [];

const location = getSourceLocation(diagnosticTarget);
const { startPos: startPosArr, indent } = findStartPositionAndIndent(location);
startPosArr.map((pos) => {
const updatedLocation = { ...location, pos };
result.push(context.prependText(updatedLocation, indent));
});

return result;
},
});
}

function isNoNewlineStartTripleQuote(start: number, end: number, input: string): boolean {
while (start < end && isWhiteSpaceSingleLine(input.charCodeAt(start))) {
start++;
}
return !isLineBreak(input.charCodeAt(start));
}

function isNoNewlineEndTripleQuote(start: number, end: number, input: string): boolean {
while (end > start && isWhiteSpaceSingleLine(input.charCodeAt(end - 1))) {
end--;
}
return !isLineBreak(input.charCodeAt(end - 1));
}

function getSpaceNumbBetweenStartPosAndVal(start: number, end: number, input: string): number {
while (start < end && isWhiteSpaceSingleLine(input.charCodeAt(start))) {
start++;
}
if (isLineBreak(input.charCodeAt(start))) {
start += 2;
}

let spaceNumb = 0;
while (start < end && isWhiteSpaceSingleLine(input.charCodeAt(start))) {
spaceNumb++;
start++;
}
return spaceNumb;
}

function getSpaceNumbBetweenEnterAndEndPos(start: number, end: number, input: string): number {
let spaceNumb = 0;
while (end > start && isWhiteSpaceSingleLine(input.charCodeAt(end - 1))) {
spaceNumb++;
end--;
}
return spaceNumb;
}

function findStartPositionAndIndent(location: SourceLocation): {
startPos: number[];
indent: string;
} {
const text = location.file.text;
const splitOrIndentStr = "\r\n";
const startPos = location.pos;
const endPos = location.end;
const offSet = 3; // The length of `"""`

const noNewlineStart = isNoNewlineStartTripleQuote(startPos + offSet, endPos, text);
const noNewlineEnd = isNoNewlineEndTripleQuote(startPos, endPos - offSet, text);
if (noNewlineStart && noNewlineEnd) {
// eg. `""" one two """`
return { startPos: [startPos + offSet, endPos - offSet], indent: splitOrIndentStr };
} else if (noNewlineStart) {
// eg. `""" one two \r\n"""`
const startSpaceNumb = getSpaceNumbBetweenStartPosAndVal(startPos + offSet, endPos, text);
const endSpaceNumb = getSpaceNumbBetweenEnterAndEndPos(startPos, endPos - offSet, text);

// Only in the case of equals, the `triple-quote-indent` warning will be triggered.
// The `no-new-line-start-triple-quote` warning is triggered when it is greater than
if (startSpaceNumb >= endSpaceNumb) {
return { startPos: [startPos + offSet], indent: splitOrIndentStr };
} else {
return {
startPos: [startPos + offSet],
indent: splitOrIndentStr + " ".repeat(endSpaceNumb - startSpaceNumb),
};
}
} else if (noNewlineEnd) {
// eg. `"""\r\n one two """`
const startSpaceNumb = getSpaceNumbBetweenStartPosAndVal(startPos + offSet, endPos, text);
const endSpaceNumb = getSpaceNumbBetweenEnterAndEndPos(startPos, endPos - offSet, text);
if (startSpaceNumb < endSpaceNumb) {
return {
startPos: [endPos - offSet],
indent: splitOrIndentStr + " ".repeat(startSpaceNumb),
};
} else {
// Detailed description: `no-new-line-start-triple-quote`, `no-new-line-end-triple-quote`
// and `triple-quote-indent` are all warnings about incorrect triple quote values.
// Currently, only `triple-quote-indent` has a quick fix.
// Todo: add codefix for `no-new-line-start-triple-quote` and `no-new-line-end-triple-quote` warning

// It will only warn that the ending """ is not on a new line and will not trigger the triple quote indent warning.
return {
startPos: [endPos - offSet],
indent: splitOrIndentStr + " ".repeat(startSpaceNumb - endSpaceNumb),
};
}
} else {
// eg. `"""\r\none\r\n two\r\n """`
const endSpaceNumb = getSpaceNumbBetweenEnterAndEndPos(startPos, endPos - offSet, text);
const arrIndents: number[] = [];
let start = startPos + offSet;

// Calculate the number of spaces needed to align each line
while (start > 0 && start < endPos) {
const currLineSpaceNumb = getSpaceNumbBetweenStartPosAndVal(start, endPos, text);
arrIndents.push(currLineSpaceNumb);

// If it is 0, the method indexOf cannot get the next `\r\n` position, so add 1
start += currLineSpaceNumb === 0 ? 1 : currLineSpaceNumb;
start = text.indexOf(splitOrIndentStr, start);
}

// Find all the positions of `\r\n` and remove the last one because it is the position of `"""`
const arrStartPos: number[] = [];
start = startPos + offSet;
while (start < endPos) {
start = text.indexOf(splitOrIndentStr, start);
if (start < 0) {
break;
}
start += 2;
if (start < endPos) {
arrStartPos.push(start);
}
}
arrStartPos.pop();

//If minSpaceNumb is larger than endSpaceNumb, codefix will not be generated
const minSpaceNumb = Math.min(...arrIndents);
return {
startPos: arrStartPos,
indent: " ".repeat(endSpaceNumb - minSpaceNumb),
};
}
}
15 changes: 12 additions & 3 deletions packages/compiler/src/core/parser.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { isArray, mutate } from "../utils/misc.js";
import { codePointBefore, isIdentifierContinue, trim } from "./charcode.js";
import { createTripleQuoteIndentCodeFix } from "./compiler-code-fixes/triple-quote-indent.codefix.js";
import { compilerAssert } from "./diagnostics.js";
import { CompilerDiagnostics, createDiagnostic } from "./messages.js";
import {
Token,
TokenDisplay,
TokenFlags,
createScanner,
isComment,
isKeyword,
Expand All @@ -15,6 +13,9 @@ import {
skipContinuousIdentifier,
skipTrivia,
skipTriviaBackward,
Token,
TokenDisplay,
TokenFlags,
} from "./scanner.js";
import {
AliasStatementNode,
Expand Down Expand Up @@ -69,6 +70,7 @@ import {
NeverKeywordNode,
Node,
NodeFlags,
NoTarget,
NumericLiteralNode,
ObjectLiteralNode,
ObjectLiteralPropertyNode,
Expand Down Expand Up @@ -3427,7 +3429,14 @@ function createParser(code: string | SourceFile, options: ParseOptions = {}): Pa
if (diagnostic.severity === "error") {
parseErrorInNextFinishedNode = true;
treePrintable = false;

const code = "triple-quote-indent";
if (diagnostic.target !== NoTarget && diagnostic.code === code) {
mutate(diagnostic).codefixes ??= [];
mutate(diagnostic.codefixes).push(createTripleQuoteIndentCodeFix(diagnostic.target));
}
}

parseDiagnostics.push(diagnostic);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { strictEqual } from "assert";
import { describe, it } from "vitest";
import { createTripleQuoteIndentCodeFix } from "../../../src/core/compiler-code-fixes/triple-quote-indent.codefix.js";
import { SyntaxKind } from "../../../src/index.js";
import { expectCodeFixOnAst } from "../../../src/testing/code-fix-testing.js";

describe("CodeFix: triple-quote-indent", () => {
it("case 1: each triple-quote is on a new line", async () => {
await expectCodeFixOnAst(
`
const a = ┆"""\r\none\r\n two\r\n """;
`,
(node) => {
strictEqual(node.kind, SyntaxKind.StringLiteral);
return createTripleQuoteIndentCodeFix(node);
},
).toChangeTo(`
const a = """\r\n one\r\n two\r\n """;
`);
});

it("case 2: all triple-quote is on one line", async () => {
await expectCodeFixOnAst(
`
const a = ┆""" one\r\n two """;
`,
(node) => {
strictEqual(node.kind, SyntaxKind.StringLiteral);
return createTripleQuoteIndentCodeFix(node);
},
).toChangeTo(`
const a = """\r\n one\r\n two \r\n""";
`);
});

it("case 3: start triple-quote is not on a new line but end one is", async () => {
await expectCodeFixOnAst(
`
const a = ┆"""one\r\n two\r\n """;
`,
(node) => {
strictEqual(node.kind, SyntaxKind.StringLiteral);
return createTripleQuoteIndentCodeFix(node);
},
).toChangeTo(`
const a = """\r\n one\r\n two\r\n """;
`);
});

it("case 4: end triple-quote is not on a new line but start one is", async () => {
await expectCodeFixOnAst(
`
const a = ┆"""\r\n one\r\n two """;
`,
(node) => {
strictEqual(node.kind, SyntaxKind.StringLiteral);
return createTripleQuoteIndentCodeFix(node);
},
).toChangeTo(`
const a = """\r\n one\r\n two \r\n """;
`);
});
});
4 changes: 4 additions & 0 deletions packages/typespec-vscode/l10n/bundle.l10n.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"Launching TypeSpec language service...": "Launching TypeSpec language service...",
"See documentation for \"{0}\"": "See documentation for \"{0}\""
}
9 changes: 7 additions & 2 deletions packages/typespec-vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
],
"type": "module",
"main": "./dist/src/extension.cjs",
"l10n": "./l10n",
"browser": "./dist/src/web/extension.js",
"engines": {
"vscode": "^1.94.0"
Expand Down Expand Up @@ -101,12 +102,12 @@
"commands": [
{
"command": "typespec.restartServer",
"title": "Restart TypeSpec server",
"title": "%typespec.restartServer.title%",
"category": "TypeSpec"
},
{
"command": "typespec.showOutputChannel",
"title": "Show Output Channel",
"title": "%typespec.showOutputChannel.title%",
"category": "TypeSpec"
}
],
Expand Down Expand Up @@ -179,12 +180,16 @@
"@vitest/ui": "^2.1.2",
"@vscode/test-web": "^0.0.62",
"@vscode/vsce": "~3.1.1",
"@vscode/l10n-dev": "^0.0.18",
"c8": "^10.1.2",
"mocha": "^10.7.3",
"rimraf": "~6.0.1",
"rollup": "~4.24.0",
"typescript": "~5.6.3",
"vitest": "^2.1.5",
"vscode-languageclient": "~9.0.1"
},
"dependencies": {
"@vscode/l10n": "^0.0.10"
}
}
4 changes: 4 additions & 0 deletions packages/typespec-vscode/package.nls.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"typespec.restartServer.title": "Restart TypeSpec server",
"typespec.showOutputChannel.title": "Show Output Channel"
}
6 changes: 2 additions & 4 deletions packages/typespec-vscode/src/code-action-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,8 @@ export class TypeSpecCodeActionProvider implements vscode.CodeActionProvider {
codeActionTitle: string,
): vscode.CodeAction {
// 'vscode.CodeActionKind.Empty' does not generate a Code Action menu, You must use 'vscode.CodeActionKind.QuickFix'
const action = new vscode.CodeAction(
`See documentation for "${codeActionTitle}"`,
vscode.CodeActionKind.QuickFix,
);
const codefixTitle = vscode.l10n.t('See documentation for "{0}"', codeActionTitle);
const action = new vscode.CodeAction(codefixTitle, vscode.CodeActionKind.QuickFix);
action.command = {
command: OPEN_URL_COMMAND,
title: diagnostic.message,
Expand Down
3 changes: 2 additions & 1 deletion packages/typespec-vscode/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,10 @@ export async function activate(context: ExtensionContext) {
}),
);

const tipToolTitle = vscode.l10n.t("Launching TypeSpec language service...");
return await vscode.window.withProgress(
{
title: "Launching TypeSpec language service...",
title: tipToolTitle,
location: vscode.ProgressLocation.Notification,
},
async () => {
Expand Down
Loading