-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathhandler.go
1759 lines (1559 loc) · 58.2 KB
/
handler.go
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
package handler
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/arduino/arduino-cli/arduino/builder"
"github.com/arduino/arduino-cli/executils"
"github.com/arduino/go-paths-helper"
"github.com/bcmi-labs/arduino-language-server/handler/sourcemapper"
"github.com/bcmi-labs/arduino-language-server/handler/textutils"
"github.com/bcmi-labs/arduino-language-server/lsp"
"github.com/bcmi-labs/arduino-language-server/streams"
"github.com/fatih/color"
"github.com/pkg/errors"
"github.com/sourcegraph/jsonrpc2"
)
var globalCliPath string
var globalClangdPath string
var enableLogging bool
// Setup initializes global variables.
func Setup(cliPath string, clangdPath string, _enableLogging bool) {
globalCliPath = cliPath
globalClangdPath = clangdPath
enableLogging = _enableLogging
}
// CLangdStarter starts clangd and returns its stdin/out/err
type CLangdStarter func() (stdin io.WriteCloser, stdout io.ReadCloser, stderr io.ReadCloser)
// InoHandler is a JSON-RPC handler that delegates messages to clangd.
type InoHandler struct {
StdioConn *jsonrpc2.Conn
ClangdConn *jsonrpc2.Conn
stdioNotificationCount int64
clangdNotificationCount int64
progressHandler *ProgressProxyHandler
closing chan bool
clangdStarted *sync.Cond
dataMux sync.RWMutex
lspInitializeParams *lsp.InitializeParams
buildPath *paths.Path
buildSketchRoot *paths.Path
buildSketchCpp *paths.Path
buildSketchCppVersion int
buildSketchSymbols []lsp.DocumentSymbol
buildSketchIncludesCanary string
buildSketchSymbolsCanary string
buildSketchSymbolsLoad bool
buildSketchSymbolsCheck bool
rebuildSketchDeadline *time.Time
rebuildSketchDeadlineMutex sync.Mutex
sketchRoot *paths.Path
sketchName string
sketchMapper *sourcemapper.InoMapper
sketchTrackedFilesCount int
docs map[string]*lsp.TextDocumentItem
inoDocsWithDiagnostics map[lsp.DocumentURI]bool
config lsp.BoardConfig
}
var yellow = color.New(color.FgHiYellow)
func (handler *InoHandler) dataLock(msg string) {
handler.dataMux.Lock()
log.Println(msg + yellow.Sprintf(" locked"))
}
func (handler *InoHandler) dataUnlock(msg string) {
log.Println(msg + yellow.Sprintf(" unlocked"))
handler.dataMux.Unlock()
}
func (handler *InoHandler) dataRLock(msg string) {
handler.dataMux.RLock()
log.Println(msg + yellow.Sprintf(" read-locked"))
}
func (handler *InoHandler) dataRUnlock(msg string) {
log.Println(msg + yellow.Sprintf(" read-unlocked"))
handler.dataMux.RUnlock()
}
func (handler *InoHandler) waitClangdStart(prefix string) error {
if handler.ClangdConn != nil {
return nil
}
log.Printf(prefix + "(throttled: waiting for clangd)")
log.Println(prefix + yellow.Sprintf(" unlocked (waiting clangd)"))
handler.clangdStarted.Wait()
log.Println(prefix + yellow.Sprintf(" locked (waiting clangd)"))
if handler.ClangdConn == nil {
log.Printf(prefix + "clangd startup failed: aborting call")
return errors.New("could not start clangd, aborted")
}
return nil
}
// NewInoHandler creates and configures an InoHandler.
func NewInoHandler(stdio io.ReadWriteCloser, board lsp.Board) *InoHandler {
handler := &InoHandler{
docs: map[string]*lsp.TextDocumentItem{},
inoDocsWithDiagnostics: map[lsp.DocumentURI]bool{},
closing: make(chan bool),
config: lsp.BoardConfig{
SelectedBoard: board,
},
}
handler.clangdStarted = sync.NewCond(&handler.dataMux)
if buildPath, err := paths.MkTempDir("", "arduino-language-server"); err != nil {
log.Fatalf("Could not create temp folder: %s", err)
} else {
handler.buildPath = buildPath.Canonical()
handler.buildSketchRoot = handler.buildPath.Join("sketch")
}
if enableLogging {
log.Println("Initial board configuration:", board)
log.Println("Language server build path:", handler.buildPath)
log.Println("Language server build sketch root:", handler.buildSketchRoot)
}
stdStream := jsonrpc2.NewBufferedStream(stdio, jsonrpc2.VSCodeObjectCodec{})
var stdHandler jsonrpc2.Handler = jsonrpc2.HandlerWithError(handler.HandleMessageFromIDE)
handler.StdioConn = jsonrpc2.NewConn(context.Background(), stdStream, stdHandler,
jsonrpc2.OnRecv(streams.JSONRPCConnLogOnRecv("IDE --> LS CL:")),
jsonrpc2.OnSend(streams.JSONRPCConnLogOnSend("IDE <-- LS CL:")),
)
handler.progressHandler = NewProgressProxy(handler.StdioConn)
go handler.rebuildEnvironmentLoop()
return handler
}
// FileData gathers information on a .ino source file.
type FileData struct {
sourceText string
sourceURI lsp.DocumentURI
targetURI lsp.DocumentURI
sourceMap *sourcemapper.InoMapper
version int
}
// Close closes all the json-rpc connections.
func (handler *InoHandler) Close() {
if handler.ClangdConn != nil {
handler.ClangdConn.Close()
handler.ClangdConn = nil
}
if handler.closing != nil {
close(handler.closing)
handler.closing = nil
}
}
// CloseNotify returns a channel that is closed when the InoHandler is closed
func (handler *InoHandler) CloseNotify() <-chan bool {
return handler.closing
}
// CleanUp performs cleanup of the workspace and temp files create by the language server
func (handler *InoHandler) CleanUp() {
if handler.buildPath != nil {
log.Printf("removing buildpath")
handler.buildPath.RemoveAll()
handler.buildPath = nil
}
}
// HandleMessageFromIDE handles a message received from the IDE client (via stdio).
func (handler *InoHandler) HandleMessageFromIDE(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (interface{}, error) {
defer streams.CatchAndLogPanic()
prefix := "IDE --> "
if req.Notif {
n := atomic.AddInt64(&handler.stdioNotificationCount, 1)
prefix += fmt.Sprintf("%s notif%d ", req.Method, n)
} else {
prefix += fmt.Sprintf("%s %v ", req.Method, req.ID)
}
params, err := lsp.ReadParams(req.Method, req.Params)
if err != nil {
return nil, err
}
if params == nil {
params = req.Params
}
// Set up RWLocks and wait for clangd startup
switch req.Method {
case // Write lock - NO clangd required
"initialize":
handler.dataLock(prefix)
defer handler.dataUnlock(prefix)
case // Write lock - clangd required
"textDocument/didOpen",
"textDocument/didChange",
"textDocument/didClose":
handler.dataLock(prefix)
defer handler.dataUnlock(prefix)
handler.waitClangdStart(prefix)
case // Read lock - NO clangd required
"initialized":
handler.dataRLock(prefix)
defer handler.dataRUnlock(prefix)
default: // Read lock - clangd required
handler.dataRLock(prefix)
// if clangd is not started...
if handler.ClangdConn == nil {
// Release the read lock and acquire a write lock
// (this is required to wait on condition variable).
handler.dataRUnlock(prefix)
handler.dataLock(prefix)
defer handler.dataUnlock(prefix)
handler.waitClangdStart(prefix)
} else {
defer handler.dataRUnlock(prefix)
}
}
// Handle LSP methods: transform parameters and send to clangd
var inoURI, cppURI lsp.DocumentURI
switch p := params.(type) {
case *lsp.InitializeParams:
// method "initialize"
go func() {
defer streams.CatchAndLogPanic()
prefix := "INIT--- "
log.Printf(prefix + "initializing workbench")
// Start clangd asynchronously
handler.dataLock(prefix)
defer handler.dataUnlock(prefix)
handler.initializeWorkbench(ctx, p)
// clangd should be running now...
handler.clangdStarted.Broadcast()
log.Printf(prefix + "initializing workbench (done)")
}()
T := true
F := false
return &lsp.InitializeResult{
Capabilities: lsp.ServerCapabilities{
TextDocumentSync: &lsp.TextDocumentSyncOptionsOrKind{Kind: &lsp.TDSKIncremental},
HoverProvider: true,
CompletionProvider: &lsp.CompletionOptions{
TriggerCharacters: []string{".", "\u003e", ":"},
},
SignatureHelpProvider: &lsp.SignatureHelpOptions{
TriggerCharacters: []string{"(", ","},
},
DefinitionProvider: true,
ReferencesProvider: false, // TODO: true
DocumentHighlightProvider: true,
DocumentSymbolProvider: true,
WorkspaceSymbolProvider: true,
CodeActionProvider: &lsp.BoolOrCodeActionOptions{IsProvider: &T},
DocumentFormattingProvider: true,
DocumentRangeFormattingProvider: true,
DocumentOnTypeFormattingProvider: &lsp.DocumentOnTypeFormattingOptions{
FirstTriggerCharacter: "\n",
},
RenameProvider: &lsp.BoolOrRenameOptions{IsProvider: &F}, // TODO: &T
ExecuteCommandProvider: &lsp.ExecuteCommandOptions{
Commands: []string{"clangd.applyFix", "clangd.applyTweak"},
},
},
}, nil
case *lsp.InitializedParams:
// method "initialized"
log.Println(prefix + "notification is not propagated to clangd")
return nil, nil // Do not propagate to clangd
case *lsp.DidOpenTextDocumentParams:
// method "textDocument/didOpen"
inoURI = p.TextDocument.URI
log.Printf(prefix+"(%s@%d as '%s')", p.TextDocument.URI, p.TextDocument.Version, p.TextDocument.LanguageID)
if res, e := handler.didOpen(p); e != nil {
params = nil
err = e
} else if res == nil {
log.Println(prefix + "notification is not propagated to clangd")
return nil, nil // do not propagate to clangd
} else {
log.Printf(prefix+"to clang: didOpen(%s@%d as '%s')", res.TextDocument.URI, res.TextDocument.Version, res.TextDocument.LanguageID)
params = res
}
case *lsp.DidCloseTextDocumentParams:
// Method: "textDocument/didClose"
inoURI = p.TextDocument.URI
log.Printf("--> didClose(%s)", p.TextDocument.URI)
if res, e := handler.didClose(p); e != nil {
} else if res == nil {
log.Println(" --X notification is not propagated to clangd")
return nil, nil // do not propagate to clangd
} else {
log.Printf(" --> didClose(%s)", res.TextDocument.URI)
params = res
}
case *lsp.DidChangeTextDocumentParams:
// notification "textDocument/didChange"
inoURI = p.TextDocument.URI
log.Printf("--> didChange(%s@%d)", p.TextDocument.URI, p.TextDocument.Version)
for _, change := range p.ContentChanges {
log.Printf(" > %s -> %s", change.Range, strconv.Quote(change.Text))
}
if res, err := handler.didChange(ctx, p); err != nil {
log.Printf(" --E error: %s", err)
return nil, err
} else if res == nil {
log.Println(" --X notification is not propagated to clangd")
return nil, err // do not propagate to clangd
} else {
p = res
}
log.Printf(" --> didChange(%s@%d)", p.TextDocument.URI, p.TextDocument.Version)
for _, change := range p.ContentChanges {
log.Printf(" > %s -> %s", change.Range, strconv.Quote(change.Text))
}
err = handler.ClangdConn.Notify(ctx, req.Method, p)
return nil, err
case *lsp.CompletionParams:
// method: "textDocument/completion"
inoURI = p.TextDocument.URI
log.Printf("--> completion(%s:%d:%d)\n", p.TextDocument.URI, p.Position.Line, p.Position.Character)
if res, e := handler.ino2cppTextDocumentPositionParams(&p.TextDocumentPositionParams); e == nil {
p.TextDocumentPositionParams = *res
log.Printf(" --> completion(%s:%d:%d)\n", p.TextDocument.URI, p.Position.Line, p.Position.Character)
} else {
err = e
}
case *lsp.CodeActionParams:
// method "textDocument/codeAction"
inoURI = p.TextDocument.URI
log.Printf("--> codeAction(%s:%s)", p.TextDocument.URI, p.Range.Start)
p.TextDocument, err = handler.ino2cppTextDocumentIdentifier(p.TextDocument)
if err != nil {
break
}
if p.TextDocument.URI.AsPath().EquivalentTo(handler.buildSketchCpp) {
p.Range = handler.sketchMapper.InoToCppLSPRange(inoURI, p.Range)
for index := range p.Context.Diagnostics {
r := &p.Context.Diagnostics[index].Range
*r = handler.sketchMapper.InoToCppLSPRange(inoURI, *r)
}
}
log.Printf(" --> codeAction(%s:%s)", p.TextDocument.URI, p.Range.Start)
case *lsp.HoverParams:
// method: "textDocument/hover"
inoURI = p.TextDocument.URI
doc := &p.TextDocumentPositionParams
log.Printf("--> hover(%s:%d:%d)\n", doc.TextDocument.URI, doc.Position.Line, doc.Position.Character)
if res, e := handler.ino2cppTextDocumentPositionParams(doc); e == nil {
p.TextDocumentPositionParams = *res
log.Printf(" --> hover(%s:%d:%d)\n", doc.TextDocument.URI, doc.Position.Line, doc.Position.Character)
} else {
err = e
}
case *lsp.DocumentSymbolParams:
// method "textDocument/documentSymbol"
inoURI = p.TextDocument.URI
log.Printf("--> documentSymbol(%s)", p.TextDocument.URI)
p.TextDocument, err = handler.ino2cppTextDocumentIdentifier(p.TextDocument)
log.Printf(" --> documentSymbol(%s)", p.TextDocument.URI)
case *lsp.DocumentFormattingParams:
// method "textDocument/formatting"
inoURI = p.TextDocument.URI
log.Printf("--> formatting(%s)", p.TextDocument.URI)
p.TextDocument, err = handler.ino2cppTextDocumentIdentifier(p.TextDocument)
cppURI = p.TextDocument.URI
log.Printf(" --> formatting(%s)", p.TextDocument.URI)
case *lsp.DocumentRangeFormattingParams:
// Method: "textDocument/rangeFormatting"
log.Printf("--> %s(%s:%s)", req.Method, p.TextDocument.URI, p.Range)
inoURI = p.TextDocument.URI
if cppParams, e := handler.ino2cppDocumentRangeFormattingParams(p); e == nil {
params = cppParams
cppURI = cppParams.TextDocument.URI
log.Printf(" --> %s(%s:%s)", req.Method, cppParams.TextDocument.URI, cppParams.Range)
} else {
err = e
}
case *lsp.TextDocumentPositionParams:
// Method: "textDocument/signatureHelp"
// Method: "textDocument/definition"
// Method: "textDocument/typeDefinition"
// Method: "textDocument/implementation"
// Method: "textDocument/documentHighlight"
log.Printf("--> %s(%s:%s)", req.Method, p.TextDocument.URI, p.Position)
inoURI = p.TextDocument.URI
if res, e := handler.ino2cppTextDocumentPositionParams(p); e == nil {
cppURI = res.TextDocument.URI
params = res
log.Printf(" --> %s(%s:%s)", req.Method, res.TextDocument.URI, res.Position)
} else {
err = e
}
case *lsp.DidSaveTextDocumentParams:
// Method: "textDocument/didSave"
log.Printf("--> %s(%s)", req.Method, p.TextDocument.URI)
inoURI = p.TextDocument.URI
p.TextDocument, err = handler.ino2cppTextDocumentIdentifier(p.TextDocument)
cppURI = p.TextDocument.URI
if cppURI.AsPath().EquivalentTo(handler.buildSketchCpp) {
log.Printf(" --| didSave not forwarded to clangd")
return nil, nil
}
log.Printf(" --> %s(%s)", req.Method, p.TextDocument.URI)
case *lsp.ReferenceParams: // "textDocument/references":
log.Printf("--X " + req.Method)
return nil, nil
inoURI = p.TextDocument.URI
_, err = handler.ino2cppTextDocumentPositionParams(&p.TextDocumentPositionParams)
case *lsp.DocumentOnTypeFormattingParams: // "textDocument/onTypeFormatting":
log.Printf("--X " + req.Method)
return nil, nil
inoURI = p.TextDocument.URI
err = handler.ino2cppDocumentOnTypeFormattingParams(p)
case *lsp.RenameParams: // "textDocument/rename":
log.Printf("--X " + req.Method)
return nil, nil
inoURI = p.TextDocument.URI
err = handler.ino2cppRenameParams(p)
case *lsp.DidChangeWatchedFilesParams: // "workspace/didChangeWatchedFiles":
log.Printf("--X " + req.Method)
return nil, nil
err = handler.ino2cppDidChangeWatchedFilesParams(p)
case *lsp.ExecuteCommandParams: // "workspace/executeCommand":
log.Printf("--X " + req.Method)
return nil, nil
err = handler.ino2cppExecuteCommand(p)
}
if err != nil {
log.Printf(prefix+"Error: %s", err)
return nil, err
}
var result interface{}
if req.Notif {
log.Printf(prefix + "sent to Clang")
err = handler.ClangdConn.Notify(ctx, req.Method, params)
} else {
log.Printf(prefix + "sent to Clang")
result, err = lsp.SendRequest(ctx, handler.ClangdConn, req.Method, params)
}
if err == nil && handler.buildSketchSymbolsLoad {
handler.buildSketchSymbolsLoad = false
handler.buildSketchSymbolsCheck = false
log.Println(prefix + "Queued resfreshing document symbols")
go handler.LoadCppDocumentSymbols()
}
if err == nil && handler.buildSketchSymbolsCheck {
handler.buildSketchSymbolsCheck = false
log.Println(prefix + "Queued check document symbols")
go handler.CheckCppDocumentSymbols()
}
if err != nil {
// Exit the process and trigger a restart by the client in case of a severe error
if err.Error() == "context deadline exceeded" {
log.Println(prefix + "Timeout exceeded while waiting for a reply from clangd.")
log.Println(prefix + "Please restart the language server.")
handler.Close()
}
if strings.Contains(err.Error(), "non-added document") || strings.Contains(err.Error(), "non-added file") {
log.Printf(prefix + "The clangd process has lost track of the open document.")
log.Printf(prefix+" %s", err)
log.Println(prefix + "Please restart the language server.")
handler.Close()
}
}
// Transform and return the result
if result != nil {
result = handler.transformClangdResult(req.Method, inoURI, cppURI, result)
}
return result, err
}
func (handler *InoHandler) initializeWorkbench(ctx context.Context, params *lsp.InitializeParams) error {
currCppTextVersion := 0
if params != nil {
log.Printf(" --> initialize(%s)\n", params.RootURI)
handler.lspInitializeParams = params
handler.sketchRoot = params.RootURI.AsPath()
handler.sketchName = handler.sketchRoot.Base()
} else {
log.Printf(" --> RE-initialize()\n")
currCppTextVersion = handler.sketchMapper.CppText.Version
}
if err := handler.generateBuildEnvironment(handler.buildPath); err != nil {
return err
}
handler.buildSketchCpp = handler.buildSketchRoot.Join(handler.sketchName + ".ino.cpp")
handler.buildSketchCppVersion = 1
handler.lspInitializeParams.RootPath = handler.buildSketchRoot.String()
handler.lspInitializeParams.RootURI = lsp.NewDocumentURIFromPath(handler.buildSketchRoot)
if cppContent, err := handler.buildSketchCpp.ReadFile(); err == nil {
handler.sketchMapper = sourcemapper.CreateInoMapper(cppContent)
handler.sketchMapper.CppText.Version = currCppTextVersion + 1
} else {
return errors.WithMessage(err, "reading generated cpp file from sketch")
}
canonicalizeCompileCommandsJSON(handler.buildPath)
if params == nil {
// If we are restarting re-synchronize clangd
cppURI := lsp.NewDocumentURIFromPath(handler.buildSketchCpp)
cppTextDocumentIdentifier := lsp.TextDocumentIdentifier{URI: cppURI}
syncEvent := &lsp.DidChangeTextDocumentParams{
TextDocument: lsp.VersionedTextDocumentIdentifier{
TextDocumentIdentifier: cppTextDocumentIdentifier,
Version: handler.sketchMapper.CppText.Version,
},
ContentChanges: []lsp.TextDocumentContentChangeEvent{
{Text: handler.sketchMapper.CppText.Text}, // Full text change
},
}
if err := handler.ClangdConn.Notify(ctx, "textDocument/didChange", syncEvent); err != nil {
log.Println(" error reinitilizing clangd:", err)
return err
}
} else {
// Otherwise start clangd!
dataFolder, err := extractDataFolderFromArduinoCLI()
if err != nil {
log.Printf(" error: %s", err)
}
clangdStdout, clangdStdin, clangdStderr := startClangd(handler.buildPath, handler.buildSketchCpp, dataFolder)
clangdStdio := streams.NewReadWriteCloser(clangdStdin, clangdStdout)
if enableLogging {
clangdStdio = streams.LogReadWriteCloserAs(clangdStdio, "inols-clangd.log")
go io.Copy(streams.OpenLogFileAs("inols-clangd-err.log"), clangdStderr)
} else {
go io.Copy(os.Stderr, clangdStderr)
}
clangdStream := jsonrpc2.NewBufferedStream(clangdStdio, jsonrpc2.VSCodeObjectCodec{})
clangdHandler := AsyncHandler{jsonrpc2.HandlerWithError(handler.FromClangd)}
handler.ClangdConn = jsonrpc2.NewConn(context.Background(), clangdStream, clangdHandler,
jsonrpc2.OnRecv(streams.JSONRPCConnLogOnRecv("IDE LS <-- CL:")),
jsonrpc2.OnSend(streams.JSONRPCConnLogOnSend("IDE LS --> CL:")))
go func() {
<-handler.ClangdConn.DisconnectNotify()
log.Printf("Lost connection with clangd!")
handler.Close()
}()
// Send initialization command to clangd
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
var resp lsp.InitializeResult
if err := handler.ClangdConn.Call(ctx, "initialize", handler.lspInitializeParams, &resp); err != nil {
log.Println(" error initilizing clangd:", err)
return err
}
if err := handler.ClangdConn.Notify(ctx, "initialized", lsp.InitializedParams{}); err != nil {
log.Println(" error sending initialize to clangd:", err)
return err
}
}
handler.buildSketchSymbolsLoad = true
return nil
}
func extractDataFolderFromArduinoCLI() (*paths.Path, error) {
// XXX: do this from IDE or via gRPC
args := []string{globalCliPath,
"config",
"dump",
"--format", "json",
}
cmd, err := executils.NewProcess(args...)
if err != nil {
return nil, errors.Errorf("running %s: %s", strings.Join(args, " "), err)
}
cmdOutput := &bytes.Buffer{}
cmd.RedirectStdoutTo(cmdOutput)
log.Println("running: ", strings.Join(args, " "))
if err := cmd.Run(); err != nil {
return nil, errors.Errorf("running %s: %s", strings.Join(args, " "), err)
}
type cmdRes struct {
Directories struct {
Data string `json:"data"`
} `json:"directories"`
}
var res cmdRes
if err := json.Unmarshal(cmdOutput.Bytes(), &res); err != nil {
return nil, errors.Errorf("parsing arduino-cli output: %s", err)
}
// Return only the build path
log.Println("Arduino Data Dir -> ", res.Directories.Data)
return paths.New(res.Directories.Data), nil
}
func (handler *InoHandler) refreshCppDocumentSymbols(prefix string) error {
// Query source code symbols
cppURI := lsp.NewDocumentURIFromPath(handler.buildSketchCpp)
log.Printf(prefix+"requesting documentSymbol for %s", cppURI)
handler.dataRUnlock(prefix)
result, err := lsp.SendRequest(context.Background(), handler.ClangdConn, "textDocument/documentSymbol", &lsp.DocumentSymbolParams{
TextDocument: lsp.TextDocumentIdentifier{URI: cppURI},
})
handler.dataRLock(prefix)
if err != nil {
log.Printf(prefix+"error: %s", err)
return errors.WithMessage(err, "quering source code symbols")
}
symbolResult, ok := result.(*lsp.DocumentSymbolArrayOrSymbolInformationArray)
if !ok || symbolResult.DocumentSymbolArray == nil {
log.Printf(prefix + "error: expected DocumenSymbol array from clangd")
return errors.New("expected array from clangd")
}
symbols := *symbolResult.DocumentSymbolArray
// Filter non-functions symbols
i := 0
for _, symbol := range symbols {
if symbol.Kind != lsp.SKFunction {
continue
}
symbols[i] = symbol
i++
}
symbols = symbols[:i]
handler.buildSketchSymbols = symbols
symbolsCanary := ""
for _, symbol := range symbols {
log.Printf(prefix+" symbol: %s %s %s", symbol.Kind, symbol.Name, symbol.Range)
if symbolText, err := textutils.ExtractRange(handler.sketchMapper.CppText.Text, symbol.Range); err != nil {
log.Printf(prefix+" > invalid range: %s", err)
symbolsCanary += "/"
} else if end := strings.Index(symbolText, "{"); end != -1 {
log.Printf(prefix+" TRIMMED> %s", symbolText[:end])
symbolsCanary += symbolText[:end]
} else {
log.Printf(prefix+" > %s", symbolText)
symbolsCanary += symbolText
}
}
handler.buildSketchSymbolsCanary = symbolsCanary
return nil
}
func (handler *InoHandler) LoadCppDocumentSymbols() error {
prefix := "SYLD--- "
defer log.Printf(prefix + "(done)")
handler.dataRLock(prefix)
defer handler.dataRUnlock(prefix)
return handler.refreshCppDocumentSymbols(prefix)
}
func (handler *InoHandler) CheckCppDocumentSymbols() error {
prefix := "SYCK--- "
defer log.Printf(prefix + "(done)")
handler.dataRLock(prefix)
defer handler.dataRUnlock(prefix)
oldSymbols := handler.buildSketchSymbols
canary := handler.buildSketchSymbolsCanary
if err := handler.refreshCppDocumentSymbols(prefix); err != nil {
return err
}
if len(oldSymbols) != len(handler.buildSketchSymbols) || canary != handler.buildSketchSymbolsCanary {
log.Println(prefix + "function symbols change detected, triggering sketch rebuild!")
handler.scheduleRebuildEnvironment()
}
return nil
}
func (handler *InoHandler) CheckCppIncludesChanges() {
prefix := "INCK--- "
includesCanary := ""
for _, line := range strings.Split(handler.sketchMapper.CppText.Text, "\n") {
if strings.Contains(line, "#include ") {
includesCanary += line
}
}
if includesCanary != handler.buildSketchIncludesCanary {
handler.buildSketchIncludesCanary = includesCanary
log.Println(prefix + "#include change detected, triggering sketch rebuild!")
handler.scheduleRebuildEnvironment()
}
}
func canonicalizeCompileCommandsJSON(compileCommandsDir *paths.Path) map[string]bool {
// Open compile_commands.json and find the main cross-compiler executable
compileCommandsJSONPath := compileCommandsDir.Join("compile_commands.json")
compileCommands, err := builder.LoadCompilationDatabase(compileCommandsJSONPath)
if err != nil {
panic("could not find compile_commands.json")
}
compilers := map[string]bool{}
for i, cmd := range compileCommands.Contents {
if len(cmd.Arguments) == 0 {
panic("invalid empty argument field in compile_commands.json")
}
// clangd requires full path to compiler (including extension .exe on Windows!)
compilerPath := paths.New(cmd.Arguments[0]).Canonical()
compiler := compilerPath.String()
if runtime.GOOS == "windows" && strings.ToLower(compilerPath.Ext()) != ".exe" {
compiler += ".exe"
}
compileCommands.Contents[i].Arguments[0] = compiler
compilers[compiler] = true
}
// Save back compile_commands.json with OS native file separator and extension
compileCommands.SaveToFile()
return compilers
}
func startClangd(compileCommandsDir, sketchCpp *paths.Path, dataFolder *paths.Path) (io.WriteCloser, io.ReadCloser, io.ReadCloser) {
// Start clangd
args := []string{
globalClangdPath,
"-log=verbose",
fmt.Sprintf(`--compile-commands-dir=%s`, compileCommandsDir),
}
if dataFolder != nil {
args = append(args, fmt.Sprintf("-query-driver=%s", dataFolder.Join("packages", "**")))
}
if enableLogging {
log.Println(" Starting clangd:", strings.Join(args, " "))
}
if clangdCmd, err := executils.NewProcess(args...); err != nil {
panic("starting clangd: " + err.Error())
} else if clangdIn, err := clangdCmd.StdinPipe(); err != nil {
panic("getting clangd stdin: " + err.Error())
} else if clangdOut, err := clangdCmd.StdoutPipe(); err != nil {
panic("getting clangd stdout: " + err.Error())
} else if clangdErr, err := clangdCmd.StderrPipe(); err != nil {
panic("getting clangd stderr: " + err.Error())
} else if err := clangdCmd.Start(); err != nil {
panic("running clangd: " + err.Error())
} else {
return clangdIn, clangdOut, clangdErr
}
}
func (handler *InoHandler) didOpen(inoDidOpen *lsp.DidOpenTextDocumentParams) (*lsp.DidOpenTextDocumentParams, error) {
// Add the TextDocumentItem in the tracked files list
inoItem := inoDidOpen.TextDocument
handler.docs[inoItem.URI.AsPath().String()] = &inoItem
// If we are tracking a .ino...
if inoItem.URI.Ext() == ".ino" {
handler.sketchTrackedFilesCount++
log.Printf(" increasing .ino tracked files count: %d", handler.sketchTrackedFilesCount)
// notify clang that sketchCpp has been opened only once
if handler.sketchTrackedFilesCount != 1 {
return nil, nil
}
}
cppItem, err := handler.ino2cppTextDocumentItem(inoItem)
return &lsp.DidOpenTextDocumentParams{
TextDocument: cppItem,
}, err
}
func (handler *InoHandler) didClose(inoDidClose *lsp.DidCloseTextDocumentParams) (*lsp.DidCloseTextDocumentParams, error) {
inoIdentifier := inoDidClose.TextDocument
if _, exist := handler.docs[inoIdentifier.URI.AsPath().String()]; exist {
delete(handler.docs, inoIdentifier.URI.AsPath().String())
} else {
log.Printf(" didClose of untracked document: %s", inoIdentifier.URI)
return nil, unknownURI(inoIdentifier.URI)
}
// If we are tracking a .ino...
if inoIdentifier.URI.Ext() == ".ino" {
handler.sketchTrackedFilesCount--
log.Printf(" decreasing .ino tracked files count: %d", handler.sketchTrackedFilesCount)
// notify clang that sketchCpp has been close only once all .ino are closed
if handler.sketchTrackedFilesCount != 0 {
return nil, nil
}
}
cppIdentifier, err := handler.ino2cppTextDocumentIdentifier(inoIdentifier)
return &lsp.DidCloseTextDocumentParams{
TextDocument: cppIdentifier,
}, err
}
func (handler *InoHandler) ino2cppTextDocumentItem(inoItem lsp.TextDocumentItem) (cppItem lsp.TextDocumentItem, err error) {
cppURI, err := handler.ino2cppDocumentURI(inoItem.URI)
if err != nil {
return cppItem, err
}
cppItem.URI = cppURI
if cppURI.AsPath().EquivalentTo(handler.buildSketchCpp) {
cppItem.LanguageID = "cpp"
cppItem.Text = handler.sketchMapper.CppText.Text
cppItem.Version = handler.sketchMapper.CppText.Version
} else {
cppItem.LanguageID = inoItem.LanguageID
inoPath := inoItem.URI.AsPath().String()
cppItem.Text = handler.docs[inoPath].Text
cppItem.Version = handler.docs[inoPath].Version
}
return cppItem, nil
}
func (handler *InoHandler) didChange(ctx context.Context, req *lsp.DidChangeTextDocumentParams) (*lsp.DidChangeTextDocumentParams, error) {
doc := req.TextDocument
trackedDoc, ok := handler.docs[doc.URI.AsPath().String()]
if !ok {
return nil, unknownURI(doc.URI)
}
textutils.ApplyLSPTextDocumentContentChangeEvent(trackedDoc, req.ContentChanges, doc.Version)
// If changes are applied to a .ino file we increment the global .ino.cpp versioning
// for each increment of the single .ino file.
if doc.URI.Ext() == ".ino" {
cppChanges := []lsp.TextDocumentContentChangeEvent{}
for _, inoChange := range req.ContentChanges {
cppRange, ok := handler.sketchMapper.InoToCppLSPRangeOk(doc.URI, *inoChange.Range)
if !ok {
return nil, errors.Errorf("invalid change range %s:%s", doc.URI, *inoChange.Range)
}
// Detect changes in critical lines (for example function definitions)
// and trigger arduino-preprocessing + clangd restart.
dirty := false
for _, sym := range handler.buildSketchSymbols {
if sym.SelectionRange.Overlaps(cppRange) {
dirty = true
log.Println("--! DIRTY CHANGE detected using symbol tables, force sketch rebuild!")
break
}
}
if handler.sketchMapper.ApplyTextChange(doc.URI, inoChange) {
dirty = true
log.Println("--! DIRTY CHANGE detected with sketch mapper, force sketch rebuild!")
}
if dirty {
handler.scheduleRebuildEnvironment()
}
// log.Println("New version:----------")
// log.Println(handler.sketchMapper.CppText.Text)
// log.Println("----------------------")
cppChange := lsp.TextDocumentContentChangeEvent{
Range: &cppRange,
RangeLength: inoChange.RangeLength,
Text: inoChange.Text,
}
cppChanges = append(cppChanges, cppChange)
}
handler.CheckCppIncludesChanges()
// build a cpp equivalent didChange request
cppReq := &lsp.DidChangeTextDocumentParams{
ContentChanges: cppChanges,
TextDocument: lsp.VersionedTextDocumentIdentifier{
TextDocumentIdentifier: lsp.TextDocumentIdentifier{
URI: lsp.NewDocumentURIFromPath(handler.buildSketchCpp),
},
Version: handler.sketchMapper.CppText.Version,
},
}
return cppReq, nil
}
// If changes are applied to other files pass them by converting just the URI
cppDoc, err := handler.ino2cppVersionedTextDocumentIdentifier(req.TextDocument)
if err != nil {
return nil, err
}
cppReq := &lsp.DidChangeTextDocumentParams{
TextDocument: cppDoc,
ContentChanges: req.ContentChanges,
}
return cppReq, err
}
func (handler *InoHandler) handleError(ctx context.Context, err error) error {
errorStr := err.Error()
var message string
if strings.Contains(errorStr, "#error") {
exp, regexpErr := regexp.Compile("#error \"(.*)\"")
if regexpErr != nil {
panic(regexpErr)
}
submatch := exp.FindStringSubmatch(errorStr)
message = submatch[1]
} else if strings.Contains(errorStr, "platform not installed") || strings.Contains(errorStr, "no FQBN provided") {
if len(handler.config.SelectedBoard.Name) > 0 {
board := handler.config.SelectedBoard.Name
message = "Editor support may be inaccurate because the core for the board `" + board + "` is not installed."
message += " Use the Boards Manager to install it."
} else {
// This case happens most often when the app is started for the first time and no
// board is selected yet. Don't bother the user with an error then.
return err
}
} else if strings.Contains(errorStr, "No such file or directory") {
exp, regexpErr := regexp.Compile("([\\w\\.\\-]+): No such file or directory")
if regexpErr != nil {
panic(regexpErr)
}
submatch := exp.FindStringSubmatch(errorStr)
message = "Editor support may be inaccurate because the header `" + submatch[1] + "` was not found."
message += " If it is part of a library, use the Library Manager to install it."
} else {
message = "Could not start editor support.\n" + errorStr
}
go handler.showMessage(ctx, lsp.MTError, message)
return errors.New(message)
}
func (handler *InoHandler) ino2cppVersionedTextDocumentIdentifier(doc lsp.VersionedTextDocumentIdentifier) (lsp.VersionedTextDocumentIdentifier, error) {
cppURI, err := handler.ino2cppDocumentURI(doc.URI)
res := doc
res.URI = cppURI
return res, err
}
func (handler *InoHandler) ino2cppTextDocumentIdentifier(doc lsp.TextDocumentIdentifier) (lsp.TextDocumentIdentifier, error) {
cppURI, err := handler.ino2cppDocumentURI(doc.URI)
res := doc
res.URI = cppURI
return res, err
}
func (handler *InoHandler) ino2cppDocumentURI(inoURI lsp.DocumentURI) (lsp.DocumentURI, error) {