Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use str::strip_{prefix,suffix} when possible #74048

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/bootstrap/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -963,10 +963,11 @@ pub fn run_cargo(
.collect::<Vec<_>>();
for (prefix, extension, expected_len) in toplevel {
let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
filename.starts_with(&prefix[..])
&& filename[prefix.len()..].starts_with('-')
&& filename.ends_with(&extension[..])
&& meta.len() == expected_len
meta.len() == expected_len
&& filename
.strip_prefix(&prefix[..])
.map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
.unwrap_or(false)
});
let max = candidates
.max_by_key(|&&(_, _, ref metadata)| FileTime::from_last_modification_time(metadata));
Expand Down
17 changes: 8 additions & 9 deletions src/bootstrap/doc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,22 +461,21 @@ impl Step for Std {

builder.run(&mut cargo.into());
};
let krates = ["alloc", "core", "std", "proc_macro", "test"];
for krate in &krates {
static KRATES: &[&str] = &["alloc", "core", "std", "proc_macro", "test"];
for krate in KRATES {
run_cargo_rustdoc_for(krate);
}
builder.cp_r(&my_out, &out);

// Look for src/libstd, src/libcore etc in the `x.py doc` arguments and
// open the corresponding rendered docs.
for path in builder.paths.iter().map(components_simplified) {
if path.get(0) == Some(&"src")
&& path.get(1).map_or(false, |dir| dir.starts_with("lib"))
{
let requested_crate = &path[1][3..];
if krates.contains(&requested_crate) {
let index = out.join(requested_crate).join("index.html");
open(builder, &index);
if let ["src", path, ..] = path.as_slice() {
if let Some(krate) = path.strip_prefix("lib") {
if KRATES.contains(&krate) {
let index = out.join(krate).join("index.html");
open(builder, &index);
}
}
}
}
Expand Down
11 changes: 5 additions & 6 deletions src/bootstrap/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,10 +436,9 @@ impl Build {
output(Command::new(&build.initial_rustc).arg("--version").arg("--verbose"));
let local_release = local_version_verbose
.lines()
.filter(|x| x.starts_with("release:"))
.filter_map(|x| x.strip_prefix("release:"))
.next()
.unwrap()
.trim_start_matches("release:")
.trim();
let my_version = channel::CFG_RELEASE_NUM;
if local_release.split('.').take(2).eq(my_version.split('.').take(2)) {
Expand Down Expand Up @@ -1089,10 +1088,10 @@ impl Build {
let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package));
let toml = t!(fs::read_to_string(&toml_file_name));
for line in toml.lines() {
let prefix = "version = \"";
let suffix = "\"";
if line.starts_with(prefix) && line.ends_with(suffix) {
return line[prefix.len()..line.len() - suffix.len()].to_string();
if let Some(stripped) =
line.strip_prefix("version = \"").and_then(|s| s.strip_suffix("\""))
{
return stripped.to_owned();
}
}

Expand Down
19 changes: 11 additions & 8 deletions src/librustc_apfloat/ieee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1191,21 +1191,24 @@ impl<S: Semantics> Float for IeeeFloat<S> {
}

// Handle a leading minus sign.
let minus = s.starts_with('-');
if minus || s.starts_with('+') {
s = &s[1..];
if s.is_empty() {
return Err(ParseError("String has no digits"));
let minus = {
let m = s.strip_prefix('-');
if let Some(remnant) = m.or_else(|| s.strip_prefix('+')) {
s = remnant;
if s.is_empty() {
return Err(ParseError("String has no digits"));
}
}
}
m.is_some()
};

// Adjust the rounding mode for the absolute value below.
if minus {
round = -round;
}

let r = if s.starts_with("0x") || s.starts_with("0X") {
s = &s[2..];
let r = if let Some(tail) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
s = tail;
if s.is_empty() {
return Err(ParseError("Invalid string"));
}
Expand Down
58 changes: 33 additions & 25 deletions src/librustc_ast/util/comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,27 +29,31 @@ pub struct Comment {
}

pub fn is_line_doc_comment(s: &str) -> bool {
let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/')
|| s.starts_with("//!");
debug!("is {:?} a doc comment? {}", s, res);
res
let yes = match s.as_bytes() {
[b'/', b'/', b'/', c, ..] => *c != b'/',
[b'/', b'/', b'/', ..] => true,
[b'/', b'/', b'!', ..] => true,
_ => false,
};
debug!("is {:?} a line doc comment? {}", s, yes);
yes
}

pub fn is_block_doc_comment(s: &str) -> bool {
// Prevent `/**/` from being parsed as a doc comment
let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*')
|| s.starts_with("/*!"))
&& s.len() >= 5;
debug!("is {:?} a doc comment? {}", s, res);
res
// Previously, `/**/` was incorrectly regarded as a doc comment because it
// starts with `/**` and ends with `*/`. However, this caused an ICE
// because some code assumed that the length of a doc comment is at least 5.
let yes = match s.as_bytes() {
[b'/', b'*', b'*', c, _, ..] => *c != b'*',
[b'/', b'*', b'!', _, _, ..] => true,
_ => false,
};
debug!("is {:?} a block doc comment? {}", s, yes);
yes
}

// FIXME(#64197): Try to privatize this again.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like this shouldn't be removed? It does look like it could be made private -- only use outside of here seems to be in src/librustc_expand/parse/lexer/tests.rs and those tests could be moved into this crate relatively easily I imagine.

pub fn is_doc_comment(s: &str) -> bool {
(s.starts_with("///") && is_line_doc_comment(s))
|| s.starts_with("//!")
|| (s.starts_with("/**") && is_block_doc_comment(s))
|| s.starts_with("/*!")
is_line_doc_comment(s) || is_block_doc_comment(s)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to be a behavior change. In particular, /*! returned true before and would now return false, as is_block_doc_comment only returns true on strings >= 5 characters in length.

}

pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
Expand Down Expand Up @@ -127,22 +131,26 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String {
const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];

for prefix in ONELINERS {
if comment.starts_with(*prefix) {
return (&comment[prefix.len()..]).to_string();
if let Some(tail) = comment.strip_prefix(*prefix) {
return tail.to_owned();
}
}

if comment.starts_with("/*") {
let lines =
comment[3..comment.len() - 2].lines().map(|s| s.to_string()).collect::<Vec<String>>();
match comment
.strip_prefix("/**")
.or_else(|| comment.strip_prefix("/*!"))
.and_then(|s| s.strip_suffix("*/"))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also looks like a behavior change -- I don't think we cared what the third character was before, and certainly not the last two characters.

{
Some(doc) => {
let lines = doc.lines().map(|s| s.to_string()).collect::<Vec<String>>();

let lines = vertical_trim(lines);
let lines = horizontal_trim(lines);
let lines = vertical_trim(lines);
let lines = horizontal_trim(lines);

return lines.join("\n");
lines.join("\n")
}
_ => panic!("not a doc-comment: {}", comment),
}

panic!("not a doc-comment: {}", comment);
}

/// Returns `None` if the first `col` chars of `s` contain a non-whitespace char.
Expand Down
6 changes: 3 additions & 3 deletions src/librustc_codegen_llvm/intrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1289,8 +1289,8 @@ fn generic_simd_intrinsic(
));
}

if name.starts_with("simd_shuffle") {
let n: u64 = name["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
if let Some(tail) = name.strip_prefix("simd_shuffle") {
let n: u64 = tail.parse().unwrap_or_else(|_| {
span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
});

Expand All @@ -1307,7 +1307,7 @@ fn generic_simd_intrinsic(
require!(
in_elem == ret_ty.simd_type(tcx),
"expected return element type `{}` (element of input `{}`), \
found `{}` with element type `{}`",
found `{}` with element type `{}`",
in_elem,
in_ty,
ret_ty,
Expand Down
7 changes: 3 additions & 4 deletions src/librustc_codegen_ssa/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1901,10 +1901,9 @@ fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(

// Converts a library file-stem into a cc -l argument
fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
if stem.starts_with("lib") && !config.target.options.is_like_windows {
&stem[3..]
} else {
stem
match stem.strip_prefix("lib") {
Some(tail) if !config.target.options.is_like_windows => tail,
_ => stem,
}
}

Expand Down
3 changes: 1 addition & 2 deletions src/librustc_driver/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use std::fs;
use std::io;

pub fn arg_expand(arg: String) -> Result<Vec<String>, Error> {
if arg.starts_with('@') {
let path = &arg[1..];
if let Some(path) = arg.strip_prefix('@') {
let file = match fs::read_to_string(path) {
Ok(file) => file,
Err(ref err) if err.kind() == io::ErrorKind::InvalidData => {
Expand Down
14 changes: 7 additions & 7 deletions src/librustc_incremental/persist/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -697,13 +697,13 @@ pub fn garbage_collect_session_directories(sess: &Session) -> io::Result<()> {
let lock_file_to_session_dir: FxHashMap<String, Option<String>> = lock_files
.into_iter()
.map(|lock_file_name| {
assert!(lock_file_name.ends_with(LOCK_FILE_EXT));
let dir_prefix_end = lock_file_name.len() - LOCK_FILE_EXT.len();
let session_dir = {
let dir_prefix = &lock_file_name[0..dir_prefix_end];
session_directories.iter().find(|dir_name| dir_name.starts_with(dir_prefix))
};
(lock_file_name, session_dir.map(String::clone))
if let Some(dir_prefix) = lock_file_name.strip_suffix(LOCK_FILE_EXT) {
let dir =
session_directories.iter().find(|dir_name| dir_name.starts_with(dir_prefix));
(lock_file_name, dir.map(String::clone))
} else {
panic!("{:?} does not end with {}", lock_file_name, LOCK_FILE_EXT);
}
})
.collect();

Expand Down
35 changes: 15 additions & 20 deletions src/librustc_llvm/build.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::borrow::Cow;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
Expand Down Expand Up @@ -188,10 +189,8 @@ fn main() {
cmd.args(&components);

for lib in output(&mut cmd).split_whitespace() {
let name = if lib.starts_with("-l") {
&lib[2..]
} else if lib.starts_with('-') {
&lib[1..]
let name = if let Some(tail) = lib.strip_prefix("-l").or_else(|| lib.strip_prefix('-')) {
tail
} else if Path::new(lib).exists() {
// On MSVC llvm-config will print the full name to libraries, but
// we're only interested in the name part
Expand Down Expand Up @@ -227,18 +226,14 @@ fn main() {
let mut cmd = Command::new(&llvm_config);
cmd.arg(llvm_link_arg).arg("--ldflags");
for lib in output(&mut cmd).split_whitespace() {
if is_crossed {
if lib.starts_with("-LIBPATH:") {
println!("cargo:rustc-link-search=native={}", lib[9..].replace(&host, &target));
} else if lib.starts_with("-L") {
println!("cargo:rustc-link-search=native={}", lib[2..].replace(&host, &target));
}
} else if lib.starts_with("-LIBPATH:") {
println!("cargo:rustc-link-search=native={}", &lib[9..]);
} else if lib.starts_with("-l") {
println!("cargo:rustc-link-lib={}", &lib[2..]);
} else if lib.starts_with("-L") {
println!("cargo:rustc-link-search=native={}", &lib[2..]);
if let Some(tail) = lib.strip_prefix("-LIBPATH:").or_else(|| lib.strip_prefix("-L")) {
let lib: Cow<'_, str> = match is_crossed {
true => tail.replace(&host, &target).into(),
false => tail.into(),
};
println!("cargo:rustc-link-search=native={}", lib);
} else if let Some(tail) = lib.strip_prefix("-l") {
println!("cargo:rustc-link-lib={}", tail);
}
}

Expand All @@ -249,10 +244,10 @@ fn main() {
let llvm_linker_flags = env::var_os("LLVM_LINKER_FLAGS");
if let Some(s) = llvm_linker_flags {
for lib in s.into_string().unwrap().split_whitespace() {
if lib.starts_with("-l") {
println!("cargo:rustc-link-lib={}", &lib[2..]);
} else if lib.starts_with("-L") {
println!("cargo:rustc-link-search=native={}", &lib[2..]);
if let Some(tail) = lib.strip_prefix("-l") {
println!("cargo:rustc-link-lib={}", tail);
} else if let Some(tail) = lib.strip_prefix("-L") {
println!("cargo:rustc-link-search=native={}", tail);
}
}
}
Expand Down
18 changes: 12 additions & 6 deletions src/librustc_metadata/locator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -551,12 +551,18 @@ impl<'a> CrateLocator<'a> {
None => return FileDoesntMatch,
Some(file) => file,
};
let (hash, found_kind) = if file.starts_with(&rlib_prefix) && file.ends_with(".rlib") {
(&file[(rlib_prefix.len())..(file.len() - ".rlib".len())], CrateFlavor::Rlib)
} else if file.starts_with(&rlib_prefix) && file.ends_with(".rmeta") {
(&file[(rlib_prefix.len())..(file.len() - ".rmeta".len())], CrateFlavor::Rmeta)
} else if file.starts_with(&dylib_prefix) && file.ends_with(&dypair.1) {
(&file[(dylib_prefix.len())..(file.len() - dypair.1.len())], CrateFlavor::Dylib)
let (hash, found_kind) = if let Some(stripped) =
file.strip_prefix(&rlib_prefix).and_then(|p| p.strip_suffix(".rlib"))
{
(stripped, CrateFlavor::Rlib)
} else if let Some(stripped) =
file.strip_prefix(&rlib_prefix).and_then(|p| p.strip_suffix(".rmeta"))
{
(stripped, CrateFlavor::Rmeta)
} else if let Some(stripped) =
file.strip_prefix(&dylib_prefix).and_then(|p| p.strip_suffix(&dypair.1))
{
(stripped, CrateFlavor::Dylib)
} else {
if file.starts_with(&staticlib_prefix) && file.ends_with(&staticpair.1) {
staticlibs
Expand Down
14 changes: 6 additions & 8 deletions src/librustc_mir/borrow_check/diagnostics/move_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -488,14 +488,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
{
if let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span)
{
if pat_snippet.starts_with('&') {
let pat_snippet = pat_snippet[1..].trim_start();
let (suggestion, to_remove) = if pat_snippet.starts_with("mut")
&& pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace)
{
(pat_snippet["mut".len()..].trim_start(), "&mut")
} else {
(pat_snippet, "&")
if let Some(snippet) = pat_snippet.strip_prefix('&').map(str::trim_start) {
let (suggestion, to_remove) = match snippet.strip_prefix("mut") {
Some(tail) if tail.starts_with(rustc_lexer::is_whitespace) => {
(tail.trim_start(), "&mut")
}
_ => (snippet, "&"),
};
suggestions.push((pat_span, to_remove, suggestion.to_owned()));
}
Expand Down
Loading