rust/crates/hir_def/src/path.rs

217 lines
6.9 KiB
Rust
Raw Normal View History

2019-11-24 08:34:36 -06:00
//! A desugared representation of paths like `crate::foo` or `<Type as Trait>::bar`.
mod lower;
2019-10-30 08:12:55 -05:00
2020-01-10 11:40:45 -06:00
use std::{
fmt::{self, Display},
iter,
};
2019-10-30 08:12:55 -05:00
2022-01-26 11:31:07 -06:00
use crate::{body::LowerCtx, intern::Interned, type_ref::LifetimeRef};
use hir_expand::name::{name, Name};
use syntax::ast;
2019-10-30 08:12:55 -05:00
use crate::type_ref::{TypeBound, TypeRef};
2019-10-30 08:12:55 -05:00
2022-01-26 11:31:07 -06:00
pub use hir_expand::mod_path::{path, ModPath, PathKind};
2019-12-18 10:06:52 -06:00
2020-02-02 07:04:06 -06:00
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImportAlias {
/// Unnamed alias, as in `use Foo as _;`
Underscore,
/// Named alias
Alias(Name),
}
2021-05-21 16:45:09 -05:00
impl Display for ImportAlias {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ImportAlias::Underscore => f.write_str("_"),
ImportAlias::Alias(name) => f.write_str(&name.to_smol_str()),
2021-05-21 16:45:09 -05:00
}
}
}
2019-10-30 08:12:55 -05:00
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Path {
2019-12-18 10:42:49 -06:00
/// Type based path like `<T>::foo`.
/// Note that paths like `<Type as Trait>::foo` are desugard to `Trait::<Self=Type>::foo`.
type_anchor: Option<Interned<TypeRef>>,
mod_path: Interned<ModPath>,
2020-03-22 12:38:55 -05:00
/// Invariant: the same len as `self.mod_path.segments`
generic_args: Box<[Option<Interned<GenericArgs>>]>,
2019-10-30 08:12:55 -05:00
}
/// Generic arguments to a path segment (e.g. the `i32` in `Option<i32>`). This
2019-12-12 10:17:57 -06:00
/// also includes bindings of associated types, like in `Iterator<Item = Foo>`.
2019-10-30 08:12:55 -05:00
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GenericArgs {
pub args: Vec<GenericArg>,
/// This specifies whether the args contain a Self type as the first
/// element. This is the case for path segments like `<T as Trait>`, where
/// `T` is actually a type parameter for the path `Trait` specifying the
/// Self type. Otherwise, when we have a path `Trait<X, Y>`, the Self type
/// is left out.
pub has_self_type: bool,
/// Associated type bindings like in `Iterator<Item = T>`.
pub bindings: Vec<AssociatedTypeBinding>,
2021-11-19 12:58:00 -06:00
/// Whether these generic args were desugared from `Trait(Arg) -> Output`
/// parenthesis notation typically used for the `Fn` traits.
pub desugared_from_fn: bool,
}
/// An associated type binding like in `Iterator<Item = T>`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AssociatedTypeBinding {
/// The name of the associated type.
pub name: Name,
/// The type bound to this associated type (in `Item = T`, this would be the
/// `T`). This can be `None` if there are bounds instead.
pub type_ref: Option<TypeRef>,
/// Bounds for the associated type, like in `Iterator<Item:
/// SomeOtherTrait>`. (This is the unstable `associated_type_bounds`
/// feature.)
pub bounds: Vec<Interned<TypeBound>>,
2019-10-30 08:12:55 -05:00
}
/// A single generic argument.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GenericArg {
Type(TypeRef),
2020-12-11 06:49:32 -06:00
Lifetime(LifetimeRef),
2019-10-30 08:12:55 -05:00
}
impl Path {
/// Converts an `ast::Path` to `Path`. Works with use trees.
/// It correctly handles `$crate` based path from macro call.
2021-05-06 16:23:50 -05:00
pub fn from_src(path: ast::Path, ctx: &LowerCtx) -> Option<Path> {
lower::lower_path(path, ctx)
2019-10-30 08:12:55 -05:00
}
2019-12-24 05:45:28 -06:00
/// Converts a known mod path to `Path`.
2021-05-31 15:44:51 -05:00
pub fn from_known_path(
path: ModPath,
generic_args: impl Into<Box<[Option<Interned<GenericArgs>>]>>,
2021-05-31 15:44:51 -05:00
) -> Path {
let generic_args = generic_args.into();
assert_eq!(path.len(), generic_args.len());
Path { type_anchor: None, mod_path: Interned::new(path), generic_args }
2019-12-24 05:45:28 -06:00
}
pub fn kind(&self) -> &PathKind {
&self.mod_path.kind
2019-10-30 08:12:55 -05:00
}
2019-12-18 10:41:33 -06:00
pub fn type_anchor(&self) -> Option<&TypeRef> {
2019-12-20 13:15:54 -06:00
self.type_anchor.as_deref()
2019-12-18 10:41:33 -06:00
}
pub fn segments(&self) -> PathSegments<'_> {
2022-01-26 11:31:07 -06:00
PathSegments { segments: self.mod_path.segments(), generic_args: &self.generic_args }
2019-10-30 08:12:55 -05:00
}
pub fn mod_path(&self) -> &ModPath {
&self.mod_path
}
pub fn qualifier(&self) -> Option<Path> {
if self.mod_path.is_ident() {
2019-10-30 08:12:55 -05:00
return None;
}
let res = Path {
2019-12-18 10:41:33 -06:00
type_anchor: self.type_anchor.clone(),
mod_path: Interned::new(ModPath::from_segments(
2021-02-04 15:42:21 -06:00
self.mod_path.kind.clone(),
2022-01-26 11:31:07 -06:00
self.mod_path.segments()[..self.mod_path.segments().len() - 1].iter().cloned(),
)),
generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec().into(),
};
Some(res)
2019-10-30 08:12:55 -05:00
}
pub fn is_self_type(&self) -> bool {
self.type_anchor.is_none()
&& *self.generic_args == [None]
&& self.mod_path.as_ident() == Some(&name!(Self))
}
}
2019-10-30 08:12:55 -05:00
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PathSegment<'a> {
pub name: &'a Name,
pub args_and_bindings: Option<&'a GenericArgs>,
}
2019-10-30 08:12:55 -05:00
pub struct PathSegments<'a> {
segments: &'a [Name],
generic_args: &'a [Option<Interned<GenericArgs>>],
}
impl<'a> PathSegments<'a> {
pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.segments.len()
}
pub fn first(&self) -> Option<PathSegment<'a>> {
self.get(0)
}
pub fn last(&self) -> Option<PathSegment<'a>> {
self.get(self.len().checked_sub(1)?)
}
pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
assert_eq!(self.segments.len(), self.generic_args.len());
let res = PathSegment {
name: self.segments.get(idx)?,
args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
};
Some(res)
}
pub fn skip(&self, len: usize) -> PathSegments<'a> {
assert_eq!(self.segments.len(), self.generic_args.len());
PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
}
pub fn take(&self, len: usize) -> PathSegments<'a> {
assert_eq!(self.segments.len(), self.generic_args.len());
PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
}
pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
name,
args_and_bindings: args.as_ref().map(|it| &**it),
})
2019-10-30 08:12:55 -05:00
}
}
impl GenericArgs {
2020-07-31 11:29:29 -05:00
pub(crate) fn from_ast(lower_ctx: &LowerCtx, node: ast::GenericArgList) -> Option<GenericArgs> {
2020-04-30 05:20:13 -05:00
lower::lower_generic_args(lower_ctx, node)
2019-10-30 08:12:55 -05:00
}
pub(crate) fn empty() -> GenericArgs {
2021-11-19 12:58:00 -06:00
GenericArgs {
args: Vec::new(),
has_self_type: false,
bindings: Vec::new(),
desugared_from_fn: false,
}
2019-10-30 08:12:55 -05:00
}
}
impl From<Name> for Path {
fn from(name: Name) -> Path {
Path {
2019-12-18 10:41:33 -06:00
type_anchor: None,
mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
generic_args: Box::new([None]),
}
}
}
impl From<Name> for Box<Path> {
fn from(name: Name) -> Box<Path> {
Box::new(Path::from(name))
}
}