catala/compiler/catala_utils/cli.ml

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

578 lines
17 KiB
OCaml
Raw Normal View History

2020-04-16 18:47:35 +03:00
(* This file is part of the Catala compiler, a specification language for tax
and social benefits computation rules. Copyright (C) 2020 Inria,
contributors: Denis Merigoux <denis.merigoux@inria.fr>, Emile Rolley
<emile.rolley@tuta.io>
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License. *)
type backend_lang = En | Fr | Pl
2021-01-09 23:03:32 +03:00
type backend_option_builtin =
[ `Latex
| `Makefile
| `Html
| `Interpret
| `Interpret_Lcalc
| `Typecheck
| `OCaml
| `Python
| `Scalc
| `Lcalc
| `Dcalc
| `Scopelang
| `Exceptions
| `Proof ]
type 'a backend_option = [ backend_option_builtin | `Plugin of 'a ]
(** Associates a {!type: Cli.backend_lang} with its string represtation. *)
let languages = ["en", En; "fr", Fr; "pl", Pl]
let language_code =
let rl = List.map (fun (a, b) -> b, a) languages in
fun l -> List.assoc l rl
let backend_option_to_string = function
| `Interpret -> "Interpret"
2023-04-05 16:38:46 +03:00
| `Interpret_Lcalc -> "Interpret_Lcalc"
| `Makefile -> "Makefile"
| `OCaml -> "Ocaml"
| `Scopelang -> "Scopelang"
| `Dcalc -> "Dcalc"
| `Latex -> "Latex"
| `Proof -> "Proof"
| `Html -> "Html"
| `Python -> "Python"
| `Typecheck -> "Typecheck"
| `Scalc -> "Scalc"
| `Lcalc -> "Lcalc"
| `Exceptions -> "Exceptions"
| `Plugin s -> s
let backend_option_of_string backend =
match String.lowercase_ascii backend with
| "interpret" -> `Interpret
2023-04-05 16:38:46 +03:00
| "interpret_lcalc" -> `Interpret_Lcalc
| "makefile" -> `Makefile
| "ocaml" -> `OCaml
| "scopelang" -> `Scopelang
| "dcalc" -> `Dcalc
| "latex" -> `Latex
| "proof" -> `Proof
| "html" -> `Html
| "python" -> `Python
| "typecheck" -> `Typecheck
| "scalc" -> `Scalc
| "lcalc" -> `Lcalc
| "exceptions" -> `Exceptions
| s -> `Plugin s
2021-01-09 23:03:32 +03:00
(** Source files to be compiled *)
let source_files : string list ref = ref []
let locale_lang : backend_lang ref = ref En
let contents : string ref = ref ""
(** Prints debug information *)
let debug_flag = ref false
2020-08-07 18:37:28 +03:00
(* Styles the terminal output *)
let style_flag = ref true
2020-12-09 18:45:23 +03:00
(* Max number of digits to show for decimal results *)
let max_prec_digits = ref 20
2020-12-11 12:51:46 +03:00
let trace_flag = ref false
let disable_warnings_flag = ref false
2021-04-03 14:44:11 +03:00
let optimize_flag = ref false
let disable_counterexamples = ref false
2022-02-24 18:46:02 +03:00
let avoid_exceptions_flag = ref false
let check_invariants_flag = ref false
2022-02-24 18:46:02 +03:00
2020-03-08 03:52:31 +03:00
open Cmdliner
let file =
Arg.(
required
& pos 1 (some file) None
2022-01-19 13:20:25 +03:00
& info [] ~docv:"FILE" ~doc:"Catala master file to be compiled.")
2020-03-08 03:52:31 +03:00
2022-01-19 13:20:25 +03:00
let debug =
Arg.(value & flag & info ["debug"; "d"] ~doc:"Prints debug information.")
2020-03-08 03:52:31 +03:00
type when_enum = Auto | Always | Never
let when_opt = Arg.enum ["auto", Auto; "always", Always; "never", Never]
let color =
Arg.(
value
& opt ~vopt:Always when_opt Auto
& info ["color"]
~doc:
"Allow output of colored and styled text. If set to $(i,auto), \
enabled when the standard output is to a terminal.")
2022-01-19 13:20:25 +03:00
let unstyled =
Arg.(
value
& flag
& info ["unstyled"; "u"]
~doc:
"Removes styling (colors, etc.) from terminal output. Equivalent to \
$(b,--color=never)")
2020-08-07 18:37:28 +03:00
2022-01-19 13:20:25 +03:00
let optimize =
Arg.(value & flag & info ["optimize"; "O"] ~doc:"Run compiler optimizations.")
2021-04-03 14:44:11 +03:00
2020-12-11 12:51:46 +03:00
let trace_opt =
2021-05-09 23:55:50 +03:00
Arg.(
2022-01-19 13:20:25 +03:00
value
& flag
& info ["trace"; "t"]
~doc:
"Displays a trace of the interpreter's computation or generates \
logging instructions in translate programs.")
2020-12-11 12:51:46 +03:00
let disable_warnings_opt =
Arg.(
value
& flag
& info ["disable_warnings"]
~doc:"Disable all the warnings emitted by the compiler.")
let check_invariants_opt =
Arg.(
value
& flag
& info ["check_invariants"] ~doc:"Check structural invariants on the AST.")
let avoid_exceptions =
Arg.(
value
& flag
& info ["avoid_exceptions"]
~doc:"Compiles the default calculus without exceptions.")
let closure_conversion =
Arg.(
value
& flag
& info ["closure_conversion"]
~doc:"Performs closure conversion on the lambda calculus.")
2020-04-29 10:55:49 +03:00
let wrap_weaved_output =
Arg.(
value
& flag
2022-01-19 13:20:25 +03:00
& info ["wrap"; "w"]
~doc:"Wraps literate programming output with a minimal preamble.")
2022-05-26 20:05:06 +03:00
let print_only_law =
Arg.(
value
& flag
& info ["print_only_law"]
~doc:
"In literate programming output, skip all code and metadata sections \
and print only the text of the law.")
2020-03-08 03:52:31 +03:00
let backend =
Arg.(
required
& pos 0 (some string) None
2022-01-19 13:20:25 +03:00
& info [] ~docv:"COMMAND"
~doc:
"Backend selection (see the list of commands for available options).")
2020-03-08 03:52:31 +03:00
let plugins_dirs =
let doc = "Set the given directory to be searched for backend plugins." in
let env = Cmd.Env.info "CATALA_PLUGINS" ~doc in
let default =
let ( / ) = Filename.concat in
2022-10-25 12:24:35 +03:00
[
Filename.dirname Sys.executable_name
2022-10-25 12:24:35 +03:00
/ Filename.parent_dir_name
/ "lib"
/ "catala"
/ "plugins";
]
in
Arg.(value & opt_all dir default & info ["plugin-dir"] ~docv:"DIR" ~env ~doc)
2020-04-19 20:16:04 +03:00
let language =
Arg.(
2020-04-19 20:25:46 +03:00
value
& opt (some string) None
2022-01-19 13:20:25 +03:00
& info ["l"; "language"] ~docv:"LANG"
~doc:"Input language among: en, fr, pl.")
2020-04-19 20:16:04 +03:00
2020-12-09 18:45:23 +03:00
let max_prec_digits_opt =
Arg.(
value
& opt (some int) None
2022-01-19 13:20:25 +03:00
& info
["p"; "max_digits_printed"]
~docv:"DIGITS"
~doc:
"Maximum number of significant digits printed for decimal results \
(default 20).")
2020-12-09 18:45:23 +03:00
let disable_counterexamples_opt =
Arg.(
value
& flag
& info
["disable_counterexamples"]
~doc:
"Disables the search for counterexamples in proof mode. Useful when \
you want a deterministic output from the Catala compiler, since \
provers can have some randomness in them.")
let ex_scope =
Arg.(
2022-01-19 13:20:25 +03:00
value
& opt (some string) None
& info ["s"; "scope"] ~docv:"SCOPE" ~doc:"Scope to be focused on.")
let ex_variable =
Arg.(
value
& opt (some string) None
& info ["v"; "variable"] ~docv:"VARIABLE" ~doc:"Variable to be focused on.")
2020-03-08 03:52:31 +03:00
let output =
Arg.(
value
2020-03-08 03:52:31 +03:00
& opt (some string) None
& info ["output"; "o"] ~docv:"OUTPUT"
2022-01-19 13:20:25 +03:00
~doc:
"$(i, OUTPUT) is the file that will contain the output of the \
compiler. Defaults to $(i,FILE).$(i,EXT) where $(i,EXT) depends on \
2022-05-31 17:24:37 +03:00
the chosen backend. Use $(b,-o -) for stdout.")
2020-03-08 03:52:31 +03:00
type options = {
debug : bool;
color : when_enum;
wrap_weaved_output : bool;
avoid_exceptions : bool;
backend : string;
plugins_dirs : string list;
language : string option;
max_prec_digits : int option;
trace : bool;
disable_warnings : bool;
disable_counterexamples : bool;
check_invariants : bool;
optimize : bool;
ex_scope : string option;
ex_variable : string option;
output_file : string option;
closure_conversion : bool;
2022-05-26 20:05:06 +03:00
print_only_law : bool;
}
let options =
let make
debug
color
unstyled
wrap_weaved_output
avoid_exceptions
closure_conversion
backend
plugins_dirs
language
max_prec_digits
disable_warnings
trace
disable_counterexamples
optimize
check_invariants
ex_scope
ex_variable
2022-05-26 20:05:06 +03:00
output_file
print_only_law : options =
{
debug;
color = (if unstyled then Never else color);
wrap_weaved_output;
avoid_exceptions;
backend;
plugins_dirs;
language;
max_prec_digits;
disable_warnings;
trace;
disable_counterexamples;
optimize;
check_invariants;
ex_scope;
ex_variable;
output_file;
closure_conversion;
2022-05-26 20:05:06 +03:00
print_only_law;
}
in
Term.(
const make
$ debug
$ color
$ unstyled
$ wrap_weaved_output
$ avoid_exceptions
$ closure_conversion
$ backend
$ plugins_dirs
$ language
$ max_prec_digits_opt
$ disable_warnings_opt
$ trace_opt
$ disable_counterexamples_opt
$ optimize
$ check_invariants_opt
2022-05-26 20:05:06 +03:00
$ ex_scope
$ ex_variable
2022-05-26 20:05:06 +03:00
$ output
$ print_only_law)
2020-03-08 03:52:31 +03:00
let catala_t f = Term.(const f $ file $ options)
let set_option_globals options : unit =
debug_flag := options.debug;
(style_flag :=
match options.color with
| Always -> true
| Never -> false
| Auto -> Unix.isatty Unix.stdout);
(match options.max_prec_digits with
| None -> ()
| Some i -> max_prec_digits := i);
disable_warnings_flag := options.disable_warnings;
trace_flag := options.trace;
optimize_flag := options.optimize;
check_invariants_flag := options.check_invariants;
disable_counterexamples := options.disable_counterexamples;
avoid_exceptions_flag := options.avoid_exceptions
Bump version to 0.8.0 Changelog: --- A lot has been going on, with more than 530 patches and 70 PRs merged since 0.7.0 last summer. In summary: - Quite a lot of syntax improvements and changes. Checkout the latest [cheat-sheet](https://catalalang.github.io/catala/syntax.pdf) for an overview - Allow local `let ... equals ... in ...` definitions - Better error messages and positions throughout - Added the ability to directly call a scope and retrieve its outputs, like a function - Added disambiguation, allowing to access structure fields without specifying the structure type each time - Added automated resolution of operators, allowing e.g. to write just `+` in place of all the type-specific operators `+.`, `+$`, `+@`, `+^`, etc. - More consistent priority for operators. It is no longer allowed to write `a and b or c` without parenthesis. - Added and changed some operators (`date + duration` now allowed either way, `int / int` now returns a decimal, added `duration / duration`) - Added the ability to have variables and functions defined at top-level (outside of any scope). See annex A of the tutorial for details. - Added support for functions with multiple arguments - Some big refactors in the compiler, allowing much better code sharing between the different passes, and making it much easier to extend. Also added the possibility to run the type-checker earlier, etc. - Countless bug-fixes - Improvements to our proof backend with Z3 - A tool to automatically synchronise with the upstream French law from Legifrance
2023-03-08 15:27:16 +03:00
let version = "0.8.0"
2020-03-08 03:52:31 +03:00
let info =
let doc =
2020-04-16 18:47:35 +03:00
"Compiler for Catala, a specification language for tax and social benefits \
computation rules."
2020-03-08 03:52:31 +03:00
in
let man =
[
`S Manpage.s_description;
`P
2020-04-19 20:04:11 +03:00
"Catala is a domain-specific language for deriving \
faithful-by-construction algorithms from legislative texts.";
2022-01-19 13:20:25 +03:00
`S Manpage.s_commands;
`I
( "$(b,Intepret)",
"Runs the interpreter on the Catala program, executing the scope \
specified by the $(b,-s) option assuming no additional external \
inputs." );
2023-04-06 14:09:49 +03:00
`I
( "$(b,Intepret_Lcalc)",
"Runs the interpreter on the lcalc pass on the Catala program, \
executing the scope specified by the $(b,-s) option assuming no \
additional external inputs." );
2022-01-31 17:28:19 +03:00
`I
( "$(b,Typecheck)",
"Parses and typechecks a Catala program, without interpreting it." );
2022-01-19 13:20:25 +03:00
`I
( "$(b,Proof)",
"Generates and proves verification conditions about the well-behaved \
execution of the Catala program." );
`I ("$(b,OCaml)", "Generates an OCaml translation of the Catala program.");
`I ("$(b,Python)", "Generates a Python translation of the Catala program.");
`I
( "$(b,LaTeX)",
"Weaves a LaTeX literate programming output of the Catala program." );
`I
( "$(b,HTML)",
"Weaves an HTML literate programming output of the Catala program." );
`I
( "$(b,Makefile)",
"Generates a Makefile-compatible list of the file dependencies of a \
Catala program." );
`I
( "$(b,Scopelang)",
"Prints a debugging verbatim of the scope language intermediate \
representation of the Catala program. Use the $(b,-s) option to \
restrict the output to a particular scope." );
`I
( "$(b,Dcalc)",
2022-02-14 19:01:34 +03:00
"Prints a debugging verbatim of the default calculus intermediate \
representation of the Catala program. Use the $(b,-s) option to \
restrict the output to a particular scope." );
`I
( "$(b,Lcalc)",
"Prints a debugging verbatim of the lambda calculus intermediate \
2022-01-19 13:20:25 +03:00
representation of the Catala program. Use the $(b,-s) option to \
restrict the output to a particular scope." );
2022-02-14 19:01:34 +03:00
`I
( "$(b,Scalc)",
"Prints a debugging verbatim of the statement calculus intermediate \
representation of the Catala program. Use the $(b,-s) option to \
restrict the output to a particular scope." );
`I
( "$(b,Exceptions)",
"Prints the exception tree for the definitions of a particular \
variable, for debugging purposes. Use the $(b,-s) option to select \
the scope and the $(b,-v) option to select the variable. Use \
foo.bar to access state bar of variable foo or variable bar of \
subscope foo." );
`I
( "$(b,pygmentize)",
"This special command is a wrapper around the $(b,pygmentize) \
command that enables support for colorising Catala code." );
2020-03-08 03:52:31 +03:00
`S Manpage.s_authors;
2022-01-19 13:20:25 +03:00
`P "The authors are listed by alphabetical order.";
2020-12-11 12:51:46 +03:00
`P "Nicolas Chataing <nicolas.chataing@ens.fr>";
2022-01-11 18:36:38 +03:00
`P "Alain Delaët-Tixeuil <alain.delaet--tixeuil@inria.fr>";
2022-01-19 13:20:25 +03:00
`P "Aymeric Fromherz <aymeric.fromherz@inria.fr>";
`P "Louis Gesbert <louis.gesbert@ocamlpro.com>";
`P "Denis Merigoux <denis.merigoux@inria.fr>";
`P "Emile Rolley <erolley@tutamail.com>";
2020-03-08 03:52:31 +03:00
`S Manpage.s_examples;
2022-01-19 13:20:25 +03:00
`Pre "catala Interpret -s Foo file.catala_en";
`Pre "catala Ocaml -o target/file.ml file.catala_en";
2020-03-08 03:52:31 +03:00
`S Manpage.s_bugs;
2020-12-11 12:51:46 +03:00
`P
"Please file bug reports at https://github.com/CatalaLang/catala/issues";
]
in
2022-05-04 18:37:03 +03:00
let exits = Cmd.Exit.defaults @ [Cmd.Exit.info ~doc:"on error." 1] in
Cmd.info "catala" ~version ~doc ~exits ~man
(**{1 Terminal formatting}*)
(**{2 Markers}*)
2021-02-28 13:15:18 +03:00
let time : float ref = ref (Unix.gettimeofday ())
let with_style
(styles : ANSITerminal.style list)
(str : ('a, unit, string) format) =
if !style_flag then ANSITerminal.sprintf styles str else Printf.sprintf str
let format_with_style (styles : ANSITerminal.style list) fmt (str : string) =
if !style_flag then
Format.pp_print_as fmt (String.length str)
(ANSITerminal.sprintf styles "%s" str)
else Format.pp_print_string fmt str
2022-07-20 17:51:28 +03:00
let call_unstyled f =
let prev = !style_flag in
style_flag := false;
let res = f () in
style_flag := prev;
res
let time_marker ppf () =
2021-02-28 13:15:18 +03:00
let new_time = Unix.gettimeofday () in
let old_time = !time in
time := new_time;
let delta = (new_time -. old_time) *. 1000. in
if delta > 50. then
format_with_style
[ANSITerminal.Bold; ANSITerminal.black]
ppf
2023-04-18 16:56:04 +03:00
(Format.sprintf "[TIME] %.0fms@\n" delta)
2020-08-07 18:37:28 +03:00
(** Prints [\[DEBUG\]] in purple on the terminal standard output *)
let debug_marker ppf () =
time_marker ppf ();
format_with_style [ANSITerminal.Bold; ANSITerminal.magenta] ppf "[DEBUG] "
(** Prints [\[ERROR\]] in red on the terminal error output *)
let error_marker ppf () =
format_with_style [ANSITerminal.Bold; ANSITerminal.red] ppf "[ERROR] "
(** Prints [\[WARNING\]] in yellow on the terminal standard output *)
let warning_marker ppf () =
format_with_style [ANSITerminal.Bold; ANSITerminal.yellow] ppf "[WARNING] "
(** Prints [\[RESULT\]] in green on the terminal standard output *)
let result_marker ppf () =
format_with_style [ANSITerminal.Bold; ANSITerminal.green] ppf "[RESULT] "
2020-12-11 12:51:46 +03:00
(** Prints [\[LOG\]] in red on the terminal error output *)
let log_marker ppf () =
format_with_style [ANSITerminal.Bold; ANSITerminal.black] ppf "[LOG] "
2020-12-11 12:51:46 +03:00
(**{2 Printers}*)
(** All the printers below print their argument after the correct marker *)
2020-04-26 19:32:03 +03:00
let concat_with_line_depending_prefix_and_suffix
(prefix : int -> string)
(suffix : int -> string)
(ss : string list) =
match ss with
| [] -> prefix 0
| _ :: _ ->
let len = List.length ss in
let suffix i = if i < len - 1 then suffix i else "" in
String.concat ""
@@ List.concat
@@ List.mapi
(fun i s -> [prefix i; (if s = "" then "" else " "); s; suffix i])
ss
2020-04-26 19:32:03 +03:00
(** The int argument of the prefix corresponds to the line number, starting at 0 *)
let add_prefix_to_each_line (s : string) (prefix : int -> string) =
concat_with_line_depending_prefix_and_suffix
(fun i -> prefix i)
(fun _ -> "\n")
(String.split_on_char '\n' s)
2020-04-26 14:39:01 +03:00
let debug_print format =
if !debug_flag then Format.printf ("%a" ^^ format ^^ "\n%!") debug_marker ()
else Format.ifprintf Format.std_formatter format
let debug_format (format : ('a, Format.formatter, unit) format) =
if !debug_flag then
Format.printf ("%a@[<hov>" ^^ format ^^ "@]@.") debug_marker ()
else Format.ifprintf Format.std_formatter format
let error_print format =
2023-04-21 12:29:07 +03:00
Format.print_flush ();
(* Flushes previous warnings *)
Format.eprintf ("%a" ^^ format ^^ "@\n") error_marker ()
let error_format (format : ('a, Format.formatter, unit) format) =
2023-04-21 12:29:07 +03:00
Format.print_flush ();
(* Flushes previous warnings *)
2023-04-14 12:21:52 +03:00
Format.printf ("%a" ^^ format ^^ "\n%!") error_marker ()
let warning_print format =
if !disable_warnings_flag then Format.ifprintf Format.std_formatter format
else Format.printf ("%a" ^^ format ^^ "@\n") warning_marker ()
let warning_format format =
Format.printf ("%a" ^^ format ^^ "\n%!") warning_marker ()
let result_print format =
Format.printf ("%a" ^^ format ^^ "\n%!") result_marker ()
let result_format format =
Format.printf ("%a" ^^ format ^^ "\n%!") result_marker ()
let log_print format = Format.printf ("%a" ^^ format ^^ "\n%!") log_marker ()
let log_format format =
Format.printf ("%a@[<hov>" ^^ format ^^ "@]@.") log_marker ()