Source file parse.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
open Elpi_util
open Elpi_lexer_config
exception ParseError = Parser_config.ParseError
module type Parser = sig
val goal : loc:Util.Loc.t -> text:string -> Ast.Goal.t
val goal_from : loc:Util.Loc.t -> Lexing.lexbuf -> Ast.Goal.t
val query : loc:Util.Loc.t -> text:string -> (Ast.Goal.t, Util.error) result * Util.warning list
val query_from : loc:Util.Loc.t -> Lexing.lexbuf -> (Ast.Goal.t, Util.error) result * Util.warning list
val program_from : ?max_errors:int -> loc:Util.Loc.t -> digest:Digest.t -> Lexing.lexbuf ->
Ast.Program.t * Util.error list * Util.warning list
val program : ?max_errors:int -> string -> Ast.Program.t * Util.error list * Util.warning list
end
module type Parser_w_Internals = sig
include Parser
module Internal : sig
val infix_SYMB : (Lexing.lexbuf -> Tokens.token) -> Lexing.lexbuf -> Ast.Func.t
val prefix_SYMB : (Lexing.lexbuf -> Tokens.token) -> Lexing.lexbuf -> Ast.Func.t
val postfix_SYMB : (Lexing.lexbuf -> Tokens.token) -> Lexing.lexbuf -> Ast.Func.t
end
end
module type Config = sig
val versions : (int * int * int) Util.StrMap.t
val resolver : ?cwd:string -> unit:string -> unit -> string
val reader : string -> string
val package_dir : pkg:string -> string
val plugin : pkg:string -> string option
val root_of_dir : dir:string -> string
end
type reference =
| Path of string
| Package_file of string * string
| Current_package_file of string
| Plugin of string
let chop_appended s =
let chop ext s = if Filename.check_suffix s ext then Filename.chop_suffix s ext else s in
List.fold_left (fun s ext -> chop ext s) s [".elpi"; ".mod"; ".sig"]
let reference_of_string s =
let n = String.length s in
if n > 1 && s.[0] = '+' then
let rest = String.sub s 1 (n - 1) in
let sep =
let slash = String.index_opt rest '/' in
if not Sys.win32 then slash else
match slash, String.index_opt rest '\\' with
| Some i, Some j -> Some (min i j)
| None, x | x, None -> x in
match sep with
| Some 0 -> Current_package_file (String.sub rest 1 (String.length rest - 1))
| Some i -> Package_file (String.sub rest 0 i, String.sub rest (i + 1) (String.length rest - i - 1))
| None -> Plugin (chop_appended rest)
else Path s
let cleanup_fname filename =
let marker = "/_build/" in
let n = String.length filename and m = String.length marker in
let rec find i = if i + m > n then None else if String.equal (String.sub filename i m) marker then Some i else find (i + 1) in
match find 0 with
| None -> filename
| Some i ->
let j = match String.index_from_opt filename (i + m) '/' with Some j -> j | None -> n in
if String.equal (String.sub filename (i + m) (j - i - m)) "install" then filename
else String.sub filename 0 i ^ String.sub filename j (n - j)
module Make(C : Config) = struct
let parse_ref : (?cwd:string -> string -> Ast.Program.t) ref =
ref (fun ?cwd:_ _ -> assert false)
let resolve_ref : (?cwd:string -> string -> string) ref =
ref (fun ?cwd:_ _ -> assert false)
exception Cannot_resolve_accumulated_file of string
module Warnings : sig
val init : unit -> unit
val add : Util.warning -> unit
val consume : unit -> Util.warning list
end = struct
let warnings : Util.warning list ref = ref []
let init () = warnings := []
let add w = warnings := w :: !warnings
let consume () = let ws = List.rev !warnings in warnings := []; ws
end
module Errors : sig
val init : max_errors:int -> unit
val max_errors_reached : unit -> bool
val add : Util.Loc.t * string -> unit
val consume : unit -> (Util.Loc.t * string) list
end = struct
let max_errors = ref 0
let count = ref 0
let errors : (Util.Loc.t * string) list ref = ref []
let init ~max_errors:n = max_errors := n; count := 0; errors := []
let max_errors_reached () = !count >= !max_errors
let add e = incr count; errors := e :: !errors
let consume () = let es = List.rev !errors in errors := []; es
end
module ParseFile = struct
let parse_accumulated_file ~loc ?cwd file =
let empty file_name = { Ast.file_name; digest = Digest.string ("not parsed " ^ file_name); deps = []; ast = [] } in
match !parse_ref ?cwd file with
| p -> p
| exception Cannot_resolve_accumulated_file msg when not (Errors.max_errors_reached ()) ->
Errors.add (loc, msg);
empty (match cwd with Some d when Filename.is_relative file -> Util.filename_concat d file | _ -> file)
| exception Parser_config.ParseError (l, msg) when not (Errors.max_errors_reached ()) ->
Errors.add (l, msg);
empty (try !resolve_ref ?cwd file with Failure _ | Cannot_resolve_accumulated_file _ -> file)
let client_payload : Obj.t option ref = ref None
let set_current_clent_loc_pyload x = client_payload := Some x
let get_current_client_loc_payload () = !client_payload
let warn = Warnings.add
let = DocComments.add
let doc_before = DocComments.before
let doc_after_dot = DocComments.after
end
module Grammar = Grammar.Make(ParseFile)
let message_of_state s = try Error_messages.message s with Not_found -> "syntax error"
let raise_parse_error lexbuf stateid =
let message = message_of_state stateid in
let loc = lexbuf.Lexing.lex_curr_p in
let loc = {
Util.Loc.client_payload = None;
source_name = loc.Lexing.pos_fname;
line = loc.Lexing.pos_lnum;
line_starts_at = loc.Lexing.pos_bol;
source_start = loc.Lexing.pos_cnum;
source_stop = loc.Lexing.pos_cnum;
} in
raise (Parser_config.ParseError(loc,message))
let lexer_config =
Lexer.config ~comment:ParseFile.add_comment ~trailing_comment:DocComments.add_trailing C.versions
let token lexbuf =
let t = Lexer.token lexer_config lexbuf in
DocComments.token_read ~fullstop:(match t with Tokens.FULLSTOP -> true | _ -> false) lexbuf.Lexing.lex_curr_p;
t
let parse ?(lexer=token) grammar lexbuf =
let buffer, lexer = MenhirLib.ErrorReports.wrap lexer in
try
Grammar.MenhirInterpreter.loop_handle
(fun x -> x)
(function (HandlingError e) -> raise_parse_error lexbuf Grammar.MenhirInterpreter.(current_state_number e) | _ -> assert false)
(Grammar.MenhirInterpreter.lexer_lexbuf_to_supplier lexer lexbuf)
(grammar lexbuf.lex_curr_p)
with
| Ast.Term.NotInProlog(loc,message) ->
raise (Parser_config.ParseError(loc,message^"\n"))
| Lexer.Error(loc,message) ->
let loc = {
Util.Loc.client_payload = None;
source_name = loc.Lexing.pos_fname;
line = loc.Lexing.pos_lnum;
line_starts_at = loc.Lexing.pos_bol;
source_start = loc.Lexing.pos_cnum;
source_stop = loc.Lexing.pos_cnum;
} in
raise (Parser_config.ParseError(loc,message))
| Lexer.Unexpected_character p ->
let loc = {
Util.Loc.client_payload = None;
source_name = p.Lexing.pos_fname;
line = p.Lexing.pos_lnum;
line_starts_at = p.Lexing.pos_bol;
source_start = p.Lexing.pos_cnum;
source_stop = p.Lexing.pos_cnum + 1;
} in
raise (Parser_config.ParseError(loc,"unexpected character"))
let already_parsed = Hashtbl.create 11
let read_sig f = try Some (C.reader f) with Failure _ -> None
let parse_file_contents ~filename text =
let digest = Digest.string text in
let key = Filename.dirname filename ^ "\000" ^ digest in
if Hashtbl.mem already_parsed key then
Hashtbl.find already_parsed key
else
let lexbuf = Lexing.from_string text in
let dest = cleanup_fname filename in
lexbuf.Lexing.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = dest };
let ast = parse Grammar.Incremental.program lexbuf in
let accumulated = List.concat_map (function
| Ast.Program.Accumulated (_, l) -> List.map (fun (p : Ast.Program.t) -> p.digest) l
| _ -> []) ast in
let digest = match accumulated with
| [] -> digest
| l -> Digest.string (String.concat "" (digest :: l)) in
let output = { Ast.file_name = filename; deps = []; digest; ast } in
Hashtbl.add already_parsed key output;
output
let parse_file ?cwd filename =
let filename =
try C.resolver ?cwd ~unit:filename ()
with Failure msg -> raise (Cannot_resolve_accumulated_file msg) in
let text = C.reader filename in
if String.equal (Filename.extension filename) ".mod" then
let sig_filename = Filename.chop_extension filename ^ ".sig" in
match read_sig sig_filename with
| Some sig_text ->
let s = parse_file_contents ~filename:sig_filename sig_text in
let m = parse_file_contents ~filename text in
{ Ast.file_name = filename; digest = Digest.string (s.digest ^ m.digest); deps = []; ast = s.ast @ m.ast }
| None -> parse_file_contents ~filename text
else parse_file_contents ~filename text
type located = Contents of string * string | File of string option * string
let locate ?cwd filename =
let host f =
try f () with Util.ElpiError { Util.loc; message; _ } ->
raise (Cannot_resolve_accumulated_file
(match loc with None -> message | Some l -> Printf.sprintf "%s: %s" (Util.Loc.show l) message)) in
let no_file () =
raise (Cannot_resolve_accumulated_file (Printf.sprintf "accumulate %S: no file after the package" (chop_appended filename))) in
match reference_of_string filename with
| Package_file (_, path) | Current_package_file path when String.equal (chop_appended path) "" -> no_file ()
| Plugin pkg when String.equal pkg "" ->
raise (Cannot_resolve_accumulated_file "accumulate \"+\": no package after +")
| Path f -> File (cwd, f)
| Package_file (pkg, path) -> File (None, Util.filename_concat (host (fun () -> C.package_dir ~pkg)) path)
| Current_package_file path ->
let dir = match cwd with Some d -> d | None -> Sys.getcwd () in
File (None, Util.filename_concat (host (fun () -> C.root_of_dir ~dir)) path)
| Plugin pkg ->
match host (fun () -> C.plugin ~pkg) with
| Some text -> Contents ("+" ^ pkg, text)
| None -> File (None, Util.filename_concat (host (fun () -> C.package_dir ~pkg)) (pkg ^ ".builtins.elpi"))
let () =
parse_ref := (fun ?cwd filename ->
match locate ?cwd filename with
| Contents (filename, text) -> parse_file_contents ~filename text
| File (cwd, f) -> parse_file ?cwd f);
resolve_ref := (fun ?cwd filename ->
match locate ?cwd filename with
| Contents (filename, _) -> filename
| File (cwd, f) -> C.resolver ?cwd ~unit:f ())
let to_lexing_loc { Util.Loc.source_name; line; line_starts_at; source_start; _ } =
{ Lexing.pos_fname = source_name;
pos_lnum = line;
pos_bol = line_starts_at;
pos_cnum = source_start; }
let lexing_set_position lexbuf loc =
Option.iter ParseFile.set_current_clent_loc_pyload loc.Util.Loc.client_payload;
let loc = to_lexing_loc loc in
let open Lexing in
lexbuf.lex_abs_pos <- loc.pos_cnum;
lexbuf.lex_start_p <- loc;
lexbuf.lex_curr_p <- loc
let to_loc lexbuf =
let p = lexbuf.Lexing.lex_start_p in
{ Util.Loc.client_payload = None; source_name = p.pos_fname; line = p.pos_lnum;
line_starts_at = p.pos_bol; source_start = p.pos_cnum; source_stop = lexbuf.Lexing.lex_curr_p.pos_cnum }
let goal_from ~loc lexbuf =
lexing_set_position lexbuf loc;
parse Grammar.Incremental.goal lexbuf
let goal ~loc ~text =
let lexbuf = Lexing.from_string text in
goal_from ~loc lexbuf
let at_eof lexbuf = lexbuf.Lexing.lex_curr_pos >= lexbuf.Lexing.lex_buffer_len
let skip_char lexbuf =
let open Lexing in
lexbuf.lex_curr_pos <- lexbuf.lex_curr_pos + 1;
lexbuf.lex_start_pos <- lexbuf.lex_curr_pos;
lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_cnum = lexbuf.lex_curr_p.pos_cnum + 1 };
lexbuf.lex_start_p <- lexbuf.lex_curr_p
let make_error (loc, message) = { Util.component = "Parser"; loc = Some loc; message }
let query_from ~loc lexbuf =
Warnings.init ();
let q =
match goal_from ~loc lexbuf with
| g -> Ok g
| exception Parser_config.ParseError (loc, message) -> Error (make_error (loc, message)) in
q, Warnings.consume ()
let query ~loc ~text = query_from ~loc (Lexing.from_string text)
let program_from ?(max_errors = max_int) ~loc:start_loc ~digest lexbuf =
DocComments.with_comments @@ fun () ->
Hashtbl.clear already_parsed;
Warnings.init ();
let token = token in
lexing_set_position lexbuf start_loc;
let last_token_lexed = ref None in
let first_token_lexed_loc = ref None in
let lexer lexbuf =
let t = token lexbuf in
last_token_lexed := Some t;
if Option.is_none !first_token_lexed_loc then
first_token_lexed_loc := Some lexbuf.Lexing.lex_start_p;
t in
let rec skip () =
match !last_token_lexed with
| Some (Tokens.FULLSTOP | Tokens.EOF) -> ()
| _ ->
let pos = lexbuf.Lexing.lex_curr_pos in
match lexer lexbuf with
| _ -> skip ()
| exception (Lexer.Error _ | Lexer.Unexpected_character _) ->
if lexbuf.Lexing.lex_curr_pos > pos then skip ()
else if at_eof lexbuf then last_token_lexed := Some Tokens.EOF
else (skip_char lexbuf; skip ()) in
let declaration_loc () =
let loc = to_loc lexbuf in
match !first_token_lexed_loc with
| Some p -> { loc with Util.Loc.source_start = p.pos_cnum; line = p.pos_lnum; line_starts_at = p.pos_bol }
| None -> loc in
let stop declarations =
Errors.add (to_loc lexbuf, Printf.sprintf "too many errors (limit %d): the rest was not parsed, the result is incomplete" max_errors);
declarations in
let rec loop declarations =
last_token_lexed := None; first_token_lexed_loc := None;
let recover (loc, msg) =
if max_errors = 0 then raise (Parser_config.ParseError (loc, msg));
if Errors.max_errors_reached () then stop declarations
else begin
Errors.add (loc, msg);
skip ();
match !last_token_lexed with
| Some Tokens.EOF -> declarations
| _ -> loop declarations
end in
if max_errors > 0 && Errors.max_errors_reached () then stop declarations
else
match parse ~lexer Grammar.Incremental.one_decl lexbuf with
| Some d -> loop (d :: declarations)
| None -> declarations
| exception Parser_config.ParseError (loc, msg) when not (String.equal loc.Util.Loc.source_name start_loc.Util.Loc.source_name) ->
recover (declaration_loc (),
Printf.sprintf "in %s, line %d, column %d: %s" loc.source_name loc.line
(loc.source_start - loc.line_starts_at + 1) msg)
| exception Parser_config.ParseError (loc, msg) ->
recover ((if loc.Util.Loc.source_start = loc.source_stop
&& loc.source_stop = lexbuf.Lexing.lex_curr_p.pos_cnum
then to_loc lexbuf else loc), msg)
| exception Cannot_resolve_accumulated_file msg -> recover (declaration_loc (), msg) in
Errors.init ~max_errors;
let declarations = loop [] in
let errors = Errors.consume () in
let ast = List.rev declarations in
let filename = let open Util.Loc in
Printf.sprintf "%s:%d:%d" start_loc.source_name start_loc.source_stop lexbuf.Lexing.lex_curr_pos in
let ws = Warnings.consume () in
let accumulated = List.concat_map (function
| Ast.Program.Accumulated (_, l) -> List.map (fun (p : Ast.Program.t) -> p.digest) l
| _ -> []) ast in
let digest = match accumulated with
| [] -> digest
| l -> Digest.string (String.concat "" (digest :: l)) in
{ Ast.file_name = filename; deps = []; digest; ast },
List.map make_error errors,
ws
let program ?max_errors file =
Hashtbl.clear already_parsed;
let filename = C.resolver ~unit:file () in
let one f text =
let dest = cleanup_fname f in
let p, errors, warnings = program_from ?max_errors ~loc:(Util.Loc.initial dest) ~digest:(Digest.string text) (Lexing.from_string text) in
{ p with Ast.file_name = f }, errors, warnings in
if String.equal (Filename.extension filename) ".mod" then begin
let sig_filename = Filename.chop_extension filename ^ ".sig" in
match read_sig sig_filename with
| Some sig_text ->
let s, es, ws = one sig_filename sig_text in
let m, em, wm = one filename (C.reader filename) in
{ Ast.file_name = filename; digest = Digest.string (s.Ast.digest ^ m.Ast.digest); deps = []; ast = s.ast @ m.ast }, es @ em, ws @ wm
| None -> one filename (C.reader filename)
end else one filename (C.reader filename)
module Internal = struct
let infix_SYMB = Grammar.infix_SYMB
let prefix_SYMB = Grammar.prefix_SYMB
let postfix_SYMB = Grammar.postfix_SYMB
end
end