Auto merge of #74175 - nnethercote:more-static-symbols, r=oli-obk

More static symbols

These commits add some more static symbols and convert lots of places to use them.

r? @oli-obk
This commit is contained in:
bors 2020-07-15 00:16:25 +00:00
commit 567ad7455d
67 changed files with 982 additions and 736 deletions

View File

@ -9,7 +9,7 @@ pub enum AllocatorKind {
}
impl AllocatorKind {
pub fn fn_name(&self, base: &str) -> String {
pub fn fn_name(&self, base: Symbol) -> String {
match *self {
AllocatorKind::Global => format!("__rg_{}", base),
AllocatorKind::Default => format!("__rdl_{}", base),
@ -26,29 +26,29 @@ pub enum AllocatorTy {
}
pub struct AllocatorMethod {
pub name: &'static str,
pub name: Symbol,
pub inputs: &'static [AllocatorTy],
pub output: AllocatorTy,
}
pub static ALLOCATOR_METHODS: &[AllocatorMethod] = &[
AllocatorMethod {
name: "alloc",
name: sym::alloc,
inputs: &[AllocatorTy::Layout],
output: AllocatorTy::ResultPtr,
},
AllocatorMethod {
name: "dealloc",
name: sym::dealloc,
inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout],
output: AllocatorTy::Unit,
},
AllocatorMethod {
name: "realloc",
name: sym::realloc,
inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout, AllocatorTy::Usize],
output: AllocatorTy::ResultPtr,
},
AllocatorMethod {
name: "alloc_zeroed",
name: sym::alloc_zeroed,
inputs: &[AllocatorTy::Layout],
output: AllocatorTy::ResultPtr,
},
@ -70,7 +70,7 @@ pub fn global_allocator_spans(krate: &ast::Crate) -> Vec<Span> {
}
}
let name = Symbol::intern(&AllocatorKind::Global.fn_name("alloc"));
let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::alloc));
let mut f = Finder { name, spans: Vec::new() };
visit::walk_crate(&mut f, krate);
f.spans

View File

