Debian Codegraph @

third_party/rust/diplomat_core/src/hir/lowering.rs

raw
1 use super::{
2 AttributeContext, AttributeValidator, Attrs, Borrow, BoundedLifetime, EnumDef, EnumPath,
3 EnumVariant, IdentBuf, IntType, Lifetime, LifetimeEnv, LifetimeLowerer, LookupId, MaybeOwn,
4 Method, NonOptional, OpaqueDef, OpaquePath, Optional, OutStructDef, OutStructField,
5 OutStructPath, OutType, Param, ParamLifetimeLowerer, ParamSelf, PrimitiveType,
6 ReturnLifetimeLowerer, ReturnType, ReturnableStructPath, SelfParamLifetimeLowerer, SelfType,
7 Slice, SpecialMethod, SpecialMethodPresence, StructDef, StructField, StructPath, SuccessType,
8 Type, TypeDef, TypeId,
9 };
10 use crate::ast::attrs::AttrInheritContext;
11 use crate::{ast, Env};
12 use core::fmt;
13 use strck_ident::IntoCk;
14
15 /// An error from lowering the AST to the HIR.
16 #[derive(Debug)]
17 #[non_exhaustive]
18 pub enum LoweringError {
19 /// The purpose of having this is that translating to the HIR has enormous
20 /// potential for really detailed error handling and giving suggestions.
21 ///
22 /// Unfortunately, working out what the error enum should look like to enable
23 /// this is really hard. The plan is that once the lowering code is completely
24 /// written, we ctrl+F for `"LoweringError::Other"` in the lowering code, and turn every
25 /// instance into an specialized enum variant, generalizing where possible
26 /// without losing any information.
27 Other(String),
28 }
29
30 impl fmt::Display for LoweringError {
31 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
32 match *self {
33 Self::Other(ref s) => s.fmt(f),
34 }
35 }
36 }
37
38 #[derive(Default, Clone)]
39 pub struct ErrorContext {
40 item: String,
41 subitem: Option<String>,
42 }
43
44 impl fmt::Display for ErrorContext {
45 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46 if let Some(ref subitem) = self.subitem {
47 write!(f, "{}::{subitem}", self.item)
48 } else {
49 self.item.fmt(f)
50 }
51 }
52 }
53
54 impl fmt::Debug for ErrorContext {
55 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56 fmt::Display::fmt(self, f)
57 }
58 }
59
60 /// An error store, which one can push errors to. It keeps track of the
61 /// current "context" for the error, usually a type or a type::method. `'tree`
62 /// is the AST/HIR tree it is temporarily borrowing from for the context.
63 #[derive(Default)]
64 pub struct ErrorStore<'tree> {
65 /// The errors
66 errors: Vec<ErrorAndContext>,
67 /// The current context (types, modules)
68 item: &'tree str,
69 /// The current sub-item context (methods, etc)
70 subitem: Option<&'tree str>,
71 }
72
73 pub type ErrorAndContext = (ErrorContext, LoweringError);
74
75 impl<'tree> ErrorStore<'tree> {
76 /// Push an error to the error store
77 pub fn push(&mut self, error: LoweringError) {
78 let context = ErrorContext {
79 item: self.item.into(),
80 subitem: self.subitem.map(|s| s.into()),
81 };
82 self.errors.push((context, error));
83 }
84
85 pub(super) fn take_errors(&mut self) -> Vec<ErrorAndContext> {
86 core::mem::take(&mut self.errors)
87 }
88
89 pub(super) fn is_empty(&self) -> bool {
90 self.errors.is_empty()
91 }
92
93 pub(super) fn set_item(&mut self, item: &'tree str) {
94 self.item = item;
95 self.subitem = None;
96 }
97 pub(super) fn set_subitem(&mut self, subitem: &'tree str) {
98 self.subitem = Some(subitem);
99 }
100 }
101
102 pub(super) struct LoweringContext<'ast> {
103 pub lookup_id: LookupId<'ast>,
104 pub errors: ErrorStore<'ast>,
105 pub env: &'ast Env,
106 pub attr_validator: Box<dyn AttributeValidator>,
107 }
108
109 /// An item and the info needed to
110 pub(crate) struct ItemAndInfo<'ast, Ast> {
111 pub(crate) item: &'ast Ast,
112 pub(crate) in_path: &'ast ast::Path,
113 /// Any parent attributes resolved from the module, for a type context
114 pub(crate) ty_parent_attrs: Attrs,
115
116 /// Any parent attributes resolved from the module, for a method context
117 pub(crate) method_parent_attrs: Attrs,
118 pub(crate) id: TypeId,
119 }
120
121 impl<'ast> LoweringContext<'ast> {
122 /// Lowers an [`ast::Ident`]s into an [`hir::IdentBuf`].
123 ///
124 /// If there are any errors, they're pushed to `errors` and `Err` is returned.
125 pub(super) fn lower_ident(
126 &mut self,
127 ident: &ast::Ident,
128 context: &'static str,
129 ) -> Result<IdentBuf, ()> {
130 match ident.as_str().ck() {
131 Ok(name) => Ok(name.to_owned()),
132 Err(e) => {
133 self.errors.push(LoweringError::Other(format!(
134 "Ident `{ident}` from {context} could not be turned into a Rust ident: {e}"
135 )));
136 Err(())
137 }
138 }
139 }
140
141 /// Lowers multiple items at once
142 fn lower_all<Ast: 'static, Hir>(
143 &mut self,
144 ast_defs: impl ExactSizeIterator<Item = ItemAndInfo<'ast, Ast>>,
145 lower: impl Fn(&mut Self, ItemAndInfo<'ast, Ast>) -> Result<Hir, ()>,
146 ) -> Result<Vec<Hir>, ()> {
147 let mut hir_types = Ok(Vec::with_capacity(ast_defs.len()));
148
149 for def in ast_defs {
150 let hir_type = lower(self, def);
151
152 match (hir_type, &mut hir_types) {
153 (Ok(hir_type), Ok(hir_types)) => hir_types.push(hir_type),
154 _ => hir_types = Err(()),
155 }
156 }
157
158 hir_types
159 }
160
161 pub(super) fn lower_all_enums(
162 &mut self,
163 ast_defs: impl ExactSizeIterator<Item = ItemAndInfo<'ast, ast::Enum>>,
164 ) -> Result<Vec<EnumDef>, ()> {
165 self.lower_all(ast_defs, Self::lower_enum)
166 }
167 pub(super) fn lower_all_structs(
168 &mut self,
169 ast_defs: impl ExactSizeIterator<Item = ItemAndInfo<'ast, ast::Struct>>,
170 ) -> Result<Vec<StructDef>, ()> {
171 self.lower_all(ast_defs, Self::lower_struct)
172 }
173 pub(super) fn lower_all_out_structs(
174 &mut self,
175 ast_defs: impl ExactSizeIterator<Item = ItemAndInfo<'ast, ast::Struct>>,
176 ) -> Result<Vec<OutStructDef>, ()> {
177 self.lower_all(ast_defs, Self::lower_out_struct)
178 }
179 pub(super) fn lower_all_opaques(
180 &mut self,
181 ast_defs: impl ExactSizeIterator<Item = ItemAndInfo<'ast, ast::OpaqueStruct>>,
182 ) -> Result<Vec<OpaqueDef>, ()> {
183 self.lower_all(ast_defs, Self::lower_opaque)
184 }
185
186 fn lower_enum(&mut self, item: ItemAndInfo<'ast, ast::Enum>) -> Result<EnumDef, ()> {
187 let ast_enum = item.item;
188 self.errors.set_item(ast_enum.name.as_str());
189 let name = self.lower_ident(&ast_enum.name, "enum name");
190 let attrs = self.attr_validator.attr_from_ast(
191 &ast_enum.attrs,
192 &item.ty_parent_attrs,
193 &mut self.errors,
194 );
195
196 let mut variants = Ok(Vec::with_capacity(ast_enum.variants.len()));
197 let variant_parent_attrs = attrs.for_inheritance(AttrInheritContext::Variant);
198 for (ident, discriminant, docs, attrs) in ast_enum.variants.iter() {
199 let name = self.lower_ident(ident, "enum variant");
200 let attrs =
201 self.attr_validator
202 .attr_from_ast(attrs, &variant_parent_attrs, &mut self.errors);
203 match (name, &mut variants) {
204 (Ok(name), Ok(variants)) => {
205 let variant = EnumVariant {
206 docs: docs.clone(),
207 name,
208 discriminant: *discriminant,
209 attrs,
210 };
211 self.attr_validator.validate(
212 &variant.attrs,
213 AttributeContext::EnumVariant(&variant),
214 &mut self.errors,
215 );
216 variants.push(variant);
217 }
218 _ => variants = Err(()),
219 }
220 }
221
222 let mut special_method_presence = SpecialMethodPresence::default();
223 let methods = if attrs.disable {
224 Vec::new()
225 } else {
226 self.lower_all_methods(
227 &ast_enum.methods[..],
228 item.in_path,
229 &item.method_parent_attrs,
230 item.id,
231 &mut special_method_presence,
232 )?
233 };
234
235 let def = EnumDef::new(
236 ast_enum.docs.clone(),
237 name?,
238 variants?,
239 methods,
240 attrs,
241 special_method_presence,
242 );
243
244 self.attr_validator.validate(
245 &def.attrs,
246 AttributeContext::Type(TypeDef::from(&def)),
247 &mut self.errors,
248 );
249
250 Ok(def)
251 }
252
253 fn lower_opaque(
254 &mut self,
255 item: ItemAndInfo<'ast, ast::OpaqueStruct>,
256 ) -> Result<OpaqueDef, ()> {
257 let ast_opaque = item.item;
258 self.errors.set_item(ast_opaque.name.as_str());
259 let name = self.lower_ident(&ast_opaque.name, "opaque name");
260
261 let attrs = self.attr_validator.attr_from_ast(
262 &ast_opaque.attrs,
263 &item.ty_parent_attrs,
264 &mut self.errors,
265 );
266 let mut special_method_presence = SpecialMethodPresence::default();
267 let methods = if attrs.disable {
268 Vec::new()
269 } else {
270 self.lower_all_methods(
271 &ast_opaque.methods[..],
272 item.in_path,
273 &item.method_parent_attrs,
274 item.id,
275 &mut special_method_presence,
276 )?
277 };
278 let lifetimes = self.lower_type_lifetime_env(&ast_opaque.lifetimes);
279
280 let def = OpaqueDef::new(
281 ast_opaque.docs.clone(),
282 name?,
283 methods,
284 attrs,
285 lifetimes?,
286 special_method_presence,
287 );
288 self.attr_validator.validate(
289 &def.attrs,
290 AttributeContext::Type(TypeDef::from(&def)),
291 &mut self.errors,
292 );
293 Ok(def)
294 }
295
296 fn lower_struct(&mut self, item: ItemAndInfo<'ast, ast::Struct>) -> Result<StructDef, ()> {
297 let ast_struct = item.item;
298 self.errors.set_item(ast_struct.name.as_str());
299 let name = self.lower_ident(&ast_struct.name, "struct name");
300
301 let fields = if ast_struct.fields.is_empty() {
302 self.errors.push(LoweringError::Other(format!(
303 "struct `{}` is a ZST because it has no fields",
304 ast_struct.name
305 )));
306 Err(())
307 } else {
308 let mut fields = Ok(Vec::with_capacity(ast_struct.fields.len()));
309
310 for (name, ty, docs) in ast_struct.fields.iter() {
311 let name = self.lower_ident(name, "struct field name");
312 let ty = self.lower_type(ty, &mut &ast_struct.lifetimes, item.in_path);
313
314 match (name, ty, &mut fields) {
315 (Ok(name), Ok(ty), Ok(fields)) => fields.push(StructField {
316 docs: docs.clone(),
317 name,
318 ty,
319 }),
320 _ => fields = Err(()),
321 }
322 }
323
324 fields
325 };
326 let attrs = self.attr_validator.attr_from_ast(
327 &ast_struct.attrs,
328 &item.ty_parent_attrs,
329 &mut self.errors,
330 );
331 let lifetimes = self.lower_type_lifetime_env(&ast_struct.lifetimes);
332
333 let mut special_method_presence = SpecialMethodPresence::default();
334 let methods = if attrs.disable {
335 Vec::new()
336 } else {
337 self.lower_all_methods(
338 &ast_struct.methods[..],
339 item.in_path,
340 &item.method_parent_attrs,
341 item.id,
342 &mut special_method_presence,
343 )?
344 };
345 let def = StructDef::new(
346 ast_struct.docs.clone(),
347 name?,
348 fields?,
349 methods,
350 attrs,
351 lifetimes?,
352 special_method_presence,
353 );
354
355 self.attr_validator.validate(
356 &def.attrs,
357 AttributeContext::Type(TypeDef::from(&def)),
358 &mut self.errors,
359 );
360 Ok(def)
361 }
362
363 fn lower_out_struct(
364 &mut self,
365 item: ItemAndInfo<'ast, ast::Struct>,
366 ) -> Result<OutStructDef, ()> {
367 let ast_out_struct = item.item;
368 self.errors.set_item(ast_out_struct.name.as_str());
369 let name = self.lower_ident(&ast_out_struct.name, "out-struct name");
370
371 let fields = if ast_out_struct.fields.is_empty() {
372 self.errors.push(LoweringError::Other(format!(
373 "struct `{}` is a ZST because it has no fields",
374 ast_out_struct.name
375 )));
376 Err(())
377 } else {
378 let mut fields = Ok(Vec::with_capacity(ast_out_struct.fields.len()));
379
380 for (name, ty, docs) in ast_out_struct.fields.iter() {
381 let name = self.lower_ident(name, "out-struct field name");
382 let ty =
383 self.lower_out_type(ty, &mut &ast_out_struct.lifetimes, item.in_path, true);
384
385 match (name, ty, &mut fields) {
386 (Ok(name), Ok(ty), Ok(fields)) => fields.push(OutStructField {
387 docs: docs.clone(),
388 name,
389 ty,
390 }),
391 _ => fields = Err(()),
392 }
393 }
394
395 fields
396 };
397 let attrs = self.attr_validator.attr_from_ast(
398 &ast_out_struct.attrs,
399 &item.ty_parent_attrs,
400 &mut self.errors,
401 );
402 let mut special_method_presence = SpecialMethodPresence::default();
403 let methods = if attrs.disable {
404 Vec::new()
405 } else {
406 self.lower_all_methods(
407 &ast_out_struct.methods[..],
408 item.in_path,
409 &item.method_parent_attrs,
410 item.id,
411 &mut special_method_presence,
412 )?
413 };
414
415 let lifetimes = self.lower_type_lifetime_env(&ast_out_struct.lifetimes);
416 let def = OutStructDef::new(
417 ast_out_struct.docs.clone(),
418 name?,
419 fields?,
420 methods,
421 attrs,
422 lifetimes?,
423 special_method_presence,
424 );
425
426 self.attr_validator.validate(
427 &def.attrs,
428 AttributeContext::Type(TypeDef::from(&def)),
429 &mut self.errors,
430 );
431 Ok(def)
432 }
433
434 /// Lowers an [`ast::Method`]s an [`hir::Method`].
435 ///
436 /// If there are any errors, they're pushed to `errors` and `None` is returned.
437 fn lower_method(
438 &mut self,
439 method: &'ast ast::Method,
440 in_path: &ast::Path,
441 method_parent_attrs: &Attrs,
442 self_id: TypeId,
443 special_method_presence: &mut SpecialMethodPresence,
444 ) -> Result<Method, ()> {
445 self.errors.set_subitem(method.name.as_str());
446 let name = self.lower_ident(&method.name, "method name");
447
448 let (ast_params, takes_writeable) = match method.params.split_last() {
449 Some((last, remaining)) if last.is_writeable() => (remaining, true),
450 _ => (&method.params[..], false),
451 };
452
453 let self_param_ltl = SelfParamLifetimeLowerer::new(&method.lifetime_env, self)?;
454
455 let (param_self, param_ltl) = if let Some(self_param) = method.self_param.as_ref() {
456 let (param_self, param_ltl) =
457 self.lower_self_param(self_param, self_param_ltl, &method.full_path_name, in_path)?;
458 (Some(param_self), param_ltl)
459 } else {
460 (None, SelfParamLifetimeLowerer::no_self_ref(self_param_ltl))
461 };
462
463 let (params, return_ltl) = self.lower_many_params(ast_params, param_ltl, in_path)?;
464
465 let (output, lifetime_env) = self.lower_return_type(
466 method.return_type.as_ref(),
467 takes_writeable,
468 return_ltl,
469 in_path,
470 )?;
471
472 let attrs =
473 self.attr_validator
474 .attr_from_ast(&method.attrs, method_parent_attrs, &mut self.errors);
475
476 let hir_method = Method {
477 docs: method.docs.clone(),
478 name: name?,
479 lifetime_env,
480 param_self,
481 params,
482 output,
483 attrs,
484 };
485
486 self.attr_validator.validate(
487 &hir_method.attrs,
488 AttributeContext::Method(&hir_method, self_id, special_method_presence),
489 &mut self.errors,
490 );
491
492 let is_comparison = matches!(
493 hir_method.attrs.special_method,
494 Some(SpecialMethod::Comparison)
495 );
496 if is_comparison && method.return_type != Some(ast::TypeName::Ordering) {
497 self.errors.push(LoweringError::Other(
498 "Found comparison method that does not return cmp::Ordering".into(),
499 ));
500 return Err(());
501 }
502
503 Ok(hir_method)
504 }
505
506 /// Lowers many [`ast::Method`]s into a vector of [`hir::Method`]s.
507 ///
508 /// If there are any errors, they're pushed to `errors` and `None` is returned.
509 fn lower_all_methods(
510 &mut self,
511 ast_methods: &'ast [ast::Method],
512 in_path: &ast::Path,
513 method_parent_attrs: &Attrs,
514 self_id: TypeId,
515 special_method_presence: &mut SpecialMethodPresence,
516 ) -> Result<Vec<Method>, ()> {
517 let mut methods = Ok(Vec::with_capacity(ast_methods.len()));
518
519 for method in ast_methods {
520 let method = self.lower_method(
521 method,
522 in_path,
523 method_parent_attrs,
524 self_id,
525 special_method_presence,
526 );
527 match (method, &mut methods) {
528 (Ok(method), Ok(methods)) => {
529 methods.push(method);
530 }
531 _ => methods = Err(()),
532 }
533 }
534
535 methods
536 }
537
538 /// Lowers an [`ast::TypeName`]s into a [`hir::Type`].
539 ///
540 /// If there are any errors, they're pushed to `errors` and `None` is returned.
541 fn lower_type(
542 &mut self,
543 ty: &ast::TypeName,
544 ltl: &mut impl LifetimeLowerer,
545 in_path: &ast::Path,
546 ) -> Result<Type, ()> {
547 match ty {
548 ast::TypeName::Primitive(prim) => Ok(Type::Primitive(PrimitiveType::from_ast(*prim))),
549 ast::TypeName::Ordering => {
550 self.errors.push(LoweringError::Other("Found cmp::Ordering in parameter or struct field, it is only allowed in return types".to_string()));
551 Err(())
552 }
553 ast::TypeName::Named(path) | ast::TypeName::SelfType(path) => {
554 match path.resolve(in_path, self.env) {
555 ast::CustomType::Struct(strct) => {
556 if let Some(tcx_id) = self.lookup_id.resolve_struct(strct) {
557 let lifetimes = ltl.lower_generics(
558 &path.lifetimes[..],
559 &strct.lifetimes,
560 ty.is_self(),
561 );
562
563 Ok(Type::Struct(StructPath::new(lifetimes, tcx_id)))
564 } else if self.lookup_id.resolve_out_struct(strct).is_some() {
565 self.errors.push(LoweringError::Other(format!("found struct in input that is marked with #[diplomat::out]: {ty} in {path}")));
566 Err(())
567 } else {
568 unreachable!("struct `{}` wasn't found in the set of structs or out-structs, this is a bug.", strct.name);
569 }
570 }
571 ast::CustomType::Opaque(_) => {
572 self.errors.push(LoweringError::Other(format!(
573 "Opaque passed by value: {path}"
574 )));
575 Err(())
576 }
577 ast::CustomType::Enum(enm) => {
578 let tcx_id = self.lookup_id.resolve_enum(enm).expect(
579 "can't find enum in lookup map, which contains all enums from env",
580 );
581
582 Ok(Type::Enum(EnumPath::new(tcx_id)))
583 }
584 }
585 }
586 ast::TypeName::Reference(lifetime, mutability, ref_ty) => match ref_ty.as_ref() {
587 ast::TypeName::Named(path) | ast::TypeName::SelfType(path) => {
588 match path.resolve(in_path, self.env) {
589 ast::CustomType::Opaque(opaque) => {
590 let borrow = Borrow::new(ltl.lower_lifetime(lifetime), *mutability);
591 let lifetimes = ltl.lower_generics(
592 &path.lifetimes[..],
593 &opaque.lifetimes,
594 ref_ty.is_self(),
595 );
596 let tcx_id = self.lookup_id.resolve_opaque(opaque).expect(
597 "can't find opaque in lookup map, which contains all opaques from env",
598 );
599
600 Ok(Type::Opaque(OpaquePath::new(
601 lifetimes,
602 Optional(false),
603 borrow,
604 tcx_id,
605 )))
606 }
607 _ => {
608 self.errors.push(LoweringError::Other(format!("found &T in input where T is a custom type, but not opaque. T = {ref_ty}")));
609 Err(())
610 }
611 }
612 }
613 _ => {
614 self.errors.push(LoweringError::Other(format!("found &T in input where T isn't a custom type and therefore not opaque. T = {ref_ty}")));
615 Err(())
616 }
617 },
618 ast::TypeName::Box(box_ty) => {
619 self.errors.push(match box_ty.as_ref() {
620 ast::TypeName::Named(path) | ast::TypeName::SelfType(path) => {
621 match path.resolve(in_path, self.env) {
622 ast::CustomType::Opaque(_) => LoweringError::Other(format!("found Box<T> in input where T is an opaque, but owned opaques aren't allowed in inputs. try &T instead? T = {path}")),
623 _ => LoweringError::Other(format!("found Box<T> in input where T is a custom type but not opaque. non-opaques can't be behind pointers, and opaques in inputs can't be owned. T = {path}")),
624 }
625 }
626 _ => LoweringError::Other(format!("found Box<T> in input where T isn't a custom type. T = {box_ty}")),
627 });
628 Err(())
629 }
630 ast::TypeName::Option(opt_ty) => {
631 match opt_ty.as_ref() {
632 ast::TypeName::Reference(lifetime, mutability, ref_ty) => match ref_ty.as_ref()
633 {
634 ast::TypeName::Named(path) | ast::TypeName::SelfType(path) => match path
635 .resolve(in_path, self.env)
636 {
637 ast::CustomType::Opaque(opaque) => {
638 let borrow = Borrow::new(ltl.lower_lifetime(lifetime), *mutability);
639 let lifetimes = ltl.lower_generics(
640 &path.lifetimes,
641 &opaque.lifetimes,
642 ref_ty.is_self(),
643 );
644 let tcx_id = self.lookup_id.resolve_opaque(opaque).expect(
645 "can't find opaque in lookup map, which contains all opaques from env",
646 );
647
648 Ok(Type::Opaque(OpaquePath::new(
649 lifetimes,
650 Optional(true),
651 borrow,
652 tcx_id,
653 )))
654 }
655 _ => {
656 self.errors.push(LoweringError::Other(format!("found Option<&T> in input where T is a custom type, but it's not opaque. T = {ref_ty}")));
657 Err(())
658 }
659 },
660 _ => {
661 self.errors.push(LoweringError::Other(format!("found Option<&T> in input, but T isn't a custom type and therefore not opaque. T = {ref_ty}")));
662 Err(())
663 }
664 },
665 ast::TypeName::Box(box_ty) => {
666 // we could see whats in the box here too
667 self.errors.push(LoweringError::Other(format!("found Option<Box<T>> in input, but box isn't allowed in inputs. T = {box_ty}")));
668 Err(())
669 }
670 _ => {
671 self.errors.push(LoweringError::Other(format!("found Option<T> in input, where T isn't a reference but Option<T> in inputs requires that T is a reference to an opaque. T = {opt_ty}")));
672 Err(())
673 }
674 }
675 }
676 ast::TypeName::Result(_, _, _) => {
677 self.errors.push(LoweringError::Other(
678 "Results can only appear as the top-level return type of methods".into(),
679 ));
680 Err(())
681 }
682 ast::TypeName::Writeable => {
683 self.errors.push(LoweringError::Other(
684 "Writeables can only appear as the last parameter of a method".into(),
685 ));
686 Err(())
687 }
688 ast::TypeName::StrReference(lifetime, encoding) => Ok(Type::Slice(Slice::Str(
689 lifetime.as_ref().map(|lt| ltl.lower_lifetime(lt)),
690 *encoding,
691 ))),
692 ast::TypeName::StrSlice(encoding) => Ok(Type::Slice(Slice::Strs(*encoding))),
693 ast::TypeName::PrimitiveSlice(lm, prim) => Ok(Type::Slice(Slice::Primitive(
694 lm.as_ref()
695 .map(|(lt, m)| Borrow::new(ltl.lower_lifetime(lt), *m)),
696 PrimitiveType::from_ast(*prim),
697 ))),
698 ast::TypeName::Unit => {
699 self.errors.push(LoweringError::Other("Unit types can only appear as the return value of a method, or as the Ok/Err variants of a returned result".into()));
700 Err(())
701 }
702 }
703 }
704
705 /// Lowers an [`ast::TypeName`]s into an [`hir::OutType`].
706 ///
707 /// If there are any errors, they're pushed to `errors` and `None` is returned.
708 fn lower_out_type(
709 &mut self,
710 ty: &ast::TypeName,
711 ltl: &mut impl LifetimeLowerer,
712 in_path: &ast::Path,
713 in_struct: bool,
714 ) -> Result<OutType, ()> {
715 match ty {
716 ast::TypeName::Primitive(prim) => {
717 Ok(OutType::Primitive(PrimitiveType::from_ast(*prim)))
718 }
719 ast::TypeName::Ordering => {
720 if in_struct {
721 self.errors.push(LoweringError::Other(
722 "Found cmp::Ordering in struct field, it is only allowed in return types"
723 .to_string(),
724 ));
725 Err(())
726 } else {
727 Ok(Type::Primitive(PrimitiveType::Int(IntType::I8)))
728 }
729 }
730 ast::TypeName::Named(path) | ast::TypeName::SelfType(path) => {
731 match path.resolve(in_path, self.env) {
732 ast::CustomType::Struct(strct) => {
733 let lifetimes =
734 ltl.lower_generics(&path.lifetimes, &strct.lifetimes, ty.is_self());
735
736 if let Some(tcx_id) = self.lookup_id.resolve_struct(strct) {
737 Ok(OutType::Struct(ReturnableStructPath::Struct(
738 StructPath::new(lifetimes, tcx_id),
739 )))
740 } else if let Some(tcx_id) = self.lookup_id.resolve_out_struct(strct) {
741 Ok(OutType::Struct(ReturnableStructPath::OutStruct(
742 OutStructPath::new(lifetimes, tcx_id),
743 )))
744 } else {
745 unreachable!("struct `{}` wasn't found in the set of structs or out-structs, this is a bug.", strct.name);
746 }
747 }
748 ast::CustomType::Opaque(_) => {
749 self.errors.push(LoweringError::Other(format!(
750 "Opaque passed by value in input: {path}"
751 )));
752 Err(())
753 }
754 ast::CustomType::Enum(enm) => {
755 let tcx_id = self.lookup_id.resolve_enum(enm).expect(
756 "can't find enum in lookup map, which contains all enums from env",
757 );
758
759 Ok(OutType::Enum(EnumPath::new(tcx_id)))
760 }
761 }
762 }
763 ast::TypeName::Reference(lifetime, mutability, ref_ty) => match ref_ty.as_ref() {
764 ast::TypeName::Named(path) | ast::TypeName::SelfType(path) => {
765 match path.resolve(in_path, self.env) {
766 ast::CustomType::Opaque(opaque) => {
767 let borrow = Borrow::new(ltl.lower_lifetime(lifetime), *mutability);
768 let lifetimes = ltl.lower_generics(
769 &path.lifetimes,
770 &opaque.lifetimes,
771 ref_ty.is_self(),
772 );
773 let tcx_id = self.lookup_id.resolve_opaque(opaque).expect(
774 "can't find opaque in lookup map, which contains all opaques from env",
775 );
776
777 Ok(OutType::Opaque(OpaquePath::new(
778 lifetimes,
779 Optional(false),
780 MaybeOwn::Borrow(borrow),
781 tcx_id,
782 )))
783 }
784 _ => {
785 self.errors.push(LoweringError::Other(format!("found &T in output where T is a custom type, but not opaque. T = {ref_ty}")));
786 Err(())
787 }
788 }
789 }
790 _ => {
791 self.errors.push(LoweringError::Other(format!("found &T in output where T isn't a custom type and therefore not opaque. T = {ref_ty}")));
792 Err(())
793 }
794 },
795 ast::TypeName::Box(box_ty) => match box_ty.as_ref() {
796 ast::TypeName::Named(path) | ast::TypeName::SelfType(path) => {
797 match path.resolve(in_path, self.env) {
798 ast::CustomType::Opaque(opaque) => {
799 let lifetimes = ltl.lower_generics(
800 &path.lifetimes,
801 &opaque.lifetimes,
802 box_ty.is_self(),
803 );
804 let tcx_id = self.lookup_id.resolve_opaque(opaque).expect(
805 "can't find opaque in lookup map, which contains all opaques from env",
806 );
807
808 Ok(OutType::Opaque(OpaquePath::new(
809 lifetimes,
810 Optional(false),
811 MaybeOwn::Own,
812 tcx_id,
813 )))
814 }
815 _ => {
816 self.errors.push(LoweringError::Other(format!("found Box<T> in output where T is a custom type but not opaque. non-opaques can't be behind pointers. T = {path}")));
817 Err(())
818 }
819 }
820 }
821 _ => {
822 self.errors.push(LoweringError::Other(format!(
823 "found Box<T> in output where T isn't a custom type. T = {box_ty}"
824 )));
825 Err(())
826 }
827 },
828 ast::TypeName::Option(opt_ty) => match opt_ty.as_ref() {
829 ast::TypeName::Reference(lifetime, mutability, ref_ty) => match ref_ty.as_ref() {
830 ast::TypeName::Named(path) | ast::TypeName::SelfType(path) => {
831 match path.resolve(in_path, self.env) {
832 ast::CustomType::Opaque(opaque) => {
833 let borrow = Borrow::new(ltl.lower_lifetime(lifetime), *mutability);
834 let lifetimes = ltl.lower_generics(
835 &path.lifetimes,
836 &opaque.lifetimes,
837 ref_ty.is_self(),
838 );
839 let tcx_id = self.lookup_id.resolve_opaque(opaque).expect(
840 "can't find opaque in lookup map, which contains all opaques from env",
841 );
842
843 Ok(OutType::Opaque(OpaquePath::new(
844 lifetimes,
845 Optional(true),
846 MaybeOwn::Borrow(borrow),
847 tcx_id,
848 )))
849 }
850 _ => {
851 self.errors.push(LoweringError::Other(format!("found Option<&T> where T is a custom type, but it's not opaque. T = {ref_ty}")));
852 Err(())
853 }
854 }
855 }
856 _ => {
857 self.errors.push(LoweringError::Other(format!("found Option<&T>, but T isn't a custom type and therefore not opaque. T = {ref_ty}")));
858 Err(())
859 }
860 },
861 ast::TypeName::Box(box_ty) => match box_ty.as_ref() {
862 ast::TypeName::Named(path) | ast::TypeName::SelfType(path) => {
863 match path.resolve(in_path, self.env) {
864 ast::CustomType::Opaque(opaque) => {
865 let lifetimes = ltl.lower_generics(
866 &path.lifetimes,
867 &opaque.lifetimes,
868 box_ty.is_self(),
869 );
870 let tcx_id = self.lookup_id.resolve_opaque(opaque).expect(
871 "can't find opaque in lookup map, which contains all opaques from env",
872 );
873
874 Ok(OutType::Opaque(OpaquePath::new(
875 lifetimes,
876 Optional(true),
877 MaybeOwn::Own,
878 tcx_id,
879 )))
880 }
881 _ => {
882 self.errors.push(LoweringError::Other(format!("found Option<Box<T>> where T is a custom type, but it's not opaque. T = {box_ty}")));
883 Err(())
884 }
885 }
886 }
887 _ => {
888 self.errors.push(LoweringError::Other(format!("found Option<Box<T>>, but T isn't a custom type and therefore not opaque. T = {box_ty}")));
889 Err(())
890 }
891 },
892 _ => {
893 self.errors.push(LoweringError::Other(format!("found Option<T>, where T isn't a reference but Option<T> requires that T is a reference to an opaque. T = {opt_ty}")));
894 Err(())
895 }
896 },
897 ast::TypeName::Result(_, _, _) => {
898 self.errors.push(LoweringError::Other(
899 "Results can only appear as the top-level return type of methods".into(),
900 ));
901 Err(())
902 }
903 ast::TypeName::Writeable => {
904 self.errors.push(LoweringError::Other(
905 "Writeables can only appear as the last parameter of a method".into(),
906 ));
907 Err(())
908 }
909 ast::TypeName::StrReference(lifetime, encoding) => Ok(OutType::Slice(Slice::Str(
910 lifetime.as_ref().map(|l| ltl.lower_lifetime(l)),
911 *encoding,
912 ))),
913 ast::TypeName::StrSlice(..) => {
914 self.errors.push(LoweringError::Other(
915 "String slices can only be an input type".into(),
916 ));
917 Err(())
918 }
919 ast::TypeName::PrimitiveSlice(lm, prim) => Ok(OutType::Slice(Slice::Primitive(
920 lm.as_ref()
921 .map(|(lt, m)| Borrow::new(ltl.lower_lifetime(lt), *m)),
922 PrimitiveType::from_ast(*prim),
923 ))),
924 ast::TypeName::Unit => {
925 self.errors.push(LoweringError::Other("Unit types can only appear as the return value of a method, or as the Ok/Err variants of a returned result".into()));
926 Err(())
927 }
928 }
929 }
930
931 /// Lowers an [`ast::SelfParam`] into an [`hir::ParamSelf`].
932 ///
933 /// If there are any errors, they're pushed to `errors` and `None` is returned.
934 fn lower_self_param(
935 &mut self,
936 self_param: &ast::SelfParam,
937 self_param_ltl: SelfParamLifetimeLowerer<'ast>,
938 method_full_path: &ast::Ident, // for better error msg
939 in_path: &ast::Path,
940 ) -> Result<(ParamSelf, ParamLifetimeLowerer<'ast>), ()> {
941 match self_param.path_type.resolve(in_path, self.env) {
942 ast::CustomType::Struct(strct) => {
943 if let Some(tcx_id) = self.lookup_id.resolve_struct(strct) {
944 if self_param.reference.is_some() {
945 self.errors.push(LoweringError::Other(format!("Method `{method_full_path}` takes a reference to a struct as a self parameter, which isn't allowed")));
946 Err(())
947 } else {
948 let mut param_ltl = self_param_ltl.no_self_ref();
949
950 // Even if we explicitly write out the type of `self` like
951 // `self: Foo<'a>`, the `'a` is still not considered for
952 // elision according to rustc, so is_self=true.
953 let type_lifetimes = param_ltl.lower_generics(
954 &self_param.path_type.lifetimes[..],
955 &strct.lifetimes,
956 true,
957 );
958
959 Ok((
960 ParamSelf::new(SelfType::Struct(StructPath::new(
961 type_lifetimes,
962 tcx_id,
963 ))),
964 param_ltl,
965 ))
966 }
967 } else if self.lookup_id.resolve_out_struct(strct).is_some() {
968 if let Some((lifetime, _)) = &self_param.reference {
969 self.errors.push(LoweringError::Other(format!("Method `{method_full_path}` takes an out-struct as the self parameter, which isn't allowed. Also, it's behind a reference, `{lifetime}`, but only opaques can be behind references")));
970 Err(())
971 } else {
972 self.errors.push(LoweringError::Other(format!("Method `{method_full_path}` takes an out-struct as the self parameter, which isn't allowed")));
973 Err(())
974 }
975 } else {
976 unreachable!(
977 "struct `{}` wasn't found in the set of structs or out-structs, this is a bug.",
978 strct.name
979 );
980 }
981 }
982 ast::CustomType::Opaque(opaque) => {
983 let tcx_id = self
984 .lookup_id
985 .resolve_opaque(opaque)
986 .expect("opaque is in env");
987
988 if let Some((lifetime, mutability)) = &self_param.reference {
989 let (borrow_lifetime, mut param_ltl) = self_param_ltl.lower_self_ref(lifetime);
990 let borrow = Borrow::new(borrow_lifetime, *mutability);
991 let lifetimes = param_ltl.lower_generics(
992 &self_param.path_type.lifetimes,
993 &opaque.lifetimes,
994 true,
995 );
996
997 Ok((
998 ParamSelf::new(SelfType::Opaque(OpaquePath::new(
999 lifetimes,
1000 NonOptional,
1001 borrow,
1002 tcx_id,
1003 ))),
1004 param_ltl,
1005 ))
1006 } else {
1007 self.errors.push(LoweringError::Other(format!("Method `{method_full_path}` takes an opaque by value as the self parameter, but opaques as inputs must be behind refs")));
1008 Err(())
1009 }
1010 }
1011 ast::CustomType::Enum(enm) => {
1012 let tcx_id = self.lookup_id.resolve_enum(enm).expect("enum is in env");
1013
1014 Ok((
1015 ParamSelf::new(SelfType::Enum(EnumPath::new(tcx_id))),
1016 self_param_ltl.no_self_ref(),
1017 ))
1018 }
1019 }
1020 }
1021
1022 /// Lowers an [`ast::Param`] into an [`hir::Param`].
1023 ///
1024 /// If there are any errors, they're pushed to `errors` and `None` is returned.
1025 ///
1026 /// Note that this expects that if there was a writeable param at the end in
1027 /// the method, it's not passed into here.
1028 fn lower_param(
1029 &mut self,
1030 param: &ast::Param,
1031 ltl: &mut impl LifetimeLowerer,
1032 in_path: &ast::Path,
1033 ) -> Result<Param, ()> {
1034 let name = self.lower_ident(&param.name, "param name");
1035 let ty = self.lower_type(&param.ty, ltl, in_path);
1036
1037 Ok(Param::new(name?, ty?))
1038 }
1039
1040 /// Lowers many [`ast::Param`]s into a vector of [`hir::Param`]s.
1041 ///
1042 /// If there are any errors, they're pushed to `errors` and `None` is returned.
1043 ///
1044 /// Note that this expects that if there was a writeable param at the end in
1045 /// the method, `ast_params` was sliced to not include it. This happens in
1046 /// `self.lower_method`, the caller of this function.
1047 fn lower_many_params(
1048 &mut self,
1049 ast_params: &[ast::Param],
1050 mut param_ltl: ParamLifetimeLowerer<'ast>,
1051 in_path: &ast::Path,
1052 ) -> Result<(Vec<Param>, ReturnLifetimeLowerer<'ast>), ()> {
1053 let mut params = Ok(Vec::with_capacity(ast_params.len()));
1054
1055 for param in ast_params {
1056 let param = self.lower_param(param, &mut param_ltl, in_path);
1057
1058 match (param, &mut params) {
1059 (Ok(param), Ok(params)) => {
1060 params.push(param);
1061 }
1062 _ => params = Err(()),
1063 }
1064 }
1065
1066 Ok((params?, param_ltl.into_return_ltl()))
1067 }
1068
1069 /// Lowers the return type of an [`ast::Method`] into a [`hir::ReturnFallability`].
1070 ///
1071 /// If there are any errors, they're pushed to `errors` and `None` is returned.
1072 fn lower_return_type(
1073 &mut self,
1074 return_type: Option<&ast::TypeName>,
1075 takes_writeable: bool,
1076 mut return_ltl: ReturnLifetimeLowerer<'_>,
1077 in_path: &ast::Path,
1078 ) -> Result<(ReturnType, LifetimeEnv), ()> {
1079 let writeable_or_unit = if takes_writeable {
1080 SuccessType::Writeable
1081 } else {
1082 SuccessType::Unit
1083 };
1084 match return_type.unwrap_or(&ast::TypeName::Unit) {
1085 ast::TypeName::Result(ok_ty, err_ty, _) => {
1086 let ok_ty = match ok_ty.as_ref() {
1087 ast::TypeName::Unit => Ok(writeable_or_unit),
1088 ty => self
1089 .lower_out_type(ty, &mut return_ltl, in_path, false)
1090 .map(SuccessType::OutType),
1091 };
1092 let err_ty = match err_ty.as_ref() {
1093 ast::TypeName::Unit => Ok(None),
1094 ty => self
1095 .lower_out_type(ty, &mut return_ltl, in_path, false)
1096 .map(Some),
1097 };
1098
1099 match (ok_ty, err_ty) {
1100 (Ok(ok_ty), Ok(err_ty)) => Ok(ReturnType::Fallible(ok_ty, err_ty)),
1101 _ => Err(()),
1102 }
1103 }
1104 ty @ ast::TypeName::Option(value_ty) => match &**value_ty {
1105 ast::TypeName::Box(..) | ast::TypeName::Reference(..) => self
1106 .lower_out_type(ty, &mut return_ltl, in_path, false)
1107 .map(SuccessType::OutType)
1108 .map(ReturnType::Infallible),
1109 _ => self
1110 .lower_out_type(value_ty, &mut return_ltl, in_path, false)
1111 .map(SuccessType::OutType)
1112 .map(ReturnType::Nullable),
1113 },
1114 ast::TypeName::Unit => Ok(ReturnType::Infallible(writeable_or_unit)),
1115 ty => self
1116 .lower_out_type(ty, &mut return_ltl, in_path, false)
1117 .map(|ty| ReturnType::Infallible(SuccessType::OutType(ty))),
1118 }
1119 .map(|r_ty| (r_ty, return_ltl.finish()))
1120 }
1121
1122 fn lower_named_lifetime(
1123 &mut self,
1124 lifetime: &ast::lifetimes::LifetimeNode,
1125 ) -> Result<BoundedLifetime, ()> {
1126 Ok(BoundedLifetime {
1127 ident: self.lower_ident(lifetime.lifetime.name(), "lifetime")?,
1128 longer: lifetime.longer.iter().copied().map(Lifetime::new).collect(),
1129 shorter: lifetime
1130 .shorter
1131 .iter()
1132 .copied()
1133 .map(Lifetime::new)
1134 .collect(),
1135 })
1136 }
1137
1138 /// Lowers a lifetime env found on a type
1139 ///
1140 /// Should not be extended to return LifetimeEnv<Method>, which needs to use the lifetime
1141 /// lowerers to handle elision.
1142 fn lower_type_lifetime_env(&mut self, ast: &ast::LifetimeEnv) -> Result<LifetimeEnv, ()> {
1143 let nodes = ast
1144 .nodes
1145 .iter()
1146 .map(|lt| self.lower_named_lifetime(lt))
1147 .collect::<Result<_, ()>>()?;
1148
1149 Ok(LifetimeEnv::new(nodes, ast.nodes.len()))
1150 }
1151 }