1 //! A desugared representation of paths like `crate::foo` or `<Type as Trait>::bar`.
9 use crate::{body::LowerCtx, db::DefDatabase, intern::Interned, type_ref::LifetimeRef};
17 use crate::type_ref::{TypeBound, TypeRef};
19 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
25 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
28 /// `self::` is `Super(0)`
31 /// Absolute path (::foo)
33 /// `$crate` from macro expansion
37 #[derive(Debug, Clone, PartialEq, Eq)]
38 pub enum ImportAlias {
39 /// Unnamed alias, as in `use Foo as _;`
45 impl Display for ImportAlias {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 ImportAlias::Underscore => f.write_str("_"),
49 ImportAlias::Alias(name) => f.write_str(&name.to_string()),
55 pub fn from_src(db: &dyn DefDatabase, path: ast::Path, hygiene: &Hygiene) -> Option<ModPath> {
56 lower::convert_path(db, None, path, hygiene)
59 pub fn from_segments(kind: PathKind, segments: impl IntoIterator<Item = Name>) -> ModPath {
60 let segments = segments.into_iter().collect::<Vec<_>>();
61 ModPath { kind, segments }
64 /// Creates a `ModPath` from a `PathKind`, with no extra path segments.
65 pub const fn from_kind(kind: PathKind) -> ModPath {
66 ModPath { kind, segments: Vec::new() }
69 pub fn segments(&self) -> &[Name] {
73 pub fn push_segment(&mut self, segment: Name) {
74 self.segments.push(segment);
77 pub fn pop_segment(&mut self) -> Option<Name> {
81 /// Returns the number of segments in the path (counting special segments like `$crate` and
83 pub fn len(&self) -> usize {
87 PathKind::Super(i) => i as usize,
90 PathKind::DollarCrate(_) => 1,
94 pub fn is_ident(&self) -> bool {
95 self.as_ident().is_some()
98 pub fn is_self(&self) -> bool {
99 self.kind == PathKind::Super(0) && self.segments.is_empty()
102 /// If this path is a single identifier, like `foo`, return its name.
103 pub fn as_ident(&self) -> Option<&Name> {
104 if self.kind != PathKind::Plain {
108 match &*self.segments {
109 [name] => Some(name),
115 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
117 /// Type based path like `<T>::foo`.
118 /// Note that paths like `<Type as Trait>::foo` are desugard to `Trait::<Self=Type>::foo`.
119 type_anchor: Option<Interned<TypeRef>>,
120 mod_path: Interned<ModPath>,
121 /// Invariant: the same len as `self.mod_path.segments`
122 generic_args: Vec<Option<Interned<GenericArgs>>>,
125 /// Generic arguments to a path segment (e.g. the `i32` in `Option<i32>`). This
126 /// also includes bindings of associated types, like in `Iterator<Item = Foo>`.
127 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
128 pub struct GenericArgs {
129 pub args: Vec<GenericArg>,
130 /// This specifies whether the args contain a Self type as the first
131 /// element. This is the case for path segments like `<T as Trait>`, where
132 /// `T` is actually a type parameter for the path `Trait` specifying the
133 /// Self type. Otherwise, when we have a path `Trait<X, Y>`, the Self type
135 pub has_self_type: bool,
136 /// Associated type bindings like in `Iterator<Item = T>`.
137 pub bindings: Vec<AssociatedTypeBinding>,
140 /// An associated type binding like in `Iterator<Item = T>`.
141 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
142 pub struct AssociatedTypeBinding {
143 /// The name of the associated type.
145 /// The type bound to this associated type (in `Item = T`, this would be the
146 /// `T`). This can be `None` if there are bounds instead.
147 pub type_ref: Option<TypeRef>,
148 /// Bounds for the associated type, like in `Iterator<Item:
149 /// SomeOtherTrait>`. (This is the unstable `associated_type_bounds`
151 pub bounds: Vec<Interned<TypeBound>>,
154 /// A single generic argument.
155 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
156 pub enum GenericArg {
158 Lifetime(LifetimeRef),
162 /// Converts an `ast::Path` to `Path`. Works with use trees.
163 /// It correctly handles `$crate` based path from macro call.
164 pub fn from_src(path: ast::Path, ctx: &LowerCtx) -> Option<Path> {
165 lower::lower_path(path, ctx)
168 /// Converts a known mod path to `Path`.
169 pub fn from_known_path(
171 generic_args: Vec<Option<Interned<GenericArgs>>>,
173 Path { type_anchor: None, mod_path: Interned::new(path), generic_args }
176 pub fn kind(&self) -> &PathKind {
180 pub fn type_anchor(&self) -> Option<&TypeRef> {
181 self.type_anchor.as_deref()
184 pub fn segments(&self) -> PathSegments<'_> {
186 segments: self.mod_path.segments.as_slice(),
187 generic_args: self.generic_args.as_slice(),
191 pub fn mod_path(&self) -> &ModPath {
195 pub fn qualifier(&self) -> Option<Path> {
196 if self.mod_path.is_ident() {
200 type_anchor: self.type_anchor.clone(),
201 mod_path: Interned::new(ModPath::from_segments(
202 self.mod_path.kind.clone(),
203 self.mod_path.segments[..self.mod_path.segments.len() - 1].iter().cloned(),
205 generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec(),
210 pub fn is_self_type(&self) -> bool {
211 self.type_anchor.is_none()
212 && self.generic_args == [None]
213 && self.mod_path.as_ident() == Some(&name!(Self))
217 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
218 pub struct PathSegment<'a> {
220 pub args_and_bindings: Option<&'a GenericArgs>,
223 pub struct PathSegments<'a> {
224 segments: &'a [Name],
225 generic_args: &'a [Option<Interned<GenericArgs>>],
228 impl<'a> PathSegments<'a> {
229 pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
230 pub fn is_empty(&self) -> bool {
233 pub fn len(&self) -> usize {
236 pub fn first(&self) -> Option<PathSegment<'a>> {
239 pub fn last(&self) -> Option<PathSegment<'a>> {
240 self.get(self.len().checked_sub(1)?)
242 pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
243 assert_eq!(self.segments.len(), self.generic_args.len());
244 let res = PathSegment {
245 name: self.segments.get(idx)?,
246 args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
250 pub fn skip(&self, len: usize) -> PathSegments<'a> {
251 assert_eq!(self.segments.len(), self.generic_args.len());
252 PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
254 pub fn take(&self, len: usize) -> PathSegments<'a> {
255 assert_eq!(self.segments.len(), self.generic_args.len());
256 PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
258 pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
259 self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
261 args_and_bindings: args.as_ref().map(|it| &**it),
267 pub(crate) fn from_ast(lower_ctx: &LowerCtx, node: ast::GenericArgList) -> Option<GenericArgs> {
268 lower::lower_generic_args(lower_ctx, node)
271 pub(crate) fn empty() -> GenericArgs {
272 GenericArgs { args: Vec::new(), has_self_type: false, bindings: Vec::new() }
276 impl From<Name> for Path {
277 fn from(name: Name) -> Path {
280 mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
281 generic_args: vec![None],
286 impl From<Name> for Box<Path> {
287 fn from(name: Name) -> Box<Path> {
288 Box::new(Path::from(name))
292 impl From<Name> for ModPath {
293 fn from(name: Name) -> ModPath {
294 ModPath::from_segments(PathKind::Plain, iter::once(name))
298 impl Display for ModPath {
299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300 let mut first_segment = true;
301 let mut add_segment = |s| -> fmt::Result {
305 first_segment = false;
310 PathKind::Plain => {}
311 PathKind::Super(0) => add_segment("self")?,
312 PathKind::Super(n) => {
314 add_segment("super")?;
317 PathKind::Crate => add_segment("crate")?,
318 PathKind::Abs => add_segment("")?,
319 PathKind::DollarCrate(_) => add_segment("$crate")?,
321 for segment in &self.segments {
325 first_segment = false;
326 write!(f, "{}", segment)?;
332 pub use hir_expand::name as __name;
335 macro_rules! __known_path {
336 (core::iter::IntoIterator) => {};
337 (core::iter::Iterator) => {};
338 (core::result::Result) => {};
339 (core::option::Option) => {};
340 (core::ops::Range) => {};
341 (core::ops::RangeFrom) => {};
342 (core::ops::RangeFull) => {};
343 (core::ops::RangeTo) => {};
344 (core::ops::RangeToInclusive) => {};
345 (core::ops::RangeInclusive) => {};
346 (core::future::Future) => {};
347 (core::ops::Try) => {};
349 compile_error!("Please register your known path in the path module")
354 macro_rules! __path {
355 ($start:ident $(:: $seg:ident)*) => ({
356 $crate::__known_path!($start $(:: $seg)*);
357 $crate::path::ModPath::from_segments($crate::path::PathKind::Abs, vec![
358 $crate::path::__name![$start], $($crate::path::__name![$seg],)*
363 pub use crate::__path as path;