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.
10 use syntax::ast::{self, HasName};
14 builtin_type::{BuiltinInt, BuiltinType, BuiltinUint},
20 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
27 pub fn from_mutable(mutable: bool) -> Mutability {
35 pub fn as_keyword_for_ref(self) -> &'static str {
37 Mutability::Shared => "",
38 Mutability::Mut => "mut ",
42 pub fn as_keyword_for_ptr(self) -> &'static str {
44 Mutability::Shared => "const ",
45 Mutability::Mut => "mut ",
49 /// Returns `true` if the mutability is [`Mut`].
51 /// [`Mut`]: Mutability::Mut
53 pub fn is_mut(&self) -> bool {
54 matches!(self, Self::Mut)
57 /// Returns `true` if the mutability is [`Shared`].
59 /// [`Shared`]: Mutability::Shared
61 pub fn is_shared(&self) -> bool {
62 matches!(self, Self::Shared)
66 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
73 pub fn from_raw(is_raw: bool) -> Rawness {
81 pub fn is_raw(&self) -> bool {
82 matches!(self, Self::RawPtr)
86 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
92 /// Converts an `ast::PathType` to a `hir::TraitRef`.
93 pub(crate) fn from_ast(ctx: &LowerCtx<'_>, node: ast::Type) -> Option<Self> {
94 // FIXME: Use `Path::from_src`
96 ast::Type::PathType(path) => {
97 path.path().and_then(|it| ctx.lower_path(it)).map(|path| TraitRef { path })
106 /// Note: Most users of `TypeRef` that end up in the salsa database intern it using
107 /// `Interned<TypeRef>` to save space. But notably, nested `TypeRef`s are not interned, since that
108 /// does not seem to save any noticeable amount of memory.
109 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
115 RawPtr(Box<TypeRef>, Mutability),
116 Reference(Box<TypeRef>, Option<LifetimeRef>, Mutability),
117 // FIXME: for full const generics, the latter element (length) here is going to have to be an
118 // expression that is further lowered later in hir_ty.
119 Array(Box<TypeRef>, ConstScalarOrPath),
121 /// A fn pointer. Last element of the vector is the return type.
122 Fn(Vec<(Option<Name>, TypeRef)>, bool /*varargs*/),
123 ImplTrait(Vec<Interned<TypeBound>>),
124 DynTrait(Vec<Interned<TypeBound>>),
125 Macro(AstId<ast::MacroCall>),
129 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
130 pub struct LifetimeRef {
135 pub(crate) fn new_name(name: Name) -> Self {
139 pub(crate) fn new(lifetime: &ast::Lifetime) -> Self {
140 LifetimeRef { name: Name::new_lifetime(lifetime) }
143 pub fn missing() -> LifetimeRef {
144 LifetimeRef { name: Name::missing() }
148 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
150 Path(Path, TraitBoundModifier),
151 ForLifetime(Box<[Name]>, Path),
152 Lifetime(LifetimeRef),
156 /// A modifier on a bound, currently this is only used for `?Sized`, where the
157 /// modifier is `Maybe`.
158 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
159 pub enum TraitBoundModifier {
165 /// Converts an `ast::TypeRef` to a `hir::TypeRef`.
166 pub fn from_ast(ctx: &LowerCtx<'_>, node: ast::Type) -> Self {
168 ast::Type::ParenType(inner) => TypeRef::from_ast_opt(ctx, inner.ty()),
169 ast::Type::TupleType(inner) => {
170 TypeRef::Tuple(inner.fields().map(|it| TypeRef::from_ast(ctx, it)).collect())
172 ast::Type::NeverType(..) => TypeRef::Never,
173 ast::Type::PathType(inner) => {
174 // FIXME: Use `Path::from_src`
177 .and_then(|it| ctx.lower_path(it))
179 .unwrap_or(TypeRef::Error)
181 ast::Type::PtrType(inner) => {
182 let inner_ty = TypeRef::from_ast_opt(ctx, inner.ty());
183 let mutability = Mutability::from_mutable(inner.mut_token().is_some());
184 TypeRef::RawPtr(Box::new(inner_ty), mutability)
186 ast::Type::ArrayType(inner) => {
187 // FIXME: This is a hack. We should probably reuse the machinery of
188 // `hir_def::body::lower` to lower this into an `Expr` and then evaluate it at the
189 // `hir_ty` level, which would allow knowing the type of:
190 // let v: [u8; 2 + 2] = [0u8; 4];
191 let len = ConstScalarOrPath::from_expr_opt(inner.expr());
192 TypeRef::Array(Box::new(TypeRef::from_ast_opt(ctx, inner.ty())), len)
194 ast::Type::SliceType(inner) => {
195 TypeRef::Slice(Box::new(TypeRef::from_ast_opt(ctx, inner.ty())))
197 ast::Type::RefType(inner) => {
198 let inner_ty = TypeRef::from_ast_opt(ctx, inner.ty());
199 let lifetime = inner.lifetime().map(|lt| LifetimeRef::new(<));
200 let mutability = Mutability::from_mutable(inner.mut_token().is_some());
201 TypeRef::Reference(Box::new(inner_ty), lifetime, mutability)
203 ast::Type::InferType(_inner) => TypeRef::Placeholder,
204 ast::Type::FnPtrType(inner) => {
207 .and_then(|rt| rt.ty())
208 .map(|it| TypeRef::from_ast(ctx, it))
209 .unwrap_or_else(|| TypeRef::Tuple(Vec::new()));
210 let mut is_varargs = false;
211 let mut params = if let Some(pl) = inner.param_list() {
212 if let Some(param) = pl.params().last() {
213 is_varargs = param.dotdotdot_token().is_some();
218 let type_ref = TypeRef::from_ast_opt(ctx, it.ty());
219 let name = match it.pat() {
220 Some(ast::Pat::IdentPat(it)) => Some(
221 it.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing),
231 params.push((None, ret_ty));
232 TypeRef::Fn(params, is_varargs)
234 // for types are close enough for our purposes to the inner type for now...
235 ast::Type::ForType(inner) => TypeRef::from_ast_opt(ctx, inner.ty()),
236 ast::Type::ImplTraitType(inner) => {
237 TypeRef::ImplTrait(type_bounds_from_ast(ctx, inner.type_bound_list()))
239 ast::Type::DynTraitType(inner) => {
240 TypeRef::DynTrait(type_bounds_from_ast(ctx, inner.type_bound_list()))
242 ast::Type::MacroType(mt) => match mt.macro_call() {
243 Some(mc) => ctx.ast_id(ctx.db, &mc).map(TypeRef::Macro).unwrap_or(TypeRef::Error),
244 None => TypeRef::Error,
249 pub(crate) fn from_ast_opt(ctx: &LowerCtx<'_>, node: Option<ast::Type>) -> Self {
251 Some(node) => TypeRef::from_ast(ctx, node),
252 None => TypeRef::Error,
256 pub(crate) fn unit() -> TypeRef {
257 TypeRef::Tuple(Vec::new())
260 pub fn walk(&self, f: &mut impl FnMut(&TypeRef)) {
263 fn go(type_ref: &TypeRef, f: &mut impl FnMut(&TypeRef)) {
266 TypeRef::Fn(params, _) => {
267 params.iter().for_each(|(_, param_type)| go(param_type, f))
269 TypeRef::Tuple(types) => types.iter().for_each(|t| go(t, f)),
270 TypeRef::RawPtr(type_ref, _)
271 | TypeRef::Reference(type_ref, ..)
272 | TypeRef::Array(type_ref, _)
273 | TypeRef::Slice(type_ref) => go(type_ref, f),
274 TypeRef::ImplTrait(bounds) | TypeRef::DynTrait(bounds) => {
275 for bound in bounds {
276 match bound.as_ref() {
277 TypeBound::Path(path, _) | TypeBound::ForLifetime(_, path) => {
280 TypeBound::Lifetime(_) | TypeBound::Error => (),
284 TypeRef::Path(path) => go_path(path, f),
285 TypeRef::Never | TypeRef::Placeholder | TypeRef::Macro(_) | TypeRef::Error => {}
289 fn go_path(path: &Path, f: &mut impl FnMut(&TypeRef)) {
290 if let Some(type_ref) = path.type_anchor() {
293 for segment in path.segments().iter() {
294 if let Some(args_and_bindings) = segment.args_and_bindings {
295 for arg in &args_and_bindings.args {
297 crate::path::GenericArg::Type(type_ref) => {
300 crate::path::GenericArg::Const(_)
301 | crate::path::GenericArg::Lifetime(_) => {}
304 for binding in &args_and_bindings.bindings {
305 if let Some(type_ref) = &binding.type_ref {
308 for bound in &binding.bounds {
309 match bound.as_ref() {
310 TypeBound::Path(path, _) | TypeBound::ForLifetime(_, path) => {
313 TypeBound::Lifetime(_) | TypeBound::Error => (),
323 pub(crate) fn type_bounds_from_ast(
324 lower_ctx: &LowerCtx<'_>,
325 type_bounds_opt: Option<ast::TypeBoundList>,
326 ) -> Vec<Interned<TypeBound>> {
327 if let Some(type_bounds) = type_bounds_opt {
328 type_bounds.bounds().map(|it| Interned::new(TypeBound::from_ast(lower_ctx, it))).collect()
335 pub(crate) fn from_ast(ctx: &LowerCtx<'_>, node: ast::TypeBound) -> Self {
336 let lower_path_type = |path_type: ast::PathType| ctx.lower_path(path_type.path()?);
339 ast::TypeBoundKind::PathType(path_type) => {
340 let m = match node.question_mark_token() {
341 Some(_) => TraitBoundModifier::Maybe,
342 None => TraitBoundModifier::None,
344 lower_path_type(path_type)
345 .map(|p| TypeBound::Path(p, m))
346 .unwrap_or(TypeBound::Error)
348 ast::TypeBoundKind::ForType(for_type) => {
349 let lt_refs = match for_type.generic_param_list() {
352 .flat_map(|lp| lp.lifetime().map(|lt| Name::new_lifetime(<)))
354 None => Box::default(),
356 let path = for_type.ty().and_then(|ty| match ty {
357 ast::Type::PathType(path_type) => lower_path_type(path_type),
361 Some(p) => TypeBound::ForLifetime(lt_refs, p),
362 None => TypeBound::Error,
365 ast::TypeBoundKind::Lifetime(lifetime) => {
366 TypeBound::Lifetime(LifetimeRef::new(&lifetime))
371 pub fn as_path(&self) -> Option<(&Path, &TraitBoundModifier)> {
373 TypeBound::Path(p, m) => Some((p, m)),
374 TypeBound::ForLifetime(_, p) => Some((p, &TraitBoundModifier::None)),
375 TypeBound::Lifetime(_) | TypeBound::Error => None,
380 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
381 pub enum ConstScalarOrPath {
386 impl std::fmt::Display for ConstScalarOrPath {
387 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
389 ConstScalarOrPath::Scalar(s) => s.fmt(f),
390 ConstScalarOrPath::Path(n) => n.fmt(f),
395 impl ConstScalarOrPath {
396 pub(crate) fn from_expr_opt(expr: Option<ast::Expr>) -> Self {
398 Some(x) => Self::from_expr(x),
399 None => Self::Scalar(ConstScalar::Unknown),
403 // FIXME: as per the comments on `TypeRef::Array`, this evaluation should not happen at this
405 fn from_expr(expr: ast::Expr) -> Self {
407 ast::Expr::PathExpr(p) => {
408 match p.path().and_then(|x| x.segment()).and_then(|x| x.name_ref()) {
409 Some(x) => Self::Path(x.as_name()),
410 None => Self::Scalar(ConstScalar::Unknown),
413 ast::Expr::PrefixExpr(prefix_expr) => match prefix_expr.op_kind() {
414 Some(ast::UnaryOp::Neg) => {
415 let unsigned = Self::from_expr_opt(prefix_expr.expr());
418 Self::Scalar(ConstScalar::UInt(num)) => {
419 Self::Scalar(ConstScalar::Int(-(num as i128)))
424 _ => Self::from_expr_opt(prefix_expr.expr()),
426 ast::Expr::Literal(literal) => Self::Scalar(match literal.kind() {
427 ast::LiteralKind::IntNumber(num) => {
428 num.value().map(ConstScalar::UInt).unwrap_or(ConstScalar::Unknown)
430 ast::LiteralKind::Char(c) => {
431 c.value().map(ConstScalar::Char).unwrap_or(ConstScalar::Unknown)
433 ast::LiteralKind::Bool(f) => ConstScalar::Bool(f),
434 _ => ConstScalar::Unknown,
436 _ => Self::Scalar(ConstScalar::Unknown),
441 /// A concrete constant value
442 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
443 pub enum ConstScalar {
449 /// Case of an unknown value that rustc might know but we don't
450 // FIXME: this is a hack to get around chalk not being able to represent unevaluatable
452 // https://github.com/rust-lang/rust-analyzer/pull/8813#issuecomment-840679177
453 // https://rust-lang.zulipchat.com/#narrow/stream/144729-wg-traits/topic/Handling.20non.20evaluatable.20constants'.20equality/near/238386348
458 pub fn builtin_type(&self) -> BuiltinType {
460 ConstScalar::UInt(_) | ConstScalar::Unknown => BuiltinType::Uint(BuiltinUint::U128),
461 ConstScalar::Int(_) => BuiltinType::Int(BuiltinInt::I128),
462 ConstScalar::Char(_) => BuiltinType::Char,
463 ConstScalar::Bool(_) => BuiltinType::Bool,
468 impl From<Literal> for ConstScalar {
469 fn from(literal: Literal) -> Self {
471 Literal::Char(c) => Self::Char(c),
472 Literal::Bool(flag) => Self::Bool(flag),
473 Literal::Int(num, _) => Self::Int(num),
474 Literal::Uint(num, _) => Self::UInt(num),
480 impl std::fmt::Display for ConstScalar {
481 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
483 ConstScalar::Int(num) => num.fmt(f),
484 ConstScalar::UInt(num) => num.fmt(f),
485 ConstScalar::Bool(flag) => flag.fmt(f),
486 ConstScalar::Char(c) => write!(f, "'{c}'"),
487 ConstScalar::Unknown => f.write_char('_'),