forked from genericptr/pascal-language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LSP.Base.pas
591 lines (483 loc) · 16.3 KB
/
LSP.Base.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
586
587
588
589
590
591
// Pascal Language Server
// Copyright 2020 Arjan Adriaanse
// Copyright 2020 Ryan Joseph
// 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 LSP.Base;
{$mode objfpc}{$H+}
{$WARN 5024 off : Parameter "$1" not used}
interface
uses
{ RTL }
Classes, SysUtils, TypInfo, RTTIUtils,
{ JSON-RPC }
fpjson, fpjsonrtti, fpjsonrpc,
{ Pasls }
LSP.BaseTypes, LSP.Streaming, LSP.Messages;
const
LSPContentType = 'application/vscode-jsonrpc; charset=utf-8';
Type
{ TLSPRequest
https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage
A request message to describe a request between the client and the server.
Every processed request must send a response back to the sender of the request. }
{ TLSPContextCustomJSONRPCHandler }
TLSPContextCustomJSONRPCHandler = class(TCustomJSONRPCHandler)
private
FTransport: TMessageTransport;
Public
Procedure DoLog(Const Msg : String); overload;
Procedure DoLog(Const Fmt : String; Const Args : Array of const); overload;
Procedure LogError(Const Msg : String; E : Exception);
Property Transport : TMessageTransport Read FTransport Write FTransport;
end;
generic TLSPRequest<T: TPersistent; U : TPersistent> = class(TLSPContextCustomJSONRPCHandler)
protected
function DoExecute(const Params: TJSONData; AContext: TJSONRPCCallContext): TJSONData; override;
function Process(var Params : T): U; virtual; abstract;
end;
{ TOutGoingID }
TOutGoingID = Class
// One ID for all outgoing requests
Private
Class Var
OutgoingRequestIndex : Integer;
Private
FTransport : TMessageTransport;
Public
Constructor Create(aTransport : TMessageTransport);
Property Transport : TMessageTransport Read FTransport;
end;
{ TLSPOutgoingRequest
A request from the server to the client }
generic TLSPOutgoingRequest<T: TLSPStreamable> = class(TOutGoingID)
public
procedure Execute(Params: T; Method: String);
end;
{ TLSPNotification
https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage
A notification message. A processed notification message must not send a response back.
They work like events. }
generic TLSPNotification<T: TLSPStreamable> = class(TLSPContextCustomJSONRPCHandler)
protected
function DoExecute(const Params: TJSONData; AContext: TJSONRPCCallContext): TJSONData; override;
procedure Process(var Params : T); virtual; abstract;
end;
{ TLSPDispatcher }
{ TLSPBaseDispatcher }
// A dispatcher is responsible for handling a request and returning the result.
TLSPBaseDispatcher = class(TObject)
protected
Function GetTransport : TMessageTransport; virtual; abstract;
Public
Function ExecuteRequest(aRequest : TJSONData): TJSONData; virtual; abstract;
Property Transport : TMessageTransport Read GetTransport;
end;
{ TJSONRPCDispatcher }
// Wrapper class for TCustomJSONRPCDispatcher, to handle a bug in fpc's JSON-rpc
TJSONRPCDispatcher = class(TCustomJSONRPCDispatcher)
private
FTransport: TMessageTransport;
protected
Function ExecuteHandler(H: TCustomJSONRPCHandler; Params, ID: TJSONData; AContext: TJSONRPCCallContext): TJSONData; override;
function ExecuteMethod(const AClassName, AMethodName: TJSONStringType;
Params, ID: TJSONData; AContext: TJSONRPCCallContext): TJSONData; override;
public
constructor Create(AOwner: TComponent); override;
Property Transport : TMessageTransport Read FTransport Write FTransport;
end;
{ TLSPLocalDispatcher }
// Dispatches the request locally through a TJSONRPCDispatcher instance.
TClientMethodResultEvent = procedure (Sender : TObject; aResponse : TObject; const aID : String; aResult : TJSONData) of object;
TClientMethodErrorEvent = procedure (Sender : TObject; aResponse : TObject; const aID : String; aError : TJSONData) of object;
TLSPLocalDispatcher = class(TLSPBaseDispatcher)
Private
FJSONDispatcher : TJSONRPCDispatcher;
FOnMethodError: TClientMethodErrorEvent;
FOnMethodResult: TClientMethodResultEvent;
FOwnsTransport: Boolean;
FTransport: TMessageTransport;
Protected
procedure ProcessClientMethodResult(aResponse: TJSONObject; const aID : String; aResult: TJSONData); virtual;
procedure ProcessClientMethodError(aResponse: TJSONObject; const aID : String; aResult: TJSONData); virtual;
function GetTransport: TMessageTransport; override;
Public
Constructor Create(aTransport : TMessageTransport; aOwnsTransport : Boolean = False);
Destructor Destroy; override;
function ExecuteRequest(aRequest : TJSONData): TJSONData; override;
Property Transport : TMessageTransport Read FTransport;
// Dispatcher owns transport !
Property OwnsTransport : Boolean Read FOwnsTransport Write FOwnsTransport;
// Called when client (acting as server) returned a result.
Property OnMethodResult : TClientMethodResultEvent Read FOnMethodResult Write FOnMethodResult;
// Called when client (acting as server) returned a result.
Property OnMethodError : TClientMethodErrorEvent Read FOnMethodError Write FOnMethodError;
end;
{ TLSPContext }
TLSPContext = Class (TObject)
Private
Class var _LogFile: TFileStream;
private
FDispatcher: TLSPBaseDispatcher;
FDispatcherOwner: Boolean;
FLastMessageID: Integer;
FTransport: TMessageTransport;
Class function GetLogFile: String; static;
procedure SetDispatcher(AValue: TLSPBaseDispatcher);
Class procedure SetLogFile(const AValue: String); static;
Protected
Class Procedure DoLog(const Msg : String);
Class Procedure DoLog(const Fmt : String; Const Args : Array of const);
Public
Class Destructor Done;
Public
Constructor Create(aTransport : TMessageTransport; aDispatcher : TLSPBaseDispatcher; aOwner : Boolean); virtual;
Constructor Create(aOwner : Boolean);
destructor Destroy; override;
Function Execute(aRequest : TJSONData) : TJSONData;
function NextMessageID: Integer;
// logging
class Function HaveLog : Boolean;
Class Procedure Log(const Msg : String);
Class Procedure Log(const Fmt : String; Const Args : Array of const);
Class Property LogFile : String Read GetLogFile Write SetLogFile;
published
Property LastMessageID: Integer Read FLastMessageID;
// The transport class for sending messages;
Property Transport : TMessageTransport Read FTransport;
// The dispatcher that actually executes requests
Property Dispatcher : TLSPBaseDispatcher Read FDispatcher Write SetDispatcher;
// Do we own the dispatcher.
Property DispatcherOwner : Boolean Read FDispatcherOwner Write FDispatcherOwner;
end;
{ LSPHandlerManager }
function LSPHandlerManager: TCustomJSONRPCHandlerManager;
function IsResponseValid(Response: TJSONData): boolean;
implementation
{ Utilities }
function IsResponseValid(Response: TJSONData): boolean;
begin
result := true;
// invalid responses without id's or null id's must not be sent to client, i.e:
// {"jsonrpc":"2.0","error":{"code":-32603,"message":"Access violation"},"id":null}
if (Response is TJSONObject) and
((TJSONObject(Response).Find('id') = nil) or
TJSONObject(Response).Nulls['id']) then
result := false;
end;
{ TLSPLocalDispatcher }
function TLSPLocalDispatcher.GetTransport: TMessageTransport;
begin
Result:=FTransport;
end;
constructor TLSPLocalDispatcher.Create(aTransport: TMessageTransport;
aOwnsTransport: Boolean);
begin
FTransport:=aTransport;
FOwnsTransport:=aOwnsTransport;
FJSONDispatcher:=TJSONRPCDispatcher.Create(Nil);
FJSONDispatcher.Transport:=Self.Transport;
end;
destructor TLSPLocalDispatcher.Destroy;
begin
FreeAndNil(FJSONDispatcher);
inherited Destroy;
end;
procedure TLSPLocalDispatcher.ProcessClientMethodResult(aResponse: TJSONObject;const aID : String; aResult: TJSONData);
begin
if Assigned(OnMethodResult) then
OnMethodResult(Self,aResponse,aID,aResult);
end;
Procedure TLSPLocalDispatcher.ProcessClientMethodError(aResponse: TJSONObject; const aID : String; aResult : TJSONData);
begin
if Assigned(OnMethodError) then
OnMethodError(Self,aResponse,aID,aResult);
end;
function TLSPLocalDispatcher.ExecuteRequest(aRequest: TJSONData): TJSONData;
var
Obj: TJSONObject absolute aRequest;
Idx: Integer;
rID: String;
begin
Result:=nil;
if Not (aRequest is TJSONObject) then
Exit;
if (Obj.Get('method','')='') then
begin
rID:='';
Idx:=Obj.IndexOfName('id');
if Idx<>-1 then
rID:=Obj.Items[Idx].AsString;
Idx:=Obj.IndexOfName('result');
if (Idx<>-1) then
ProcessClientMethodResult(Obj,rID,Obj.Items[Idx])
else
begin
Idx:=Obj.IndexOfName('error');
ProcessClientMethodError(Obj,rID,Obj.Items[Idx]);
end;
end
else
Result:=FJSONDispatcher.Execute(aRequest);
end;
{ TLSPContextCustomJSONRPCHandler }
procedure TLSPContextCustomJSONRPCHandler.DoLog(const Msg: String);
begin
if Assigned(Transport) then
Transport.SendDiagnostic(Msg);
end;
procedure TLSPContextCustomJSONRPCHandler.DoLog(const Fmt: String;
const Args: array of const);
begin
if Assigned(Transport) then
Transport.SendDiagnostic(Fmt,Args);
end;
procedure TLSPContextCustomJSONRPCHandler.LogError(const Msg: String;
E: Exception);
begin
DoLog('% : Error %s with message "%s"',[Msg,E.ClassName,E.Message]);
end;
{ TLSPRequest }
function TLSPRequest.DoExecute(const Params: TJSONData; AContext: TJSONRPCCallContext): TJSONData;
var
Input: T;
Output: U;
Streamer: TLSPStreamer;
AObject: TObject;
ArrayTypeInfo: PTypeInfo;
ElementType: PTypeInfo;
begin
if (Transport=Nil) then
Raise EArgumentNilException.Create('No transport available');
Streamer:=Nil;
Input := specialize TLSPStreaming<T>.ToObject(Params);
try
Output := Process(Input);
if Output = nil then
begin
Result := TJSONNull.Create;
exit;
end;
Streamer := TLSPStreamer.Create(nil);
Streamer.Options := Streamer.Options + [jsoEnumeratedAsInteger, jsoSetEnumeratedAsInteger, jsoTStringsAsArray];
if GetTypeKind(U) = tkDynArray then
begin
ArrayTypeInfo := PTypeInfo(TypeInfo(U));
// Class kinds are in ElType2 (not sure why)
ElementType := GetTypeData(ArrayTypeInfo)^.ElType;
if ElementType = nil then
ElementType := GetTypeData(ArrayTypeInfo)^.ElType2;
case ElementType^.Kind of
tkClass:
begin
if GetTypeData(ElementType)^.ClassType.InheritsFrom(TLSPStreamable) then
begin
Result := specialize TLSPStreaming<TLSPStreamable>.ToJSON(TObjectArray(Output));
// Free all objects
for AObject in TObjectArray(Output) do
AObject.Free;
end;
end;
otherwise
raise EUnknownErrorCode.Create('Dynamic array element type "'+Integer(ElementType^.Kind).ToString+'" is not supported for responses.');
end;
end
else if GetTypeKind(U) = tkClass then
begin
begin
Result := specialize TLSPStreaming<U>.ToJSON(TObject(Output));
TObject(Output).Free;
end;
end;
if Result = nil then
Result := TJSONNull.Create;
finally
Input.Free;
Streamer.Free;
end;
end;
{ TOutGoingID }
constructor TOutGoingID.Create(aTransport: TMessageTransport);
begin
FTransport:=aTransport;
end;
{ TLSPOutgoingRequest }
procedure TLSPOutgoingRequest.Execute(Params: T; Method: String);
var
Message: TRequestMessage;
begin
Message := TRequestMessage.Create;
try
Message.id := '_'+OutgoingRequestIndex.ToString;
Inc(OutgoingRequestIndex);
Message.params := Params;
Message.method := Method;
Message.Send(Self.Transport);
finally
Message.Free;
end;
end;
{ TLSPNotification }
function TLSPNotification.DoExecute(const Params: TJSONData; AContext: TJSONRPCCallContext): TJSONData;
var
Input: T;
begin
Input := specialize TLSPStreaming<T>.ToObject(Params);
try
Process(Input);
finally
Input.Free;
end;
result := nil;
end;
{ TLSPBaseDispatcher }
{ TLSPDispatcher }
function TJSONRPCDispatcher.ExecuteHandler(H: TCustomJSONRPCHandler; Params,
ID: TJSONData; AContext: TJSONRPCCallContext): TJSONData;
begin
if H is TLSPContextCustomJSONRPCHandler then
TLSPContextCustomJSONRPCHandler(H).Transport:=Self.FTransport;
Result:=Inherited ExecuteHandler(H,Params,ID,AContext);
end;
function TJSONRPCDispatcher.ExecuteMethod(const AClassName, AMethodName: TJSONStringType;
Params, ID: TJSONData; AContext: TJSONRPCCallContext): TJSONData;
{$IFDEF VER3_2}
Var
lID : TJSONData;
{$ENDIF}
begin
try
{$IFDEF VER3_2}
lID:=ID;
if lID=Nil then
lID:=TJSONIntegerNumber.Create(0);
try
Result := inherited ExecuteMethod(AClassName, AMethodName, Params, lID, AContext);
finally
if lID<>ID then
lID.Free;
end;
{$ELSE}
Result := inherited ExecuteMethod(AClassName, AMethodName, Params, ID, AContext);
{$ENDIF}
except
on E: LSPException do // handle errors specific to LSP
Exit(CreateJSON2Error(E.Message, E.Code, ID.Clone, TransactionProperty))
else raise;
end;
end;
constructor TJSONRPCDispatcher.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Options := [jdoSearchRegistry, jdoJSONRPC2, jdoNotifications, jdoStrictNotifications];
end;
{ LSPHandlerManager }
function LSPHandlerManager: TCustomJSONRPCHandlerManager;
begin
Result := JSONRPCHandlerManager;
end;
procedure TLSPContext.SetDispatcher(AValue: TLSPBaseDispatcher);
begin
if FDispatcher=AValue then Exit;
if FDispatcherOwner then
FreeAndNil(FDispatcher);
FDispatcher:=AValue;
end;
class function TLSPContext.GetLogFile: String;
begin
Result:='';
if assigned(_LogFile) then
Result:=_LogFile.FileName;
end;
class procedure TLSPContext.SetLogFile(const AValue: String);
begin
if aValue=GetLogFile then exit;
FreeAndNil(_LogFile);
if aValue<>'' then
_LogFile:=TFileStream.Create(aValue,fmCreate);
end;
class procedure TLSPContext.DoLog(const Msg: String);
Var
NL : String;
begin
if HaveLog and (Length(Msg)>0) then
begin
_LogFile.WriteBuffer(Msg[1],Length(Msg));
NL:=sLineBreak;
_LogFile.WriteBuffer(NL[1],Length(NL));
end;
end;
class procedure TLSPContext.DoLog(const Fmt: String;
const Args: array of const);
begin
DoLog(Format(Fmt,Args));
end;
constructor TLSPContext.Create(aTransport: TMessageTransport;
aDispatcher: TLSPBaseDispatcher; aOwner: Boolean);
begin
Create(aOwner);
Dispatcher:=aDispatcher;
FTransport:=aTransport;
end;
constructor TLSPContext.Create(aOwner: Boolean);
begin
FDispatcherOwner:=aOwner;
end;
destructor TLSPContext.Destroy;
begin
Dispatcher:=Nil;
inherited Destroy;
end;
class destructor TLSPContext.Done;
begin
FreeAndNil(_LogFile);
end;
function TLSPContext.NextMessageID: Integer;
begin
Result:=InterlockedIncrement(FLastMessageID);
end;
class function TLSPContext.HaveLog: Boolean;
begin
Result:=assigned(_LogFile);
end;
function TLSPContext.Execute(aRequest: TJSONData): TJSONData;
begin
If HaveLog then
DoLog('Executing request: %s',[aRequest.AsJSON]);
try
Result:=Dispatcher.ExecuteRequest(aRequest);
If HaveLog then
if Result<>Nil then
DoLog('Request response: %s',[Result.AsJSON])
else
DoLog('Request returned no response.');
except
on E : Exception do
begin
if HaveLog then
DoLog('Error %d while executing request: %s',[E.ClassName,E.Message]);
Raise;
end;
end;
end;
class procedure TLSPContext.Log(const Msg: String);
begin
If HaveLog then
DoLog(Msg);
end;
class procedure TLSPContext.Log(const Fmt: String; const Args: array of const);
begin
If HaveLog then
DoLog(Fmt,Args);
end;
end.