summaryrefslogtreecommitdiff
path: root/server/src/server.ts
blob: 5d99ca3b471889f46e332538b888c766c6a03e00 (plain)
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
/* Perl Navigator server. See licenses.txt file for licensing and copyright information */

import {
    createConnection,
    TextDocuments,
    Diagnostic,
    ProposedFeatures,
    InitializeParams,
    DidChangeConfigurationNotification,
    TextDocumentSyncKind,
    InitializeResult,
    Location,
    WorkspaceFolder,
    CompletionItem,
    CompletionList,
    TextDocumentPositionParams,
    TextEdit,
} from "vscode-languageserver/node";
import { basename } from "path";
import { homedir } from "os";
import { TextDocument } from "vscode-languageserver-textdocument";
import { PublishDiagnosticsParams } from "vscode-languageserver-protocol";

import Uri from "vscode-uri";
import { perlcompile, perlcritic, perlimports } from "./diagnostics";
import { cleanupTemporaryAssetPath } from "./assets";
import { getDefinition, getAvailableMods } from "./navigation";
import { getSymbols, getWorkspaceSymbols } from "./symbols";
import { NavigatorSettings, PerlDocument, PerlElem, completionElem} from "./types";
import { getHover } from "./hover";
import { getCompletions, getCompletionDoc } from "./completion";
import { formatDoc, formatRange } from "./formatting";
import { nLog } from "./utils";
import { startProgress, endProgress } from "./progress";
import { getSignature } from "./signatures";

var LRU = require("lru-cache");

// It the editor doesn't request node-ipc, use stdio instead. Make sure this runs before createConnection
if (process.argv.length <= 2) {
    process.argv.push("--stdio");
}

// Create a connection for the server
// Also include all preview / proposed LSP features.
const connection = createConnection(ProposedFeatures.all);

// Create a simple text document manager.
const documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument);

let hasConfigurationCapability = false;
let hasWorkspaceFolderCapability = false;

connection.onInitialize((params: InitializeParams) => {
    const capabilities = params.capabilities;

    // Does the client support the `workspace/configuration` request?
    // If not, we fall back using global settings.
    hasConfigurationCapability = !!(capabilities.workspace && !!capabilities.workspace.configuration);
    hasWorkspaceFolderCapability = !!(capabilities.workspace && !!capabilities.workspace.workspaceFolders);

    const result: InitializeResult = {
        capabilities: {
            textDocumentSync: TextDocumentSyncKind.Incremental,

            completionProvider: {
                resolveProvider: true,
                triggerCharacters: ["$", "@", "%", "-", ">", ":"],
            },

            definitionProvider: true, // goto definition
            documentSymbolProvider: true, // Outline view and breadcrumbs
            workspaceSymbolProvider: true,
            hoverProvider: true,
            documentFormattingProvider: true,
            documentRangeFormattingProvider: true,
            signatureHelpProvider: {
                // Triggers open signature help, switch to next param, and then close help
                triggerCharacters: ["(", ",", ")"],
            },
        },
    };
    if (hasWorkspaceFolderCapability) {
        result.capabilities.workspace = {
            workspaceFolders: {
                supported: true,
            },
        };
    }
    return result;
});

connection.onInitialized(() => {
    if (hasConfigurationCapability) {
        // Register for all configuration changes.
        connection.client.register(DidChangeConfigurationNotification.type, undefined);
    }
});

// The global settings, used when the `workspace/configuration` request is not supported by the client.
// Does not happen with the vscode client could happen with other clients.
// The "real" default settings are in the top-level package.json
const defaultSettings: NavigatorSettings = {
    perlPath: "perl",
    perlParams: [],
    enableWarnings: true,
    perlimportsProfile: "",
    perltidyProfile: "",
    perlcriticProfile: "",
    perlcriticEnabled: true,
    perlcriticSeverity: undefined,
    perlcriticTheme: undefined,
    perlcriticExclude: undefined,
    perlcriticInclude: undefined,
    perlimportsLintEnabled: false,
    perlimportsTidyEnabled: false,
    perltidyEnabled: true,
    perlCompileEnabled: true,
    perlEnv: undefined,
    perlEnvAdd: true,
    severity5: "warning",
    severity4: "info",
    severity3: "hint",
    severity2: "hint",
    severity1: "hint",
    includePaths: [],
    includeLib: true,
    logging: false, // Get logging from vscode, but turn it off elsewhere. Sublime Text seems to struggle with it on Windows
    enableProgress: false,
};

