hir_expand/
mod_path.rs

1//! A lowering for `use`-paths (more generally, paths without angle-bracketed segments).
2
3use std::{
4    fmt::{self, Display as _},
5    iter,
6};
7
8use crate::{
9    db::ExpandDatabase,
10    hygiene::Transparency,
11    name::{AsName, Name},
12    tt,
13};
14use base_db::Crate;
15use intern::sym;
16use smallvec::SmallVec;
17use span::{Edition, SyntaxContext};
18use syntax::{AstNode, ast};
19
20#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub struct ModPath {
22    pub kind: PathKind,
23    segments: SmallVec<[Name; 1]>,
24}
25
26#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub enum PathKind {
28    Plain,
29    /// `self::` is `Super(0)`
30    Super(u8),
31    Crate,
32    /// Absolute path (::foo)
33    Abs,
34    // FIXME: Can we remove this somehow?
35    /// `$crate` from macro expansion
36    DollarCrate(Crate),
37}
38
39impl PathKind {
40    pub const SELF: PathKind = PathKind::Super(0);
41}
42
43impl ModPath {
44    pub fn from_src(
45        db: &dyn ExpandDatabase,
46        path: ast::Path,
47        span_for_range: &mut dyn FnMut(::tt::TextRange) -> SyntaxContext,
48    ) -> Option<ModPath> {
49        convert_path(db, path, span_for_range)
50    }
51
52    pub fn from_tt(db: &dyn ExpandDatabase, tt: tt::TokenTreesView<'_>) -> Option<ModPath> {
53        convert_path_tt(db, tt)
54    }
55
56    pub fn from_segments(kind: PathKind, segments: impl IntoIterator<Item = Name>) -> ModPath {
57        let mut segments: SmallVec<_> = segments.into_iter().collect();
58        segments.shrink_to_fit();
59        ModPath { kind, segments }
60    }
61
62    /// Creates a `ModPath` from a `PathKind`, with no extra path segments.
63    pub const fn from_kind(kind: PathKind) -> ModPath {
64        ModPath { kind, segments: SmallVec::new_const() }
65    }
66
67    pub fn segments(&self) -> &[Name] {
68        &self.segments
69    }
70
71    pub fn push_segment(&mut self, segment: Name) {
72        self.segments.push(segment);
73    }
74
75    pub fn pop_segment(&mut self) -> Option<Name> {
76        self.segments.pop()
77    }
78
79    /// Returns the number of segments in the path (counting special segments like `$crate` and
80    /// `super`).
81    pub fn len(&self) -> usize {
82        self.segments.len()
83            + match self.kind {
84                PathKind::Plain => 0,
85                PathKind::Super(i) => i as usize,
86                PathKind::Crate => 1,
87                PathKind::Abs => 0,
88                PathKind::DollarCrate(_) => 1,
89            }
90    }
91
92    pub fn textual_len(&self) -> usize {
93        let base = match self.kind {
94            PathKind::Plain => 0,
95            PathKind::SELF => "self".len(),
96            PathKind::Super(i) => "super".len() * i as usize,
97            PathKind::Crate => "crate".len(),
98            PathKind::Abs => 0,
99            PathKind::DollarCrate(_) => "$crate".len(),
100        };
101        self.segments().iter().map(|segment| segment.as_str().len()).fold(base, core::ops::Add::add)
102    }
103
104    pub fn is_ident(&self) -> bool {
105        self.as_ident().is_some()
106    }
107
108    pub fn is_self(&self) -> bool {
109        self.kind == PathKind::SELF && self.segments.is_empty()
110    }
111
112    #[allow(non_snake_case)]
113    pub fn is_Self(&self) -> bool {
114        self.kind == PathKind::Plain && matches!(&*self.segments, [name] if *name == sym::Self_)
115    }
116
117    /// If this path is a single identifier, like `foo`, return its name.
118    pub fn as_ident(&self) -> Option<&Name> {
119        if self.kind != PathKind::Plain {
120            return None;
121        }
122
123        match &*self.segments {
124            [name] => Some(name),
125            _ => None,
126        }
127    }
128    pub fn display_verbatim<'a>(
129        &'a self,
130        db: &'a dyn crate::db::ExpandDatabase,
131    ) -> impl fmt::Display + 'a {
132        Display { db, path: self, edition: None }
133    }
134
135    pub fn display<'a>(
136        &'a self,
137        db: &'a dyn crate::db::ExpandDatabase,
138        edition: Edition,
139    ) -> impl fmt::Display + 'a {
140        Display { db, path: self, edition: Some(edition) }
141    }
142}
143
144impl Extend<Name> for ModPath {
145    fn extend<T: IntoIterator<Item = Name>>(&mut self, iter: T) {
146        self.segments.extend(iter);
147    }
148}
149
150struct Display<'a> {
151    db: &'a dyn ExpandDatabase,
152    path: &'a ModPath,
153    edition: Option<Edition>,
154}
155
156impl fmt::Display for Display<'_> {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        display_fmt_path(self.db, self.path, f, self.edition)
159    }
160}
161
162impl From<Name> for ModPath {
163    fn from(name: Name) -> ModPath {
164        ModPath::from_segments(PathKind::Plain, iter::once(name))
165    }
166}
167
168fn display_fmt_path(
169    db: &dyn ExpandDatabase,
170    path: &ModPath,
171    f: &mut fmt::Formatter<'_>,
172    edition: Option<Edition>,
173) -> fmt::Result {
174    let mut first_segment = true;
175    let mut add_segment = |s| -> fmt::Result {
176        if !first_segment {
177            f.write_str("::")?;
178        }
179        first_segment = false;
180        f.write_str(s)?;
181        Ok(())
182    };
183    match path.kind {
184        PathKind::Plain => {}
185        PathKind::SELF => add_segment("self")?,
186        PathKind::Super(n) => {
187            for _ in 0..n {
188                add_segment("super")?;
189            }
190        }
191        PathKind::Crate => add_segment("crate")?,
192        PathKind::Abs => add_segment("")?,
193        PathKind::DollarCrate(_) => add_segment("$crate")?,
194    }
195    for segment in &path.segments {
196        if !first_segment {
197            f.write_str("::")?;
198        }
199        first_segment = false;
200        match edition {
201            Some(edition) => segment.display(db, edition).fmt(f)?,
202            None => fmt::Display::fmt(segment.as_str(), f)?,
203        };
204    }
205    Ok(())
206}
207
208fn convert_path(
209    db: &dyn ExpandDatabase,
210    path: ast::Path,
211    span_for_range: &mut dyn FnMut(::tt::TextRange) -> SyntaxContext,
212) -> Option<ModPath> {
213    let mut segments = path.segments();
214
215    let segment = &segments.next()?;
216    let handle_super_kw = &mut |init_deg| {
217        let mut deg = init_deg;
218        let mut next_segment = None;
219        for segment in segments.by_ref() {
220            match segment.kind()? {
221                ast::PathSegmentKind::SuperKw => deg += 1,
222                ast::PathSegmentKind::Name(name) => {
223                    next_segment = Some(name.as_name());
224                    break;
225                }
226                ast::PathSegmentKind::Type { .. }
227                | ast::PathSegmentKind::SelfTypeKw
228                | ast::PathSegmentKind::SelfKw
229                | ast::PathSegmentKind::CrateKw => return None,
230            }
231        }
232
233        Some(ModPath::from_segments(PathKind::Super(deg), next_segment))
234    };
235
236    let mut mod_path = match segment.kind()? {
237        ast::PathSegmentKind::Name(name_ref) => {
238            if name_ref.text() == "$crate" {
239                ModPath::from_kind(
240                    resolve_crate_root(db, span_for_range(name_ref.syntax().text_range()))
241                        .map(PathKind::DollarCrate)
242                        .unwrap_or(PathKind::Crate),
243                )
244            } else {
245                let mut res = ModPath::from_kind(
246                    segment.coloncolon_token().map_or(PathKind::Plain, |_| PathKind::Abs),
247                );
248                res.segments.push(name_ref.as_name());
249                res
250            }
251        }
252        ast::PathSegmentKind::SelfTypeKw => {
253            ModPath::from_segments(PathKind::Plain, Some(Name::new_symbol_root(sym::Self_)))
254        }
255        ast::PathSegmentKind::CrateKw => ModPath::from_segments(PathKind::Crate, iter::empty()),
256        ast::PathSegmentKind::SelfKw => handle_super_kw(0)?,
257        ast::PathSegmentKind::SuperKw => handle_super_kw(1)?,
258        ast::PathSegmentKind::Type { .. } => {
259            // not allowed in imports
260            return None;
261        }
262    };
263
264    for segment in segments {
265        let name = match segment.kind()? {
266            ast::PathSegmentKind::Name(name) => name.as_name(),
267            _ => return None,
268        };
269        mod_path.segments.push(name);
270    }
271
272    // handle local_inner_macros :
273    // Basically, even in rustc it is quite hacky:
274    // https://github.com/rust-lang/rust/blob/614f273e9388ddd7804d5cbc80b8865068a3744e/src/librustc_resolve/macros.rs#L456
275    // We follow what it did anyway :)
276    if mod_path.segments.len() == 1
277        && mod_path.kind == PathKind::Plain
278        && let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast)
279    {
280        let syn_ctx = span_for_range(segment.syntax().text_range());
281        if let Some(macro_call_id) = syn_ctx.outer_expn(db)
282            && db.lookup_intern_macro_call(macro_call_id.into()).def.local_inner
283        {
284            mod_path.kind = match resolve_crate_root(db, syn_ctx) {
285                Some(crate_root) => PathKind::DollarCrate(crate_root),
286                None => PathKind::Crate,
287            }
288        }
289    }
290
291    Some(mod_path)
292}
293
294fn convert_path_tt(db: &dyn ExpandDatabase, tt: tt::TokenTreesView<'_>) -> Option<ModPath> {
295    let mut leaves = tt.iter().filter_map(|tt| match tt {
296        tt::TtElement::Leaf(leaf) => Some(leaf),
297        tt::TtElement::Subtree(..) => None,
298    });
299    let mut segments = smallvec::smallvec![];
300    let kind = match leaves.next()? {
301        tt::Leaf::Punct(tt::Punct { char: ':', .. }) => match leaves.next()? {
302            tt::Leaf::Punct(tt::Punct { char: ':', .. }) => PathKind::Abs,
303            _ => return None,
304        },
305        tt::Leaf::Ident(tt::Ident { sym: text, span, .. }) if *text == sym::dollar_crate => {
306            resolve_crate_root(db, span.ctx).map(PathKind::DollarCrate).unwrap_or(PathKind::Crate)
307        }
308        tt::Leaf::Ident(tt::Ident { sym: text, .. }) if *text == sym::self_ => PathKind::SELF,
309        tt::Leaf::Ident(tt::Ident { sym: text, .. }) if *text == sym::super_ => {
310            let mut deg = 1;
311            while let Some(tt::Leaf::Ident(tt::Ident { sym: text, span, is_raw: _ })) =
312                leaves.next()
313            {
314                if *text != sym::super_ {
315                    segments.push(Name::new_symbol(text.clone(), span.ctx));
316                    break;
317                }
318                deg += 1;
319            }
320            PathKind::Super(deg)
321        }
322        tt::Leaf::Ident(tt::Ident { sym: text, .. }) if *text == sym::crate_ => PathKind::Crate,
323        tt::Leaf::Ident(ident) => {
324            segments.push(Name::new_symbol(ident.sym.clone(), ident.span.ctx));
325            PathKind::Plain
326        }
327        _ => return None,
328    };
329    segments.extend(leaves.filter_map(|leaf| match leaf {
330        ::tt::Leaf::Ident(ident) => Some(Name::new_symbol(ident.sym.clone(), ident.span.ctx)),
331        _ => None,
332    }));
333    Some(ModPath { kind, segments })
334}
335
336pub fn resolve_crate_root(db: &dyn ExpandDatabase, mut ctxt: SyntaxContext) -> Option<Crate> {
337    // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
338    // we don't want to pretend that the `macro_rules!` definition is in the `macro`
339    // as described in `SyntaxContextId::apply_mark`, so we ignore prepended opaque marks.
340    // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
341    // definitions actually produced by `macro` and `macro` definitions produced by
342    // `macro_rules!`, but at least such configurations are not stable yet.
343    ctxt = ctxt.normalize_to_macro_rules(db);
344    let mut iter = ctxt.marks_rev(db).peekable();
345    let mut result_mark = None;
346    // Find the last opaque mark from the end if it exists.
347    while let Some(&(mark, Transparency::Opaque)) = iter.peek() {
348        result_mark = Some(mark);
349        iter.next();
350    }
351    // Then find the last semi-transparent mark from the end if it exists.
352    while let Some((mark, Transparency::SemiTransparent)) = iter.next() {
353        result_mark = Some(mark);
354    }
355
356    result_mark.map(|call| db.lookup_intern_macro_call(call.into()).def.krate)
357}
358
359pub use crate::name as __name;
360
361#[macro_export]
362macro_rules! __known_path {
363    (core::iter::IntoIterator) => {};
364    (core::iter::Iterator) => {};
365    (core::result::Result) => {};
366    (core::option::Option) => {};
367    (core::ops::Range) => {};
368    (core::ops::RangeFrom) => {};
369    (core::ops::RangeFull) => {};
370    (core::ops::RangeTo) => {};
371    (core::ops::RangeToInclusive) => {};
372    (core::ops::RangeInclusive) => {};
373    (core::future::Future) => {};
374    (core::future::IntoFuture) => {};
375    (core::fmt::Debug) => {};
376    (std::fmt::format) => {};
377    (core::ops::Try) => {};
378    (core::convert::From) => {};
379    (core::convert::TryFrom) => {};
380    (core::str::FromStr) => {};
381    ($path:path) => {
382        compile_error!("Please register your known path in the path module")
383    };
384}
385
386#[macro_export]
387macro_rules! __path {
388    ($start:ident $(:: $seg:ident)*) => ({
389        $crate::__known_path!($start $(:: $seg)*);
390        $crate::mod_path::ModPath::from_segments($crate::mod_path::PathKind::Abs, vec![
391            $crate::name::Name::new_symbol_root($crate::intern::sym::$start.clone()), $($crate::name::Name::new_symbol_root($crate::intern::sym::$seg.clone()),)*
392        ])
393    });
394}
395
396pub use crate::__path as path;
397
398#[macro_export]
399macro_rules! __tool_path {
400    ($start:ident $(:: $seg:ident)*) => ({
401        $crate::mod_path::ModPath::from_segments($crate::mod_path::PathKind::Plain, vec![
402            $crate::name::Name::new_symbol_root($crate::intern::sym::rust_analyzer), $crate::name::Name::new_symbol_root($crate::intern::sym::$start.clone()), $($crate::name::Name::new_symbol_root($crate::intern::sym::$seg.clone()),)*
403        ])
404    });
405}
406
407pub use crate::__tool_path as tool_path;