Skip to content

Commit

Permalink
Use as_deref in compiler (but only where it makes sense)
Browse files Browse the repository at this point in the history
  • Loading branch information
WaffleLapkin committed Nov 16, 2022
1 parent e702534 commit 94470f4
Show file tree
Hide file tree
Showing 27 changed files with 45 additions and 63 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_ast_passes/src/ast_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1637,7 +1637,7 @@ fn deny_equality_constraints(
// Remove `Bar` from `Foo::Bar`.
assoc_path.segments.pop();
let len = assoc_path.segments.len() - 1;
let gen_args = args.as_ref().map(|p| (**p).clone());
let gen_args = args.as_deref().cloned();
// Build `<Bar = RhsTy>`.
let arg = AngleBracketedArg::Constraint(AssocConstraint {
id: rustc_ast::node_id::DUMMY_NODE_ID,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_builtin_macros/src/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
let template_snippet = ecx.source_map().span_to_snippet(template_sp).ok();
template_strs.push((
template_str,
template_snippet.as_ref().map(|s| Symbol::intern(s)),
template_snippet.as_deref().map(Symbol::intern),
template_sp,
));
let template_str = template_str.as_str();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ fn test_iter() {
let s = "The %d'th word %% is: `%.*s` %!\n";
let subs: Vec<_> = iter_subs(s, 0).map(|sub| sub.translate().ok()).collect();
assert_eq!(
subs.iter().map(|ms| ms.as_ref().map(|s| &s[..])).collect::<Vec<_>>(),
subs.iter().map(Option::as_deref).collect::<Vec<_>>(),
vec![Some("{}"), None, Some("{:.*}"), None]
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ fn test_iter() {
let s = "The $0'th word $$ is: `$WORD` $!\n";
let subs: Vec<_> = iter_subs(s, 0).map(|sub| sub.translate().ok()).collect();
assert_eq!(
subs.iter().map(|ms| ms.as_ref().map(|s| &s[..])).collect::<Vec<_>>(),
subs.iter().map(Option::as_deref).collect::<Vec<_>>(),
vec![Some("{0}"), None, Some("{WORD}")]
);
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_cranelift/build_system/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,5 +104,5 @@ pub(crate) fn copy_dir_recursively(from: &Path, to: &Path) {
}

pub(crate) fn is_ci() -> bool {
env::var("CI").as_ref().map(|val| &**val) == Ok("true")
env::var("CI").as_deref() == Ok("true")
}
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_cranelift/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::env;
use std::str::FromStr;

fn bool_env_var(key: &str) -> bool {
env::var(key).as_ref().map(|val| &**val) == Ok("1")
env::var(key).as_deref() == Ok("1")
}

/// The mode to use for compilation.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ impl CoverageMapGenerator {
counter_regions.sort_unstable_by_key(|(_counter, region)| *region);
for (counter, region) in counter_regions {
let CodeRegion { file_name, start_line, start_col, end_line, end_col } = *region;
let same_file = current_file_name.as_ref().map_or(false, |p| *p == file_name);
let same_file = current_file_name.map_or(false, |p| p == file_name);
if !same_file {
if current_file_name.is_some() {
current_file_id += 1;
Expand Down
9 changes: 3 additions & 6 deletions compiler/rustc_driver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ fn run_compiler(
compiler.input(),
&*expanded_crate,
*ppm,
compiler.output_file().as_ref().map(|p| &**p),
compiler.output_file().as_deref(),
);
Ok(())
})?;
Expand All @@ -329,7 +329,7 @@ fn run_compiler(
compiler.input(),
&krate,
*ppm,
compiler.output_file().as_ref().map(|p| &**p),
compiler.output_file().as_deref(),
);
}
trace!("finished pretty-printing");
Expand Down Expand Up @@ -383,10 +383,7 @@ fn run_compiler(
&crate_name,
compiler.input(),
None,
DumpHandler::new(
compiler.output_dir().as_ref().map(|p| &**p),
&crate_name,
),
DumpHandler::new(compiler.output_dir().as_deref(), &crate_name),
)
});
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_errors/src/emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ pub trait Emitter: Translate {
fluent_args: &FluentArgs<'_>,
) -> (MultiSpan, &'a [CodeSuggestion]) {
let mut primary_span = diag.span.clone();
let suggestions = diag.suggestions.as_ref().map_or(&[][..], |suggestions| &suggestions[..]);
let suggestions = diag.suggestions.as_deref().unwrap_or(&[]);
if let Some((sugg, rest)) = suggestions.split_first() {
let msg = self.translate_message(&sugg.msg, fluent_args);
if rest.is_empty() &&
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2179,7 +2179,7 @@ fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
.emit();
}
let meta_item_list = attr.meta_item_list();
let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
let meta_item_list = meta_item_list.as_deref();
let sole_meta_list = match meta_item_list {
Some([item]) => item.literal(),
Some(_) => {
Expand Down
11 changes: 5 additions & 6 deletions compiler/rustc_hir_typeck/src/callee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::error_reporting::DefIdOrName;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;

use std::iter;
use std::{iter, slice};

/// Checks that it is legal to call methods of the trait corresponding
/// to `trait_id` (this only cares about the trait, not the specific
Expand Down Expand Up @@ -227,22 +227,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
] {
let Some(trait_def_id) = opt_trait_def_id else { continue };

let opt_input_types = opt_arg_exprs.map(|arg_exprs| {
[self.tcx.mk_tup(arg_exprs.iter().map(|e| {
let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
self.tcx.mk_tup(arg_exprs.iter().map(|e| {
self.next_ty_var(TypeVariableOrigin {
kind: TypeVariableOriginKind::TypeInference,
span: e.span,
})
}))]
}))
});
let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);

if let Some(ok) = self.lookup_method_in_trait(
call_expr.span,
method_name,
trait_def_id,
adjusted_ty,
opt_input_types,
opt_input_type.as_ref().map(slice::from_ref),
) {
let method = self.register_infer_ok_obligations(ok);
let mut autoref = None;
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/coercion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
}
_ => None,
};
let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);

// Setup either a subtyping or a LUB relationship between
// the `CoerceUnsized` target type and the expected type.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_interface/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
parse_sess_created(&mut sess.parse_sess);
}

let temps_dir = sess.opts.unstable_opts.temps_dir.as_ref().map(|o| PathBuf::from(&o));
let temps_dir = sess.opts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);

let compiler = Compiler {
sess: Lrc::new(sess),
Expand Down
6 changes: 1 addition & 5 deletions compiler/rustc_interface/src/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,7 @@ pub struct Query<T> {

impl<T> Query<T> {
fn compute<F: FnOnce() -> Result<T>>(&self, f: F) -> Result<&Query<T>> {
let mut result = self.result.borrow_mut();
if result.is_none() {
*result = Some(f());
}
result.as_ref().unwrap().as_ref().map(|_| self).map_err(|err| *err)
self.result.borrow_mut().get_or_insert_with(f).as_ref().map(|_| self).map_err(|&err| err)
}

/// Takes ownership of the query result. Further attempts to take or peek the query
Expand Down
7 changes: 2 additions & 5 deletions compiler/rustc_interface/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,7 @@ pub fn create_session(
let codegen_backend = if let Some(make_codegen_backend) = make_codegen_backend {
make_codegen_backend(&sopts)
} else {
get_codegen_backend(
&sopts.maybe_sysroot,
sopts.unstable_opts.codegen_backend.as_ref().map(|name| &name[..]),
)
get_codegen_backend(&sopts.maybe_sysroot, sopts.unstable_opts.codegen_backend.as_deref())
};

// target_override is documented to be called before init(), so this is okay
Expand Down Expand Up @@ -260,7 +257,7 @@ pub fn rustc_path<'a>() -> Option<&'a Path> {

const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");

RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_deref()
}

fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
Expand Down
6 changes: 2 additions & 4 deletions compiler/rustc_lexer/src/unescape/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,7 @@ fn test_unescape_str_good() {
}
}
});
let buf = buf.as_ref().map(|it| it.as_ref());
assert_eq!(buf, Ok(expected))
assert_eq!(buf.as_deref(), Ok(expected))
}

check("foo", "foo");
Expand Down Expand Up @@ -250,8 +249,7 @@ fn test_unescape_byte_str_good() {
}
}
});
let buf = buf.as_ref().map(|it| it.as_ref());
assert_eq!(buf, Ok(expected))
assert_eq!(buf.as_deref(), Ok(expected))
}

