ra_ap_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 && mod_path.kind == PathKind::Plain {
277        if let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) {
278            let syn_ctx = span_for_range(segment.syntax().text_range());
279            if let Some(macro_call_id) = syn_ctx.outer_expn(db) {
280                if db.lookup_intern_macro_call(macro_call_id.into()).def.local_inner {
281                    mod_path.kind = match resolve_crate_root(db, syn_ctx) {
282                        Some(crate_root) => PathKind::DollarCrate(crate_root),
283                        None => PathKind::Crate,
284                    }
285                }
286            }
287        }
288    }
289
290    Some(mod_path)
291}
292
293fn convert_path_tt(db: &dyn ExpandDatabase, tt: tt::TokenTreesView<'_>) -> Option<ModPath> {
294    let mut leaves = tt.iter().filter_map(|tt| match tt {
295        tt::TtElement::Leaf(leaf) => Some(leaf),
296        tt::TtElement::Subtree(..) => None,
297    });
298    let mut segments = smallvec::smallvec![];
299    let kind = match leaves.next()? {
300        tt::Leaf::Punct(tt::Punct { char: ':', .. }) => match leaves.next()? {
301            tt::Leaf::Punct(tt::Punct { char: ':', .. }) => PathKind::Abs,
302            _ => return None,
303        },
304        tt::Leaf::Ident(tt::Ident { sym: text, span, .. }) if *text == sym::dollar_crate => {
305            resolve_crate_root(db, span.ctx).map(PathKind::DollarCrate).unwrap_or(PathKind::Crate)
306        }
307        tt::Leaf::Ident(tt::Ident { sym: text, .. }) if *text == sym::self_ => PathKind::SELF,
308        tt::Leaf::Ident(tt::Ident { sym: text, .. }) if *text == sym::super_ => {
309            let mut deg = 1;
310            while let Some(tt::Leaf::Ident(tt::Ident { sym: text, span, is_raw: _ })) =
311                leaves.next()
312            {
313                if *text != sym::super_ {
314                    segments.push(Name::new_symbol(text.clone(), span.ctx));
315                    break;
316                }
317                deg += 1;
318            }
319            PathKind::Super(deg)
320        }
321        tt::Leaf::Ident(tt::Ident { sym: text, .. }) if *text == sym::crate_ => PathKind::Crate,
322        tt::Leaf::Ident(ident) => {
323            segments.push(Name::new_symbol(ident.sym.clone(), ident.span.ctx));
324            PathKind::Plain
325        }
326        _ => return None,
327    };
328    segments.extend(leaves.filter_map(|leaf| match leaf {
329        ::tt::Leaf::Ident(ident) => Some(Name::new_symbol(ident.sym.clone(), ident.span.ctx)),
330        _ => None,
331    }));
332    Some(ModPath { kind, segments })
333}
334
335pub fn resolve_crate_root(db: &dyn ExpandDatabase, mut ctxt: SyntaxContext) -> Option<Crate> {
336    // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
337    // we don't want to pretend that the `macro_rules!` definition is in the `macro`
338    // as described in `SyntaxContextId::apply_mark`, so we ignore prepended opaque marks.
339    // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
340    // definitions actually produced by `macro` and `macro` definitions produced by
341    // `macro_rules!`, but at least such configurations are not stable yet.
342    ctxt = ctxt.normalize_to_macro_rules(db);
343    let mut iter = ctxt.marks_rev(db).peekable();
344    let mut result_mark = None;
345    // Find the last opaque mark from the end if it exists.
346    while let Some(&(mark, Transparency::Opaque)) = iter.peek() {
347        result_mark = Some(mark);
348        iter.next();
349    }
350    // Then find the last semi-transparent mark from the end if it exists.
351    while let Some((mark, Transparency::SemiTransparent)) = iter.next() {
352        result_mark = Some(mark);
353    }
354
355    result_mark.map(|call| db.lookup_intern_macro_call(call.into()).def.krate)
356}
357
358pub use crate::name as __name;
359
360#[macro_export]
361macro_rules! __known_path {
362    (core::iter::IntoIterator) => {};
363    (core::iter::Iterator) => {};
364    (core::result::Result) => {};
365    (core::option::Option) => {};
366    (core::ops::Range) => {};
367    (core::ops::RangeFrom) => {};
368    (core::ops::RangeFull) => {};
369    (core::ops::RangeTo) => {};
370    (core::ops::RangeToInclusive) => {};
371    (core::ops::RangeInclusive) => {};
372    (core::future::Future) => {};
373    (core::future::IntoFuture) => {};
374    (core::fmt::Debug) => {};
375    (std::fmt::format) => {};
376    (core::ops::Try) => {};
377    (core::convert::From) => {};
378    (core::convert::TryFrom) => {};
379    (core::str::FromStr) => {};
380    ($path:path) => {
381        compile_error!("Please register your known path in the path module")
382    };
383}
384
385#[macro_export]
386macro_rules! __path {
387    ($start:ident $(:: $seg:ident)*) => ({
388        $crate::__known_path!($start $(:: $seg)*);
389        $crate::mod_path::ModPath::from_segments($crate::mod_path::PathKind::Abs, vec![
390            $crate::name::Name::new_symbol_root($crate::intern::sym::$start.clone()), $($crate::name::Name::new_symbol_root($crate::intern::sym::$seg.clone()),)*
391        ])
392    });
393}
394
395pub use crate::__path as path;
396
397#[macro_export]
398macro_rules! __tool_path {
399    ($start:ident $(:: $seg:ident)*) => ({
400        $crate::mod_path::ModPath::from_segments($crate::mod_path::PathKind::Plain, vec![
401            $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()),)*
402        ])
403    });
404}
405
406pub use crate::__tool_path as tool_path;