@ -2,7 +2,7 @@ pub use CommentStyle::*;
use crate::ast;
use rustc_span::source_map::SourceMap;
use rustc_span::{BytePos, CharPos, FileName, Pos};
use rustc_span::{BytePos, CharPos, FileName, Pos, Symbol};
use log::debug;
@ -52,7 +52,8 @@ pub fn is_doc_comment(s: &str) -> bool {
|| s.starts_with("/*!")
}
pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
pub fn doc_comment_style(comment: Symbol) -> ast::AttrStyle {
let comment = &comment.as_str();
assert!(is_doc_comment(comment));
if comment.starts_with("//!") || comment.starts_with("/*!") {
ast::AttrStyle::Inner
@ -61,7 +62,9 @@ pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
}
}
pub fn strip_doc_comment_decoration(comment: &str) -> String {
pub fn strip_doc_comment_decoration(comment: Symbol) -> String {
let comment = &comment.as_str();
/// remove whitespace-only lines from the start/end of lines
fn vertical_trim(lines: Vec<String>) -> Vec<String> {
let mut i = 0;

View File

@ -1,47 +1,58 @@
use super::*;
use crate::with_default_session_globals;
#[test]
fn test_block_doc_comment_1() {
let comment = "/**\n * Test \n ** Test\n * Test\n*/";
let stripped = strip_doc_comment_decoration(comment);
assert_eq!(stripped, " Test \n* Test\n Test");
with_default_session_globals(|| {
let comment = "/**\n * Test \n ** Test\n * Test\n*/";
let stripped = strip_doc_comment_decoration(Symbol::intern(comment));
assert_eq!(stripped, " Test \n* Test\n Test");
})
}
#[test]
fn test_block_doc_comment_2() {
let comment = "/**\n * Test\n * Test\n*/";
let stripped = strip_doc_comment_decoration(comment);
assert_eq!(stripped, " Test\n Test");
with_default_session_globals(|| {
let comment = "/**\n * Test\n * Test\n*/";
let stripped = strip_doc_comment_decoration(Symbol::intern(comment));
assert_eq!(stripped, " Test\n Test");
})
}
#[test]
fn test_block_doc_comment_3() {
let comment = "/**\n let a: *i32;\n *a = 5;\n*/";
let stripped = strip_doc_comment_decoration(comment);
assert_eq!(stripped, " let a: *i32;\n *a = 5;");
with_default_session_globals(|| {
let comment = "/**\n let a: *i32;\n *a = 5;\n*/";
let stripped = strip_doc_comment_decoration(Symbol::intern(comment));
assert_eq!(stripped, " let a: *i32;\n *a = 5;");
})
}
#[test]
fn test_block_doc_comment_4() {
let comment = "/*******************\n test\n *********************/";
let stripped = strip_doc_comment_decoration(comment);
assert_eq!(stripped, " test");
with_default_session_globals(|| {
let comment = "/*******************\n test\n *********************/";
let stripped = strip_doc_comment_decoration(Symbol::intern(comment));
assert_eq!(stripped, " test");
})
}
#[test]
fn test_line_doc_comment() {
let stripped = strip_doc_comment_decoration("/// test");
assert_eq!(stripped, " test");
let stripped = strip_doc_comment_decoration("///! test");
assert_eq!(stripped, " test");
let stripped = strip_doc_comment_decoration("// test");
assert_eq!(stripped, " test");
let stripped = strip_doc_comment_decoration("// test");
assert_eq!(stripped, " test");
let stripped = strip_doc_comment_decoration("///test");
assert_eq!(stripped, "test");
let stripped = strip_doc_comment_decoration("///!test");
assert_eq!(stripped, "test");
let stripped = strip_doc_comment_decoration("//test");
assert_eq!(stripped, "test");
with_default_session_globals(|| {
let stripped = strip_doc_comment_decoration(Symbol::intern("/// test"));
assert_eq!(stripped, " test");
let stripped = strip_doc_comment_decoration(Symbol::intern("///! test"));
assert_eq!(stripped, " test");
let stripped = strip_doc_comment_decoration(Symbol::intern("// test"));
assert_eq!(stripped, " test");
let stripped = strip_doc_comment_decoration(Symbol::intern("// test"));
assert_eq!(stripped, " test");
let stripped = strip_doc_comment_decoration(Symbol::intern("///test"));
assert_eq!(stripped, "test");
let stripped = strip_doc_comment_decoration(Symbol::intern("///!test"));
assert_eq!(stripped, "test");
let stripped = strip_doc_comment_decoration(Symbol::intern("//test"));
assert_eq!(stripped, "test");
})
}

View File

@ -47,12 +47,13 @@ pub fn lev_distance(a: &str, b: &str) -> usize {
/// a lower(upper)case letters mismatch.
pub fn find_best_match_for_name<'a, T>(
iter_names: T,
lookup: &str,
lookup: Symbol,
dist: Option<usize>,
) -> Option<Symbol>
where
T: Iterator<Item = &'a Symbol>,
{
let lookup = &lookup.as_str();
let max_dist = dist.map_or_else(|| cmp::max(lookup.len(), 3) / 3, |d| d);
let name_vec: Vec<&Symbol> = iter_names.collect();

View File

@ -25,31 +25,34 @@ fn test_find_best_match_for_name() {
with_default_session_globals(|| {
let input = vec![Symbol::intern("aaab"), Symbol::intern("aaabc")];
assert_eq!(
find_best_match_for_name(input.iter(), "aaaa", None),
find_best_match_for_name(input.iter(), Symbol::intern("aaaa"), None),
Some(Symbol::intern("aaab"))
);
assert_eq!(find_best_match_for_name(input.iter(), "1111111111", None), None);
assert_eq!(
find_best_match_for_name(input.iter(), Symbol::intern("1111111111"), None),
None
);
let input = vec![Symbol::intern("aAAA")];
assert_eq!(
find_best_match_for_name(input.iter(), "AAAA", None),
find_best_match_for_name(input.iter(), Symbol::intern("AAAA"), None),
Some(Symbol::intern("aAAA"))
);
let input = vec![Symbol::intern("AAAA")];
// Returns None because `lev_distance > max_dist / 3`
assert_eq!(find_best_match_for_name(input.iter(), "aaaa", None), None);
assert_eq!(find_best_match_for_name(input.iter(), Symbol::intern("aaaa"), None), None);
let input = vec![Symbol::intern("AAAA")];
assert_eq!(
find_best_match_for_name(input.iter(), "aaaa", Some(4)),
find_best_match_for_name(input.iter(), Symbol::intern("aaaa"), Some(4)),
Some(Symbol::intern("AAAA"))
);
let input = vec![Symbol::intern("a_longer_variable_name")];
assert_eq!(
find_best_match_for_name(input.iter(), "a_variable_longer_name", None),
find_best_match_for_name(input.iter(), Symbol::intern("a_variable_longer_name"), None),
Some(Symbol::intern("a_longer_variable_name"))
);
})

View File

@ -533,6 +533,10 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
self.word(st)
}
fn print_symbol(&mut self, sym: Symbol, style: ast::StrStyle) {
self.print_string(&sym.as_str(), style);
}
fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) {
self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
}
@ -2061,7 +2065,7 @@ impl<'a> State<'a> {
let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r
{
InlineAsmRegOrRegClass::Reg(r) => {
s.print_string(&r.as_str(), ast::StrStyle::Cooked)
s.print_symbol(*r, ast::StrStyle::Cooked)
}
InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
};
@ -2155,7 +2159,7 @@ impl<'a> State<'a> {
ast::ExprKind::LlvmInlineAsm(ref a) => {
self.s.word("llvm_asm!");
self.popen();
self.print_string(&a.asm.as_str(), a.asm_str_style);
self.print_symbol(a.asm, a.asm_str_style);
self.word_space(":");
self.commasep(Inconsistent, &a.outputs, |s, out| {
@ -2175,7 +2179,7 @@ impl<'a> State<'a> {
self.word_space(":");
self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
s.print_string(&co.as_str(), ast::StrStyle::Cooked);
s.print_symbol(co, ast::StrStyle::Cooked);
s.popen();
s.print_expr(o);
s.pclose();
@ -2183,8 +2187,8 @@ impl<'a> State<'a> {
self.s.space();
self.word_space(":");
self.commasep(Inconsistent, &a.clobbers, |s, co| {
s.print_string(&co.as_str(), ast::StrStyle::Cooked);
self.commasep(Inconsistent, &a.clobbers, |s, &co| {
s.print_symbol(co, ast::StrStyle::Cooked);
});
let mut options = vec![];

View File

@ -1041,10 +1041,10 @@ pub fn find_transparency(
break;
} else if let Some(value) = attr.value_str() {
transparency = Some((
match &*value.as_str() {
"transparent" => Transparency::Transparent,
"semitransparent" => Transparency::SemiTransparent,
"opaque" => Transparency::Opaque,
match value {
sym::transparent => Transparency::Transparent,
sym::semitransparent => Transparency::SemiTransparent,
sym::opaque => Transparency::Opaque,
_ => {
error = Some(TransparencyError::UnknownTransparency(value, attr.span));
continue;

View File

@ -84,7 +84,7 @@ pub fn expand_deriving_clone(
is_unsafe: false,
supports_unions: true,
methods: vec![MethodDef {
name: "clone",
name: sym::clone,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: Vec::new(),

View File

@ -28,7 +28,7 @@ pub fn expand_deriving_eq(
is_unsafe: false,
supports_unions: true,
methods: vec![MethodDef {
name: "assert_receiver_is_total_eq",
name: sym::assert_receiver_is_total_eq,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec![],

View File

@ -26,7 +26,7 @@ pub fn expand_deriving_ord(
is_unsafe: false,
supports_unions: false,
methods: vec![MethodDef {
name: "cmp",
name: sym::cmp,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec![(borrowed_self(), "other")],

View File

@ -92,9 +92,9 @@ pub fn expand_deriving_partial_eq(
// avoid defining `ne` if we can
// c-like enums, enums without any fields and structs without fields
// can safely define only `eq`.
let mut methods = vec![md!("eq", cs_eq)];
let mut methods = vec![md!(sym::eq, cs_eq)];
if !is_type_without_fields(item) {
methods.push(md!("ne", cs_ne));
methods.push(md!(sym::ne, cs_ne));
}
let trait_def = TraitDef {

View File

@ -49,7 +49,7 @@ pub fn expand_deriving_partial_ord(
let attrs = vec![cx.attribute(inline)];
let partial_cmp_def = MethodDef {
name: "partial_cmp",
name: sym::partial_cmp,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec![(borrowed_self(), "other")],
@ -70,10 +70,10 @@ pub fn expand_deriving_partial_ord(
} else {
vec![
partial_cmp_def,
md!("lt", true, false),
md!("le", true, true),
md!("gt", false, false),
md!("ge", false, true),
md!(sym::lt, true, false),
md!(sym::le, true, true),
md!(sym::gt, false, false),
md!(sym::ge, false, true),
]
};
@ -108,14 +108,14 @@ pub fn some_ordering_collapsed(
) -> P<ast::Expr> {
let lft = cx.expr_ident(span, self_arg_tags[0]);
let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1]));
let op_str = match op {
PartialCmpOp => "partial_cmp",
LtOp => "lt",
LeOp => "le",
GtOp => "gt",
GeOp => "ge",
let op_sym = match op {
PartialCmpOp => sym::partial_cmp,
LtOp => sym::lt,
LeOp => sym::le,
GtOp => sym::gt,
GeOp => sym::ge,
};
cx.expr_method_call(span, lft, cx.ident_of(op_str, span), vec![rgt])
cx.expr_method_call(span, lft, Ident::new(op_sym, span), vec![rgt])
}
pub fn cs_partial_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> P<Expr> {

View File

@ -29,7 +29,7 @@ pub fn expand_deriving_debug(
is_unsafe: false,
supports_unions: false,
methods: vec![MethodDef {
name: "fmt",
name: sym::fmt,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec![(fmtr, "f")],

View File

@ -8,7 +8,7 @@ use rustc_ast::ast;
use rustc_ast::ast::{Expr, MetaItem, Mutability};
use rustc_ast::ptr::P;
use rustc_expand::base::{Annotatable, ExtCtxt};
use rustc_span::symbol::Symbol;
use rustc_span::symbol::{sym, Symbol};
use rustc_span::Span;
pub fn expand_deriving_rustc_decodable(
@ -30,7 +30,7 @@ pub fn expand_deriving_rustc_decodable(
is_unsafe: false,
supports_unions: false,
methods: vec![MethodDef {
name: "decode",
name: sym::decode,
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec![(

View File

@ -27,7 +27,7 @@ pub fn expand_deriving_default(
is_unsafe: false,
supports_unions: false,
methods: vec![MethodDef {
name: "default",
name: kw::Default,
generics: LifetimeBounds::empty(),
explicit_self: None,
args: Vec::new(),

View File

@ -92,7 +92,7 @@ use crate::deriving::pathvec_std;
use rustc_ast::ast::{Expr, ExprKind, MetaItem, Mutability};
use rustc_ast::ptr::P;
use rustc_expand::base::{Annotatable, ExtCtxt};
use rustc_span::symbol::Symbol;
use rustc_span::symbol::{sym, Symbol};
use rustc_span::Span;
pub fn expand_deriving_rustc_encodable(
@ -114,7 +114,7 @@ pub fn expand_deriving_rustc_encodable(
is_unsafe: false,
supports_unions: false,
methods: vec![MethodDef {
name: "encode",
name: sym::encode,
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec![(

View File

@ -226,7 +226,7 @@ pub struct TraitDef<'a> {
pub struct MethodDef<'a> {
/// name of the method
pub name: &'a str,
pub name: Symbol,
/// List of generics, e.g., `R: rand::Rng`
pub generics: LifetimeBounds<'a>,
@ -681,7 +681,7 @@ impl<'a> TraitDef<'a> {
let opt_trait_ref = Some(trait_ref);
let unused_qual = {
let word = rustc_ast::attr::mk_nested_word_item(Ident::new(
Symbol::intern("unused_qualifications"),
sym::unused_qualifications,
self.span,
));
let list = rustc_ast::attr::mk_list_item(Ident::new(sym::allow, self.span), vec![word]);
@ -818,7 +818,7 @@ impl<'a> MethodDef<'a> {
) -> P<Expr> {
let substructure = Substructure {
type_ident,
method_ident: cx.ident_of(self.name, trait_.span),
method_ident: Ident::new(self.name, trait_.span),
self_args,
nonself_args,
fields,
@ -913,7 +913,7 @@ impl<'a> MethodDef<'a> {
let ret_type = self.get_ret_ty(cx, trait_, generics, type_ident);
let method_ident = cx.ident_of(self.name, trait_.span);
let method_ident = Ident::new(self.name, trait_.span);
let fn_decl = cx.fn_decl(args, ast::FnRetTy::Ty(ret_type));
let body_block = cx.block_expr(body);
@ -1315,7 +1315,7 @@ impl<'a> MethodDef<'a> {
// Since we know that all the arguments will match if we reach
// the match expression we add the unreachable intrinsics as the
// result of the catch all which should help llvm in optimizing it
Some(deriving::call_intrinsic(cx, sp, "unreachable", vec![]))
Some(deriving::call_intrinsic(cx, sp, sym::unreachable, vec![]))
}
_ => None,
};
@ -1363,7 +1363,7 @@ impl<'a> MethodDef<'a> {
for (&ident, self_arg) in vi_idents.iter().zip(&self_args) {
let self_addr = cx.expr_addr_of(sp, self_arg.clone());
let variant_value =
deriving::call_intrinsic(cx, sp, "discriminant_value", vec![self_addr]);
deriving::call_intrinsic(cx, sp, sym::discriminant_value, vec![self_addr]);
let let_stmt = cx.stmt_let(sp, false, ident, variant_value);
index_let_stmts.push(let_stmt);
@ -1464,7 +1464,7 @@ impl<'a> MethodDef<'a> {
// derive Debug on such a type could here generate code
// that needs the feature gate enabled.)
deriving::call_intrinsic(cx, sp, "unreachable", vec![])
deriving::call_intrinsic(cx, sp, sym::unreachable, vec![])
} else {
// Final wrinkle: the self_args are expressions that deref
// down to desired places, but we cannot actually deref

View File

@ -29,7 +29,7 @@ pub fn expand_deriving_hash(
is_unsafe: false,
supports_unions: false,
methods: vec![MethodDef {
name: "hash",
name: sym::hash,
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec![(typaram, vec![path_std!(cx, hash::Hasher)])],
@ -73,7 +73,7 @@ fn hash_substructure(cx: &mut ExtCtxt<'_>, trait_span: Span, substr: &Substructu
let variant_value = deriving::call_intrinsic(
cx,
trait_span,
"discriminant_value",
sym::discriminant_value,
vec![cx.expr_self(trait_span)],
);

View File

@ -62,11 +62,11 @@ impl MultiItemModifier for BuiltinDerive {
fn call_intrinsic(
cx: &ExtCtxt<'_>,
span: Span,
intrinsic: &str,
intrinsic: Symbol,
args: Vec<P<ast::Expr>>,
) -> P<ast::Expr> {
let span = cx.with_def_site_ctxt(span);
let path = cx.std_path(&[sym::intrinsics, Symbol::intern(intrinsic)]);
let path = cx.std_path(&[sym::intrinsics, intrinsic]);
let call = cx.expr_call_global(span, path, args);
cx.expr_block(P(ast::Block {

View File

@ -79,12 +79,8 @@ impl AllocFnFactory<'_, '_> {
self.cx.stmt_item(self.span, item)
}
fn call_allocator(&self, method: &str, mut args: Vec<P<Expr>>) -> P<Expr> {
let method = self.cx.std_path(&[
Symbol::intern("alloc"),
Symbol::intern("GlobalAlloc"),
Symbol::intern(method),
]);
fn call_allocator(&self, method: Symbol, mut args: Vec<P<Expr>>) -> P<Expr> {
let method = self.cx.std_path(&[sym::alloc, sym::GlobalAlloc, method]);
let method = self.cx.expr_path(self.cx.path(self.span, method));
let allocator = self.cx.path_ident(self.span, self.global);
let allocator = self.cx.expr_path(allocator);
@ -115,11 +111,8 @@ impl AllocFnFactory<'_, '_> {
args.push(self.cx.param(self.span, size, ty_usize.clone()));
args.push(self.cx.param(self.span, align, ty_usize));
let layout_new = self.cx.std_path(&[
Symbol::intern("alloc"),
Symbol::intern("Layout"),
Symbol::intern("from_size_align_unchecked"),
]);
let layout_new =
self.cx.std_path(&[sym::alloc, sym::Layout, sym::from_size_align_unchecked]);
let layout_new = self.cx.expr_path(self.cx.path(self.span, layout_new));
let size = self.cx.expr_ident(self.span, size);
let align = self.cx.expr_ident(self.span, align);

View File

@ -164,10 +164,8 @@ impl MutVisitor for EntryPointCleaner {
EntryPointType::MainNamed | EntryPointType::MainAttr | EntryPointType::Start => item
.map(|ast::Item { id, ident, attrs, kind, vis, span, tokens }| {
let allow_ident = Ident::new(sym::allow, self.def_site);
let dc_nested = attr::mk_nested_word_item(Ident::from_str_and_span(
"dead_code",
self.def_site,
));
let dc_nested =
attr::mk_nested_word_item(Ident::new(sym::dead_code, self.def_site));
let allow_dead_code_item = attr::mk_list_item(allow_ident, vec![dc_nested]);
let allow_dead_code = attr::mk_attr_outer(allow_dead_code_item);
let attrs = attrs

View File

@ -658,7 +658,7 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
// `nontrapping-fptoint` target feature is activated. We'll use those if
// they are available.
if self.sess().target.target.arch == "wasm32"
&& self.sess().target_features.contains(&sym::nontrapping_fptoint)
&& self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
{
let src_ty = self.cx.val_ty(val);
let float_width = self.cx.float_width(src_ty);
@ -683,7 +683,7 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
// `nontrapping-fptoint` target feature is activated. We'll use those if
// they are available.
if self.sess().target.target.arch == "wasm32"
&& self.sess().target_features.contains(&sym::nontrapping_fptoint)
&& self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
{
let src_ty = self.cx.val_ty(val);
let float_width = self.cx.float_width(src_ty);

View File

@ -25,59 +25,59 @@ use rustc_middle::mir::Operand;
use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
use rustc_middle::ty::{self, Ty};
use rustc_middle::{bug, span_bug};
use rustc_span::Span;
use rustc_span::{sym, symbol::kw, Span, Symbol};
use rustc_target::abi::{self, HasDataLayout, LayoutOf, Primitive};
use rustc_target::spec::PanicStrategy;
use std::cmp::Ordering;
use std::iter;
fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: Symbol) -> Option<&'ll Value> {
let llvm_name = match name {
"sqrtf32" => "llvm.sqrt.f32",
"sqrtf64" => "llvm.sqrt.f64",
"powif32" => "llvm.powi.f32",
"powif64" => "llvm.powi.f64",
"sinf32" => "llvm.sin.f32",
"sinf64" => "llvm.sin.f64",
"cosf32" => "llvm.cos.f32",
"cosf64" => "llvm.cos.f64",
"powf32" => "llvm.pow.f32",
"powf64" => "llvm.pow.f64",
"expf32" => "llvm.exp.f32",
"expf64" => "llvm.exp.f64",
"exp2f32" => "llvm.exp2.f32",
"exp2f64" => "llvm.exp2.f64",
"logf32" => "llvm.log.f32",
"logf64" => "llvm.log.f64",
"log10f32" => "llvm.log10.f32",
"log10f64" => "llvm.log10.f64",
"log2f32" => "llvm.log2.f32",
"log2f64" => "llvm.log2.f64",
"fmaf32" => "llvm.fma.f32",
"fmaf64" => "llvm.fma.f64",
"fabsf32" => "llvm.fabs.f32",
"fabsf64" => "llvm.fabs.f64",
"minnumf32" => "llvm.minnum.f32",
"minnumf64" => "llvm.minnum.f64",
"maxnumf32" => "llvm.maxnum.f32",
"maxnumf64" => "llvm.maxnum.f64",
"copysignf32" => "llvm.copysign.f32",
"copysignf64" => "llvm.copysign.f64",
"floorf32" => "llvm.floor.f32",
"floorf64" => "llvm.floor.f64",
"ceilf32" => "llvm.ceil.f32",
"ceilf64" => "llvm.ceil.f64",
"truncf32" => "llvm.trunc.f32",
"truncf64" => "llvm.trunc.f64",
"rintf32" => "llvm.rint.f32",
"rintf64" => "llvm.rint.f64",
"nearbyintf32" => "llvm.nearbyint.f32",
"nearbyintf64" => "llvm.nearbyint.f64",
"roundf32" => "llvm.round.f32",
"roundf64" => "llvm.round.f64",
"assume" => "llvm.assume",
"abort" => "llvm.trap",
sym::sqrtf32 => "llvm.sqrt.f32",
sym::sqrtf64 => "llvm.sqrt.f64",
sym::powif32 => "llvm.powi.f32",
sym::powif64 => "llvm.powi.f64",
sym::sinf32 => "llvm.sin.f32",
sym::sinf64 => "llvm.sin.f64",
sym::cosf32 => "llvm.cos.f32",
sym::cosf64 => "llvm.cos.f64",
sym::powf32 => "llvm.pow.f32",
sym::powf64 => "llvm.pow.f64",
sym::expf32 => "llvm.exp.f32",
sym::expf64 => "llvm.exp.f64",
sym::exp2f32 => "llvm.exp2.f32",
sym::exp2f64 => "llvm.exp2.f64",
sym::logf32 => "llvm.log.f32",
sym::logf64 => "llvm.log.f64",
sym::log10f32 => "llvm.log10.f32",
sym::log10f64 => "llvm.log10.f64",
sym::log2f32 => "llvm.log2.f32",
sym::log2f64 => "llvm.log2.f64",
sym::fmaf32 => "llvm.fma.f32",
sym::fmaf64 => "llvm.fma.f64",
sym::fabsf32 => "llvm.fabs.f32",
sym::fabsf64 => "llvm.fabs.f64",
sym::minnumf32 => "llvm.minnum.f32",
sym::minnumf64 => "llvm.minnum.f64",
sym::maxnumf32 => "llvm.maxnum.f32",
sym::maxnumf64 => "llvm.maxnum.f64",
sym::copysignf32 => "llvm.copysign.f32",
sym::copysignf64 => "llvm.copysign.f64",
sym::floorf32 => "llvm.floor.f32",
sym::floorf64 => "llvm.floor.f64",
sym::ceilf32 => "llvm.ceil.f32",
sym::ceilf64 => "llvm.ceil.f64",
sym::truncf32 => "llvm.trunc.f32",
sym::truncf64 => "llvm.trunc.f64",
sym::rintf32 => "llvm.rint.f32",
sym::rintf64 => "llvm.rint.f64",
sym::nearbyintf32 => "llvm.nearbyint.f32",
sym::nearbyintf64 => "llvm.nearbyint.f64",
sym::roundf32 => "llvm.round.f32",
sym::roundf64 => "llvm.round.f64",
sym::assume => "llvm.assume",
sym::abort => "llvm.trap",
_ => return None,
};
Some(cx.get_intrinsic(&llvm_name))
@ -86,12 +86,12 @@ fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Valu
impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
fn is_codegen_intrinsic(
&mut self,
intrinsic: &str,
intrinsic: Symbol,
args: &Vec<Operand<'tcx>>,
caller_instance: ty::Instance<'tcx>,
) -> bool {
match intrinsic {
"count_code_region" => {
sym::count_code_region => {
use coverage::count_code_region_args::*;
self.add_counter_region(
caller_instance,
@ -101,13 +101,13 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
);
true // Also inject the counter increment in the backend
}
"coverage_counter_add" | "coverage_counter_subtract" => {
sym::coverage_counter_add | sym::coverage_counter_subtract => {
use coverage::coverage_counter_expression_args::*;
self.add_counter_expression_region(
caller_instance,
op_to_u32(&args[COUNTER_EXPRESSION_INDEX]),
op_to_u32(&args[LEFT_INDEX]),
if intrinsic == "coverage_counter_add" {
if intrinsic == sym::coverage_counter_add {
CounterOp::Add
} else {
CounterOp::Subtract
@ -118,7 +118,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
);
false // Does not inject backend code
}
"coverage_unreachable" => {
sym::coverage_unreachable => {
use coverage::coverage_unreachable_args::*;
self.add_unreachable_region(
caller_instance,
@ -152,7 +152,8 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
let arg_tys = sig.inputs();
let ret_ty = sig.output();
let name = &*tcx.item_name(def_id).as_str();
let name = tcx.item_name(def_id);
let name_str = &*name.as_str();
let llret_ty = self.layout_of(ret_ty).llvm_type(self);
let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
@ -164,18 +165,18 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
&args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
None,
),
"unreachable" => {
sym::unreachable => {
return;
}
"likely" => {
sym::likely => {
let expect = self.get_intrinsic(&("llvm.expect.i1"));
self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
}
"unlikely" => {
sym::unlikely => {
let expect = self.get_intrinsic(&("llvm.expect.i1"));
self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
}
"try" => {
kw::Try => {
try_intrinsic(
self,
args[0].immediate(),
@ -185,11 +186,11 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
);
return;
}
"breakpoint" => {
sym::breakpoint => {
let llfn = self.get_intrinsic(&("llvm.debugtrap"));
self.call(llfn, &[], None)
}
"count_code_region" => {
sym::count_code_region => {
// FIXME(richkadel): The current implementation assumes the MIR for the given
// caller_instance represents a single function. Validate and/or correct if inlining
// and/or monomorphization invalidates these assumptions.
@ -206,13 +207,13 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
);
self.instrprof_increment(mangled_fn_name, hash, num_counters, index)
}
"va_start" => self.va_start(args[0].immediate()),
"va_end" => self.va_end(args[0].immediate()),
"va_copy" => {
sym::va_start => self.va_start(args[0].immediate()),
sym::va_end => self.va_end(args[0].immediate()),
sym::va_copy => {
let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
}
"va_arg" => {
sym::va_arg => {
match fn_abi.ret.layout.abi {
abi::Abi::Scalar(ref scalar) => {
match scalar.value {
@ -238,7 +239,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
_ => bug!("the va_arg intrinsic does not work with non-scalar types"),
}
}
"size_of_val" => {
sym::size_of_val => {
let tp_ty = substs.type_at(0);
if let OperandValue::Pair(_, meta) = args[0].val {
let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
@ -247,7 +248,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
self.const_usize(self.size_of(tp_ty).bytes())
}
}
"min_align_of_val" => {
sym::min_align_of_val => {
let tp_ty = substs.type_at(0);
if let OperandValue::Pair(_, meta) = args[0].val {
let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
@ -256,8 +257,13 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
self.const_usize(self.align_of(tp_ty).bytes())
}
}
"size_of" | "pref_align_of" | "min_align_of" | "needs_drop" | "type_id"
| "type_name" | "variant_count" => {
sym::size_of
| sym::pref_align_of
| sym::min_align_of
| sym::needs_drop
| sym::type_id
| sym::type_name
| sym::variant_count => {
let value = self
.tcx
.const_eval_instance(ty::ParamEnv::reveal_all(), instance, None)
@ -265,21 +271,21 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
OperandRef::from_const(self, value, ret_ty).immediate_or_packed_pair(self)
}
// Effectively no-op
"forget" => {
sym::forget => {
return;
}
"offset" => {
sym::offset => {
let ptr = args[0].immediate();
let offset = args[1].immediate();
self.inbounds_gep(ptr, &[offset])
}
"arith_offset" => {
sym::arith_offset => {
let ptr = args[0].immediate();
let offset = args[1].immediate();
self.gep(ptr, &[offset])
}
"copy_nonoverlapping" => {
sym::copy_nonoverlapping => {
copy_intrinsic(
self,
false,
@ -291,7 +297,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
);
return;
}
"copy" => {
sym::copy => {
copy_intrinsic(
self,
true,
@ -303,7 +309,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
);
return;
}
"write_bytes" => {
sym::write_bytes => {
memset_intrinsic(
self,
false,
@ -315,7 +321,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
return;
}
"volatile_copy_nonoverlapping_memory" => {
sym::volatile_copy_nonoverlapping_memory => {
copy_intrinsic(
self,
false,
@ -327,7 +333,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
);
return;
}
"volatile_copy_memory" => {
sym::volatile_copy_memory => {
copy_intrinsic(
self,
true,
@ -339,7 +345,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
);
return;
}
"volatile_set_memory" => {
sym::volatile_set_memory => {
memset_intrinsic(
self,
true,
@ -350,14 +356,14 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
);
return;
}
"volatile_load" | "unaligned_volatile_load" => {
sym::volatile_load | sym::unaligned_volatile_load => {
let tp_ty = substs.type_at(0);
let mut ptr = args[0].immediate();
if let PassMode::Cast(ty) = fn_abi.ret.mode {
ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
}
let load = self.volatile_load(ptr);
let align = if name == "unaligned_volatile_load" {
let align = if name == sym::unaligned_volatile_load {
1
} else {
self.align_of(tp_ty).bytes() as u32
@ -367,26 +373,26 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
}
to_immediate(self, load, self.layout_of(tp_ty))
}
"volatile_store" => {
sym::volatile_store => {
let dst = args[0].deref(self.cx());
args[1].val.volatile_store(self, dst);
return;
}
"unaligned_volatile_store" => {
sym::unaligned_volatile_store => {
let dst = args[0].deref(self.cx());
args[1].val.unaligned_volatile_store(self, dst);
return;
}
"prefetch_read_data"
| "prefetch_write_data"
| "prefetch_read_instruction"
| "prefetch_write_instruction" => {
sym::prefetch_read_data
| sym::prefetch_write_data
| sym::prefetch_read_instruction
| sym::prefetch_write_instruction => {
let expect = self.get_intrinsic(&("llvm.prefetch"));
let (rw, cache_type) = match name {
"prefetch_read_data" => (0, 1),
"prefetch_write_data" => (1, 1),
"prefetch_read_instruction" => (0, 0),
"prefetch_write_instruction" => (1, 0),
sym::prefetch_read_data => (0, 1),
sym::prefetch_write_data => (1, 1),
sym::prefetch_read_instruction => (0, 0),
sym::prefetch_write_instruction => (1, 0),
_ => bug!(),
};
self.call(
@ -400,32 +406,51 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
None,
)
}
"ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap"
| "bitreverse" | "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow"
| "wrapping_add" | "wrapping_sub" | "wrapping_mul" | "unchecked_div"
| "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "unchecked_add"
| "unchecked_sub" | "unchecked_mul" | "exact_div" | "rotate_left" | "rotate_right"
| "saturating_add" | "saturating_sub" => {
sym::ctlz
| sym::ctlz_nonzero
| sym::cttz
| sym::cttz_nonzero
| sym::ctpop
| sym::bswap
| sym::bitreverse
| sym::add_with_overflow
| sym::sub_with_overflow
| sym::mul_with_overflow
| sym::wrapping_add
| sym::wrapping_sub
| sym::wrapping_mul
| sym::unchecked_div
| sym::unchecked_rem
| sym::unchecked_shl
| sym::unchecked_shr
| sym::unchecked_add
| sym::unchecked_sub
| sym::unchecked_mul
| sym::exact_div
| sym::rotate_left
| sym::rotate_right
| sym::saturating_add
| sym::saturating_sub => {
let ty = arg_tys[0];
match int_type_width_signed(ty, self) {
Some((width, signed)) => match name {
"ctlz" | "cttz" => {
sym::ctlz | sym::cttz => {
let y = self.const_bool(false);
let llfn = self.get_intrinsic(&format!("llvm.{}.i{}", name, width));
self.call(llfn, &[args[0].immediate(), y], None)
}
"ctlz_nonzero" | "cttz_nonzero" => {
sym::ctlz_nonzero | sym::cttz_nonzero => {
let y = self.const_bool(true);
let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
let llvm_name = &format!("llvm.{}.i{}", &name_str[..4], width);
let llfn = self.get_intrinsic(llvm_name);
self.call(llfn, &[args[0].immediate(), y], None)
}
"ctpop" => self.call(
sym::ctpop => self.call(
self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
&[args[0].immediate()],
None,
),
"bswap" => {
sym::bswap => {
if width == 8 {
args[0].immediate() // byte swap a u8/i8 is just a no-op
} else {
@ -436,16 +461,18 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
)
}
}
"bitreverse" => self.call(
sym::bitreverse => self.call(
self.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
&[args[0].immediate()],
None,
),
"add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
sym::add_with_overflow
| sym::sub_with_overflow
| sym::mul_with_overflow => {
let intrinsic = format!(
"llvm.{}{}.with.overflow.i{}",
if signed { 's' } else { 'u' },
&name[..3],
&name_str[..3],
width
);
let llfn = self.get_intrinsic(&intrinsic);
@ -464,61 +491,61 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
return;
}
"wrapping_add" => self.add(args[0].immediate(), args[1].immediate()),
"wrapping_sub" => self.sub(args[0].immediate(), args[1].immediate()),
"wrapping_mul" => self.mul(args[0].immediate(), args[1].immediate()),
"exact_div" => {
sym::wrapping_add => self.add(args[0].immediate(), args[1].immediate()),
sym::wrapping_sub => self.sub(args[0].immediate(), args[1].immediate()),
sym::wrapping_mul => self.mul(args[0].immediate(), args[1].immediate()),
sym::exact_div => {
if signed {
self.exactsdiv(args[0].immediate(), args[1].immediate())
} else {
self.exactudiv(args[0].immediate(), args[1].immediate())
}
}
"unchecked_div" => {
sym::unchecked_div => {
if signed {
self.sdiv(args[0].immediate(), args[1].immediate())
} else {
self.udiv(args[0].immediate(), args[1].immediate())
}
}
"unchecked_rem" => {
sym::unchecked_rem => {
if signed {
self.srem(args[0].immediate(), args[1].immediate())
} else {
self.urem(args[0].immediate(), args[1].immediate())
}
}
"unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
"unchecked_shr" => {
sym::unchecked_shl => self.shl(args[0].immediate(), args[1].immediate()),
sym::unchecked_shr => {
if signed {
self.ashr(args[0].immediate(), args[1].immediate())
} else {
self.lshr(args[0].immediate(), args[1].immediate())
}
}
"unchecked_add" => {
sym::unchecked_add => {
if signed {
self.unchecked_sadd(args[0].immediate(), args[1].immediate())
} else {
self.unchecked_uadd(args[0].immediate(), args[1].immediate())
}
}
"unchecked_sub" => {
sym::unchecked_sub => {
if signed {
self.unchecked_ssub(args[0].immediate(), args[1].immediate())
} else {
self.unchecked_usub(args[0].immediate(), args[1].immediate())
}
}
"unchecked_mul" => {
sym::unchecked_mul => {
if signed {
self.unchecked_smul(args[0].immediate(), args[1].immediate())
} else {
self.unchecked_umul(args[0].immediate(), args[1].immediate())
}
}
"rotate_left" | "rotate_right" => {
let is_left = name == "rotate_left";
sym::rotate_left | sym::rotate_right => {
let is_left = name == sym::rotate_left;
let val = args[0].immediate();
let raw_shift = args[1].immediate();
// rotate = funnel shift with first two args the same
@ -527,8 +554,8 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
let llfn = self.get_intrinsic(llvm_name);
self.call(llfn, &[val, val, raw_shift], None)
}
"saturating_add" | "saturating_sub" => {
let is_add = name == "saturating_add";
sym::saturating_add | sym::saturating_sub => {
let is_add = name == sym::saturating_add;
let lhs = args[0].immediate();
let rhs = args[1].immediate();
let llvm_name = &format!(
@ -556,14 +583,14 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
}
}
}
"fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
sym::fadd_fast | sym::fsub_fast | sym::fmul_fast | sym::fdiv_fast | sym::frem_fast => {
match float_type_width(arg_tys[0]) {
Some(_width) => match name {
"fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
"fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
"fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
"fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
"frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
sym::fadd_fast => self.fadd_fast(args[0].immediate(), args[1].immediate()),
sym::fsub_fast => self.fsub_fast(args[0].immediate(), args[1].immediate()),
sym::fmul_fast => self.fmul_fast(args[0].immediate(), args[1].immediate()),
sym::fdiv_fast => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
sym::frem_fast => self.frem_fast(args[0].immediate(), args[1].immediate()),
_ => bug!(),
},
None => {
@ -581,7 +608,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
}
}
"float_to_int_unchecked" => {
sym::float_to_int_unchecked => {
if float_type_width(arg_tys[0]).is_none() {
span_invalid_monomorphization_error(
tcx.sess,
@ -619,7 +646,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
}
}
"discriminant_value" => {
sym::discriminant_value => {
if ret_ty.is_integral() {
args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
} else {
@ -627,7 +654,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
}
}
name if name.starts_with("simd_") => {
_ if name_str.starts_with("simd_") => {
match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
Ok(llval) => llval,
Err(()) => return,
@ -635,11 +662,11 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
}
// This requires that atomic intrinsics follow a specific naming pattern:
// "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
name if name.starts_with("atomic_") => {
name if name_str.starts_with("atomic_") => {
use rustc_codegen_ssa::common::AtomicOrdering::*;
use rustc_codegen_ssa::common::{AtomicRmwBinOp, SynchronizationScope};
let split: Vec<&str> = name.split('_').collect();
let split: Vec<&str> = name_str.split('_').collect();
let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
let (order, failorder) = match split.len() {
@ -769,23 +796,23 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
}
}
"nontemporal_store" => {
sym::nontemporal_store => {
let dst = args[0].deref(self.cx());
args[1].val.nontemporal_store(self, dst);
return;
}
"ptr_guaranteed_eq" | "ptr_guaranteed_ne" => {
sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => {
let a = args[0].immediate();
let b = args[1].immediate();
if name == "ptr_guaranteed_eq" {
if name == sym::ptr_guaranteed_eq {
self.icmp(IntPredicate::IntEQ, a, b)
} else {
self.icmp(IntPredicate::IntNE, a, b)
}
}
"ptr_offset_from" => {
sym::ptr_offset_from => {
let ty = substs.type_at(0);
let pointee_size = self.size_of(ty);
@ -1172,7 +1199,7 @@ fn get_rust_try_fn<'ll, 'tcx>(
fn generic_simd_intrinsic(
bx: &mut Builder<'a, 'll, 'tcx>,
name: &str,
name: Symbol,
callee_ty: Ty<'tcx>,
args: &[OperandRef<'tcx, &'ll Value>],
ret_ty: Ty<'tcx>,
@ -1219,8 +1246,9 @@ fn generic_simd_intrinsic(
let sig = tcx
.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &callee_ty.fn_sig(tcx));
let arg_tys = sig.inputs();
let name_str = &*name.as_str();
if name == "simd_select_bitmask" {
if name == sym::simd_select_bitmask {
let in_ty = arg_tys[0];
let m_len = match in_ty.kind {
// Note that this `.unwrap()` crashes for isize/usize, that's sort
@ -1250,12 +1278,12 @@ fn generic_simd_intrinsic(
let in_len = arg_tys[0].simd_size(tcx);
let comparison = match name {
"simd_eq" => Some(hir::BinOpKind::Eq),
"simd_ne" => Some(hir::BinOpKind::Ne),
"simd_lt" => Some(hir::BinOpKind::Lt),
"simd_le" => Some(hir::BinOpKind::Le),
"simd_gt" => Some(hir::BinOpKind::Gt),
"simd_ge" => Some(hir::BinOpKind::Ge),
sym::simd_eq => Some(hir::BinOpKind::Eq),
sym::simd_ne => Some(hir::BinOpKind::Ne),
sym::simd_lt => Some(hir::BinOpKind::Lt),
sym::simd_le => Some(hir::BinOpKind::Le),
sym::simd_gt => Some(hir::BinOpKind::Gt),
sym::simd_ge => Some(hir::BinOpKind::Ge),
_ => None,
};
@ -1289,8 +1317,8 @@ fn generic_simd_intrinsic(
));
}
if name.starts_with("simd_shuffle") {
let n: u64 = name["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
if name_str.starts_with("simd_shuffle") {
let n: u64 = name_str["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
});
@ -1351,7 +1379,7 @@ fn generic_simd_intrinsic(
));
}
if name == "simd_insert" {
if name == sym::simd_insert {
require!(
in_elem == arg_tys[2],
"expected inserted type `{}` (element of input `{}`), found `{}`",
@ -1365,7 +1393,7 @@ fn generic_simd_intrinsic(
args[1].immediate(),
));
}
if name == "simd_extract" {
if name == sym::simd_extract {
require!(
ret_ty == in_elem,
"expected return type `{}` (element of input `{}`), found `{}`",
@ -1376,7 +1404,7 @@ fn generic_simd_intrinsic(
return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
}
if name == "simd_select" {
if name == sym::simd_select {
let m_elem_ty = in_elem;
let m_len = in_len;
require_simd!(arg_tys[1], "argument");
@ -1398,7 +1426,7 @@ fn generic_simd_intrinsic(
return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
}
if name == "simd_bitmask" {
if name == sym::simd_bitmask {
// The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
// vector mask and returns an unsigned integer containing the most
// significant bit (MSB) of each lane.
@ -1513,46 +1541,46 @@ fn generic_simd_intrinsic(
}
match name {
"simd_fsqrt" => {
sym::simd_fsqrt => {
return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
}
"simd_fsin" => {
sym::simd_fsin => {
return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
}
"simd_fcos" => {
sym::simd_fcos => {
return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
}
"simd_fabs" => {
sym::simd_fabs => {
return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
}
"simd_floor" => {
sym::simd_floor => {
return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
}
"simd_ceil" => {
sym::simd_ceil => {
return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
}
"simd_fexp" => {
sym::simd_fexp => {
return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
}
"simd_fexp2" => {
sym::simd_fexp2 => {
return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
}
"simd_flog10" => {
sym::simd_flog10 => {
return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
}
"simd_flog2" => {
sym::simd_flog2 => {
return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
}
"simd_flog" => {
sym::simd_flog => {
return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
}
"simd_fpowi" => {
sym::simd_fpowi => {
return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
}
"simd_fpow" => {
sym::simd_fpow => {
return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
}
"simd_fma" => {
sym::simd_fma => {
return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
}
_ => { /* fallthrough */ }
@ -1591,7 +1619,7 @@ fn generic_simd_intrinsic(
cx.type_vector(elem_ty, vec_len)
}
if name == "simd_gather" {
if name == sym::simd_gather {
// simd_gather(values: <N x T>, pointers: <N x *_ T>,
// mask: <N x i{M}>) -> <N x T>
// * N: number of elements in the input vectors
@ -1718,7 +1746,7 @@ fn generic_simd_intrinsic(
return Ok(v);
}
if name == "simd_scatter" {
if name == sym::simd_scatter {
// simd_scatter(values: <N x T>, pointers: <N x *mut T>,
// mask: <N x i{M}>) -> ()
// * N: number of elements in the input vectors
@ -1841,8 +1869,9 @@ fn generic_simd_intrinsic(
}
macro_rules! arith_red {
($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
if name == $name {
($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
$identity:expr) => {
if name == sym::$name {
require!(
ret_ty == in_elem,
"expected return type `{}` (element of input `{}`), found `{}`",
@ -1856,11 +1885,7 @@ fn generic_simd_intrinsic(
if $ordered {
// if overflow occurs, the result is the
// mathematical result modulo 2^n:
if name.contains("mul") {
Ok(bx.mul(args[1].immediate(), r))
} else {
Ok(bx.add(args[1].immediate(), r))
}
Ok(bx.$op(args[1].immediate(), r))
} else {
Ok(bx.$integer_reduce(args[0].immediate()))
}
@ -1871,14 +1896,13 @@ fn generic_simd_intrinsic(
args[1].immediate()
} else {
// unordered arithmetic reductions use the identity accumulator
let identity_acc = if $name.contains("mul") { 1.0 } else { 0.0 };
match f.bit_width() {
32 => bx.const_real(bx.type_f32(), identity_acc),
64 => bx.const_real(bx.type_f64(), identity_acc),
32 => bx.const_real(bx.type_f32(), $identity),
64 => bx.const_real(bx.type_f64(), $identity),
v => return_error!(
r#"
unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
$name,
sym::$name,
in_ty,
in_elem,
v,
@ -1890,7 +1914,7 @@ unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
}
_ => return_error!(
"unsupported {} from `{}` with element `{}` to `{}`",
$name,
sym::$name,
in_ty,
in_elem,
ret_ty
@ -1900,14 +1924,26 @@ unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
};
}
arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd, true);
arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul, true);
arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
arith_red!(
simd_reduce_add_unordered: vector_reduce_add,
vector_reduce_fadd_fast,
false,
add,
0.0
);
arith_red!(
simd_reduce_mul_unordered: vector_reduce_mul,
vector_reduce_fmul_fast,
false,
mul,
1.0
);
macro_rules! minmax_red {
($name:tt: $int_red:ident, $float_red:ident) => {
if name == $name {
($name:ident: $int_red:ident, $float_red:ident) => {
if name == sym::$name {
require!(
ret_ty == in_elem,
"expected return type `{}` (element of input `{}`), found `{}`",
@ -1921,7 +1957,7 @@ unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
_ => return_error!(
"unsupported {} from `{}` with element `{}` to `{}`",
$name,
sym::$name,
in_ty,
in_elem,
ret_ty
@ -1931,15 +1967,15 @@ unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
};
}
minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
macro_rules! bitwise_red {
($name:tt : $red:ident, $boolean:expr) => {
if name == $name {
($name:ident : $red:ident, $boolean:expr) => {
if name == sym::$name {
let input = if !$boolean {
require!(
ret_ty == in_elem,
@ -1954,7 +1990,7 @@ unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
ty::Int(_) | ty::Uint(_) => {}
_ => return_error!(
"unsupported {} from `{}` with element `{}` to `{}`",
$name,
sym::$name,
in_ty,
in_elem,
ret_ty
@ -1973,7 +2009,7 @@ unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
}
_ => return_error!(
"unsupported {} from `{}` with element `{}` to `{}`",
$name,
sym::$name,
in_ty,
in_elem,
ret_ty
@ -1983,13 +2019,13 @@ unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
};
}
bitwise_red!("simd_reduce_and": vector_reduce_and, false);
bitwise_red!("simd_reduce_or": vector_reduce_or, false);
bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
bitwise_red!("simd_reduce_all": vector_reduce_and, true);
bitwise_red!("simd_reduce_any": vector_reduce_or, true);
bitwise_red!(simd_reduce_and: vector_reduce_and, false);
bitwise_red!(simd_reduce_or: vector_reduce_or, false);
bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
bitwise_red!(simd_reduce_all: vector_reduce_and, true);
bitwise_red!(simd_reduce_any: vector_reduce_or, true);
if name == "simd_cast" {
if name == sym::simd_cast {
require_simd!(ret_ty, "return");
let out_len = ret_ty.simd_size(tcx);
require!(
@ -2077,7 +2113,7 @@ unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
}
macro_rules! arith {
($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
$(if name == stringify!($name) {
$(if name == sym::$name {
match in_elem.kind {
$($(ty::$p(_))|* => {
return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
@ -2107,10 +2143,10 @@ unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
}
if name == "simd_saturating_add" || name == "simd_saturating_sub" {
if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
let lhs = args[0].immediate();
let rhs = args[1].immediate();
let is_add = name == "simd_saturating_add";
let is_add = name == sym::simd_saturating_add;
let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
let (signed, elem_width, elem_ty) = match in_elem.kind {
ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),

View File

@ -16,6 +16,7 @@ use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
use rustc_middle::ty::Instance;
use rustc_middle::ty::{SymbolName, TyCtxt};
use rustc_session::config::{CrateType, SanitizerSet};
use rustc_span::symbol::sym;
pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
crates_export_threshold(&tcx.sess.crate_types())
@ -107,7 +108,7 @@ fn reachable_non_generics_provider(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<
})
.map(|def_id| {
let export_level = if special_runtime_crate {
let name = tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())).name.as_str();
let name = tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())).name;
// We can probably do better here by just ensuring that
// it has hidden visibility rather than public
// visibility, as this is primarily here to ensure it's
@ -115,13 +116,12 @@ fn reachable_non_generics_provider(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<
//
// In general though we won't link right if these
// symbols are stripped, and LTO currently strips them.
if name == "rust_eh_personality"
|| name == "rust_eh_register_frames"
|| name == "rust_eh_unregister_frames"
{
SymbolExportLevel::C
} else {
SymbolExportLevel::Rust
match name {
sym::rust_eh_personality
| sym::rust_eh_register_frames
| sym::rust_eh_unregister_frames =>
SymbolExportLevel::C,
_ => SymbolExportLevel::Rust,
}
} else {
symbol_export_level(tcx, def_id.to_def_id())

View File

@ -17,7 +17,8 @@ use rustc_middle::mir::interpret::{AllocId, ConstValue, Pointer, Scalar};
use rustc_middle::mir::AssertKind;
use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
use rustc_middle::ty::{self, Instance, Ty, TypeFoldable};
use rustc_span::{source_map::Span, symbol::Symbol};
use rustc_span::source_map::Span;
use rustc_span::{sym, Symbol};
use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode};
use rustc_target::abi::{self, LayoutOf};
use rustc_target::spec::abi::Abi;
@ -445,7 +446,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
&mut self,
helper: &TerminatorCodegenHelper<'tcx>,
bx: &mut Bx,
intrinsic: Option<&str>,
intrinsic: Option<Symbol>,
instance: Option<Instance<'tcx>>,
span: Span,
destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
@ -461,10 +462,9 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
UninitValid,
};
let panic_intrinsic = intrinsic.and_then(|i| match i {
// FIXME: Move to symbols instead of strings.
"assert_inhabited" => Some(AssertIntrinsic::Inhabited),
"assert_zero_valid" => Some(AssertIntrinsic::ZeroValid),
"assert_uninit_valid" => Some(AssertIntrinsic::UninitValid),
sym::assert_inhabited => Some(AssertIntrinsic::Inhabited),
sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid),
sym::assert_uninit_valid => Some(AssertIntrinsic::UninitValid),
_ => None,
});
if let Some(intrinsic) = panic_intrinsic {
@ -568,10 +568,9 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
// Handle intrinsics old codegen wants Expr's for, ourselves.
let intrinsic = match def {
Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id).as_str()),
Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id)),
_ => None,
};
let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
let extra_args = &args[sig.inputs().skip_binder().len()..];
let extra_args = extra_args
@ -587,7 +586,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
None => FnAbi::of_fn_ptr(&bx, sig, &extra_args),
};
if intrinsic == Some("transmute") {
if intrinsic == Some(sym::transmute) {
if let Some(destination_ref) = destination.as_ref() {
let &(dest, target) = destination_ref;
self.codegen_transmute(&mut bx, &args[0], dest);
@ -607,7 +606,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
}
// For normal codegen, this Miri-specific intrinsic should never occur.
if intrinsic == Some("miri_start_panic") {
if intrinsic == Some(sym::miri_start_panic) {
bug!("`miri_start_panic` should never end up in compiled code");
}
@ -635,7 +634,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
ReturnDest::Nothing
};
if intrinsic == Some("caller_location") {
if intrinsic == Some(sym::caller_location) {
if let Some((_, target)) = destination.as_ref() {
let location = self.get_caller_location(&mut bx, fn_span);
@ -650,7 +649,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
return;
}
if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
if intrinsic.is_some() && intrinsic != Some(sym::drop_in_place) {
let intrinsic = intrinsic.unwrap();
// `is_codegen_intrinsic()` allows the backend implementation to perform compile-time
@ -682,7 +681,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
// third argument must be constant. This is
// checked by const-qualification, which also
// promotes any complex rvalues to constants.
if i == 2 && intrinsic.starts_with("simd_shuffle") {
if i == 2 && intrinsic.as_str().starts_with("simd_shuffle") {
if let mir::Operand::Constant(constant) = arg {
let c = self.eval_mir_constant(constant);
let (llval, ty) = self.simd_shuffle_indices(

View File

@ -2,7 +2,7 @@ use super::BackendTypes;
use crate::mir::operand::OperandRef;
use rustc_middle::mir::Operand;
use rustc_middle::ty::{self, Ty};
use rustc_span::Span;
use rustc_span::{Span, Symbol};
use rustc_target::abi::call::FnAbi;
pub trait IntrinsicCallMethods<'tcx>: BackendTypes {
@ -24,7 +24,7 @@ pub trait IntrinsicCallMethods<'tcx>: BackendTypes {
/// the intrinsic does not need code generation.
fn is_codegen_intrinsic(
&mut self,
intrinsic: &str,
intrinsic: Symbol,
args: &Vec<Operand<'tcx>>,
caller_instance: ty::Instance<'tcx>,
) -> bool;

View File

@ -698,7 +698,7 @@ impl RustcDefaultCalls {
.parse_sess
.config
.iter()
.filter_map(|&(name, ref value)| {
.filter_map(|&(name, value)| {
// Note that crt-static is a specially recognized cfg
// directive that's printed out here as part of
// rust-lang/rust#37406, but in general the
@ -707,9 +707,7 @@ impl RustcDefaultCalls {
// specifically allowing the crt-static cfg and that's
// it, this is intended to get into Cargo and then go
// through to build scripts.
let value = value.as_ref().map(|s| s.as_str());
let value = value.as_ref().map(|s| s.as_ref());
if (name != sym::target_feature || value != Some("crt-static"))
if (name != sym::target_feature || value != Some(sym::crt_dash_static))
&& !allow_unstable_cfg
&& find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
{

View File

@ -149,8 +149,8 @@ impl FromInternal<(TreeAndJoint, &'_ ParseSess, &'_ mut Vec<Self>)>
}
Literal(lit) => tt!(Literal { lit }),
DocComment(c) => {
let style = comments::doc_comment_style(&c.as_str());
let stripped = comments::strip_doc_comment_decoration(&c.as_str());
let style = comments::doc_comment_style(c);
let stripped = comments::strip_doc_comment_decoration(c);
let mut escaped = String::new();
for ch in stripped.chars() {
escaped.extend(ch.escape_debug());

View File

@ -16,7 +16,7 @@ use rustc_ast::ast;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_macros::HashStable_Generic;
use rustc_span::symbol::{sym, Symbol};
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_span::Span;
use lazy_static::lazy_static;
@ -52,10 +52,10 @@ macro_rules! language_item_table {
}
impl LangItem {
/// Returns the `name` in `#[lang = "$name"]`.
/// Returns the `name` symbol in `#[lang = "$name"]`.
/// For example, `LangItem::EqTraitLangItem`,
/// that is `#[lang = "eq"]` would result in `"eq"`.
pub fn name(self) -> &'static str {
/// that is `#[lang = "eq"]` would result in `sym::eq`.
pub fn name(self) -> Symbol {
match self {
$( $variant => $name, )*
}
@ -110,9 +110,8 @@ macro_rules! language_item_table {
}
$(
/// Returns the corresponding `DefId` for the lang item
#[doc = $name]
/// if it exists.
/// Returns the corresponding `DefId` for the lang item if it
/// exists.
#[allow(dead_code)]
pub fn $method(&self) -> Option<DefId> {
self.items[$variant as usize]
@ -122,7 +121,7 @@ macro_rules! language_item_table {
lazy_static! {
/// A mapping from the name of the lang item to its order and the form it must be of.
pub static ref ITEM_REFS: FxHashMap<&'static str, (usize, Target)> = {
pub static ref ITEM_REFS: FxHashMap<Symbol, (usize, Target)> = {
let mut item_refs = FxHashMap::default();
$( item_refs.insert($name, ($variant as usize, $target)); )*
item_refs
@ -154,100 +153,100 @@ pub fn extract(attrs: &[ast::Attribute]) -> Option<(Symbol, Span)> {
}
language_item_table! {
// Variant name, Name, Method name, Target;
BoolImplItem, "bool", bool_impl, Target::Impl;
CharImplItem, "char", char_impl, Target::Impl;
StrImplItem, "str", str_impl, Target::Impl;
SliceImplItem, "slice", slice_impl, Target::Impl;
SliceU8ImplItem, "slice_u8", slice_u8_impl, Target::Impl;
StrAllocImplItem, "str_alloc", str_alloc_impl, Target::Impl;
SliceAllocImplItem, "slice_alloc", slice_alloc_impl, Target::Impl;
SliceU8AllocImplItem, "slice_u8_alloc", slice_u8_alloc_impl, Target::Impl;
ConstPtrImplItem, "const_ptr", const_ptr_impl, Target::Impl;
MutPtrImplItem, "mut_ptr", mut_ptr_impl, Target::Impl;
ConstSlicePtrImplItem, "const_slice_ptr", const_slice_ptr_impl, Target::Impl;
MutSlicePtrImplItem, "mut_slice_ptr", mut_slice_ptr_impl, Target::Impl;
I8ImplItem, "i8", i8_impl, Target::Impl;
I16ImplItem, "i16", i16_impl, Target::Impl;
I32ImplItem, "i32", i32_impl, Target::Impl;
I64ImplItem, "i64", i64_impl, Target::Impl;
I128ImplItem, "i128", i128_impl, Target::Impl;
IsizeImplItem, "isize", isize_impl, Target::Impl;
U8ImplItem, "u8", u8_impl, Target::Impl;
U16ImplItem, "u16", u16_impl, Target::Impl;
U32ImplItem, "u32", u32_impl, Target::Impl;
U64ImplItem, "u64", u64_impl, Target::Impl;
U128ImplItem, "u128", u128_impl, Target::Impl;
UsizeImplItem, "usize", usize_impl, Target::Impl;
F32ImplItem, "f32", f32_impl, Target::Impl;
F64ImplItem, "f64", f64_impl, Target::Impl;
F32RuntimeImplItem, "f32_runtime", f32_runtime_impl, Target::Impl;
F64RuntimeImplItem, "f64_runtime", f64_runtime_impl, Target::Impl;
// Variant name, Name, Method name, Target;
BoolImplItem, sym::bool, bool_impl, Target::Impl;
CharImplItem, sym::char, char_impl, Target::Impl;
StrImplItem, sym::str, str_impl, Target::Impl;
SliceImplItem, sym::slice, slice_impl, Target::Impl;
SliceU8ImplItem, sym::slice_u8, slice_u8_impl, Target::Impl;
StrAllocImplItem, sym::str_alloc, str_alloc_impl, Target::Impl;
SliceAllocImplItem, sym::slice_alloc, slice_alloc_impl, Target::Impl;
SliceU8AllocImplItem, sym::slice_u8_alloc, slice_u8_alloc_impl, Target::Impl;
ConstPtrImplItem, sym::const_ptr, const_ptr_impl, Target::Impl;
MutPtrImplItem, sym::mut_ptr, mut_ptr_impl, Target::Impl;
ConstSlicePtrImplItem, sym::const_slice_ptr, const_slice_ptr_impl, Target::Impl;
MutSlicePtrImplItem, sym::mut_slice_ptr, mut_slice_ptr_impl, Target::Impl;
I8ImplItem, sym::i8, i8_impl, Target::Impl;
I16ImplItem, sym::i16, i16_impl, Target::Impl;
I32ImplItem, sym::i32, i32_impl, Target::Impl;
I64ImplItem, sym::i64, i64_impl, Target::Impl;
I128ImplItem, sym::i128, i128_impl, Target::Impl;
IsizeImplItem, sym::isize, isize_impl, Target::Impl;
U8ImplItem, sym::u8, u8_impl, Target::Impl;
U16ImplItem, sym::u16, u16_impl, Target::Impl;
U32ImplItem, sym::u32, u32_impl, Target::Impl;
U64ImplItem, sym::u64, u64_impl, Target::Impl;
U128ImplItem, sym::u128, u128_impl, Target::Impl;
UsizeImplItem, sym::usize, usize_impl, Target::Impl;
F32ImplItem, sym::f32, f32_impl, Target::Impl;
F64ImplItem, sym::f64, f64_impl, Target::Impl;
F32RuntimeImplItem, sym::f32_runtime, f32_runtime_impl, Target::Impl;
F64RuntimeImplItem, sym::f64_runtime, f64_runtime_impl, Target::Impl;
SizedTraitLangItem, "sized", sized_trait, Target::Trait;
UnsizeTraitLangItem, "unsize", unsize_trait, Target::Trait;
SizedTraitLangItem, sym::sized, sized_trait, Target::Trait;
UnsizeTraitLangItem, sym::unsize, unsize_trait, Target::Trait;
// trait injected by #[derive(PartialEq)], (i.e. "Partial EQ").
StructuralPeqTraitLangItem, "structural_peq", structural_peq_trait, Target::Trait;
StructuralPeqTraitLangItem, sym::structural_peq, structural_peq_trait, Target::Trait;
// trait injected by #[derive(Eq)], (i.e. "Total EQ"; no, I will not apologize).
StructuralTeqTraitLangItem, "structural_teq", structural_teq_trait, Target::Trait;
CopyTraitLangItem, "copy", copy_trait, Target::Trait;
CloneTraitLangItem, "clone", clone_trait, Target::Trait;
SyncTraitLangItem, "sync", sync_trait, Target::Trait;
DiscriminantKindTraitLangItem,"discriminant_kind", discriminant_kind_trait, Target::Trait;
FreezeTraitLangItem, "freeze", freeze_trait, Target::Trait;
StructuralTeqTraitLangItem, sym::structural_teq, structural_teq_trait, Target::Trait;
CopyTraitLangItem, sym::copy, copy_trait, Target::Trait;
CloneTraitLangItem, sym::clone, clone_trait, Target::Trait;
SyncTraitLangItem, sym::sync, sync_trait, Target::Trait;
DiscriminantKindTraitLangItem, sym::discriminant_kind, discriminant_kind_trait, Target::Trait;
FreezeTraitLangItem, sym::freeze, freeze_trait, Target::Trait;
DropTraitLangItem, "drop", drop_trait, Target::Trait;
DropTraitLangItem, sym::drop, drop_trait, Target::Trait;
CoerceUnsizedTraitLangItem, "coerce_unsized", coerce_unsized_trait, Target::Trait;
DispatchFromDynTraitLangItem,"dispatch_from_dyn", dispatch_from_dyn_trait, Target::Trait;
CoerceUnsizedTraitLangItem, sym::coerce_unsized, coerce_unsized_trait, Target::Trait;
DispatchFromDynTraitLangItem, sym::dispatch_from_dyn, dispatch_from_dyn_trait, Target::Trait;
AddTraitLangItem(Op), "add", add_trait, Target::Trait;
SubTraitLangItem(Op), "sub", sub_trait, Target::Trait;
MulTraitLangItem(Op), "mul", mul_trait, Target::Trait;
DivTraitLangItem(Op), "div", div_trait, Target::Trait;
RemTraitLangItem(Op), "rem", rem_trait, Target::Trait;
NegTraitLangItem(Op), "neg", neg_trait, Target::Trait;
NotTraitLangItem(Op), "not", not_trait, Target::Trait;
BitXorTraitLangItem(Op), "bitxor", bitxor_trait, Target::Trait;
BitAndTraitLangItem(Op), "bitand", bitand_trait, Target::Trait;
BitOrTraitLangItem(Op), "bitor", bitor_trait, Target::Trait;
ShlTraitLangItem(Op), "shl", shl_trait, Target::Trait;
ShrTraitLangItem(Op), "shr", shr_trait, Target::Trait;
AddAssignTraitLangItem(Op), "add_assign", add_assign_trait, Target::Trait;
SubAssignTraitLangItem(Op), "sub_assign", sub_assign_trait, Target::Trait;
MulAssignTraitLangItem(Op), "mul_assign", mul_assign_trait, Target::Trait;
DivAssignTraitLangItem(Op), "div_assign", div_assign_trait, Target::Trait;
RemAssignTraitLangItem(Op), "rem_assign", rem_assign_trait, Target::Trait;
BitXorAssignTraitLangItem(Op),"bitxor_assign", bitxor_assign_trait, Target::Trait;
BitAndAssignTraitLangItem(Op),"bitand_assign", bitand_assign_trait, Target::Trait;
BitOrAssignTraitLangItem(Op),"bitor_assign", bitor_assign_trait, Target::Trait;
ShlAssignTraitLangItem(Op), "shl_assign", shl_assign_trait, Target::Trait;
ShrAssignTraitLangItem(Op), "shr_assign", shr_assign_trait, Target::Trait;
IndexTraitLangItem(Op), "index", index_trait, Target::Trait;
IndexMutTraitLangItem(Op), "index_mut", index_mut_trait, Target::Trait;
AddTraitLangItem(Op), sym::add, add_trait, Target::Trait;
SubTraitLangItem(Op), sym::sub, sub_trait, Target::Trait;
MulTraitLangItem(Op), sym::mul, mul_trait, Target::Trait;
DivTraitLangItem(Op), sym::div, div_trait, Target::Trait;
RemTraitLangItem(Op), sym::rem, rem_trait, Target::Trait;
NegTraitLangItem(Op), sym::neg, neg_trait, Target::Trait;
NotTraitLangItem(Op), sym::not, not_trait, Target::Trait;
BitXorTraitLangItem(Op), sym::bitxor, bitxor_trait, Target::Trait;
BitAndTraitLangItem(Op), sym::bitand, bitand_trait, Target::Trait;
BitOrTraitLangItem(Op), sym::bitor, bitor_trait, Target::Trait;
ShlTraitLangItem(Op), sym::shl, shl_trait, Target::Trait;
ShrTraitLangItem(Op), sym::shr, shr_trait, Target::Trait;
AddAssignTraitLangItem(Op), sym::add_assign, add_assign_trait, Target::Trait;
SubAssignTraitLangItem(Op), sym::sub_assign, sub_assign_trait, Target::Trait;
MulAssignTraitLangItem(Op), sym::mul_assign, mul_assign_trait, Target::Trait;
DivAssignTraitLangItem(Op), sym::div_assign, div_assign_trait, Target::Trait;
RemAssignTraitLangItem(Op), sym::rem_assign, rem_assign_trait, Target::Trait;
BitXorAssignTraitLangItem(Op), sym::bitxor_assign, bitxor_assign_trait, Target::Trait;
BitAndAssignTraitLangItem(Op), sym::bitand_assign, bitand_assign_trait, Target::Trait;
BitOrAssignTraitLangItem(Op), sym::bitor_assign, bitor_assign_trait, Target::Trait;
ShlAssignTraitLangItem(Op), sym::shl_assign, shl_assign_trait, Target::Trait;
ShrAssignTraitLangItem(Op), sym::shr_assign, shr_assign_trait, Target::Trait;
IndexTraitLangItem(Op), sym::index, index_trait, Target::Trait;
IndexMutTraitLangItem(Op), sym::index_mut, index_mut_trait, Target::Trait;
UnsafeCellTypeLangItem, "unsafe_cell", unsafe_cell_type, Target::Struct;
VaListTypeLangItem, "va_list", va_list, Target::Struct;
UnsafeCellTypeLangItem, sym::unsafe_cell, unsafe_cell_type, Target::Struct;
VaListTypeLangItem, sym::va_list, va_list, Target::Struct;
DerefTraitLangItem, "deref", deref_trait, Target::Trait;
DerefMutTraitLangItem, "deref_mut", deref_mut_trait, Target::Trait;
ReceiverTraitLangItem, "receiver", receiver_trait, Target::Trait;
DerefTraitLangItem, sym::deref, deref_trait, Target::Trait;
DerefMutTraitLangItem, sym::deref_mut, deref_mut_trait, Target::Trait;
ReceiverTraitLangItem, sym::receiver, receiver_trait, Target::Trait;
FnTraitLangItem, "fn", fn_trait, Target::Trait;
FnMutTraitLangItem, "fn_mut", fn_mut_trait, Target::Trait;
FnOnceTraitLangItem, "fn_once", fn_once_trait, Target::Trait;
FnTraitLangItem, kw::Fn, fn_trait, Target::Trait;
FnMutTraitLangItem, sym::fn_mut, fn_mut_trait, Target::Trait;
FnOnceTraitLangItem, sym::fn_once, fn_once_trait, Target::Trait;
FnOnceOutputLangItem, "fn_once_output", fn_once_output, Target::AssocTy;
FnOnceOutputLangItem, sym::fn_once_output, fn_once_output, Target::AssocTy;
FutureTraitLangItem, "future_trait", future_trait, Target::Trait;
GeneratorStateLangItem, "generator_state", gen_state, Target::Enum;
GeneratorTraitLangItem, "generator", gen_trait, Target::Trait;
UnpinTraitLangItem, "unpin", unpin_trait, Target::Trait;
PinTypeLangItem, "pin", pin_type, Target::Struct;
FutureTraitLangItem, sym::future_trait, future_trait, Target::Trait;
GeneratorStateLangItem, sym::generator_state, gen_state, Target::Enum;
GeneratorTraitLangItem, sym::generator, gen_trait, Target::Trait;
UnpinTraitLangItem, sym::unpin, unpin_trait, Target::Trait;
PinTypeLangItem, sym::pin, pin_type, Target::Struct;
// Don't be fooled by the naming here: this lang item denotes `PartialEq`, not `Eq`.
EqTraitLangItem, "eq", eq_trait, Target::Trait;
PartialOrdTraitLangItem, "partial_ord", partial_ord_trait, Target::Trait;
EqTraitLangItem, sym::eq, eq_trait, Target::Trait;
PartialOrdTraitLangItem, sym::partial_ord, partial_ord_trait, Target::Trait;
// A number of panic-related lang items. The `panic` item corresponds to
// divide-by-zero and various panic cases with `match`. The
@ -258,39 +257,39 @@ language_item_table! {
// defined to use it, but a final product is required to define it
// somewhere. Additionally, there are restrictions on crates that use a weak
// lang item, but do not have it defined.
PanicFnLangItem, "panic", panic_fn, Target::Fn;
PanicBoundsCheckFnLangItem, "panic_bounds_check", panic_bounds_check_fn, Target::Fn;
PanicInfoLangItem, "panic_info", panic_info, Target::Struct;
PanicLocationLangItem, "panic_location", panic_location, Target::Struct;
PanicImplLangItem, "panic_impl", panic_impl, Target::Fn;
PanicFnLangItem, sym::panic, panic_fn, Target::Fn;
PanicBoundsCheckFnLangItem, sym::panic_bounds_check, panic_bounds_check_fn, Target::Fn;
PanicInfoLangItem, sym::panic_info, panic_info, Target::Struct;
PanicLocationLangItem, sym::panic_location, panic_location, Target::Struct;
PanicImplLangItem, sym::panic_impl, panic_impl, Target::Fn;
// Libstd panic entry point. Necessary for const eval to be able to catch it
BeginPanicFnLangItem, "begin_panic", begin_panic_fn, Target::Fn;
BeginPanicFnLangItem, sym::begin_panic, begin_panic_fn, Target::Fn;
ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn, Target::Fn;
BoxFreeFnLangItem, "box_free", box_free_fn, Target::Fn;
DropInPlaceFnLangItem, "drop_in_place", drop_in_place_fn, Target::Fn;
OomLangItem, "oom", oom, Target::Fn;
AllocLayoutLangItem, "alloc_layout", alloc_layout, Target::Struct;
ExchangeMallocFnLangItem, sym::exchange_malloc, exchange_malloc_fn, Target::Fn;
BoxFreeFnLangItem, sym::box_free, box_free_fn, Target::Fn;
DropInPlaceFnLangItem, sym::drop_in_place, drop_in_place_fn, Target::Fn;
OomLangItem, sym::oom, oom, Target::Fn;
AllocLayoutLangItem, sym::alloc_layout, alloc_layout, Target::Struct;
StartFnLangItem, "start", start_fn, Target::Fn;
StartFnLangItem, sym::start, start_fn, Target::Fn;
CountCodeRegionFnLangItem, "count_code_region", count_code_region_fn, Target::Fn;
CountCodeRegionFnLangItem, sym::count_code_region, count_code_region_fn, Target::Fn;
EhPersonalityLangItem, "eh_personality", eh_personality, Target::Fn;
EhCatchTypeinfoLangItem, "eh_catch_typeinfo", eh_catch_typeinfo, Target::Static;
EhPersonalityLangItem, sym::eh_personality, eh_personality, Target::Fn;
EhCatchTypeinfoLangItem, sym::eh_catch_typeinfo, eh_catch_typeinfo, Target::Static;
OwnedBoxLangItem, "owned_box", owned_box, Target::Struct;
OwnedBoxLangItem, sym::owned_box, owned_box, Target::Struct;
PhantomDataItem, "phantom_data", phantom_data, Target::Struct;
PhantomDataItem, sym::phantom_data, phantom_data, Target::Struct;
ManuallyDropItem, "manually_drop", manually_drop, Target::Struct;
ManuallyDropItem, sym::manually_drop, manually_drop, Target::Struct;
MaybeUninitLangItem, "maybe_uninit", maybe_uninit, Target::Union;
MaybeUninitLangItem, sym::maybe_uninit, maybe_uninit, Target::Union;
// Align offset for stride != 1; must not panic.
AlignOffsetLangItem, "align_offset", align_offset_fn, Target::Fn;
AlignOffsetLangItem, sym::align_offset, align_offset_fn, Target::Fn;
TerminationTraitLangItem, "termination", termination, Target::Trait;
TerminationTraitLangItem, sym::termination, termination, Target::Trait;
TryTraitLangItem, "try", try_trait, Target::Trait;
TryTraitLangItem, kw::Try, try_trait, Target::Trait;
}

View File

@ -1557,7 +1557,7 @@ impl<'a> State<'a> {
let i = &a.inner;
self.s.word("llvm_asm!");
self.popen();
self.print_string(&i.asm.as_str(), i.asm_str_style);
self.print_symbol(i.asm, i.asm_str_style);
self.word_space(":");
let mut out_idx = 0;
@ -1579,8 +1579,8 @@ impl<'a> State<'a> {
self.word_space(":");
let mut in_idx = 0;
self.commasep(Inconsistent, &i.inputs, |s, co| {
s.print_string(&co.as_str(), ast::StrStyle::Cooked);
self.commasep(Inconsistent, &i.inputs, |s, &co| {
s.print_symbol(co, ast::StrStyle::Cooked);
s.popen();
s.print_expr(&a.inputs_exprs[in_idx]);
s.pclose();
@ -1589,8 +1589,8 @@ impl<'a> State<'a> {
self.s.space();
self.word_space(":");
self.commasep(Inconsistent, &i.clobbers, |s, co| {
s.print_string(&co.as_str(), ast::StrStyle::Cooked);
self.commasep(Inconsistent, &i.clobbers, |s, &co| {
s.print_symbol(co, ast::StrStyle::Cooked);
});
let mut options = vec![];

View File

@ -62,11 +62,11 @@ impl AssertModuleSource<'tcx> {
} else if attr.check_name(sym::rustc_partition_codegened) {
(CguReuse::No, ComparisonKind::Exact)
} else if attr.check_name(sym::rustc_expected_cgu_reuse) {
match &*self.field(attr, sym::kind).as_str() {
"no" => (CguReuse::No, ComparisonKind::Exact),
"pre-lto" => (CguReuse::PreLto, ComparisonKind::Exact),
"post-lto" => (CguReuse::PostLto, ComparisonKind::Exact),
"any" => (CguReuse::PreLto, ComparisonKind::AtLeast),
match self.field(attr, sym::kind) {
sym::no => (CguReuse::No, ComparisonKind::Exact),
sym::pre_dash_lto => (CguReuse::PreLto, ComparisonKind::Exact),
sym::post_dash_lto => (CguReuse::PostLto, ComparisonKind::Exact),
sym::any => (CguReuse::PreLto, ComparisonKind::AtLeast),
other => {
self.tcx.sess.span_fatal(
attr.span,
@ -139,7 +139,7 @@ impl AssertModuleSource<'tcx> {
}
self.tcx.sess.cgu_reuse_tracker.set_expectation(
&cgu_name.as_str(),
cgu_name,
&user_path,
attr.span,
expected_reuse,

View File

@ -234,7 +234,7 @@ impl DirtyCleanVisitor<'tcx> {
for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
if item.check_name(LABEL) {
let value = expect_associated_value(self.tcx, &item);
return Some(self.resolve_labels(&item, &value.as_str()));
return Some(self.resolve_labels(&item, value));
}
}
None
@ -245,7 +245,7 @@ impl DirtyCleanVisitor<'tcx> {
for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
if item.check_name(EXCEPT) {
let value = expect_associated_value(self.tcx, &item);
return self.resolve_labels(&item, &value.as_str());
return self.resolve_labels(&item, value);
}
}
// if no `label` or `except` is given, only the node's group are asserted
@ -347,9 +347,9 @@ impl DirtyCleanVisitor<'tcx> {
(name, labels)
}
fn resolve_labels(&self, item: &NestedMetaItem, value: &str) -> Labels {
fn resolve_labels(&self, item: &NestedMetaItem, value: Symbol) -> Labels {
let mut out = Labels::default();
for label in value.split(',') {
for label in value.as_str().split(',') {
let label = label.trim();
if DepNode::has_label_string(label) {
if out.contains(label) {

View File

@ -53,7 +53,7 @@ pub fn add_configuration(
cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat))));
if sess.crt_static(None) {
cfg.insert((tf, Some(Symbol::intern("crt-static"))));
cfg.insert((tf, Some(sym::crt_dash_static)));
}
}
@ -427,11 +427,8 @@ pub(crate) fn check_attr_crate_type(attrs: &[ast::Attribute], lint_buffer: &mut
if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().kind {
let span = spanned.span;
let lev_candidate = find_best_match_for_name(
CRATE_TYPES.iter().map(|(k, _)| k),
&n.as_str(),
None,
);
let lev_candidate =
find_best_match_for_name(CRATE_TYPES.iter().map(|(k, _)| k), n, None);
if let Some(candidate) = lev_candidate {
lint_buffer.buffer_lint_with_diagnostic(
lint::builtin::UNKNOWN_CRATE_TYPES,

View File

@ -394,8 +394,11 @@ impl LintStore {
let symbols =
self.by_name.keys().map(|name| Symbol::intern(&name)).collect::<Vec<_>>();
let suggestion =
find_best_match_for_name(symbols.iter(), &lint_name.to_lowercase(), None);
let suggestion = find_best_match_for_name(
symbols.iter(),
Symbol::intern(&lint_name.to_lowercase()),
None,
);
CheckLintNameResult::NoLint(suggestion)
}

View File

@ -679,8 +679,8 @@ impl<'a> CrateLoader<'a> {
// in terms of everyone has a compatible panic runtime format, that's
// performed later as part of the `dependency_format` module.
let name = match desired_strategy {
PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
PanicStrategy::Abort => Symbol::intern("panic_abort"),
PanicStrategy::Unwind => sym::panic_unwind,
PanicStrategy::Abort => sym::panic_abort,
};
info!("panic runtime not found -- loading {}", name);
@ -713,7 +713,7 @@ impl<'a> CrateLoader<'a> {
{
info!("loading profiler");
let name = Symbol::intern("profiler_builtins");
let name = sym::profiler_builtins;
let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
let data = self.cstore.get_crate_data(cnum);

View File

@ -1,7 +1,7 @@
use rustc_hir as hir;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::sym;
use rustc_span::symbol::{sym, Symbol};
use rustc_target::spec::abi::Abi;
crate fn collect(tcx: TyCtxt<'_>) -> Vec<String> {
@ -11,7 +11,7 @@ crate fn collect(tcx: TyCtxt<'_>) -> Vec<String> {
for attr in tcx.hir().krate().item.attrs.iter() {
if attr.has_name(sym::link_args) {
if let Some(linkarg) = attr.value_str() {
collector.add_link_args(&linkarg.as_str());
collector.add_link_args(linkarg);
}
}
}
@ -36,7 +36,7 @@ impl<'tcx> ItemLikeVisitor<'tcx> for Collector {
// First, add all of the custom #[link_args] attributes
for m in it.attrs.iter().filter(|a| a.check_name(sym::link_args)) {
if let Some(linkarg) = m.value_str() {
self.add_link_args(&linkarg.as_str());
self.add_link_args(linkarg);
}
}
}
@ -46,7 +46,7 @@ impl<'tcx> ItemLikeVisitor<'tcx> for Collector {
}
impl Collector {
fn add_link_args(&mut self, args: &str) {
self.args.extend(args.split(' ').filter(|s| !s.is_empty()).map(|s| s.to_string()))
fn add_link_args(&mut self, args: Symbol) {
self.args.extend(args.as_str().split(' ').filter(|s| !s.is_empty()).map(|s| s.to_string()))
}
}

View File

@ -448,8 +448,7 @@ impl CodegenUnitNameBuilder<'tcx> {
if self.tcx.sess.opts.debugging_opts.human_readable_cgu_names {
cgu_name
} else {
let cgu_name = &cgu_name.as_str();
Symbol::intern(&CodegenUnit::mangle_name(cgu_name))
Symbol::intern(&CodegenUnit::mangle_name(&cgu_name.as_str()))
}
}

View File

@ -2,7 +2,7 @@ use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_middle::mir::*;
use rustc_middle::ty;
use rustc_span::source_map::DesugaringKind;
use rustc_span::{Span, Symbol};
use rustc_span::{sym, Span};
use crate::borrow_check::diagnostics::UseSpans;
use crate::borrow_check::prefixes::PrefixSet;
@ -394,10 +394,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
| ty::Opaque(def_id, _) => def_id,
_ => return err,
};
let is_option =
self.infcx.tcx.is_diagnostic_item(Symbol::intern("option_type"), def_id);
let is_result =
self.infcx.tcx.is_diagnostic_item(Symbol::intern("result_type"), def_id);
let is_option = self.infcx.tcx.is_diagnostic_item(sym::option_type, def_id);
let is_result = self.infcx.tcx.is_diagnostic_item(sym::result_type, def_id);
if (is_option || is_result) && use_spans.map_or(true, |v| !v.for_closure()) {
err.span_suggestion(
span,
@ -409,7 +407,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
Applicability::MaybeIncorrect,
);
} else if matches!(span.desugaring_kind(), Some(DesugaringKind::ForLoop(_)))
&& self.infcx.tcx.is_diagnostic_item(Symbol::intern("vec_type"), def_id)
&& self.infcx.tcx.is_diagnostic_item(sym::vec_type, def_id)
{
// FIXME: suggest for anything that implements `IntoIterator`.
err.span_suggestion(

View File

@ -74,7 +74,7 @@ impl<'a> Parser<'a> {
}
fn mk_doc_comment(&self, s: Symbol) -> ast::Attribute {
attr::mk_doc_comment(comments::doc_comment_style(&s.as_str()), s, self.token.span)
attr::mk_doc_comment(comments::doc_comment_style(s), s, self.token.span)
}
/// Matches `attribute = # ! [ meta_item ]`.

View File

@ -213,7 +213,7 @@ impl TokenCursor {
tok => return tok,
};
let stripped = strip_doc_comment_decoration(&name.as_str());
let stripped = strip_doc_comment_decoration(name);
// Searches for the occurrences of `"#*` and returns the minimum number of `#`s
// required to wrap the text.
@ -250,7 +250,7 @@ impl TokenCursor {
TokenCursorFrame::new(
delim_span,
token::NoDelim,
&if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
&if doc_comment_style(name) == AttrStyle::Inner {
[TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
.iter()
.cloned()

View File

@ -57,7 +57,7 @@ impl LanguageItemCollector<'tcx> {
fn check_for_lang(&mut self, actual_target: Target, hir_id: HirId, attrs: &[Attribute]) {
if let Some((value, span)) = extract(&attrs) {
match ITEM_REFS.get(&*value.as_str()).cloned() {
match ITEM_REFS.get(&value).cloned() {
// Known lang item with attribute on correct target.
Some((item_index, expected_target)) if actual_target == expected_target => {
let def_id = self.tcx.hir().local_def_id(hir_id);

View File

@ -620,7 +620,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
// available as we'd like it to be.
// FIXME: only remove `libc` when `stdbuild` is active.
// FIXME: remove special casing for `test`.
remaining_lib_features.remove(&Symbol::intern("libc"));
remaining_lib_features.remove(&sym::libc);
remaining_lib_features.remove(&sym::test);
let check_features = |remaining_lib_features: &mut FxHashMap<_, _>, defined_features: &[_]| {

View File

@ -81,7 +81,7 @@ impl<'a, 'tcx> Context<'a, 'tcx> {
// `core::intrinsics::code_count_region()` is (currently) the only `extern` lang item
// that is never actually linked. It is not a `weak_lang_item` that can be registered
// when used, and should be registered here instead.
if let Some((item_index, _)) = ITEM_REFS.get(&*name.as_str()).cloned() {
if let Some((item_index, _)) = ITEM_REFS.get(&name).cloned() {
if self.items.items[item_index].is_none() {
let item_def_id = self.tcx.hir().local_def_id(hir_id).to_def_id();
self.items.items[item_index] = Some(item_def_id);

View File

@ -16,7 +16,7 @@ use rustc_middle::ty::{self, DefIdTree};
use rustc_session::Session;
use rustc_span::hygiene::MacroKind;
use rustc_span::source_map::SourceMap;
use rustc_span::symbol::{kw, Ident, Symbol};
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{BytePos, MultiSpan, Span};
use crate::imports::{Import, ImportKind, ImportResolver};
@ -674,7 +674,7 @@ impl<'a> Resolver<'a> {
match find_best_match_for_name(
suggestions.iter().map(|suggestion| &suggestion.candidate),
&ident.as_str(),
ident.name,
None,
) {
Some(found) if found != ident.name => {
@ -882,8 +882,7 @@ impl<'a> Resolver<'a> {
);
self.add_typo_suggestion(err, suggestion, ident.span);
if macro_kind == MacroKind::Derive && (ident.as_str() == "Send" || ident.as_str() == "Sync")
{
if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
err.span_note(ident.span, &msg);
}

View File

@ -1034,8 +1034,7 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
let initial_res = source_bindings[ns].get().map(|initial_binding| {
all_ns_err = false;
if let Some(target_binding) = target_bindings[ns].get() {
// Note that as_str() de-gensyms the Symbol
if target.name.as_str() == "_"
if target.name == kw::Underscore
&& initial_binding.is_extern_crate()
&& !initial_binding.is_import()
{
@ -1133,7 +1132,7 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
});
let lev_suggestion =
find_best_match_for_name(names, &ident.as_str(), None).map(|suggestion| {
find_best_match_for_name(names, ident.name, None).map(|suggestion| {
(
vec![(ident.span, suggestion.to_string())],
String::from("a similar name exists in the module"),

View File

@ -760,7 +760,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
self.r.report_error(
original_span,
ResolutionError::UnreachableLabel {
name: &label.name.as_str(),
name: label.name,
definition_span: ident.span,
suggestion,
},
@ -777,7 +777,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
self.r.report_error(
original_span,
ResolutionError::UndeclaredLabel { name: &label.name.as_str(), suggestion },
ResolutionError::UndeclaredLabel { name: label.name, suggestion },
);
None
}
@ -1550,7 +1550,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
// `Variant(a, a)`:
_ => IdentifierBoundMoreThanOnceInSamePattern,
};
self.r.report_error(ident.span, error(&ident.as_str()));
self.r.report_error(ident.span, error(ident.name));
}
// Record as bound if it's valid:

View File

@ -811,7 +811,7 @@ impl<'a> LateResolutionVisitor<'a, '_, '_> {
match find_best_match_for_name(
names.iter().map(|suggestion| &suggestion.candidate),
&name.as_str(),
name,
None,
) {
Some(found) if found != name => {
@ -1054,7 +1054,7 @@ impl<'a> LateResolutionVisitor<'a, '_, '_> {
.filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
.map(|(id, _)| &id.name);
find_best_match_for_name(names, &label.as_str(), None).map(|symbol| {
find_best_match_for_name(names, label.name, None).map(|symbol| {
// Upon finding a similar name, get the ident that it was from - the span
// contained within helps make a useful diagnostic. In addition, determine
// whether this candidate is within scope.

View File

@ -2364,7 +2364,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
if let Some(params) = error {
// If there's no lifetime available, suggest `'static`.
if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
lifetime_names.insert(Ident::from_str("'static"));
lifetime_names.insert(Ident::with_dummy_span(kw::StaticLifetime));
}
}
self.add_missing_lifetime_specifiers_label(

View File

@ -193,11 +193,11 @@ enum ResolutionError<'a> {
/// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
VariableBoundWithDifferentMode(Symbol, Span),
/// Error E0415: identifier is bound more than once in this parameter list.
IdentifierBoundMoreThanOnceInParameterList(&'a str),
IdentifierBoundMoreThanOnceInParameterList(Symbol),
/// Error E0416: identifier is bound more than once in the same pattern.
IdentifierBoundMoreThanOnceInSamePattern(&'a str),
IdentifierBoundMoreThanOnceInSamePattern(Symbol),
/// Error E0426: use of undeclared label.
UndeclaredLabel { name: &'a str, suggestion: Option<LabelSuggestion> },
UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
/// Error E0429: `self` imports are only allowed within a `{ }` list.
SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
/// Error E0430: `self` import can only appear once in the list.
@ -211,13 +211,13 @@ enum ResolutionError<'a> {
/// Error E0435: attempt to use a non-constant value in a constant.
AttemptToUseNonConstantValueInConstant,
/// Error E0530: `X` bindings cannot shadow `Y`s.
BindingShadowsSomethingUnacceptable(&'a str, Symbol, &'a NameBinding<'a>),
BindingShadowsSomethingUnacceptable(&'static str, Symbol, &'a NameBinding<'a>),
/// Error E0128: type parameters with a default cannot use forward-declared identifiers.
ForwardDeclaredTyParam, // FIXME(const_generics:defaults)
/// Error E0735: type parameters with a default cannot use `Self`
SelfInTyParamDefault,
/// Error E0767: use of unreachable label
UnreachableLabel { name: &'a str, definition_span: Span, suggestion: Option<LabelSuggestion> },
UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
}
enum VisResolutionError<'a> {

View File

@ -824,7 +824,7 @@ impl<'tcx> SaveContext<'tcx> {
for attr in attrs {
if let Some(val) = attr.doc_str() {
if attr.is_doc_comment() {
result.push_str(&strip_doc_comment_decoration(&val.as_str()));
result.push_str(&strip_doc_comment_decoration(val));
} else {
result.push_str(&val.as_str());
}

View File

@ -4,7 +4,7 @@
use log::debug;
use rustc_data_structures::fx::FxHashMap;
use rustc_span::Span;
use rustc_span::{Span, Symbol};
use std::sync::{Arc, Mutex};
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
@ -67,7 +67,7 @@ impl CguReuseTracker {
pub fn set_expectation(
&self,
cgu_name: &str,
cgu_name: Symbol,
cgu_user_name: &str,
error_span: Span,
expected_reuse: CguReuse,

View File

@ -717,18 +717,20 @@ pub fn default_configuration(sess: &Session) -> CrateConfig {
let mut ret = FxHashSet::default();
ret.reserve(6); // the minimum number of insertions
// Target bindings.
ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
ret.insert((sym::target_os, Some(Symbol::intern(os))));
if let Some(ref fam) = sess.target.target.options.target_family {
ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
if fam == "windows" || fam == "unix" {
ret.insert((Symbol::intern(fam), None));
ret.insert((sym::target_family, Some(Symbol::intern(fam))));
if fam == "windows" {
ret.insert((sym::windows, None));
} else if fam == "unix" {
ret.insert((sym::unix, None));
}
}
ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
ret.insert((Symbol::intern("target_pointer_width"), Some(Symbol::intern(wordsz))));
ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
ret.insert((Symbol::intern("target_vendor"), Some(Symbol::intern(vendor))));
ret.insert((sym::target_arch, Some(Symbol::intern(arch))));
ret.insert((sym::target_endian, Some(Symbol::intern(end))));
ret.insert((sym::target_pointer_width, Some(Symbol::intern(wordsz))));
ret.insert((sym::target_env, Some(Symbol::intern(env))));
ret.insert((sym::target_vendor, Some(Symbol::intern(vendor))));
if sess.target.target.options.has_elf_tls {
ret.insert((sym::target_thread_local, None));
}
@ -754,7 +756,7 @@ pub fn default_configuration(sess: &Session) -> CrateConfig {
}
if sess.opts.debug_assertions {
ret.insert((Symbol::intern("debug_assertions"), None));
ret.insert((sym::debug_assertions, None));
}
if sess.opts.crate_types.contains(&CrateType::ProcMacro) {
ret.insert((sym::proc_macro, None));

View File

@ -102,16 +102,23 @@ symbols! {
Union: "union",
}
// Symbols that can be referred to with rustc_span::sym::*. The symbol is
// the stringified identifier unless otherwise specified (e.g.
// `proc_dash_macro` represents "proc-macro").
// Pre-interned symbols that can be referred to with `rustc_span::sym::*`.
//
// The symbol is the stringified identifier unless otherwise specified, in
// which case the name should mention the non-identifier punctuation.
// E.g. `sym::proc_dash_macro` represents "proc-macro", and it shouldn't be
// called `sym::proc_macro` because then it's easy to mistakenly think it
// represents "proc_macro".
//
// As well as the symbols listed, there are symbols for the the strings
// "0", "1", ..., "9", which are accessible via `sym::integer`.
//
// Keep this list in sorted order, as defined by the Unix `sort` utility.
Symbols {
aarch64_target_feature,
abi,
abi_amdgpu_kernel,
abi_avr_interrupt,
abi_efiapi,
abi_msp430_interrupt,
abi_ptx,
@ -120,20 +127,25 @@ symbols! {
abi_unadjusted,
abi_vectorcall,
abi_x86_interrupt,
abi_avr_interrupt,
abort,
aborts,
add,
add_assign,
address,
add_with_overflow,
advanced_slice_patterns,
adx_target_feature,
alias,
align,
align_offset,
alignstack,
all,
alloc,
allocator,
allocator_internals,
alloc_error_handler,
alloc_layout,
alloc_zeroed,
allow,
allowed,
allow_fail,
@ -150,15 +162,18 @@ symbols! {
ArgumentV1,
arith_offset,
arm_target_feature,
array,
asm,
assert,
assert_inhabited,
assert_receiver_is_total_eq,
assert_uninit_valid,
assert_zero_valid,
associated_consts,
associated_type_bounds,
associated_type_defaults,
associated_types,
as_str,
assume,
assume_init,
async_await,
@ -177,19 +192,29 @@ symbols! {
bin,
bind_by_move_pattern_guards,
bindings_after_at,
bitand,
bitand_assign,
bitor,
bitor_assign,
bitreverse,
bitxor,
bitxor_assign,
block,
bool,
borrowck_graphviz_format,
borrowck_graphviz_postflow,
borrowck_graphviz_preflow,
box_free,
box_patterns,
box_syntax,
braced_empty_structs,
breakpoint,
bswap,
bitreverse,
C,
call,
caller_location,
call_mut,
call_once,
cdylib,
ceilf32,
ceilf64,
@ -213,6 +238,7 @@ symbols! {
closure_to_fn_coercion,
cmp,
cmpxchg16b_target_feature,
coerce_unsized,
cold,
column,
compile_error,
@ -230,24 +256,26 @@ symbols! {
const_fn_union,
const_generics,
const_if_match,
const_indexing,
const_in_array_repeat_expressions,
const_indexing,
const_let,
const_loop,
const_mut_refs,
const_panic,
const_precise_live_drops,
const_ptr,
const_raw_ptr_deref,
const_raw_ptr_to_usize_cast,
const_transmute,
const_slice_ptr,
const_trait_bound_opt_out,
const_trait_impl,
const_transmute,
contents,
context,
convert,
copy,
Copy,
copy_closures,
copy,
copy_nonoverlapping,
copysignf32,
copysignf64,
@ -265,22 +293,27 @@ symbols! {
crate_name,
crate_type,
crate_visibility_modifier,
crt_dash_static: "crt-static",
ctlz,
ctlz_nonzero,
ctpop,
cttz,
cttz_nonzero,
ctlz,
ctlz_nonzero,
custom_attribute,
custom_derive,
custom_inner_attributes,
custom_test_frameworks,
c_variadic,
dead_code,
dealloc,
debug,
Debug,
debug_assertions,
debug_trait,
declare_lint_pass,
decl_macro,
debug,
Debug,
Decodable,
decode,
Default,
default_lib_allocator,
default_type_parameter_fallback,
@ -293,7 +326,11 @@ symbols! {
derive,
diagnostic,
direct,
discriminant_kind,
discriminant_value,
dispatch_from_dyn,
div,
div_assign,
doc,
doc_alias,
doc_cfg,
@ -303,40 +340,44 @@ symbols! {
document_private_items,
dotdoteq_in_patterns,
dotdot_in_tuple_patterns,
double_braced_closure: "{{closure}}",
double_braced_constant: "{{constant}}",
double_braced_constructor: "{{constructor}}",
double_braced_crate: "{{crate}}",
double_braced_impl: "{{impl}}",
double_braced_misc: "{{misc}}",
double_braced_closure: "{{closure}}",
double_braced_constructor: "{{constructor}}",
double_braced_constant: "{{constant}}",
double_braced_opaque: "{{opaque}}",
drop,
dropck_eyepatch,
dropck_parametricity,
drop_types_in_const,
drop_in_place,
drop_types_in_const,
dylib,
dyn_trait,
eh_catch_typeinfo,
eh_personality,
enable,
enclosing_scope,
Encodable,
encode,
env,
eq,
err,
Err,
Eq,
Equal,
enclosing_scope,
err,
Err,
exact_div,
except,
exchange_malloc,
exclusive_range_pattern,
exhaustive_integer_patterns,
exhaustive_patterns,
existential_type,
expf32,
expf64,
exp2f32,
exp2f64,
expected,
expf32,
expf64,
export_name,
expr,
extern_absolute_paths,
@ -348,10 +389,12 @@ symbols! {
extern_types,
f16c_target_feature,
f32,
f32_runtime,
f64,
fadd_fast,
f64_runtime,
fabsf32,
fabsf64,
fadd_fast,
fdiv_fast,
feature,
ffi_const,
@ -361,19 +404,23 @@ symbols! {
field_init_shorthand,
file,
float_to_int_unchecked,
floorf64,
floorf32,
floorf64,
fmaf32,
fmaf64,
fmt,
fmt_internals,
fmul_fast,
fn_must_use,
fn_mut,
fn_once,
fn_once_output,
forbid,
forget,
format_args,
format_args_nl,
format_args_capture,
format_args_nl,
freeze,
frem_fast,
from,
From,
@ -382,28 +429,35 @@ symbols! {
from_generator,
from_method,
from_ok,
from_usize,
from_size_align_unchecked,
from_trait,
from_usize,
fsub_fast,
fundamental,
future,
Future,
FxHashSet,
future_trait,
FxHashMap,
gen_future,
gen_kill,
FxHashSet,
ge,
generator,
generators,
generator_state,
generic_associated_types,
generic_param_attrs,
gen_future,
gen_kill,
get_context,
GlobalAlloc,
global_allocator,
global_asm,
globs,
gt,
half_open_range_patterns,
hash,
Hash,
HashSet,
HashMap,
HashSet,
hexagon_target_feature,
hidden,
homogeneous_aggregate,
@ -422,22 +476,22 @@ symbols! {
if_let,
if_while_or_patterns,
ignore,
inlateout,
inout,
impl_header_lifetime_elision,
impl_lint_pass,
impl_trait_in_bindings,
import_shadowing,
index,
index_mut,
in_band_lifetimes,
include,
include_bytes,
include_str,
inclusive_range_syntax,
index,
index_mut,
infer_outlives_requirements,
infer_static_outlives_requirements,
inlateout,
inline,
inout,
Input,
intel,
into_iter,
@ -460,11 +514,14 @@ symbols! {
label_break_value,
lang,
lang_items,
lazy_normalization_consts,
lateout,
Layout,
lazy_normalization_consts,
le,
let_chains,
lhs,
lib,
libc,
lifetime,
likely,
line,
@ -481,14 +538,15 @@ symbols! {
literal,
llvm_asm,
local_inner_macros,
log_syntax,
logf32,
logf64,
log10f32,
log10f64,
log2f32,
log2f64,
logf32,
logf64,
log_syntax,
loop_break_value,
lt,
macro_at_most_once_rep,
macro_escape,
macro_export,
@ -500,57 +558,66 @@ symbols! {
macro_vis_matcher,
main,
managed_boxes,
manually_drop,
marker,
marker_trait_attr,
masked,
match_beginning_vert,
match_default_bindings,
may_dangle,
maxnumf32,
maxnumf64,
maybe_uninit,
maybe_uninit_uninit,
maybe_uninit_zeroed,
mem_uninitialized,
mem_zeroed,
may_dangle,
member_constraints,
memory,
mem_uninitialized,
mem_zeroed,
message,
meta,
min_align_of,
min_align_of_val,
min_const_fn,
min_const_unsafe_fn,
min_specialization,
minnumf32,
minnumf64,
maxnumf32,
maxnumf64,
min_specialization,
mips_target_feature,
miri_start_panic,
mmx_target_feature,
module,
module_path,
more_struct_aliases,
movbe_target_feature,
move_ref_pattern,
move_val_init,
movbe_target_feature,
mul,
mul_assign,
mul_with_overflow,
must_use,
mut_ptr,
mut_slice_ptr,
naked,
naked_functions,
name,
ne,
nearbyintf32,
nearbyintf64,
needs_allocator,
needs_drop,
needs_panic_runtime,
neg,
negate_unsigned,
negative_impls,
never,
never_type,
never_type_fallback,
new,
next,
__next,
next,
nll,
no,
no_builtins,
no_core,
no_crate_inject,
@ -565,11 +632,11 @@ symbols! {
non_ascii_idents,
None,
non_exhaustive,
no_niche,
non_modrs_mods,
nontemporal_store,
nontrapping_fptoint: "nontrapping-fptoint",
nontrapping_dash_fptoint: "nontrapping-fptoint",
noreturn,
no_niche,
no_sanitize,
nostack,
no_stack_check,
@ -584,6 +651,7 @@ symbols! {
on,
on_unimplemented,
oom,
opaque,
ops,
optimize,
optimize_attribute,
@ -592,30 +660,39 @@ symbols! {
Option,
option_env,
options,
option_type,
opt_out_copy,
or,
or_patterns,
Ord,
Ordering,
or_patterns,
out,
Output,
overlapping_marker_traits,
owned_box,
packed,
panic,
panic_abort,
panic_bounds_check,
panic_handler,
panic_impl,
panic_implementation,
panic_info,
panic_location,
panic_runtime,
panic_unwind,
param_attrs,
parent_trait,
partial_cmp,
param_attrs,
PartialEq,
partial_ord,
PartialOrd,
passes,
pat,
path,
pattern_parentheses,
Pending,
phantom_data,
pin,
Pin,
pinned,
@ -623,14 +700,17 @@ symbols! {
plugin,
plugin_registrar,
plugins,
pointer,
poll,
Poll,
post_dash_lto: "post-lto",
powerpc_target_feature,
powf32,
powf64,
powif32,
powif64,
precise_pointer_size_matching,
pre_dash_lto: "pre-lto",
pref_align_of,
prefetch_read_data,
prefetch_read_instruction,
@ -641,19 +721,19 @@ symbols! {
preserves_flags,
primitive,
proc_dash_macro: "proc-macro",
ProceduralMasqueradeDummyType,
proc_macro,
proc_macro_attribute,
proc_macro_def_site,
proc_macro_derive,
proc_macro_expr,
proc_macro_gen,
ProcMacroHack,
proc_macro_hygiene,
proc_macro_internals,
proc_macro_mod,
proc_macro_non_items,
proc_macro_path_invoc,
ProceduralMasqueradeDummyType,
ProcMacroHack,
profiler_builtins,
profiler_runtime,
ptr_guaranteed_eq,
@ -677,13 +757,18 @@ symbols! {
Rc,
readonly,
Ready,
realloc,
reason,
receiver,
recursion_limit,
reexport_test_harness_main,
reference,
reflect,
register_attr,
register_tool,
relaxed_adts,
rem,
rem_assign,
repr,
repr128,
repr_align,
@ -695,6 +780,7 @@ symbols! {
re_rebalance_coherence,
result,
Result,
result_type,
Return,
rhs,
rintf32,
@ -712,8 +798,6 @@ symbols! {
rust_2018_preview,
rust_begin_unwind,
rustc,
RustcDecodable,
RustcEncodable,
rustc_allocator,
rustc_allocator_nounwind,
rustc_allow_const_fn_ptr,
@ -721,9 +805,10 @@ symbols! {
rustc_attrs,
rustc_builtin_macro,
rustc_clean,
rustc_const_unstable,
rustc_const_stable,
rustc_const_unstable,
rustc_conversion_suggestion,
RustcDecodable,
rustc_def_path,
rustc_deprecated,
rustc_diagnostic_item,
@ -733,6 +818,7 @@ symbols! {
rustc_dump_env_program_clauses,
rustc_dump_program_clauses,
rustc_dump_user_substs,
RustcEncodable,
rustc_error,
rustc_expected_cgu_reuse,
rustc_if_this_changed,
@ -751,26 +837,28 @@ symbols! {
rustc_partition_reused,
rustc_peek,
rustc_peek_definite_init,
rustc_peek_indirectly_mutable,
rustc_peek_liveness,
rustc_peek_maybe_init,
rustc_peek_maybe_uninit,
rustc_peek_indirectly_mutable,
rustc_private,
rustc_proc_macro_decls,
rustc_promotable,
rustc_regions,
rustc_unsafe_specialization_marker,
rustc_reservation_impl,
rustc_specialization_trait,
rustc_stable,
rustc_std_internal_symbol,
rustc_symbol_name,
rustc_synthetic,
rustc_reservation_impl,
rustc_test_marker,
rustc_then_this_would_need,
rustc_unsafe_specialization_marker,
rustc_variance,
rustfmt,
rust_eh_personality,
rust_eh_register_frames,
rust_eh_unregister_frames,
rustfmt,
rust_oom,
rvalue_static_promotion,
sanitize,
@ -780,19 +868,83 @@ symbols! {
_Self,
self_in_typedefs,
self_struct_ctor,
semitransparent,
Send,
send_trait,
shl,
shl_assign,
should_panic,
shr,
shr_assign,
simd,
simd_add,
simd_and,
simd_bitmask,
simd_cast,
simd_ceil,
simd_div,
simd_eq,
simd_extract,
simd_fabs,
simd_fcos,
simd_fexp,
simd_fexp2,
simd_ffi,
simd_flog,
simd_flog10,
simd_flog2,
simd_floor,
simd_fma,
simd_fmax,
simd_fmin,
simd_fpow,
simd_fpowi,
simd_fsin,
simd_fsqrt,
simd_gather,
simd_ge,
simd_gt,
simd_insert,
simd_le,
simd_lt,
simd_mul,
simd_ne,
simd_or,
simd_reduce_add_ordered,
simd_reduce_add_unordered,
simd_reduce_all,
simd_reduce_and,
simd_reduce_any,
simd_reduce_max,
simd_reduce_max_nanless,
simd_reduce_min,
simd_reduce_min_nanless,
simd_reduce_mul_ordered,
simd_reduce_mul_unordered,
simd_reduce_or,
simd_reduce_xor,
simd_rem,
simd_saturating_add,
simd_saturating_sub,
simd_scatter,
simd_select,
simd_select_bitmask,
simd_shl,
simd_shr,
simd_sub,
simd_xor,
since,
sinf32,
sinf64,
size,
sized,
size_of,
size_of_val,
slice,
slice_alloc,
slice_patterns,
slice_u8,
slice_u8_alloc,
slicing_syntax,
soft,
Some,
@ -810,28 +962,45 @@ symbols! {
static_recursion,
std,
std_inject,
str,
stringify,
stmt,
stmt_expr_attributes,
stop_after_dataflow,
str,
str_alloc,
stringify,
struct_field_attributes,
struct_inherit,
structural_match,
structural_peq,
structural_teq,
struct_variant,
sty,
sub,
sub_assign,
sub_with_overflow,
suggestion,
sym,
sync,
Sync,
sync_trait,
Target,
target_arch,
target_endian,
target_env,
target_family,
target_feature,
target_feature_11,
target_has_atomic,
target_has_atomic_load_store,
target_os,
target_pointer_width,
target_target_vendor,
target_thread_local,
target_vendor,
task,
_task_context,
tbm_target_feature,
termination,
termination_trait,
termination_trait_test,
test,
@ -859,19 +1028,20 @@ symbols! {
try_blocks,
try_trait,
tt,
tuple,
tuple_indexing,
two_phase,
Ty,
ty,
type_alias_impl_trait,
type_id,
type_name,
Ty,
TyCtxt,
TyKind,
type_alias_enum_variants,
type_alias_impl_trait,
type_ascription,
type_id,
type_length_limit,
type_macros,
type_name,
u128,
u16,
u32,
@ -891,18 +1061,24 @@ symbols! {
underscore_imports,
underscore_lifetimes,
uniform_paths,
unit,
universal_impl_trait,
unix,
unlikely,
unmarked_api,
unpin,
unreachable,
unreachable_code,
unrestricted_attribute_tokens,
unsafe_block_in_unsafe_fn,
unsafe_cell,
unsafe_no_drop_flag,
unsize,
unsized_locals,
unsized_tuple_coercion,
unstable,
untagged_unions,
unused_qualifications,
unwind,
unwind_attributes,
unwrap_or,
@ -911,15 +1087,17 @@ symbols! {
use_nested_groups,
usize,
v1,
val,
var,
variant_count,
va_arg,
va_copy,
va_end,
val,
va_list,
var,
variant_count,
va_start,
vec,
Vec,
vec_type,
version,
vis,
visible_private_types,
@ -936,8 +1114,8 @@ symbols! {
windows,
windows_subsystem,
wrapping_add,
wrapping_sub,
wrapping_mul,
wrapping_sub,
write_bytes,
Yield,
}
@ -1419,7 +1597,7 @@ impl !Sync for SymbolStr {}
/// This impl means that if `ss` is a `SymbolStr`:
/// - `*ss` is a `str`;
/// - `&*ss` is a `&str`;
/// - `&*ss` is a `&str` (and `match &*ss { ... }` is a common pattern).
/// - `&ss as &str` is a `&str`, which means that `&ss` can be passed to a
/// function expecting a `&str`.
impl std::ops::Deref for SymbolStr {

View File

@ -6,7 +6,7 @@ use rustc_infer::infer::InferCtxt;
use rustc_middle::ty::{self, TraitRef, Ty, TyCtxt, WithConstness};
use rustc_middle::ty::{ToPredicate, TypeFoldable};
use rustc_session::DiagnosticMessageId;
use rustc_span::symbol::Ident;
use rustc_span::symbol::{sym, Ident};
use rustc_span::Span;
#[derive(Copy, Clone, Debug)]
@ -143,7 +143,11 @@ impl<'a, 'tcx> Autoderef<'a, 'tcx> {
let normalized_ty = fulfillcx.normalize_projection_type(
&self.infcx,
self.param_env,
ty::ProjectionTy::from_ref_and_name(tcx, trait_ref, Ident::from_str("Target")),
ty::ProjectionTy::from_ref_and_name(
tcx,
trait_ref,
Ident::with_dummy_span(sym::Target),
),
cause,
);
if let Err(e) = fulfillcx.select_where_possible(&self.infcx) {

View File

@ -1247,7 +1247,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
.generic_args()
.bindings
.iter()
.find_map(|b| match (b.ident.as_str() == "Output", &b.kind) {
.find_map(|b| match (b.ident.name == sym::Output, &b.kind) {
(true, hir::TypeBindingKind::Equality { ty }) => {
sess.source_map().span_to_snippet(ty.span).ok()
}
@ -2254,7 +2254,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
.collect();
if let (Some(suggested_name), true) = (
find_best_match_for_name(all_candidate_names.iter(), &assoc_name.as_str(), None),
find_best_match_for_name(all_candidate_names.iter(), assoc_name.name, None),
assoc_name.span != DUMMY_SP,
) {
err.span_suggestion(
@ -2354,7 +2354,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
if let Some(suggested_name) = find_best_match_for_name(
adt_def.variants.iter().map(|variant| &variant.ident.name),
&assoc_ident.as_str(),
assoc_ident.name,
None,
) {
err.span_suggestion(

View File

@ -13,7 +13,7 @@ use rustc_middle::ty::adjustment::{
};
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
use rustc_span::symbol::Ident;
use rustc_span::symbol::{sym, Ident};
use rustc_span::Span;
use rustc_target::spec::abi;
use rustc_trait_selection::autoderef::Autoderef;
@ -192,9 +192,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
// Try the options that are least restrictive on the caller first.
for &(opt_trait_def_id, method_name, borrow) in &[
(self.tcx.lang_items().fn_trait(), Ident::from_str("call"), true),
(self.tcx.lang_items().fn_mut_trait(), Ident::from_str("call_mut"), true),
(self.tcx.lang_items().fn_once_trait(), Ident::from_str("call_once"), false),
(self.tcx.lang_items().fn_trait(), Ident::with_dummy_span(sym::call), true),
(self.tcx.lang_items().fn_mut_trait(), Ident::with_dummy_span(sym::call_mut), true),
(self.tcx.lang_items().fn_once_trait(), Ident::with_dummy_span(sym::call_once), false),
] {
let trait_def_id = match opt_trait_def_id {
Some(def_id) => def_id,

View File

@ -1336,7 +1336,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// prevent all specified fields from being suggested
let skip_fields = skip_fields.iter().map(|ref x| x.ident.name);
if let Some(field_name) =
Self::suggest_field_name(variant, &field.ident.as_str(), skip_fields.collect())
Self::suggest_field_name(variant, field.ident.name, skip_fields.collect())
{
err.span_suggestion(
field.ident.span,
@ -1377,7 +1377,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// Return an hint about the closest match in field names
fn suggest_field_name(
variant: &'tcx ty::VariantDef,
field: &str,
field: Symbol,
skip: Vec<Symbol>,
) -> Option<Symbol> {
let names = variant.fields.iter().filter_map(|field| {
@ -1621,7 +1621,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
field: Ident,
) {
if let Some(suggested_field_name) =
Self::suggest_field_name(def.non_enum_variant(), &field.as_str(), vec![])
Self::suggest_field_name(def.non_enum_variant(), field.name, vec![])
{
err.span_suggestion(
field.span,

View File

@ -423,70 +423,81 @@ pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>)
};
let def_id = tcx.hir().local_def_id(it.hir_id).to_def_id();
let name = it.ident.as_str();
let name = it.ident.name;
let (n_tps, inputs, output) = match &*name {
"simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
let (n_tps, inputs, output) = match name {
sym::simd_eq | sym::simd_ne | sym::simd_lt | sym::simd_le | sym::simd_gt | sym::simd_ge => {
(2, vec![param(0), param(0)], param(1))
}
"simd_add"
| "simd_sub"
| "simd_mul"
| "simd_rem"
| "simd_div"
| "simd_shl"
| "simd_shr"
| "simd_and"
| "simd_or"
| "simd_xor"
| "simd_fmin"
| "simd_fmax"
| "simd_fpow"
| "simd_saturating_add"
| "simd_saturating_sub" => (1, vec![param(0), param(0)], param(0)),
"simd_fsqrt" | "simd_fsin" | "simd_fcos" | "simd_fexp" | "simd_fexp2" | "simd_flog2"
| "simd_flog10" | "simd_flog" | "simd_fabs" | "simd_floor" | "simd_ceil" => {
(1, vec![param(0)], param(0))
sym::simd_add
| sym::simd_sub
| sym::simd_mul
| sym::simd_rem
| sym::simd_div
| sym::simd_shl
| sym::simd_shr
| sym::simd_and
| sym::simd_or
| sym::simd_xor
| sym::simd_fmin
| sym::simd_fmax
| sym::simd_fpow
| sym::simd_saturating_add
| sym::simd_saturating_sub => (1, vec![param(0), param(0)], param(0)),
sym::simd_fsqrt
| sym::simd_fsin
| sym::simd_fcos
| sym::simd_fexp
| sym::simd_fexp2
| sym::simd_flog2
| sym::simd_flog10
| sym::simd_flog
| sym::simd_fabs
| sym::simd_floor
| sym::simd_ceil => (1, vec![param(0)], param(0)),
sym::simd_fpowi => (1, vec![param(0), tcx.types.i32], param(0)),
sym::simd_fma => (1, vec![param(0), param(0), param(0)], param(0)),
sym::simd_gather => (3, vec![param(0), param(1), param(2)], param(0)),
sym::simd_scatter => (3, vec![param(0), param(1), param(2)], tcx.mk_unit()),
sym::simd_insert => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
sym::simd_extract => (2, vec![param(0), tcx.types.u32], param(1)),
sym::simd_cast => (2, vec![param(0)], param(1)),
sym::simd_bitmask => (2, vec![param(0)], param(1)),
sym::simd_select | sym::simd_select_bitmask => {
(2, vec![param(0), param(1), param(1)], param(1))
}
"simd_fpowi" => (1, vec![param(0), tcx.types.i32], param(0)),
"simd_fma" => (1, vec![param(0), param(0), param(0)], param(0)),
"simd_gather" => (3, vec![param(0), param(1), param(2)], param(0)),
"simd_scatter" => (3, vec![param(0), param(1), param(2)], tcx.mk_unit()),
"simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
"simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
"simd_cast" => (2, vec![param(0)], param(1)),
"simd_bitmask" => (2, vec![param(0)], param(1)),
"simd_select" | "simd_select_bitmask" => (2, vec![param(0), param(1), param(1)], param(1)),
"simd_reduce_all" | "simd_reduce_any" => (1, vec![param(0)], tcx.types.bool),
"simd_reduce_add_ordered" | "simd_reduce_mul_ordered" => {
sym::simd_reduce_all | sym::simd_reduce_any => (1, vec![param(0)], tcx.types.bool),
sym::simd_reduce_add_ordered | sym::simd_reduce_mul_ordered => {
(2, vec![param(0), param(1)], param(1))
}
"simd_reduce_add_unordered"
| "simd_reduce_mul_unordered"
| "simd_reduce_and"
| "simd_reduce_or"
| "simd_reduce_xor"
| "simd_reduce_min"
| "simd_reduce_max"
| "simd_reduce_min_nanless"
| "simd_reduce_max_nanless" => (2, vec![param(0)], param(1)),
name if name.starts_with("simd_shuffle") => match name["simd_shuffle".len()..].parse() {
Ok(n) => {
let params = vec![param(0), param(0), tcx.mk_array(tcx.types.u32, n)];
(2, params, param(1))
sym::simd_reduce_add_unordered
| sym::simd_reduce_mul_unordered
| sym::simd_reduce_and
| sym::simd_reduce_or
| sym::simd_reduce_xor
| sym::simd_reduce_min
| sym::simd_reduce_max
| sym::simd_reduce_min_nanless
| sym::simd_reduce_max_nanless => (2, vec![param(0)], param(1)),
name if name.as_str().starts_with("simd_shuffle") => {
match name.as_str()["simd_shuffle".len()..].parse() {
Ok(n) => {
let params = vec![param(0), param(0), tcx.mk_array(tcx.types.u32, n)];
(2, params, param(1))
}
Err(_) => {
struct_span_err!(
tcx.sess,
it.span,
E0439,
"invalid `simd_shuffle`, needs length: `{}`",
name
)
.emit();
return;
}
}
Err(_) => {
struct_span_err!(
tcx.sess,
it.span,
E0439,
"invalid `simd_shuffle`, needs length: `{}`",
name
)
.emit();
return;
}
},
}
_ => {
let msg = format!("unrecognized platform-specific intrinsic function: `{}`", name);
tcx.sess.struct_span_err(it.span, &msg).emit();

View File

@ -1536,7 +1536,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
} else {
let best_name = {
let names = applicable_close_candidates.iter().map(|cand| &cand.ident.name);
find_best_match_for_name(names, &self.method_name.unwrap().as_str(), None)
find_best_match_for_name(names, self.method_name.unwrap().name, None)
}
.unwrap();
Ok(applicable_close_candidates

View File

@ -17,7 +17,7 @@ use rustc_middle::ty::print::with_crate_prefix;
use rustc_middle::ty::{
self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
};
use rustc_span::symbol::{kw, Ident};
use rustc_span::symbol::{kw, sym, Ident};
use rustc_span::{source_map, FileName, Span};
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
use rustc_trait_selection::traits::Obligation;
@ -729,7 +729,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let adt_def = actual.ty_adt_def().expect("enum is not an ADT");
if let Some(suggestion) = lev_distance::find_best_match_for_name(
adt_def.variants.iter().map(|s| &s.ident.name),
&item_name.as_str(),
item_name.name,
None,
) {
err.span_suggestion(
@ -743,7 +743,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let mut fallback_span = true;
let msg = "remove this method call";
if item_name.as_str() == "as_str" && actual.peel_refs().is_str() {
if item_name.name == sym::as_str && actual.peel_refs().is_str() {
if let SelfSource::MethodCall(expr) = source {
let call_expr =
self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id));

View File

@ -13,7 +13,7 @@ use rustc_middle::ty::TyKind::{Adt, Array, Char, FnDef, Never, Ref, Str, Tuple,
use rustc_middle::ty::{
self, suggest_constraining_type_param, Ty, TyCtxt, TypeFoldable, TypeVisitor,
};
use rustc_span::symbol::Ident;
use rustc_span::symbol::{sym, Ident};
use rustc_span::Span;
use rustc_trait_selection::infer::InferCtxtExt;
@ -702,16 +702,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};
let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
match op.node {
hir::BinOpKind::Add => ("add_assign", lang.add_assign_trait()),
hir::BinOpKind::Sub => ("sub_assign", lang.sub_assign_trait()),
hir::BinOpKind::Mul => ("mul_assign", lang.mul_assign_trait()),
hir::BinOpKind::Div => ("div_assign", lang.div_assign_trait()),
hir::BinOpKind::Rem => ("rem_assign", lang.rem_assign_trait()),
hir::BinOpKind::BitXor => ("bitxor_assign", lang.bitxor_assign_trait()),
hir::BinOpKind::BitAnd => ("bitand_assign", lang.bitand_assign_trait()),
hir::BinOpKind::BitOr => ("bitor_assign", lang.bitor_assign_trait()),
hir::BinOpKind::Shl => ("shl_assign", lang.shl_assign_trait()),
hir::BinOpKind::Shr => ("shr_assign", lang.shr_assign_trait()),
hir::BinOpKind::Add => (sym::add_assign, lang.add_assign_trait()),
hir::BinOpKind::Sub => (sym::sub_assign, lang.sub_assign_trait()),
hir::BinOpKind::Mul => (sym::mul_assign, lang.mul_assign_trait()),
hir::BinOpKind::Div => (sym::div_assign, lang.div_assign_trait()),
hir::BinOpKind::Rem => (sym::rem_assign, lang.rem_assign_trait()),
hir::BinOpKind::BitXor => (sym::bitxor_assign, lang.bitxor_assign_trait()),
hir::BinOpKind::BitAnd => (sym::bitand_assign, lang.bitand_assign_trait()),
hir::BinOpKind::BitOr => (sym::bitor_assign, lang.bitor_assign_trait()),
hir::BinOpKind::Shl => (sym::shl_assign, lang.shl_assign_trait()),
hir::BinOpKind::Shr => (sym::shr_assign, lang.shr_assign_trait()),
hir::BinOpKind::Lt
| hir::BinOpKind::Le
| hir::BinOpKind::Ge
@ -725,30 +725,30 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
} else if let Op::Binary(op, IsAssign::No) = op {
match op.node {
hir::BinOpKind::Add => ("add", lang.add_trait()),
hir::BinOpKind::Sub => ("sub", lang.sub_trait()),
hir::BinOpKind::Mul => ("mul", lang.mul_trait()),
hir::BinOpKind::Div => ("div", lang.div_trait()),
hir::BinOpKind::Rem => ("rem", lang.rem_trait()),
hir::BinOpKind::BitXor => ("bitxor", lang.bitxor_trait()),
hir::BinOpKind::BitAnd => ("bitand", lang.bitand_trait()),
hir::BinOpKind::BitOr => ("bitor", lang.bitor_trait()),
hir::BinOpKind::Shl => ("shl", lang.shl_trait()),
hir::BinOpKind::Shr => ("shr", lang.shr_trait()),
hir::BinOpKind::Lt => ("lt", lang.partial_ord_trait()),
hir::BinOpKind::Le => ("le", lang.partial_ord_trait()),
hir::BinOpKind::Ge => ("ge", lang.partial_ord_trait()),
hir::BinOpKind::Gt => ("gt", lang.partial_ord_trait()),
hir::BinOpKind::Eq => ("eq", lang.eq_trait()),
hir::BinOpKind::Ne => ("ne", lang.eq_trait()),
hir::BinOpKind::Add => (sym::add, lang.add_trait()),
hir::BinOpKind::Sub => (sym::sub, lang.sub_trait()),
hir::BinOpKind::Mul => (sym::mul, lang.mul_trait()),
hir::BinOpKind::Div => (sym::div, lang.div_trait()),
hir::BinOpKind::Rem => (sym::rem, lang.rem_trait()),
hir::BinOpKind::BitXor => (sym::bitxor, lang.bitxor_trait()),
hir::BinOpKind::BitAnd => (sym::bitand, lang.bitand_trait()),
hir::BinOpKind::BitOr => (sym::bitor, lang.bitor_trait()),
hir::BinOpKind::Shl => (sym::shl, lang.shl_trait()),
hir::BinOpKind::Shr => (sym::shr, lang.shr_trait()),
hir::BinOpKind::Lt => (sym::lt, lang.partial_ord_trait()),
hir::BinOpKind::Le => (sym::le, lang.partial_ord_trait()),
hir::BinOpKind::Ge => (sym::ge, lang.partial_ord_trait()),
hir::BinOpKind::Gt => (sym::gt, lang.partial_ord_trait()),
hir::BinOpKind::Eq => (sym::eq, lang.eq_trait()),
hir::BinOpKind::Ne => (sym::ne, lang.eq_trait()),
hir::BinOpKind::And | hir::BinOpKind::Or => {
span_bug!(span, "&& and || are not overloadable")
}
}
} else if let Op::Unary(hir::UnOp::UnNot, _) = op {
("not", lang.not_trait())
(sym::not, lang.not_trait())
} else if let Op::Unary(hir::UnOp::UnNeg, _) = op {
("neg", lang.neg_trait())
(sym::neg, lang.neg_trait())
} else {
bug!("lookup_op_method: op not supported: {:?}", op)
};
@ -759,7 +759,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
);
let method = trait_did.and_then(|trait_did| {
let opname = Ident::from_str(opname);
let opname = Ident::with_dummy_span(opname);
self.lookup_method_in_trait(span, opname, trait_did, lhs_ty, Some(other_tys))
});

View File

@ -1216,7 +1216,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
);
if plural == "" {
let input = unmentioned_fields.iter().map(|field| &field.name);
let suggested_name = find_best_match_for_name(input, &ident.as_str(), None);
let suggested_name = find_best_match_for_name(input, ident.name, None);
if let Some(suggested_name) = suggested_name {
err.span_suggestion(
ident.span,

View File

@ -162,8 +162,8 @@ impl Cfg {
Cfg::Any(ref sub_cfgs) | Cfg::All(ref sub_cfgs) => {
sub_cfgs.first().map(Cfg::should_capitalize_first_letter).unwrap_or(false)
}
Cfg::Cfg(name, _) => match &*name.as_str() {
"debug_assertions" | "target_endian" => true,
Cfg::Cfg(name, _) => match name {
sym::debug_assertions | sym::target_endian => true,
_ => false,
},
}
@ -347,12 +347,11 @@ impl<'a> fmt::Display for Html<'a> {
Cfg::False => fmt.write_str("nowhere"),
Cfg::Cfg(name, value) => {
let n = &*name.as_str();
let human_readable = match (n, value) {
("unix", None) => "Unix",
("windows", None) => "Windows",
("debug_assertions", None) => "debug-assertions enabled",
("target_os", Some(os)) => match &*os.as_str() {
let human_readable = match (name, value) {
(sym::unix, None) => "Unix",
(sym::windows, None) => "Windows",
(sym::debug_assertions, None) => "debug-assertions enabled",
(sym::target_os, Some(os)) => match &*os.as_str() {
"android" => "Android",
"dragonfly" => "DragonFly BSD",
"emscripten" => "Emscripten",
@ -372,7 +371,7 @@ impl<'a> fmt::Display for Html<'a> {
"windows" => "Windows",
_ => "",
},
("target_arch", Some(arch)) => match &*arch.as_str() {
(sym::target_arch, Some(arch)) => match &*arch.as_str() {
"aarch64" => "AArch64",
"arm" => "ARM",
"asmjs" => "JavaScript",
@ -388,7 +387,7 @@ impl<'a> fmt::Display for Html<'a> {
"x86_64" => "x86-64",
_ => "",
},
("target_vendor", Some(vendor)) => match &*vendor.as_str() {
(sym::target_vendor, Some(vendor)) => match &*vendor.as_str() {
"apple" => "Apple",
"pc" => "PC",
"rumprun" => "Rumprun",
@ -396,7 +395,7 @@ impl<'a> fmt::Display for Html<'a> {
"fortanix" => "Fortanix",
_ => "",
},
("target_env", Some(env)) => match &*env.as_str() {
(sym::target_env, Some(env)) => match &*env.as_str() {
"gnu" => "GNU",
"msvc" => "MSVC",
"musl" => "musl",
@ -405,9 +404,9 @@ impl<'a> fmt::Display for Html<'a> {
"sgx" => "SGX",
_ => "",
},
("target_endian", Some(endian)) => return write!(fmt, "{}-endian", endian),
("target_pointer_width", Some(bits)) => return write!(fmt, "{}-bit", bits),
("target_feature", Some(feat)) => {
(sym::target_endian, Some(endian)) => return write!(fmt, "{}-endian", endian),
(sym::target_pointer_width, Some(bits)) => return write!(fmt, "{}-bit", bits),
(sym::target_feature, Some(feat)) => {
if self.1 {
return write!(fmt, "<code>{}</code>", feat);
} else {
@ -419,9 +418,14 @@ impl<'a> fmt::Display for Html<'a> {
if !human_readable.is_empty() {
fmt.write_str(human_readable)
} else if let Some(v) = value {
write!(fmt, "<code>{}=\"{}\"</code>", Escape(n), Escape(&v.as_str()))
write!(
fmt,
"<code>{}=\"{}\"</code>",
Escape(&name.as_str()),
Escape(&v.as_str())
)
} else {
write!(fmt, "<code>{}</code>", Escape(n))
write!(fmt, "<code>{}</code>", Escape(&name.as_str()))
}
}
}

View File

@ -114,7 +114,7 @@ impl Clean<ExternalCrate> for CrateNum {
for attr in attrs.lists(sym::doc) {
if let Some(v) = attr.value_str() {
if attr.check_name(sym::primitive) {
prim = PrimitiveType::from_str(&v.as_str());
prim = PrimitiveType::from_symbol(v);
if prim.is_some() {
break;
}

View File

@ -21,7 +21,7 @@ use rustc_index::vec::IndexVec;
use rustc_middle::middle::stability;
use rustc_span::hygiene::MacroKind;
use rustc_span::source_map::DUMMY_SP;
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{self, FileName};
use rustc_target::abi::VariantIdx;
use rustc_target::spec::abi::Abi;
@ -540,7 +540,7 @@ impl Attributes {
.filter_map(|attr| {
if let Some(value) = attr.doc_str() {
let (value, mk_fragment): (_, fn(_, _, _) -> _) = if attr.is_doc_comment() {
(strip_doc_comment_decoration(&value.as_str()), DocFragment::SugaredDoc)
(strip_doc_comment_decoration(value), DocFragment::SugaredDoc)
} else {
(value.to_string(), DocFragment::RawDoc)
};
@ -1230,33 +1230,33 @@ impl GetDefId for Type {
}
impl PrimitiveType {
pub fn from_str(s: &str) -> Option<PrimitiveType> {
pub fn from_symbol(s: Symbol) -> Option<PrimitiveType> {
match s {
"isize" => Some(PrimitiveType::Isize),
"i8" => Some(PrimitiveType::I8),
"i16" => Some(PrimitiveType::I16),
"i32" => Some(PrimitiveType::I32),
"i64" => Some(PrimitiveType::I64),
"i128" => Some(PrimitiveType::I128),
"usize" => Some(PrimitiveType::Usize),
"u8" => Some(PrimitiveType::U8),
"u16" => Some(PrimitiveType::U16),
"u32" => Some(PrimitiveType::U32),
"u64" => Some(PrimitiveType::U64),
"u128" => Some(PrimitiveType::U128),
"bool" => Some(PrimitiveType::Bool),
"char" => Some(PrimitiveType::Char),
"str" => Some(PrimitiveType::Str),
"f32" => Some(PrimitiveType::F32),
"f64" => Some(PrimitiveType::F64),
"array" => Some(PrimitiveType::Array),
"slice" => Some(PrimitiveType::Slice),
"tuple" => Some(PrimitiveType::Tuple),
"unit" => Some(PrimitiveType::Unit),
"pointer" => Some(PrimitiveType::RawPointer),
"reference" => Some(PrimitiveType::Reference),
"fn" => Some(PrimitiveType::Fn),
"never" => Some(PrimitiveType::Never),
sym::isize => Some(PrimitiveType::Isize),
sym::i8 => Some(PrimitiveType::I8),
sym::i16 => Some(PrimitiveType::I16),
sym::i32 => Some(PrimitiveType::I32),
sym::i64 => Some(PrimitiveType::I64),
sym::i128 => Some(PrimitiveType::I128),
sym::usize => Some(PrimitiveType::Usize),
sym::u8 => Some(PrimitiveType::U8),
sym::u16 => Some(PrimitiveType::U16),
sym::u32 => Some(PrimitiveType::U32),
sym::u64 => Some(PrimitiveType::U64),
sym::u128 => Some(PrimitiveType::U128),
sym::bool => Some(PrimitiveType::Bool),
sym::char => Some(PrimitiveType::Char),
sym::str => Some(PrimitiveType::Str),
sym::f32 => Some(PrimitiveType::F32),
sym::f64 => Some(PrimitiveType::F64),
sym::array => Some(PrimitiveType::Array),
sym::slice => Some(PrimitiveType::Slice),
sym::tuple => Some(PrimitiveType::Tuple),
sym::unit => Some(PrimitiveType::Unit),
sym::pointer => Some(PrimitiveType::RawPointer),
sym::reference => Some(PrimitiveType::Reference),
kw::Fn => Some(PrimitiveType::Fn),
sym::never => Some(PrimitiveType::Never),
_ => None,
}
}

View File

@ -10,7 +10,10 @@
macro_rules! foo /* 0#0 */ { ($ x : ident) => { y + $ x } }
fn bar /* 0#0 */() { let x /* 0#0 */ = 1; y /* 0#1 */ + x /* 0#0 */ }
fn bar /* 0#0 */() {
let x /* 0#0 */ = 1;
y /* 0#1 */ + x /* 0#0 */
}
fn y /* 0#0 */() { }

View File

@ -421,7 +421,11 @@ fn check_clippy_lint_names(cx: &LateContext<'_>, ident: &str, items: &[NestedMet
.iter()
.map(|l| Symbol::intern(&l.name_lower()))
.collect::<Vec<_>>();
let sugg = find_best_match_for_name(symbols.iter(), &format!("clippy::{}", name_lower), None);
let sugg = find_best_match_for_name(
symbols.iter(),
Symbol::intern(&format!("clippy::{}", name_lower)),
None,
);
if lint_name.chars().any(char::is_uppercase)
&& lint_store.find_lints(&format!("clippy::{}", name_lower)).is_ok()
{