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

Add support for inlay hints #265

Merged
merged 4 commits into from
May 12, 2022
Merged
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
6 changes: 6 additions & 0 deletions .changeset/quiet-olives-appear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@astrojs/language-server': minor
'astro-vscode': minor
---

Updated language server to latest version of LSP, added support for Inlay Hints
8 changes: 4 additions & 4 deletions packages/language-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@
"@vscode/emmet-helper": "^2.8.4",
"lodash": "^4.17.21",
"source-map": "^0.7.3",
"typescript": "~4.6.2",
"typescript": "~4.6.4",
"vscode-css-languageservice": "^5.1.13",
"vscode-html-languageservice": "^4.2.2",
"vscode-languageserver": "7.0.0",
"vscode-languageserver-protocol": "^3.16.0",
"vscode-languageserver": "^8.0.0",
"vscode-languageserver-protocol": "^3.17.0",
"vscode-languageserver-textdocument": "^1.0.1",
"vscode-languageserver-types": "^3.16.0",
"vscode-languageserver-types": "^3.17.0",
"vscode-uri": "^3.0.2"
},
"devDependencies": {
Expand Down
53 changes: 49 additions & 4 deletions packages/language-server/src/core/config/ConfigManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ import { VSCodeEmmetConfig } from '@vscode/emmet-helper';
import { LSConfig, LSCSSConfig, LSHTMLConfig, LSTypescriptConfig } from './interfaces';
import { Connection, DidChangeConfigurationParams } from 'vscode-languageserver';
import { TextDocument } from 'vscode-languageserver-textdocument';
import { FormatCodeSettings, SemicolonPreference, TsConfigSourceFile, UserPreferences } from 'typescript';
import {
FormatCodeSettings,
InlayHintsOptions,
SemicolonPreference,
TsConfigSourceFile,
UserPreferences,
} from 'typescript';

export const defaultLSConfig: LSConfig = {
typescript: {
Expand Down Expand Up @@ -145,6 +151,25 @@ export class ConfigManager {
};
}

async getTSInlayHintsPreferences(document: TextDocument): Promise<InlayHintsOptions> {
const config = (await this.getConfig<any>('typescript', document.uri)) ?? {};

const tsPreferences = this.getTSPreferences(document);

return {
...tsPreferences,
includeInlayParameterNameHints: getInlayParameterNameHintsPreference(config),
includeInlayParameterNameHintsWhenArgumentMatchesName: !(
config.inlayHints?.parameterNames?.suppressWhenArgumentMatchesName ?? true
),
includeInlayFunctionParameterTypeHints: config.inlayHints?.parameterTypes?.enabled ?? false,
includeInlayVariableTypeHints: config.inlayHints?.variableTypes?.enabled ?? false,
includeInlayPropertyDeclarationTypeHints: config.inlayHints?.propertyDeclarationTypes?.enabled ?? false,
includeInlayFunctionLikeReturnTypeHints: config.inlayHints?.functionLikeReturnTypes?.enabled ?? false,
includeInlayEnumMemberValueHints: config.inlayHints?.enumMemberValues?.enabled ?? false,
};
}

/**
* Return true if a plugin and an optional feature is enabled
*/
Expand All @@ -160,10 +185,17 @@ export class ConfigManager {

/**
* Updating the global config should only be done in cases where the client doesn't support `workspace/configuration`
* or inside of tests
* or inside of tests.
*
* The `outsideAstro` parameter can be set to true to change configurations in the global scope.
* For example, to change TypeScript settings
*/
updateGlobalConfig(config: DeepPartial<LSConfig>) {
this.globalConfig.astro = merge({}, defaultLSConfig, this.globalConfig.astro, config);
updateGlobalConfig(config: DeepPartial<LSConfig> | any, outsideAstro?: boolean) {
if (outsideAstro) {
this.globalConfig = merge({}, this.globalConfig, config);
} else {
this.globalConfig.astro = merge({}, defaultLSConfig, this.globalConfig.astro, config);
}
}
}

Expand Down Expand Up @@ -203,3 +235,16 @@ function getImportModuleSpecifierEndingPreference(config: any) {
return 'auto';
}
}

function getInlayParameterNameHintsPreference(config: any) {
switch (config.inlayHints?.parameterNames?.enabled) {
case 'none':
return 'none';
case 'literals':
return 'literals';
case 'all':
return 'all';
default:
return undefined;
}
}
11 changes: 11 additions & 0 deletions packages/language-server/src/plugins/PluginHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
SemanticTokens,
CodeActionContext,
CodeAction,
InlayHint,
} from 'vscode-languageserver';
import type { AppCompletionItem, Plugin, LSProvider } from './interfaces';
import { flatten } from 'lodash';
Expand Down Expand Up @@ -224,6 +225,16 @@ export class PluginHost {
return flatten(await this.execute<ColorInformation[]>('getDocumentColors', [document], ExecuteMode.Collect));
}

async getInlayHints(
textDocument: TextDocumentIdentifier,
range: Range,
cancellationToken: CancellationToken
): Promise<InlayHint[]> {
const document = this.getDocument(textDocument.uri);

return flatten(await this.execute<InlayHint[]>('getInlayHints', [document, range], ExecuteMode.FirstNonNull));
}

async getColorPresentations(
textDocument: TextDocumentIdentifier,
range: Range,
Expand Down
6 changes: 6 additions & 0 deletions packages/language-server/src/plugins/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
FoldingRange,
FormattingOptions,
Hover,
InlayHint,
LinkedEditingRanges,
Position,
Range,
Expand Down Expand Up @@ -103,6 +104,10 @@ export interface UpdateImportsProvider {
updateImports(fileRename: FileRename): Resolvable<WorkspaceEdit | null>;
}

export interface InlayHintsProvider {
getInlayHints(document: TextDocument, range: Range): Resolvable<InlayHint[]>;
}

export interface RenameProvider {
rename(document: TextDocument, position: Position, newName: string): Resolvable<WorkspaceEdit | null>;
prepareRename(document: TextDocument, position: Position): Resolvable<Range | null>;
Expand Down Expand Up @@ -164,6 +169,7 @@ type ProviderBase = DiagnosticsProvider &
SelectionRangeProvider &
OnWatchFileChangesProvider &
LinkedEditingRangesProvider &
InlayHintsProvider &
UpdateNonAstroFile;

export type LSProvider = ProviderBase;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
FileChangeType,
FoldingRange,
Hover,
InlayHint,
Position,
Range,
SemanticTokens,
Expand All @@ -32,6 +33,7 @@ import { SemanticTokensProviderImpl } from './features/SemanticTokenProvider';
import { FoldingRangesProviderImpl } from './features/FoldingRangesProvider';
import { CodeActionsProviderImpl } from './features/CodeActionsProvider';
import { DefinitionsProviderImpl } from './features/DefinitionsProvider';
import { InlayHintsProviderImpl } from './features/InlayHintsProvider';

export class TypeScriptPlugin implements Plugin {
__name = 'typescript';
Expand All @@ -46,6 +48,7 @@ export class TypeScriptPlugin implements Plugin {
private readonly signatureHelpProvider: SignatureHelpProviderImpl;
private readonly diagnosticsProvider: DiagnosticsProviderImpl;
private readonly documentSymbolsProvider: DocumentSymbolsProviderImpl;
private readonly inlayHintsProvider: InlayHintsProviderImpl;
private readonly semanticTokensProvider: SemanticTokensProviderImpl;
private readonly foldingRangesProvider: FoldingRangesProviderImpl;

Expand All @@ -61,6 +64,7 @@ export class TypeScriptPlugin implements Plugin {
this.diagnosticsProvider = new DiagnosticsProviderImpl(this.languageServiceManager);
this.documentSymbolsProvider = new DocumentSymbolsProviderImpl(this.languageServiceManager);
this.semanticTokensProvider = new SemanticTokensProviderImpl(this.languageServiceManager);
this.inlayHintsProvider = new InlayHintsProviderImpl(this.languageServiceManager, this.configManager);
this.foldingRangesProvider = new FoldingRangesProviderImpl(this.languageServiceManager);
}

Expand Down Expand Up @@ -169,6 +173,10 @@ export class TypeScriptPlugin implements Plugin {
return this.completionProvider.resolveCompletion(document, completionItem, cancellationToken);
}

async getInlayHints(document: AstroDocument, range: Range): Promise<InlayHint[]> {
return this.inlayHintsProvider.getInlayHints(document, range);
}

async getDefinitions(document: AstroDocument, position: Position): Promise<DefinitionLink[]> {
return this.definitionsProvider.getDefinitions(document, position);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,10 @@ export class CompletionsProviderImpl implements CompletionsProvider<CompletionIt
if (detail) {
const { detail: itemDetail, documentation: itemDocumentation } = this.getCompletionDocument(detail);

if (data.originalItem.source) {
item.labelDetails = { description: data.originalItem.source };
}

Comment on lines +258 to +261
Copy link
Member Author

Choose a reason for hiding this comment

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

Just a quick fix since we now support label details with the latest version of LSP, we also need to set it when resolving imports otherwise the resolved import label details will be empty

item.detail = itemDetail;
item.documentation = itemDocumentation;
}
Expand Down Expand Up @@ -343,9 +347,8 @@ export class CompletionsProviderImpl implements CompletionsProvider<CompletionIt
}
}

// Label details are currently unsupported, however, they'll be supported in the next version of LSP
if (comp.sourceDisplay) {
(item as any).labelDetails = { description: ts.displayPartsToString(comp.sourceDisplay) };
item.labelDetails = { description: ts.displayPartsToString(comp.sourceDisplay) };
}

item.commitCharacters = getCommitCharactersForScriptElement(comp.kind);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { InlayHint } from 'vscode-languageserver';
import { AstroDocument } from '../../../core/documents';
import { InlayHintsProvider } from '../../interfaces';
import { LanguageServiceManager } from '../LanguageServiceManager';
import { toVirtualAstroFilePath } from '../utils';
import { InlayHintKind, Range } from 'vscode-languageserver-types';
import ts from 'typescript';
import { ConfigManager } from '../../../core/config';

export class InlayHintsProviderImpl implements InlayHintsProvider {
constructor(private languageServiceManager: LanguageServiceManager, private configManager: ConfigManager) {}

async getInlayHints(document: AstroDocument, range: Range): Promise<InlayHint[]> {
const { lang, tsDoc } = await this.languageServiceManager.getLSAndTSDoc(document);

const filePath = toVirtualAstroFilePath(tsDoc.filePath);
const fragment = await tsDoc.createFragment();

const start = fragment.offsetAt(fragment.getGeneratedPosition(range.start));
const end = fragment.offsetAt(fragment.getGeneratedPosition(range.end));

const tsPreferences = await this.configManager.getTSInlayHintsPreferences(document);

const inlayHints = lang.provideInlayHints(filePath, { start, length: end - start }, tsPreferences);

return inlayHints.map((hint) => {
const result = InlayHint.create(
fragment.getOriginalPosition(fragment.positionAt(hint.position)),
hint.text,
hint.kind === ts.InlayHintKind.Type
? InlayHintKind.Type
: hint.kind === ts.InlayHintKind.Parameter
? InlayHintKind.Parameter
: undefined
);

result.paddingLeft = hint.whitespaceBefore;
result.paddingRight = hint.whitespaceAfter;

return result;
});
}
}
6 changes: 6 additions & 0 deletions packages/language-server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as vscode from 'vscode-languageserver';
import {
CodeActionKind,
DidChangeConfigurationNotification,
InlayHintRequest,
MessageType,
SemanticTokensRangeRequest,
SemanticTokensRequest,
Expand Down Expand Up @@ -134,6 +135,7 @@ export function startLanguageServer(connection: vscode.Connection) {
range: true,
full: true,
},
inlayHintProvider: true,
signatureHelpProvider: {
triggerCharacters: ['(', ',', '<'],
retriggerCharacters: [')'],
Expand Down Expand Up @@ -229,6 +231,10 @@ export function startLanguageServer(connection: vscode.Connection) {
pluginHost.getColorPresentations(params.textDocument, params.range, params.color)
);

connection.onRequest(InlayHintRequest.type, (params: vscode.InlayHintParams, cancellationToken) =>
pluginHost.getInlayHints(params.textDocument, params.range, cancellationToken)
);

connection.onRequest(TagCloseRequest, (evt: any) => pluginHost.doTagComplete(evt.textDocument, evt.position));
connection.onSignatureHelp((evt, cancellationToken) =>
pluginHost.getSignatureHelp(evt.textDocument, evt.position, evt.context, cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,31 @@ describe('TypeScript Plugin', () => {
});
});

describe('provide inlay hints', async () => {
it('return inlay hints', async () => {
const { plugin, document, configManager } = setup('inlayHints/basic.astro');

configManager.updateGlobalConfig(
{
typescript: {
inlayHints: {
parameterNames: {
enabled: 'all',
},
parameterTypes: {
enabled: 'all',
},
},
},
},
true
);

const inlayHints = await plugin.getInlayHints(document, Range.create(0, 0, 7, 0));
expect(inlayHints).to.not.be.empty;
});
});

describe('provide folding ranges', async () => {
it('return folding ranges', async () => {
const { plugin, document } = setup('foldingRanges/frontmatter.astro');
Expand Down
Loading