Skip to content

Commit 872631d

Browse files
committed
Auto merge of #104507 - WaffleLapkin:asderefsyou, r=wesleywiser
Use `as_deref` in compiler (but only where it makes sense) This simplifies some code :3 (there are some changes that are not exacly `as_deref`, but more like "clever `Option`/`Result` method use")
2 parents 70f8737 + 94470f4 commit 872631d

File tree

27 files changed

+45
-63
lines changed

27 files changed

+45
-63
lines changed

compiler/rustc_ast_passes/src/ast_validation.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1637,7 +1637,7 @@ fn deny_equality_constraints(
16371637
// Remove `Bar` from `Foo::Bar`.
16381638
assoc_path.segments.pop();
16391639
let len = assoc_path.segments.len() - 1;
1640-
let gen_args = args.as_ref().map(|p| (**p).clone());
1640+
let gen_args = args.as_deref().cloned();
16411641
// Build `<Bar = RhsTy>`.
16421642
let arg = AngleBracketedArg::Constraint(AssocConstraint {
16431643
id: rustc_ast::node_id::DUMMY_NODE_ID,

compiler/rustc_builtin_macros/src/asm.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -564,7 +564,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
564564
let template_snippet = ecx.source_map().span_to_snippet(template_sp).ok();
565565
template_strs.push((
566566
template_str,
567-
template_snippet.as_ref().map(|s| Symbol::intern(s)),
567+
template_snippet.as_deref().map(Symbol::intern),
568568
template_sp,
569569
));
570570
let template_str = template_str.as_str();

compiler/rustc_builtin_macros/src/format_foreign/printf/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ fn test_iter() {
100100
let s = "The %d'th word %% is: `%.*s` %!\n";
101101
let subs: Vec<_> = iter_subs(s, 0).map(|sub| sub.translate().ok()).collect();
102102
assert_eq!(
103-
subs.iter().map(|ms| ms.as_ref().map(|s| &s[..])).collect::<Vec<_>>(),
103+
subs.iter().map(Option::as_deref).collect::<Vec<_>>(),
104104
vec![Some("{}"), None, Some("{:.*}"), None]
105105
);
106106
}

compiler/rustc_builtin_macros/src/format_foreign/shell/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ fn test_iter() {
3939
let s = "The $0'th word $$ is: `$WORD` $!\n";
4040
let subs: Vec<_> = iter_subs(s, 0).map(|sub| sub.translate().ok()).collect();
4141
assert_eq!(
42-
subs.iter().map(|ms| ms.as_ref().map(|s| &s[..])).collect::<Vec<_>>(),
42+
subs.iter().map(Option::as_deref).collect::<Vec<_>>(),
4343
vec![Some("{0}"), None, Some("{WORD}")]
4444
);
4545
}

compiler/rustc_codegen_cranelift/build_system/utils.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -104,5 +104,5 @@ pub(crate) fn copy_dir_recursively(from: &Path, to: &Path) {
104104
}
105105

106106
pub(crate) fn is_ci() -> bool {
107-
env::var("CI").as_ref().map(|val| &**val) == Ok("true")
107+
env::var("CI").as_deref() == Ok("true")
108108
}

compiler/rustc_codegen_cranelift/src/config.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::env;
22
use std::str::FromStr;
33

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

88
/// The mode to use for compilation.

compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ impl CoverageMapGenerator {
174174
counter_regions.sort_unstable_by_key(|(_counter, region)| *region);
175175
for (counter, region) in counter_regions {
176176
let CodeRegion { file_name, start_line, start_col, end_line, end_col } = *region;
177-
let same_file = current_file_name.as_ref().map_or(false, |p| *p == file_name);
177+
let same_file = current_file_name.map_or(false, |p| p == file_name);
178178
if !same_file {
179179
if current_file_name.is_some() {
180180
current_file_id += 1;

compiler/rustc_driver/src/lib.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ fn run_compiler(
318318
compiler.input(),
319319
&*expanded_crate,
320320
*ppm,
321-
compiler.output_file().as_ref().map(|p| &**p),
321+
compiler.output_file().as_deref(),
322322
);
323323
Ok(())
324324
})?;
@@ -329,7 +329,7 @@ fn run_compiler(
329329
compiler.input(),
330330
&krate,
331331
*ppm,
332-
compiler.output_file().as_ref().map(|p| &**p),
332+
compiler.output_file().as_deref(),
333333
);
334334
}
335335
trace!("finished pretty-printing");
@@ -383,10 +383,7 @@ fn run_compiler(
383383
&crate_name,
384384
compiler.input(),
385385
None,
386-
DumpHandler::new(
387-
compiler.output_dir().as_ref().map(|p| &**p),
388-
&crate_name,
389-
),
386+
DumpHandler::new(compiler.output_dir().as_deref(), &crate_name),
390387
)
391388
});
392389
}

compiler/rustc_errors/src/emitter.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ pub trait Emitter: Translate {
248248
fluent_args: &FluentArgs<'_>,
249249
) -> (MultiSpan, &'a [CodeSuggestion]) {
250250
let mut primary_span = diag.span.clone();
251-
let suggestions = diag.suggestions.as_ref().map_or(&[][..], |suggestions| &suggestions[..]);
251+
let suggestions = diag.suggestions.as_deref().unwrap_or(&[]);
252252
if let Some((sugg, rest)) = suggestions.split_first() {
253253
let msg = self.translate_message(&sugg.msg, fluent_args);
254254
if rest.is_empty() &&

compiler/rustc_hir_analysis/src/collect.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2157,7 +2157,7 @@ fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
21572157
.emit();
21582158
}
21592159
let meta_item_list = attr.meta_item_list();
2160-
let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2160+
let meta_item_list = meta_item_list.as_deref();
21612161
let sole_meta_list = match meta_item_list {
21622162
Some([item]) => item.literal(),
21632163
Some(_) => {

compiler/rustc_hir_typeck/src/callee.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use rustc_trait_selection::infer::InferCtxtExt as _;
3030
use rustc_trait_selection::traits::error_reporting::DefIdOrName;
3131
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
3232

33-
use std::iter;
33+
use std::{iter, slice};
3434

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

230-
let opt_input_types = opt_arg_exprs.map(|arg_exprs| {
231-
[self.tcx.mk_tup(arg_exprs.iter().map(|e| {
230+
let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
231+
self.tcx.mk_tup(arg_exprs.iter().map(|e| {
232232
self.next_ty_var(TypeVariableOrigin {
233233
kind: TypeVariableOriginKind::TypeInference,
234234
span: e.span,
235235
})
236-
}))]
236+
}))
237237
});
238-
let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);
239238

240239
if let Some(ok) = self.lookup_method_in_trait(
241240
call_expr.span,
242241
method_name,
243242
trait_def_id,
244243
adjusted_ty,
245-
opt_input_types,
244+
opt_input_type.as_ref().map(slice::from_ref),
246245
) {
247246
let method = self.register_infer_ok_obligations(ok);
248247
let mut autoref = None;

compiler/rustc_hir_typeck/src/coercion.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -588,7 +588,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
588588
}
589589
_ => None,
590590
};
591-
let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
591+
let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
592592

593593
// Setup either a subtyping or a LUB relationship between
594594
// the `CoerceUnsized` target type and the expected type.

compiler/rustc_interface/src/interface.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
304304
parse_sess_created(&mut sess.parse_sess);
305305
}
306306

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

309309
let compiler = Compiler {
310310
sess: Lrc::new(sess),

compiler/rustc_interface/src/queries.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,7 @@ pub struct Query<T> {
3333

3434
impl<T> Query<T> {
3535
fn compute<F: FnOnce() -> Result<T>>(&self, f: F) -> Result<&Query<T>> {
36-
let mut result = self.result.borrow_mut();
37-
if result.is_none() {
38-
*result = Some(f());
39-
}
40-
result.as_ref().unwrap().as_ref().map(|_| self).map_err(|err| *err)
36+
self.result.borrow_mut().get_or_insert_with(f).as_ref().map(|_| self).map_err(|&err| err)
4137
}
4238

4339
/// Takes ownership of the query result. Further attempts to take or peek the query

compiler/rustc_interface/src/util.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,7 @@ pub fn create_session(
6868
let codegen_backend = if let Some(make_codegen_backend) = make_codegen_backend {
6969
make_codegen_backend(&sopts)
7070
} else {
71-
get_codegen_backend(
72-
&sopts.maybe_sysroot,
73-
sopts.unstable_opts.codegen_backend.as_ref().map(|name| &name[..]),
74-
)
71+
get_codegen_backend(&sopts.maybe_sysroot, sopts.unstable_opts.codegen_backend.as_deref())
7572
};
7673

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

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

263-
RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
260+
RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_deref()
264261
}
265262

266263
fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {

compiler/rustc_lexer/src/unescape/tests.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,7 @@ fn test_unescape_str_good() {
132132
}
133133
}
134134
});
135-
let buf = buf.as_ref().map(|it| it.as_ref());
136-
assert_eq!(buf, Ok(expected))
135+
assert_eq!(buf.as_deref(), Ok(expected))
137136
}
138137

139138
check("foo", "foo");
@@ -250,8 +249,7 @@ fn test_unescape_byte_str_good() {
250249
}
251250
}
252251
});
253-
let buf = buf.as_ref().map(|it| it.as_ref());
254-
assert_eq!(buf, Ok(expected))
252+
assert_eq!(buf.as_deref(), Ok(expected))
255253
}
256254

