Source file diagnostic.ml
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
type theme = {
error_header : string;
warning_header : string;
hint_header : string;
error_label : string;
warning_label : string;
secondary_label : string;
line_numbers : string;
body : Colors.theme;
}
let get_theme ?(color = Colors.Auto) ?(palette = Colors.wax_theme) () =
let use_color = Colors.should_use_color ~color ~out_channel:(Some stderr) in
let body = if use_color then palette else Colors.no_color in
let open Colors in
if use_color then
{
error_header = Ansi.bold ^ Ansi.high_red;
warning_header = Ansi.bold ^ Ansi.high_yellow;
hint_header = Ansi.bold ^ Ansi.cyan;
error_label = Ansi.red;
warning_label = Ansi.yellow;
secondary_label = Ansi.bold ^ Ansi.blue;
line_numbers = Ansi.cyan;
body;
}
else
{
error_header = "";
warning_header = "";
hint_header = "";
error_label = "";
warning_label = "";
secondary_label = "";
line_numbers = "";
body;
}
type sink = { write : string -> unit; flush : unit -> unit }
let channel_sink oc =
{ write = (fun s -> output_string oc s); flush = (fun () -> flush oc) }
let buffer_sink b =
{ write = (fun s -> Buffer.add_string b s); flush = (fun () -> ()) }
let line sink s =
sink.write (s ^ "\n");
sink.flush ()
let with_style color s = if color = "" then s else color ^ s ^ Colors.Ansi.reset
type label = { location : Ast.location; message : Message.t }
type severity = Error | Warning | Suggestion
type edit = { edit_location : Ast.location; new_text : string }
type t = {
location : Ast.location;
severity : severity;
warning : Warning.t option;
message : Message.t;
hint : Message.t option;
edit : edit option;
related : label list;
universal : bool;
}
type output_format = Human | Json | Short
let global_format = ref Human
let set_format f = global_format := f
let output_error_json ~output ~location ~severity ?warning ?hint ?(related = [])
?edit msg =
let col (p : Lexing.position) = p.pos_cnum - p.pos_bol in
let span { Ast.loc_start; loc_end } : (string * Yojson.Safe.t) list =
[
("startLine", `Int loc_start.Lexing.pos_lnum);
("startColumn", `Int (col loc_start));
("endLine", `Int loc_end.Lexing.pos_lnum);
("endColumn", `Int (col loc_end));
("startOffset", `Int loc_start.Lexing.pos_cnum);
("endOffset", `Int loc_end.Lexing.pos_cnum);
]
in
let obj : Yojson.Safe.t =
`Assoc
([
( "severity",
`String
(match severity with
| Error -> "error"
| Warning -> "warning"
| Suggestion -> "suggestion") );
("file", `String location.Ast.loc_start.Lexing.pos_fname);
]
@ span location
@ [
("message", `String (Message.to_plain_string msg));
( "warning",
match warning with
| Some w -> `String (Warning.name w)
| None -> `Null );
( "hint",
match hint with
| Some m -> `String (Message.to_plain_string m)
| None -> `Null );
( "related",
`List
(List.map
(fun (l : label) : Yojson.Safe.t ->
`Assoc
(span l.location
@ [
("message", `String (Message.to_plain_string l.message));
]))
related) );
]
@
match edit with
| Some { edit_location; new_text } ->
[
( "edit",
`Assoc (span edit_location @ [ ("newText", `String new_text) ]) );
]
| None -> [])
in
line output (Yojson.Safe.to_string obj)
let output_error_short ~output ~location ~severity ?warning msg =
let one_line m =
String.trim
(String.map
(fun c -> if c = '\n' then ' ' else c)
(Message.to_plain_string m))
in
let sev =
match severity with
| Error -> "error"
| Warning -> "warning"
| Suggestion -> "suggestion"
in
let suffix =
match warning with
| Some w -> Printf.sprintf " [%s]" (Warning.name w)
| None -> ""
in
let p = location.Ast.loc_start in
if p = Lexing.dummy_pos then
line output (Printf.sprintf "%s: %s%s" sev (one_line msg) suffix)
else
line output
(Printf.sprintf "%s:%d:%d: %s: %s%s" p.Lexing.pos_fname p.Lexing.pos_lnum
(p.Lexing.pos_cnum - p.Lexing.pos_bol + 1)
sev (one_line msg) suffix)
let render_body ~theme p m = Message.render ~theme:theme.body p m
let headed sink ~ ~ body =
let rendered =
Printer.run_string (fun p ->
Printer.hvbox p ~indent:2 (fun () ->
Printer.string_as p (String.length header_plain) header_styled;
Printer.space p ();
body p))
in
List.iter (line sink) (String.split_on_char '\n' rendered)
let print_hint ?(output = channel_sink stderr) ~theme hint =
match hint with
| None -> ()
| Some m ->
headed output ~header_plain:"Hint:"
~header_styled:(with_style theme.hint_header "Hint" ^ ":")
(fun p -> render_body ~theme p m)
let print_fix ?(output = channel_sink stderr) ~theme ~severity ?warning edit =
match (severity, warning, edit) with
| Error, None, Some { edit_location; new_text } ->
let action =
if
edit_location.Ast.loc_start.Lexing.pos_cnum
= edit_location.loc_end.Lexing.pos_cnum
then Printf.sprintf "insert '%s'" new_text
else if new_text = "" then "remove this"
else Printf.sprintf "replace with '%s'" new_text
in
headed output ~header_plain:"Help:"
~header_styled:(with_style theme.hint_header "Help" ^ ":")
(fun p -> Printer.string p action)
| _ -> ()
let output_error_no_loc ?(output = channel_sink stderr) ~theme ~severity
?warning ~hint msg =
let name_suffix =
match warning with
| Some w -> Printf.sprintf " [%s]" (Warning.name w)
| None -> ""
in
let word, color =
match severity with
| Error -> ("Error", theme.error_header)
| Warning -> ("Warning", theme.warning_header)
| Suggestion -> ("Suggestion", theme.hint_header)
in
headed output
~header_plain:(word ^ name_suffix ^ ":")
~header_styled:(with_style color word ^ name_suffix ^ ":")
(fun p -> render_body ~theme p msg);
print_hint ~output ~theme hint
let output_error_no_source ?(output = channel_sink stderr) ~theme
~location:{ Ast.loc_start; loc_end } ~severity ?warning ?hint msg =
let start_line = loc_start.Lexing.pos_lnum in
let end_line = loc_end.Lexing.pos_lnum in
let filename = loc_start.Lexing.pos_fname in
let s_bol = loc_start.Lexing.pos_bol in
let s_cnum = loc_start.Lexing.pos_cnum in
let start_col = s_cnum - s_bol in
let e_bol = loc_end.Lexing.pos_bol in
let e_cnum = loc_end.Lexing.pos_cnum in
let end_col = e_cnum - e_bol in
if start_line = end_line then
line output
(Printf.sprintf "File \"%s\", line %d, characters %d-%d:" filename
start_line start_col end_col)
else
line output
(Printf.sprintf
"File \"%s\", line %d, character %d to line %d, character %d:" filename
start_line start_col end_line end_col);
output_error_no_loc ~output ~theme ~severity ?warning ~hint msg
type annotation = {
start_line : int;
end_line : int;
start_col : int;
end_col : int;
color : string;
label : Message.t option;
}
let get_annotations ~theme ~severity ~location ~related =
let main =
let { Ast.loc_start; loc_end } = location in
let start_line = loc_start.Lexing.pos_lnum in
let end_line = loc_end.Lexing.pos_lnum in
let start_col = loc_start.Lexing.pos_cnum - loc_start.Lexing.pos_bol in
let end_col = loc_end.Lexing.pos_cnum - loc_end.Lexing.pos_bol in
let color =
match severity with
| Error -> theme.error_label
| Warning -> theme.warning_label
| Suggestion -> theme.secondary_label
in
{ start_line; end_line; start_col; end_col; color; label = None }
in
let secondary =
List.map
(fun ({ location; message } : label) ->
let { Ast.loc_start; loc_end } = location in
let start_line = loc_start.Lexing.pos_lnum in
let end_line = loc_end.Lexing.pos_lnum in
let start_col = loc_start.Lexing.pos_cnum - loc_start.Lexing.pos_bol in
let end_col = loc_end.Lexing.pos_cnum - loc_end.Lexing.pos_bol in
{
start_line;
end_line;
start_col;
end_col;
color = theme.secondary_label;
label = Some message;
})
related
in
main :: secondary
let get_hunks annotations =
let context = 2 in
let ranges =
List.concat_map
(fun a ->
[
(a.start_line - context, a.start_line + context);
(a.end_line - context, a.end_line + context);
])
annotations
in
let ranges = List.sort (fun (s1, _) (s2, _) -> compare s1 s2) ranges in
let rec merge = function
| [] -> []
| [ r ] -> [ r ]
| (s1, e1) :: (s2, e2) :: rest ->
if s2 <= e1 + 1 then merge ((min s1 s2, max e1 e2) :: rest)
else (s1, e1) :: merge ((s2, e2) :: rest)
in
merge ranges |> List.map (fun (s, e) -> (max 1 s, e))
let modern = true
let line_starts_cache = ref ("", [||])
let get_line_starts source =
let cached_source, cached_array = !line_starts_cache in
if source == cached_source then cached_array
else
let len = String.length source in
let starts = ref [ 0 ] in
let i = ref 0 in
while !i < len do
match String.index_from source !i '\n' with
| j ->
starts := (j + 1) :: !starts;
i := j + 1
| exception Not_found -> i := len
done;
let array = Array.of_list (List.rev !starts) in
line_starts_cache := (source, array);
array
let output_error_with_source ?(output = channel_sink stderr) ~theme ~source
~location ~severity ?warning ?hint ?edit ?(related = []) msg =
match !global_format with
| Json ->
output_error_json ~output ~location ~severity ?hint ~related ?edit msg
| Short -> output_error_short ~output ~location ~severity msg
| Human ->
let annotations = get_annotations ~theme ~severity ~location ~related in
let hunks = get_hunks annotations in
let line_starts = get_line_starts source in
let total_lines = Array.length line_starts in
let max_hunk_line =
List.fold_left (fun acc (_, e) -> max acc e) 0 hunks
in
let max_line = min max_hunk_line total_lines in
let gutter_width = max 1 (String.length (string_of_int max_line)) in
let gutter_padding = String.make gutter_width ' ' in
let filename = location.Ast.loc_start.Lexing.pos_fname in
let start_line = location.Ast.loc_start.Lexing.pos_lnum in
let start_col =
location.Ast.loc_start.Lexing.pos_cnum
- location.Ast.loc_start.Lexing.pos_bol
in
output_error_no_loc ~output ~theme ~severity ?warning ~hint:None msg;
if modern then
line output
(with_style theme.line_numbers (gutter_padding ^ "──➤")
^ Printf.sprintf " %s:%d:%d" filename start_line (start_col + 1));
let find_eol text start_pos =
try String.index_from text start_pos '\n'
with Not_found -> String.length text
in
let get_line_info text pos_bol =
if pos_bol >= String.length text then ("", pos_bol)
else
let line_end = find_eol text pos_bol in
let content = String.sub text pos_bol (line_end - pos_bol) in
(content, line_end)
in
let print_line ?(gutter_char = "│") contents =
line output
(with_style theme.line_numbers (header ^ " " ^ gutter_char)
^ " " ^ contents)
in
let curr_pos = ref 0 in
let curr_line = ref 1 in
let seek line =
if line <= total_lines then (
curr_pos := line_starts.(line - 1);
curr_line := line)
else (
curr_pos := String.length source;
curr_line := total_lines + 1)
in
let total_hunks = List.length hunks in
List.iteri
(fun i (s_line, e_line) ->
if i > 0 then
line output
(with_style theme.line_numbers (gutter_padding ^ " ·") ^ " ...");
seek s_line;
while !curr_line <= min e_line total_lines do
let is_last_line =
!curr_line = min e_line total_lines && i = total_hunks - 1
in
let raw_content, next_eol = get_line_info source !curr_pos in
let display_content = Unicode.expand_tabs raw_content in
print_line
(Printf.sprintf "%*d" gutter_width !curr_line)
display_content;
let line_annotations =
List.filter
(fun a ->
!curr_line >= a.start_line && !curr_line <= a.end_line)
annotations
in
let num_annots = List.length line_annotations in
let vis_col col =
let col = min (String.length raw_content) col in
Unicode.terminal_width (String.sub raw_content 0 col)
in
List.iteri
(fun j a ->
let is_last_annot = is_last_line && j = num_annots - 1 in
let gutter_char = if is_last_annot then " " else "·" in
let is_start = !curr_line = a.start_line in
let is_end = !curr_line = a.end_line in
let carets =
if is_start && is_end then
let start_vis = vis_col a.start_col in
let end_vis = vis_col a.end_col in
let underline =
String.make (max 1 (end_vis - start_vis)) '^'
in
String.make start_vis ' ' ^ underline
else
let reach caret =
if caret <= 0 then ""
else
let dashes =
String.concat ""
(List.init (caret - 1) (fun _ -> "─"))
in
dashes ^ "^"
in
if is_start then "╭" ^ reach (vis_col a.start_col)
else if is_end then
"╰" ^ reach (max 1 (vis_col a.end_col) - 1)
else "│"
in
let label =
match a.label with
| Some m when is_end ->
" " ^ with_style a.color (Message.to_plain_string m)
| _ -> ""
in
print_line ~gutter_char gutter_padding
(with_style a.color carets ^ label))
line_annotations;
curr_pos := min (String.length source) (next_eol + 1);
incr curr_line
done)
hunks;
print_hint ~output ~theme hint;
print_fix ~output ~theme ~severity ?warning edit
let output_error ?(output = channel_sink stderr) ~theme ~source ~location
~severity ?warning ?hint ?edit ?(related = []) msg =
match !global_format with
| Json ->
output_error_json ~output ~location ~severity ?warning ?hint ~related
?edit msg
| Short -> output_error_short ~output ~location ~severity ?warning msg
| Human -> (
if location.Ast.loc_start = Lexing.dummy_pos then
output_error_no_loc ~output ~theme ~severity ?warning ~hint msg
else
match source with
| None ->
output_error_no_source ~output ~theme ~location ~severity ?warning
?hint msg
| Some source ->
output_error_with_source ~output ~theme ~source ~location ~severity
?warning ?hint ?edit ~related msg)
type render = { theme : theme; output : sink; exit_on_error : bool }
type context = {
max : int;
queue : t Queue.t;
source : string option;
related : label list;
policy : Warning.policy;
render : render option;
mutable recovery : bool;
}
let global_policy = ref Warning.default_policy
let set_policy policy = global_policy := policy
let source context = context.source
let make ~source ?(related = []) ?(max = 1) ?(policy = !global_policy) ?render
() =
{
max;
queue = Queue.create ();
source;
related;
policy;
render;
recovery = false;
}
let collector ?parent ?source () =
let c = make ~source ~max:max_int () in
Option.iter (fun p -> c.recovery <- p.recovery) parent;
c
let in_recovery context = context.recovery
let set_recovery context v = context.recovery <- v
type entry = t
let collected context = List.of_seq (Queue.to_seq context.queue)
let entry_location (e : entry) = e.location
let entry_severity (e : entry) = e.severity
let entry_warning (e : entry) = e.warning
let entry_universal (e : entry) = e.universal
let entry_message (e : entry) = e.message
let entry_hint (e : entry) = e.hint
let entry_edit (e : entry) = e.edit
let entry_related (e : entry) = e.related
let output_errors ?exit_on_error context =
match context.render with
| None ->
()
| Some render ->
let exit_on_error =
match exit_on_error with Some b -> b | None -> render.exit_on_error
in
if not (Queue.is_empty context.queue) then (
Queue.iter
(fun ({
location;
severity;
hint;
message;
related;
warning;
edit;
universal = _;
} :
t) ->
output_error ~output:render.output ~theme:render.theme
~source:context.source ~location ~severity ?warning ?hint ?edit
~related message)
context.queue;
Queue.clear context.queue;
if exit_on_error then (
render.output.flush ();
exit 128))
let report context ~location ~severity ?warning ?(universal = false) ?hint ?edit
?(related = []) ~message () =
let all_related = context.related @ related in
let entry severity =
{
location;
severity;
warning;
message;
hint;
edit;
related = all_related;
universal;
}
in
match context.render with
| None ->
Queue.push (entry severity) context.queue
| Some render -> (
let severity =
match (severity, warning) with
| (Warning | Suggestion), Some w -> (
match Warning.resolve context.policy w with
| Warning.Hidden -> None
| Warning.Displayed -> Some severity
| Warning.Error -> Some Error)
| _ -> Some severity
in
match severity with
| None -> ()
| Some ((Warning | Suggestion) as severity) ->
output_error ~output:render.output ~theme:render.theme
~source:context.source ~location ~severity ?warning ?hint ?edit
~related:all_related message
| Some Error ->
Queue.push (entry Error) context.queue;
if Queue.length context.queue = context.max then output_errors context
)
exception Aborted
let abort () = raise Aborted
let run ~color ~palette ~source ?related ?(exit = true) ?output ?policy f =
let render =
{
theme = get_theme ~color ~palette ();
output = Option.value output ~default:(channel_sink stderr);
exit_on_error = exit;
}
in
let d = make ~source ?related ?policy ~render () in
match f d with
| res ->
output_errors d;
res
| exception Aborted ->
output_errors d;
raise Aborted