forked from genericptr/pascal-language-server
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgeneral.pas
586 lines (472 loc) · 18.3 KB
/
general.pas
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
// Pascal Language Server
// Copyright 2020 Arjan Adriaanse
// This file is part of Pascal Language Server.
// Pascal Language Server is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
// Pascal Language Server is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pascal Language Server. If not, see
// <https://www.gnu.org/licenses/>.
unit general;
{$mode objfpc}{$H+}
{$modeswitch arrayoperators}
interface
uses
{$ifdef FreePascalMake}
FPMConfig,
{$endif}
Classes, CodeToolManager, CodeToolsConfig, LinkScanner,URIParser, LazUTF8,
lsp, basic, capabilities, documentSymbol, settings,FileProcs;
type
{ TWorkspaceFolder }
TWorkspaceFolder = class(TCollectionItem)
private
fUri: TDocumentUri;
fName: String;
published
// The associated URI for this workspace folder.
property uri: TDocumentUri read fUri write fUri;
// The name of the workspace folder. Used to refer to this
// workspace folder in the user interface.
property name: string read fName write fName;
end;
TWorkspaceFolderItems = specialize TGenericCollection<TWorkspaceFolder>;
{ TVoidParams }
TVoidParams = class(TPersistent);
{ TInitializationOptions }
TInitializationOptions = class(TServerSettings)
end;
{ TInitializeParams }
TInitializeParams = class(TPersistent)
private
fProcessId: integer;
fClientInfo: TClientInfo;
fRootUri: string;
fCapabilities: TClientCapabilities;
fTrace: string;
fInitializationOptions: TInitializationOptions;
fWorkspaceFolders: TWorkspaceFolderItems;
published
// The process Id of the parent process that started
// the server. Is null if the process has not been started by another process.
// If the parent process is not alive then the server should exit (see exit notification) its process.
property processId: integer read fProcessId write fProcessId;
// Information about the client
property clientInfo: TClientInfo read fClientInfo write fClientInfo;
// The rootUri of the workspace. Is null if no
// folder is open. If both `rootPath` and `rootUri` are set
// `rootUri` wins.
property rootUri: string read fRootUri write fRootUri;
// User provided initialization options.
property initializationOptions: TInitializationOptions read fInitializationOptions write fInitializationOptions;
// The capabilities provided by the client (editor or tool)
property capabilities: TClientCapabilities read fCapabilities write fCapabilities;
// The initial trace setting. If omitted trace is disabled ('off').
property trace: string read fTrace write fTrace;
// The workspace folders configured in the client when the server starts.
// This property is only available if the client supports workspace folders.
// It can be `null` if the client supports workspace folders but none are
// configured.
property workspaceFolders: TWorkspaceFolderItems read fWorkspaceFolders write fWorkspaceFolders;
public
procedure AfterConstruction; override;
destructor Destroy; override;
end;
{ TInitializeResult }
TInitializeResult = class(TPersistent)
private
fCapabilities: TServerCapabilities;
published
property capabilities: TServerCapabilities read fCapabilities write fCapabilities;
end;
{ TInitialize }
TInitialize = class(specialize TLSPRequest<TInitializeParams, TInitializeResult>)
function Process(var Params : TInitializeParams): TInitializeResult; override;
end;
{ TInitialized }
TInitialized = class(specialize TLSPNotification<TVoidParams>)
procedure Process(var Params : TVoidParams); override;
end;
{ TCancelParams }
TCancelParams = class(TPersistent)
private
fId: Integer;
published
property id: Integer read fId write fId;
end;
{ TShutdown }
TShutdown = class(specialize TLSPRequest<TVoidParams, TPersistent>)
function Process(var Params : TVoidParams): TPersistent; override;
end;
{ TExit }
TExit = class(specialize TLSPNotification<TVoidParams>)
procedure Process(var Params : TVoidParams); override;
end;
{ TCancel }
TCancel = class(specialize TLSPNotification<TCancelParams>)
procedure Process(var Params : TCancelParams); override;
end;
{ TSetTrace }
TSetTraceParams = class(TPersistent)
private
fvalue: string;
published
property value: string read fvalue write fvalue;
end;
TSetTrace = class(specialize TLSPNotification<TSetTraceParams>)
procedure Process(var Params : TSetTraceParams); override;
end;
implementation
uses
SysUtils, RegExpr,DefineTemplates,CodeToolsUtil;
{ TSetTrace }
procedure TSetTrace.Process(var Params: TSetTraceParams);
begin
end;
{ TInitializeParams }
procedure TInitializeParams.AfterConstruction;
begin
inherited;
if clientInfo = nil then
clientInfo := TClientInfo.Create;
if initializationOptions = nil then
initializationOptions := TInitializationOptions.Create;
workspaceFolders := TWorkspaceFolderItems.Create;
end;
destructor TInitializeParams.Destroy;
begin
// note: it's a hack for now but we don't want to free initializationOptions and clientInfo
//initializationOptions.Free;
//clientInfo.Free;
workspaceFolders.Free;
inherited;
end;
{ TInitialize }
function TInitialize.Process(var Params : TInitializeParams): TInitializeResult;
const
kStatusPrefix = '✓ ';
kFailedPrefix = '⚠️ ';
procedure ShowConfigStatus(CodeToolsOptions: TCodeToolsOptions);
begin
writeln(StdErr, kStatusPrefix+'Client: ', Params.clientInfo.name, ' ', Params.clientInfo.version);
writeln(StdErr, kStatusPrefix+'FPCPath: ', CodeToolsOptions.FPCPath);
writeln(StdErr, kStatusPrefix+'FPCSrcDir: ', CodeToolsOptions.FPCSrcDir);
writeln(StdErr, kStatusPrefix+'TargetOS: ', CodeToolsOptions.TargetOS);
writeln(StdErr, kStatusPrefix+'TargetProcessor: ', CodeToolsOptions.TargetProcessor);
writeln(StdErr, kStatusPrefix+'LazarusSrcDir: ', CodeToolsOptions.LazarusSrcDir);
writeln(StdErr, kStatusPrefix+'LazarusSrcOptions: ', CodeToolsOptions.LazarusSrcOptions);
writeln(StdErr, kStatusPrefix+'Working directory: ', GetCurrentDir);
if CodeToolsOptions.FPCOptions <> '' then
writeln(stderr, kStatusPrefix+'FPCOptions: ', CodeToolsOptions.FPCOptions)
else
writeln(stderr, kStatusPrefix+'FPCOptions: [unspecified]');
if ServerSettings.&program <> '' then
writeln(StdErr, kStatusPrefix+'Main program file: ', ServerSettings.&program);
if CodeToolsOptions.ProjectDir <> '' then
writeln(stderr, kStatusPrefix+'ProjectDir: ', CodeToolsOptions.ProjectDir)
else
writeln(stderr, kStatusPrefix+'ProjectDir: [unspecified]');
if ServerSettings.symbolDatabase <> '' then
writeln(stderr, kStatusPrefix+'Symbol Database: ', ServerSettings.symbolDatabase)
else
writeln(stderr, kStatusPrefix+'Symbol Database: [unspecified]');
// other settings
writeln(stderr, kStatusPrefix+'Settings:');
writeln(stderr, ' ► maximumCompletions: ', ServerSettings.maximumCompletions);
writeln(stderr, ' ► overloadPolicy: ', ServerSettings.overloadPolicy);
writeln(stderr, ' ► insertCompletionsAsSnippets: ', ServerSettings.insertCompletionsAsSnippets);
writeln(stderr, ' ► insertCompletionProcedureBrackets: ', ServerSettings.insertCompletionProcedureBrackets);
writeln(stderr, ' ► includeWorkspaceFoldersAsUnitPaths: ', ServerSettings.includeWorkspaceFoldersAsUnitPaths);
writeln(stderr, ' ► includeWorkspaceFoldersAsIncludePaths: ', ServerSettings.includeWorkspaceFoldersAsIncludePaths);
writeln(stderr, ' ► checkSyntax: ', ServerSettings.checkSyntax);
writeln(stderr, ' ► publishDiagnostics: ', ServerSettings.publishDiagnostics);
writeln(stderr, ' ► workspaceSymbols: ', ServerSettings.workspaceSymbols);
writeln(stderr, ' ► documentSymbols: ', ServerSettings.documentSymbols);
writeln(stderr, ' ► minimalisticCompletions: ', ServerSettings.minimalisticCompletions);
writeln(stderr, ' ► showSyntaxErrors: ', ServerSettings.showSyntaxErrors);
Flush(stderr);
end;
function FindAllFiles(path: string): TStringArray;
var
info: TSearchRec;
begin
if not DirectoryExists(path) then
raise Exception.Create('Directory "'+path+'"" doesn''t exist');
path := path+DirectorySeparator+'*';
result := [];
if FindFirst(path, faAnyFile, info) = 0 then
begin
repeat
result += [info.name];
until FindNext(info) <> 0;
FindClose(info);
end;
end;
{ Find all sub directories which contain Pascal source files }
procedure FindPascalSourceDirectories(RootPath: String; var Results: TStringArray);
var
Files: TStringArray;
Name,
Path,
Extension: String;
Found: Boolean;
begin
Files := FindAllFiles(RootPath);
Found := false;
for Name in Files do
begin
if (Name = '.') or (Name = '..') then
continue;
Extension := ExtractFileExt(name);
if (Extension = '.pas') or (Extension = '.pp') or (Extension = '.inc') then
begin
if not Found then
Results += [RootPath];
Found := true;
end
else
begin
Path := RootPath+DirectorySeparator+Name;
if DirectoryExists(Path) then
FindPascalSourceDirectories(Path, Results);
end;
end;
end;
{$ifdef FreePascalMake}
function LoadFromFPM(ConfigFile: String; CodeToolsOptions: TCodeToolsOptions): Boolean;
var
Path, Flag: String;
Config: TFPMConfig;
begin
// set the working directory based on the config file
if DirectoryExists(ConfigFile) then
ChDir(ConfigFile)
else if FileExists(ConfigFile) then
ChDir(ExtractFileDir(ConfigFile))
else
exit(false);
Getdir(0, Path);
try
config := TFPMConfig.Create(Path);
writeln(StdErr, '► Loading from FPM: ', Path);
// set the CodeTools project directory to match
CodeToolsOptions.ProjectDir := Path;
ServerSettings.&program := config.GetProgramFile;
for flag in config.GetCodeToolOptions do
ServerSettings.FPCOptions.Add(flag);
config.Free;
except
end;
try
finally
end;
result := true;
end;
{$endif}
var
CodeToolsOptions: TCodeToolsOptions;
Option, Path: String;
URI: TURI;
Item: TCollectionItem;
re: TRegExpr;
DirectoryTemplate,
UnitPathTemplate,IncPathTemplate: TDefineTemplate;
ServerCapabilities: TServerCapabilities;
Macros: TMacroMap;
Paths: TStringArray;
cfg:TPCTargetConfigCache;
fpcTarget:String;
begin with Params do
begin
CodeToolsOptions := TCodeToolsOptions.Create;
CodeToolBoss.CatchExceptions:=true;
//RaiseUnhandableExceptions:=True;
// TODO: we need to copy this or implement ref counting
// once we figure out how memory is going to work with
// the JSON-RPC streaming model
ServerSettings := initializationOptions;
settings.ClientInfo := clientInfo;
URIToFilename(rootUri,Path);
// replace macros in server settings
Macros := TMacroMap.Create;
Macros.Add('tmpdir', GetTempDir(true));
Macros.Add('root', Path);
ServerSettings.ReplaceMacros(Macros);
// set the project directory based on root URI path
if rootUri <> '' then
begin
if ServerSettings.cwd='' then
begin
CodeToolsOptions.ProjectDir := path;//URI.Path + URI.Document;
end;
end;
if ServerSettings.cwd<>'' then
begin
CodeToolsOptions.ProjectDir:=ServerSettings.cwd;
end;
// print the root URI so we know which workspace folder is default
writeln(StdErr, '► RootURI: ', rootUri);
writeln(StdErr, '► ProjectDir: ', CodeToolsOptions.ProjectDir);
{$ifdef FreePascalMake}
{ attempt to load settings from FPM config file or search in the
default workspace if there is there is only one available.
We can't search multiple workspaces because they may contain
config files also but there is no guarentee the workspaces will
arrive in order to the language server, so we can make no assumptions
based on ambigous ordering. }
if ((initializationOptions.config <> '') and LoadFromFPM(initializationOptions.config, CodeToolsOptions)) or
((workspaceFolders.Count = 1) and LoadFromFPM(CodeToolsOptions.ProjectDir, CodeToolsOptions)) then
begin
// disable other settings which may interfer with FPM
ServerSettings.includeWorkspaceFoldersAsUnitPaths := false;
ServerSettings.includeWorkspaceFoldersAsIncludePaths := false;
end;
{$endif}
// load the symbol manager if it's enabled
if ServerSettings.documentSymbols or ServerSettings.workspaceSymbols then
SymbolManager := TSymbolManager.Create;
ServerCapabilities := TServerCapabilities.Create(initializationOptions);
re := TRegExpr.Create('^(-(Fu|Fi)+)(.*)$');
with CodeToolsOptions do
begin
// set some built-in defaults based on platform
{$ifdef DARWIN}
FPCPath := '/usr/local/bin/fpc';
FPCSrcDir := '/usr/local/share/fpcsrc';
{$endif}
{$ifdef MSWINDOWS}
FPCPath := 'C:/lazarus/fpc/3.2.2/bin/i386-win32/fpc.exe';
LazarusSrcDir:='c:/lazarus';
{$endif}
{$ifdef LINUX}
FPCPath := '/usr/local/bin/fpc';
FPCSrcDir := '/usr/local/share/fpcsrc';
{$endif}
InitWithEnvironmentVariables;
// attempt to load optional config file
Path := ExpandFileName(initializationOptions.CodeToolsConfig);
if FileExists(Path) then
begin
writeln(StdErr, 'Loading config file: ', Path);
LoadFromFile(Path);
end;
// include workspace paths as search paths
if ServerSettings.includeWorkspaceFoldersAsUnitPaths or
ServerSettings.includeWorkspaceFoldersAsIncludePaths then
begin
Paths := [];
for Item in workspaceFolders do
begin
URIToFilename(TWorkspaceFolder(Item).uri,Path);
FindPascalSourceDirectories(Path, Paths);
end;
for Path in Paths do
begin
// add directory as search paths
if ServerSettings.includeWorkspaceFoldersAsUnitPaths then
begin
initializationOptions.FPCOptions.Add('-Fu'+Path);
initializationOptions.FPCOptions.Add('-Fi'+Path);
end;
// if the server supports workspace symbols then
// scan the workspace folder for symbols
if ServerCapabilities.workspaceSymbolProvider then
SymbolManager.Scan(Path, false);
end;
end;
for Option in initializationOptions.FPCOptions do
begin
// expand file names in switches with paths
if re.Exec(Option) then
FPCOptions := FPCOptions + '-' + re.Match[2] + ExpandFileName(re.Match[3]) + ' '
else if option.StartsWith('-T') then
begin
CodeToolsOptions.TargetOS:=option.SubString(2);
end
else if option.StartsWith('-P') then
begin
CodeToolsOptions.TargetProcessor:=option.SubString(2);
end
else
FPCOptions := FPCOptions + Option + ' ';
end;
if ServerSettings.&program <> '' then
begin
Path := ExpandFileName(ServerSettings.&program);
if FileExists(Path) then
ServerSettings.&program := Path
else
begin
writeln(StdErr, kFailedPrefix+'Main program file ', Path, ' can''t be found.');
ServerSettings.&program := '';
end;
end;
ShowConfigStatus(CodeToolsOptions);
end;
re.Free;
with CodeToolBoss do
begin
Init(CodeToolsOptions);
IdentifierList.SortForHistory := True;
IdentifierList.SortForScope := True;
//CatchExceptions:=True;
end;
if DirectoryExists(CodeToolsOptions.LazarusSrcDir) then
begin
fpcTarget:=CodeToolsOptions.TargetOS+'-'+CodeToolsOptions.TargetProcessor;
//CodeToolBoss.DefinePool.CreateLCLProjectTemplate();
UnitPathTemplate:=TDefineTemplate.Create('UnitPath', 'Unit Path',
UnitPathMacroName,
UnitPathMacro+';'+ CodeToolsOptions.LazarusSrcDir+'/lcl/units/'+fpcTarget+';'+
{$IFDEF MSWINDOWS}
CodeToolsOptions.LazarusSrcDir+'/lcl/units/'+fpcTarget+'/win32;'+
{$ENDIF}
CodeToolsOptions.LazarusSrcDir+'/components/lazutils/;'+
CodeToolsOptions.LazarusSrcDir+'/components/lazutils/lib/'+fpcTarget+';'+
CodeToolsOptions.LazarusSrcDir+'/packager/units/'+fpcTarget,
da_Define);
IncPathTemplate:=TDefineTemplate.Create('IncPath','Inc Path',
IncludePathMacroName,
IncludePathMacro+';'+ CodeToolsOptions.LazarusSrcDir+'/lcl/include',
da_Define);
CodeToolBoss.DefineTree.Add(UnitPathTemplate);
CodeToolBoss.DefineTree.Add(IncPathTemplate);
end;
Result := TInitializeResult.Create;
Result.capabilities := ServerCapabilities;
end;
end;
{ TInitialized }
procedure TInitialized.Process(var Params : TVoidParams);
begin
// do nothing
end;
{ TShutdown }
function TShutdown.Process(var Params : TVoidParams): TPersistent;
begin
// do nothing
result := nil;
end;
{ TExit }
procedure TExit.Process(var Params : TVoidParams);
begin
Halt(0);
end;
{ TCancel }
procedure TCancel.Process(var Params : TCancelParams);
begin
// not supported
end;
initialization
LSPHandlerManager.RegisterHandler('initialize', TInitialize);
LSPHandlerManager.RegisterHandler('initialized', TInitialized);
LSPHandlerManager.RegisterHandler('shutdown', TShutdown);
LSPHandlerManager.RegisterHandler('exit', TExit);
LSPHandlerManager.RegisterHandler('$/cancelRequest', TCancel);
LSPHandlerManager.RegisterHandler('$/setTrace', TSetTrace);
end.