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};
18 type_ref::{TypeBound, TypeRef},
22 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
28 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
31 /// `self::` is `Super(0)`
34 /// Absolute path (::foo)
36 /// `$crate` from macro expansion
40 #[derive(Debug, Clone, PartialEq, Eq)]
41 pub enum ImportAlias {
42 /// Unnamed alias, as in `use Foo as _;`
48 impl Display for ImportAlias {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 ImportAlias::Underscore => f.write_str("_"),
52 ImportAlias::Alias(name) => f.write_str(&name.to_string()),
58 pub fn from_src(db: &dyn DefDatabase, path: ast::Path, hygiene: &Hygiene) -> Option<ModPath> {
59 let ctx = LowerCtx::with_hygiene(db, hygiene);
60 lower::lower_path(path, &ctx).map(|it| (*it.mod_path).clone())
63 pub fn from_segments(kind: PathKind, segments: impl IntoIterator<Item = Name>) -> ModPath {
64 let segments = segments.into_iter().collect::<Vec<_>>();
65 ModPath { kind, segments }
68 /// Creates a `ModPath` from a `PathKind`, with no extra path segments.
69 pub const fn from_kind(kind: PathKind) -> ModPath {
70 ModPath { kind, segments: Vec::new() }
73 /// Calls `cb` with all paths, represented by this use item.
74 pub fn expand_use_item(
76 item_src: InFile<ast::Use>,
78 mut cb: impl FnMut(ModPath, &ast::UseTree, /* is_glob */ bool, Option<ImportAlias>),
80 if let Some(tree) = item_src.value.use_tree() {
81 lower::lower_use_tree(db, None, tree, hygiene, &mut cb);
85 pub fn segments(&self) -> &[Name] {
89 pub fn push_segment(&mut self, segment: Name) {
90 self.segments.push(segment);
93 pub fn pop_segment(&mut self) -> Option<Name> {
97 /// Returns the number of segments in the path (counting special segments like `$crate` and
99 pub fn len(&self) -> usize {
102 PathKind::Plain => 0,
103 PathKind::Super(i) => i as usize,
104 PathKind::Crate => 1,
106 PathKind::DollarCrate(_) => 1,
110 pub fn is_ident(&self) -> bool {
111 self.as_ident().is_some()
114 pub fn is_self(&self) -> bool {
115 self.kind == PathKind::Super(0) && self.segments.is_empty()
118 /// If this path is a single identifier, like `foo`, return its name.
119 pub fn as_ident(&self) -> Option<&Name> {
120 if self.kind != PathKind::Plain {
124 match &*self.segments {
125 [name] => Some(name),
131 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
133 /// Type based path like `<T>::foo`.
134 /// Note that paths like `<Type as Trait>::foo` are desugard to `Trait::<Self=Type>::foo`.
135 type_anchor: Option<Interned<TypeRef>>,
136 mod_path: Interned<ModPath>,
137 /// Invariant: the same len as `self.mod_path.segments`
138 generic_args: Vec<Option<Interned<GenericArgs>>>,
141 /// Generic arguments to a path segment (e.g. the `i32` in `Option<i32>`). This
142 /// also includes bindings of associated types, like in `Iterator<Item = Foo>`.
143 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
144 pub struct GenericArgs {
145 pub args: Vec<GenericArg>,
146 /// This specifies whether the args contain a Self type as the first
147 /// element. This is the case for path segments like `<T as Trait>`, where
148 /// `T` is actually a type parameter for the path `Trait` specifying the
149 /// Self type. Otherwise, when we have a path `Trait<X, Y>`, the Self type
151 pub has_self_type: bool,
152 /// Associated type bindings like in `Iterator<Item = T>`.
153 pub bindings: Vec<AssociatedTypeBinding>,
156 /// An associated type binding like in `Iterator<Item = T>`.
157 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
158 pub struct AssociatedTypeBinding {
159 /// The name of the associated type.
161 /// The type bound to this associated type (in `Item = T`, this would be the
162 /// `T`). This can be `None` if there are bounds instead.
163 pub type_ref: Option<TypeRef>,
164 /// Bounds for the associated type, like in `Iterator<Item:
165 /// SomeOtherTrait>`. (This is the unstable `associated_type_bounds`
167 pub bounds: Vec<Interned<TypeBound>>,
170 /// A single generic argument.
171 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
172 pub enum GenericArg {
174 Lifetime(LifetimeRef),
178 /// Converts an `ast::Path` to `Path`. Works with use trees.
179 /// It correctly handles `$crate` based path from macro call.
180 pub fn from_src(path: ast::Path, ctx: &LowerCtx) -> Option<Path> {
181 lower::lower_path(path, ctx)
184 /// Converts a known mod path to `Path`.
185 pub(crate) fn from_known_path(
187 generic_args: Vec<Option<Interned<GenericArgs>>>,
189 Path { type_anchor: None, mod_path: Interned::new(path), generic_args }
192 pub fn kind(&self) -> &PathKind {
196 pub fn type_anchor(&self) -> Option<&TypeRef> {
197 self.type_anchor.as_deref()
200 pub fn segments(&self) -> PathSegments<'_> {
202 segments: self.mod_path.segments.as_slice(),
203 generic_args: self.generic_args.as_slice(),
207 pub fn mod_path(&self) -> &ModPath {
211 pub fn qualifier(&self) -> Option<Path> {
212 if self.mod_path.is_ident() {
216 type_anchor: self.type_anchor.clone(),
217 mod_path: Interned::new(ModPath::from_segments(
218 self.mod_path.kind.clone(),
219 self.mod_path.segments[..self.mod_path.segments.len() - 1].iter().cloned(),
221 generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec(),
226 pub fn is_self_type(&self) -> bool {
227 self.type_anchor.is_none()
228 && self.generic_args == &[None]
229 && self.mod_path.as_ident() == Some(&name!(Self))
233 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
234 pub struct PathSegment<'a> {
236 pub args_and_bindings: Option<&'a GenericArgs>,
239 pub struct PathSegments<'a> {
240 segments: &'a [Name],
241 generic_args: &'a [Option<Interned<GenericArgs>>],
244 impl<'a> PathSegments<'a> {
245 pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
246 pub fn is_empty(&self) -> bool {
249 pub fn len(&self) -> usize {
252 pub fn first(&self) -> Option<PathSegment<'a>> {
255 pub fn last(&self) -> Option<PathSegment<'a>> {
256 self.get(self.len().checked_sub(1)?)
258 pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
259 assert_eq!(self.segments.len(), self.generic_args.len());
260 let res = PathSegment {
261 name: self.segments.get(idx)?,
262 args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
266 pub fn skip(&self, len: usize) -> PathSegments<'a> {
267 assert_eq!(self.segments.len(), self.generic_args.len());
268 PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
270 pub fn take(&self, len: usize) -> PathSegments<'a> {
271 assert_eq!(self.segments.len(), self.generic_args.len());
272 PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
274 pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
275 self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
277 args_and_bindings: args.as_ref().map(|it| &**it),
283 pub(crate) fn from_ast(lower_ctx: &LowerCtx, node: ast::GenericArgList) -> Option<GenericArgs> {
284 lower::lower_generic_args(lower_ctx, node)
287 pub(crate) fn empty() -> GenericArgs {
288 GenericArgs { args: Vec::new(), has_self_type: false, bindings: Vec::new() }
292 impl From<Name> for Path {
293 fn from(name: Name) -> Path {
296 mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
297 generic_args: vec![None],
302 impl From<Name> for Box<Path> {
303 fn from(name: Name) -> Box<Path> {
304 Box::new(Path::from(name))
308 impl From<Name> for ModPath {
309 fn from(name: Name) -> ModPath {
310 ModPath::from_segments(PathKind::Plain, iter::once(name))
314 impl Display for ModPath {
315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316 let mut first_segment = true;
317 let mut add_segment = |s| -> fmt::Result {
321 first_segment = false;
326 PathKind::Plain => {}
327 PathKind::Super(0) => add_segment("self")?,
328 PathKind::Super(n) => {
330 add_segment("super")?;
333 PathKind::Crate => add_segment("crate")?,
334 PathKind::Abs => add_segment("")?,
335 PathKind::DollarCrate(_) => add_segment("$crate")?,
337 for segment in &self.segments {
341 first_segment = false;
342 write!(f, "{}", segment)?;
348 pub use hir_expand::name as __name;
351 macro_rules! __known_path {
352 (core::iter::IntoIterator) => {};
353 (core::iter::Iterator) => {};
354 (core::result::Result) => {};
355 (core::option::Option) => {};
356 (core::ops::Range) => {};
357 (core::ops::RangeFrom) => {};
358 (core::ops::RangeFull) => {};
359 (core::ops::RangeTo) => {};
360 (core::ops::RangeToInclusive) => {};
361 (core::ops::RangeInclusive) => {};
362 (core::future::Future) => {};
363 (core::ops::Try) => {};
365 compile_error!("Please register your known path in the path module")
370 macro_rules! __path {
371 ($start:ident $(:: $seg:ident)*) => ({
372 $crate::__known_path!($start $(:: $seg)*);
373 $crate::path::ModPath::from_segments($crate::path::PathKind::Abs, vec![
374 $crate::path::__name![$start], $($crate::path::__name![$seg],)*
379 pub use crate::__path as path;