let globalSettings: NavigatorSettings = defaultSettings;

// Cache the settings of all open documents
const documentSettings: Map<string, NavigatorSettings> = new Map();

// Store recent critic diags to prevent blinking of diagnostics
const documentDiags: Map<string, Diagnostic[]> = new Map();

// Store recent compilation diags to prevent old diagnostics from resurfacing
const documentCompDiags: Map<string, Diagnostic[]> = new Map();

// My ballpark estimate is that 350k symbols will be about 35MB. Huge map, but a reasonable limit.
const navSymbols = new LRU({
    max: 350000,
    length: function (value: PerlDocument, key: string) {
        return value.elems.size;
    },
});

const timers: Map<string, NodeJS.Timeout> = new Map();

// Keep track of modules available for import. Building this is a slow operations and varies based on workspace settings, not documents
const availableMods: Map<string, Map<string, string>> = new Map();
let modCacheBuilt: boolean = false;

async function rebuildModCache() {
    const allDocs = documents.all();
    if (allDocs.length > 0) {
        modCacheBuilt = true;
        dispatchForMods(allDocs[allDocs.length - 1]); // Rebuild with recent file
    }
    return;
}

async function buildModCache(textDocument: TextDocument) {
    if (!modCacheBuilt) {
        modCacheBuilt = true; // Set true first to prevent other files from building concurrently.
        dispatchForMods(textDocument);
    }
    return;
}

async function dispatchForMods(textDocument: TextDocument) {
    // BIG TODO: Resolution of workspace settings? How to do? Maybe build a hash of all include paths.
    const settings = await getDocumentSettings(textDocument.uri);
    const workspaceFolders = await getWorkspaceFoldersSafe();
    const newMods = await getAvailableMods(workspaceFolders, settings);
    availableMods.set("default", newMods);
    return;
}

async function getWorkspaceFoldersSafe(): Promise<WorkspaceFolder[]> {
    try {
        const workspaceFolders = await connection.workspace.getWorkspaceFolders();
        if (!workspaceFolders) {
            return [];
        } else {
            return workspaceFolders;
        }
    } catch (error) {
        return [];
    }
}

function expandTildePaths(paths: string, settings: NavigatorSettings): string {
    const path = paths;
    // Consider that this not a Windows feature,
    // so, Windows "%USERPROFILE%" currently is ignored (and rarely used).
    if (path.startsWith("~/")) {
        const newPath = homedir() + path.slice(1);
        nLog("Expanding tilde path '" + path + "' to '" + newPath + "'", settings);
        return newPath;
    } else {
        return path;
    }
}

async function getDocumentSettings(resource: string): Promise<NavigatorSettings> {
    if (!hasConfigurationCapability) {
        return globalSettings;
    }
    let result = documentSettings.get(resource);
    if (!result) {
        result = await connection.workspace.getConfiguration({
            scopeUri: resource,
            section: "perlnavigator",
        });
        if (!result) return globalSettings;
        const resolvedSettings = { ...globalSettings, ...result };

        if(resolvedSettings.includePaths) {
            resolvedSettings.includePaths = resolvedSettings.includePaths.map((path: string) => expandTildePaths(path, resolvedSettings));
        }
        if(resolvedSettings.perlPath) {
            resolvedSettings.perlPath = expandTildePaths(resolvedSettings.perlPath, resolvedSettings);
        }
        if(resolvedSettings.perlimportsProfile) {
            resolvedSettings.perlimportsProfile = expandTildePaths(resolvedSettings.perlimportsProfile, resolvedSettings);
        }
        if(resolvedSettings.perltidyProfile) {
            resolvedSettings.perltidyProfile = expandTildePaths(resolvedSettings.perltidyProfile, resolvedSettings);
        }
        if(resolvedSettings.perlcriticProfile) {
            resolvedSettings.perlcriticProfile = expandTildePaths(resolvedSettings.perlcriticProfile, resolvedSettings);
        }
        if(resolvedSettings.perlEnv) {
            resolvedSettings.perlEnv = Object.fromEntries(Object.entries(resolvedSettings.perlEnv).map(([key, value]) => [key, expandTildePaths(value, resolvedSettings)]));
        }

        documentSettings.set(resource, resolvedSettings);
        return resolvedSettings;
    }
    return result;
}

