1use 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
15pub const CHARON_ARGS: &str = "CHARON_ARGS";
18
19#[derive(Debug, Default, Clone, clap::Args, PartialEq, Eq, Serialize, Deserialize)]
28#[clap(name = "Charon")]
29#[charon::rename("cli_options")]
30pub struct CliOpts {
31 #[clap(long = "ullbc")]
33 #[serde(default)]
34 pub ullbc: bool,
35 #[clap(long = "lib")]
37 #[serde(default)]
38 pub lib: bool,
39 #[clap(long = "bin")]
41 #[serde(default)]
42 pub bin: Option<String>,
43 #[clap(long = "mir_promoted")]
45 #[serde(default)]
46 pub mir_promoted: bool,
47 #[clap(long = "mir_optimized")]
49 #[serde(default)]
50 pub mir_optimized: bool,
51 #[arg(long)]
54 pub mir: Option<MirLevel>,
55 #[clap(long = "input", value_parser)]
59 #[serde(default)]
60 pub input_file: Option<PathBuf>,
61 #[clap(long = "read-llbc", value_parser)]
63 #[serde(default)]
64 pub read_llbc: Option<PathBuf>,
65 #[clap(long = "dest", value_parser)]
68 #[serde(default)]
69 pub dest_dir: Option<PathBuf>,
70 #[clap(long = "dest-file", value_parser)]
73 #[serde(default)]
74 pub dest_file: Option<PathBuf>,
75 #[clap(long = "polonius")]
78 #[serde(default)]
79 pub use_polonius: bool,
80 #[clap(long = "skip-borrowck")]
82 #[serde(default)]
83 pub skip_borrowck: bool,
84 #[clap(long, visible_alias = "mono")]
88 #[serde(default)]
89 pub monomorphize: bool,
90 #[clap(
94 long,
95 value_name("INCLUDE_TYPES"),
96 num_args(0..=1),
97 require_equals(true),
98 default_missing_value("all"),
99 )]
100 #[serde(default)]
101 pub monomorphize_mut: Option<MonomorphizeMut>,
102 #[clap(long = "extract-opaque-bodies")]
105 #[serde(default)]
106 pub extract_opaque_bodies: bool,
107 #[clap(long = "translate-all-methods")]
110 #[serde(default)]
111 pub translate_all_methods: bool,
112 #[clap(
114 long = "include",
115 help = indoc!("
116 Whitelist of items to translate. These use the name-matcher syntax (note: this differs
117 a bit from the ocaml NameMatcher).
118
119 Note: This is very rough at the moment. E.g. this parses `u64` as a path instead of the
120 built-in type. It is also not possible to filter a trait impl (this will only filter
121 its methods). Please report bugs or missing features.
122
123 Examples:
124 - `crate::module1::module2::item`: refers to this item and all its subitems (e.g.
125 submodules or trait methods);
126 - `crate::module1::module2::item::_`: refers only to the subitems of this item;
127 - `core::convert::{impl core::convert::Into<_> for _}`: retrieve the body of this
128 very useful impl;
129
130 When multiple patterns in the `--include` and `--opaque` options match the same item,
131 the most precise pattern wins. E.g.: `charon --opaque crate::module --include
132 crate::module::_` makes the `module` opaque (we won't explore its contents), but the
133 items in it transparent (we will translate them if we encounter them.)
134 "))]
135 #[serde(default)]
136 #[charon::rename("included")]
137 pub include: Vec<String>,
138 #[clap(
140 long = "opaque",
141 help = "Blacklist of items to keep opaque. Works just like `--include`, see the doc there."
142 )]
143 #[serde(default)]
144 pub opaque: Vec<String>,
145 #[clap(
147 long = "exclude",
148 help = "Blacklist of items to not translate at all. Works just like `--include`, see the doc there."
149 )]
150 #[serde(default)]
151 pub exclude: Vec<String>,
152 #[clap(
154 long = "remove-associated-types",
155 help = "List of traits for which we transform associated types to type parameters. \
156 The syntax is like `--include`, see the doc there."
157 )]
158 #[serde(default)]
159 pub remove_associated_types: Vec<String>,
160 #[clap(long = "hide-marker-traits")]
163 #[serde(default)]
164 pub hide_marker_traits: bool,
165 #[clap(long)]
169 #[serde(default)]
170 pub remove_adt_clauses: bool,
171 #[clap(long)]
173 #[serde(default)]
174 pub hide_allocator: bool,
175 #[clap(long)]
180 #[serde(default)]
181 pub remove_unused_self_clauses: bool,
182 #[clap(long)]
185 #[serde(default)]
186 pub add_drop_bounds: bool,
187 #[clap(long = "start-from")]
191 #[serde(default)]
192 pub start_from: Vec<String>,
193 #[clap(long = "no-cargo")]
195 #[serde(default)]
196 pub no_cargo: bool,
197 #[clap(long = "rustc-flag", alias = "rustc-arg")]
199 #[serde(default)]
200 pub rustc_args: Vec<String>,
201 #[clap(long = "cargo-arg")]
203 #[serde(default)]
204 pub cargo_args: Vec<String>,
205 #[clap(long = "abort-on-error")]
207 #[serde(default)]
208 pub abort_on_error: bool,
209 #[clap(long = "error-on-warnings", help = "Consider any warnings as errors")]
211 #[serde(default)]
212 pub error_on_warnings: bool,
213 #[clap(
214 long = "no-serialize",
215 help = "Don't serialize the final (U)LLBC to a file."
216 )]
217 #[serde(default)]
218 pub no_serialize: bool,
219 #[clap(
220 long = "print-original-ullbc",
221 help = "Print the ULLBC immediately after extraction from MIR."
222 )]
223 #[serde(default)]
224 pub print_original_ullbc: bool,
225 #[clap(
226 long = "print-ullbc",
227 help = "Print the ULLBC after applying the micro-passes (before serialization/control-flow reconstruction)."
228 )]
229 #[serde(default)]
230 pub print_ullbc: bool,
231 #[clap(
232 long = "print-built-llbc",
233 help = "Print the LLBC just after we built it (i.e., immediately after loop reconstruction)."
234 )]
235 #[serde(default)]
236 pub print_built_llbc: bool,
237 #[clap(
238 long = "print-llbc",
239 help = "Print the final LLBC (after all the cleaning micro-passes)."
240 )]
241 #[serde(default)]
242 pub print_llbc: bool,
243 #[clap(
244 long = "no-merge-goto-chains",
245 help = "Do not merge the chains of gotos in the ULLBC control-flow graph."
246 )]
247 #[serde(default)]
248 pub no_merge_goto_chains: bool,
249
250 #[clap(
251 long = "no-ops-to-function-calls",
252 help = "Do not transform ArrayToSlice, Repeat, and RawPtr aggregates to builtin function calls for ULLBC"
253 )]
254 #[serde(default)]
255 pub no_ops_to_function_calls: bool,
256
257 #[clap(
258 long = "raw-boxes",
259 help = "Do not special-case the translation of `Box<T>` into a builtin ADT."
260 )]
261 #[serde(default)]
262 pub raw_boxes: bool,
263
264 #[clap(long = "preset")]
267 #[arg(value_enum)]
268 pub preset: Option<Preset>,
269}
270
271#[derive(
274 Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize,
275)]
276pub enum MirLevel {
277 #[default]
279 Built,
280 Promoted,
282 Elaborated,
285 Optimized,
288}
289
290#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize)]
293#[non_exhaustive]
294pub enum Preset {
295 OldDefaults,
298 Aeneas,
299 Eurydice,
300 Soteria,
301 Tests,
302}
303
304#[derive(
305 Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize,
306)]
307pub enum MonomorphizeMut {
308 #[default]
310 All,
311 ExceptTypes,
313}
314
315impl CliOpts {
316 pub fn apply_preset(&mut self) {
317 if let Some(preset) = self.preset {
318 match preset {
319 Preset::OldDefaults => {
320 self.hide_allocator = !self.raw_boxes;
321 }
322 Preset::Aeneas => {
323 self.remove_associated_types.push("*".to_owned());
324 self.hide_marker_traits = true;
325 self.hide_allocator = true;
326 self.remove_unused_self_clauses = true;
327 self.exclude.push("core::ops::drop::Drop".to_owned());
330 self.exclude
331 .push("{impl core::ops::drop::Drop for _}".to_owned());
332 }
333 Preset::Eurydice => {
334 self.hide_allocator = true;
335 self.remove_associated_types.push("*".to_owned());
336 self.include.push("core::marker::MetaSized".to_owned());
338 }
339 Preset::Soteria => {
340 self.extract_opaque_bodies = true;
341 self.monomorphize = true;
342 self.raw_boxes = true;
343 self.mir = Some(MirLevel::Elaborated);
344 self.ullbc = true;
345 }
346 Preset::Tests => {
347 self.hide_allocator = !self.raw_boxes;
348 self.rustc_args.push("--edition=2021".to_owned());
349 self.rustc_args
350 .push("-Zcrate-attr=feature(register_tool)".to_owned());
351 self.rustc_args
352 .push("-Zcrate-attr=register_tool(charon)".to_owned());
353 self.exclude.push("core::fmt::Formatter".to_owned());
354 }
355 }
356 }
357 }
358
359 pub fn validate(&self) -> anyhow::Result<()> {
361 assert!(
362 !self.lib || self.bin.is_none(),
363 "Can't use --lib and --bin at the same time"
364 );
365
366 assert!(
367 !self.mir_promoted || !self.mir_optimized,
368 "Can't use --mir_promoted and --mir_optimized at the same time"
369 );
370
371 if self.input_file.is_some() {
372 display_unspanned_error(
373 Level::WARNING,
374 "`--input` is deprecated, use `charon rustc [charon options] -- [rustc options] <input file>` instead",
375 )
376 }
377 if self.no_cargo {
378 display_unspanned_error(
379 Level::WARNING,
380 "`--no-cargo` is deprecated, use `charon rustc [charon options] -- [rustc options] <input file>` instead",
381 )
382 }
383 if self.read_llbc.is_some() {
384 display_unspanned_error(
385 Level::WARNING,
386 "`--read_llbc` is deprecated, use `charon pretty-print <input file>` instead",
387 )
388 }
389 if self.use_polonius {
390 display_unspanned_error(
391 Level::WARNING,
392 "`--polonius` is deprecated, use `--rustc-arg=-Zpolonius` instead",
393 )
394 }
395 if self.mir_optimized {
396 display_unspanned_error(
397 Level::WARNING,
398 "`--mir_optimized` is deprecated, use `--mir optimized` instead",
399 )
400 }
401 if self.mir_promoted {
402 display_unspanned_error(
403 Level::WARNING,
404 "`--mir_promoted` is deprecated, use `--mir promoted` instead",
405 )
406 }
407 if self.lib {
408 display_unspanned_error(
409 Level::WARNING,
410 "`--lib` is deprecated, use `charon cargo -- --lib` instead",
411 )
412 }
413 if self.bin.is_some() {
414 display_unspanned_error(
415 Level::WARNING,
416 "`--bin` is deprecated, use `charon cargo -- --bin <name>` instead",
417 )
418 }
419 if self.dest_dir.is_some() {
420 display_unspanned_error(
421 Level::WARNING,
422 "`--dest` is deprecated, use `--dest-file` instead",
423 )
424 }
425
426 if self.remove_adt_clauses && self.remove_associated_types.is_empty() {
427 anyhow::bail!(
428 "`--remove-adt-clauses` should be used with `--remove-associated-types='*'` \
429 to avoid missing clause errors",
430 )
431 }
432 if matches!(self.monomorphize_mut, Some(MonomorphizeMut::ExceptTypes))
433 && !self.remove_adt_clauses
434 {
435 anyhow::bail!(
436 "`--monomorphize-mut=except-types` should be used with `--remove-adt-clauses` \
437 to avoid generics mismatches"
438 )
439 }
440 Ok(())
441 }
442}
443
444pub struct TranslateOptions {
446 pub mir_level: MirLevel,
448 pub translate_all_methods: bool,
451 pub monomorphize_mut: Option<MonomorphizeMut>,
454 pub hide_marker_traits: bool,
457 pub remove_adt_clauses: bool,
459 pub hide_allocator: bool,
461 pub remove_unused_self_clauses: bool,
463 pub monomorphize_with_hax: bool,
465 pub no_ops_to_function_calls: bool,
467 pub no_merge_goto_chains: bool,
469 pub print_built_llbc: bool,
471 pub raw_boxes: bool,
473 pub item_opacities: Vec<(NamePattern, ItemOpacity)>,
476 pub remove_associated_types: Vec<NamePattern>,
478}
479
480impl TranslateOptions {
481 pub fn new(error_ctx: &mut ErrorCtx, options: &CliOpts) -> Self {
482 let mut parse_pattern = |s: &str| match NamePattern::parse(s) {
483 Ok(p) => Ok(p),
484 Err(e) => {
485 raise_error!(
486 error_ctx,
487 crate(&TranslatedCrate::default()),
488 Span::dummy(),
489 "failed to parse pattern `{s}` ({e})"
490 )
491 }
492 };
493
494 let mir_level = if options.mir_optimized {
495 MirLevel::Optimized
496 } else if options.mir_promoted {
497 MirLevel::Promoted
498 } else {
499 options.mir.unwrap_or_default()
500 };
501
502 let item_opacities = {
503 use ItemOpacity::*;
504 let mut opacities = vec![];
505
506 if options.extract_opaque_bodies {
508 opacities.push(("_".to_string(), Transparent));
509 } else {
510 opacities.push(("_".to_string(), Foreign));
511 }
512
513 opacities.push(("crate".to_owned(), Transparent));
515
516 for pat in options.include.iter() {
517 opacities.push((pat.to_string(), Transparent));
518 }
519 for pat in options.opaque.iter() {
520 opacities.push((pat.to_string(), Opaque));
521 }
522 for pat in options.exclude.iter() {
523 opacities.push((pat.to_string(), Invisible));
524 }
525
526 if options.hide_allocator {
527 opacities.push((format!("core::alloc::Allocator"), Invisible));
528 opacities.push((
529 format!("alloc::alloc::{{impl core::alloc::Allocator for _}}"),
530 Invisible,
531 ));
532 }
533
534 opacities
535 .into_iter()
536 .filter_map(|(s, opacity)| parse_pattern(&s).ok().map(|pat| (pat, opacity)))
537 .collect()
538 };
539
540 let remove_associated_types = options
541 .remove_associated_types
542 .iter()
543 .filter_map(|s| parse_pattern(&s).ok())
544 .collect();
545
546 TranslateOptions {
547 mir_level,
548 monomorphize_mut: options.monomorphize_mut,
549 hide_marker_traits: options.hide_marker_traits,
550 remove_adt_clauses: options.remove_adt_clauses,
551 hide_allocator: options.hide_allocator,
552 remove_unused_self_clauses: options.remove_unused_self_clauses,
553 monomorphize_with_hax: options.monomorphize,
554 no_merge_goto_chains: options.no_merge_goto_chains,
555 no_ops_to_function_calls: options.no_ops_to_function_calls,
556 print_built_llbc: options.print_built_llbc,
557 item_opacities,
558 raw_boxes: options.raw_boxes,
559 remove_associated_types,
560 translate_all_methods: options.translate_all_methods,
561 }
562 }
563
564 #[tracing::instrument(skip(self, krate), ret)]
567 pub fn opacity_for_name(&self, krate: &TranslatedCrate, name: &Name) -> ItemOpacity {
568 let (_, opacity) = self
572 .item_opacities
573 .iter()
574 .filter(|(pat, _)| pat.matches(krate, name))
575 .max()
576 .unwrap();
577 *opacity
578 }
579}