Merge pull request #19644 from ChayimFriedman2/const-syms

internal: Make predefined symbols `const` instead of `static`
This commit is contained in:
Lukas Wirth 2025-04-21 12:34:59 +00:00 committed by GitHub
commit 34e7d60e30
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
72 changed files with 432 additions and 473 deletions

View file

@ -31,7 +31,7 @@ pub struct CfgOptions {
impl Default for CfgOptions { impl Default for CfgOptions {
fn default() -> Self { fn default() -> Self {
Self { enabled: FxHashSet::from_iter([CfgAtom::Flag(sym::true_.clone())]) } Self { enabled: FxHashSet::from_iter([CfgAtom::Flag(sym::true_)]) }
} }
} }

View file

@ -117,17 +117,20 @@ impl Attrs {
} }
impl Attrs { impl Attrs {
pub fn by_key<'attrs>(&'attrs self, key: &'attrs Symbol) -> AttrQuery<'attrs> { #[inline]
pub fn by_key(&self, key: Symbol) -> AttrQuery<'_> {
AttrQuery { attrs: self, key } AttrQuery { attrs: self, key }
} }
#[inline]
pub fn rust_analyzer_tool(&self) -> impl Iterator<Item = &Attr> { pub fn rust_analyzer_tool(&self) -> impl Iterator<Item = &Attr> {
self.iter() self.iter()
.filter(|&attr| attr.path.segments().first().is_some_and(|s| *s == sym::rust_analyzer)) .filter(|&attr| attr.path.segments().first().is_some_and(|s| *s == sym::rust_analyzer))
} }
#[inline]
pub fn cfg(&self) -> Option<CfgExpr> { pub fn cfg(&self) -> Option<CfgExpr> {
let mut cfgs = self.by_key(&sym::cfg).tt_values().map(CfgExpr::parse); let mut cfgs = self.by_key(sym::cfg).tt_values().map(CfgExpr::parse);
let first = cfgs.next()?; let first = cfgs.next()?;
match cfgs.next() { match cfgs.next() {
Some(second) => { Some(second) => {
@ -138,10 +141,12 @@ impl Attrs {
} }
} }
#[inline]
pub fn cfgs(&self) -> impl Iterator<Item = CfgExpr> + '_ { pub fn cfgs(&self) -> impl Iterator<Item = CfgExpr> + '_ {
self.by_key(&sym::cfg).tt_values().map(CfgExpr::parse) self.by_key(sym::cfg).tt_values().map(CfgExpr::parse)
} }
#[inline]
pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool { pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool {
match self.cfg() { match self.cfg() {
None => true, None => true,
@ -149,81 +154,92 @@ impl Attrs {
} }
} }
#[inline]
pub fn lang(&self) -> Option<&Symbol> { pub fn lang(&self) -> Option<&Symbol> {
self.by_key(&sym::lang).string_value() self.by_key(sym::lang).string_value()
} }
#[inline]
pub fn lang_item(&self) -> Option<LangItem> { pub fn lang_item(&self) -> Option<LangItem> {
self.by_key(&sym::lang).string_value().and_then(LangItem::from_symbol) self.by_key(sym::lang).string_value().and_then(LangItem::from_symbol)
} }
#[inline]
pub fn has_doc_hidden(&self) -> bool { pub fn has_doc_hidden(&self) -> bool {
self.by_key(&sym::doc).tt_values().any(|tt| { self.by_key(sym::doc).tt_values().any(|tt| {
tt.top_subtree().delimiter.kind == DelimiterKind::Parenthesis && tt.top_subtree().delimiter.kind == DelimiterKind::Parenthesis &&
matches!(tt.token_trees().flat_tokens(), [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.sym == sym::hidden) matches!(tt.token_trees().flat_tokens(), [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.sym == sym::hidden)
}) })
} }
#[inline]
pub fn has_doc_notable_trait(&self) -> bool { pub fn has_doc_notable_trait(&self) -> bool {
self.by_key(&sym::doc).tt_values().any(|tt| { self.by_key(sym::doc).tt_values().any(|tt| {
tt.top_subtree().delimiter.kind == DelimiterKind::Parenthesis && tt.top_subtree().delimiter.kind == DelimiterKind::Parenthesis &&
matches!(tt.token_trees().flat_tokens(), [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.sym == sym::notable_trait) matches!(tt.token_trees().flat_tokens(), [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.sym == sym::notable_trait)
}) })
} }
#[inline]
pub fn doc_exprs(&self) -> impl Iterator<Item = DocExpr> + '_ { pub fn doc_exprs(&self) -> impl Iterator<Item = DocExpr> + '_ {
self.by_key(&sym::doc).tt_values().map(DocExpr::parse) self.by_key(sym::doc).tt_values().map(DocExpr::parse)
} }
#[inline]
pub fn doc_aliases(&self) -> impl Iterator<Item = Symbol> + '_ { pub fn doc_aliases(&self) -> impl Iterator<Item = Symbol> + '_ {
self.doc_exprs().flat_map(|doc_expr| doc_expr.aliases().to_vec()) self.doc_exprs().flat_map(|doc_expr| doc_expr.aliases().to_vec())
} }
#[inline]
pub fn export_name(&self) -> Option<&Symbol> { pub fn export_name(&self) -> Option<&Symbol> {
self.by_key(&sym::export_name).string_value() self.by_key(sym::export_name).string_value()
} }
#[inline]
pub fn is_proc_macro(&self) -> bool { pub fn is_proc_macro(&self) -> bool {
self.by_key(&sym::proc_macro).exists() self.by_key(sym::proc_macro).exists()
} }
#[inline]
pub fn is_proc_macro_attribute(&self) -> bool { pub fn is_proc_macro_attribute(&self) -> bool {
self.by_key(&sym::proc_macro_attribute).exists() self.by_key(sym::proc_macro_attribute).exists()
} }
#[inline]
pub fn is_proc_macro_derive(&self) -> bool { pub fn is_proc_macro_derive(&self) -> bool {
self.by_key(&sym::proc_macro_derive).exists() self.by_key(sym::proc_macro_derive).exists()
} }
#[inline]
pub fn is_test(&self) -> bool { pub fn is_test(&self) -> bool {
self.iter().any(|it| { self.iter().any(|it| {
it.path() it.path()
.segments() .segments()
.iter() .iter()
.rev() .rev()
.zip( .zip([sym::core, sym::prelude, sym::v1, sym::test].iter().rev())
[sym::core.clone(), sym::prelude.clone(), sym::v1.clone(), sym::test.clone()]
.iter()
.rev(),
)
.all(|it| it.0 == it.1) .all(|it| it.0 == it.1)
}) })
} }
#[inline]
pub fn is_ignore(&self) -> bool { pub fn is_ignore(&self) -> bool {
self.by_key(&sym::ignore).exists() self.by_key(sym::ignore).exists()
} }
#[inline]
pub fn is_bench(&self) -> bool { pub fn is_bench(&self) -> bool {
self.by_key(&sym::bench).exists() self.by_key(sym::bench).exists()
} }
#[inline]
pub fn is_unstable(&self) -> bool { pub fn is_unstable(&self) -> bool {
self.by_key(&sym::unstable).exists() self.by_key(sym::unstable).exists()
} }
#[inline]
pub fn rustc_legacy_const_generics(&self) -> Option<Box<Box<[u32]>>> { pub fn rustc_legacy_const_generics(&self) -> Option<Box<Box<[u32]>>> {
self.by_key(&sym::rustc_legacy_const_generics) self.by_key(sym::rustc_legacy_const_generics)
.tt_values() .tt_values()
.next() .next()
.map(parse_rustc_legacy_const_generics) .map(parse_rustc_legacy_const_generics)
@ -231,8 +247,9 @@ impl Attrs {
.map(Box::new) .map(Box::new)
} }
#[inline]
pub fn repr(&self) -> Option<ReprOptions> { pub fn repr(&self) -> Option<ReprOptions> {
self.by_key(&sym::repr).tt_values().filter_map(parse_repr_tt).fold(None, |acc, repr| { self.by_key(sym::repr).tt_values().filter_map(parse_repr_tt).fold(None, |acc, repr| {
acc.map_or(Some(repr), |mut acc| { acc.map_or(Some(repr), |mut acc| {
merge_repr(&mut acc, repr); merge_repr(&mut acc, repr);
Some(acc) Some(acc)
@ -681,36 +698,42 @@ impl AttrSourceMap {
} }
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone)]
pub struct AttrQuery<'attr> { pub struct AttrQuery<'attr> {
attrs: &'attr Attrs, attrs: &'attr Attrs,
key: &'attr Symbol, key: Symbol,
} }
impl<'attr> AttrQuery<'attr> { impl<'attr> AttrQuery<'attr> {
#[inline]
pub fn tt_values(self) -> impl Iterator<Item = &'attr crate::tt::TopSubtree> { pub fn tt_values(self) -> impl Iterator<Item = &'attr crate::tt::TopSubtree> {
self.attrs().filter_map(|attr| attr.token_tree_value()) self.attrs().filter_map(|attr| attr.token_tree_value())
} }
#[inline]
pub fn string_value(self) -> Option<&'attr Symbol> { pub fn string_value(self) -> Option<&'attr Symbol> {
self.attrs().find_map(|attr| attr.string_value()) self.attrs().find_map(|attr| attr.string_value())
} }
#[inline]
pub fn string_value_with_span(self) -> Option<(&'attr Symbol, span::Span)> { pub fn string_value_with_span(self) -> Option<(&'attr Symbol, span::Span)> {
self.attrs().find_map(|attr| attr.string_value_with_span()) self.attrs().find_map(|attr| attr.string_value_with_span())
} }
#[inline]
pub fn string_value_unescape(self) -> Option<Cow<'attr, str>> { pub fn string_value_unescape(self) -> Option<Cow<'attr, str>> {
self.attrs().find_map(|attr| attr.string_value_unescape()) self.attrs().find_map(|attr| attr.string_value_unescape())
} }
#[inline]
pub fn exists(self) -> bool { pub fn exists(self) -> bool {
self.attrs().next().is_some() self.attrs().next().is_some()
} }
#[inline]
pub fn attrs(self) -> impl Iterator<Item = &'attr Attr> + Clone { pub fn attrs(self) -> impl Iterator<Item = &'attr Attr> + Clone {
let key = self.key; let key = self.key;
self.attrs.iter().filter(move |attr| attr.path.as_ident().is_some_and(|s| *s == *key)) self.attrs.iter().filter(move |attr| attr.path.as_ident().is_some_and(|s| *s == key))
} }
/// Find string value for a specific key inside token tree /// Find string value for a specific key inside token tree
@ -719,10 +742,11 @@ impl<'attr> AttrQuery<'attr> {
/// #[doc(html_root_url = "url")] /// #[doc(html_root_url = "url")]
/// ^^^^^^^^^^^^^ key /// ^^^^^^^^^^^^^ key
/// ``` /// ```
pub fn find_string_value_in_tt(self, key: &'attr Symbol) -> Option<&'attr str> { #[inline]
pub fn find_string_value_in_tt(self, key: Symbol) -> Option<&'attr str> {
self.tt_values().find_map(|tt| { self.tt_values().find_map(|tt| {
let name = tt.iter() let name = tt.iter()
.skip_while(|tt| !matches!(tt, TtElement::Leaf(tt::Leaf::Ident(tt::Ident { sym, ..} )) if *sym == *key)) .skip_while(|tt| !matches!(tt, TtElement::Leaf(tt::Leaf::Ident(tt::Ident { sym, ..} )) if *sym == key))
.nth(2); .nth(2);
match name { match name {

View file

@ -51,28 +51,28 @@ impl BuiltinType {
#[rustfmt::skip] #[rustfmt::skip]
pub fn all_builtin_types() -> [(Name, BuiltinType); 19] { pub fn all_builtin_types() -> [(Name, BuiltinType); 19] {
[ [
(Name::new_symbol_root(sym::char.clone()), BuiltinType::Char), (Name::new_symbol_root(sym::char), BuiltinType::Char),
(Name::new_symbol_root(sym::bool.clone()), BuiltinType::Bool), (Name::new_symbol_root(sym::bool), BuiltinType::Bool),
(Name::new_symbol_root(sym::str.clone()), BuiltinType::Str), (Name::new_symbol_root(sym::str), BuiltinType::Str),
(Name::new_symbol_root(sym::isize.clone()), BuiltinType::Int(BuiltinInt::Isize)), (Name::new_symbol_root(sym::isize), BuiltinType::Int(BuiltinInt::Isize)),
(Name::new_symbol_root(sym::i8.clone()), BuiltinType::Int(BuiltinInt::I8)), (Name::new_symbol_root(sym::i8), BuiltinType::Int(BuiltinInt::I8)),
(Name::new_symbol_root(sym::i16.clone()), BuiltinType::Int(BuiltinInt::I16)), (Name::new_symbol_root(sym::i16), BuiltinType::Int(BuiltinInt::I16)),
(Name::new_symbol_root(sym::i32.clone()), BuiltinType::Int(BuiltinInt::I32)), (Name::new_symbol_root(sym::i32), BuiltinType::Int(BuiltinInt::I32)),
(Name::new_symbol_root(sym::i64.clone()), BuiltinType::Int(BuiltinInt::I64)), (Name::new_symbol_root(sym::i64), BuiltinType::Int(BuiltinInt::I64)),
(Name::new_symbol_root(sym::i128.clone()), BuiltinType::Int(BuiltinInt::I128)), (Name::new_symbol_root(sym::i128), BuiltinType::Int(BuiltinInt::I128)),
(Name::new_symbol_root(sym::usize.clone()), BuiltinType::Uint(BuiltinUint::Usize)), (Name::new_symbol_root(sym::usize), BuiltinType::Uint(BuiltinUint::Usize)),
(Name::new_symbol_root(sym::u8.clone()), BuiltinType::Uint(BuiltinUint::U8)), (Name::new_symbol_root(sym::u8), BuiltinType::Uint(BuiltinUint::U8)),
(Name::new_symbol_root(sym::u16.clone()), BuiltinType::Uint(BuiltinUint::U16)), (Name::new_symbol_root(sym::u16), BuiltinType::Uint(BuiltinUint::U16)),
(Name::new_symbol_root(sym::u32.clone()), BuiltinType::Uint(BuiltinUint::U32)), (Name::new_symbol_root(sym::u32), BuiltinType::Uint(BuiltinUint::U32)),
(Name::new_symbol_root(sym::u64.clone()), BuiltinType::Uint(BuiltinUint::U64)), (Name::new_symbol_root(sym::u64), BuiltinType::Uint(BuiltinUint::U64)),
(Name::new_symbol_root(sym::u128.clone()), BuiltinType::Uint(BuiltinUint::U128)), (Name::new_symbol_root(sym::u128), BuiltinType::Uint(BuiltinUint::U128)),
(Name::new_symbol_root(sym::f16.clone()), BuiltinType::Float(BuiltinFloat::F16)), (Name::new_symbol_root(sym::f16), BuiltinType::Float(BuiltinFloat::F16)),
(Name::new_symbol_root(sym::f32.clone()), BuiltinType::Float(BuiltinFloat::F32)), (Name::new_symbol_root(sym::f32), BuiltinType::Float(BuiltinFloat::F32)),
(Name::new_symbol_root(sym::f64.clone()), BuiltinType::Float(BuiltinFloat::F64)), (Name::new_symbol_root(sym::f64), BuiltinType::Float(BuiltinFloat::F64)),
(Name::new_symbol_root(sym::f128.clone()), BuiltinType::Float(BuiltinFloat::F128)), (Name::new_symbol_root(sym::f128), BuiltinType::Float(BuiltinFloat::F128)),
] ]
} }
@ -86,30 +86,30 @@ impl BuiltinType {
impl AsName for BuiltinType { impl AsName for BuiltinType {
fn as_name(&self) -> Name { fn as_name(&self) -> Name {
match self { match self {
BuiltinType::Char => Name::new_symbol_root(sym::char.clone()), BuiltinType::Char => Name::new_symbol_root(sym::char),
BuiltinType::Bool => Name::new_symbol_root(sym::bool.clone()), BuiltinType::Bool => Name::new_symbol_root(sym::bool),
BuiltinType::Str => Name::new_symbol_root(sym::str.clone()), BuiltinType::Str => Name::new_symbol_root(sym::str),
BuiltinType::Int(it) => match it { BuiltinType::Int(it) => match it {
BuiltinInt::Isize => Name::new_symbol_root(sym::isize.clone()), BuiltinInt::Isize => Name::new_symbol_root(sym::isize),
BuiltinInt::I8 => Name::new_symbol_root(sym::i8.clone()), BuiltinInt::I8 => Name::new_symbol_root(sym::i8),
BuiltinInt::I16 => Name::new_symbol_root(sym::i16.clone()), BuiltinInt::I16 => Name::new_symbol_root(sym::i16),
BuiltinInt::I32 => Name::new_symbol_root(sym::i32.clone()), BuiltinInt::I32 => Name::new_symbol_root(sym::i32),
BuiltinInt::I64 => Name::new_symbol_root(sym::i64.clone()), BuiltinInt::I64 => Name::new_symbol_root(sym::i64),
BuiltinInt::I128 => Name::new_symbol_root(sym::i128.clone()), BuiltinInt::I128 => Name::new_symbol_root(sym::i128),
}, },
BuiltinType::Uint(it) => match it { BuiltinType::Uint(it) => match it {
BuiltinUint::Usize => Name::new_symbol_root(sym::usize.clone()), BuiltinUint::Usize => Name::new_symbol_root(sym::usize),
BuiltinUint::U8 => Name::new_symbol_root(sym::u8.clone()), BuiltinUint::U8 => Name::new_symbol_root(sym::u8),
BuiltinUint::U16 => Name::new_symbol_root(sym::u16.clone()), BuiltinUint::U16 => Name::new_symbol_root(sym::u16),
BuiltinUint::U32 => Name::new_symbol_root(sym::u32.clone()), BuiltinUint::U32 => Name::new_symbol_root(sym::u32),
BuiltinUint::U64 => Name::new_symbol_root(sym::u64.clone()), BuiltinUint::U64 => Name::new_symbol_root(sym::u64),
BuiltinUint::U128 => Name::new_symbol_root(sym::u128.clone()), BuiltinUint::U128 => Name::new_symbol_root(sym::u128),
}, },
BuiltinType::Float(it) => match it { BuiltinType::Float(it) => match it {
BuiltinFloat::F16 => Name::new_symbol_root(sym::f16.clone()), BuiltinFloat::F16 => Name::new_symbol_root(sym::f16),
BuiltinFloat::F32 => Name::new_symbol_root(sym::f32.clone()), BuiltinFloat::F32 => Name::new_symbol_root(sym::f32),
BuiltinFloat::F64 => Name::new_symbol_root(sym::f64.clone()), BuiltinFloat::F64 => Name::new_symbol_root(sym::f64),
BuiltinFloat::F128 => Name::new_symbol_root(sym::f128.clone()), BuiltinFloat::F128 => Name::new_symbol_root(sym::f128),
}, },
} }
} }

View file

@ -387,8 +387,8 @@ fn crate_supports_no_std(db: &dyn DefDatabase, crate_id: Crate) -> bool {
let attrs = item_tree.raw_attrs(AttrOwner::TopLevel); let attrs = item_tree.raw_attrs(AttrOwner::TopLevel);
for attr in &**attrs { for attr in &**attrs {
match attr.path().as_ident() { match attr.path().as_ident() {
Some(ident) if *ident == sym::no_std.clone() => return true, Some(ident) if *ident == sym::no_std => return true,
Some(ident) if *ident == sym::cfg_attr.clone() => {} Some(ident) if *ident == sym::cfg_attr => {}
_ => continue, _ => continue,
} }

View file

@ -105,7 +105,7 @@ pub(super) fn lower_body(
let is_mutable = let is_mutable =
self_param_syn.mut_token().is_some() && self_param_syn.amp_token().is_none(); self_param_syn.mut_token().is_some() && self_param_syn.amp_token().is_none();
let binding_id: la_arena::Idx<Binding> = collector.alloc_binding( let binding_id: la_arena::Idx<Binding> = collector.alloc_binding(
Name::new_symbol_root(sym::self_.clone()), Name::new_symbol_root(sym::self_),
BindingAnnotation::new(is_mutable, false), BindingAnnotation::new(is_mutable, false),
); );
self_param = Some(binding_id); self_param = Some(binding_id);
@ -137,7 +137,7 @@ pub(super) fn lower_body(
let is_mutable = let is_mutable =
self_param_syn.mut_token().is_some() && self_param_syn.amp_token().is_none(); self_param_syn.mut_token().is_some() && self_param_syn.amp_token().is_none();
let binding_id: la_arena::Idx<Binding> = collector.alloc_binding( let binding_id: la_arena::Idx<Binding> = collector.alloc_binding(
Name::new_symbol_root(sym::self_.clone()), Name::new_symbol_root(sym::self_),
BindingAnnotation::new(is_mutable, false), BindingAnnotation::new(is_mutable, false),
); );
let hygiene = self_param_syn let hygiene = self_param_syn
@ -322,7 +322,7 @@ pub(crate) fn lower_function(
Some(ty) => collector.lower_type_ref(ty, &mut impl_trait_lower_fn), Some(ty) => collector.lower_type_ref(ty, &mut impl_trait_lower_fn),
None => { None => {
let self_type = collector.alloc_type_ref_desugared(TypeRef::Path( let self_type = collector.alloc_type_ref_desugared(TypeRef::Path(
Name::new_symbol_root(sym::Self_.clone()).into(), Name::new_symbol_root(sym::Self_).into(),
)); ));
let lifetime = param let lifetime = param
.lifetime() .lifetime()
@ -375,7 +375,7 @@ pub(crate) fn lower_function(
let mut generic_args: Vec<_> = let mut generic_args: Vec<_> =
std::iter::repeat_n(None, path.segments().len() - 1).collect(); std::iter::repeat_n(None, path.segments().len() - 1).collect();
let binding = AssociatedTypeBinding { let binding = AssociatedTypeBinding {
name: Name::new_symbol_root(sym::Output.clone()), name: Name::new_symbol_root(sym::Output),
args: None, args: None,
type_ref: Some( type_ref: Some(
return_type return_type
@ -631,7 +631,7 @@ impl ExprCollector<'_> {
match abi.abi_string() { match abi.abi_string() {
Some(tok) => Symbol::intern(tok.text_without_quotes()), Some(tok) => Symbol::intern(tok.text_without_quotes()),
// `extern` default to be `extern "C"`. // `extern` default to be `extern "C"`.
_ => sym::C.clone(), _ => sym::C,
} }
} }
@ -760,7 +760,7 @@ impl ExprCollector<'_> {
let bindings = if let Some(ret_type) = ret_type { let bindings = if let Some(ret_type) = ret_type {
let type_ref = self.lower_type_ref_opt(ret_type.ty(), impl_trait_lower_fn); let type_ref = self.lower_type_ref_opt(ret_type.ty(), impl_trait_lower_fn);
Box::new([AssociatedTypeBinding { Box::new([AssociatedTypeBinding {
name: Name::new_symbol_root(sym::Output.clone()), name: Name::new_symbol_root(sym::Output),
args: None, args: None,
type_ref: Some(type_ref), type_ref: Some(type_ref),
bounds: Box::default(), bounds: Box::default(),
@ -769,7 +769,7 @@ impl ExprCollector<'_> {
// -> () // -> ()
let type_ref = self.alloc_type_ref_desugared(TypeRef::unit()); let type_ref = self.alloc_type_ref_desugared(TypeRef::unit());
Box::new([AssociatedTypeBinding { Box::new([AssociatedTypeBinding {
name: Name::new_symbol_root(sym::Output.clone()), name: Name::new_symbol_root(sym::Output),
args: None, args: None,
type_ref: Some(type_ref), type_ref: Some(type_ref),
bounds: Box::default(), bounds: Box::default(),
@ -2804,12 +2804,12 @@ impl ExprCollector<'_> {
let new_v1_formatted = LangItem::FormatArguments.ty_rel_path( let new_v1_formatted = LangItem::FormatArguments.ty_rel_path(
self.db, self.db,
self.module.krate(), self.module.krate(),
Name::new_symbol_root(sym::new_v1_formatted.clone()), Name::new_symbol_root(sym::new_v1_formatted),
); );
let unsafe_arg_new = LangItem::FormatUnsafeArg.ty_rel_path( let unsafe_arg_new = LangItem::FormatUnsafeArg.ty_rel_path(
self.db, self.db,
self.module.krate(), self.module.krate(),
Name::new_symbol_root(sym::new.clone()), Name::new_symbol_root(sym::new),
); );
let new_v1_formatted = let new_v1_formatted =
self.alloc_expr_desugared(new_v1_formatted.map_or(Expr::Missing, Expr::Path)); self.alloc_expr_desugared(new_v1_formatted.map_or(Expr::Missing, Expr::Path));
@ -2924,20 +2924,15 @@ impl ExprCollector<'_> {
Some(BuiltinUint::U32), Some(BuiltinUint::U32),
))); )));
let position = RecordLitField { let position =
name: Name::new_symbol_root(sym::position.clone()), RecordLitField { name: Name::new_symbol_root(sym::position), expr: position };
expr: position, let flags = RecordLitField { name: Name::new_symbol_root(sym::flags), expr: flags };
};
let flags =
RecordLitField { name: Name::new_symbol_root(sym::flags.clone()), expr: flags };
let precision = RecordLitField { let precision = RecordLitField {
name: Name::new_symbol_root(sym::precision.clone()), name: Name::new_symbol_root(sym::precision),
expr: precision_expr, expr: precision_expr,
}; };
let width = RecordLitField { let width =
name: Name::new_symbol_root(sym::width.clone()), RecordLitField { name: Name::new_symbol_root(sym::width), expr: width_expr };
expr: width_expr,
};
self.alloc_expr_desugared(Expr::RecordLit { self.alloc_expr_desugared(Expr::RecordLit {
path: LangItem::FormatPlaceholder.path(self.db, self.module.krate()).map(Box::new), path: LangItem::FormatPlaceholder.path(self.db, self.module.krate()).map(Box::new),
fields: Box::new([position, flags, precision, width]), fields: Box::new([position, flags, precision, width]),
@ -2948,7 +2943,7 @@ impl ExprCollector<'_> {
let format_placeholder_new = LangItem::FormatPlaceholder.ty_rel_path( let format_placeholder_new = LangItem::FormatPlaceholder.ty_rel_path(
self.db, self.db,
self.module.krate(), self.module.krate(),
Name::new_symbol_root(sym::new.clone()), Name::new_symbol_root(sym::new),
); );
match format_placeholder_new { match format_placeholder_new {
Some(path) => self.alloc_expr_desugared(Expr::Path(path)), Some(path) => self.alloc_expr_desugared(Expr::Path(path)),
@ -2972,10 +2967,10 @@ impl ExprCollector<'_> {
self.db, self.db,
self.module.krate(), self.module.krate(),
match alignment { match alignment {
Some(FormatAlignment::Left) => Name::new_symbol_root(sym::Left.clone()), Some(FormatAlignment::Left) => Name::new_symbol_root(sym::Left),
Some(FormatAlignment::Right) => Name::new_symbol_root(sym::Right.clone()), Some(FormatAlignment::Right) => Name::new_symbol_root(sym::Right),
Some(FormatAlignment::Center) => Name::new_symbol_root(sym::Center.clone()), Some(FormatAlignment::Center) => Name::new_symbol_root(sym::Center),
None => Name::new_symbol_root(sym::Unknown.clone()), None => Name::new_symbol_root(sym::Unknown),
}, },
); );
match align { match align {
@ -3024,7 +3019,7 @@ impl ExprCollector<'_> {
let count_is = match LangItem::FormatCount.ty_rel_path( let count_is = match LangItem::FormatCount.ty_rel_path(
self.db, self.db,
self.module.krate(), self.module.krate(),
Name::new_symbol_root(sym::Is.clone()), Name::new_symbol_root(sym::Is),
) { ) {
Some(count_is) => self.alloc_expr_desugared(Expr::Path(count_is)), Some(count_is) => self.alloc_expr_desugared(Expr::Path(count_is)),
None => self.missing_expr(), None => self.missing_expr(),
@ -3042,7 +3037,7 @@ impl ExprCollector<'_> {
let count_param = match LangItem::FormatCount.ty_rel_path( let count_param = match LangItem::FormatCount.ty_rel_path(
self.db, self.db,
self.module.krate(), self.module.krate(),
Name::new_symbol_root(sym::Param.clone()), Name::new_symbol_root(sym::Param),
) { ) {
Some(count_param) => self.alloc_expr_desugared(Expr::Path(count_param)), Some(count_param) => self.alloc_expr_desugared(Expr::Path(count_param)),
None => self.missing_expr(), None => self.missing_expr(),
@ -3060,7 +3055,7 @@ impl ExprCollector<'_> {
None => match LangItem::FormatCount.ty_rel_path( None => match LangItem::FormatCount.ty_rel_path(
self.db, self.db,
self.module.krate(), self.module.krate(),
Name::new_symbol_root(sym::Implied.clone()), Name::new_symbol_root(sym::Implied),
) { ) {
Some(count_param) => self.alloc_expr_desugared(Expr::Path(count_param)), Some(count_param) => self.alloc_expr_desugared(Expr::Path(count_param)),
None => self.missing_expr(), None => self.missing_expr(),
@ -3083,16 +3078,16 @@ impl ExprCollector<'_> {
self.db, self.db,
self.module.krate(), self.module.krate(),
Name::new_symbol_root(match ty { Name::new_symbol_root(match ty {
Format(Display) => sym::new_display.clone(), Format(Display) => sym::new_display,
Format(Debug) => sym::new_debug.clone(), Format(Debug) => sym::new_debug,
Format(LowerExp) => sym::new_lower_exp.clone(), Format(LowerExp) => sym::new_lower_exp,
Format(UpperExp) => sym::new_upper_exp.clone(), Format(UpperExp) => sym::new_upper_exp,
Format(Octal) => sym::new_octal.clone(), Format(Octal) => sym::new_octal,
Format(Pointer) => sym::new_pointer.clone(), Format(Pointer) => sym::new_pointer,
Format(Binary) => sym::new_binary.clone(), Format(Binary) => sym::new_binary,
Format(LowerHex) => sym::new_lower_hex.clone(), Format(LowerHex) => sym::new_lower_hex,
Format(UpperHex) => sym::new_upper_hex.clone(), Format(UpperHex) => sym::new_upper_hex,
Usize => sym::from_usize.clone(), Usize => sym::from_usize,
}), }),
) { ) {
Some(new_fn) => self.alloc_expr_desugared(Expr::Path(new_fn)), Some(new_fn) => self.alloc_expr_desugared(Expr::Path(new_fn)),

View file

@ -43,7 +43,7 @@ impl<'db, 'c> GenericParamsCollector<'db, 'c> {
} }
pub(crate) fn fill_self_param(&mut self, bounds: Option<ast::TypeBoundList>) { pub(crate) fn fill_self_param(&mut self, bounds: Option<ast::TypeBoundList>) {
let self_ = Name::new_symbol_root(sym::Self_.clone()); let self_ = Name::new_symbol_root(sym::Self_);
let idx = self.type_or_consts.alloc( let idx = self.type_or_consts.alloc(
TypeParamData { TypeParamData {
name: Some(self_.clone()), name: Some(self_.clone()),

View file

@ -105,7 +105,7 @@ pub(super) fn lower_path(
push_segment(&segment, &mut segments, name); push_segment(&segment, &mut segments, name);
} }
ast::PathSegmentKind::SelfTypeKw => { ast::PathSegmentKind::SelfTypeKw => {
push_segment(&segment, &mut segments, Name::new_symbol_root(sym::Self_.clone())); push_segment(&segment, &mut segments, Name::new_symbol_root(sym::Self_));
} }
ast::PathSegmentKind::Type { type_ref, trait_ref } => { ast::PathSegmentKind::Type { type_ref, trait_ref } => {
debug_assert!(path.qualifier().is_none()); // this can only occur at the first segment debug_assert!(path.qualifier().is_none()); // this can only occur at the first segment

View file

@ -532,7 +532,7 @@ fn lower_abi(abi: ast::Abi) -> Symbol {
match abi.abi_string() { match abi.abi_string() {
Some(tok) => Symbol::intern(tok.text_without_quotes()), Some(tok) => Symbol::intern(tok.text_without_quotes()),
// `extern` default to be `extern "C"`. // `extern` default to be `extern "C"`.
_ => sym::C.clone(), _ => sym::C,
} }
} }

View file

@ -268,24 +268,24 @@ impl DefCollector<'_> {
let Some(attr_name) = attr.path.as_ident() else { continue }; let Some(attr_name) = attr.path.as_ident() else { continue };
match () { match () {
() if *attr_name == sym::recursion_limit.clone() => { () if *attr_name == sym::recursion_limit => {
if let Some(limit) = attr.string_value() { if let Some(limit) = attr.string_value() {
if let Ok(limit) = limit.as_str().parse() { if let Ok(limit) = limit.as_str().parse() {
crate_data.recursion_limit = Some(limit); crate_data.recursion_limit = Some(limit);
} }
} }
} }
() if *attr_name == sym::crate_type.clone() => { () if *attr_name == sym::crate_type => {
if attr.string_value() == Some(&sym::proc_dash_macro) { if attr.string_value() == Some(&sym::proc_dash_macro) {
self.is_proc_macro = true; self.is_proc_macro = true;
} }
} }
() if *attr_name == sym::no_core.clone() => crate_data.no_core = true, () if *attr_name == sym::no_core => crate_data.no_core = true,
() if *attr_name == sym::no_std.clone() => crate_data.no_std = true, () if *attr_name == sym::no_std => crate_data.no_std = true,
() if *attr_name == sym::rustc_coherence_is_core.clone() => { () if *attr_name == sym::rustc_coherence_is_core => {
crate_data.rustc_coherence_is_core = true; crate_data.rustc_coherence_is_core = true;
} }
() if *attr_name == sym::feature.clone() => { () if *attr_name == sym::feature => {
let features = let features =
attr.parse_path_comma_token_tree(self.db).into_iter().flatten().filter_map( attr.parse_path_comma_token_tree(self.db).into_iter().flatten().filter_map(
|(feat, _)| match feat.segments() { |(feat, _)| match feat.segments() {
@ -295,13 +295,13 @@ impl DefCollector<'_> {
); );
crate_data.unstable_features.extend(features); crate_data.unstable_features.extend(features);
} }
() if *attr_name == sym::register_attr.clone() => { () if *attr_name == sym::register_attr => {
if let Some(ident) = attr.single_ident_value() { if let Some(ident) = attr.single_ident_value() {
crate_data.registered_attrs.push(ident.sym.clone()); crate_data.registered_attrs.push(ident.sym.clone());
cov_mark::hit!(register_attr); cov_mark::hit!(register_attr);
} }
} }
() if *attr_name == sym::register_tool.clone() => { () if *attr_name == sym::register_tool => {
if let Some(ident) = attr.single_ident_value() { if let Some(ident) = attr.single_ident_value() {
crate_data.registered_tools.push(ident.sym.clone()); crate_data.registered_tools.push(ident.sym.clone());
cov_mark::hit!(register_tool); cov_mark::hit!(register_tool);
@ -507,20 +507,20 @@ impl DefCollector<'_> {
} }
let krate = if self.def_map.data.no_std { let krate = if self.def_map.data.no_std {
Name::new_symbol_root(sym::core.clone()) Name::new_symbol_root(sym::core)
} else if self.local_def_map().extern_prelude().any(|(name, _)| *name == sym::std.clone()) { } else if self.local_def_map().extern_prelude().any(|(name, _)| *name == sym::std) {
Name::new_symbol_root(sym::std.clone()) Name::new_symbol_root(sym::std)
} else { } else {
// If `std` does not exist for some reason, fall back to core. This mostly helps // If `std` does not exist for some reason, fall back to core. This mostly helps
// keep r-a's own tests minimal. // keep r-a's own tests minimal.
Name::new_symbol_root(sym::core.clone()) Name::new_symbol_root(sym::core)
}; };
let edition = match self.def_map.data.edition { let edition = match self.def_map.data.edition {
Edition::Edition2015 => Name::new_symbol_root(sym::rust_2015.clone()), Edition::Edition2015 => Name::new_symbol_root(sym::rust_2015),
Edition::Edition2018 => Name::new_symbol_root(sym::rust_2018.clone()), Edition::Edition2018 => Name::new_symbol_root(sym::rust_2018),
Edition::Edition2021 => Name::new_symbol_root(sym::rust_2021.clone()), Edition::Edition2021 => Name::new_symbol_root(sym::rust_2021),
Edition::Edition2024 => Name::new_symbol_root(sym::rust_2024.clone()), Edition::Edition2024 => Name::new_symbol_root(sym::rust_2024),
}; };
let path_kind = match self.def_map.data.edition { let path_kind = match self.def_map.data.edition {
@ -529,7 +529,7 @@ impl DefCollector<'_> {
}; };
let path = ModPath::from_segments( let path = ModPath::from_segments(
path_kind, path_kind,
[krate, Name::new_symbol_root(sym::prelude.clone()), edition], [krate, Name::new_symbol_root(sym::prelude), edition],
); );
let (per_ns, _) = self.def_map.resolve_path( let (per_ns, _) = self.def_map.resolve_path(
@ -1373,8 +1373,7 @@ impl DefCollector<'_> {
MacroDefKind::BuiltInAttr(_, expander) MacroDefKind::BuiltInAttr(_, expander)
if expander.is_test() || expander.is_bench() || expander.is_test_case() if expander.is_test() || expander.is_bench() || expander.is_test_case()
) { ) {
let test_is_active = let test_is_active = self.cfg_options.check_atom(&CfgAtom::Flag(sym::test));
self.cfg_options.check_atom(&CfgAtom::Flag(sym::test.clone()));
if test_is_active { if test_is_active {
return recollect_without(self); return recollect_without(self);
} }
@ -1712,7 +1711,7 @@ impl ModCollector<'_, '_> {
id: ItemTreeId::new(self.tree_id, item_tree_id), id: ItemTreeId::new(self.tree_id, item_tree_id),
} }
.intern(db); .intern(db);
let is_prelude = attrs.by_key(&sym::prelude_import).exists(); let is_prelude = attrs.by_key(sym::prelude_import).exists();
Import::from_use( Import::from_use(
self.item_tree, self.item_tree,
ItemTreeId::new(self.tree_id, item_tree_id), ItemTreeId::new(self.tree_id, item_tree_id),
@ -1770,7 +1769,7 @@ impl ModCollector<'_, '_> {
if !is_self { if !is_self {
self.process_macro_use_extern_crate( self.process_macro_use_extern_crate(
id, id,
attrs.by_key(&sym::macro_use).attrs(), attrs.by_key(sym::macro_use).attrs(),
resolved.krate, resolved.krate,
); );
} }
@ -2015,8 +2014,8 @@ impl ModCollector<'_, '_> {
} }
fn collect_module(&mut self, module_id: FileItemTreeId<Mod>, attrs: &Attrs) { fn collect_module(&mut self, module_id: FileItemTreeId<Mod>, attrs: &Attrs) {
let path_attr = attrs.by_key(&sym::path).string_value_unescape(); let path_attr = attrs.by_key(sym::path).string_value_unescape();
let is_macro_use = attrs.by_key(&sym::macro_use).exists(); let is_macro_use = attrs.by_key(sym::macro_use).exists();
let module = &self.item_tree[module_id]; let module = &self.item_tree[module_id];
match &module.kind { match &module.kind {
// inline module, just recurse // inline module, just recurse
@ -2093,7 +2092,7 @@ impl ModCollector<'_, '_> {
let is_macro_use = is_macro_use let is_macro_use = is_macro_use
|| item_tree || item_tree
.top_level_attrs(db, krate) .top_level_attrs(db, krate)
.by_key(&sym::macro_use) .by_key(sym::macro_use)
.exists(); .exists();
if is_macro_use { if is_macro_use {
self.import_all_legacy_macros(module_id); self.import_all_legacy_macros(module_id);
@ -2252,11 +2251,11 @@ impl ModCollector<'_, '_> {
let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into()); let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into());
let ast_id = InFile::new(self.file_id(), mac.ast_id.upcast()); let ast_id = InFile::new(self.file_id(), mac.ast_id.upcast());
let export_attr = attrs.by_key(&sym::macro_export); let export_attr = || attrs.by_key(sym::macro_export);
let is_export = export_attr.exists(); let is_export = export_attr().exists();
let local_inner = if is_export { let local_inner = if is_export {
export_attr.tt_values().flat_map(|it| it.iter()).any(|it| match it { export_attr().tt_values().flat_map(|it| it.iter()).any(|it| match it {
tt::TtElement::Leaf(tt::Leaf::Ident(ident)) => ident.sym == sym::local_inner_macros, tt::TtElement::Leaf(tt::Leaf::Ident(ident)) => ident.sym == sym::local_inner_macros,
_ => false, _ => false,
}) })
@ -2265,17 +2264,17 @@ impl ModCollector<'_, '_> {
}; };
// Case 1: builtin macros // Case 1: builtin macros
let expander = if attrs.by_key(&sym::rustc_builtin_macro).exists() { let expander = if attrs.by_key(sym::rustc_builtin_macro).exists() {
// `#[rustc_builtin_macro = "builtin_name"]` overrides the `macro_rules!` name. // `#[rustc_builtin_macro = "builtin_name"]` overrides the `macro_rules!` name.
let name; let name;
let name = match attrs.by_key(&sym::rustc_builtin_macro).string_value_with_span() { let name = match attrs.by_key(sym::rustc_builtin_macro).string_value_with_span() {
Some((it, span)) => { Some((it, span)) => {
name = Name::new_symbol(it.clone(), span.ctx); name = Name::new_symbol(it.clone(), span.ctx);
&name &name
} }
None => { None => {
let explicit_name = let explicit_name =
attrs.by_key(&sym::rustc_builtin_macro).tt_values().next().and_then(|tt| { attrs.by_key(sym::rustc_builtin_macro).tt_values().next().and_then(|tt| {
match tt.token_trees().flat_tokens().first() { match tt.token_trees().flat_tokens().first() {
Some(tt::TokenTree::Leaf(tt::Leaf::Ident(name))) => Some(name), Some(tt::TokenTree::Leaf(tt::Leaf::Ident(name))) => Some(name),
_ => None, _ => None,
@ -2305,7 +2304,7 @@ impl ModCollector<'_, '_> {
// Case 2: normal `macro_rules!` macro // Case 2: normal `macro_rules!` macro
MacroExpander::Declarative MacroExpander::Declarative
}; };
let allow_internal_unsafe = attrs.by_key(&sym::allow_internal_unsafe).exists(); let allow_internal_unsafe = attrs.by_key(sym::allow_internal_unsafe).exists();
let mut flags = MacroRulesLocFlags::empty(); let mut flags = MacroRulesLocFlags::empty();
flags.set(MacroRulesLocFlags::LOCAL_INNER, local_inner); flags.set(MacroRulesLocFlags::LOCAL_INNER, local_inner);
@ -2339,14 +2338,14 @@ impl ModCollector<'_, '_> {
// Case 1: builtin macros // Case 1: builtin macros
let mut helpers_opt = None; let mut helpers_opt = None;
let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into()); let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into());
let expander = if attrs.by_key(&sym::rustc_builtin_macro).exists() { let expander = if attrs.by_key(sym::rustc_builtin_macro).exists() {
if let Some(expander) = find_builtin_macro(&mac.name) { if let Some(expander) = find_builtin_macro(&mac.name) {
match expander { match expander {
Either::Left(it) => MacroExpander::BuiltIn(it), Either::Left(it) => MacroExpander::BuiltIn(it),
Either::Right(it) => MacroExpander::BuiltInEager(it), Either::Right(it) => MacroExpander::BuiltInEager(it),
} }
} else if let Some(expander) = find_builtin_derive(&mac.name) { } else if let Some(expander) = find_builtin_derive(&mac.name) {
if let Some(attr) = attrs.by_key(&sym::rustc_builtin_macro).tt_values().next() { if let Some(attr) = attrs.by_key(sym::rustc_builtin_macro).tt_values().next() {
// NOTE: The item *may* have both `#[rustc_builtin_macro]` and `#[proc_macro_derive]`, // NOTE: The item *may* have both `#[rustc_builtin_macro]` and `#[proc_macro_derive]`,
// in which case rustc ignores the helper attributes from the latter, but it // in which case rustc ignores the helper attributes from the latter, but it
// "doesn't make sense in practice" (see rust-lang/rust#87027). // "doesn't make sense in practice" (see rust-lang/rust#87027).
@ -2377,7 +2376,7 @@ impl ModCollector<'_, '_> {
// Case 2: normal `macro` // Case 2: normal `macro`
MacroExpander::Declarative MacroExpander::Declarative
}; };
let allow_internal_unsafe = attrs.by_key(&sym::allow_internal_unsafe).exists(); let allow_internal_unsafe = attrs.by_key(sym::allow_internal_unsafe).exists();
let macro_id = Macro2Loc { let macro_id = Macro2Loc {
container: module, container: module,

View file

@ -35,7 +35,7 @@ impl Attrs {
Some(ProcMacroDef { name: func_name.clone(), kind: ProcMacroKind::Bang }) Some(ProcMacroDef { name: func_name.clone(), kind: ProcMacroKind::Bang })
} else if self.is_proc_macro_attribute() { } else if self.is_proc_macro_attribute() {
Some(ProcMacroDef { name: func_name.clone(), kind: ProcMacroKind::Attr }) Some(ProcMacroDef { name: func_name.clone(), kind: ProcMacroKind::Attr })
} else if self.by_key(&sym::proc_macro_derive).exists() { } else if self.by_key(sym::proc_macro_derive).exists() {
let derive = self.parse_proc_macro_derive(); let derive = self.parse_proc_macro_derive();
Some(match derive { Some(match derive {
Some((name, helpers)) => { Some((name, helpers)) => {
@ -52,12 +52,12 @@ impl Attrs {
} }
pub fn parse_proc_macro_derive(&self) -> Option<(Name, Box<[Name]>)> { pub fn parse_proc_macro_derive(&self) -> Option<(Name, Box<[Name]>)> {
let derive = self.by_key(&sym::proc_macro_derive).tt_values().next()?; let derive = self.by_key(sym::proc_macro_derive).tt_values().next()?;
parse_macro_name_and_helper_attrs(derive) parse_macro_name_and_helper_attrs(derive)
} }
pub fn parse_rustc_builtin_macro(&self) -> Option<(Name, Box<[Name]>)> { pub fn parse_rustc_builtin_macro(&self) -> Option<(Name, Box<[Name]>)> {
let derive = self.by_key(&sym::rustc_builtin_macro).tt_values().next()?; let derive = self.by_key(sym::rustc_builtin_macro).tt_values().next()?;
parse_macro_name_and_helper_attrs(derive) parse_macro_name_and_helper_attrs(derive)
} }
} }

View file

@ -219,7 +219,7 @@ impl Resolver {
Scope::ExprScope(_) | Scope::MacroDefScope(_) => continue, Scope::ExprScope(_) | Scope::MacroDefScope(_) => continue,
Scope::GenericParams { params, def } => { Scope::GenericParams { params, def } => {
if let &GenericDefId::ImplId(impl_) = def { if let &GenericDefId::ImplId(impl_) = def {
if *first_name == sym::Self_.clone() { if *first_name == sym::Self_ {
return Some(( return Some((
TypeNs::SelfType(impl_), TypeNs::SelfType(impl_),
remaining_idx(), remaining_idx(),
@ -228,7 +228,7 @@ impl Resolver {
)); ));
} }
} else if let &GenericDefId::AdtId(adt) = def { } else if let &GenericDefId::AdtId(adt) = def {
if *first_name == sym::Self_.clone() { if *first_name == sym::Self_ {
return Some(( return Some((
TypeNs::AdtSelfType(adt), TypeNs::AdtSelfType(adt),
remaining_idx(), remaining_idx(),
@ -365,7 +365,7 @@ impl Resolver {
} }
}; };
let n_segments = path.segments().len(); let n_segments = path.segments().len();
let tmp = Name::new_symbol_root(sym::self_.clone()); let tmp = Name::new_symbol_root(sym::self_);
let first_name = if path.is_self() { &tmp } else { path.segments().first()? }; let first_name = if path.is_self() { &tmp } else { path.segments().first()? };
let skip_to_mod = path.kind != PathKind::Plain && !path.is_self(); let skip_to_mod = path.kind != PathKind::Plain && !path.is_self();
if skip_to_mod { if skip_to_mod {
@ -397,7 +397,7 @@ impl Resolver {
} }
Scope::GenericParams { params, def } => { Scope::GenericParams { params, def } => {
if let &GenericDefId::ImplId(impl_) = def { if let &GenericDefId::ImplId(impl_) = def {
if *first_name == sym::Self_.clone() { if *first_name == sym::Self_ {
return Some(( return Some((
ResolveValueResult::ValueNs(ValueNs::ImplSelf(impl_), None), ResolveValueResult::ValueNs(ValueNs::ImplSelf(impl_), None),
ResolvePathResultPrefixInfo::default(), ResolvePathResultPrefixInfo::default(),
@ -425,14 +425,14 @@ impl Resolver {
Scope::ExprScope(_) | Scope::MacroDefScope(_) => continue, Scope::ExprScope(_) | Scope::MacroDefScope(_) => continue,
Scope::GenericParams { params, def } => { Scope::GenericParams { params, def } => {
if let &GenericDefId::ImplId(impl_) = def { if let &GenericDefId::ImplId(impl_) = def {
if *first_name == sym::Self_.clone() { if *first_name == sym::Self_ {
return Some(( return Some((
ResolveValueResult::Partial(TypeNs::SelfType(impl_), 1, None), ResolveValueResult::Partial(TypeNs::SelfType(impl_), 1, None),
ResolvePathResultPrefixInfo::default(), ResolvePathResultPrefixInfo::default(),
)); ));
} }
} else if let &GenericDefId::AdtId(adt) = def { } else if let &GenericDefId::AdtId(adt) = def {
if *first_name == sym::Self_.clone() { if *first_name == sym::Self_ {
let ty = TypeNs::AdtSelfType(adt); let ty = TypeNs::AdtSelfType(adt);
return Some(( return Some((
ResolveValueResult::Partial(ty, 1, None), ResolveValueResult::Partial(ty, 1, None),
@ -1004,12 +1004,9 @@ impl Scope {
} }
&Scope::GenericParams { ref params, def: parent } => { &Scope::GenericParams { ref params, def: parent } => {
if let GenericDefId::ImplId(impl_) = parent { if let GenericDefId::ImplId(impl_) = parent {
acc.add( acc.add(&Name::new_symbol_root(sym::Self_), ScopeDef::ImplSelfType(impl_));
&Name::new_symbol_root(sym::Self_.clone()),
ScopeDef::ImplSelfType(impl_),
);
} else if let GenericDefId::AdtId(adt) = parent { } else if let GenericDefId::AdtId(adt) = parent {
acc.add(&Name::new_symbol_root(sym::Self_.clone()), ScopeDef::AdtSelfType(adt)); acc.add(&Name::new_symbol_root(sym::Self_), ScopeDef::AdtSelfType(adt));
} }
for (local_id, param) in params.iter_type_or_consts() { for (local_id, param) in params.iter_type_or_consts() {

View file

@ -74,10 +74,10 @@ impl StructSignature {
let attrs = item_tree.attrs(db, loc.container.krate, ModItem::from(loc.id.value).into()); let attrs = item_tree.attrs(db, loc.container.krate, ModItem::from(loc.id.value).into());
let mut flags = StructFlags::empty(); let mut flags = StructFlags::empty();
if attrs.by_key(&sym::rustc_has_incoherent_inherent_impls).exists() { if attrs.by_key(sym::rustc_has_incoherent_inherent_impls).exists() {
flags |= StructFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPLS; flags |= StructFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPLS;
} }
if attrs.by_key(&sym::fundamental).exists() { if attrs.by_key(sym::fundamental).exists() {
flags |= StructFlags::FUNDAMENTAL; flags |= StructFlags::FUNDAMENTAL;
} }
if let Some(lang) = attrs.lang_item() { if let Some(lang) = attrs.lang_item() {
@ -131,10 +131,10 @@ impl UnionSignature {
let item_tree = loc.id.item_tree(db); let item_tree = loc.id.item_tree(db);
let attrs = item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()); let attrs = item_tree.attrs(db, krate, ModItem::from(loc.id.value).into());
let mut flags = StructFlags::empty(); let mut flags = StructFlags::empty();
if attrs.by_key(&sym::rustc_has_incoherent_inherent_impls).exists() { if attrs.by_key(sym::rustc_has_incoherent_inherent_impls).exists() {
flags |= StructFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPLS; flags |= StructFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPLS;
} }
if attrs.by_key(&sym::fundamental).exists() { if attrs.by_key(sym::fundamental).exists() {
flags |= StructFlags::FUNDAMENTAL; flags |= StructFlags::FUNDAMENTAL;
} }
@ -184,7 +184,7 @@ impl EnumSignature {
let item_tree = loc.id.item_tree(db); let item_tree = loc.id.item_tree(db);
let attrs = item_tree.attrs(db, loc.container.krate, ModItem::from(loc.id.value).into()); let attrs = item_tree.attrs(db, loc.container.krate, ModItem::from(loc.id.value).into());
let mut flags = EnumFlags::empty(); let mut flags = EnumFlags::empty();
if attrs.by_key(&sym::rustc_has_incoherent_inherent_impls).exists() { if attrs.by_key(sym::rustc_has_incoherent_inherent_impls).exists() {
flags |= EnumFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPLS; flags |= EnumFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPLS;
} }
@ -244,7 +244,7 @@ impl ConstSignature {
let module = loc.container.module(db); let module = loc.container.module(db);
let attrs = item_tree.attrs(db, module.krate, ModItem::from(loc.id.value).into()); let attrs = item_tree.attrs(db, module.krate, ModItem::from(loc.id.value).into());
let mut flags = ConstFlags::empty(); let mut flags = ConstFlags::empty();
if attrs.by_key(&sym::rustc_allow_incoherent_impl).exists() { if attrs.by_key(sym::rustc_allow_incoherent_impl).exists() {
flags |= ConstFlags::RUSTC_ALLOW_INCOHERENT_IMPL; flags |= ConstFlags::RUSTC_ALLOW_INCOHERENT_IMPL;
} }
let source = loc.source(db); let source = loc.source(db);
@ -300,7 +300,7 @@ impl StaticSignature {
let module = loc.container.module(db); let module = loc.container.module(db);
let attrs = item_tree.attrs(db, module.krate, ModItem::from(loc.id.value).into()); let attrs = item_tree.attrs(db, module.krate, ModItem::from(loc.id.value).into());
let mut flags = StaticFlags::empty(); let mut flags = StaticFlags::empty();
if attrs.by_key(&sym::rustc_allow_incoherent_impl).exists() { if attrs.by_key(sym::rustc_allow_incoherent_impl).exists() {
flags |= StaticFlags::RUSTC_ALLOW_INCOHERENT_IMPL; flags |= StaticFlags::RUSTC_ALLOW_INCOHERENT_IMPL;
} }
@ -418,19 +418,19 @@ impl TraitSignature {
if source.value.unsafe_token().is_some() { if source.value.unsafe_token().is_some() {
flags.insert(TraitFlags::UNSAFE); flags.insert(TraitFlags::UNSAFE);
} }
if attrs.by_key(&sym::fundamental).exists() { if attrs.by_key(sym::fundamental).exists() {
flags |= TraitFlags::FUNDAMENTAL; flags |= TraitFlags::FUNDAMENTAL;
} }
if attrs.by_key(&sym::rustc_has_incoherent_inherent_impls).exists() { if attrs.by_key(sym::rustc_has_incoherent_inherent_impls).exists() {
flags |= TraitFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPLS; flags |= TraitFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPLS;
} }
if attrs.by_key(&sym::rustc_paren_sugar).exists() { if attrs.by_key(sym::rustc_paren_sugar).exists() {
flags |= TraitFlags::RUSTC_PAREN_SUGAR; flags |= TraitFlags::RUSTC_PAREN_SUGAR;
} }
let mut skip_array_during_method_dispatch = let mut skip_array_during_method_dispatch =
attrs.by_key(&sym::rustc_skip_array_during_method_dispatch).exists(); attrs.by_key(sym::rustc_skip_array_during_method_dispatch).exists();
let mut skip_boxed_slice_during_method_dispatch = false; let mut skip_boxed_slice_during_method_dispatch = false;
for tt in attrs.by_key(&sym::rustc_skip_during_method_dispatch).tt_values() { for tt in attrs.by_key(sym::rustc_skip_during_method_dispatch).tt_values() {
for tt in tt.iter() { for tt in tt.iter() {
if let tt::iter::TtElement::Leaf(tt::Leaf::Ident(ident)) = tt { if let tt::iter::TtElement::Leaf(tt::Leaf::Ident(ident)) = tt {
skip_array_during_method_dispatch |= ident.sym == sym::array; skip_array_during_method_dispatch |= ident.sym == sym::array;
@ -534,11 +534,11 @@ impl FunctionSignature {
let mut flags = FnFlags::empty(); let mut flags = FnFlags::empty();
let attrs = item_tree.attrs(db, module.krate, ModItem::from(loc.id.value).into()); let attrs = item_tree.attrs(db, module.krate, ModItem::from(loc.id.value).into());
if attrs.by_key(&sym::rustc_allow_incoherent_impl).exists() { if attrs.by_key(sym::rustc_allow_incoherent_impl).exists() {
flags.insert(FnFlags::RUSTC_ALLOW_INCOHERENT_IMPL); flags.insert(FnFlags::RUSTC_ALLOW_INCOHERENT_IMPL);
} }
if attrs.by_key(&sym::target_feature).exists() { if attrs.by_key(sym::target_feature).exists() {
flags.insert(FnFlags::HAS_TARGET_FEATURE); flags.insert(FnFlags::HAS_TARGET_FEATURE);
} }
let legacy_const_generics_indices = attrs.rustc_legacy_const_generics(); let legacy_const_generics_indices = attrs.rustc_legacy_const_generics();
@ -546,7 +546,7 @@ impl FunctionSignature {
let source = loc.source(db); let source = loc.source(db);
if source.value.unsafe_token().is_some() { if source.value.unsafe_token().is_some() {
if attrs.by_key(&sym::rustc_deprecated_safe_2024).exists() { if attrs.by_key(sym::rustc_deprecated_safe_2024).exists() {
flags.insert(FnFlags::DEPRECATED_SAFE_2024); flags.insert(FnFlags::DEPRECATED_SAFE_2024);
} else { } else {
flags.insert(FnFlags::UNSAFE); flags.insert(FnFlags::UNSAFE);
@ -569,8 +569,7 @@ impl FunctionSignature {
} }
let abi = source.value.abi().map(|abi| { let abi = source.value.abi().map(|abi| {
abi.abi_string() abi.abi_string().map_or_else(|| sym::C, |it| Symbol::intern(it.text_without_quotes()))
.map_or_else(|| sym::C.clone(), |it| Symbol::intern(it.text_without_quotes()))
}); });
let (store, source_map, generic_params, params, ret_type, self_param, variadic) = let (store, source_map, generic_params, params, ret_type, self_param, variadic) =
lower_function(db, module, source, id); lower_function(db, module, source, id);
@ -671,10 +670,10 @@ impl TypeAliasSignature {
loc.container.module(db).krate(), loc.container.module(db).krate(),
ModItem::from(loc.id.value).into(), ModItem::from(loc.id.value).into(),
); );
if attrs.by_key(&sym::rustc_has_incoherent_inherent_impls).exists() { if attrs.by_key(sym::rustc_has_incoherent_inherent_impls).exists() {
flags.insert(TypeAliasFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPL); flags.insert(TypeAliasFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPL);
} }
if attrs.by_key(&sym::rustc_allow_incoherent_impl).exists() { if attrs.by_key(sym::rustc_allow_incoherent_impl).exists() {
flags.insert(TypeAliasFlags::RUSTC_ALLOW_INCOHERENT_IMPL); flags.insert(TypeAliasFlags::RUSTC_ALLOW_INCOHERENT_IMPL);
} }
if matches!(loc.container, ItemContainerId::ExternBlockId(_)) { if matches!(loc.container, ItemContainerId::ExternBlockId(_)) {

View file

@ -66,10 +66,7 @@ impl RawAttrs {
kind, kind,
suffix: None, suffix: None,
}))), }))),
path: Interned::new(ModPath::from(Name::new_symbol( path: Interned::new(ModPath::from(Name::new_symbol(sym::doc, span.ctx))),
sym::doc.clone(),
span.ctx,
))),
ctxt: span.ctx, ctxt: span.ctx,
} }
}), }),
@ -120,48 +117,47 @@ impl RawAttrs {
/// Processes `cfg_attr`s, returning the resulting semantic `Attrs`. /// Processes `cfg_attr`s, returning the resulting semantic `Attrs`.
// FIXME: This should return a different type, signaling it was filtered? // FIXME: This should return a different type, signaling it was filtered?
pub fn filter(self, db: &dyn ExpandDatabase, krate: Crate) -> RawAttrs { pub fn filter(self, db: &dyn ExpandDatabase, krate: Crate) -> RawAttrs {
let has_cfg_attrs = self let has_cfg_attrs =
.iter() self.iter().any(|attr| attr.path.as_ident().is_some_and(|name| *name == sym::cfg_attr));
.any(|attr| attr.path.as_ident().is_some_and(|name| *name == sym::cfg_attr.clone()));
if !has_cfg_attrs { if !has_cfg_attrs {
return self; return self;
} }
let cfg_options = krate.cfg_options(db); let cfg_options = krate.cfg_options(db);
let new_attrs = let new_attrs = self
self.iter() .iter()
.flat_map(|attr| -> SmallVec<[_; 1]> { .flat_map(|attr| -> SmallVec<[_; 1]> {
let is_cfg_attr = let is_cfg_attr = attr.path.as_ident().is_some_and(|name| *name == sym::cfg_attr);
attr.path.as_ident().is_some_and(|name| *name == sym::cfg_attr.clone()); if !is_cfg_attr {
if !is_cfg_attr { return smallvec![attr.clone()];
return smallvec![attr.clone()]; }
}
let subtree = match attr.token_tree_value() { let subtree = match attr.token_tree_value() {
Some(it) => it, Some(it) => it,
_ => return smallvec![attr.clone()], _ => return smallvec![attr.clone()],
}; };
let (cfg, parts) = match parse_cfg_attr_input(subtree) { let (cfg, parts) = match parse_cfg_attr_input(subtree) {
Some(it) => it, Some(it) => it,
None => return smallvec![attr.clone()], None => return smallvec![attr.clone()],
}; };
let index = attr.id; let index = attr.id;
let attrs = parts.enumerate().take(1 << AttrId::CFG_ATTR_BITS).filter_map( let attrs = parts
|(idx, attr)| Attr::from_tt(db, attr, index.with_cfg_attr(idx)), .enumerate()
); .take(1 << AttrId::CFG_ATTR_BITS)
.filter_map(|(idx, attr)| Attr::from_tt(db, attr, index.with_cfg_attr(idx)));
let cfg = TopSubtree::from_token_trees(subtree.top_subtree().delimiter, cfg); let cfg = TopSubtree::from_token_trees(subtree.top_subtree().delimiter, cfg);
let cfg = CfgExpr::parse(&cfg); let cfg = CfgExpr::parse(&cfg);
if cfg_options.check(&cfg) == Some(false) { if cfg_options.check(&cfg) == Some(false) {
smallvec![] smallvec![]
} else { } else {
cov_mark::hit!(cfg_attr_active); cov_mark::hit!(cfg_attr_active);
attrs.collect() attrs.collect()
} }
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let entries = if new_attrs.is_empty() { let entries = if new_attrs.is_empty() {
None None
} else { } else {
@ -401,7 +397,7 @@ impl Attr {
} }
pub fn cfg(&self) -> Option<CfgExpr> { pub fn cfg(&self) -> Option<CfgExpr> {
if *self.path.as_ident()? == sym::cfg.clone() { if *self.path.as_ident()? == sym::cfg {
self.token_tree_value().map(CfgExpr::parse) self.token_tree_value().map(CfgExpr::parse)
} else { } else {
None None

View file

@ -177,10 +177,10 @@ fn line_expand(
ExpandResult::ok(tt::TopSubtree::invisible_from_leaves( ExpandResult::ok(tt::TopSubtree::invisible_from_leaves(
span, span,
[tt::Leaf::Literal(tt::Literal { [tt::Leaf::Literal(tt::Literal {
symbol: sym::INTEGER_0.clone(), symbol: sym::INTEGER_0,
span, span,
kind: tt::LitKind::Integer, kind: tt::LitKind::Integer,
suffix: Some(sym::u32.clone()), suffix: Some(sym::u32),
})], })],
)) ))
} }
@ -347,11 +347,7 @@ fn panic_expand(
let dollar_crate = dollar_crate(span); let dollar_crate = dollar_crate(span);
let call_site_span = span_with_call_site_ctxt(db, span, id.into(), Edition::CURRENT); let call_site_span = span_with_call_site_ctxt(db, span, id.into(), Edition::CURRENT);
let mac = if use_panic_2021(db, call_site_span) { let mac = if use_panic_2021(db, call_site_span) { sym::panic_2021 } else { sym::panic_2015 };
sym::panic_2021.clone()
} else {
sym::panic_2015.clone()
};
// Pass the original arguments // Pass the original arguments
let subtree = WithDelimiter { let subtree = WithDelimiter {
@ -379,9 +375,9 @@ fn unreachable_expand(
let call_site_span = span_with_call_site_ctxt(db, span, id.into(), Edition::CURRENT); let call_site_span = span_with_call_site_ctxt(db, span, id.into(), Edition::CURRENT);
let mac = if use_panic_2021(db, call_site_span) { let mac = if use_panic_2021(db, call_site_span) {
sym::unreachable_2021.clone() sym::unreachable_2021
} else { } else {
sym::unreachable_2015.clone() sym::unreachable_2015
}; };
// Pass the original arguments // Pass the original arguments
@ -411,7 +407,7 @@ fn use_panic_2021(db: &dyn ExpandDatabase, span: Span) -> bool {
// FIXME: Record allow_internal_unstable in the macro def (not been done yet because it // FIXME: Record allow_internal_unstable in the macro def (not been done yet because it
// would consume quite a bit extra memory for all call locs...) // would consume quite a bit extra memory for all call locs...)
// if let Some(features) = expn.def.allow_internal_unstable { // if let Some(features) = expn.def.allow_internal_unstable {
// if features.iter().any(|&f| f == sym::edition_panic.clone()) { // if features.iter().any(|&f| f == sym::edition_panic) {
// span = expn.call_site; // span = expn.call_site;
// continue; // continue;
// } // }

View file

@ -9,7 +9,7 @@ use tt::IdentIsRaw;
use crate::{name::Name, tt::TopSubtreeBuilder}; use crate::{name::Name, tt::TopSubtreeBuilder};
pub(crate) fn dollar_crate(span: Span) -> tt::Ident<Span> { pub(crate) fn dollar_crate(span: Span) -> tt::Ident<Span> {
tt::Ident { sym: sym::dollar_crate.clone(), span, is_raw: tt::IdentIsRaw::No } tt::Ident { sym: sym::dollar_crate, span, is_raw: tt::IdentIsRaw::No }
} }
// A helper macro quote macro // A helper macro quote macro
@ -203,7 +203,7 @@ impl_to_to_tokentrees! {
span: u32 => self { crate::tt::Literal{symbol: Symbol::integer(self as _), span, kind: tt::LitKind::Integer, suffix: None } }; span: u32 => self { crate::tt::Literal{symbol: Symbol::integer(self as _), span, kind: tt::LitKind::Integer, suffix: None } };
span: usize => self { crate::tt::Literal{symbol: Symbol::integer(self as _), span, kind: tt::LitKind::Integer, suffix: None } }; span: usize => self { crate::tt::Literal{symbol: Symbol::integer(self as _), span, kind: tt::LitKind::Integer, suffix: None } };
span: i32 => self { crate::tt::Literal{symbol: Symbol::integer(self as _), span, kind: tt::LitKind::Integer, suffix: None } }; span: i32 => self { crate::tt::Literal{symbol: Symbol::integer(self as _), span, kind: tt::LitKind::Integer, suffix: None } };
span: bool => self { crate::tt::Ident{sym: if self { sym::true_.clone() } else { sym::false_.clone() }, span, is_raw: tt::IdentIsRaw::No } }; span: bool => self { crate::tt::Ident{sym: if self { sym::true_ } else { sym::false_ }, span, is_raw: tt::IdentIsRaw::No } };
_span: crate::tt::Leaf => self { self }; _span: crate::tt::Leaf => self { self };
_span: crate::tt::Literal => self { self }; _span: crate::tt::Literal => self { self };
_span: crate::tt::Ident => self { self }; _span: crate::tt::Ident => self { self };

View file

@ -88,7 +88,7 @@ impl DeclarativeMacroExpander {
.find(|it| { .find(|it| {
it.path it.path
.as_ident() .as_ident()
.map(|it| *it == sym::rustc_macro_transparency.clone()) .map(|it| *it == sym::rustc_macro_transparency)
.unwrap_or(false) .unwrap_or(false)
})? })?
.token_tree_value()? .token_tree_value()?

View file

@ -82,7 +82,7 @@ pub(crate) fn fixup_syntax(
original.push(original_tree); original.push(original_tree);
let span = span_map.span_for_range(node_range); let span = span_map.span_for_range(node_range);
let replacement = Leaf::Ident(Ident { let replacement = Leaf::Ident(Ident {
sym: sym::__ra_fixup.clone(), sym: sym::__ra_fixup,
span: Span { span: Span {
range: TextRange::new(TextSize::new(idx), FIXUP_DUMMY_RANGE_END), range: TextRange::new(TextSize::new(idx), FIXUP_DUMMY_RANGE_END),
anchor: SpanAnchor { ast_id: FIXUP_DUMMY_AST_ID, ..span.anchor }, anchor: SpanAnchor { ast_id: FIXUP_DUMMY_AST_ID, ..span.anchor },
@ -102,7 +102,7 @@ pub(crate) fn fixup_syntax(
// incomplete field access: some_expr.| // incomplete field access: some_expr.|
append.insert(node.clone().into(), vec![ append.insert(node.clone().into(), vec![
Leaf::Ident(Ident { Leaf::Ident(Ident {
sym: sym::__ra_fixup.clone(), sym: sym::__ra_fixup,
span: fake_span(node_range), span: fake_span(node_range),
is_raw: tt::IdentIsRaw::No is_raw: tt::IdentIsRaw::No
}), }),
@ -141,7 +141,7 @@ pub(crate) fn fixup_syntax(
}; };
append.insert(if_token.into(), vec![ append.insert(if_token.into(), vec![
Leaf::Ident(Ident { Leaf::Ident(Ident {
sym: sym::__ra_fixup.clone(), sym: sym::__ra_fixup,
span: fake_span(node_range), span: fake_span(node_range),
is_raw: tt::IdentIsRaw::No is_raw: tt::IdentIsRaw::No
}), }),
@ -171,7 +171,7 @@ pub(crate) fn fixup_syntax(
}; };
append.insert(while_token.into(), vec![ append.insert(while_token.into(), vec![
Leaf::Ident(Ident { Leaf::Ident(Ident {
sym: sym::__ra_fixup.clone(), sym: sym::__ra_fixup,
span: fake_span(node_range), span: fake_span(node_range),
is_raw: tt::IdentIsRaw::No is_raw: tt::IdentIsRaw::No
}), }),
@ -217,7 +217,7 @@ pub(crate) fn fixup_syntax(
}; };
append.insert(match_token.into(), vec![ append.insert(match_token.into(), vec![
Leaf::Ident(Ident { Leaf::Ident(Ident {
sym: sym::__ra_fixup.clone(), sym: sym::__ra_fixup,
span: fake_span(node_range), span: fake_span(node_range),
is_raw: tt::IdentIsRaw::No is_raw: tt::IdentIsRaw::No
}), }),
@ -246,9 +246,9 @@ pub(crate) fn fixup_syntax(
}; };
let [pat, in_token, iter] = [ let [pat, in_token, iter] = [
sym::underscore.clone(), sym::underscore,
sym::in_.clone(), sym::in_,
sym::__ra_fixup.clone(), sym::__ra_fixup,
].map(|sym| ].map(|sym|
Leaf::Ident(Ident { Leaf::Ident(Ident {
sym, sym,
@ -284,7 +284,7 @@ pub(crate) fn fixup_syntax(
if it.name_ref().is_some() && it.expr().is_none() { if it.name_ref().is_some() && it.expr().is_none() {
append.insert(colon.into(), vec![ append.insert(colon.into(), vec![
Leaf::Ident(Ident { Leaf::Ident(Ident {
sym: sym::__ra_fixup.clone(), sym: sym::__ra_fixup,
span: fake_span(node_range), span: fake_span(node_range),
is_raw: tt::IdentIsRaw::No is_raw: tt::IdentIsRaw::No
}) })
@ -297,7 +297,7 @@ pub(crate) fn fixup_syntax(
if it.segment().is_none() { if it.segment().is_none() {
append.insert(colon.into(), vec![ append.insert(colon.into(), vec![
Leaf::Ident(Ident { Leaf::Ident(Ident {
sym: sym::__ra_fixup.clone(), sym: sym::__ra_fixup,
span: fake_span(node_range), span: fake_span(node_range),
is_raw: tt::IdentIsRaw::No is_raw: tt::IdentIsRaw::No
}) })
@ -309,7 +309,7 @@ pub(crate) fn fixup_syntax(
if it.body().is_none() { if it.body().is_none() {
append.insert(node.into(), vec![ append.insert(node.into(), vec![
Leaf::Ident(Ident { Leaf::Ident(Ident {
sym: sym::__ra_fixup.clone(), sym: sym::__ra_fixup,
span: fake_span(node_range), span: fake_span(node_range),
is_raw: tt::IdentIsRaw::No is_raw: tt::IdentIsRaw::No
}) })

View file

@ -562,7 +562,7 @@ pub const INERT_ATTRIBUTES: &[BuiltinAttribute] = &[
), ),
BuiltinAttribute { BuiltinAttribute {
// name: sym::rustc_diagnostic_item.clone(), // name: sym::rustc_diagnostic_item,
name: "rustc_diagnostic_item", name: "rustc_diagnostic_item",
// FIXME: This can be `true` once we always use `tcx.is_diagnostic_item`. // FIXME: This can be `true` once we always use `tcx.is_diagnostic_item`.
// only_local: false, // only_local: false,
@ -571,7 +571,7 @@ pub const INERT_ATTRIBUTES: &[BuiltinAttribute] = &[
// duplicates: ErrorFollowing, // duplicates: ErrorFollowing,
// gate: Gated( // gate: Gated(
// Stability::Unstable, // Stability::Unstable,
// sym::rustc_attrs.clone(), // sym::rustc_attrs,
// "diagnostic items compiler internal support for linting", // "diagnostic items compiler internal support for linting",
// cfg_fn!(rustc_attrs), // cfg_fn!(rustc_attrs),
// ), // ),

View file

@ -111,8 +111,7 @@ impl ModPath {
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub fn is_Self(&self) -> bool { pub fn is_Self(&self) -> bool {
self.kind == PathKind::Plain self.kind == PathKind::Plain && matches!(&*self.segments, [name] if *name == sym::Self_)
&& matches!(&*self.segments, [name] if *name == sym::Self_.clone())
} }
/// If this path is a single identifier, like `foo`, return its name. /// If this path is a single identifier, like `foo`, return its name.
@ -251,7 +250,7 @@ fn convert_path(
} }
} }
ast::PathSegmentKind::SelfTypeKw => { ast::PathSegmentKind::SelfTypeKw => {
ModPath::from_segments(PathKind::Plain, Some(Name::new_symbol_root(sym::Self_.clone()))) ModPath::from_segments(PathKind::Plain, Some(Name::new_symbol_root(sym::Self_)))
} }
ast::PathSegmentKind::CrateKw => ModPath::from_segments(PathKind::Crate, iter::empty()), ast::PathSegmentKind::CrateKw => ModPath::from_segments(PathKind::Crate, iter::empty()),
ast::PathSegmentKind::SelfKw => handle_super_kw(0)?, ast::PathSegmentKind::SelfKw => handle_super_kw(0)?,
@ -399,7 +398,7 @@ pub use crate::__path as path;
macro_rules! __tool_path { macro_rules! __tool_path {
($start:ident $(:: $seg:ident)*) => ({ ($start:ident $(:: $seg:ident)*) => ({
$crate::mod_path::ModPath::from_segments($crate::mod_path::PathKind::Plain, vec![ $crate::mod_path::ModPath::from_segments($crate::mod_path::PathKind::Plain, vec![
$crate::name::Name::new_symbol_root($crate::intern::sym::rust_analyzer.clone()), $crate::name::Name::new_symbol_root($crate::intern::sym::$start.clone()), $($crate::name::Name::new_symbol_root($crate::intern::sym::$seg.clone()),)* $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()),)*
]) ])
}); });
} }

View file

@ -93,22 +93,22 @@ impl Name {
pub fn new_tuple_field(idx: usize) -> Name { pub fn new_tuple_field(idx: usize) -> Name {
let symbol = match idx { let symbol = match idx {
0 => sym::INTEGER_0.clone(), 0 => sym::INTEGER_0,
1 => sym::INTEGER_1.clone(), 1 => sym::INTEGER_1,
2 => sym::INTEGER_2.clone(), 2 => sym::INTEGER_2,
3 => sym::INTEGER_3.clone(), 3 => sym::INTEGER_3,
4 => sym::INTEGER_4.clone(), 4 => sym::INTEGER_4,
5 => sym::INTEGER_5.clone(), 5 => sym::INTEGER_5,
6 => sym::INTEGER_6.clone(), 6 => sym::INTEGER_6,
7 => sym::INTEGER_7.clone(), 7 => sym::INTEGER_7,
8 => sym::INTEGER_8.clone(), 8 => sym::INTEGER_8,
9 => sym::INTEGER_9.clone(), 9 => sym::INTEGER_9,
10 => sym::INTEGER_10.clone(), 10 => sym::INTEGER_10,
11 => sym::INTEGER_11.clone(), 11 => sym::INTEGER_11,
12 => sym::INTEGER_12.clone(), 12 => sym::INTEGER_12,
13 => sym::INTEGER_13.clone(), 13 => sym::INTEGER_13,
14 => sym::INTEGER_14.clone(), 14 => sym::INTEGER_14,
15 => sym::INTEGER_15.clone(), 15 => sym::INTEGER_15,
_ => Symbol::intern(&idx.to_string()), _ => Symbol::intern(&idx.to_string()),
}; };
Name { symbol, ctx: () } Name { symbol, ctx: () }
@ -142,7 +142,7 @@ impl Name {
/// name is equal only to itself. It's not clear how to implement this in /// name is equal only to itself. It's not clear how to implement this in
/// salsa though, so we punt on that bit for a moment. /// salsa though, so we punt on that bit for a moment.
pub const fn missing() -> Name { pub const fn missing() -> Name {
Name { symbol: sym::consts::MISSING_NAME, ctx: () } Name { symbol: sym::MISSING_NAME, ctx: () }
} }
/// Returns true if this is a fake name for things missing in the source code. See /// Returns true if this is a fake name for things missing in the source code. See

View file

@ -209,9 +209,8 @@ pub(crate) fn deref_by_trait(
db.lang_item(table.trait_env.krate, LangItem::Deref).and_then(|l| l.as_trait()) db.lang_item(table.trait_env.krate, LangItem::Deref).and_then(|l| l.as_trait())
}; };
let trait_id = trait_id()?; let trait_id = trait_id()?;
let target = db let target =
.trait_items(trait_id) db.trait_items(trait_id).associated_type_by_name(&Name::new_symbol_root(sym::Target))?;
.associated_type_by_name(&Name::new_symbol_root(sym::Target.clone()))?;
let projection = { let projection = {
let b = TyBuilder::subst_for_def(db, trait_id, None); let b = TyBuilder::subst_for_def(db, trait_id, None);

View file

@ -289,16 +289,17 @@ impl chalk_solve::RustIrDatabase<Interner> for ChalkContext<'_> {
chalk_ir::Binders::new(binders, bound) chalk_ir::Binders::new(binders, bound)
} }
crate::ImplTraitId::AsyncBlockTypeImplTrait(..) => { crate::ImplTraitId::AsyncBlockTypeImplTrait(..) => {
if let Some((future_trait, future_output)) = if let Some((future_trait, future_output)) = self
self.db .db
.lang_item(self.krate, LangItem::Future) .lang_item(self.krate, LangItem::Future)
.and_then(|item| item.as_trait()) .and_then(|item| item.as_trait())
.and_then(|trait_| { .and_then(|trait_| {
let alias = self.db.trait_items(trait_).associated_type_by_name( let alias = self
&Name::new_symbol_root(sym::Output.clone()), .db
)?; .trait_items(trait_)
Some((trait_, alias)) .associated_type_by_name(&Name::new_symbol_root(sym::Output))?;
}) Some((trait_, alias))
})
{ {
// Making up Symbols value as variable is void: AsyncBlock<T>: // Making up Symbols value as variable is void: AsyncBlock<T>:
// //

View file

@ -201,7 +201,7 @@ impl<'a> DeclValidator<'a> {
// Don't run the lint on extern "[not Rust]" fn items with the // Don't run the lint on extern "[not Rust]" fn items with the
// #[no_mangle] attribute. // #[no_mangle] attribute.
let no_mangle = self.db.attrs(func.into()).by_key(&sym::no_mangle).exists(); let no_mangle = self.db.attrs(func.into()).by_key(sym::no_mangle).exists();
if no_mangle && data.abi.as_ref().is_some_and(|abi| *abi != sym::Rust) { if no_mangle && data.abi.as_ref().is_some_and(|abi| *abi != sym::Rust) {
cov_mark::hit!(extern_func_no_mangle_ignored); cov_mark::hit!(extern_func_no_mangle_ignored);
} else { } else {

View file

@ -492,9 +492,7 @@ impl FilterMapNextChecker {
ItemContainerId::TraitId(iterator_trait_id) => { ItemContainerId::TraitId(iterator_trait_id) => {
let iterator_trait_items = &db.trait_items(iterator_trait_id).items; let iterator_trait_items = &db.trait_items(iterator_trait_id).items;
iterator_trait_items.iter().find_map(|(name, it)| match it { iterator_trait_items.iter().find_map(|(name, it)| match it {
&AssocItemId::FunctionId(id) if *name == sym::filter_map.clone() => { &AssocItemId::FunctionId(id) if *name == sym::filter_map => Some(id),
Some(id)
}
_ => None, _ => None,
}) })
} }

View file

@ -106,7 +106,7 @@ impl<'db> MatchCheckCtx<'db> {
/// Returns whether the given ADT is from another crate declared `#[non_exhaustive]`. /// Returns whether the given ADT is from another crate declared `#[non_exhaustive]`.
fn is_foreign_non_exhaustive(&self, adt: hir_def::AdtId) -> bool { fn is_foreign_non_exhaustive(&self, adt: hir_def::AdtId) -> bool {
let is_local = adt.krate(self.db) == self.module.krate(); let is_local = adt.krate(self.db) == self.module.krate();
!is_local && self.db.attrs(adt.into()).by_key(&sym::non_exhaustive).exists() !is_local && self.db.attrs(adt.into()).by_key(sym::non_exhaustive).exists()
} }
fn variant_id_for_adt( fn variant_id_for_adt(

View file

@ -1350,9 +1350,8 @@ impl HirDisplay for Ty {
.lang_item(body.module(db).krate(), LangItem::Future) .lang_item(body.module(db).krate(), LangItem::Future)
.and_then(LangItemTarget::as_trait); .and_then(LangItemTarget::as_trait);
let output = future_trait.and_then(|t| { let output = future_trait.and_then(|t| {
db.trait_items(t).associated_type_by_name(&Name::new_symbol_root( db.trait_items(t)
sym::Output.clone(), .associated_type_by_name(&Name::new_symbol_root(sym::Output))
))
}); });
write!(f, "impl ")?; write!(f, "impl ")?;
if let Some(t) = future_trait { if let Some(t) = future_trait {
@ -2314,8 +2313,8 @@ impl HirDisplayWithExpressionStore for Path {
let name = crate_data let name = crate_data
.display_name .display_name
.as_ref() .as_ref()
.map(|name| name.canonical_name()) .map(|name| (*name.canonical_name()).clone())
.unwrap_or(&sym::dollar_crate); .unwrap_or(sym::dollar_crate);
write!(f, "{name}")? write!(f, "{name}")?
} }
} }

View file

@ -1737,9 +1737,7 @@ impl<'a> InferenceContext<'a> {
} }
fn resolve_output_on(&self, trait_: TraitId) -> Option<TypeAliasId> { fn resolve_output_on(&self, trait_: TraitId) -> Option<TypeAliasId> {
self.db self.db.trait_items(trait_).associated_type_by_name(&Name::new_symbol_root(sym::Output))
.trait_items(trait_)
.associated_type_by_name(&Name::new_symbol_root(sym::Output.clone()))
} }
fn resolve_lang_trait(&self, lang: LangItem) -> Option<TraitId> { fn resolve_lang_trait(&self, lang: LangItem) -> Option<TraitId> {

View file

@ -1175,7 +1175,7 @@ impl InferenceContext<'_> {
if let Some(deref_fn) = self if let Some(deref_fn) = self
.db .db
.trait_items(deref_trait) .trait_items(deref_trait)
.method_by_name(&Name::new_symbol_root(sym::deref_mut.clone())) .method_by_name(&Name::new_symbol_root(sym::deref_mut))
{ {
break 'b deref_fn == f; break 'b deref_fn == f;
} }

View file

@ -654,7 +654,7 @@ impl InferenceContext<'_> {
if let Some(deref_fn) = self if let Some(deref_fn) = self
.db .db
.trait_items(deref_trait) .trait_items(deref_trait)
.method_by_name(&Name::new_symbol_root(sym::deref.clone())) .method_by_name(&Name::new_symbol_root(sym::deref))
{ {
// FIXME: this is wrong in multiple ways, subst is empty, and we emit it even for builtin deref (note that // FIXME: this is wrong in multiple ways, subst is empty, and we emit it even for builtin deref (note that
// the mutability is not wrong, and will be fixed in `self.infer_mut`). // the mutability is not wrong, and will be fixed in `self.infer_mut`).
@ -813,7 +813,7 @@ impl InferenceContext<'_> {
if let Some(func) = self if let Some(func) = self
.db .db
.trait_items(index_trait) .trait_items(index_trait)
.method_by_name(&Name::new_symbol_root(sym::index.clone())) .method_by_name(&Name::new_symbol_root(sym::index))
{ {
let subst = TyBuilder::subst_for_def(self.db, index_trait, None); let subst = TyBuilder::subst_for_def(self.db, index_trait, None);
if subst.remaining() != 2 { if subst.remaining() != 2 {

View file

@ -134,7 +134,7 @@ impl InferenceContext<'_> {
if let Some(index_fn) = self if let Some(index_fn) = self
.db .db
.trait_items(index_trait) .trait_items(index_trait)
.method_by_name(&Name::new_symbol_root(sym::index_mut.clone())) .method_by_name(&Name::new_symbol_root(sym::index_mut))
{ {
*f = index_fn; *f = index_fn;
let mut base_ty = None; let mut base_ty = None;
@ -201,7 +201,7 @@ impl InferenceContext<'_> {
} else if let Some(deref_fn) = self } else if let Some(deref_fn) = self
.db .db
.trait_items(deref_trait) .trait_items(deref_trait)
.method_by_name(&Name::new_symbol_root(sym::deref_mut.clone())) .method_by_name(&Name::new_symbol_root(sym::deref_mut))
{ {
*f = deref_fn; *f = deref_fn;
} }

View file

@ -853,9 +853,9 @@ impl<'a> InferenceTable<'a> {
num_args: usize, num_args: usize,
) -> Option<(FnTrait, Vec<Ty>, Ty)> { ) -> Option<(FnTrait, Vec<Ty>, Ty)> {
for (fn_trait_name, output_assoc_name, subtraits) in [ for (fn_trait_name, output_assoc_name, subtraits) in [
(FnTrait::FnOnce, sym::Output.clone(), &[FnTrait::Fn, FnTrait::FnMut][..]), (FnTrait::FnOnce, sym::Output, &[FnTrait::Fn, FnTrait::FnMut][..]),
(FnTrait::AsyncFnMut, sym::CallRefFuture.clone(), &[FnTrait::AsyncFn]), (FnTrait::AsyncFnMut, sym::CallRefFuture, &[FnTrait::AsyncFn]),
(FnTrait::AsyncFnOnce, sym::CallOnceFuture.clone(), &[]), (FnTrait::AsyncFnOnce, sym::CallOnceFuture, &[]),
] { ] {
let krate = self.trait_env.krate; let krate = self.trait_env.krate;
let fn_trait = fn_trait_name.get_id(self.db, krate)?; let fn_trait = fn_trait_name.get_id(self.db, krate)?;

View file

@ -16,53 +16,43 @@ pub fn lang_items_for_bin_op(op: syntax::ast::BinaryOp) -> Option<(Name, LangIte
Some(match op { Some(match op {
BinaryOp::LogicOp(_) => return None, BinaryOp::LogicOp(_) => return None,
BinaryOp::ArithOp(aop) => match aop { BinaryOp::ArithOp(aop) => match aop {
ArithOp::Add => (Name::new_symbol_root(sym::add.clone()), LangItem::Add), ArithOp::Add => (Name::new_symbol_root(sym::add), LangItem::Add),
ArithOp::Mul => (Name::new_symbol_root(sym::mul.clone()), LangItem::Mul), ArithOp::Mul => (Name::new_symbol_root(sym::mul), LangItem::Mul),
ArithOp::Sub => (Name::new_symbol_root(sym::sub.clone()), LangItem::Sub), ArithOp::Sub => (Name::new_symbol_root(sym::sub), LangItem::Sub),
ArithOp::Div => (Name::new_symbol_root(sym::div.clone()), LangItem::Div), ArithOp::Div => (Name::new_symbol_root(sym::div), LangItem::Div),
ArithOp::Rem => (Name::new_symbol_root(sym::rem.clone()), LangItem::Rem), ArithOp::Rem => (Name::new_symbol_root(sym::rem), LangItem::Rem),
ArithOp::Shl => (Name::new_symbol_root(sym::shl.clone()), LangItem::Shl), ArithOp::Shl => (Name::new_symbol_root(sym::shl), LangItem::Shl),
ArithOp::Shr => (Name::new_symbol_root(sym::shr.clone()), LangItem::Shr), ArithOp::Shr => (Name::new_symbol_root(sym::shr), LangItem::Shr),
ArithOp::BitXor => (Name::new_symbol_root(sym::bitxor.clone()), LangItem::BitXor), ArithOp::BitXor => (Name::new_symbol_root(sym::bitxor), LangItem::BitXor),
ArithOp::BitOr => (Name::new_symbol_root(sym::bitor.clone()), LangItem::BitOr), ArithOp::BitOr => (Name::new_symbol_root(sym::bitor), LangItem::BitOr),
ArithOp::BitAnd => (Name::new_symbol_root(sym::bitand.clone()), LangItem::BitAnd), ArithOp::BitAnd => (Name::new_symbol_root(sym::bitand), LangItem::BitAnd),
}, },
BinaryOp::Assignment { op: Some(aop) } => match aop { BinaryOp::Assignment { op: Some(aop) } => match aop {
ArithOp::Add => (Name::new_symbol_root(sym::add_assign.clone()), LangItem::AddAssign), ArithOp::Add => (Name::new_symbol_root(sym::add_assign), LangItem::AddAssign),
ArithOp::Mul => (Name::new_symbol_root(sym::mul_assign.clone()), LangItem::MulAssign), ArithOp::Mul => (Name::new_symbol_root(sym::mul_assign), LangItem::MulAssign),
ArithOp::Sub => (Name::new_symbol_root(sym::sub_assign.clone()), LangItem::SubAssign), ArithOp::Sub => (Name::new_symbol_root(sym::sub_assign), LangItem::SubAssign),
ArithOp::Div => (Name::new_symbol_root(sym::div_assign.clone()), LangItem::DivAssign), ArithOp::Div => (Name::new_symbol_root(sym::div_assign), LangItem::DivAssign),
ArithOp::Rem => (Name::new_symbol_root(sym::rem_assign.clone()), LangItem::RemAssign), ArithOp::Rem => (Name::new_symbol_root(sym::rem_assign), LangItem::RemAssign),
ArithOp::Shl => (Name::new_symbol_root(sym::shl_assign.clone()), LangItem::ShlAssign), ArithOp::Shl => (Name::new_symbol_root(sym::shl_assign), LangItem::ShlAssign),
ArithOp::Shr => (Name::new_symbol_root(sym::shr_assign.clone()), LangItem::ShrAssign), ArithOp::Shr => (Name::new_symbol_root(sym::shr_assign), LangItem::ShrAssign),
ArithOp::BitXor => { ArithOp::BitXor => (Name::new_symbol_root(sym::bitxor_assign), LangItem::BitXorAssign),
(Name::new_symbol_root(sym::bitxor_assign.clone()), LangItem::BitXorAssign) ArithOp::BitOr => (Name::new_symbol_root(sym::bitor_assign), LangItem::BitOrAssign),
} ArithOp::BitAnd => (Name::new_symbol_root(sym::bitand_assign), LangItem::BitAndAssign),
ArithOp::BitOr => {
(Name::new_symbol_root(sym::bitor_assign.clone()), LangItem::BitOrAssign)
}
ArithOp::BitAnd => {
(Name::new_symbol_root(sym::bitand_assign.clone()), LangItem::BitAndAssign)
}
}, },
BinaryOp::CmpOp(cop) => match cop { BinaryOp::CmpOp(cop) => match cop {
CmpOp::Eq { negated: false } => { CmpOp::Eq { negated: false } => (Name::new_symbol_root(sym::eq), LangItem::PartialEq),
(Name::new_symbol_root(sym::eq.clone()), LangItem::PartialEq) CmpOp::Eq { negated: true } => (Name::new_symbol_root(sym::ne), LangItem::PartialEq),
}
CmpOp::Eq { negated: true } => {
(Name::new_symbol_root(sym::ne.clone()), LangItem::PartialEq)
}
CmpOp::Ord { ordering: Ordering::Less, strict: false } => { CmpOp::Ord { ordering: Ordering::Less, strict: false } => {
(Name::new_symbol_root(sym::le.clone()), LangItem::PartialOrd) (Name::new_symbol_root(sym::le), LangItem::PartialOrd)
} }
CmpOp::Ord { ordering: Ordering::Less, strict: true } => { CmpOp::Ord { ordering: Ordering::Less, strict: true } => {
(Name::new_symbol_root(sym::lt.clone()), LangItem::PartialOrd) (Name::new_symbol_root(sym::lt), LangItem::PartialOrd)
} }
CmpOp::Ord { ordering: Ordering::Greater, strict: false } => { CmpOp::Ord { ordering: Ordering::Greater, strict: false } => {
(Name::new_symbol_root(sym::ge.clone()), LangItem::PartialOrd) (Name::new_symbol_root(sym::ge), LangItem::PartialOrd)
} }
CmpOp::Ord { ordering: Ordering::Greater, strict: true } => { CmpOp::Ord { ordering: Ordering::Greater, strict: true } => {
(Name::new_symbol_root(sym::gt.clone()), LangItem::PartialOrd) (Name::new_symbol_root(sym::gt), LangItem::PartialOrd)
} }
}, },
BinaryOp::Assignment { op: None } => return None, BinaryOp::Assignment { op: None } => return None,

View file

@ -128,10 +128,7 @@ fn layout_scalar_valid_range(db: &dyn HirDatabase, def: AdtId) -> (Bound<u128>,
} }
Bound::Unbounded Bound::Unbounded
}; };
( (get(sym::rustc_layout_scalar_valid_range_start), get(sym::rustc_layout_scalar_valid_range_end))
get(&sym::rustc_layout_scalar_valid_range_start),
get(&sym::rustc_layout_scalar_valid_range_end),
)
} }
pub(crate) fn layout_of_adt_recover( pub(crate) fn layout_of_adt_recover(

View file

@ -889,7 +889,7 @@ pub fn callable_sig_from_fn_trait(
let fn_once_trait = FnTrait::FnOnce.get_id(db, krate)?; let fn_once_trait = FnTrait::FnOnce.get_id(db, krate)?;
let output_assoc_type = db let output_assoc_type = db
.trait_items(fn_once_trait) .trait_items(fn_once_trait)
.associated_type_by_name(&Name::new_symbol_root(sym::Output.clone()))?; .associated_type_by_name(&Name::new_symbol_root(sym::Output))?;
let mut table = InferenceTable::new(db, trait_env.clone()); let mut table = InferenceTable::new(db, trait_env.clone());
let b = TyBuilder::trait_ref(db, fn_once_trait); let b = TyBuilder::trait_ref(db, fn_once_trait);

View file

@ -197,7 +197,7 @@ impl TraitImpls {
// FIXME: Reservation impls should be considered during coherence checks. If we are // FIXME: Reservation impls should be considered during coherence checks. If we are
// (ever) to implement coherence checks, this filtering should be done by the trait // (ever) to implement coherence checks, this filtering should be done by the trait
// solver. // solver.
if db.attrs(impl_id.into()).by_key(&sym::rustc_reservation_impl).exists() { if db.attrs(impl_id.into()).by_key(sym::rustc_reservation_impl).exists() {
continue; continue;
} }
let target_trait = match db.impl_trait(impl_id) { let target_trait = match db.impl_trait(impl_id) {

View file

@ -658,20 +658,18 @@ impl Evaluator<'_> {
cached_fn_trait_func: db cached_fn_trait_func: db
.lang_item(crate_id, LangItem::Fn) .lang_item(crate_id, LangItem::Fn)
.and_then(|x| x.as_trait()) .and_then(|x| x.as_trait())
.and_then(|x| { .and_then(|x| db.trait_items(x).method_by_name(&Name::new_symbol_root(sym::call))),
db.trait_items(x).method_by_name(&Name::new_symbol_root(sym::call.clone()))
}),
cached_fn_mut_trait_func: db cached_fn_mut_trait_func: db
.lang_item(crate_id, LangItem::FnMut) .lang_item(crate_id, LangItem::FnMut)
.and_then(|x| x.as_trait()) .and_then(|x| x.as_trait())
.and_then(|x| { .and_then(|x| {
db.trait_items(x).method_by_name(&Name::new_symbol_root(sym::call_mut.clone())) db.trait_items(x).method_by_name(&Name::new_symbol_root(sym::call_mut))
}), }),
cached_fn_once_trait_func: db cached_fn_once_trait_func: db
.lang_item(crate_id, LangItem::FnOnce) .lang_item(crate_id, LangItem::FnOnce)
.and_then(|x| x.as_trait()) .and_then(|x| x.as_trait())
.and_then(|x| { .and_then(|x| {
db.trait_items(x).method_by_name(&Name::new_symbol_root(sym::call_once.clone())) db.trait_items(x).method_by_name(&Name::new_symbol_root(sym::call_once))
}), }),
}) })
} }
@ -2814,9 +2812,7 @@ impl Evaluator<'_> {
) -> Result<()> { ) -> Result<()> {
let Some(drop_fn) = (|| { let Some(drop_fn) = (|| {
let drop_trait = self.db.lang_item(self.crate_id, LangItem::Drop)?.as_trait()?; let drop_trait = self.db.lang_item(self.crate_id, LangItem::Drop)?.as_trait()?;
self.db self.db.trait_items(drop_trait).method_by_name(&Name::new_symbol_root(sym::drop))
.trait_items(drop_trait)
.method_by_name(&Name::new_symbol_root(sym::drop.clone()))
})() else { })() else {
// in some tests we don't have drop trait in minicore, and // in some tests we don't have drop trait in minicore, and
// we can ignore drop in them. // we can ignore drop in them.
@ -2926,7 +2922,7 @@ pub fn render_const_using_debug_impl(
not_supported!("core::fmt::Debug not found"); not_supported!("core::fmt::Debug not found");
}; };
let Some(debug_fmt_fn) = let Some(debug_fmt_fn) =
db.trait_items(debug_trait).method_by_name(&Name::new_symbol_root(sym::fmt.clone())) db.trait_items(debug_trait).method_by_name(&Name::new_symbol_root(sym::fmt))
else { else {
not_supported!("core::fmt::Debug::fmt not found"); not_supported!("core::fmt::Debug::fmt not found");
}; };

View file

@ -59,7 +59,7 @@ impl Evaluator<'_> {
let function_data = self.db.function_signature(def); let function_data = self.db.function_signature(def);
let attrs = self.db.attrs(def.into()); let attrs = self.db.attrs(def.into());
let is_intrinsic = attrs.by_key(&sym::rustc_intrinsic).exists() let is_intrinsic = attrs.by_key(sym::rustc_intrinsic).exists()
// Keep this around for a bit until extern "rustc-intrinsic" abis are no longer used // Keep this around for a bit until extern "rustc-intrinsic" abis are no longer used
|| (match &function_data.abi { || (match &function_data.abi {
Some(abi) => *abi == sym::rust_dash_intrinsic, Some(abi) => *abi == sym::rust_dash_intrinsic,
@ -82,7 +82,7 @@ impl Evaluator<'_> {
locals, locals,
span, span,
!function_data.has_body() !function_data.has_body()
|| attrs.by_key(&sym::rustc_intrinsic_must_be_overridden).exists(), || attrs.by_key(sym::rustc_intrinsic_must_be_overridden).exists(),
); );
} }
let is_extern_c = match def.lookup(self.db).container { let is_extern_c = match def.lookup(self.db).container {
@ -299,7 +299,7 @@ impl Evaluator<'_> {
use LangItem::*; use LangItem::*;
let attrs = self.db.attrs(def.into()); let attrs = self.db.attrs(def.into());
if attrs.by_key(&sym::rustc_const_panic_str).exists() { if attrs.by_key(sym::rustc_const_panic_str).exists() {
// `#[rustc_const_panic_str]` is treated like `lang = "begin_panic"` by rustc CTFE. // `#[rustc_const_panic_str]` is treated like `lang = "begin_panic"` by rustc CTFE.
return Some(LangItem::BeginPanic); return Some(LangItem::BeginPanic);
} }
@ -1261,7 +1261,7 @@ impl Evaluator<'_> {
if let Some(def) = target.as_trait().and_then(|it| { if let Some(def) = target.as_trait().and_then(|it| {
self.db self.db
.trait_items(it) .trait_items(it)
.method_by_name(&Name::new_symbol_root(sym::call_once.clone())) .method_by_name(&Name::new_symbol_root(sym::call_once))
}) { }) {
self.exec_fn_trait( self.exec_fn_trait(
def, def,

View file

@ -193,10 +193,10 @@ impl MirLowerCtx<'_> {
if let Some(deref_trait) = if let Some(deref_trait) =
self.resolve_lang_item(LangItem::DerefMut)?.as_trait() self.resolve_lang_item(LangItem::DerefMut)?.as_trait()
{ {
if let Some(deref_fn) = if let Some(deref_fn) = self
self.db.trait_items(deref_trait).method_by_name( .db
&Name::new_symbol_root(sym::deref_mut.clone()), .trait_items(deref_trait)
) .method_by_name(&Name::new_symbol_root(sym::deref_mut))
{ {
break 'b deref_fn == f; break 'b deref_fn == f;
} }
@ -331,14 +331,14 @@ impl MirLowerCtx<'_> {
( (
Mutability::Not, Mutability::Not,
LangItem::Deref, LangItem::Deref,
Name::new_symbol_root(sym::deref.clone()), Name::new_symbol_root(sym::deref),
BorrowKind::Shared, BorrowKind::Shared,
) )
} else { } else {
( (
Mutability::Mut, Mutability::Mut,
LangItem::DerefMut, LangItem::DerefMut,
Name::new_symbol_root(sym::deref_mut.clone()), Name::new_symbol_root(sym::deref_mut),
BorrowKind::Mut { kind: MutBorrowKind::Default }, BorrowKind::Mut { kind: MutBorrowKind::Default },
) )
}; };

View file

@ -36,7 +36,7 @@ impl TargetFeatures {
/// Retrieves the target features from the attributes, and does not expand the target features implied by them. /// Retrieves the target features from the attributes, and does not expand the target features implied by them.
pub(crate) fn from_attrs_no_implications(attrs: &Attrs) -> Self { pub(crate) fn from_attrs_no_implications(attrs: &Attrs) -> Self {
let enabled = attrs let enabled = attrs
.by_key(&sym::target_feature) .by_key(sym::target_feature)
.tt_values() .tt_values()
.filter_map(|tt| match tt.token_trees().flat_tokens() { .filter_map(|tt| match tt.token_trees().flat_tokens() {
[ [

View file

@ -282,12 +282,12 @@ impl FnTrait {
pub fn method_name(self) -> Name { pub fn method_name(self) -> Name {
match self { match self {
FnTrait::FnOnce => Name::new_symbol_root(sym::call_once.clone()), FnTrait::FnOnce => Name::new_symbol_root(sym::call_once),
FnTrait::FnMut => Name::new_symbol_root(sym::call_mut.clone()), FnTrait::FnMut => Name::new_symbol_root(sym::call_mut),
FnTrait::Fn => Name::new_symbol_root(sym::call.clone()), FnTrait::Fn => Name::new_symbol_root(sym::call),
FnTrait::AsyncFnOnce => Name::new_symbol_root(sym::async_call_once.clone()), FnTrait::AsyncFnOnce => Name::new_symbol_root(sym::async_call_once),
FnTrait::AsyncFnMut => Name::new_symbol_root(sym::async_call_mut.clone()), FnTrait::AsyncFnMut => Name::new_symbol_root(sym::async_call_mut),
FnTrait::AsyncFn => Name::new_symbol_root(sym::async_call.clone()), FnTrait::AsyncFn => Name::new_symbol_root(sym::async_call),
} }
} }

View file

@ -305,7 +305,7 @@ pub fn is_fn_unsafe_to_call(
if is_intrinsic_block { if is_intrinsic_block {
// legacy intrinsics // legacy intrinsics
// extern "rust-intrinsic" intrinsics are unsafe unless they have the rustc_safe_intrinsic attribute // extern "rust-intrinsic" intrinsics are unsafe unless they have the rustc_safe_intrinsic attribute
if db.attrs(func.into()).by_key(&sym::rustc_safe_intrinsic).exists() { if db.attrs(func.into()).by_key(sym::rustc_safe_intrinsic).exists() {
Unsafety::Safe Unsafety::Safe
} else { } else {
Unsafety::Unsafe Unsafety::Unsafe

View file

@ -274,7 +274,7 @@ impl Crate {
pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> { pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
// Look for #![doc(html_root_url = "...")] // Look for #![doc(html_root_url = "...")]
let attrs = db.attrs(AttrDefId::ModuleId(self.root_module().into())); let attrs = db.attrs(AttrDefId::ModuleId(self.root_module().into()));
let doc_url = attrs.by_key(&sym::doc).find_string_value_in_tt(&sym::html_root_url); let doc_url = attrs.by_key(sym::doc).find_string_value_in_tt(sym::html_root_url);
doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/") doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
} }
@ -799,7 +799,7 @@ impl Module {
)) ))
}); });
let res = type_params.chain(lifetime_params).any(|p| { let res = type_params.chain(lifetime_params).any(|p| {
db.attrs(AttrDefId::GenericParamId(p)).by_key(&sym::may_dangle).exists() db.attrs(AttrDefId::GenericParamId(p)).by_key(sym::may_dangle).exists()
}); });
Some(res) Some(res)
})() })()
@ -2056,7 +2056,7 @@ impl DefWithBody {
continue; continue;
} }
let mut need_mut = &mol[local]; let mut need_mut = &mol[local];
if body[binding_id].name == sym::self_.clone() if body[binding_id].name == sym::self_
&& need_mut == &mir::MutabilityReason::Unused && need_mut == &mir::MutabilityReason::Unused
{ {
need_mut = &mir::MutabilityReason::Not; need_mut = &mir::MutabilityReason::Not;
@ -3045,7 +3045,7 @@ pub struct StaticLifetime;
impl StaticLifetime { impl StaticLifetime {
pub fn name(self) -> Name { pub fn name(self) -> Name {
Name::new_symbol_root(sym::tick_static.clone()) Name::new_symbol_root(sym::tick_static)
} }
} }
@ -3160,7 +3160,7 @@ impl Macro {
} }
pub fn is_macro_export(self, db: &dyn HirDatabase) -> bool { pub fn is_macro_export(self, db: &dyn HirDatabase) -> bool {
matches!(self.id, MacroId::MacroRulesId(_) if db.attrs(self.id.into()).by_key(&sym::macro_export).exists()) matches!(self.id, MacroId::MacroRulesId(_) if db.attrs(self.id.into()).by_key(sym::macro_export).exists())
} }
pub fn is_proc_macro(self) -> bool { pub fn is_proc_macro(self) -> bool {
@ -3871,7 +3871,7 @@ impl Local {
} }
pub fn is_self(self, db: &dyn HirDatabase) -> bool { pub fn is_self(self, db: &dyn HirDatabase) -> bool {
self.name(db) == sym::self_.clone() self.name(db) == sym::self_
} }
pub fn is_mut(self, db: &dyn HirDatabase) -> bool { pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
@ -4987,9 +4987,8 @@ impl Type {
return None; return None;
} }
let output_assoc_type = db let output_assoc_type =
.trait_items(trait_) db.trait_items(trait_).associated_type_by_name(&Name::new_symbol_root(sym::Output))?;
.associated_type_by_name(&Name::new_symbol_root(sym::Output.clone()))?;
self.normalize_trait_assoc_type(db, &[], output_assoc_type.into()) self.normalize_trait_assoc_type(db, &[], output_assoc_type.into())
} }
@ -5005,7 +5004,7 @@ impl Type {
let iterator_trait = db.lang_item(self.env.krate, LangItem::Iterator)?.as_trait()?; let iterator_trait = db.lang_item(self.env.krate, LangItem::Iterator)?.as_trait()?;
let iterator_item = db let iterator_item = db
.trait_items(iterator_trait) .trait_items(iterator_trait)
.associated_type_by_name(&Name::new_symbol_root(sym::Item.clone()))?; .associated_type_by_name(&Name::new_symbol_root(sym::Item))?;
self.normalize_trait_assoc_type(db, &[], iterator_item.into()) self.normalize_trait_assoc_type(db, &[], iterator_item.into())
} }
@ -5037,7 +5036,7 @@ impl Type {
let into_iter_assoc_type = db let into_iter_assoc_type = db
.trait_items(trait_) .trait_items(trait_)
.associated_type_by_name(&Name::new_symbol_root(sym::IntoIter.clone()))?; .associated_type_by_name(&Name::new_symbol_root(sym::IntoIter))?;
self.normalize_trait_assoc_type(db, &[], into_iter_assoc_type.into()) self.normalize_trait_assoc_type(db, &[], into_iter_assoc_type.into())
} }

View file

@ -2058,7 +2058,7 @@ impl SemanticsScope<'_> {
ast::PathSegmentKind::Name(name_ref) => segments.push(name_ref.as_name()), ast::PathSegmentKind::Name(name_ref) => segments.push(name_ref.as_name()),
ast::PathSegmentKind::Type { .. } => continue, ast::PathSegmentKind::Type { .. } => continue,
ast::PathSegmentKind::SelfTypeKw => { ast::PathSegmentKind::SelfTypeKw => {
segments.push(Name::new_symbol_root(sym::Self_.clone())) segments.push(Name::new_symbol_root(sym::Self_))
} }
ast::PathSegmentKind::SelfKw => kind = PathKind::Super(0), ast::PathSegmentKind::SelfKw => kind = PathKind::Super(0),
ast::PathSegmentKind::SuperKw => match kind { ast::PathSegmentKind::SuperKw => match kind {

View file

@ -540,7 +540,7 @@ impl SourceAnalyzer {
let items = into_future_trait.items(db); let items = into_future_trait.items(db);
let into_future_type = items.into_iter().find_map(|item| match item { let into_future_type = items.into_iter().find_map(|item| match item {
AssocItem::TypeAlias(alias) AssocItem::TypeAlias(alias)
if alias.name(db) == Name::new_symbol_root(sym::IntoFuture.clone()) => if alias.name(db) == Name::new_symbol_root(sym::IntoFuture) =>
{ {
Some(alias) Some(alias)
} }
@ -569,11 +569,8 @@ impl SourceAnalyzer {
// This can be either `Deref::deref` or `DerefMut::deref_mut`. // This can be either `Deref::deref` or `DerefMut::deref_mut`.
// Since deref kind is inferenced and stored in `InferenceResult.method_resolution`, // Since deref kind is inferenced and stored in `InferenceResult.method_resolution`,
// use that result to find out which one it is. // use that result to find out which one it is.
let (deref_trait, deref) = self.lang_trait_fn( let (deref_trait, deref) =
db, self.lang_trait_fn(db, LangItem::Deref, &Name::new_symbol_root(sym::deref))?;
LangItem::Deref,
&Name::new_symbol_root(sym::deref.clone()),
)?;
self.infer() self.infer()
.and_then(|infer| { .and_then(|infer| {
let expr = self.expr_id(prefix_expr.clone().into())?.as_expr()?; let expr = self.expr_id(prefix_expr.clone().into())?.as_expr()?;
@ -581,17 +578,17 @@ impl SourceAnalyzer {
let (deref_mut_trait, deref_mut) = self.lang_trait_fn( let (deref_mut_trait, deref_mut) = self.lang_trait_fn(
db, db,
LangItem::DerefMut, LangItem::DerefMut,
&Name::new_symbol_root(sym::deref_mut.clone()), &Name::new_symbol_root(sym::deref_mut),
)?; )?;
if func == deref_mut { Some((deref_mut_trait, deref_mut)) } else { None } if func == deref_mut { Some((deref_mut_trait, deref_mut)) } else { None }
}) })
.unwrap_or((deref_trait, deref)) .unwrap_or((deref_trait, deref))
} }
ast::UnaryOp::Not => { ast::UnaryOp::Not => {
self.lang_trait_fn(db, LangItem::Not, &Name::new_symbol_root(sym::not.clone()))? self.lang_trait_fn(db, LangItem::Not, &Name::new_symbol_root(sym::not))?
} }
ast::UnaryOp::Neg => { ast::UnaryOp::Neg => {
self.lang_trait_fn(db, LangItem::Neg, &Name::new_symbol_root(sym::neg.clone()))? self.lang_trait_fn(db, LangItem::Neg, &Name::new_symbol_root(sym::neg))?
} }
}; };
@ -613,7 +610,7 @@ impl SourceAnalyzer {
let index_ty = self.ty_of_expr(index_expr.index()?)?; let index_ty = self.ty_of_expr(index_expr.index()?)?;
let (index_trait, index_fn) = let (index_trait, index_fn) =
self.lang_trait_fn(db, LangItem::Index, &Name::new_symbol_root(sym::index.clone()))?; self.lang_trait_fn(db, LangItem::Index, &Name::new_symbol_root(sym::index))?;
let (op_trait, op_fn) = self let (op_trait, op_fn) = self
.infer() .infer()
.and_then(|infer| { .and_then(|infer| {
@ -622,7 +619,7 @@ impl SourceAnalyzer {
let (index_mut_trait, index_mut_fn) = self.lang_trait_fn( let (index_mut_trait, index_mut_fn) = self.lang_trait_fn(
db, db,
LangItem::IndexMut, LangItem::IndexMut,
&Name::new_symbol_root(sym::index_mut.clone()), &Name::new_symbol_root(sym::index_mut),
)?; )?;
if func == index_mut_fn { Some((index_mut_trait, index_mut_fn)) } else { None } if func == index_mut_fn { Some((index_mut_trait, index_mut_fn)) } else { None }
}) })

View file

@ -386,7 +386,7 @@ impl ExtendedEnum {
fn is_non_exhaustive(self, db: &RootDatabase, krate: Crate) -> bool { fn is_non_exhaustive(self, db: &RootDatabase, krate: Crate) -> bool {
match self { match self {
ExtendedEnum::Enum(e) => { ExtendedEnum::Enum(e) => {
e.attrs(db).by_key(&sym::non_exhaustive).exists() && e.module(db).krate() != krate e.attrs(db).by_key(sym::non_exhaustive).exists() && e.module(db).krate() != krate
} }
_ => false, _ => false,
} }

View file

@ -245,7 +245,7 @@ fn option_variants(
let fam = FamousDefs(sema, sema.scope(expr)?.krate()); let fam = FamousDefs(sema, sema.scope(expr)?.krate());
let option_variants = fam.core_option_Option()?.variants(sema.db); let option_variants = fam.core_option_Option()?.variants(sema.db);
match &*option_variants { match &*option_variants {
&[variant0, variant1] => Some(if variant0.name(sema.db) == sym::None.clone() { &[variant0, variant1] => Some(if variant0.name(sema.db) == sym::None {
(variant0, variant1) (variant0, variant1)
} else { } else {
(variant1, variant0) (variant1, variant0)

View file

@ -118,9 +118,9 @@ fn is_ref_and_impls_iter_method(
_ => return None, _ => return None,
}; };
let wanted_method = Name::new_symbol_root(if ref_expr.mut_token().is_some() { let wanted_method = Name::new_symbol_root(if ref_expr.mut_token().is_some() {
sym::iter_mut.clone() sym::iter_mut
} else { } else {
sym::iter.clone() sym::iter
}); });
let expr_behind_ref = ref_expr.expr()?; let expr_behind_ref = ref_expr.expr()?;
let ty = sema.type_of_expr(&expr_behind_ref)?.adjusted(); let ty = sema.type_of_expr(&expr_behind_ref)?.adjusted();

View file

@ -154,9 +154,9 @@ fn is_ref_and_impls_iter_method(
_ => return None, _ => return None,
}; };
let wanted_method = Name::new_symbol_root(if ref_expr.mut_token().is_some() { let wanted_method = Name::new_symbol_root(if ref_expr.mut_token().is_some() {
sym::iter_mut.clone() sym::iter_mut
} else { } else {
sym::iter.clone() sym::iter
}); });
let expr_behind_ref = ref_expr.expr()?; let expr_behind_ref = ref_expr.expr()?;
let ty = sema.type_of_expr(&expr_behind_ref)?.adjusted(); let ty = sema.type_of_expr(&expr_behind_ref)?.adjusted();

View file

@ -93,7 +93,7 @@ fn collect_data(ident_pat: ast::IdentPat, ctx: &AssistContext<'_>) -> Option<Str
let kind = struct_type.kind(ctx.db()); let kind = struct_type.kind(ctx.db());
let struct_def_path = module.find_path(ctx.db(), struct_def, cfg)?; let struct_def_path = module.find_path(ctx.db(), struct_def, cfg)?;
let is_non_exhaustive = struct_def.attrs(ctx.db())?.by_key(&sym::non_exhaustive).exists(); let is_non_exhaustive = struct_def.attrs(ctx.db())?.by_key(sym::non_exhaustive).exists();
let is_foreign_crate = struct_def.module(ctx.db()).is_some_and(|m| m.krate() != module.krate()); let is_foreign_crate = struct_def.module(ctx.db()).is_some_and(|m| m.krate() != module.krate());
let fields = struct_type.fields(ctx.db()); let fields = struct_type.fields(ctx.db());

View file

@ -54,13 +54,13 @@ pub(crate) fn generate_is_empty_from_len(acc: &mut Assists, ctx: &AssistContext<
} }
let impl_ = fn_node.syntax().ancestors().find_map(ast::Impl::cast)?; let impl_ = fn_node.syntax().ancestors().find_map(ast::Impl::cast)?;
let len_fn = get_impl_method(ctx, &impl_, &Name::new_symbol_root(sym::len.clone()))?; let len_fn = get_impl_method(ctx, &impl_, &Name::new_symbol_root(sym::len))?;
if !len_fn.ret_type(ctx.sema.db).is_usize() { if !len_fn.ret_type(ctx.sema.db).is_usize() {
cov_mark::hit!(len_fn_different_return_type); cov_mark::hit!(len_fn_different_return_type);
return None; return None;
} }
if get_impl_method(ctx, &impl_, &Name::new_symbol_root(sym::is_empty.clone())).is_some() { if get_impl_method(ctx, &impl_, &Name::new_symbol_root(sym::is_empty)).is_some() {
cov_mark::hit!(is_empty_already_implemented); cov_mark::hit!(is_empty_already_implemented);
return None; return None;
} }

View file

@ -451,7 +451,7 @@ fn inline(
let ty = sema.type_of_expr(expr).filter(TypeInfo::has_adjustment).and(param_ty); let ty = sema.type_of_expr(expr).filter(TypeInfo::has_adjustment).and(param_ty);
let is_self = param.name(sema.db).is_some_and(|name| name == sym::self_.clone()); let is_self = param.name(sema.db).is_some_and(|name| name == sym::self_);
if is_self { if is_self {
let mut this_pat = make::ident_pat(false, false, make::name("this")); let mut this_pat = make::ident_pat(false, false, make::name("this"));

View file

@ -57,7 +57,7 @@ pub(crate) fn move_module_to_file(acc: &mut Assists, ctx: &AssistContext<'_>) ->
if !parent_module.is_mod_rs(db) if !parent_module.is_mod_rs(db)
&& parent_module && parent_module
.attrs(db) .attrs(db)
.by_key(&sym::path) .by_key(sym::path)
.string_value_unescape() .string_value_unescape()
.is_none() => .is_none() =>
{ {

View file

@ -181,8 +181,8 @@ impl WrapperKind {
fn symbol(&self) -> hir::Symbol { fn symbol(&self) -> hir::Symbol {
match self { match self {
WrapperKind::Option => hir::sym::Option.clone(), WrapperKind::Option => hir::sym::Option,
WrapperKind::Result => hir::sym::Result.clone(), WrapperKind::Result => hir::sym::Result,
} }
} }
} }

View file

@ -631,8 +631,7 @@ fn enum_variants_with_paths(
let mut process_variant = |variant: Variant| { let mut process_variant = |variant: Variant| {
let self_path = hir::ModPath::from_segments( let self_path = hir::ModPath::from_segments(
hir::PathKind::Plain, hir::PathKind::Plain,
iter::once(Name::new_symbol_root(sym::Self_.clone())) iter::once(Name::new_symbol_root(sym::Self_)).chain(iter::once(variant.name(ctx.db))),
.chain(iter::once(variant.name(ctx.db))),
); );
cb(acc, ctx, variant, self_path); cb(acc, ctx, variant, self_path);

View file

@ -260,7 +260,7 @@ pub(crate) fn complete_expr_path(
path_ctx, path_ctx,
strukt, strukt,
None, None,
Some(Name::new_symbol_root(sym::Self_.clone())), Some(Name::new_symbol_root(sym::Self_)),
); );
} }
} }
@ -280,7 +280,7 @@ pub(crate) fn complete_expr_path(
ctx, ctx,
un, un,
None, None,
Some(Name::new_symbol_root(sym::Self_.clone())), Some(Name::new_symbol_root(sym::Self_)),
); );
} }
} }

View file

@ -31,13 +31,13 @@ pub(crate) fn complete_lifetime(
acc.add_lifetime(ctx, name); acc.add_lifetime(ctx, name);
} }
}); });
acc.add_lifetime(ctx, Name::new_symbol_root(sym::tick_static.clone())); acc.add_lifetime(ctx, Name::new_symbol_root(sym::tick_static));
if !in_lifetime_param_bound if !in_lifetime_param_bound
&& def.is_some_and(|def| { && def.is_some_and(|def| {
!matches!(def, hir::GenericDef::Function(_) | hir::GenericDef::Impl(_)) !matches!(def, hir::GenericDef::Function(_) | hir::GenericDef::Impl(_))
}) })
{ {
acc.add_lifetime(ctx, Name::new_symbol_root(sym::tick_underscore.clone())); acc.add_lifetime(ctx, Name::new_symbol_root(sym::tick_underscore));
} }
} }

View file

@ -92,7 +92,7 @@ impl<'a> RenderContext<'a> {
fn is_deprecated(&self, def: impl HasAttrs) -> bool { fn is_deprecated(&self, def: impl HasAttrs) -> bool {
let attrs = def.attrs(self.db()); let attrs = def.attrs(self.db());
attrs.by_key(&sym::deprecated).exists() attrs.by_key(sym::deprecated).exists()
} }
fn is_deprecated_assoc_item(&self, as_assoc_item: impl AsAssocItem) -> bool { fn is_deprecated_assoc_item(&self, as_assoc_item: impl AsAssocItem) -> bool {

View file

@ -96,7 +96,7 @@ pub(crate) fn visible_fields(
.copied() .copied()
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let has_invisible_field = n_fields - fields.len() > 0; let has_invisible_field = n_fields - fields.len() > 0;
let is_foreign_non_exhaustive = item.attrs(ctx.db).by_key(&sym::non_exhaustive).exists() let is_foreign_non_exhaustive = item.attrs(ctx.db).by_key(sym::non_exhaustive).exists()
&& item.krate(ctx.db) != module.krate(); && item.krate(ctx.db) != module.krate();
let fields_omitted = has_invisible_field || is_foreign_non_exhaustive; let fields_omitted = has_invisible_field || is_foreign_non_exhaustive;
Some((fields, fields_omitted)) Some((fields, fields_omitted))

View file

@ -93,7 +93,7 @@ pub fn docs_with_rangemap(
attrs: &AttrsWithOwner, attrs: &AttrsWithOwner,
) -> Option<(Documentation, DocsRangeMap)> { ) -> Option<(Documentation, DocsRangeMap)> {
let docs = attrs let docs = attrs
.by_key(&sym::doc) .by_key(sym::doc)
.attrs() .attrs()
.filter_map(|attr| attr.string_value_unescape().map(|s| (s, attr.id))); .filter_map(|attr| attr.string_value_unescape().map(|s| (s, attr.id)));
let indent = doc_indent(attrs); let indent = doc_indent(attrs);
@ -135,7 +135,7 @@ pub fn docs_with_rangemap(
} }
pub fn docs_from_attrs(attrs: &hir::Attrs) -> Option<String> { pub fn docs_from_attrs(attrs: &hir::Attrs) -> Option<String> {
let docs = attrs.by_key(&sym::doc).attrs().filter_map(|attr| attr.string_value_unescape()); let docs = attrs.by_key(sym::doc).attrs().filter_map(|attr| attr.string_value_unescape());
let indent = doc_indent(attrs); let indent = doc_indent(attrs);
let mut buf = String::new(); let mut buf = String::new();
for doc in docs { for doc in docs {
@ -266,7 +266,7 @@ fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
fn doc_indent(attrs: &hir::Attrs) -> usize { fn doc_indent(attrs: &hir::Attrs) -> usize {
let mut min = !0; let mut min = !0;
for val in attrs.by_key(&sym::doc).attrs().filter_map(|attr| attr.string_value_unescape()) { for val in attrs.by_key(sym::doc).attrs().filter_map(|attr| attr.string_value_unescape()) {
if let Some(m) = if let Some(m) =
val.lines().filter_map(|line| line.chars().position(|c| !c.is_whitespace())).min() val.lines().filter_map(|line| line.chars().position(|c| !c.is_whitespace())).min()
{ {

View file

@ -369,7 +369,7 @@ impl Definition {
if let Definition::Macro(macro_def) = self { if let Definition::Macro(macro_def) = self {
return match macro_def.kind(db) { return match macro_def.kind(db) {
hir::MacroKind::Declarative => { hir::MacroKind::Declarative => {
if macro_def.attrs(db).by_key(&sym::macro_export).exists() { if macro_def.attrs(db).by_key(sym::macro_export).exists() {
SearchScope::reverse_dependencies(db, module.krate()) SearchScope::reverse_dependencies(db, module.krate())
} else { } else {
SearchScope::krate(db, module.krate()) SearchScope::krate(db, module.krate())

View file

@ -217,7 +217,7 @@ fn get_default_constructor(
let has_new_func = ty let has_new_func = ty
.iterate_assoc_items(ctx.sema.db, krate, |assoc_item| { .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| {
if let AssocItem::Function(func) = assoc_item { if let AssocItem::Function(func) = assoc_item {
if func.name(ctx.sema.db) == sym::new.clone() if func.name(ctx.sema.db) == sym::new
&& func.assoc_fn_params(ctx.sema.db).is_empty() && func.assoc_fn_params(ctx.sema.db).is_empty()
{ {
return Some(()); return Some(());

View file

@ -597,7 +597,7 @@ fn filename_and_frag_for_def(
Definition::Module(m) => match m.name(db) { Definition::Module(m) => match m.name(db) {
// `#[doc(keyword = "...")]` is internal used only by rust compiler // `#[doc(keyword = "...")]` is internal used only by rust compiler
Some(name) => { Some(name) => {
match m.attrs(db).by_key(&sym::doc).find_string_value_in_tt(&sym::keyword) { match m.attrs(db).by_key(sym::doc).find_string_value_in_tt(sym::keyword) {
Some(kw) => { Some(kw) => {
format!("keyword.{}.html", kw) format!("keyword.{}.html", kw)
} }

View file

@ -797,7 +797,7 @@ fn hint_iterator(
if ty.impls_trait(db, iter_trait, &[]) { if ty.impls_trait(db, iter_trait, &[]) {
let assoc_type_item = iter_trait.items(db).into_iter().find_map(|item| match item { let assoc_type_item = iter_trait.items(db).into_iter().find_map(|item| match item {
hir::AssocItem::TypeAlias(alias) if alias.name(db) == sym::Item.clone() => Some(alias), hir::AssocItem::TypeAlias(alias) if alias.name(db) == sym::Item => Some(alias),
_ => None, _ => None,
})?; })?;
if let Some(ty) = ty.normalize_trait_assoc_type(db, &[], assoc_type_item) { if let Some(ty) = ty.normalize_trait_assoc_type(db, &[], assoc_type_item) {

View file

@ -249,7 +249,7 @@ impl Analysis {
TryFrom::try_from(&*std::env::current_dir().unwrap().as_path().to_string_lossy()) TryFrom::try_from(&*std::env::current_dir().unwrap().as_path().to_string_lossy())
.unwrap(), .unwrap(),
); );
cfg_options.insert_atom(sym::test.clone()); cfg_options.insert_atom(sym::test);
crate_graph.add_crate_root( crate_graph.add_crate_root(
file_id, file_id,
Edition::CURRENT, Edition::CURRENT,

View file

@ -160,7 +160,7 @@ pub(super) fn doc_comment(
let mut new_comments = Vec::new(); let mut new_comments = Vec::new();
let mut string; let mut string;
for attr in attributes.by_key(&sym::doc).attrs() { for attr in attributes.by_key(sym::doc).attrs() {
let InFile { file_id, value: src } = attrs_source_map.source_of(attr); let InFile { file_id, value: src } = attrs_source_map.source_of(attr);
if file_id != src_file_id { if file_id != src_file_id {
continue; continue;

View file

@ -13,35 +13,18 @@ use crate::{
macro_rules! define_symbols { macro_rules! define_symbols {
(@WITH_NAME: $($alias:ident = $value:literal,)* @PLAIN: $($name:ident,)*) => { (@WITH_NAME: $($alias:ident = $value:literal,)* @PLAIN: $($name:ident,)*) => {
// We define symbols as both `const`s and `static`s because some const code requires const symbols, // The strings should be in `static`s so that symbol equality holds.
// but code from before the transition relies on the lifetime of the predefined symbols and making them
// `const`s make it error (because now they're temporaries). In the future we probably should only
// use consts.
/// Predefined symbols as `const`s (instead of the default `static`s).
pub mod consts {
use super::{Symbol, TaggedArcPtr};
// The strings should be in `static`s so that symbol equality holds.
$(
pub const $name: Symbol = {
static SYMBOL_STR: &str = stringify!($name);
Symbol { repr: TaggedArcPtr::non_arc(&SYMBOL_STR) }
};
)*
$(
pub const $alias: Symbol = {
static SYMBOL_STR: &str = $value;
Symbol { repr: TaggedArcPtr::non_arc(&SYMBOL_STR) }
};
)*
}
$( $(
pub static $name: Symbol = consts::$name; pub const $name: Symbol = {
static SYMBOL_STR: &str = stringify!($name);
Symbol { repr: TaggedArcPtr::non_arc(&SYMBOL_STR) }
};
)* )*
$( $(
pub static $alias: Symbol = consts::$alias; pub const $alias: Symbol = {
static SYMBOL_STR: &str = $value;
Symbol { repr: TaggedArcPtr::non_arc(&SYMBOL_STR) }
};
)* )*

View file

@ -80,7 +80,7 @@ impl<'t> Bindings<'t> {
| MetaVarKind::Expr(_) | MetaVarKind::Expr(_)
| MetaVarKind::Ident => { | MetaVarKind::Ident => {
builder.push(tt::Leaf::Ident(tt::Ident { builder.push(tt::Leaf::Ident(tt::Ident {
sym: sym::missing.clone(), sym: sym::missing,
span, span,
is_raw: tt::IdentIsRaw::No, is_raw: tt::IdentIsRaw::No,
})); }));
@ -93,7 +93,7 @@ impl<'t> Bindings<'t> {
spacing: tt::Spacing::Joint, spacing: tt::Spacing::Joint,
}), }),
tt::Leaf::Ident(tt::Ident { tt::Leaf::Ident(tt::Ident {
sym: sym::missing.clone(), sym: sym::missing,
span, span,
is_raw: tt::IdentIsRaw::No, is_raw: tt::IdentIsRaw::No,
}), }),
@ -101,7 +101,7 @@ impl<'t> Bindings<'t> {
} }
MetaVarKind::Literal => { MetaVarKind::Literal => {
builder.push(tt::Leaf::Ident(tt::Ident { builder.push(tt::Leaf::Ident(tt::Ident {
sym: sym::missing.clone(), sym: sym::missing,
span, span,
is_raw: tt::IdentIsRaw::No, is_raw: tt::IdentIsRaw::No,
})); }));

View file

@ -228,7 +228,7 @@ fn next_op(
tt::Leaf::Ident(ident) if ident.sym == sym::crate_ => { tt::Leaf::Ident(ident) if ident.sym == sym::crate_ => {
// We simply produce identifier `$crate` here. And it will be resolved when lowering ast to Path. // We simply produce identifier `$crate` here. And it will be resolved when lowering ast to Path.
Op::Ident(tt::Ident { Op::Ident(tt::Ident {
sym: sym::dollar_crate.clone(), sym: sym::dollar_crate,
span: ident.span, span: ident.span,
is_raw: tt::IdentIsRaw::No, is_raw: tt::IdentIsRaw::No,
}) })

View file

@ -284,14 +284,14 @@ mod tests {
}, },
); );
builder.push(Leaf::Literal(Literal { builder.push(Leaf::Literal(Literal {
symbol: sym::INTEGER_0.clone(), symbol: sym::INTEGER_0,
span: Span { span: Span {
range: TextRange::at(TextSize::new(15), TextSize::of("0u32")), range: TextRange::at(TextSize::new(15), TextSize::of("0u32")),
anchor, anchor,
ctx: SyntaxContext::root(Edition::CURRENT), ctx: SyntaxContext::root(Edition::CURRENT),
}, },
kind: tt::LitKind::Integer, kind: tt::LitKind::Integer,
suffix: Some(sym::u32.clone()), suffix: Some(sym::u32),
})); }));
builder.close(Span { builder.close(Span {
range: TextRange::at(TextSize::new(19), TextSize::of('}')), range: TextRange::at(TextSize::new(19), TextSize::of('}')),

View file

@ -140,7 +140,7 @@ fn check_crate_graph(crate_graph: CrateGraphBuilder, expect: ExpectFile) {
#[test] #[test]
fn cargo_hello_world_project_model_with_wildcard_overrides() { fn cargo_hello_world_project_model_with_wildcard_overrides() {
let cfg_overrides = CfgOverrides { let cfg_overrides = CfgOverrides {
global: CfgDiff::new(Vec::new(), vec![CfgAtom::Flag(sym::test.clone())]), global: CfgDiff::new(Vec::new(), vec![CfgAtom::Flag(sym::test)]),
selective: Default::default(), selective: Default::default(),
}; };
let (crate_graph, _proc_macros) = let (crate_graph, _proc_macros) =
@ -159,7 +159,7 @@ fn cargo_hello_world_project_model_with_selective_overrides() {
global: Default::default(), global: Default::default(),
selective: std::iter::once(( selective: std::iter::once((
"libc".to_owned(), "libc".to_owned(),
CfgDiff::new(Vec::new(), vec![CfgAtom::Flag(sym::test.clone())]), CfgDiff::new(Vec::new(), vec![CfgAtom::Flag(sym::test)]),
)) ))
.collect(), .collect(),
}; };

View file

@ -1036,9 +1036,9 @@ fn project_json_to_crate_graph(
if *is_workspace_member { if *is_workspace_member {
if set_test && !is_sysroot { if set_test && !is_sysroot {
// Add test cfg for local crates // Add test cfg for local crates
cfg_options.insert_atom(sym::test.clone()); cfg_options.insert_atom(sym::test);
} }
cfg_options.insert_atom(sym::rust_analyzer.clone()); cfg_options.insert_atom(sym::rust_analyzer);
} }
override_cfg.apply( override_cfg.apply(
@ -1159,9 +1159,9 @@ fn cargo_to_crate_graph(
if cargo[pkg].is_local { if cargo[pkg].is_local {
if set_test && !cargo.is_sysroot() { if set_test && !cargo.is_sysroot() {
// Add test cfg for local crates // Add test cfg for local crates
cfg_options.insert_atom(sym::test.clone()); cfg_options.insert_atom(sym::test);
} }
cfg_options.insert_atom(sym::rust_analyzer.clone()); cfg_options.insert_atom(sym::rust_analyzer);
} }
override_cfg.apply(&mut cfg_options, &cargo[pkg].name); override_cfg.apply(&mut cfg_options, &cargo[pkg].name);
@ -1351,9 +1351,9 @@ fn detached_file_to_crate_graph(
let mut cfg_options = CfgOptions::from_iter(rustc_cfg); let mut cfg_options = CfgOptions::from_iter(rustc_cfg);
if set_test { if set_test {
cfg_options.insert_atom(sym::test.clone()); cfg_options.insert_atom(sym::test);
} }
cfg_options.insert_atom(sym::rust_analyzer.clone()); cfg_options.insert_atom(sym::rust_analyzer);
override_cfg.apply(&mut cfg_options, ""); override_cfg.apply(&mut cfg_options, "");
let cfg_options = cfg_options; let cfg_options = cfg_options;
@ -1519,16 +1519,17 @@ fn add_target_crate_root(
None None
} else { } else {
let mut potential_cfg_options = cfg_options.clone(); let mut potential_cfg_options = cfg_options.clone();
potential_cfg_options.extend(pkg.features.iter().map(|feat| CfgAtom::KeyValue { potential_cfg_options.extend(
key: sym::feature.clone(), pkg.features
value: Symbol::intern(feat.0), .iter()
})); .map(|feat| CfgAtom::KeyValue { key: sym::feature, value: Symbol::intern(feat.0) }),
);
Some(potential_cfg_options) Some(potential_cfg_options)
}; };
let cfg_options = { let cfg_options = {
let mut opts = cfg_options; let mut opts = cfg_options;
for feature in pkg.active_features.iter() { for feature in pkg.active_features.iter() {
opts.insert_key_value(sym::feature.clone(), Symbol::intern(feature)); opts.insert_key_value(sym::feature, Symbol::intern(feature));
} }
if let Some(cfgs) = build_data.map(|(it, _)| &it.cfgs) { if let Some(cfgs) = build_data.map(|(it, _)| &it.cfgs) {
opts.extend(cfgs.iter().cloned()); opts.extend(cfgs.iter().cloned());
@ -1662,11 +1663,11 @@ fn sysroot_to_crate_graph(
&CfgOverrides { &CfgOverrides {
global: CfgDiff::new( global: CfgDiff::new(
vec![ vec![
CfgAtom::Flag(sym::debug_assertions.clone()), CfgAtom::Flag(sym::debug_assertions),
CfgAtom::Flag(sym::miri.clone()), CfgAtom::Flag(sym::miri),
CfgAtom::Flag(sym::bootstrap.clone()), CfgAtom::Flag(sym::bootstrap),
], ],
vec![CfgAtom::Flag(sym::test.clone())], vec![CfgAtom::Flag(sym::test)],
), ),
..Default::default() ..Default::default()
}, },
@ -1686,10 +1687,7 @@ fn sysroot_to_crate_graph(
&FxHashMap::default(), &FxHashMap::default(),
&CfgOverrides { &CfgOverrides {
global: CfgDiff::new( global: CfgDiff::new(
vec![ vec![CfgAtom::Flag(sym::debug_assertions), CfgAtom::Flag(sym::miri)],
CfgAtom::Flag(sym::debug_assertions.clone()),
CfgAtom::Flag(sym::miri.clone()),
],
vec![], vec![],
), ),
..Default::default() ..Default::default()
@ -1705,8 +1703,8 @@ fn sysroot_to_crate_graph(
let cfg_options = { let cfg_options = {
let mut cfg_options = CfgOptions::default(); let mut cfg_options = CfgOptions::default();
cfg_options.extend(rustc_cfg); cfg_options.extend(rustc_cfg);
cfg_options.insert_atom(sym::debug_assertions.clone()); cfg_options.insert_atom(sym::debug_assertions);
cfg_options.insert_atom(sym::miri.clone()); cfg_options.insert_atom(sym::miri);
cfg_options cfg_options
}; };
let sysroot_crates: FxHashMap< let sysroot_crates: FxHashMap<

View file

@ -59,7 +59,7 @@ impl flags::AnalysisStats {
all_targets: true, all_targets: true,
set_test: !self.no_test, set_test: !self.no_test,
cfg_overrides: CfgOverrides { cfg_overrides: CfgOverrides {
global: CfgDiff::new(vec![CfgAtom::Flag(hir::sym::miri.clone())], vec![]), global: CfgDiff::new(vec![CfgAtom::Flag(hir::sym::miri)], vec![]),
selective: Default::default(), selective: Default::default(),
}, },
..Default::default() ..Default::default()