1 //! A desugared representation of paths like `crate::foo` or `<Type as Trait>::bar`.
9 use crate::{body::LowerCtx, intern::Interned, type_ref::LifetimeRef};
10 use hir_expand::name::{name, Name};
13 use crate::type_ref::{TypeBound, TypeRef};
15 pub use hir_expand::mod_path::{path, ModPath, PathKind};
17 #[derive(Debug, Clone, PartialEq, Eq)]
18 pub enum ImportAlias {
19 /// Unnamed alias, as in `use Foo as _;`
25 impl Display for ImportAlias {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28 ImportAlias::Underscore => f.write_str("_"),
29 ImportAlias::Alias(name) => f.write_str(&name.to_smol_str()),
34 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
36 /// Type based path like `<T>::foo`.
37 /// Note that paths like `<Type as Trait>::foo` are desugard to `Trait::<Self=Type>::foo`.
38 type_anchor: Option<Interned<TypeRef>>,
39 mod_path: Interned<ModPath>,
40 /// Invariant: the same len as `self.mod_path.segments`
41 generic_args: Box<[Option<Interned<GenericArgs>>]>,
44 /// Generic arguments to a path segment (e.g. the `i32` in `Option<i32>`). This
45 /// also includes bindings of associated types, like in `Iterator<Item = Foo>`.
46 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
47 pub struct GenericArgs {
48 pub args: Vec<GenericArg>,
49 /// This specifies whether the args contain a Self type as the first
50 /// element. This is the case for path segments like `<T as Trait>`, where
51 /// `T` is actually a type parameter for the path `Trait` specifying the
52 /// Self type. Otherwise, when we have a path `Trait<X, Y>`, the Self type
54 pub has_self_type: bool,
55 /// Associated type bindings like in `Iterator<Item = T>`.
56 pub bindings: Vec<AssociatedTypeBinding>,
57 /// Whether these generic args were desugared from `Trait(Arg) -> Output`
58 /// parenthesis notation typically used for the `Fn` traits.
59 pub desugared_from_fn: bool,
62 /// An associated type binding like in `Iterator<Item = T>`.
63 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
64 pub struct AssociatedTypeBinding {
65 /// The name of the associated type.
67 /// The type bound to this associated type (in `Item = T`, this would be the
68 /// `T`). This can be `None` if there are bounds instead.
69 pub type_ref: Option<TypeRef>,
70 /// Bounds for the associated type, like in `Iterator<Item:
71 /// SomeOtherTrait>`. (This is the unstable `associated_type_bounds`
73 pub bounds: Vec<Interned<TypeBound>>,
76 /// A single generic argument.
77 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
80 Lifetime(LifetimeRef),
84 /// Converts an `ast::Path` to `Path`. Works with use trees.
85 /// It correctly handles `$crate` based path from macro call.
86 pub fn from_src(path: ast::Path, ctx: &LowerCtx) -> Option<Path> {
87 lower::lower_path(path, ctx)
90 /// Converts a known mod path to `Path`.
91 pub fn from_known_path(
93 generic_args: impl Into<Box<[Option<Interned<GenericArgs>>]>>,
95 let generic_args = generic_args.into();
96 assert_eq!(path.len(), generic_args.len());
97 Path { type_anchor: None, mod_path: Interned::new(path), generic_args }
100 pub fn kind(&self) -> &PathKind {
104 pub fn type_anchor(&self) -> Option<&TypeRef> {
105 self.type_anchor.as_deref()
108 pub fn segments(&self) -> PathSegments<'_> {
109 PathSegments { segments: self.mod_path.segments(), generic_args: &self.generic_args }
112 pub fn mod_path(&self) -> &ModPath {
116 pub fn qualifier(&self) -> Option<Path> {
117 if self.mod_path.is_ident() {
121 type_anchor: self.type_anchor.clone(),
122 mod_path: Interned::new(ModPath::from_segments(
123 self.mod_path.kind.clone(),
124 self.mod_path.segments()[..self.mod_path.segments().len() - 1].iter().cloned(),
126 generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec().into(),
131 pub fn is_self_type(&self) -> bool {
132 self.type_anchor.is_none()
133 && *self.generic_args == [None]
134 && self.mod_path.as_ident() == Some(&name!(Self))
138 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
139 pub struct PathSegment<'a> {
141 pub args_and_bindings: Option<&'a GenericArgs>,
144 pub struct PathSegments<'a> {
145 segments: &'a [Name],
146 generic_args: &'a [Option<Interned<GenericArgs>>],
149 impl<'a> PathSegments<'a> {
150 pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
151 pub fn is_empty(&self) -> bool {
154 pub fn len(&self) -> usize {
157 pub fn first(&self) -> Option<PathSegment<'a>> {
160 pub fn last(&self) -> Option<PathSegment<'a>> {
161 self.get(self.len().checked_sub(1)?)
163 pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
164 assert_eq!(self.segments.len(), self.generic_args.len());
165 let res = PathSegment {
166 name: self.segments.get(idx)?,
167 args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
171 pub fn skip(&self, len: usize) -> PathSegments<'a> {
172 assert_eq!(self.segments.len(), self.generic_args.len());
173 PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
175 pub fn take(&self, len: usize) -> PathSegments<'a> {
176 assert_eq!(self.segments.len(), self.generic_args.len());
177 PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
179 pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
180 self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
182 args_and_bindings: args.as_ref().map(|it| &**it),
188 pub(crate) fn from_ast(lower_ctx: &LowerCtx, node: ast::GenericArgList) -> Option<GenericArgs> {
189 lower::lower_generic_args(lower_ctx, node)
192 pub(crate) fn empty() -> GenericArgs {
195 has_self_type: false,
196 bindings: Vec::new(),
197 desugared_from_fn: false,
202 impl From<Name> for Path {
203 fn from(name: Name) -> Path {
206 mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
207 generic_args: Box::new([None]),
212 impl From<Name> for Box<Path> {
213 fn from(name: Name) -> Box<Path> {
214 Box::new(Path::from(name))