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;
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() && *self.generic_args == [None] && self.mod_path.is_Self()
141 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
142 pub struct PathSegment<'a> {
144 pub args_and_bindings: Option<&'a GenericArgs>,
147 pub struct PathSegments<'a> {
148 segments: &'a [Name],
149 generic_args: &'a [Option<Interned<GenericArgs>>],
152 impl<'a> PathSegments<'a> {
153 pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
154 pub fn is_empty(&self) -> bool {
157 pub fn len(&self) -> usize {
160 pub fn first(&self) -> Option<PathSegment<'a>> {
163 pub fn last(&self) -> Option<PathSegment<'a>> {
164 self.get(self.len().checked_sub(1)?)
166 pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
167 assert_eq!(self.segments.len(), self.generic_args.len());
168 let res = PathSegment {
169 name: self.segments.get(idx)?,
170 args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
174 pub fn skip(&self, len: usize) -> PathSegments<'a> {
175 assert_eq!(self.segments.len(), self.generic_args.len());
176 PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
178 pub fn take(&self, len: usize) -> PathSegments<'a> {
179 assert_eq!(self.segments.len(), self.generic_args.len());
180 PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
182 pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
183 self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
185 args_and_bindings: args.as_ref().map(|it| &**it),
191 pub(crate) fn from_ast(
192 lower_ctx: &LowerCtx<'_>,
193 node: ast::GenericArgList,
194 ) -> Option<GenericArgs> {
195 lower::lower_generic_args(lower_ctx, node)
198 pub(crate) fn empty() -> GenericArgs {
201 has_self_type: false,
202 bindings: Vec::new(),
203 desugared_from_fn: false,
208 impl From<Name> for Path {
209 fn from(name: Name) -> Path {
212 mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
213 generic_args: Box::new([None]),
218 impl From<Name> for Box<Path> {
219 fn from(name: Name) -> Box<Path> {
220 Box::new(Path::from(name))