Skip to main content

hir_expand/
name.rs

1//! See [`Name`].
2
3use std::fmt;
4
5use base_db::SourceDatabase;
6use intern::{Symbol, sym};
7use span::{Edition, SyntaxContext};
8use syntax::utils::is_raw_identifier;
9use syntax::{ast, format_smolstr};
10
11/// `Name` is a wrapper around string, which is used in hir for both references
12/// and declarations. In theory, names should also carry hygiene info, but we are
13/// not there yet!
14///
15/// Note that the rawness (`r#`) of names is not preserved. Names are always stored without a `r#` prefix.
16/// This is because we want to show (in completions etc.) names as raw depending on the needs
17/// of the current crate, for example if it is edition 2021 complete `gen` even if the defining
18/// crate is in edition 2024 and wrote `r#gen`, and the opposite holds as well.
19///
20/// `k#` of forced keywords is *not* stripped, because `Name` is supposed to be used for names and not keywords.
21#[derive(Clone, PartialEq, Eq, Hash)]
22pub struct Name {
23    symbol: Symbol,
24    // If you are making this carry actual hygiene, beware that the special handling for variables and labels
25    // in bodies can go.
26    ctx: (),
27}
28
29impl fmt::Debug for Name {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        f.debug_struct("Name")
32            .field("symbol", &self.symbol.as_str())
33            .field("ctx", &self.ctx)
34            .finish()
35    }
36}
37
38impl Ord for Name {
39    #[inline]
40    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
41        self.symbol.as_str().cmp(other.symbol.as_str())
42    }
43}
44
45impl PartialOrd for Name {
46    #[inline]
47    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
48        Some(self.cmp(other))
49    }
50}
51
52// No need to strip `r#`, all comparisons are done against well-known symbols.
53impl PartialEq<Symbol> for Name {
54    #[inline]
55    fn eq(&self, sym: &Symbol) -> bool {
56        self.symbol == *sym
57    }
58}
59
60impl PartialEq<&Symbol> for Name {
61    #[inline]
62    fn eq(&self, &sym: &&Symbol) -> bool {
63        self.symbol == *sym
64    }
65}
66
67impl PartialEq<Name> for Symbol {
68    #[inline]
69    fn eq(&self, name: &Name) -> bool {
70        *self == name.symbol
71    }
72}
73
74impl PartialEq<Name> for &Symbol {
75    #[inline]
76    fn eq(&self, name: &Name) -> bool {
77        **self == name.symbol
78    }
79}
80
81impl Name {
82    #[inline]
83    fn new_text(text: &str) -> Name {
84        Name { symbol: Symbol::intern(text), ctx: () }
85    }
86
87    #[inline]
88    pub fn new(text: &str, mut ctx: SyntaxContext) -> Name {
89        // For comparisons etc. we remove the edition, because sometimes we search for some `Name`
90        // and we don't know which edition it came from.
91        // Can't do that for all `SyntaxContextId`s because it breaks Salsa.
92        ctx.remove_root_edition();
93        _ = ctx;
94        let text = text.strip_prefix("r#").unwrap_or(text);
95        Self::new_text(text)
96    }
97
98    #[inline]
99    pub fn new_root(text: &str) -> Name {
100        // The edition doesn't matter for hygiene.
101        Self::new(text, SyntaxContext::root(Edition::Edition2015))
102    }
103
104    #[inline]
105    pub fn new_tuple_field(idx: usize) -> Name {
106        Name::new_symbol_root(sym::Integer::get(idx))
107    }
108
109    #[inline]
110    pub fn new_lifetime(lt: &str) -> Name {
111        match lt.strip_prefix("'r#") {
112            Some(lt) => Self::new_text(&format_smolstr!("'{lt}")),
113            None => Self::new_text(lt),
114        }
115    }
116
117    #[inline]
118    pub fn new_symbol(symbol: Symbol, ctx: SyntaxContext) -> Self {
119        debug_assert!(!symbol.as_str().starts_with("r#"));
120        _ = ctx;
121        Self { symbol, ctx: () }
122    }
123
124    // FIXME: This needs to go once we have hygiene
125    #[inline]
126    pub fn new_symbol_root(sym: Symbol) -> Self {
127        Self::new_symbol(sym, SyntaxContext::root(Edition::Edition2015))
128    }
129
130    /// A fake name for things missing in the source code.
131    ///
132    /// For example, `impl Foo for {}` should be treated as a trait impl for a
133    /// type with a missing name. Similarly, `struct S { : u32 }` should have a
134    /// single field with a missing name.
135    ///
136    /// Ideally, we want a `gensym` semantics for missing names -- each missing
137    /// name is equal only to itself. It's not clear how to implement this in
138    /// salsa though, so we punt on that bit for a moment.
139    #[inline]
140    pub const fn missing() -> Name {
141        Name { symbol: sym::MISSING_NAME, ctx: () }
142    }
143
144    /// Returns true if this is a fake name for things missing in the source code. See
145    /// [`missing()`][Self::missing] for details.
146    ///
147    /// Use this method instead of comparing with `Self::missing()` as missing names
148    /// (ideally should) have a `gensym` semantics.
149    #[inline]
150    pub fn is_missing(&self) -> bool {
151        self.symbol == sym::MISSING_NAME
152    }
153
154    /// Generates a new name that attempts to be unique. Should only be used when body lowering and
155    /// creating desugared locals and labels. The caller is responsible for picking an index
156    /// that is stable across re-executions
157    #[inline]
158    pub fn generate_new_name(idx: usize) -> Name {
159        Name::new_symbol_root(sym::RaGeneratedName::get(idx))
160    }
161
162    /// Returns the tuple index this name represents if it is a tuple field.
163    #[inline]
164    pub fn as_tuple_index(&self) -> Option<usize> {
165        sym::Integer::as_uint(&self.symbol)
166    }
167
168    /// Whether this name needs to be escaped in the given edition via `r#`.
169    #[inline]
170    pub fn needs_escape(&self, edition: Edition) -> bool {
171        is_raw_identifier(self.symbol.as_str(), edition)
172    }
173
174    /// Returns the text this name represents if it isn't a tuple field.
175    ///
176    /// Do not use this for user-facing text, use `display` instead to handle editions properly.
177    // FIXME: This should take a database argument to hide the interning
178    #[inline]
179    pub fn as_str(&self) -> &str {
180        self.symbol.as_str()
181    }
182
183    #[inline]
184    pub fn display<'a>(
185        &'a self,
186        db: &dyn SourceDatabase,
187        edition: Edition,
188    ) -> impl fmt::Display + 'a {
189        _ = db;
190        self.display_no_db(edition)
191    }
192
193    // FIXME: Remove this in favor of `display`, see fixme on `as_str`
194    #[doc(hidden)]
195    #[inline]
196    pub fn display_no_db(&self, edition: Edition) -> impl fmt::Display + '_ {
197        Display { name: self, edition }
198    }
199
200    #[inline]
201    pub fn symbol(&self) -> &Symbol {
202        &self.symbol
203    }
204
205    #[inline]
206    pub fn is_generated(&self) -> bool {
207        is_generated(self.as_str())
208    }
209}
210
211#[inline]
212pub fn is_generated(name: &str) -> bool {
213    name.starts_with("<ra@gennew>")
214}
215
216struct Display<'a> {
217    name: &'a Name,
218    edition: Edition,
219}
220
221impl fmt::Display for Display<'_> {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        let mut symbol = self.name.symbol.as_str();
224
225        if symbol == "'static" {
226            // FIXME: '`static` can also be a label, and there it does need escaping.
227            // But knowing where it is will require adding a parameter to `display()`,
228            // and that is an infectious change.
229            return f.write_str(symbol);
230        }
231
232        if let Some(s) = symbol.strip_prefix('\'') {
233            f.write_str("'")?;
234            symbol = s;
235        }
236        if is_raw_identifier(symbol, self.edition) {
237            f.write_str("r#")?;
238        }
239        f.write_str(symbol)
240    }
241}
242
243pub trait AsName {
244    fn as_name(&self) -> Name;
245}
246
247impl AsName for ast::NameRef {
248    fn as_name(&self) -> Name {
249        match self.as_tuple_field() {
250            Some(idx) => Name::new_tuple_field(idx),
251            None => Name::new_root(self.text()),
252        }
253    }
254}
255
256impl AsName for ast::Name {
257    fn as_name(&self) -> Name {
258        Name::new_root(self.text())
259    }
260}
261
262impl AsName for ast::NameOrNameRef {
263    fn as_name(&self) -> Name {
264        match self {
265            ast::NameOrNameRef::Name(it) => it.as_name(),
266            ast::NameOrNameRef::NameRef(it) => it.as_name(),
267        }
268    }
269}
270
271impl AsName for tt::Ident {
272    fn as_name(&self) -> Name {
273        Name::new_root(self.sym.as_str())
274    }
275}
276
277impl AsName for ast::FieldKind {
278    fn as_name(&self) -> Name {
279        match self {
280            ast::FieldKind::Name(nr) => nr.as_name(),
281            ast::FieldKind::Index(idx) => {
282                let idx = idx.text().parse::<usize>().unwrap_or(0);
283                Name::new_tuple_field(idx)
284            }
285        }
286    }
287}
288
289impl AsName for base_db::BuiltDependency {
290    fn as_name(&self) -> Name {
291        Name::new_symbol_root((*self.name).clone())
292    }
293}