-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathRascalLSPConnection.ts
More file actions
278 lines (242 loc) · 10.5 KB
/
RascalLSPConnection.ts
File metadata and controls
278 lines (242 loc) · 10.5 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/*
* Copyright (c) 2018-2025, NWO-I CWI and Swat.engineering
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import * as net from 'net';
import * as os from 'os';
import * as path from 'path';
import * as vscode from 'vscode';
import { integer, LanguageClient, LanguageClientOptions, ServerOptions, StreamInfo } from 'vscode-languageclient/node';
import { getJavaExecutable } from '../auto-jvm/JavaLookup';
import { RascalFileSystemProvider } from '../fs/RascalFileSystemProviders';
import { VSCodeUriResolverServer } from '../fs/VSCodeURIResolver';
import { JsonParserOutputChannel } from './JsonOutputChannel';
export async function activateLanguageClient(
{ language, title, jarPath, vfsServer, isParametricServer = false, deployMode = true, devPort = -1, dedicated = false, lspArg = "" } :
{language: string, title: string, jarPath: string, vfsServer: VSCodeUriResolverServer, isParametricServer: boolean, deployMode: boolean, devPort: integer, dedicated: boolean, lspArg: string | undefined} )
: Promise<LanguageClient> {
const logger = new JsonParserOutputChannel(title);
const serverOptions: ServerOptions = deployMode
? await buildRascalServerOptions(jarPath, isParametricServer, dedicated, lspArg, logger)
: () => connectToRascalLanguageServerSocket(devPort) // we assume a server is running in debug mode
.then((socket) => <StreamInfo> { writer: socket, reader: socket});
const clientOptions = <LanguageClientOptions>{
documentSelector: [{ scheme: '*', language: language }],
outputChannel: logger,
};
const client = new LanguageClient(language, title, serverOptions, clientOptions, !deployMode);
await client.start();
logger.setClient(client);
client.sendNotification("rascal/vfs/register", {
port: await vfsServer.serverPort
});
client.onNotification("rascal/showContent", (uri: string, title: string, viewColumn: integer) => {
showContentPanel(uri, title, viewColumn);
});
client.onNotification("rascal/editDocument", (uri: string, range: vscode.Range, viewColumn: integer) => {
openEditor(uri, range, viewColumn);
});
const schemesReply = client.sendRequest<string[]>("rascal/filesystem/schemes");
schemesReply.then( schemes => {
vfsServer.ignoreSchemes(schemes);
new RascalFileSystemProvider(client, logger).tryRegisterSchemes(schemes);
});
return client;
}
const contentPanels: Map<string, vscode.WebviewPanel> = new Map();
async function showContentPanel(url: string, title:string, viewColumn:integer): Promise<void> {
// dispose of old panel in case it existed
const externalURL = (await vscode.env.asExternalUri(vscode.Uri.parse(url))).toString();
const id = title;
const existingPanel = contentPanels.get(id);
if (existingPanel) {
// reuse the tab, but reload the content
existingPanel.reveal(viewColumn, true);
loadURLintoPanel(existingPanel, externalURL);
return;
}
const panel = vscode.window.createWebviewPanel(
"text/html",
title,
{
viewColumn: viewColumn,
preserveFocus: true /* the next editor should appear in the old column */
},
{
enableScripts: true,
retainContextWhenHidden: true, /* otherwise the whole page reloads every time we loose focus */
}
);
loadURLintoPanel(panel, externalURL);
panel.onDidDispose(() => contentPanels.delete(id));
contentPanels.set(id, panel);
}
async function openEditor(uriString: string, range:vscode.Range, viewColumn: integer) {
const uri = vscode.Uri.parse(uriString);
const doc = await vscode.workspace.openTextDocument(uri);
// Show it in an editor
const editor = await vscode.window.showTextDocument(doc, {
// make sure it's not a preview, otherwise it will dissappear with the next focus change:
preview: false,
// put it where we want: if another editor is open for the same URI _and_ the same viewColumn, that one will be reused:
viewColumn: viewColumn,
// will let this editor take focus:
preserveFocus: false,
// don't use the `selection` field here because we can not control scrolling behavior from that with editors which are already open
});
if (range !== null) {
// set the primary selection and move it into view (but don't scroll unless necessary)
editor.selection = new vscode.Selection(range.start, range.end);
editor.revealRange(range, vscode.TextEditorRevealType.InCenterIfOutsideViewport);
}
}
function loadURLintoPanel(panel:vscode.WebviewPanel, url:string): void {
panel.webview.html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<iframe
id="iframe-rascal-content"
src="${url}"
frameborder="0"
sandbox="allow-scripts allow-forms allow-same-origin allow-pointer-lock allow-downloads allow-top-navigation"
style="display: block; margin: 0px; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: visible;"
>
Loading ${url} at ${new Date().toLocaleTimeString()}
</iframe>
</body>
</html>`;
}
async function buildRascalServerOptions(jarPath: string, isParametricServer: boolean, dedicated: boolean, lspArg: string | undefined, logger: vscode.LogOutputChannel): Promise<ServerOptions> {
const classpath = buildCompilerJVMPath(jarPath);
const commandArgs = [
'-Dlog4j2.configurationFactory=org.rascalmpl.vscode.lsp.log.LogJsonConfiguration'
, '-Dlog4j2.level=DEBUG'
, '-Drascal.fallbackResolver=org.rascalmpl.vscode.lsp.uri.FallbackResolver'
, '-Drascal.lsp.deploy=true'
, '-Drascal.compilerClasspath=' + classpath
];
let mainClass: string;
if (isParametricServer) {
mainClass = 'org.rascalmpl.vscode.lsp.parametric.ParametricLanguageServer';
commandArgs.push(calculateDSLMemoryReservation(dedicated));
}
else {
mainClass = 'org.rascalmpl.vscode.lsp.rascal.RascalLanguageServer';
commandArgs.push(calculateRascalMemoryReservation());
}
commandArgs.push('-cp', classpath, mainClass);
if (isParametricServer && dedicated && lspArg !== undefined) {
commandArgs.push(lspArg);
}
return {
command: await getJavaExecutable(logger),
args: commandArgs
};
}
function buildCompilerJVMPath(jarPath:string) :string {
return ['rascal-lsp.jar', 'rascal.jar']
.map(j => path.join(jarPath, j))
.join(path.delimiter);
}
function gb(amount: integer) {
return amount * (1024 * 1024 * 1024);
}
function calculateRascalMemoryReservation() {
const config = vscode.workspace.getConfiguration('rascal.lSP');
if (config.has('maxHeapSize')) {
const maxHeapSize = config.get('maxHeapSize');
if (maxHeapSize !== null) {
return `-Xmx${maxHeapSize}M`;
}
}
// rascal lsp needs at least 800M but runs better with 2G or even 2.5G (especially the type checker)
if (os.totalmem() >= gb(32)) {
return "-Xmx2500M";
}
if (os.totalmem() >= gb(16)) {
return "-Xmx1500M";
}
if (os.totalmem() >= gb(8)) {
return "-Xmx1200M";
}
return "-Xmx800M";
}
function calculateDSLMemoryReservation(_dedicated: boolean) {
const config = vscode.workspace.getConfiguration('rascal.parametric.lSP');
if (config.has('maxHeapSize')) {
const maxHeapSize = config.get('maxHeapSize');
if (maxHeapSize !== null) {
return `-Xmx${maxHeapSize}M`;
}
}
// this is a hard one, if you register many DSLs, it can grow quite a bit
// 400MB per language is a reasonable estimate (for average sized languages)
if (os.totalmem() >= gb(32)) {
return "-Xmx2400M";
}
if (os.totalmem() >= gb(16)) {
return "-Xmx1600M";
}
if (os.totalmem() >= gb(8)) {
return "-Xmx1200M";
}
return "-Xmx800M";
}
function connectToRascalLanguageServerSocket(port: number): Promise<net.Socket> {
return new Promise((connected, failed) => {
const maxTries = 20;
const host = '127.0.0.1';
let retryDelay = 0;
const client = new net.Socket();
let tries = 0;
function retry(err?: Error) : net.Socket | void {
if (tries <= maxTries) {
setTimeout (() => {
tries++;
retryDelay = Math.min(2500, retryDelay + 250);
client.connect(port, host);
}, retryDelay);
}
else {
return failed("Connection retries exceeded" + (err ? (": " + err.message) : ""));
}
}
client.setTimeout(1000);
client.on('timeout', retry);
client.on('error', retry);
client.once('connect', () => {
client.setTimeout(0);
client.setNoDelay(true);
client.removeAllListeners();
return connected(client);
});
return retry();
});
}