// Only keep settings for open documents
documents.onDidClose((e) => {
    documentSettings.delete(e.document.uri);
    documentDiags.delete(e.document.uri);
    documentCompDiags.delete(e.document.uri);
    navSymbols.del(e.document.uri);
    connection.sendDiagnostics({ uri: e.document.uri, diagnostics: [] });
});

documents.onDidOpen((change) => {
    validatePerlDocument(change.document);
    buildModCache(change.document);
});

documents.onDidSave((change) => {
    validatePerlDocument(change.document);
});

documents.onDidChangeContent((change) => {
    // VSCode sends a firehose of change events. Only check after it's been quiet for 1 second.
    const timer = timers.get(change.document.uri);
    if (timer) clearTimeout(timer);
    const newTimer = setTimeout(function () {
        validatePerlDocument(change.document);
    }, 1000);
    timers.set(change.document.uri, newTimer);
});

async function validatePerlDocument(textDocument: TextDocument): Promise<void> {
    const fileName = basename(Uri.parse(textDocument.uri).fsPath);

    const settings = await getDocumentSettings(textDocument.uri);
    nLog("Found settings", settings);

    const progressToken = navSymbols.has(textDocument.uri) ? null : await startProgress(connection, `Initializing ${fileName}`, settings);

    const start = Date.now();

    const workspaceFolders = await getWorkspaceFoldersSafe();

    const pCompile = perlcompile(textDocument, workspaceFolders, settings); // Start compilation
    const pCritic = perlcritic(textDocument, workspaceFolders, settings); // Start perlcritic
    const pImports = perlimports(textDocument, workspaceFolders, settings); // Start perlimports

    let perlOut = await pCompile;
    nLog("Compilation Time: " + (Date.now() - start) / 1000 + " seconds", settings);
    let oldCriticDiags = documentDiags.get(textDocument.uri);
    if (!perlOut) {
        documentCompDiags.delete(textDocument.uri);
        endProgress(connection, progressToken);
        return;
    }
    documentCompDiags.set(textDocument.uri, perlOut.diags);

    let mixOldAndNew = perlOut.diags;
    if (oldCriticDiags && settings.perlcriticEnabled) {
        // Resend old critic diags to avoid overall file "blinking" in between receiving compilation and critic. TODO: async wait if it's not that long.
        mixOldAndNew = perlOut.diags.concat(oldCriticDiags);
    }
    sendDiags({ uri: textDocument.uri, diagnostics: mixOldAndNew });

    navSymbols.set(textDocument.uri, perlOut.perlDoc);

    // Perl critic things
    const diagCritic = await pCritic;
    const diagImports = await pImports;
    let newDiags: Diagnostic[] = [];

    if (settings.perlcriticEnabled) {
        newDiags = newDiags.concat(diagCritic);
        nLog("Perl Critic Time: " + (Date.now() - start) / 1000 + " seconds", settings);
    }

    if (settings.perlimportsLintEnabled) {
        newDiags = newDiags.concat(diagImports);
        nLog(`perlimports Time: ${(Date.now() - start) / 1000} seconds`, settings);
    }

    documentDiags.set(textDocument.uri, newDiags); // May need to clear out old ones if a user changed their settings.

    let compDiags = documentCompDiags.get(textDocument.uri);
    compDiags = compDiags ?? [];

    if (newDiags) {
        const allNewDiags = compDiags.concat(newDiags);
        sendDiags({ uri: textDocument.uri, diagnostics: allNewDiags });
    }
    endProgress(connection, progressToken);
    return;
}

function sendDiags(params: PublishDiagnosticsParams): void {
    // Before sending new diagnostics, check if the file is still open.
    if (documents.get(params.uri)) {
        connection.sendDiagnostics(params);
    } else {
        connection.sendDiagnostics({ uri: params.uri, diagnostics: [] });
    }
}

