cxx_gen/syntax/
types.rs

1use crate::syntax::improper::ImproperCtype;
2use crate::syntax::instantiate::ImplKey;
3use crate::syntax::map::{OrderedMap, UnorderedMap};
4use crate::syntax::report::Errors;
5use crate::syntax::resolve::Resolution;
6use crate::syntax::set::{OrderedSet, UnorderedSet};
7use crate::syntax::trivial::{self, TrivialReason};
8use crate::syntax::visit::{self, Visit};
9use crate::syntax::{
10    toposort, Api, Atom, Enum, ExternType, Impl, Lifetimes, Pair, Struct, Type, TypeAlias,
11};
12use proc_macro2::Ident;
13use quote::ToTokens;
14
15pub(crate) struct Types<'a> {
16    pub all: OrderedSet<&'a Type>,
17    pub structs: UnorderedMap<&'a Ident, &'a Struct>,
18    pub enums: UnorderedMap<&'a Ident, &'a Enum>,
19    pub cxx: UnorderedSet<&'a Ident>,
20    pub rust: UnorderedSet<&'a Ident>,
21    pub aliases: UnorderedMap<&'a Ident, &'a TypeAlias>,
22    pub untrusted: UnorderedMap<&'a Ident, &'a ExternType>,
23    pub required_trivial: UnorderedMap<&'a Ident, Vec<TrivialReason<'a>>>,
24    pub impls: OrderedMap<ImplKey<'a>, Option<&'a Impl>>,
25    pub resolutions: UnorderedMap<&'a Ident, Resolution<'a>>,
26    pub struct_improper_ctypes: UnorderedSet<&'a Ident>,
27    pub toposorted_structs: Vec<&'a Struct>,
28}
29
30impl<'a> Types<'a> {
31    pub(crate) fn collect(cx: &mut Errors, apis: &'a [Api]) -> Self {
32        let mut all = OrderedSet::new();
33        let mut structs = UnorderedMap::new();
34        let mut enums = UnorderedMap::new();
35        let mut cxx = UnorderedSet::new();
36        let mut rust = UnorderedSet::new();
37        let mut aliases = UnorderedMap::new();
38        let mut untrusted = UnorderedMap::new();
39        let mut impls = OrderedMap::new();
40        let mut resolutions = UnorderedMap::new();
41        let struct_improper_ctypes = UnorderedSet::new();
42        let toposorted_structs = Vec::new();
43
44        fn visit<'a>(all: &mut OrderedSet<&'a Type>, ty: &'a Type) {
45            struct CollectTypes<'s, 'a>(&'s mut OrderedSet<&'a Type>);
46
47            impl<'s, 'a> Visit<'a> for CollectTypes<'s, 'a> {
48                fn visit_type(&mut self, ty: &'a Type) {
49                    self.0.insert(ty);
50                    visit::visit_type(self, ty);
51                }
52            }
53
54            CollectTypes(all).visit_type(ty);
55        }
56
57        let mut add_resolution = |name: &'a Pair, generics: &'a Lifetimes| {
58            resolutions.insert(&name.rust, Resolution { name, generics });
59        };
60
61        let mut type_names = UnorderedSet::new();
62        let mut function_names = UnorderedSet::new();
63        for api in apis {
64            // The same identifier is permitted to be declared as both a shared
65            // enum and extern C++ type, or shared struct and extern C++ type.
66            // That indicates to not emit the C++ enum/struct definition because
67            // it's defined by the included headers already.
68            //
69            // All other cases of duplicate identifiers are reported as an error.
70            match api {
71                Api::Include(_) => {}
72                Api::Struct(strct) => {
73                    let ident = &strct.name.rust;
74                    if !type_names.insert(ident)
75                        && (!cxx.contains(ident)
76                            || structs.contains_key(ident)
77                            || enums.contains_key(ident))
78                    {
79                        // If already declared as a struct or enum, or if
80                        // colliding with something other than an extern C++
81                        // type, then error.
82                        duplicate_name(cx, strct, ItemName::Type(ident));
83                    }
84                    structs.insert(&strct.name.rust, strct);
85                    for field in &strct.fields {
86                        visit(&mut all, &field.ty);
87                    }
88                    add_resolution(&strct.name, &strct.generics);
89                }
90                Api::Enum(enm) => {
91                    all.insert(&enm.repr.repr_type);
92                    let ident = &enm.name.rust;
93                    if !type_names.insert(ident)
94                        && (!cxx.contains(ident)
95                            || structs.contains_key(ident)
96                            || enums.contains_key(ident))
97                    {
98                        // If already declared as a struct or enum, or if
99                        // colliding with something other than an extern C++
100                        // type, then error.
101                        duplicate_name(cx, enm, ItemName::Type(ident));
102                    }
103                    enums.insert(ident, enm);
104                    add_resolution(&enm.name, &enm.generics);
105                }
106                Api::CxxType(ety) => {
107                    let ident = &ety.name.rust;
108                    if !type_names.insert(ident)
109                        && (cxx.contains(ident)
110                            || !structs.contains_key(ident) && !enums.contains_key(ident))
111                    {
112                        // If already declared as an extern C++ type, or if
113                        // colliding with something which is neither struct nor
114                        // enum, then error.
115                        duplicate_name(cx, ety, ItemName::Type(ident));
116                    }
117                    cxx.insert(ident);
118                    if !ety.trusted {
119                        untrusted.insert(ident, ety);
120                    }
121                    add_resolution(&ety.name, &ety.generics);
122                }
123                Api::RustType(ety) => {
124                    let ident = &ety.name.rust;
125                    if !type_names.insert(ident) {
126                        duplicate_name(cx, ety, ItemName::Type(ident));
127                    }
128                    rust.insert(ident);
129                    add_resolution(&ety.name, &ety.generics);
130                }
131                Api::CxxFunction(efn) | Api::RustFunction(efn) => {
132                    // Note: duplication of the C++ name is fine because C++ has
133                    // function overloading.
134                    let self_type = efn.self_type();
135                    if !self_type.is_some_and(|self_type| self_type == "Self")
136                        && !function_names.insert((self_type, &efn.name.rust))
137                    {
138                        duplicate_name(cx, efn, ItemName::Function(self_type, &efn.name.rust));
139                    }
140                    for arg in &efn.args {
141                        visit(&mut all, &arg.ty);
142                    }
143                    if let Some(ret) = &efn.ret {
144                        visit(&mut all, ret);
145                    }
146                }
147                Api::TypeAlias(alias) => {
148                    let ident = &alias.name.rust;
149                    if !type_names.insert(ident) {
150                        duplicate_name(cx, alias, ItemName::Type(ident));
151                    }
152                    cxx.insert(ident);
153                    aliases.insert(ident, alias);
154                    add_resolution(&alias.name, &alias.generics);
155                }
156                Api::Impl(imp) => {
157                    visit(&mut all, &imp.ty);
158                    if let Some(key) = imp.ty.impl_key() {
159                        impls.insert(key, Some(imp));
160                    }
161                }
162            }
163        }
164
165        for ty in &all {
166            let Some(impl_key) = ty.impl_key() else {
167                continue;
168            };
169            let implicit_impl = match &impl_key {
170                ImplKey::RustBox(ident)
171                | ImplKey::RustVec(ident)
172                | ImplKey::UniquePtr(ident)
173                | ImplKey::SharedPtr(ident)
174                | ImplKey::WeakPtr(ident)
175                | ImplKey::CxxVector(ident) => {
176                    Atom::from(ident.rust).is_none() && !aliases.contains_key(ident.rust)
177                }
178            };
179            if implicit_impl && !impls.contains_key(&impl_key) {
180                impls.insert(impl_key, None);
181            }
182        }
183
184        // All these APIs may contain types passed by value. We need to ensure
185        // we check that this is permissible. We do this _after_ scanning all
186        // the APIs above, in case some function or struct references a type
187        // which is declared subsequently.
188        let required_trivial =
189            trivial::required_trivial_reasons(apis, &all, &structs, &enums, &cxx);
190
191        let mut types = Types {
192            all,
193            structs,
194            enums,
195            cxx,
196            rust,
197            aliases,
198            untrusted,
199            required_trivial,
200            impls,
201            resolutions,
202            struct_improper_ctypes,
203            toposorted_structs,
204        };
205
206        types.toposorted_structs = toposort::sort(cx, apis, &types);
207
208        let mut unresolved_structs = types.structs.keys();
209        let mut new_information = true;
210        while new_information {
211            new_information = false;
212            unresolved_structs.retain(|ident| {
213                let mut retain = false;
214                for var in &types.structs[ident].fields {
215                    if match types.determine_improper_ctype(&var.ty) {
216                        ImproperCtype::Depends(inner) => {
217                            retain = true;
218                            types.struct_improper_ctypes.contains(inner)
219                        }
220                        ImproperCtype::Definite(improper) => improper,
221                    } {
222                        types.struct_improper_ctypes.insert(ident);
223                        new_information = true;
224                        return false;
225                    }
226                }
227                // If all fields definite false, remove from unresolved_structs.
228                retain
229            });
230        }
231
232        types
233    }
234
235    pub(crate) fn needs_indirect_abi(&self, ty: &Type) -> bool {
236        match ty {
237            Type::RustBox(_)
238            | Type::UniquePtr(_)
239            | Type::Ref(_)
240            | Type::Ptr(_)
241            | Type::Str(_)
242            | Type::Fn(_)
243            | Type::SliceRef(_) => false,
244            Type::Array(_) => true,
245            _ => !self.is_guaranteed_pod(ty) || self.is_considered_improper_ctype(ty),
246        }
247    }
248
249    // Types that trigger rustc's default #[warn(improper_ctypes)] lint, even if
250    // they may be otherwise unproblematic to mention in an extern signature.
251    // For example in a signature like `extern "C" fn(*const String)`, rustc
252    // refuses to believe that C could know how to supply us with a pointer to a
253    // Rust String, even though C could easily have obtained that pointer
254    // legitimately from a Rust call.
255    #[allow(dead_code)] // only used by cxxbridge-macro, not cxx-build
256    pub(crate) fn is_considered_improper_ctype(&self, ty: &Type) -> bool {
257        match self.determine_improper_ctype(ty) {
258            ImproperCtype::Definite(improper) => improper,
259            ImproperCtype::Depends(ident) => self.struct_improper_ctypes.contains(ident),
260        }
261    }
262
263    // Types which we need to assume could possibly exist by value on the Rust
264    // side.
265    pub(crate) fn is_maybe_trivial(&self, ty: &Ident) -> bool {
266        self.structs.contains_key(ty)
267            || self.enums.contains_key(ty)
268            || self.aliases.contains_key(ty)
269    }
270}
271
272impl<'t, 'a> IntoIterator for &'t Types<'a> {
273    type Item = &'a Type;
274    type IntoIter = crate::syntax::set::Iter<'t, 'a, Type>;
275    fn into_iter(self) -> Self::IntoIter {
276        self.all.into_iter()
277    }
278}
279
280enum ItemName<'a> {
281    Type(&'a Ident),
282    Function(Option<&'a Ident>, &'a Ident),
283}
284
285fn duplicate_name(cx: &mut Errors, sp: impl ToTokens, name: ItemName) {
286    let description = match name {
287        ItemName::Type(name) => format!("type `{}`", name),
288        ItemName::Function(Some(self_type), name) => {
289            format!("associated function `{}::{}`", self_type, name)
290        }
291        ItemName::Function(None, name) => format!("function `{}`", name),
292    };
293    let msg = format!("the {} is defined multiple times", description);
294    cx.error(sp, msg);
295}