-
Notifications
You must be signed in to change notification settings - Fork 113
/
clangd-context.ts
209 lines (193 loc) · 8.87 KB
/
clangd-context.ts
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import * as vscode from 'vscode';
import * as vscodelc from 'vscode-languageclient/node';
import * as ast from './ast';
import * as config from './config';
import * as configFileWatcher from './config-file-watcher';
import * as fileStatus from './file-status';
import * as inactiveRegions from './inactive-regions';
import * as inlayHints from './inlay-hints';
import * as install from './install';
import * as memoryUsage from './memory-usage';
import * as openConfig from './open-config';
import * as switchSourceHeader from './switch-source-header';
import * as typeHierarchy from './type-hierarchy';
export const clangdDocumentSelector = [
{scheme: 'file', language: 'c'},
{scheme: 'file', language: 'cpp'},
{scheme: 'file', language: 'cuda-cpp'},
{scheme: 'file', language: 'objective-c'},
{scheme: 'file', language: 'objective-cpp'},
];
export function isClangdDocument(document: vscode.TextDocument) {
return vscode.languages.match(clangdDocumentSelector, document);
}
class ClangdLanguageClient extends vscodelc.LanguageClient {
// Override the default implementation for failed requests. The default
// behavior is just to log failures in the output panel, however output panel
// is designed for extension debugging purpose, normal users will not open it,
// thus when the failure occurs, normal users doesn't know that.
//
// For user-interactive operations (e.g. applyFixIt, applyTweaks), we will
// prompt up the failure to users.
handleFailedRequest<T>(type: vscodelc.MessageSignature, error: any,
token: vscode.CancellationToken|undefined,
defaultValue: T): T {
if (error instanceof vscodelc.ResponseError &&
type.method === 'workspace/executeCommand')
vscode.window.showErrorMessage(error.message);
return super.handleFailedRequest(type, token, error, defaultValue);
}
}
class EnableEditsNearCursorFeature implements vscodelc.StaticFeature {
initialize() {}
fillClientCapabilities(capabilities: vscodelc.ClientCapabilities): void {
const extendedCompletionCapabilities: any =
capabilities.textDocument?.completion;
extendedCompletionCapabilities.editsNearCursor = true;
}
getState(): vscodelc.FeatureState { return {kind: 'static'}; }
dispose() {}
}
export class ClangdContext implements vscode.Disposable {
subscriptions: vscode.Disposable[] = [];
client!: ClangdLanguageClient;
async activate(globalStoragePath: string,
outputChannel: vscode.OutputChannel) {
const clangdPath = await install.activate(this, globalStoragePath);
if (!clangdPath)
return;
const clangd: vscodelc.Executable = {
command: clangdPath,
args: await config.get<string[]>('arguments'),
options: {cwd: vscode.workspace.rootPath || process.cwd(), shell: true}
};
const traceFile = config.get<string>('trace');
if (!!traceFile) {
const trace = {CLANGD_TRACE: traceFile};
clangd.options = {env: {...process.env, ...trace}};
}
const serverOptions: vscodelc.ServerOptions = clangd;
const clientOptions: vscodelc.LanguageClientOptions = {
// Register the server for c-family and cuda files.
documentSelector: clangdDocumentSelector,
initializationOptions: {
clangdFileStatus: true,
fallbackFlags: config.get<string[]>('fallbackFlags')
},
outputChannel: outputChannel,
// Do not switch to output window when clangd returns output.
revealOutputChannelOn: vscodelc.RevealOutputChannelOn.Never,
// We hack up the completion items a bit to prevent VSCode from re-ranking
// and throwing away all our delicious signals like type information.
//
// VSCode sorts by (fuzzymatch(prefix, item.filterText), item.sortText)
// By adding the prefix to the beginning of the filterText, we get a
// perfect
// fuzzymatch score for every item.
// The sortText (which reflects clangd ranking) breaks the tie.
// This also prevents VSCode from filtering out any results due to the
// differences in how fuzzy filtering is applies, e.g. enable dot-to-arrow
// fixes in completion.
//
// We also mark the list as incomplete to force retrieving new rankings.
// See https://github.com/microsoft/language-server-protocol/issues/898
middleware: {
provideCompletionItem: async (document, position, context, token,
next) => {
if (!config.get<boolean>('enableCodeCompletion'))
return new vscode.CompletionList([], /*isIncomplete=*/ false);
let list = await next(document, position, context, token);
if (!config.get<boolean>('serverCompletionRanking'))
return list;
let items = (Array.isArray(list) ? list : list!.items).map(item => {
// Gets the prefix used by VSCode when doing fuzzymatch.
let prefix = document.getText(
new vscode.Range((item.range as vscode.Range).start, position))
if (prefix)
item.filterText = prefix + '_' + item.filterText;
// Workaround for https://github.com/clangd/vscode-clangd/issues/357
// clangd's used of commit-characters was well-intentioned, but
// overall UX is poor. Due to vscode-languageclient bugs, we didn't
// notice until the behavior was in several releases, so we need
// to override it on the client.
item.commitCharacters = [];
// VSCode won't automatically trigger signature help when entering
// a placeholder, e.g. if the completion inserted brackets and
// placed the cursor inside them.
// https://github.com/microsoft/vscode/issues/164310
// They say a plugin should trigger this, but LSP has no mechanism.
// https://github.com/microsoft/language-server-protocol/issues/274
// (This workaround is incomplete, and only helps the first param).
if (item.insertText instanceof vscode.SnippetString &&
!item.command &&
item.insertText.value.match(/[([{<,] ?\$\{?[01]\D/))
item.command = {
title: 'Signature help',
command: 'editor.action.triggerParameterHints'
};
return item;
})
return new vscode.CompletionList(items, /*isIncomplete=*/ true);
},
provideHover: async (document, position, token, next) => {
if (!config.get<boolean>('enableHover'))
return null;
return next(document, position, token);
},
// VSCode applies fuzzy match only on the symbol name, thus it throws
// away all results if query token is a prefix qualified name.
// By adding the containerName to the symbol name, it prevents VSCode
// from filtering out any results, e.g. enable workspaceSymbols for
// qualified symbols.
provideWorkspaceSymbols: async (query, token, next) => {
let symbols = await next(query, token);
return symbols?.map(symbol => {
// Only make this adjustment if the query is in fact qualified.
// Otherwise, we get a suboptimal ordering of results because
// including the name's qualifier (if it has one) in symbol.name
// means vscode can no longer tell apart exact matches from
// partial matches.
if (query.includes('::')) {
if (symbol.containerName)
symbol.name = `${symbol.containerName}::${symbol.name}`;
// Clean the containerName to avoid displaying it twice.
symbol.containerName = '';
}
return symbol;
})
},
},
};
this.client = new ClangdLanguageClient('Clang Language Server',
serverOptions, clientOptions);
this.client.clientOptions.errorHandler =
this.client.createDefaultErrorHandler(
// max restart count
config.get<boolean>('restartAfterCrash') ? /*default*/ 4 : 0);
this.client.registerFeature(new EnableEditsNearCursorFeature);
typeHierarchy.activate(this);
inlayHints.activate(this);
memoryUsage.activate(this);
ast.activate(this);
openConfig.activate(this);
inactiveRegions.activate(this);
this.client.start();
console.log('Clang Language Server is now active!');
fileStatus.activate(this);
switchSourceHeader.activate(this);
configFileWatcher.activate(this);
}
get visibleClangdEditors(): vscode.TextEditor[] {
return vscode.window.visibleTextEditors.filter(
(e) => isClangdDocument(e.document));
}
clientIsStarting() {
return this.client && this.client.state == vscodelc.State.Starting;
}
dispose() {
this.subscriptions.forEach((d) => { d.dispose(); });
if (this.client)
this.client.stop();
this.subscriptions = []
}
}