connection.onDidChangeConfiguration(async (change) => {
    if (hasConfigurationCapability) {
        // Reset all cached document settings
        documentSettings.clear();
    } else {
        globalSettings = { ...defaultSettings, ...change?.settings?.perlnavigator };
    }

    if (change?.settings?.perlnavigator) {
        // Despite what it looks like, this fires on all settings changes, not just Navigator
        await rebuildModCache();
        for (const doc of documents.all()) {
            // sequential changes
            await validatePerlDocument(doc);
        }
    }
});

// This handler provides the initial list of the completion items.
connection.onCompletion((params: TextDocumentPositionParams): CompletionList | undefined => {
    let document = documents.get(params.textDocument.uri);
    let perlDoc = navSymbols.get(params.textDocument.uri);
    let mods = availableMods.get("default");

    if (!document) return;
    if (!perlDoc) return; // navSymbols is an LRU cache, so the navigation elements will be missing if you open lots of files
    if (!mods) mods = new Map();
    const completions: CompletionItem[] = getCompletions(params, perlDoc, document, mods);
    return {
        items: completions,
        isIncomplete: false,
    };
});

connection.onCompletionResolve(async (item: CompletionItem): Promise<CompletionItem> => {

    const perlElem: PerlElem = item.data.perlElem;

    let perlDoc = navSymbols.get(item.data?.docUri);
    if (!perlDoc) return item;

    let mods = availableMods.get("default");
    if (!mods) mods = new Map();
    
    const docs = await getCompletionDoc(perlElem, perlDoc, mods);
    if (docs?.match(/\w/)) {
        item.documentation = { kind: "markdown", value: docs };;
    }
    return item;
});


connection.onHover(async (params) => {
    let document = documents.get(params.textDocument.uri);
    let perlDoc = navSymbols.get(params.textDocument.uri);
    let mods = availableMods.get("default");
    if (!mods) mods = new Map();

    if (!document || !perlDoc) return;

    return await getHover(params, perlDoc, document, mods);
});

connection.onDefinition(async (params) => {
    let document = documents.get(params.textDocument.uri);
    let perlDoc = navSymbols.get(params.textDocument.uri);
    let mods = availableMods.get("default");
    if (!mods) mods = new Map();
    if (!document) return;
    if (!perlDoc) return; // navSymbols is an LRU cache, so the navigation elements will be missing if you open lots of files
    let locOut: Location | Location[] | undefined = await getDefinition(params, perlDoc, document, mods);
    return locOut;
});

connection.onDocumentSymbol(async (params) => {
    let document = documents.get(params.textDocument.uri);
    // We might  need to async wait for the document to be processed, but I suspect the order is fine
    if (!document) return;
    return getSymbols(document, params.textDocument.uri);
});

connection.onWorkspaceSymbol((params) => {
    let defaultMods = availableMods.get("default");
    if (!defaultMods) return;
    return getWorkspaceSymbols(params, defaultMods);
});

connection.onDocumentFormatting(async (params) => {
    let document = documents.get(params.textDocument.uri);
    let settings = documentSettings.get(params.textDocument.uri);
    const workspaceFolders = await getWorkspaceFoldersSafe();

    if (!document || !settings) return;
    const editOut: TextEdit[] | undefined = await formatDoc(params, document, settings, workspaceFolders, connection);
    return editOut;
});

connection.onDocumentRangeFormatting(async (params) => {
    let document = documents.get(params.textDocument.uri);
    let settings = documentSettings.get(params.textDocument.uri);
    const workspaceFolders = await getWorkspaceFoldersSafe();

    if (!document || !settings) return;
    const editOut: TextEdit[] | undefined = await formatRange(params, document, settings, workspaceFolders, connection);
    return editOut;
});

connection.onSignatureHelp(async (params) => {
    let document = documents.get(params.textDocument.uri);
    let perlDoc = navSymbols.get(params.textDocument.uri);
    let mods = availableMods.get("default");
    if (!mods) mods = new Map();
    if (!document || !perlDoc) return;
    const signature = await getSignature(params, perlDoc, document, mods);
    return signature;
});

connection.onShutdown((handler) => {
    try {
        cleanupTemporaryAssetPath();
    } catch (error) {}
});

process.on("unhandledRejection", function (reason, p) {
    console.error("Caught an unhandled Rejection at: Promise ", p, " reason: ", reason);
});

// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);

// Listen on the connection
connection.listen();