257255
check("foo", b"foo");

compiler/rustc_metadata/src/creader.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ impl CStore {
162162
pub(crate) fn iter_crate_data(&self) -> impl Iterator<Item = (CrateNum, &CrateMetadata)> {
163163
self.metas
164164
.iter_enumerated()
165-
.filter_map(|(cnum, data)| data.as_ref().map(|data| (cnum, &**data)))
165+
.filter_map(|(cnum, data)| data.as_deref().map(|data| (cnum, data)))
166166
}
167167

168168
fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {

compiler/rustc_metadata/src/rmeta/encoder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2166,7 +2166,7 @@ impl EncodedMetadata {
21662166

21672167
#[inline]
21682168
pub fn raw_data(&self) -> &[u8] {
2169-
self.mmap.as_ref().map(|mmap| mmap.as_ref()).unwrap_or_default()
2169+
self.mmap.as_deref().unwrap_or_default()
21702170
}
21712171
}
21722172

compiler/rustc_mir_build/src/thir/cx/expr.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,7 @@ impl<'tcx> Cx<'tcx> {
486486
substs,
487487
user_ty,
488488
fields: self.field_refs(fields),
489-
base: base.as_ref().map(|base| FruInfo {
489+
base: base.map(|base| FruInfo {
490490
base: self.mirror_expr(base),
491491
field_types: self.typeck_results().fru_field_types()[expr.hir_id]
492492
.iter()
@@ -589,7 +589,7 @@ impl<'tcx> Cx<'tcx> {
589589
InlineAsmOperand::Out {
590590
reg,
591591
late,
592-
expr: expr.as_ref().map(|expr| self.mirror_expr(expr)),
592+
expr: expr.map(|expr| self.mirror_expr(expr)),
593593
}
594594
}
595595
hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
@@ -604,7 +604,7 @@ impl<'tcx> Cx<'tcx> {
604604
reg,
605605
late,
606606
in_expr: self.mirror_expr(in_expr),
607-
out_expr: out_expr.as_ref().map(|expr| self.mirror_expr(expr)),
607+
out_expr: out_expr.map(|expr| self.mirror_expr(expr)),
608608
},
609609
hir::InlineAsmOperand::Const { ref anon_const } => {
610610
let value = mir::ConstantKind::from_anon_const(
@@ -656,13 +656,11 @@ impl<'tcx> Cx<'tcx> {
656656

657657
ExprKind::Repeat { value: self.mirror_expr(v), count: *count }
658658
}
659-
hir::ExprKind::Ret(ref v) => {
660-
ExprKind::Return { value: v.as_ref().map(|v| self.mirror_expr(v)) }
661-
}
659+
hir::ExprKind::Ret(ref v) => ExprKind::Return { value: v.map(|v| self.mirror_expr(v)) },
662660
hir::ExprKind::Break(dest, ref value) => match dest.target_id {
663661
Ok(target_id) => ExprKind::Break {
664662
label: region::Scope { id: target_id.local_id, data: region::ScopeData::Node },
665-
value: value.as_ref().map(|value| self.mirror_expr(value)),
663+
value: value.map(|value| self.mirror_expr(value)),
666664
},
667665
Err(err) => bug!("invalid loop id for break: {}", err),
668666
},

compiler/rustc_mir_build/src/thir/pattern/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
216216
let lo = lo_expr.map(|e| self.lower_range_expr(e));
217217
let hi = hi_expr.map(|e| self.lower_range_expr(e));
218218

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

364364
fn slice_or_array_pattern(

compiler/rustc_parse/src/parser/diagnostics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2565,7 +2565,7 @@ impl<'a> Parser<'a> {
25652565
if let [a, b] = segments {
25662566
let (a_span, b_span) = (a.span(), b.span());
25672567
let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2568-
if self.span_to_snippet(between_span).as_ref().map(|a| &a[..]) == Ok(":: ") {
2568+
if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
25692569
return Err(DoubleColonInBound {
25702570
span: path.span.shrink_to_hi(),
25712571
between: between_span,

compiler/rustc_passes/src/liveness.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -922,8 +922,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
922922
// v v
923923
// ( succ )
924924
//
925-
let else_ln =
926-
self.propagate_through_opt_expr(else_opt.as_ref().map(|e| &**e), succ);
925+
let else_ln = self.propagate_through_opt_expr(else_opt.as_deref(), succ);
927926
let then_ln = self.propagate_through_expr(&then, succ);
928927
let ln = self.live_node(expr.hir_id, expr.span);
929928
self.init_from_succ(ln, else_ln);
@@ -966,7 +965,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
966965

967966
hir::ExprKind::Ret(ref o_e) => {
968967
// Ignore succ and subst exit_ln.
969-
self.propagate_through_opt_expr(o_e.as_ref().map(|e| &**e), self.exit_ln)
968+
self.propagate_through_opt_expr(o_e.as_deref(), self.exit_ln)
970969
}
971970

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

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

10281027
hir::ExprKind::Struct(_, ref fields, ref with_expr) => {
1029-
let succ = self.propagate_through_opt_expr(with_expr.as_ref().map(|e| &**e), succ);
1028+
let succ = self.propagate_through_opt_expr(with_expr.as_deref(), succ);
10301029
fields
10311030
.iter()
10321031
.rev()

compiler/rustc_save_analysis/src/dump_visitor.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1029,7 +1029,7 @@ impl<'tcx> DumpVisitor<'tcx> {
10291029
trait_item.hir_id(),
10301030
trait_item.ident,
10311031
Some(bounds),
1032-
default_ty.as_ref().map(|ty| &**ty),
1032+
default_ty.as_deref(),
10331033
&self.save_ctxt,
10341034
),
10351035
attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),

compiler/rustc_session/src/config.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1480,7 +1480,7 @@ pub fn get_cmd_lint_options(
14801480

14811481
/// Parses the `--color` flag.
14821482
pub fn parse_color(matches: &getopts::Matches) -> ColorConfig {
1483-
match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1483+
match matches.opt_str("color").as_deref() {
14841484
Some("auto") => ColorConfig::Auto,
14851485
Some("always") => ColorConfig::Always,
14861486
Some("never") => ColorConfig::Never,
@@ -1589,7 +1589,7 @@ pub fn parse_error_format(
15891589
// is unstable, it will not be present. We have to use `opts_present` not
15901590
// `opt_present` because the latter will panic.
15911591
let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1592-
match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1592+
match matches.opt_str("error-format").as_deref() {
15931593
None | Some("human") => {
15941594
ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color))
15951595
}

compiler/rustc_session/src/session.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1357,7 +1357,7 @@ pub fn build_session(
13571357
let profiler = SelfProfiler::new(
13581358
directory,
13591359
sopts.crate_name.as_deref(),
1360-
sopts.unstable_opts.self_profile_events.as_ref().map(|xs| &xs[..]),
1360+
sopts.unstable_opts.self_profile_events.as_deref(),
13611361
&sopts.unstable_opts.self_profile_counter,
13621362
);
13631363
match profiler {
@@ -1391,7 +1391,7 @@ pub fn build_session(
13911391
local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
13921392

13931393
let optimization_fuel = Lock::new(OptimizationFuel {
1394-
remaining: sopts.unstable_opts.fuel.as_ref().map_or(0, |i| i.1),
1394+
remaining: sopts.unstable_opts.fuel.as_ref().map_or(0, |&(_, i)| i),
13951395
out_of_fuel: false,
13961396
});
13971397
let print_fuel = AtomicU64::new(0);

compiler/rustc_span/src/lib.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -217,9 +217,7 @@ impl RealFileName {
217217
pub fn local_path(&self) -> Option<&Path> {
218218
match self {
219219
RealFileName::LocalPath(p) => Some(p),
220-
RealFileName::Remapped { local_path: p, virtual_name: _ } => {
221-
p.as_ref().map(PathBuf::as_path)
222-
}
220+
RealFileName::Remapped { local_path, virtual_name: _ } => local_path.as_deref(),
223221
}
224222
}
225223

0 commit comments

Comments
 (0)