charon_lib/
options.rs

1//! The options that control charon behavior.
2use annotate_snippets::Level;
3use clap::ValueEnum;
4use indoc::indoc;
5use serde::{Deserialize, Serialize};
6use std::path::PathBuf;
7
8use crate::{
9    ast::*,
10    errors::{ErrorCtx, display_unspanned_error},
11    name_matcher::NamePattern,
12    raise_error, register_error,
13};
14
15/// The name of the environment variable we use to save the serialized Cli options
16/// when calling charon-driver from cargo-charon.
17pub const CHARON_ARGS: &str = "CHARON_ARGS";
18
19// This structure is used to store the command-line instructions.
20// We automatically derive a command-line parser based on this structure.
21// Note that the doc comments are used to generate the help message when using
22// `--help`.
23//
24// Note that because we need to transmit the options to the charon driver,
25// we store them in a file before calling this driver (hence the `Serialize`,
26// `Deserialize` options).
27#[derive(Debug, Default, Clone, clap::Args, PartialEq, Eq, Serialize, Deserialize)]
28#[clap(name = "Charon")]
29#[charon::rename("cli_options")]
30pub struct CliOpts {
31    /// Extract the unstructured LLBC (i.e., don't reconstruct the control-flow)
32    #[clap(long)]
33    #[serde(default)]
34    pub ullbc: bool,
35    /// Whether to precisely translate drops and drop-related code. For this, we add explicit
36    /// `Destruct` bounds to all generic parameters, set the MIR level to at least `elaborated`,
37    /// and attempt to retrieve drop glue for all types.
38    ///
39    /// This option is known to cause panics inside rustc, because their drop handling is not
40    /// design to work on polymorphic types. To silence the warning, pass appropriate `--opaque
41    /// '{impl core::marker::Destruct for some::Type}'` options.
42    ///
43    /// Without this option, drops may be "conditional" and we may lack information about what code
44    /// is run on drop in a given polymorphic function body.
45    #[clap(long)]
46    #[serde(default)]
47    pub precise_drops: bool,
48    /// If activated, this skips borrow-checking of the crate.
49    #[clap(long)]
50    #[serde(default)]
51    pub skip_borrowck: bool,
52    /// The MIR stage to extract. This is only relevant for the current crate; for dpendencies only
53    /// MIR optimized is available.
54    #[arg(long)]
55    pub mir: Option<MirLevel>,
56    /// Extra flags to pass to rustc.
57    #[clap(long = "rustc-arg")]
58    #[serde(default)]
59    pub rustc_args: Vec<String>,
60    /// Monomorphize the items encountered when possible. Generic items found in the crate are
61    /// skipped. To only translate a particular call graph, use `--start-from`. Note: this doesn't
62    /// currently support `dyn Trait`.
63    #[clap(long, visible_alias = "mono")]
64    #[serde(default)]
65    pub monomorphize: bool,
66    /// Partially monomorphize items to make it so that no item is ever monomorphized with a
67    /// mutable reference (or type containing one); said differently, so that the presence of
68    /// mutable references in a type is independent of its generics. This is used by Aeneas.
69    #[clap(
70        long,
71        value_name("INCLUDE_TYPES"),
72        num_args(0..=1),
73        require_equals(true),
74        default_missing_value("all"),
75    )]
76    #[serde(default)]
77    pub monomorphize_mut: Option<MonomorphizeMut>,
78
79    /// A list of item paths to use as starting points for the translation. We will translate these
80    /// items and any items they refer to, according to the opacity rules. When absent, we start
81    /// from the path `crate` (which translates the whole crate).
82    #[clap(long, value_delimiter = ',')]
83    #[serde(default)]
84    pub start_from: Vec<String>,
85    /// Whitelist of items to translate. These use the name-matcher syntax.
86    #[clap(
87        long,
88        help = indoc!("
89            Whitelist of items to translate. These use the name-matcher syntax (note: this differs
90            a bit from the ocaml NameMatcher).
91
92            Note: This is very rough at the moment. E.g. this parses `u64` as a path instead of the
93            built-in type. It is also not possible to filter a trait impl (this will only filter
94            its methods). Please report bugs or missing features.
95
96            Examples:
97              - `crate::module1::module2::item`: refers to this item and all its subitems (e.g.
98                  submodules or trait methods);
99              - `crate::module1::module2::item::_`: refers only to the subitems of this item;
100              - `core::convert::{impl core::convert::Into<_> for _}`: retrieve the body of this
101                  very useful impl;
102
103            When multiple patterns in the `--include` and `--opaque` options match the same item,
104            the most precise pattern wins. E.g.: `charon --opaque crate::module --include
105            crate::module::_` makes the `module` opaque (we won't explore its contents), but the
106            items in it transparent (we will translate them if we encounter them.)
107    "))]
108    #[serde(default)]
109    #[charon::rename("included")]
110    pub include: Vec<String>,
111    /// Blacklist of items to keep opaque. Works just like `--include`, see the doc there.
112    #[clap(long)]
113    #[serde(default)]
114    pub opaque: Vec<String>,
115    /// Blacklist of items to not translate at all. Works just like `--include`, see the doc there.
116    #[clap(long)]
117    #[serde(default)]
118    pub exclude: Vec<String>,
119    /// Usually we skip the bodies of foreign methods and structs with private fields. When this
120    /// flag is on, we don't.
121    #[clap(long)]
122    #[serde(default)]
123    pub extract_opaque_bodies: bool,
124    /// Usually we skip the provided methods that aren't used. When this flag is on, we translate
125    /// them all.
126    #[clap(long)]
127    #[serde(default)]
128    pub translate_all_methods: bool,
129
130    /// Transforma the associate types of traits to be type parameters instead. This takes a list
131    /// of name patterns of the traits to transform, using the same syntax as `--include`.
132    #[clap(long)]
133    #[serde(default)]
134    pub remove_associated_types: Vec<String>,
135    /// Whether to hide various marker traits such as `Sized`, `Sync`, `Send` and `Destruct`
136    /// anywhere they show up. This can considerably speed up translation.
137    #[clap(long)]
138    #[serde(default)]
139    pub hide_marker_traits: bool,
140    /// Remove trait clauses from type declarations. Must be combined with
141    /// `--remove-associated-types` for type declarations that use trait associated types in their
142    /// fields, otherwise this will result in errors.
143    #[clap(long)]
144    #[serde(default)]
145    pub remove_adt_clauses: bool,
146    /// Hide the `A` type parameter on standard library containers (`Box`, `Vec`, etc).
147    #[clap(long)]
148    #[serde(default)]
149    pub hide_allocator: bool,
150    /// Trait method declarations take a `Self: Trait` clause as parameter, so that they can be
151    /// reused by multiple trait impls. This however causes trait definitions to be mutually
152    /// recursive with their method declarations. This flag removes `Self` clauses that aren't used
153    /// to break this mutual recursion when possible.
154    #[clap(long)]
155    #[serde(default)]
156    pub remove_unused_self_clauses: bool,
157
158    /// Transform precise drops to the equivalent `drop_in_place(&raw mut p)` call.
159    #[clap(long)]
160    #[serde(default)]
161    pub desugar_drops: bool,
162    /// Transform array-to-slice unsizing, repeat expressions, and raw pointer construction into
163    /// builtin functions in ULLBC.
164    #[clap(long)]
165    #[serde(default)]
166    pub ops_to_function_calls: bool,
167    /// Transform array/slice indexing into builtin functions in ULLBC. Note that this may
168    /// introduce UB since it creates references that were not normally created, including when
169    /// indexing behind a raw pointer.
170    #[clap(long)]
171    #[serde(default)]
172    pub index_to_function_calls: bool,
173    /// Treat `Box<T>` as if it was a built-in type.
174    #[clap(long)]
175    #[serde(default)]
176    pub treat_box_as_builtin: bool,
177    /// Do not inline or evaluate constants.
178    #[clap(long)]
179    #[serde(default)]
180    pub raw_consts: bool,
181    /// Replace "bound checks followed by UB-on-overflow operation" with the corresponding
182    /// panic-on-overflow operation. This loses unwinding information.
183    #[clap(long)]
184    #[serde(default)]
185    pub reconstruct_fallible_operations: bool,
186    /// Replace "if x { panic() }" with "assert(x)".
187    #[clap(long)]
188    #[serde(default)]
189    pub reconstruct_asserts: bool,
190    /// Use `DeBruijnVar::Free` for the variables bound in item signatures, instead of
191    /// `DeBruijnVar::Bound` everywhere. This simplifies the management of generics for projects
192    /// that don't intend to manipulate them too much.
193    #[clap(long)]
194    #[serde(default)]
195    pub unbind_item_vars: bool,
196
197    /// Pretty-print the ULLBC immediately after extraction from MIR.
198    #[clap(long)]
199    #[serde(default)]
200    pub print_original_ullbc: bool,
201    /// Pretty-print the ULLBC after applying the micro-passes (before serialization/control-flow reconstruction).
202    #[clap(long)]
203    #[serde(default)]
204    pub print_ullbc: bool,
205    /// Pretty-print the LLBC just after we built it (i.e., immediately after loop reconstruction).
206    #[clap(long)]
207    #[serde(default)]
208    pub print_built_llbc: bool,
209    /// Pretty-print the final LLBC (after all the cleaning micro-passes).
210    #[clap(long)]
211    #[serde(default)]
212    pub print_llbc: bool,
213
214    /// The destination directory. Files will be generated as `<dest_dir>/<crate_name>.{u}llbc`,
215    /// unless `dest_file` is set. `dest_dir` defaults to the current directory.
216    #[clap(long = "dest", value_parser)]
217    #[serde(default)]
218    pub dest_dir: Option<PathBuf>,
219    /// The destination file. By default `<dest_dir>/<crate_name>.llbc`. If this is set we ignore
220    /// `dest_dir`.
221    #[clap(long, value_parser)]
222    #[serde(default)]
223    pub dest_file: Option<PathBuf>,
224    /// Don't deduplicate values (types, trait refs) in the .(u)llbc file. This makes the file easier to inspect.
225    #[clap(long)]
226    #[serde(default)]
227    pub no_dedup_serialized_ast: bool,
228    /// Don't serialize the final (U)LLBC to a file.
229    #[clap(long)]
230    #[serde(default)]
231    pub no_serialize: bool,
232    /// Panic on the first error. This is useful for debugging.
233    #[clap(long)]
234    #[serde(default)]
235    pub abort_on_error: bool,
236    /// Consider any warnings to be errors.
237    #[clap(long)]
238    #[serde(default)]
239    pub error_on_warnings: bool,
240
241    /// Named builtin sets of options.
242    #[clap(long)]
243    #[arg(value_enum)]
244    pub preset: Option<Preset>,
245}
246
247/// The MIR stage to use. This is only relevant for the current crate: for dependencies, only mir
248/// optimized is available (or mir elaborated for consts).
249#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize)]
250pub enum MirLevel {
251    /// The MIR just after MIR lowering.
252    Built,
253    /// The MIR after const promotion. This is the MIR used by the borrow-checker.
254    Promoted,
255    /// The MIR after drop elaboration. This is the first MIR to include all the runtime
256    /// information.
257    Elaborated,
258    /// The MIR after optimizations. Charon disables all the optimizations it can, so this is
259    /// sensibly the same MIR as the elaborated MIR.
260    Optimized,
261}
262
263/// Presets to make it easier to tweak options without breaking dependent projects. Eventually we
264/// should define semantically-meaningful presets instead of project-specific ones.
265#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize)]
266#[non_exhaustive]
267pub enum Preset {
268    /// The default translation used before May 2025. After that, many passes were made optional
269    /// and disabled by default.
270    OldDefaults,
271    /// Emit the MIR as unmodified as possible. This is very imperfect for now, we should make more
272    /// passes optional.
273    RawMir,
274    Aeneas,
275    Eurydice,
276    Soteria,
277    Tests,
278}
279
280#[derive(
281    Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize,
282)]
283pub enum MonomorphizeMut {
284    /// Monomorphize any item instantiated with `&mut`.
285    #[default]
286    All,
287    /// Monomorphize all non-typedecl items instantiated with `&mut`.
288    ExceptTypes,
289}
290
291impl CliOpts {
292    pub fn apply_preset(&mut self) {
293        if let Some(preset) = self.preset {
294            match preset {
295                Preset::OldDefaults => {
296                    self.treat_box_as_builtin = true;
297                    self.hide_allocator = true;
298                    self.ops_to_function_calls = true;
299                    self.index_to_function_calls = true;
300                    self.reconstruct_fallible_operations = true;
301                    self.reconstruct_asserts = true;
302                    self.unbind_item_vars = true;
303                }
304                Preset::RawMir => {
305                    self.extract_opaque_bodies = true;
306                    self.raw_consts = true;
307                    self.ullbc = true;
308                }
309                Preset::Aeneas => {
310                    self.remove_associated_types.push("*".to_owned());
311                    self.treat_box_as_builtin = true;
312                    self.ops_to_function_calls = true;
313                    self.index_to_function_calls = true;
314                    self.reconstruct_fallible_operations = true;
315                    self.reconstruct_asserts = true;
316                    self.hide_marker_traits = true;
317                    self.hide_allocator = true;
318                    self.remove_unused_self_clauses = true;
319                    self.unbind_item_vars = true;
320                    // Hide drop impls because they often involve nested borrows. which aeneas
321                    // doesn't handle yet.
322                    self.exclude.push("core::ops::drop::Drop".to_owned());
323                    self.exclude
324                        .push("{impl core::ops::drop::Drop for _}".to_owned());
325                }
326                Preset::Eurydice => {
327                    self.hide_allocator = true;
328                    self.treat_box_as_builtin = true;
329                    self.ops_to_function_calls = true;
330                    self.index_to_function_calls = true;
331                    self.reconstruct_fallible_operations = true;
332                    self.reconstruct_asserts = true;
333                    self.remove_associated_types.push("*".to_owned());
334                    self.unbind_item_vars = true;
335                    // Eurydice doesn't support opaque vtables it seems?
336                    self.include.push("core::marker::MetaSized".to_owned());
337                }
338                Preset::Soteria => {
339                    self.extract_opaque_bodies = true;
340                    self.monomorphize = true;
341                    self.mir = Some(MirLevel::Elaborated);
342                    self.ullbc = true;
343                }
344                Preset::Tests => {
345                    self.no_dedup_serialized_ast = true; // Helps debug
346                    self.treat_box_as_builtin = true;
347                    self.hide_allocator = true;
348                    self.reconstruct_fallible_operations = true;
349                    self.reconstruct_asserts = true;
350                    self.ops_to_function_calls = true;
351                    self.index_to_function_calls = true;
352                    self.rustc_args.push("--edition=2021".to_owned());
353                    self.rustc_args
354                        .push("-Zcrate-attr=feature(register_tool)".to_owned());
355                    self.rustc_args
356                        .push("-Zcrate-attr=register_tool(charon)".to_owned());
357                    self.exclude.push("core::fmt::Formatter".to_owned());
358                }
359            }
360        }
361    }
362
363    /// Check that the options are meaningful
364    pub fn validate(&self) -> anyhow::Result<()> {
365        if self.dest_dir.is_some() {
366            display_unspanned_error(
367                Level::WARNING,
368                "`--dest` is deprecated, use `--dest-file` instead",
369            )
370        }
371
372        if self.remove_adt_clauses && self.remove_associated_types.is_empty() {
373            anyhow::bail!(
374                "`--remove-adt-clauses` should be used with `--remove-associated-types='*'` \
375                to avoid missing clause errors",
376            )
377        }
378        if matches!(self.monomorphize_mut, Some(MonomorphizeMut::ExceptTypes))
379            && !self.remove_adt_clauses
380        {
381            anyhow::bail!(
382                "`--monomorphize-mut=except-types` should be used with `--remove-adt-clauses` \
383                to avoid generics mismatches"
384            )
385        }
386        Ok(())
387    }
388}
389
390/// The options that control translation and transformation.
391pub struct TranslateOptions {
392    /// Items from which to start translation.
393    pub start_from: Vec<NamePattern>,
394    /// The level at which to extract the MIR
395    pub mir_level: MirLevel,
396    /// Usually we skip the provided methods that aren't used. When this flag is on, we translate
397    /// them all.
398    pub translate_all_methods: bool,
399    /// If `Some(_)`, run the partial mutability monomorphization pass. The contained enum
400    /// indicates whether to partially monomorphize types.
401    pub monomorphize_mut: Option<MonomorphizeMut>,
402    /// Whether to hide various marker traits such as `Sized`, `Sync`, `Send` and `Destruct`
403    /// anywhere they show up.
404    pub hide_marker_traits: bool,
405    /// Remove trait clauses attached to type declarations.
406    pub remove_adt_clauses: bool,
407    /// Hide the `A` type parameter on standard library containers (`Box`, `Vec`, etc).
408    pub hide_allocator: bool,
409    /// Remove unused `Self: Trait` clauses on method declarations.
410    pub remove_unused_self_clauses: bool,
411    /// Monomorphize code using hax's instantiation mechanism.
412    pub monomorphize_with_hax: bool,
413    /// Transform array-to-slice unsizing, repeat expressions, and raw pointer construction into
414    /// builtin functions in ULLBC.
415    pub ops_to_function_calls: bool,
416    /// Transform array/slice indexing into builtin functions in ULLBC.
417    pub index_to_function_calls: bool,
418    /// Print the llbc just after control-flow reconstruction.
419    pub print_built_llbc: bool,
420    /// Treat `Box<T>` as if it was a built-in type.
421    pub treat_box_as_builtin: bool,
422    /// Don't inline or evaluate constants.
423    pub raw_consts: bool,
424    /// Replace "bound checks followed by UB-on-overflow operation" with the corresponding
425    /// panic-on-overflow operation. This loses unwinding information.
426    pub reconstruct_fallible_operations: bool,
427    /// Replace "if x { panic() }" with "assert(x)".
428    pub reconstruct_asserts: bool,
429    // Use `DeBruijnVar::Free` for the variables bound in item signatures.
430    pub unbind_item_vars: bool,
431    /// List of patterns to assign a given opacity to. Same as the corresponding `TranslateOptions`
432    /// field.
433    pub item_opacities: Vec<(NamePattern, ItemOpacity)>,
434    /// List of traits for which we transform associated types to type parameters.
435    pub remove_associated_types: Vec<NamePattern>,
436    /// Transform Drop to Call drop_in_place
437    pub desugar_drops: bool,
438    /// Add `Destruct` bounds to all generic params.
439    pub add_destruct_bounds: bool,
440    /// Translate drop glue for poly types, knowing that this may cause ICEs.
441    pub translate_poly_drop_glue: bool,
442}
443
444impl TranslateOptions {
445    pub fn new(error_ctx: &mut ErrorCtx, options: &CliOpts) -> Self {
446        let mut parse_pattern = |s: &str| match NamePattern::parse(s) {
447            Ok(p) => Ok(p),
448            Err(e) => {
449                raise_error!(
450                    error_ctx,
451                    crate(&TranslatedCrate::default()),
452                    Span::dummy(),
453                    "failed to parse pattern `{s}` ({e})"
454                )
455            }
456        };
457
458        let mut mir_level = options.mir.unwrap_or(MirLevel::Promoted);
459        if options.precise_drops {
460            mir_level = std::cmp::max(mir_level, MirLevel::Elaborated);
461        }
462
463        let start_from = if options.start_from.is_empty() {
464            vec![parse_pattern("crate").unwrap()]
465        } else {
466            options
467                .start_from
468                .iter()
469                .filter_map(|path| parse_pattern(&path).ok())
470                .collect()
471        };
472
473        let item_opacities = {
474            use ItemOpacity::*;
475            let mut opacities = vec![];
476
477            // This is how to treat items that don't match any other pattern.
478            if options.extract_opaque_bodies {
479                opacities.push(("_".to_string(), Transparent));
480            } else {
481                opacities.push(("_".to_string(), Foreign));
482            }
483
484            // We always include the items from the crate.
485            opacities.push(("crate".to_owned(), Transparent));
486
487            for pat in options.include.iter() {
488                opacities.push((pat.to_string(), Transparent));
489            }
490            for pat in options.opaque.iter() {
491                opacities.push((pat.to_string(), Opaque));
492            }
493            for pat in options.exclude.iter() {
494                opacities.push((pat.to_string(), Invisible));
495            }
496
497            if options.hide_allocator {
498                opacities.push((format!("core::alloc::Allocator"), Invisible));
499                opacities.push((
500                    format!("alloc::alloc::{{impl core::alloc::Allocator for _}}"),
501                    Invisible,
502                ));
503            }
504
505            opacities
506                .into_iter()
507                .filter_map(|(s, opacity)| parse_pattern(&s).ok().map(|pat| (pat, opacity)))
508                .collect()
509        };
510
511        let remove_associated_types = options
512            .remove_associated_types
513            .iter()
514            .filter_map(|s| parse_pattern(&s).ok())
515            .collect();
516
517        TranslateOptions {
518            start_from,
519            mir_level,
520            monomorphize_mut: options.monomorphize_mut,
521            hide_marker_traits: options.hide_marker_traits,
522            remove_adt_clauses: options.remove_adt_clauses,
523            hide_allocator: options.hide_allocator,
524            remove_unused_self_clauses: options.remove_unused_self_clauses,
525            monomorphize_with_hax: options.monomorphize,
526            ops_to_function_calls: options.ops_to_function_calls,
527            index_to_function_calls: options.index_to_function_calls,
528            print_built_llbc: options.print_built_llbc,
529            item_opacities,
530            treat_box_as_builtin: options.treat_box_as_builtin,
531            raw_consts: options.raw_consts,
532            reconstruct_fallible_operations: options.reconstruct_fallible_operations,
533            reconstruct_asserts: options.reconstruct_asserts,
534            remove_associated_types,
535            unbind_item_vars: options.unbind_item_vars,
536            translate_all_methods: options.translate_all_methods,
537            desugar_drops: options.desugar_drops,
538            add_destruct_bounds: options.precise_drops,
539            translate_poly_drop_glue: options.precise_drops,
540        }
541    }
542
543    /// Find the opacity requested for the given name. This does not take into account
544    /// `#[charon::opaque]` annotations, only cli parameters.
545    #[tracing::instrument(skip(self, krate), ret)]
546    pub fn opacity_for_name(&self, krate: &TranslatedCrate, name: &Name) -> ItemOpacity {
547        // Find the most precise pattern that matches this name. There is always one since
548        // the list contains the `_` pattern. If there are conflicting settings for this item, we
549        // err on the side of being more opaque.
550        let (_, opacity) = self
551            .item_opacities
552            .iter()
553            .filter(|(pat, _)| pat.matches(krate, name))
554            .max()
555            .unwrap();
556        *opacity
557    }
558}