Skip to content

Commit ef71df1

Browse files
committed
Auto merge of rust-lang#71600 - Dylan-DPC:rollup-7tvzi9n, r=Dylan-DPC
Rollup of 6 pull requests Successful merges: - rust-lang#68716 (Stabilize `Span::mixed_site`) - rust-lang#71263 (Remove unused abs_path method from rustc_span::source_map::FileLoader) - rust-lang#71409 (Point at the return type on `.into()` failure caused by `?`) - rust-lang#71419 (add message for resolution failure because wrong namespace) - rust-lang#71438 (Tweak some suggestions in `rustc_resolve`) - rust-lang#71589 (remove Unique::from for shared pointer types) Failed merges: r? @ghost
2 parents 5794e77 + cddbed0 commit ef71df1

File tree

21 files changed

+206
-118
lines changed

21 files changed

+206
-118
lines changed

src/liballoc/collections/btree/node.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ impl<K, V> BoxedNode<K, V> {
131131
}
132132

133133
unsafe fn from_ptr(ptr: NonNull<LeafNode<K, V>>) -> Self {
134-
BoxedNode { ptr: Unique::from(ptr) }
134+
BoxedNode { ptr: Unique::new_unchecked(ptr.as_ptr()) }
135135
}
136136

137137
fn as_ptr(&self) -> NonNull<LeafNode<K, V>> {

src/liballoc/raw_vec.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ impl<T, A: AllocRef> RawVec<T, A> {
151151

152152
let memory = alloc.alloc(layout, init).unwrap_or_else(|_| handle_alloc_error(layout));
153153
Self {
154-
ptr: memory.ptr.cast().into(),
154+
ptr: unsafe { Unique::new_unchecked(memory.ptr.cast().as_ptr()) },
155155
cap: Self::capacity_from_bytes(memory.size),
156156
alloc,
157157
}
@@ -469,7 +469,7 @@ impl<T, A: AllocRef> RawVec<T, A> {
469469
}
470470

471471
fn set_memory(&mut self, memory: MemoryBlock) {
472-
self.ptr = memory.ptr.cast().into();
472+
self.ptr = unsafe { Unique::new_unchecked(memory.ptr.cast().as_ptr()) };
473473
self.cap = Self::capacity_from_bytes(memory.size);
474474
}
475475

src/libcore/ptr/unique.rs

-17
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ use crate::fmt;
33
use crate::marker::{PhantomData, Unsize};
44
use crate::mem;
55
use crate::ops::{CoerceUnsized, DispatchFromDyn};
6-
use crate::ptr::NonNull;
76

87
// ignore-tidy-undocumented-unsafe
98

@@ -171,19 +170,3 @@ impl<T: ?Sized> From<&mut T> for Unique<T> {
171170
unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }
172171
}
173172
}
174-
175-
#[unstable(feature = "ptr_internals", issue = "none")]
176-
impl<T: ?Sized> From<&T> for Unique<T> {
177-
#[inline]
178-
fn from(reference: &T) -> Self {
179-
unsafe { Unique { pointer: reference as *const T, _marker: PhantomData } }
180-
}
181-
}
182-
183-
#[unstable(feature = "ptr_internals", issue = "none")]
184-
impl<T: ?Sized> From<NonNull<T>> for Unique<T> {
185-
#[inline]
186-
fn from(p: NonNull<T>) -> Self {
187-
unsafe { Unique::new_unchecked(p.as_ptr()) }
188-
}
189-
}

