1 //! A desugared representation of paths like `crate::foo` or `<Type as Trait>::bar`.
10 use crate::{body::LowerCtx, intern::Interned, type_ref::LifetimeRef};
19 type_ref::{TypeBound, TypeRef},
23 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
29 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
32 /// `self::` is `Super(0)`
35 /// Absolute path (::foo)
37 /// `$crate` from macro expansion
41 #[derive(Debug, Clone, PartialEq, Eq)]
42 pub enum ImportAlias {
43 /// Unnamed alias, as in `use Foo as _;`
50 pub fn from_src(path: ast::Path, hygiene: &Hygiene) -> Option<ModPath> {
51 lower::lower_path(path, hygiene).map(|it| (*it.mod_path).clone())
54 pub fn from_segments(kind: PathKind, segments: impl IntoIterator<Item = Name>) -> ModPath {
55 let segments = segments.into_iter().collect::<Vec<_>>();
56 ModPath { kind, segments }
59 /// Creates a `ModPath` from a `PathKind`, with no extra path segments.
60 pub const fn from_kind(kind: PathKind) -> ModPath {
61 ModPath { kind, segments: Vec::new() }
64 /// Calls `cb` with all paths, represented by this use item.
65 pub(crate) fn expand_use_item(
66 item_src: InFile<ast::Use>,
68 mut cb: impl FnMut(ModPath, &ast::UseTree, /* is_glob */ bool, Option<ImportAlias>),
70 if let Some(tree) = item_src.value.use_tree() {
71 lower::lower_use_tree(None, tree, hygiene, &mut cb);
75 pub fn segments(&self) -> &[Name] {
79 pub fn push_segment(&mut self, segment: Name) {
80 self.segments.push(segment);
83 pub fn pop_segment(&mut self) -> Option<Name> {
87 /// Returns the number of segments in the path (counting special segments like `$crate` and
89 pub fn len(&self) -> usize {
93 PathKind::Super(i) => i as usize,
96 PathKind::DollarCrate(_) => 1,
100 pub fn is_ident(&self) -> bool {
101 self.as_ident().is_some()
104 pub fn is_self(&self) -> bool {
105 self.kind == PathKind::Super(0) && self.segments.is_empty()
108 /// If this path is a single identifier, like `foo`, return its name.
109 pub fn as_ident(&self) -> Option<&Name> {
110 if self.kind != PathKind::Plain {
114 match &*self.segments {
115 [name] => Some(name),
121 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
123 /// Type based path like `<T>::foo`.
124 /// Note that paths like `<Type as Trait>::foo` are desugard to `Trait::<Self=Type>::foo`.
125 type_anchor: Option<Interned<TypeRef>>,
126 mod_path: Interned<ModPath>,
127 /// Invariant: the same len as `self.mod_path.segments`
128 generic_args: Vec<Option<Arc<GenericArgs>>>,
131 /// Generic arguments to a path segment (e.g. the `i32` in `Option<i32>`). This
132 /// also includes bindings of associated types, like in `Iterator<Item = Foo>`.
133 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
134 pub struct GenericArgs {
135 pub args: Vec<GenericArg>,
136 /// This specifies whether the args contain a Self type as the first
137 /// element. This is the case for path segments like `<T as Trait>`, where
138 /// `T` is actually a type parameter for the path `Trait` specifying the
139 /// Self type. Otherwise, when we have a path `Trait<X, Y>`, the Self type
141 pub has_self_type: bool,
142 /// Associated type bindings like in `Iterator<Item = T>`.
143 pub bindings: Vec<AssociatedTypeBinding>,
146 /// An associated type binding like in `Iterator<Item = T>`.
147 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
148 pub struct AssociatedTypeBinding {
149 /// The name of the associated type.
151 /// The type bound to this associated type (in `Item = T`, this would be the
152 /// `T`). This can be `None` if there are bounds instead.
153 pub type_ref: Option<TypeRef>,
154 /// Bounds for the associated type, like in `Iterator<Item:
155 /// SomeOtherTrait>`. (This is the unstable `associated_type_bounds`
157 pub bounds: Vec<TypeBound>,
160 /// A single generic argument.
161 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
162 pub enum GenericArg {
164 Lifetime(LifetimeRef),
168 /// Converts an `ast::Path` to `Path`. Works with use trees.
169 /// It correctly handles `$crate` based path from macro call.
170 pub fn from_src(path: ast::Path, hygiene: &Hygiene) -> Option<Path> {
171 lower::lower_path(path, hygiene)
174 /// Converts a known mod path to `Path`.
175 pub(crate) fn from_known_path(
177 generic_args: Vec<Option<Arc<GenericArgs>>>,
179 Path { type_anchor: None, mod_path: Interned::new(path), generic_args }
182 pub fn kind(&self) -> &PathKind {
186 pub fn type_anchor(&self) -> Option<&TypeRef> {
187 self.type_anchor.as_deref()
190 pub fn segments(&self) -> PathSegments<'_> {
192 segments: self.mod_path.segments.as_slice(),
193 generic_args: self.generic_args.as_slice(),
197 pub fn mod_path(&self) -> &ModPath {
201 pub fn qualifier(&self) -> Option<Path> {
202 if self.mod_path.is_ident() {
206 type_anchor: self.type_anchor.clone(),
207 mod_path: Interned::new(ModPath::from_segments(
208 self.mod_path.kind.clone(),
209 self.mod_path.segments[..self.mod_path.segments.len() - 1].iter().cloned(),
211 generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec(),
216 pub fn is_self_type(&self) -> bool {
217 self.type_anchor.is_none()
218 && self.generic_args == &[None]
219 && self.mod_path.as_ident() == Some(&name!(Self))
223 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
224 pub struct PathSegment<'a> {
226 pub args_and_bindings: Option<&'a GenericArgs>,
229 pub struct PathSegments<'a> {
230 segments: &'a [Name],
231 generic_args: &'a [Option<Arc<GenericArgs>>],
234 impl<'a> PathSegments<'a> {
235 pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
236 pub fn is_empty(&self) -> bool {
239 pub fn len(&self) -> usize {
242 pub fn first(&self) -> Option<PathSegment<'a>> {
245 pub fn last(&self) -> Option<PathSegment<'a>> {
246 self.get(self.len().checked_sub(1)?)
248 pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
249 assert_eq!(self.segments.len(), self.generic_args.len());
250 let res = PathSegment {
251 name: self.segments.get(idx)?,
252 args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
256 pub fn skip(&self, len: usize) -> PathSegments<'a> {
257 assert_eq!(self.segments.len(), self.generic_args.len());
258 PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
260 pub fn take(&self, len: usize) -> PathSegments<'a> {
261 assert_eq!(self.segments.len(), self.generic_args.len());
262 PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
264 pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
265 self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
267 args_and_bindings: args.as_ref().map(|it| &**it),
273 pub(crate) fn from_ast(lower_ctx: &LowerCtx, node: ast::GenericArgList) -> Option<GenericArgs> {
274 lower::lower_generic_args(lower_ctx, node)
277 pub(crate) fn empty() -> GenericArgs {
278 GenericArgs { args: Vec::new(), has_self_type: false, bindings: Vec::new() }
282 impl From<Name> for Path {
283 fn from(name: Name) -> Path {
286 mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
287 generic_args: vec![None],
292 impl From<Name> for Box<Path> {
293 fn from(name: Name) -> Box<Path> {
294 Box::new(Path::from(name))
298 impl From<Name> for ModPath {
299 fn from(name: Name) -> ModPath {
300 ModPath::from_segments(PathKind::Plain, iter::once(name))
304 impl Display for ModPath {
305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306 let mut first_segment = true;
307 let mut add_segment = |s| -> fmt::Result {
311 first_segment = false;
316 PathKind::Plain => {}
317 PathKind::Super(0) => add_segment("self")?,
318 PathKind::Super(n) => {
320 add_segment("super")?;
323 PathKind::Crate => add_segment("crate")?,
324 PathKind::Abs => add_segment("")?,
325 PathKind::DollarCrate(_) => add_segment("$crate")?,
327 for segment in &self.segments {
331 first_segment = false;
332 write!(f, "{}", segment)?;
338 pub use hir_expand::name as __name;
341 macro_rules! __known_path {
342 (core::iter::IntoIterator) => {};
343 (core::iter::Iterator) => {};
344 (core::result::Result) => {};
345 (core::option::Option) => {};
346 (core::ops::Range) => {};
347 (core::ops::RangeFrom) => {};
348 (core::ops::RangeFull) => {};
349 (core::ops::RangeTo) => {};
350 (core::ops::RangeToInclusive) => {};
351 (core::ops::RangeInclusive) => {};
352 (core::future::Future) => {};
353 (core::ops::Try) => {};
355 compile_error!("Please register your known path in the path module")
360 macro_rules! __path {
361 ($start:ident $(:: $seg:ident)*) => ({
362 $crate::__known_path!($start $(:: $seg)*);
363 $crate::path::ModPath::from_segments($crate::path::PathKind::Abs, vec![
364 $crate::path::__name![$start], $($crate::path::__name![$seg],)*
369 pub use crate::__path as path;