Skip to content

feat: add semantic tokens #2191

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
10 changes: 10 additions & 0 deletions client/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,16 @@ export class AngularLanguageClient implements vscode.Disposable {
}
return next(document, context, token);
},
provideDocumentSemanticTokens: async (document, token, next) => {
if (await this.isInAngularProject(document)) {
return next(document, token);
}
},
provideDocumentRangeSemanticTokens: async (document, range, token, next) => {
if (await this.isInAngularProject(document)) {
return next(document, range, token);
}
},
}
};
}
Expand Down
62 changes: 62 additions & 0 deletions server/src/semantic_tokens.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import * as ts from 'typescript/lib/tsserverlibrary';
import * as lsp from 'vscode-languageserver/node';

export enum TokenEncodingConsts {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you mind linking to the TS definitions like you did in angular/angular#60260? Context is pretty lost between the two sometimes

typeOffset = 8,
modifierMask = (1 << typeOffset) - 1,
}

export function getSemanticTokens(
classifications: ts.Classifications, script: ts.server.ScriptInfo): lsp.SemanticTokens {
const spans = classifications.spans;
const builder = new lsp.SemanticTokensBuilder();

for (let i = 0; i < spans.length;) {
const offset = spans[i++];
const length = spans[i++];
const tsClassification = spans[i++];

const tokenType = getTokenTypeFromClassification(tsClassification);
if (tokenType === undefined) {
continue;
}

const tokenModifiers = getTokenModifierFromClassification(tsClassification);

const startPos = script.positionToLineOffset(offset);
startPos.line -= 1;
startPos.offset -= 1;

const endPos = script.positionToLineOffset(offset + length);
endPos.line -= 1;
endPos.offset -= 1;

for (let line = startPos.line; line <= endPos.line; line++) {
const startCharacter = line === startPos.line ? startPos.offset : 0;
const endCharacter =
line === endPos.line ? endPos.offset : script.lineToTextSpan(line - 1).length;
builder.push(line, startCharacter, endCharacter - startCharacter, tokenType, tokenModifiers);
}
}

return builder.build();
}

function getTokenTypeFromClassification(tsClassification: number): number|undefined {
if (tsClassification > TokenEncodingConsts.modifierMask) {
return (tsClassification >> TokenEncodingConsts.typeOffset) - 1;
}
return undefined;
}

function getTokenModifierFromClassification(tsClassification: number) {
return tsClassification & TokenEncodingConsts.modifierMask;
}
Comment on lines +53 to +62
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I wonder if this should really be something that the language service provides since it's so highly dependent on the offset and modifier mask actually matching what the language service returns.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used the integrated Typescript Server from VSCode as a reference. They don't have a "single source of truth" either, most likely because Typescript doesn't include these definitions in the public API.

If I understand you correctly, we could add these methods to @angular/language-service/api, then import them here. On the one hand this probably improves cohesion, on the other hand these bit mask operations will likely not change in the future (unlike the underlying values).

Let me know if I should move this code to the language service!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be good to move them over to @angular/language-service/api. I know that we likely won't change them and once it's working, it'll just be working. But from the standpoint of being able to follow the code, it would be good to not duplicate this and only have a single source of truth. It'd be a lot clearer why these conversions exist and where their sources come from that way.

42 changes: 42 additions & 0 deletions server/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {GetComponentsWithTemplateFile, GetTcbParams, GetTcbRequest, GetTcbRespon
import {readNgCompletionData, tsCompletionEntryToLspCompletionItem} from './completion';
import {tsDiagnosticToLspDiagnostic} from './diagnostic';
import {getHTMLVirtualContent} from './embedded_support';
import {getSemanticTokens} from './semantic_tokens';
import {ServerHost} from './server_host';
import {documentationToMarkdown} from './text_render';
import {filePathToUri, getMappedDefinitionInfo, isConfiguredProject, isDebugMode, lspPositionToTsPosition, lspRangeToTsPositions, MruTracker, tsDisplayPartsToText, tsFileTextChangesToLspWorkspaceEdit, tsTextSpanToLspRange, uriToFilePath} from './utils';
Expand Down Expand Up @@ -217,8 +218,38 @@ export class Session {
conn.onSignatureHelp(p => this.onSignatureHelp(p));
conn.onCodeAction(p => this.onCodeAction(p));
conn.onCodeActionResolve(async p => await this.onCodeActionResolve(p));
conn.onRequest(lsp.SemanticTokensRequest.type, p => this.onSemanticTokensRequest(p));
conn.onRequest(lsp.SemanticTokensRangeRequest.type, p => this.onSemanticTokensRangeRequest(p));
}

private onSemanticTokensRequest(params: lsp.SemanticTokensParams): lsp.SemanticTokens|null {
const lsInfo = this.getLSAndScriptInfo(params.textDocument);
if (lsInfo === null) {
return null;
}
const {languageService, scriptInfo} = lsInfo;
const span = {start: 0, length: scriptInfo.getSnapshot().getLength()};
const classifications = languageService.getEncodedSemanticClassifications(
scriptInfo.fileName, span, ts.SemanticClassificationFormat.TwentyTwenty);
return getSemanticTokens(classifications, scriptInfo);
}

private onSemanticTokensRangeRequest(params: lsp.SemanticTokensRangeParams): lsp.SemanticTokens
|null {
const lsInfo = this.getLSAndScriptInfo(params.textDocument);
if (lsInfo === null) {
return null;
}
const {languageService, scriptInfo} = lsInfo;
const start = lspPositionToTsPosition(lsInfo.scriptInfo, params.range.start);
const end = lspPositionToTsPosition(lsInfo.scriptInfo, params.range.end);
const span = {start, length: end - start};
const classifications = languageService.getEncodedSemanticClassifications(
scriptInfo.fileName, span, ts.SemanticClassificationFormat.TwentyTwenty);
return getSemanticTokens(classifications, scriptInfo);
}


private onCodeAction(params: lsp.CodeActionParams): lsp.CodeAction[]|null {
const filePath = uriToFilePath(params.textDocument.uri);
const lsInfo = this.getLSAndScriptInfo(params.textDocument);
Expand Down Expand Up @@ -809,6 +840,17 @@ export class Session {
// [here](https://github.com/angular/vscode-ng-language-service/issues/1828)
codeActionKinds: [lsp.CodeActionKind.QuickFix],
},
semanticTokensProvider: {
documentSelector: null,
legend: {
tokenTypes: [
'class',
],
tokenModifiers: [],
},
full: true,
range: true
}
},
serverOptions,
};
Expand Down
Loading