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