123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655(* 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. *)openGlobalmoduleG=Global(* Manipulation of types used by flags & options *)(** Associates a {!type: Global.backend_lang} with its string represtation. *)letlanguages=["en",En;"fr",Fr;"pl",Pl]letlanguage_code=letrl=List.map(fun(a,b)->b,a)languagesinfunl->List.assoclrlletmessage_format_opt=["human",(Human:message_format_enum);"gnu",GNU]lettrace_format_opt=["human",(Human:trace_format_enum);"json",JSON]openCmdliner(* Arg converters for our custom types *)letwhen_opt=Arg.enum["auto",Auto;"always",Always;"never",Never]letraw_file=Arg.conv~docv:"FILE"((funf->Result.mapraw_file(Arg.conv_parserArg.stringf)),funppff->Format.pp_print_stringppf(f:>string))(* Some helpers for catala sources *)letextensions=[".catala_fr",Fr;".catala_en",En;".catala_pl",Pl]letfile_langfilename=List.assoc_opt(Filename.extensionfilename)extensions|>function|Somelang->lang|None->(matchGlobal.options.languagewith|Somelang->lang|None->Format.kasprintffailwith"Could not infer language variant from the extension of \
@{<yellow>%s@}, and @{<bold>--language@} was not specified"filename)letexec_dir=letcmd=Sys.argv.(0)inifString.containscmd'/'then(* Do not use Sys.executable_name, which may resolve symlinks: we want the
original path. (e.g. _build/install/default/bin/foo is a symlink) *)Filename.dirnamecmdelse(* searched in PATH *)Filename.dirnameSys.executable_name(** CLI flags and options *)lets_plugins="INSTALLED PLUGINS"lets_debug="DEBUGGING COMMANDS"moduleFlags=structopenCmdlineropenArgmoduleGlobal=structletinfo=info~docs:Manpage.s_common_optionsletinput_src=letconverter=conv~docv:"FILE"((funs->ifs="-"thenOk(Stdin(Global.raw_file"-stdin-"))elseResult.map(funf->FileName(Global.raw_filef))(conv_parsernon_dir_files)),funppf->function|Stdin_->Format.pp_print_stringppf"-"|FileNamef->conv_printernon_dir_fileppf(f:>file)|_->assertfalse)inrequired&pos0(someconverter)None&Arg.info[]~docv:"FILE"~docs:Manpage.s_arguments~doc:"Catala master file to be compiled ($(b,-) for stdin)."letlanguage=value&opt(some(enumlanguages))None&info["l";"language"]~docv:"LANG"~doc:"Locale variant of the input language to use when it can not be \
inferred from the file extension."letdebug=value&flag&info["debug";"d"]~env:(Cmd.Env.info"CATALA_DEBUG")~doc:"Prints debug information."letcolor=letunstyled=value&flag&info["unstyled"]~doc:"Removes styling (colors, etc.) from terminal output."~deprecated:"Use $(b,--color=)$(i,never) instead"inletcolor=value&opt~vopt:Alwayswhen_optAuto&info["color"]~env:(Cmd.Env.info"CATALA_COLOR")~doc:"Allow output of colored and styled text. Use $(i,auto), to \
enable when the standard output is to a terminal, $(i,never) to \
disable."inTerm.(const(funcolorunstyled->ifunstyledthenNeverelsecolor)$color$unstyled)letmessage_format=value&opt(enummessage_format_opt)Human&info["message-format"]~doc:"Selects the format of error and warning messages emitted by the \
compiler. If set to $(i,human), the messages will be nicely \
displayed and meant to be read by a human. If set to $(i, gnu), \
the messages will be rendered according to the GNU coding \
standards."lettrace=letconverter=conv~docv:"FILE"((funs->ifs="-"thenOk`StdoutelseifFilename.extensions|>String.starts_with~prefix:".catala"thenError(`Msg"Output trace file cannot have a .catala extension")elseOk(`FileName(Global.raw_files))),funppf->function|`Stdout->Format.pp_print_stringppf"-"|`FileNamef->Format.pp_print_stringppf(f:>string))invalue&opt(someconverter)None~vopt:(Some`Stdout)&info["trace";"t"]~docv:"FILE"~env:(Cmd.Env.info"CATALA_TRACE")~doc:"Displays a trace of the interpreter's computation or generates \
logging instructions in translated programs. If set as a flag, \
outputs trace to stdout. If $(docv) is defined, outputs the trace \
to a file while interpreting.\n\
Defining a filename does not affect code generation. Cannot use \
.catala extension."lettrace_format=value&opt(some(enumtrace_format_opt))None&info["trace-format"]~doc:"Selects the format of trace logs emitted by the interpreter. If \
set to $(i,human), the messages will be nicely displayed and \
meant to be read by a human. If set to $(i, json), the messages \
will be emitted as a JSON structured object."letplugins_dirs=letdoc="Set the given directory to be searched for backend plugins."inletenv=Cmd.Env.info"CATALA_PLUGINS"inletdefault=let(/)=Filename.concatinletdev_plugin_dir=exec_dir/"plugins"inifSys.file_existsdev_plugin_dirthen(* When running tests in place, may need to lookup in _build/default
besides the exec *)[dev_plugin_dir]else(* Otherwise, assume a standard layout: "<prefix>/bin/catala" besides
"<prefix>/lib/catala" *)[Filename.(dirnameexec_dir)/"lib"/"catala"/"plugins"]invalue&opt_allstringdefault&info["plugin-dir"]~docv:"DIR"~env~docletdisable_warnings=value&flag&info["disable-warnings"]~doc:"Disable all the warnings emitted by the compiler."letmax_prec_digits=value&optint20&info["p";"max-digits-printed"]~docv:"NUM"~doc:"Maximum number of significant digits printed for decimal results."letname_flag=value&opt(somestring)None&info["name"]~docv:"FILE"~doc:"Treat the input as coming from a file with the given name. Useful \
e.g. when reading from stdin"letdirectory=value&opt(somedir)None&info["C";"directory"]~docv:"DIR"~doc:"Behave as if run from the given directory for file and error \
reporting. Does not affect resolution of files in arguments."letstop_on_error=value&flag&info["x";"stop-on-error"]~doc:"Stops the compilation as soon as an error is encountered."letno_fail_on_assert=value&flag&info["no-fail-on-assert"]~doc:"Instead of reporting an error on assertion failure, reports a \
warning and carry on with the interpretation as usual."letwhole_program=value&flag&info["W";"whole-program"]~doc:"Compile the full chain of module dependencies without requiring a \
separate module compilation."letbin_dir=value&opt(someraw_file)None&info["bin"]~docv:"DIR"~doc:"Directory containing compiled artifacts. This is used to load \
shared modules. Defaults to the value of $(b,--directory) if that \
is set, or to $(b,_build) otherwise, consistently with the \
defaults used by clerk to create these files."letgen_external=value&flag&info["gen-external"]~doc:"Run on a file defining an external module, this generates \
template files in the target language, to be used as a basis for \
writing the corresponding implementation."letflags=letmakelanguagedebugcolormessage_formattracetrace_formatplugins_dirsdisable_warningsmax_prec_digitsdirectorystop_on_errorno_fail_on_assertwhole_programbin_dirgen_external:options=ifdebugthenPrintexc.record_backtracetrue;letpath_rewrite=matchdirectorywith|None->fun(f:Global.raw_file)->(f:>file)|Someto_dir->(fun(f:Global.raw_file)->match(f:>file)with|"-"->"-"|f->File.reverse_path~to_dirf)inlettrace,trace_format=matchtrace,trace_formatwith|None,_->None,trace_format|Some`Stdout,_->Some(lazy(Message.std_ppf())),trace_format|Some(`FileNamef),Some_->(Some(lazy(Message.formatter_of_out_channel(open_out(path_rewritef))())),trace_format)|Some(`FileNamef),None->lettrace_format=ifFilename.extension(f:>file)=".json"thenJSONelseHumanin(Some(lazy(Message.formatter_of_out_channel(open_out(path_rewritef))())),Sometrace_format)inletbin_dir=matchbin_dirwith|Somed->path_rewrited|None->(matchdirectorywith|Some_->Filename.current_dir_name|None->"_build")inlettrace_format=Option.valuetrace_format~default:Humanin(* This sets some global refs for convenience, but most importantly
returns the options record. *)Global.enforce_options~language~debug~color~message_format~trace~trace_format~plugins_dirs~disable_warnings~max_prec_digits~path_rewrite~stop_on_error~no_fail_on_assert~whole_program~bin_dir~gen_external()inTerm.(constmake$language$debug$color$message_format$trace$trace_format$plugins_dirs$disable_warnings$max_prec_digits$directory$stop_on_error$no_fail_on_assert$whole_program$bin_dir$gen_external)letoptions=letmakeinput_srcnamedirectoryoptions:options=(* Set some global refs for convenience *)letinput_src=letrenamef=matchnamewithNone->f|Somen->Global.raw_fileninmatchinput_srcwith|FileNamef->FileName(options.path_rewritef)|Contents(str,f)->Contents(str,options.path_rewrite(renamef))|Stdinf->Stdin(options.path_rewrite(renamef))inOption.iterSys.chdirdirectory;Global.enforce_options~input_src()inTerm.(constmake$input_src$name_flag$directory$flags)endletstdlib_dir=letno_stdlib=Arg.(value&flag&info["no-stdlib"]~doc:"Disable loading of the standard library. Required for compiling \
the standard library itself.")inletstdlib=Arg.(value&optraw_fileFile.(G.raw_file("_build"/"libcatala"))&info["stdlib"]~docv:"DIR"~env:(Cmd.Env.info"CATALA_STDLIB")~doc:"Specifies where the standard library will be found. This is \
normally handled automatically by $(b,clerk).")inTerm.(const(funno_stdlibstdlib->ifno_stdlibthenNoneelseSomestdlib)$no_stdlib$stdlib)letinclude_dirs=letarg=Arg.(value&opt_all(list~sep:':'raw_file)[]&info["I";"include"]~docv:"DIR"~env:(Cmd.Env.info"CATALA_INCLUDE")~doc:"Make modules from the given directory available from \
everywhere. Several dirs can be specified by repeating the flag \
or separating them with '$(b,:)'.")inTerm.(constList.flatten$arg)letcheck_invariants=value&flag&info["check-invariants"]~doc:"Check structural invariants on the AST."letquiet=value&flag&info["quiet"]~doc:"Only display a short summary of results."letautotest=value&flag&info["autotest"]~env:(Cmd.Env.info"CATALA_AUTOTEST")~doc:"Insert automatic test assertions in the compiled program. This \
affects scopes marked with the $(i,#[test]) attribute, running the \
interpreter to pre-compute their values, then adding runtime \
assertions that ensure that the actual output of the scopes match \
their pre-computed values. This is meaningful for validating the \
different backends, guaranteeing consistency of their results that \
of the interpreter."letno_typing=value&flag&info["no-typing"]~doc:"Don't check the consistency of types"letwrap_weaved_output=value&flag&info["wrap";"w"]~doc:"Wraps literate programming output with a minimal preamble."letprint_only_law=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."letex_scope=required&opt(somestring)None&info["s";"scope"]~docv:"SCOPE"~doc:"Scope to be focused on."letex_scope_opt=value&opt(somestring)None&info["s";"scope"]~docv:"SCOPE"~doc:"Scope to be focused on."letex_scopes=value&opt_allstring[]&info["s";"scope"]~docv:"SCOPE"~doc:"Scope to be focused on."letex_variable=required&opt(somestring)None&info["v";"variable"]~docv:"VARIABLE"~doc:"Variable to be focused on."letoutput=value&opt(someraw_file)None&info["output";"o"]~docv:"OUTPUT"~env:(Cmd.Env.info"CATALA_OUT")~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 \
the chosen backend. Use $(b,-o -) for stdout."letoptimize=value&flag&info["optimize";"O"]~env:(Cmd.Env.info"CATALA_OPTIMIZE")~doc:"Run compiler optimizations."letkeep_special_ops=value&flag&info["keep-special-ops"]~doc:"During closure conversion (between Lcalc and Scalc), do not convert \
the functional arguments of higher-order operators."letmonomorphize_types=value&flag&info["monomorphize-types"]~doc:"In LCalc, replaces the polymorphic option type by monomorphized \
versions of the enumeration, and transform tuples into named \
structs. "letexpand_ops=value&flag&info["expand-ops"]~doc:"In LCalc, expand equality operators to only rely on comparisons of \
literals. "letdead_value_assignment=value&flag&info["dead-value-assignment"]~doc:"During the Lcalc->Scalc translation, insert dummy variable \
assignments before raising terminal exception to please gradual \
typing tools that check exhaustivity of variable definitions in \
every code branch."letno_struct_literals=value&flag&info["no-struct-literals"]~doc:"During the Lcalc->Scalc translation, insert temporary variable \
assignments to hold the result of array and structure \
initializations (matches the absence of struct literals of C89)."letclosure_conversion=value&flag&info["closure-conversion"]~doc:"Performs closure conversion on the lambda calculus."letdisable_counterexamples=value&flag&info["disable-counterexamples"]~doc:"Disables the search for counterexamples. Useful when you want a \
deterministic output from the Catala compiler, since provers can \
have some randomness in them."letextra_files=value&pos_right0file[]&Arg.info[]~docv:"FILES"~docs:Manpage.s_arguments~doc:"Additional input files."letlcalc=value&flag&info["lcalc"]~doc:"Compile all the way to lcalc before interpreting (the default is to \
interpret at dcalc stage). For debugging purposes."letextension=value&opt_allstring[]&info["extension";"e"]~docv:"EXT"~doc:"Replace the original file extensions with $(i,.EXT). If repeated, \
the file will be listed once which each supplied extension."letprefix=value&opt(somestring)None&info["prefix"]~docv:"PATH"~doc:"Prepend the given path to each of the files in the returned list."letsubdir=value&opt(somestring)None&info["subdir"]~docv:"PATH"~doc:"Append the given subdir at the end of the path of each of the files \
in the returned list. Usually matches the name of the backend used."end(* Retrieve current version from dune *)letversion=Version.vletman_header=[`SManpage.s_description;`P"Catala is a domain-specific language for deriving \
faithful-by-construction algorithms from legislative texts.";]letman_footer=[`SManpage.s_common_options;`SManpage.s_authors;`P"The authors are listed by alphabetical order:";`P"Vincent Botbol <$(i,vincent.botbol@inria.fr)>";`Noblank;`P"Nicolas Chataing <$(i,nicolas.chataing@ens.fr)>";`Noblank;`P"Alain Delaët-Tixeuil <$(i,alain.delaet--tixeuil@inria.fr)>";`Noblank;`P"Aymeric Fromherz <$(i,aymeric.fromherz@inria.fr)>";`Noblank;`P"Louis Gesbert <$(i,louis.gesbert@ocamlpro.com)>";`Noblank;`P"Denis Merigoux <$(i,denis.merigoux@inria.fr)>";`Noblank;`P"Emile Rolley <$(i,erolley@tutamail.com)>";`SManpage.s_bugs;`P"Please file bug reports at https://github.com/CatalaLang/catala/issues";]letman_base=man_header@man_footerletinfo=letdoc="Compiler for Catala, a specification language for tax and social benefits \
computation rules."inletman=man_header@[`SManpage.s_synopsis;`P"$(mname) [$(i,COMMAND)] $(i,FILE) [$(i,OPTION)]…";`P"Use $(mname) [$(i,COMMAND)] $(b,--hel)p for documentation on a \
specific command";`SManpage.s_commands;`Ss_plugins;`Ss_debug;`P"These commands are intended for debugging of the Catala compiler \
itself, and unlikely to be useful to the end-user";`SManpage.s_examples;`Pre"catala Interpret -s Foo file.catala_en";`Pre"catala Ocaml -o target/file.ml file.catala_en";]@man_footerinletexits=Cmd.Exit.defaults@[Cmd.Exit.info~doc:"on error."1]inCmd.info"catala"~version~doc~exits~manexceptionExit_withofint