check("foo", b"foo");
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/creader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ impl CStore {
pub(crate) fn iter_crate_data(&self) -> impl Iterator<Item = (CrateNum, &CrateMetadata)> {
self.metas
.iter_enumerated()
.filter_map(|(cnum, data)| data.as_ref().map(|data| (cnum, &**data)))
.filter_map(|(cnum, data)| data.as_deref().map(|data| (cnum, data)))
}

fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/rmeta/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2189,7 +2189,7 @@ impl EncodedMetadata {

#[inline]
pub fn raw_data(&self) -> &[u8] {
self.mmap.as_ref().map(|mmap| mmap.as_ref()).unwrap_or_default()
self.mmap.as_deref().unwrap_or_default()
}
}

Expand Down
12 changes: 5 additions & 7 deletions compiler/rustc_mir_build/src/thir/cx/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ impl<'tcx> Cx<'tcx> {
substs,
user_ty,
fields: self.field_refs(fields),
base: base.as_ref().map(|base| FruInfo {
base: base.map(|base| FruInfo {
base: self.mirror_expr(base),
field_types: self.typeck_results().fru_field_types()[expr.hir_id]
.iter()
Expand Down Expand Up @@ -590,7 +590,7 @@ impl<'tcx> Cx<'tcx> {
InlineAsmOperand::Out {
reg,
late,
expr: expr.as_ref().map(|expr| self.mirror_expr(expr)),
expr: expr.map(|expr| self.mirror_expr(expr)),
}
}
hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
Expand All @@ -605,7 +605,7 @@ impl<'tcx> Cx<'tcx> {
reg,
late,
in_expr: self.mirror_expr(in_expr),
out_expr: out_expr.as_ref().map(|expr| self.mirror_expr(expr)),
out_expr: out_expr.map(|expr| self.mirror_expr(expr)),
},
hir::InlineAsmOperand::Const { ref anon_const } => {
let anon_const_def_id = tcx.hir().local_def_id(anon_const.hir_id);
Expand Down Expand Up @@ -659,13 +659,11 @@ impl<'tcx> Cx<'tcx> {

ExprKind::Repeat { value: self.mirror_expr(v), count: *count }
}
hir::ExprKind::Ret(ref v) => {
ExprKind::Return { value: v.as_ref().map(|v| self.mirror_expr(v)) }
}
hir::ExprKind::Ret(ref v) => ExprKind::Return { value: v.map(|v| self.mirror_expr(v)) },
hir::ExprKind::Break(dest, ref value) => match dest.target_id {
Ok(target_id) => ExprKind::Break {
label: region::Scope { id: target_id.local_id, data: region::ScopeData::Node },
value: value.as_ref().map(|value| self.mirror_expr(value)),
value: value.map(|value| self.mirror_expr(value)),
},
Err(err) => bug!("invalid loop id for break: {}", err),
},
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_mir_build/src/thir/pattern/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
let lo = lo_expr.map(|e| self.lower_range_expr(e));
let hi = hi_expr.map(|e| self.lower_range_expr(e));

let (lp, hp) = (lo.as_ref().map(|x| &x.0), hi.as_ref().map(|x| &x.0));
let (lp, hp) = (lo.as_ref().map(|(x, _)| x), hi.as_ref().map(|(x, _)| x));
let mut kind = match self.normalize_range_pattern_ends(ty, lp, hp) {
Some((lc, hc)) => self.lower_pattern_range(ty, lc, hc, end, lo_span),
None => {
Expand Down Expand Up @@ -358,7 +358,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
&mut self,
pat: &'tcx Option<&'tcx hir::Pat<'tcx>>,
) -> Option<Box<Pat<'tcx>>> {
pat.as_ref().map(|p| self.lower_pattern(p))
pat.map(|p| self.lower_pattern(p))
}

fn slice_or_array_pattern(
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_parse/src/parser/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2562,7 +2562,7 @@ impl<'a> Parser<'a> {
if let [a, b] = segments {
let (a_span, b_span) = (a.span(), b.span());
let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
if self.span_to_snippet(between_span).as_ref().map(|a| &a[..]) == Ok(":: ") {
if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
return Err(DoubleColonInBound {
span: path.span.shrink_to_hi(),
between: between_span,
Expand Down
9 changes: 4 additions & 5 deletions compiler/rustc_passes/src/liveness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -923,8 +923,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
// v v
// ( succ )
//
let else_ln =
self.propagate_through_opt_expr(else_opt.as_ref().map(|e| &**e), succ);
let else_ln = self.propagate_through_opt_expr(else_opt.as_deref(), succ);
let then_ln = self.propagate_through_expr(&then, succ);
let ln = self.live_node(expr.hir_id, expr.span);
self.init_from_succ(ln, else_ln);
Expand Down Expand Up @@ -967,7 +966,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {

hir::ExprKind::Ret(ref o_e) => {
// Ignore succ and subst exit_ln.
self.propagate_through_opt_expr(o_e.as_ref().map(|e| &**e), self.exit_ln)
self.propagate_through_opt_expr(o_e.as_deref(), self.exit_ln)
}

hir::ExprKind::Break(label, ref opt_expr) => {
Expand All @@ -982,7 +981,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
// look it up in the break loop nodes table

match target {
Some(b) => self.propagate_through_opt_expr(opt_expr.as_ref().map(|e| &**e), b),
Some(b) => self.propagate_through_opt_expr(opt_expr.as_deref(), b),
None => span_bug!(expr.span, "`break` to unknown label"),
}
}
Expand Down Expand Up @@ -1027,7 +1026,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
hir::ExprKind::Array(ref exprs) => self.propagate_through_exprs(exprs, succ),

hir::ExprKind::Struct(_, ref fields, ref with_expr) => {
let succ = self.propagate_through_opt_expr(with_expr.as_ref().map(|e| &**e), succ);
let succ = self.propagate_through_opt_expr(with_expr.as_deref(), succ);
fields
.iter()
.rev()
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_save_analysis/src/dump_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1029,7 +1029,7 @@ impl<'tcx> DumpVisitor<'tcx> {
trait_item.hir_id(),
trait_item.ident,
Some(bounds),
default_ty.as_ref().map(|ty| &**ty),
default_ty.as_deref(),
&self.save_ctxt,
),
attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1480,7 +1480,7 @@ pub fn get_cmd_lint_options(

/// Parses the `--color` flag.
pub fn parse_color(matches: &getopts::Matches) -> ColorConfig {
match matches.opt_str("color").as_ref().map(|s| &s[..]) {
match matches.opt_str("color").as_deref() {
Some("auto") => ColorConfig::Auto,
Some("always") => ColorConfig::Always,
Some("never") => ColorConfig::Never,
Expand Down Expand Up @@ -1589,7 +1589,7 @@ pub fn parse_error_format(
// is unstable, it will not be present. We have to use `opts_present` not
// `opt_present` because the latter will panic.
let error_format = if matches.opts_present(&["error-format".to_owned()]) {
match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
match matches.opt_str("error-format").as_deref() {
None | Some("human") => {
ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color))
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_session/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1354,7 +1354,7 @@ pub fn build_session(
let profiler = SelfProfiler::new(
directory,
sopts.crate_name.as_deref(),
sopts.unstable_opts.self_profile_events.as_ref().map(|xs| &xs[..]),
sopts.unstable_opts.self_profile_events.as_deref(),
&sopts.unstable_opts.self_profile_counter,
);
match profiler {
Expand Down Expand Up @@ -1388,7 +1388,7 @@ pub fn build_session(
local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);

let optimization_fuel = Lock::new(OptimizationFuel {
remaining: sopts.unstable_opts.fuel.as_ref().map_or(0, |i| i.1),
remaining: sopts.unstable_opts.fuel.as_ref().map_or(0, |&(_, i)| i),
out_of_fuel: false,
});
let print_fuel = AtomicU64::new(0);
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_span/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,7 @@ impl RealFileName {
pub fn local_path(&self) -> Option<&Path> {
match self {
RealFileName::LocalPath(p) => Some(p),
RealFileName::Remapped { local_path: p, virtual_name: _ } => {
p.as_ref().map(PathBuf::as_path)
}
RealFileName::Remapped { local_path, virtual_name: _ } => local_path.as_deref(),
}
}

Expand Down
Loading

0 comments on commit 94470f4

Please sign in to comment.