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. Note: this emits constants that the OCaml bindings
178 /// can't parse; if you need this ping me so I can fix that.
179 #[clap(long)]
180 #[serde(default)]
181 pub raw_consts: bool,
182 /// Replace "bound checks followed by UB-on-overflow operation" with the corresponding
183 /// panic-on-overflow operation. This loses unwinding information.
184 #[clap(long)]
185 #[serde(default)]
186 pub reconstruct_fallible_operations: bool,
187 /// Replace "if x { panic() }" with "assert(x)".
188 #[clap(long)]
189 #[serde(default)]
190 pub reconstruct_asserts: bool,
191 // Use `DeBruijnVar::Free` for the variables bound in item signatures, instead of
192 // `DeBruijnVar::Bound` everywhere. This simplifies the management of generics for projects
193 // that don't intend to manipulate them too much.
194 #[clap(long)]
195 #[serde(default)]
196 pub unbind_item_vars: bool,
197
198 /// Pretty-print the ULLBC immediately after extraction from MIR.
199 #[clap(long)]
200 #[serde(default)]
201 pub print_original_ullbc: bool,
202 /// Pretty-print the ULLBC after applying the micro-passes (before serialization/control-flow reconstruction).
203 #[clap(long)]
204 #[serde(default)]
205 pub print_ullbc: bool,
206 /// Pretty-print the LLBC just after we built it (i.e., immediately after loop reconstruction).
207 #[clap(long)]
208 #[serde(default)]
209 pub print_built_llbc: bool,
210 /// Pretty-print the final LLBC (after all the cleaning micro-passes).
211 #[clap(long)]
212 #[serde(default)]
213 pub print_llbc: bool,
214
215 /// The destination directory. Files will be generated as `<dest_dir>/<crate_name>.{u}llbc`,
216 /// unless `dest_file` is set. `dest_dir` defaults to the current directory.
217 #[clap(long = "dest", value_parser)]
218 #[serde(default)]
219 pub dest_dir: Option<PathBuf>,
220 /// The destination file. By default `<dest_dir>/<crate_name>.llbc`. If this is set we ignore
221 /// `dest_dir`.
222 #[clap(long, value_parser)]
223 #[serde(default)]
224 pub dest_file: Option<PathBuf>,
225 /// Don't deduplicate values (types, trait refs) in the .(u)llbc file. This makes the file easier to inspect.
226 #[clap(long)]
227 #[serde(default)]
228 pub no_dedup_serialized_ast: bool,
229 /// Don't serialize the final (U)LLBC to a file.
230 #[clap(long)]
231 #[serde(default)]
232 pub no_serialize: bool,
233 /// Panic on the first error. This is useful for debugging.
234 #[clap(long)]
235 #[serde(default)]
236 pub abort_on_error: bool,
237 /// Consider any warnings to be errors.
238 #[clap(long)]
239 #[serde(default)]
240 pub error_on_warnings: bool,
241
242 /// Named builtin sets of options.
243 #[clap(long)]
244 #[arg(value_enum)]
245 pub preset: Option<Preset>,
246}
247
248/// The MIR stage to use. This is only relevant for the current crate: for dependencies, only mir
249/// optimized is available (or mir elaborated for consts).
250#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize)]
251pub enum MirLevel {
252 /// The MIR just after MIR lowering.
253 Built,
254 /// The MIR after const promotion. This is the MIR used by the borrow-checker.
255 Promoted,
256 /// The MIR after drop elaboration. This is the first MIR to include all the runtime
257 /// information.
258 Elaborated,
259 /// The MIR after optimizations. Charon disables all the optimizations it can, so this is
260 /// sensibly the same MIR as the elaborated MIR.
261 Optimized,
262}
263
264/// Presets to make it easier to tweak options without breaking dependent projects. Eventually we
265/// should define semantically-meaningful presets instead of project-specific ones.
266#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize)]
267#[non_exhaustive]
268pub enum Preset {
269 /// The default translation used before May 2025. After that, many passes were made optional
270 /// and disabled by default.
271 OldDefaults,
272 /// Emit the MIR as unmodified as possible. This is very imperfect for now, we should make more
273 /// passes optional.
274 RawMir,
275 Aeneas,
276 Eurydice,
277 Soteria,
278 Tests,
279}
280
281#[derive(
282 Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize,
283)]
284pub enum MonomorphizeMut {
285 /// Monomorphize any item instantiated with `&mut`.
286 #[default]
287 All,
288 /// Monomorphize all non-typedecl items instantiated with `&mut`.
289 ExceptTypes,
290}
291
292impl CliOpts {
293 pub fn apply_preset(&mut self) {
294 if let Some(preset) = self.preset {
295 match preset {
296 Preset::OldDefaults => {
297 self.treat_box_as_builtin = true;
298 self.hide_allocator = true;
299 self.ops_to_function_calls = true;
300 self.index_to_function_calls = true;
301 self.reconstruct_fallible_operations = true;
302 self.reconstruct_asserts = true;
303 self.unbind_item_vars = true;
304 }
305 Preset::RawMir => {
306 self.extract_opaque_bodies = true;
307 self.raw_consts = true;
308 self.ullbc = true;
309 }
310 Preset::Aeneas => {
311 self.remove_associated_types.push("*".to_owned());
312 self.treat_box_as_builtin = true;
313 self.ops_to_function_calls = true;
314 self.index_to_function_calls = true;
315 self.reconstruct_fallible_operations = true;
316 self.reconstruct_asserts = true;
317 self.hide_marker_traits = true;
318 self.hide_allocator = true;
319 self.remove_unused_self_clauses = true;
320 self.unbind_item_vars = true;
321 // Hide drop impls because they often involve nested borrows. which aeneas
322 // doesn't handle yet.
323 self.exclude.push("core::ops::drop::Drop".to_owned());
324 self.exclude
325 .push("{impl core::ops::drop::Drop for _}".to_owned());
326 }
327 Preset::Eurydice => {
328 self.hide_allocator = true;
329 self.treat_box_as_builtin = true;
330 self.ops_to_function_calls = true;
331 self.index_to_function_calls = true;
332 self.reconstruct_fallible_operations = true;
333 self.reconstruct_asserts = true;
334 self.remove_associated_types.push("*".to_owned());
335 self.unbind_item_vars = true;
336 // Eurydice doesn't support opaque vtables it seems?
337 self.include.push("core::marker::MetaSized".to_owned());
338 }
339 Preset::Soteria => {
340 self.extract_opaque_bodies = true;
341 self.monomorphize = true;
342 self.mir = Some(MirLevel::Elaborated);
343 self.ullbc = true;
344 }
345 Preset::Tests => {
346 self.no_dedup_serialized_ast = true; // Helps debug
347 self.treat_box_as_builtin = true;
348 self.hide_allocator = true;
349 self.reconstruct_fallible_operations = true;
350 self.reconstruct_asserts = true;
351 self.ops_to_function_calls = true;
352 self.index_to_function_calls = true;
353 self.rustc_args.push("--edition=2021".to_owned());
354 self.rustc_args
355 .push("-Zcrate-attr=feature(register_tool)".to_owned());
356 self.rustc_args
357 .push("-Zcrate-attr=register_tool(charon)".to_owned());
358 self.exclude.push("core::fmt::Formatter".to_owned());
359 }
360 }
361 }
362 }
363
364 /// Check that the options are meaningful
365 pub fn validate(&self) -> anyhow::Result<()> {
366 if self.dest_dir.is_some() {
367 display_unspanned_error(
368 Level::WARNING,
369 "`--dest` is deprecated, use `--dest-file` instead",
370 )
371 }
372
373 if self.remove_adt_clauses && self.remove_associated_types.is_empty() {
374 anyhow::bail!(
375 "`--remove-adt-clauses` should be used with `--remove-associated-types='*'` \
376 to avoid missing clause errors",
377 )
378 }
379 if matches!(self.monomorphize_mut, Some(MonomorphizeMut::ExceptTypes))
380 && !self.remove_adt_clauses
381 {
382 anyhow::bail!(
383 "`--monomorphize-mut=except-types` should be used with `--remove-adt-clauses` \
384 to avoid generics mismatches"
385 )
386 }
387 Ok(())
388 }
389}
390
391/// The options that control translation and transformation.
392pub struct TranslateOptions {
393 /// The level at which to extract the MIR
394 pub mir_level: MirLevel,
395 /// Usually we skip the provided methods that aren't used. When this flag is on, we translate
396 /// them all.
397 pub translate_all_methods: bool,
398 /// If `Some(_)`, run the partial mutability monomorphization pass. The contained enum
399 /// indicates whether to partially monomorphize types.
400 pub monomorphize_mut: Option<MonomorphizeMut>,
401 /// Whether to hide various marker traits such as `Sized`, `Sync`, `Send` and `Destruct`
402 /// anywhere they show up.
403 pub hide_marker_traits: bool,
404 /// Remove trait clauses attached to type declarations.
405 pub remove_adt_clauses: bool,
406 /// Hide the `A` type parameter on standard library containers (`Box`, `Vec`, etc).
407 pub hide_allocator: bool,
408 /// Remove unused `Self: Trait` clauses on method declarations.
409 pub remove_unused_self_clauses: bool,
410 /// Monomorphize code using hax's instantiation mechanism.
411 pub monomorphize_with_hax: bool,
412 /// Transform array-to-slice unsizing, repeat expressions, and raw pointer construction into
413 /// builtin functions in ULLBC.
414 pub ops_to_function_calls: bool,
415 /// Transform array/slice indexing into builtin functions in ULLBC.
416 pub index_to_function_calls: bool,
417 /// Print the llbc just after control-flow reconstruction.
418 pub print_built_llbc: bool,
419 /// Treat `Box<T>` as if it was a built-in type.
420 pub treat_box_as_builtin: bool,
421 /// Don't inline or evaluate constants.
422 pub raw_consts: bool,
423 /// Replace "bound checks followed by UB-on-overflow operation" with the corresponding
424 /// panic-on-overflow operation. This loses unwinding information.
425 pub reconstruct_fallible_operations: bool,
426 /// Replace "if x { panic() }" with "assert(x)".
427 pub reconstruct_asserts: bool,
428 // Use `DeBruijnVar::Free` for the variables bound in item signatures.
429 pub unbind_item_vars: bool,
430 /// List of patterns to assign a given opacity to. Same as the corresponding `TranslateOptions`
431 /// field.
432 pub item_opacities: Vec<(NamePattern, ItemOpacity)>,
433 /// List of traits for which we transform associated types to type parameters.
434 pub remove_associated_types: Vec<NamePattern>,
435 /// Transform Drop to Call drop_in_place
436 pub desugar_drops: bool,
437 /// Add `Destruct` bounds to all generic params.
438 pub add_destruct_bounds: bool,
439 /// Translate drop glue for poly types, knowing that this may cause ICEs.
440 pub translate_poly_drop_glue: bool,
441}
442
443impl TranslateOptions {
444 pub fn new(error_ctx: &mut ErrorCtx, options: &CliOpts) -> Self {
445 let mut parse_pattern = |s: &str| match NamePattern::parse(s) {
446 Ok(p) => Ok(p),
447 Err(e) => {
448 raise_error!(
449 error_ctx,
450 crate(&TranslatedCrate::default()),
451 Span::dummy(),
452 "failed to parse pattern `{s}` ({e})"
453 )
454 }
455 };
456
457 let mut mir_level = options.mir.unwrap_or(MirLevel::Promoted);
458 if options.precise_drops {
459 mir_level = std::cmp::max(mir_level, MirLevel::Elaborated);
460 }
461
462 let item_opacities = {
463 use ItemOpacity::*;
464 let mut opacities = vec![];
465
466 // This is how to treat items that don't match any other pattern.
467 if options.extract_opaque_bodies {
468 opacities.push(("_".to_string(), Transparent));
469 } else {
470 opacities.push(("_".to_string(), Foreign));
471 }
472
473 // We always include the items from the crate.
474 opacities.push(("crate".to_owned(), Transparent));
475
476 for pat in options.include.iter() {
477 opacities.push((pat.to_string(), Transparent));
478 }
479 for pat in options.opaque.iter() {
480 opacities.push((pat.to_string(), Opaque));
481 }
482 for pat in options.exclude.iter() {
483 opacities.push((pat.to_string(), Invisible));
484 }
485
486 if options.hide_allocator {
487 opacities.push((format!("core::alloc::Allocator"), Invisible));
488 opacities.push((
489 format!("alloc::alloc::{{impl core::alloc::Allocator for _}}"),
490 Invisible,
491 ));
492 }
493
494 opacities
495 .into_iter()
496 .filter_map(|(s, opacity)| parse_pattern(&s).ok().map(|pat| (pat, opacity)))
497 .collect()
498 };
499
500 let remove_associated_types = options
501 .remove_associated_types
502 .iter()
503 .filter_map(|s| parse_pattern(&s).ok())
504 .collect();
505
506 TranslateOptions {
507 mir_level,
508 monomorphize_mut: options.monomorphize_mut,
509 hide_marker_traits: options.hide_marker_traits,
510 remove_adt_clauses: options.remove_adt_clauses,
511 hide_allocator: options.hide_allocator,
512 remove_unused_self_clauses: options.remove_unused_self_clauses,
513 monomorphize_with_hax: options.monomorphize,
514 ops_to_function_calls: options.ops_to_function_calls,
515 index_to_function_calls: options.index_to_function_calls,
516 print_built_llbc: options.print_built_llbc,
517 item_opacities,
518 treat_box_as_builtin: options.treat_box_as_builtin,
519 raw_consts: options.raw_consts,
520 reconstruct_fallible_operations: options.reconstruct_fallible_operations,
521 reconstruct_asserts: options.reconstruct_asserts,
522 remove_associated_types,
523 unbind_item_vars: options.unbind_item_vars,
524 translate_all_methods: options.translate_all_methods,
525 desugar_drops: options.desugar_drops,
526 add_destruct_bounds: options.precise_drops,
527 translate_poly_drop_glue: options.precise_drops,
528 }
529 }
530
531 /// Find the opacity requested for the given name. This does not take into account
532 /// `#[charon::opaque]` annotations, only cli parameters.
533 #[tracing::instrument(skip(self, krate), ret)]
534 pub fn opacity_for_name(&self, krate: &TranslatedCrate, name: &Name) -> ItemOpacity {
535 // Find the most precise pattern that matches this name. There is always one since
536 // the list contains the `_` pattern. If there are conflicting settings for this item, we
537 // err on the side of being more opaque.
538 let (_, opacity) = self
539 .item_opacities
540 .iter()
541 .filter(|(pat, _)| pat.matches(krate, name))
542 .max()
543 .unwrap();
544 *opacity
545 }
546}