-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathdiagnostic.jl
More file actions
1722 lines (1586 loc) · 68.6 KB
/
diagnostic.jl
File metadata and controls
1722 lines (1586 loc) · 68.6 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
# configuration
# =============
# parse and validation
# --------------------
struct DiagnosticConfigError <: Exception
msg::AbstractString
end
Base.showerror(io::IO, e::DiagnosticConfigError) = print(io, "DiagnosticConfigError: ", e.msg)
function parse_diagnostic_severity(
@nospecialize(severity_value), pattern::AbstractString
)
if severity_value isa Int
if 0 ≤ severity_value ≤ 4
return severity_value
else
throw(DiagnosticConfigError(
lazy"Invalid severity value \"$severity_value\" for diagnostic pattern \"$pattern\". " *
"Valid integer values are: 0 (off), 1 (error), 2 (warning), 3 (information), 4 (hint)"))
end
elseif severity_value isa String
severity_str = lowercase(severity_value)
if severity_str == "off"
return 0
elseif severity_str == "error"
return DiagnosticSeverity.Error
elseif severity_str == "warning" || severity_str == "warn"
return DiagnosticSeverity.Warning
elseif severity_str == "information" || severity_str == "info"
return DiagnosticSeverity.Information
elseif severity_str == "hint"
return DiagnosticSeverity.Hint
else
throw(DiagnosticConfigError(
lazy"Invalid severity value \"$severity_value\" for diagnostic pattern \"$pattern\". " *
"Valid string values are: \"off\", \"error\", \"warning\"/\"warn\", \"information\"/\"info\", \"hint\""))
end
else
throw(DiagnosticConfigError(
lazy"Invalid severity value \"$severity_value\" for diagnostic pattern \"$pattern\". " *
"Severity must be an integer (0-4) or string"))
end
end
function parse_diagnostic_pattern(x::AbstractDict{String})
if !haskey(x, "pattern")
throw(DiagnosticConfigError("Missing required field `pattern` in diagnostic pattern"))
end
pattern_value = x["pattern"]
if !(pattern_value isa String)
throw(DiagnosticConfigError(
lazy"Invalid `pattern` value. Must be a string, got $(typeof(pattern_value))"))
end
for key in keys(x)
if key ∉ ("pattern", "match_by", "match_type", "severity", "path")
throw(DiagnosticConfigError(
lazy"Unknown field \"$key\" in diagnostic pattern for pattern \"$pattern_value\". " *
"Valid fields are: pattern, match_by, match_type, severity, path"))
end
end
if !haskey(x, "match_by")
throw(DiagnosticConfigError(
lazy"Missing required field `match_by` in diagnostic pattern for pattern \"$pattern_value\""))
end
match_by = x["match_by"]
if !(match_by isa String)
throw(DiagnosticConfigError(
lazy"Invalid `match_by` value for pattern \"$pattern_value\". Must be a string, got $(typeof(match_by))"))
end
if !(match_by in ("code", "message"))
throw(DiagnosticConfigError(
lazy"Invalid `match_by` value \"$match_by\" for pattern \"$pattern_value\". Must be \"code\" or \"message\""))
end
if !haskey(x, "match_type")
throw(DiagnosticConfigError(
lazy"Missing required field `match_type` in diagnostic pattern for pattern \"$pattern_value\""))
end
match_type = x["match_type"]
if !(match_type isa String)
throw(DiagnosticConfigError(
lazy"Invalid `match_type` value for pattern \"$pattern_value\". Must be a string, got $(typeof(match_type))"))
end
if !(match_type in ("literal", "regex"))
throw(DiagnosticConfigError(
lazy"Invalid `match_type` value \"$match_type\" for pattern \"$pattern_value\". Must be \"literal\" or \"regex\""))
end
pattern = if match_type == "regex"
try
Regex(pattern_value)
catch e
throw(DiagnosticConfigError(
lazy"Invalid regex pattern \"$pattern_value\": $(sprint(showerror, e))"))
end
else
pattern_value
end
if !haskey(x, "severity")
throw(DiagnosticConfigError(
lazy"Missing required field `severity` in diagnostic pattern for pattern \"$pattern_value\""))
end
severity = parse_diagnostic_severity(x["severity"], pattern_value)
path_glob = if haskey(x, "path")
path_value = x["path"]
if !(path_value isa String)
throw(DiagnosticConfigError(
lazy"Invalid `path` value for pattern \"$pattern_value\". Must be a string, got $(typeof(path_value))"))
end
try
Glob.FilenameMatch(path_value, "dp")
catch e
throw(DiagnosticConfigError(
lazy"Invalid glob pattern \"$path_value\" for pattern \"$pattern_value\": $(sprint(showerror, e))"))
end
else
nothing
end
return DiagnosticPattern(pattern, match_by, match_type, severity, path_glob, pattern_value)
end
# application
# -----------
"""
calculate_match_specificity(pattern, target, is_message_match) -> UInt
Calculate the specificity score for a diagnostic pattern match.
# Priority Strategy
Higher specificity scores indicate more specific matches that should take precedence.
The scoring follows this priority order (highest to lowest):
1. **Message literal match**: `4`
2. **Message regex match**: `3`
3. **Code literal match**: `2`
4. **Code regex match**: `1`
Message-based patterns receive a priority bonus because they allow more fine-grained
control over specific diagnostic instances, whereas code-based patterns are more
categorical.
# Returns
- `0` if the pattern does not match the target
- An unsigned integer representing the match specificity if the pattern matches
"""
function calculate_match_specificity(
pattern::Union{Regex,String},
target::String,
is_message_match::Bool
)
local specificity::UInt8 = 0
if pattern isa String
specificity = pattern == target ? 2 : 0
else
specificity = occursin(pattern, target) ? 1 : 0
end
specificity == 0 && return specificity
if is_message_match
specificity += 2
end
return specificity
end
function _apply_diagnostic_config(
diagnostic::Diagnostic, manager::ConfigManager, uri::URI,
root_path::Union{Nothing,String}
)
code = diagnostic.code
if !(code isa String)
if JETLS_DEV_MODE
@warn "Unexpected diagnostic code type" code
elseif JETLS_TEST_MODE
error(lazy"Unexpected diagnostic code type: $code")
end
return diagnostic
elseif code ∉ ALL_DIAGNOSTIC_CODES
if JETLS_DEV_MODE
@warn "Unknown diagnostic code" code
elseif JETLS_TEST_MODE
error(lazy"Unknown diagnostic code: $code")
end
return diagnostic
end
patterns = get_config(manager, :diagnostic, :patterns)
if isempty(patterns)
# Diagnostics with severity=0 are off by default; filter them out
return diagnostic.severity == 0 ? missing : diagnostic
end
filepath = uri2filename(uri)
if root_path !== nothing && startswith(filepath, root_path)
path_for_glob = relpath(filepath, root_path)
else
path_for_glob = filepath
end
message = diagnostic.message
severity = nothing
best_specificity = 0
for pattern_config in patterns
globpath = pattern_config.path
if globpath !== nothing && !occursin(globpath, path_for_glob)
continue
end
target = pattern_config.match_by == "message" ? message : code
is_message_match = pattern_config.match_by == "message"
specificity = calculate_match_specificity(
pattern_config.pattern, target, is_message_match)
if specificity > best_specificity
best_specificity = specificity
severity = pattern_config.severity
end
end
if severity === nothing
return diagnostic.severity == 0 ? missing : diagnostic
elseif severity == 0
return missing
elseif severity == diagnostic.severity
return nothing
else
return Diagnostic(diagnostic; severity)
end
end
function apply_diagnostic_config!(
diagnostics::Vector{Diagnostic}, manager::ConfigManager, uri::URI,
root_path::Union{Nothing,String}
)
get_config(manager, :diagnostic, :enabled) || return empty!(diagnostics)
i = 1
while i <= length(diagnostics)
applied = _apply_diagnostic_config(diagnostics[i], manager, uri, root_path)
if applied === missing
deleteat!(diagnostics, i)
continue
end
if applied !== nothing
diagnostics[i] = applied
end
i += 1
end
return diagnostics
end
function diagnostic_code_description(code::AbstractString)
return CodeDescription(;
href = URI("https://aviatesk.github.io/JETLS.jl/release/diagnostic/#diagnostic/reference/$code"))
end
# utilities
# =========
function jet_frame_to_location(frame)
frame.file === :none && return nothing
return Location(;
uri = something(jet_frame_to_uri(frame)),
range = jet_frame_to_range(frame))
end
function jet_frame_to_uri(frame)
frame.file === :none && return nothing
filename = String(frame.file)
# TODO Clean this up and make we can always use `filename2uri` here.
if startswith(filename, "Untitled")
return filename2uri(filename)
else
return filepath2uri(to_full_path(filename))
end
end
function jet_frame_to_range(frame)
line = JET.fixed_line_number(frame)
return line_range(line)
end
# 1 based line to LSP-compatible line range
function line_range(line::Int)
line = line < 1 ? 0 : line - 1
start = Position(; line, character=0)
var"end" = Position(; line, character=Int(typemax(Int32)))
return Range(; start, var"end")
end
function lines_range((start_line, end_line)::Pair{Int,Int})
start_line = start_line < 1 ? 0 : start_line - 1
end_line = end_line < 1 ? 0 : end_line - 1
start = Position(; line=start_line, character=0)
var"end" = Position(; line=end_line, character=Int(typemax(Int32)))
return Range(; start, var"end")
end
# syntax diagnostics
# ==================
function parsed_stream_to_diagnostics(fi::FileInfo)
diagnostics = Diagnostic[]
for diagnostic in fi.parsed_stream.diagnostics
push!(diagnostics, jsdiag_to_lspdiag(diagnostic, fi))
end
return diagnostics
end
function jsdiag_to_lspdiag(diagnostic::JS.Diagnostic, fi::FileInfo)
return Diagnostic(;
range = jsobj_to_range(diagnostic, fi),
severity =
diagnostic.level === :error ? DiagnosticSeverity.Error :
diagnostic.level === :warning ? DiagnosticSeverity.Warning :
diagnostic.level === :note ? DiagnosticSeverity.Information :
DiagnosticSeverity.Hint,
message = diagnostic.message,
source = DIAGNOSTIC_SOURCE_LIVE,
code = SYNTAX_DIAGNOSTIC_CODE,
codeDescription = diagnostic_code_description(SYNTAX_DIAGNOSTIC_CODE))
end
# JET diagnostics
# ===============
function jet_result_to_diagnostics!(uri2diagnostics::URI2Diagnostics, result::JET.JETToplevelResult, postprocessor::JET.PostProcessor)
for report in result.res.toplevel_error_reports
if report isa JET.LoweringErrorReport || report isa JET.MacroExpansionErrorReport
# the equivalent report should have been reported by `lowering_diagnostics!`
# with more precise location information
continue
end
diagnostic = @something jet_toplevel_error_report_to_diagnostic(report, postprocessor) continue
filename = report.file
filename === :none && continue
if startswith(filename, "Untitled")
uri = filename2uri(filename)
else
uri = filepath2uri(to_full_path(filename))
end
push!(uri2diagnostics[uri], diagnostic)
end
displayable_reports = collect_displayable_reports(result.res.inference_error_reports, keys(uri2diagnostics))
jet_inference_error_reports_to_diagnostics!(uri2diagnostics, displayable_reports, postprocessor)
return uri2diagnostics
end
# toplevel diagnostic
# -------------------
function jet_toplevel_error_report_to_diagnostic(
@nospecialize(report::JET.ToplevelErrorReport), postprocessor::JET.PostProcessor
)
report isa JET.ParseErrorReport && return nothing # Syntax errors should be reported via `textDocument/diagnostic` or `workspace/diangostic`
message = JET.with_bufferring(:limit=>true) do io
JET.print_report(io, report)
end |> postprocessor
return Diagnostic(;
range = line_range(report.line),
severity = DiagnosticSeverity.Error,
message,
source = DIAGNOSTIC_SOURCE_SAVE,
code = TOPLEVEL_ERROR_CODE,
codeDescription = diagnostic_code_description(TOPLEVEL_ERROR_CODE))
end
# inference diagnostic
# --------------------
function jet_inference_error_reports_to_diagnostics!(
uri2diagnostics::URI2Diagnostics, reports::Vector{JET.InferenceErrorReport},
postprocessor::JET.PostProcessor
)
for report in reports
diagnostic = jet_inference_error_report_to_diagnostic(report, postprocessor)
topframeidx = first(inference_error_report_stack(report))
topframe = report.vst[topframeidx]
topframe.file === :none && continue # TODO Figure out why this is necessary
uri = jet_frame_to_uri(topframe)
push!(uri2diagnostics[uri], diagnostic) # collect_displayable_reports asserts that this `uri` key exists for `uri2diagnostics`
end
return uri2diagnostics
end
function jet_inference_error_report_to_diagnostic(@nospecialize(report::JET.InferenceErrorReport), postprocessor::JET.PostProcessor)
rstack = inference_error_report_stack(report)
topframe = report.vst[first(rstack)]
message = JET.with_bufferring(:limit=>true) do io
JET.print_report_message(io, report)
end |> postprocessor
relatedInformation = DiagnosticRelatedInformation[]
for i = 2:length(rstack)
frame = report.vst[rstack[i]]
location = @something jet_frame_to_location(frame) continue
local message = postprocessor(sprint(JET.print_frame_sig, frame, JET.PrintConfig()))
push!(relatedInformation, DiagnosticRelatedInformation(; location, message))
end
code = inference_error_report_code(report)
return Diagnostic(;
range = jet_frame_to_range(topframe),
severity = inference_error_report_severity(report),
message,
source = DIAGNOSTIC_SOURCE_SAVE,
code,
codeDescription = diagnostic_code_description(code),
relatedInformation)
end
function inference_error_report_code(@nospecialize report::JET.InferenceErrorReport)
if report isa UndefVarErrorReport
if report.var isa GlobalRef
return INFERENCE_UNDEF_GLOBAL_VAR_CODE
else
return INFERENCE_UNDEF_STATIC_PARAM_CODE
end
elseif report isa FieldErrorReport
return INFERENCE_FIELD_ERROR_CODE
elseif report isa BoundsErrorReport
return INFERENCE_BOUNDS_ERROR_CODE
elseif report isa MethodErrorReport
return INFERENCE_METHOD_ERROR_CODE
end
error(lazy"Diagnostic code is not defined for this report: $report")
end
# toplevel warning diagnostic
# ===========================
abstract type ToplevelWarningReport end
toplevel_warning_report_to_uri(report::ToplevelWarningReport) = toplevel_warning_report_to_uri_impl(report)::URI
toplevel_warning_report_to_uri_impl(::ToplevelWarningReport) =
error("Missing `toplevel_warning_report_to_uri_impl(::ToplevelWarningReport)` interface")
toplevel_warning_report_to_diagnostic(report::ToplevelWarningReport, sfi::SavedFileInfo, postprocessor::JET.PostProcessor) =
toplevel_warning_report_to_diagnostic_impl(report, sfi, postprocessor)::Diagnostic
toplevel_warning_report_to_diagnostic_impl(::ToplevelWarningReport, ::SavedFileInfo, ::JET.PostProcessor) =
error("Missing `toplevel_warning_report_to_diagnostic_impl(::ToplevelWarningReport, ::SavedFileInfo, ::JET.PostProcessor)` interface")
function toplevel_warning_reports_to_diagnostics!(
uri2diagnostics::URI2Diagnostics, reports::Vector{ToplevelWarningReport},
server::Server, postprocessor::JET.PostProcessor
)
for report in reports
uri = toplevel_warning_report_to_uri(report)
haskey(uri2diagnostics, uri) || continue
sfi = @something get_saved_file_info(server.state, uri) continue
diagnostic = toplevel_warning_report_to_diagnostic(report, sfi, postprocessor)
push!(uri2diagnostics[uri], diagnostic)
end
return uri2diagnostics
end
struct MethodOverwriteReport <: ToplevelWarningReport
mod::Module
sig::Type
filepath::String
lines::Pair{Int,Int}
original_filepath::String
original_lines::Pair{Int,Int}
MethodOverwriteReport(
mod::Module, @nospecialize(sig::Type), filepath::AbstractString, lines::Pair{Int,Int},
original_filepath::AbstractString, original_lines::Pair{Int,Int}
) = new(mod, sig, filepath, lines, original_filepath, original_lines)
end
toplevel_warning_report_to_uri_impl(report::MethodOverwriteReport) = filepath2uri(report.filepath)
function toplevel_warning_report_to_diagnostic_impl(report::MethodOverwriteReport, ::SavedFileInfo, postprocessor::JET.PostProcessor)
sig_str = postprocessor(sprint(Base.show_tuple_as_call, Symbol(""), report.sig))
mod_str = postprocessor(sprint(show, report.mod))
message = "Method definition $sig_str in module $mod_str overwritten"
relatedInformation = DiagnosticRelatedInformation[
DiagnosticRelatedInformation(;
location = Location(;
uri = filepath2uri(report.original_filepath),
range = lines_range(report.original_lines)),
message = "The first method definition $sig_str")
]
return Diagnostic(;
range = lines_range(report.lines),
severity = DiagnosticSeverity.Warning,
message,
source = DIAGNOSTIC_SOURCE_SAVE,
code = TOPLEVEL_METHOD_OVERWRITE_CODE,
codeDescription = diagnostic_code_description(TOPLEVEL_METHOD_OVERWRITE_CODE),
relatedInformation)
end
struct AbstractFieldReport <: ToplevelWarningReport
filepath::String
fieldline::Union{Int,JS.SyntaxNode}
typ::Type
fname::Symbol
ft
AbstractFieldReport(
filepath::AbstractString, fieldline::Union{Int,JS.SyntaxNode}, @nospecialize(typ::Type), fname::Symbol, @nospecialize(ft)
) = new(filepath, fieldline, typ, fname, ft)
end
toplevel_warning_report_to_uri_impl(report::AbstractFieldReport) = filepath2uri(report.filepath)
function toplevel_warning_report_to_diagnostic_impl(report::AbstractFieldReport, sfi::SavedFileInfo, postprocessor::JET.PostProcessor)
typ_str = postprocessor(sprint(show, report.typ))
ft_str = postprocessor(sprint(show, report.ft))
message = "`$typ_str` has abstract field `$(report.fname)::$ft_str`"
fieldline = report.fieldline
range = fieldline isa Int ? line_range(fieldline) : jsobj_to_range(fieldline, sfi)
return Diagnostic(;
range,
severity = DiagnosticSeverity.Information,
message,
source = DIAGNOSTIC_SOURCE_SAVE,
code = TOPLEVEL_ABSTRACT_FIELD_CODE,
codeDescription = diagnostic_code_description(TOPLEVEL_ABSTRACT_FIELD_CODE))
end
# lowering diagnostic
# ===================
const JL_MACRO_FILE = only(methods(JL.expand_macro, (JL.MacroExpansionContext,JS.SyntaxTree))).file
function scrub_expand_macro_stacktrace(stacktrace::Vector{Base.StackTraces.StackFrame})
idx = @something findfirst(stacktrace) do stackframe::Base.StackTraces.StackFrame
stackframe.func === :expand_macro && stackframe.file === JL_MACRO_FILE
end return stacktrace
return stacktrace[1:idx-1]
end
function stacktrace_to_related_information(stacktrace::Vector{Base.StackTraces.StackFrame})
relatedInformation = DiagnosticRelatedInformation[]
for stackframe in stacktrace
stackframe.file === :none && continue
uri = filepath2uri(to_full_path(stackframe.file))
range = line_range(stackframe.line)
location = Location(; uri, range)
message = let linfo = stackframe.linfo
linfo isa Core.CodeInstance && (linfo = linfo.def)
if linfo isa Core.MethodInstance
sprint(Base.show_tuple_as_call, Symbol(""), linfo.specTypes)
else
String(stackframe.func)
end
end
push!(relatedInformation, DiagnosticRelatedInformation(; location, message))
end
return relatedInformation
end
# TODO Use actual file cache (with proper character encoding)
function provenances_to_related_information!(relatedInformation::Vector{DiagnosticRelatedInformation}, provs, msg)
for prov in provs
filename = JS.filename(prov)
uri = filepath2uri(to_full_path(filename))
sr = JS.sourceref(prov)
if sr isa JS.SourceRef
# use precise location information if available
sf = JS.sourcefile(sr)
code = JS.sourcetext(sf)
location = Location(;
uri,
range = Range(;
start = offset_to_xy(code, JS.first_byte(sr), filename),
var"end" = offset_to_xy(code, JS.last_byte(sr), filename)))
message = JS.sourcetext(sr)
else
location = Location(;
uri,
range = line_range(first(JS.source_location(prov))))
message = msg
end
push!(relatedInformation, DiagnosticRelatedInformation(; location, message))
end
return relatedInformation
end
struct LoweringDiagnosticKey
range::Range
kind::Symbol
name::String
end
# Compute a mapping from source locations to the set of identifier names found in keyword
# argument type annotations.
function compute_kwarg_type_annotation_names(st0::JS.SyntaxTree)
result = Dict{Tuple{Int,Int},Set{String}}()
traverse(st0) do node
JS.kind(node) === JS.K"kw" || return
JS.numchildren(node) >= 1 || return traversal_no_recurse
child = node[1]
if JS.kind(child) === JS.K"::" && JS.numchildren(child) >= 2
names = Set{String}()
collect_identifier_names!(names, child[2])
if !isempty(names)
result[JS.source_location(child)] = names
end
end
return traversal_no_recurse
end
return result
end
function collect_identifier_names!(names::Set{String}, st::JS.SyntaxTree)
if JS.kind(st) === JS.K"Identifier"
name = get(st, :name_val, nothing)
if name !== nothing
push!(names, name::String)
end
return
end
for i = 1:JS.numchildren(st)
collect_identifier_names!(names, st[i])
end
end
# Check if a keyword argument's type annotation constrains a `where`-clause static parameter
# that is actually used in the function body.
# For example, in `f(; dtype::Type{T}=Float32) where {T} = T.(xs)`, `dtype` is not directly
# used in the body but it constrains `T` which is used, so `dtype` should not be reported.
# NOTE: This exception is only for keyword arguments. Positional arguments can be replaced with
# `_::Type{T}` or `::Type{T}` to suppress the unused warning.
function is_kwarg_constraining_used_sparam(
kwarg_type_names::Dict{Tuple{Int,Int},Set{String}},
prov_loc::Tuple{Int,Int},
ctx3::JL.VariableAnalysisContext
)
names = @something get(kwarg_type_names, prov_loc, nothing) return false
for binfo in ctx3.bindings.info
binfo.kind === :static_parameter || continue
binfo.is_read || continue
binfo.name in names && return true
end
return false
end
function has_matching_argument_binding(
binding_occurrences::Dict{JL.BindingInfo,Set{BindingOccurrence{Tree3}}},
name::String, range::Range,
fi::FileInfo, ctx3::JL.VariableAnalysisContext
) where Tree3<:JS.SyntaxTree
for (binfo2, _) in binding_occurrences
binfo2.kind === :argument || continue
binfo2.name == name || continue
provs2 = JS.flattened_provenance(JL.binding_ex(ctx3, binfo2.id))
is_from_user_ast(provs2) || continue
jsobj_to_range(last(provs2), fi) == range && return true
end
return false
end
function analyze_unused_bindings!(
diagnostics::Vector{Diagnostic}, fi::FileInfo, st0::JS.SyntaxTree, ctx3::JL.VariableAnalysisContext,
binding_occurrences::Dict{JL.BindingInfo,Set{BindingOccurrence{Tree3}}},
has_implicit_args::Bool, reported::Set{LoweringDiagnosticKey},
kwarg_type_names::Dict{Tuple{Int,Int},Set{String}};
allow_unused_underscore::Bool
) where Tree3<:JS.SyntaxTree
for (binfo, occurrences) in binding_occurrences
bk = binfo.kind
bk === :global && continue
if any(occurrence::BindingOccurrence->occurrence.kind===:use, occurrences)
continue
end
bn = binfo.name
if has_implicit_args && bn in _IMPLICIT_BINDING_NAMES
continue
end
if allow_unused_underscore && startswith(bn, '_')
continue
end
provs = JS.flattened_provenance(JL.binding_ex(ctx3, binfo.id))
is_from_user_ast(provs) || continue
prov = last(provs)
if bk === :argument
prov_loc = JS.source_location(prov)
if is_kwarg_constraining_used_sparam(kwarg_type_names, prov_loc, ctx3)
continue
end
end
range = jsobj_to_range(prov, fi)
key = LoweringDiagnosticKey(range, bk, bn)
key in reported ? continue : push!(reported, key)
if bk === :local && has_matching_argument_binding(binding_occurrences, bn, range, fi, ctx3)
# When `:argument` and `:local` bindings are merged at the same
# location (keyword dependent defaults), only the `:argument`
# diagnostic should be reported.
continue
end
if bk === :argument
message = "Unused argument `$bn`"
code = LOWERING_UNUSED_ARGUMENT_CODE
data = nothing
else
message = "Unused local binding `$bn`"
code = LOWERING_UNUSED_LOCAL_CODE
data = compute_unused_variable_data(st0, prov, fi)
end
push!(diagnostics, Diagnostic(;
range,
severity = DiagnosticSeverity.Information,
message,
source = DIAGNOSTIC_SOURCE_LIVE,
code,
codeDescription = diagnostic_code_description(code),
tags = DiagnosticTag.Ty[DiagnosticTag.Unnecessary],
data))
end
end
# This analysis reports `lowering/undef-global-var` on a change basis, utilizing an already
# analyzed analysis context. Full-analysis also reports similar diagnostics as
# `inference/undef-global-var`. These two diagnostics have the following differences:
# - `inference/undef-global-var` (full-analysis): Triggered on a save basis. Since it's not
# integrated with JuliaLowering, position information can only be reported on a line basis.
# On the other hand, it can also report cases like `Base.undefvar` and generally is more correct.
# - `lowering/undef-global-var` (lowering analysis): Triggered on a change basis, so feedback is
# faster. Since it's based on JuliaLowering, position information is accurate. However, it
# cannot analyze cases like `Base.undefvar`, so it basically detects a subset of what
# full-analysis reports.
function analyze_undefined_global_bindings!(
diagnostics::Vector{Diagnostic}, fi::FileInfo, ctx3::JL.VariableAnalysisContext,
binding_occurrences::Dict{JL.BindingInfo,Set{BindingOccurrence{Tree3}}},
reported::Set{LoweringDiagnosticKey};
analyzer::Union{Nothing,LSAnalyzer} = nothing,
postprocessor::LSPostProcessor = LSPostProcessor()
) where Tree3<:JS.SyntaxTree
world = Base.get_world_counter()
for (binfo, occurrences) in binding_occurrences
bk = binfo.kind
bk === :global || continue
binfo.is_internal && continue
startswith(binfo.name, '#') && continue
any(o->o.kind===:def, occurrences) && continue
mod = binfo.mod
isnothing(mod) && continue
Base.invoke_in_world(world, isdefinedglobal, mod, Symbol(binfo.name))::Bool && continue
if !isnothing(analyzer)
bp = Base.lookup_binding_partition(world, GlobalRef(mod, Symbol(binfo.name)))
haskey(JET.AnalyzerState(analyzer).binding_states, bp) && continue
end
bn = binfo.name
provs = JS.flattened_provenance(JL.binding_ex(ctx3, binfo.id))
is_from_user_ast(provs) || continue
range = jsobj_to_range(last(provs), fi)
key = LoweringDiagnosticKey(range, bk, bn)
key in reported ? continue : push!(reported, key)
code = LOWERING_UNDEF_GLOBAL_VAR_CODE
push!(diagnostics, Diagnostic(;
range,
severity = DiagnosticSeverity.Warning,
message = postprocessor("`$(mod).$(binfo.name)` is not defined"),
source = DIAGNOSTIC_SOURCE_LIVE,
code,
codeDescription = diagnostic_code_description(code)))
end
end
# This analysis reports `lowering/undef-local-var` on a change basis, based on
# `analyze_undef_all_lambdas`, which analyzes local binding definedness with the event
# based binding assignment reachability analysis.
# Severity levels:
# - Warning: `undef===true` → strict undef (guaranteed UndefVarError on some path)
# - Information: `undef===nothing` → maybe undef (possible UndefVarError)
function analyze_undefined_local_bindings!(
diagnostics::Vector{Diagnostic}, uri::URI, fi::FileInfo,
undef_info::Dict{JL.BindingInfo, UndefInfo},
reported::Set{LoweringDiagnosticKey}
)
for (binfo, uinfo) in undef_info
binfo.kind === :local || continue # defensive check (already filtered in analyze_undef)
binfo.is_read || continue # optimization: skip expensive checks below if not read
binfo.is_internal && continue
startswith(binfo.name, '#') && continue
undef_status = uinfo.undef
undef_status === false && continue
first_use_tree = first(uinfo.uses)
provs = JL.flattened_provenance(first_use_tree)
is_from_user_ast(provs) || continue
range = jsobj_to_range(last(provs), fi)
key = LoweringDiagnosticKey(range, binfo.kind, binfo.name)
key in reported ? continue : push!(reported, key)
relatedInformation = DiagnosticRelatedInformation[]
for def_tree in uinfo.defs
def_provs = JL.flattened_provenance(def_tree)
isempty(def_provs) && continue
innermost = last(def_provs)
uri2filename(uri) == JS.filename(innermost) || continue
def_range = jsobj_to_range(innermost, fi)
push!(relatedInformation, DiagnosticRelatedInformation(;
location = Location(uri, def_range),
message = "`$(binfo.name)` is defined here"))
end
push!(diagnostics, Diagnostic(;
range,
# Determine severity based on whether this is strict undef or maybe undef
severity = undef_status === true ? DiagnosticSeverity.Warning : DiagnosticSeverity.Information,
message = undef_status === true ?
"Variable `$(binfo.name)` is used before it is defined" :
"Variable `$(binfo.name)` may be used before it is defined",
source = DIAGNOSTIC_SOURCE_LIVE,
code = LOWERING_UNDEF_LOCAL_VAR_CODE,
codeDescription = diagnostic_code_description(LOWERING_UNDEF_LOCAL_VAR_CODE),
relatedInformation = @somereal relatedInformation Some(nothing)))
end
end
function compute_unused_variable_data(
st0::JS.SyntaxTree,
prov::JS.SyntaxTree,
fi::FileInfo
)
# Find parent K"=" node using byte_ancestors
ancestors = byte_ancestors(st::JS.SyntaxTree->JS.kind(st)===JS.K"=", st0, JS.byte_range(prov))
isempty(ancestors) && return nothing
assignment = first(ancestors)
JS.numchildren(assignment) ≥ 2 || return nothing
lhs, rhs = assignment[1], assignment[2]
# Check for destructuring patterns (tuple unpacking)
is_tuple = JS.kind(lhs) === JS.K"tuple"
if is_tuple
return UnusedVariableData(true, nothing, nothing)
end
# lhs_eq_range: from LHS start to RHS start (exclusive)
assignment_range = jsobj_to_range(assignment, fi)
lhs_start = offset_to_xy(fi, JS.first_byte(lhs))
rhs_start = offset_to_xy(fi, JS.first_byte(rhs))
lhs_eq_range = Range(; start=lhs_start, var"end"=rhs_start)
return UnusedVariableData(false, assignment_range, lhs_eq_range)
end
function analyze_captured_boxes!(
diagnostics::Vector{Diagnostic}, uri::URI, fi::FileInfo,
ctx4::JL.ClosureConversionCtx, st3::JL.SyntaxTree,
reported::Set{LoweringDiagnosticKey}
)
for binfo in ctx4.bindings.info
JL.is_boxed(binfo) || continue
binfo.is_internal && continue
startswith(binfo.name, '#') && continue
is_captured_binding(binfo, ctx4) || continue
bn = binfo.name
provs = JL.flattened_provenance(JL.binding_ex(ctx4, binfo.id))
is_from_user_ast(provs) || continue
range = jsobj_to_range(last(provs), fi)
key = LoweringDiagnosticKey(range, :boxed, bn)
key in reported ? continue : push!(reported, key)
code = LOWERING_CAPTURED_BOXED_VARIABLE_CODE
relatedInformation = find_capture_sites(st3, binfo, ctx4, uri, fi)
push!(diagnostics, Diagnostic(;
range,
severity = DiagnosticSeverity.Information,
message = "`$bn` is captured and boxed",
source = DIAGNOSTIC_SOURCE_LIVE,
code,
codeDescription = diagnostic_code_description(code),
relatedInformation))
end
end
# Normally JuliaLowering only applies binding analysis to variables that are actually captured,
# but currently there are some edge cases where incorrect bindings are introduced, resulting
# in false positive captured boxes being reported.
# This check is basically a band-aid, and the fundamental issue should be resolved on the
# JuliaLowering side.
function is_captured_binding(binfo::JL.BindingInfo, ctx4::JL.ClosureConversionCtx)
for (_, closure_bindings) in ctx4.closure_bindings
for lambda in closure_bindings.lambdas
haskey(lambda.locals_capt, binfo.id) && return true
end
end
return false
end
function find_capture_sites(
st3::JL.SyntaxTree, binfo::JL.BindingInfo, ctx4::JL.ClosureConversionCtx,
uri::URI, fi::FileInfo
)
relatedInformation = DiagnosticRelatedInformation[]
for (_, closure_bindings) in ctx4.closure_bindings
for lambda in closure_bindings.lambdas
haskey(lambda.locals_capt, binfo.id) || continue
lambda.locals_capt[binfo.id] || continue
# Find the lambda in st3 that has matching lambda_bindings.self
traverse(st3) do node::JL.SyntaxTree
JS.kind(node) === JS.K"lambda" || return nothing
hasproperty(node, :lambda_bindings) || return nothing
lambda_bindings = node.lambda_bindings::JL.LambdaBindings
lambda_bindings.self == lambda.self || return nothing
# Find references to binfo.id inside this lambda
traverse(node) do inner::JL.SyntaxTree
if JS.kind(inner) === JS.K"BindingId" && JL._binding_id(inner) == binfo.id
varprov = first(JL.flattened_provenance(inner))
push!(relatedInformation, DiagnosticRelatedInformation(;
location = Location(; uri, range = jsobj_to_range(varprov, fi)),
message = "Captured by closure"))
end
end
return traversal_no_recurse
end
end
end
return @somereal relatedInformation Some(nothing)
end
const SORT_IMPORTS_MAX_LINE_LENGTH = 92
const SORT_IMPORTS_INDENT = " "
function analyze_unsorted_imports!(
diagnostics::Vector{Diagnostic}, fi::FileInfo, st0::JS.SyntaxTree
)
traverse(st0) do st0′::JS.SyntaxTree
kind = JS.kind(st0′)
if kind ∉ JS.KSet"import using export public"
return nothing
end
names = collect_import_names(st0′)
if !is_sorted_imports(names)
range = jsobj_to_range(st0′, fi)
sorted_names = sort!(names; by=get_import_sort_key)
base_indent = get_line_indent(fi, JS.first_byte(st0′))
new_text = generate_sorted_import_text(st0′, sorted_names, base_indent)
push!(diagnostics, Diagnostic(;
range,
severity = DiagnosticSeverity.Hint,
message = "Names are not sorted alphabetically",
source = DIAGNOSTIC_SOURCE_LIVE,
code = LOWERING_UNSORTED_IMPORT_NAMES_CODE,
codeDescription = diagnostic_code_description(LOWERING_UNSORTED_IMPORT_NAMES_CODE),
data = UnsortedImportData(new_text)))
end
return traversal_no_recurse
end
return diagnostics
end
function generate_sorted_import_text(
node::JS.SyntaxTree, sorted_names::Vector{JS.SyntaxTree},
base_indent::Union{String,Nothing}
)
kind = JS.kind(node)
keyword = kind === JS.K"import" ? "import" :
kind === JS.K"using" ? "using" :
kind === JS.K"export" ? "export" : "public"
if kind === JS.K"import" || kind === JS.K"using"
nchildren = JS.numchildren(node)
if nchildren == 1 && JS.kind(node[1]) === JS.K":"
module_path = lstrip(JS.sourcetext(node[1][1]))
prefix = "$keyword $module_path: "
else
prefix = "$keyword "
end
else
prefix = "$keyword "
end
name_texts = String[lstrip(JS.sourcetext(n)) for n in sorted_names]
single_line = prefix * join(name_texts, ", ")
if base_indent === nothing
return single_line
end
if length(base_indent) + length(single_line) <= SORT_IMPORTS_MAX_LINE_LENGTH
return single_line
end
continuation_indent = base_indent * SORT_IMPORTS_INDENT
lines = String[prefix * name_texts[1]]
current_line_idx = 1
for i = 2:length(name_texts)
name = name_texts[i]
current_indent = current_line_idx == 1 ? base_indent : continuation_indent
potential_line = lines[current_line_idx] * ", " * name
if length(current_indent) + length(potential_line) <= SORT_IMPORTS_MAX_LINE_LENGTH
lines[current_line_idx] = potential_line
else
lines[current_line_idx] *= ","
push!(lines, continuation_indent * name)
current_line_idx += 1
end
end
return join(lines, "\n")
end
function collect_import_names(st0::JS.SyntaxTree)
kind = JS.kind(st0)
names = JS.SyntaxTree[]
if kind === JS.K"import" || kind === JS.K"using"
nchildren = JS.numchildren(st0)
if nchildren == 1
child = st0[1]
if JS.kind(child) === JS.K":"
for i = 2:JS.numchildren(child)
push!(names, child[i])
end
end
elseif nchildren > 1
for i = 1:nchildren
push!(names, st0[i])