Skip to main content

charon_lib/
options.rs

1//! The options that control charon behavior.
2use annotate_snippets::Level;
3use clap::ValueEnum;
4use enum_as_inner::EnumAsInner;
5use indoc::indoc;
6use itertools::Itertools;
7use serde::{Deserialize, Serialize};
8use std::path::PathBuf;
9
10use crate::{
11    ast::*,
12    errors::{ErrorCtx, display_unspanned_error},
13    name_matcher::NamePattern,
14    raise_error, register_error,
15};
16
17/// The name of the environment variable we use to save the serialized Cli options
18/// when calling charon-driver from cargo-charon.
19pub const CHARON_ARGS: &str = "CHARON_ARGS";
20
21/// The name of an environment variable we use to control `cargo`'s caching, so that cargo reruns
22/// `charon-driver` on exactly the selected crates and keeps every other crate cached.
23pub fn selected_crate_var(crate_name: &str) -> String {
24    format!("CHARON_SELECTED_CRATE_{crate_name}")
25}
26
27// This structure is used to store the command-line instructions.
28// We automatically derive a command-line parser based on this structure.
29// Note that the doc comments are used to generate the help message when using
30// `--help`.
31//
32// Note that because we need to transmit the options to the charon driver,
33// we store them in a file before calling this driver (hence the `Serialize`,
34// `Deserialize` options).
35#[derive(Debug, Default, Clone, PartialEq, Eq)]
36#[derive(clap::Args)]
37#[derive(Serialize, Deserialize)]
38#[clap(name = "Charon")]
39#[cfg_attr(feature = "charon_on_charon", charon::rename("cli_options"))]
40pub struct CliOpts {
41    /// Extract the unstructured LLBC (i.e., don't reconstruct the control-flow)
42    #[clap(long)]
43    #[serde(default)]
44    pub ullbc: bool,
45    /// Reconstruct the control-flow without duplicating blocks: a block reachable from several
46    /// branches is emitted once, and the branches `break` forward to it out of an enclosing
47    /// `loop`. This can shrink bodies a lot, at the cost of control-flow that is harder to read.
48    /// Note that consumers which expect `if`/`loop`-shaped bodies (e.g. aeneas) may not support
49    /// the result.
50    #[clap(long)]
51    #[serde(default)]
52    pub no_code_duplication: bool,
53    /// Whether to precisely translate drops and drop-related code. For this, we add explicit
54    /// `Destruct` bounds to all generic parameters and set the MIR level to at least `elaborated`.
55    ///
56    /// Without this option, drops may be "conditional" and we may lack information about what code
57    /// is run on drop in a given polymorphic function body.
58    #[clap(long)]
59    #[serde(default)]
60    pub precise_drops: bool,
61    /// The MIR stage to extract. This is only relevant for the current crate; for dependencies only
62    /// MIR optimized is available.
63    #[arg(long)]
64    pub mir: Option<MirLevel>,
65    /// Extra flags to pass to rustc.
66    #[clap(long = "rustc-arg")]
67    #[serde(default)]
68    pub rustc_args: Vec<String>,
69    /// A list of target architectures to translate for. Charon will run the compiler once for each
70    /// target and aggregate the results, which is useful if the code includes `#[cfg(..)]`
71    /// filters.
72    /// Warning: this is an initial implementation which is extremely slow.
73    #[clap(long, value_delimiter = ',')]
74    #[serde(default)]
75    pub targets: Vec<String>,
76    /// When cargo builds several crates (e.g. with `charon cargo -- --workspace`), translate each
77    /// of them as the local crate and merge the results into a single output, as if they were one
78    /// crate. Only supported with `charon cargo`.
79    #[clap(long)]
80    #[serde(default)]
81    pub merge_crates: bool,
82    /// The crate name to give the merged crate when using `--merge-crates`. Defaults to the first
83    /// crate selected by cargo.
84    #[clap(long)]
85    #[serde(default)]
86    pub merged_crate_name: Option<String>,
87    /// Sysroot to use for rustc invocations. By default Charon builds a sysroot that has full MIR
88    /// for the standard library. You can pass a custom sysroot to use instead, or pass "default"
89    /// to use the normal distributed sysroot, which lacks MIR bodies for many standard library
90    /// functions.
91    #[clap(long)]
92    #[serde(default)]
93    pub sysroot: Option<String>,
94
95    /// Monomorphize the items encountered when possible. Generic items found in the crate are
96    /// skipped. To only translate a particular call graph, use `--start-from`. Note: this doesn't
97    /// currently support `dyn Trait`.
98    #[clap(long, visible_alias = "mono")]
99    #[serde(default)]
100    pub monomorphize: bool,
101    /// Partially monomorphize items to make it so that no item is ever monomorphized with a
102    /// mutable reference (or type containing one); said differently, so that the presence of
103    /// mutable references in a type is independent of its generics. This is used by Aeneas.
104    #[clap(
105        long,
106        value_name("INCLUDE_TYPES"),
107        num_args(0..=1),
108        require_equals(true),
109        default_missing_value("all"),
110    )]
111    #[serde(default)]
112    pub monomorphize_mut: Option<MonomorphizeMut>,
113    /// Record the layout of each instantiation of a polymorphic type that we encounter during
114    /// translation. The instantiated layouts are stored in `TypeDecl::monomorphic_layouts`.
115    ///
116    /// This does not collect all the instantiations we would see post-monomorphization however,
117    /// e.g. `fn foo<T>() -> usize { size_of::<Option<T>>() }; foo<&u8>()` will not record
118    /// `Option<&u8>`.
119    #[clap(long)]
120    #[serde(default)]
121    pub collect_instantiated_layouts: bool,
122
123    /// A list of item paths to use as starting points for the translation. We will translate these
124    /// items and any items they refer to, according to the opacity rules. When absent, we start
125    /// from the path `crate` (which translates the whole crate).
126    #[clap(long, value_delimiter = ',')]
127    #[serde(default)]
128    pub start_from: Vec<String>,
129    /// Same as --start-from, but won't raise an error if a pattern doesn't match any item. This is useful
130    /// when the patterns are generated by a build script and may be out of sync with the code.
131    #[clap(long, value_delimiter = ',')]
132    #[serde(default)]
133    pub start_from_if_exists: Vec<String>,
134    /// Use all the items annotated with the given attribute(s) as starting points for translation
135    /// (except modules).
136    /// If an attribute name is not specified, `verify::start_from` is used.
137    #[clap(
138        long,
139        value_name("ATTRIBUTE"),
140        num_args(0..),
141        require_equals(true),
142        value_delimiter = ',',
143        default_missing_value("verify::start_from"),
144    )]
145    #[serde(default)]
146    pub start_from_attribute: Vec<String>,
147    /// Use all the `pub` items as starting points for translation (except modules).
148    #[clap(long)]
149    #[serde(default)]
150    pub start_from_pub: bool,
151    /// Use global constructors as starting points for translation, i.e. the `#[used]` statics
152    /// placed in the linker section that the target runs at startup (e.g. `.init_array` on ELF).
153    #[clap(long)]
154    #[serde(default)]
155    pub start_from_global_ctors: bool,
156
157    /// Whitelist of items to translate. These use the name-matcher syntax.
158    #[clap(
159        long,
160        help = indoc!("
161            Whitelist of items to translate. These use the name-matcher syntax (note: this differs
162            a bit from the ocaml NameMatcher).
163
164            Note: This is very rough at the moment. E.g. this parses `u64` as a path instead of the
165            built-in type. It is also not possible to filter a trait impl (this will only filter
166            its methods). Please report bugs or missing features.
167
168            Examples:
169              - `crate::module1::module2::item`: refers to this item and all its subitems (e.g.
170                  submodules or trait methods);
171              - `crate::module1::module2::item::_`: refers only to the subitems of this item;
172              - `core::convert::{impl core::convert::Into<_> for _}`: retrieve the body of this
173                  very useful impl;
174
175            When multiple patterns in the `--include` and `--opaque` options match the same item,
176            the most precise pattern wins. E.g.: `charon --opaque crate::module --include
177            crate::module::_` makes the `module` opaque (we won't explore its contents), but the
178            items in it transparent (we will translate them if we encounter them.)
179    "))]
180    #[serde(default)]
181    #[cfg_attr(feature = "charon_on_charon", charon::rename("included"))]
182    pub include: Vec<String>,
183    /// Blacklist of items to keep opaque. Works just like `--include`, see the doc there.
184    #[clap(long)]
185    #[serde(default)]
186    pub opaque: Vec<String>,
187    /// Blacklist of items to not translate at all. Works just like `--include`, see the doc there.
188    #[clap(long)]
189    #[serde(default)]
190    pub exclude: Vec<String>,
191    /// Usually we skip the bodies of foreign methods and structs with private fields. When this
192    /// flag is on, we don't.
193    #[clap(long)]
194    #[serde(default)]
195    pub extract_opaque_bodies: bool,
196    /// Usually we skip the provided methods that aren't used. When this flag is on, we translate
197    /// them all.
198    #[clap(long)]
199    #[serde(default)]
200    pub translate_all_methods: bool,
201    /// Usually we only translate the vtables that are used in an unsizing coercion, and leave the
202    /// `vtable` field of the other trait impls as `Lazy`. When this flag is on, we translate the
203    /// vtable of every trait impl of a dyn-compatible trait.
204    #[clap(long)]
205    #[serde(default)]
206    pub eager_vtables: bool,
207    /// For functions declared in `extern { .. }` blocks, also translate the function exported under
208    /// the same symbol, i.e. what the linker will resolve them to, and record it in `Body::Extern`.
209    #[clap(long)]
210    #[serde(default)]
211    pub link_extern_fns: bool,
212    /// Whenever an impl doesn't implement a method (because it has a default body), this creates a
213    /// duplicate method as if it had been implemented. This can simplify the call-graphs as
214    /// otherwise calls within the default body would be indirected through trait proofs.
215    #[clap(long)]
216    #[serde(default)]
217    pub duplicate_defaulted_methods: bool,
218
219    /// Transform the associate types of traits to be type parameters instead. This takes a list
220    /// of name patterns of the traits to transform, using the same syntax as `--include`.
221    #[clap(long, alias = "remove-associated-types")]
222    #[serde(default)]
223    pub lift_associated_types: Vec<String>,
224    /// Whether to hide various marker traits such as `Sized`, `Sync`, and `Send`
225    /// anywhere they show up. This can considerably speed up translation.
226    #[clap(long)]
227    #[serde(default)]
228    pub hide_marker_traits: bool,
229    /// Hide the `A` type parameter on standard library containers (`Box`, `Vec`, etc).
230    #[clap(long)]
231    #[serde(default)]
232    pub hide_allocator: bool,
233    /// Don't translate doc comments.
234    #[clap(long)]
235    #[serde(default)]
236    pub no_doc_comments: bool,
237
238    /// Remove trait clauses that aren't ultimately used anywhere. This is potentially incorrect as
239    /// sometimes the mere presence of a trait clause is used to justify an operation, e.g. copying
240    /// `Copy` data using `unsafe`.
241    #[clap(long)]
242    #[serde(default)]
243    pub remove_unused_clauses: bool,
244    /// Trait method default bodies take a `Self: Trait` clause as parameter, so that they can be
245    /// reused by multiple trait impls. This however causes trait definitions to be mutually
246    /// recursive with their default methods. This flag removes `Self` clauses that aren't used to
247    /// break this mutual recursion when possible.
248    #[clap(long)]
249    #[serde(default)]
250    pub remove_unused_self_clauses: bool,
251    /// Remove trait clauses from type declarations. Best combined with `--lift-associated-types`
252    /// for type declarations that use trait associated types in their fields.
253    #[clap(long)]
254    #[serde(default)]
255    pub remove_adt_clauses: bool,
256
257    /// Transform precise drops to the equivalent `drop_glue(&mut p)` call.
258    #[clap(long)]
259    #[serde(default)]
260    pub desugar_drops: bool,
261    /// Reconstruct conditional drops from the drop-flags and precise drops introduced by rustc's
262    /// drop elaboration, when possible. This may leave drop flags if we couldn't identify a known
263    /// pattern.
264    #[clap(long)]
265    #[serde(default)]
266    pub resugar_drops: bool,
267    /// Detect the drop flags inserted by rustc, which are booleans that track initialedness of a place.
268    #[clap(long)]
269    #[serde(default)]
270    pub detect_drop_flags: bool,
271    /// Transform array-to-slice unsizing and repeat expressions into standard library function
272    /// calls in LLBC.
273    #[clap(long)]
274    #[serde(default)]
275    pub ops_to_function_calls: bool,
276    /// Transform array/slice indexing into standard library function calls in LLBC. Note that this may
277    /// introduce UB since it creates references that were not normally created, including when
278    /// indexing behind a raw pointer.
279    #[clap(long)]
280    #[serde(default)]
281    pub index_to_function_calls: bool,
282    /// Treat `Box<T>` as if it was a built-in type.
283    #[clap(long)]
284    #[serde(default)]
285    pub treat_box_as_builtin: bool,
286    /// Don't generate a type declaration per tuple arity. Instead, every tuple type refers to the
287    /// single opaque declaration with id `TypeDeclId::UNIT`, and stores its field types in its
288    /// generic arguments. This is meant for consumers that build tuples of arbitrary arity on the
289    /// fly and don't care about their declaration. Note that this makes tuple types ill-typed with
290    /// respect to their declaration; it is also incompatible with `--monomorphize`.
291    #[clap(long)]
292    #[serde(default)]
293    pub no_gen_tuple_structs: bool,
294    /// Do not inline or evaluate constants.
295    #[clap(long)]
296    #[serde(default)]
297    pub raw_consts: bool,
298    /// Inline anonymous constants, including promoted constants and inline const blocks. This is
299    /// unsound for promoted constants if they're used with a `'static` lifetime, as this will move
300    /// the constant to a local variable.
301    #[clap(long)]
302    #[serde(default)]
303    pub inline_anon_consts: bool,
304    /// How to represent constants and statics: as a call to their initializer function, as an
305    /// evaluated value, or as raw bytes. This is always best-effort: in some cases we only get the
306    /// evaluated constant, and in others we cannot evaluate the constant and keep the initializer.
307    #[clap(long)]
308    #[serde(default)]
309    pub consts: Option<ConstHandling>,
310    /// Replace "bound checks followed by UB-on-overflow operation" with the corresponding
311    /// panic-on-overflow operation. This loses unwinding information.
312    #[clap(long)]
313    #[serde(default)]
314    pub reconstruct_fallible_operations: bool,
315    /// Replace calls to built-in panic functions with a `Panic` terminator.
316    #[clap(long)]
317    #[serde(default)]
318    pub reconstruct_panic_calls: bool,
319    /// Replace `if x { panic() }` with `assert(x)`.
320    #[clap(long)]
321    #[serde(default)]
322    pub reconstruct_asserts: bool,
323    /// Recombine a `read_discriminant(place)` followed by a `switch` into a single operation that
324    /// uses enum variants instead of their discriminants.
325    #[clap(long)]
326    #[serde(default)]
327    pub reconstruct_matches: bool,
328    /// Ensure all local deallocations are made explicit with `StorageDead` statements. If this flag is not passed,
329    /// every non-return local is implicitly deallocated on function return.
330    /// Note this can add a lot of statements (quadratically-many, because of unwind paths).
331    #[clap(long)]
332    #[serde(default)]
333    pub deallocate_all_locals: bool,
334    /// Use `DeBruijnVar::Free` for the variables bound in item signatures, instead of
335    /// `DeBruijnVar::Bound` everywhere. This simplifies the management of generics for projects
336    /// that don't intend to manipulate them too much.
337    #[clap(long)]
338    #[serde(default)]
339    pub unbind_item_vars: bool,
340
341    /// Pretty-print the ULLBC immediately after extraction from MIR.
342    #[clap(long)]
343    #[serde(default)]
344    pub print_original_ullbc: bool,
345    /// Pretty-print the ULLBC after applying the micro-passes (before serialization/control-flow reconstruction).
346    #[clap(long)]
347    #[serde(default)]
348    pub print_ullbc: bool,
349    /// Pretty-print the LLBC just after we built it (i.e., immediately after loop reconstruction).
350    #[clap(long)]
351    #[serde(default)]
352    pub print_built_llbc: bool,
353    /// Pretty-print the final LLBC (after all the cleaning micro-passes).
354    #[clap(long)]
355    #[serde(default)]
356    pub print_llbc: bool,
357    /// When pretty-printing, also print the layout of every type declaration.
358    #[clap(long)]
359    #[serde(default)]
360    pub print_layouts: bool,
361    /// When pretty-printing, add comments that indicate which items and statements are unsafe.
362    #[clap(long)]
363    #[serde(default)]
364    pub print_safety: bool,
365    /// The destination directory. Files will be generated as
366    /// `<dest_dir>/<crate_name>.{u}llbc` for json and `<dest_dir>/<crate_name>.{u}llbc.postcard`
367    /// for postcard, unless `dest_file` is set. `dest_dir` defaults to the current directory.
368    #[clap(long = "dest", value_parser)]
369    #[serde(default)]
370    pub dest_dir: Option<PathBuf>,
371    /// The destination file. By default this depends on `format` and `ullbc`. If this is set we
372    /// ignore `dest_dir`. If used with `format=all`, will add an extension corresponding to the file format
373    /// at the end of the provided file name.
374    #[clap(long, value_parser)]
375    #[serde(default)]
376    pub dest_file: Option<PathBuf>,
377    /// Don't deduplicate values (types, trait refs) in the .(u)llbc file. This makes the file easier to inspect.
378    #[clap(long)]
379    #[serde(default)]
380    pub no_dedup_serialized_ast: bool,
381    /// Serialization format for emitted files. Defaults to json.
382    #[clap(long, value_enum)]
383    #[serde(default)]
384    pub format: Option<SerializationFormatArg>,
385    /// Run the translated program with MiniRust.
386    #[clap(long)]
387    #[serde(default)]
388    pub run_with_minirust: bool,
389    /// Don't serialize the final (U)LLBC to a file.
390    #[clap(long)]
391    #[serde(default)]
392    pub no_serialize: bool,
393    /// If activated, this skips borrow-checking of the crate.
394    #[clap(
395        long = "skip-borrow-check",
396        alias = "skip-borrowck",
397        visible_alias = "no-borrow-check",
398        alias = "no-borrowck"
399    )]
400    #[serde(default)]
401    pub skip_borrowck: bool,
402    /// Don't generate distinct `Region::Body` lifetimes inside function bodies; use `Region::Erased` instead.
403    #[clap(long)]
404    #[serde(default)]
405    pub erase_body_lifetimes: bool,
406    /// Skip the typecheck passes.
407    #[clap(long)]
408    #[serde(default)]
409    pub no_typecheck: bool,
410    /// Don't normalize associated types.
411    #[clap(long)]
412    #[serde(default)]
413    pub no_normalize: bool,
414    /// Don't compute a stable order for declarations.
415    #[clap(long)]
416    #[serde(default)]
417    pub no_reorder_decls: bool,
418    /// Don't compute type layout guarantees.
419    #[clap(long)]
420    #[serde(default)]
421    pub no_compute_layout_guarantees: bool,
422    /// Panic on the first error. This is useful for debugging.
423    #[clap(long)]
424    #[serde(default)]
425    pub abort_on_error: bool,
426    /// Consider any warnings to be errors.
427    #[clap(long)]
428    #[serde(default)]
429    pub error_on_warnings: bool,
430
431    /// Named builtin sets of options.
432    #[clap(long)]
433    #[arg(value_enum)]
434    pub preset: Option<Preset>,
435}
436
437/// The MIR stage to use. This is only relevant for the current crate: for dependencies, only mir
438/// optimized is available (or mir elaborated for consts).
439#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
440#[derive(ValueEnum)]
441#[derive(Serialize, Deserialize)]
442pub enum MirLevel {
443    /// The MIR just after MIR lowering.
444    Built,
445    /// The MIR after const promotion. This is the MIR used by the borrow-checker.
446    Promoted,
447    /// The MIR after drop elaboration. This is the first MIR to include all the runtime
448    /// information.
449    Elaborated,
450    /// The MIR after optimizations. Charon disables all the optimizations it can, so this is
451    /// sensibly the same MIR as the elaborated MIR.
452    Optimized,
453}
454
455/// Presets to make it easier to tweak options without breaking dependent projects. Eventually we
456/// should define semantically-meaningful presets instead of project-specific ones.
457#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
458#[derive(ValueEnum)]
459#[derive(Serialize, Deserialize)]
460#[non_exhaustive]
461pub enum Preset {
462    /// The default translation used before May 2025. After that, many passes were made optional
463    /// and disabled by default.
464    OldDefaults,
465    /// Emit the MIR as unmodified as possible. This is very imperfect for now, we should make more
466    /// passes optional.
467    RawMir,
468    /// Skip as many optional transformations as possible.
469    Fast,
470    Aeneas,
471    Eurydice,
472    Soteria,
473    Tests,
474}
475
476/// How to handle constants and statics.
477#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
478#[derive(ValueEnum)]
479#[derive(Serialize, Deserialize)]
480pub enum ConstHandling {
481    /// Keep consts as calls to their initializer with `ConstantExprKind::Call`, without attempting
482    /// to do any const-evaluation. This is the default.
483    #[default]
484    Initializers,
485    /// Try evaluating consts and statics to their final value. If evaluation fails, we fall back to the
486    /// initializer call.
487    Values,
488    /// Try evaluating consts and statics to raw bytes, using `ConstantExprKind::RawMemory`. If
489    /// evaluation fails, we fall back to the initializer call.
490    Bytes,
491}
492
493#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
494#[derive(ValueEnum)]
495#[derive(Serialize, Deserialize)]
496pub enum MonomorphizeMut {
497    /// Monomorphize any item instantiated with `&mut`.
498    #[default]
499    All,
500    /// Monomorphize all non-typedecl items instantiated with `&mut`.
501    ExceptTypes,
502}
503
504#[derive(Debug, Copy, Clone, PartialEq, Eq)]
505#[derive(ValueEnum)]
506#[derive(Serialize, Deserialize)]
507pub enum SerializationFormatArg {
508    Json,
509    Postcard,
510    #[value(name = "minirust")]
511    MiniRust,
512    #[cfg_attr(feature = "charon_on_charon", charon::rename("AllFormats"))]
513    All,
514}
515
516#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
517#[derive(ValueEnum)]
518#[derive(Serialize, Deserialize)]
519pub enum SerializationFormat {
520    #[default]
521    Json,
522    Postcard,
523    #[value(name = "minirust")]
524    MiniRust,
525}
526
527impl SerializationFormatArg {
528    pub fn as_format(self) -> Option<SerializationFormat> {
529        match self {
530            SerializationFormatArg::Json => Some(SerializationFormat::Json),
531            SerializationFormatArg::Postcard => Some(SerializationFormat::Postcard),
532            SerializationFormatArg::MiniRust => Some(SerializationFormat::MiniRust),
533            SerializationFormatArg::All => None,
534        }
535    }
536}
537
538impl From<SerializationFormat> for SerializationFormatArg {
539    fn from(format: SerializationFormat) -> SerializationFormatArg {
540        match format {
541            SerializationFormat::Json => SerializationFormatArg::Json,
542            SerializationFormat::Postcard => SerializationFormatArg::Postcard,
543            SerializationFormat::MiniRust => SerializationFormatArg::MiniRust,
544        }
545    }
546}
547
548impl SerializationFormat {
549    pub fn output_extension(self, ullbc: bool) -> &'static str {
550        match (ullbc, self) {
551            (true, SerializationFormat::Json) => "ullbc",
552            (false, SerializationFormat::Json) => "llbc",
553            (true, SerializationFormat::Postcard) => "ullbc.postcard",
554            (false, SerializationFormat::Postcard) => "llbc.postcard",
555            (_, SerializationFormat::MiniRust) => "minirust.json",
556        }
557    }
558}
559
560impl CliOpts {
561    pub fn apply_preset(&mut self) {
562        if let Some(preset) = self.preset {
563            match preset {
564                Preset::OldDefaults => {
565                    self.inline_anon_consts = true;
566                    self.treat_box_as_builtin = true;
567                    self.hide_allocator = true;
568                    self.ops_to_function_calls = true;
569                    self.index_to_function_calls = true;
570                    self.reconstruct_fallible_operations = true;
571                    self.reconstruct_asserts = true;
572                    self.reconstruct_panic_calls = true;
573                    self.reconstruct_matches = true;
574                    self.unbind_item_vars = true;
575                    self.duplicate_defaulted_methods = true;
576                }
577                Preset::RawMir => {
578                    self.extract_opaque_bodies = true;
579                    self.raw_consts = true;
580                    self.ullbc = true;
581                }
582                Preset::Fast => {
583                    self.ullbc = true;
584                    self.no_typecheck = true;
585                    self.no_normalize = true;
586                    self.no_reorder_decls = true;
587                    self.no_compute_layout_guarantees = true;
588                    self.hide_marker_traits = true;
589                    self.raw_consts = true;
590                }
591                Preset::Aeneas => {
592                    self.lift_associated_types.push("*".to_owned());
593                    self.treat_box_as_builtin = true;
594                    self.ops_to_function_calls = true;
595                    self.index_to_function_calls = true;
596                    self.reconstruct_fallible_operations = true;
597                    self.reconstruct_panic_calls = true;
598                    self.reconstruct_asserts = true;
599                    self.reconstruct_matches = true;
600                    self.hide_marker_traits = true;
601                    self.hide_allocator = true;
602                    self.remove_unused_self_clauses = true;
603                    self.remove_adt_clauses = true;
604                    self.unbind_item_vars = true;
605                    self.deallocate_all_locals = true;
606                    self.no_gen_tuple_structs = true;
607                }
608                Preset::Eurydice => {
609                    self.inline_anon_consts = true;
610                    self.hide_allocator = true;
611                    self.treat_box_as_builtin = true;
612                    self.reconstruct_fallible_operations = true;
613                    self.reconstruct_panic_calls = true;
614                    self.reconstruct_asserts = true;
615                    self.reconstruct_matches = true;
616                    self.lift_associated_types.push("*".to_owned());
617                    self.unbind_item_vars = true;
618                    self.duplicate_defaulted_methods = true;
619                    // Eurydice doesn't support opaque vtables it seems?
620                    self.include.push("core::marker::MetaSized".to_owned());
621                }
622                Preset::Soteria => {
623                    self.desugar_drops = true;
624                    self.extract_opaque_bodies = true;
625                    self.mir = Some(MirLevel::Elaborated);
626                    self.reconstruct_fallible_operations = true;
627                    self.reconstruct_asserts = true;
628                    self.monomorphize = true;
629                    self.no_normalize = true;
630                    self.no_typecheck = true;
631                    self.no_reorder_decls = true;
632                    self.no_compute_layout_guarantees = true;
633                    self.erase_body_lifetimes = true;
634                    self.no_doc_comments = true;
635                    self.precise_drops = true;
636                    self.consts = Some(ConstHandling::Values);
637                    self.ullbc = true;
638                }
639                Preset::Tests => {
640                    self.inline_anon_consts = true;
641                    self.no_dedup_serialized_ast = true; // Helps debug
642                    self.treat_box_as_builtin = true;
643                    self.hide_allocator = true;
644                    self.reconstruct_fallible_operations = true;
645                    self.reconstruct_panic_calls = true;
646                    self.reconstruct_asserts = true;
647                    self.reconstruct_matches = true;
648                    if !self.desugar_drops {
649                        self.resugar_drops = true;
650                    }
651                    if !self.monomorphize {
652                        self.ops_to_function_calls = true;
653                        self.index_to_function_calls = true;
654                    }
655                    self.duplicate_defaulted_methods = true;
656                    self.deallocate_all_locals = true;
657                    self.rustc_args.push("--edition=2021".to_owned());
658                    self.rustc_args
659                        .push("-Zcrate-attr=feature(register_tool)".to_owned());
660                    self.rustc_args
661                        .push("-Zcrate-attr=register_tool(charon)".to_owned());
662                    self.exclude.push("core::fmt".to_owned());
663                    if self.extract_opaque_bodies {
664                        self.exclude
665                            .extend(["core::array".to_owned(), "core::slice::index".to_owned()]);
666                    }
667                }
668            }
669        }
670
671        if self.run_with_minirust || matches!(self.format, Some(SerializationFormatArg::MiniRust)) {
672            self.monomorphize = true;
673            self.ullbc = true;
674            self.precise_drops = true;
675            self.desugar_drops = true;
676            self.deallocate_all_locals = true;
677            self.treat_box_as_builtin = true;
678            self.extract_opaque_bodies = true;
679            self.consts = Some(ConstHandling::Bytes);
680            self.mir = Some(
681                self.mir
682                    .unwrap_or(MirLevel::Elaborated)
683                    .max(MirLevel::Elaborated),
684            );
685        }
686    }
687
688    /// Check that the options are meaningful
689    pub fn validate(&self) -> anyhow::Result<()> {
690        if self.dest_dir.is_some() {
691            display_unspanned_error(
692                Level::WARNING,
693                "`--dest` is deprecated, use `--dest-file` instead",
694            )
695        }
696
697        if self.remove_adt_clauses && self.lift_associated_types.is_empty() {
698            anyhow::bail!(
699                "`--remove-adt-clauses` should be used with `--lift-associated-types='*'` \
700                to avoid missing clause errors",
701            )
702        }
703        if matches!(self.monomorphize_mut, Some(MonomorphizeMut::ExceptTypes))
704            && !self.remove_adt_clauses
705        {
706            anyhow::bail!(
707                "`--monomorphize-mut=except-types` should be used with `--remove-adt-clauses` \
708                to avoid generics mismatches"
709            )
710        }
711        if self.no_gen_tuple_structs && self.monomorphize {
712            anyhow::bail!(
713                "`--no-gen-tuple-structs` is not compatible with `--monomorphize`, as \
714                monomorphization requires each tuple to have its own type declaration"
715            )
716        }
717        if self.monomorphize && (self.ops_to_function_calls || self.index_to_function_calls) {
718            anyhow::bail!(
719                "`--monomorphize` is not compatible with `--ops-to-function-calls` or \
720                  `--index-to-function-calls`"
721            )
722        }
723        if self.no_serialize && self.format.is_some() {
724            anyhow::bail!(
725                "`--no-serialize` is not compatible with `--format`, the format is only relevant if we serialize"
726            );
727        }
728        if self.run_with_minirust || matches!(self.format, Some(SerializationFormatArg::MiniRust)) {
729            if !cfg!(feature = "minirust") {
730                anyhow::bail!(
731                    "MiniRust output is unavailable because Charon was built without the `minirust` feature"
732                );
733            }
734            if !self.targets.is_empty() {
735                anyhow::bail!("MiniRust output does not support multi-target translation");
736            }
737        }
738        if self.resugar_drops && self.desugar_drops {
739            anyhow::bail!("`--desugar-drops` and `--resugar-drops` are mutually incompatible")
740        }
741        if self.collect_instantiated_layouts && self.monomorphize {
742            anyhow::bail!(
743                "`--collect-instantiated-layouts` is not compatible with `--monomorphize`, we \
744                  already translate instantiated layouts with it. "
745            )
746        }
747        Ok(())
748    }
749
750    fn target_filename(
751        &self,
752        path_base: PathBuf,
753        format: SerializationFormat,
754    ) -> (PathBuf, SerializationFormat) {
755        let extension = format.output_extension(self.ullbc);
756        let target_filename = path_base.with_added_extension(extension);
757        (target_filename, format)
758    }
759
760    pub fn targets(&self, crate_name: &str) -> Vec<(PathBuf, SerializationFormat)> {
761        if self.no_serialize {
762            return vec![];
763        }
764
765        let format = self.format.unwrap_or(SerializationFormatArg::Json);
766        let mut path_base = self.dest_dir.clone().unwrap_or_default();
767        path_base.push(crate_name);
768
769        match format.as_format() {
770            Some(format) => match self.dest_file.clone() {
771                Some(dest) => vec![(dest, format)],
772                None => vec![self.target_filename(path_base, format)],
773            },
774            None => {
775                let path_base = self.dest_file.clone().unwrap_or(path_base);
776                vec![
777                    self.target_filename(path_base.clone(), SerializationFormat::Json),
778                    self.target_filename(path_base, SerializationFormat::Postcard),
779                ]
780            }
781        }
782    }
783}
784
785/// Predicates that determine wihch items to use as starting point for translation.
786#[derive(Debug, Clone, EnumAsInner)]
787pub enum StartFrom {
788    /// Item identified by a pattern/path. If strict is true, then failing to
789    /// find an item matching the pattern is an error; otherwise, we just ignore this pattern.
790    Pattern { pattern: NamePattern, strict: bool },
791    /// Item annotated with the given attribute.
792    Attribute(String),
793    /// Item marked `pub`. Note that this does not take accessibility into account; a
794    /// non-reexported `pub` item will be included here.
795    Pub,
796    /// The global constructors of the target.
797    GlobalCtors,
798}
799
800/// The options that control translation and transformation.
801pub struct TranslateOptions {
802    /// Items from which to start translation.
803    pub start_from: Vec<StartFrom>,
804    /// Whether we are using `--merge-crates`, which affects what items we start translating from.
805    pub merge_crates: bool,
806    /// The level at which to extract the MIR
807    pub mir_level: MirLevel,
808    /// Usually we skip the provided methods that aren't used. When this flag is on, we translate
809    /// them all.
810    pub translate_all_methods: bool,
811    /// Translate the vtable of every trait impl, not just those used in an unsizing coercion.
812    pub eager_vtables: bool,
813    /// Translate the definitions that extern functions link to.
814    pub link_extern_fns: bool,
815    /// Duplicate trait default methods into impls that use them.
816    pub duplicate_defaulted_methods: bool,
817    /// If `Some(_)`, run the partial mutability monomorphization pass. The contained enum
818    /// indicates whether to partially monomorphize types.
819    pub monomorphize_mut: Option<MonomorphizeMut>,
820    /// Record the layouts of the instantiated poly ADTs in `TypeDecl::monomorphic_layouts`.
821    pub collect_instantiated_layouts: bool,
822    /// Whether to hide various marker traits such as `*Sized` and `Destruct` anywhere they show
823    /// up.
824    pub hide_marker_traits: bool,
825    /// Hide the `A` type parameter on standard library containers (`Box`, `Vec`, etc).
826    pub hide_allocator: bool,
827    /// Don't translate doc comments.
828    pub no_doc_comments: bool,
829    /// List of traits to remove any mentions of. Influenced by `hide_marker_traits`,
830    /// `hide_allocator`, and `precise_drops`.
831    pub hide_traits: Vec<NamePattern>,
832    /// Remove trait clauses that aren't ultimately used anywhere. This is potentially incorrect as
833    /// sometimes the mere presence of a trait clause is used to justify an operation, e.g. copying
834    /// `Copy` data using `unsafe`.
835    pub remove_unused_clauses: bool,
836    /// Remove unused `Self: Trait` clauses on method declarations.
837    pub remove_unused_self_clauses: bool,
838    /// Remove trait clauses attached to type declarations.
839    pub remove_adt_clauses: bool,
840    /// Monomorphize code using hax's instantiation mechanism.
841    pub monomorphize_with_hax: bool,
842    /// Extract the unstructured LLBC (i.e., don't reconstruct the control-flow)
843    pub ullbc: bool,
844    /// Reconstruct the control-flow by breaking forward out of enclosing loops instead of
845    /// duplicating the blocks reachable from several branches.
846    pub no_code_duplication: bool,
847    /// Transform array-to-slice unsizing and repeat expressions into standard library function
848    /// calls in LLBC.
849    pub ops_to_function_calls: bool,
850    /// Transform array/slice indexing into standard library function calls in LLBC.
851    pub index_to_function_calls: bool,
852    /// Treat `Box<T>` as if it was a built-in type.
853    pub treat_box_as_builtin: bool,
854    /// Make all tuples refer to the single opaque `TypeDeclId::UNIT` declaration, and store their
855    /// field types in their generic arguments.
856    pub no_gen_tuple_structs: bool,
857    /// Don't inline or evaluate constants.
858    pub raw_consts: bool,
859    /// Inline anonymous constants.
860    pub inline_anon_consts: bool,
861    /// How much to evaluate constants and statics.
862    pub consts: ConstHandling,
863    /// Replace "bound checks followed by UB-on-overflow operation" with the corresponding
864    /// panic-on-overflow operation. This loses unwinding information.
865    pub reconstruct_fallible_operations: bool,
866    /// Replace calls to built-in panic functions with a `Panic` terminator.
867    pub reconstruct_panic_calls: bool,
868    /// Replace `if x { panic() }` with `assert(x)`.
869    pub reconstruct_asserts: bool,
870    /// Reconstruct matches on enum variants.
871    pub reconstruct_matches: bool,
872    /// Insert the `StorageDead`s that MIR omits for some locals.
873    pub deallocate_all_locals: bool,
874    // Use `DeBruijnVar::Free` for the variables bound in item signatures.
875    pub unbind_item_vars: bool,
876    /// List of patterns to assign a given opacity to. Same as the corresponding `TranslateOptions`
877    /// field.
878    pub item_opacities: Vec<(NamePattern, ItemOpacity)>,
879    /// List of traits for which we transform associated types to type parameters.
880    pub lift_associated_types: Vec<NamePattern>,
881    /// Use `Region::Erased` instead of fresh `Region::Body` lifetimes inside function bodies.
882    pub erase_body_lifetimes: bool,
883    /// Skip the typecheck passes.
884    pub no_typecheck: bool,
885    /// Don't normalize associated types.
886    pub no_normalize: bool,
887    /// Don't reorder declarations and compute recursive declaration groups.
888    pub no_reorder_decls: bool,
889    /// Don't compute type layout guarantees.
890    pub no_compute_layout_guarantees: bool,
891    /// Transform Drop to Call drop_glue
892    pub desugar_drops: bool,
893    /// Reconstruct conditional drops from rustc drop flags.
894    pub resugar_drops: bool,
895    /// Detect rustc drop flags.
896    pub detect_drop_flags: bool,
897    /// Add `Destruct` bounds to all generic params.
898    pub add_destruct_bounds: bool,
899}
900
901impl TranslateOptions {
902    pub fn new(error_ctx: &mut ErrorCtx, options: &CliOpts) -> Self {
903        let mut parse_pattern = |s: &str| -> Result<_, Error> {
904            match NamePattern::parse(s) {
905                Ok(p) => Ok(p),
906                Err(e) => raise_error!(error_ctx, no_crate, "failed to parse pattern `{s}` ({e})"),
907            }
908        };
909
910        let mut mir_level = options.mir.unwrap_or(MirLevel::Promoted);
911        if options.precise_drops {
912            mir_level = std::cmp::max(mir_level, MirLevel::Elaborated);
913        }
914
915        let mut start_from = options
916            .start_from
917            .iter()
918            .filter_map(|path| parse_pattern(path).ok())
919            .map(|p| StartFrom::Pattern {
920                pattern: p,
921                strict: true,
922            })
923            .collect_vec();
924        start_from.extend(
925            options
926                .start_from_if_exists
927                .iter()
928                .filter_map(|path| parse_pattern(path).ok())
929                .map(|p| StartFrom::Pattern {
930                    pattern: p,
931                    strict: false,
932                }),
933        );
934        for attr in options.start_from_attribute.iter().cloned() {
935            start_from.push(StartFrom::Attribute(attr));
936        }
937        if options.start_from_pub {
938            start_from.push(StartFrom::Pub);
939        }
940        if options.start_from_global_ctors {
941            start_from.push(StartFrom::GlobalCtors);
942        }
943        if start_from.is_empty() {
944            start_from.push(StartFrom::Pattern {
945                pattern: parse_pattern("crate").unwrap(),
946                strict: true,
947            });
948        }
949
950        let hide_traits = options
951            .hide_marker_traits
952            .then_some([
953                "core::marker::Sized",
954                "core::marker::MetaSized",
955                "core::marker::PointeeSized",
956                "core::marker::Tuple",
957                "core::clone::TrivialClone",
958            ])
959            .into_iter()
960            .flatten()
961            .chain(options.hide_allocator.then_some("core::alloc::Allocator"))
962            .filter_map(|s| parse_pattern(s).ok())
963            .collect_vec();
964
965        let item_opacities = {
966            use ItemOpacity::*;
967            let mut opacities = vec![];
968
969            // This is how to treat items that don't match any other pattern.
970            if options.extract_opaque_bodies {
971                opacities.push(("_".to_string(), Transparent));
972            } else {
973                opacities.push(("_".to_string(), Foreign));
974            }
975
976            if options.treat_box_as_builtin {
977                // Include this item's body, we inline it in a pass.
978                opacities.push((
979                    "alloc::boxed::box_assume_init_into_vec_unsafe".to_string(),
980                    Transparent,
981                ));
982            }
983
984            // We always include the items from the crate.
985            opacities.push(("crate".to_owned(), Transparent));
986
987            for pat in options.include.iter() {
988                opacities.push((pat.to_string(), Transparent));
989            }
990            for pat in options.opaque.iter() {
991                opacities.push((pat.to_string(), Opaque));
992            }
993            if options.run_with_minirust
994                || matches!(options.format, Some(SerializationFormatArg::MiniRust))
995            {
996                // This is the `intrinsics` crate used by MiniRust's `minimize` test suite. We make
997                // it opaque because we replace the function bodies so we don't need to translate
998                // them.
999                opacities.push(("intrinsics".to_owned(), Opaque));
1000                // The MiniRust translation models these as a plain unwind.
1001                for panic_fn in [
1002                    "core::panicking::panic",
1003                    "core::panicking::panic_fmt",
1004                    "core::panicking::panic_bounds_check",
1005                    "core::panicking::panic_misaligned_pointer_dereference",
1006                    "core::panicking::panic_null_pointer_dereference",
1007                    "core::panicking::panic_null_reference_constructed",
1008                    "core::panicking::panic_invalid_enum_construction",
1009                    "core::panicking::panic_cannot_unwind",
1010                    "core::panicking::panic_in_cleanup",
1011                    "core::panic::panic_const",
1012                ] {
1013                    opacities.push((panic_fn.to_owned(), Opaque));
1014                }
1015            }
1016            for pat in options.exclude.iter() {
1017                opacities.push((pat.to_string(), Invisible));
1018            }
1019
1020            for trait_name in &hide_traits {
1021                opacities.push((trait_name.to_string(), Invisible));
1022            }
1023
1024            // Hide trait impls and defs for the excluded traits.
1025            let hide_traits = hide_traits
1026                .iter()
1027                .cloned()
1028                .flat_map(|pat| [pat.clone(), NamePattern::impl_for(pat)])
1029                .map(|pat| (pat, Invisible));
1030            opacities
1031                .into_iter()
1032                .filter_map(|(s, opacity)| parse_pattern(&s).ok().map(|pat| (pat, opacity)))
1033                .chain(hide_traits)
1034                .collect()
1035        };
1036
1037        let lift_associated_types = options
1038            .lift_associated_types
1039            .iter()
1040            .filter_map(|s| parse_pattern(s).ok())
1041            .collect();
1042
1043        TranslateOptions {
1044            start_from,
1045            merge_crates: options.merge_crates,
1046            mir_level,
1047            monomorphize_mut: options.monomorphize_mut,
1048            collect_instantiated_layouts: options.collect_instantiated_layouts,
1049            hide_marker_traits: options.hide_marker_traits,
1050            hide_allocator: options.hide_allocator,
1051            no_doc_comments: options.no_doc_comments,
1052            hide_traits,
1053            remove_unused_clauses: options.remove_unused_clauses,
1054            remove_unused_self_clauses: options.remove_unused_self_clauses,
1055            remove_adt_clauses: options.remove_adt_clauses,
1056            monomorphize_with_hax: options.monomorphize,
1057            ullbc: options.ullbc,
1058            no_code_duplication: options.no_code_duplication,
1059            ops_to_function_calls: options.ops_to_function_calls,
1060            index_to_function_calls: options.index_to_function_calls,
1061            item_opacities,
1062            treat_box_as_builtin: options.treat_box_as_builtin,
1063            no_gen_tuple_structs: options.no_gen_tuple_structs,
1064            raw_consts: options.raw_consts,
1065            inline_anon_consts: options.inline_anon_consts,
1066            consts: options.consts.unwrap_or_default(),
1067            reconstruct_fallible_operations: options.reconstruct_fallible_operations,
1068            reconstruct_panic_calls: options.reconstruct_panic_calls,
1069            reconstruct_asserts: options.reconstruct_asserts,
1070            reconstruct_matches: options.reconstruct_matches,
1071            deallocate_all_locals: options.deallocate_all_locals,
1072            lift_associated_types,
1073            unbind_item_vars: options.unbind_item_vars,
1074            translate_all_methods: options.translate_all_methods,
1075            eager_vtables: options.eager_vtables,
1076            link_extern_fns: options.link_extern_fns,
1077            duplicate_defaulted_methods: options.duplicate_defaulted_methods,
1078            erase_body_lifetimes: options.erase_body_lifetimes,
1079            no_typecheck: options.no_typecheck,
1080            no_normalize: options.no_normalize,
1081            no_reorder_decls: options.no_reorder_decls,
1082            no_compute_layout_guarantees: options.no_compute_layout_guarantees,
1083            desugar_drops: options.desugar_drops,
1084            resugar_drops: options.resugar_drops,
1085            detect_drop_flags: options.detect_drop_flags,
1086            add_destruct_bounds: options.precise_drops,
1087        }
1088    }
1089
1090    /// Find the opacity requested for the given name. This does not take into account
1091    /// `#[charon::opaque]` annotations, only cli parameters.
1092    #[tracing::instrument(skip(self, krate), ret)]
1093    pub fn opacity_for_name(&self, krate: &TranslatedCrate, name: &Name) -> ItemOpacity {
1094        // Builtin names (str, tuples) are always transparent.
1095        if name.is_builtin() {
1096            return ItemOpacity::Transparent;
1097        }
1098        // Find the most precise pattern that matches this name. There is always one since
1099        // the list contains the `_` pattern. If there are conflicting settings for this item, we
1100        // err on the side of being more opaque.
1101        let (_, opacity) = self
1102            .item_opacities
1103            .iter()
1104            .filter(|(pat, _)| pat.matches(krate, name))
1105            .max()
1106            .unwrap();
1107        *opacity
1108    }
1109}