Skip to main content

charon_lib/
options.rs

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