1 //! A desugared representation of paths like `crate::foo` or `<Type as Trait>::bar`.
12 type_ref::{ConstScalarOrPath, LifetimeRef},
14 use hir_expand::name::{name, Name};
17 use crate::type_ref::{TypeBound, TypeRef};
19 pub use hir_expand::mod_path::{path, ModPath, PathKind};
21 #[derive(Debug, Clone, PartialEq, Eq)]
22 pub enum ImportAlias {
23 /// Unnamed alias, as in `use Foo as _;`
29 impl Display for ImportAlias {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 ImportAlias::Underscore => f.write_str("_"),
33 ImportAlias::Alias(name) => f.write_str(&name.to_smol_str()),
38 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
40 /// Type based path like `<T>::foo`.
41 /// Note that paths like `<Type as Trait>::foo` are desugard to `Trait::<Self=Type>::foo`.
42 type_anchor: Option<Interned<TypeRef>>,
43 mod_path: Interned<ModPath>,
44 /// Invariant: the same len as `self.mod_path.segments`
45 generic_args: Box<[Option<Interned<GenericArgs>>]>,
48 /// Generic arguments to a path segment (e.g. the `i32` in `Option<i32>`). This
49 /// also includes bindings of associated types, like in `Iterator<Item = Foo>`.
50 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
51 pub struct GenericArgs {
52 pub args: Vec<GenericArg>,
53 /// This specifies whether the args contain a Self type as the first
54 /// element. This is the case for path segments like `<T as Trait>`, where
55 /// `T` is actually a type parameter for the path `Trait` specifying the
56 /// Self type. Otherwise, when we have a path `Trait<X, Y>`, the Self type
58 pub has_self_type: bool,
59 /// Associated type bindings like in `Iterator<Item = T>`.
60 pub bindings: Vec<AssociatedTypeBinding>,
61 /// Whether these generic args were desugared from `Trait(Arg) -> Output`
62 /// parenthesis notation typically used for the `Fn` traits.
63 pub desugared_from_fn: bool,
66 /// An associated type binding like in `Iterator<Item = T>`.
67 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
68 pub struct AssociatedTypeBinding {
69 /// The name of the associated type.
71 /// The type bound to this associated type (in `Item = T`, this would be the
72 /// `T`). This can be `None` if there are bounds instead.
73 pub type_ref: Option<TypeRef>,
74 /// Bounds for the associated type, like in `Iterator<Item:
75 /// SomeOtherTrait>`. (This is the unstable `associated_type_bounds`
77 pub bounds: Vec<Interned<TypeBound>>,
80 /// A single generic argument.
81 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
84 Lifetime(LifetimeRef),
85 Const(ConstScalarOrPath),
89 /// Converts an `ast::Path` to `Path`. Works with use trees.
90 /// It correctly handles `$crate` based path from macro call.
91 pub fn from_src(path: ast::Path, ctx: &LowerCtx) -> Option<Path> {
92 lower::lower_path(path, ctx)
95 /// Converts a known mod path to `Path`.
96 pub fn from_known_path(
98 generic_args: impl Into<Box<[Option<Interned<GenericArgs>>]>>,
100 let generic_args = generic_args.into();
101 assert_eq!(path.len(), generic_args.len());
102 Path { type_anchor: None, mod_path: Interned::new(path), generic_args }
105 pub fn kind(&self) -> &PathKind {
109 pub fn type_anchor(&self) -> Option<&TypeRef> {
110 self.type_anchor.as_deref()
113 pub fn segments(&self) -> PathSegments<'_> {
114 PathSegments { segments: self.mod_path.segments(), generic_args: &self.generic_args }
117 pub fn mod_path(&self) -> &ModPath {
121 pub fn qualifier(&self) -> Option<Path> {
122 if self.mod_path.is_ident() {
126 type_anchor: self.type_anchor.clone(),
127 mod_path: Interned::new(ModPath::from_segments(
129 self.mod_path.segments()[..self.mod_path.segments().len() - 1].iter().cloned(),
131 generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec().into(),
136 pub fn is_self_type(&self) -> bool {
137 self.type_anchor.is_none()
138 && *self.generic_args == [None]
139 && self.mod_path.as_ident() == Some(&name!(Self))
143 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
144 pub struct PathSegment<'a> {
146 pub args_and_bindings: Option<&'a GenericArgs>,
149 pub struct PathSegments<'a> {
150 segments: &'a [Name],
151 generic_args: &'a [Option<Interned<GenericArgs>>],
154 impl<'a> PathSegments<'a> {
155 pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
156 pub fn is_empty(&self) -> bool {
159 pub fn len(&self) -> usize {
162 pub fn first(&self) -> Option<PathSegment<'a>> {
165 pub fn last(&self) -> Option<PathSegment<'a>> {
166 self.get(self.len().checked_sub(1)?)
168 pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
169 assert_eq!(self.segments.len(), self.generic_args.len());
170 let res = PathSegment {
171 name: self.segments.get(idx)?,
172 args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
176 pub fn skip(&self, len: usize) -> PathSegments<'a> {
177 assert_eq!(self.segments.len(), self.generic_args.len());
178 PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
180 pub fn take(&self, len: usize) -> PathSegments<'a> {
181 assert_eq!(self.segments.len(), self.generic_args.len());
182 PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
184 pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
185 self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
187 args_and_bindings: args.as_ref().map(|it| &**it),
193 pub(crate) fn from_ast(lower_ctx: &LowerCtx, node: ast::GenericArgList) -> Option<GenericArgs> {
194 lower::lower_generic_args(lower_ctx, node)
197 pub(crate) fn empty() -> GenericArgs {
200 has_self_type: false,
201 bindings: Vec::new(),
202 desugared_from_fn: false,
207 impl From<Name> for Path {
208 fn from(name: Name) -> Path {
211 mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
212 generic_args: Box::new([None]),
217 impl From<Name> for Box<Path> {
218 fn from(name: Name) -> Box<Path> {
219 Box::new(Path::from(name))