-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProtocol.lean
More file actions
1335 lines (1188 loc) · 46 KB
/
Copy pathProtocol.lean
File metadata and controls
1335 lines (1188 loc) · 46 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
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/-
Copyright (c) 2026 Lean FRO LLC. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Emilio J. Gallego Arias
-/
import Lean
import Beam.LSP.Todo
import Beam.Workspace.Protocol
open Lean
namespace Beam.Broker
abbrev WorkspaceId := Beam.Workspace.WorkspaceId
/-- Identity of one wrapper-owned daemon generation. -/
structure DaemonIdentity where
daemonId : String
configHash : String
deriving BEq, Repr, FromJson, ToJson
def serverHelloSchemaVersion : Nat :=
1
/-- Identity greeting emitted by a wrapper daemon before it accepts one request connection. -/
structure ServerHello where
schemaVersion : Nat
identity : DaemonIdentity
deriving Repr, FromJson, ToJson
def ServerHello.current (identity : DaemonIdentity) : ServerHello := {
schemaVersion := serverHelloSchemaVersion
identity
}
def ServerHello.decode
(expectedIdentity : DaemonIdentity)
(msg : String) : Except String Unit := do
let json ←
match Json.parse msg with
| .ok json => pure json
| .error err => throw s!"invalid Beam daemon greeting json: {err}"
let hello ←
match fromJson? (α := ServerHello) json with
| .ok hello => pure hello
| .error err => throw s!"invalid Beam daemon greeting payload: {err}"
unless hello.schemaVersion == serverHelloSchemaVersion do
throw s!"unsupported Beam daemon greeting schema {hello.schemaVersion}"
unless hello.identity == expectedIdentity do
throw "Beam daemon greeting identity does not match the selected session"
instance : Repr Lsp.DiagnosticSeverity where
reprPrec severity _ :=
match severity with
| .error => "error"
| .warning => "warning"
| .information => "information"
| .hint => "hint"
inductive Op where
| ensure
| openDocs
| cancel
| updateFile
| syncFile
| refreshFile
| close
| runAt
| hover
| signatureHelp
| definition
| references
| documentSymbols
| workspaceSymbols
| codeActionResolve
| saveOlean
| goals
| todo
| runWith
| release
| initWorkspace
| listWorkspaces
| dropWorkspace
| stats
| shutdown
deriving Inhabited, BEq, Repr
def Op.all : Array Op := #[
.ensure, .openDocs, .cancel, .updateFile, .syncFile, .refreshFile, .close, .runAt,
.hover, .signatureHelp, .definition, .references, .documentSymbols, .workspaceSymbols,
.codeActionResolve, .saveOlean, .goals, .todo, .runWith, .release, .initWorkspace,
.listWorkspaces, .dropWorkspace, .stats, .shutdown
]
def Op.key : Op → String
| .ensure => "ensure"
| .openDocs => "open_docs"
| .cancel => "cancel"
| .updateFile => "update_file"
| .syncFile => "sync_file"
| .refreshFile => "refresh_file"
| .close => "close"
| .runAt => "run_at"
| .hover => "hover"
| .signatureHelp => "signature_help"
| .definition => "definition"
| .references => "references"
| .documentSymbols => "document_symbols"
| .workspaceSymbols => "workspace_symbols"
| .codeActionResolve => "code_action_resolve"
| .saveOlean => "save_olean"
| .goals => "goals"
| .todo => "todo"
| .runWith => "run_with"
| .release => "release"
| .initWorkspace => "init_workspace"
| .listWorkspaces => "list_workspaces"
| .dropWorkspace => "drop_workspace"
| .stats => "stats"
| .shutdown => "shutdown"
instance : ToJson Op where
toJson op := toJson op.key
instance : FromJson Op where
fromJson?
| .str "ensure" => .ok .ensure
| .str "open_docs" => .ok .openDocs
| .str "cancel" => .ok .cancel
| .str "update_file" => .ok .updateFile
| .str "sync_file" => .ok .syncFile
| .str "refresh_file" => .ok .refreshFile
| .str "close" => .ok .close
| .str "run_at" => .ok .runAt
| .str "hover" => .ok .hover
| .str "signature_help" => .ok .signatureHelp
| .str "definition" => .ok .definition
| .str "references" => .ok .references
| .str "document_symbols" => .ok .documentSymbols
| .str "workspace_symbols" => .ok .workspaceSymbols
| .str "code_action_resolve" => .ok .codeActionResolve
| .str "save_olean" => .ok .saveOlean
| .str "goals" => .ok .goals
| .str "todo" => .ok .todo
| .str "run_with" => .ok .runWith
| .str "release" => .ok .release
| .str "init_workspace" => .ok .initWorkspace
| .str "list_workspaces" => .ok .listWorkspaces
| .str "drop_workspace" => .ok .dropWorkspace
| .str "stats" => .ok .stats
| .str "shutdown" => .ok .shutdown
| j => .error s!"expected Beam daemon op, got {j.compress}"
inductive Backend where
| lean
| rocq
deriving Inhabited, BEq, Repr, Ord
instance : ToJson Backend where
toJson
| .lean => "lean"
| .rocq => "rocq"
instance : FromJson Backend where
fromJson?
| .str "lean" => .ok .lean
| .str "rocq" => .ok .rocq
| j => .error s!"expected backend 'lean' or 'rocq', got {j.compress}"
inductive GoalMode where
| before
| after
deriving Inhabited, BEq, Repr
def GoalMode.key : GoalMode → String
| .before => "before"
| .after => "after"
instance : ToJson GoalMode where
toJson mode := toJson mode.key
instance : FromJson GoalMode where
fromJson?
| .str "before" => .ok .before
| .str "after" => .ok .after
| j => .error s!"expected goal mode 'before' or 'after', got {j.compress}"
inductive GoalPpFormat where
| box
| pp
| str
deriving Inhabited, BEq, Repr
def GoalPpFormat.key : GoalPpFormat → String
| .box => "Box"
| .pp => "Pp"
| .str => "Str"
instance : ToJson GoalPpFormat where
toJson format := toJson format.key
instance : FromJson GoalPpFormat where
fromJson?
| .str "Box" => .ok .box
| .str "Pp" => .ok .pp
| .str "Str" => .ok .str
| j => .error s!"expected pp format 'Box', 'Pp', or 'Str', got {j.compress}"
structure Handle where
workspaceId : WorkspaceId
backend : Backend
epoch : Nat
session : String
raw : Json
deriving Inhabited, FromJson, ToJson
/-- Select which user-facing Lean diagnostic severities a request may display. -/
inductive DiagnosticScope where
| errors
| all
deriving Inhabited, BEq, Repr
def DiagnosticScope.key : DiagnosticScope → String
| .errors => "errors"
| .all => "all"
instance : ToJson DiagnosticScope where
toJson scope := toJson scope.key
instance : FromJson DiagnosticScope where
fromJson?
| .str "errors" => .ok .errors
| .str "all" => .ok .all
| json => .error s!"expected diagnostic scope 'errors' or 'all', got {json.compress}"
/-!
Broker requests keep routing and correlation in one small envelope. Operation-specific data lives in
`RequestPayload`, so a typed request cannot carry fields owned by another operation. The JSON codec
below deliberately keeps the wire shape flat.
-/
structure RequestBackend where
backend : Backend := .lean
structure RequestFile extends RequestBackend where
path : String
structure RequestVersionedFile extends RequestFile where
version : Nat
structure RequestPosition extends RequestVersionedFile where
line : Nat
character : Nat
structure SyncFileRequest extends RequestFile where
diagnosticScope? : Option DiagnosticScope := none
diagnosticsInResult? : Option Bool := none
structure CloseRequest extends RequestFile where
diagnosticScope? : Option DiagnosticScope := none
saveArtifacts? : Option Bool := none
structure RunAtRequest extends RequestPosition where
text : String
storeHandle? : Option Bool := none
structure ReferencesRequest extends RequestPosition where
includeDeclaration? : Option Bool := none
structure WorkspaceSymbolsRequest extends RequestBackend where
query : String
structure CodeActionResolveRequest extends RequestVersionedFile where
codeAction : Lsp.CodeAction
structure SaveOleanRequest extends RequestFile where
diagnosticScope? : Option DiagnosticScope := none
structure GoalsRequest extends RequestPosition where
text? : Option String := none
mode? : Option GoalMode := none
compact? : Option Bool := none
ppFormat? : Option GoalPpFormat := none
structure TodoRequest extends RequestPosition where
endLine : Nat
endCharacter : Nat
kinds? : Option (Array Beam.LSP.Todo.TodoKind) := none
suggest? : Option Beam.LSP.Todo.TodoSuggestMode := none
structure RunWithRequest where
path : String
text : String
storeHandle? : Option Bool := none
linear? : Option Bool := none
handle : Handle
structure ReleaseRequest where
path : String
handle : Handle
structure InitLeanBackendConfig where
command : String
plugin : String
structure InitWorkspaceRequest where
workspaceMode? : Option Beam.Workspace.InitMode := none
root : String
lean? : Option InitLeanBackendConfig := none
rocqCmd? : Option String := none
/-- The fields owned by exactly one broker operation. -/
inductive RequestPayload where
| ensure (request : RequestBackend)
| openDocs
| cancel (cancelRequestId : String)
| updateFile (request : RequestFile)
| syncFile (request : SyncFileRequest)
| refreshFile (request : SyncFileRequest)
| close (request : CloseRequest)
| runAt (request : RunAtRequest)
| hover (request : RequestPosition)
| signatureHelp (request : RequestPosition)
| definition (request : RequestPosition)
| references (request : ReferencesRequest)
| documentSymbols (request : RequestVersionedFile)
| workspaceSymbols (request : WorkspaceSymbolsRequest)
| codeActionResolve (request : CodeActionResolveRequest)
| saveOlean (request : SaveOleanRequest)
| goals (request : GoalsRequest)
| todo (request : TodoRequest)
| runWith (request : RunWithRequest)
| release (request : ReleaseRequest)
| initWorkspace (request : InitWorkspaceRequest)
| listWorkspaces
| dropWorkspace
| stats
| shutdown
structure Request where
payload : RequestPayload
workspaceId? : Option WorkspaceId := none
clientRequestId? : Option String := none
daemonCapability? : Option String := none
def RequestPayload.op : RequestPayload → Op
| .ensure _ => .ensure
| .openDocs => .openDocs
| .cancel _ => .cancel
| .updateFile _ => .updateFile
| .syncFile _ => .syncFile
| .refreshFile _ => .refreshFile
| .close _ => .close
| .runAt _ => .runAt
| .hover _ => .hover
| .signatureHelp _ => .signatureHelp
| .definition _ => .definition
| .references _ => .references
| .documentSymbols _ => .documentSymbols
| .workspaceSymbols _ => .workspaceSymbols
| .codeActionResolve _ => .codeActionResolve
| .saveOlean _ => .saveOlean
| .goals _ => .goals
| .todo _ => .todo
| .runWith _ => .runWith
| .release _ => .release
| .initWorkspace _ => .initWorkspace
| .listWorkspaces => .listWorkspaces
| .dropWorkspace => .dropWorkspace
| .stats => .stats
| .shutdown => .shutdown
def Request.op (request : Request) : Op :=
request.payload.op
def Request.ensure
(backend : Backend := .lean) : Request :=
{ payload := .ensure { backend } }
def Request.openDocs : Request :=
{ payload := .openDocs }
def Request.cancel (cancelRequestId : String) : Request :=
{ payload := .cancel cancelRequestId }
def Request.listWorkspaces : Request :=
{ payload := .listWorkspaces }
def Request.dropWorkspace : Request :=
{ payload := .dropWorkspace }
def Request.stats : Request :=
{ payload := .stats }
def Request.shutdown : Request :=
{ payload := .shutdown }
inductive WorkspaceScope where
| none
| optional
| required
deriving BEq, Repr
/-- Describe whether a broker operation is process-wide or resolves one workspace. -/
def Op.workspaceScope : Op → WorkspaceScope
| .listWorkspaces | .shutdown => .none
| .openDocs | .stats => .optional
| .cancel
| .ensure | .updateFile | .syncFile | .refreshFile | .close | .runAt | .hover
| .signatureHelp | .definition | .references | .documentSymbols | .workspaceSymbols
| .codeActionResolve | .saveOlean | .goals | .todo | .runWith | .release
| .initWorkspace | .dropWorkspace => .required
/-- Whether an operation participates in active-request tracking and exact cancellation. -/
def Op.tracksActiveRequest : Op → Bool
| .cancel | .shutdown => false
| .ensure | .openDocs | .updateFile | .syncFile | .refreshFile | .close | .runAt | .hover
| .signatureHelp | .definition | .references | .documentSymbols | .workspaceSymbols
| .codeActionResolve | .saveOlean | .goals | .todo | .runWith | .release | .initWorkspace
| .listWorkspaces | .dropWorkspace | .stats => true
private def Op.requestFields (op : Op) : Array String :=
#["clientRequestId", "daemonCapability"] ++
(match op.workspaceScope with
| .none => #[]
| .optional | .required => #["workspaceId"]) ++
match op with
| .ensure | .openDocs | .stats => #[]
| .cancel => #["cancelRequestId"]
| .updateFile => #["path"]
| .syncFile | .refreshFile =>
#["path", "diagnosticScope", "diagnosticsInResult"]
| .close => #["path", "diagnosticScope", "saveArtifacts"]
| .runAt =>
#["path", "version", "line", "character", "text", "storeHandle"]
| .hover | .signatureHelp | .definition =>
#["path", "version", "line", "character"]
| .references =>
#["path", "version", "line", "character", "includeDeclaration"]
| .documentSymbols => #["path", "version"]
| .workspaceSymbols => #["query"]
| .codeActionResolve => #["path", "version", "codeAction"]
| .saveOlean => #["path", "diagnosticScope"]
| .goals =>
#[
"path", "version", "line", "character", "text", "mode", "compact",
"ppFormat"
]
| .todo =>
#[
"path", "version", "line", "character", "endLine", "endCharacter", "kinds",
"suggest"
]
| .runWith =>
#["path", "text", "storeHandle", "linear", "handle"]
| .release => #["path", "handle"]
| .initWorkspace =>
#["workspaceMode", "root", "leanCmd", "leanPlugin", "rocqCmd"]
| .dropWorkspace => #[]
| .listWorkspaces | .shutdown => #[]
private def Op.acceptsBackendField : Op → Bool
| .ensure | .updateFile | .syncFile | .refreshFile | .close | .runAt | .hover
| .signatureHelp | .definition | .references | .documentSymbols | .workspaceSymbols
| .codeActionResolve | .saveOlean | .goals | .todo => true
| .runWith | .release
| .openDocs | .cancel | .initWorkspace | .listWorkspaces | .dropWorkspace | .stats
| .shutdown => false
private def optionalJsonField [ToJson α] (name : String) : Option α → List (String × Json)
| some value => [(name, toJson value)]
| none => []
private def RequestFile.jsonFields (request : RequestFile) : List (String × Json) :=
[("path", toJson request.path)]
private def RequestVersionedFile.jsonFields
(request : RequestVersionedFile) : List (String × Json) :=
request.toRequestFile.jsonFields ++ [("version", toJson request.version)]
private def RequestPosition.jsonFields (request : RequestPosition) : List (String × Json) :=
request.toRequestVersionedFile.jsonFields ++ [
("line", toJson request.line),
("character", toJson request.character)
]
private def RequestPayload.jsonFields : RequestPayload → List (String × Json)
| .ensure _ => []
| .openDocs => []
| .cancel cancelRequestId => [("cancelRequestId", toJson cancelRequestId)]
| .updateFile request => request.jsonFields
| .syncFile request | .refreshFile request =>
request.toRequestFile.jsonFields ++
optionalJsonField "diagnosticScope" request.diagnosticScope? ++
optionalJsonField "diagnosticsInResult" request.diagnosticsInResult?
| .close request =>
request.toRequestFile.jsonFields ++
optionalJsonField "diagnosticScope" request.diagnosticScope? ++
optionalJsonField "saveArtifacts" request.saveArtifacts?
| .runAt request =>
request.toRequestPosition.jsonFields ++
[("text", toJson request.text)] ++
optionalJsonField "storeHandle" request.storeHandle?
| .hover request | .signatureHelp request | .definition request =>
request.jsonFields
| .references request =>
request.toRequestPosition.jsonFields ++
optionalJsonField "includeDeclaration" request.includeDeclaration?
| .documentSymbols request => request.jsonFields
| .workspaceSymbols request =>
[("query", toJson request.query)]
| .codeActionResolve request =>
request.toRequestVersionedFile.jsonFields ++ [("codeAction", toJson request.codeAction)]
| .saveOlean request =>
request.toRequestFile.jsonFields ++
optionalJsonField "diagnosticScope" request.diagnosticScope?
| .goals request =>
request.toRequestPosition.jsonFields ++
optionalJsonField "text" request.text? ++
optionalJsonField "mode" request.mode? ++
optionalJsonField "compact" request.compact? ++
optionalJsonField "ppFormat" request.ppFormat?
| .todo request =>
request.toRequestPosition.jsonFields ++ [
("endLine", toJson request.endLine),
("endCharacter", toJson request.endCharacter)
] ++
optionalJsonField "kinds" request.kinds? ++
optionalJsonField "suggest" request.suggest?
| .runWith request =>
[("path", toJson request.path), ("text", toJson request.text)] ++
optionalJsonField "storeHandle" request.storeHandle? ++
optionalJsonField "linear" request.linear? ++
[("handle", toJson request.handle)]
| .release request =>
[("path", toJson request.path), ("handle", toJson request.handle)]
| .initWorkspace request =>
optionalJsonField "workspaceMode" request.workspaceMode? ++
[("root", toJson request.root)] ++
(match request.lean? with
| some lean => [
("leanCmd", toJson lean.command),
("leanPlugin", toJson lean.plugin)
]
| none => []) ++
optionalJsonField "rocqCmd" request.rocqCmd?
| .stats | .listWorkspaces | .dropWorkspace | .shutdown => []
def RequestPayload.backend? : RequestPayload → Option Backend
| .ensure request => some request.backend
| .updateFile request => some request.backend
| .syncFile request | .refreshFile request => some request.backend
| .close request => some request.backend
| .runAt request => some request.backend
| .hover request | .signatureHelp request | .definition request => some request.backend
| .references request => some request.backend
| .documentSymbols request => some request.backend
| .workspaceSymbols request => some request.backend
| .codeActionResolve request => some request.backend
| .saveOlean request => some request.backend
| .goals request => some request.backend
| .todo request => some request.backend
| .runWith request => some request.handle.backend
| .release request => some request.handle.backend
| .openDocs | .cancel _ | .initWorkspace _ | .listWorkspaces | .dropWorkspace
| .stats | .shutdown => none
def Request.handle? (request : Request) : Option Handle :=
match request.payload with
| .runWith value => some value.handle
| .release value => some value.handle
| _ => none
instance : ToJson Request where
toJson req := Json.mkObj <|
[("op", toJson req.op)] ++
(if req.op.acceptsBackendField then
optionalJsonField "backend" req.payload.backend?
else
[]) ++
optionalJsonField "workspaceId" req.workspaceId? ++
optionalJsonField "clientRequestId" req.clientRequestId? ++
optionalJsonField "daemonCapability" req.daemonCapability? ++
req.payload.jsonFields
private def requireRequestJsonFields (op : Op) : Json → Except String Unit
| .obj fields =>
let backendFields := if op.acceptsBackendField then #["backend"] else #[]
let allowed := #["op"] ++ backendFields ++ op.requestFields
let unexpected := fields.foldl (init := #[]) fun unexpected field _ =>
if allowed.contains field then unexpected else unexpected.push field
unless unexpected.isEmpty do
throw s!"broker op '{op.key}' accepts no undeclared or unrelated fields: {String.intercalate ", " unexpected.toList}"
| other => throw s!"broker request must be an object, got {other.compress}"
/-- Validate the few routing invariants that remain in the common request envelope. -/
def Request.validateFields (req : Request) : Except String Unit := do
if req.op.workspaceScope == .none && req.workspaceId?.isSome then
throw s!"broker op '{req.op.key}' accepts no unrelated field 'workspaceId'"
if let some workspaceId := req.workspaceId? then
if let some handle := req.handle? then
if workspaceId != handle.workspaceId then
throw s!"request workspace '{workspaceId}' does not match handle workspace '{handle.workspaceId}'"
private def optionalField? [FromJson α] (j : Json) (field : String) : Except String (Option α) := do
match j.getObjVal? field with
| .ok value =>
match fromJson? value with
| .ok decoded => pure (some decoded)
| .error err => throw s!"invalid '{field}': {err}"
| .error _ =>
pure none
private def requiredField [FromJson α] (j : Json) (field : String) : Except String α := do
let value ←
match j.getObjVal? field with
| .ok value => pure value
| .error _ => throw s!"missing '{field}'"
match fromJson? value with
| .ok decoded => pure decoded
| .error err => throw s!"invalid '{field}': {err}"
private def decodeRequestFile
(j : Json)
(backend : Backend) : Except String RequestFile := do
pure {
backend
path := ← requiredField j "path"
}
private def decodeRequestVersionedFile
(j : Json)
(backend : Backend) : Except String RequestVersionedFile := do
let target ← decodeRequestFile j backend
pure {
toRequestFile := target
version := ← requiredField j "version"
}
private def decodeRequestPosition
(j : Json)
(backend : Backend) : Except String RequestPosition := do
let target ← decodeRequestVersionedFile j backend
pure {
toRequestVersionedFile := target
line := ← requiredField j "line"
character := ← requiredField j "character"
}
instance : FromJson Request where
fromJson? j := do
let op ← j.getObjValAs? Op "op"
requireRequestJsonFields op j
let backend? ← optionalField? (α := Backend) j "backend"
let backend := backend?.getD .lean
let payload ←
match op with
| .ensure => pure <| .ensure { backend }
| .openDocs => pure .openDocs
| .cancel => pure <| .cancel (← requiredField j "cancelRequestId")
| .updateFile => .updateFile <$> decodeRequestFile j backend
| .syncFile | .refreshFile => do
let target ← decodeRequestFile j backend
let request : SyncFileRequest := {
toRequestFile := target
diagnosticScope? := ← optionalField? (α := DiagnosticScope) j "diagnosticScope"
diagnosticsInResult? := ← optionalField? (α := Bool) j "diagnosticsInResult"
}
pure <| if op == .syncFile then .syncFile request else .refreshFile request
| .close => do
let target ← decodeRequestFile j backend
pure <| .close {
toRequestFile := target
diagnosticScope? := ← optionalField? (α := DiagnosticScope) j "diagnosticScope"
saveArtifacts? := ← optionalField? (α := Bool) j "saveArtifacts"
}
| .runAt => do
let target ← decodeRequestPosition j backend
pure <| .runAt {
toRequestPosition := target
text := ← requiredField j "text"
storeHandle? := ← optionalField? (α := Bool) j "storeHandle"
}
| .hover | .signatureHelp | .definition => do
let target ← decodeRequestPosition j backend
pure <|
if op == .hover then .hover target
else if op == .signatureHelp then .signatureHelp target
else .definition target
| .references => do
let target ← decodeRequestPosition j backend
pure <| .references {
toRequestPosition := target
includeDeclaration? := ← optionalField? (α := Bool) j "includeDeclaration"
}
| .documentSymbols => .documentSymbols <$> decodeRequestVersionedFile j backend
| .workspaceSymbols =>
pure <| .workspaceSymbols {
backend
query := ← requiredField j "query"
}
| .codeActionResolve => do
let target ← decodeRequestVersionedFile j backend
pure <| .codeActionResolve {
toRequestVersionedFile := target
codeAction := ← requiredField j "codeAction"
}
| .saveOlean => do
let target ← decodeRequestFile j backend
pure <| .saveOlean {
toRequestFile := target
diagnosticScope? := ← optionalField? (α := DiagnosticScope) j "diagnosticScope"
}
| .goals => do
let target ← decodeRequestPosition j backend
pure <| .goals {
toRequestPosition := target
text? := ← optionalField? (α := String) j "text"
mode? := ← optionalField? (α := GoalMode) j "mode"
compact? := ← optionalField? (α := Bool) j "compact"
ppFormat? := ← optionalField? (α := GoalPpFormat) j "ppFormat"
}
| .todo => do
let target ← decodeRequestPosition j backend
pure <| .todo {
toRequestPosition := target
endLine := ← requiredField j "endLine"
endCharacter := ← requiredField j "endCharacter"
kinds? := ← optionalField? (α := Array Beam.LSP.Todo.TodoKind) j "kinds"
suggest? := ← optionalField? (α := Beam.LSP.Todo.TodoSuggestMode) j "suggest"
}
| .runWith => do
let handle ← requiredField j "handle"
pure <| .runWith {
path := ← requiredField j "path"
text := ← requiredField j "text"
storeHandle? := ← optionalField? (α := Bool) j "storeHandle"
linear? := ← optionalField? (α := Bool) j "linear"
handle
}
| .release => do
let handle ← requiredField j "handle"
pure <| .release {
path := ← requiredField j "path"
handle
}
| .initWorkspace =>
let leanCmd? ← optionalField? (α := String) j "leanCmd"
let leanPlugin? ← optionalField? (α := String) j "leanPlugin"
let lean? ←
match leanCmd?, leanPlugin? with
| none, none => pure none
| some command, some plugin => pure <| some { command, plugin }
| some _, none => throw "'leanCmd' requires 'leanPlugin'"
| none, some _ => throw "'leanPlugin' requires 'leanCmd'"
pure <| .initWorkspace {
workspaceMode? := ← optionalField? (α := Beam.Workspace.InitMode) j "workspaceMode"
root := ← requiredField j "root"
lean?
rocqCmd? := ← optionalField? (α := String) j "rocqCmd"
}
| .listWorkspaces => pure .listWorkspaces
| .dropWorkspace => pure .dropWorkspace
| .stats => pure .stats
| .shutdown => pure .shutdown
let request : Request := {
payload
workspaceId? := ← optionalField? (α := WorkspaceId) j "workspaceId"
clientRequestId? := ← optionalField? (α := String) j "clientRequestId"
daemonCapability? := ← optionalField? (α := String) j "daemonCapability"
}
request.validateFields
pure request
structure Error where
code : String
message : String := ""
data? : Option Json := none
deriving Inhabited, FromJson, ToJson
structure SyncFileProgress where
updates : Nat := 0
done : Bool := true
/-- Earliest one-based line in Lean's current processing ranges, when any range is active. -/
rangeStartLine? : Option Nat := none
/-- One-based upper line bound from Lean's processing ranges; not the source file line count. -/
rangeEndLine? : Option Nat := none
deriving Inhabited, FromJson, ToJson, BEq, Repr
namespace SyncFileProgress
def rangeText? (progress : SyncFileProgress) : Option String :=
match progress.rangeStartLine?, progress.rangeEndLine? with
| some startLine, some endLine => some s!"range={startLine}..{endLine}"
| some startLine, none => some s!"rangeStartLine={startLine}"
| none, some endLine => some s!"rangeEndLine={endLine}"
| none, none => none
def displayDetails (progress : SyncFileProgress) (includeDoneTrue : Bool := true) : String :=
let rangePrefix :=
match progress.rangeText? with
| some text => text ++ " "
| none => ""
let doneSuffix :=
if progress.done then
if includeDoneTrue then
" done=true"
else
""
else
" done=false"
s!"{rangePrefix}updates={progress.updates}{doneSuffix}"
end SyncFileProgress
private def requireOnlyJsonFields
(label : String)
(allowed : Array String) : Json → Except String Unit
| .obj fields =>
let unexpected := fields.foldl (init := #[]) fun unexpected field _ =>
if allowed.contains field then unexpected else unexpected.push field
unless unexpected.isEmpty do
throw s!"{label} accepts no undeclared fields: {String.intercalate ", " unexpected.toList}"
| other => throw s!"{label} must be an object, got {other.compress}"
structure SyncDiagnosticCounts where
error : Nat := 0
warning : Nat := 0
information : Nat := 0
hint : Nat := 0
unknown : Nat := 0
deriving Inhabited, BEq, Repr
def SyncDiagnosticCounts.total (counts : SyncDiagnosticCounts) : Nat :=
counts.error + counts.warning + counts.information + counts.hint + counts.unknown
instance : ToJson SyncDiagnosticCounts where
toJson counts := Json.mkObj [
("error", toJson counts.error),
("warning", toJson counts.warning),
("information", toJson counts.information),
("hint", toJson counts.hint),
("unknown", toJson counts.unknown),
("total", toJson counts.total)
]
instance : FromJson SyncDiagnosticCounts where
fromJson? json := do
requireOnlyJsonFields "sync diagnostic counts"
#["error", "warning", "information", "hint", "unknown", "total"] json
let errorCount ← json.getObjValAs? Nat "error"
let warning ← json.getObjValAs? Nat "warning"
let information ← json.getObjValAs? Nat "information"
let hint ← json.getObjValAs? Nat "hint"
let unknown ← json.getObjValAs? Nat "unknown"
let total ← json.getObjValAs? Nat "total"
let severityTotal := errorCount + warning + information + hint + unknown
unless total == severityTotal do
throw s!"sync diagnostic count total {total} does not match severity sum {severityTotal}"
pure {
error := errorCount
warning
information
hint
unknown
}
structure SyncBlockingDiagnostic where
range : Lsp.Range
severity? : Option Lsp.DiagnosticSeverity := some .error
message : String
saveBlocking : Bool := false
completionBlocking : Bool := false
deriving Inhabited, ToJson, BEq, Repr
instance : FromJson SyncBlockingDiagnostic where
fromJson? json := do
requireOnlyJsonFields "sync blocking diagnostic"
#["range", "severity", "message", "saveBlocking", "completionBlocking"] json
let range ← json.getObjValAs? Lsp.Range "range"
let severity? ← optionalField? (α := Lsp.DiagnosticSeverity) json "severity"
let message ← json.getObjValAs? String "message"
let saveBlocking? ← optionalField? (α := Bool) json "saveBlocking"
let completionBlocking? ← optionalField? (α := Bool) json "completionBlocking"
pure {
range
severity?
message
saveBlocking := saveBlocking?.getD false
completionBlocking := completionBlocking?.getD false
}
structure SyncBlockingCommandMessage where
message : String
saveBlocking : Bool := true
completionBlocking : Bool := false
deriving Inhabited, ToJson, BEq, Repr
instance : FromJson SyncBlockingCommandMessage where
fromJson? json := do
requireOnlyJsonFields "sync blocking message"
#["message", "saveBlocking", "completionBlocking"] json
let message ← json.getObjValAs? String "message"
let saveBlocking? ← optionalField? (α := Bool) json "saveBlocking"
let completionBlocking? ← optionalField? (α := Bool) json "completionBlocking"
pure {
message
saveBlocking := saveBlocking?.getD true
completionBlocking := completionBlocking?.getD false
}
structure SyncResultReadiness where
saveReady : Bool := true
reason : String := "ok"
/-- Number of save-blocking errors, including command messages that have no diagnostic. -/
blockingErrorCount : Nat := 0
blockingDiagnostics : Array SyncBlockingDiagnostic := #[]
blockingMessages : Array SyncBlockingCommandMessage := #[]
deriving Inhabited, ToJson, BEq, Repr
instance : FromJson SyncResultReadiness where
fromJson? json := do
requireOnlyJsonFields "sync readiness"
#["saveReady", "reason", "blockingErrorCount", "blockingDiagnostics", "blockingMessages"]
json
let saveReady ← json.getObjValAs? Bool "saveReady"
let reason ← json.getObjValAs? String "reason"
let blockingErrorCount ← json.getObjValAs? Nat "blockingErrorCount"
let blockingDiagnostics ←
json.getObjValAs? (Array SyncBlockingDiagnostic) "blockingDiagnostics"
let blockingMessages ←
json.getObjValAs? (Array SyncBlockingCommandMessage) "blockingMessages"
pure {
saveReady
reason
blockingErrorCount
blockingDiagnostics
blockingMessages
}
structure StreamDiagnostic where
path : String
uri : String
version? : Option Int := none
severity? : Option Lsp.DiagnosticSeverity := none
range : Lsp.Range
message : String
saveBlocking? : Option Bool := none
completionBlocking : Bool := false
deriving Inhabited, ToJson
instance : FromJson StreamDiagnostic where
fromJson? json := do
requireOnlyJsonFields "stream diagnostic"
#[
"path", "uri", "version", "severity", "range", "message", "saveBlocking",
"completionBlocking"
] json
let path ← json.getObjValAs? String "path"
let uri ← json.getObjValAs? String "uri"
let version? ← optionalField? (α := Int) json "version"
let severity? ← optionalField? (α := Lsp.DiagnosticSeverity) json "severity"
let range ← json.getObjValAs? Lsp.Range "range"
let message ← json.getObjValAs? String "message"
let saveBlocking? ← optionalField? (α := Bool) json "saveBlocking"
let completionBlocking? ← optionalField? (α := Bool) json "completionBlocking"
pure {
path
uri
version?
severity?
range
message
saveBlocking?
completionBlocking := completionBlocking?.getD false
}
structure SyncResultDiagnostics where
counts : SyncDiagnosticCounts := {}
items? : Option (Array StreamDiagnostic) := none
deriving Inhabited
instance : ToJson SyncResultDiagnostics where
toJson diagnostics :=
Json.mkObj <|
[("counts", toJson diagnostics.counts)] ++
match diagnostics.items? with
| some items => [("items", toJson items)]
| none => []
instance : FromJson SyncResultDiagnostics where
fromJson? json := do
requireOnlyJsonFields "sync diagnostics" #["counts", "items"] json
let counts ← json.getObjValAs? SyncDiagnosticCounts "counts"
let items? ← optionalField? (α := Array StreamDiagnostic) json "items"
pure { counts, items? }
structure SyncFileResult where
path : String