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 Path { type_anchor: None, mod_path: Interned::new(path), generic_args: generic_args.into() }
98 pub fn kind(&self) -> &PathKind {
102 pub fn type_anchor(&self) -> Option<&TypeRef> {
103 self.type_anchor.as_deref()
106 pub fn segments(&self) -> PathSegments<'_> {
107 PathSegments { segments: self.mod_path.segments(), generic_args: &self.generic_args }
110 pub fn mod_path(&self) -> &ModPath {
114 pub fn qualifier(&self) -> Option<Path> {
115 if self.mod_path.is_ident() {
119 type_anchor: self.type_anchor.clone(),
120 mod_path: Interned::new(ModPath::from_segments(
121 self.mod_path.kind.clone(),
122 self.mod_path.segments()[..self.mod_path.segments().len() - 1].iter().cloned(),
124 generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec().into(),
129 pub fn is_self_type(&self) -> bool {
130 self.type_anchor.is_none()
131 && *self.generic_args == [None]
132 && self.mod_path.as_ident() == Some(&name!(Self))
136 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
137 pub struct PathSegment<'a> {
139 pub args_and_bindings: Option<&'a GenericArgs>,
142 pub struct PathSegments<'a> {
143 segments: &'a [Name],
144 generic_args: &'a [Option<Interned<GenericArgs>>],
147 impl<'a> PathSegments<'a> {
148 pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
149 pub fn is_empty(&self) -> bool {
152 pub fn len(&self) -> usize {
155 pub fn first(&self) -> Option<PathSegment<'a>> {
158 pub fn last(&self) -> Option<PathSegment<'a>> {
159 self.get(self.len().checked_sub(1)?)
161 pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
162 assert_eq!(self.segments.len(), self.generic_args.len());
163 let res = PathSegment {
164 name: self.segments.get(idx)?,
165 args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
169 pub fn skip(&self, len: usize) -> PathSegments<'a> {
170 assert_eq!(self.segments.len(), self.generic_args.len());
171 PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
173 pub fn take(&self, len: usize) -> PathSegments<'a> {
174 assert_eq!(self.segments.len(), self.generic_args.len());
175 PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
177 pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
178 self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
180 args_and_bindings: args.as_ref().map(|it| &**it),
186 pub(crate) fn from_ast(lower_ctx: &LowerCtx, node: ast::GenericArgList) -> Option<GenericArgs> {
187 lower::lower_generic_args(lower_ctx, node)
190 pub(crate) fn empty() -> GenericArgs {
193 has_self_type: false,
194 bindings: Vec::new(),
195 desugared_from_fn: false,
200 impl From<Name> for Path {
201 fn from(name: Name) -> Path {
204 mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
205 generic_args: Box::new([None]),
210 impl From<Name> for Box<Path> {
211 fn from(name: Name) -> Box<Path> {
212 Box::new(Path::from(name))