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

Rollup of 9 pull requests #91621

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
9e5939a
Remove a code path that is neither documented nor can I see the reaso…
oli-obk Aug 20, 2021
93564c3
Tweak "call this function" suggestion to have smaller span
estebank Dec 3, 2021
14c6193
Add test for evaluate_obligation: Ok(EvaluatedToOkModuloRegions) ICE
wesleywiser Nov 19, 2021
98e9b32
Add test with `#[rustc_evaluate_where_clauses]`
wesleywiser Nov 22, 2021
6fe13f6
Add test case that evals to `EvaluatedToOkModuloRegions`
wesleywiser Dec 4, 2021
aa3370c
doc: suggest try_reserve in try_reserve_exact
TennyZhuang Dec 5, 2021
a9f14c1
Add pretty printer test for async blocks
dtolnay Dec 5, 2021
33c29a3
Pretty print async block without redundant space
dtolnay Dec 5, 2021
fa054cf
Document all public items in `rustc_incremental`
pierwill Oct 29, 2021
a0fb992
Fix AnonConst ICE
terrarier2111 Nov 28, 2021
6a17ee6
Recommend fix `count()` -> `len()` on slices
notriddle Jul 30, 2021
880eb59
Update books
ehuss Dec 7, 2021
bdd6f8c
Rollup merge of #87614 - notriddle:notriddle-count2len, r=Mark-Simula…
matthiaskrgr Dec 7, 2021
3c9860b
Rollup merge of #90407 - pierwill:edit-rustc-incremental-docs, r=cjgi…
matthiaskrgr Dec 7, 2021
95fb5a6
Rollup merge of #91065 - wesleywiser:add_incr_test, r=jackh726
matthiaskrgr Dec 7, 2021
eac24b8
Rollup merge of #91312 - terrarier2111:anon-const-ice, r=jackh726
matthiaskrgr Dec 7, 2021
43e7c0c
Rollup merge of #91493 - oli-obk:cleanup, r=michaelwoerister
matthiaskrgr Dec 7, 2021
c65807d
Rollup merge of #91503 - estebank:call-fn-span, r=michaelwoerister
matthiaskrgr Dec 7, 2021
00c847a
Rollup merge of #91547 - TennyZhuang:suggest_try_reserve, r=scottmcm
matthiaskrgr Dec 7, 2021
2de2cae
Rollup merge of #91562 - dtolnay:asyncspace, r=Mark-Simulacrum
matthiaskrgr Dec 7, 2021
71e3343
Rollup merge of #91620 - ehuss:update-books, r=ehuss
matthiaskrgr Dec 7, 2021
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
1 change: 0 additions & 1 deletion compiler/rustc_ast_pretty/src/pprust/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2077,7 +2077,6 @@ impl<'a> State<'a> {
ast::ExprKind::Async(capture_clause, _, ref blk) => {
self.word_nbsp("async");
self.print_capture_clause(capture_clause);
self.s.space();
// cbox/ibox in analogy to the `ExprKind::Block` arm above
self.cbox(INDENT_UNIT);
self.ibox(0);
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_incremental/src/assert_dep_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ use std::env;
use std::fs::{self, File};
use std::io::{BufWriter, Write};

#[allow(missing_docs)]
pub fn assert_dep_graph(tcx: TyCtxt<'_>) {
tcx.dep_graph.with_ignore(|| {
if tcx.sess.opts.debugging_opts.dump_dep_graph {
Expand Down Expand Up @@ -262,6 +263,7 @@ fn dump_graph(query: &DepGraphQuery) {
}
}

#[allow(missing_docs)]
pub struct GraphvizDepGraph<'q>(FxHashSet<&'q DepNode>, Vec<(&'q DepNode, &'q DepNode)>);

impl<'a, 'q> dot::GraphWalk<'a> for GraphvizDepGraph<'q> {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_incremental/src/assert_module_sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use rustc_session::cgu_reuse_tracker::*;
use rustc_span::symbol::{sym, Symbol};
use std::collections::BTreeSet;

#[allow(missing_docs)]
pub fn assert_module_sources(tcx: TyCtxt<'_>) {
tcx.dep_graph.with_ignore(|| {
if tcx.sess.opts.incremental.is_none() {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_incremental/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Support for serializing the dep-graph and reloading it.

#![deny(missing_docs)]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![feature(in_band_lifetimes)]
#![feature(let_else)]
Expand Down
34 changes: 26 additions & 8 deletions compiler/rustc_incremental/src/persist/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,21 +133,26 @@ const QUERY_CACHE_FILENAME: &str = "query-cache.bin";
// case-sensitive (as opposed to base64, for example).
const INT_ENCODE_BASE: usize = base_n::CASE_INSENSITIVE;

/// Returns the path to a session's dependency graph.
pub fn dep_graph_path(sess: &Session) -> PathBuf {
in_incr_comp_dir_sess(sess, DEP_GRAPH_FILENAME)
}
/// Returns the path to a session's staging dependency graph.
///
/// On the difference between dep-graph and staging dep-graph,
/// see [`rustc_incremental::persist::save::build_dep_graph`].
pub fn staging_dep_graph_path(sess: &Session) -> PathBuf {
in_incr_comp_dir_sess(sess, STAGING_DEP_GRAPH_FILENAME)
}

pub fn work_products_path(sess: &Session) -> PathBuf {
in_incr_comp_dir_sess(sess, WORK_PRODUCTS_FILENAME)
}

/// Returns the path to a session's query cache.
pub fn query_cache_path(sess: &Session) -> PathBuf {
in_incr_comp_dir_sess(sess, QUERY_CACHE_FILENAME)
}

/// Locks a given session directory.
pub fn lock_file_path(session_dir: &Path) -> PathBuf {
let crate_dir = session_dir.parent().unwrap();

Expand All @@ -166,23 +171,35 @@ pub fn lock_file_path(session_dir: &Path) -> PathBuf {
crate_dir.join(&directory_name[0..dash_indices[2]]).with_extension(&LOCK_FILE_EXT[1..])
}

/// Returns the path for a given filename within the incremental compilation directory
/// in the current session.
pub fn in_incr_comp_dir_sess(sess: &Session, file_name: &str) -> PathBuf {
in_incr_comp_dir(&sess.incr_comp_session_dir(), file_name)
}

/// Returns the path for a given filename within the incremental compilation directory,
/// not necessarily from the current session.
///
/// To ensure the file is part of the current session, use [`in_incr_comp_dir_sess`].
pub fn in_incr_comp_dir(incr_comp_session_dir: &Path, file_name: &str) -> PathBuf {
incr_comp_session_dir.join(file_name)
}

/// Allocates the private session directory. The boolean in the Ok() result
/// indicates whether we should try loading a dep graph from the successfully
/// initialized directory, or not.
/// The post-condition of this fn is that we have a valid incremental
/// compilation session directory, if the result is `Ok`. A valid session
/// Allocates the private session directory.
///
/// If the result of this function is `Ok`, we have a valid incremental
/// compilation session directory. A valid session
/// directory is one that contains a locked lock file. It may or may not contain
/// a dep-graph and work products from a previous session.
/// If the call fails, the fn may leave behind an invalid session directory.
///
/// This always attempts to load a dep-graph from the directory.
/// If loading fails for some reason, we fallback to a disabled [`DepGraph`].
/// See [`rustc_interface::queries::dep_graph`].
///
/// If this function returns an error, it may leave behind an invalid session directory.
/// The garbage collection will take care of it.
///
/// [`rustc_interface::queries::dep_graph`]: ../../rustc_interface/struct.Queries.html#structfield.dep_graph
pub fn prepare_session_directory(
sess: &Session,
crate_name: &str,
Expand Down Expand Up @@ -661,6 +678,7 @@ fn is_old_enough_to_be_collected(timestamp: SystemTime) -> bool {
timestamp < SystemTime::now() - Duration::from_secs(10)
}

/// Runs garbage collection for the current session.
pub fn garbage_collect_session_directories(sess: &Session) -> io::Result<()> {
debug!("garbage_collect_session_directories() - begin");

Expand Down
17 changes: 15 additions & 2 deletions compiler/rustc_incremental/src/persist/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,24 @@ use super::work_product;
type WorkProductMap = FxHashMap<WorkProductId, WorkProduct>;

#[derive(Debug)]
/// Represents the result of an attempt to load incremental compilation data.
pub enum LoadResult<T> {
Ok { data: T },
/// Loading was successful.
Ok {
#[allow(missing_docs)]
data: T,
},
/// The file either didn't exist or was produced by an incompatible compiler version.
DataOutOfDate,
Error { message: String },
/// An error occured.
Error {
#[allow(missing_docs)]
message: String,
},
}

impl<T: Default> LoadResult<T> {
/// Accesses the data returned in [`LoadResult::Ok`].
pub fn open(self, sess: &Session) -> T {
// Check for errors when using `-Zassert-incremental-state`
match (sess.opts.assert_incr_state, &self) {
Expand Down Expand Up @@ -99,6 +110,7 @@ pub enum MaybeAsync<T> {
}

impl<T> MaybeAsync<LoadResult<T>> {
/// Accesses the data returned in [`LoadResult::Ok`] in an asynchronous way if possible.
pub fn open(self) -> LoadResult<T> {
match self {
MaybeAsync::Sync(result) => result,
Expand All @@ -109,6 +121,7 @@ impl<T> MaybeAsync<LoadResult<T>> {
}
}

/// An asynchronous type for computing the dependency graph.
pub type DepGraphFuture = MaybeAsync<LoadResult<(SerializedDepGraph, WorkProductMap)>>;

/// Launch a thread and load the dependency graph in the background.
Expand Down
15 changes: 13 additions & 2 deletions compiler/rustc_incremental/src/persist/save.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,13 @@ use super::file_format;
use super::fs::*;
use super::work_product;

/// Save and dump the DepGraph.
/// Saves and writes the [`DepGraph`] to the file system.
///
/// No query must be invoked after this function.
/// This function saves both the dep-graph and the query result cache,
/// and drops the result cache.
///
/// This function should only run after all queries have completed.
/// Trying to execute a query afterwards would attempt to read the result cache we just dropped.
pub fn save_dep_graph(tcx: TyCtxt<'_>) {
debug!("save_dep_graph()");
tcx.dep_graph.with_ignore(|| {
Expand Down Expand Up @@ -75,6 +79,7 @@ pub fn save_dep_graph(tcx: TyCtxt<'_>) {
})
}

/// Saves the work product index.
pub fn save_work_product_index(
sess: &Session,
dep_graph: &DepGraph,
Expand Down Expand Up @@ -139,6 +144,12 @@ fn encode_query_cache(tcx: TyCtxt<'_>, encoder: &mut FileEncoder) -> FileEncodeR
tcx.sess.time("incr_comp_serialize_result_cache", || tcx.serialize_query_result_cache(encoder))
}

/// Builds the dependency graph.
///
/// This function breates the *staging dep-graph*. When the dep-graph is modified by a query
/// execution, the new dependency information is not kept in memory but directly
/// output to this file. `save_dep_graph` then finalizes the staging dep-graph
/// and moves it to the permanent dep-graph path
pub fn build_dep_graph(
sess: &Session,
prev_graph: SerializedDepGraph,
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_incremental/src/persist/work_product.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
//! This module contains files for saving intermediate work-products.
//! Functions for saving and removing intermediate [work products].
//!
//! [work products]: WorkProduct

use crate::persist::fs::*;
use rustc_fs_util::link_or_copy;
Expand All @@ -7,6 +9,7 @@ use rustc_session::Session;
use std::fs as std_fs;
use std::path::PathBuf;

/// Copies a CGU work product to the incremental compilation directory, so next compilation can find and reuse it.
pub fn copy_cgu_workproduct_to_incr_comp_cache_dir(
sess: &Session,
cgu_name: &str,
Expand Down Expand Up @@ -40,6 +43,7 @@ pub fn copy_cgu_workproduct_to_incr_comp_cache_dir(
Some((work_product_id, work_product))
}

/// Removes files for a given work product.
pub fn delete_workproduct_files(sess: &Session, work_product: &WorkProduct) {
if let Some(ref file_name) = work_product.saved_file {
let path = in_incr_comp_dir_sess(sess, file_name);
Expand Down
13 changes: 8 additions & 5 deletions compiler/rustc_infer/src/infer/opaque_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,10 +461,6 @@ impl<'a, 'tcx> Instantiator<'a, 'tcx> {
if let Some(def_id) = def_id.as_local() {
let opaque_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
let parent_def_id = self.infcx.defining_use_anchor;
let def_scope_default = || {
let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id);
parent_def_id == tcx.hir().local_def_id(opaque_parent_hir_id)
};
let (in_definition_scope, origin) = match tcx.hir().expect_item(def_id).kind
{
// Anonymous `impl Trait`
Expand All @@ -481,7 +477,14 @@ impl<'a, 'tcx> Instantiator<'a, 'tcx> {
}) => {
(may_define_opaque_type(tcx, parent_def_id, opaque_hir_id), origin)
}
_ => (def_scope_default(), hir::OpaqueTyOrigin::TyAlias),
ref itemkind => {
span_bug!(
self.value_span,
"weird opaque type: {:#?}, {:#?}",
ty.kind(),
itemkind
)
}
};
if in_definition_scope {
let opaque_type_key =
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,7 @@ symbols! {
core_panic_macro,
cosf32,
cosf64,
count,
cr,
crate_id,
crate_in_paths,
Expand Down
26 changes: 23 additions & 3 deletions compiler/rustc_typeck/src/check/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}

fn is_slice_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
self.autoderef(span, ty).any(|(ty, _)| matches!(ty.kind(), ty::Slice(..) | ty::Array(..)))
}

pub fn report_method_error(
&self,
mut span: Span,
Expand Down Expand Up @@ -691,7 +695,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {

let mut restrict_type_params = false;
let mut unsatisfied_bounds = false;
if !unsatisfied_predicates.is_empty() {
if item_name.name == sym::count && self.is_slice_ty(actual, span) {
let msg = "consider using `len` instead";
if let SelfSource::MethodCall(_expr) = source {
err.span_suggestion_short(
span,
msg,
String::from("len"),
Applicability::MachineApplicable,
);
} else {
err.span_label(span, msg);
}
if let Some(iterator_trait) = self.tcx.get_diagnostic_item(sym::Iterator) {
let iterator_trait = self.tcx.def_path_str(iterator_trait);
err.note(&format!("`count` is defined on `{iterator_trait}`, which `{actual}` does not implement"));
}
} else if !unsatisfied_predicates.is_empty() {
let def_span = |def_id| {
self.tcx.sess.source_map().guess_head_span(self.tcx.def_span(def_id))
};
Expand Down Expand Up @@ -990,9 +1010,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}

let mut fallback_span = true;
let msg = "remove this method call";
if item_name.name == sym::as_str && actual.peel_refs().is_str() {
let msg = "remove this method call";
let mut fallback_span = true;
if let SelfSource::MethodCall(expr) = source {
let call_expr =
self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id));
Expand Down
25 changes: 11 additions & 14 deletions compiler/rustc_typeck/src/check/op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
) -> bool /* did we suggest to call a function because of missing parentheses? */ {
err.span_label(span, ty.to_string());
if let FnDef(def_id, _) = *ty.kind() {
let source_map = self.tcx.sess.source_map();
if !self.tcx.has_typeck_results(def_id) {
return false;
}
Expand All @@ -517,20 +516,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.lookup_op_method(fn_sig.output(), &[other_ty], Op::Binary(op, is_assign))
.is_ok()
{
if let Ok(snippet) = source_map.span_to_snippet(span) {
let (variable_snippet, applicability) = if !fn_sig.inputs().is_empty() {
(format!("{}( /* arguments */ )", snippet), Applicability::HasPlaceholders)
} else {
(format!("{}()", snippet), Applicability::MaybeIncorrect)
};
let (variable_snippet, applicability) = if !fn_sig.inputs().is_empty() {
("( /* arguments */ )".to_string(), Applicability::HasPlaceholders)
} else {
("()".to_string(), Applicability::MaybeIncorrect)
};

err.span_suggestion(
span,
"you might have forgotten to call this function",
variable_snippet,
applicability,
);
}
err.span_suggestion_verbose(
span.shrink_to_hi(),
"you might have forgotten to call this function",
variable_snippet,
applicability,
);
return true;
}
}
Expand Down
15 changes: 11 additions & 4 deletions compiler/rustc_typeck/src/collect/type_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ pub(super) fn opt_const_param_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<
// We've encountered an `AnonConst` in some path, so we need to
// figure out which generic parameter it corresponds to and return
// the relevant type.
let (arg_index, segment) = path
let filtered = path
.segments
.iter()
.filter_map(|seg| seg.args.map(|args| (args.args, seg)))
Expand All @@ -181,10 +181,17 @@ pub(super) fn opt_const_param_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<
.filter(|arg| arg.is_const())
.position(|arg| arg.id() == hir_id)
.map(|index| (index, seg))
})
.unwrap_or_else(|| {
bug!("no arg matching AnonConst in path");
});
let (arg_index, segment) = match filtered {
None => {
tcx.sess.delay_span_bug(
tcx.def_span(def_id),
"no arg matching AnonConst in path",
);
return None;
}
Some(inner) => inner,
};

// Try to use the segment resolution if it is valid, otherwise we
// default to the path resolution.
Expand Down
4 changes: 2 additions & 2 deletions library/alloc/src/collections/vec_deque/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -720,9 +720,9 @@ impl<T, A: Allocator> VecDeque<T, A> {
///
/// Note that the allocator may give the collection more space than it
/// requests. Therefore, capacity can not be relied upon to be precisely
/// minimal. Prefer [`reserve`] if future insertions are expected.
/// minimal. Prefer [`try_reserve`] if future insertions are expected.
///
/// [`reserve`]: VecDeque::reserve
/// [`try_reserve`]: VecDeque::try_reserve
///
/// # Errors
///
Expand Down
4 changes: 2 additions & 2 deletions library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1044,9 +1044,9 @@ impl String {
///
/// Note that the allocator may give the collection more space than it
/// requests. Therefore, capacity can not be relied upon to be precisely
/// minimal. Prefer [`reserve`] if future insertions are expected.
/// minimal. Prefer [`try_reserve`] if future insertions are expected.
///
/// [`reserve`]: String::reserve
/// [`try_reserve`]: String::try_reserve
///
/// # Errors
///
Expand Down
Loading