1 //! HIR for references to types. Paths in these are not yet resolved. They can
2 //! be directly created from an ast::TypeRef, without further queries.
4 use hir_expand::{name::Name, AstId, InFile};
5 use std::convert::TryInto;
8 use crate::{body::LowerCtx, intern::Interned, path::Path};
10 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
17 pub fn from_mutable(mutable: bool) -> Mutability {
25 pub fn as_keyword_for_ref(self) -> &'static str {
27 Mutability::Shared => "",
28 Mutability::Mut => "mut ",
32 pub fn as_keyword_for_ptr(self) -> &'static str {
34 Mutability::Shared => "const ",
35 Mutability::Mut => "mut ",
40 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
47 pub fn from_raw(is_raw: bool) -> Rawness {
56 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
62 /// Converts an `ast::PathType` to a `hir::TraitRef`.
63 pub(crate) fn from_ast(ctx: &LowerCtx, node: ast::Type) -> Option<Self> {
64 // FIXME: Use `Path::from_src`
66 ast::Type::PathType(path) => {
67 path.path().and_then(|it| ctx.lower_path(it)).map(|path| TraitRef { path })
76 /// Note: Most users of `TypeRef` that end up in the salsa database intern it using
77 /// `Interned<TypeRef>` to save space. But notably, nested `TypeRef`s are not interned, since that
78 /// does not seem to save any noticeable amount of memory.
79 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
85 RawPtr(Box<TypeRef>, Mutability),
86 Reference(Box<TypeRef>, Option<LifetimeRef>, Mutability),
87 // FIXME: for full const generics, the latter element (length) here is going to have to be an
88 // expression that is further lowered later in hir_ty.
89 Array(Box<TypeRef>, ConstScalar),
91 /// A fn pointer. Last element of the vector is the return type.
92 Fn(Vec<TypeRef>, bool /*varargs*/),
94 ImplTrait(Vec<Interned<TypeBound>>),
95 DynTrait(Vec<Interned<TypeBound>>),
96 Macro(AstId<ast::MacroCall>),
100 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
101 pub struct LifetimeRef {
106 pub(crate) fn new_name(name: Name) -> Self {
110 pub(crate) fn new(lifetime: &ast::Lifetime) -> Self {
111 LifetimeRef { name: Name::new_lifetime(lifetime) }
114 pub fn missing() -> LifetimeRef {
115 LifetimeRef { name: Name::missing() }
119 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
121 Path(Path, TraitBoundModifier),
122 ForLifetime(Box<[Name]>, Path),
123 Lifetime(LifetimeRef),
127 /// A modifier on a bound, currently this is only used for `?Sized`, where the
128 /// modifier is `Maybe`.
129 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
130 pub enum TraitBoundModifier {
136 /// Converts an `ast::TypeRef` to a `hir::TypeRef`.
137 pub fn from_ast(ctx: &LowerCtx, node: ast::Type) -> Self {
139 ast::Type::ParenType(inner) => TypeRef::from_ast_opt(ctx, inner.ty()),
140 ast::Type::TupleType(inner) => {
141 TypeRef::Tuple(inner.fields().map(|it| TypeRef::from_ast(ctx, it)).collect())
143 ast::Type::NeverType(..) => TypeRef::Never,
144 ast::Type::PathType(inner) => {
145 // FIXME: Use `Path::from_src`
148 .and_then(|it| ctx.lower_path(it))
150 .unwrap_or(TypeRef::Error)
152 ast::Type::PtrType(inner) => {
153 let inner_ty = TypeRef::from_ast_opt(ctx, inner.ty());
154 let mutability = Mutability::from_mutable(inner.mut_token().is_some());
155 TypeRef::RawPtr(Box::new(inner_ty), mutability)
157 ast::Type::ArrayType(inner) => {
158 // FIXME: This is a hack. We should probably reuse the machinery of
159 // `hir_def::body::lower` to lower this into an `Expr` and then evaluate it at the
160 // `hir_ty` level, which would allow knowing the type of:
161 // let v: [u8; 2 + 2] = [0u8; 4];
164 .map(ConstScalar::usize_from_literal_expr)
165 .unwrap_or(ConstScalar::Unknown);
167 TypeRef::Array(Box::new(TypeRef::from_ast_opt(ctx, inner.ty())), len)
169 ast::Type::SliceType(inner) => {
170 TypeRef::Slice(Box::new(TypeRef::from_ast_opt(ctx, inner.ty())))
172 ast::Type::RefType(inner) => {
173 let inner_ty = TypeRef::from_ast_opt(ctx, inner.ty());
174 let lifetime = inner.lifetime().map(|lt| LifetimeRef::new(<));
175 let mutability = Mutability::from_mutable(inner.mut_token().is_some());
176 TypeRef::Reference(Box::new(inner_ty), lifetime, mutability)
178 ast::Type::InferType(_inner) => TypeRef::Placeholder,
179 ast::Type::FnPtrType(inner) => {
182 .and_then(|rt| rt.ty())
183 .map(|it| TypeRef::from_ast(ctx, it))
184 .unwrap_or_else(|| TypeRef::Tuple(Vec::new()));
185 let mut is_varargs = false;
186 let mut params = if let Some(pl) = inner.param_list() {
187 if let Some(param) = pl.params().last() {
188 is_varargs = param.dotdotdot_token().is_some();
191 pl.params().map(|p| p.ty()).map(|it| TypeRef::from_ast_opt(ctx, it)).collect()
196 TypeRef::Fn(params, is_varargs)
198 // for types are close enough for our purposes to the inner type for now...
199 ast::Type::ForType(inner) => TypeRef::from_ast_opt(ctx, inner.ty()),
200 ast::Type::ImplTraitType(inner) => {
201 TypeRef::ImplTrait(type_bounds_from_ast(ctx, inner.type_bound_list()))
203 ast::Type::DynTraitType(inner) => {
204 TypeRef::DynTrait(type_bounds_from_ast(ctx, inner.type_bound_list()))
206 ast::Type::MacroType(mt) => match mt.macro_call() {
209 .map(|mc| TypeRef::Macro(InFile::new(ctx.file_id(), mc)))
210 .unwrap_or(TypeRef::Error),
211 None => TypeRef::Error,
216 pub(crate) fn from_ast_opt(ctx: &LowerCtx, node: Option<ast::Type>) -> Self {
218 Some(node) => TypeRef::from_ast(ctx, node),
219 None => TypeRef::Error,
223 pub(crate) fn unit() -> TypeRef {
224 TypeRef::Tuple(Vec::new())
227 pub fn walk(&self, f: &mut impl FnMut(&TypeRef)) {
230 fn go(type_ref: &TypeRef, f: &mut impl FnMut(&TypeRef)) {
233 TypeRef::Fn(types, _) | TypeRef::Tuple(types) => {
234 types.iter().for_each(|t| go(t, f))
236 TypeRef::RawPtr(type_ref, _)
237 | TypeRef::Reference(type_ref, ..)
238 | TypeRef::Array(type_ref, _)
239 | TypeRef::Slice(type_ref) => go(type_ref, f),
240 TypeRef::ImplTrait(bounds) | TypeRef::DynTrait(bounds) => {
241 for bound in bounds {
242 match bound.as_ref() {
243 TypeBound::Path(path, _) | TypeBound::ForLifetime(_, path) => {
246 TypeBound::Lifetime(_) | TypeBound::Error => (),
250 TypeRef::Path(path) => go_path(path, f),
251 TypeRef::Never | TypeRef::Placeholder | TypeRef::Macro(_) | TypeRef::Error => {}
255 fn go_path(path: &Path, f: &mut impl FnMut(&TypeRef)) {
256 if let Some(type_ref) = path.type_anchor() {
259 for segment in path.segments().iter() {
260 if let Some(args_and_bindings) = segment.args_and_bindings {
261 for arg in &args_and_bindings.args {
263 crate::path::GenericArg::Type(type_ref) => {
266 crate::path::GenericArg::Lifetime(_) => {}
269 for binding in &args_and_bindings.bindings {
270 if let Some(type_ref) = &binding.type_ref {
273 for bound in &binding.bounds {
274 match bound.as_ref() {
275 TypeBound::Path(path, _) | TypeBound::ForLifetime(_, path) => {
278 TypeBound::Lifetime(_) | TypeBound::Error => (),
288 pub(crate) fn type_bounds_from_ast(
289 lower_ctx: &LowerCtx,
290 type_bounds_opt: Option<ast::TypeBoundList>,
291 ) -> Vec<Interned<TypeBound>> {
292 if let Some(type_bounds) = type_bounds_opt {
293 type_bounds.bounds().map(|it| Interned::new(TypeBound::from_ast(lower_ctx, it))).collect()
300 pub(crate) fn from_ast(ctx: &LowerCtx, node: ast::TypeBound) -> Self {
301 let lower_path_type = |path_type: ast::PathType| ctx.lower_path(path_type.path()?);
304 ast::TypeBoundKind::PathType(path_type) => {
305 let m = match node.question_mark_token() {
306 Some(_) => TraitBoundModifier::Maybe,
307 None => TraitBoundModifier::None,
309 lower_path_type(path_type)
310 .map(|p| TypeBound::Path(p, m))
311 .unwrap_or(TypeBound::Error)
313 ast::TypeBoundKind::ForType(for_type) => {
314 let lt_refs = match for_type.generic_param_list() {
317 .flat_map(|lp| lp.lifetime().map(|lt| Name::new_lifetime(<)))
319 None => Box::default(),
321 let path = for_type.ty().and_then(|ty| match ty {
322 ast::Type::PathType(path_type) => lower_path_type(path_type),
326 Some(p) => TypeBound::ForLifetime(lt_refs, p),
327 None => TypeBound::Error,
330 ast::TypeBoundKind::Lifetime(lifetime) => {
331 TypeBound::Lifetime(LifetimeRef::new(&lifetime))
336 pub fn as_path(&self) -> Option<(&Path, &TraitBoundModifier)> {
338 TypeBound::Path(p, m) => Some((p, m)),
339 TypeBound::ForLifetime(_, p) => Some((p, &TraitBoundModifier::None)),
340 TypeBound::Lifetime(_) | TypeBound::Error => None,
345 /// A concrete constant value
346 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
347 pub enum ConstScalar {
348 // for now, we only support the trivial case of constant evaluating the length of an array
349 // Note that this is u64 because the target usize may be bigger than our usize
352 /// Case of an unknown value that rustc might know but we don't
353 // FIXME: this is a hack to get around chalk not being able to represent unevaluatable
355 // https://github.com/rust-analyzer/rust-analyzer/pull/8813#issuecomment-840679177
356 // https://rust-lang.zulipchat.com/#narrow/stream/144729-wg-traits/topic/Handling.20non.20evaluatable.20constants'.20equality/near/238386348
360 impl std::fmt::Display for ConstScalar {
361 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
363 ConstScalar::Usize(us) => write!(fmt, "{}", us),
364 ConstScalar::Unknown => write!(fmt, "_"),
370 /// Gets a target usize out of the ConstScalar
371 pub fn as_usize(&self) -> Option<u64> {
373 &ConstScalar::Usize(us) => Some(us),
378 // FIXME: as per the comments on `TypeRef::Array`, this evaluation should not happen at this
380 fn usize_from_literal_expr(expr: ast::Expr) -> ConstScalar {
382 ast::Expr::Literal(lit) => {
383 let lkind = lit.kind();
385 ast::LiteralKind::IntNumber(num)
386 if num.suffix() == None || num.suffix() == Some("usize") =>
388 num.value().and_then(|v| v.try_into().ok())
395 .map(ConstScalar::Usize)
396 .unwrap_or(ConstScalar::Unknown)