1 use crate::syntax::atom::Atom::{self, *};
2 use crate::syntax::report::Errors;
3 use crate::syntax::types::TrivialReason;
4 use crate::syntax::{
5     error, ident, Api, Enum, ExternFn, ExternType, Impl, Lang, Receiver, Ref, Slice, Struct, Ty1,
6     Type, Types,
7 };
8 use proc_macro2::{Delimiter, Group, Ident, TokenStream};
9 use quote::{quote, ToTokens};
10 use std::fmt::Display;
11 
12 pub(crate) struct Check<'a> {
13     apis: &'a [Api],
14     types: &'a Types<'a>,
15     errors: &'a mut Errors,
16 }
17 
typecheck(cx: &mut Errors, apis: &[Api], types: &Types)18 pub(crate) fn typecheck(cx: &mut Errors, apis: &[Api], types: &Types) {
19     do_typecheck(&mut Check {
20         apis,
21         types,
22         errors: cx,
23     });
24 }
25 
do_typecheck(cx: &mut Check)26 fn do_typecheck(cx: &mut Check) {
27     ident::check_all(cx, cx.apis);
28 
29     for ty in cx.types {
30         match ty {
31             Type::Ident(ident) => check_type_ident(cx, &ident.rust),
32             Type::RustBox(ptr) => check_type_box(cx, ptr),
33             Type::RustVec(ty) => check_type_rust_vec(cx, ty),
34             Type::UniquePtr(ptr) => check_type_unique_ptr(cx, ptr),
35             Type::CxxVector(ptr) => check_type_cxx_vector(cx, ptr),
36             Type::Ref(ty) => check_type_ref(cx, ty),
37             Type::Slice(ty) => check_type_slice(cx, ty),
38             _ => {}
39         }
40     }
41 
42     for api in cx.apis {
43         match api {
44             Api::Struct(strct) => check_api_struct(cx, strct),
45             Api::Enum(enm) => check_api_enum(cx, enm),
46             Api::CxxType(ety) | Api::RustType(ety) => check_api_type(cx, ety),
47             Api::CxxFunction(efn) | Api::RustFunction(efn) => check_api_fn(cx, efn),
48             Api::Impl(imp) => check_api_impl(cx, imp),
49             _ => {}
50         }
51     }
52 }
53 
54 impl Check<'_> {
error(&mut self, sp: impl ToTokens, msg: impl Display)55     pub(crate) fn error(&mut self, sp: impl ToTokens, msg: impl Display) {
56         self.errors.error(sp, msg);
57     }
58 }
59 
check_type_ident(cx: &mut Check, ident: &Ident)60 fn check_type_ident(cx: &mut Check, ident: &Ident) {
61     if Atom::from(ident).is_none()
62         && !cx.types.structs.contains_key(ident)
63         && !cx.types.enums.contains_key(ident)
64         && !cx.types.cxx.contains(ident)
65         && !cx.types.rust.contains(ident)
66     {
67         let msg = format!("unsupported type: {}", ident);
68         cx.error(ident, &msg);
69     }
70 }
71 
check_type_box(cx: &mut Check, ptr: &Ty1)72 fn check_type_box(cx: &mut Check, ptr: &Ty1) {
73     if let Type::Ident(ident) = &ptr.inner {
74         if cx.types.cxx.contains(&ident.rust)
75             && !cx.types.structs.contains_key(&ident.rust)
76             && !cx.types.enums.contains_key(&ident.rust)
77         {
78             cx.error(ptr, error::BOX_CXX_TYPE.msg);
79         }
80 
81         if Atom::from(&ident.rust).is_none() {
82             return;
83         }
84     }
85 
86     cx.error(ptr, "unsupported target type of Box");
87 }
88 
check_type_rust_vec(cx: &mut Check, ty: &Ty1)89 fn check_type_rust_vec(cx: &mut Check, ty: &Ty1) {
90     if let Type::Ident(ident) = &ty.inner {
91         if cx.types.cxx.contains(&ident.rust)
92             && !cx.types.structs.contains_key(&ident.rust)
93             && !cx.types.enums.contains_key(&ident.rust)
94         {
95             cx.error(ty, "Rust Vec containing C++ type is not supported yet");
96             return;
97         }
98 
99         match Atom::from(&ident.rust) {
100             None | Some(U8) | Some(U16) | Some(U32) | Some(U64) | Some(Usize) | Some(I8)
101             | Some(I16) | Some(I32) | Some(I64) | Some(Isize) | Some(F32) | Some(F64)
102             | Some(RustString) => return,
103             Some(Bool) => { /* todo */ }
104             Some(CxxString) => {}
105         }
106     }
107 
108     cx.error(ty, "unsupported element type of Vec");
109 }
110 
check_type_unique_ptr(cx: &mut Check, ptr: &Ty1)111 fn check_type_unique_ptr(cx: &mut Check, ptr: &Ty1) {
112     if let Type::Ident(ident) = &ptr.inner {
113         if cx.types.rust.contains(&ident.rust) {
114             cx.error(ptr, "unique_ptr of a Rust type is not supported yet");
115         }
116 
117         match Atom::from(&ident.rust) {
118             None | Some(CxxString) => return,
119             _ => {}
120         }
121     } else if let Type::CxxVector(_) = &ptr.inner {
122         return;
123     }
124 
125     cx.error(ptr, "unsupported unique_ptr target type");
126 }
127 
check_type_cxx_vector(cx: &mut Check, ptr: &Ty1)128 fn check_type_cxx_vector(cx: &mut Check, ptr: &Ty1) {
129     if let Type::Ident(ident) = &ptr.inner {
130         if cx.types.rust.contains(&ident.rust) {
131             cx.error(
132                 ptr,
133                 "C++ vector containing a Rust type is not supported yet",
134             );
135         }
136 
137         match Atom::from(&ident.rust) {
138             None | Some(U8) | Some(U16) | Some(U32) | Some(U64) | Some(Usize) | Some(I8)
139             | Some(I16) | Some(I32) | Some(I64) | Some(Isize) | Some(F32) | Some(F64)
140             | Some(CxxString) => return,
141             Some(Bool) | Some(RustString) => {}
142         }
143     }
144 
145     cx.error(ptr, "unsupported vector target type");
146 }
147 
check_type_ref(cx: &mut Check, ty: &Ref)148 fn check_type_ref(cx: &mut Check, ty: &Ref) {
149     if ty.lifetime.is_some() {
150         cx.error(ty, "references with explicit lifetimes are not supported");
151     }
152 
153     match ty.inner {
154         Type::Fn(_) | Type::Void(_) => {}
155         Type::Ref(_) => {
156             cx.error(ty, "C++ does not allow references to references");
157             return;
158         }
159         _ => return,
160     }
161 
162     cx.error(ty, "unsupported reference type");
163 }
164 
check_type_slice(cx: &mut Check, ty: &Slice)165 fn check_type_slice(cx: &mut Check, ty: &Slice) {
166     cx.error(ty, "only &[u8] is supported so far, not other slice types");
167 }
168 
check_api_struct(cx: &mut Check, strct: &Struct)169 fn check_api_struct(cx: &mut Check, strct: &Struct) {
170     let name = &strct.name;
171     check_reserved_name(cx, &name.rust);
172 
173     if strct.fields.is_empty() {
174         let span = span_for_struct_error(strct);
175         cx.error(span, "structs without any fields are not supported");
176     }
177 
178     if cx.types.cxx.contains(&name.rust) {
179         if let Some(ety) = cx.types.untrusted.get(&name.rust) {
180             let msg = "extern shared struct must be declared in an `unsafe extern` block";
181             cx.error(ety, msg);
182         }
183     }
184 
185     for field in &strct.fields {
186         if is_unsized(cx, &field.ty) {
187             let desc = describe(cx, &field.ty);
188             let msg = format!("using {} by value is not supported", desc);
189             cx.error(field, msg);
190         }
191         if let Type::Fn(_) = field.ty {
192             cx.error(
193                 field,
194                 "function pointers in a struct field are not implemented yet",
195             );
196         }
197     }
198 }
199 
check_api_enum(cx: &mut Check, enm: &Enum)200 fn check_api_enum(cx: &mut Check, enm: &Enum) {
201     check_reserved_name(cx, &enm.name.rust);
202 
203     if enm.variants.is_empty() {
204         let span = span_for_enum_error(enm);
205         cx.error(span, "enums without any variants are not supported");
206     }
207 }
208 
check_api_type(cx: &mut Check, ety: &ExternType)209 fn check_api_type(cx: &mut Check, ety: &ExternType) {
210     check_reserved_name(cx, &ety.name.rust);
211 
212     if let Some(reason) = cx.types.required_trivial.get(&ety.name.rust) {
213         let what = match reason {
214             TrivialReason::StructField(strct) => format!("a field of `{}`", strct.name.rust),
215             TrivialReason::FunctionArgument(efn) => format!("an argument of `{}`", efn.name.rust),
216             TrivialReason::FunctionReturn(efn) => format!("a return value of `{}`", efn.name.rust),
217         };
218         let msg = format!(
219             "needs a cxx::ExternType impl in order to be used as {}",
220             what,
221         );
222         cx.error(ety, msg);
223     }
224 }
225 
check_api_fn(cx: &mut Check, efn: &ExternFn)226 fn check_api_fn(cx: &mut Check, efn: &ExternFn) {
227     if let Some(receiver) = &efn.receiver {
228         let ref span = span_for_receiver_error(receiver);
229 
230         if receiver.ty.is_self() {
231             let mutability = match receiver.mutability {
232                 Some(_) => "mut ",
233                 None => "",
234             };
235             let msg = format!(
236                 "unnamed receiver type is only allowed if the surrounding \
237                  extern block contains exactly one extern type; \
238                  use `self: &{mutability}TheType`",
239                 mutability = mutability,
240             );
241             cx.error(span, msg);
242         } else if !cx.types.structs.contains_key(&receiver.ty.rust)
243             && !cx.types.cxx.contains(&receiver.ty.rust)
244             && !cx.types.rust.contains(&receiver.ty.rust)
245         {
246             cx.error(span, "unrecognized receiver type");
247         }
248 
249         if receiver.lifetime.is_some() {
250             cx.error(span, "references with explicit lifetimes are not supported");
251         }
252     }
253 
254     for arg in &efn.args {
255         if is_unsized(cx, &arg.ty) {
256             let desc = describe(cx, &arg.ty);
257             let msg = format!("passing {} by value is not supported", desc);
258             cx.error(arg, msg);
259         }
260         if let Type::Fn(_) = arg.ty {
261             if efn.lang == Lang::Rust {
262                 cx.error(
263                     arg,
264                     "passing a function pointer from C++ to Rust is not implemented yet",
265                 );
266             }
267         }
268     }
269 
270     if let Some(ty) = &efn.ret {
271         if is_unsized(cx, ty) {
272             let desc = describe(cx, ty);
273             let msg = format!("returning {} by value is not supported", desc);
274             cx.error(ty, msg);
275         }
276         if let Type::Fn(_) = ty {
277             cx.error(ty, "returning a function pointer is not implemented yet");
278         }
279     }
280 
281     if efn.lang == Lang::Cxx {
282         check_mut_return_restriction(cx, efn);
283     }
284 
285     check_multiple_arg_lifetimes(cx, efn);
286 }
287 
check_api_impl(cx: &mut Check, imp: &Impl)288 fn check_api_impl(cx: &mut Check, imp: &Impl) {
289     if let Type::UniquePtr(ty) | Type::CxxVector(ty) = &imp.ty {
290         if let Type::Ident(inner) = &ty.inner {
291             if Atom::from(&inner.rust).is_none() {
292                 return;
293             }
294         }
295     }
296 
297     cx.error(imp, "unsupported Self type of explicit impl");
298 }
299 
check_mut_return_restriction(cx: &mut Check, efn: &ExternFn)300 fn check_mut_return_restriction(cx: &mut Check, efn: &ExternFn) {
301     match &efn.ret {
302         Some(Type::Ref(ty)) if ty.mutability.is_some() => {}
303         _ => return,
304     }
305 
306     for arg in &efn.args {
307         if let Type::Ref(ty) = &arg.ty {
308             if ty.mutability.is_some() {
309                 return;
310             }
311         }
312     }
313 
314     cx.error(
315         efn,
316         "&mut return type is not allowed unless there is a &mut argument",
317     );
318 }
319 
check_multiple_arg_lifetimes(cx: &mut Check, efn: &ExternFn)320 fn check_multiple_arg_lifetimes(cx: &mut Check, efn: &ExternFn) {
321     match &efn.ret {
322         Some(Type::Ref(_)) => {}
323         _ => return,
324     }
325 
326     let mut reference_args = 0;
327     for arg in &efn.args {
328         if let Type::Ref(_) = &arg.ty {
329             reference_args += 1;
330         }
331     }
332 
333     if efn.receiver.is_some() {
334         reference_args += 1;
335     }
336 
337     if reference_args != 1 {
338         cx.error(
339             efn,
340             "functions that return a reference must take exactly one input reference",
341         );
342     }
343 }
344 
check_reserved_name(cx: &mut Check, ident: &Ident)345 fn check_reserved_name(cx: &mut Check, ident: &Ident) {
346     if ident == "Box"
347         || ident == "UniquePtr"
348         || ident == "Vec"
349         || ident == "CxxVector"
350         || Atom::from(ident).is_some()
351     {
352         cx.error(ident, "reserved name");
353     }
354 }
355 
is_unsized(cx: &mut Check, ty: &Type) -> bool356 fn is_unsized(cx: &mut Check, ty: &Type) -> bool {
357     let ident = match ty {
358         Type::Ident(ident) => &ident.rust,
359         Type::CxxVector(_) | Type::Slice(_) | Type::Void(_) => return true,
360         _ => return false,
361     };
362     ident == CxxString
363         || cx.types.cxx.contains(ident)
364             && !cx.types.structs.contains_key(ident)
365             && !cx.types.enums.contains_key(ident)
366             && !(cx.types.aliases.contains_key(ident)
367                 && cx.types.required_trivial.contains_key(ident))
368         || cx.types.rust.contains(ident)
369 }
370 
span_for_struct_error(strct: &Struct) -> TokenStream371 fn span_for_struct_error(strct: &Struct) -> TokenStream {
372     let struct_token = strct.struct_token;
373     let mut brace_token = Group::new(Delimiter::Brace, TokenStream::new());
374     brace_token.set_span(strct.brace_token.span);
375     quote!(#struct_token #brace_token)
376 }
377 
span_for_enum_error(enm: &Enum) -> TokenStream378 fn span_for_enum_error(enm: &Enum) -> TokenStream {
379     let enum_token = enm.enum_token;
380     let mut brace_token = Group::new(Delimiter::Brace, TokenStream::new());
381     brace_token.set_span(enm.brace_token.span);
382     quote!(#enum_token #brace_token)
383 }
384 
span_for_receiver_error(receiver: &Receiver) -> TokenStream385 fn span_for_receiver_error(receiver: &Receiver) -> TokenStream {
386     let ampersand = receiver.ampersand;
387     let lifetime = &receiver.lifetime;
388     let mutability = receiver.mutability;
389     if receiver.shorthand {
390         let var = receiver.var;
391         quote!(#ampersand #lifetime #mutability #var)
392     } else {
393         let ty = &receiver.ty;
394         quote!(#ampersand #lifetime #mutability #ty)
395     }
396 }
397 
describe(cx: &mut Check, ty: &Type) -> String398 fn describe(cx: &mut Check, ty: &Type) -> String {
399     match ty {
400         Type::Ident(ident) => {
401             if cx.types.structs.contains_key(&ident.rust) {
402                 "struct".to_owned()
403             } else if cx.types.enums.contains_key(&ident.rust) {
404                 "enum".to_owned()
405             } else if cx.types.aliases.contains_key(&ident.rust) {
406                 "C++ type".to_owned()
407             } else if cx.types.cxx.contains(&ident.rust) {
408                 "opaque C++ type".to_owned()
409             } else if cx.types.rust.contains(&ident.rust) {
410                 "opaque Rust type".to_owned()
411             } else if Atom::from(&ident.rust) == Some(CxxString) {
412                 "C++ string".to_owned()
413             } else {
414                 ident.rust.to_string()
415             }
416         }
417         Type::RustBox(_) => "Box".to_owned(),
418         Type::RustVec(_) => "Vec".to_owned(),
419         Type::UniquePtr(_) => "unique_ptr".to_owned(),
420         Type::Ref(_) => "reference".to_owned(),
421         Type::Str(_) => "&str".to_owned(),
422         Type::CxxVector(_) => "C++ vector".to_owned(),
423         Type::Slice(_) => "slice".to_owned(),
424         Type::SliceRefU8(_) => "&[u8]".to_owned(),
425         Type::Fn(_) => "function pointer".to_owned(),
426         Type::Void(_) => "()".to_owned(),
427     }
428 }
429