src/libproc_macro/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ impl Span {
303303
/// definition site (local variables, labels, `$crate`) and sometimes at the macro
304304
/// call site (everything else).
305305
/// The span location is taken from the call-site.
306-
#[unstable(feature = "proc_macro_mixed_site", issue = "65049")]
306+
#[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
307307
pub fn mixed_site() -> Span {
308308
Span(bridge::client::Span::mixed_site())
309309
}

src/librustc_resolve/late/diagnostics.rs

+24-15
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ impl<'a> LateResolutionVisitor<'a, '_, '_> {
383383
has_self_arg
384384
}
385385

386-
fn followed_by_brace(&self, span: Span) -> (bool, Option<(Span, String)>) {
386+
fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
387387
// HACK(estebank): find a better way to figure out that this was a
388388
// parser issue where a struct literal is being used on an expression
389389
// where a brace being opened means a block is being started. Look
@@ -406,18 +406,15 @@ impl<'a> LateResolutionVisitor<'a, '_, '_> {
406406
_ => false,
407407
};
408408
// In case this could be a struct literal that needs to be surrounded
409-
// by parenthesis, find the appropriate span.
409+
// by parentheses, find the appropriate span.
410410
let mut i = 0;
411411
let mut closing_brace = None;
412412
loop {
413413
sp = sm.next_point(sp);
414414
match sm.span_to_snippet(sp) {
415415
Ok(ref snippet) => {
416416
if snippet == "}" {
417-
let sp = span.to(sp);
418-
if let Ok(snippet) = sm.span_to_snippet(sp) {
419-
closing_brace = Some((sp, snippet));
420-
}
417+
closing_brace = Some(span.to(sp));
421418
break;
422419
}
423420
}
@@ -479,17 +476,23 @@ impl<'a> LateResolutionVisitor<'a, '_, '_> {
479476
suggested = path_sep(err, &parent);
480477
}
481478
PathSource::Expr(None) if followed_by_brace => {
482-
if let Some((sp, snippet)) = closing_brace {
483-
err.span_suggestion(
484-
sp,
485-
"surround the struct literal with parenthesis",
486-
format!("({})", snippet),
479+
if let Some(sp) = closing_brace {
480+
err.multipart_suggestion(
481+
"surround the struct literal with parentheses",
482+
vec![
483+
(sp.shrink_to_lo(), "(".to_string()),
484+
(sp.shrink_to_hi(), ")".to_string()),
485+
],
487486
Applicability::MaybeIncorrect,
488487
);
489488
} else {
490489
err.span_label(
491-
span, // Note the parenthesis surrounding the suggestion below
492-
format!("did you mean `({} {{ /* fields */ }})`?", path_str),
490+
span, // Note the parentheses surrounding the suggestion below
491+
format!(
492+
"you might want to surround a struct literal with parentheses: \
493+
`({} {{ /* fields */ }})`?",
494+
path_str
495+
),
493496
);
494497
}
495498
suggested = true;
@@ -516,10 +519,16 @@ impl<'a> LateResolutionVisitor<'a, '_, '_> {
516519
err.note("if you want the `try` keyword, you need to be in the 2018 edition");
517520
}
518521
}
519-
(Res::Def(DefKind::TyAlias, _), PathSource::Trait(_)) => {
522+
(Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
520523
err.span_label(span, "type aliases cannot be used as traits");
521524
if nightly_options::is_nightly_build() {
522-
err.note("did you mean to use a trait alias?");
525+
let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
526+
`type` alias";
527+
if let Some(span) = self.r.definitions.opt_span(def_id) {
528+
err.span_help(span, msg);
529+
} else {
530+
err.help(msg);
531+
}
523532
}
524533
}
525534
(Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {

src/librustc_resolve/lib.rs

+83-45
Original file line numberDiff line numberDiff line change
@@ -2066,52 +2066,64 @@ impl<'a> Resolver<'a> {
20662066
};
20672067
}
20682068

2069-
let binding = if let Some(module) = module {
2070-
self.resolve_ident_in_module(
2071-
module,
2072-
ident,
2073-
ns,
2074-
parent_scope,
2075-
record_used,
2076-
path_span,
2077-
)
2078-
} else if ribs.is_none() || opt_ns.is_none() || opt_ns == Some(MacroNS) {
2079-
let scopes = ScopeSet::All(ns, opt_ns.is_none());
2080-
self.early_resolve_ident_in_lexical_scope(
2081-
ident,
2082-
scopes,
2083-
parent_scope,
2084-
record_used,
2085-
record_used,
2086-
path_span,
2087-
)
2088-
} else {
2089-
let record_used_id =
2090-
if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
2091-
match self.resolve_ident_in_lexical_scope(
2092-
ident,
2093-
ns,
2094-
parent_scope,
2095-
record_used_id,
2096-
path_span,
2097-
&ribs.unwrap()[ns],
2098-
) {
2099-
// we found a locally-imported or available item/module
2100-
Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
2101-
// we found a local variable or type param
2102-
Some(LexicalScopeBinding::Res(res))
2103-
if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) =>
2104-
{
2105-
record_segment_res(self, res);
2106-
return PathResult::NonModule(PartialRes::with_unresolved_segments(
2107-
res,
2108-
path.len() - 1,
2109-
));
2069+
enum FindBindingResult<'a> {
2070+
Binding(Result<&'a NameBinding<'a>, Determinacy>),
2071+
PathResult(PathResult<'a>),
2072+
}
2073+
let find_binding_in_ns = |this: &mut Self, ns| {
2074+
let binding = if let Some(module) = module {
2075+
this.resolve_ident_in_module(
2076+
module,
2077+
ident,
2078+
ns,
2079+
parent_scope,
2080+
record_used,
2081+
path_span,
2082+
)
2083+
} else if ribs.is_none() || opt_ns.is_none() || opt_ns == Some(MacroNS) {
2084+
let scopes = ScopeSet::All(ns, opt_ns.is_none());
2085+
this.early_resolve_ident_in_lexical_scope(
2086+
ident,
2087+
scopes,
2088+
parent_scope,
2089+
record_used,
2090+
record_used,
2091+
path_span,
2092+
)
2093+
} else {
2094+
let record_used_id = if record_used {
2095+
crate_lint.node_id().or(Some(CRATE_NODE_ID))
2096+
} else {
2097+
None
2098+
};
2099+
match this.resolve_ident_in_lexical_scope(
2100+
ident,
2101+
ns,
2102+
parent_scope,
2103+
record_used_id,
2104+
path_span,
2105+
&ribs.unwrap()[ns],
2106+
) {
2107+
// we found a locally-imported or available item/module
2108+
Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
2109+
// we found a local variable or type param
2110+
Some(LexicalScopeBinding::Res(res))
2111+
if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) =>
2112+
{
2113+
record_segment_res(this, res);
2114+
return FindBindingResult::PathResult(PathResult::NonModule(
2115+
PartialRes::with_unresolved_segments(res, path.len() - 1),
2116+
));
2117+
}
2118+
_ => Err(Determinacy::determined(record_used)),
21102119
}
2111-
_ => Err(Determinacy::determined(record_used)),
2112-
}
2120+
};
2121+
FindBindingResult::Binding(binding)
2122+
};
2123+
let binding = match find_binding_in_ns(self, ns) {
2124+
FindBindingResult::PathResult(x) => return x,
2125+
FindBindingResult::Binding(binding) => binding,
21132126
};
2114-
21152127
match binding {
21162128
Ok(binding) => {
21172129
if i == 1 {
@@ -2201,7 +2213,33 @@ impl<'a> Resolver<'a> {
22012213
} else if i == 0 {
22022214
(format!("use of undeclared type or module `{}`", ident), None)
22032215
} else {
2204-
(format!("could not find `{}` in `{}`", ident, path[i - 1].ident), None)
2216+
let mut msg =
2217+
format!("could not find `{}` in `{}`", ident, path[i - 1].ident);
2218+
if ns == TypeNS || ns == ValueNS {
2219+
let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2220+
if let FindBindingResult::Binding(Ok(binding)) =
2221+
find_binding_in_ns(self, ns_to_try)
2222+
{
2223+
let mut found = |what| {
2224+
msg = format!(
2225+
"expected {}, found {} `{}` in `{}`",
2226+
ns.descr(),
2227+
what,
2228+
ident,
2229+
path[i - 1].ident
2230+
)
2231+
};
2232+
if binding.module().is_some() {
2233+
found("module")
2234+
} else {
2235+
match binding.res() {
2236+
def::Res::<NodeId>::Def(kind, id) => found(kind.descr(id)),
2237+
_ => found(ns_to_try.descr()),
2238+
}
2239+
}
2240+
};
2241+
}
2242+
(msg, None)
22052243
};
22062244
return PathResult::Failed {
22072245
span: ident.span,

src/librustc_span/source_map.rs

-12
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ use std::path::{Path, PathBuf};
2020
use std::sync::atomic::Ordering;
2121

2222
use log::debug;
23-
use std::env;
2423
use std::fs;
2524
use std::io;
2625

@@ -64,9 +63,6 @@ pub trait FileLoader {
6463
/// Query the existence of a file.
6564
fn file_exists(&self, path: &Path) -> bool;
6665

67-
/// Returns an absolute path to a file, if possible.
68-
fn abs_path(&self, path: &Path) -> Option<PathBuf>;
69-
7066
/// Read the contents of an UTF-8 file into memory.
7167
fn read_file(&self, path: &Path) -> io::Result<String>;
7268
}
@@ -79,14 +75,6 @@ impl FileLoader for RealFileLoader {
7975
fs::metadata(path).is_ok()
8076
}
8177

82-
fn abs_path(&self, path: &Path) -> Option<PathBuf> {
83-
if path.is_absolute() {
84-
Some(path.to_path_buf())
85-
} else {
86-
env::current_dir().ok().map(|cwd| cwd.join(path))
87-
}
88-
}
89-
9078
fn read_file(&self, path: &Path) -> io::Result<String> {
9179
fs::read_to_string(path)
9280
}

src/librustc_trait_selection/traits/error_reporting/mod.rs

+24-14
Original file line numberDiff line numberDiff line change
@@ -317,20 +317,30 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
317317
.starts_with("std::convert::From<std::option::NoneError");
318318
let should_convert_result_to_option = format!("{}", trait_ref)
319319
.starts_with("<std::option::NoneError as std::convert::From<");
320-
if is_try && is_from && should_convert_option_to_result {
321-
err.span_suggestion_verbose(
322-
span.shrink_to_lo(),
323-
"consider converting the `Option<T>` into a `Result<T, _>` using `Option::ok_or` or `Option::ok_or_else`",
324-
".ok_or_else(|| /* error value */)".to_string(),
325-
Applicability::HasPlaceholders,
326-
);
327-
} else if is_try && is_from && should_convert_result_to_option {
328-
err.span_suggestion_verbose(
329-
span.shrink_to_lo(),
330-
"consider converting the `Result<T, _>` into an `Option<T>` using `Result::ok`",
331-
".ok()".to_string(),
332-
Applicability::MachineApplicable,
333-
);
320+
if is_try && is_from {
321+
if should_convert_option_to_result {
322+
err.span_suggestion_verbose(
323+
span.shrink_to_lo(),
324+
"consider converting the `Option<T>` into a `Result<T, _>` \
325+
using `Option::ok_or` or `Option::ok_or_else`",
326+
".ok_or_else(|| /* error value */)".to_string(),
327+
Applicability::HasPlaceholders,
328+
);
329+
} else if should_convert_result_to_option {
330+
err.span_suggestion_verbose(
331+
span.shrink_to_lo(),
332+
"consider converting the `Result<T, _>` into an `Option<T>` \
333+
using `Result::ok`",
334+
".ok()".to_string(),
335+
Applicability::MachineApplicable,
336+
);
337+
}
338+
if let Some(ret_span) = self.return_type_span(obligation) {
339+
err.span_label(
340+
ret_span,
341+
&format!("expected `{}` because of this", trait_ref.self_ty()),
342+
);
343+
}
334344
}
335345

336346
let explanation =

src/librustc_trait_selection/traits/error_reporting/suggestions.rs

+13
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ pub trait InferCtxtExt<'tcx> {
8484
trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
8585
);
8686

87+
fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
88+
8789
fn suggest_impl_trait(
8890
&self,
8991
err: &mut DiagnosticBuilder<'tcx>,
@@ -761,6 +763,17 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
761763
}
762764
}
763765

766+
fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
767+
let hir = self.tcx.hir();
768+
let parent_node = hir.get_parent_node(obligation.cause.body_id);
769+
let sig = match hir.find(parent_node) {
770+
Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) => sig,
771+
_ => return None,
772+
};
773+
774+
if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
775+
}
776+
764777
/// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
765778
/// applicable and signal that the error has been expanded appropriately and needs to be
766779
/// emitted.

0 commit comments

Comments
 (0)