Skip to main content

charon_lib/ast/items/
fun_decl.rs

1use crate::ast::*;
2use derive_generic_visitor::{Drive, DriveMut, DriveTwo};
3use enum_as_inner::EnumAsInner;
4use serde_state::DeserializeState;
5use serde_state::SerializeState;
6
7/// A function definition
8#[derive(Debug, Clone)]
9#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
10pub struct FunDecl {
11    pub def_id: FunDeclId,
12    /// The meta data associated with the declaration.
13    pub item_meta: ItemMeta,
14    pub generics: GenericParams,
15    /// The signature contains the inputs/output types and ABI details.
16    pub signature: Box<FunSig>,
17    /// The function kind: "regular" function, trait method declaration, etc.
18    pub src: FunSource,
19    /// The function body.
20    pub body: Body,
21}
22
23/// A function signature.
24#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
25#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
26pub struct FunSig {
27    /// Is the function unsafe or not
28    pub is_unsafe: bool,
29    /// The calling convention of this function.
30    pub abi: Abi,
31    /// Whether this is a C-variadic function (its last parameter is `...`).
32    pub is_variadic: bool,
33    pub inputs: Vec<Ty>,
34    pub output: Ty,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
38#[derive(EnumAsInner)]
39#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
40#[serde_state(stateless)]
41#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("Abi"))]
42pub enum Abi {
43    Rust,
44    C,
45    /// Rust's spelling for the ABI, e.g. "C-unwind" or "system".
46    Other(ustr::Ustr),
47}
48
49/// Where a given function came from.
50#[derive(Debug, Clone)]
51#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
52#[cfg_attr(feature = "charon_on_charon", charon::variants_suffix("Fun"))]
53pub enum FunSource {
54    /// A normal function.
55    Normal,
56    /// A synthetic function representing an ADT constructor.
57    AdtConstructor,
58    /// A method in an inherent implementation.
59    InherentImpl {
60        /// The self type of the impl block.
61        self_ty: Ty,
62    },
63    /// A default method in a trait declaration.
64    TraitDefault {
65        /// The trait declaration this item belongs to.
66        trait_ref: TraitDeclRef,
67        /// The method this corresponds to.
68        // TODO: also include method generics so we can recover a full `FnPtr::TraitMethod`
69        item_id: TraitMethodId,
70    },
71    /// A method in a trait implementation.
72    TraitImpl {
73        /// The trait implementation the method belongs to.
74        impl_ref: TraitImplRef,
75        /// The trait declaration that the impl block implements.
76        trait_ref: TraitDeclRef,
77        /// The method this corresponds to.
78        // TODO: also include method generics so we can recover a full `FnPtr::TraitMethod`
79        item_id: TraitMethodId,
80        /// True if the trait decl had a default implementation for this method and this item is a
81        /// copy of the default item.
82        reuses_default: bool,
83    },
84    /// Wraps a concrete implementation of a method into a function that takes `dyn Trait` as its
85    /// `Self` type. This shim casts the receiver to the known concrete type and calls the real
86    /// method.
87    VTableShim,
88    /// The initializer for a global.
89    GlobalInitializer(GlobalDeclRef),
90    /// A target-specific variant behind a `TargetDispatch` façade. The dispatcher is the function
91    /// with the `Body::TargetDispatch` body that dispatches to this function.
92    TargetDependent { dispatcher: FunDeclRef },
93}
94
95impl FunDecl {
96    /// Replace the generic parameters of this function with the ones given by the binder.
97    pub fn substitute_params(self, subst: Binder<GenericArgs>) -> Self {
98        let FunDecl {
99            def_id,
100            item_meta,
101            generics: _,
102            signature,
103            src,
104            body,
105        } = self;
106        let signature = signature.substitute(&subst.skip_binder);
107        let src = src.substitute(&subst.skip_binder);
108        let body = body.substitute(&subst.skip_binder);
109        FunDecl {
110            def_id,
111            item_meta,
112            generics: subst.params,
113            signature,
114            src,
115            body,
116        }
117    }
118
119    /// Whether this function is unsafe to call, because it is declared `unsafe` (safety.unsafe-call),
120    /// or because it is a safe `#[target_feature]` function (safety.unsafe-target-feature-call). This
121    /// may be overriden at the call site, if we can statically discharge the unsafety (see [`CallSafety`]).
122    pub fn is_unsafe_to_call(&self, _krate: &TranslatedCrate) -> bool {
123        self.signature.is_unsafe
124    }
125
126    /// Whether this function is unsafe to declare.
127    pub fn is_unsafe_to_declare(&self, _krate: &TranslatedCrate) -> bool {
128        // The initializer of a global is part of the global's declaration.
129        !matches!(self.src, FunSource::GlobalInitializer(_))
130            && self.item_meta.is_unsafe_to_declare()
131    }
132
133    /// The function pointer signature of this item, binding its late-bound regions.
134    pub fn as_fn_ptr(&self) -> RegionBinder<FunSig> {
135        struct RebindLateRegions<'a> {
136            late_regions: &'a IndexVec<RegionId, Option<RegionId>>,
137        }
138
139        impl VarsVisitor for RebindLateRegions<'_> {
140            fn visit_region_var(&mut self, var: RegionDbVar) -> Option<Region> {
141                let DeBruijnVar::Bound(depth, id) = var else {
142                    return None;
143                };
144                if depth == DeBruijnId::one() {
145                    self.late_regions[id].map(|id| Region::Var(DeBruijnVar::new_at_zero(id)))
146                } else {
147                    None
148                }
149            }
150        }
151
152        let mut regions = IndexVec::new();
153        let late_regions = self.generics.regions.map_ref(|param| {
154            if param.late_bound {
155                Some(regions.push_with(|index| RegionParam {
156                    index,
157                    ..param.clone()
158                }))
159            } else {
160                None
161            }
162        });
163        let mut signature = self.signature.as_ref().clone().move_under_binder();
164        signature.visit_vars(&mut RebindLateRegions {
165            late_regions: &late_regions,
166        });
167        RegionBinder {
168            regions,
169            // Late-bound regions are guaranteed to not be involved in any non-implied outlives
170            // relations.
171            outlives: Vec::new(),
172            skip_binder: signature,
173        }
174    }
175}
176
177impl Abi {
178    pub fn rust() -> Self {
179        Self::Rust
180    }
181
182    pub fn rust_name(&self) -> &str {
183        match self {
184            Self::Rust => "Rust",
185            Self::C => "C",
186            Self::Other(name) => name.as_str(),
187        }
188    }
189}