Source file parsing.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
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
exception
Syntax_error of (Lexing.position * Lexing.position) * Wax_utils.Message.t
type syntax_error = {
location : Wax_utils.Ast.location;
message : Wax_utils.Message.t;
related : Wax_utils.Diagnostic.label list;
}
type sync_class = Open | Close | Boundary | Leader | Terminal | Skip
exception Detailed_error of syntax_error
module E = MenhirLib.ErrorReports
module Lu = MenhirLib.LexerUtil
let succeed v = v
let show text positions =
E.extract text positions |> E.sanitize |> E.compress
|> E.shorten 20
let report_syntax_error ?(related = []) ~color source (loc_start, loc_end) msg =
let theme = Wax_utils.Diagnostic.get_theme ?color () in
Wax_utils.Diagnostic.output_error_with_source ~theme ~source ~severity:Error
~location:{ loc_start; loc_end } ~related msg;
raise (Syntax_error ((loc_start, loc_end), msg))
let read filename = In_channel.with_open_bin filename In_channel.input_all
let initialize_lexing filename text =
let lexbuf = Sedlexing.Utf8.from_string text in
Sedlexing.set_filename lexbuf filename;
lexbuf
let lexer_lexbuf_to_supplier (lexer, start_override) (lexbuf : Sedlexing.lexbuf)
() =
let token = lexer lexbuf in
let startp, endp = Sedlexing.lexing_bytes_positions lexbuf in
let startp = match !start_override with Some p -> p | None -> startp in
(token, startp, endp)
module Make (Output : sig
type t
end) (Tokens : sig
type token
end) (Parser : sig
module Make (_ : sig
type t = Wax_utils.Trivia.context
val context : t
end) : sig
type token = Tokens.token
module MenhirInterpreter :
MenhirLib.IncrementalEngine.INCREMENTAL_ENGINE with type token = token
module Incremental : sig
val parse : Lexing.position -> Output.t MenhirInterpreter.checkpoint
end
end
end) (Parser_messages : sig
val message : int -> string
end) (Lexer : sig
val token :
Wax_utils.Trivia.context ->
(Sedlexing.lexbuf -> Tokens.token) * Lexing.position option ref
end) =
struct
module Inner (Context : sig
type t = Wax_utils.Trivia.context
val context : t
end) =
struct
module P = Parser.Make (Context)
let state checkpoint : int =
match checkpoint with
| P.MenhirInterpreter.HandlingError env -> (
match P.MenhirInterpreter.top env with
| Some (Element (s, _, _, _)) -> P.MenhirInterpreter.number s
| None -> 0)
| _ -> assert false
let rec positions_in_stack env i =
match P.MenhirInterpreter.get i env with
| Some (Element (_, _, pos1, pos2)) ->
if false then Format.eprintf "%d--%d@." pos1.pos_cnum pos2.pos_cnum;
positions_in_stack env (i + 1)
| None -> ()
let get text checkpoint i =
match checkpoint with
| P.MenhirInterpreter.HandlingError env -> (
match P.MenhirInterpreter.get i env with
| Some (Element (_, _, pos1, pos2)) -> show text (pos1, pos2)
| None -> "???")
| _ -> assert false
let build_syntax_error text buffer checkpoint =
let env =
match checkpoint with
| P.MenhirInterpreter.HandlingError env -> env
| _ -> assert false
in
positions_in_stack env 0;
let location = E.last buffer in
let s = state checkpoint in
let message =
try Parser_messages.message s
with Not_found -> Printf.sprintf "Syntax error (%d)\n" s
in
let message =
if message = "<YOUR SYNTAX ERROR MESSAGE HERE>\n" then
Printf.sprintf "Syntax error (%d)\n" s
else message
in
let message = E.expand (get text checkpoint) message in
let lines = String.split_on_char '\n' message in
let related = ref [] in
let main_message = ref [] in
List.iter
(fun line ->
let len = String.length line in
if len > 2 && line.[0] = '<' then
try
let i = String.index line '>' in
let depth = int_of_string (String.sub line 1 (i - 1)) in
let msg = String.trim (String.sub line (i + 1) (len - i - 1)) in
match P.MenhirInterpreter.get (depth - 1) env with
| Some (Element (_, _, pos1, _pos2)) ->
let cnum = pos1.Lexing.pos_cnum in
let is_delim c = c = '(' || c = '[' || c = '{' in
let blank c = c = ' ' || c = '\t' in
let dcnum =
if cnum < String.length text && is_delim text.[cnum] then
cnum
else
let rec back i =
if i < 0 || not (blank text.[i]) then
if i >= 0 && is_delim text.[i] then i else cnum
else back (i - 1)
in
back (cnum - 1)
in
let start = { pos1 with Lexing.pos_cnum = dcnum } in
let loc =
{
Wax_utils.Ast.loc_start = start;
loc_end = { start with Lexing.pos_cnum = dcnum + 1 };
}
in
related :=
{
Wax_utils.Diagnostic.location = loc;
message = Wax_utils.Message.text msg;
}
:: !related
| None -> main_message := line :: !main_message
with _ -> main_message := line :: !main_message
else main_message := line :: !main_message)
lines;
let main_message = List.rev !main_message in
let related_labels = List.rev !related in
let main_message =
match List.rev main_message with
| "" :: rest when related_labels <> [] -> List.rev rest
| _ -> main_message
in
let message = String.concat "\n" main_message in
(location, message, related_labels)
let fail_detailed text buffer checkpoint =
let (loc_start, loc_end), message, related =
build_syntax_error text buffer checkpoint
in
raise
(Detailed_error
{
location = { Wax_utils.Ast.loc_start; loc_end };
message = Wax_utils.Message.text message;
related;
})
let parse_diagnostics ~filename text =
let lexbuf = initialize_lexing filename text in
let supplier =
lexer_lexbuf_to_supplier (Lexer.token Context.context) lexbuf
in
let buffer, supplier = E.wrap_supplier supplier in
let checkpoint =
P.Incremental.parse (snd (Sedlexing.lexing_bytes_positions lexbuf))
in
try
Ok
(P.MenhirInterpreter.loop_handle succeed
(fail_detailed text buffer)
supplier checkpoint)
with
| Detailed_error e -> Error e
| Syntax_error ((loc_start, loc_end), msg) ->
Error
{
location = { Wax_utils.Ast.loc_start; loc_end };
message = msg;
related = [];
}
| Sedlexing.InvalidCodepoint _ | Sedlexing.MalFormed ->
let loc_start, loc_end = Sedlexing.lexing_bytes_positions lexbuf in
Error
{
location = { Wax_utils.Ast.loc_start; loc_end };
message =
Wax_utils.Message.text
"Input file contains malformed UTF-8 byte sequences";
related = [];
}
let parse_recover ~filename ~sync ?(insert = []) ?(closers = []) ?barrier
text =
let module MI = P.MenhirInterpreter in
let lexbuf = initialize_lexing filename text in
let errors = ref [] in
let last_insert = ref (-1) in
let exception Lexing_gave_up in
let record_error location message =
errors := { location; message; related = [] } :: !errors
in
let base_supplier =
lexer_lexbuf_to_supplier (Lexer.token Context.context) lexbuf
in
let cnum () =
(Sedlexing.lexing_bytes_position_curr lexbuf).Lexing.pos_cnum
in
let rec recovering_supplier () =
let before = cnum () in
let resume () =
if cnum () > before then recovering_supplier ()
else raise Lexing_gave_up
in
try base_supplier () with
| Syntax_error ((loc_start, loc_end), message) ->
record_error { Wax_utils.Ast.loc_start; loc_end } message;
resume ()
| Sedlexing.InvalidCodepoint _ | Sedlexing.MalFormed ->
let loc_start, loc_end = Sedlexing.lexing_bytes_positions lexbuf in
record_error
{ Wax_utils.Ast.loc_start; loc_end }
(Wax_utils.Message.text
"Input file contains malformed UTF-8 byte sequences");
resume ()
in
let buffer, supplier = E.wrap_supplier recovering_supplier in
let paren_depth = ref 0 in
let supplier () =
let ((t, _, _) as tok) = supplier () in
(match sync t with
| Open -> incr paren_depth
| Close -> decr paren_depth
| Boundary | Leader | Terminal | Skip -> ());
tok
in
let record checkpoint =
let (loc_start, loc_end), message, related =
build_syntax_error text buffer checkpoint
in
errors :=
{
location = { Wax_utils.Ast.loc_start; loc_end };
message = Wax_utils.Message.text message;
related;
}
:: !errors
in
let only_blank_between lo hi =
let ok = ref (lo <= hi) in
for i = lo to hi - 1 do
match text.[i] with
| ' ' | '\t' | '\n' | '\r' -> ()
| _ -> ok := false
done;
!ok
in
let record_missing message (pos : Lexing.position) =
let already_flagged =
match !errors with
| { location; _ } :: _ ->
only_blank_between location.Wax_utils.Ast.loc_end.Lexing.pos_cnum
pos.pos_cnum
| [] -> false
in
if not already_flagged then
errors :=
{
location = { Wax_utils.Ast.loc_start = pos; loc_end = pos };
message;
related = [];
}
:: !errors
in
let rec find_sync depth tok0 =
let step ((t, tsp, _) as tok) =
match sync t with
| Skip -> find_sync depth None
| Open -> (
match barrier with
| None -> find_sync (depth + 1) None
| Some (_, is_leader, is_fused) ->
if is_fused t then
if depth = 0 then `Barrier ([ t ], tsp)
else find_sync (depth + 1) None
else
let ((t2, sp2, _) as tok2) = supplier () in
if depth = 0 && is_leader t2 then `Barrier ([ t; t2 ], sp2)
else find_sync (depth + 1) (Some tok2))
| Close -> if depth > 0 then find_sync (depth - 1) None else `Sync tok
| Boundary -> if depth > 0 then find_sync depth None else `Sync tok
| Leader | Terminal -> `Sync tok
in
match tok0 with Some tok -> step tok | None -> step (supplier ())
in
let rec pop_to env tok (startp : Lexing.position) =
if MI.acceptable (MI.input_needed env) tok startp then Some env
else
match MI.pop env with
| Some env' -> pop_to env' tok startp
| None -> None
in
let unwind env ((tok, startp, _endp) as sync_tok) =
match pop_to env tok startp with
| Some env' -> Some (MI.offer (MI.input_needed env') sync_tok)
| None -> None
in
let rec settle checkpoint =
match checkpoint with
| MI.Shifting _ | MI.AboutToReduce _ -> settle (MI.resume checkpoint)
| _ -> checkpoint
in
let try_insert env last =
match last with
| Some ((_, startp, _) as held)
when insert <> [] && !last_insert <> startp.Lexing.pos_cnum ->
last_insert := startp.Lexing.pos_cnum;
let cp = MI.input_needed env in
let attempt (tok, message) =
if not (MI.acceptable cp tok startp) then None
else
match settle (MI.offer cp (tok, startp, startp)) with
| MI.InputNeeded _ as after_insert -> (
match settle (MI.offer after_insert held) with
| (MI.InputNeeded _ | MI.Accepted _) as after_held ->
record_missing message startp;
Some after_held
| _ -> None)
| _ -> None
in
List.find_map attempt insert
| _ -> None
in
let insert_to_goal ~goal ~with_insert pos checkpoint =
let rec loop checkpoint prev_insert fuel =
if fuel <= 0 then None
else
match goal checkpoint with
| Some _ as r -> r
| None -> (
match
List.find_opt
(fun c -> MI.acceptable checkpoint c pos)
closers
with
| Some c ->
loop
(settle (MI.offer checkpoint (c, pos, pos)))
false (fuel - 1)
| None -> (
if (not with_insert) || prev_insert then None
else
match
List.find_opt
(fun (tok, _) -> MI.acceptable checkpoint tok pos)
insert
with
| Some (tok, _) ->
loop
(settle (MI.offer checkpoint (tok, pos, pos)))
true (fuel - 1)
| None -> None))
in
loop checkpoint false 1000
in
let close_pending env last =
match (last, closers) with
| Some ((t, pos, _) as target), _ :: _
when match sync t with
| Close | Boundary | Terminal -> true
| Open | Leader | Skip -> false ->
insert_to_goal ~with_insert:true pos (MI.input_needed env)
~goal:(fun cp ->
if MI.acceptable cp t pos then
Some (settle (MI.offer cp target))
else None)
| _ -> None
in
let place_field env toks pos =
let offer_all checkpoint =
let rec go cp = function
| [] -> (
match cp with
| MI.InputNeeded _ | MI.Accepted _ -> Some cp
| _ -> None)
| tok :: rest -> (
match cp with
| MI.InputNeeded _ when MI.acceptable cp tok pos ->
go (settle (MI.offer cp (tok, pos, pos))) rest
| _ -> None)
in
go checkpoint toks
in
insert_to_goal ~goal:offer_all ~with_insert:false pos
(MI.input_needed env)
in
let try_barrier env prev last =
match (barrier, prev, last) with
| Some (lparen, is_leader, _), Some (pt, _, _), Some (t, pos, _)
when is_leader t && pt = lparen -> (
match MI.pop env with
| Some env' -> place_field env' [ lparen; t ] pos
| None -> None)
| _ -> None
in
let rec run checkpoint prev last =
match checkpoint with
| MI.InputNeeded _ ->
let tok = supplier () in
run (MI.offer checkpoint tok) last (Some tok)
| MI.Shifting _ | MI.AboutToReduce _ ->
run (MI.resume checkpoint) prev last
| MI.HandlingError env -> recover checkpoint env prev last
| MI.Accepted v -> Some v
| MI.Rejected -> None
and recover checkpoint env prev last =
match try_insert env last with
| Some checkpoint -> run checkpoint None None
| None -> (
record checkpoint;
match close_pending env last with
| Some checkpoint -> run checkpoint None None
| None -> (
match try_barrier env prev last with
| Some checkpoint -> run checkpoint None None
| None -> skip env last))
and skip env last =
match find_sync 0 last with
| `Barrier (toks, pos) -> place_barrier env toks pos
| `Sync ((tok, startp, _) as sync_tok) ->
let enclosing_depth =
!paren_depth
- match sync tok with Open -> 1 | Close -> -1 | _ -> 0
in
if
barrier <> None
&& (match sync tok with Close -> true | _ -> false)
&& enclosing_depth > 0
&& not (MI.acceptable (MI.input_needed env) tok startp)
then group_drop env tok startp sync_tok
else offer_sync env sync_tok
and group_drop env tok startp sync_tok =
match pop_to env tok startp with
| None -> offer_sync env sync_tok
| Some env' -> (
match find_sync 0 None with
| `Barrier (toks, pos) -> place_barrier env' toks pos
| `Sync sync_tok -> offer_sync env' sync_tok)
and place_barrier env toks pos =
match place_field env toks pos with
| Some checkpoint -> run checkpoint None None
| None -> skip env None
and offer_sync env ((tok, _, _) as sync_tok) =
match unwind env sync_tok with
| Some checkpoint -> run checkpoint None None
| None -> (
match sync tok with
| Terminal -> None
| _ -> skip env None)
in
let start = snd (Sedlexing.lexing_bytes_positions lexbuf) in
let ast =
try run (P.Incremental.parse start) None None with
| Lexing_gave_up -> None
| Syntax_error ((loc_start, loc_end), message) ->
record_error { Wax_utils.Ast.loc_start; loc_end } message;
None
| Sedlexing.InvalidCodepoint _ | Sedlexing.MalFormed ->
let loc_start, loc_end = Sedlexing.lexing_bytes_positions lexbuf in
record_error
{ Wax_utils.Ast.loc_start; loc_end }
(Wax_utils.Message.text
"Input file contains malformed UTF-8 byte sequences");
None
in
(ast, List.rev !errors)
let parse_from_string ?color ~filename text =
match parse_diagnostics ~filename text with
| Ok ast -> ast
| Error { location = { loc_start; loc_end }; message; related } ->
report_syntax_error ~related ~color text (loc_start, loc_end) message
end
let parse_from_string ?color ~filename text =
Wax_utils.Debug.timed "parse" @@ fun () ->
let ctx = Wax_utils.Trivia.make () in
let module Context = struct
type t = Wax_utils.Trivia.context
let context = ctx
end in
let module I = Inner (Context) in
(I.parse_from_string ?color ~filename text, ctx)
let parse ?color ~filename () =
parse_from_string ?color ~filename (read filename)
let parse_diagnostics ~filename text =
Wax_utils.Debug.timed "parse" @@ fun () ->
let ctx = Wax_utils.Trivia.make () in
let module Context = struct
type t = Wax_utils.Trivia.context
let context = ctx
end in
let module I = Inner (Context) in
match I.parse_diagnostics ~filename text with
| Ok ast -> Ok (ast, ctx)
| Error e -> Error e
let parse_recover ~filename ~sync ?insert ?closers ?barrier text =
Wax_utils.Debug.timed "parse" @@ fun () ->
let ctx = Wax_utils.Trivia.make () in
let module Context = struct
type t = Wax_utils.Trivia.context
let context = ctx
end in
let module I = Inner (Context) in
let ast, errors =
I.parse_recover ~filename ~sync ?insert ?closers ?barrier text
in
(ast, errors, ctx)
end
module Make_parser (Output : sig
type t
end) (Tokens : sig
type token
end) (Parser : sig
module Make (_ : sig
type t = Wax_utils.Trivia.context
val context : t
end) : sig
type token = Tokens.token
module MenhirInterpreter :
MenhirLib.IncrementalEngine.INCREMENTAL_ENGINE with type token = token
module Incremental : sig
val parse : Lexing.position -> Output.t MenhirInterpreter.checkpoint
end
end
end) (Fast_parser : sig
module Make (_ : sig
type t = Wax_utils.Trivia.context
val context : t
end) : sig
type token = Tokens.token
exception Error
val parse : (Lexing.lexbuf -> token) -> Lexing.lexbuf -> Output.t
end
end) (Parser_messages : sig
val message : int -> string
end) (Lexer : sig
val token :
Wax_utils.Trivia.context ->
(Sedlexing.lexbuf -> Tokens.token) * Lexing.position option ref
end) =
struct
module Core = Make (Output) (Tokens) (Parser) (Parser_messages) (Lexer)
include Core
let parse_from_string ?color ~filename text =
Wax_utils.Debug.timed "parse" @@ fun () ->
let ctx = Wax_utils.Trivia.make () in
let module Context = struct
type t = Wax_utils.Trivia.context
let context = ctx
end in
let module F = Fast_parser.Make (Context) in
let lexbuf = initialize_lexing filename text in
try
let supplier =
lexer_lexbuf_to_supplier (Lexer.token Context.context) lexbuf
in
let revised_parser =
MenhirLib.Convert.Simplified.traditional2revised F.parse
in
(revised_parser supplier, ctx)
with
| F.Error | Syntax_error _ | Sedlexing.InvalidCodepoint _
| Sedlexing.MalFormed
->
Core.parse_from_string ?color ~filename text
let parse ?color ~filename () =
parse_from_string ?color ~filename (read filename)
end