• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::syntax::improper::ImproperCtype;
2 use crate::syntax::instantiate::ImplKey;
3 use crate::syntax::map::{OrderedMap, UnorderedMap};
4 use crate::syntax::report::Errors;
5 use crate::syntax::resolve::Resolution;
6 use crate::syntax::set::{OrderedSet, UnorderedSet};
7 use crate::syntax::trivial::{self, TrivialReason};
8 use crate::syntax::visit::{self, Visit};
9 use crate::syntax::{
10     toposort, Api, Atom, Enum, EnumRepr, ExternType, Impl, Lifetimes, Pair, Struct, Type, TypeAlias,
11 };
12 use proc_macro2::Ident;
13 use quote::ToTokens;
14 
15 pub 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 
30 impl<'a> Types<'a> {
collect(cx: &mut Errors, apis: &'a [Api]) -> Self31     pub 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, 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                     match &enm.repr {
92                         EnumRepr::Native { atom: _, repr_type } => {
93                             all.insert(repr_type);
94                         }
95                         EnumRepr::Foreign { rust_type: _ } => {}
96                     }
97                     let ident = &enm.name.rust;
98                     if !type_names.insert(ident)
99                         && (!cxx.contains(ident)
100                             || structs.contains_key(ident)
101                             || enums.contains_key(ident))
102                     {
103                         // If already declared as a struct or enum, or if
104                         // colliding with something other than an extern C++
105                         // type, then error.
106                         duplicate_name(cx, enm, ident);
107                     }
108                     enums.insert(ident, enm);
109                     if enm.variants_from_header {
110                         // #![variants_from_header] enums are implicitly extern
111                         // C++ type.
112                         cxx.insert(&enm.name.rust);
113                     }
114                     add_resolution(&enm.name, &enm.generics);
115                 }
116                 Api::CxxType(ety) => {
117                     let ident = &ety.name.rust;
118                     if !type_names.insert(ident)
119                         && (cxx.contains(ident)
120                             || !structs.contains_key(ident) && !enums.contains_key(ident))
121                     {
122                         // If already declared as an extern C++ type, or if
123                         // colliding with something which is neither struct nor
124                         // enum, then error.
125                         duplicate_name(cx, ety, ident);
126                     }
127                     cxx.insert(ident);
128                     if !ety.trusted {
129                         untrusted.insert(ident, ety);
130                     }
131                     add_resolution(&ety.name, &ety.generics);
132                 }
133                 Api::RustType(ety) => {
134                     let ident = &ety.name.rust;
135                     if !type_names.insert(ident) {
136                         duplicate_name(cx, ety, ident);
137                     }
138                     rust.insert(ident);
139                     add_resolution(&ety.name, &ety.generics);
140                 }
141                 Api::CxxFunction(efn) | Api::RustFunction(efn) => {
142                     // Note: duplication of the C++ name is fine because C++ has
143                     // function overloading.
144                     if !function_names.insert((&efn.receiver, &efn.name.rust)) {
145                         duplicate_name(cx, efn, &efn.name.rust);
146                     }
147                     for arg in &efn.args {
148                         visit(&mut all, &arg.ty);
149                     }
150                     if let Some(ret) = &efn.ret {
151                         visit(&mut all, ret);
152                     }
153                 }
154                 Api::TypeAlias(alias) => {
155                     let ident = &alias.name.rust;
156                     if !type_names.insert(ident) {
157                         duplicate_name(cx, alias, ident);
158                     }
159                     cxx.insert(ident);
160                     aliases.insert(ident, alias);
161                     add_resolution(&alias.name, &alias.generics);
162                 }
163                 Api::Impl(imp) => {
164                     visit(&mut all, &imp.ty);
165                     if let Some(key) = imp.ty.impl_key() {
166                         impls.insert(key, Some(imp));
167                     }
168                 }
169             }
170         }
171 
172         for ty in &all {
173             let impl_key = match ty.impl_key() {
174                 Some(impl_key) => impl_key,
175                 None => continue,
176             };
177             let implicit_impl = match impl_key {
178                 ImplKey::RustBox(ident)
179                 | ImplKey::RustVec(ident)
180                 | ImplKey::UniquePtr(ident)
181                 | ImplKey::SharedPtr(ident)
182                 | ImplKey::WeakPtr(ident)
183                 | ImplKey::CxxVector(ident) => {
184                     Atom::from(ident.rust).is_none() && !aliases.contains_key(ident.rust)
185                 }
186             };
187             if implicit_impl && !impls.contains_key(&impl_key) {
188                 impls.insert(impl_key, None);
189             }
190         }
191 
192         // All these APIs may contain types passed by value. We need to ensure
193         // we check that this is permissible. We do this _after_ scanning all
194         // the APIs above, in case some function or struct references a type
195         // which is declared subsequently.
196         let required_trivial =
197             trivial::required_trivial_reasons(apis, &all, &structs, &enums, &cxx);
198 
199         let mut types = Types {
200             all,
201             structs,
202             enums,
203             cxx,
204             rust,
205             aliases,
206             untrusted,
207             required_trivial,
208             impls,
209             resolutions,
210             struct_improper_ctypes,
211             toposorted_structs,
212         };
213 
214         types.toposorted_structs = toposort::sort(cx, apis, &types);
215 
216         let mut unresolved_structs = types.structs.keys();
217         let mut new_information = true;
218         while new_information {
219             new_information = false;
220             unresolved_structs.retain(|ident| {
221                 let mut retain = false;
222                 for var in &types.structs[ident].fields {
223                     if match types.determine_improper_ctype(&var.ty) {
224                         ImproperCtype::Depends(inner) => {
225                             retain = true;
226                             types.struct_improper_ctypes.contains(inner)
227                         }
228                         ImproperCtype::Definite(improper) => improper,
229                     } {
230                         types.struct_improper_ctypes.insert(ident);
231                         new_information = true;
232                         return false;
233                     }
234                 }
235                 // If all fields definite false, remove from unresolved_structs.
236                 retain
237             });
238         }
239 
240         types
241     }
242 
needs_indirect_abi(&self, ty: &Type) -> bool243     pub fn needs_indirect_abi(&self, ty: &Type) -> bool {
244         match ty {
245             Type::RustBox(_) | Type::UniquePtr(_) => false,
246             Type::Array(_) => true,
247             _ => !self.is_guaranteed_pod(ty),
248         }
249     }
250 
251     // Types that trigger rustc's default #[warn(improper_ctypes)] lint, even if
252     // they may be otherwise unproblematic to mention in an extern signature.
253     // For example in a signature like `extern "C" fn(*const String)`, rustc
254     // refuses to believe that C could know how to supply us with a pointer to a
255     // Rust String, even though C could easily have obtained that pointer
256     // legitimately from a Rust call.
is_considered_improper_ctype(&self, ty: &Type) -> bool257     pub fn is_considered_improper_ctype(&self, ty: &Type) -> bool {
258         match self.determine_improper_ctype(ty) {
259             ImproperCtype::Definite(improper) => improper,
260             ImproperCtype::Depends(ident) => self.struct_improper_ctypes.contains(ident),
261         }
262     }
263 
264     // Types which we need to assume could possibly exist by value on the Rust
265     // side.
is_maybe_trivial(&self, ty: &Ident) -> bool266     pub fn is_maybe_trivial(&self, ty: &Ident) -> bool {
267         self.structs.contains_key(ty)
268             || self.enums.contains_key(ty)
269             || self.aliases.contains_key(ty)
270     }
271 }
272 
273 impl<'t, 'a> IntoIterator for &'t Types<'a> {
274     type Item = &'a Type;
275     type IntoIter = crate::syntax::set::Iter<'t, 'a, Type>;
into_iter(self) -> Self::IntoIter276     fn into_iter(self) -> Self::IntoIter {
277         self.all.into_iter()
278     }
279 }
280 
duplicate_name(cx: &mut Errors, sp: impl ToTokens, ident: &Ident)281 fn duplicate_name(cx: &mut Errors, sp: impl ToTokens, ident: &Ident) {
282     let msg = format!("the name `{}` is defined multiple times", ident);
283     cx.error(sp, msg);
284 }
285