Debian Codegraph @

checker/coqchk_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 Pp
12 open CErrors
13 open Util
14 open System
15 open Names
16 open Environ
17
18 let () = at_exit flush_all
19
20 let fatal_error info code =
21 flush_all (); Format.eprintf "@[Fatal Error: @[%a@]@]@\n%!" Pp.pp_with info; flush_all ();
22 exit code
23
24 let rocq_root = Id.of_string "Corelib"
25 let parse_dir s =
26 let len = String.length s in
27 let rec decoupe_dirs dirs n =
28 if n>=len then dirs else
29 let pos =
30 try
31 String.index_from s n '.'
32 with Not_found -> len
33 in
34 let dir = String.sub s n (pos-n) in
35 decoupe_dirs (dir::dirs) (pos+1)
36 in
37 decoupe_dirs [] 0
38 let dirpath_of_string s =
39 match parse_dir s with
40 | [] -> CheckLibrary.default_root_prefix
41 | dir -> DirPath.make (List.map Id.of_string dir)
42 let path_of_string s =
43 if Filename.check_suffix s ".vo" then CheckLibrary.PhysicalFile s
44 else match parse_dir s with
45 | [] -> invalid_arg "path_of_string"
46 | l::dir -> CheckLibrary.LogicalFile {dirpath=dir; basename=l}
47
48 let get_version env () =
49 match env with
50 | Boot.Env.Boot -> Coq_config.version
51 | Env env ->
52 try
53 let revision = Boot.Env.(Path.to_string (revision env)) in
54 let ch = open_in revision in
55 let ver = input_line ch in
56 let rev = input_line ch in
57 let () = close_in ch in
58 Printf.sprintf "%s (%s)" ver rev
59 with Sys_error _ | End_of_file -> Coq_config.version
60
61 let print_header env () =
62 Printf.printf "Welcome to Chicken %s\n%!" (get_version env ())
63
64 (* Adding files to Rocq loadpath *)
65
66 let add_path ~unix_path:dir ~rocq_root:rocq_dirpath =
67 if exists_dir dir then
68 begin
69 CheckLibrary.add_load_path (dir,rocq_dirpath)
70 end
71 else
72 Feedback.msg_warning (str "Cannot open " ++ str dir)
73
74 let convert_string d =
75 try Id.of_string d
76 with CErrors.UserError _ ->
77 Flags.if_verbose Feedback.msg_warning
78 (str "Directory " ++ str d ++ str " cannot be used as a Rocq identifier (skipped)");
79 raise_notrace Exit
80
81 let add_rec_path ~unix_path ~rocq_root =
82 if exists_dir unix_path then
83 let dirs = all_subdirs ~unix_path in
84 let prefix = DirPath.repr rocq_root in
85 let convert_dirs (lp, cp) =
86 try
87 let path = List.rev_map convert_string cp @ prefix in
88 Some (lp, Names.DirPath.make path)
89 with Exit -> None
90 in
91 let dirs = List.map_filter convert_dirs dirs in
92 List.iter CheckLibrary.add_load_path dirs;
93 CheckLibrary.add_load_path (unix_path, rocq_root)
94 else
95 Feedback.msg_warning (str "Cannot open " ++ str unix_path)
96
97 (* By the option -R/-Q of the command line *)
98 let includes = ref []
99 let push_include (s, alias) = includes := (s,alias) :: !includes
100
101 let set_include d p =
102 let p = if String.equal p "Coq" then "Corelib" else p in
103 let p = dirpath_of_string p in
104 push_include (d,p)
105
106 (* Initializes the LoadPath *)
107 let init_load_path rocqenv =
108 (* the to_string casting won't be necessary once Boot handles
109 include paths *)
110 let plugins = Boot.Env.plugins rocqenv |> Boot.Path.to_string in
111 let theories = Boot.Env.corelib rocqenv |> Boot.Path.to_string in
112 let user_contrib = Boot.Env.user_contrib rocqenv |> Boot.Path.to_string in
113 let xdg_dirs = Envars.xdg_dirs in
114 let rocqpath = Envars.coqpath in
115 (* NOTE: These directories are searched from last to first *)
116 (* first standard library *)
117 add_rec_path ~unix_path:theories ~rocq_root:(Names.DirPath.make[rocq_root]);
118 (* then plugins *)
119 add_rec_path ~unix_path:plugins ~rocq_root:(Names.DirPath.make [rocq_root]);
120 (* then user-contrib *)
121 if Sys.file_exists user_contrib then
122 add_rec_path ~unix_path:user_contrib ~rocq_root:CheckLibrary.default_root_prefix;
123 (* then directories in XDG_DATA_DIRS and XDG_DATA_HOME *)
124 List.iter (fun s -> add_rec_path ~unix_path:s ~rocq_root:CheckLibrary.default_root_prefix)
125 (xdg_dirs ~warn:(fun x -> Feedback.msg_warning (str x)));
126 (* then directories in ROCQPATH *)
127 List.iter (fun s -> add_rec_path ~unix_path:s ~rocq_root:CheckLibrary.default_root_prefix) (rocqpath());
128 (* then current directory *)
129 add_path ~unix_path:"." ~rocq_root:CheckLibrary.default_root_prefix
130
131 let init_load_path env : unit =
132 NewProfile.profile "init_load_path"
133 (fun () -> init_load_path env)
134 ()
135
136 let impredicative_set = ref false
137 let set_impredicative_set () = impredicative_set := true
138
139 let boot = ref false
140 let set_boot () = boot := true
141
142 let coqlib = ref None
143 let set_coqlib v = coqlib := Some v
144
145 let indices_matter = ref false
146
147 let enable_vm = ref false
148
149 let make_senv () =
150 let senv = Safe_typing.empty_environment in
151 let senv = Safe_typing.set_impredicative_set !impredicative_set senv in
152 let senv = Safe_typing.set_indices_matter !indices_matter senv in
153 let senv = Safe_typing.set_VM !enable_vm senv in
154 let senv = Safe_typing.set_allow_sprop true senv in (* be smarter later *)
155 Safe_typing.set_native_compiler false senv
156
157 let admit_list = ref ([] : CheckLibrary.object_file list)
158 let add_admit s =
159 admit_list := path_of_string s :: !admit_list
160
161 let norec_list = ref ([] : CheckLibrary.object_file list)
162 let add_norec s =
163 norec_list := path_of_string s :: !norec_list
164
165 let compile_list = ref ([] : CheckLibrary.object_file list)
166 let add_compile s =
167 compile_list := path_of_string s :: !compile_list
168
169 (*s Parsing of the command line.
170 We no longer use [Arg.parse], in order to use share [Usage.print_usage]
171 between coqtop and coqc. *)
172
173 let compile_files senv =
174 CheckLibrary.recheck_library senv
175 ~norec:(List.rev !norec_list)
176 ~admit:(List.rev !admit_list)
177 ~check:(List.rev !compile_list)
178
179 let version () =
180 Printf.printf "The Rocq Proof Checker, version %s\n" Coq_config.version;
181 exit 0
182
183 (* print the usage of coqtop (or coqc) on channel co *)
184
185 let print_usage_channel co command =
186 output_string co command;
187 output_string co "coqchk options are:\n";
188 output_string co
189 "\
190 \n -Q dir coqdir map physical dir to logical coqdir\
191 \n -R dir coqdir synonymous for -Q\
192 \n -coqlib dir set coqchk's standard library location\
193 \n -boot don't initialize the library paths automatically\
194 \n\
195 \n -admit module load module and dependencies without checking\
196 \n -norec module check module but admit dependencies without checking\
197 \n\
198 \n -d (d1,..,dn) enable specified debug messages\
199 \n -debug enable all debug messages\
200 \n -profile file output profiling info to file\
201 \n -where print coqchk's standard library location and exit\
202 \n -v, --version print coqchk version and exit\
203 \n -o, --output-context print the list of assumptions\
204 \n -m, --memory print the maximum heap size\
205 \n -silent disable trace of constants being checked\
206 \n\
207 \n -impredicative-set set sort Set impredicative\
208 \n -indices-matter levels of indices (and nonuniform parameters)\
209 \n contribute to the level of inductives\
210 \n -bytecode-compiler (yes|no) enable the vm_compute reduction machine (default is no)\
211 \n\
212 \n -h, --help print this list of options\
213 \n"
214
215 (* print the usage on standard error *)
216
217 let print_usage = print_usage_channel stderr
218
219 let print_usage_rocqtop () =
220 print_usage "Usage: coqchk <options> modules\n\n"
221
222 let usage exitcode =
223 print_usage_rocqtop ();
224 flush stderr;
225 exit exitcode
226
227 open Type_errors
228
229 let anomaly_string () = str "Anomaly: "
230 let report () = strbrk (". Please report at " ^ Coq_config.wwwbugtracker ^ ".")
231
232 let guill s = str "\"" ++ str s ++ str "\""
233
234 let explain_exn = function
235 | Sys_error msg ->
236 hov 0 (anomaly_string () ++ str "uncaught exception Sys_error " ++ guill msg ++ report() )
237 | UserError pps ->
238 hov 1 (str "User error: " ++ pps)
239 | Out_of_memory ->
240 hov 0 (str "Out of memory")
241 | Stack_overflow ->
242 hov 0 (str "Stack overflow")
243 | Match_failure(filename,pos1,pos2) ->
244 hov 1 (anomaly_string () ++ str "Match failure in file " ++
245 guill filename ++ str " at line " ++ int pos1 ++
246 str " character " ++ int pos2 ++ report ())
247 | Not_found ->
248 hov 0 (anomaly_string () ++ str "uncaught exception Not_found" ++ report ())
249 | Failure s ->
250 hov 0 (str "Failure: " ++ str s ++ report ())
251 | Invalid_argument s ->
252 hov 0 (anomaly_string () ++ str "uncaught exception Invalid_argument " ++ guill s ++ report ())
253 | Sys.Break ->
254 hov 0 (fnl () ++ str "User interrupt.")
255 | UGraph.UniverseInconsistency i ->
256 let msg =
257 if CDebug.(get_flag misc) then
258 str "." ++ spc() ++
259 UGraph.explain_universe_inconsistency Sorts.QVar.raw_pr Univ.Level.raw_pr i
260 else
261 mt() in
262 hov 0 (str "Error: Universe inconsistency" ++ msg ++ str ".")
263 | QGraph.EliminationError e ->
264 let msg =
265 if CDebug.(get_flag misc) then
266 str "." ++ spc() ++
267 QGraph.explain_elimination_error Sorts.QVar.raw_pr e
268 else
269 mt() in
270 hov 0 (str "Error: Elimination error" ++ msg ++ str ".")
271 | TypeError(ctx,te) ->
272 hov 0 (str "Type error: " ++
273 (match te with
274 | UnboundRel i -> str"UnboundRel " ++ int i
275 | UnboundVar v -> str"UnboundVar" ++ str(Names.Id.to_string v)
276 | NotAType _ -> str"NotAType"
277 | BadAssumption _ -> str"BadAssumption"
278 | ReferenceVariables _ -> str"ReferenceVariables"
279 | ElimArity _ -> str"ElimArity"
280 | CaseNotInductive _ -> str"CaseNotInductive"
281 | CaseOnPrivateInd _ -> str"CaseOnPrivateInd"
282 | WrongCaseInfo _ -> str"WrongCaseInfo"
283 | NumberBranches _ -> str"NumberBranches"
284 | IllFormedBranch _ -> str"IllFormedBranch"
285 | IllFormedCaseParams -> str "IllFormedCaseParams"
286 | BadProjType _ -> str "BadProjType"
287 | Generalization _ -> str"Generalization"
288 | ActualType _ -> str"ActualType"
289 | IncorrectPrimitive _ -> str"IncorrectPrimitive"
290 | CantApplyBadType ((n,a,b),{uj_val = hd; uj_type = hdty},args) ->
291 let pp_arg i judge =
292 hv 1 (str"arg " ++ int (i+1) ++ str"= " ++
293 Constr.debug_print judge.uj_val ++
294 str ",type= " ++ Constr.debug_print judge.uj_type) ++ fnl ()
295 in
296 Feedback.msg_notice (str"====== ill-typed term ====" ++ fnl () ++
297 hov 2 (str"application head= " ++ Constr.debug_print hd) ++ fnl () ++
298 hov 2 (str"head type= " ++ Constr.debug_print hdty) ++ fnl () ++
299 str"arguments:" ++ fnl () ++ hv 1 (prvecti pp_arg args));
300 Feedback.msg_notice (str"====== type error ====@" ++ fnl () ++
301 Constr.debug_print b ++ fnl () ++
302 str"is not convertible with" ++ fnl () ++
303 Constr.debug_print a ++ fnl ());
304 Feedback.msg_notice (str"====== universes ====" ++ fnl () ++
305 (UGraph.pr_universes Univ.Level.raw_pr
306 (UGraph.repr (Environ.universes ctx))));
307 str "CantApplyBadType at argument " ++ int n
308 | CantApplyNonFunctional _ -> str"CantApplyNonFunctional"
309 | IllFormedRecBody _ -> str"IllFormedRecBody"
310 | IllTypedRecBody _ -> str"IllTypedRecBody"
311 | UnsatisfiedUnivConstraints _ -> str"UnsatisfiedUnivConstraints"
312 | UnsatisfiedPConstraints _ -> str"UnsatisfiedPConstraints"
313 | NotAllowedSProp -> str"NotAllowedSProp"
314 | BadBinderRelevance _ -> str"BadBinderRelevance"
315 | BadCaseRelevance _ -> str"BadCaseRelevance"
316 | BadInvert -> str"BadInvert"
317 | UndeclaredQualities _ -> str"UndeclaredQualities"
318 | UndeclaredUniverses _ -> str"UndeclaredUniverse"
319 | BadVariance _ -> str "BadVariance"
320 | UndeclaredUsedVariables _ -> str "UndeclaredUsedVariables"
321 | IllFormedConstant _ -> str "IllFormedConstant"
322 | IllFormedInductive _ -> str "IllFormedInductive"
323 ))
324
325 | InductiveError (env,e) ->
326 hov 0 (str "Error related to inductive types")
327 (* let ctx = Check.get_env() in
328 hov 0
329 (str "Error:" ++ spc () ++ Himsg.explain_inductive_error ctx e)*)
330
331 | CheckInductive.InductiveMismatch (mind,field) ->
332 hov 0 (MutInd.print mind ++ str ": field " ++ str field ++ str " is incorrect.")
333
334 | Mod_checking.BadConstant (cst, why) ->
335 hov 0 (Constant.print cst ++ spc() ++ why)
336
337 | Assert_failure (s,b,e) ->
338 hov 0 (anomaly_string () ++ str "assert failure" ++ spc () ++
339 (if s = "" then mt ()
340 else
341 (str "(file \"" ++ str s ++ str "\", line " ++ int b ++
342 str ", characters " ++ int e ++ str "-" ++
343 int (e+6) ++ str ")")) ++
344 report ())
345 | e -> CErrors.print e (* for anomalies and other uncaught exceptions *)
346
347 let profile = ref None
348
349 let parse_args argv =
350 let rec parse = function
351 | [] -> ()
352 | "-impredicative-set" :: rem ->
353 set_impredicative_set (); parse rem
354
355 | "-indices-matter" :: rem ->
356 indices_matter:=true; parse rem
357
358 | "-bytecode-compiler" :: "yes" :: rem ->
359 enable_vm := true; parse rem
360 | "-bytecode-compiler" :: "no" :: rem ->
361 enable_vm := false; parse rem
362
363 | "-coqlib" :: s :: rem ->
364 if not (exists_dir s) then
365 fatal_error (str "Directory '" ++ str s ++ str "' does not exist") 1;
366 set_coqlib s;
367 parse rem
368
369 | "-boot" :: rem ->
370 set_boot ();
371 parse rem
372
373 | ("-Q"|"-R") :: d :: p :: rem -> set_include d p;parse rem
374 | ("-Q"|"-R") :: ([] | [_]) -> usage 1
375
376 | "-d" :: s :: rem ->
377 CDebug.set_flags s;
378 parse rem
379 | "-debug" :: rem -> CDebug.set_debug_all true; parse rem
380
381 | "-profile" :: s :: rem ->
382 profile := Some s;
383 parse rem
384
385 | "-profile" :: [] -> usage 1
386
387 | "-where" :: _ ->
388 let env = Boot.Env.init_with ~coqlib:!coqlib in
389 let rocqlib = Boot.Env.coqlib env |> Boot.Path.to_string in
390 print_endline rocqlib;
391 exit 0
392
393 | ("-?"|"-h"|"-H"|"-help"|"--help") :: _ -> usage 0
394
395 | ("-v"|"--version") :: _ -> version ()
396 | ("-m" | "--memory") :: rem -> Check_stat.memory_stat := true; parse rem
397 | ("-o" | "--output-context") :: rem ->
398 Check_stat.output_context := true; parse rem
399
400 | "-admit" :: s :: rem -> add_admit s; parse rem
401 | "-admit" :: [] -> usage 1
402
403 | "-norec" :: s :: rem -> add_norec s; parse rem
404 | "-norec" :: [] -> usage 1
405
406 | "-silent" :: rem ->
407 Flags.quiet := true; parse rem
408
409 | s :: _ when s<>"" && s.[0]='-' ->
410 fatal_error (str "Unknown option " ++ str s) 1
411 | s :: rem -> add_compile s; parse rem
412 in
413 parse (List.tl (Array.to_list argv))
414
415 let init_profile ~file =
416 let ch = open_out file in
417 let fname = Filename.basename file in
418 NewProfile.init { output = Format.formatter_of_out_channel ch; fname; };
419 at_exit (fun () ->
420 NewProfile.finish ();
421 close_out ch)
422
423 (* XXX: At some point we need to either port the checker to use the
424 feedback system or to remove its use completely. *)
425 let init_with_argv argv =
426 let _fhandle = Feedback.(add_feeder (console_feedback_listener Format.err_formatter)) in
427 try
428 parse_args argv;
429 Option.iter (fun file -> init_profile ~file) !profile;
430 if CDebug.(get_flag misc) then Printexc.record_backtrace true;
431 let coqenv = Boot.Env.maybe_init ~boot:!boot ~coqlib:!coqlib
432 ~warn_ignored_coqlib:CWarnings.warn_ignored_coqlib
433 in
434 Flags.if_verbose (fun () -> print_header coqenv ()) ();
435 let () = match coqenv with
436 | Boot -> ()
437 | Env coqenv -> init_load_path coqenv
438 in
439 (* additional loadpath, given with -R/-Q options *)
440 NewProfile.profile "add_load_paths" (fun () ->
441 List.iter
442 (fun (unix_path, rocq_root) -> add_rec_path ~unix_path ~rocq_root)
443 (List.rev !includes))
444 ();
445 includes := [];
446 make_senv ()
447 with e ->
448 fatal_error (str "Error during initialization :" ++ (explain_exn e)) (CErrors.exit_code e)
449
450 let init() = init_with_argv Sys.argv
451
452 let run senv =
453 try
454 let senv = compile_files senv in
455 flush_all(); senv
456 with e ->
457 if CDebug.(get_flag misc) then Printexc.print_backtrace stderr;
458 fatal_error (explain_exn e) (CErrors.exit_code e)
459
460 let main () =
461 let senv = init() in
462 let senv, opac = run senv in
463 Check_stat.stats (Safe_typing.env_of_safe_env senv) opac;
464 exit 0