-
Notifications
You must be signed in to change notification settings - Fork 7
/
MesonServer.swift
1861 lines (1778 loc) · 66.2 KB
/
MesonServer.swift
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
import Dispatch
import Foundation
import IOUtils
import LanguageServerProtocol
import Logging
import LSPLogging
import MesonAnalyze
import MesonAST
import MesonDocs
import Timing
import Wrap
// There seem to be some name collisions
public typealias MesonVoid = ()
public final actor MesonServer: MessageHandler {
static let LOG = Logger(label: "LanguageServer::MesonServer")
static let MIN_PORT = 65000
static let MAX_PORT = 65550
var memfilesQueue = DispatchQueue(label: "mesonserver.memfiles")
private let messageHandlingQueue = AsyncQueue<TaskMetadata>()
private let cancellationMessageHandlingQueue = AsyncQueue<Serial>()
private let notificationIDForLoggingLock = NSLock()
private var notificationIDForLogging: Int = 0
var onExit: () -> MesonVoid
var path: String?
var tree: MesonTree?
var ns: TypeNamespace
var memfiles: [String: String] = [:]
var parseSubprojectTask: Task<(), Error>?
var parseTask: Task<(), Error>?
var docs: MesonDocs = MesonDocs()
var openFiles: Set<String> = []
var openSubprojectFiles: [String: Set<String>] = [:]
var astCache: [String: Node] = [:]
var astCaches: [String: [String: Node]] = [:]
var tasks: [String: Task<(), Error>] = [:]
let interval = DispatchTimeInterval.seconds(60)
let mtimeChecker = DispatchTimeInterval.milliseconds(300)
var subprojects: SubprojectState?
var mapper: FileMapper = FileMapper()
var token: ProgressToken?
var subprojectsDirectoryMtime: Date?
var pkgNames: Set<String> = []
let codeActionState = CodeActionState()
var stats: [String: [(Date, UInt64)]] = [:]
var analysisOptions = AnalysisOptions()
var otherSettings = OtherSettings(
ignoreDiagnosticsFromSubprojects: nil,
neverDownloadAutomatically: false,
disableInlayHints: false,
muonPath: nil
)
let client: Connection
var notificationCount: UInt64 = 0
var requestCount: UInt64 = 0
internal var notifications: [String: UInt] = [:]
internal var requests: [String: UInt] = [:]
public let queue: DispatchQueue = DispatchQueue(
label: "language-server-queue",
qos: .userInitiated
)
public init(client: Connection, onExit: @escaping () -> MesonVoid) {
self.onExit = onExit
self.ns = TypeNamespace()
self.client = client
Task.detached {
do { try await WrapDB.INSTANCE.initDB() } catch {
Self.LOG.error("Failed to init WrapDB: \(error)")
}
}
let task = Process()
let pipe = Pipe()
let inPipe = Pipe()
task.standardOutput = pipe
task.arguments = ["--list-package-names"]
inPipe.fileHandleForWriting.write("".data(using: .utf8)!)
inPipe.fileHandleForWriting.closeFile()
task.standardInput = inPipe
task.executableURL = URL(fileURLWithPath: "/usr/bin/pkg-config")
do {
try task.run()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
Task {
for str in output!.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) {
await self.insertPkgName(String(str))
}
}
} catch { Self.LOG.error("\(error)") }
}
private func insertPkgName(_ str: String) async { self.pkgNames.insert(str) }
private func setSubprojects(_ subprojects: SubprojectState?) async {
self.subprojects = subprojects
}
private func checkMtime() {
if let date = self.getDirectoryModificationTime(
path: self.path! + "\(Path.separator)subprojects"
) {
if let oldDate = self.subprojectsDirectoryMtime {
if date > oldDate {
Self.LOG.info("subprojects/ was modified. Recreating subprojects")
if let t = self.parseSubprojectTask { t.cancel() }
self.parseSubprojectTask = Task.detached {
await self.setSubprojects(nil)
await self.setupSubprojects()
}
}
} else {
Self.LOG.info("subprojects/ was added. Setting up subprojects")
if let t = self.parseSubprojectTask { t.cancel() }
self.parseSubprojectTask = Task.detached { await self.setupSubprojects() }
}
}
}
private func scheduleNextMtimeCheck() {
self.queue.asyncAfter(deadline: .now() + mtimeChecker) {
Task {
await self.checkMtime()
await self.scheduleNextMtimeCheck()
}
}
}
public func prepareForExit() {
if let t = self.parseSubprojectTask { t.cancel() }
if let t = self.parseTask { t.cancel() }
self.tasks.values.forEach { $0.cancel() }
Self.LOG.warning("Killing \(Processes.PROCESSES.count) processes")
if let t = self.token {
let endMessage = WorkDoneProgress(
token: t,
value: WorkDoneProgressKind.end(WorkDoneProgressEnd())
)
self.client.send(endMessage)
}
Processes.CLEANUP_HANDLER()
}
private func semanticTokenFull(_ req: DocumentSemanticTokensRequest) async throws
-> DocumentSemanticTokensResponse
{
let begin = clock()
let file = mapper.fromSubprojectToCache(file: req.textDocument.uri.fileURL!.path)
if let t = self.findTree(req.textDocument.uri) {
if let mt = t.findSubdirTree(file: file), let ast = mt.ast {
let stv = SemanticTokenVisitor()
ast.visit(visitor: stv)
Timing.INSTANCE.registerMeasurement(name: "semanticTokens", begin: begin, end: clock())
return DocumentSemanticTokensResponse(data: stv.finish())
} else if req.textDocument.uri.pseudoPath.hasSuffix("meson.options")
|| req.textDocument.uri.pseudoPath.hasSuffix("meson_options.txt"), let ast = t.optionsAst
{
let stv = SemanticTokenVisitor()
ast.visit(visitor: stv)
Timing.INSTANCE.registerMeasurement(name: "semanticTokens", begin: begin, end: clock())
return DocumentSemanticTokensResponse(data: stv.finish())
}
}
Timing.INSTANCE.registerMeasurement(name: "semanticTokens", begin: begin, end: clock())
return DocumentSemanticTokensResponse(data: [])
}
private func foldingRanges(_ req: FoldingRangeRequest) async throws -> [FoldingRange] {
let begin = clock()
let file = mapper.fromSubprojectToCache(file: req.textDocument.uri.fileURL!.path)
if let t = self.findTree(req.textDocument.uri), let mt = t.findSubdirTree(file: file),
let ast = mt.ast
{
let stv = FoldingRangeVisitor()
ast.visit(visitor: stv)
Timing.INSTANCE.registerMeasurement(name: "foldingRanges", begin: begin, end: clock())
return stv.ranges
}
Timing.INSTANCE.registerMeasurement(name: "foldingRanges", begin: begin, end: clock())
return []
}
private func rename(_ req: RenameRequest) async throws -> WorkspaceEdit {
let params = req
guard let t = self.tree else {
throw ResponseError(code: .requestFailed, message: "No tree available!")
}
guard
let id = t.metadata?.findIdentifierAt(
params.textDocument.uri.fileURL!.absoluteURL.path,
params.position.line,
params.position.utf16index
)
else {
throw ResponseError(code: .requestFailed, message: "No identifier found at this location!")
}
if let parentLoop = id.parent as? IterationStatement, parentLoop.containsAsId(id) {
let lvr = LoopVariableRename(id.id, params.newName, t)
parentLoop.visit(visitor: lvr)
return WorkspaceEdit(changes: lvr.edits)
}
if let kw = id.parent as? KeywordItem, kw.key.equals(right: id) {
return WorkspaceEdit(changes: [:])
}
if let fn = id.parent as? FunctionExpression, fn.id.equals(right: id) {
return WorkspaceEdit(changes: [:])
}
if let fn = id.parent as? MethodExpression, fn.id.equals(right: id) {
return WorkspaceEdit(changes: [:])
}
var edits: [DocumentURI: [TextEdit]] = [:]
for m in t.metadata!.identifiers.keys {
let ids = t.metadata!.identifiers[m]!
ids.filter { $0.id == id.id }.forEach {
let d = DocumentURI(
URL(fileURLWithPath: Path($0.file.file).normalize().absolute().description)
)
let range = Shared.nodeToRange($0)
let textEdit = TextEdit(range: range, newText: params.newName)
edits[d] = (edits[d] ?? []) + [textEdit]
}
}
return WorkspaceEdit(changes: edits)
}
private func codeActions(_ req: CodeActionRequest) async throws -> CodeActionRequestResponse? {
let begin = clock()
let uri = req.textDocument.uri
let range = req.range
let cav = CodeActionVisitor(range)
let file = uri.fileURL!.absoluteURL.path
var actions: [CodeAction] = []
if let tree = self.findTree(uri), tree.ast != nil, let a = tree.findSubdirTree(file: file),
let a2 = a.ast
{
a2.visit(visitor: cav)
for node in cav.applicableNodes {
actions += self.codeActionState.apply(uri: uri, node: node, tree: tree)
}
if self.tree?.findSubdirTree(
file: Path(uri.fileURL!.absoluteURL.path).absolute().normalize().description
) != nil {
for node in cav.applicableNodes {
actions += self.codeActionState.applyToMainTree(
uri: uri,
node: node,
tree: tree,
subprojects: self.subprojects,
rootDirectory: self.path!
)
}
}
}
Self.LOG.info(
"Found \(actions.count) code actions at \(uri):\(range): \(actions.map { $0.title })"
)
Timing.INSTANCE.registerMeasurement(name: "codeaction", begin: begin, end: clock())
return CodeActionRequestResponse(
codeActions: actions,
clientCapabilities: TextDocumentClientCapabilities.CodeAction(
codeActionLiteralSupport: TextDocumentClientCapabilities.CodeAction
.CodeActionLiteralSupport(
codeActionKind: TextDocumentClientCapabilities.CodeAction.CodeActionLiteralSupport
.CodeActionKind(valueSet: [])
)
)
)
}
private func findTree(_ uri: DocumentURI) -> MesonTree? {
guard let p = self.path else { return self.tree }
let rootPath = Path(p).absolute().normalize().description
if let url = uri.fileURL {
let filePath = Path(url.absoluteURL.path).absolute().normalize().description
// dropFirst to drop leading slash
let relativePath = filePath.replacingOccurrences(of: rootPath, with: "").dropFirst()
.description
if relativePath.hasPrefix("subprojects"), let s = self.subprojects {
let parts = relativePath.split(separator: "/")
// At least subprojects/<name>/meson.build
if parts.count < 3 { return self.tree }
let name = parts[1]
var found = false
Self.LOG.info("subprojects/\(name)/")
let l = s.subprojects.map { $0.realpath }
Self.LOG.info("\(l)")
for sp in s.subprojects
where sp.realpath.hasPrefix("subprojects\(Path.separator)\(name)\(Path.separator)") {
found = true
if let t = sp.tree {
Self.LOG.info("Found subproject `\(sp.description)` for path \(filePath)")
return t
}
}
// We found a matching subproject, but
// sadly it contains no MesonTree
if found { return nil }
}
}
return self.tree
}
private func findSubprojectForUri(_ uri: DocumentURI) -> MesonAnalyze.Subproject? {
guard let p = self.path else { return nil }
let rootPath = Path(p).absolute().normalize().description
if let url = uri.fileURL {
let filePath = Path(url.absoluteURL.path).absolute().normalize().description
// dropFirst to drop leading slash
let relativePath = filePath.replacingOccurrences(of: rootPath, with: "").dropFirst()
.description
if relativePath.hasPrefix("subprojects"), let s = self.subprojects {
let parts = relativePath.split(separator: "/")
// At least subprojects/<name>/meson.build
if parts.count < 3 { return nil }
let name = parts[1]
if name == "packagefiles" || name == "packagecache" { return nil }
for sp in s.subprojects
where sp.realpath.hasPrefix("subprojects\(Path.separator)\(name)\(Path.separator)") {
return sp
}
}
}
return nil
}
private func inlayHints(_ req: InlayHintRequest) async throws -> [InlayHint] {
if self.otherSettings.disableInlayHints { return [] }
return collectInlayHints(self.findTree(req.textDocument.uri), req, self.mapper)
}
private func highlight(_ req: DocumentHighlightRequest) async throws -> [DocumentHighlight]? {
return highlightTree(self.findTree(req.textDocument.uri), req, self.mapper)
}
// swiftlint:disable cyclomatic_complexity
private func complete(_ req: CompletionRequest) async throws -> CompletionList {
let begin = clock()
var arr: [CompletionItem] = []
let fp = req.textDocument.uri.fileURL!.path
while self.parseTask != nil {
}
if let t = self.tree, let mt = t.findSubdirTree(file: fp), mt.ast != nil,
let content = self.getContents(file: fp)
{
let pos = req.position
let line = pos.line
let column = pos.utf16index
let lines = content.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline)
Self.LOG.info("Completion at: [\(line):\(column)]")
if line < lines.count {
let str = lines[line]
Self.LOG.info("Entire line: '\(str)'")
let prev = str.prefix(column + 1).description.trimmingCharacters(in: .whitespaces)
Self.LOG.info("Prev = '\(prev)'")
if prev.hasSuffix(".") || (prev.hasSuffix(")") && !prev.hasSuffix(" )")), let t = self.tree,
let md = t.metadata
{
let exprTypes = self.afterDotCompletion(md, fp, line, column)
if let types = exprTypes {
let s: Set<MesonAST.Method> = self.fillTypes(types)
for c in s {
arr.append(
CompletionItem(
label: c.name,
kind: .method,
insertText: createTextForFunction(c),
insertTextFormat: .snippet
)
)
}
} else {
let errorId = self.extractErrorId(prev)
if let err = errorId {
let types = md.findAllTypes(fp, err)
let s: Set<MesonAST.Method> = self.fillTypes(types)
for c in s {
arr.append(
CompletionItem(
label: c.name,
kind: .method,
insertText: createTextForFunction(c),
insertTextFormat: .snippet
)
)
}
}
}
}
if let t = self.tree, let md = t.metadata {
self.subprojectGetVariableSpecialCase(fp, line, column, md, &arr)
self.dependencySpecialCase(fp, line, column, md, prev, &arr)
self.getOptionSpecialCase(t, fp, line, column, md, &arr)
self.sourceFilesSpecialCase(t, fp, line, column, md, &arr)
if let idexpr = md.findIdentifierAt(fp, line, column),
let al = idexpr.parent as? ArgumentList
{
let callExpr = idexpr.parent!.parent!
let usedKwargs: Set<String> = self.enumerateUsedKwargs(al)
let s: Set<String> = self.fillKwargs(callExpr)
for c in s where !usedKwargs.contains(c) {
arr.append(
CompletionItem(
label: c,
kind: .keyword,
insertText: "\(c): ${1:\(c)}",
insertTextFormat: .snippet
)
)
}
} else if let idexpr = md.findIdentifierAt(fp, line, column) {
let currId = idexpr.id
for f in self.ns.functions where f.name.lowercased().contains(currId.lowercased()) {
arr.append(
CompletionItem(
label: f.name,
kind: .function,
insertText: createTextForFunction(f),
insertTextFormat: .snippet
)
)
}
self.findMatchingIdentifiers(t, idexpr, &arr)
}
finalAttempt(prev, line, fp, md, &arr)
}
if prev.isEmpty || prev == ")" {
if let t = self.tree, let md = t.metadata {
self.subprojectGetVariableSpecialCase(fp, line, column, md, &arr)
self.dependencySpecialCase(fp, line, column, md, prev, &arr)
self.getOptionSpecialCase(t, fp, line, column, md, &arr)
self.sourceFilesSpecialCase(t, fp, line, column, md, &arr)
}
if let t = self.tree, let md = t.metadata,
let call = md.findFullMethodCallAt(fp, line, column),
let al = call.argumentList as? ArgumentList
{
let usedKwargs: Set<String> = self.enumerateUsedKwargs(al)
let s: Set<String> = self.fillKwargs(call)
for c in s where !usedKwargs.contains(c) {
arr.insert(
CompletionItem(
label: c,
kind: .keyword,
insertText: "\(c): ${1:\(c)}",
insertTextFormat: .snippet
),
at: 0
)
}
} else if let t = self.tree, let md = t.metadata,
let call = md.findFullFunctionCallAt(fp, line, column),
let al = call.argumentList as? ArgumentList
{
let usedKwargs: Set<String> = self.enumerateUsedKwargs(al)
let s: Set<String> = self.fillKwargs(call)
for c in s where !usedKwargs.contains(c) {
arr.insert(
CompletionItem(
label: c,
kind: .keyword,
insertText: "\(c): ${1:\(c)}",
insertTextFormat: .snippet
),
at: 0
)
}
} else {
for f in self.ns.functions {
arr.append(
CompletionItem(
label: f.name,
kind: .function,
insertText: createTextForFunction(f),
insertTextFormat: .snippet
)
)
}
}
}
} else {
Self.LOG.error("Line out of bounds: \(line) > \(lines.count)")
}
}
var insertions: Set<String> = []
var realRet: [CompletionItem] = []
for completion in arr where !insertions.contains(completion.insertText!) {
insertions.insert(completion.insertText!)
realRet.append(completion)
}
Timing.INSTANCE.registerMeasurement(name: "complete", begin: begin, end: clock())
return CompletionList(isIncomplete: false, items: realRet)
}
// swiftlint:enable cyclomatic_complexity
private func extractErrorId(_ prev: String) -> String? {
if prev.isEmpty { return nil }
var ret = ""
var idx = prev.count - 1
while idx > 0 {
idx -= 1
let c = prev[idx]
if c.isWhitespace {
return ret
} else if !(c.isLetter || c.isNumber || c == "_") {
return ret
}
ret = "\(c)\(ret)"
}
return ret
}
// swiftlint:disable function_parameter_count
private func dependencySpecialCase(
_ fp: String,
_ line: Int,
_ column: Int,
_ md: MesonMetadata,
_ prev: String,
_ arr: inout [CompletionItem]
) {
if let fexpr = md.findFullFunctionCallAt(fp, line, column), let f = fexpr.function,
f.id() == "dependency", let al = fexpr.argumentList as? ArgumentList, !al.args.isEmpty,
al.args[0] is StringLiteral
{
Self.LOG.info("Found special call to dependency")
let inLiteral = md.findStringLiteralAt(fp, line, column) != nil || prev.hasSuffix("'")
for c in self.pkgNames {
arr.append(
CompletionItem(
label: c,
kind: .variable,
insertText: inLiteral ? c : "'\(c)'",
insertTextFormat: .snippet
)
)
}
}
}
private func sourceFilesSpecialCase(
_ t: MesonTree,
_ fp: String,
_ line: Int,
_ column: Int,
_ md: MesonMetadata,
_ arr: inout [CompletionItem]
) {
if let fexpr = md.findFullFunctionCallAt(fp, line, column), let f = fexpr.function,
self.isSourceFileFunction(f.id())
{
Self.LOG.info("Found special call to a function taking source files")
var keys: [String] = []
do {
let children = try Path(fexpr.file.file).parent().children()
for c in children {
if c.isDirectory { continue }
let ext = c.lastComponent.replacingOccurrences(
of: c.lastComponentWithoutExtension,
with: ""
).lowercased()
if ext == ".c" || ext == ".cpp" || ext == ".vala" || ext == ".d" || ext == ".rs"
|| ext == ".h" || ext == ".hpp"
{
keys.append(c.lastComponent)
}
}
} catch let e { Self.LOG.error("\(e)") }
for c in keys {
arr.append(
CompletionItem(label: c, kind: .variable, insertText: c, insertTextFormat: .snippet)
)
}
}
}
// swiftlint:enable function_parameter_count
private func isSourceFileFunction(_ s: String) -> Bool {
return s == "both_libraries" || s == "build_target" || s == "executable" || s == "files"
|| s == "jar" || s == "library" || s == "shared_library" || s == "static_library"
|| s == "shared_module"
}
// swiftlint:disable function_parameter_count
private func getOptionSpecialCase(
_ t: MesonTree,
_ fp: String,
_ line: Int,
_ column: Int,
_ md: MesonMetadata,
_ arr: inout [CompletionItem]
) {
if let fexpr = md.findFullFunctionCallAt(fp, line, column), let f = fexpr.function,
f.id() == "get_option", let al = fexpr.argumentList as? ArgumentList, !al.args.isEmpty,
al.args[0] is StringLiteral
{
Self.LOG.info("Found special call to get_option")
for c in t.options.opts.keys {
arr.append(
CompletionItem(label: c, kind: .variable, insertText: c, insertTextFormat: .snippet)
)
}
}
}
// swiftlint:enable function_parameter_count
private func subprojectGetVariableSpecialCase(
_ fp: String,
_ line: Int,
_ column: Int,
_ md: MesonMetadata,
_ arr: inout [CompletionItem]
) {
if let mexpr = md.findFullMethodCallAt(fp, line, column), let m = mexpr.method,
m.id() == "subproject.get_variable", let al = mexpr.argumentList as? ArgumentList,
!al.args.isEmpty, al.args[0] is StringLiteral,
let subprojects = self.findSubproject(mexpr.obj.types), !subprojects.names.isEmpty,
let ssT = self.subprojects
{
Self.LOG.info(
"Found special call to subproject.get_variable for subprojects \(subprojects.names)"
)
var names: Set<String> = []
for subproject in ssT.subprojects where subprojects.names.contains(subproject.name) {
if let ast = subproject.tree, let sscope = ast.scope {
sscope.variables.keys.forEach { names.insert($0) }
}
}
for c in names {
if c == "meson" || c == "build_machine" || c == "target_machine" || c == "host_machine" {
continue
}
arr.append(
CompletionItem(label: c, kind: .variable, insertText: c, insertTextFormat: .snippet)
)
}
}
}
private func findSubproject(_ types: [Type]) -> MesonAST.Subproject? {
return types.filter { $0 is MesonAST.Subproject }.map { $0 as! MesonAST.Subproject }.first
}
private func contains(_ node: Node, _ line: Int, _ column: Int) -> Bool {
if node.location.startLine <= line && node.location.endLine >= line {
if node.location.startColumn <= column && node.location.endColumn >= column { return true }
}
return false
}
private func findMatchingIdentifiers(
_ t: MesonTree,
_ idexpr: IdExpression,
_ arr: inout [CompletionItem]
) {
guard let mt = t.metadata else { return }
guard let idexprs = mt.identifiers[idexpr.file.file] else { return }
var other: [String] = []
var idx = 0
let mappedFile = self.mapper.fromSubprojectToCache(file: idexpr.file.file)
for f in t.visitedFiles {
if mappedFile == f {
Self.LOG.info("Found file in visited files. Breaking...")
break
}
other += t.foundVariables[idx]
Self.LOG.info("Adding variables from \(f) to completion")
idx += 1
}
let filtered =
Array(
idexprs.filter { $0.location.endLine < idexpr.location.startLine }.filter {
($0.parent is AssignmentStatement
&& ($0.parent as! AssignmentStatement).lhs.equals(right: $0))
|| ($0.parent is IterationStatement
&& ($0.parent as! IterationStatement).containsAsId($0))
}.map { $0.id }
) + other
let matching = Array(Set(filtered.filter { $0.lowercased().contains(idexpr.id.lowercased()) }))
Self.LOG.info("findMatchingIdentifiers - Found matching identifiers: \(matching)")
for m in matching + ["meson", "host_machine", "build_machine"] {
arr.append(CompletionItem(label: m, kind: .variable, insertText: m, insertTextFormat: .plain))
}
}
private func finalAttempt(
_ prev: String,
_ line: Int,
_ fp: String,
_ md: MesonMetadata,
_ arr: inout [CompletionItem]
) {
var n = prev.count - 1
if n <= 0 { return }
var invalid = false
while prev[n] != "." && n >= 0 {
Self.LOG.info("Finalcompletion: \(prev[0..<n])")
if prev[n].isNumber || prev[n] == " " || prev[n] == "(" {
invalid = true
break
}
n -= 1
if n == -1 {
invalid = true
break
}
}
if invalid { return }
let exprTypes = self.afterDotCompletion(md, fp, line, n)
// The editor should filter this client side
if let types = exprTypes {
let s: Set<MesonAST.Method> = self.fillTypes(types)
for c in s {
arr.append(
CompletionItem(
label: c.name,
kind: .method,
insertText: createTextForFunction(c),
insertTextFormat: .snippet
)
)
}
}
}
private func createTextForFunction(_ m: Function) -> String {
var str = m.name + "("
var n = 1
for arg in m.args where arg is PositionalArgument {
let p = (arg as! PositionalArgument)
if !p.opt {
str += "${\(n):\(p.name)}, "
n += 1
}
}
for arg in m.args where arg is Kwarg {
let p = (arg as! Kwarg)
if !p.opt {
str += "\(p.name): ${\(n):\(p.name)}, "
n += 1
}
}
return (str + ")").replacingOccurrences(of: ", )", with: ")")
}
private func fillTypes(_ types: [Type]) -> Set<MesonAST.Method> {
var s: Set<MesonAST.Method> = []
for t in types {
for m in self.ns.vtables[t.name]! {
Self.LOG.info("Inserting completion: \(m.name)")
s.insert(m)
}
if let t1 = t as? AbstractObject {
var p = t1.parent
while p != nil {
for m in self.ns.vtables[p!.name]! {
Self.LOG.info("Inserting completion: \(m.name)")
s.insert(m)
}
p = p!.parent
}
}
}
return s
}
private func fillKwargs(_ callExpr: Node) -> Set<String> {
var s: Set<String> = []
if let fe = callExpr as? FunctionExpression, let f = fe.function {
for arg in f.args where arg is Kwarg {
Self.LOG.info("Adding kwarg to completion list: \((arg as! Kwarg).name)")
s.insert((arg as! Kwarg).name)
}
} else if let me = callExpr as? MethodExpression, let m = me.method {
for arg in m.args where arg is Kwarg {
Self.LOG.info("Adding kwarg to completion list: \((arg as! Kwarg).name)")
s.insert((arg as! Kwarg).name)
}
}
return s
}
private func enumerateUsedKwargs(_ al: ArgumentList) -> Set<String> {
var usedKwargs: Set<String> = []
for arg in al.args where arg is KeywordItem {
let kwi = (arg as! KeywordItem)
let kwik = (kwi.key as! IdExpression)
Self.LOG.info("Found already used kwarg: \(kwik.id)")
usedKwargs.insert(kwik.id)
}
return usedKwargs
}
private func afterDotCompletion(
_ md: MesonMetadata,
_ fp: String,
_ line: Int,
_ column: Int,
_ recurse: Bool = true
) -> [Type]? {
Self.LOG.info("Starting afterDotCompletion: \(fp)[\(line):\(column)]")
if let idexpr = md.findIdentifierAt(fp, line, column - 1) {
Self.LOG.info("Found id expr: \(idexpr.id)")
return idexpr.types
} else if let fc = md.findFullFunctionCallAt(fp, line, column - 1), fc.function != nil {
Self.LOG.info("Found function expr: \(fc.functionName())")
return fc.types
} else if let me = md.findFullMethodCallAt(fp, line, column - 1), me.method != nil {
Self.LOG.info("Found method expr: \(me.method!.id())")
return me.types
} else if let aa = md.findFullArrayAccessAt(fp, line, column - 1) {
Self.LOG.info("Found subscript expression")
return aa.types
} else if let sl = md.findStringLiteralAt(fp, line, column - 1) {
return sl.types
}
if recurse && column > 0 {
Self.LOG.info("afterDotCompletion - recursing")
return self.afterDotCompletion(md, fp, line, column - 1, false)
}
Self.LOG.info("Ending afterDotCompletion without results")
return nil
}
private func documentSymbol(_ req: DocumentSymbolRequest) async throws -> DocumentSymbolResponse?
{ return collectDocumentSymbols(self.findTree(req.textDocument.uri), req, self.mapper) }
private func formatting(_ req: DocumentFormattingRequest) async throws -> [TextEdit] {
let begin = clock()
do {
Self.LOG.info("Formatting \(req.textDocument.uri.fileURL!.path)")
if let contents = self.getContents(file: req.textDocument.uri.fileURL!.path) {
if let formatted = try formatFile(
content: contents,
params: req.options,
muonPath: self.otherSettings.muonPath
) {
Self.LOG.info(
"Finished formatting document (New: \(formatted.count); Old: \(contents.count))"
)
let newLines = formatted.split(whereSeparator: \.isNewline)
let endOfLastLine = newLines.isEmpty ? 1024 : (newLines[newLines.count - 1].count)
let range =
Position(
line: 0,
utf16index: 0
)..<Position(line: newLines.count + 2048, utf16index: endOfLastLine)
let edit = TextEdit(range: range, newText: formatted)
Timing.INSTANCE.registerMeasurement(name: "formatting", begin: begin, end: clock())
if let sb = self.findSubprojectForUri(req.textDocument.uri),
let csp = sb as? FolderSubproject
{
self.rebuildSubproject(csp)
}
return [edit]
} else {
Self.LOG.error("Unable to format file")
}
} else {
Self.LOG.error("Unable to read file")
}
} catch {
Self.LOG.error("Error formatting file \(error)")
Timing.INSTANCE.registerMeasurement(name: "formatting", begin: begin, end: clock())
throw ResponseError(code: .internalError, message: "Unable to format using muon: \(error)")
}
Timing.INSTANCE.registerMeasurement(name: "formatting", begin: begin, end: clock())
throw ResponseError(
code: .internalError,
message: "Either failed to read the input file or to format using muon"
)
}
private func getContents(file: String) -> String? {
if let sf = self.memfiles[file] { return sf }
Self.LOG.warning("Unable to find \(file) in memfiles")
return try? String(contentsOfFile: file)
}
private func hover(_ req: HoverRequest) -> HoverResponse? {
return collectHoverInformation(self.findTree(req.textDocument.uri), req, self.mapper, docs)
}
private func declaration(_ req: DeclarationRequest) async throws
-> LocationsOrLocationLinksResponse?
{ return findDeclaration(self.findTree(req.textDocument.uri), req, self.mapper, Self.LOG) }
private func definition(_ req: DefinitionRequest) async throws
-> LocationsOrLocationLinksResponse?
{ return findDefinition(self.findTree(req.textDocument.uri), req, self.mapper, Self.LOG) }
private func clearDiagnostics() { self.clearDiagnosticsForTree(tree: self.tree) }
private func clearDiagnosticsForTree(tree: MesonTree?) {
if tree != nil && tree!.metadata != nil {
for k in tree!.metadata!.diagnostics.keys where tree!.metadata!.diagnostics[k] != nil {
let arr: [Diagnostic] = []
self.client.send(
PublishDiagnosticsNotification(
uri: DocumentURI(URL(fileURLWithPath: k)),
diagnostics: arr
)
)
tree!.metadata!.diagnostics.removeValue(forKey: k)
}
}
}
private func rebuildTree() {
if self.parseTask != nil { self.parseTask!.cancel() }
self.parseTask = Task {
let beginSleep = clock()
do {
// 100 ms
try await Task.sleep(nanoseconds: 100 * 1_000_000)
} catch { Self.LOG.error("Error during sleeping: \(error)") }
if Task.isCancelled {
Self.LOG.info("Cancelling parsing - After sleeping")
Timing.INSTANCE.registerMeasurement(
name: "interruptedSleep",
begin: beginSleep,
end: clock()
)
return
}
let beginRebuilding = clock()
self.clearDiagnostics()
let endClearing = clock()
Timing.INSTANCE.registerMeasurement(
name: "clearingDiagnostics",
begin: beginRebuilding,
end: endClearing
)
if Task.isCancelled {
Self.LOG.info("Cancelling parsing - After clearing diagnostics")
return
}
let tmptree = MesonTree(
file: self.path! + "/meson.build",
ns: self.ns,
dontCache: self.openFiles,
cache: &self.astCache,
memfiles: self.memfiles
)
let endParsingEntireTree = clock()
Timing.INSTANCE.registerMeasurement(
name: "parsingEntireTree",
begin: endClearing,
end: endParsingEntireTree
)
if Task.isCancelled {
Self.LOG.info("Cancelling build - After building tree")
return
}
tmptree.analyzeTypes(
ns: self.ns,
dontCache: self.openFiles,
cache: &self.astCache,
memfiles: self.memfiles,
subprojectState: self.subprojects,
analysisOptions: self.analysisOptions
)
if Task.isCancelled {
Self.LOG.info("Cancelling build - After analyzing types")
return
}
let endAnalyzingTypes = clock()
Timing.INSTANCE.registerMeasurement(
name: "analyzingTypes",
begin: endParsingEntireTree,
end: endAnalyzingTypes
)
if tmptree.metadata == nil {
let endRebuilding = clock()
Timing.INSTANCE.registerMeasurement(
name: "rebuildTree",
begin: beginRebuilding,
end: endRebuilding
)
return
}
if Task.isCancelled {
Self.LOG.info("Cancelling build - Before sending diagnostics")
return
}
self.sendNewDiagnostics(tmptree)
let endSendingDiagnostics = clock()
Timing.INSTANCE.registerMeasurement(
name: "sendingDiagnostics",
begin: endAnalyzingTypes,
end: endSendingDiagnostics
)
Timing.INSTANCE.registerMeasurement(
name: "rebuildTree",
begin: beginRebuilding,
end: endSendingDiagnostics
)
if Task.isCancelled {