Debian Codegraph @

coqpp/coqpp_main.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open Lexing
12 open Coqpp_ast
13 open Format
14 open Coqpp_parser
15
16 let fatal msg =
17 let () = Format.eprintf "Error: %s@\n%!" msg in
18 exit 1
19
20 let mk_code s = { code = s; loc = None }
21
22 (** Annotating at the end of user code with the current line of the generated file.
23
24 To get the current line while generating the output we would need
25 to flush format and either intercept format's output
26 (Format.formatter_of_out_functions) or read the generated file as
27 we generate it. This is both inconvenient to write, and also the
28 flushing breaks the formatting.
29
30 Instead we generate the code with the following dummy annotation
31 and afterwards replace it with the real annotation.
32 *)
33 let exit_code_str = "# COQPP EXIT CODE"
34
35 let exit_code fmt () =
36 fprintf fmt "@<0>%s" ("\n"^exit_code_str^"\n")
37
38 let fix_exit_code ~filename str =
39 let lines = String.split_on_char '\n' str in
40 let lines = List.mapi (fun i l ->
41 if String.equal l exit_code_str then
42 asprintf "# %i \"%s\"" (i+2) filename
43 else l) lines in
44 String.concat "\n" lines
45
46 let print_code fmt c =
47 match c.loc with
48 | None -> fprintf fmt "%s" c.code
49 | Some loc ->
50 (* Print the line location as a source annotation *)
51 let loc = loc.loc_start in
52 let padding = String.make (loc.pos_cnum - loc.pos_bol + 1) ' ' in
53 let code_insert = asprintf "\n# %i \"%s\"\n%s%s" loc.pos_lnum loc.pos_fname padding c.code in
54 fprintf fmt "@[@<0>%s@]" code_insert;
55 exit_code fmt ()
56
57 module StringSet = Set.Make(String)
58
59 let string_split s =
60 let len = String.length s in
61 let rec split n =
62 try
63 let pos = String.index_from s n '.' in
64 let dir = String.sub s n (pos-n) in
65 dir :: split (succ pos)
66 with
67 | Not_found -> [String.sub s n (len-n)]
68 in
69 if len == 0 then [] else split 0
70
71 (* Used to generate unique ids *)
72 let file_name = ref ""
73
74 (* We used to output __plugin_name = "bla" then refer to __plugin_name in generated code
75 but this is not robust to eg
76
77 DECLARE PLUGIN "bla"
78 open G_ltac
79 use the plugin name
80
81 since g_ltac has no mli its __plugin_name will shadow the local one and wreak havoc
82 *)
83 let plugin_name = ref None
84
85 let force_is_plugin ~what () = match !plugin_name with
86 | Some (Some n) -> n
87 | Some None | None -> fatal ("DECLARE PLUGIN required before "^what)
88
89 let check_is_plugin ~what () = match !plugin_name with
90 | Some b -> b
91 | None -> fatal ("DECLARE PLUGIN required before "^what)
92
93 let pp_opt_plugin_arg ~what () =
94 match check_is_plugin ~what () with
95 | Some name -> "(Some \""^name^"\")"
96 | None -> "None"
97
98 let ignore_kw = ref false
99
100 let print_ignore_kw fmt () =
101 let s = if !ignore_kw then "true" else "false" in
102 Format.pp_print_string fmt s
103
104 let print_list fmt pr l =
105 let rec prl fmt = function
106 | [] -> ()
107 | [x] -> fprintf fmt "%a" pr x
108 | x :: l -> fprintf fmt "%a;@ %a" pr x prl l
109 in
110 fprintf fmt "@[<hv>[%a]@]" prl l
111
112 let rec print_binders fmt = function
113 | [] -> ()
114 | ExtTerminal _ :: rem -> print_binders fmt rem
115 | ExtNonTerminal (_, TokNone) :: rem ->
116 fprintf fmt "_@ %a" print_binders rem
117 | ExtNonTerminal (_, TokName id) :: rem ->
118 fprintf fmt "%s@ %a" id print_binders rem
119
120 let rec print_symbol fmt = function
121 | Ulist1 s ->
122 fprintf fmt "@[Extend.TUlist1 (%a)@]" print_symbol s
123 | Ulist1sep (s, sep) ->
124 fprintf fmt "@[Extend.TUlist1sep (%a, \"%s\")@]" print_symbol s sep
125 | Ulist0 s ->
126 fprintf fmt "@[Extend.TUlist0 (%a)@]" print_symbol s
127 | Ulist0sep (s, sep) ->
128 fprintf fmt "@[Extend.TUlist0sep (%a, \"%s\")@]" print_symbol s sep
129 | Uopt s ->
130 fprintf fmt "@[Extend.TUopt (%a)@]" print_symbol s
131 | Uentry e ->
132 fprintf fmt "@[Extend.TUentry (Genarg.get_arg_tag wit_%s)@]" e
133 | Uentryl (e, l) ->
134 assert (e = "tactic");
135 fprintf fmt "@[Extend.TUentryl (Genarg.get_arg_tag wit_%s, %i)@]" e l
136
137 let print_string fmt s = fprintf fmt "\"%s\"" s
138
139 let print_opt fmt pr = function
140 | None -> fprintf fmt "None"
141 | Some x -> fprintf fmt "Some@ @[(%a)@]" pr x
142
143 module GramExt :
144 sig
145
146 val print_extrule : Format.formatter -> (symb list * string option list * code) -> unit
147 val print_ast : Format.formatter -> grammar_ext -> unit
148
149 end =
150 struct
151
152 let is_uident s = match s.[0] with
153 | 'A'..'Z' -> true
154 | _ -> false
155
156 let is_qualified = is_uident
157
158 let get_local_entries ext =
159 let global = StringSet.of_list ext.gramext_globals in
160 let map e = e.gentry_name in
161 let entries = List.map map ext.gramext_entries in
162 let local = List.filter (fun e -> not (is_qualified e || StringSet.mem e global)) entries in
163 let rec uniquize seen = function
164 | [] -> []
165 | id :: rem ->
166 let rem = uniquize (StringSet.add id seen) rem in
167 if StringSet.mem id seen then rem else id :: rem
168 in
169 uniquize StringSet.empty local
170
171 let print_local fmt ext =
172 let locals = get_local_entries ext in
173 match locals with
174 | [] -> ()
175 | e :: locals ->
176 let mk_e fmt e = fprintf fmt "Procq.Entry.make \"%s\"" e in
177 let () = fprintf fmt "@[<hv 2>let %s =@ @[%a@]@]@ " e mk_e e in
178 let iter e = fprintf fmt "@[<hv 2>and %s =@ @[%a@]@]@ " e mk_e e in
179 let () = List.iter iter locals in
180 fprintf fmt "in@ "
181
182 let print_position fmt pos = match pos with
183 | First -> fprintf fmt "Gramlib.Gramext.First"
184 | Last -> fprintf fmt "Gramlib.Gramext.Last"
185 | Before s -> fprintf fmt "Gramlib.Gramext.Before@ \"%s\"" s
186 | After s -> fprintf fmt "Gramlib.Gramext.After@ \"%s\"" s
187
188 let print_assoc fmt = function
189 | LeftA -> fprintf fmt "Gramlib.Gramext.LeftA"
190 | RightA -> fprintf fmt "Gramlib.Gramext.RightA"
191 | NonA -> fprintf fmt "Gramlib.Gramext.NonA"
192 | BothA -> fprintf fmt "Gramlib.Gramext.BothA"
193
194 let is_token s = match string_split s with
195 | [s] -> is_uident s
196 | _ -> false
197
198 let rec parse_tokens ?(in_anon=false) =
199 let err_anon () =
200 if in_anon then
201 fatal (Printf.sprintf "'SELF' or 'NEXT' illegal in anonymous entry level") in
202 function
203 | [GSymbString s] -> SymbToken ("", Some s)
204 | [GSymbQualid ("QUOTATION", None); GSymbString s] ->
205 SymbToken ("QUOTATION", Some s)
206 | [GSymbQualid ("SELF", None)] -> err_anon (); SymbSelf
207 | [GSymbQualid ("NEXT", None)] -> err_anon (); SymbNext
208 | [GSymbQualid ("LIST0", None); tkn] ->
209 SymbList0 (parse_token ~in_anon tkn, None)
210 | [GSymbQualid ("LIST1", None); tkn] ->
211 SymbList1 (parse_token ~in_anon tkn, None)
212 | [GSymbQualid ("LIST0", None); tkn; GSymbQualid ("SEP", None); tkn'] ->
213 SymbList0 (parse_token ~in_anon tkn, Some (parse_token ~in_anon tkn'))
214 | [GSymbQualid ("LIST1", None); tkn; GSymbQualid ("SEP", None); tkn'] ->
215 SymbList1 (parse_token ~in_anon tkn, Some (parse_token ~in_anon tkn'))
216 | [GSymbQualid ("OPT", None); tkn] ->
217 SymbOpt (parse_token ~in_anon tkn)
218 | [GSymbQualid (e, None)] when is_token e -> SymbToken (e, None)
219 | [GSymbQualid (e, None); GSymbString s] when is_token e -> SymbToken (e, Some s)
220 | [GSymbQualid (e, lvl)] when not (is_token e) -> SymbEntry (e, lvl)
221 | [GSymbParen tkns] -> parse_tokens ~in_anon tkns
222 | [GSymbProd prds] ->
223 let map p =
224 let map (pat, tkns) = (pat, parse_tokens ~in_anon:true tkns) in
225 (List.map map p.gprod_symbs, p.gprod_body)
226 in
227 SymbRules (List.map map prds)
228 | t ->
229 let rec db_token = function
230 | GSymbString s -> Printf.sprintf "\"%s\"" s
231 | GSymbQualid (s, _) -> Printf.sprintf "%s" s
232 | GSymbParen s -> Printf.sprintf "(%s)" (db_tokens s)
233 | GSymbProd _ -> Printf.sprintf "[...]"
234 and db_tokens tkns =
235 let s = List.map db_token tkns in
236 String.concat " " s
237 in
238 fatal (Printf.sprintf "Invalid token: %s" (db_tokens t))
239
240 and parse_token ~in_anon tkn = parse_tokens ~in_anon [tkn]
241
242 let print_fun fmt (vars, body) =
243 let vars = List.rev vars in
244 let iter = function
245 | None -> fprintf fmt "_@ "
246 | Some id -> fprintf fmt "%s@ " id
247 in
248 let () = fprintf fmt "fun@ " in
249 let () = List.iter iter vars in
250 let () = fprintf fmt "loc ->@ @[%a@]" print_code body in
251 ()
252
253 (** Meta-program instead of calling Tok.of_pattern here because otherwise
254 violates value restriction *)
255 let print_tok fmt =
256 let print_pat fmt = print_opt fmt print_string in
257 function
258 | "", Some s -> fprintf fmt "Tok.PKEYWORD (%a)" print_string s
259 | "IDENT", s -> fprintf fmt "Tok.PIDENT (%a)" print_pat s
260 | "FIELD", s -> fprintf fmt "Tok.PFIELD (%a)" print_pat s
261 | "NUMBER", None -> fprintf fmt "Tok.PNUMBER None"
262 | "NUMBER", Some s -> fprintf fmt "Tok.PNUMBER (Some (Option.get (NumTok.Unsigned.parse_string %a)))" print_string s
263 | "STRING", s -> fprintf fmt "Tok.PSTRING (%a)" print_pat s
264 | "LEFTQMARK", None -> fprintf fmt "Tok.PLEFTQMARK"
265 | "BULLET", s -> fprintf fmt "Tok.PBULLET (%a)" print_pat s
266 | "QUOTATION", Some s -> fprintf fmt "Tok.PQUOTATION %a" print_string s
267 | "EOI", None -> fprintf fmt "Tok.PEOI"
268 | _ -> failwith "Tok.of_pattern: not a constructor"
269
270 let rec print_prod fmt p =
271 let (vars, tkns) = List.split p.gprod_symbs in
272 let tkn = List.map parse_tokens tkns in
273 print_extrule fmt (tkn, vars, p.gprod_body)
274
275 and print_extrule fmt (tkn, vars, body) =
276 let tkn = List.rev tkn in
277 fprintf fmt "@[Procq.Production.make@ @[(%a)@]@ @[(%a)@]@]" (print_symbols ~norec:false) tkn print_fun (vars, body)
278
279 and print_symbols ~norec fmt = function
280 | [] -> fprintf fmt "Procq.Rule.stop"
281 | tkn :: tkns ->
282 let c = if norec then "Procq.Rule.next_norec" else "Procq.Rule.next" in
283 fprintf fmt "@[%s@ (%a)@ (%a)@]" c (print_symbols ~norec) tkns print_symbol tkn
284
285 and print_symbol fmt tkn = match tkn with
286 | SymbToken (t, s) ->
287 fprintf fmt "(Procq.Symbol.token (%a))" print_tok (t, s)
288 | SymbEntry (e, None) ->
289 fprintf fmt "(Procq.Symbol.nterm %s)" e
290 | SymbEntry (e, Some l) ->
291 fprintf fmt "(Procq.Symbol.nterml %s (%a))" e print_string l
292 | SymbSelf ->
293 fprintf fmt "Procq.Symbol.self"
294 | SymbNext ->
295 fprintf fmt "Procq.Symbol.next"
296 | SymbList0 (s, None) ->
297 fprintf fmt "(Procq.Symbol.list0 %a)" print_symbol s
298 | SymbList0 (s, Some sep) ->
299 fprintf fmt "(Procq.Symbol.list0sep (%a) (%a))" print_symbol s print_anonymized_symbol sep
300 | SymbList1 (s, None) ->
301 fprintf fmt "(Procq.Symbol.list1 (%a))" print_symbol s
302 | SymbList1 (s, Some sep) ->
303 fprintf fmt "(Procq.Symbol.list1sep (%a) (%a))" print_symbol s print_anonymized_symbol sep
304 | SymbOpt s ->
305 fprintf fmt "(Procq.Symbol.opt %a)" print_symbol s
306 | SymbRules rules ->
307 let pr fmt (r, body) =
308 let (vars, tkn) = List.split r in
309 let tkn = List.rev tkn in
310 fprintf fmt "Procq.Rules.make @[(%a)@ (%a)@]" (print_symbols ~norec:true) tkn print_fun (vars, body)
311 in
312 let pr fmt rules = print_list fmt pr rules in
313 fprintf fmt "(Procq.Symbol.rules %a)" pr (List.rev rules)
314 | SymbQuote c ->
315 fprintf fmt "(%s)" c
316
317 and print_anonymized_symbol fmt tkn = match tkn with
318 | SymbToken (t, s) ->
319 fprintf fmt "(Procq.Symbol.tokens [Procq.TPattern (%a)])" print_tok (t, s)
320 | _ -> print_symbol fmt (SymbRules [[None, tkn], mk_code "()"])
321
322 let print_rule fmt r =
323 let pr_lvl fmt lvl = print_opt fmt print_string lvl in
324 let pr_asc fmt asc = print_opt fmt print_assoc asc in
325 let pr_prd fmt prd = print_list fmt print_prod prd in
326 fprintf fmt "@[(%a,@ %a,@ %a)@]" pr_lvl r.grule_label pr_asc r.grule_assoc pr_prd (List.rev r.grule_prods)
327
328 let gramext_count = ref 0
329
330 let gramext_plugin_uid name =
331 let cnt = !gramext_count in
332 incr gramext_count;
333 " ~plugin_uid:(\""^name^"\", \""^(!file_name)^":"^string_of_int cnt^"\")"
334
335 let grammar_extend fmt () =
336 match check_is_plugin ~what:"GRAMMAR EXTEND" () with
337 | Some name ->
338 Format.fprintf fmt "Egramml.grammar_extend%s ~ignore_kw:%a"
339 (gramext_plugin_uid name)
340 print_ignore_kw ()
341 | None ->
342 Format.fprintf fmt "Procq.grammar_extend ~ignore_kw:%a"
343 print_ignore_kw ()
344
345 let print_entry fmt e = match e.gentry_rules with
346 | GDataReuse (pos, r) ->
347 let rules = List.rev r in
348 let pr_pos fmt pos = print_opt fmt print_string pos in
349 let pr_prd fmt prd = print_list fmt print_prod prd in
350 fprintf fmt "let () =@ @[%a@ %s@ @[(Procq.Reuse (%a, %a))@]@]@ in@ "
351 grammar_extend ()
352 e.gentry_name pr_pos pos pr_prd rules
353 | GDataFresh (pos, rules) ->
354 let print_rules fmt rules = print_list fmt print_rule rules in
355 let pr_check fmt () = match pos with
356 | None -> fprintf fmt "let () =@ @[assert@ (Procq.Entry.is_empty@ %s)@]@ in@\n" e.gentry_name
357 | Some _ -> fprintf fmt ""
358 in
359 let pos = match pos with None -> First | Some pos -> pos in
360 fprintf fmt "%alet () =@ @[%a@ %s@ @[(Procq.Fresh@ (%a, %a))@]@]@ in@ "
361 pr_check ()
362 grammar_extend ()
363 e.gentry_name print_position pos print_rules rules
364
365 let print_ast fmt ext =
366 let () = fprintf fmt "@[<2>let _ =@ " in
367 let () = fprintf fmt "@[<v>%a@]" print_local ext in
368 let () = List.iter (fun e -> print_entry fmt e) ext.gramext_entries in
369 let () = fprintf fmt "()@]@\n" in
370 ()
371
372 end
373
374 module VernacExt :
375 sig
376
377 val print_ast : Format.formatter -> vernac_ext -> unit
378
379 end =
380 struct
381
382 let print_rule_classifier fmt r = match r.vernac_class with
383 | None -> fprintf fmt "None"
384 | Some f ->
385 let no_binder = function ExtTerminal _ -> true | ExtNonTerminal _ -> false in
386 if List.for_all no_binder r.vernac_toks then
387 fprintf fmt "Some @[(fun ~atts -> %a)@]" print_code f
388 else
389 fprintf fmt "Some @[(fun %a ~atts -> %a)@]" print_binders r.vernac_toks print_code f
390
391 (* let print_atts fmt = function *)
392 (* | None -> fprintf fmt "@[let () = Attributes.unsupported_attributes atts in@] " *)
393 (* | Some atts -> *)
394 (* let rec print_left fmt = function *)
395 (* | [] -> assert false *)
396 (* | [x,_] -> fprintf fmt "%s" x *)
397 (* | (x,_) :: rem -> fprintf fmt "(%s, %a)" x print_left rem *)
398 (* in *)
399 (* let rec print_right fmt = function *)
400 (* | [] -> assert false *)
401 (* | [_,y] -> fprintf fmt "%s" y *)
402 (* | (_,y) :: rem -> fprintf fmt "(%s ++ %a)" y print_right rem *)
403 (* in *)
404 (* let nota = match atts with [_] -> "" | _ -> "Attributes.Notations." in *)
405 (* fprintf fmt "@[let %a = Attributes.parse %s(%a) atts in@] " *)
406 (* print_left atts nota print_right atts *)
407
408 let print_atts_left fmt = function
409 | None -> fprintf fmt "()"
410 | Some atts ->
411 let rec aux fmt = function
412 | [] -> assert false
413 | [x,_] -> fprintf fmt "%s" x
414 | (x,_) :: rem -> fprintf fmt "(%s, %a)" x aux rem
415 in
416 aux fmt atts
417
418 let print_atts_right fmt = function
419 | None -> fprintf fmt "(Attributes.unsupported_attributes atts)"
420 | Some atts ->
421 let rec aux fmt = function
422 | [] -> assert false
423 | [_,y] -> print_code fmt y
424 | (_,y) :: rem -> fprintf fmt "(%a ++ %a)" print_code y aux rem
425 in
426 let nota = match atts with [_] -> "" | _ -> "Attributes.Notations." in
427 fprintf fmt "(Attributes.parse %s%a atts)" nota aux atts
428
429 let understand_state = function
430 | "close_proof" -> "vtcloseproof", ["lemma"; "pm"]
431 | "open_proof" -> "vtopenproof", []
432 | "proof" -> "vtmodifyproof", ["pstate"]
433 | "proof_opt_query" -> "vtreadproofopt", ["pstate"]
434 | "proof_query" -> "vtreadproof", ["pstate"]
435 | "read_program" -> "vtreadprogram", ["pm"]
436 | "program" -> "vtmodifyprogram", ["pm"]
437 | "declare_program" -> "vtdeclareprogram", ["pm"]
438 | "program_interactive" -> "vtopenproofprogram", ["pm"]
439 | "opaque_access" -> "vtopaqueaccess", ["opaque_access"]
440 | s -> fatal ("unsupported state specifier: " ^ s)
441
442 let rec pr_named_arguments fmt = function
443 | [] -> assert false
444 | [s] -> fprintf fmt "~%s" s
445 | s :: l -> fprintf fmt "~%s@ %a" s pr_named_arguments l
446
447 let pr_begin_wrapper fmt = function
448 | [] -> fprintf fmt "fun () ->"
449 | args -> fprintf fmt "fun %a ->" pr_named_arguments args
450
451 let pr_end_wrapper fmt = function
452 | [] -> fprintf fmt ""
453 | args -> fprintf fmt "@ %a" pr_named_arguments args
454
455 let print_body_state state fmt r =
456 let state = match r.vernac_state with Some _ as s -> s | None -> state in
457 match state with
458 | None -> fprintf fmt "Vernactypes.vtdefault (fun () -> %a)" print_code r.vernac_body
459 | Some "CUSTOM" -> print_code fmt r.vernac_body
460 | Some state ->
461 let state, wrap = understand_state state in
462 fprintf fmt "Vernactypes.%s (%a (%a)%a)" state pr_begin_wrapper wrap
463 print_code r.vernac_body pr_end_wrapper wrap
464
465 let print_body_fun state fmt r =
466 match r.vernac_synterp with
467 | None ->
468 fprintf fmt "let coqpp_body %a%a =@ @[%a@] in@ "
469 print_binders r.vernac_toks print_atts_left r.vernac_atts (print_body_state state) r
470 | Some (id,pe) ->
471 fprintf fmt "let coqpp_body %a%a =@ @[(let %s = %a in %a)@] in@ "
472 print_binders r.vernac_toks print_atts_left r.vernac_atts id print_code pe (print_body_state state) r
473
474 let print_body state fmt r =
475 fprintf fmt "@[<2>(%a@[<2>fun %a?loc ~atts () ->@]@ @[<2>coqpp_body@ %a%a@])@]"
476 (print_body_fun state) r print_binders r.vernac_toks
477 print_binders r.vernac_toks print_atts_right r.vernac_atts
478
479 let rec print_sig fmt = function
480 | [] -> fprintf fmt "@[Vernacextend.TyNil@]"
481 | ExtTerminal s :: rem ->
482 fprintf fmt "@[Vernacextend.TyTerminal@ @[<1>(\"%s\",@ %a)@]@]" s print_sig rem
483 | ExtNonTerminal (symb, _) :: rem ->
484 fprintf fmt "@[Vernacextend.TyNonTerminal (%a,@ %a)@]"
485 print_symbol symb print_sig rem
486
487 let print_rule state fmt r =
488 fprintf fmt "Vernacextend.TyML@ @[<v1>(%b,@ %a,@ %a,@ %a)@]"
489 r.vernac_depr print_sig r.vernac_toks (print_body state) r print_rule_classifier r
490
491 let print_rules state fmt rules =
492 print_list fmt (fun fmt r -> fprintf fmt "(%a)" (print_rule state) r) rules
493
494 let print_classifier fmt = function
495 (* error could be interesting but would need to check that not all of the rules have a classifier,
496 if we do that we could also check that at least 1 rule has no classifier
497 when the block level classifier is specified *)
498 | ClassifDefault -> fprintf fmt ""
499 | ClassifName "QUERY" ->
500 fprintf fmt "~classifier:(fun ~atts:_ _ -> Vernacextend.classify_as_query)"
501 | ClassifName "SIDEFF" ->
502 fprintf fmt "~classifier:(fun ~atts:_ _ -> Vernacextend.classify_as_sideeff)"
503 | ClassifName s -> fatal (Printf.sprintf "Unknown classifier %s" s)
504 | ClassifCode c -> fprintf fmt "~classifier:(fun ~atts -> %s)" c.code
505
506 let print_entry fmt = function
507 | None -> fprintf fmt "None"
508 | Some e -> fprintf fmt "(Some (%s))" e.code
509
510 let print_ast fmt ext =
511 let pr fmt () =
512 fprintf fmt "Vernacextend.static_vernac_extend ~plugin:%s ~command:\"%s\" %a ~ignore_kw:%a ?entry:%a %a"
513 (pp_opt_plugin_arg ~what:"VERNAC EXTEND" ())
514 ext.vernacext_name
515 print_classifier ext.vernacext_class
516 print_ignore_kw ()
517 print_entry ext.vernacext_entry (print_rules ext.vernacext_state) ext.vernacext_rules
518 in
519 let () = fprintf fmt "let () = @[%a@]@\n" pr () in
520 ()
521
522 end
523
524 module TacticExt :
525 sig
526
527 val print_ast : Format.formatter -> tactic_ext -> unit
528
529 end =
530 struct
531
532 let rec print_clause fmt = function
533 | [] -> fprintf fmt "@[Tacentries.TyNil@]"
534 | ExtTerminal s :: cl -> fprintf fmt "@[Tacentries.TyIdent (\"%s\", %a)@]" s print_clause cl
535 | ExtNonTerminal (g, _) :: cl ->
536 fprintf fmt "@[Tacentries.TyArg (%a, %a)@]"
537 print_symbol g print_clause cl
538
539 let print_rule fmt r =
540 fprintf fmt "@[Tacentries.TyML (%a, @[(fun %aist@ -> %a)@])@]"
541 print_clause r.tac_toks print_binders r.tac_toks print_code r.tac_body
542
543 let print_rules fmt rules =
544 print_list fmt (fun fmt r -> fprintf fmt "(%a)" print_rule r) rules
545
546 let print_ast fmt ext =
547 let deprecation fmt =
548 function
549 | None -> ()
550 | Some { code } -> fprintf fmt "~deprecation:(%s) " code
551 in
552 let pr fmt () =
553 let level = match ext.tacext_level with None -> 0 | Some i -> i in
554 let name = force_is_plugin ~what:"TACTIC EXTEND" () in
555 fprintf fmt "Tacentries.tactic_extend \"%s\" \"%s\" ~level:%i %a%a"
556 name ext.tacext_name level
557 deprecation ext.tacext_deprecated
558 print_rules ext.tacext_rules
559 in
560 let () = fprintf fmt "let () = @[%a@]\n" pr () in
561 ()
562
563 end
564
565 module VernacArgumentExt :
566 sig
567
568 val print_ast : Format.formatter -> vernac_argument_ext -> unit
569 val print_rules : Format.formatter -> string * tactic_rule list -> unit
570
571 end =
572 struct
573
574 let terminal s =
575 let p =
576 if s <> "" && s.[0] >= '0' && s.[0] <= '9' then "CLexer.terminal_number"
577 else "CLexer.terminal" in
578 let c = Printf.sprintf "Procq.Symbol.token (%s \"%s\")" p s in
579 SymbQuote c
580
581 let rec parse_symb self = function
582 | Ulist1 s -> SymbList1 (parse_symb self s, None)
583 | Ulist1sep (s, sep) -> SymbList1 (parse_symb self s, Some (terminal sep))
584 | Ulist0 s -> SymbList0 (parse_symb self s, None)
585 | Ulist0sep (s, sep) -> SymbList0 (parse_symb self s, Some (terminal sep))
586 | Uopt s -> SymbOpt (parse_symb self s)
587 | Uentry e -> if e = self then SymbSelf else SymbEntry (e, None)
588 | Uentryl (e, l) ->
589 assert (e = "tactic");
590 if l = 5 then SymbEntry ("Pltac.binder_tactic", None)
591 else SymbEntry ("Pltac.ltac_expr", Some (string_of_int l))
592
593 let parse_token self = function
594 | ExtTerminal s -> (terminal s, None)
595 | ExtNonTerminal (e, TokNone) -> (parse_symb self e, None)
596 | ExtNonTerminal (e, TokName s) -> (parse_symb self e, Some s)
597
598 let parse_rule self r =
599 let symbs = List.map (fun t -> parse_token self t) r.tac_toks in
600 let symbs, vars = List.split symbs in
601 (symbs, vars, r.tac_body)
602
603 let print_rules fmt (name, rules) =
604 (* Rules are reversed. *)
605 let rules = List.rev rules in
606 let rules = List.map (fun r -> parse_rule name r) rules in
607 let pr fmt l = print_list fmt (fun fmt r -> fprintf fmt "(%a)" GramExt.print_extrule r) l in
608 match rules with
609 | [([SymbEntry (e, None)], [Some s], { code = c } )] when String.trim c = s ->
610 (* This is a horrible hack to work around limitations of camlp5 regarding
611 factorization of parsing rules. It allows to recognize rules of the
612 form [ entry(x) ] -> [ x ] so as not to generate a proxy entry and
613 reuse the same entry directly. *)
614 fprintf fmt "@[Vernacextend.Arg_alias@ @[<2>(%s)@]@]" e
615 | _ -> fprintf fmt "@[Vernacextend.Arg_rules@ %a@]" pr rules
616
617 let print_printer fmt = function
618 | None -> fprintf fmt "@[fun _ -> Pp.str \"missing printer\"@]"
619 | Some f -> print_code fmt f
620
621 let print_ast fmt arg =
622 let name = arg.vernacargext_name in
623 let pr fmt () =
624 fprintf fmt "Vernacextend.vernac_argument_extend ~plugin:%s ~name:%a ~ignore_kw:%a@[<2>{@\n\
625 Vernacextend.arg_parsing =@ %a;@\n\
626 Vernacextend.arg_printer = fun env sigma ->@ %a;@\n}@]"
627 (pp_opt_plugin_arg ~what:"VERNAC ARGUMENT EXTEND" ())
628 print_string name print_ignore_kw () print_rules (name, arg.vernacargext_rules)
629 print_printer arg.vernacargext_printer
630 in
631 fprintf fmt "@[<2>let (wit_%s, %s) =@ @[%a@]@]@\nlet _ = (wit_%s, %s)@\n"
632 name name pr () name name
633
634 end
635
636 module ArgumentExt :
637 sig
638
639 val print_ast : Format.formatter -> argument_ext -> unit
640
641 end =
642 struct
643
644 let rec print_argtype fmt = function
645 | ExtraArgType s ->
646 fprintf fmt "Geninterp.val_tag (Genarg.topwit wit_%s)" s
647 | PairArgType (arg1, arg2) ->
648 fprintf fmt "Geninterp.Val.Pair (@[(%a)@], @[(%a)@])" print_argtype arg1 print_argtype arg2
649 | ListArgType arg ->
650 fprintf fmt "Geninterp.Val.List @[(%a)@]" print_argtype arg
651 | OptArgType arg ->
652 fprintf fmt "Geninterp.Val.Opt @[(%a)@]" print_argtype arg
653
654 let rec print_wit fmt = function
655 | ExtraArgType s ->
656 fprintf fmt "wit_%s" s
657 | PairArgType (arg1, arg2) ->
658 fprintf fmt "Genarg.PairArg (@[(%a)@], @[(%a)@])" print_wit arg1 print_wit arg2
659 | ListArgType arg ->
660 fprintf fmt "Genarg.ListArg @[(%a)@]" print_wit arg
661 | OptArgType arg ->
662 fprintf fmt "Genarg.OptArg @[(%a)@]" print_wit arg
663
664 let print_ast fmt arg =
665 let name = arg.argext_name in
666 let pr_tag fmt t = print_opt fmt print_argtype t in
667 let intern fmt () = match arg.argext_glob, arg.argext_type with
668 | Some f, (None | Some _) ->
669 fprintf fmt "@[Tacentries.ArgInternFun ((fun f ist v -> (ist, f ist v)) (%a))@]" print_code f
670 | None, Some t ->
671 fprintf fmt "@[Tacentries.ArgInternWit (%a)@]" print_wit t
672 | None, None ->
673 fprintf fmt "@[Tacentries.ArgInternFun (fun ist v -> (ist, v))@]"
674 in
675 let subst fmt () = match arg.argext_subst, arg.argext_type with
676 | Some f, (None | Some _) ->
677 fprintf fmt "@[Tacentries.ArgSubstFun (%a)@]" print_code f
678 | None, Some t ->
679 fprintf fmt "@[Tacentries.ArgSubstWit (%a)@]" print_wit t
680 | None, None ->
681 fprintf fmt "@[Tacentries.ArgSubstFun (fun s v -> v)@]"
682 in
683 let interp fmt () = match arg.argext_interp, arg.argext_type with
684 | Some (None, f), (None | Some _) ->
685 fprintf fmt "@[Tacentries.ArgInterpSimple (%a)@]" print_code f
686 | Some (Some kind, f), (None | Some _) ->
687 fatal (Printf.sprintf "Unknown kind %s of interpretation function" kind)
688 | None, Some t ->
689 fprintf fmt "@[Tacentries.ArgInterpWit (%a)@]" print_wit t
690 | None, None ->
691 fprintf fmt "@[Tacentries.ArgInterpRet@]"
692 in
693 let default_printer = mk_code "fun _ _ _ _ -> Pp.str \"missing printer\"" in
694 let rpr = match arg.argext_rprinter, arg.argext_tprinter with
695 | Some f, (None | Some _) -> f
696 | None, Some f -> f
697 | None, None -> default_printer
698 in
699 let gpr = match arg.argext_gprinter, arg.argext_tprinter with
700 | Some f, (None | Some _) -> f
701 | None, Some f -> f
702 | None, None -> default_printer
703 in
704 let tpr = match arg.argext_tprinter with
705 | Some f -> f
706 | None -> default_printer
707 in
708 let pr fmt () =
709 fprintf fmt "Tacentries.argument_extend ~plugin:\"%s\" ~name:%a ~ignore_kw:%a@ @[{@\n\
710 Tacentries.arg_parsing =@ %a;@\n\
711 Tacentries.arg_tag = @[%a@];@\n\
712 Tacentries.arg_intern = @[%a@];@\n\
713 Tacentries.arg_subst = @[%a@];@\n\
714 Tacentries.arg_interp = @[%a@];@\n\
715 Tacentries.arg_printer = @[((fun env sigma -> %a), (fun env sigma -> %a), (fun env sigma -> %a))@];@\n}@]"
716 (force_is_plugin ~what:"ARGUMENT EXTEND" ())
717 print_string name
718 print_ignore_kw ()
719 VernacArgumentExt.print_rules (name, arg.argext_rules)
720 pr_tag arg.argext_type
721 intern () subst () interp () print_code rpr print_code gpr print_code tpr
722 in
723 fprintf fmt "@[<2>let (wit_%s, %s) =@ @[%a@]@]@\nlet _ = (wit_%s, %s)@\n"
724 name name pr () name name
725
726 end
727
728 let declare_plugin fmt name =
729 let () = match !plugin_name with
730 | None -> plugin_name := Some name
731 | Some _ -> fatal "Multiple DECLARE PLUGIN not allowed";
732 in
733 ()
734
735 let pr_ast fmt = function
736 | Code s -> fprintf fmt "%a@\n" print_code s
737 | Comment s -> fprintf fmt "%s@\n" s
738 | DeclarePlugin name -> declare_plugin fmt name
739 | GramExt gram -> fprintf fmt "%a@\n" GramExt.print_ast gram
740 | VernacExt vernac -> fprintf fmt "%a@\n" VernacExt.print_ast vernac
741 | VernacArgumentExt arg -> fprintf fmt "%a@\n" VernacArgumentExt.print_ast arg
742 | TacticExt tac -> fprintf fmt "%a@\n" TacticExt.print_ast tac
743 | ArgumentExt arg -> fprintf fmt "%a@\n" ArgumentExt.print_ast arg
744 | IgnoreKeywords -> ignore_kw := true
745
746 let help () =
747 Format.eprintf "Usage: rocq preprocess-mlg file.mlg@\n%!";
748 exit 1
749
750 let parse = function
751 | ["-help"|"--help"] -> help()
752 | [file] -> file
753 | _ -> help ()
754
755 let output_name file =
756 try
757 Filename.chop_extension file ^ ".ml"
758 with
759 | Invalid_argument _ ->
760 fatal "Input file must have an extension for coqpp [input.ext -> input.ml]"
761
762 let main args =
763 let file = parse args in
764 let output = output_name file in
765 let ast = parse_file file in
766 let () = file_name := Filename.basename file in
767 let iter fmt ast = Format.fprintf fmt "@[%a@]%!" pr_ast ast in
768 let str = asprintf "%a" (fun fmt ast -> List.iter (iter fmt) ast) ast in
769 let str = fix_exit_code ~filename:output str in
770 let chan = open_out output in
771 let () = output_string chan str in
772 let () = close_out chan in
773 exit 0