Debian Codegraph @

tools/rocqmakefile.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 (* rocq makefile: automatically create a Makefile for a Rocq development *)
12
13 open CoqProject_file
14 open Printf
15
16 let (>) f g = fun x -> g (f x)
17
18 let usage_coq_makefile ~ok =
19 let out = if ok then stdout else stderr in
20 output_string out "Usage summary:\
21 \n\
22 \nrocq makefile .... [file.v] ... [file.ml[ig]?] ... [file.ml{lib,pack}]\
23 \n ... [-I dir] ... [-R physicalpath logicalpath]\
24 \n ... [-Q physicalpath logicalpath] ... [VARIABLE = value]\
25 \n ... [-arg opt] ... [-docroot path] [-f file] [-o file]\
26 \n ... [-generate-meta-for-package project-name]\
27 \n [-h] [--help] [-v] [--version]\
28 \n";
29 output_string out "\
30 \nFull list of options:\
31 \n\
32 \n[file.v]: Rocq file to be compiled\
33 \n[file.ml[ig]?]: Objective Caml file to be compiled\
34 \n[file.ml{lib,pack}]: ocamlbuild-style file that describes a Objective Caml\
35 \n library/module\
36 \n[-I dir]: look for Objective Caml dependencies in \"dir\"\
37 \n[-R physicalpath logicalpath]: look for Rocq dependencies recursively\
38 \n starting from \"physicalpath\". The logical path associated to the\
39 \n physical path is \"logicalpath\".\
40 \n[-Q physicalpath logicalpath]: look for Rocq dependencies starting from\
41 \n \"physicalpath\". The logical path associated to the physical path\
42 \n is \"logicalpath\".\
43 \n[-coqlib dir]: set the Rocq Corelib directory\
44 \n[VARIABLE = value]: Add the variable definition \"VARIABLE=value\"\
45 \n[-arg opt]: send option \"opt\" to rocq compile\
46 \n[-docroot path]: Install the documentation in this folder, relative to\
47 \n \"user-contrib\".\
48 \n[-f file]: take the contents of file as arguments\
49 \n[-o file]: output should go in file file (recommended)\
50 \n Output file outside the current directory is forbidden.\
51 \n[-generate-meta-for-package project-name]: generate META.project-name.\
52 \n[-h]: print this usage summary\
53 \n[--help]: equivalent to [-h]\
54 \n[-v]: print version information\
55 \n[--version]: equivalent to [-v]\
56 \n";
57 exit (if ok then 0 else 1)
58
59 let is_prefix dir1 dir2 =
60 let l1 = String.length dir1 in
61 let l2 = String.length dir2 in
62 let sep = Filename.dir_sep in
63 if dir1 = dir2 then true
64 else if l1 + String.length sep <= l2 then
65 let dir1' = String.sub dir2 0 l1 in
66 let sep' = String.sub dir2 l1 (String.length sep) in
67 dir1' = dir1 && sep' = sep
68 else false
69
70 let physical_dir_of_logical_dir ldir =
71 let ldir = Bytes.of_string ldir in
72 let le = Bytes.length ldir - 1 in
73 let pdir =
74 if le >= 0 && Bytes.get ldir le = '.' then Bytes.sub ldir 0 (le - 1)
75 else Bytes.copy ldir
76 in
77 for i = 0 to le - 1 do
78 if Bytes.get pdir i = '.' then Bytes.set pdir i '/';
79 done;
80 Bytes.to_string pdir
81
82 let read_whole_file s =
83 let ic = open_in s in
84 let b = Buffer.create (1 lsl 12) in
85 try
86 while true do
87 let s = input_line ic in
88 Buffer.add_string b s;
89 Buffer.add_char b '\n';
90 done;
91 assert false;
92 with End_of_file ->
93 close_in ic;
94 Buffer.contents b
95
96 (* Use this for quoting contents of variables which never appears as target or
97 * pattern. *)
98 let makefile_quote s =
99 let out = Buffer.create 16 in
100 Buffer.add_string out "'";
101 String.iter
102 (fun c ->
103 match c with
104 | '$' -> Buffer.add_string out "$$"
105 | '#' -> Buffer.add_string out "\\#"
106 | '\'' -> Buffer.add_string out "'\\''"
107 | _ -> Buffer.add_char out c
108 )
109 s;
110 Buffer.add_string out "'";
111 Buffer.contents out
112
113 let quote s = if String.contains s ' ' || CString.is_empty s then "'" ^ s ^ "'" else s
114
115 let generate_makefile oc env conf_file local_file local_late_file dep_file args project =
116 (* XX coq makefile should ship files on its own dir *)
117 let cmf_dir = Boot.Env.tool env "" in
118 let makefile_template = Boot.Path.relative cmf_dir "CoqMakefile.in" in
119 if not (Boot.Path.exists makefile_template) then
120 begin
121 let makefile_template = Boot.Path.to_string makefile_template in
122 Format.eprintf "Error: cannot find %s" makefile_template;
123 exit 1
124 end;
125 let makefile_template = Boot.Path.to_string makefile_template in
126 let s = read_whole_file makefile_template in
127 let s = List.fold_left
128 (* We use global_substitute to avoid running into backslash issues due to \1 etc. *)
129 (fun s (k,v) -> Str.global_substitute (Str.regexp_string k) (fun _ -> v) s) s
130 [ "@CONF_FILE@", conf_file;
131 "@LOCAL_FILE@", local_file;
132 "@LOCAL_LATE_FILE@", local_late_file;
133 "@DEP_FILE@", dep_file;
134 "@COQ_VERSION@", Coq_config.version;
135 "@PROJECT_FILE@", (Option.default "" project.project_file);
136 "@COQ_MAKEFILE_INVOCATION@",String.concat " " (List.map quote args);
137 ] in
138 output_string oc s
139
140 let generate_meta_file p =
141 try
142 match p.meta_file with
143 | Absent -> p
144 | Generate proj ->
145 let cmname = List.map (fun { thing } -> thing)
146 (files_by_suffix p.files [".mllib"; ".mlpack"]) in
147 let dir, cmname =
148 match cmname with
149 | [] -> Printf.eprintf "In order to generate a META file one needs an .mlpack or .mllib file\n"; exit 1
150 | [x] -> Filename.dirname x, Filename.(basename @@ chop_extension x)
151 | _ -> Printf.eprintf "Automatic META generation only works for one .mlpack or .mllib file, since you have more you need to write the META file by hand\n"; exit 1 in
152 let f = dir ^ "/META." ^ proj in
153 let oc = open_out f in
154 let meta : _ format = {|
155 package "plugin" (
156 directory = "."
157 requires = "rocq-runtime.plugins.ltac"
158 archive(byte) = "%s.cma"
159 archive(native) = "%s.cmxa"
160 plugin(byte) = "%s.cma"
161 plugin(native) = "%s.cmxs"
162 )
163 directory = "."
164 |}
165 in
166 let meta = Printf.sprintf meta cmname cmname cmname cmname in
167 output_string oc meta;
168 close_out oc;
169 { p with meta_file = Present f }
170 | Present f ->
171 let ext = Filename.extension f in
172 if ext = ".in" then
173 let meta_file = Filename.chop_extension f in
174 let oc = open_out meta_file in
175 (* META generation is just a renaming for now, we lack some metadata *)
176 output_string oc (read_whole_file f);
177 close_out oc;
178 { p with meta_file = Present meta_file }
179 else
180 p (* already a META.package file *)
181 with Sys_error e ->
182 Printf.eprintf "Error: %s\n" e;
183 exit 1
184
185 let section oc s =
186 let pad = String.make (76 - String.length s) ' ' in
187 let sharps = String.make 79 '#' in
188 let spaces = "#" ^ String.make 77 ' ' ^ "#" in
189 fprintf oc "\n%s\n" sharps;
190 fprintf oc "%s\n" spaces;
191 fprintf oc "# %s%s#\n" s pad;
192 fprintf oc "%s\n" spaces;
193 fprintf oc "%s\n\n" sharps
194 ;;
195
196 let generate_conf_includes oc { ml_includes; r_includes; q_includes } =
197 section oc "Path directives (-I, -R, -Q).";
198 let module S = String in
199 let map = map_sourced_list in
200 let dash1 opt v = sprintf "-%s %s" opt (quote v) in
201 let dash2 opt v1 v2 = sprintf "-%s %s %s" opt (quote v1) (quote v2) in
202 fprintf oc "COQMF_OCAMLLIBS = %s\n"
203 (S.concat " " (map (fun { path } -> dash1 "I" path) ml_includes));
204 fprintf oc "COQMF_SRC_SUBDIRS = %s\n"
205 (S.concat " " (map (fun { path } -> quote path) ml_includes));
206 fprintf oc "COQMF_COQLIBS = %s %s %s\n"
207 (S.concat " " (map (fun { path } -> dash1 "I" path) ml_includes))
208 (S.concat " " (map (fun ({ path },l) -> dash2 "Q" path l) q_includes))
209 (S.concat " " (map (fun ({ path },l) -> dash2 "R" path l) r_includes));
210 fprintf oc "COQMF_COQLIBS_NOML = %s %s\n"
211 (S.concat " " (map (fun ({ path },l) -> dash2 "Q" path l) q_includes))
212 (S.concat " " (map (fun ({ path },l) -> dash2 "R" path l) r_includes));
213 fprintf oc "COQMF_CMDLINE_COQLIBS = %s %s %s\n"
214 (S.concat " " (map_cmdline (fun { path } -> dash1 "I" path) ml_includes))
215 (S.concat " " (map_cmdline (fun ({ path },l) -> dash2 "Q" path l) q_includes))
216 (S.concat " " (map_cmdline (fun ({ path },l) -> dash2 "R" path l) r_includes));
217 ;;
218
219 let windrive s =
220 if Coq_config.arch_is_win32 && Str.(string_match (regexp "^[a-zA-Z]:") s 0)
221 then Str.matched_string s
222 else ""
223 ;;
224
225 let generate_conf_coq_config oc env =
226 section oc "Rocq configuration.";
227 Boot.Env.print_config ~prefix_var_name:"COQMF_" env oc;
228 let coqlib = Boot.Env.(coqlib env |> Path.to_string) in
229 (* XXX: FIXME, why does this variable needs the root lib *)
230 fprintf oc "COQMF_WINDRIVE=%s\n" (windrive coqlib)
231 ;;
232
233 let check_metafile p =
234 if files_by_suffix p.files [".mlpack"; ".mllib"] <> [] && p.meta_file = Absent then begin
235 eprintf "Warning: it is recommended you provide a META.package-name file\n";
236 eprintf "Warning: since you build plugins. See also -generate-meta-for-package.\n";
237 end
238
239 let write_coqbin oc =
240 fprintf oc "%s\n"
241 "COQBIN?=\n\
242 ifneq (,$(COQBIN))\n\
243 # add an ending /\n\
244 COQBIN:=$(COQBIN)/\n\
245 endif\n\
246 COQMKFILE ?= \"$(COQBIN)rocq\" makefile"
247
248 let generate_conf_files oc p
249 =
250 let module S = String in
251 let fout varname suffix =
252 fprintf oc "COQMF_%s := $(filter %%%s, $(COQMF_SOURCES))\n" varname suffix;
253 in
254 section oc "Project files.";
255
256 let cmdline_vfiles = p.cmd_line_files in
257 fprintf oc "COQMF_CMDLINE_VFILES := %s\n" (S.concat " " (map_sourced_list quote cmdline_vfiles));
258 let proj_arg = match p.project_file with
259 | Some pfile -> Printf.sprintf "-f %s" pfile
260 | None -> ""
261 in
262 fprintf oc "COQMF_SOURCES := $(shell $(COQMKFILE) -sources-of %s $(COQMF_CMDLINE_VFILES))\n" proj_arg;
263 fout "VFILES" ".v";
264 fout "MLIFILES" ".mli";
265 fout "MLFILES" ".ml";
266 fout "MLGFILES" ".mlg";
267 fout "MLPACKFILES" ".mlpack";
268 fout "MLLIBFILES" ".mllib";
269 fprintf oc "COQMF_METAFILE = %s\n" (match p.meta_file with Present x -> x | _ -> "")
270
271 let rec all_start_with prefix = function
272 | [] -> true
273 | [] :: _ -> false
274 | (x :: _) :: rest -> x = prefix && all_start_with prefix rest
275
276 let rec logic_gcd acc = function
277 | [] -> acc
278 | [] :: _ -> acc
279 | (hd :: tl) :: rest ->
280 if all_start_with hd rest
281 then logic_gcd (acc @ [hd]) (tl :: List.map List.tl rest)
282 else acc
283
284 let generate_conf_doc oc { docroot; q_includes; r_includes } =
285 let includes = List.map (forget_source > snd) (q_includes @ r_includes) in
286 let logpaths = List.map (String.split_on_char '.') includes in
287 let gcd = logic_gcd [] logpaths in
288 let root =
289 match docroot with
290 | None ->
291 if gcd = [] then
292 let destination = "orphan_" ^ (String.concat "_" includes) in
293 eprintf "Warning: No common logical root.\n";
294 eprintf "Warning: In this case the -docroot option should be given.\n";
295 eprintf "Warning: Otherwise the install-doc target is going to install files\n";
296 eprintf "Warning: in %s\n" destination;
297 destination
298 else String.concat Filename.dir_sep gcd
299 | Some p -> p in
300 Printf.fprintf oc "COQMF_INSTALLCOQDOCROOT = %s\n" (quote root)
301
302 let generate_conf_native oc native_compiler =
303 section oc "Native compiler.";
304 let flag = match native_compiler with
305 | None -> ""
306 | Some NativeYes -> "yes"
307 | Some NativeNo -> "no"
308 | Some NativeOndemand -> "ondemand"
309 in
310 Printf.fprintf oc "COQMF_COQPROJECTNATIVEFLAG = %s\n" flag
311
312
313 let generate_conf_defs oc { defs; extra_args } =
314 section oc "Extra variables.";
315 List.iter (forget_source > (fun (k,v) -> Printf.fprintf oc "%s = %s\n" k v)) defs;
316 Printf.fprintf oc "COQMF_OTHERFLAGS = %s\n"
317 (String.concat " " (List.map (forget_source > makefile_quote) extra_args))
318
319 let generate_conf oc env project args =
320 fprintf oc "# This configuration file was generated by running:\n";
321 fprintf oc "# %s\n\n" (String.concat " " (List.map quote args));
322 write_coqbin oc;
323 generate_conf_files oc project;
324 generate_conf_includes oc project;
325 generate_conf_coq_config oc env;
326 generate_conf_native oc project.native_compiler;
327 generate_conf_defs oc project;
328 generate_conf_doc oc project;
329 ;;
330
331 let ensure_root_dir
332 ({ ml_includes; r_includes; q_includes; files } as project)
333 =
334 let exists f = List.exists (forget_source > f) in
335 let here = Sys.getcwd () in
336 let not_tops = List.for_all (fun s -> s.thing <> Filename.basename s.thing) in
337 if exists (fun { canonical_path = x } -> x = here) ml_includes
338 || exists (fun ({ canonical_path = x },_) -> is_prefix x here) r_includes
339 || exists (fun ({ canonical_path = x },_) -> is_prefix x here) q_includes
340 || not_tops files
341 then
342 project
343 else
344 let source x = {thing=x; source=CmdLine} in
345 let here_path = { path = "."; canonical_path = here } in
346 { project with
347 ml_includes = source here_path :: ml_includes;
348 r_includes = source (here_path, "Top") :: r_includes }
349 ;;
350
351 let check_overlapping_include { q_includes; r_includes } =
352 let pwd = Sys.getcwd () in
353 let aux = function
354 | [] -> ()
355 | {thing = { path; canonical_path }, _} :: l ->
356 if not (is_prefix pwd canonical_path) then
357 eprintf "Warning: %s (used in -R or -Q) is not a subdirectory of the current directory\n\n" path;
358 List.iter (fun {thing={ path = p; canonical_path = cp }, _} ->
359 if is_prefix canonical_path cp || is_prefix cp canonical_path then
360 eprintf "Warning: %s and %s overlap (used in -R or -Q)\n\n"
361 path p) l
362 in
363 aux (q_includes @ r_includes)
364 ;;
365
366 let check_native_compiler = function
367 | None -> ()
368 | Some flag ->
369 match Coq_config.native_compiler, flag with
370 | Coq_config.NativeOff, (NativeYes | NativeOndemand) ->
371 eprintf "Warning: native compilation is globally deactivated by the configure flag\n"
372 | _ -> ()
373
374 let chop_prefix p f =
375 let len_p = String.length p in
376 let len_f = String.length f in
377 String.sub f len_p (len_f - len_p)
378
379 type extra_opts = {
380 only_destination : string option;
381 only_sources : bool;
382 coqlib : string option;
383 }
384
385 let empty_extra = {
386 only_destination = None;
387 only_sources = false;
388 coqlib = None;
389 }
390
391 let parse_extra f r opts = match f, r with
392 | "-destination-of", tgt :: r -> Some (r, { opts with only_destination = Some tgt })
393 | "-sources-of", r -> Some (r, { opts with only_sources = true })
394 | "-coqlib", v :: r -> Some (r, { opts with coqlib = Some v })
395 | ("-h"|"--help"), _ -> usage_coq_makefile ~ok:true
396 | ("-v"|"--version"), _ -> Boot.Usage.version (); exit 0
397 | _ -> None
398
399 let destination_of { ml_includes; q_includes; r_includes; } file =
400 let file_dir = CUnix.canonical_path_name (Filename.dirname file) in
401 let includes = q_includes @ r_includes in
402 let mk_destination logic canonical_path =
403 Filename.concat
404 (physical_dir_of_logical_dir logic)
405 (chop_prefix canonical_path file_dir) in
406 let candidates =
407 CList.map_filter (fun {thing={ canonical_path }, logic} ->
408 if is_prefix canonical_path file_dir then
409 Some(mk_destination logic canonical_path)
410 else None) includes
411 in
412 match candidates with
413 | [] ->
414 (* BACKWARD COMPATIBILITY: -I into the only logical root *)
415 begin match
416 r_includes,
417 List.find (fun {thing={ canonical_path = p }} -> is_prefix p file_dir)
418 ml_includes
419 with
420 | [{thing={ canonical_path }, logic}], {thing={ canonical_path = p }} ->
421 let destination =
422 Filename.concat
423 (physical_dir_of_logical_dir logic)
424 (chop_prefix p file_dir) in
425 Printf.printf "%s" (quote destination)
426 | _ -> () (* skip *)
427 | exception Not_found -> () (* skip *)
428 end
429 | [s] -> Printf.printf "%s" (quote s)
430 | _ -> assert false
431
432 let normal_mode ~coqlib project prog args =
433 if project.makefile = None then
434 eprintf "Warning: Omitting -o is deprecated\n\n";
435 (* We want to know the name of the Makefile (say m) in order to
436 * generate m.conf and include m.local *)
437
438 let conf_file = Option.default "CoqMakefile" project.makefile ^ ".conf" in
439 let local_file = Option.default "CoqMakefile" project.makefile ^ ".local" in
440 let local_late_file = Option.default "CoqMakefile" project.makefile ^ ".local-late" in
441 let dep_file = "." ^ Option.default "CoqMakefile" project.makefile ^ ".d" in
442
443 let project = ensure_root_dir project in
444
445 check_overlapping_include project;
446
447 check_native_compiler project.native_compiler;
448
449 check_metafile project;
450
451 let project = generate_meta_file project in
452
453 (* NB: we need a full Boot.Env not just the runtime half because the
454 conf file contains coqlib *)
455 let env = Boot.Env.init_with ~coqlib in
456
457 let ocm = Option.cata open_out stdout project.makefile in
458 generate_makefile ocm env conf_file local_file local_late_file dep_file (prog @ args) project;
459 close_out ocm;
460 let occ = open_out conf_file in
461 generate_conf occ env project (prog @ args);
462 close_out occ;
463 ()
464
465 let main ~prog args =
466 let _fhandle = Feedback.(add_feeder (console_feedback_listener Format.err_formatter)) in
467
468 let { extra_data = { only_destination; only_sources; coqlib } } as project =
469 let warning_fn x = Format.eprintf "%s@\n%!" x in
470 try cmdline_args_to_project ~warning_fn ~curdir:Filename.current_dir_name ~parse_extra empty_extra args
471 with Parsing_error s -> prerr_endline s; usage_coq_makefile ~ok:false in
472
473 match only_destination, only_sources with
474 | None, false -> normal_mode ~coqlib project prog args
475 | Some dest, false ->
476 destination_of project dest
477 | None, true ->
478 let paths = String.concat " " (List.map (fun i -> i.thing) project.files) in
479 Printf.printf "%s" paths
480 | Some _, true ->
481 prerr_endline "Cannot combine -destination-of and -sources-of";
482 usage_coq_makefile ~ok:false