1use annotate_snippets::Level;
3use clap::ValueEnum;
4use indoc::indoc;
5use itertools::Itertools;
6use macros::EnumAsGetters;
7use serde::{Deserialize, Serialize};
8use std::path::PathBuf;
9
10use crate::{
11 ast::*,
12 errors::{ErrorCtx, display_unspanned_error},
13 name_matcher::NamePattern,
14 raise_error, register_error,
15};
16
17pub const CHARON_ARGS: &str = "CHARON_ARGS";
20
21#[derive(Debug, Default, Clone, clap::Args, PartialEq, Eq, Serialize, Deserialize)]
30#[clap(name = "Charon")]
31#[cfg_attr(feature = "charon_on_charon", charon::rename("cli_options"))]
32pub struct CliOpts {
33 #[clap(long)]
35 #[serde(default)]
36 pub ullbc: bool,
37 #[clap(long)]
43 #[serde(default)]
44 pub precise_drops: bool,
45 #[arg(long)]
48 pub mir: Option<MirLevel>,
49 #[clap(long = "rustc-arg")]
51 #[serde(default)]
52 pub rustc_args: Vec<String>,
53 #[clap(long, value_delimiter = ',')]
58 #[serde(default)]
59 pub targets: Vec<String>,
60 #[clap(long)]
65 #[serde(default)]
66 pub sysroot: Option<String>,
67
68 #[clap(long, visible_alias = "mono")]
72 #[serde(default)]
73 pub monomorphize: bool,
74 #[clap(
78 long,
79 value_name("INCLUDE_TYPES"),
80 num_args(0..=1),
81 require_equals(true),
82 default_missing_value("all"),
83 )]
84 #[serde(default)]
85 pub monomorphize_mut: Option<MonomorphizeMut>,
86
87 #[clap(long, value_delimiter = ',')]
91 #[serde(default)]
92 pub start_from: Vec<String>,
93 #[clap(long, value_delimiter = ',')]
96 #[serde(default)]
97 pub start_from_if_exists: Vec<String>,
98 #[clap(
102 long,
103 value_name("ATTRIBUTE"),
104 num_args(0..),
105 require_equals(true),
106 value_delimiter = ',',
107 default_missing_value("verify::start_from"),
108 )]
109 #[serde(default)]
110 pub start_from_attribute: Vec<String>,
111 #[clap(long)]
113 #[serde(default)]
114 pub start_from_pub: bool,
115
116 #[clap(
118 long,
119 help = indoc!("
120 Whitelist of items to translate. These use the name-matcher syntax (note: this differs
121 a bit from the ocaml NameMatcher).
122
123 Note: This is very rough at the moment. E.g. this parses `u64` as a path instead of the
124 built-in type. It is also not possible to filter a trait impl (this will only filter
125 its methods). Please report bugs or missing features.
126
127 Examples:
128 - `crate::module1::module2::item`: refers to this item and all its subitems (e.g.
129 submodules or trait methods);
130 - `crate::module1::module2::item::_`: refers only to the subitems of this item;
131 - `core::convert::{impl core::convert::Into<_> for _}`: retrieve the body of this
132 very useful impl;
133
134 When multiple patterns in the `--include` and `--opaque` options match the same item,
135 the most precise pattern wins. E.g.: `charon --opaque crate::module --include
136 crate::module::_` makes the `module` opaque (we won't explore its contents), but the
137 items in it transparent (we will translate them if we encounter them.)
138 "))]
139 #[serde(default)]
140 #[cfg_attr(feature = "charon_on_charon", charon::rename("included"))]
141 pub include: Vec<String>,
142 #[clap(long)]
144 #[serde(default)]
145 pub opaque: Vec<String>,
146 #[clap(long)]
148 #[serde(default)]
149 pub exclude: Vec<String>,
150 #[clap(long)]
153 #[serde(default)]
154 pub extract_opaque_bodies: bool,
155 #[clap(long)]
158 #[serde(default)]
159 pub translate_all_methods: bool,
160 #[clap(long)]
164 #[serde(default)]
165 pub duplicate_defaulted_methods: bool,
166
167 #[clap(long, alias = "remove-associated-types")]
170 #[serde(default)]
171 pub lift_associated_types: Vec<String>,
172 #[clap(long)]
175 #[serde(default)]
176 pub hide_marker_traits: bool,
177 #[clap(long)]
179 #[serde(default)]
180 pub hide_allocator: bool,
181
182 #[clap(long)]
186 #[serde(default)]
187 pub remove_unused_clauses: bool,
188 #[clap(long)]
193 #[serde(default)]
194 pub remove_unused_self_clauses: bool,
195 #[clap(long)]
198 #[serde(default)]
199 pub remove_adt_clauses: bool,
200
201 #[clap(long)]
203 #[serde(default)]
204 pub desugar_drops: bool,
205 #[clap(long)]
208 #[serde(default)]
209 pub ops_to_function_calls: bool,
210 #[clap(long)]
214 #[serde(default)]
215 pub index_to_function_calls: bool,
216 #[clap(long)]
218 #[serde(default)]
219 pub treat_box_as_builtin: bool,
220 #[clap(long)]
226 #[serde(default)]
227 pub no_gen_tuple_structs: bool,
228 #[clap(long)]
230 #[serde(default)]
231 pub raw_consts: bool,
232 #[clap(long)]
237 #[serde(default)]
238 pub consts: Option<ConstHandling>,
239 #[clap(long)]
242 #[serde(default)]
243 pub unsized_strings: bool,
244 #[clap(long)]
247 #[serde(default)]
248 pub reconstruct_fallible_operations: bool,
249 #[clap(long)]
251 #[serde(default)]
252 pub reconstruct_asserts: bool,
253 #[clap(long)]
256 #[serde(default)]
257 pub reconstruct_matches: bool,
258 #[clap(long)]
262 #[serde(default)]
263 pub deallocate_all_locals: bool,
264 #[clap(long)]
268 #[serde(default)]
269 pub unbind_item_vars: bool,
270
271 #[clap(long)]
273 #[serde(default)]
274 pub print_original_ullbc: bool,
275 #[clap(long)]
277 #[serde(default)]
278 pub print_ullbc: bool,
279 #[clap(long)]
281 #[serde(default)]
282 pub print_built_llbc: bool,
283 #[clap(long)]
285 #[serde(default)]
286 pub print_llbc: bool,
287 #[clap(long = "dest", value_parser)]
291 #[serde(default)]
292 pub dest_dir: Option<PathBuf>,
293 #[clap(long, value_parser)]
297 #[serde(default)]
298 pub dest_file: Option<PathBuf>,
299 #[clap(long)]
301 #[serde(default)]
302 pub no_dedup_serialized_ast: bool,
303 #[clap(long, value_enum)]
305 #[serde(default)]
306 pub format: Option<SerializationFormatArg>,
307 #[clap(long)]
309 #[serde(default)]
310 pub no_serialize: bool,
311 #[clap(
313 long = "skip-borrow-check",
314 alias = "skip-borrowck",
315 visible_alias = "no-borrow-check",
316 alias = "no-borrowck"
317 )]
318 #[serde(default)]
319 pub skip_borrowck: bool,
320 #[clap(long)]
322 #[serde(default)]
323 pub no_typecheck: bool,
324 #[clap(long)]
326 #[serde(default)]
327 pub no_normalize: bool,
328 #[clap(long)]
330 #[serde(default)]
331 pub no_reorder_decls: bool,
332 #[clap(long)]
334 #[serde(default)]
335 pub abort_on_error: bool,
336 #[clap(long)]
338 #[serde(default)]
339 pub error_on_warnings: bool,
340
341 #[clap(long)]
343 #[arg(value_enum)]
344 pub preset: Option<Preset>,
345}
346
347#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize)]
350pub enum MirLevel {
351 Built,
353 Promoted,
355 Elaborated,
358 Optimized,
361}
362
363#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize)]
366#[non_exhaustive]
367pub enum Preset {
368 OldDefaults,
371 RawMir,
374 Fast,
376 Aeneas,
377 Eurydice,
378 Soteria,
379 Tests,
380}
381
382#[derive(
384 Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize,
385)]
386pub enum ConstHandling {
387 #[default]
390 Initializers,
391 Values,
394}
395
396#[derive(
397 Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize,
398)]
399pub enum MonomorphizeMut {
400 #[default]
402 All,
403 ExceptTypes,
405}
406
407#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum, Serialize, Deserialize)]
408pub enum SerializationFormatArg {
409 Json,
410 Postcard,
411 #[cfg_attr(feature = "charon_on_charon", charon::rename("AllFormats"))]
412 All,
413}
414
415#[derive(
416 Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize,
417)]
418pub enum SerializationFormat {
419 #[default]
420 Json,
421 Postcard,
422}
423
424impl SerializationFormatArg {
425 pub fn as_format(self) -> Option<SerializationFormat> {
426 match self {
427 SerializationFormatArg::Json => Some(SerializationFormat::Json),
428 SerializationFormatArg::Postcard => Some(SerializationFormat::Postcard),
429 SerializationFormatArg::All => None,
430 }
431 }
432}
433
434impl From<SerializationFormat> for SerializationFormatArg {
435 fn from(format: SerializationFormat) -> SerializationFormatArg {
436 match format {
437 SerializationFormat::Json => SerializationFormatArg::Json,
438 SerializationFormat::Postcard => SerializationFormatArg::Postcard,
439 }
440 }
441}
442
443impl SerializationFormat {
444 pub fn output_extension(self, ullbc: bool) -> &'static str {
445 match (ullbc, self) {
446 (true, SerializationFormat::Json) => "ullbc",
447 (false, SerializationFormat::Json) => "llbc",
448 (true, SerializationFormat::Postcard) => "ullbc.postcard",
449 (false, SerializationFormat::Postcard) => "llbc.postcard",
450 }
451 }
452}
453
454impl CliOpts {
455 pub fn apply_preset(&mut self) {
456 if let Some(preset) = self.preset {
457 match preset {
458 Preset::OldDefaults => {
459 self.treat_box_as_builtin = true;
460 self.hide_allocator = true;
461 self.ops_to_function_calls = true;
462 self.index_to_function_calls = true;
463 self.reconstruct_fallible_operations = true;
464 self.reconstruct_asserts = true;
465 self.reconstruct_matches = true;
466 self.unbind_item_vars = true;
467 self.duplicate_defaulted_methods = true;
468 }
469 Preset::RawMir => {
470 self.extract_opaque_bodies = true;
471 self.raw_consts = true;
472 self.ullbc = true;
473 }
474 Preset::Fast => {
475 self.ullbc = true;
476 self.no_typecheck = true;
477 self.no_normalize = true;
478 self.no_reorder_decls = true;
479 self.hide_marker_traits = true;
480 self.raw_consts = true;
481 }
482 Preset::Aeneas => {
483 self.lift_associated_types.push("*".to_owned());
484 self.treat_box_as_builtin = true;
485 self.ops_to_function_calls = true;
486 self.index_to_function_calls = true;
487 self.reconstruct_fallible_operations = true;
488 self.reconstruct_asserts = true;
489 self.reconstruct_matches = true;
490 self.hide_marker_traits = true;
491 self.hide_allocator = true;
492 self.remove_unused_self_clauses = true;
493 self.remove_adt_clauses = true;
494 self.unbind_item_vars = true;
495 self.deallocate_all_locals = true;
496 self.no_gen_tuple_structs = true;
497 }
498 Preset::Eurydice => {
499 self.hide_allocator = true;
500 self.treat_box_as_builtin = true;
501 self.reconstruct_fallible_operations = true;
502 self.reconstruct_asserts = true;
503 self.reconstruct_matches = true;
504 self.lift_associated_types.push("*".to_owned());
505 self.unbind_item_vars = true;
506 self.duplicate_defaulted_methods = true;
507 self.include.push("core::marker::MetaSized".to_owned());
509 }
510 Preset::Soteria => {
511 self.desugar_drops = true;
512 self.extract_opaque_bodies = true;
513 self.mir = Some(MirLevel::Elaborated);
514 self.monomorphize = true;
515 self.no_normalize = true;
516 self.no_reorder_decls = true;
517 self.precise_drops = true;
518 self.consts = Some(ConstHandling::Values);
519 self.ullbc = true;
520 }
521 Preset::Tests => {
522 self.no_dedup_serialized_ast = true; self.treat_box_as_builtin = true;
524 self.hide_allocator = true;
525 self.reconstruct_fallible_operations = true;
526 self.reconstruct_asserts = true;
527 self.reconstruct_matches = true;
528 self.ops_to_function_calls = true;
529 self.index_to_function_calls = true;
530 self.duplicate_defaulted_methods = true;
531 self.deallocate_all_locals = true;
532 self.rustc_args.push("--edition=2021".to_owned());
533 self.rustc_args
534 .push("-Zcrate-attr=feature(register_tool)".to_owned());
535 self.rustc_args
536 .push("-Zcrate-attr=register_tool(charon)".to_owned());
537 self.exclude.push("core::fmt".to_owned());
538 }
539 }
540 }
541 }
542
543 pub fn validate(&self) -> anyhow::Result<()> {
545 if self.dest_dir.is_some() {
546 display_unspanned_error(
547 Level::WARNING,
548 "`--dest` is deprecated, use `--dest-file` instead",
549 )
550 }
551
552 if self.remove_adt_clauses && self.lift_associated_types.is_empty() {
553 anyhow::bail!(
554 "`--remove-adt-clauses` should be used with `--lift-associated-types='*'` \
555 to avoid missing clause errors",
556 )
557 }
558 if matches!(self.monomorphize_mut, Some(MonomorphizeMut::ExceptTypes))
559 && !self.remove_adt_clauses
560 {
561 anyhow::bail!(
562 "`--monomorphize-mut=except-types` should be used with `--remove-adt-clauses` \
563 to avoid generics mismatches"
564 )
565 }
566 if self.no_gen_tuple_structs && self.monomorphize {
567 anyhow::bail!(
568 "`--no-gen-tuple-structs` is not compatible with `--monomorphize`, as \
569 monomorphization requires each tuple to have its own type declaration"
570 )
571 }
572 if self.no_serialize && self.format.is_some() {
573 anyhow::bail!(
574 "`--no-serialize` is not compatible with `--format`, the format is only relevant if we serialize"
575 );
576 }
577 Ok(())
578 }
579
580 fn target_filename(
581 &self,
582 path_base: PathBuf,
583 format: SerializationFormat,
584 ) -> (PathBuf, SerializationFormat) {
585 let extension = format.output_extension(self.ullbc);
586 let target_filename = path_base.with_added_extension(extension);
587 (target_filename, format)
588 }
589
590 pub fn targets(&self, crate_name: &str) -> Vec<(PathBuf, SerializationFormat)> {
591 if self.no_serialize {
592 return vec![];
593 }
594
595 let format = self.format.unwrap_or(SerializationFormatArg::Json);
596 let mut path_base = self.dest_dir.clone().unwrap_or_default();
597 path_base.push(crate_name);
598
599 match format.as_format() {
600 Some(format) => match self.dest_file.clone() {
601 Some(dest) => vec![(dest, format)],
602 None => vec![self.target_filename(path_base, format)],
603 },
604 None => {
605 let path_base = self.dest_file.clone().unwrap_or(path_base);
606 vec![
607 self.target_filename(path_base.clone(), SerializationFormat::Json),
608 self.target_filename(path_base, SerializationFormat::Postcard),
609 ]
610 }
611 }
612 }
613}
614
615#[derive(Debug, Clone, EnumAsGetters)]
617pub enum StartFrom {
618 Pattern { pattern: NamePattern, strict: bool },
621 Attribute(String),
623 Pub,
626}
627
628impl StartFrom {
629 pub fn matches(&self, ctx: &TranslatedCrate, item_meta: &ItemMeta) -> bool {
630 match self {
631 StartFrom::Pattern { pattern, .. } => pattern.matches(ctx, &item_meta.name),
632 StartFrom::Attribute(attr) => item_meta
633 .attr_info
634 .attributes
635 .iter()
636 .filter_map(|a| a.as_unknown())
637 .any(|raw_attr| raw_attr.path == *attr),
638 StartFrom::Pub => item_meta.attr_info.public && item_meta.is_local,
639 }
640 }
641}
642
643pub struct TranslateOptions {
645 pub start_from: Vec<StartFrom>,
647 pub mir_level: MirLevel,
649 pub translate_all_methods: bool,
652 pub duplicate_defaulted_methods: bool,
654 pub monomorphize_mut: Option<MonomorphizeMut>,
657 pub hide_marker_traits: bool,
660 pub hide_allocator: bool,
662 pub hide_traits: Vec<NamePattern>,
665 pub remove_unused_clauses: bool,
669 pub remove_unused_self_clauses: bool,
671 pub remove_adt_clauses: bool,
673 pub monomorphize_with_hax: bool,
675 pub ops_to_function_calls: bool,
678 pub index_to_function_calls: bool,
680 pub print_built_llbc: bool,
682 pub treat_box_as_builtin: bool,
684 pub no_gen_tuple_structs: bool,
687 pub raw_consts: bool,
689 pub consts: ConstHandling,
692 pub unsized_strings: bool,
695 pub reconstruct_fallible_operations: bool,
698 pub reconstruct_asserts: bool,
700 pub reconstruct_matches: bool,
702 pub deallocate_all_locals: bool,
704 pub unbind_item_vars: bool,
706 pub item_opacities: Vec<(NamePattern, ItemOpacity)>,
709 pub lift_associated_types: Vec<NamePattern>,
711 pub no_typecheck: bool,
713 pub no_normalize: bool,
715 pub no_reorder_decls: bool,
717 pub desugar_drops: bool,
719 pub add_destruct_bounds: bool,
721}
722
723impl TranslateOptions {
724 pub fn new(error_ctx: &mut ErrorCtx, options: &CliOpts) -> Self {
725 let mut parse_pattern = |s: &str| -> Result<_, Error> {
726 match NamePattern::parse(s) {
727 Ok(p) => Ok(p),
728 Err(e) => raise_error!(error_ctx, no_crate, "failed to parse pattern `{s}` ({e})"),
729 }
730 };
731
732 let mut mir_level = options.mir.unwrap_or(MirLevel::Promoted);
733 if options.precise_drops {
734 mir_level = std::cmp::max(mir_level, MirLevel::Elaborated);
735 }
736
737 let mut start_from = options
738 .start_from
739 .iter()
740 .filter_map(|path| parse_pattern(path).ok())
741 .map(|p| StartFrom::Pattern {
742 pattern: p,
743 strict: true,
744 })
745 .collect_vec();
746 start_from.extend(
747 options
748 .start_from_if_exists
749 .iter()
750 .filter_map(|path| parse_pattern(path).ok())
751 .map(|p| StartFrom::Pattern {
752 pattern: p,
753 strict: false,
754 }),
755 );
756 for attr in options.start_from_attribute.iter().cloned() {
757 start_from.push(StartFrom::Attribute(attr));
758 }
759 if options.start_from_pub {
760 start_from.push(StartFrom::Pub);
761 }
762 if start_from.is_empty() {
763 start_from.push(StartFrom::Pattern {
764 pattern: parse_pattern("crate").unwrap(),
765 strict: true,
766 });
767 }
768
769 let hide_traits = options
770 .hide_marker_traits
771 .then_some([
772 "core::marker::Sized",
773 "core::marker::MetaSized",
774 "core::marker::PointeeSized",
775 "core::marker::Tuple",
776 "core::clone::TrivialClone",
777 ])
778 .into_iter()
779 .flatten()
780 .chain(options.hide_allocator.then_some("core::alloc::Allocator"))
781 .filter_map(|s| parse_pattern(s).ok())
782 .collect_vec();
783
784 let item_opacities = {
785 use ItemOpacity::*;
786 let mut opacities = vec![];
787
788 if options.extract_opaque_bodies {
790 opacities.push(("_".to_string(), Transparent));
791 } else {
792 opacities.push(("_".to_string(), Foreign));
793 }
794
795 if options.treat_box_as_builtin {
796 opacities.push((
798 "alloc::boxed::box_assume_init_into_vec_unsafe".to_string(),
799 Transparent,
800 ));
801 }
802
803 opacities.push(("crate".to_owned(), Transparent));
805
806 for pat in options.include.iter() {
807 opacities.push((pat.to_string(), Transparent));
808 }
809 for pat in options.opaque.iter() {
810 opacities.push((pat.to_string(), Opaque));
811 }
812 for pat in options.exclude.iter() {
813 opacities.push((pat.to_string(), Invisible));
814 }
815
816 for trait_name in &hide_traits {
817 opacities.push((trait_name.to_string(), Invisible));
818 }
819
820 let hide_traits = hide_traits
822 .iter()
823 .cloned()
824 .flat_map(|pat| [pat.clone(), NamePattern::impl_for(pat)])
825 .map(|pat| (pat, Invisible));
826 opacities
827 .into_iter()
828 .filter_map(|(s, opacity)| parse_pattern(&s).ok().map(|pat| (pat, opacity)))
829 .chain(hide_traits)
830 .collect()
831 };
832
833 let lift_associated_types = options
834 .lift_associated_types
835 .iter()
836 .filter_map(|s| parse_pattern(s).ok())
837 .collect();
838
839 TranslateOptions {
840 start_from,
841 mir_level,
842 monomorphize_mut: options.monomorphize_mut,
843 hide_marker_traits: options.hide_marker_traits,
844 hide_allocator: options.hide_allocator,
845 hide_traits,
846 remove_unused_clauses: options.remove_unused_clauses,
847 remove_unused_self_clauses: options.remove_unused_self_clauses,
848 remove_adt_clauses: options.remove_adt_clauses,
849 monomorphize_with_hax: options.monomorphize,
850 ops_to_function_calls: options.ops_to_function_calls,
851 index_to_function_calls: options.index_to_function_calls,
852 print_built_llbc: options.print_built_llbc,
853 item_opacities,
854 treat_box_as_builtin: options.treat_box_as_builtin,
855 no_gen_tuple_structs: options.no_gen_tuple_structs,
856 raw_consts: options.raw_consts,
857 consts: options.consts.unwrap_or_default(),
858 unsized_strings: options.unsized_strings,
859 reconstruct_fallible_operations: options.reconstruct_fallible_operations,
860 reconstruct_asserts: options.reconstruct_asserts,
861 reconstruct_matches: options.reconstruct_matches,
862 deallocate_all_locals: options.deallocate_all_locals,
863 lift_associated_types,
864 unbind_item_vars: options.unbind_item_vars,
865 translate_all_methods: options.translate_all_methods,
866 duplicate_defaulted_methods: options.duplicate_defaulted_methods,
867 no_typecheck: options.no_typecheck,
868 no_normalize: options.no_normalize,
869 no_reorder_decls: options.no_reorder_decls,
870 desugar_drops: options.desugar_drops,
871 add_destruct_bounds: options.precise_drops,
872 }
873 }
874
875 #[tracing::instrument(skip(self, krate), ret)]
878 pub fn opacity_for_name(&self, krate: &TranslatedCrate, name: &Name) -> ItemOpacity {
879 if name.is_builtin() {
881 return ItemOpacity::Transparent;
882 }
883 let (_, opacity) = self
887 .item_opacities
888 .iter()
889 .filter(|(pat, _)| pat.matches(krate, name))
890 .max()
891 .unwrap();
892 *opacity
893 }
894}