Skip to content

Commit

Permalink
Remove lots of Symbol::as_str() calls.
Browse files Browse the repository at this point in the history
In various ways, such as changing functions to take a `Symbol` instead
of a `&str`.
  • Loading branch information
nnethercote committed Jul 14, 2020
1 parent f04e866 commit 5930081
Show file tree
Hide file tree
Showing 30 changed files with 121 additions and 96 deletions.
9 changes: 6 additions & 3 deletions src/librustc_ast/util/comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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
Expand All @@ -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;
Expand Down
63 changes: 37 additions & 26 deletions src/librustc_ast/util/comments/tests.rs
Original file line number Diff line number Diff line change
@@ -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");
})
}
3 changes: 2 additions & 1 deletion src/librustc_ast/util/lev_distance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
15 changes: 9 additions & 6 deletions src/librustc_ast/util/lev_distance/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
);
})
Expand Down
14 changes: 9 additions & 5 deletions src/librustc_ast_pretty/pprust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,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)
}
Expand Down Expand Up @@ -2050,7 +2054,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()),
};
Expand Down Expand Up @@ -2144,7 +2148,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| {
Expand All @@ -2164,16 +2168,16 @@ 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();
});
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![];
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_expand/proc_macro_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
10 changes: 5 additions & 5 deletions src/librustc_hir_pretty/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
Expand All @@ -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![];
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_incremental/assert_module_sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
8 changes: 4 additions & 4 deletions src/librustc_incremental/persist/dirty_clean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
7 changes: 2 additions & 5 deletions src/librustc_interface/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 5 additions & 2 deletions src/librustc_lint/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
10 changes: 5 additions & 5 deletions src/librustc_metadata/link_args.rs
Original file line number Diff line number Diff line change
@@ -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> {
Expand All @@ -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);
}
}
}
Expand All @@ -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);
}
}
}
Expand All @@ -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()))
}
}
3 changes: 1 addition & 2 deletions src/librustc_middle/mir/mono.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/librustc_parse/parser/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 ]`.
Expand Down
Loading

0 comments on commit 5930081

Please sign in to comment.