From ac595dd57a151a16a168e6596404ada8f079b778 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Wed, 22 Jun 2022 22:14:32 -0500 Subject: [PATCH 001/500] Merge commit 'c4416f20dcaec5d93077f72470e83e150fb923b1' into sync-rustfmt --- .github/workflows/linux.yml | 14 +- .github/workflows/mac.yml | 10 +- .github/workflows/windows.yml | 11 +- CHANGELOG.md | 26 +- Cargo.lock | 2 +- Cargo.toml | 6 +- Configurations.md | 8 + ci/build_and_test.bat | 14 + ci/build_and_test.sh | 18 + ci/integration.sh | 2 +- config_proc_macro/Cargo.lock | 44 +- config_proc_macro/src/lib.rs | 4 + rust-toolchain | 2 +- src/cargo-fmt/main.rs | 3 +- src/comment.rs | 4 + src/config/mod.rs | 3 + src/expr.rs | 51 +- src/formatting.rs | 2 - src/imports.rs | 343 +- src/reorder.rs | 10 +- src/rewrite.rs | 13 - src/shape.rs | 4 +- src/visitor.rs | 7 +- .../doc_comment_code_block_width/100.rs | 16 + .../100_greater_max_width.rs | 17 + .../doc_comment_code_block_width/50.rs | 16 + .../imports_raw_identifiers/version_One.rs | 5 + .../imports_raw_identifiers/version_Two.rs | 5 + tests/source/performance/issue-4476.rs | 638 -- tests/source/performance/issue-5128.rs | 5127 ----------------- .../doc_comment_code_block_width/100.rs | 16 + .../100_greater_max_width.rs | 29 + .../doc_comment_code_block_width/50.rs | 22 + .../imports_raw_identifiers/version_One.rs | 5 + .../imports_raw_identifiers/version_Two.rs | 5 + tests/target/issue_5399.rs | 48 + tests/target/performance/issue-4476.rs | 705 --- tests/target/performance/issue-4867.rs | 13 - tests/target/performance/issue-5128.rs | 4898 ---------------- 39 files changed, 533 insertions(+), 11633 deletions(-) create mode 100755 ci/build_and_test.bat create mode 100755 ci/build_and_test.sh create mode 100644 tests/source/configs/doc_comment_code_block_width/100.rs create mode 100644 tests/source/configs/doc_comment_code_block_width/100_greater_max_width.rs create mode 100644 tests/source/configs/doc_comment_code_block_width/50.rs create mode 100644 tests/source/imports_raw_identifiers/version_One.rs create mode 100644 tests/source/imports_raw_identifiers/version_Two.rs delete mode 100644 tests/source/performance/issue-4476.rs delete mode 100644 tests/source/performance/issue-5128.rs create mode 100644 tests/target/configs/doc_comment_code_block_width/100.rs create mode 100644 tests/target/configs/doc_comment_code_block_width/100_greater_max_width.rs create mode 100644 tests/target/configs/doc_comment_code_block_width/50.rs create mode 100644 tests/target/imports_raw_identifiers/version_One.rs create mode 100644 tests/target/imports_raw_identifiers/version_Two.rs create mode 100644 tests/target/issue_5399.rs delete mode 100644 tests/target/performance/issue-4476.rs delete mode 100644 tests/target/performance/issue-4867.rs delete mode 100644 tests/target/performance/issue-5128.rs diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 6a3f9d89d98fc..bce9b0c8d5a95 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -35,15 +35,5 @@ jobs: sh rustup-init.sh -y --default-toolchain none rustup target add ${{ matrix.target }} - - name: build - run: | - rustc -Vv - cargo -V - cargo build - env: - RUSTFLAGS: '-D warnings' - - - name: test - run: cargo test - env: - RUSTFLAGS: '-D warnings' + - name: Build and Test + run: ./ci/build_and_test.sh diff --git a/.github/workflows/mac.yml b/.github/workflows/mac.yml index 7dfda3142ca9d..89a980c42c5a0 100644 --- a/.github/workflows/mac.yml +++ b/.github/workflows/mac.yml @@ -32,11 +32,5 @@ jobs: sh rustup-init.sh -y --default-toolchain none rustup target add ${{ matrix.target }} - - name: build - run: | - rustc -Vv - cargo -V - cargo build - - - name: test - run: cargo test + - name: Build and Test + run: ./ci/build_and_test.sh diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 4ebc296384905..ec37c714b0851 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -57,13 +57,6 @@ jobs: if: matrix.target == 'x86_64-pc-windows-gnu' && matrix.channel == 'nightly' shell: bash - - name: build - run: | - rustc -Vv - cargo -V - cargo build - shell: cmd - - - name: test - run: cargo test + - name: Build and Test shell: cmd + run: ci\build_and_test.bat diff --git a/CHANGELOG.md b/CHANGELOG.md index bfc155cd656a6..0c1893bf8c387 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,29 @@ ## [Unreleased] -## [1.5.0] 2022-06-13 +## [1.5.1] 2022-06-24 + +**N.B** A bug was introduced in v1.5.0/nightly-2022-06-15 which modified formatting. If you happened to run rustfmt over your code with one of those ~10 nightlies it's possible you may have seen formatting changes, and you may see additional changes after this fix since that bug has now been reverted. + +### Fixed + +- Correct an issue introduced in v1.5.0 where formatting changes were unintentionally introduced in a few cases with a large/long construct in a right hand side position (e.g. a large chain on the RHS of a local/assignment statement) +- `cargo fmt --version` properly displays the version value again [#5395](https://github.com/rust-lang/rustfmt/issues/5395) + +### Changed + +- Properly sort imports containing raw identifiers [#3791](https://github.com/rust-lang/rustfmt/issues/3791) (note this is change version gated, and not applied by default) + +### Added + +- Add new configuration option, `doc_comment_code_block_width`, which allows for setting a shorter width limit to use for formatting code snippets in doc comments [#5384](https://github.com/rust-lang/rustfmt/issues/5384) + +### Install/Download Options +- **rustup (nightly)** - nightly-2022-06-24 +- **GitHub Release Binaries** - [Release v1.5.1](https://github.com/rust-lang/rustfmt/releases/tag/v1.5.0) +- **Build from source** - [Tag v1.5.1](https://github.com/rust-lang/rustfmt/tree/v1.5.1), see instructions for how to [install rustfmt from source][install-from-source] + +## [1.5.0] 2022-06-14 ### Changed @@ -75,7 +97,7 @@ - Improved performance when formatting large and deeply nested expression trees, often found in generated code, which have many expressions that exceed `max_width` [#5128](https://github.com/rust-lang/rustfmt/issues/5128), [#4867](https://github.com/rust-lang/rustfmt/issues/4867), [#4476](https://github.com/rust-lang/rustfmt/issues/4476), [#5139](https://github.com/rust-lang/rustfmt/pull/5139) ### Install/Download Options -- **rustup (nightly)** - *pending* +- **rustup (nightly)** - nightly-2022-06-15 - **GitHub Release Binaries** - [Release v1.5.0](https://github.com/rust-lang/rustfmt/releases/tag/v1.5.0) - **Build from source** - [Tag v1.5.0](https://github.com/rust-lang/rustfmt/tree/v1.5.0), see instructions for how to [install rustfmt from source][install-from-source] diff --git a/Cargo.lock b/Cargo.lock index 639d35886dcda..311df226da19d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -485,7 +485,7 @@ dependencies = [ [[package]] name = "rustfmt-nightly" -version = "1.5.0" +version = "1.5.1" dependencies = [ "annotate-snippets", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index f26e982406234..7a4e02d69eddc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustfmt-nightly" -version = "1.5.0" +version = "1.5.1" description = "Tool to find and fix Rust formatting issues" repository = "https://github.com/rust-lang/rustfmt" readme = "README.md" @@ -65,3 +65,7 @@ rustfmt-config_proc_macro = { version = "0.2", path = "config_proc_macro" } rustc-workspace-hack = "1.0.0" # Rustc dependencies are loaded from the sysroot, Cargo doesn't know about them. + +[package.metadata.rust-analyzer] +# This package uses #[feature(rustc_private)] +rustc_private = true diff --git a/Configurations.md b/Configurations.md index 8c84614352ca2..8b96b9d36892a 100644 --- a/Configurations.md +++ b/Configurations.md @@ -926,6 +926,14 @@ fn add_one(x: i32) -> i32 { } ``` +## `doc_comment_code_block_width` + +Max width for code snippets included in doc comments. Only used if [`format_code_in_doc_comments`](#format_code_in_doc_comments) is true. + +- **Default value**: `100` +- **Possible values**: any positive integer that is less than or equal to the value specified for [`max_width`](#max_width) +- **Stable**: No (tracking issue: [#5359](https://github.com/rust-lang/rustfmt/issues/5359)) + ## `format_generated_files` Format generated files. A file is considered generated diff --git a/ci/build_and_test.bat b/ci/build_and_test.bat new file mode 100755 index 0000000000000..ef41017783feb --- /dev/null +++ b/ci/build_and_test.bat @@ -0,0 +1,14 @@ +set "RUSTFLAGS=-D warnings" + +:: Print version information +rustc -Vv || exit /b 1 +cargo -V || exit /b 1 + +:: Build and test main crate +cargo build --locked || exit /b 1 +cargo test || exit /b 1 + +:: Build and test other crates +cd config_proc_macro || exit /b 1 +cargo build --locked || exit /b 1 +cargo test || exit /b 1 diff --git a/ci/build_and_test.sh b/ci/build_and_test.sh new file mode 100755 index 0000000000000..8fa0f67b0d021 --- /dev/null +++ b/ci/build_and_test.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +set -euo pipefail + +export RUSTFLAGS="-D warnings" + +# Print version information +rustc -Vv +cargo -V + +# Build and test main crate +cargo build --locked +cargo test + +# Build and test other crates +cd config_proc_macro +cargo build --locked +cargo test diff --git a/ci/integration.sh b/ci/integration.sh index 0269e3ee4af93..562d5d70c70ba 100755 --- a/ci/integration.sh +++ b/ci/integration.sh @@ -15,7 +15,7 @@ set -ex # it again. # #which cargo-fmt || cargo install --force -CFG_RELEASE=nightly CFG_RELEASE_CHANNEL=nightly cargo install --path . --force +CFG_RELEASE=nightly CFG_RELEASE_CHANNEL=nightly cargo install --path . --force --locked echo "Integration tests for: ${INTEGRATION}" cargo fmt -- --version diff --git a/config_proc_macro/Cargo.lock b/config_proc_macro/Cargo.lock index abcf9654e5d77..ecf561f28fb6a 100644 --- a/config_proc_macro/Cargo.lock +++ b/config_proc_macro/Cargo.lock @@ -1,68 +1,68 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +version = 3 + [[package]] name = "proc-macro2" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e98a83a9f9b331f54b924e68a66acb1bb35cb01fb0a23645139967abefb697e8" dependencies = [ - "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid", ] [[package]] name = "quote" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" dependencies = [ - "proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2", ] [[package]] name = "rustfmt-config_proc_macro" -version = "0.1.2" +version = "0.2.0" dependencies = [ - "proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2", + "quote", + "serde", + "syn", ] [[package]] name = "serde" version = "1.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fec2851eb56d010dc9a21b89ca53ee75e6528bab60c11e89d38390904982da9f" dependencies = [ - "serde_derive 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4dc18c61206b08dc98216c98faa0232f4337e1e1b8574551d5bad29ea1b425" dependencies = [ - "proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "syn" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66850e97125af79138385e9b88339cbcd037e3f28ceab8c5ad98e64f0f1f80bf" dependencies = [ - "proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2", + "quote", + "unicode-xid", ] [[package]] name = "unicode-xid" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" - -[metadata] -"checksum proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e98a83a9f9b331f54b924e68a66acb1bb35cb01fb0a23645139967abefb697e8" -"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" -"checksum serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)" = "fec2851eb56d010dc9a21b89ca53ee75e6528bab60c11e89d38390904982da9f" -"checksum serde_derive 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)" = "cb4dc18c61206b08dc98216c98faa0232f4337e1e1b8574551d5bad29ea1b425" -"checksum syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "66850e97125af79138385e9b88339cbcd037e3f28ceab8c5ad98e64f0f1f80bf" -"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" +checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" diff --git a/config_proc_macro/src/lib.rs b/config_proc_macro/src/lib.rs index 513018213192d..e772c53f42361 100644 --- a/config_proc_macro/src/lib.rs +++ b/config_proc_macro/src/lib.rs @@ -29,6 +29,8 @@ pub fn config_type(_args: TokenStream, input: TokenStream) -> TokenStream { /// Used to conditionally output the TokenStream for tests that need to be run on nightly only. /// /// ```rust +/// # use rustfmt_config_proc_macro::nightly_only_test; +/// /// #[nightly_only_test] /// #[test] /// fn test_needs_nightly_rustfmt() { @@ -49,6 +51,8 @@ pub fn nightly_only_test(_args: TokenStream, input: TokenStream) -> TokenStream /// Used to conditionally output the TokenStream for tests that need to be run on stable only. /// /// ```rust +/// # use rustfmt_config_proc_macro::stable_only_test; +/// /// #[stable_only_test] /// #[test] /// fn test_needs_stable_rustfmt() { diff --git a/rust-toolchain b/rust-toolchain index 813e5e2c10fea..2640a9e0ecc28 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-06-06" +channel = "nightly-2022-06-21" components = ["rustc-dev"] diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index 55fd75f6de9b8..9031d29b45f7f 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -14,7 +14,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; use std::str; -use clap::{CommandFactory, Parser}; +use clap::{AppSettings, CommandFactory, Parser}; #[path = "test/mod.rs"] #[cfg(test)] @@ -22,6 +22,7 @@ mod cargo_fmt_tests; #[derive(Parser)] #[clap( + global_setting(AppSettings::NoAutoVersion), bin_name = "cargo fmt", about = "This utility formats all bin and lib files of \ the current crate using rustfmt." diff --git a/src/comment.rs b/src/comment.rs index eb195b1f7628f..4d565afc1e026 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -730,6 +730,10 @@ impl<'a> CommentRewrite<'a> { { let mut config = self.fmt.config.clone(); config.set().wrap_comments(false); + let comment_max_width = config + .doc_comment_code_block_width() + .min(config.max_width()); + config.set().max_width(comment_max_width); if let Some(s) = crate::format_code_block(&self.code_block_buffer, &config, false) { diff --git a/src/config/mod.rs b/src/config/mod.rs index a516952818783..f49c18d3a4603 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -57,6 +57,8 @@ create_config! { // Comments. macros, and strings wrap_comments: bool, false, false, "Break comments to fit on the line"; format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments."; + doc_comment_code_block_width: usize, 100, false, "Maximum width for code snippets in doc \ + comments. No effect unless format_code_in_doc_comments = true"; comment_width: usize, 80, false, "Maximum length of comments. No effect unless wrap_comments = true"; normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible"; @@ -532,6 +534,7 @@ chain_width = 60 single_line_if_else_max_width = 50 wrap_comments = false format_code_in_doc_comments = false +doc_comment_code_block_width = 100 comment_width = 80 normalize_comments = false normalize_doc_attributes = false diff --git a/src/expr.rs b/src/expr.rs index 4ccf1ca70c9d9..e4cc93026f10b 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1,6 +1,5 @@ use std::borrow::Cow; use std::cmp::min; -use std::collections::HashMap; use itertools::Itertools; use rustc_ast::token::{Delimiter, LitKind}; @@ -23,7 +22,7 @@ use crate::macros::{rewrite_macro, MacroPosition}; use crate::matches::rewrite_match; use crate::overflow::{self, IntoOverflowableItem, OverflowableItem}; use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts}; -use crate::rewrite::{QueryId, Rewrite, RewriteContext}; +use crate::rewrite::{Rewrite, RewriteContext}; use crate::shape::{Indent, Shape}; use crate::source_map::{LineRangeUtils, SpanUtils}; use crate::spanned::Spanned; @@ -54,54 +53,6 @@ pub(crate) fn format_expr( expr_type: ExprType, context: &RewriteContext<'_>, shape: Shape, -) -> Option { - // when max_width is tight, we should check all possible formattings, in order to find - // if we can fit expression in the limit. Doing it recursively takes exponential time - // relative to input size, and people hit it with rustfmt takes minutes in #4476 #4867 #5128 - // By memoization of format_expr function, we format each pair of expression and shape - // only once, so worst case execution time becomes O(n*max_width^3). - if context.inside_macro() || context.is_macro_def { - // span ids are not unique in macros, so we don't memoize result of them. - return format_expr_inner(expr, expr_type, context, shape); - } - let clean; - let query_id = QueryId { - shape, - span: expr.span, - }; - if let Some(map) = context.memoize.take() { - if let Some(r) = map.get(&query_id) { - let r = r.clone(); - context.memoize.set(Some(map)); // restore map in the memoize cell for other users - return r; - } - context.memoize.set(Some(map)); - clean = false; - } else { - context.memoize.set(Some(HashMap::default())); - clean = true; // We got None, so we are the top level called function. When - // this function finishes, no one is interested in what is in the map, because - // all of them are sub expressions of this top level expression, and this is - // done. So we should clean up memoize map to save some memory. - } - - let r = format_expr_inner(expr, expr_type, context, shape); - if clean { - context.memoize.set(None); - } else { - if let Some(mut map) = context.memoize.take() { - map.insert(query_id, r.clone()); // insert the result in the memoize map - context.memoize.set(Some(map)); // so it won't be computed again - } - } - r -} - -fn format_expr_inner( - expr: &ast::Expr, - expr_type: ExprType, - context: &RewriteContext<'_>, - shape: Shape, ) -> Option { skip_out_of_file_lines_range!(context, expr.span); diff --git a/src/formatting.rs b/src/formatting.rs index e644ea50effd7..1dfd8a514f0bc 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -2,7 +2,6 @@ use std::collections::HashMap; use std::io::{self, Write}; -use std::rc::Rc; use std::time::{Duration, Instant}; use rustc_ast::ast; @@ -203,7 +202,6 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> { self.config, &snippet_provider, self.report.clone(), - Rc::default(), ); visitor.skip_context.update_with_attrs(&self.krate.attrs); visitor.is_macro_def = is_macro_def; diff --git a/src/imports.rs b/src/imports.rs index 559ed3917dba7..8d41c881589e5 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -15,7 +15,7 @@ use rustc_span::{ use crate::comment::combine_strs_with_missing_comments; use crate::config::lists::*; use crate::config::ImportGranularity; -use crate::config::{Edition, IndentStyle}; +use crate::config::{Edition, IndentStyle, Version}; use crate::lists::{ definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator, }; @@ -92,7 +92,7 @@ impl<'a> FmtVisitor<'a> { // FIXME we do a lot of allocation to make our own representation. #[derive(Clone, Eq, Hash, PartialEq)] -pub(crate) enum UseSegment { +pub(crate) enum UseSegmentKind { Ident(String, Option), Slf(Option), Super(Option), @@ -101,6 +101,12 @@ pub(crate) enum UseSegment { List(Vec), } +#[derive(Clone, Eq, PartialEq)] +pub(crate) struct UseSegment { + pub(crate) kind: UseSegmentKind, + pub(crate) version: Version, +} + #[derive(Clone)] pub(crate) struct UseTree { pub(crate) path: Vec, @@ -134,34 +140,38 @@ impl Spanned for UseTree { impl UseSegment { // Clone a version of self with any top-level alias removed. fn remove_alias(&self) -> UseSegment { - match *self { - UseSegment::Ident(ref s, _) => UseSegment::Ident(s.clone(), None), - UseSegment::Slf(_) => UseSegment::Slf(None), - UseSegment::Super(_) => UseSegment::Super(None), - UseSegment::Crate(_) => UseSegment::Crate(None), - _ => self.clone(), + let kind = match self.kind { + UseSegmentKind::Ident(ref s, _) => UseSegmentKind::Ident(s.clone(), None), + UseSegmentKind::Slf(_) => UseSegmentKind::Slf(None), + UseSegmentKind::Super(_) => UseSegmentKind::Super(None), + UseSegmentKind::Crate(_) => UseSegmentKind::Crate(None), + _ => return self.clone(), + }; + UseSegment { + kind, + version: self.version, } } // Check if self == other with their aliases removed. fn equal_except_alias(&self, other: &Self) -> bool { - match (self, other) { - (UseSegment::Ident(ref s1, _), UseSegment::Ident(ref s2, _)) => s1 == s2, - (UseSegment::Slf(_), UseSegment::Slf(_)) - | (UseSegment::Super(_), UseSegment::Super(_)) - | (UseSegment::Crate(_), UseSegment::Crate(_)) - | (UseSegment::Glob, UseSegment::Glob) => true, - (UseSegment::List(ref list1), UseSegment::List(ref list2)) => list1 == list2, + match (&self.kind, &other.kind) { + (UseSegmentKind::Ident(ref s1, _), UseSegmentKind::Ident(ref s2, _)) => s1 == s2, + (UseSegmentKind::Slf(_), UseSegmentKind::Slf(_)) + | (UseSegmentKind::Super(_), UseSegmentKind::Super(_)) + | (UseSegmentKind::Crate(_), UseSegmentKind::Crate(_)) + | (UseSegmentKind::Glob, UseSegmentKind::Glob) => true, + (UseSegmentKind::List(ref list1), UseSegmentKind::List(ref list2)) => list1 == list2, _ => false, } } fn get_alias(&self) -> Option<&str> { - match self { - UseSegment::Ident(_, a) - | UseSegment::Slf(a) - | UseSegment::Super(a) - | UseSegment::Crate(a) => a.as_deref(), + match &self.kind { + UseSegmentKind::Ident(_, a) + | UseSegmentKind::Slf(a) + | UseSegmentKind::Super(a) + | UseSegmentKind::Crate(a) => a.as_deref(), _ => None, } } @@ -175,19 +185,24 @@ impl UseSegment { if name.is_empty() || name == "{{root}}" { return None; } - Some(match name { - "self" => UseSegment::Slf(None), - "super" => UseSegment::Super(None), - "crate" => UseSegment::Crate(None), + let kind = match name { + "self" => UseSegmentKind::Slf(None), + "super" => UseSegmentKind::Super(None), + "crate" => UseSegmentKind::Crate(None), _ => { let mod_sep = if modsep { "::" } else { "" }; - UseSegment::Ident(format!("{}{}", mod_sep, name), None) + UseSegmentKind::Ident(format!("{}{}", mod_sep, name), None) } + }; + + Some(UseSegment { + kind, + version: context.config.version(), }) } fn contains_comment(&self) -> bool { - if let UseSegment::List(list) = self { + if let UseSegmentKind::List(list) = &self.kind { list.iter().any(|subtree| subtree.contains_comment()) } else { false @@ -254,20 +269,38 @@ impl fmt::Debug for UseTree { impl fmt::Debug for UseSegment { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(self, f) + fmt::Display::fmt(&self.kind, f) } } impl fmt::Display for UseSegment { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&self.kind, f) + } +} + +impl Hash for UseSegment { + fn hash(&self, state: &mut H) { + self.kind.hash(state); + } +} + +impl fmt::Debug for UseSegmentKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl fmt::Display for UseSegmentKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - UseSegment::Glob => write!(f, "*"), - UseSegment::Ident(ref s, Some(ref alias)) => write!(f, "{} as {}", s, alias), - UseSegment::Ident(ref s, None) => write!(f, "{}", s), - UseSegment::Slf(..) => write!(f, "self"), - UseSegment::Super(..) => write!(f, "super"), - UseSegment::Crate(..) => write!(f, "crate"), - UseSegment::List(ref list) => { + UseSegmentKind::Glob => write!(f, "*"), + UseSegmentKind::Ident(ref s, Some(ref alias)) => write!(f, "{} as {}", s, alias), + UseSegmentKind::Ident(ref s, None) => write!(f, "{}", s), + UseSegmentKind::Slf(..) => write!(f, "self"), + UseSegmentKind::Super(..) => write!(f, "super"), + UseSegmentKind::Crate(..) => write!(f, "crate"), + UseSegmentKind::List(ref list) => { write!(f, "{{")?; for (i, item) in list.iter().enumerate() { if i != 0 { @@ -411,13 +444,19 @@ impl UseTree { } } + let version = context.config.version(); + match a.kind { UseTreeKind::Glob => { // in case of a global path and the glob starts at the root, e.g., "::*" if a.prefix.segments.len() == 1 && leading_modsep { - result.path.push(UseSegment::Ident("".to_owned(), None)); + let kind = UseSegmentKind::Ident("".to_owned(), None); + result.path.push(UseSegment { kind, version }); } - result.path.push(UseSegment::Glob); + result.path.push(UseSegment { + kind: UseSegmentKind::Glob, + version, + }); } UseTreeKind::Nested(ref list) => { // Extract comments between nested use items. @@ -438,16 +477,18 @@ impl UseTree { // in case of a global path and the nested list starts at the root, // e.g., "::{foo, bar}" if a.prefix.segments.len() == 1 && leading_modsep { - result.path.push(UseSegment::Ident("".to_owned(), None)); + let kind = UseSegmentKind::Ident("".to_owned(), None); + result.path.push(UseSegment { kind, version }); } - result.path.push(UseSegment::List( + let kind = UseSegmentKind::List( list.iter() .zip(items) .map(|(t, list_item)| { Self::from_ast(context, &t.0, Some(list_item), None, None, None) }) .collect(), - )); + ); + result.path.push(UseSegment { kind, version }); } UseTreeKind::Simple(ref rename, ..) => { // If the path has leading double colons and is composed of only 2 segments, then we @@ -469,13 +510,15 @@ impl UseTree { Some(rewrite_ident(context, ident).to_owned()) } }); - let segment = match name.as_ref() { - "self" => UseSegment::Slf(alias), - "super" => UseSegment::Super(alias), - "crate" => UseSegment::Crate(alias), - _ => UseSegment::Ident(name, alias), + let kind = match name.as_ref() { + "self" => UseSegmentKind::Slf(alias), + "super" => UseSegmentKind::Super(alias), + "crate" => UseSegmentKind::Crate(alias), + _ => UseSegmentKind::Ident(name, alias), }; + let segment = UseSegment { kind, version }; + // `name` is already in result. result.path.pop(); result.path.push(segment); @@ -492,13 +535,13 @@ impl UseTree { let mut aliased_self = false; // Remove foo::{} or self without attributes. - match last { + match last.kind { _ if self.attrs.is_some() => (), - UseSegment::List(ref list) if list.is_empty() => { + UseSegmentKind::List(ref list) if list.is_empty() => { self.path = vec![]; return self; } - UseSegment::Slf(None) if self.path.is_empty() && self.visibility.is_some() => { + UseSegmentKind::Slf(None) if self.path.is_empty() && self.visibility.is_some() => { self.path = vec![]; return self; } @@ -506,15 +549,19 @@ impl UseTree { } // Normalise foo::self -> foo. - if let UseSegment::Slf(None) = last { + if let UseSegmentKind::Slf(None) = last.kind { if !self.path.is_empty() { return self; } } // Normalise foo::self as bar -> foo as bar. - if let UseSegment::Slf(_) = last { - if let Some(UseSegment::Ident(_, None)) = self.path.last() { + if let UseSegmentKind::Slf(_) = last.kind { + if let Some(UseSegment { + kind: UseSegmentKind::Ident(_, None), + .. + }) = self.path.last() + { aliased_self = true; } } @@ -522,9 +569,12 @@ impl UseTree { let mut done = false; if aliased_self { match self.path.last_mut() { - Some(UseSegment::Ident(_, ref mut old_rename)) => { + Some(UseSegment { + kind: UseSegmentKind::Ident(_, ref mut old_rename), + .. + }) => { assert!(old_rename.is_none()); - if let UseSegment::Slf(Some(rename)) = last.clone() { + if let UseSegmentKind::Slf(Some(rename)) = last.clone().kind { *old_rename = Some(rename); done = true; } @@ -538,15 +588,15 @@ impl UseTree { } // Normalise foo::{bar} -> foo::bar - if let UseSegment::List(ref list) = last { + if let UseSegmentKind::List(ref list) = last.kind { if list.len() == 1 && list[0].to_string() != "self" { normalize_sole_list = true; } } if normalize_sole_list { - match last { - UseSegment::List(list) => { + match last.kind { + UseSegmentKind::List(list) => { for seg in &list[0].path { self.path.push(seg.clone()); } @@ -557,10 +607,13 @@ impl UseTree { } // Recursively normalize elements of a list use (including sorting the list). - if let UseSegment::List(list) = last { + if let UseSegmentKind::List(list) = last.kind { let mut list = list.into_iter().map(UseTree::normalize).collect::>(); list.sort(); - last = UseSegment::List(list); + last = UseSegment { + kind: UseSegmentKind::List(list), + version: last.version, + }; } self.path.push(last); @@ -620,10 +673,10 @@ impl UseTree { if self.path.is_empty() || self.contains_comment() { return vec![self]; } - match self.path.clone().last().unwrap() { - UseSegment::List(list) => { + match &self.path.clone().last().unwrap().kind { + UseSegmentKind::List(list) => { if list.len() == 1 && list[0].path.len() == 1 { - if let UseSegment::Slf(..) = list[0].path[0] { + if let UseSegmentKind::Slf(..) = list[0].path[0].kind { return vec![self]; }; } @@ -671,12 +724,15 @@ impl UseTree { /// If this tree ends in `::self`, rewrite it to `::{self}`. fn nest_trailing_self(mut self) -> UseTree { - if let Some(UseSegment::Slf(..)) = self.path.last() { + if let Some(UseSegment { + kind: UseSegmentKind::Slf(..), + .. + }) = self.path.last() + { let self_segment = self.path.pop().unwrap(); - self.path.push(UseSegment::List(vec![UseTree::from_path( - vec![self_segment], - DUMMY_SP, - )])); + let version = self_segment.version; + let kind = UseSegmentKind::List(vec![UseTree::from_path(vec![self_segment], DUMMY_SP)]); + self.path.push(UseSegment { kind, version }); } self } @@ -692,7 +748,8 @@ fn merge_rest( return None; } if a.len() != len && b.len() != len { - if let UseSegment::List(ref list) = a[len] { + let version = a[len].version; + if let UseSegmentKind::List(ref list) = a[len].kind { let mut list = list.clone(); merge_use_trees_inner( &mut list, @@ -700,7 +757,8 @@ fn merge_rest( merge_by, ); let mut new_path = b[..len].to_vec(); - new_path.push(UseSegment::List(list)); + let kind = UseSegmentKind::List(list); + new_path.push(UseSegment { kind, version }); return Some(new_path); } } else if len == 1 { @@ -709,15 +767,28 @@ fn merge_rest( } else { (&b[0], &a[1..]) }; + let kind = UseSegmentKind::Slf(common.get_alias().map(ToString::to_string)); + let version = a[0].version; let mut list = vec![UseTree::from_path( - vec![UseSegment::Slf(common.get_alias().map(ToString::to_string))], + vec![UseSegment { kind, version }], DUMMY_SP, )]; match rest { - [UseSegment::List(rest_list)] => list.extend(rest_list.clone()), + [ + UseSegment { + kind: UseSegmentKind::List(rest_list), + .. + }, + ] => list.extend(rest_list.clone()), _ => list.push(UseTree::from_path(rest.to_vec(), DUMMY_SP)), } - return Some(vec![b[0].clone(), UseSegment::List(list)]); + return Some(vec![ + b[0].clone(), + UseSegment { + kind: UseSegmentKind::List(list), + version, + }, + ]); } else { len -= 1; } @@ -727,7 +798,9 @@ fn merge_rest( ]; list.sort(); let mut new_path = b[..len].to_vec(); - new_path.push(UseSegment::List(list)); + let kind = UseSegmentKind::List(list); + let version = a[0].version; + new_path.push(UseSegment { kind, version }); Some(new_path) } @@ -805,19 +878,33 @@ impl PartialOrd for UseTree { } impl Ord for UseSegment { fn cmp(&self, other: &UseSegment) -> Ordering { - use self::UseSegment::*; + use self::UseSegmentKind::*; fn is_upper_snake_case(s: &str) -> bool { s.chars() .all(|c| c.is_uppercase() || c == '_' || c.is_numeric()) } - match (self, other) { - (&Slf(ref a), &Slf(ref b)) - | (&Super(ref a), &Super(ref b)) - | (&Crate(ref a), &Crate(ref b)) => a.cmp(b), - (&Glob, &Glob) => Ordering::Equal, - (&Ident(ref ia, ref aa), &Ident(ref ib, ref ab)) => { + match (&self.kind, &other.kind) { + (Slf(ref a), Slf(ref b)) + | (Super(ref a), Super(ref b)) + | (Crate(ref a), Crate(ref b)) => match (a, b) { + (Some(sa), Some(sb)) => { + if self.version == Version::Two { + sa.trim_start_matches("r#").cmp(sb.trim_start_matches("r#")) + } else { + a.cmp(b) + } + } + (_, _) => a.cmp(b), + }, + (Glob, Glob) => Ordering::Equal, + (Ident(ref pia, ref aa), Ident(ref pib, ref ab)) => { + let (ia, ib) = if self.version == Version::Two { + (pia.trim_start_matches("r#"), pib.trim_start_matches("r#")) + } else { + (pia.as_str(), pib.as_str()) + }; // snake_case < CamelCase < UPPER_SNAKE_CASE if ia.starts_with(char::is_uppercase) && ib.starts_with(char::is_lowercase) { return Ordering::Greater; @@ -835,15 +922,21 @@ impl Ord for UseSegment { if ident_ord != Ordering::Equal { return ident_ord; } - if aa.is_none() && ab.is_some() { - return Ordering::Less; - } - if aa.is_some() && ab.is_none() { - return Ordering::Greater; + match (aa, ab) { + (None, Some(_)) => Ordering::Less, + (Some(_), None) => Ordering::Greater, + (Some(aas), Some(abs)) => { + if self.version == Version::Two { + aas.trim_start_matches("r#") + .cmp(abs.trim_start_matches("r#")) + } else { + aas.cmp(abs) + } + } + (None, None) => Ordering::Equal, } - aa.cmp(ab) } - (&List(ref a), &List(ref b)) => { + (List(ref a), List(ref b)) => { for (a, b) in a.iter().zip(b.iter()) { let ord = a.cmp(b); if ord != Ordering::Equal { @@ -853,16 +946,16 @@ impl Ord for UseSegment { a.len().cmp(&b.len()) } - (&Slf(_), _) => Ordering::Less, - (_, &Slf(_)) => Ordering::Greater, - (&Super(_), _) => Ordering::Less, - (_, &Super(_)) => Ordering::Greater, - (&Crate(_), _) => Ordering::Less, - (_, &Crate(_)) => Ordering::Greater, - (&Ident(..), _) => Ordering::Less, - (_, &Ident(..)) => Ordering::Greater, - (&Glob, _) => Ordering::Less, - (_, &Glob) => Ordering::Greater, + (Slf(_), _) => Ordering::Less, + (_, Slf(_)) => Ordering::Greater, + (Super(_), _) => Ordering::Less, + (_, Super(_)) => Ordering::Greater, + (Crate(_), _) => Ordering::Less, + (_, Crate(_)) => Ordering::Greater, + (Ident(..), _) => Ordering::Less, + (_, Ident(..)) => Ordering::Greater, + (Glob, _) => Ordering::Less, + (_, Glob) => Ordering::Greater, } } } @@ -906,7 +999,7 @@ fn rewrite_nested_use_tree( } let has_nested_list = use_tree_list.iter().any(|use_segment| { use_segment.path.last().map_or(false, |last_segment| { - matches!(last_segment, UseSegment::List(..)) + matches!(last_segment.kind, UseSegmentKind::List(..)) }) }); @@ -957,17 +1050,19 @@ fn rewrite_nested_use_tree( impl Rewrite for UseSegment { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { - Some(match self { - UseSegment::Ident(ref ident, Some(ref rename)) => format!("{} as {}", ident, rename), - UseSegment::Ident(ref ident, None) => ident.clone(), - UseSegment::Slf(Some(ref rename)) => format!("self as {}", rename), - UseSegment::Slf(None) => "self".to_owned(), - UseSegment::Super(Some(ref rename)) => format!("super as {}", rename), - UseSegment::Super(None) => "super".to_owned(), - UseSegment::Crate(Some(ref rename)) => format!("crate as {}", rename), - UseSegment::Crate(None) => "crate".to_owned(), - UseSegment::Glob => "*".to_owned(), - UseSegment::List(ref use_tree_list) => rewrite_nested_use_tree( + Some(match self.kind { + UseSegmentKind::Ident(ref ident, Some(ref rename)) => { + format!("{} as {}", ident, rename) + } + UseSegmentKind::Ident(ref ident, None) => ident.clone(), + UseSegmentKind::Slf(Some(ref rename)) => format!("self as {}", rename), + UseSegmentKind::Slf(None) => "self".to_owned(), + UseSegmentKind::Super(Some(ref rename)) => format!("super as {}", rename), + UseSegmentKind::Super(None) => "super".to_owned(), + UseSegmentKind::Crate(Some(ref rename)) => format!("crate as {}", rename), + UseSegmentKind::Crate(None) => "crate".to_owned(), + UseSegmentKind::Glob => "*".to_owned(), + UseSegmentKind::List(ref use_tree_list) => rewrite_nested_use_tree( context, use_tree_list, // 1 = "{" and "}" @@ -1016,6 +1111,7 @@ mod test { struct Parser<'a> { input: Peekable>, + version: Version, } impl<'a> Parser<'a> { @@ -1028,34 +1124,40 @@ mod test { } fn push_segment( + &self, result: &mut Vec, buf: &mut String, alias_buf: &mut Option, ) { + let version = self.version; if !buf.is_empty() { let mut alias = None; swap(alias_buf, &mut alias); match buf.as_ref() { "self" => { - result.push(UseSegment::Slf(alias)); + let kind = UseSegmentKind::Slf(alias); + result.push(UseSegment { kind, version }); *buf = String::new(); *alias_buf = None; } "super" => { - result.push(UseSegment::Super(alias)); + let kind = UseSegmentKind::Super(alias); + result.push(UseSegment { kind, version }); *buf = String::new(); *alias_buf = None; } "crate" => { - result.push(UseSegment::Crate(alias)); + let kind = UseSegmentKind::Crate(alias); + result.push(UseSegment { kind, version }); *buf = String::new(); *alias_buf = None; } _ => { let mut name = String::new(); swap(buf, &mut name); - result.push(UseSegment::Ident(name, alias)); + let kind = UseSegmentKind::Ident(name, alias); + result.push(UseSegment { kind, version }); } } } @@ -1070,21 +1172,29 @@ mod test { '{' => { assert!(buf.is_empty()); self.bump(); - result.push(UseSegment::List(self.parse_list())); + let kind = UseSegmentKind::List(self.parse_list()); + result.push(UseSegment { + kind, + version: self.version, + }); self.eat('}'); } '*' => { assert!(buf.is_empty()); self.bump(); - result.push(UseSegment::Glob); + let kind = UseSegmentKind::Glob; + result.push(UseSegment { + kind, + version: self.version, + }); } ':' => { self.bump(); self.eat(':'); - Self::push_segment(&mut result, &mut buf, &mut alias_buf); + self.push_segment(&mut result, &mut buf, &mut alias_buf); } '}' | ',' => { - Self::push_segment(&mut result, &mut buf, &mut alias_buf); + self.push_segment(&mut result, &mut buf, &mut alias_buf); return UseTree { path: result, span: DUMMY_SP, @@ -1110,7 +1220,7 @@ mod test { } } } - Self::push_segment(&mut result, &mut buf, &mut alias_buf); + self.push_segment(&mut result, &mut buf, &mut alias_buf); UseTree { path: result, span: DUMMY_SP, @@ -1136,6 +1246,7 @@ mod test { let mut parser = Parser { input: s.chars().peekable(), + version: Version::One, }; parser.parse_in_list() } diff --git a/src/reorder.rs b/src/reorder.rs index 8ae297de25bc2..9e4a668aa4930 100644 --- a/src/reorder.rs +++ b/src/reorder.rs @@ -12,7 +12,7 @@ use rustc_ast::ast; use rustc_span::{symbol::sym, Span}; use crate::config::{Config, GroupImportsTactic}; -use crate::imports::{normalize_use_trees_with_granularity, UseSegment, UseTree}; +use crate::imports::{normalize_use_trees_with_granularity, UseSegmentKind, UseTree}; use crate::items::{is_mod_decl, rewrite_extern_crate, rewrite_mod}; use crate::lists::{itemize_list, write_list, ListFormatting, ListItem}; use crate::rewrite::RewriteContext; @@ -182,16 +182,16 @@ fn group_imports(uts: Vec) -> Vec> { external_imports.push(ut); continue; } - match &ut.path[0] { - UseSegment::Ident(id, _) => match id.as_ref() { + match &ut.path[0].kind { + UseSegmentKind::Ident(id, _) => match id.as_ref() { "std" | "alloc" | "core" => std_imports.push(ut), _ => external_imports.push(ut), }, - UseSegment::Slf(_) | UseSegment::Super(_) | UseSegment::Crate(_) => { + UseSegmentKind::Slf(_) | UseSegmentKind::Super(_) | UseSegmentKind::Crate(_) => { local_imports.push(ut) } // These are probably illegal here - UseSegment::Glob | UseSegment::List(_) => external_imports.push(ut), + UseSegmentKind::Glob | UseSegmentKind::List(_) => external_imports.push(ut), } } diff --git a/src/rewrite.rs b/src/rewrite.rs index f97df70cc6a7b..4a3bd129d16f5 100644 --- a/src/rewrite.rs +++ b/src/rewrite.rs @@ -12,7 +12,6 @@ use crate::shape::Shape; use crate::skip::SkipContext; use crate::visitor::SnippetProvider; use crate::FormatReport; -use rustc_data_structures::stable_map::FxHashMap; pub(crate) trait Rewrite { /// Rewrite self into shape. @@ -25,22 +24,10 @@ impl Rewrite for ptr::P { } } -#[derive(Clone, PartialEq, Eq, Hash)] -pub(crate) struct QueryId { - pub(crate) shape: Shape, - pub(crate) span: Span, -} - -// We use Option instead of HashMap, because in case of `None` -// the function clean the memoize map, but it doesn't clean when -// there is `Some(empty)`, so they are different. -pub(crate) type Memoize = Rc>>>>; - #[derive(Clone)] pub(crate) struct RewriteContext<'a> { pub(crate) parse_sess: &'a ParseSess, pub(crate) config: &'a Config, - pub(crate) memoize: Memoize, pub(crate) inside_macro: Rc>, // Force block indent style even if we are using visual indent style. pub(crate) use_block: Cell, diff --git a/src/shape.rs b/src/shape.rs index b3f785a9470ee..4376fd12b5260 100644 --- a/src/shape.rs +++ b/src/shape.rs @@ -4,7 +4,7 @@ use std::ops::{Add, Sub}; use crate::Config; -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug)] pub(crate) struct Indent { // Width of the block indent, in characters. Must be a multiple of // Config::tab_spaces. @@ -139,7 +139,7 @@ impl Sub for Indent { // 8096 is close enough to infinite for rustfmt. const INFINITE_SHAPE_WIDTH: usize = 8096; -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug)] pub(crate) struct Shape { pub(crate) width: usize, // The current indentation of code. diff --git a/src/visitor.rs b/src/visitor.rs index 3ff56d52f92d6..9a0e0752c12f5 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -17,7 +17,7 @@ use crate::items::{ use crate::macros::{macro_style, rewrite_macro, rewrite_macro_def, MacroPosition}; use crate::modules::Module; use crate::parse::session::ParseSess; -use crate::rewrite::{Memoize, Rewrite, RewriteContext}; +use crate::rewrite::{Rewrite, RewriteContext}; use crate::shape::{Indent, Shape}; use crate::skip::{is_skip_attr, SkipContext}; use crate::source_map::{LineRangeUtils, SpanUtils}; @@ -71,7 +71,6 @@ impl SnippetProvider { pub(crate) struct FmtVisitor<'a> { parent_context: Option<&'a RewriteContext<'a>>, - pub(crate) memoize: Memoize, pub(crate) parse_sess: &'a ParseSess, pub(crate) buffer: String, pub(crate) last_pos: BytePos, @@ -759,7 +758,6 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ctx.config, ctx.snippet_provider, ctx.report.clone(), - ctx.memoize.clone(), ); visitor.skip_context.update(ctx.skip_context.clone()); visitor.set_parent_context(ctx); @@ -771,12 +769,10 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { config: &'a Config, snippet_provider: &'a SnippetProvider, report: FormatReport, - memoize: Memoize, ) -> FmtVisitor<'a> { FmtVisitor { parent_context: None, parse_sess: parse_session, - memoize, buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2), last_pos: BytePos(0), block_indent: Indent::empty(), @@ -999,7 +995,6 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { RewriteContext { parse_sess: self.parse_sess, config: self.config, - memoize: self.memoize.clone(), inside_macro: Rc::new(Cell::new(false)), use_block: Cell::new(false), is_if_else_block: Cell::new(false), diff --git a/tests/source/configs/doc_comment_code_block_width/100.rs b/tests/source/configs/doc_comment_code_block_width/100.rs new file mode 100644 index 0000000000000..515780761670c --- /dev/null +++ b/tests/source/configs/doc_comment_code_block_width/100.rs @@ -0,0 +1,16 @@ +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 100 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes(v: &[u8]) -> Result { +/// Self::from_bytes_manual_slice(v, 0, v.len() ) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes(v: &[u8]) -> Result { + Self::from_bytes_manual_slice(v, 0, v.len() ) + } +} diff --git a/tests/source/configs/doc_comment_code_block_width/100_greater_max_width.rs b/tests/source/configs/doc_comment_code_block_width/100_greater_max_width.rs new file mode 100644 index 0000000000000..96505c69714e5 --- /dev/null +++ b/tests/source/configs/doc_comment_code_block_width/100_greater_max_width.rs @@ -0,0 +1,17 @@ +// rustfmt-max_width: 50 +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 100 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes(v: &[u8]) -> Result { +/// Self::from_bytes_manual_slice(v, 0, v.len() ) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes(v: &[u8]) -> Result { + Self::from_bytes_manual_slice(v, 0, v.len() ) + } +} diff --git a/tests/source/configs/doc_comment_code_block_width/50.rs b/tests/source/configs/doc_comment_code_block_width/50.rs new file mode 100644 index 0000000000000..2c6307951c84e --- /dev/null +++ b/tests/source/configs/doc_comment_code_block_width/50.rs @@ -0,0 +1,16 @@ +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 50 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes(v: &[u8]) -> Result { +/// Self::from_bytes_manual_slice(v, 0, v.len() ) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes(v: &[u8]) -> Result { + Self::from_bytes_manual_slice(v, 0, v.len() ) + } +} diff --git a/tests/source/imports_raw_identifiers/version_One.rs b/tests/source/imports_raw_identifiers/version_One.rs new file mode 100644 index 0000000000000..bc4b5b135696a --- /dev/null +++ b/tests/source/imports_raw_identifiers/version_One.rs @@ -0,0 +1,5 @@ +// rustfmt-version:One + +use websocket::client::ClientBuilder; +use websocket::r#async::futures::Stream; +use websocket::result::WebSocketError; diff --git a/tests/source/imports_raw_identifiers/version_Two.rs b/tests/source/imports_raw_identifiers/version_Two.rs new file mode 100644 index 0000000000000..88e7fbd01ca6e --- /dev/null +++ b/tests/source/imports_raw_identifiers/version_Two.rs @@ -0,0 +1,5 @@ +// rustfmt-version:Two + +use websocket::client::ClientBuilder; +use websocket::r#async::futures::Stream; +use websocket::result::WebSocketError; diff --git a/tests/source/performance/issue-4476.rs b/tests/source/performance/issue-4476.rs deleted file mode 100644 index 8da3f19b62d60..0000000000000 --- a/tests/source/performance/issue-4476.rs +++ /dev/null @@ -1,638 +0,0 @@ -use super::SemverParser; - -#[allow(dead_code, non_camel_case_types)] -#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub enum Rule { - EOI, - range_set, - logical_or, - range, - empty, - hyphen, - simple, - primitive, - primitive_op, - partial, - xr, - xr_op, - nr, - tilde, - caret, - qualifier, - parts, - part, - space, -} -#[allow(clippy::all)] -impl ::pest::Parser for SemverParser { - fn parse<'i>( - rule: Rule, - input: &'i str, - ) -> ::std::result::Result<::pest::iterators::Pairs<'i, Rule>, ::pest::error::Error> { - mod rules { - pub mod hidden { - use super::super::Rule; - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn skip( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - Ok(state) - } - } - pub mod visible { - use super::super::Rule; - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn range_set( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::range_set, |state| { - state.sequence(|state| { - self::SOI(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::range(state)) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - self::logical_or(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::range(state)) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| { - state.sequence(|state| { - self::logical_or(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::range(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::EOI(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn logical_or( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::logical_or, |state| { - state.sequence(|state| { - state - .sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| state.match_string("||")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn range( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::range, |state| { - self::hyphen(state) - .or_else(|state| { - state.sequence(|state| { - self::simple(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - state - .optional(|state| state.match_string(",")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::simple(state)) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| { - state.sequence(|state| { - state - .optional(|state| state.match_string(",")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::simple(state)) - }) - }) - }) - }) - }) - }) - }) - }) - }) - }) - .or_else(|state| self::empty(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn empty( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::empty, |state| state.match_string("")) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn hyphen( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::hyphen, |state| { - state.sequence(|state| { - self::partial(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| state.match_string("-")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn simple( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::simple, |state| { - self::primitive(state) - .or_else(|state| self::partial(state)) - .or_else(|state| self::tilde(state)) - .or_else(|state| self::caret(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn primitive( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::primitive, |state| { - state.sequence(|state| { - self::primitive_op(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn primitive_op( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::primitive_op, |state| { - state - .match_string("<=") - .or_else(|state| state.match_string(">=")) - .or_else(|state| state.match_string(">")) - .or_else(|state| state.match_string("<")) - .or_else(|state| state.match_string("=")) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn partial( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::partial, |state| { - state.sequence(|state| { - self::xr(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.optional(|state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::xr(state)) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.optional(|state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::xr(state)) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| state.optional(|state| self::qualifier(state))) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn xr( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::xr, |state| { - self::xr_op(state).or_else(|state| self::nr(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn xr_op( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::xr_op, |state| { - state - .match_string("x") - .or_else(|state| state.match_string("X")) - .or_else(|state| state.match_string("*")) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn nr( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::nr, |state| { - state.match_string("0").or_else(|state| { - state.sequence(|state| { - state - .match_range('1'..'9') - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state.match_range('0'..'9').and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| state.match_range('0'..'9')) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn tilde( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::tilde, |state| { - state.sequence(|state| { - state - .match_string("~>") - .or_else(|state| state.match_string("~")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn caret( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::caret, |state| { - state.sequence(|state| { - state - .match_string("^") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn qualifier( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::qualifier, |state| { - state.sequence(|state| { - state - .match_string("-") - .or_else(|state| state.match_string("+")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::parts(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn parts( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::parts, |state| { - state.sequence(|state| { - self::part(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - state - .match_string(".") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::part(state)) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::part(state)) - }) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn part( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::part, |state| { - self::nr(state).or_else(|state| { - state.sequence(|state| { - state - .match_string("-") - .or_else(|state| state.match_range('0'..'9')) - .or_else(|state| state.match_range('A'..'Z')) - .or_else(|state| state.match_range('a'..'z')) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .match_string("-") - .or_else(|state| state.match_range('0'..'9')) - .or_else(|state| state.match_range('A'..'Z')) - .or_else(|state| state.match_range('a'..'z')) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| { - state - .match_string("-") - .or_else(|state| state.match_range('0'..'9')) - .or_else(|state| state.match_range('A'..'Z')) - .or_else(|state| state.match_range('a'..'z')) - }) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn space( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state - .match_string(" ") - .or_else(|state| state.match_string("\t")) - } - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn EOI( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::EOI, |state| state.end_of_input()) - } - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn SOI( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.start_of_input() - } - } - pub use self::visible::*; - } - ::pest::state(input, |state| match rule { - Rule::range_set => rules::range_set(state), - Rule::logical_or => rules::logical_or(state), - Rule::range => rules::range(state), - Rule::empty => rules::empty(state), - Rule::hyphen => rules::hyphen(state), - Rule::simple => rules::simple(state), - Rule::primitive => rules::primitive(state), - Rule::primitive_op => rules::primitive_op(state), - Rule::partial => rules::partial(state), - Rule::xr => rules::xr(state), - Rule::xr_op => rules::xr_op(state), - Rule::nr => rules::nr(state), - Rule::tilde => rules::tilde(state), - Rule::caret => rules::caret(state), - Rule::qualifier => rules::qualifier(state), - Rule::parts => rules::parts(state), - Rule::part => rules::part(state), - Rule::space => rules::space(state), - Rule::EOI => rules::EOI(state), - }) - } -} \ No newline at end of file diff --git a/tests/source/performance/issue-5128.rs b/tests/source/performance/issue-5128.rs deleted file mode 100644 index 3adce49601c0c..0000000000000 --- a/tests/source/performance/issue-5128.rs +++ /dev/null @@ -1,5127 +0,0 @@ - -fn takes_a_long_time_to_rustfmt() { - let inner_cte = vec![Node { - node: Some(node::Node::CommonTableExpr(Box::new(CommonTableExpr { - ctename: String::from("ranked_by_age_within_key"), - aliascolnames: vec![], - ctematerialized: CteMaterialize::Default as i32, - ctequery: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - target_list: vec![ - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from(""), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::AStar(AStar{})) - }], - location: 80 - })) - })), - location: 80 - }))) - }, - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("rank_in_key"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::FuncCall(Box::new(FuncCall { - funcname: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("row_number") - })) - }], - args: vec![], - agg_order: vec![], - agg_filter: None, - agg_within_group: false, - agg_star: false, - agg_distinct: false, - func_variadic: false, - over: Some(Box::new(WindowDef { - name: String::from(""), - refname: String::from(""), - partition_clause: vec![ - Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("synthetic_key") - })) - }], location: 123 - })) - }], order_clause: vec![Node { - node: Some(node::Node::SortBy(Box::new(SortBy { - node: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("logical_timestamp") - })) - }], location: 156 - })) - })), - sortby_dir: SortByDir::SortbyDesc as i32, - sortby_nulls: SortByNulls::SortbyNullsDefault as i32, - use_op: vec![], - location: -1 - }))) - }], frame_options: 1058, start_offset: None, end_offset: None, location: 109 - })), - location: 91 - }))) - })), - location: 91 - }))) - }], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), schemaname: String::from("_supertables"), relname: String::from("9999-9999-9999"), inh: true, relpersistence: String::from("p"), alias: None, location: 206 - })) - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("<=") - })) - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("logical_timestamp") - })) - }], - location: 250 - })) - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer(Integer { - ival: 9000 - })) - })), - location: 271 - }))) - })), - location: 268 - }))) - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: None, - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None - }))), - })), - location: 29, - cterecursive: false, - cterefcount: 0, - ctecolnames: vec![], - ctecoltypes: vec![], - ctecoltypmods: vec![], - ctecolcollations: vec![], - }))), - }]; - let outer_cte = vec![Node { - node: Some(node::Node::CommonTableExpr(Box::new(CommonTableExpr { - ctename: String::from("table_name"), - aliascolnames: vec![], - ctematerialized: CteMaterialize::Default as i32, - ctequery: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - target_list: vec![ - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("column1"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("c1"), - })), - }], - location: 301, - })), - })), - location: 301, - }))), - }, - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("column2"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("c2"), - })), - }], - location: 324, - })), - })), - location: 324, - }))), - }, - ], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), - schemaname: String::from(""), - relname: String::from("ranked_by_age_within_key"), - inh: true, - relpersistence: String::from("p"), - alias: None, - location: 347, - })), - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::BoolExpr(Box::new(BoolExpr { - xpr: None, - boolop: BoolExprType::AndExpr as i32, - args: vec![ - Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("="), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String( - String2 { - str: String::from("rank_in_key"), - }, - )), - }], - location: 382, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer( - Integer { ival: 1 }, - )), - })), - location: 396, - }))), - })), - location: 394, - }))), - }, - Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("="), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String( - String2 { - str: String::from("is_deleted"), - }, - )), - }], - location: 402, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::TypeCast(Box::new( - TypeCast { - arg: Some(Box::new(Node { - node: Some(node::Node::AConst( - Box::new(AConst { - val: Some(Box::new(Node { - node: Some( - node::Node::String( - String2 { - str: - String::from( - "f", - ), - }, - ), - ), - })), - location: 415, - }), - )), - })), - type_name: Some(TypeName { - names: vec![ - Node { - node: Some(node::Node::String( - String2 { - str: String::from( - "pg_catalog", - ), - }, - )), - }, - Node { - node: Some(node::Node::String( - String2 { - str: String::from( - "bool", - ), - }, - )), - }, - ], - type_oid: 0, - setof: false, - pct_type: false, - typmods: vec![], - typemod: -1, - array_bounds: vec![], - location: -1, - }), - location: -1, - }, - ))), - })), - location: 413, - }))), - }, - ], - location: 398, - }))), - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: Some(WithClause { - ctes: inner_cte, - recursive: false, - location: 24, - }), - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None, - }))), - })), - location: 5, - cterecursive: false, - cterefcount: 0, - ctecolnames: vec![], - ctecoltypes: vec![], - ctecoltypmods: vec![], - ctecolcollations: vec![], - }))), - }]; - let expected_result = ParseResult { - version: 130003, - stmts: vec![RawStmt { - stmt: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - - target_list: vec![Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from(""), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("column1"), - })), - }], - location: 430, - })), - })), - location: 430, - }))), - }], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), - schemaname: String::from(""), - relname: String::from("table_name"), - inh: true, - relpersistence: String::from("p"), - alias: None, - location: 443, - })), - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from(">"), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("column2"), - })), - }], - location: 460, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer(Integer { - ival: 9000, - })), - })), - location: 470, - }))), - })), - location: 468, - }))), - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: Some(WithClause { - ctes: outer_cte, - recursive: false, - location: 0, - }), - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None, - }))), - })), - stmt_location: 0, - stmt_len: 0, - }], - }; - -} -#[derive(Clone, PartialEq)] -pub struct ParseResult { - - pub version: i32, - - pub stmts: Vec, -} -#[derive(Clone, PartialEq)] -pub struct ScanResult { - - pub version: i32, - - pub tokens: Vec, -} -#[derive(Clone, PartialEq)] -pub struct Node { - pub node: ::core::option::Option, -} -/// Nested message and enum types in `Node`. -pub mod node { - #[derive(Clone, PartialEq)] - pub enum Node { - - Alias(super::Alias), - - RangeVar(super::RangeVar), - - TableFunc(Box), - - Expr(super::Expr), - - Var(Box), - - Param(Box), - - Aggref(Box), - - GroupingFunc(Box), - - WindowFunc(Box), - - SubscriptingRef(Box), - - FuncExpr(Box), - - NamedArgExpr(Box), - - OpExpr(Box), - - DistinctExpr(Box), - - NullIfExpr(Box), - - ScalarArrayOpExpr(Box), - - BoolExpr(Box), - - SubLink(Box), - - SubPlan(Box), - - AlternativeSubPlan(Box), - - FieldSelect(Box), - - FieldStore(Box), - - RelabelType(Box), - - CoerceViaIo(Box), - - ArrayCoerceExpr(Box), - - ConvertRowtypeExpr(Box), - - CollateExpr(Box), - - CaseExpr(Box), - - CaseWhen(Box), - - CaseTestExpr(Box), - - ArrayExpr(Box), - - RowExpr(Box), - - RowCompareExpr(Box), - - CoalesceExpr(Box), - - MinMaxExpr(Box), - - SqlvalueFunction(Box), - - XmlExpr(Box), - - NullTest(Box), - - BooleanTest(Box), - - CoerceToDomain(Box), - - CoerceToDomainValue(Box), - - SetToDefault(Box), - - CurrentOfExpr(Box), - - NextValueExpr(Box), - - InferenceElem(Box), - - TargetEntry(Box), - - RangeTblRef(super::RangeTblRef), - - JoinExpr(Box), - - FromExpr(Box), - - OnConflictExpr(Box), - - IntoClause(Box), - - RawStmt(Box), - - Query(Box), - - InsertStmt(Box), - - DeleteStmt(Box), - - UpdateStmt(Box), - - SelectStmt(Box), - - AlterTableStmt(super::AlterTableStmt), - - AlterTableCmd(Box), - - AlterDomainStmt(Box), - - SetOperationStmt(Box), - - GrantStmt(super::GrantStmt), - - GrantRoleStmt(super::GrantRoleStmt), - - AlterDefaultPrivilegesStmt(super::AlterDefaultPrivilegesStmt), - - ClosePortalStmt(super::ClosePortalStmt), - - ClusterStmt(super::ClusterStmt), - - CopyStmt(Box), - - CreateStmt(super::CreateStmt), - - DefineStmt(super::DefineStmt), - - DropStmt(super::DropStmt), - - TruncateStmt(super::TruncateStmt), - - CommentStmt(Box), - - FetchStmt(super::FetchStmt), - - IndexStmt(Box), - - CreateFunctionStmt(super::CreateFunctionStmt), - - AlterFunctionStmt(super::AlterFunctionStmt), - - DoStmt(super::DoStmt), - - RenameStmt(Box), - - RuleStmt(Box), - - NotifyStmt(super::NotifyStmt), - - ListenStmt(super::ListenStmt), - - UnlistenStmt(super::UnlistenStmt), - - TransactionStmt(super::TransactionStmt), - - ViewStmt(Box), - - LoadStmt(super::LoadStmt), - - CreateDomainStmt(Box), - - CreatedbStmt(super::CreatedbStmt), - - DropdbStmt(super::DropdbStmt), - - VacuumStmt(super::VacuumStmt), - - ExplainStmt(Box), - - CreateTableAsStmt(Box), - - CreateSeqStmt(super::CreateSeqStmt), - - AlterSeqStmt(super::AlterSeqStmt), - - VariableSetStmt(super::VariableSetStmt), - - VariableShowStmt(super::VariableShowStmt), - - DiscardStmt(super::DiscardStmt), - - CreateTrigStmt(Box), - - CreatePlangStmt(super::CreatePLangStmt), - - CreateRoleStmt(super::CreateRoleStmt), - - AlterRoleStmt(super::AlterRoleStmt), - - DropRoleStmt(super::DropRoleStmt), - - LockStmt(super::LockStmt), - - ConstraintsSetStmt(super::ConstraintsSetStmt), - - ReindexStmt(super::ReindexStmt), - - CheckPointStmt(super::CheckPointStmt), - - CreateSchemaStmt(super::CreateSchemaStmt), - - AlterDatabaseStmt(super::AlterDatabaseStmt), - - AlterDatabaseSetStmt(super::AlterDatabaseSetStmt), - - AlterRoleSetStmt(super::AlterRoleSetStmt), - - CreateConversionStmt(super::CreateConversionStmt), - - CreateCastStmt(super::CreateCastStmt), - - CreateOpClassStmt(super::CreateOpClassStmt), - - CreateOpFamilyStmt(super::CreateOpFamilyStmt), - - AlterOpFamilyStmt(super::AlterOpFamilyStmt), - - PrepareStmt(Box), - - ExecuteStmt(super::ExecuteStmt), - - DeallocateStmt(super::DeallocateStmt), - - DeclareCursorStmt(Box), - - CreateTableSpaceStmt(super::CreateTableSpaceStmt), - - DropTableSpaceStmt(super::DropTableSpaceStmt), - - AlterObjectDependsStmt(Box), - - AlterObjectSchemaStmt(Box), - - AlterOwnerStmt(Box), - - AlterOperatorStmt(super::AlterOperatorStmt), - - AlterTypeStmt(super::AlterTypeStmt), - - DropOwnedStmt(super::DropOwnedStmt), - - ReassignOwnedStmt(super::ReassignOwnedStmt), - - CompositeTypeStmt(super::CompositeTypeStmt), - - CreateEnumStmt(super::CreateEnumStmt), - - CreateRangeStmt(super::CreateRangeStmt), - - AlterEnumStmt(super::AlterEnumStmt), - - AlterTsdictionaryStmt(super::AlterTsDictionaryStmt), - - AlterTsconfigurationStmt(super::AlterTsConfigurationStmt), - - CreateFdwStmt(super::CreateFdwStmt), - - AlterFdwStmt(super::AlterFdwStmt), - - CreateForeignServerStmt(super::CreateForeignServerStmt), - - AlterForeignServerStmt(super::AlterForeignServerStmt), - - CreateUserMappingStmt(super::CreateUserMappingStmt), - - AlterUserMappingStmt(super::AlterUserMappingStmt), - - DropUserMappingStmt(super::DropUserMappingStmt), - - AlterTableSpaceOptionsStmt(super::AlterTableSpaceOptionsStmt), - - AlterTableMoveAllStmt(super::AlterTableMoveAllStmt), - - SecLabelStmt(Box), - - CreateForeignTableStmt(super::CreateForeignTableStmt), - - ImportForeignSchemaStmt(super::ImportForeignSchemaStmt), - - CreateExtensionStmt(super::CreateExtensionStmt), - - AlterExtensionStmt(super::AlterExtensionStmt), - - AlterExtensionContentsStmt(Box), - - CreateEventTrigStmt(super::CreateEventTrigStmt), - - AlterEventTrigStmt(super::AlterEventTrigStmt), - - RefreshMatViewStmt(super::RefreshMatViewStmt), - - ReplicaIdentityStmt(super::ReplicaIdentityStmt), - - AlterSystemStmt(super::AlterSystemStmt), - - CreatePolicyStmt(Box), - - AlterPolicyStmt(Box), - - CreateTransformStmt(super::CreateTransformStmt), - - CreateAmStmt(super::CreateAmStmt), - - CreatePublicationStmt(super::CreatePublicationStmt), - - AlterPublicationStmt(super::AlterPublicationStmt), - - CreateSubscriptionStmt(super::CreateSubscriptionStmt), - - AlterSubscriptionStmt(super::AlterSubscriptionStmt), - - DropSubscriptionStmt(super::DropSubscriptionStmt), - - CreateStatsStmt(super::CreateStatsStmt), - - AlterCollationStmt(super::AlterCollationStmt), - - CallStmt(Box), - - AlterStatsStmt(super::AlterStatsStmt), - - AExpr(Box), - - ColumnRef(super::ColumnRef), - - ParamRef(super::ParamRef), - - AConst(Box), - - FuncCall(Box), - - AStar(super::AStar), - - AIndices(Box), - - AIndirection(Box), - - AArrayExpr(super::AArrayExpr), - - ResTarget(Box), - - MultiAssignRef(Box), - - TypeCast(Box), - - CollateClause(Box), - - SortBy(Box), - - WindowDef(Box), - - RangeSubselect(Box), - - RangeFunction(super::RangeFunction), - - RangeTableSample(Box), - - RangeTableFunc(Box), - - RangeTableFuncCol(Box), - - TypeName(super::TypeName), - - ColumnDef(Box), - - IndexElem(Box), - - Constraint(Box), - - DefElem(Box), - - RangeTblEntry(Box), - - RangeTblFunction(Box), - - TableSampleClause(Box), - - WithCheckOption(Box), - - SortGroupClause(super::SortGroupClause), - - GroupingSet(super::GroupingSet), - - WindowClause(Box), - - ObjectWithArgs(super::ObjectWithArgs), - - AccessPriv(super::AccessPriv), - - CreateOpClassItem(super::CreateOpClassItem), - - TableLikeClause(super::TableLikeClause), - - FunctionParameter(Box), - - LockingClause(super::LockingClause), - - RowMarkClause(super::RowMarkClause), - - XmlSerialize(Box), - - WithClause(super::WithClause), - - InferClause(Box), - - OnConflictClause(Box), - - CommonTableExpr(Box), - - RoleSpec(super::RoleSpec), - - TriggerTransition(super::TriggerTransition), - - PartitionElem(Box), - - PartitionSpec(super::PartitionSpec), - - PartitionBoundSpec(super::PartitionBoundSpec), - - PartitionRangeDatum(Box), - - PartitionCmd(super::PartitionCmd), - - VacuumRelation(super::VacuumRelation), - - InlineCodeBlock(super::InlineCodeBlock), - - CallContext(super::CallContext), - - Integer(super::Integer), - - Float(super::Float), - - String(super::String2), - - BitString(super::BitString), - - Null(super::Null), - - List(super::List), - - IntList(super::IntList), - - OidList(super::OidList), - } -} -#[derive(Clone, PartialEq)] -pub struct Integer { - /// machine integer - - pub ival: i32, -} -#[derive(Clone, PartialEq)] -pub struct Float { - /// string - - pub str: String, -} -#[derive(Clone, PartialEq)] -pub struct String2 { - /// string - - pub str: String, -} -#[derive(Clone, PartialEq)] -pub struct BitString { - /// string - - pub str: String, -} -/// intentionally empty -#[derive(Clone, PartialEq)] -pub struct Null {} -#[derive(Clone, PartialEq)] -pub struct List { - - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct OidList { - - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct IntList { - - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct Alias { - - pub aliasname: String, - - pub colnames: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeVar { - - pub catalogname: String, - - pub schemaname: String, - - pub relname: String, - - pub inh: bool, - - pub relpersistence: String, - - pub alias: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TableFunc { - - pub ns_uris: Vec, - - pub ns_names: Vec, - - pub docexpr: ::core::option::Option>, - - pub rowexpr: ::core::option::Option>, - - pub colnames: Vec, - - pub coltypes: Vec, - - pub coltypmods: Vec, - - pub colcollations: Vec, - - pub colexprs: Vec, - - pub coldefexprs: Vec, - - pub notnulls: Vec, - - pub ordinalitycol: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Expr {} -#[derive(Clone, PartialEq)] -pub struct Var { - - pub xpr: ::core::option::Option>, - - pub varno: u32, - - pub varattno: i32, - - pub vartype: u32, - - pub vartypmod: i32, - - pub varcollid: u32, - - pub varlevelsup: u32, - - pub varnosyn: u32, - - pub varattnosyn: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Param { - - pub xpr: ::core::option::Option>, - - pub paramkind: i32, - - pub paramid: i32, - - pub paramtype: u32, - - pub paramtypmod: i32, - - pub paramcollid: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Aggref { - - pub xpr: ::core::option::Option>, - - pub aggfnoid: u32, - - pub aggtype: u32, - - pub aggcollid: u32, - - pub inputcollid: u32, - - pub aggtranstype: u32, - - pub aggargtypes: Vec, - - pub aggdirectargs: Vec, - - pub args: Vec, - - pub aggorder: Vec, - - pub aggdistinct: Vec, - - pub aggfilter: ::core::option::Option>, - - pub aggstar: bool, - - pub aggvariadic: bool, - - pub aggkind: String, - - pub agglevelsup: u32, - - pub aggsplit: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct GroupingFunc { - - pub xpr: ::core::option::Option>, - - pub args: Vec, - - pub refs: Vec, - - pub cols: Vec, - - pub agglevelsup: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowFunc { - - pub xpr: ::core::option::Option>, - - pub winfnoid: u32, - - pub wintype: u32, - - pub wincollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub aggfilter: ::core::option::Option>, - - pub winref: u32, - - pub winstar: bool, - - pub winagg: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubscriptingRef { - - pub xpr: ::core::option::Option>, - - pub refcontainertype: u32, - - pub refelemtype: u32, - - pub reftypmod: i32, - - pub refcollid: u32, - - pub refupperindexpr: Vec, - - pub reflowerindexpr: Vec, - - pub refexpr: ::core::option::Option>, - - pub refassgnexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct FuncExpr { - - pub xpr: ::core::option::Option>, - - pub funcid: u32, - - pub funcresulttype: u32, - - pub funcretset: bool, - - pub funcvariadic: bool, - - pub funcformat: i32, - - pub funccollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NamedArgExpr { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub name: String, - - pub argnumber: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct OpExpr { - - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct DistinctExpr { - - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NullIfExpr { - - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ScalarArrayOpExpr { - - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub use_or: bool, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct BoolExpr { - - pub xpr: ::core::option::Option>, - - pub boolop: i32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubLink { - - pub xpr: ::core::option::Option>, - - pub sub_link_type: i32, - - pub sub_link_id: i32, - - pub testexpr: ::core::option::Option>, - - pub oper_name: Vec, - - pub subselect: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubPlan { - - pub xpr: ::core::option::Option>, - - pub sub_link_type: i32, - - pub testexpr: ::core::option::Option>, - - pub param_ids: Vec, - - pub plan_id: i32, - - pub plan_name: String, - - pub first_col_type: u32, - - pub first_col_typmod: i32, - - pub first_col_collation: u32, - - pub use_hash_table: bool, - - pub unknown_eq_false: bool, - - pub parallel_safe: bool, - - pub set_param: Vec, - - pub par_param: Vec, - - pub args: Vec, - - pub startup_cost: f64, - - pub per_call_cost: f64, -} -#[derive(Clone, PartialEq)] -pub struct AlternativeSubPlan { - - pub xpr: ::core::option::Option>, - - pub subplans: Vec, -} -#[derive(Clone, PartialEq)] -pub struct FieldSelect { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub fieldnum: i32, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, -} -#[derive(Clone, PartialEq)] -pub struct FieldStore { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub newvals: Vec, - - pub fieldnums: Vec, - - pub resulttype: u32, -} -#[derive(Clone, PartialEq)] -pub struct RelabelType { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub relabelformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceViaIo { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resultcollid: u32, - - pub coerceformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ArrayCoerceExpr { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub elemexpr: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub coerceformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ConvertRowtypeExpr { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub convertformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CollateExpr { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub coll_oid: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseExpr { - - pub xpr: ::core::option::Option>, - - pub casetype: u32, - - pub casecollid: u32, - - pub arg: ::core::option::Option>, - - pub args: Vec, - - pub defresult: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseWhen { - - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub result: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseTestExpr { - - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, -} -#[derive(Clone, PartialEq)] -pub struct ArrayExpr { - - pub xpr: ::core::option::Option>, - - pub array_typeid: u32, - - pub array_collid: u32, - - pub element_typeid: u32, - - pub elements: Vec, - - pub multidims: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowExpr { - - pub xpr: ::core::option::Option>, - - pub args: Vec, - - pub row_typeid: u32, - - pub row_format: i32, - - pub colnames: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowCompareExpr { - - pub xpr: ::core::option::Option>, - - pub rctype: i32, - - pub opnos: Vec, - - pub opfamilies: Vec, - - pub inputcollids: Vec, - - pub largs: Vec, - - pub rargs: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CoalesceExpr { - - pub xpr: ::core::option::Option>, - - pub coalescetype: u32, - - pub coalescecollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct MinMaxExpr { - - pub xpr: ::core::option::Option>, - - pub minmaxtype: u32, - - pub minmaxcollid: u32, - - pub inputcollid: u32, - - pub op: i32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SqlValueFunction { - - pub xpr: ::core::option::Option>, - - pub op: i32, - - pub r#type: u32, - - pub typmod: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct XmlExpr { - - pub xpr: ::core::option::Option>, - - pub op: i32, - - pub name: String, - - pub named_args: Vec, - - pub arg_names: Vec, - - pub args: Vec, - - pub xmloption: i32, - - pub r#type: u32, - - pub typmod: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NullTest { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub nulltesttype: i32, - - pub argisrow: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct BooleanTest { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub booltesttype: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceToDomain { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub coercionformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceToDomainValue { - - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SetToDefault { - - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CurrentOfExpr { - - pub xpr: ::core::option::Option>, - - pub cvarno: u32, - - pub cursor_name: String, - - pub cursor_param: i32, -} -#[derive(Clone, PartialEq)] -pub struct NextValueExpr { - - pub xpr: ::core::option::Option>, - - pub seqid: u32, - - pub type_id: u32, -} -#[derive(Clone, PartialEq)] -pub struct InferenceElem { - - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub infercollid: u32, - - pub inferopclass: u32, -} -#[derive(Clone, PartialEq)] -pub struct TargetEntry { - - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub resno: i32, - - pub resname: String, - - pub ressortgroupref: u32, - - pub resorigtbl: u32, - - pub resorigcol: i32, - - pub resjunk: bool, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblRef { - - pub rtindex: i32, -} -#[derive(Clone, PartialEq)] -pub struct JoinExpr { - - pub jointype: i32, - - pub is_natural: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, - - pub using_clause: Vec, - - pub quals: ::core::option::Option>, - - pub alias: ::core::option::Option, - - pub rtindex: i32, -} -#[derive(Clone, PartialEq)] -pub struct FromExpr { - - pub fromlist: Vec, - - pub quals: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct OnConflictExpr { - - pub action: i32, - - pub arbiter_elems: Vec, - - pub arbiter_where: ::core::option::Option>, - - pub constraint: u32, - - pub on_conflict_set: Vec, - - pub on_conflict_where: ::core::option::Option>, - - pub excl_rel_index: i32, - - pub excl_rel_tlist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct IntoClause { - - pub rel: ::core::option::Option, - - pub col_names: Vec, - - pub access_method: String, - - pub options: Vec, - - pub on_commit: i32, - - pub table_space_name: String, - - pub view_query: ::core::option::Option>, - - pub skip_data: bool, -} -#[derive(Clone, PartialEq)] -pub struct RawStmt { - - pub stmt: ::core::option::Option>, - - pub stmt_location: i32, - - pub stmt_len: i32, -} -#[derive(Clone, PartialEq)] -pub struct Query { - - pub command_type: i32, - - pub query_source: i32, - - pub can_set_tag: bool, - - pub utility_stmt: ::core::option::Option>, - - pub result_relation: i32, - - pub has_aggs: bool, - - pub has_window_funcs: bool, - - pub has_target_srfs: bool, - - pub has_sub_links: bool, - - pub has_distinct_on: bool, - - pub has_recursive: bool, - - pub has_modifying_cte: bool, - - pub has_for_update: bool, - - pub has_row_security: bool, - - pub cte_list: Vec, - - pub rtable: Vec, - - pub jointree: ::core::option::Option>, - - pub target_list: Vec, - - pub r#override: i32, - - pub on_conflict: ::core::option::Option>, - - pub returning_list: Vec, - - pub group_clause: Vec, - - pub grouping_sets: Vec, - - pub having_qual: ::core::option::Option>, - - pub window_clause: Vec, - - pub distinct_clause: Vec, - - pub sort_clause: Vec, - - pub limit_offset: ::core::option::Option>, - - pub limit_count: ::core::option::Option>, - - pub limit_option: i32, - - pub row_marks: Vec, - - pub set_operations: ::core::option::Option>, - - pub constraint_deps: Vec, - - pub with_check_options: Vec, - - pub stmt_location: i32, - - pub stmt_len: i32, -} -#[derive(Clone, PartialEq)] -pub struct InsertStmt { - - pub relation: ::core::option::Option, - - pub cols: Vec, - - pub select_stmt: ::core::option::Option>, - - pub on_conflict_clause: ::core::option::Option>, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, - - pub r#override: i32, -} -#[derive(Clone, PartialEq)] -pub struct DeleteStmt { - - pub relation: ::core::option::Option, - - pub using_clause: Vec, - - pub where_clause: ::core::option::Option>, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct UpdateStmt { - - pub relation: ::core::option::Option, - - pub target_list: Vec, - - pub where_clause: ::core::option::Option>, - - pub from_clause: Vec, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct SelectStmt { - - pub distinct_clause: Vec, - - pub into_clause: ::core::option::Option>, - - pub target_list: Vec, - - pub from_clause: Vec, - - pub where_clause: ::core::option::Option>, - - pub group_clause: Vec, - - pub having_clause: ::core::option::Option>, - - pub window_clause: Vec, - - pub values_lists: Vec, - - pub sort_clause: Vec, - - pub limit_offset: ::core::option::Option>, - - pub limit_count: ::core::option::Option>, - - pub limit_option: i32, - - pub locking_clause: Vec, - - pub with_clause: ::core::option::Option, - - pub op: i32, - - pub all: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableStmt { - - pub relation: ::core::option::Option, - - pub cmds: Vec, - - pub relkind: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableCmd { - - pub subtype: i32, - - pub name: String, - - pub num: i32, - - pub newowner: ::core::option::Option, - - pub def: ::core::option::Option>, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterDomainStmt { - - pub subtype: String, - - pub type_name: Vec, - - pub name: String, - - pub def: ::core::option::Option>, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct SetOperationStmt { - - pub op: i32, - - pub all: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, - - pub col_types: Vec, - - pub col_typmods: Vec, - - pub col_collations: Vec, - - pub group_clauses: Vec, -} -#[derive(Clone, PartialEq)] -pub struct GrantStmt { - - pub is_grant: bool, - - pub targtype: i32, - - pub objtype: i32, - - pub objects: Vec, - - pub privileges: Vec, - - pub grantees: Vec, - - pub grant_option: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct GrantRoleStmt { - - pub granted_roles: Vec, - - pub grantee_roles: Vec, - - pub is_grant: bool, - - pub admin_opt: bool, - - pub grantor: ::core::option::Option, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct AlterDefaultPrivilegesStmt { - - pub options: Vec, - - pub action: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct ClosePortalStmt { - - pub portalname: String, -} -#[derive(Clone, PartialEq)] -pub struct ClusterStmt { - - pub relation: ::core::option::Option, - - pub indexname: String, - - pub options: i32, -} -#[derive(Clone, PartialEq)] -pub struct CopyStmt { - - pub relation: ::core::option::Option, - - pub query: ::core::option::Option>, - - pub attlist: Vec, - - pub is_from: bool, - - pub is_program: bool, - - pub filename: String, - - pub options: Vec, - - pub where_clause: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateStmt { - - pub relation: ::core::option::Option, - - pub table_elts: Vec, - - pub inh_relations: Vec, - - pub partbound: ::core::option::Option, - - pub partspec: ::core::option::Option, - - pub of_typename: ::core::option::Option, - - pub constraints: Vec, - - pub options: Vec, - - pub oncommit: i32, - - pub tablespacename: String, - - pub access_method: String, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct DefineStmt { - - pub kind: i32, - - pub oldstyle: bool, - - pub defnames: Vec, - - pub args: Vec, - - pub definition: Vec, - - pub if_not_exists: bool, - - pub replace: bool, -} -#[derive(Clone, PartialEq)] -pub struct DropStmt { - - pub objects: Vec, - - pub remove_type: i32, - - pub behavior: i32, - - pub missing_ok: bool, - - pub concurrent: bool, -} -#[derive(Clone, PartialEq)] -pub struct TruncateStmt { - - pub relations: Vec, - - pub restart_seqs: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct CommentStmt { - - pub objtype: i32, - - pub object: ::core::option::Option>, - - pub comment: String, -} -#[derive(Clone, PartialEq)] -pub struct FetchStmt { - - pub direction: i32, - - pub how_many: i64, - - pub portalname: String, - - pub ismove: bool, -} -#[derive(Clone, PartialEq)] -pub struct IndexStmt { - - pub idxname: String, - - pub relation: ::core::option::Option, - - pub access_method: String, - - pub table_space: String, - - pub index_params: Vec, - - pub index_including_params: Vec, - - pub options: Vec, - - pub where_clause: ::core::option::Option>, - - pub exclude_op_names: Vec, - - pub idxcomment: String, - - pub index_oid: u32, - - pub old_node: u32, - - pub old_create_subid: u32, - - pub old_first_relfilenode_subid: u32, - - pub unique: bool, - - pub primary: bool, - - pub isconstraint: bool, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub transformed: bool, - - pub concurrent: bool, - - pub if_not_exists: bool, - - pub reset_default_tblspc: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateFunctionStmt { - - pub is_procedure: bool, - - pub replace: bool, - - pub funcname: Vec, - - pub parameters: Vec, - - pub return_type: ::core::option::Option, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterFunctionStmt { - - pub objtype: i32, - - pub func: ::core::option::Option, - - pub actions: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DoStmt { - - pub args: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RenameStmt { - - pub rename_type: i32, - - pub relation_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub subname: String, - - pub newname: String, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct RuleStmt { - - pub relation: ::core::option::Option, - - pub rulename: String, - - pub where_clause: ::core::option::Option>, - - pub event: i32, - - pub instead: bool, - - pub actions: Vec, - - pub replace: bool, -} -#[derive(Clone, PartialEq)] -pub struct NotifyStmt { - - pub conditionname: String, - - pub payload: String, -} -#[derive(Clone, PartialEq)] -pub struct ListenStmt { - - pub conditionname: String, -} -#[derive(Clone, PartialEq)] -pub struct UnlistenStmt { - - pub conditionname: String, -} -#[derive(Clone, PartialEq)] -pub struct TransactionStmt { - - pub kind: i32, - - pub options: Vec, - - pub savepoint_name: String, - - pub gid: String, - - pub chain: bool, -} -#[derive(Clone, PartialEq)] -pub struct ViewStmt { - - pub view: ::core::option::Option, - - pub aliases: Vec, - - pub query: ::core::option::Option>, - - pub replace: bool, - - pub options: Vec, - - pub with_check_option: i32, -} -#[derive(Clone, PartialEq)] -pub struct LoadStmt { - - pub filename: String, -} -#[derive(Clone, PartialEq)] -pub struct CreateDomainStmt { - - pub domainname: Vec, - - pub type_name: ::core::option::Option, - - pub coll_clause: ::core::option::Option>, - - pub constraints: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreatedbStmt { - - pub dbname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropdbStmt { - - pub dbname: String, - - pub missing_ok: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct VacuumStmt { - - pub options: Vec, - - pub rels: Vec, - - pub is_vacuumcmd: bool, -} -#[derive(Clone, PartialEq)] -pub struct ExplainStmt { - - pub query: ::core::option::Option>, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateTableAsStmt { - - pub query: ::core::option::Option>, - - pub into: ::core::option::Option>, - - pub relkind: i32, - - pub is_select_into: bool, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateSeqStmt { - - pub sequence: ::core::option::Option, - - pub options: Vec, - - pub owner_id: u32, - - pub for_identity: bool, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterSeqStmt { - - pub sequence: ::core::option::Option, - - pub options: Vec, - - pub for_identity: bool, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct VariableSetStmt { - - pub kind: i32, - - pub name: String, - - pub args: Vec, - - pub is_local: bool, -} -#[derive(Clone, PartialEq)] -pub struct VariableShowStmt { - - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct DiscardStmt { - - pub target: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateTrigStmt { - - pub trigname: String, - - pub relation: ::core::option::Option, - - pub funcname: Vec, - - pub args: Vec, - - pub row: bool, - - pub timing: i32, - - pub events: i32, - - pub columns: Vec, - - pub when_clause: ::core::option::Option>, - - pub isconstraint: bool, - - pub transition_rels: Vec, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub constrrel: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreatePLangStmt { - - pub replace: bool, - - pub plname: String, - - pub plhandler: Vec, - - pub plinline: Vec, - - pub plvalidator: Vec, - - pub pltrusted: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateRoleStmt { - - pub stmt_type: i32, - - pub role: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterRoleStmt { - - pub role: ::core::option::Option, - - pub options: Vec, - - pub action: i32, -} -#[derive(Clone, PartialEq)] -pub struct DropRoleStmt { - - pub roles: Vec, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct LockStmt { - - pub relations: Vec, - - pub mode: i32, - - pub nowait: bool, -} -#[derive(Clone, PartialEq)] -pub struct ConstraintsSetStmt { - - pub constraints: Vec, - - pub deferred: bool, -} -#[derive(Clone, PartialEq)] -pub struct ReindexStmt { - - pub kind: i32, - - pub relation: ::core::option::Option, - - pub name: String, - - pub options: i32, - - pub concurrent: bool, -} -#[derive(Clone, PartialEq)] -pub struct CheckPointStmt {} -#[derive(Clone, PartialEq)] -pub struct CreateSchemaStmt { - - pub schemaname: String, - - pub authrole: ::core::option::Option, - - pub schema_elts: Vec, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterDatabaseStmt { - - pub dbname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterDatabaseSetStmt { - - pub dbname: String, - - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct AlterRoleSetStmt { - - pub role: ::core::option::Option, - - pub database: String, - - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreateConversionStmt { - - pub conversion_name: Vec, - - pub for_encoding_name: String, - - pub to_encoding_name: String, - - pub func_name: Vec, - - pub def: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateCastStmt { - - pub sourcetype: ::core::option::Option, - - pub targettype: ::core::option::Option, - - pub func: ::core::option::Option, - - pub context: i32, - - pub inout: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpClassStmt { - - pub opclassname: Vec, - - pub opfamilyname: Vec, - - pub amname: String, - - pub datatype: ::core::option::Option, - - pub items: Vec, - - pub is_default: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpFamilyStmt { - - pub opfamilyname: Vec, - - pub amname: String, -} -#[derive(Clone, PartialEq)] -pub struct AlterOpFamilyStmt { - - pub opfamilyname: Vec, - - pub amname: String, - - pub is_drop: bool, - - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct PrepareStmt { - - pub name: String, - - pub argtypes: Vec, - - pub query: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct ExecuteStmt { - - pub name: String, - - pub params: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DeallocateStmt { - - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct DeclareCursorStmt { - - pub portalname: String, - - pub options: i32, - - pub query: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateTableSpaceStmt { - - pub tablespacename: String, - - pub owner: ::core::option::Option, - - pub location: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropTableSpaceStmt { - - pub tablespacename: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterObjectDependsStmt { - - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub extname: ::core::option::Option>, - - pub remove: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterObjectSchemaStmt { - - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub newschema: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterOwnerStmt { - - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub newowner: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct AlterOperatorStmt { - - pub opername: ::core::option::Option, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterTypeStmt { - - pub type_name: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropOwnedStmt { - - pub roles: Vec, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct ReassignOwnedStmt { - - pub roles: Vec, - - pub newrole: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CompositeTypeStmt { - - pub typevar: ::core::option::Option, - - pub coldeflist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateEnumStmt { - - pub type_name: Vec, - - pub vals: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateRangeStmt { - - pub type_name: Vec, - - pub params: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterEnumStmt { - - pub type_name: Vec, - - pub old_val: String, - - pub new_val: String, - - pub new_val_neighbor: String, - - pub new_val_is_after: bool, - - pub skip_if_new_val_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTsDictionaryStmt { - - pub dictname: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterTsConfigurationStmt { - - pub kind: i32, - - pub cfgname: Vec, - - pub tokentype: Vec, - - pub dicts: Vec, - - pub r#override: bool, - - pub replace: bool, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateFdwStmt { - - pub fdwname: String, - - pub func_options: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterFdwStmt { - - pub fdwname: String, - - pub func_options: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateForeignServerStmt { - - pub servername: String, - - pub servertype: String, - - pub version: String, - - pub fdwname: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterForeignServerStmt { - - pub servername: String, - - pub version: String, - - pub options: Vec, - - pub has_version: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateUserMappingStmt { - - pub user: ::core::option::Option, - - pub servername: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterUserMappingStmt { - - pub user: ::core::option::Option, - - pub servername: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropUserMappingStmt { - - pub user: ::core::option::Option, - - pub servername: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableSpaceOptionsStmt { - - pub tablespacename: String, - - pub options: Vec, - - pub is_reset: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableMoveAllStmt { - - pub orig_tablespacename: String, - - pub objtype: i32, - - pub roles: Vec, - - pub new_tablespacename: String, - - pub nowait: bool, -} -#[derive(Clone, PartialEq)] -pub struct SecLabelStmt { - - pub objtype: i32, - - pub object: ::core::option::Option>, - - pub provider: String, - - pub label: String, -} -#[derive(Clone, PartialEq)] -pub struct CreateForeignTableStmt { - - pub base_stmt: ::core::option::Option, - - pub servername: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct ImportForeignSchemaStmt { - - pub server_name: String, - - pub remote_schema: String, - - pub local_schema: String, - - pub list_type: i32, - - pub table_list: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateExtensionStmt { - - pub extname: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterExtensionStmt { - - pub extname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterExtensionContentsStmt { - - pub extname: String, - - pub action: i32, - - pub objtype: i32, - - pub object: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateEventTrigStmt { - - pub trigname: String, - - pub eventname: String, - - pub whenclause: Vec, - - pub funcname: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterEventTrigStmt { - - pub trigname: String, - - pub tgenabled: String, -} -#[derive(Clone, PartialEq)] -pub struct RefreshMatViewStmt { - - pub concurrent: bool, - - pub skip_data: bool, - - pub relation: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct ReplicaIdentityStmt { - - pub identity_type: String, - - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct AlterSystemStmt { - - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreatePolicyStmt { - - pub policy_name: String, - - pub table: ::core::option::Option, - - pub cmd_name: String, - - pub permissive: bool, - - pub roles: Vec, - - pub qual: ::core::option::Option>, - - pub with_check: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterPolicyStmt { - - pub policy_name: String, - - pub table: ::core::option::Option, - - pub roles: Vec, - - pub qual: ::core::option::Option>, - - pub with_check: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateTransformStmt { - - pub replace: bool, - - pub type_name: ::core::option::Option, - - pub lang: String, - - pub fromsql: ::core::option::Option, - - pub tosql: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreateAmStmt { - - pub amname: String, - - pub handler_name: Vec, - - pub amtype: String, -} -#[derive(Clone, PartialEq)] -pub struct CreatePublicationStmt { - - pub pubname: String, - - pub options: Vec, - - pub tables: Vec, - - pub for_all_tables: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterPublicationStmt { - - pub pubname: String, - - pub options: Vec, - - pub tables: Vec, - - pub for_all_tables: bool, - - pub table_action: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateSubscriptionStmt { - - pub subname: String, - - pub conninfo: String, - - pub publication: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterSubscriptionStmt { - - pub kind: i32, - - pub subname: String, - - pub conninfo: String, - - pub publication: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropSubscriptionStmt { - - pub subname: String, - - pub missing_ok: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateStatsStmt { - - pub defnames: Vec, - - pub stat_types: Vec, - - pub exprs: Vec, - - pub relations: Vec, - - pub stxcomment: String, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterCollationStmt { - - pub collname: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CallStmt { - - pub funccall: ::core::option::Option>, - - pub funcexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterStatsStmt { - - pub defnames: Vec, - - pub stxstattarget: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AExpr { - - pub kind: i32, - - pub name: Vec, - - pub lexpr: ::core::option::Option>, - - pub rexpr: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ColumnRef { - - pub fields: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ParamRef { - - pub number: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct AConst { - - pub val: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct FuncCall { - - pub funcname: Vec, - - pub args: Vec, - - pub agg_order: Vec, - - pub agg_filter: ::core::option::Option>, - - pub agg_within_group: bool, - - pub agg_star: bool, - - pub agg_distinct: bool, - - pub func_variadic: bool, - - pub over: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct AStar {} -#[derive(Clone, PartialEq)] -pub struct AIndices { - - pub is_slice: bool, - - pub lidx: ::core::option::Option>, - - pub uidx: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AIndirection { - - pub arg: ::core::option::Option>, - - pub indirection: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AArrayExpr { - - pub elements: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ResTarget { - - pub name: String, - - pub indirection: Vec, - - pub val: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct MultiAssignRef { - - pub source: ::core::option::Option>, - - pub colno: i32, - - pub ncolumns: i32, -} -#[derive(Clone, PartialEq)] -pub struct TypeCast { - - pub arg: ::core::option::Option>, - - pub type_name: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CollateClause { - - pub arg: ::core::option::Option>, - - pub collname: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SortBy { - - pub node: ::core::option::Option>, - - pub sortby_dir: i32, - - pub sortby_nulls: i32, - - pub use_op: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowDef { - - pub name: String, - - pub refname: String, - - pub partition_clause: Vec, - - pub order_clause: Vec, - - pub frame_options: i32, - - pub start_offset: ::core::option::Option>, - - pub end_offset: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeSubselect { - - pub lateral: bool, - - pub subquery: ::core::option::Option>, - - pub alias: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct RangeFunction { - - pub lateral: bool, - - pub ordinality: bool, - - pub is_rowsfrom: bool, - - pub functions: Vec, - - pub alias: ::core::option::Option, - - pub coldeflist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableSample { - - pub relation: ::core::option::Option>, - - pub method: Vec, - - pub args: Vec, - - pub repeatable: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableFunc { - - pub lateral: bool, - - pub docexpr: ::core::option::Option>, - - pub rowexpr: ::core::option::Option>, - - pub namespaces: Vec, - - pub columns: Vec, - - pub alias: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableFuncCol { - - pub colname: String, - - pub type_name: ::core::option::Option, - - pub for_ordinality: bool, - - pub is_not_null: bool, - - pub colexpr: ::core::option::Option>, - - pub coldefexpr: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TypeName { - - pub names: Vec, - - pub type_oid: u32, - - pub setof: bool, - - pub pct_type: bool, - - pub typmods: Vec, - - pub typemod: i32, - - pub array_bounds: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ColumnDef { - - pub colname: String, - - pub type_name: ::core::option::Option, - - pub inhcount: i32, - - pub is_local: bool, - - pub is_not_null: bool, - - pub is_from_type: bool, - - pub storage: String, - - pub raw_default: ::core::option::Option>, - - pub cooked_default: ::core::option::Option>, - - pub identity: String, - - pub identity_sequence: ::core::option::Option, - - pub generated: String, - - pub coll_clause: ::core::option::Option>, - - pub coll_oid: u32, - - pub constraints: Vec, - - pub fdwoptions: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct IndexElem { - - pub name: String, - - pub expr: ::core::option::Option>, - - pub indexcolname: String, - - pub collation: Vec, - - pub opclass: Vec, - - pub opclassopts: Vec, - - pub ordering: i32, - - pub nulls_ordering: i32, -} -#[derive(Clone, PartialEq)] -pub struct Constraint { - - pub contype: i32, - - pub conname: String, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub location: i32, - - pub is_no_inherit: bool, - - pub raw_expr: ::core::option::Option>, - - pub cooked_expr: String, - - pub generated_when: String, - - pub keys: Vec, - - pub including: Vec, - - pub exclusions: Vec, - - pub options: Vec, - - pub indexname: String, - - pub indexspace: String, - - pub reset_default_tblspc: bool, - - pub access_method: String, - - pub where_clause: ::core::option::Option>, - - pub pktable: ::core::option::Option, - - pub fk_attrs: Vec, - - pub pk_attrs: Vec, - - pub fk_matchtype: String, - - pub fk_upd_action: String, - - pub fk_del_action: String, - - pub old_conpfeqop: Vec, - - pub old_pktable_oid: u32, - - pub skip_validation: bool, - - pub initially_valid: bool, -} -#[derive(Clone, PartialEq)] -pub struct DefElem { - - pub defnamespace: String, - - pub defname: String, - - pub arg: ::core::option::Option>, - - pub defaction: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblEntry { - - pub rtekind: i32, - - pub relid: u32, - - pub relkind: String, - - pub rellockmode: i32, - - pub tablesample: ::core::option::Option>, - - pub subquery: ::core::option::Option>, - - pub security_barrier: bool, - - pub jointype: i32, - - pub joinmergedcols: i32, - - pub joinaliasvars: Vec, - - pub joinleftcols: Vec, - - pub joinrightcols: Vec, - - pub functions: Vec, - - pub funcordinality: bool, - - pub tablefunc: ::core::option::Option>, - - pub values_lists: Vec, - - pub ctename: String, - - pub ctelevelsup: u32, - - pub self_reference: bool, - - pub coltypes: Vec, - - pub coltypmods: Vec, - - pub colcollations: Vec, - - pub enrname: String, - - pub enrtuples: f64, - - pub alias: ::core::option::Option, - - pub eref: ::core::option::Option, - - pub lateral: bool, - - pub inh: bool, - - pub in_from_cl: bool, - - pub required_perms: u32, - - pub check_as_user: u32, - - pub selected_cols: Vec, - - pub inserted_cols: Vec, - - pub updated_cols: Vec, - - pub extra_updated_cols: Vec, - - pub security_quals: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblFunction { - - pub funcexpr: ::core::option::Option>, - - pub funccolcount: i32, - - pub funccolnames: Vec, - - pub funccoltypes: Vec, - - pub funccoltypmods: Vec, - - pub funccolcollations: Vec, - - pub funcparams: Vec, -} -#[derive(Clone, PartialEq)] -pub struct TableSampleClause { - - pub tsmhandler: u32, - - pub args: Vec, - - pub repeatable: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct WithCheckOption { - - pub kind: i32, - - pub relname: String, - - pub polname: String, - - pub qual: ::core::option::Option>, - - pub cascaded: bool, -} -#[derive(Clone, PartialEq)] -pub struct SortGroupClause { - - pub tle_sort_group_ref: u32, - - pub eqop: u32, - - pub sortop: u32, - - pub nulls_first: bool, - - pub hashable: bool, -} -#[derive(Clone, PartialEq)] -pub struct GroupingSet { - - pub kind: i32, - - pub content: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowClause { - - pub name: String, - - pub refname: String, - - pub partition_clause: Vec, - - pub order_clause: Vec, - - pub frame_options: i32, - - pub start_offset: ::core::option::Option>, - - pub end_offset: ::core::option::Option>, - - pub start_in_range_func: u32, - - pub end_in_range_func: u32, - - pub in_range_coll: u32, - - pub in_range_asc: bool, - - pub in_range_nulls_first: bool, - - pub winref: u32, - - pub copied_order: bool, -} -#[derive(Clone, PartialEq)] -pub struct ObjectWithArgs { - - pub objname: Vec, - - pub objargs: Vec, - - pub args_unspecified: bool, -} -#[derive(Clone, PartialEq)] -pub struct AccessPriv { - - pub priv_name: String, - - pub cols: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpClassItem { - - pub itemtype: i32, - - pub name: ::core::option::Option, - - pub number: i32, - - pub order_family: Vec, - - pub class_args: Vec, - - pub storedtype: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct TableLikeClause { - - pub relation: ::core::option::Option, - - pub options: u32, - - pub relation_oid: u32, -} -#[derive(Clone, PartialEq)] -pub struct FunctionParameter { - - pub name: String, - - pub arg_type: ::core::option::Option, - - pub mode: i32, - - pub defexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct LockingClause { - - pub locked_rels: Vec, - - pub strength: i32, - - pub wait_policy: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowMarkClause { - - pub rti: u32, - - pub strength: i32, - - pub wait_policy: i32, - - pub pushed_down: bool, -} -#[derive(Clone, PartialEq)] -pub struct XmlSerialize { - - pub xmloption: i32, - - pub expr: ::core::option::Option>, - - pub type_name: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WithClause { - - pub ctes: Vec, - - pub recursive: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct InferClause { - - pub index_elems: Vec, - - pub where_clause: ::core::option::Option>, - - pub conname: String, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct OnConflictClause { - - pub action: i32, - - pub infer: ::core::option::Option>, - - pub target_list: Vec, - - pub where_clause: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CommonTableExpr { - - pub ctename: String, - - pub aliascolnames: Vec, - - pub ctematerialized: i32, - - pub ctequery: ::core::option::Option>, - - pub location: i32, - - pub cterecursive: bool, - - pub cterefcount: i32, - - pub ctecolnames: Vec, - - pub ctecoltypes: Vec, - - pub ctecoltypmods: Vec, - - pub ctecolcollations: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RoleSpec { - - pub roletype: i32, - - pub rolename: String, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TriggerTransition { - - pub name: String, - - pub is_new: bool, - - pub is_table: bool, -} -#[derive(Clone, PartialEq)] -pub struct PartitionElem { - - pub name: String, - - pub expr: ::core::option::Option>, - - pub collation: Vec, - - pub opclass: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionSpec { - - pub strategy: String, - - pub part_params: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionBoundSpec { - - pub strategy: String, - - pub is_default: bool, - - pub modulus: i32, - - pub remainder: i32, - - pub listdatums: Vec, - - pub lowerdatums: Vec, - - pub upperdatums: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionRangeDatum { - - pub kind: i32, - - pub value: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionCmd { - - pub name: ::core::option::Option, - - pub bound: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct VacuumRelation { - - pub relation: ::core::option::Option, - - pub oid: u32, - - pub va_cols: Vec, -} -#[derive(Clone, PartialEq)] -pub struct InlineCodeBlock { - - pub source_text: String, - - pub lang_oid: u32, - - pub lang_is_trusted: bool, - - pub atomic: bool, -} -#[derive(Clone, PartialEq)] -pub struct CallContext { - - pub atomic: bool, -} -#[derive(Clone, PartialEq)] -pub struct ScanToken { - - pub start: i32, - - pub end: i32, - - pub token: i32, - - pub keyword_kind: i32, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OverridingKind { - Undefined = 0, - OverridingNotSet = 1, - OverridingUserValue = 2, - OverridingSystemValue = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum QuerySource { - Undefined = 0, - QsrcOriginal = 1, - QsrcParser = 2, - QsrcInsteadRule = 3, - QsrcQualInsteadRule = 4, - QsrcNonInsteadRule = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SortByDir { - Undefined = 0, - SortbyDefault = 1, - SortbyAsc = 2, - SortbyDesc = 3, - SortbyUsing = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SortByNulls { - Undefined = 0, - SortbyNullsDefault = 1, - SortbyNullsFirst = 2, - SortbyNullsLast = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AExprKind { - Undefined = 0, - AexprOp = 1, - AexprOpAny = 2, - AexprOpAll = 3, - AexprDistinct = 4, - AexprNotDistinct = 5, - AexprNullif = 6, - AexprOf = 7, - AexprIn = 8, - AexprLike = 9, - AexprIlike = 10, - AexprSimilar = 11, - AexprBetween = 12, - AexprNotBetween = 13, - AexprBetweenSym = 14, - AexprNotBetweenSym = 15, - AexprParen = 16, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RoleSpecType { - Undefined = 0, - RolespecCstring = 1, - RolespecCurrentUser = 2, - RolespecSessionUser = 3, - RolespecPublic = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum TableLikeOption { - Undefined = 0, - CreateTableLikeComments = 1, - CreateTableLikeConstraints = 2, - CreateTableLikeDefaults = 3, - CreateTableLikeGenerated = 4, - CreateTableLikeIdentity = 5, - CreateTableLikeIndexes = 6, - CreateTableLikeStatistics = 7, - CreateTableLikeStorage = 8, - CreateTableLikeAll = 9, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DefElemAction { - Undefined = 0, - DefelemUnspec = 1, - DefelemSet = 2, - DefelemAdd = 3, - DefelemDrop = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum PartitionRangeDatumKind { - Undefined = 0, - PartitionRangeDatumMinvalue = 1, - PartitionRangeDatumValue = 2, - PartitionRangeDatumMaxvalue = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RteKind { - RtekindUndefined = 0, - RteRelation = 1, - RteSubquery = 2, - RteJoin = 3, - RteFunction = 4, - RteTablefunc = 5, - RteValues = 6, - RteCte = 7, - RteNamedtuplestore = 8, - RteResult = 9, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum WcoKind { - WcokindUndefined = 0, - WcoViewCheck = 1, - WcoRlsInsertCheck = 2, - WcoRlsUpdateCheck = 3, - WcoRlsConflictCheck = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum GroupingSetKind { - Undefined = 0, - GroupingSetEmpty = 1, - GroupingSetSimple = 2, - GroupingSetRollup = 3, - GroupingSetCube = 4, - GroupingSetSets = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CteMaterialize { - CtematerializeUndefined = 0, - Default = 1, - Always = 2, - Never = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOperation { - Undefined = 0, - SetopNone = 1, - SetopUnion = 2, - SetopIntersect = 3, - SetopExcept = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ObjectType { - Undefined = 0, - ObjectAccessMethod = 1, - ObjectAggregate = 2, - ObjectAmop = 3, - ObjectAmproc = 4, - ObjectAttribute = 5, - ObjectCast = 6, - ObjectColumn = 7, - ObjectCollation = 8, - ObjectConversion = 9, - ObjectDatabase = 10, - ObjectDefault = 11, - ObjectDefacl = 12, - ObjectDomain = 13, - ObjectDomconstraint = 14, - ObjectEventTrigger = 15, - ObjectExtension = 16, - ObjectFdw = 17, - ObjectForeignServer = 18, - ObjectForeignTable = 19, - ObjectFunction = 20, - ObjectIndex = 21, - ObjectLanguage = 22, - ObjectLargeobject = 23, - ObjectMatview = 24, - ObjectOpclass = 25, - ObjectOperator = 26, - ObjectOpfamily = 27, - ObjectPolicy = 28, - ObjectProcedure = 29, - ObjectPublication = 30, - ObjectPublicationRel = 31, - ObjectRole = 32, - ObjectRoutine = 33, - ObjectRule = 34, - ObjectSchema = 35, - ObjectSequence = 36, - ObjectSubscription = 37, - ObjectStatisticExt = 38, - ObjectTabconstraint = 39, - ObjectTable = 40, - ObjectTablespace = 41, - ObjectTransform = 42, - ObjectTrigger = 43, - ObjectTsconfiguration = 44, - ObjectTsdictionary = 45, - ObjectTsparser = 46, - ObjectTstemplate = 47, - ObjectType = 48, - ObjectUserMapping = 49, - ObjectView = 50, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DropBehavior { - Undefined = 0, - DropRestrict = 1, - DropCascade = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterTableType { - Undefined = 0, - AtAddColumn = 1, - AtAddColumnRecurse = 2, - AtAddColumnToView = 3, - AtColumnDefault = 4, - AtCookedColumnDefault = 5, - AtDropNotNull = 6, - AtSetNotNull = 7, - AtDropExpression = 8, - AtCheckNotNull = 9, - AtSetStatistics = 10, - AtSetOptions = 11, - AtResetOptions = 12, - AtSetStorage = 13, - AtDropColumn = 14, - AtDropColumnRecurse = 15, - AtAddIndex = 16, - AtReAddIndex = 17, - AtAddConstraint = 18, - AtAddConstraintRecurse = 19, - AtReAddConstraint = 20, - AtReAddDomainConstraint = 21, - AtAlterConstraint = 22, - AtValidateConstraint = 23, - AtValidateConstraintRecurse = 24, - AtAddIndexConstraint = 25, - AtDropConstraint = 26, - AtDropConstraintRecurse = 27, - AtReAddComment = 28, - AtAlterColumnType = 29, - AtAlterColumnGenericOptions = 30, - AtChangeOwner = 31, - AtClusterOn = 32, - AtDropCluster = 33, - AtSetLogged = 34, - AtSetUnLogged = 35, - AtDropOids = 36, - AtSetTableSpace = 37, - AtSetRelOptions = 38, - AtResetRelOptions = 39, - AtReplaceRelOptions = 40, - AtEnableTrig = 41, - AtEnableAlwaysTrig = 42, - AtEnableReplicaTrig = 43, - AtDisableTrig = 44, - AtEnableTrigAll = 45, - AtDisableTrigAll = 46, - AtEnableTrigUser = 47, - AtDisableTrigUser = 48, - AtEnableRule = 49, - AtEnableAlwaysRule = 50, - AtEnableReplicaRule = 51, - AtDisableRule = 52, - AtAddInherit = 53, - AtDropInherit = 54, - AtAddOf = 55, - AtDropOf = 56, - AtReplicaIdentity = 57, - AtEnableRowSecurity = 58, - AtDisableRowSecurity = 59, - AtForceRowSecurity = 60, - AtNoForceRowSecurity = 61, - AtGenericOptions = 62, - AtAttachPartition = 63, - AtDetachPartition = 64, - AtAddIdentity = 65, - AtSetIdentity = 66, - AtDropIdentity = 67, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum GrantTargetType { - Undefined = 0, - AclTargetObject = 1, - AclTargetAllInSchema = 2, - AclTargetDefaults = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum VariableSetKind { - Undefined = 0, - VarSetValue = 1, - VarSetDefault = 2, - VarSetCurrent = 3, - VarSetMulti = 4, - VarReset = 5, - VarResetAll = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ConstrType { - Undefined = 0, - ConstrNull = 1, - ConstrNotnull = 2, - ConstrDefault = 3, - ConstrIdentity = 4, - ConstrGenerated = 5, - ConstrCheck = 6, - ConstrPrimary = 7, - ConstrUnique = 8, - ConstrExclusion = 9, - ConstrForeign = 10, - ConstrAttrDeferrable = 11, - ConstrAttrNotDeferrable = 12, - ConstrAttrDeferred = 13, - ConstrAttrImmediate = 14, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ImportForeignSchemaType { - Undefined = 0, - FdwImportSchemaAll = 1, - FdwImportSchemaLimitTo = 2, - FdwImportSchemaExcept = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RoleStmtType { - Undefined = 0, - RolestmtRole = 1, - RolestmtUser = 2, - RolestmtGroup = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum FetchDirection { - Undefined = 0, - FetchForward = 1, - FetchBackward = 2, - FetchAbsolute = 3, - FetchRelative = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum FunctionParameterMode { - Undefined = 0, - FuncParamIn = 1, - FuncParamOut = 2, - FuncParamInout = 3, - FuncParamVariadic = 4, - FuncParamTable = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum TransactionStmtKind { - Undefined = 0, - TransStmtBegin = 1, - TransStmtStart = 2, - TransStmtCommit = 3, - TransStmtRollback = 4, - TransStmtSavepoint = 5, - TransStmtRelease = 6, - TransStmtRollbackTo = 7, - TransStmtPrepare = 8, - TransStmtCommitPrepared = 9, - TransStmtRollbackPrepared = 10, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ViewCheckOption { - Undefined = 0, - NoCheckOption = 1, - LocalCheckOption = 2, - CascadedCheckOption = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ClusterOption { - Undefined = 0, - CluoptRecheck = 1, - CluoptVerbose = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DiscardMode { - Undefined = 0, - DiscardAll = 1, - DiscardPlans = 2, - DiscardSequences = 3, - DiscardTemp = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ReindexObjectType { - Undefined = 0, - ReindexObjectIndex = 1, - ReindexObjectTable = 2, - ReindexObjectSchema = 3, - ReindexObjectSystem = 4, - ReindexObjectDatabase = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterTsConfigType { - AlterTsconfigTypeUndefined = 0, - AlterTsconfigAddMapping = 1, - AlterTsconfigAlterMappingForToken = 2, - AlterTsconfigReplaceDict = 3, - AlterTsconfigReplaceDictForToken = 4, - AlterTsconfigDropMapping = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterSubscriptionType { - Undefined = 0, - AlterSubscriptionOptions = 1, - AlterSubscriptionConnection = 2, - AlterSubscriptionPublication = 3, - AlterSubscriptionRefresh = 4, - AlterSubscriptionEnabled = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OnCommitAction { - Undefined = 0, - OncommitNoop = 1, - OncommitPreserveRows = 2, - OncommitDeleteRows = 3, - OncommitDrop = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ParamKind { - Undefined = 0, - ParamExtern = 1, - ParamExec = 2, - ParamSublink = 3, - ParamMultiexpr = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CoercionContext { - Undefined = 0, - CoercionImplicit = 1, - CoercionAssignment = 2, - CoercionExplicit = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CoercionForm { - Undefined = 0, - CoerceExplicitCall = 1, - CoerceExplicitCast = 2, - CoerceImplicitCast = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum BoolExprType { - Undefined = 0, - AndExpr = 1, - OrExpr = 2, - NotExpr = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SubLinkType { - Undefined = 0, - ExistsSublink = 1, - AllSublink = 2, - AnySublink = 3, - RowcompareSublink = 4, - ExprSublink = 5, - MultiexprSublink = 6, - ArraySublink = 7, - CteSublink = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RowCompareType { - Undefined = 0, - RowcompareLt = 1, - RowcompareLe = 2, - RowcompareEq = 3, - RowcompareGe = 4, - RowcompareGt = 5, - RowcompareNe = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum MinMaxOp { - Undefined = 0, - IsGreatest = 1, - IsLeast = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SqlValueFunctionOp { - SqlvalueFunctionOpUndefined = 0, - SvfopCurrentDate = 1, - SvfopCurrentTime = 2, - SvfopCurrentTimeN = 3, - SvfopCurrentTimestamp = 4, - SvfopCurrentTimestampN = 5, - SvfopLocaltime = 6, - SvfopLocaltimeN = 7, - SvfopLocaltimestamp = 8, - SvfopLocaltimestampN = 9, - SvfopCurrentRole = 10, - SvfopCurrentUser = 11, - SvfopUser = 12, - SvfopSessionUser = 13, - SvfopCurrentCatalog = 14, - SvfopCurrentSchema = 15, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum XmlExprOp { - Undefined = 0, - IsXmlconcat = 1, - IsXmlelement = 2, - IsXmlforest = 3, - IsXmlparse = 4, - IsXmlpi = 5, - IsXmlroot = 6, - IsXmlserialize = 7, - IsDocument = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum XmlOptionType { - Undefined = 0, - XmloptionDocument = 1, - XmloptionContent = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum NullTestType { - Undefined = 0, - IsNull = 1, - IsNotNull = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum BoolTestType { - Undefined = 0, - IsTrue = 1, - IsNotTrue = 2, - IsFalse = 3, - IsNotFalse = 4, - IsUnknown = 5, - IsNotUnknown = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CmdType { - Undefined = 0, - CmdUnknown = 1, - CmdSelect = 2, - CmdUpdate = 3, - CmdInsert = 4, - CmdDelete = 5, - CmdUtility = 6, - CmdNothing = 7, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum JoinType { - Undefined = 0, - JoinInner = 1, - JoinLeft = 2, - JoinFull = 3, - JoinRight = 4, - JoinSemi = 5, - JoinAnti = 6, - JoinUniqueOuter = 7, - JoinUniqueInner = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AggStrategy { - Undefined = 0, - AggPlain = 1, - AggSorted = 2, - AggHashed = 3, - AggMixed = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AggSplit { - Undefined = 0, - AggsplitSimple = 1, - AggsplitInitialSerial = 2, - AggsplitFinalDeserial = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOpCmd { - Undefined = 0, - SetopcmdIntersect = 1, - SetopcmdIntersectAll = 2, - SetopcmdExcept = 3, - SetopcmdExceptAll = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOpStrategy { - Undefined = 0, - SetopSorted = 1, - SetopHashed = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OnConflictAction { - Undefined = 0, - OnconflictNone = 1, - OnconflictNothing = 2, - OnconflictUpdate = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LimitOption { - Undefined = 0, - Default = 1, - Count = 2, - WithTies = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockClauseStrength { - Undefined = 0, - LcsNone = 1, - LcsForkeyshare = 2, - LcsForshare = 3, - LcsFornokeyupdate = 4, - LcsForupdate = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockWaitPolicy { - Undefined = 0, - LockWaitBlock = 1, - LockWaitSkip = 2, - LockWaitError = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockTupleMode { - Undefined = 0, - LockTupleKeyShare = 1, - LockTupleShare = 2, - LockTupleNoKeyExclusive = 3, - LockTupleExclusive = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum KeywordKind { - NoKeyword = 0, - UnreservedKeyword = 1, - ColNameKeyword = 2, - TypeFuncNameKeyword = 3, - ReservedKeyword = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum Token { - Nul = 0, - /// Single-character tokens that are returned 1:1 (identical with "self" list in scan.l) - /// Either supporting syntax, or single-character operators (some can be both) - /// Also see - /// - /// "%" - Ascii37 = 37, - /// "(" - Ascii40 = 40, - /// ")" - Ascii41 = 41, - /// "*" - Ascii42 = 42, - /// "+" - Ascii43 = 43, - /// "," - Ascii44 = 44, - /// "-" - Ascii45 = 45, - /// "." - Ascii46 = 46, - /// "/" - Ascii47 = 47, - /// ":" - Ascii58 = 58, - /// ";" - Ascii59 = 59, - /// "<" - Ascii60 = 60, - /// "=" - Ascii61 = 61, - /// ">" - Ascii62 = 62, - /// "?" - Ascii63 = 63, - /// "[" - Ascii91 = 91, - /// "\" - Ascii92 = 92, - /// "]" - Ascii93 = 93, - /// "^" - Ascii94 = 94, - /// Named tokens in scan.l - Ident = 258, - Uident = 259, - Fconst = 260, - Sconst = 261, - Usconst = 262, - Bconst = 263, - Xconst = 264, - Op = 265, - Iconst = 266, - Param = 267, - Typecast = 268, - DotDot = 269, - ColonEquals = 270, - EqualsGreater = 271, - LessEquals = 272, - GreaterEquals = 273, - NotEquals = 274, - SqlComment = 275, - CComment = 276, - AbortP = 277, - AbsoluteP = 278, - Access = 279, - Action = 280, - AddP = 281, - Admin = 282, - After = 283, - Aggregate = 284, - All = 285, - Also = 286, - Alter = 287, - Always = 288, - Analyse = 289, - Analyze = 290, - And = 291, - Any = 292, - Array = 293, - As = 294, - Asc = 295, - Assertion = 296, - Assignment = 297, - Asymmetric = 298, - At = 299, - Attach = 300, - Attribute = 301, - Authorization = 302, - Backward = 303, - Before = 304, - BeginP = 305, - Between = 306, - Bigint = 307, - Binary = 308, - Bit = 309, - BooleanP = 310, - Both = 311, - By = 312, - Cache = 313, - Call = 314, - Called = 315, - Cascade = 316, - Cascaded = 317, - Case = 318, - Cast = 319, - CatalogP = 320, - Chain = 321, - CharP = 322, - Character = 323, - Characteristics = 324, - Check = 325, - Checkpoint = 326, - Class = 327, - Close = 328, - Cluster = 329, - Coalesce = 330, - Collate = 331, - Collation = 332, - Column = 333, - Columns = 334, - Comment = 335, - Comments = 336, - Commit = 337, - Committed = 338, - Concurrently = 339, - Configuration = 340, - Conflict = 341, - Connection = 342, - Constraint = 343, - Constraints = 344, - ContentP = 345, - ContinueP = 346, - ConversionP = 347, - Copy = 348, - Cost = 349, - Create = 350, - Cross = 351, - Csv = 352, - Cube = 353, - CurrentP = 354, - CurrentCatalog = 355, - CurrentDate = 356, - CurrentRole = 357, - CurrentSchema = 358, - CurrentTime = 359, - CurrentTimestamp = 360, - CurrentUser = 361, - Cursor = 362, - Cycle = 363, - DataP = 364, - Database = 365, - DayP = 366, - Deallocate = 367, - Dec = 368, - DecimalP = 369, - Declare = 370, - Default = 371, - Defaults = 372, - Deferrable = 373, - Deferred = 374, - Definer = 375, - DeleteP = 376, - Delimiter = 377, - Delimiters = 378, - Depends = 379, - Desc = 380, - Detach = 381, - Dictionary = 382, - DisableP = 383, - Discard = 384, - Distinct = 385, - Do = 386, - DocumentP = 387, - DomainP = 388, - DoubleP = 389, - Drop = 390, - Each = 391, - Else = 392, - EnableP = 393, - Encoding = 394, - Encrypted = 395, - EndP = 396, - EnumP = 397, - Escape = 398, - Event = 399, - Except = 400, - Exclude = 401, - Excluding = 402, - Exclusive = 403, - Execute = 404, - Exists = 405, - Explain = 406, - Expression = 407, - Extension = 408, - External = 409, - Extract = 410, - FalseP = 411, - Family = 412, - Fetch = 413, - Filter = 414, - FirstP = 415, - FloatP = 416, - Following = 417, - For = 418, - Force = 419, - Foreign = 420, - Forward = 421, - Freeze = 422, - From = 423, - Full = 424, - Function = 425, - Functions = 426, - Generated = 427, - Global = 428, - Grant = 429, - Granted = 430, - Greatest = 431, - GroupP = 432, - Grouping = 433, - Groups = 434, - Handler = 435, - Having = 436, - HeaderP = 437, - Hold = 438, - HourP = 439, - IdentityP = 440, - IfP = 441, - Ilike = 442, - Immediate = 443, - Immutable = 444, - ImplicitP = 445, - ImportP = 446, - InP = 447, - Include = 448, - Including = 449, - Increment = 450, - Index = 451, - Indexes = 452, - Inherit = 453, - Inherits = 454, - Initially = 455, - InlineP = 456, - InnerP = 457, - Inout = 458, - InputP = 459, - Insensitive = 460, - Insert = 461, - Instead = 462, - IntP = 463, - Integer = 464, - Intersect = 465, - Interval = 466, - Into = 467, - Invoker = 468, - Is = 469, - Isnull = 470, - Isolation = 471, - Join = 472, - Key = 473, - Label = 474, - Language = 475, - LargeP = 476, - LastP = 477, - LateralP = 478, - Leading = 479, - Leakproof = 480, - Least = 481, - Left = 482, - Level = 483, - Like = 484, - Limit = 485, - Listen = 486, - Load = 487, - Local = 488, - Localtime = 489, - Localtimestamp = 490, - Location = 491, - LockP = 492, - Locked = 493, - Logged = 494, - Mapping = 495, - Match = 496, - Materialized = 497, - Maxvalue = 498, - Method = 499, - MinuteP = 500, - Minvalue = 501, - Mode = 502, - MonthP = 503, - Move = 504, - NameP = 505, - Names = 506, - National = 507, - Natural = 508, - Nchar = 509, - New = 510, - Next = 511, - Nfc = 512, - Nfd = 513, - Nfkc = 514, - Nfkd = 515, - No = 516, - None = 517, - Normalize = 518, - Normalized = 519, - Not = 520, - Nothing = 521, - Notify = 522, - Notnull = 523, - Nowait = 524, - NullP = 525, - Nullif = 526, - NullsP = 527, - Numeric = 528, - ObjectP = 529, - Of = 530, - Off = 531, - Offset = 532, - Oids = 533, - Old = 534, - On = 535, - Only = 536, - Operator = 537, - Option = 538, - Options = 539, - Or = 540, - Order = 541, - Ordinality = 542, - Others = 543, - OutP = 544, - OuterP = 545, - Over = 546, - Overlaps = 547, - Overlay = 548, - Overriding = 549, - Owned = 550, - Owner = 551, - Parallel = 552, - Parser = 553, - Partial = 554, - Partition = 555, - Passing = 556, - Password = 557, - Placing = 558, - Plans = 559, - Policy = 560, - Position = 561, - Preceding = 562, - Precision = 563, - Preserve = 564, - Prepare = 565, - Prepared = 566, - Primary = 567, - Prior = 568, - Privileges = 569, - Procedural = 570, - Procedure = 571, - Procedures = 572, - Program = 573, - Publication = 574, - Quote = 575, - Range = 576, - Read = 577, - Real = 578, - Reassign = 579, - Recheck = 580, - Recursive = 581, - Ref = 582, - References = 583, - Referencing = 584, - Refresh = 585, - Reindex = 586, - RelativeP = 587, - Release = 588, - Rename = 589, - Repeatable = 590, - Replace = 591, - Replica = 592, - Reset = 593, - Restart = 594, - Restrict = 595, - Returning = 596, - Returns = 597, - Revoke = 598, - Right = 599, - Role = 600, - Rollback = 601, - Rollup = 602, - Routine = 603, - Routines = 604, - Row = 605, - Rows = 606, - Rule = 607, - Savepoint = 608, - Schema = 609, - Schemas = 610, - Scroll = 611, - Search = 612, - SecondP = 613, - Security = 614, - Select = 615, - Sequence = 616, - Sequences = 617, - Serializable = 618, - Server = 619, - Session = 620, - SessionUser = 621, - Set = 622, - Sets = 623, - Setof = 624, - Share = 625, - Show = 626, - Similar = 627, - Simple = 628, - Skip = 629, - Smallint = 630, - Snapshot = 631, - Some = 632, - SqlP = 633, - Stable = 634, - StandaloneP = 635, - Start = 636, - Statement = 637, - Statistics = 638, - Stdin = 639, - Stdout = 640, - Storage = 641, - Stored = 642, - StrictP = 643, - StripP = 644, - Subscription = 645, - Substring = 646, - Support = 647, - Symmetric = 648, - Sysid = 649, - SystemP = 650, - Table = 651, - Tables = 652, - Tablesample = 653, - Tablespace = 654, - Temp = 655, - Template = 656, - Temporary = 657, - TextP = 658, - Then = 659, - Ties = 660, - Time = 661, - Timestamp = 662, - To = 663, - Trailing = 664, - Transaction = 665, - Transform = 666, - Treat = 667, - Trigger = 668, - Trim = 669, - TrueP = 670, - Truncate = 671, - Trusted = 672, - TypeP = 673, - TypesP = 674, - Uescape = 675, - Unbounded = 676, - Uncommitted = 677, - Unencrypted = 678, - Union = 679, - Unique = 680, - Unknown = 681, - Unlisten = 682, - Unlogged = 683, - Until = 684, - Update = 685, - User = 686, - Using = 687, - Vacuum = 688, - Valid = 689, - Validate = 690, - Validator = 691, - ValueP = 692, - Values = 693, - Varchar = 694, - Variadic = 695, - Varying = 696, - Verbose = 697, - VersionP = 698, - View = 699, - Views = 700, - Volatile = 701, - When = 702, - Where = 703, - WhitespaceP = 704, - Window = 705, - With = 706, - Within = 707, - Without = 708, - Work = 709, - Wrapper = 710, - Write = 711, - XmlP = 712, - Xmlattributes = 713, - Xmlconcat = 714, - Xmlelement = 715, - Xmlexists = 716, - Xmlforest = 717, - Xmlnamespaces = 718, - Xmlparse = 719, - Xmlpi = 720, - Xmlroot = 721, - Xmlserialize = 722, - Xmltable = 723, - YearP = 724, - YesP = 725, - Zone = 726, - NotLa = 727, - NullsLa = 728, - WithLa = 729, - Postfixop = 730, - Uminus = 731, -} diff --git a/tests/target/configs/doc_comment_code_block_width/100.rs b/tests/target/configs/doc_comment_code_block_width/100.rs new file mode 100644 index 0000000000000..c010a28aab615 --- /dev/null +++ b/tests/target/configs/doc_comment_code_block_width/100.rs @@ -0,0 +1,16 @@ +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 100 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes(v: &[u8]) -> Result { +/// Self::from_bytes_manual_slice(v, 0, v.len()) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes(v: &[u8]) -> Result { + Self::from_bytes_manual_slice(v, 0, v.len()) + } +} diff --git a/tests/target/configs/doc_comment_code_block_width/100_greater_max_width.rs b/tests/target/configs/doc_comment_code_block_width/100_greater_max_width.rs new file mode 100644 index 0000000000000..6bcb99b915ff9 --- /dev/null +++ b/tests/target/configs/doc_comment_code_block_width/100_greater_max_width.rs @@ -0,0 +1,29 @@ +// rustfmt-max_width: 50 +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 100 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes( +/// v: &[u8], +/// ) -> Result { +/// Self::from_bytes_manual_slice( +/// v, +/// 0, +/// v.len(), +/// ) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes( + v: &[u8], + ) -> Result { + Self::from_bytes_manual_slice( + v, + 0, + v.len(), + ) + } +} diff --git a/tests/target/configs/doc_comment_code_block_width/50.rs b/tests/target/configs/doc_comment_code_block_width/50.rs new file mode 100644 index 0000000000000..e8ab6f28bdc5a --- /dev/null +++ b/tests/target/configs/doc_comment_code_block_width/50.rs @@ -0,0 +1,22 @@ +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 50 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes( +/// v: &[u8], +/// ) -> Result { +/// Self::from_bytes_manual_slice( +/// v, +/// 0, +/// v.len(), +/// ) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes(v: &[u8]) -> Result { + Self::from_bytes_manual_slice(v, 0, v.len()) + } +} diff --git a/tests/target/imports_raw_identifiers/version_One.rs b/tests/target/imports_raw_identifiers/version_One.rs new file mode 100644 index 0000000000000..bc4b5b135696a --- /dev/null +++ b/tests/target/imports_raw_identifiers/version_One.rs @@ -0,0 +1,5 @@ +// rustfmt-version:One + +use websocket::client::ClientBuilder; +use websocket::r#async::futures::Stream; +use websocket::result::WebSocketError; diff --git a/tests/target/imports_raw_identifiers/version_Two.rs b/tests/target/imports_raw_identifiers/version_Two.rs new file mode 100644 index 0000000000000..22bfe93122f95 --- /dev/null +++ b/tests/target/imports_raw_identifiers/version_Two.rs @@ -0,0 +1,5 @@ +// rustfmt-version:Two + +use websocket::r#async::futures::Stream; +use websocket::client::ClientBuilder; +use websocket::result::WebSocketError; diff --git a/tests/target/issue_5399.rs b/tests/target/issue_5399.rs new file mode 100644 index 0000000000000..17364c38919a2 --- /dev/null +++ b/tests/target/issue_5399.rs @@ -0,0 +1,48 @@ +// rustfmt-max_width: 140 + +impl NotificationRepository { + fn set_status_changed( + &self, + repo_tx_conn: &RepoTxConn, + rid: &RoutableId, + changed_at: NaiveDateTime, + ) -> NukeResult> { + repo_tx_conn.run(move |conn| { + let res = diesel::update(client_notification::table) + .filter( + client_notification::routable_id.eq(DieselRoutableId(rid.clone())).and( + client_notification::changed_at + .lt(changed_at) + .or(client_notification::changed_at.is_null()), + ), + ) + .set(client_notification::changed_at.eq(changed_at)) + .returning(( + client_notification::id, + client_notification::changed_at, + client_notification::polled_at, + client_notification::notified_at, + )) + .get_result::<(Uuid, Option, Option, Option)>(conn) + .optional()?; + + match res { + Some(row) => { + let client_id = client_contract::table + .inner_join(client_notification::table) + .filter(client_notification::id.eq(row.0)) + .select(client_contract::client_id) + .get_result::(conn)?; + + Ok(Some(NotificationStatus { + client_id: client_id.into(), + changed_at: row.1, + polled_at: row.2, + notified_at: row.3, + })) + } + None => Ok(None), + } + }) + } +} diff --git a/tests/target/performance/issue-4476.rs b/tests/target/performance/issue-4476.rs deleted file mode 100644 index 30567f2644b74..0000000000000 --- a/tests/target/performance/issue-4476.rs +++ /dev/null @@ -1,705 +0,0 @@ -use super::SemverParser; - -#[allow(dead_code, non_camel_case_types)] -#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub enum Rule { - EOI, - range_set, - logical_or, - range, - empty, - hyphen, - simple, - primitive, - primitive_op, - partial, - xr, - xr_op, - nr, - tilde, - caret, - qualifier, - parts, - part, - space, -} -#[allow(clippy::all)] -impl ::pest::Parser for SemverParser { - fn parse<'i>( - rule: Rule, - input: &'i str, - ) -> ::std::result::Result<::pest::iterators::Pairs<'i, Rule>, ::pest::error::Error> { - mod rules { - pub mod hidden { - use super::super::Rule; - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn skip( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - Ok(state) - } - } - pub mod visible { - use super::super::Rule; - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn range_set( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::range_set, |state| { - state.sequence(|state| { - self::SOI(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::range(state)) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - self::logical_or(state) - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| self::range(state)) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then( - |state| { - state.sequence(|state| { - self::logical_or(state) - .and_then(|state| { - super::hidden::skip( - state, - ) - }) - .and_then(|state| { - self::range(state) - }) - }) - }, - ) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::EOI(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn logical_or( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::logical_or, |state| { - state.sequence(|state| { - state - .sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| state.match_string("||")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn range( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::range, |state| { - self::hyphen(state) - .or_else(|state| { - state.sequence(|state| { - self::simple(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - state - .optional(|state| { - state.match_string(",") - }) - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| { - self::simple(state) - }) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| { - state.sequence( - |state| { - state - .optional(|state| state.match_string(",")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::simple(state)) - }, - ) - }) - }) - }) - }) - }) - }) - }) - }) - }) - .or_else(|state| self::empty(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn empty( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::empty, |state| state.match_string("")) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn hyphen( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::hyphen, |state| { - state.sequence(|state| { - self::partial(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| { - self::space(state) - }) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| state.match_string("-")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| { - self::space(state) - }) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn simple( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::simple, |state| { - self::primitive(state) - .or_else(|state| self::partial(state)) - .or_else(|state| self::tilde(state)) - .or_else(|state| self::caret(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn primitive( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::primitive, |state| { - state.sequence(|state| { - self::primitive_op(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn primitive_op( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::primitive_op, |state| { - state - .match_string("<=") - .or_else(|state| state.match_string(">=")) - .or_else(|state| state.match_string(">")) - .or_else(|state| state.match_string("<")) - .or_else(|state| state.match_string("=")) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn partial( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::partial, |state| { - state.sequence(|state| { - self::xr(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.optional(|state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::xr(state)) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.optional(|state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| self::xr(state)) - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| { - state.optional(|state| { - self::qualifier(state) - }) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn xr( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::xr, |state| { - self::xr_op(state).or_else(|state| self::nr(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn xr_op( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::xr_op, |state| { - state - .match_string("x") - .or_else(|state| state.match_string("X")) - .or_else(|state| state.match_string("*")) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn nr( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::nr, |state| { - state.match_string("0").or_else(|state| { - state.sequence(|state| { - state - .match_range('1'..'9') - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state.match_range('0'..'9').and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then( - |state| state.match_range('0'..'9'), - ) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn tilde( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::tilde, |state| { - state.sequence(|state| { - state - .match_string("~>") - .or_else(|state| state.match_string("~")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn caret( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::caret, |state| { - state.sequence(|state| { - state - .match_string("^") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn qualifier( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::qualifier, |state| { - state.sequence(|state| { - state - .match_string("-") - .or_else(|state| state.match_string("+")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::parts(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn parts( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::parts, |state| { - state.sequence(|state| { - self::part(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - state - .match_string(".") - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| self::part(state)) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then( - |state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| { - super::hidden::skip( - state, - ) - }) - .and_then(|state| { - self::part(state) - }) - }) - }, - ) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn part( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::part, |state| { - self::nr(state).or_else(|state| { - state.sequence(|state| { - state - .match_string("-") - .or_else(|state| state.match_range('0'..'9')) - .or_else(|state| state.match_range('A'..'Z')) - .or_else(|state| state.match_range('a'..'z')) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .match_string("-") - .or_else(|state| state.match_range('0'..'9')) - .or_else(|state| state.match_range('A'..'Z')) - .or_else(|state| state.match_range('a'..'z')) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then( - |state| { - state - .match_string("-") - .or_else(|state| { - state.match_range( - '0'..'9', - ) - }) - .or_else(|state| { - state.match_range( - 'A'..'Z', - ) - }) - .or_else(|state| { - state.match_range( - 'a'..'z', - ) - }) - }, - ) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn space( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state - .match_string(" ") - .or_else(|state| state.match_string("\t")) - } - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn EOI( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::EOI, |state| state.end_of_input()) - } - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn SOI( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.start_of_input() - } - } - pub use self::visible::*; - } - ::pest::state(input, |state| match rule { - Rule::range_set => rules::range_set(state), - Rule::logical_or => rules::logical_or(state), - Rule::range => rules::range(state), - Rule::empty => rules::empty(state), - Rule::hyphen => rules::hyphen(state), - Rule::simple => rules::simple(state), - Rule::primitive => rules::primitive(state), - Rule::primitive_op => rules::primitive_op(state), - Rule::partial => rules::partial(state), - Rule::xr => rules::xr(state), - Rule::xr_op => rules::xr_op(state), - Rule::nr => rules::nr(state), - Rule::tilde => rules::tilde(state), - Rule::caret => rules::caret(state), - Rule::qualifier => rules::qualifier(state), - Rule::parts => rules::parts(state), - Rule::part => rules::part(state), - Rule::space => rules::space(state), - Rule::EOI => rules::EOI(state), - }) - } -} diff --git a/tests/target/performance/issue-4867.rs b/tests/target/performance/issue-4867.rs deleted file mode 100644 index 336dae1b64ab8..0000000000000 --- a/tests/target/performance/issue-4867.rs +++ /dev/null @@ -1,13 +0,0 @@ -mod modA { - mod modB { - mod modC { - mod modD { - mod modE { - fn func() { - state . rule (Rule :: myrule , | state | { state . sequence (| state | { state . sequence (| state | { state . match_string ("abc") . and_then (| state | { super :: hidden :: skip (state) }) . and_then (| state | { state . match_string ("def") }) }) . and_then (| state | { super :: hidden :: skip (state) }) . and_then (| state | { state . sequence (| state | { state . optional (| state | { state . sequence (| state | { state . match_string ("abc") . and_then (| state | { super :: hidden :: skip (state) }) . and_then (| state | { state . match_string ("def") }) }) . and_then (| state | { state . repeat (| state | { state . sequence (| state | { super :: hidden :: skip (state) . and_then (| state | { state . sequence (| state | { state . match_string ("abc") . and_then (| state | { super :: hidden :: skip (state) }) . and_then (| state | { state . match_string ("def") }) }) }) }) }) }) }) }) }) }) }); - } - } - } - } - } -} diff --git a/tests/target/performance/issue-5128.rs b/tests/target/performance/issue-5128.rs deleted file mode 100644 index ba9ebfc6243f2..0000000000000 --- a/tests/target/performance/issue-5128.rs +++ /dev/null @@ -1,4898 +0,0 @@ -fn takes_a_long_time_to_rustfmt() { - let inner_cte = vec![Node { - node: Some(node::Node::CommonTableExpr(Box::new(CommonTableExpr { - ctename: String::from("ranked_by_age_within_key"), - aliascolnames: vec![], - ctematerialized: CteMaterialize::Default as i32, - ctequery: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - target_list: vec![ - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from(""), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::AStar(AStar {})), - }], - location: 80, - })), - })), - location: 80, - }))), - }, - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("rank_in_key"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::FuncCall(Box::new(FuncCall { - funcname: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("row_number"), - })), - }], - args: vec![], - agg_order: vec![], - agg_filter: None, - agg_within_group: false, - agg_star: false, - agg_distinct: false, - func_variadic: false, - over: Some(Box::new(WindowDef { - name: String::from(""), - refname: String::from(""), - partition_clause: vec![Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("synthetic_key"), - })), - }], - location: 123, - })), - }], - order_clause: vec![Node { - node: Some(node::Node::SortBy(Box::new(SortBy { - node: Some(Box::new(Node { - node: Some(node::Node::ColumnRef( - ColumnRef { - fields: vec![Node { - node: Some(node::Node::String( - String2 { - str: String::from( - "logical_timestamp", - ), - }, - )), - }], - location: 156, - }, - )), - })), - sortby_dir: SortByDir::SortbyDesc as i32, - sortby_nulls: SortByNulls::SortbyNullsDefault - as i32, - use_op: vec![], - location: -1, - }))), - }], - frame_options: 1058, - start_offset: None, - end_offset: None, - location: 109, - })), - location: 91, - }))), - })), - location: 91, - }))), - }, - ], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), - schemaname: String::from("_supertables"), - relname: String::from("9999-9999-9999"), - inh: true, - relpersistence: String::from("p"), - alias: None, - location: 206, - })), - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("<="), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("logical_timestamp"), - })), - }], - location: 250, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer(Integer { ival: 9000 })), - })), - location: 271, - }))), - })), - location: 268, - }))), - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: None, - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None, - }))), - })), - location: 29, - cterecursive: false, - cterefcount: 0, - ctecolnames: vec![], - ctecoltypes: vec![], - ctecoltypmods: vec![], - ctecolcollations: vec![], - }))), - }]; - let outer_cte = vec![Node { - node: Some(node::Node::CommonTableExpr(Box::new(CommonTableExpr { - ctename: String::from("table_name"), - aliascolnames: vec![], - ctematerialized: CteMaterialize::Default as i32, - ctequery: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - target_list: vec![ - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("column1"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("c1"), - })), - }], - location: 301, - })), - })), - location: 301, - }))), - }, - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("column2"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("c2"), - })), - }], - location: 324, - })), - })), - location: 324, - }))), - }, - ], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), - schemaname: String::from(""), - relname: String::from("ranked_by_age_within_key"), - inh: true, - relpersistence: String::from("p"), - alias: None, - location: 347, - })), - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::BoolExpr(Box::new(BoolExpr { - xpr: None, - boolop: BoolExprType::AndExpr as i32, - args: vec![ - Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("="), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("rank_in_key"), - })), - }], - location: 382, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer(Integer { - ival: 1, - })), - })), - location: 396, - }))), - })), - location: 394, - }))), - }, - Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("="), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("is_deleted"), - })), - }], - location: 402, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::TypeCast(Box::new(TypeCast { - arg: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new( - AConst { - val: Some(Box::new(Node { - node: Some(node::Node::String( - String2 { - str: String::from("f"), - }, - )), - })), - location: 415, - }, - ))), - })), - type_name: Some(TypeName { - names: vec![ - Node { - node: Some(node::Node::String( - String2 { - str: String::from("pg_catalog"), - }, - )), - }, - Node { - node: Some(node::Node::String( - String2 { - str: String::from("bool"), - }, - )), - }, - ], - type_oid: 0, - setof: false, - pct_type: false, - typmods: vec![], - typemod: -1, - array_bounds: vec![], - location: -1, - }), - location: -1, - }))), - })), - location: 413, - }))), - }, - ], - location: 398, - }))), - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: Some(WithClause { - ctes: inner_cte, - recursive: false, - location: 24, - }), - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None, - }))), - })), - location: 5, - cterecursive: false, - cterefcount: 0, - ctecolnames: vec![], - ctecoltypes: vec![], - ctecoltypmods: vec![], - ctecolcollations: vec![], - }))), - }]; - let expected_result = ParseResult { - version: 130003, - stmts: vec![RawStmt { - stmt: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - - target_list: vec![Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from(""), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("column1"), - })), - }], - location: 430, - })), - })), - location: 430, - }))), - }], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), - schemaname: String::from(""), - relname: String::from("table_name"), - inh: true, - relpersistence: String::from("p"), - alias: None, - location: 443, - })), - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from(">"), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("column2"), - })), - }], - location: 460, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer(Integer { ival: 9000 })), - })), - location: 470, - }))), - })), - location: 468, - }))), - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: Some(WithClause { - ctes: outer_cte, - recursive: false, - location: 0, - }), - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None, - }))), - })), - stmt_location: 0, - stmt_len: 0, - }], - }; -} -#[derive(Clone, PartialEq)] -pub struct ParseResult { - pub version: i32, - - pub stmts: Vec, -} -#[derive(Clone, PartialEq)] -pub struct ScanResult { - pub version: i32, - - pub tokens: Vec, -} -#[derive(Clone, PartialEq)] -pub struct Node { - pub node: ::core::option::Option, -} -/// Nested message and enum types in `Node`. -pub mod node { - #[derive(Clone, PartialEq)] - pub enum Node { - Alias(super::Alias), - - RangeVar(super::RangeVar), - - TableFunc(Box), - - Expr(super::Expr), - - Var(Box), - - Param(Box), - - Aggref(Box), - - GroupingFunc(Box), - - WindowFunc(Box), - - SubscriptingRef(Box), - - FuncExpr(Box), - - NamedArgExpr(Box), - - OpExpr(Box), - - DistinctExpr(Box), - - NullIfExpr(Box), - - ScalarArrayOpExpr(Box), - - BoolExpr(Box), - - SubLink(Box), - - SubPlan(Box), - - AlternativeSubPlan(Box), - - FieldSelect(Box), - - FieldStore(Box), - - RelabelType(Box), - - CoerceViaIo(Box), - - ArrayCoerceExpr(Box), - - ConvertRowtypeExpr(Box), - - CollateExpr(Box), - - CaseExpr(Box), - - CaseWhen(Box), - - CaseTestExpr(Box), - - ArrayExpr(Box), - - RowExpr(Box), - - RowCompareExpr(Box), - - CoalesceExpr(Box), - - MinMaxExpr(Box), - - SqlvalueFunction(Box), - - XmlExpr(Box), - - NullTest(Box), - - BooleanTest(Box), - - CoerceToDomain(Box), - - CoerceToDomainValue(Box), - - SetToDefault(Box), - - CurrentOfExpr(Box), - - NextValueExpr(Box), - - InferenceElem(Box), - - TargetEntry(Box), - - RangeTblRef(super::RangeTblRef), - - JoinExpr(Box), - - FromExpr(Box), - - OnConflictExpr(Box), - - IntoClause(Box), - - RawStmt(Box), - - Query(Box), - - InsertStmt(Box), - - DeleteStmt(Box), - - UpdateStmt(Box), - - SelectStmt(Box), - - AlterTableStmt(super::AlterTableStmt), - - AlterTableCmd(Box), - - AlterDomainStmt(Box), - - SetOperationStmt(Box), - - GrantStmt(super::GrantStmt), - - GrantRoleStmt(super::GrantRoleStmt), - - AlterDefaultPrivilegesStmt(super::AlterDefaultPrivilegesStmt), - - ClosePortalStmt(super::ClosePortalStmt), - - ClusterStmt(super::ClusterStmt), - - CopyStmt(Box), - - CreateStmt(super::CreateStmt), - - DefineStmt(super::DefineStmt), - - DropStmt(super::DropStmt), - - TruncateStmt(super::TruncateStmt), - - CommentStmt(Box), - - FetchStmt(super::FetchStmt), - - IndexStmt(Box), - - CreateFunctionStmt(super::CreateFunctionStmt), - - AlterFunctionStmt(super::AlterFunctionStmt), - - DoStmt(super::DoStmt), - - RenameStmt(Box), - - RuleStmt(Box), - - NotifyStmt(super::NotifyStmt), - - ListenStmt(super::ListenStmt), - - UnlistenStmt(super::UnlistenStmt), - - TransactionStmt(super::TransactionStmt), - - ViewStmt(Box), - - LoadStmt(super::LoadStmt), - - CreateDomainStmt(Box), - - CreatedbStmt(super::CreatedbStmt), - - DropdbStmt(super::DropdbStmt), - - VacuumStmt(super::VacuumStmt), - - ExplainStmt(Box), - - CreateTableAsStmt(Box), - - CreateSeqStmt(super::CreateSeqStmt), - - AlterSeqStmt(super::AlterSeqStmt), - - VariableSetStmt(super::VariableSetStmt), - - VariableShowStmt(super::VariableShowStmt), - - DiscardStmt(super::DiscardStmt), - - CreateTrigStmt(Box), - - CreatePlangStmt(super::CreatePLangStmt), - - CreateRoleStmt(super::CreateRoleStmt), - - AlterRoleStmt(super::AlterRoleStmt), - - DropRoleStmt(super::DropRoleStmt), - - LockStmt(super::LockStmt), - - ConstraintsSetStmt(super::ConstraintsSetStmt), - - ReindexStmt(super::ReindexStmt), - - CheckPointStmt(super::CheckPointStmt), - - CreateSchemaStmt(super::CreateSchemaStmt), - - AlterDatabaseStmt(super::AlterDatabaseStmt), - - AlterDatabaseSetStmt(super::AlterDatabaseSetStmt), - - AlterRoleSetStmt(super::AlterRoleSetStmt), - - CreateConversionStmt(super::CreateConversionStmt), - - CreateCastStmt(super::CreateCastStmt), - - CreateOpClassStmt(super::CreateOpClassStmt), - - CreateOpFamilyStmt(super::CreateOpFamilyStmt), - - AlterOpFamilyStmt(super::AlterOpFamilyStmt), - - PrepareStmt(Box), - - ExecuteStmt(super::ExecuteStmt), - - DeallocateStmt(super::DeallocateStmt), - - DeclareCursorStmt(Box), - - CreateTableSpaceStmt(super::CreateTableSpaceStmt), - - DropTableSpaceStmt(super::DropTableSpaceStmt), - - AlterObjectDependsStmt(Box), - - AlterObjectSchemaStmt(Box), - - AlterOwnerStmt(Box), - - AlterOperatorStmt(super::AlterOperatorStmt), - - AlterTypeStmt(super::AlterTypeStmt), - - DropOwnedStmt(super::DropOwnedStmt), - - ReassignOwnedStmt(super::ReassignOwnedStmt), - - CompositeTypeStmt(super::CompositeTypeStmt), - - CreateEnumStmt(super::CreateEnumStmt), - - CreateRangeStmt(super::CreateRangeStmt), - - AlterEnumStmt(super::AlterEnumStmt), - - AlterTsdictionaryStmt(super::AlterTsDictionaryStmt), - - AlterTsconfigurationStmt(super::AlterTsConfigurationStmt), - - CreateFdwStmt(super::CreateFdwStmt), - - AlterFdwStmt(super::AlterFdwStmt), - - CreateForeignServerStmt(super::CreateForeignServerStmt), - - AlterForeignServerStmt(super::AlterForeignServerStmt), - - CreateUserMappingStmt(super::CreateUserMappingStmt), - - AlterUserMappingStmt(super::AlterUserMappingStmt), - - DropUserMappingStmt(super::DropUserMappingStmt), - - AlterTableSpaceOptionsStmt(super::AlterTableSpaceOptionsStmt), - - AlterTableMoveAllStmt(super::AlterTableMoveAllStmt), - - SecLabelStmt(Box), - - CreateForeignTableStmt(super::CreateForeignTableStmt), - - ImportForeignSchemaStmt(super::ImportForeignSchemaStmt), - - CreateExtensionStmt(super::CreateExtensionStmt), - - AlterExtensionStmt(super::AlterExtensionStmt), - - AlterExtensionContentsStmt(Box), - - CreateEventTrigStmt(super::CreateEventTrigStmt), - - AlterEventTrigStmt(super::AlterEventTrigStmt), - - RefreshMatViewStmt(super::RefreshMatViewStmt), - - ReplicaIdentityStmt(super::ReplicaIdentityStmt), - - AlterSystemStmt(super::AlterSystemStmt), - - CreatePolicyStmt(Box), - - AlterPolicyStmt(Box), - - CreateTransformStmt(super::CreateTransformStmt), - - CreateAmStmt(super::CreateAmStmt), - - CreatePublicationStmt(super::CreatePublicationStmt), - - AlterPublicationStmt(super::AlterPublicationStmt), - - CreateSubscriptionStmt(super::CreateSubscriptionStmt), - - AlterSubscriptionStmt(super::AlterSubscriptionStmt), - - DropSubscriptionStmt(super::DropSubscriptionStmt), - - CreateStatsStmt(super::CreateStatsStmt), - - AlterCollationStmt(super::AlterCollationStmt), - - CallStmt(Box), - - AlterStatsStmt(super::AlterStatsStmt), - - AExpr(Box), - - ColumnRef(super::ColumnRef), - - ParamRef(super::ParamRef), - - AConst(Box), - - FuncCall(Box), - - AStar(super::AStar), - - AIndices(Box), - - AIndirection(Box), - - AArrayExpr(super::AArrayExpr), - - ResTarget(Box), - - MultiAssignRef(Box), - - TypeCast(Box), - - CollateClause(Box), - - SortBy(Box), - - WindowDef(Box), - - RangeSubselect(Box), - - RangeFunction(super::RangeFunction), - - RangeTableSample(Box), - - RangeTableFunc(Box), - - RangeTableFuncCol(Box), - - TypeName(super::TypeName), - - ColumnDef(Box), - - IndexElem(Box), - - Constraint(Box), - - DefElem(Box), - - RangeTblEntry(Box), - - RangeTblFunction(Box), - - TableSampleClause(Box), - - WithCheckOption(Box), - - SortGroupClause(super::SortGroupClause), - - GroupingSet(super::GroupingSet), - - WindowClause(Box), - - ObjectWithArgs(super::ObjectWithArgs), - - AccessPriv(super::AccessPriv), - - CreateOpClassItem(super::CreateOpClassItem), - - TableLikeClause(super::TableLikeClause), - - FunctionParameter(Box), - - LockingClause(super::LockingClause), - - RowMarkClause(super::RowMarkClause), - - XmlSerialize(Box), - - WithClause(super::WithClause), - - InferClause(Box), - - OnConflictClause(Box), - - CommonTableExpr(Box), - - RoleSpec(super::RoleSpec), - - TriggerTransition(super::TriggerTransition), - - PartitionElem(Box), - - PartitionSpec(super::PartitionSpec), - - PartitionBoundSpec(super::PartitionBoundSpec), - - PartitionRangeDatum(Box), - - PartitionCmd(super::PartitionCmd), - - VacuumRelation(super::VacuumRelation), - - InlineCodeBlock(super::InlineCodeBlock), - - CallContext(super::CallContext), - - Integer(super::Integer), - - Float(super::Float), - - String(super::String2), - - BitString(super::BitString), - - Null(super::Null), - - List(super::List), - - IntList(super::IntList), - - OidList(super::OidList), - } -} -#[derive(Clone, PartialEq)] -pub struct Integer { - /// machine integer - pub ival: i32, -} -#[derive(Clone, PartialEq)] -pub struct Float { - /// string - pub str: String, -} -#[derive(Clone, PartialEq)] -pub struct String2 { - /// string - pub str: String, -} -#[derive(Clone, PartialEq)] -pub struct BitString { - /// string - pub str: String, -} -/// intentionally empty -#[derive(Clone, PartialEq)] -pub struct Null {} -#[derive(Clone, PartialEq)] -pub struct List { - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct OidList { - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct IntList { - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct Alias { - pub aliasname: String, - - pub colnames: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeVar { - pub catalogname: String, - - pub schemaname: String, - - pub relname: String, - - pub inh: bool, - - pub relpersistence: String, - - pub alias: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TableFunc { - pub ns_uris: Vec, - - pub ns_names: Vec, - - pub docexpr: ::core::option::Option>, - - pub rowexpr: ::core::option::Option>, - - pub colnames: Vec, - - pub coltypes: Vec, - - pub coltypmods: Vec, - - pub colcollations: Vec, - - pub colexprs: Vec, - - pub coldefexprs: Vec, - - pub notnulls: Vec, - - pub ordinalitycol: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Expr {} -#[derive(Clone, PartialEq)] -pub struct Var { - pub xpr: ::core::option::Option>, - - pub varno: u32, - - pub varattno: i32, - - pub vartype: u32, - - pub vartypmod: i32, - - pub varcollid: u32, - - pub varlevelsup: u32, - - pub varnosyn: u32, - - pub varattnosyn: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Param { - pub xpr: ::core::option::Option>, - - pub paramkind: i32, - - pub paramid: i32, - - pub paramtype: u32, - - pub paramtypmod: i32, - - pub paramcollid: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Aggref { - pub xpr: ::core::option::Option>, - - pub aggfnoid: u32, - - pub aggtype: u32, - - pub aggcollid: u32, - - pub inputcollid: u32, - - pub aggtranstype: u32, - - pub aggargtypes: Vec, - - pub aggdirectargs: Vec, - - pub args: Vec, - - pub aggorder: Vec, - - pub aggdistinct: Vec, - - pub aggfilter: ::core::option::Option>, - - pub aggstar: bool, - - pub aggvariadic: bool, - - pub aggkind: String, - - pub agglevelsup: u32, - - pub aggsplit: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct GroupingFunc { - pub xpr: ::core::option::Option>, - - pub args: Vec, - - pub refs: Vec, - - pub cols: Vec, - - pub agglevelsup: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowFunc { - pub xpr: ::core::option::Option>, - - pub winfnoid: u32, - - pub wintype: u32, - - pub wincollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub aggfilter: ::core::option::Option>, - - pub winref: u32, - - pub winstar: bool, - - pub winagg: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubscriptingRef { - pub xpr: ::core::option::Option>, - - pub refcontainertype: u32, - - pub refelemtype: u32, - - pub reftypmod: i32, - - pub refcollid: u32, - - pub refupperindexpr: Vec, - - pub reflowerindexpr: Vec, - - pub refexpr: ::core::option::Option>, - - pub refassgnexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct FuncExpr { - pub xpr: ::core::option::Option>, - - pub funcid: u32, - - pub funcresulttype: u32, - - pub funcretset: bool, - - pub funcvariadic: bool, - - pub funcformat: i32, - - pub funccollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NamedArgExpr { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub name: String, - - pub argnumber: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct OpExpr { - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct DistinctExpr { - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NullIfExpr { - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ScalarArrayOpExpr { - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub use_or: bool, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct BoolExpr { - pub xpr: ::core::option::Option>, - - pub boolop: i32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubLink { - pub xpr: ::core::option::Option>, - - pub sub_link_type: i32, - - pub sub_link_id: i32, - - pub testexpr: ::core::option::Option>, - - pub oper_name: Vec, - - pub subselect: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubPlan { - pub xpr: ::core::option::Option>, - - pub sub_link_type: i32, - - pub testexpr: ::core::option::Option>, - - pub param_ids: Vec, - - pub plan_id: i32, - - pub plan_name: String, - - pub first_col_type: u32, - - pub first_col_typmod: i32, - - pub first_col_collation: u32, - - pub use_hash_table: bool, - - pub unknown_eq_false: bool, - - pub parallel_safe: bool, - - pub set_param: Vec, - - pub par_param: Vec, - - pub args: Vec, - - pub startup_cost: f64, - - pub per_call_cost: f64, -} -#[derive(Clone, PartialEq)] -pub struct AlternativeSubPlan { - pub xpr: ::core::option::Option>, - - pub subplans: Vec, -} -#[derive(Clone, PartialEq)] -pub struct FieldSelect { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub fieldnum: i32, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, -} -#[derive(Clone, PartialEq)] -pub struct FieldStore { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub newvals: Vec, - - pub fieldnums: Vec, - - pub resulttype: u32, -} -#[derive(Clone, PartialEq)] -pub struct RelabelType { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub relabelformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceViaIo { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resultcollid: u32, - - pub coerceformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ArrayCoerceExpr { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub elemexpr: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub coerceformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ConvertRowtypeExpr { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub convertformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CollateExpr { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub coll_oid: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseExpr { - pub xpr: ::core::option::Option>, - - pub casetype: u32, - - pub casecollid: u32, - - pub arg: ::core::option::Option>, - - pub args: Vec, - - pub defresult: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseWhen { - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub result: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseTestExpr { - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, -} -#[derive(Clone, PartialEq)] -pub struct ArrayExpr { - pub xpr: ::core::option::Option>, - - pub array_typeid: u32, - - pub array_collid: u32, - - pub element_typeid: u32, - - pub elements: Vec, - - pub multidims: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowExpr { - pub xpr: ::core::option::Option>, - - pub args: Vec, - - pub row_typeid: u32, - - pub row_format: i32, - - pub colnames: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowCompareExpr { - pub xpr: ::core::option::Option>, - - pub rctype: i32, - - pub opnos: Vec, - - pub opfamilies: Vec, - - pub inputcollids: Vec, - - pub largs: Vec, - - pub rargs: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CoalesceExpr { - pub xpr: ::core::option::Option>, - - pub coalescetype: u32, - - pub coalescecollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct MinMaxExpr { - pub xpr: ::core::option::Option>, - - pub minmaxtype: u32, - - pub minmaxcollid: u32, - - pub inputcollid: u32, - - pub op: i32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SqlValueFunction { - pub xpr: ::core::option::Option>, - - pub op: i32, - - pub r#type: u32, - - pub typmod: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct XmlExpr { - pub xpr: ::core::option::Option>, - - pub op: i32, - - pub name: String, - - pub named_args: Vec, - - pub arg_names: Vec, - - pub args: Vec, - - pub xmloption: i32, - - pub r#type: u32, - - pub typmod: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NullTest { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub nulltesttype: i32, - - pub argisrow: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct BooleanTest { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub booltesttype: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceToDomain { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub coercionformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceToDomainValue { - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SetToDefault { - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CurrentOfExpr { - pub xpr: ::core::option::Option>, - - pub cvarno: u32, - - pub cursor_name: String, - - pub cursor_param: i32, -} -#[derive(Clone, PartialEq)] -pub struct NextValueExpr { - pub xpr: ::core::option::Option>, - - pub seqid: u32, - - pub type_id: u32, -} -#[derive(Clone, PartialEq)] -pub struct InferenceElem { - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub infercollid: u32, - - pub inferopclass: u32, -} -#[derive(Clone, PartialEq)] -pub struct TargetEntry { - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub resno: i32, - - pub resname: String, - - pub ressortgroupref: u32, - - pub resorigtbl: u32, - - pub resorigcol: i32, - - pub resjunk: bool, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblRef { - pub rtindex: i32, -} -#[derive(Clone, PartialEq)] -pub struct JoinExpr { - pub jointype: i32, - - pub is_natural: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, - - pub using_clause: Vec, - - pub quals: ::core::option::Option>, - - pub alias: ::core::option::Option, - - pub rtindex: i32, -} -#[derive(Clone, PartialEq)] -pub struct FromExpr { - pub fromlist: Vec, - - pub quals: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct OnConflictExpr { - pub action: i32, - - pub arbiter_elems: Vec, - - pub arbiter_where: ::core::option::Option>, - - pub constraint: u32, - - pub on_conflict_set: Vec, - - pub on_conflict_where: ::core::option::Option>, - - pub excl_rel_index: i32, - - pub excl_rel_tlist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct IntoClause { - pub rel: ::core::option::Option, - - pub col_names: Vec, - - pub access_method: String, - - pub options: Vec, - - pub on_commit: i32, - - pub table_space_name: String, - - pub view_query: ::core::option::Option>, - - pub skip_data: bool, -} -#[derive(Clone, PartialEq)] -pub struct RawStmt { - pub stmt: ::core::option::Option>, - - pub stmt_location: i32, - - pub stmt_len: i32, -} -#[derive(Clone, PartialEq)] -pub struct Query { - pub command_type: i32, - - pub query_source: i32, - - pub can_set_tag: bool, - - pub utility_stmt: ::core::option::Option>, - - pub result_relation: i32, - - pub has_aggs: bool, - - pub has_window_funcs: bool, - - pub has_target_srfs: bool, - - pub has_sub_links: bool, - - pub has_distinct_on: bool, - - pub has_recursive: bool, - - pub has_modifying_cte: bool, - - pub has_for_update: bool, - - pub has_row_security: bool, - - pub cte_list: Vec, - - pub rtable: Vec, - - pub jointree: ::core::option::Option>, - - pub target_list: Vec, - - pub r#override: i32, - - pub on_conflict: ::core::option::Option>, - - pub returning_list: Vec, - - pub group_clause: Vec, - - pub grouping_sets: Vec, - - pub having_qual: ::core::option::Option>, - - pub window_clause: Vec, - - pub distinct_clause: Vec, - - pub sort_clause: Vec, - - pub limit_offset: ::core::option::Option>, - - pub limit_count: ::core::option::Option>, - - pub limit_option: i32, - - pub row_marks: Vec, - - pub set_operations: ::core::option::Option>, - - pub constraint_deps: Vec, - - pub with_check_options: Vec, - - pub stmt_location: i32, - - pub stmt_len: i32, -} -#[derive(Clone, PartialEq)] -pub struct InsertStmt { - pub relation: ::core::option::Option, - - pub cols: Vec, - - pub select_stmt: ::core::option::Option>, - - pub on_conflict_clause: ::core::option::Option>, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, - - pub r#override: i32, -} -#[derive(Clone, PartialEq)] -pub struct DeleteStmt { - pub relation: ::core::option::Option, - - pub using_clause: Vec, - - pub where_clause: ::core::option::Option>, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct UpdateStmt { - pub relation: ::core::option::Option, - - pub target_list: Vec, - - pub where_clause: ::core::option::Option>, - - pub from_clause: Vec, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct SelectStmt { - pub distinct_clause: Vec, - - pub into_clause: ::core::option::Option>, - - pub target_list: Vec, - - pub from_clause: Vec, - - pub where_clause: ::core::option::Option>, - - pub group_clause: Vec, - - pub having_clause: ::core::option::Option>, - - pub window_clause: Vec, - - pub values_lists: Vec, - - pub sort_clause: Vec, - - pub limit_offset: ::core::option::Option>, - - pub limit_count: ::core::option::Option>, - - pub limit_option: i32, - - pub locking_clause: Vec, - - pub with_clause: ::core::option::Option, - - pub op: i32, - - pub all: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableStmt { - pub relation: ::core::option::Option, - - pub cmds: Vec, - - pub relkind: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableCmd { - pub subtype: i32, - - pub name: String, - - pub num: i32, - - pub newowner: ::core::option::Option, - - pub def: ::core::option::Option>, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterDomainStmt { - pub subtype: String, - - pub type_name: Vec, - - pub name: String, - - pub def: ::core::option::Option>, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct SetOperationStmt { - pub op: i32, - - pub all: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, - - pub col_types: Vec, - - pub col_typmods: Vec, - - pub col_collations: Vec, - - pub group_clauses: Vec, -} -#[derive(Clone, PartialEq)] -pub struct GrantStmt { - pub is_grant: bool, - - pub targtype: i32, - - pub objtype: i32, - - pub objects: Vec, - - pub privileges: Vec, - - pub grantees: Vec, - - pub grant_option: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct GrantRoleStmt { - pub granted_roles: Vec, - - pub grantee_roles: Vec, - - pub is_grant: bool, - - pub admin_opt: bool, - - pub grantor: ::core::option::Option, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct AlterDefaultPrivilegesStmt { - pub options: Vec, - - pub action: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct ClosePortalStmt { - pub portalname: String, -} -#[derive(Clone, PartialEq)] -pub struct ClusterStmt { - pub relation: ::core::option::Option, - - pub indexname: String, - - pub options: i32, -} -#[derive(Clone, PartialEq)] -pub struct CopyStmt { - pub relation: ::core::option::Option, - - pub query: ::core::option::Option>, - - pub attlist: Vec, - - pub is_from: bool, - - pub is_program: bool, - - pub filename: String, - - pub options: Vec, - - pub where_clause: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateStmt { - pub relation: ::core::option::Option, - - pub table_elts: Vec, - - pub inh_relations: Vec, - - pub partbound: ::core::option::Option, - - pub partspec: ::core::option::Option, - - pub of_typename: ::core::option::Option, - - pub constraints: Vec, - - pub options: Vec, - - pub oncommit: i32, - - pub tablespacename: String, - - pub access_method: String, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct DefineStmt { - pub kind: i32, - - pub oldstyle: bool, - - pub defnames: Vec, - - pub args: Vec, - - pub definition: Vec, - - pub if_not_exists: bool, - - pub replace: bool, -} -#[derive(Clone, PartialEq)] -pub struct DropStmt { - pub objects: Vec, - - pub remove_type: i32, - - pub behavior: i32, - - pub missing_ok: bool, - - pub concurrent: bool, -} -#[derive(Clone, PartialEq)] -pub struct TruncateStmt { - pub relations: Vec, - - pub restart_seqs: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct CommentStmt { - pub objtype: i32, - - pub object: ::core::option::Option>, - - pub comment: String, -} -#[derive(Clone, PartialEq)] -pub struct FetchStmt { - pub direction: i32, - - pub how_many: i64, - - pub portalname: String, - - pub ismove: bool, -} -#[derive(Clone, PartialEq)] -pub struct IndexStmt { - pub idxname: String, - - pub relation: ::core::option::Option, - - pub access_method: String, - - pub table_space: String, - - pub index_params: Vec, - - pub index_including_params: Vec, - - pub options: Vec, - - pub where_clause: ::core::option::Option>, - - pub exclude_op_names: Vec, - - pub idxcomment: String, - - pub index_oid: u32, - - pub old_node: u32, - - pub old_create_subid: u32, - - pub old_first_relfilenode_subid: u32, - - pub unique: bool, - - pub primary: bool, - - pub isconstraint: bool, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub transformed: bool, - - pub concurrent: bool, - - pub if_not_exists: bool, - - pub reset_default_tblspc: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateFunctionStmt { - pub is_procedure: bool, - - pub replace: bool, - - pub funcname: Vec, - - pub parameters: Vec, - - pub return_type: ::core::option::Option, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterFunctionStmt { - pub objtype: i32, - - pub func: ::core::option::Option, - - pub actions: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DoStmt { - pub args: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RenameStmt { - pub rename_type: i32, - - pub relation_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub subname: String, - - pub newname: String, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct RuleStmt { - pub relation: ::core::option::Option, - - pub rulename: String, - - pub where_clause: ::core::option::Option>, - - pub event: i32, - - pub instead: bool, - - pub actions: Vec, - - pub replace: bool, -} -#[derive(Clone, PartialEq)] -pub struct NotifyStmt { - pub conditionname: String, - - pub payload: String, -} -#[derive(Clone, PartialEq)] -pub struct ListenStmt { - pub conditionname: String, -} -#[derive(Clone, PartialEq)] -pub struct UnlistenStmt { - pub conditionname: String, -} -#[derive(Clone, PartialEq)] -pub struct TransactionStmt { - pub kind: i32, - - pub options: Vec, - - pub savepoint_name: String, - - pub gid: String, - - pub chain: bool, -} -#[derive(Clone, PartialEq)] -pub struct ViewStmt { - pub view: ::core::option::Option, - - pub aliases: Vec, - - pub query: ::core::option::Option>, - - pub replace: bool, - - pub options: Vec, - - pub with_check_option: i32, -} -#[derive(Clone, PartialEq)] -pub struct LoadStmt { - pub filename: String, -} -#[derive(Clone, PartialEq)] -pub struct CreateDomainStmt { - pub domainname: Vec, - - pub type_name: ::core::option::Option, - - pub coll_clause: ::core::option::Option>, - - pub constraints: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreatedbStmt { - pub dbname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropdbStmt { - pub dbname: String, - - pub missing_ok: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct VacuumStmt { - pub options: Vec, - - pub rels: Vec, - - pub is_vacuumcmd: bool, -} -#[derive(Clone, PartialEq)] -pub struct ExplainStmt { - pub query: ::core::option::Option>, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateTableAsStmt { - pub query: ::core::option::Option>, - - pub into: ::core::option::Option>, - - pub relkind: i32, - - pub is_select_into: bool, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateSeqStmt { - pub sequence: ::core::option::Option, - - pub options: Vec, - - pub owner_id: u32, - - pub for_identity: bool, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterSeqStmt { - pub sequence: ::core::option::Option, - - pub options: Vec, - - pub for_identity: bool, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct VariableSetStmt { - pub kind: i32, - - pub name: String, - - pub args: Vec, - - pub is_local: bool, -} -#[derive(Clone, PartialEq)] -pub struct VariableShowStmt { - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct DiscardStmt { - pub target: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateTrigStmt { - pub trigname: String, - - pub relation: ::core::option::Option, - - pub funcname: Vec, - - pub args: Vec, - - pub row: bool, - - pub timing: i32, - - pub events: i32, - - pub columns: Vec, - - pub when_clause: ::core::option::Option>, - - pub isconstraint: bool, - - pub transition_rels: Vec, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub constrrel: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreatePLangStmt { - pub replace: bool, - - pub plname: String, - - pub plhandler: Vec, - - pub plinline: Vec, - - pub plvalidator: Vec, - - pub pltrusted: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateRoleStmt { - pub stmt_type: i32, - - pub role: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterRoleStmt { - pub role: ::core::option::Option, - - pub options: Vec, - - pub action: i32, -} -#[derive(Clone, PartialEq)] -pub struct DropRoleStmt { - pub roles: Vec, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct LockStmt { - pub relations: Vec, - - pub mode: i32, - - pub nowait: bool, -} -#[derive(Clone, PartialEq)] -pub struct ConstraintsSetStmt { - pub constraints: Vec, - - pub deferred: bool, -} -#[derive(Clone, PartialEq)] -pub struct ReindexStmt { - pub kind: i32, - - pub relation: ::core::option::Option, - - pub name: String, - - pub options: i32, - - pub concurrent: bool, -} -#[derive(Clone, PartialEq)] -pub struct CheckPointStmt {} -#[derive(Clone, PartialEq)] -pub struct CreateSchemaStmt { - pub schemaname: String, - - pub authrole: ::core::option::Option, - - pub schema_elts: Vec, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterDatabaseStmt { - pub dbname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterDatabaseSetStmt { - pub dbname: String, - - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct AlterRoleSetStmt { - pub role: ::core::option::Option, - - pub database: String, - - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreateConversionStmt { - pub conversion_name: Vec, - - pub for_encoding_name: String, - - pub to_encoding_name: String, - - pub func_name: Vec, - - pub def: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateCastStmt { - pub sourcetype: ::core::option::Option, - - pub targettype: ::core::option::Option, - - pub func: ::core::option::Option, - - pub context: i32, - - pub inout: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpClassStmt { - pub opclassname: Vec, - - pub opfamilyname: Vec, - - pub amname: String, - - pub datatype: ::core::option::Option, - - pub items: Vec, - - pub is_default: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpFamilyStmt { - pub opfamilyname: Vec, - - pub amname: String, -} -#[derive(Clone, PartialEq)] -pub struct AlterOpFamilyStmt { - pub opfamilyname: Vec, - - pub amname: String, - - pub is_drop: bool, - - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct PrepareStmt { - pub name: String, - - pub argtypes: Vec, - - pub query: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct ExecuteStmt { - pub name: String, - - pub params: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DeallocateStmt { - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct DeclareCursorStmt { - pub portalname: String, - - pub options: i32, - - pub query: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateTableSpaceStmt { - pub tablespacename: String, - - pub owner: ::core::option::Option, - - pub location: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropTableSpaceStmt { - pub tablespacename: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterObjectDependsStmt { - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub extname: ::core::option::Option>, - - pub remove: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterObjectSchemaStmt { - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub newschema: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterOwnerStmt { - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub newowner: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct AlterOperatorStmt { - pub opername: ::core::option::Option, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterTypeStmt { - pub type_name: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropOwnedStmt { - pub roles: Vec, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct ReassignOwnedStmt { - pub roles: Vec, - - pub newrole: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CompositeTypeStmt { - pub typevar: ::core::option::Option, - - pub coldeflist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateEnumStmt { - pub type_name: Vec, - - pub vals: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateRangeStmt { - pub type_name: Vec, - - pub params: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterEnumStmt { - pub type_name: Vec, - - pub old_val: String, - - pub new_val: String, - - pub new_val_neighbor: String, - - pub new_val_is_after: bool, - - pub skip_if_new_val_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTsDictionaryStmt { - pub dictname: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterTsConfigurationStmt { - pub kind: i32, - - pub cfgname: Vec, - - pub tokentype: Vec, - - pub dicts: Vec, - - pub r#override: bool, - - pub replace: bool, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateFdwStmt { - pub fdwname: String, - - pub func_options: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterFdwStmt { - pub fdwname: String, - - pub func_options: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateForeignServerStmt { - pub servername: String, - - pub servertype: String, - - pub version: String, - - pub fdwname: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterForeignServerStmt { - pub servername: String, - - pub version: String, - - pub options: Vec, - - pub has_version: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateUserMappingStmt { - pub user: ::core::option::Option, - - pub servername: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterUserMappingStmt { - pub user: ::core::option::Option, - - pub servername: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropUserMappingStmt { - pub user: ::core::option::Option, - - pub servername: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableSpaceOptionsStmt { - pub tablespacename: String, - - pub options: Vec, - - pub is_reset: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableMoveAllStmt { - pub orig_tablespacename: String, - - pub objtype: i32, - - pub roles: Vec, - - pub new_tablespacename: String, - - pub nowait: bool, -} -#[derive(Clone, PartialEq)] -pub struct SecLabelStmt { - pub objtype: i32, - - pub object: ::core::option::Option>, - - pub provider: String, - - pub label: String, -} -#[derive(Clone, PartialEq)] -pub struct CreateForeignTableStmt { - pub base_stmt: ::core::option::Option, - - pub servername: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct ImportForeignSchemaStmt { - pub server_name: String, - - pub remote_schema: String, - - pub local_schema: String, - - pub list_type: i32, - - pub table_list: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateExtensionStmt { - pub extname: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterExtensionStmt { - pub extname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterExtensionContentsStmt { - pub extname: String, - - pub action: i32, - - pub objtype: i32, - - pub object: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateEventTrigStmt { - pub trigname: String, - - pub eventname: String, - - pub whenclause: Vec, - - pub funcname: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterEventTrigStmt { - pub trigname: String, - - pub tgenabled: String, -} -#[derive(Clone, PartialEq)] -pub struct RefreshMatViewStmt { - pub concurrent: bool, - - pub skip_data: bool, - - pub relation: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct ReplicaIdentityStmt { - pub identity_type: String, - - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct AlterSystemStmt { - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreatePolicyStmt { - pub policy_name: String, - - pub table: ::core::option::Option, - - pub cmd_name: String, - - pub permissive: bool, - - pub roles: Vec, - - pub qual: ::core::option::Option>, - - pub with_check: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterPolicyStmt { - pub policy_name: String, - - pub table: ::core::option::Option, - - pub roles: Vec, - - pub qual: ::core::option::Option>, - - pub with_check: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateTransformStmt { - pub replace: bool, - - pub type_name: ::core::option::Option, - - pub lang: String, - - pub fromsql: ::core::option::Option, - - pub tosql: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreateAmStmt { - pub amname: String, - - pub handler_name: Vec, - - pub amtype: String, -} -#[derive(Clone, PartialEq)] -pub struct CreatePublicationStmt { - pub pubname: String, - - pub options: Vec, - - pub tables: Vec, - - pub for_all_tables: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterPublicationStmt { - pub pubname: String, - - pub options: Vec, - - pub tables: Vec, - - pub for_all_tables: bool, - - pub table_action: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateSubscriptionStmt { - pub subname: String, - - pub conninfo: String, - - pub publication: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterSubscriptionStmt { - pub kind: i32, - - pub subname: String, - - pub conninfo: String, - - pub publication: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropSubscriptionStmt { - pub subname: String, - - pub missing_ok: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateStatsStmt { - pub defnames: Vec, - - pub stat_types: Vec, - - pub exprs: Vec, - - pub relations: Vec, - - pub stxcomment: String, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterCollationStmt { - pub collname: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CallStmt { - pub funccall: ::core::option::Option>, - - pub funcexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterStatsStmt { - pub defnames: Vec, - - pub stxstattarget: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AExpr { - pub kind: i32, - - pub name: Vec, - - pub lexpr: ::core::option::Option>, - - pub rexpr: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ColumnRef { - pub fields: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ParamRef { - pub number: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct AConst { - pub val: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct FuncCall { - pub funcname: Vec, - - pub args: Vec, - - pub agg_order: Vec, - - pub agg_filter: ::core::option::Option>, - - pub agg_within_group: bool, - - pub agg_star: bool, - - pub agg_distinct: bool, - - pub func_variadic: bool, - - pub over: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct AStar {} -#[derive(Clone, PartialEq)] -pub struct AIndices { - pub is_slice: bool, - - pub lidx: ::core::option::Option>, - - pub uidx: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AIndirection { - pub arg: ::core::option::Option>, - - pub indirection: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AArrayExpr { - pub elements: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ResTarget { - pub name: String, - - pub indirection: Vec, - - pub val: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct MultiAssignRef { - pub source: ::core::option::Option>, - - pub colno: i32, - - pub ncolumns: i32, -} -#[derive(Clone, PartialEq)] -pub struct TypeCast { - pub arg: ::core::option::Option>, - - pub type_name: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CollateClause { - pub arg: ::core::option::Option>, - - pub collname: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SortBy { - pub node: ::core::option::Option>, - - pub sortby_dir: i32, - - pub sortby_nulls: i32, - - pub use_op: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowDef { - pub name: String, - - pub refname: String, - - pub partition_clause: Vec, - - pub order_clause: Vec, - - pub frame_options: i32, - - pub start_offset: ::core::option::Option>, - - pub end_offset: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeSubselect { - pub lateral: bool, - - pub subquery: ::core::option::Option>, - - pub alias: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct RangeFunction { - pub lateral: bool, - - pub ordinality: bool, - - pub is_rowsfrom: bool, - - pub functions: Vec, - - pub alias: ::core::option::Option, - - pub coldeflist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableSample { - pub relation: ::core::option::Option>, - - pub method: Vec, - - pub args: Vec, - - pub repeatable: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableFunc { - pub lateral: bool, - - pub docexpr: ::core::option::Option>, - - pub rowexpr: ::core::option::Option>, - - pub namespaces: Vec, - - pub columns: Vec, - - pub alias: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableFuncCol { - pub colname: String, - - pub type_name: ::core::option::Option, - - pub for_ordinality: bool, - - pub is_not_null: bool, - - pub colexpr: ::core::option::Option>, - - pub coldefexpr: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TypeName { - pub names: Vec, - - pub type_oid: u32, - - pub setof: bool, - - pub pct_type: bool, - - pub typmods: Vec, - - pub typemod: i32, - - pub array_bounds: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ColumnDef { - pub colname: String, - - pub type_name: ::core::option::Option, - - pub inhcount: i32, - - pub is_local: bool, - - pub is_not_null: bool, - - pub is_from_type: bool, - - pub storage: String, - - pub raw_default: ::core::option::Option>, - - pub cooked_default: ::core::option::Option>, - - pub identity: String, - - pub identity_sequence: ::core::option::Option, - - pub generated: String, - - pub coll_clause: ::core::option::Option>, - - pub coll_oid: u32, - - pub constraints: Vec, - - pub fdwoptions: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct IndexElem { - pub name: String, - - pub expr: ::core::option::Option>, - - pub indexcolname: String, - - pub collation: Vec, - - pub opclass: Vec, - - pub opclassopts: Vec, - - pub ordering: i32, - - pub nulls_ordering: i32, -} -#[derive(Clone, PartialEq)] -pub struct Constraint { - pub contype: i32, - - pub conname: String, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub location: i32, - - pub is_no_inherit: bool, - - pub raw_expr: ::core::option::Option>, - - pub cooked_expr: String, - - pub generated_when: String, - - pub keys: Vec, - - pub including: Vec, - - pub exclusions: Vec, - - pub options: Vec, - - pub indexname: String, - - pub indexspace: String, - - pub reset_default_tblspc: bool, - - pub access_method: String, - - pub where_clause: ::core::option::Option>, - - pub pktable: ::core::option::Option, - - pub fk_attrs: Vec, - - pub pk_attrs: Vec, - - pub fk_matchtype: String, - - pub fk_upd_action: String, - - pub fk_del_action: String, - - pub old_conpfeqop: Vec, - - pub old_pktable_oid: u32, - - pub skip_validation: bool, - - pub initially_valid: bool, -} -#[derive(Clone, PartialEq)] -pub struct DefElem { - pub defnamespace: String, - - pub defname: String, - - pub arg: ::core::option::Option>, - - pub defaction: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblEntry { - pub rtekind: i32, - - pub relid: u32, - - pub relkind: String, - - pub rellockmode: i32, - - pub tablesample: ::core::option::Option>, - - pub subquery: ::core::option::Option>, - - pub security_barrier: bool, - - pub jointype: i32, - - pub joinmergedcols: i32, - - pub joinaliasvars: Vec, - - pub joinleftcols: Vec, - - pub joinrightcols: Vec, - - pub functions: Vec, - - pub funcordinality: bool, - - pub tablefunc: ::core::option::Option>, - - pub values_lists: Vec, - - pub ctename: String, - - pub ctelevelsup: u32, - - pub self_reference: bool, - - pub coltypes: Vec, - - pub coltypmods: Vec, - - pub colcollations: Vec, - - pub enrname: String, - - pub enrtuples: f64, - - pub alias: ::core::option::Option, - - pub eref: ::core::option::Option, - - pub lateral: bool, - - pub inh: bool, - - pub in_from_cl: bool, - - pub required_perms: u32, - - pub check_as_user: u32, - - pub selected_cols: Vec, - - pub inserted_cols: Vec, - - pub updated_cols: Vec, - - pub extra_updated_cols: Vec, - - pub security_quals: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblFunction { - pub funcexpr: ::core::option::Option>, - - pub funccolcount: i32, - - pub funccolnames: Vec, - - pub funccoltypes: Vec, - - pub funccoltypmods: Vec, - - pub funccolcollations: Vec, - - pub funcparams: Vec, -} -#[derive(Clone, PartialEq)] -pub struct TableSampleClause { - pub tsmhandler: u32, - - pub args: Vec, - - pub repeatable: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct WithCheckOption { - pub kind: i32, - - pub relname: String, - - pub polname: String, - - pub qual: ::core::option::Option>, - - pub cascaded: bool, -} -#[derive(Clone, PartialEq)] -pub struct SortGroupClause { - pub tle_sort_group_ref: u32, - - pub eqop: u32, - - pub sortop: u32, - - pub nulls_first: bool, - - pub hashable: bool, -} -#[derive(Clone, PartialEq)] -pub struct GroupingSet { - pub kind: i32, - - pub content: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowClause { - pub name: String, - - pub refname: String, - - pub partition_clause: Vec, - - pub order_clause: Vec, - - pub frame_options: i32, - - pub start_offset: ::core::option::Option>, - - pub end_offset: ::core::option::Option>, - - pub start_in_range_func: u32, - - pub end_in_range_func: u32, - - pub in_range_coll: u32, - - pub in_range_asc: bool, - - pub in_range_nulls_first: bool, - - pub winref: u32, - - pub copied_order: bool, -} -#[derive(Clone, PartialEq)] -pub struct ObjectWithArgs { - pub objname: Vec, - - pub objargs: Vec, - - pub args_unspecified: bool, -} -#[derive(Clone, PartialEq)] -pub struct AccessPriv { - pub priv_name: String, - - pub cols: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpClassItem { - pub itemtype: i32, - - pub name: ::core::option::Option, - - pub number: i32, - - pub order_family: Vec, - - pub class_args: Vec, - - pub storedtype: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct TableLikeClause { - pub relation: ::core::option::Option, - - pub options: u32, - - pub relation_oid: u32, -} -#[derive(Clone, PartialEq)] -pub struct FunctionParameter { - pub name: String, - - pub arg_type: ::core::option::Option, - - pub mode: i32, - - pub defexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct LockingClause { - pub locked_rels: Vec, - - pub strength: i32, - - pub wait_policy: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowMarkClause { - pub rti: u32, - - pub strength: i32, - - pub wait_policy: i32, - - pub pushed_down: bool, -} -#[derive(Clone, PartialEq)] -pub struct XmlSerialize { - pub xmloption: i32, - - pub expr: ::core::option::Option>, - - pub type_name: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WithClause { - pub ctes: Vec, - - pub recursive: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct InferClause { - pub index_elems: Vec, - - pub where_clause: ::core::option::Option>, - - pub conname: String, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct OnConflictClause { - pub action: i32, - - pub infer: ::core::option::Option>, - - pub target_list: Vec, - - pub where_clause: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CommonTableExpr { - pub ctename: String, - - pub aliascolnames: Vec, - - pub ctematerialized: i32, - - pub ctequery: ::core::option::Option>, - - pub location: i32, - - pub cterecursive: bool, - - pub cterefcount: i32, - - pub ctecolnames: Vec, - - pub ctecoltypes: Vec, - - pub ctecoltypmods: Vec, - - pub ctecolcollations: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RoleSpec { - pub roletype: i32, - - pub rolename: String, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TriggerTransition { - pub name: String, - - pub is_new: bool, - - pub is_table: bool, -} -#[derive(Clone, PartialEq)] -pub struct PartitionElem { - pub name: String, - - pub expr: ::core::option::Option>, - - pub collation: Vec, - - pub opclass: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionSpec { - pub strategy: String, - - pub part_params: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionBoundSpec { - pub strategy: String, - - pub is_default: bool, - - pub modulus: i32, - - pub remainder: i32, - - pub listdatums: Vec, - - pub lowerdatums: Vec, - - pub upperdatums: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionRangeDatum { - pub kind: i32, - - pub value: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionCmd { - pub name: ::core::option::Option, - - pub bound: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct VacuumRelation { - pub relation: ::core::option::Option, - - pub oid: u32, - - pub va_cols: Vec, -} -#[derive(Clone, PartialEq)] -pub struct InlineCodeBlock { - pub source_text: String, - - pub lang_oid: u32, - - pub lang_is_trusted: bool, - - pub atomic: bool, -} -#[derive(Clone, PartialEq)] -pub struct CallContext { - pub atomic: bool, -} -#[derive(Clone, PartialEq)] -pub struct ScanToken { - pub start: i32, - - pub end: i32, - - pub token: i32, - - pub keyword_kind: i32, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OverridingKind { - Undefined = 0, - OverridingNotSet = 1, - OverridingUserValue = 2, - OverridingSystemValue = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum QuerySource { - Undefined = 0, - QsrcOriginal = 1, - QsrcParser = 2, - QsrcInsteadRule = 3, - QsrcQualInsteadRule = 4, - QsrcNonInsteadRule = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SortByDir { - Undefined = 0, - SortbyDefault = 1, - SortbyAsc = 2, - SortbyDesc = 3, - SortbyUsing = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SortByNulls { - Undefined = 0, - SortbyNullsDefault = 1, - SortbyNullsFirst = 2, - SortbyNullsLast = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AExprKind { - Undefined = 0, - AexprOp = 1, - AexprOpAny = 2, - AexprOpAll = 3, - AexprDistinct = 4, - AexprNotDistinct = 5, - AexprNullif = 6, - AexprOf = 7, - AexprIn = 8, - AexprLike = 9, - AexprIlike = 10, - AexprSimilar = 11, - AexprBetween = 12, - AexprNotBetween = 13, - AexprBetweenSym = 14, - AexprNotBetweenSym = 15, - AexprParen = 16, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RoleSpecType { - Undefined = 0, - RolespecCstring = 1, - RolespecCurrentUser = 2, - RolespecSessionUser = 3, - RolespecPublic = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum TableLikeOption { - Undefined = 0, - CreateTableLikeComments = 1, - CreateTableLikeConstraints = 2, - CreateTableLikeDefaults = 3, - CreateTableLikeGenerated = 4, - CreateTableLikeIdentity = 5, - CreateTableLikeIndexes = 6, - CreateTableLikeStatistics = 7, - CreateTableLikeStorage = 8, - CreateTableLikeAll = 9, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DefElemAction { - Undefined = 0, - DefelemUnspec = 1, - DefelemSet = 2, - DefelemAdd = 3, - DefelemDrop = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum PartitionRangeDatumKind { - Undefined = 0, - PartitionRangeDatumMinvalue = 1, - PartitionRangeDatumValue = 2, - PartitionRangeDatumMaxvalue = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RteKind { - RtekindUndefined = 0, - RteRelation = 1, - RteSubquery = 2, - RteJoin = 3, - RteFunction = 4, - RteTablefunc = 5, - RteValues = 6, - RteCte = 7, - RteNamedtuplestore = 8, - RteResult = 9, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum WcoKind { - WcokindUndefined = 0, - WcoViewCheck = 1, - WcoRlsInsertCheck = 2, - WcoRlsUpdateCheck = 3, - WcoRlsConflictCheck = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum GroupingSetKind { - Undefined = 0, - GroupingSetEmpty = 1, - GroupingSetSimple = 2, - GroupingSetRollup = 3, - GroupingSetCube = 4, - GroupingSetSets = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CteMaterialize { - CtematerializeUndefined = 0, - Default = 1, - Always = 2, - Never = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOperation { - Undefined = 0, - SetopNone = 1, - SetopUnion = 2, - SetopIntersect = 3, - SetopExcept = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ObjectType { - Undefined = 0, - ObjectAccessMethod = 1, - ObjectAggregate = 2, - ObjectAmop = 3, - ObjectAmproc = 4, - ObjectAttribute = 5, - ObjectCast = 6, - ObjectColumn = 7, - ObjectCollation = 8, - ObjectConversion = 9, - ObjectDatabase = 10, - ObjectDefault = 11, - ObjectDefacl = 12, - ObjectDomain = 13, - ObjectDomconstraint = 14, - ObjectEventTrigger = 15, - ObjectExtension = 16, - ObjectFdw = 17, - ObjectForeignServer = 18, - ObjectForeignTable = 19, - ObjectFunction = 20, - ObjectIndex = 21, - ObjectLanguage = 22, - ObjectLargeobject = 23, - ObjectMatview = 24, - ObjectOpclass = 25, - ObjectOperator = 26, - ObjectOpfamily = 27, - ObjectPolicy = 28, - ObjectProcedure = 29, - ObjectPublication = 30, - ObjectPublicationRel = 31, - ObjectRole = 32, - ObjectRoutine = 33, - ObjectRule = 34, - ObjectSchema = 35, - ObjectSequence = 36, - ObjectSubscription = 37, - ObjectStatisticExt = 38, - ObjectTabconstraint = 39, - ObjectTable = 40, - ObjectTablespace = 41, - ObjectTransform = 42, - ObjectTrigger = 43, - ObjectTsconfiguration = 44, - ObjectTsdictionary = 45, - ObjectTsparser = 46, - ObjectTstemplate = 47, - ObjectType = 48, - ObjectUserMapping = 49, - ObjectView = 50, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DropBehavior { - Undefined = 0, - DropRestrict = 1, - DropCascade = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterTableType { - Undefined = 0, - AtAddColumn = 1, - AtAddColumnRecurse = 2, - AtAddColumnToView = 3, - AtColumnDefault = 4, - AtCookedColumnDefault = 5, - AtDropNotNull = 6, - AtSetNotNull = 7, - AtDropExpression = 8, - AtCheckNotNull = 9, - AtSetStatistics = 10, - AtSetOptions = 11, - AtResetOptions = 12, - AtSetStorage = 13, - AtDropColumn = 14, - AtDropColumnRecurse = 15, - AtAddIndex = 16, - AtReAddIndex = 17, - AtAddConstraint = 18, - AtAddConstraintRecurse = 19, - AtReAddConstraint = 20, - AtReAddDomainConstraint = 21, - AtAlterConstraint = 22, - AtValidateConstraint = 23, - AtValidateConstraintRecurse = 24, - AtAddIndexConstraint = 25, - AtDropConstraint = 26, - AtDropConstraintRecurse = 27, - AtReAddComment = 28, - AtAlterColumnType = 29, - AtAlterColumnGenericOptions = 30, - AtChangeOwner = 31, - AtClusterOn = 32, - AtDropCluster = 33, - AtSetLogged = 34, - AtSetUnLogged = 35, - AtDropOids = 36, - AtSetTableSpace = 37, - AtSetRelOptions = 38, - AtResetRelOptions = 39, - AtReplaceRelOptions = 40, - AtEnableTrig = 41, - AtEnableAlwaysTrig = 42, - AtEnableReplicaTrig = 43, - AtDisableTrig = 44, - AtEnableTrigAll = 45, - AtDisableTrigAll = 46, - AtEnableTrigUser = 47, - AtDisableTrigUser = 48, - AtEnableRule = 49, - AtEnableAlwaysRule = 50, - AtEnableReplicaRule = 51, - AtDisableRule = 52, - AtAddInherit = 53, - AtDropInherit = 54, - AtAddOf = 55, - AtDropOf = 56, - AtReplicaIdentity = 57, - AtEnableRowSecurity = 58, - AtDisableRowSecurity = 59, - AtForceRowSecurity = 60, - AtNoForceRowSecurity = 61, - AtGenericOptions = 62, - AtAttachPartition = 63, - AtDetachPartition = 64, - AtAddIdentity = 65, - AtSetIdentity = 66, - AtDropIdentity = 67, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum GrantTargetType { - Undefined = 0, - AclTargetObject = 1, - AclTargetAllInSchema = 2, - AclTargetDefaults = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum VariableSetKind { - Undefined = 0, - VarSetValue = 1, - VarSetDefault = 2, - VarSetCurrent = 3, - VarSetMulti = 4, - VarReset = 5, - VarResetAll = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ConstrType { - Undefined = 0, - ConstrNull = 1, - ConstrNotnull = 2, - ConstrDefault = 3, - ConstrIdentity = 4, - ConstrGenerated = 5, - ConstrCheck = 6, - ConstrPrimary = 7, - ConstrUnique = 8, - ConstrExclusion = 9, - ConstrForeign = 10, - ConstrAttrDeferrable = 11, - ConstrAttrNotDeferrable = 12, - ConstrAttrDeferred = 13, - ConstrAttrImmediate = 14, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ImportForeignSchemaType { - Undefined = 0, - FdwImportSchemaAll = 1, - FdwImportSchemaLimitTo = 2, - FdwImportSchemaExcept = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RoleStmtType { - Undefined = 0, - RolestmtRole = 1, - RolestmtUser = 2, - RolestmtGroup = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum FetchDirection { - Undefined = 0, - FetchForward = 1, - FetchBackward = 2, - FetchAbsolute = 3, - FetchRelative = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum FunctionParameterMode { - Undefined = 0, - FuncParamIn = 1, - FuncParamOut = 2, - FuncParamInout = 3, - FuncParamVariadic = 4, - FuncParamTable = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum TransactionStmtKind { - Undefined = 0, - TransStmtBegin = 1, - TransStmtStart = 2, - TransStmtCommit = 3, - TransStmtRollback = 4, - TransStmtSavepoint = 5, - TransStmtRelease = 6, - TransStmtRollbackTo = 7, - TransStmtPrepare = 8, - TransStmtCommitPrepared = 9, - TransStmtRollbackPrepared = 10, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ViewCheckOption { - Undefined = 0, - NoCheckOption = 1, - LocalCheckOption = 2, - CascadedCheckOption = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ClusterOption { - Undefined = 0, - CluoptRecheck = 1, - CluoptVerbose = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DiscardMode { - Undefined = 0, - DiscardAll = 1, - DiscardPlans = 2, - DiscardSequences = 3, - DiscardTemp = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ReindexObjectType { - Undefined = 0, - ReindexObjectIndex = 1, - ReindexObjectTable = 2, - ReindexObjectSchema = 3, - ReindexObjectSystem = 4, - ReindexObjectDatabase = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterTsConfigType { - AlterTsconfigTypeUndefined = 0, - AlterTsconfigAddMapping = 1, - AlterTsconfigAlterMappingForToken = 2, - AlterTsconfigReplaceDict = 3, - AlterTsconfigReplaceDictForToken = 4, - AlterTsconfigDropMapping = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterSubscriptionType { - Undefined = 0, - AlterSubscriptionOptions = 1, - AlterSubscriptionConnection = 2, - AlterSubscriptionPublication = 3, - AlterSubscriptionRefresh = 4, - AlterSubscriptionEnabled = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OnCommitAction { - Undefined = 0, - OncommitNoop = 1, - OncommitPreserveRows = 2, - OncommitDeleteRows = 3, - OncommitDrop = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ParamKind { - Undefined = 0, - ParamExtern = 1, - ParamExec = 2, - ParamSublink = 3, - ParamMultiexpr = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CoercionContext { - Undefined = 0, - CoercionImplicit = 1, - CoercionAssignment = 2, - CoercionExplicit = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CoercionForm { - Undefined = 0, - CoerceExplicitCall = 1, - CoerceExplicitCast = 2, - CoerceImplicitCast = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum BoolExprType { - Undefined = 0, - AndExpr = 1, - OrExpr = 2, - NotExpr = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SubLinkType { - Undefined = 0, - ExistsSublink = 1, - AllSublink = 2, - AnySublink = 3, - RowcompareSublink = 4, - ExprSublink = 5, - MultiexprSublink = 6, - ArraySublink = 7, - CteSublink = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RowCompareType { - Undefined = 0, - RowcompareLt = 1, - RowcompareLe = 2, - RowcompareEq = 3, - RowcompareGe = 4, - RowcompareGt = 5, - RowcompareNe = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum MinMaxOp { - Undefined = 0, - IsGreatest = 1, - IsLeast = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SqlValueFunctionOp { - SqlvalueFunctionOpUndefined = 0, - SvfopCurrentDate = 1, - SvfopCurrentTime = 2, - SvfopCurrentTimeN = 3, - SvfopCurrentTimestamp = 4, - SvfopCurrentTimestampN = 5, - SvfopLocaltime = 6, - SvfopLocaltimeN = 7, - SvfopLocaltimestamp = 8, - SvfopLocaltimestampN = 9, - SvfopCurrentRole = 10, - SvfopCurrentUser = 11, - SvfopUser = 12, - SvfopSessionUser = 13, - SvfopCurrentCatalog = 14, - SvfopCurrentSchema = 15, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum XmlExprOp { - Undefined = 0, - IsXmlconcat = 1, - IsXmlelement = 2, - IsXmlforest = 3, - IsXmlparse = 4, - IsXmlpi = 5, - IsXmlroot = 6, - IsXmlserialize = 7, - IsDocument = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum XmlOptionType { - Undefined = 0, - XmloptionDocument = 1, - XmloptionContent = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum NullTestType { - Undefined = 0, - IsNull = 1, - IsNotNull = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum BoolTestType { - Undefined = 0, - IsTrue = 1, - IsNotTrue = 2, - IsFalse = 3, - IsNotFalse = 4, - IsUnknown = 5, - IsNotUnknown = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CmdType { - Undefined = 0, - CmdUnknown = 1, - CmdSelect = 2, - CmdUpdate = 3, - CmdInsert = 4, - CmdDelete = 5, - CmdUtility = 6, - CmdNothing = 7, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum JoinType { - Undefined = 0, - JoinInner = 1, - JoinLeft = 2, - JoinFull = 3, - JoinRight = 4, - JoinSemi = 5, - JoinAnti = 6, - JoinUniqueOuter = 7, - JoinUniqueInner = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AggStrategy { - Undefined = 0, - AggPlain = 1, - AggSorted = 2, - AggHashed = 3, - AggMixed = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AggSplit { - Undefined = 0, - AggsplitSimple = 1, - AggsplitInitialSerial = 2, - AggsplitFinalDeserial = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOpCmd { - Undefined = 0, - SetopcmdIntersect = 1, - SetopcmdIntersectAll = 2, - SetopcmdExcept = 3, - SetopcmdExceptAll = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOpStrategy { - Undefined = 0, - SetopSorted = 1, - SetopHashed = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OnConflictAction { - Undefined = 0, - OnconflictNone = 1, - OnconflictNothing = 2, - OnconflictUpdate = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LimitOption { - Undefined = 0, - Default = 1, - Count = 2, - WithTies = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockClauseStrength { - Undefined = 0, - LcsNone = 1, - LcsForkeyshare = 2, - LcsForshare = 3, - LcsFornokeyupdate = 4, - LcsForupdate = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockWaitPolicy { - Undefined = 0, - LockWaitBlock = 1, - LockWaitSkip = 2, - LockWaitError = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockTupleMode { - Undefined = 0, - LockTupleKeyShare = 1, - LockTupleShare = 2, - LockTupleNoKeyExclusive = 3, - LockTupleExclusive = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum KeywordKind { - NoKeyword = 0, - UnreservedKeyword = 1, - ColNameKeyword = 2, - TypeFuncNameKeyword = 3, - ReservedKeyword = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum Token { - Nul = 0, - /// Single-character tokens that are returned 1:1 (identical with "self" list in scan.l) - /// Either supporting syntax, or single-character operators (some can be both) - /// Also see - /// - /// "%" - Ascii37 = 37, - /// "(" - Ascii40 = 40, - /// ")" - Ascii41 = 41, - /// "*" - Ascii42 = 42, - /// "+" - Ascii43 = 43, - /// "," - Ascii44 = 44, - /// "-" - Ascii45 = 45, - /// "." - Ascii46 = 46, - /// "/" - Ascii47 = 47, - /// ":" - Ascii58 = 58, - /// ";" - Ascii59 = 59, - /// "<" - Ascii60 = 60, - /// "=" - Ascii61 = 61, - /// ">" - Ascii62 = 62, - /// "?" - Ascii63 = 63, - /// "[" - Ascii91 = 91, - /// "\" - Ascii92 = 92, - /// "]" - Ascii93 = 93, - /// "^" - Ascii94 = 94, - /// Named tokens in scan.l - Ident = 258, - Uident = 259, - Fconst = 260, - Sconst = 261, - Usconst = 262, - Bconst = 263, - Xconst = 264, - Op = 265, - Iconst = 266, - Param = 267, - Typecast = 268, - DotDot = 269, - ColonEquals = 270, - EqualsGreater = 271, - LessEquals = 272, - GreaterEquals = 273, - NotEquals = 274, - SqlComment = 275, - CComment = 276, - AbortP = 277, - AbsoluteP = 278, - Access = 279, - Action = 280, - AddP = 281, - Admin = 282, - After = 283, - Aggregate = 284, - All = 285, - Also = 286, - Alter = 287, - Always = 288, - Analyse = 289, - Analyze = 290, - And = 291, - Any = 292, - Array = 293, - As = 294, - Asc = 295, - Assertion = 296, - Assignment = 297, - Asymmetric = 298, - At = 299, - Attach = 300, - Attribute = 301, - Authorization = 302, - Backward = 303, - Before = 304, - BeginP = 305, - Between = 306, - Bigint = 307, - Binary = 308, - Bit = 309, - BooleanP = 310, - Both = 311, - By = 312, - Cache = 313, - Call = 314, - Called = 315, - Cascade = 316, - Cascaded = 317, - Case = 318, - Cast = 319, - CatalogP = 320, - Chain = 321, - CharP = 322, - Character = 323, - Characteristics = 324, - Check = 325, - Checkpoint = 326, - Class = 327, - Close = 328, - Cluster = 329, - Coalesce = 330, - Collate = 331, - Collation = 332, - Column = 333, - Columns = 334, - Comment = 335, - Comments = 336, - Commit = 337, - Committed = 338, - Concurrently = 339, - Configuration = 340, - Conflict = 341, - Connection = 342, - Constraint = 343, - Constraints = 344, - ContentP = 345, - ContinueP = 346, - ConversionP = 347, - Copy = 348, - Cost = 349, - Create = 350, - Cross = 351, - Csv = 352, - Cube = 353, - CurrentP = 354, - CurrentCatalog = 355, - CurrentDate = 356, - CurrentRole = 357, - CurrentSchema = 358, - CurrentTime = 359, - CurrentTimestamp = 360, - CurrentUser = 361, - Cursor = 362, - Cycle = 363, - DataP = 364, - Database = 365, - DayP = 366, - Deallocate = 367, - Dec = 368, - DecimalP = 369, - Declare = 370, - Default = 371, - Defaults = 372, - Deferrable = 373, - Deferred = 374, - Definer = 375, - DeleteP = 376, - Delimiter = 377, - Delimiters = 378, - Depends = 379, - Desc = 380, - Detach = 381, - Dictionary = 382, - DisableP = 383, - Discard = 384, - Distinct = 385, - Do = 386, - DocumentP = 387, - DomainP = 388, - DoubleP = 389, - Drop = 390, - Each = 391, - Else = 392, - EnableP = 393, - Encoding = 394, - Encrypted = 395, - EndP = 396, - EnumP = 397, - Escape = 398, - Event = 399, - Except = 400, - Exclude = 401, - Excluding = 402, - Exclusive = 403, - Execute = 404, - Exists = 405, - Explain = 406, - Expression = 407, - Extension = 408, - External = 409, - Extract = 410, - FalseP = 411, - Family = 412, - Fetch = 413, - Filter = 414, - FirstP = 415, - FloatP = 416, - Following = 417, - For = 418, - Force = 419, - Foreign = 420, - Forward = 421, - Freeze = 422, - From = 423, - Full = 424, - Function = 425, - Functions = 426, - Generated = 427, - Global = 428, - Grant = 429, - Granted = 430, - Greatest = 431, - GroupP = 432, - Grouping = 433, - Groups = 434, - Handler = 435, - Having = 436, - HeaderP = 437, - Hold = 438, - HourP = 439, - IdentityP = 440, - IfP = 441, - Ilike = 442, - Immediate = 443, - Immutable = 444, - ImplicitP = 445, - ImportP = 446, - InP = 447, - Include = 448, - Including = 449, - Increment = 450, - Index = 451, - Indexes = 452, - Inherit = 453, - Inherits = 454, - Initially = 455, - InlineP = 456, - InnerP = 457, - Inout = 458, - InputP = 459, - Insensitive = 460, - Insert = 461, - Instead = 462, - IntP = 463, - Integer = 464, - Intersect = 465, - Interval = 466, - Into = 467, - Invoker = 468, - Is = 469, - Isnull = 470, - Isolation = 471, - Join = 472, - Key = 473, - Label = 474, - Language = 475, - LargeP = 476, - LastP = 477, - LateralP = 478, - Leading = 479, - Leakproof = 480, - Least = 481, - Left = 482, - Level = 483, - Like = 484, - Limit = 485, - Listen = 486, - Load = 487, - Local = 488, - Localtime = 489, - Localtimestamp = 490, - Location = 491, - LockP = 492, - Locked = 493, - Logged = 494, - Mapping = 495, - Match = 496, - Materialized = 497, - Maxvalue = 498, - Method = 499, - MinuteP = 500, - Minvalue = 501, - Mode = 502, - MonthP = 503, - Move = 504, - NameP = 505, - Names = 506, - National = 507, - Natural = 508, - Nchar = 509, - New = 510, - Next = 511, - Nfc = 512, - Nfd = 513, - Nfkc = 514, - Nfkd = 515, - No = 516, - None = 517, - Normalize = 518, - Normalized = 519, - Not = 520, - Nothing = 521, - Notify = 522, - Notnull = 523, - Nowait = 524, - NullP = 525, - Nullif = 526, - NullsP = 527, - Numeric = 528, - ObjectP = 529, - Of = 530, - Off = 531, - Offset = 532, - Oids = 533, - Old = 534, - On = 535, - Only = 536, - Operator = 537, - Option = 538, - Options = 539, - Or = 540, - Order = 541, - Ordinality = 542, - Others = 543, - OutP = 544, - OuterP = 545, - Over = 546, - Overlaps = 547, - Overlay = 548, - Overriding = 549, - Owned = 550, - Owner = 551, - Parallel = 552, - Parser = 553, - Partial = 554, - Partition = 555, - Passing = 556, - Password = 557, - Placing = 558, - Plans = 559, - Policy = 560, - Position = 561, - Preceding = 562, - Precision = 563, - Preserve = 564, - Prepare = 565, - Prepared = 566, - Primary = 567, - Prior = 568, - Privileges = 569, - Procedural = 570, - Procedure = 571, - Procedures = 572, - Program = 573, - Publication = 574, - Quote = 575, - Range = 576, - Read = 577, - Real = 578, - Reassign = 579, - Recheck = 580, - Recursive = 581, - Ref = 582, - References = 583, - Referencing = 584, - Refresh = 585, - Reindex = 586, - RelativeP = 587, - Release = 588, - Rename = 589, - Repeatable = 590, - Replace = 591, - Replica = 592, - Reset = 593, - Restart = 594, - Restrict = 595, - Returning = 596, - Returns = 597, - Revoke = 598, - Right = 599, - Role = 600, - Rollback = 601, - Rollup = 602, - Routine = 603, - Routines = 604, - Row = 605, - Rows = 606, - Rule = 607, - Savepoint = 608, - Schema = 609, - Schemas = 610, - Scroll = 611, - Search = 612, - SecondP = 613, - Security = 614, - Select = 615, - Sequence = 616, - Sequences = 617, - Serializable = 618, - Server = 619, - Session = 620, - SessionUser = 621, - Set = 622, - Sets = 623, - Setof = 624, - Share = 625, - Show = 626, - Similar = 627, - Simple = 628, - Skip = 629, - Smallint = 630, - Snapshot = 631, - Some = 632, - SqlP = 633, - Stable = 634, - StandaloneP = 635, - Start = 636, - Statement = 637, - Statistics = 638, - Stdin = 639, - Stdout = 640, - Storage = 641, - Stored = 642, - StrictP = 643, - StripP = 644, - Subscription = 645, - Substring = 646, - Support = 647, - Symmetric = 648, - Sysid = 649, - SystemP = 650, - Table = 651, - Tables = 652, - Tablesample = 653, - Tablespace = 654, - Temp = 655, - Template = 656, - Temporary = 657, - TextP = 658, - Then = 659, - Ties = 660, - Time = 661, - Timestamp = 662, - To = 663, - Trailing = 664, - Transaction = 665, - Transform = 666, - Treat = 667, - Trigger = 668, - Trim = 669, - TrueP = 670, - Truncate = 671, - Trusted = 672, - TypeP = 673, - TypesP = 674, - Uescape = 675, - Unbounded = 676, - Uncommitted = 677, - Unencrypted = 678, - Union = 679, - Unique = 680, - Unknown = 681, - Unlisten = 682, - Unlogged = 683, - Until = 684, - Update = 685, - User = 686, - Using = 687, - Vacuum = 688, - Valid = 689, - Validate = 690, - Validator = 691, - ValueP = 692, - Values = 693, - Varchar = 694, - Variadic = 695, - Varying = 696, - Verbose = 697, - VersionP = 698, - View = 699, - Views = 700, - Volatile = 701, - When = 702, - Where = 703, - WhitespaceP = 704, - Window = 705, - With = 706, - Within = 707, - Without = 708, - Work = 709, - Wrapper = 710, - Write = 711, - XmlP = 712, - Xmlattributes = 713, - Xmlconcat = 714, - Xmlelement = 715, - Xmlexists = 716, - Xmlforest = 717, - Xmlnamespaces = 718, - Xmlparse = 719, - Xmlpi = 720, - Xmlroot = 721, - Xmlserialize = 722, - Xmltable = 723, - YearP = 724, - YesP = 725, - Zone = 726, - NotLa = 727, - NullsLa = 728, - WithLa = 729, - Postfixop = 730, - Uminus = 731, -} From b3d4fb448c79240785d8ccd78b73d40c59fc5071 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Tue, 21 Jun 2022 19:28:04 -0400 Subject: [PATCH 002/500] Allow `#[ignore]` tests to run in rustfmt's test suite There are some tests in the rustfmt test suite that are ignored by default. I believe these tests are ignored because they have caused issues with the the `rust-lang/rust` test suite. However, we recently experienced an issue (5395) that would have been avoided had these tests been running. With the introduction of the new `#[rustfmt_only_ci_test]` attribute macro we can run these tests when the `RUSTFMT_CI` environment variable is set, which will presumably only be set during rustfmts CI runs. When the environment variable is not set the `#[rustfmt_only_ci_test]` will be replaced with an `#[ignore]`. --- ci/build_and_test.bat | 1 + ci/build_and_test.sh | 1 + config_proc_macro/src/lib.rs | 13 +++++++++++++ tests/cargo-fmt/main.rs | 10 ++++++---- tests/rustfmt/main.rs | 6 ++++-- 5 files changed, 25 insertions(+), 6 deletions(-) diff --git a/ci/build_and_test.bat b/ci/build_and_test.bat index ef41017783feb..69dae1fff7b4d 100755 --- a/ci/build_and_test.bat +++ b/ci/build_and_test.bat @@ -1,4 +1,5 @@ set "RUSTFLAGS=-D warnings" +set "RUSTFMT_CI=1" :: Print version information rustc -Vv || exit /b 1 diff --git a/ci/build_and_test.sh b/ci/build_and_test.sh index 8fa0f67b0d021..94991853263ce 100755 --- a/ci/build_and_test.sh +++ b/ci/build_and_test.sh @@ -3,6 +3,7 @@ set -euo pipefail export RUSTFLAGS="-D warnings" +export RUSTFMT_CI=1 # Print version information rustc -Vv diff --git a/config_proc_macro/src/lib.rs b/config_proc_macro/src/lib.rs index e772c53f42361..0c54c132c97d8 100644 --- a/config_proc_macro/src/lib.rs +++ b/config_proc_macro/src/lib.rs @@ -69,3 +69,16 @@ pub fn stable_only_test(_args: TokenStream, input: TokenStream) -> TokenStream { TokenStream::from_str("").unwrap() } } + +/// Used to conditionally output the TokenStream for tests that should be run as part of rustfmts +/// test suite, but should be ignored when running in the rust-lang/rust test suite. +#[proc_macro_attribute] +pub fn rustfmt_only_ci_test(_args: TokenStream, input: TokenStream) -> TokenStream { + if option_env!("RUSTFMT_CI").is_some() { + input + } else { + let mut token_stream = TokenStream::from_str("#[ignore]").unwrap(); + token_stream.extend(input); + token_stream + } +} diff --git a/tests/cargo-fmt/main.rs b/tests/cargo-fmt/main.rs index 348876cd264fa..5aa4388518b8a 100644 --- a/tests/cargo-fmt/main.rs +++ b/tests/cargo-fmt/main.rs @@ -4,6 +4,8 @@ use std::env; use std::path::Path; use std::process::Command; +use rustfmt_config_proc_macro::rustfmt_only_ci_test; + /// Run the cargo-fmt executable and return its output. fn cargo_fmt(args: &[&str]) -> (String, String) { let mut bin_dir = env::current_exe().unwrap(); @@ -47,7 +49,7 @@ macro_rules! assert_that { }; } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn version() { assert_that!(&["--version"], starts_with("rustfmt ")); @@ -56,7 +58,7 @@ fn version() { assert_that!(&["--", "--version"], starts_with("rustfmt ")); } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn print_config() { assert_that!( @@ -65,7 +67,7 @@ fn print_config() { ); } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn rustfmt_help() { assert_that!(&["--", "--help"], contains("Format Rust code")); @@ -73,7 +75,7 @@ fn rustfmt_help() { assert_that!(&["--", "--help=config"], contains("Configuration Options:")); } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn cargo_fmt_out_of_line_test_modules() { // See also https://github.com/rust-lang/rustfmt/issues/5119 diff --git a/tests/rustfmt/main.rs b/tests/rustfmt/main.rs index 4c6d52726f3fe..636e3053e0f8e 100644 --- a/tests/rustfmt/main.rs +++ b/tests/rustfmt/main.rs @@ -5,6 +5,8 @@ use std::fs::remove_file; use std::path::Path; use std::process::Command; +use rustfmt_config_proc_macro::rustfmt_only_ci_test; + /// Run the rustfmt executable and return its output. fn rustfmt(args: &[&str]) -> (String, String) { let mut bin_dir = env::current_exe().unwrap(); @@ -47,7 +49,7 @@ macro_rules! assert_that { }; } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn print_config() { assert_that!( @@ -76,7 +78,7 @@ fn print_config() { remove_file("minimal-config").unwrap(); } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn inline_config() { // single invocation From 2ae63f0018a7e18deb7ac0063379c2350a631fca Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Fri, 10 Jun 2022 12:17:29 +0100 Subject: [PATCH 003/500] config_type: add unstable_variant attribute --- Cargo.lock | 2 +- Cargo.toml | 2 +- config_proc_macro/Cargo.lock | 2 +- config_proc_macro/Cargo.toml | 2 +- config_proc_macro/src/attrs.rs | 27 +++++-- config_proc_macro/src/item_enum.rs | 40 ++++++++++- config_proc_macro/tests/smoke.rs | 1 + src/config/config_type.rs | 90 ++++++++++++++++++----- src/config/mod.rs | 112 +++++++++++++++++++++++++++-- 9 files changed, 244 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 311df226da19d..e51755289706c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -476,7 +476,7 @@ checksum = "fc71d2faa173b74b232dedc235e3ee1696581bb132fc116fa3626d6151a1a8fb" [[package]] name = "rustfmt-config_proc_macro" -version = "0.2.0" +version = "0.3.0" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 7a4e02d69eddc..7438335eaa78f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,7 +57,7 @@ unicode-segmentation = "1.9" unicode-width = "0.1" unicode_categories = "0.1" -rustfmt-config_proc_macro = { version = "0.2", path = "config_proc_macro" } +rustfmt-config_proc_macro = { version = "0.3", path = "config_proc_macro" } # A noop dependency that changes in the Rust repository, it's a bit of a hack. # See the `src/tools/rustc-workspace-hack/README.md` file in `rust-lang/rust` diff --git a/config_proc_macro/Cargo.lock b/config_proc_macro/Cargo.lock index ecf561f28fb6a..49f2f72a8d219 100644 --- a/config_proc_macro/Cargo.lock +++ b/config_proc_macro/Cargo.lock @@ -22,7 +22,7 @@ dependencies = [ [[package]] name = "rustfmt-config_proc_macro" -version = "0.2.0" +version = "0.3.0" dependencies = [ "proc-macro2", "quote", diff --git a/config_proc_macro/Cargo.toml b/config_proc_macro/Cargo.toml index a41b3a5e6bf88..d10d0469cc401 100644 --- a/config_proc_macro/Cargo.toml +++ b/config_proc_macro/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rustfmt-config_proc_macro" -version = "0.2.0" +version = "0.3.0" edition = "2018" description = "A collection of procedural macros for rustfmt" license = "Apache-2.0/MIT" diff --git a/config_proc_macro/src/attrs.rs b/config_proc_macro/src/attrs.rs index 0baba046f9e91..dd18ff572cb1c 100644 --- a/config_proc_macro/src/attrs.rs +++ b/config_proc_macro/src/attrs.rs @@ -1,8 +1,10 @@ //! This module provides utilities for handling attributes on variants -//! of `config_type` enum. Currently there are two types of attributes -//! that could appear on the variants of `config_type` enum: `doc_hint` -//! and `value`. Both comes in the form of name-value pair whose value -//! is string literal. +//! of `config_type` enum. Currently there are the following attributes +//! that could appear on the variants of `config_type` enum: +//! +//! - `doc_hint`: name-value pair whose value is string literal +//! - `value`: name-value pair whose value is string literal +//! - `unstable_variant`: name only /// Returns the value of the first `doc_hint` attribute in the given slice or /// `None` if `doc_hint` attribute is not available. @@ -27,6 +29,11 @@ pub fn find_config_value(attrs: &[syn::Attribute]) -> Option { attrs.iter().filter_map(config_value).next() } +/// Returns `true` if the there is at least one `unstable` attribute in the given slice. +pub fn any_unstable_variant(attrs: &[syn::Attribute]) -> bool { + attrs.iter().any(is_unstable_variant) +} + /// Returns a string literal value if the given attribute is `value` /// attribute or `None` otherwise. pub fn config_value(attr: &syn::Attribute) -> Option { @@ -38,6 +45,11 @@ pub fn is_config_value(attr: &syn::Attribute) -> bool { is_attr_name_value(attr, "value") } +/// Returns `true` if the given attribute is an `unstable` attribute. +pub fn is_unstable_variant(attr: &syn::Attribute) -> bool { + is_attr_path(attr, "unstable_variant") +} + fn is_attr_name_value(attr: &syn::Attribute, name: &str) -> bool { attr.parse_meta().ok().map_or(false, |meta| match meta { syn::Meta::NameValue(syn::MetaNameValue { ref path, .. }) if path.is_ident(name) => true, @@ -45,6 +57,13 @@ fn is_attr_name_value(attr: &syn::Attribute, name: &str) -> bool { }) } +fn is_attr_path(attr: &syn::Attribute, name: &str) -> bool { + attr.parse_meta().ok().map_or(false, |meta| match meta { + syn::Meta::Path(path) if path.is_ident(name) => true, + _ => false, + }) +} + fn get_name_value_str_lit(attr: &syn::Attribute, name: &str) -> Option { attr.parse_meta().ok().and_then(|meta| match meta { syn::Meta::NameValue(syn::MetaNameValue { diff --git a/config_proc_macro/src/item_enum.rs b/config_proc_macro/src/item_enum.rs index dcee77a8549c5..731a7ea06077b 100644 --- a/config_proc_macro/src/item_enum.rs +++ b/config_proc_macro/src/item_enum.rs @@ -1,5 +1,6 @@ use proc_macro2::TokenStream; -use quote::quote; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; use crate::attrs::*; use crate::utils::*; @@ -47,12 +48,23 @@ fn process_variant(variant: &syn::Variant) -> TokenStream { let metas = variant .attrs .iter() - .filter(|attr| !is_doc_hint(attr) && !is_config_value(attr)); + .filter(|attr| !is_doc_hint(attr) && !is_config_value(attr) && !is_unstable_variant(attr)); let attrs = fold_quote(metas, |meta| quote!(#meta)); let syn::Variant { ident, fields, .. } = variant; quote!(#attrs #ident #fields) } +/// Return the correct syntax to pattern match on the enum variant, discarding all +/// internal field data. +fn fields_in_variant(variant: &syn::Variant) -> TokenStream { + // With thanks to https://stackoverflow.com/a/65182902 + match &variant.fields { + syn::Fields::Unnamed(_) => quote_spanned! { variant.span() => (..) }, + syn::Fields::Unit => quote_spanned! { variant.span() => }, + syn::Fields::Named(_) => quote_spanned! { variant.span() => {..} }, + } +} + fn impl_doc_hint(ident: &syn::Ident, variants: &Variants) -> TokenStream { let doc_hint = variants .iter() @@ -60,12 +72,26 @@ fn impl_doc_hint(ident: &syn::Ident, variants: &Variants) -> TokenStream { .collect::>() .join("|"); let doc_hint = format!("[{}]", doc_hint); + + let variant_stables = variants + .iter() + .map(|v| (&v.ident, fields_in_variant(&v), !unstable_of_variant(v))); + let match_patterns = fold_quote(variant_stables, |(v, fields, stable)| { + quote! { + #ident::#v #fields => #stable, + } + }); quote! { use crate::config::ConfigType; impl ConfigType for #ident { fn doc_hint() -> String { #doc_hint.to_owned() } + fn stable_variant(&self) -> bool { + match self { + #match_patterns + } + } } } } @@ -123,13 +149,21 @@ fn impl_from_str(ident: &syn::Ident, variants: &Variants) -> TokenStream { } fn doc_hint_of_variant(variant: &syn::Variant) -> String { - find_doc_hint(&variant.attrs).unwrap_or(variant.ident.to_string()) + let mut text = find_doc_hint(&variant.attrs).unwrap_or(variant.ident.to_string()); + if unstable_of_variant(&variant) { + text.push_str(" (unstable)") + }; + text } fn config_value_of_variant(variant: &syn::Variant) -> String { find_config_value(&variant.attrs).unwrap_or(variant.ident.to_string()) } +fn unstable_of_variant(variant: &syn::Variant) -> bool { + any_unstable_variant(&variant.attrs) +} + fn impl_serde(ident: &syn::Ident, variants: &Variants) -> TokenStream { let arms = fold_quote(variants.iter(), |v| { let v_ident = &v.ident; diff --git a/config_proc_macro/tests/smoke.rs b/config_proc_macro/tests/smoke.rs index 940a8a0c251e4..c8a83e39c9efc 100644 --- a/config_proc_macro/tests/smoke.rs +++ b/config_proc_macro/tests/smoke.rs @@ -1,6 +1,7 @@ pub mod config { pub trait ConfigType: Sized { fn doc_hint() -> String; + fn stable_variant(&self) -> bool; } } diff --git a/src/config/config_type.rs b/src/config/config_type.rs index e37ed798cb559..26d57a13791a5 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -6,6 +6,14 @@ pub(crate) trait ConfigType: Sized { /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a /// pipe-separated list of variants; for other types it returns "". fn doc_hint() -> String; + + /// Return `true` if the variant (i.e. value of this type) is stable. + /// + /// By default, return true for all values. Enums annotated with `#[config_type]` + /// are automatically implemented, based on the `#[unstable_variant]` annotation. + fn stable_variant(&self) -> bool { + true + } } impl ConfigType for bool { @@ -51,6 +59,13 @@ impl ConfigType for IgnoreList { } macro_rules! create_config { + // Options passed in to the macro. + // + // - $i: the ident name of the option + // - $ty: the type of the option value + // - $def: the default value of the option + // - $stb: true if the option is stable + // - $dstring: description of the option ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => ( #[cfg(test)] use std::collections::HashSet; @@ -61,9 +76,12 @@ macro_rules! create_config { #[derive(Clone)] #[allow(unreachable_pub)] pub struct Config { - // For each config item, we store a bool indicating whether it has - // been accessed and the value, and a bool whether the option was - // manually initialised, or taken from the default, + // For each config item, we store: + // + // - 0: true if the value has been access + // - 1: true if the option was manually initialized + // - 2: the option value + // - 3: true if the option is unstable $($i: (Cell, bool, $ty, bool)),+ } @@ -143,18 +161,13 @@ macro_rules! create_config { fn fill_from_parsed_config(mut self, parsed: PartialConfig, dir: &Path) -> Config { $( - if let Some(val) = parsed.$i { - if self.$i.3 { + if let Some(option_value) = parsed.$i { + let option_stable = self.$i.3; + if $crate::config::config_type::is_stable_option_and_value( + stringify!($i), option_stable, &option_value + ) { self.$i.1 = true; - self.$i.2 = val; - } else { - if crate::is_nightly_channel!() { - self.$i.1 = true; - self.$i.2 = val; - } else { - eprintln!("Warning: can't set `{} = {:?}`, unstable features are only \ - available in nightly channel.", stringify!($i), val); - } + self.$i.2 = option_value; } } )+ @@ -221,12 +234,22 @@ macro_rules! create_config { match key { $( stringify!($i) => { - self.$i.1 = true; - self.$i.2 = val.parse::<$ty>() + let option_value = val.parse::<$ty>() .expect(&format!("Failed to parse override for {} (\"{}\") as a {}", stringify!($i), val, stringify!($ty))); + + // Users are currently allowed to set unstable + // options/variants via the `--config` options override. + // + // There is ongoing discussion about how to move forward here: + // https://github.com/rust-lang/rustfmt/pull/5379 + // + // For now, do not validate whether the option or value is stable, + // just always set it. + self.$i.1 = true; + self.$i.2 = option_value; } )+ _ => panic!("Unknown config key in override: {}", key) @@ -424,3 +447,38 @@ macro_rules! create_config { } ) } + +pub(crate) fn is_stable_option_and_value( + option_name: &str, + option_stable: bool, + option_value: &T, +) -> bool +where + T: PartialEq + std::fmt::Debug + ConfigType, +{ + let nightly = crate::is_nightly_channel!(); + let variant_stable = option_value.stable_variant(); + match (nightly, option_stable, variant_stable) { + // Stable with an unstable option + (false, false, _) => { + eprintln!( + "Warning: can't set `{} = {:?}`, unstable features are only \ + available in nightly channel.", + option_name, option_value + ); + false + } + // Stable with a stable option, but an unstable variant + (false, true, false) => { + eprintln!( + "Warning: can't set `{} = {:?}`, unstable variants are only \ + available in nightly channel.", + option_name, option_value + ); + false + } + // Nightly: everything allowed + // Stable with stable option and variant: allowed + (true, _, _) | (false, true, true) => true, + } +} diff --git a/src/config/mod.rs b/src/config/mod.rs index f49c18d3a4603..eaada8db090a8 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -408,6 +408,15 @@ mod test { #[allow(dead_code)] mod mock { use super::super::*; + use rustfmt_config_proc_macro::config_type; + + #[config_type] + pub enum PartiallyUnstableOption { + V1, + V2, + #[unstable_variant] + V3, + } create_config! { // Options that are used by the generated functions @@ -451,6 +460,63 @@ mod test { // Options that are used by the tests stable_option: bool, false, true, "A stable option"; unstable_option: bool, false, false, "An unstable option"; + partially_unstable_option: PartiallyUnstableOption, PartiallyUnstableOption::V1, true, + "A partially unstable option"; + } + + #[cfg(test)] + mod partially_unstable_option { + use super::{Config, PartialConfig, PartiallyUnstableOption}; + use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test}; + use std::path::Path; + + /// From the config file, we can fill with a stable variant + #[test] + fn test_from_toml_stable_value() { + let toml = r#" + partially_unstable_option = "V2" + "#; + let partial_config: PartialConfig = toml::from_str(toml).unwrap(); + let config = Config::default(); + let config = config.fill_from_parsed_config(partial_config, Path::new("")); + assert_eq!( + config.partially_unstable_option(), + PartiallyUnstableOption::V2 + ); + } + + /// From the config file, we cannot fill with an unstable variant (stable only) + #[stable_only_test] + #[test] + fn test_from_toml_unstable_value_on_stable() { + let toml = r#" + partially_unstable_option = "V3" + "#; + let partial_config: PartialConfig = toml::from_str(toml).unwrap(); + let config = Config::default(); + let config = config.fill_from_parsed_config(partial_config, Path::new("")); + assert_eq!( + config.partially_unstable_option(), + // default value from config, i.e. fill failed + PartiallyUnstableOption::V1 + ); + } + + /// From the config file, we can fill with an unstable variant (nightly only) + #[nightly_only_test] + #[test] + fn test_from_toml_unstable_value_on_nightly() { + let toml = r#" + partially_unstable_option = "V3" + "#; + let partial_config: PartialConfig = toml::from_str(toml).unwrap(); + let config = Config::default(); + let config = config.fill_from_parsed_config(partial_config, Path::new("")); + assert_eq!( + config.partially_unstable_option(), + PartiallyUnstableOption::V3 + ); + } } } @@ -489,6 +555,11 @@ mod test { assert_eq!(config.was_set().verbose(), false); } + const PRINT_DOCS_STABLE_OPTION: &str = "stable_option Default: false"; + const PRINT_DOCS_UNSTABLE_OPTION: &str = "unstable_option Default: false (unstable)"; + const PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION: &str = + "partially_unstable_option [V1|V2|V3 (unstable)] Default: V1"; + #[test] fn test_print_docs_exclude_unstable() { use self::mock::Config; @@ -497,10 +568,9 @@ mod test { Config::print_docs(&mut output, false); let s = str::from_utf8(&output).unwrap(); - - assert_eq!(s.contains("stable_option"), true); - assert_eq!(s.contains("unstable_option"), false); - assert_eq!(s.contains("(unstable)"), false); + assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true); + assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), false); + assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true); } #[test] @@ -511,9 +581,9 @@ mod test { Config::print_docs(&mut output, true); let s = str::from_utf8(&output).unwrap(); - assert_eq!(s.contains("stable_option"), true); - assert_eq!(s.contains("unstable_option"), true); - assert_eq!(s.contains("(unstable)"), true); + assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true); + assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), true); + assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true); } #[test] @@ -921,4 +991,32 @@ make_backup = false assert_eq!(config.single_line_if_else_max_width(), 100); } } + + #[cfg(test)] + mod partially_unstable_option { + use super::mock::{Config, PartiallyUnstableOption}; + use super::*; + + /// From the command line, we can override with a stable variant. + #[test] + fn test_override_stable_value() { + let mut config = Config::default(); + config.override_value("partially_unstable_option", "V2"); + assert_eq!( + config.partially_unstable_option(), + PartiallyUnstableOption::V2 + ); + } + + /// From the command line, we can override with an unstable variant. + #[test] + fn test_override_unstable_value() { + let mut config = Config::default(); + config.override_value("partially_unstable_option", "V3"); + assert_eq!( + config.partially_unstable_option(), + PartiallyUnstableOption::V3 + ); + } + } } From 45f4f6ccf7fbccd81db84f2a7ee7881884668ab2 Mon Sep 17 00:00:00 2001 From: Nixon Enraght-Moony Date: Sat, 2 Jul 2022 18:25:55 +0100 Subject: [PATCH 004/500] ast: Add span to `Extern` --- src/items.rs | 2 +- src/utils.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/items.rs b/src/items.rs index bab881f4b4e8d..8f35068e35f04 100644 --- a/src/items.rs +++ b/src/items.rs @@ -148,7 +148,7 @@ impl<'a> Item<'a> { Item { unsafety: fm.unsafety, abi: format_extern( - ast::Extern::from_abi(fm.abi), + ast::Extern::from_abi(fm.abi, DUMMY_SP), config.force_explicit_abi(), true, ), diff --git a/src/utils.rs b/src/utils.rs index 58fd95c656e79..4b26f4e40df98 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -138,8 +138,8 @@ pub(crate) fn format_extern( ) -> Cow<'static, str> { let abi = match ext { ast::Extern::None => "Rust".to_owned(), - ast::Extern::Implicit => "C".to_owned(), - ast::Extern::Explicit(abi) => abi.symbol_unescaped.to_string(), + ast::Extern::Implicit(_) => "C".to_owned(), + ast::Extern::Explicit(abi, _) => abi.symbol_unescaped.to_string(), }; if abi == "Rust" && !is_mod { From 35f4c55bf476884feadf525e110453f6815f8dd8 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sun, 3 Jul 2022 22:09:42 -0500 Subject: [PATCH 005/500] refactor: remove some unnecessary clones --- src/chains.rs | 21 ++++++++++----------- src/expr.rs | 9 ++++----- src/macros.rs | 15 +++++++-------- src/utils.rs | 5 +++-- 4 files changed, 24 insertions(+), 26 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index e26e24ec55ad6..5bccb22db4c17 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -70,8 +70,8 @@ use crate::rewrite::{Rewrite, RewriteContext}; use crate::shape::Shape; use crate::source_map::SpanUtils; use crate::utils::{ - self, first_line_width, last_line_extendable, last_line_width, mk_sp, rewrite_ident, - trimmed_last_line_width, wrap_str, + self, filtered_str_fits, first_line_width, last_line_extendable, last_line_width, mk_sp, + rewrite_ident, trimmed_last_line_width, wrap_str, }; pub(crate) fn rewrite_chain( @@ -810,15 +810,14 @@ impl<'a> ChainFormatter for ChainFormatterVisual<'a> { .visual_indent(self.offset) .sub_width(self.offset)?; let rewrite = item.rewrite(context, child_shape)?; - match wrap_str(rewrite, context.config.max_width(), shape) { - Some(rewrite) => root_rewrite.push_str(&rewrite), - None => { - // We couldn't fit in at the visual indent, try the last - // indent. - let rewrite = item.rewrite(context, parent_shape)?; - root_rewrite.push_str(&rewrite); - self.offset = 0; - } + if filtered_str_fits(&rewrite, context.config.max_width(), shape) { + root_rewrite.push_str(&rewrite); + } else { + // We couldn't fit in at the visual indent, try the last + // indent. + let rewrite = item.rewrite(context, parent_shape)?; + root_rewrite.push_str(&rewrite); + self.offset = 0; } self.shared.children = &self.shared.children[1..]; diff --git a/src/expr.rs b/src/expr.rs index e4cc93026f10b..13d068d0c2dd5 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -29,9 +29,9 @@ use crate::spanned::Spanned; use crate::string::{rewrite_string, StringFormat}; use crate::types::{rewrite_path, PathContext}; use crate::utils::{ - colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes, - last_line_extendable, last_line_width, mk_sp, outer_attributes, semicolon_for_expr, - unicode_str_width, wrap_str, + colon_spaces, contains_skip, count_newlines, filtered_str_fits, first_line_ends_with, + inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes, + semicolon_for_expr, unicode_str_width, wrap_str, }; use crate::vertical::rewrite_with_alignment; use crate::visitor::FmtVisitor; @@ -2037,8 +2037,7 @@ fn choose_rhs( match (orig_rhs, new_rhs) { (Some(ref orig_rhs), Some(ref new_rhs)) - if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape) - .is_none() => + if !filtered_str_fits(&new_rhs, context.config.max_width(), new_shape) => { Some(format!("{}{}", before_space_str, orig_rhs)) } diff --git a/src/macros.rs b/src/macros.rs index f4b2bcf281577..e78ef1f806678 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -35,8 +35,8 @@ use crate::shape::{Indent, Shape}; use crate::source_map::SpanUtils; use crate::spanned::Spanned; use crate::utils::{ - format_visibility, indent_next_line, is_empty_line, mk_sp, remove_trailing_white_spaces, - rewrite_ident, trim_left_preserve_layout, wrap_str, NodeIdExt, + filtered_str_fits, format_visibility, indent_next_line, is_empty_line, mk_sp, + remove_trailing_white_spaces, rewrite_ident, trim_left_preserve_layout, NodeIdExt, }; use crate::visitor::FmtVisitor; @@ -1241,15 +1241,14 @@ impl MacroBranch { } } }; - let new_body = wrap_str( - new_body_snippet.snippet.to_string(), - config.max_width(), - shape, - )?; + + if !filtered_str_fits(&new_body_snippet.snippet, config.max_width(), shape) { + return None; + } // Indent the body since it is in a block. let indent_str = body_indent.to_string(&config); - let mut new_body = LineClasses::new(new_body.trim_end()) + let mut new_body = LineClasses::new(new_body_snippet.snippet.trim_end()) .enumerate() .fold( (String::new(), true), diff --git a/src/utils.rs b/src/utils.rs index 58fd95c656e79..0e87d6bb50e2d 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -384,14 +384,15 @@ macro_rules! skip_out_of_file_lines_range_visitor { // Wraps String in an Option. Returns Some when the string adheres to the // Rewrite constraints defined for the Rewrite trait and None otherwise. pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option { - if is_valid_str(&filter_normal_code(&s), max_width, shape) { + if filtered_str_fits(&s, max_width, shape) { Some(s) } else { None } } -fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool { +pub(crate) fn filtered_str_fits(snippet: &str, max_width: usize, shape: Shape) -> bool { + let snippet = &filter_normal_code(snippet); if !snippet.is_empty() { // First line must fits with `shape.width`. if first_line_width(snippet) > shape.width { From 2403f827bf1e427a04ce45c88a64cbebe91041d7 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Sat, 9 Jul 2022 17:54:59 -0400 Subject: [PATCH 006/500] Add test case for issue 1306 which was resolved Closes 1306 It's unclear when the issue was fixed, but it cannot be reproduced. --- tests/source/issue_1306.rs | 29 +++++++++++++++++++++++++++++ tests/target/issue_1306.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 tests/source/issue_1306.rs create mode 100644 tests/target/issue_1306.rs diff --git a/tests/source/issue_1306.rs b/tests/source/issue_1306.rs new file mode 100644 index 0000000000000..03b78e34108cc --- /dev/null +++ b/tests/source/issue_1306.rs @@ -0,0 +1,29 @@ +// rustfmt-max_width: 160 +// rustfmt-fn_call_width: 96 +// rustfmt-fn_args_layout: Compressed +// rustfmt-trailing_comma: Always +// rustfmt-wrap_comments: true + +fn foo() { + for elem in try!(gen_epub_book::ops::parse_descriptor_file(&mut try!(File::open(&opts.source_file.1).map_err(|_| { + gen_epub_book::Error::Io { + desc: "input file", + op: "open", + more: None, + } + })), + "input file")) { + println!("{}", elem); + } +} + +fn write_content() { + io::copy(try!(File::open(in_f).map_err(|_| { + Error::Io { + desc: "Content", + op: "open", + more: None, + } + })), + w); +} diff --git a/tests/target/issue_1306.rs b/tests/target/issue_1306.rs new file mode 100644 index 0000000000000..6bb514cdfe550 --- /dev/null +++ b/tests/target/issue_1306.rs @@ -0,0 +1,33 @@ +// rustfmt-max_width: 160 +// rustfmt-fn_call_width: 96 +// rustfmt-fn_args_layout: Compressed +// rustfmt-trailing_comma: Always +// rustfmt-wrap_comments: true + +fn foo() { + for elem in try!(gen_epub_book::ops::parse_descriptor_file( + &mut try!(File::open(&opts.source_file.1).map_err(|_| { + gen_epub_book::Error::Io { + desc: "input file", + op: "open", + more: None, + } + })), + "input file" + )) { + println!("{}", elem); + } +} + +fn write_content() { + io::copy( + try!(File::open(in_f).map_err(|_| { + Error::Io { + desc: "Content", + op: "open", + more: None, + } + })), + w, + ); +} From 2964d0a5332fb0fd4d2c056ee9b651215b99b027 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Thu, 30 Jun 2022 17:40:38 +0400 Subject: [PATCH 007/500] implement rustfmt formatting for `for<>` closure binders --- src/closures.rs | 33 +++++++++++++++++++++++++++------ src/expr.rs | 16 +++++++++++----- src/types.rs | 2 +- src/utils.rs | 2 +- 4 files changed, 40 insertions(+), 13 deletions(-) diff --git a/src/closures.rs b/src/closures.rs index e688db1c39d7c..88a6bebb68c84 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -11,6 +11,7 @@ use crate::overflow::OverflowableItem; use crate::rewrite::{Rewrite, RewriteContext}; use crate::shape::Shape; use crate::source_map::SpanUtils; +use crate::types::rewrite_lifetime_param; use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt}; // This module is pretty messy because of the rules around closures and blocks: @@ -24,6 +25,7 @@ use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt}; // can change whether it is treated as an expression or statement. pub(crate) fn rewrite_closure( + binder: &ast::ClosureBinder, capture: ast::CaptureBy, is_async: &ast::Async, movability: ast::Movability, @@ -36,7 +38,7 @@ pub(crate) fn rewrite_closure( debug!("rewrite_closure {:?}", body); let (prefix, extra_offset) = rewrite_closure_fn_decl( - capture, is_async, movability, fn_decl, body, span, context, shape, + binder, capture, is_async, movability, fn_decl, body, span, context, shape, )?; // 1 = space between `|...|` and body. let body_shape = shape.offset_left(extra_offset)?; @@ -227,6 +229,7 @@ fn rewrite_closure_block( // Return type is (prefix, extra_offset) fn rewrite_closure_fn_decl( + binder: &ast::ClosureBinder, capture: ast::CaptureBy, asyncness: &ast::Async, movability: ast::Movability, @@ -236,6 +239,17 @@ fn rewrite_closure_fn_decl( context: &RewriteContext<'_>, shape: Shape, ) -> Option<(String, usize)> { + let binder = match binder { + ast::ClosureBinder::For { generic_params, .. } if generic_params.is_empty() => { + "for<> ".to_owned() + } + ast::ClosureBinder::For { generic_params, .. } => { + let lifetime_str = rewrite_lifetime_param(context, shape, generic_params)?; + format!("for<{lifetime_str}> ") + } + ast::ClosureBinder::NotPresent => "".to_owned(), + }; + let immovable = if movability == ast::Movability::Static { "static " } else { @@ -250,7 +264,7 @@ fn rewrite_closure_fn_decl( // 4 = "|| {".len(), which is overconservative when the closure consists of // a single expression. let nested_shape = shape - .shrink_left(immovable.len() + is_async.len() + mover.len())? + .shrink_left(binder.len() + immovable.len() + is_async.len() + mover.len())? .sub_width(4)?; // 1 = | @@ -288,7 +302,7 @@ fn rewrite_closure_fn_decl( .tactic(tactic) .preserve_newline(true); let list_str = write_list(&item_vec, &fmt)?; - let mut prefix = format!("{}{}{}|{}|", immovable, is_async, mover, list_str); + let mut prefix = format!("{}{}{}{}|{}|", binder, immovable, is_async, mover, list_str); if !ret_str.is_empty() { if prefix.contains('\n') { @@ -312,8 +326,15 @@ pub(crate) fn rewrite_last_closure( expr: &ast::Expr, shape: Shape, ) -> Option { - if let ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) = - expr.kind + if let ast::ExprKind::Closure( + ref binder, + capture, + ref is_async, + movability, + ref fn_decl, + ref body, + _, + ) = expr.kind { let body = match body.kind { ast::ExprKind::Block(ref block, _) @@ -326,7 +347,7 @@ pub(crate) fn rewrite_last_closure( _ => body, }; let (prefix, extra_offset) = rewrite_closure_fn_decl( - capture, is_async, movability, fn_decl, body, expr.span, context, shape, + binder, capture, is_async, movability, fn_decl, body, expr.span, context, shape, )?; // If the closure goes multi line before its body, do not overflow the closure. if prefix.contains('\n') { diff --git a/src/expr.rs b/src/expr.rs index e4cc93026f10b..a7b73ba78c59e 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -203,11 +203,17 @@ pub(crate) fn format_expr( Some("yield".to_string()) } } - ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => { - closures::rewrite_closure( - capture, is_async, movability, fn_decl, body, expr.span, context, shape, - ) - } + ast::ExprKind::Closure( + ref binder, + capture, + ref is_async, + movability, + ref fn_decl, + ref body, + _, + ) => closures::rewrite_closure( + binder, capture, is_async, movability, fn_decl, body, expr.span, context, shape, + ), ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) diff --git a/src/types.rs b/src/types.rs index 64a201e45ddd4..2627886db109d 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1067,7 +1067,7 @@ pub(crate) fn can_be_overflowed_type( } /// Returns `None` if there is no `LifetimeDef` in the given generic parameters. -fn rewrite_lifetime_param( +pub(crate) fn rewrite_lifetime_param( context: &RewriteContext<'_>, shape: Shape, generic_params: &[ast::GenericParam], diff --git a/src/utils.rs b/src/utils.rs index 4b26f4e40df98..cd852855602e8 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -479,7 +479,7 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Binary(_, _, ref expr) | ast::ExprKind::Index(_, ref expr) | ast::ExprKind::Unary(_, ref expr) - | ast::ExprKind::Closure(_, _, _, _, ref expr, _) + | ast::ExprKind::Closure(_, _, _, _, _, ref expr, _) | ast::ExprKind::Try(ref expr) | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr), // This can only be a string lit From f026688c2abd95fdfabe50ace0a422004d4c47d5 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Sun, 3 Jul 2022 16:11:46 +0400 Subject: [PATCH 008/500] Add rustfmt test for formatting `for<>` before closures --- tests/source/closure.rs | 10 ++++++++++ tests/target/closure.rs | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/tests/source/closure.rs b/tests/source/closure.rs index e93cc3fb40f59..b2d28b305d0ad 100644 --- a/tests/source/closure.rs +++ b/tests/source/closure.rs @@ -51,6 +51,16 @@ fn main() { "--emit=dep-info" } else { a } }); + + for<> || -> () {}; + for< >|| -> () {}; + for< +> || -> () {}; + +for< 'a + ,'b, +'c > |_: &'a (), _: &'b (), _: &'c ()| -> () {}; + } fn issue311() { diff --git a/tests/target/closure.rs b/tests/target/closure.rs index f3107d19c2fbf..e8b4ff7a96bb8 100644 --- a/tests/target/closure.rs +++ b/tests/target/closure.rs @@ -71,6 +71,12 @@ fn main() { a } }); + + for<> || -> () {}; + for<> || -> () {}; + for<> || -> () {}; + + for<'a, 'b, 'c> |_: &'a (), _: &'b (), _: &'c ()| -> () {}; } fn issue311() { From c240f3a6b3f0b7f91113dc999217f40f029a2776 Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Wed, 13 Jul 2022 01:31:19 +0100 Subject: [PATCH 009/500] feat: add skip_macro_invocations option (#5347) * feat: add skip_macro_names option * [review] update configuration documentation * [review] fix docstring * [feat] implement wildcard macro invocation skip * commit missed files * [review] test override skip macro names * [review] skip_macro_names -> skip_macro_invocations * [review] expand doc configuration * [review] add lots more tests * [review] add use alias test examples * [review] add link to standard macro behaviour --- Configurations.md | 56 +++++++++ src/config/config_type.rs | 7 ++ src/config/macro_names.rs | 118 ++++++++++++++++++ src/config/mod.rs | 20 +++ src/skip.rs | 10 +- src/test/configuration_snippet.rs | 7 +- src/visitor.rs | 13 +- tests/source/skip_macro_invocations/all.rs | 11 ++ .../skip_macro_invocations/all_and_name.rs | 11 ++ tests/source/skip_macro_invocations/empty.rs | 11 ++ tests/source/skip_macro_invocations/name.rs | 11 ++ .../skip_macro_invocations/name_unknown.rs | 6 + tests/source/skip_macro_invocations/names.rs | 16 +++ .../path_qualified_invocation_mismatch.rs | 6 + .../path_qualified_match.rs | 6 + .../path_qualified_name_mismatch.rs | 6 + .../use_alias_examples.rs | 32 +++++ tests/target/skip_macro_invocations/all.rs | 11 ++ .../skip_macro_invocations/all_and_name.rs | 11 ++ tests/target/skip_macro_invocations/empty.rs | 11 ++ tests/target/skip_macro_invocations/name.rs | 11 ++ .../skip_macro_invocations/name_unknown.rs | 6 + tests/target/skip_macro_invocations/names.rs | 16 +++ .../path_qualified_invocation_mismatch.rs | 6 + .../path_qualified_match.rs | 6 + .../path_qualified_name_mismatch.rs | 6 + .../use_alias_examples.rs | 32 +++++ 27 files changed, 459 insertions(+), 4 deletions(-) create mode 100644 src/config/macro_names.rs create mode 100644 tests/source/skip_macro_invocations/all.rs create mode 100644 tests/source/skip_macro_invocations/all_and_name.rs create mode 100644 tests/source/skip_macro_invocations/empty.rs create mode 100644 tests/source/skip_macro_invocations/name.rs create mode 100644 tests/source/skip_macro_invocations/name_unknown.rs create mode 100644 tests/source/skip_macro_invocations/names.rs create mode 100644 tests/source/skip_macro_invocations/path_qualified_invocation_mismatch.rs create mode 100644 tests/source/skip_macro_invocations/path_qualified_match.rs create mode 100644 tests/source/skip_macro_invocations/path_qualified_name_mismatch.rs create mode 100644 tests/source/skip_macro_invocations/use_alias_examples.rs create mode 100644 tests/target/skip_macro_invocations/all.rs create mode 100644 tests/target/skip_macro_invocations/all_and_name.rs create mode 100644 tests/target/skip_macro_invocations/empty.rs create mode 100644 tests/target/skip_macro_invocations/name.rs create mode 100644 tests/target/skip_macro_invocations/name_unknown.rs create mode 100644 tests/target/skip_macro_invocations/names.rs create mode 100644 tests/target/skip_macro_invocations/path_qualified_invocation_mismatch.rs create mode 100644 tests/target/skip_macro_invocations/path_qualified_match.rs create mode 100644 tests/target/skip_macro_invocations/path_qualified_name_mismatch.rs create mode 100644 tests/target/skip_macro_invocations/use_alias_examples.rs diff --git a/Configurations.md b/Configurations.md index 8b96b9d36892a..5579b5095afac 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1014,6 +1014,62 @@ macro_rules! foo { See also [`format_macro_matchers`](#format_macro_matchers). +## `skip_macro_invocations` + +Skip formatting the bodies of macro invocations with the following names. + +rustfmt will not format any macro invocation for macros with names set in this list. +Including the special value "*" will prevent any macro invocations from being formatted. + +Note: This option does not have any impact on how rustfmt formats macro definitions. + +- **Default value**: `[]` +- **Possible values**: a list of macro name idents, `["name_0", "name_1", ..., "*"]` +- **Stable**: No (tracking issue: [#5346](https://github.com/rust-lang/rustfmt/issues/5346)) + +#### `[]` (default): + +rustfmt will follow its standard approach to formatting macro invocations. + +No macro invocations will be skipped based on their name. More information about rustfmt's standard macro invocation formatting behavior can be found in [#5437](https://github.com/rust-lang/rustfmt/discussions/5437). + +```rust +lorem!( + const _: u8 = 0; +); + +ipsum!( + const _: u8 = 0; +); +``` + +#### `["lorem"]`: + +The named macro invocations will be skipped. + +```rust +lorem!( + const _: u8 = 0; +); + +ipsum!( + const _: u8 = 0; +); +``` + +#### `["*"]`: + +The special selector `*` will skip all macro invocations. + +```rust +lorem!( + const _: u8 = 0; +); + +ipsum!( + const _: u8 = 0; +); +``` ## `format_strings` diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 26d57a13791a5..48f4d9ce80e40 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -1,4 +1,5 @@ use crate::config::file_lines::FileLines; +use crate::config::macro_names::MacroSelectors; use crate::config::options::{IgnoreList, WidthHeuristics}; /// Trait for types that can be used in `Config`. @@ -46,6 +47,12 @@ impl ConfigType for FileLines { } } +impl ConfigType for MacroSelectors { + fn doc_hint() -> String { + String::from("[, ...]") + } +} + impl ConfigType for WidthHeuristics { fn doc_hint() -> String { String::new() diff --git a/src/config/macro_names.rs b/src/config/macro_names.rs new file mode 100644 index 0000000000000..26ad78d6dcae8 --- /dev/null +++ b/src/config/macro_names.rs @@ -0,0 +1,118 @@ +//! This module contains types and functions to support formatting specific macros. + +use itertools::Itertools; +use std::{fmt, str}; + +use serde::{Deserialize, Serialize}; +use serde_json as json; +use thiserror::Error; + +/// Defines the name of a macro. +#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Deserialize, Serialize)] +pub struct MacroName(String); + +impl MacroName { + pub fn new(other: String) -> Self { + Self(other) + } +} + +impl fmt::Display for MacroName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +impl From for String { + fn from(other: MacroName) -> Self { + other.0 + } +} + +/// Defines a selector to match against a macro. +#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Deserialize, Serialize)] +pub enum MacroSelector { + Name(MacroName), + All, +} + +impl fmt::Display for MacroSelector { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Name(name) => name.fmt(f), + Self::All => write!(f, "*"), + } + } +} + +impl str::FromStr for MacroSelector { + type Err = std::convert::Infallible; + + fn from_str(s: &str) -> Result { + Ok(match s { + "*" => MacroSelector::All, + name => MacroSelector::Name(MacroName(name.to_owned())), + }) + } +} + +/// A set of macro selectors. +#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)] +pub struct MacroSelectors(pub Vec); + +impl fmt::Display for MacroSelectors { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0.iter().format(", ")) + } +} + +#[derive(Error, Debug)] +pub enum MacroSelectorsError { + #[error("{0}")] + Json(json::Error), +} + +// This impl is needed for `Config::override_value` to work for use in tests. +impl str::FromStr for MacroSelectors { + type Err = MacroSelectorsError; + + fn from_str(s: &str) -> Result { + let raw: Vec<&str> = json::from_str(s).map_err(MacroSelectorsError::Json)?; + Ok(Self( + raw.into_iter() + .map(|raw| { + MacroSelector::from_str(raw).expect("MacroSelector from_str is infallible") + }) + .collect(), + )) + } +} + +#[cfg(test)] +mod test { + use super::*; + use std::str::FromStr; + + #[test] + fn macro_names_from_str() { + let macro_names = MacroSelectors::from_str(r#"["foo", "*", "bar"]"#).unwrap(); + assert_eq!( + macro_names, + MacroSelectors( + [ + MacroSelector::Name(MacroName("foo".to_owned())), + MacroSelector::All, + MacroSelector::Name(MacroName("bar".to_owned())) + ] + .into_iter() + .collect() + ) + ); + } + + #[test] + fn macro_names_display() { + let macro_names = MacroSelectors::from_str(r#"["foo", "*", "bar"]"#).unwrap(); + assert_eq!(format!("{}", macro_names), "foo, *, bar"); + } +} diff --git a/src/config/mod.rs b/src/config/mod.rs index eaada8db090a8..0c6a3cbc9532a 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -13,6 +13,8 @@ pub use crate::config::file_lines::{FileLines, FileName, Range}; #[allow(unreachable_pub)] pub use crate::config::lists::*; #[allow(unreachable_pub)] +pub use crate::config::macro_names::{MacroSelector, MacroSelectors}; +#[allow(unreachable_pub)] pub use crate::config::options::*; #[macro_use] @@ -22,6 +24,7 @@ pub(crate) mod options; pub(crate) mod file_lines; pub(crate) mod lists; +pub(crate) mod macro_names; // This macro defines configuration options used in rustfmt. Each option // is defined as follows: @@ -67,6 +70,8 @@ create_config! { format_macro_matchers: bool, false, false, "Format the metavariable matching patterns in macros"; format_macro_bodies: bool, true, false, "Format the bodies of macros"; + skip_macro_invocations: MacroSelectors, MacroSelectors::default(), false, + "Skip formatting the bodies of macros invoked with the following names."; hex_literal_case: HexLiteralCase, HexLiteralCase::Preserve, false, "Format hexadecimal integer literals"; @@ -403,6 +408,7 @@ mod test { use super::*; use std::str; + use crate::config::macro_names::MacroName; use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test}; #[allow(dead_code)] @@ -611,6 +617,7 @@ normalize_doc_attributes = false format_strings = false format_macro_matchers = false format_macro_bodies = true +skip_macro_invocations = [] hex_literal_case = "Preserve" empty_item_single_line = true struct_lit_single_line = true @@ -1019,4 +1026,17 @@ make_backup = false ); } } + + #[test] + fn test_override_skip_macro_invocations() { + let mut config = Config::default(); + config.override_value("skip_macro_invocations", r#"["*", "println"]"#); + assert_eq!( + config.skip_macro_invocations(), + MacroSelectors(vec![ + MacroSelector::All, + MacroSelector::Name(MacroName::new("println".to_owned())) + ]) + ); + } } diff --git a/src/skip.rs b/src/skip.rs index 0fdc097efc23f..8b2fd7736ae51 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -7,6 +7,7 @@ use rustc_ast_pretty::pprust; /// by other context. Query this context to know if you need skip a block. #[derive(Default, Clone)] pub(crate) struct SkipContext { + pub(crate) all_macros: bool, macros: Vec, attributes: Vec, } @@ -23,8 +24,15 @@ impl SkipContext { self.attributes.append(&mut other.attributes); } + pub(crate) fn update_macros(&mut self, other: T) + where + T: IntoIterator, + { + self.macros.extend(other.into_iter()); + } + pub(crate) fn skip_macro(&self, name: &str) -> bool { - self.macros.iter().any(|n| n == name) + self.all_macros || self.macros.iter().any(|n| n == name) } pub(crate) fn skip_attribute(&self, name: &str) -> bool { diff --git a/src/test/configuration_snippet.rs b/src/test/configuration_snippet.rs index c8fda7c8556db..c70b3c5facd50 100644 --- a/src/test/configuration_snippet.rs +++ b/src/test/configuration_snippet.rs @@ -27,8 +27,13 @@ impl ConfigurationSection { lazy_static! { static ref CONFIG_NAME_REGEX: regex::Regex = regex::Regex::new(r"^## `([^`]+)`").expect("failed creating configuration pattern"); + // Configuration values, which will be passed to `from_str`: + // + // - must be prefixed with `####` + // - must be wrapped in backticks + // - may by wrapped in double quotes (which will be stripped) static ref CONFIG_VALUE_REGEX: regex::Regex = - regex::Regex::new(r#"^#### `"?([^`"]+)"?`"#) + regex::Regex::new(r#"^#### `"?([^`]+?)"?`"#) .expect("failed creating configuration value pattern"); } diff --git a/src/visitor.rs b/src/visitor.rs index 9a0e0752c12f5..b93153de154a8 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -8,7 +8,7 @@ use rustc_span::{symbol, BytePos, Pos, Span}; use crate::attr::*; use crate::comment::{contains_comment, rewrite_comment, CodeCharKind, CommentCodeSlices}; use crate::config::Version; -use crate::config::{BraceStyle, Config}; +use crate::config::{BraceStyle, Config, MacroSelector}; use crate::coverage::transform_missing_snippet; use crate::items::{ format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item, rewrite_extern_crate, @@ -770,6 +770,15 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { snippet_provider: &'a SnippetProvider, report: FormatReport, ) -> FmtVisitor<'a> { + let mut skip_context = SkipContext::default(); + let mut macro_names = Vec::new(); + for macro_selector in config.skip_macro_invocations().0 { + match macro_selector { + MacroSelector::Name(name) => macro_names.push(name.to_string()), + MacroSelector::All => skip_context.all_macros = true, + } + } + skip_context.update_macros(macro_names); FmtVisitor { parent_context: None, parse_sess: parse_session, @@ -784,7 +793,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { is_macro_def: false, macro_rewrite_failure: false, report, - skip_context: Default::default(), + skip_context, } } diff --git a/tests/source/skip_macro_invocations/all.rs b/tests/source/skip_macro_invocations/all.rs new file mode 100644 index 0000000000000..d0437ee10fd15 --- /dev/null +++ b/tests/source/skip_macro_invocations/all.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["*"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/all_and_name.rs b/tests/source/skip_macro_invocations/all_and_name.rs new file mode 100644 index 0000000000000..1f6722344fe3b --- /dev/null +++ b/tests/source/skip_macro_invocations/all_and_name.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["*","items"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should also skip this invocation, as the wildcard covers it +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/empty.rs b/tests/source/skip_macro_invocations/empty.rs new file mode 100644 index 0000000000000..f3dd89dc4db33 --- /dev/null +++ b/tests/source/skip_macro_invocations/empty.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: [] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); + +// Should not skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/name.rs b/tests/source/skip_macro_invocations/name.rs new file mode 100644 index 0000000000000..7fa5d3a6f715a --- /dev/null +++ b/tests/source/skip_macro_invocations/name.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["items"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should not skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/name_unknown.rs b/tests/source/skip_macro_invocations/name_unknown.rs new file mode 100644 index 0000000000000..d56695325240d --- /dev/null +++ b/tests/source/skip_macro_invocations/name_unknown.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["unknown"] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/names.rs b/tests/source/skip_macro_invocations/names.rs new file mode 100644 index 0000000000000..a920381a4552c --- /dev/null +++ b/tests/source/skip_macro_invocations/names.rs @@ -0,0 +1,16 @@ +// rustfmt-skip_macro_invocations: ["foo","bar"] + +// Should skip this invocation +foo!( + const _: u8 = 0; +); + +// Should skip this invocation +bar!( + const _: u8 = 0; +); + +// Should not skip this invocation +baz!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/path_qualified_invocation_mismatch.rs b/tests/source/skip_macro_invocations/path_qualified_invocation_mismatch.rs new file mode 100644 index 0000000000000..61296869a5065 --- /dev/null +++ b/tests/source/skip_macro_invocations/path_qualified_invocation_mismatch.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["items"] + +// Should not skip this invocation +self::items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/path_qualified_match.rs b/tests/source/skip_macro_invocations/path_qualified_match.rs new file mode 100644 index 0000000000000..9398918a9e11e --- /dev/null +++ b/tests/source/skip_macro_invocations/path_qualified_match.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["self::items"] + +// Should skip this invocation +self::items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/path_qualified_name_mismatch.rs b/tests/source/skip_macro_invocations/path_qualified_name_mismatch.rs new file mode 100644 index 0000000000000..4e3eb542dbea4 --- /dev/null +++ b/tests/source/skip_macro_invocations/path_qualified_name_mismatch.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["self::items"] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/use_alias_examples.rs b/tests/source/skip_macro_invocations/use_alias_examples.rs new file mode 100644 index 0000000000000..43cb8015de58a --- /dev/null +++ b/tests/source/skip_macro_invocations/use_alias_examples.rs @@ -0,0 +1,32 @@ +// rustfmt-skip_macro_invocations: ["aaa","ccc"] + +// These tests demonstrate a realistic use case with use aliases. +// The use statements should not impact functionality in any way. + +use crate::{aaa, bbb, ddd}; + +// No use alias, invocation in list +// Should skip this invocation +aaa!( + const _: u8 = 0; +); + +// Use alias, invocation in list +// Should skip this invocation +use crate::bbb as ccc; +ccc!( + const _: u8 = 0; +); + +// Use alias, invocation not in list +// Should not skip this invocation +use crate::ddd as eee; +eee!( + const _: u8 = 0; +); + +// No use alias, invocation not in list +// Should not skip this invocation +fff!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/all.rs b/tests/target/skip_macro_invocations/all.rs new file mode 100644 index 0000000000000..d0437ee10fd15 --- /dev/null +++ b/tests/target/skip_macro_invocations/all.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["*"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/all_and_name.rs b/tests/target/skip_macro_invocations/all_and_name.rs new file mode 100644 index 0000000000000..1f6722344fe3b --- /dev/null +++ b/tests/target/skip_macro_invocations/all_and_name.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["*","items"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should also skip this invocation, as the wildcard covers it +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/empty.rs b/tests/target/skip_macro_invocations/empty.rs new file mode 100644 index 0000000000000..4a398cc59c6ee --- /dev/null +++ b/tests/target/skip_macro_invocations/empty.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: [] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); + +// Should not skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/name.rs b/tests/target/skip_macro_invocations/name.rs new file mode 100644 index 0000000000000..c4d577269c6f0 --- /dev/null +++ b/tests/target/skip_macro_invocations/name.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["items"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should not skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/name_unknown.rs b/tests/target/skip_macro_invocations/name_unknown.rs new file mode 100644 index 0000000000000..7ab1440395c32 --- /dev/null +++ b/tests/target/skip_macro_invocations/name_unknown.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["unknown"] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/names.rs b/tests/target/skip_macro_invocations/names.rs new file mode 100644 index 0000000000000..c6b41ff93d79d --- /dev/null +++ b/tests/target/skip_macro_invocations/names.rs @@ -0,0 +1,16 @@ +// rustfmt-skip_macro_invocations: ["foo","bar"] + +// Should skip this invocation +foo!( + const _: u8 = 0; +); + +// Should skip this invocation +bar!( + const _: u8 = 0; +); + +// Should not skip this invocation +baz!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/path_qualified_invocation_mismatch.rs b/tests/target/skip_macro_invocations/path_qualified_invocation_mismatch.rs new file mode 100644 index 0000000000000..6e372c726952a --- /dev/null +++ b/tests/target/skip_macro_invocations/path_qualified_invocation_mismatch.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["items"] + +// Should not skip this invocation +self::items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/path_qualified_match.rs b/tests/target/skip_macro_invocations/path_qualified_match.rs new file mode 100644 index 0000000000000..9398918a9e11e --- /dev/null +++ b/tests/target/skip_macro_invocations/path_qualified_match.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["self::items"] + +// Should skip this invocation +self::items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/path_qualified_name_mismatch.rs b/tests/target/skip_macro_invocations/path_qualified_name_mismatch.rs new file mode 100644 index 0000000000000..aa57a2a655c4a --- /dev/null +++ b/tests/target/skip_macro_invocations/path_qualified_name_mismatch.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["self::items"] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/use_alias_examples.rs b/tests/target/skip_macro_invocations/use_alias_examples.rs new file mode 100644 index 0000000000000..799dd8c08af15 --- /dev/null +++ b/tests/target/skip_macro_invocations/use_alias_examples.rs @@ -0,0 +1,32 @@ +// rustfmt-skip_macro_invocations: ["aaa","ccc"] + +// These tests demonstrate a realistic use case with use aliases. +// The use statements should not impact functionality in any way. + +use crate::{aaa, bbb, ddd}; + +// No use alias, invocation in list +// Should skip this invocation +aaa!( + const _: u8 = 0; +); + +// Use alias, invocation in list +// Should skip this invocation +use crate::bbb as ccc; +ccc!( + const _: u8 = 0; +); + +// Use alias, invocation not in list +// Should not skip this invocation +use crate::ddd as eee; +eee!( + const _: u8 = 0; +); + +// No use alias, invocation not in list +// Should not skip this invocation +fff!( + const _: u8 = 0; +); From 0cb294f05c421d6b6ef266e3ec01c2d8739194b3 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Wed, 15 Jun 2022 22:43:51 -0400 Subject: [PATCH 010/500] Deprecate and Rename `fn_args_layout` -> `fn_params_layout` fn_args_layout is now deprecated. This option was renamed to better communicate that it affects the layout of parameters in function signatures and not the layout of arguments in function calls. Because the `fn_args_layout` is a stable option the renamed option is also stable, however users who set `fn_args_layout` will get a warning message letting them know that the option has been renamed. --- Configurations.md | 116 +++++++++++++++++- src/config/config_type.rs | 25 +++- src/config/mod.rs | 13 +- src/items.rs | 2 +- tests/config/small_tabs.toml | 2 +- .../compressed.rs | 2 +- .../tall.rs | 2 +- .../vertical.rs | 2 +- tests/source/fn-custom-7.rs | 2 +- tests/source/fn-custom.rs | 2 +- tests/source/fn_args_layout-vertical.rs | 2 +- .../compressed.rs | 2 +- .../tall.rs | 2 +- .../vertical.rs | 2 +- tests/target/fn-custom-7.rs | 2 +- tests/target/fn-custom.rs | 2 +- tests/target/fn_args_layout-vertical.rs | 2 +- tests/target/issue-4791/issue_4928.rs | 2 +- 18 files changed, 164 insertions(+), 20 deletions(-) rename tests/source/configs/{fn_args_layout => fn_params_layout}/compressed.rs (92%) rename tests/source/configs/{fn_args_layout => fn_params_layout}/tall.rs (93%) rename tests/source/configs/{fn_args_layout => fn_params_layout}/vertical.rs (92%) rename tests/target/configs/{fn_args_layout => fn_params_layout}/compressed.rs (92%) rename tests/target/configs/{fn_args_layout => fn_params_layout}/tall.rs (94%) rename tests/target/configs/{fn_args_layout => fn_params_layout}/vertical.rs (94%) diff --git a/Configurations.md b/Configurations.md index 5579b5095afac..17eabd48759e3 100644 --- a/Configurations.md +++ b/Configurations.md @@ -645,7 +645,8 @@ trailing whitespaces. ## `fn_args_layout` -Control the layout of arguments in a function +This option is deprecated and has been renamed to `fn_params_layout` to better communicate that +it affects the layout of parameters in function signatures. - **Default value**: `"Tall"` - **Possible values**: `"Compressed"`, `"Tall"`, `"Vertical"` @@ -753,6 +754,8 @@ trait Lorem { } ``` +See also [`fn_params_layout`](#fn_params_layout) + ## `fn_call_width` Maximum width of the args of a function call before falling back to vertical formatting. @@ -765,6 +768,117 @@ By default this option is set as a percentage of [`max_width`](#max_width) provi See also [`max_width`](#max_width) and [`use_small_heuristics`](#use_small_heuristics) +## `fn_params_layout` + +Control the layout of parameters in function signatures. + +- **Default value**: `"Tall"` +- **Possible values**: `"Compressed"`, `"Tall"`, `"Vertical"` +- **Stable**: Yes + +#### `"Tall"` (default): + +```rust +trait Lorem { + fn lorem(ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet); + + fn lorem(ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet) { + // body + } + + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + consectetur: Consectetur, + adipiscing: Adipiscing, + elit: Elit, + ); + + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + consectetur: Consectetur, + adipiscing: Adipiscing, + elit: Elit, + ) { + // body + } +} +``` + +#### `"Compressed"`: + +```rust +trait Lorem { + fn lorem(ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet); + + fn lorem(ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet) { + // body + } + + fn lorem( + ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet, consectetur: Consectetur, + adipiscing: Adipiscing, elit: Elit, + ); + + fn lorem( + ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet, consectetur: Consectetur, + adipiscing: Adipiscing, elit: Elit, + ) { + // body + } +} +``` + +#### `"Vertical"`: + +```rust +trait Lorem { + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + ); + + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + ) { + // body + } + + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + consectetur: Consectetur, + adipiscing: Adipiscing, + elit: Elit, + ); + + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + consectetur: Consectetur, + adipiscing: Adipiscing, + elit: Elit, + ) { + // body + } +} +``` + + ## `fn_single_line` Put single-expression functions on a single line diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 48f4d9ce80e40..90a67e12c5a71 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -127,6 +127,7 @@ macro_rules! create_config { | "array_width" | "chain_width" => self.0.set_heuristics(), "merge_imports" => self.0.set_merge_imports(), + "fn_args_layout" => self.0.set_fn_args_layout(), &_ => (), } } @@ -181,6 +182,7 @@ macro_rules! create_config { self.set_heuristics(); self.set_ignore(dir); self.set_merge_imports(); + self.set_fn_args_layout(); self } @@ -273,14 +275,21 @@ macro_rules! create_config { | "array_width" | "chain_width" => self.set_heuristics(), "merge_imports" => self.set_merge_imports(), + "fn_args_layout" => self.set_fn_args_layout(), &_ => (), } } #[allow(unreachable_pub)] pub fn is_hidden_option(name: &str) -> bool { - const HIDE_OPTIONS: [&str; 5] = - ["verbose", "verbose_diff", "file_lines", "width_heuristics", "merge_imports"]; + const HIDE_OPTIONS: [&str; 6] = [ + "verbose", + "verbose_diff", + "file_lines", + "width_heuristics", + "merge_imports", + "fn_args_layout" + ]; HIDE_OPTIONS.contains(&name) } @@ -430,6 +439,18 @@ macro_rules! create_config { } } + fn set_fn_args_layout(&mut self) { + if self.was_set().fn_args_layout() { + eprintln!( + "Warning: the `fn_args_layout` option is deprecated. \ + Use `fn_params_layout`. instead" + ); + if !self.was_set().fn_params_layout() { + self.fn_params_layout.2 = self.fn_args_layout(); + } + } + } + #[allow(unreachable_pub)] /// Returns `true` if the config key was explicitly set and is the default value. pub fn is_default(&self, key: &str) -> bool { diff --git a/src/config/mod.rs b/src/config/mod.rs index 0c6a3cbc9532a..5492519f3894a 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -124,7 +124,9 @@ create_config! { force_multiline_blocks: bool, false, false, "Force multiline closure bodies and match arms to be wrapped in a block"; fn_args_layout: Density, Density::Tall, true, - "Control the layout of arguments in a function"; + "(deprecated: use fn_params_layout instead)"; + fn_params_layout: Density, Density::Tall, true, + "Control the layout of parameters in function signatures."; brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items"; control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false, "Brace style for control flow constructs"; @@ -196,6 +198,7 @@ impl PartialConfig { cloned.width_heuristics = None; cloned.print_misformatted_file_names = None; cloned.merge_imports = None; + cloned.fn_args_layout = None; ::toml::to_string(&cloned).map_err(ToTomlError) } @@ -442,6 +445,12 @@ mod test { "Merge imports"; merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)"; + // fn_args_layout renamed to fn_params_layout + fn_args_layout: Density, Density::Tall, true, + "(deprecated: use fn_params_layout instead)"; + fn_params_layout: Density, Density::Tall, true, + "Control the layout of parameters in a function signatures."; + // Width Heuristics use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different formatting for items and \ @@ -644,7 +653,7 @@ enum_discrim_align_threshold = 0 match_arm_blocks = true match_arm_leading_pipes = "Never" force_multiline_blocks = false -fn_args_layout = "Tall" +fn_params_layout = "Tall" brace_style = "SameLineWhere" control_brace_style = "AlwaysSameLine" trailing_semicolon = true diff --git a/src/items.rs b/src/items.rs index bab881f4b4e8d..6ab02e7f9239b 100644 --- a/src/items.rs +++ b/src/items.rs @@ -2602,7 +2602,7 @@ fn rewrite_params( ¶m_items, context .config - .fn_args_layout() + .fn_params_layout() .to_list_tactic(param_items.len()), Separator::Comma, one_line_budget, diff --git a/tests/config/small_tabs.toml b/tests/config/small_tabs.toml index c3cfd34317a37..4c37100894f83 100644 --- a/tests/config/small_tabs.toml +++ b/tests/config/small_tabs.toml @@ -3,7 +3,7 @@ comment_width = 80 tab_spaces = 2 newline_style = "Unix" brace_style = "SameLineWhere" -fn_args_layout = "Tall" +fn_params_layout = "Tall" trailing_comma = "Vertical" indent_style = "Block" reorder_imports = false diff --git a/tests/source/configs/fn_args_layout/compressed.rs b/tests/source/configs/fn_params_layout/compressed.rs similarity index 92% rename from tests/source/configs/fn_args_layout/compressed.rs rename to tests/source/configs/fn_params_layout/compressed.rs index 66a371c259f0c..eb573d3121f57 100644 --- a/tests/source/configs/fn_args_layout/compressed.rs +++ b/tests/source/configs/fn_params_layout/compressed.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Compressed +// rustfmt-fn_params_layout: Compressed // Function arguments density trait Lorem { diff --git a/tests/source/configs/fn_args_layout/tall.rs b/tests/source/configs/fn_params_layout/tall.rs similarity index 93% rename from tests/source/configs/fn_args_layout/tall.rs rename to tests/source/configs/fn_params_layout/tall.rs index f11e86fd3139c..4be34f0fe4ac1 100644 --- a/tests/source/configs/fn_args_layout/tall.rs +++ b/tests/source/configs/fn_params_layout/tall.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Tall +// rustfmt-fn_params_layout: Tall // Function arguments density trait Lorem { diff --git a/tests/source/configs/fn_args_layout/vertical.rs b/tests/source/configs/fn_params_layout/vertical.rs similarity index 92% rename from tests/source/configs/fn_args_layout/vertical.rs rename to tests/source/configs/fn_params_layout/vertical.rs index a23cc025225fb..674968023f997 100644 --- a/tests/source/configs/fn_args_layout/vertical.rs +++ b/tests/source/configs/fn_params_layout/vertical.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // Function arguments density trait Lorem { diff --git a/tests/source/fn-custom-7.rs b/tests/source/fn-custom-7.rs index d5330196bf795..3ecd8701727ad 100644 --- a/tests/source/fn-custom-7.rs +++ b/tests/source/fn-custom-7.rs @@ -1,5 +1,5 @@ // rustfmt-normalize_comments: true -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // rustfmt-brace_style: AlwaysNextLine // Case with only one variable. diff --git a/tests/source/fn-custom.rs b/tests/source/fn-custom.rs index 77ced4c5e0e10..64ef0ecfaae49 100644 --- a/tests/source/fn-custom.rs +++ b/tests/source/fn-custom.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Compressed +// rustfmt-fn_params_layout: Compressed // Test some of the ways function signatures can be customised. // Test compressed layout of args. diff --git a/tests/source/fn_args_layout-vertical.rs b/tests/source/fn_args_layout-vertical.rs index 759bc83d01570..fd6e3f0442ec1 100644 --- a/tests/source/fn_args_layout-vertical.rs +++ b/tests/source/fn_args_layout-vertical.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // Empty list should stay on one line. fn do_bar( diff --git a/tests/target/configs/fn_args_layout/compressed.rs b/tests/target/configs/fn_params_layout/compressed.rs similarity index 92% rename from tests/target/configs/fn_args_layout/compressed.rs rename to tests/target/configs/fn_params_layout/compressed.rs index f189446e25d44..ff32f0f1d5868 100644 --- a/tests/target/configs/fn_args_layout/compressed.rs +++ b/tests/target/configs/fn_params_layout/compressed.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Compressed +// rustfmt-fn_params_layout: Compressed // Function arguments density trait Lorem { diff --git a/tests/target/configs/fn_args_layout/tall.rs b/tests/target/configs/fn_params_layout/tall.rs similarity index 94% rename from tests/target/configs/fn_args_layout/tall.rs rename to tests/target/configs/fn_params_layout/tall.rs index 20f308973acbc..25a86799af0d8 100644 --- a/tests/target/configs/fn_args_layout/tall.rs +++ b/tests/target/configs/fn_params_layout/tall.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Tall +// rustfmt-fn_params_layout: Tall // Function arguments density trait Lorem { diff --git a/tests/target/configs/fn_args_layout/vertical.rs b/tests/target/configs/fn_params_layout/vertical.rs similarity index 94% rename from tests/target/configs/fn_args_layout/vertical.rs rename to tests/target/configs/fn_params_layout/vertical.rs index 6c695a75df9a2..7a0e42415f3b9 100644 --- a/tests/target/configs/fn_args_layout/vertical.rs +++ b/tests/target/configs/fn_params_layout/vertical.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // Function arguments density trait Lorem { diff --git a/tests/target/fn-custom-7.rs b/tests/target/fn-custom-7.rs index 2c20ac5a75249..f6a1a90c3fc68 100644 --- a/tests/target/fn-custom-7.rs +++ b/tests/target/fn-custom-7.rs @@ -1,5 +1,5 @@ // rustfmt-normalize_comments: true -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // rustfmt-brace_style: AlwaysNextLine // Case with only one variable. diff --git a/tests/target/fn-custom.rs b/tests/target/fn-custom.rs index 2eb2a973d243d..506d9de34370b 100644 --- a/tests/target/fn-custom.rs +++ b/tests/target/fn-custom.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Compressed +// rustfmt-fn_params_layout: Compressed // Test some of the ways function signatures can be customised. // Test compressed layout of args. diff --git a/tests/target/fn_args_layout-vertical.rs b/tests/target/fn_args_layout-vertical.rs index da0ac981d872d..bfeca15c967ed 100644 --- a/tests/target/fn_args_layout-vertical.rs +++ b/tests/target/fn_args_layout-vertical.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // Empty list should stay on one line. fn do_bar() -> u8 { diff --git a/tests/target/issue-4791/issue_4928.rs b/tests/target/issue-4791/issue_4928.rs index 588656b535fa1..29f6bda90631b 100644 --- a/tests/target/issue-4791/issue_4928.rs +++ b/tests/target/issue-4791/issue_4928.rs @@ -1,7 +1,7 @@ // rustfmt-brace_style: SameLineWhere // rustfmt-comment_width: 100 // rustfmt-edition: 2018 -// rustfmt-fn_args_layout: Compressed +// rustfmt-fn_params_layout: Compressed // rustfmt-hard_tabs: false // rustfmt-match_block_trailing_comma: true // rustfmt-max_width: 100 From dde28314da7fa634f89411fc974ce08ada1077a7 Mon Sep 17 00:00:00 2001 From: waynewaynetsai Date: Sat, 16 Jul 2022 12:13:19 +0800 Subject: [PATCH 011/500] docs: fix duplicated names example --- Configurations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Configurations.md b/Configurations.md index 17eabd48759e3..eaff09431acea 100644 --- a/Configurations.md +++ b/Configurations.md @@ -589,7 +589,7 @@ doesn't get ignored when aligning. #### `0` (default): ```rust -enum Bar { +enum Foo { A = 0, Bb = 1, RandomLongVariantGoesHere = 10, From 85fdf8ecec5551e79dc5ac3a8babaf514a58ef86 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sun, 17 Jul 2022 14:18:57 +0200 Subject: [PATCH 012/500] Remove useless conditional compilation - 2 --- src/test/mod.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/test/mod.rs b/src/test/mod.rs index 6b5bc2b30dd5a..cfad4a8ed0e3e 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -982,11 +982,7 @@ fn rustfmt() -> PathBuf { assert!( me.is_file() || me.with_extension("exe").is_file(), "{}", - if cfg!(release) { - "no rustfmt bin, try running `cargo build --release` before testing" - } else { - "no rustfmt bin, try running `cargo build` before testing" - } + "no rustfmt bin, try running `cargo build` or `cargo build --release` before testing" ); me } From a7bf0090347d8523dd62c0508a4c8413cdba099a Mon Sep 17 00:00:00 2001 From: Jorge Martin Juarez <50276574+jmj0502@users.noreply.github.com> Date: Sun, 17 Jul 2022 21:39:25 -0400 Subject: [PATCH 013/500] Fix/comments inside trait generics gets duplicated (#5446) * Bugfix: Now slash/start comments aren't duplicated on trait parameters. * Removing unnecesary comment. * Improvements: Improving the BytePos offset. * Improvements: Improving the description of the test cases. --- src/items.rs | 6 +++++- tests/target/issue-5358.rs | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 tests/target/issue-5358.rs diff --git a/src/items.rs b/src/items.rs index 6ab02e7f9239b..a76e88b77d484 100644 --- a/src/items.rs +++ b/src/items.rs @@ -1084,7 +1084,11 @@ pub(crate) fn format_trait( let item_snippet = context.snippet(item.span); if let Some(lo) = item_snippet.find('/') { // 1 = `{` - let comment_hi = body_lo - BytePos(1); + let comment_hi = if generics.params.len() > 0 { + generics.span.lo() - BytePos(1) + } else { + body_lo - BytePos(1) + }; let comment_lo = item.span.lo() + BytePos(lo as u32); if comment_lo < comment_hi { match recover_missing_comment_in_span( diff --git a/tests/target/issue-5358.rs b/tests/target/issue-5358.rs new file mode 100644 index 0000000000000..d4bf4909ad76f --- /dev/null +++ b/tests/target/issue-5358.rs @@ -0,0 +1,4 @@ +// Test /* comment */ inside trait generics does not get duplicated. +trait Test {} + +trait TestTwo {} From 05332b8c50c79c86b4715b764e4967016845273f Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Tue, 19 Jul 2022 11:48:49 -0400 Subject: [PATCH 014/500] Add test for issue 3033 Closes 3033 The issue is no longer reproducible. --- tests/target/issue_3033.rs | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 tests/target/issue_3033.rs diff --git a/tests/target/issue_3033.rs b/tests/target/issue_3033.rs new file mode 100644 index 0000000000000..e12249a6da6f3 --- /dev/null +++ b/tests/target/issue_3033.rs @@ -0,0 +1,2 @@ +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerBinding:: + BluetoothRemoteGATTServerMethods; From f2c31ba04db6bf07c140c86bfbe2cb16f1b83a8e Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Tue, 19 Jul 2022 00:37:32 -0400 Subject: [PATCH 015/500] Add tests for issue 2534 Closes 2534 The behavior described in the original issue can no longer be reproduced. The tests show that to be the case regardless of if `format_macro_matchers` is `true` or `false`. --- tests/target/issue-2534/format_macro_matchers_false.rs | 6 ++++++ tests/target/issue-2534/format_macro_matchers_true.rs | 6 ++++++ 2 files changed, 12 insertions(+) create mode 100644 tests/target/issue-2534/format_macro_matchers_false.rs create mode 100644 tests/target/issue-2534/format_macro_matchers_true.rs diff --git a/tests/target/issue-2534/format_macro_matchers_false.rs b/tests/target/issue-2534/format_macro_matchers_false.rs new file mode 100644 index 0000000000000..2038ed7f1d014 --- /dev/null +++ b/tests/target/issue-2534/format_macro_matchers_false.rs @@ -0,0 +1,6 @@ +// rustfmt-format_macro_matchers: false + +macro_rules! foo { + ($a:ident : $b:ty) => {}; + ($a:ident $b:ident $c:ident) => {}; +} diff --git a/tests/target/issue-2534/format_macro_matchers_true.rs b/tests/target/issue-2534/format_macro_matchers_true.rs new file mode 100644 index 0000000000000..01d939add4dc2 --- /dev/null +++ b/tests/target/issue-2534/format_macro_matchers_true.rs @@ -0,0 +1,6 @@ +// rustfmt-format_macro_matchers: true + +macro_rules! foo { + ($a:ident : $b:ty) => {}; + ($a:ident $b:ident $c:ident) => {}; +} From 4c78c738ba45c4ac4bab3bb74009712e00d307c7 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Tue, 19 Jul 2022 18:47:03 -0400 Subject: [PATCH 016/500] Add tests for 3245 and 3561 Closes 3245 Closes 3561 These issues were originally linked in issue 3672 and as was mentioned in PR 3706, it's unclear which commit resolved the issue but the issue can no longer be reproduced. --- tests/source/issue_3245.rs | 4 ++++ tests/source/issue_3561.rs | 6 ++++++ tests/target/issue_3245.rs | 4 ++++ tests/target/issue_3561.rs | 7 +++++++ 4 files changed, 21 insertions(+) create mode 100644 tests/source/issue_3245.rs create mode 100644 tests/source/issue_3561.rs create mode 100644 tests/target/issue_3245.rs create mode 100644 tests/target/issue_3561.rs diff --git a/tests/source/issue_3245.rs b/tests/source/issue_3245.rs new file mode 100644 index 0000000000000..0279246ed6ac4 --- /dev/null +++ b/tests/source/issue_3245.rs @@ -0,0 +1,4 @@ +fn main() { + let x = 1; + ;let y = 3; +} diff --git a/tests/source/issue_3561.rs b/tests/source/issue_3561.rs new file mode 100644 index 0000000000000..8f6cd8f9fbce5 --- /dev/null +++ b/tests/source/issue_3561.rs @@ -0,0 +1,6 @@ +fn main() {;7 +} + +fn main() { + ;7 +} diff --git a/tests/target/issue_3245.rs b/tests/target/issue_3245.rs new file mode 100644 index 0000000000000..8f442f1181a59 --- /dev/null +++ b/tests/target/issue_3245.rs @@ -0,0 +1,4 @@ +fn main() { + let x = 1; + let y = 3; +} diff --git a/tests/target/issue_3561.rs b/tests/target/issue_3561.rs new file mode 100644 index 0000000000000..846a14d86a5ff --- /dev/null +++ b/tests/target/issue_3561.rs @@ -0,0 +1,7 @@ +fn main() { + 7 +} + +fn main() { + 7 +} From c19b14539b79d44f5f433ac189d70e07fb152354 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Wed, 20 Jul 2022 09:15:51 -0400 Subject: [PATCH 017/500] test for issue 3164 Closes 3164 Show that when `error_on_line_overflow=true` is set in the rustfmt.toml that an error message is written to stderr. --- tests/cargo-fmt/main.rs | 19 +++++++++++++++++++ tests/cargo-fmt/source/issue_3164/Cargo.toml | 8 ++++++++ tests/cargo-fmt/source/issue_3164/src/main.rs | 13 +++++++++++++ tests/rustfmt/main.rs | 15 +++++++++++++++ 4 files changed, 55 insertions(+) create mode 100644 tests/cargo-fmt/source/issue_3164/Cargo.toml create mode 100644 tests/cargo-fmt/source/issue_3164/src/main.rs diff --git a/tests/cargo-fmt/main.rs b/tests/cargo-fmt/main.rs index 5aa4388518b8a..701c36fadeafa 100644 --- a/tests/cargo-fmt/main.rs +++ b/tests/cargo-fmt/main.rs @@ -98,3 +98,22 @@ fn cargo_fmt_out_of_line_test_modules() { assert!(stdout.contains(&format!("Diff in {}", path.display()))) } } + +#[rustfmt_only_ci_test] +#[test] +fn cargo_fmt_emits_error_on_line_overflow_true() { + // See also https://github.com/rust-lang/rustfmt/issues/3164 + let args = [ + "--check", + "--manifest-path", + "tests/cargo-fmt/source/issue_3164/Cargo.toml", + "--", + "--config", + "error_on_line_overflow=true", + ]; + + let (_stdout, stderr) = cargo_fmt(&args); + assert!(stderr.contains( + "line formatted, but exceeded maximum width (maximum: 100 (see `max_width` option)" + )) +} diff --git a/tests/cargo-fmt/source/issue_3164/Cargo.toml b/tests/cargo-fmt/source/issue_3164/Cargo.toml new file mode 100644 index 0000000000000..580ef7e6e24fe --- /dev/null +++ b/tests/cargo-fmt/source/issue_3164/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "issue_3164" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/tests/cargo-fmt/source/issue_3164/src/main.rs b/tests/cargo-fmt/source/issue_3164/src/main.rs new file mode 100644 index 0000000000000..9330107ac8dc7 --- /dev/null +++ b/tests/cargo-fmt/source/issue_3164/src/main.rs @@ -0,0 +1,13 @@ +#[allow(unused_macros)] +macro_rules! foo { + ($id:ident) => { + macro_rules! bar { + ($id2:tt) => { + #[cfg(any(target_feature = $id2, target_feature = $id2, target_feature = $id2, target_feature = $id2, target_feature = $id2))] + fn $id() {} + }; + } + }; +} + +fn main() {} diff --git a/tests/rustfmt/main.rs b/tests/rustfmt/main.rs index 636e3053e0f8e..7ff301e80195a 100644 --- a/tests/rustfmt/main.rs +++ b/tests/rustfmt/main.rs @@ -159,3 +159,18 @@ fn mod_resolution_error_path_attribute_does_not_exist() { // The path attribute points to a file that does not exist assert!(stderr.contains("does_not_exist.rs does not exist")); } + +#[test] +fn rustfmt_emits_error_on_line_overflow_true() { + // See also https://github.com/rust-lang/rustfmt/issues/3164 + let args = [ + "--config", + "error_on_line_overflow=true", + "tests/cargo-fmt/source/issue_3164/src/main.rs", + ]; + + let (_stdout, stderr) = rustfmt(&args); + assert!(stderr.contains( + "line formatted, but exceeded maximum width (maximum: 100 (see `max_width` option)" + )) +} From a451a39dec2bd5d7f0822eaa092e1423b42ea1d3 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Wed, 20 Jul 2022 13:59:57 -0400 Subject: [PATCH 018/500] Add test for issue 4350 Closes 4350 Its unclear which commit resolved this, but the original issue is no longer reproducible. --- tests/target/issue_4350.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 tests/target/issue_4350.rs diff --git a/tests/target/issue_4350.rs b/tests/target/issue_4350.rs new file mode 100644 index 0000000000000..a94c5c32188d2 --- /dev/null +++ b/tests/target/issue_4350.rs @@ -0,0 +1,13 @@ +//rustfmt-format_macro_bodies: true + +macro_rules! mto_text_left { + ($buf:ident, $n:ident, $pos:ident, $state:ident) => {{ + let cursor = loop { + state = match iter.next() { + None if $pos == DP::Start => break last_char_idx($buf), + None /*some comment */ => break 0, + }; + }; + Ok(saturate_cursor($buf, cursor)) + }}; +} From ed77962d243f93e1690ac62f0b8d733383090240 Mon Sep 17 00:00:00 2001 From: Martin Juarez Date: Tue, 26 Jul 2022 12:21:22 -0400 Subject: [PATCH 019/500] Improvements: Adding tests for the issue-4643. --- tests/source/issue-4643.rs | 23 +++++++++++++++++++++++ tests/target/issue-4643.rs | 19 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 tests/source/issue-4643.rs create mode 100644 tests/target/issue-4643.rs diff --git a/tests/source/issue-4643.rs b/tests/source/issue-4643.rs new file mode 100644 index 0000000000000..382072d9004bf --- /dev/null +++ b/tests/source/issue-4643.rs @@ -0,0 +1,23 @@ +// output doesn't get corrupted when using comments within generic type parameters of a trait + +pub trait Something< + A, + // some comment + B, + C +> { + fn a(&self, x: A) -> i32; + fn b(&self, x: B) -> i32; + fn c(&self, x: C) -> i32; +} + +pub trait SomethingElse< + A, + /* some comment */ + B, + C +> { + fn a(&self, x: A) -> i32; + fn b(&self, x: B) -> i32; + fn c(&self, x: C) -> i32; +} diff --git a/tests/target/issue-4643.rs b/tests/target/issue-4643.rs new file mode 100644 index 0000000000000..ef99e4db382cb --- /dev/null +++ b/tests/target/issue-4643.rs @@ -0,0 +1,19 @@ +// output doesn't get corrupted when using comments within generic type parameters of a trait + +pub trait Something< + A, + // some comment + B, + C, +> +{ + fn a(&self, x: A) -> i32; + fn b(&self, x: B) -> i32; + fn c(&self, x: C) -> i32; +} + +pub trait SomethingElse { + fn a(&self, x: A) -> i32; + fn b(&self, x: B) -> i32; + fn c(&self, x: C) -> i32; +} From 7432422008f8be71df989e357d949072c77e9060 Mon Sep 17 00:00:00 2001 From: aizpurua23a <57321880+aizpurua23a@users.noreply.github.com> Date: Wed, 27 Jul 2022 18:59:29 +0200 Subject: [PATCH 020/500] Update Configurations.md to point to dirs 4.0 docs --- Configurations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Configurations.md b/Configurations.md index eaff09431acea..e066553dc63f3 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1,6 +1,6 @@ # Configuring Rustfmt -Rustfmt is designed to be very configurable. You can create a TOML file called `rustfmt.toml` or `.rustfmt.toml`, place it in the project or any other parent directory and it will apply the options in that file. If none of these directories contain such a file, both your home directory and a directory called `rustfmt` in your [global config directory](https://docs.rs/dirs/1.0.4/dirs/fn.config_dir.html) (e.g. `.config/rustfmt/`) are checked as well. +Rustfmt is designed to be very configurable. You can create a TOML file called `rustfmt.toml` or `.rustfmt.toml`, place it in the project or any other parent directory and it will apply the options in that file. If none of these directories contain such a file, both your home directory and a directory called `rustfmt` in your [global config directory](https://docs.rs/dirs/4.0.0/dirs/fn.config_dir.html) (e.g. `.config/rustfmt/`) are checked as well. A possible content of `rustfmt.toml` or `.rustfmt.toml` might look like this: From a7801aac272ce50da191af86bab988284de534be Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Mon, 25 Jul 2022 21:38:09 -0400 Subject: [PATCH 021/500] Add test for issue 3987 Closes 3987 It's unclear which commit resolved this issue, but it can no longer be reproduced. --- .../issue-3987/format_macro_bodies_true.rs | 26 +++++++++++++++++++ .../issue-3987/format_macro_bodies_false.rs | 26 +++++++++++++++++++ .../issue-3987/format_macro_bodies_true.rs | 21 +++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 tests/source/issue-3987/format_macro_bodies_true.rs create mode 100644 tests/target/issue-3987/format_macro_bodies_false.rs create mode 100644 tests/target/issue-3987/format_macro_bodies_true.rs diff --git a/tests/source/issue-3987/format_macro_bodies_true.rs b/tests/source/issue-3987/format_macro_bodies_true.rs new file mode 100644 index 0000000000000..9af114fbe574d --- /dev/null +++ b/tests/source/issue-3987/format_macro_bodies_true.rs @@ -0,0 +1,26 @@ +// rustfmt-format_macro_bodies: true + +// with comments +macro_rules! macros { + () => {{ + Struct { + field: ( + 42 + //comment 1 + 42 + //comment 2 + ), + }; + }}; +} + +// without comments +macro_rules! macros { + () => {{ + Struct { + field: ( + 42 + + 42 + ), + }; + }}; +} diff --git a/tests/target/issue-3987/format_macro_bodies_false.rs b/tests/target/issue-3987/format_macro_bodies_false.rs new file mode 100644 index 0000000000000..1352b762e4509 --- /dev/null +++ b/tests/target/issue-3987/format_macro_bodies_false.rs @@ -0,0 +1,26 @@ +// rustfmt-format_macro_bodies: false + +// with comments +macro_rules! macros { + () => {{ + Struct { + field: ( + 42 + //comment 1 + 42 + //comment 2 + ), + }; + }}; +} + +// without comments +macro_rules! macros { + () => {{ + Struct { + field: ( + 42 + + 42 + ), + }; + }}; +} diff --git a/tests/target/issue-3987/format_macro_bodies_true.rs b/tests/target/issue-3987/format_macro_bodies_true.rs new file mode 100644 index 0000000000000..88d57159c859f --- /dev/null +++ b/tests/target/issue-3987/format_macro_bodies_true.rs @@ -0,0 +1,21 @@ +// rustfmt-format_macro_bodies: true + +// with comments +macro_rules! macros { + () => {{ + Struct { + field: ( + 42 + //comment 1 + 42 + //comment 2 + ), + }; + }}; +} + +// without comments +macro_rules! macros { + () => {{ + Struct { field: (42 + 42) }; + }}; +} From af72f7a17f01a2d61490556e32c91c2d98416c9b Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 28 Jul 2022 10:31:04 +1000 Subject: [PATCH 022/500] Remove `TreeAndSpacing`. A `TokenStream` contains a `Lrc>`. But this is not quite right. `Spacing` makes sense for `TokenTree::Token`, but does not make sense for `TokenTree::Delimited`, because a `TokenTree::Delimited` cannot be joined with another `TokenTree`. This commit fixes this problem, by adding `Spacing` to `TokenTree::Token`, changing `TokenStream` to contain a `Lrc>`, and removing the `TreeAndSpacing` typedef. The commit removes these two impls: - `impl From for TokenStream` - `impl From for TreeAndSpacing` These were useful, but also resulted in code with many `.into()` calls that was hard to read, particularly for anyone not highly familiar with the relevant types. This commit makes some other changes to compensate: - `TokenTree::token()` becomes `TokenTree::token_{alone,joint}()`. - `TokenStream::token_{alone,joint}()` are added. - `TokenStream::delimited` is added. This results in things like this: ```rust TokenTree::token(token::Semi, stmt.span).into() ``` changing to this: ```rust TokenStream::token_alone(token::Semi, stmt.span) ``` This makes the type of the result, and its spacing, clearer. These changes also simplifies `Cursor` and `CursorRef`, because they no longer need to distinguish between `next` and `next_with_spacing`. --- src/macros.rs | 98 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 61 insertions(+), 37 deletions(-) diff --git a/src/macros.rs b/src/macros.rs index f4b2bcf281577..3a641fab5d647 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -13,7 +13,7 @@ use std::collections::HashMap; use std::panic::{catch_unwind, AssertUnwindSafe}; use rustc_ast::token::{BinOpToken, Delimiter, Token, TokenKind}; -use rustc_ast::tokenstream::{Cursor, Spacing, TokenStream, TokenTree}; +use rustc_ast::tokenstream::{Cursor, TokenStream, TokenTree}; use rustc_ast::{ast, ptr}; use rustc_ast_pretty::pprust; use rustc_span::{ @@ -682,7 +682,7 @@ struct MacroArgParser { fn last_tok(tt: &TokenTree) -> Token { match *tt { - TokenTree::Token(ref t) => t.clone(), + TokenTree::Token(ref t, _) => t.clone(), TokenTree::Delimited(delim_span, delim, _) => Token { kind: TokenKind::CloseDelim(delim), span: delim_span.close, @@ -737,10 +737,13 @@ impl MacroArgParser { fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> { match iter.next() { - Some(TokenTree::Token(Token { - kind: TokenKind::Ident(name, _), - .. - })) => { + Some(TokenTree::Token( + Token { + kind: TokenKind::Ident(name, _), + .. + }, + _, + )) => { self.result.push(ParsedMacroArg { kind: MacroArgKind::MetaVariable(name, self.buf.clone()), }); @@ -777,21 +780,30 @@ impl MacroArgParser { } match tok { - TokenTree::Token(Token { - kind: TokenKind::BinOp(BinOpToken::Plus), - .. - }) - | TokenTree::Token(Token { - kind: TokenKind::Question, - .. - }) - | TokenTree::Token(Token { - kind: TokenKind::BinOp(BinOpToken::Star), - .. - }) => { + TokenTree::Token( + Token { + kind: TokenKind::BinOp(BinOpToken::Plus), + .. + }, + _, + ) + | TokenTree::Token( + Token { + kind: TokenKind::Question, + .. + }, + _, + ) + | TokenTree::Token( + Token { + kind: TokenKind::BinOp(BinOpToken::Star), + .. + }, + _, + ) => { break; } - TokenTree::Token(ref t) => { + TokenTree::Token(ref t, _) => { buffer.push_str(&pprust::token_to_string(t)); } _ => return None, @@ -859,10 +871,13 @@ impl MacroArgParser { while let Some(tok) = iter.next() { match tok { - TokenTree::Token(Token { - kind: TokenKind::Dollar, - span, - }) => { + TokenTree::Token( + Token { + kind: TokenKind::Dollar, + span, + }, + _, + ) => { // We always want to add a separator before meta variables. if !self.buf.is_empty() { self.add_separator(); @@ -875,13 +890,16 @@ impl MacroArgParser { span, }; } - TokenTree::Token(Token { - kind: TokenKind::Colon, - .. - }) if self.is_meta_var => { + TokenTree::Token( + Token { + kind: TokenKind::Colon, + .. + }, + _, + ) if self.is_meta_var => { self.add_meta_variable(&mut iter)?; } - TokenTree::Token(ref t) => self.update_buffer(t), + TokenTree::Token(ref t, _) => self.update_buffer(t), TokenTree::Delimited(_delimited_span, delimited, ref tts) => { if !self.buf.is_empty() { if next_space(&self.last_tok.kind) == SpaceState::Always { @@ -1123,12 +1141,15 @@ impl MacroParser { TokenTree::Token(..) => return None, TokenTree::Delimited(delimited_span, d, _) => (delimited_span.open.lo(), d), }; - let args = TokenStream::new(vec![(tok, Spacing::Joint)]); + let args = TokenStream::new(vec![tok]); match self.toks.next()? { - TokenTree::Token(Token { - kind: TokenKind::FatArrow, - .. - }) => {} + TokenTree::Token( + Token { + kind: TokenKind::FatArrow, + .. + }, + _, + ) => {} _ => return None, } let (mut hi, body, whole_body) = match self.toks.next()? { @@ -1147,10 +1168,13 @@ impl MacroParser { ) } }; - if let Some(TokenTree::Token(Token { - kind: TokenKind::Semi, - span, - })) = self.toks.look_ahead(0) + if let Some(TokenTree::Token( + Token { + kind: TokenKind::Semi, + span, + }, + _, + )) = self.toks.look_ahead(0) { hi = span.hi(); self.toks.next(); From 7cc126180f8340071741586c9b455b88b920b116 Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Wed, 20 Jul 2022 07:46:49 +0100 Subject: [PATCH 023/500] feat: nicer skip context for macro/attribute --- src/attr.rs | 4 ++-- src/macros.rs | 3 ++- src/skip.rs | 59 +++++++++++++++++++++++++++++++++----------------- src/visitor.rs | 4 ++-- 4 files changed, 45 insertions(+), 25 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index 41ba9a847e67a..b1efaa21f2746 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -337,7 +337,7 @@ impl Rewrite for ast::Attribute { } else { let should_skip = self .ident() - .map(|s| context.skip_context.skip_attribute(s.name.as_str())) + .map(|s| context.skip_context.attributes.skip(s.name.as_str())) .unwrap_or(false); let prefix = attr_prefix(self); @@ -391,7 +391,7 @@ impl Rewrite for [ast::Attribute] { // Determine if the source text is annotated with `#[rustfmt::skip::attributes(derive)]` // or `#![rustfmt::skip::attributes(derive)]` - let skip_derives = context.skip_context.skip_attribute("derive"); + let skip_derives = context.skip_context.attributes.skip("derive"); // This is not just a simple map because we need to handle doc comments // (where we take as many doc comment attributes as possible) and possibly diff --git a/src/macros.rs b/src/macros.rs index e78ef1f806678..1ef5a095bf981 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -157,7 +157,8 @@ pub(crate) fn rewrite_macro( ) -> Option { let should_skip = context .skip_context - .skip_macro(context.snippet(mac.path.span)); + .macros + .skip(context.snippet(mac.path.span)); if should_skip { None } else { diff --git a/src/skip.rs b/src/skip.rs index 8b2fd7736ae51..4ebbee542a265 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -2,41 +2,60 @@ use rustc_ast::ast; use rustc_ast_pretty::pprust; +use std::collections::HashSet; -/// Take care of skip name stack. You can update it by attributes slice or -/// by other context. Query this context to know if you need skip a block. +/// Track which blocks of code are to be skipped when formatting. +/// +/// You can update it by: +/// +/// - attributes slice +/// - manually feeding values into the underlying contexts +/// +/// Query this context to know if you need skip a block. #[derive(Default, Clone)] pub(crate) struct SkipContext { - pub(crate) all_macros: bool, - macros: Vec, - attributes: Vec, + pub(crate) macros: SkipNameContext, + pub(crate) attributes: SkipNameContext, } impl SkipContext { pub(crate) fn update_with_attrs(&mut self, attrs: &[ast::Attribute]) { - self.macros.append(&mut get_skip_names("macros", attrs)); - self.attributes - .append(&mut get_skip_names("attributes", attrs)); + self.macros.append(get_skip_names("macros", attrs)); + self.attributes.append(get_skip_names("attributes", attrs)); } - pub(crate) fn update(&mut self, mut other: SkipContext) { - self.macros.append(&mut other.macros); - self.attributes.append(&mut other.attributes); + pub(crate) fn update(&mut self, other: SkipContext) { + let SkipContext { macros, attributes } = other; + self.macros.update(macros); + self.attributes.update(attributes); + } +} + +/// Track which names to skip. +/// +/// Query this context with a string to know whether to skip it. +#[derive(Default, Clone)] +pub(crate) struct SkipNameContext { + all: bool, + values: HashSet, +} + +impl SkipNameContext { + pub(crate) fn append(&mut self, values: Vec) { + self.values.extend(values); } - pub(crate) fn update_macros(&mut self, other: T) - where - T: IntoIterator, - { - self.macros.extend(other.into_iter()); + pub(crate) fn update(&mut self, other: Self) { + self.all = self.all || other.all; + self.values.extend(other.values); } - pub(crate) fn skip_macro(&self, name: &str) -> bool { - self.all_macros || self.macros.iter().any(|n| n == name) + pub(crate) fn skip(&self, name: &str) -> bool { + self.all || self.values.contains(name) } - pub(crate) fn skip_attribute(&self, name: &str) -> bool { - self.attributes.iter().any(|n| n == name) + pub(crate) fn set_all(&mut self, all: bool) { + self.all = all; } } diff --git a/src/visitor.rs b/src/visitor.rs index b93153de154a8..4b3ee7f76e185 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -775,10 +775,10 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { for macro_selector in config.skip_macro_invocations().0 { match macro_selector { MacroSelector::Name(name) => macro_names.push(name.to_string()), - MacroSelector::All => skip_context.all_macros = true, + MacroSelector::All => skip_context.macros.set_all(true), } } - skip_context.update_macros(macro_names); + skip_context.macros.append(macro_names); FmtVisitor { parent_context: None, parse_sess: parse_session, From 3fa81c6dbf72a83e4612d9490cdceade5eb2d2ae Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Wed, 20 Jul 2022 22:24:50 +0100 Subject: [PATCH 024/500] [review] use extend trait, enum for skip context --- src/skip.rs | 54 ++++++++++++++++++++++++++++++++++++-------------- src/visitor.rs | 4 ++-- 2 files changed, 41 insertions(+), 17 deletions(-) diff --git a/src/skip.rs b/src/skip.rs index 4ebbee542a265..59d6d84c96430 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -11,7 +11,7 @@ use std::collections::HashSet; /// - attributes slice /// - manually feeding values into the underlying contexts /// -/// Query this context to know if you need skip a block. +/// Query this context to know if you need to skip a block. #[derive(Default, Clone)] pub(crate) struct SkipContext { pub(crate) macros: SkipNameContext, @@ -20,8 +20,8 @@ pub(crate) struct SkipContext { impl SkipContext { pub(crate) fn update_with_attrs(&mut self, attrs: &[ast::Attribute]) { - self.macros.append(get_skip_names("macros", attrs)); - self.attributes.append(get_skip_names("attributes", attrs)); + self.macros.extend(get_skip_names("macros", attrs)); + self.attributes.extend(get_skip_names("attributes", attrs)); } pub(crate) fn update(&mut self, other: SkipContext) { @@ -34,28 +34,52 @@ impl SkipContext { /// Track which names to skip. /// /// Query this context with a string to know whether to skip it. -#[derive(Default, Clone)] -pub(crate) struct SkipNameContext { - all: bool, - values: HashSet, +#[derive(Clone)] +pub(crate) enum SkipNameContext { + All, + Values(HashSet), } -impl SkipNameContext { - pub(crate) fn append(&mut self, values: Vec) { - self.values.extend(values); +impl Default for SkipNameContext { + fn default() -> Self { + Self::Values(Default::default()) + } +} + +impl Extend for SkipNameContext { + fn extend>(&mut self, iter: T) { + match self { + Self::All => {} + Self::Values(values) => values.extend(iter), + } } +} +impl SkipNameContext { pub(crate) fn update(&mut self, other: Self) { - self.all = self.all || other.all; - self.values.extend(other.values); + match (self, other) { + // If we're already skipping everything, nothing more can be added + (Self::All, _) => {} + // If we want to skip all, set it + (this, Self::All) => { + *this = Self::All; + } + // If we have some new values to skip, add them + (Self::Values(existing_values), Self::Values(new_values)) => { + existing_values.extend(new_values) + } + } } pub(crate) fn skip(&self, name: &str) -> bool { - self.all || self.values.contains(name) + match self { + Self::All => true, + Self::Values(values) => values.contains(name), + } } - pub(crate) fn set_all(&mut self, all: bool) { - self.all = all; + pub(crate) fn skip_all(&mut self) { + *self = Self::All; } } diff --git a/src/visitor.rs b/src/visitor.rs index 4b3ee7f76e185..c0fc37eaaa899 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -775,10 +775,10 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { for macro_selector in config.skip_macro_invocations().0 { match macro_selector { MacroSelector::Name(name) => macro_names.push(name.to_string()), - MacroSelector::All => skip_context.macros.set_all(true), + MacroSelector::All => skip_context.macros.skip_all(), } } - skip_context.macros.append(macro_names); + skip_context.macros.extend(macro_names); FmtVisitor { parent_context: None, parse_sess: parse_session, From 23ef4b7ac476714886582865b39d396d615a3901 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sun, 31 Jul 2022 13:53:37 -0500 Subject: [PATCH 025/500] refactor(chains): encapsulate shared code, prep for overflows --- src/chains.rs | 99 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 77 insertions(+), 22 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index 5bccb22db4c17..a2976bbe92a5e 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -74,6 +74,60 @@ use crate::utils::{ rewrite_ident, trimmed_last_line_width, wrap_str, }; +/// Provides the original input contents from the span +/// of a chain element with trailing spaces trimmed. +fn format_overflow_style(span: Span, context: &RewriteContext<'_>) -> Option { + context.snippet_provider.span_to_snippet(span).map(|s| { + s.lines() + .map(|l| l.trim_end()) + .collect::>() + .join("\n") + }) +} + +fn format_chain_item( + item: &ChainItem, + context: &RewriteContext<'_>, + rewrite_shape: Shape, + allow_overflow: bool, +) -> Option { + if allow_overflow { + item.rewrite(context, rewrite_shape) + .or_else(|| format_overflow_style(item.span, context)) + } else { + item.rewrite(context, rewrite_shape) + } +} + +fn get_block_child_shape( + prev_ends_with_block: bool, + context: &RewriteContext<'_>, + shape: Shape, +) -> Shape { + if prev_ends_with_block { + shape.block_indent(0) + } else { + shape.block_indent(context.config.tab_spaces()) + } + .with_max_width(context.config) +} + +fn get_visual_style_child_shape( + context: &RewriteContext<'_>, + shape: Shape, + offset: usize, + parent_overflowing: bool, +) -> Option { + if !parent_overflowing { + shape + .with_max_width(context.config) + .offset_left(offset) + .map(|s| s.visual_indent(0)) + } else { + Some(shape.visual_indent(offset)) + } +} + pub(crate) fn rewrite_chain( expr: &ast::Expr, context: &RewriteContext<'_>, @@ -498,6 +552,8 @@ struct ChainFormatterShared<'a> { // The number of children in the chain. This is not equal to `self.children.len()` // because `self.children` will change size as we process the chain. child_count: usize, + // Whether elements are allowed to overflow past the max_width limit + allow_overflow: bool, } impl<'a> ChainFormatterShared<'a> { @@ -507,6 +563,8 @@ impl<'a> ChainFormatterShared<'a> { rewrites: Vec::with_capacity(chain.children.len() + 1), fits_single_line: false, child_count: chain.children.len(), + // TODO(calebcartwright) + allow_overflow: false, } } @@ -519,6 +577,14 @@ impl<'a> ChainFormatterShared<'a> { } } + fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> { + for item in &self.children[..self.children.len() - 1] { + let rewrite = format_chain_item(item, context, child_shape, self.allow_overflow)?; + self.rewrites.push(rewrite); + } + Some(()) + } + // Rewrite the last child. The last child of a chain requires special treatment. We need to // know whether 'overflowing' the last child make a better formatting: // @@ -731,22 +797,12 @@ impl<'a> ChainFormatter for ChainFormatterBlock<'a> { } fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { - Some( - if self.root_ends_with_block { - shape.block_indent(0) - } else { - shape.block_indent(context.config.tab_spaces()) - } - .with_max_width(context.config), - ) + let block_end = self.root_ends_with_block; + Some(get_block_child_shape(block_end, context, shape)) } fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> { - for item in &self.shared.children[..self.shared.children.len() - 1] { - let rewrite = item.rewrite(context, child_shape)?; - self.shared.rewrites.push(rewrite); - } - Some(()) + self.shared.format_children(context, child_shape) } fn format_last_child( @@ -828,18 +884,17 @@ impl<'a> ChainFormatter for ChainFormatterVisual<'a> { } fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { - shape - .with_max_width(context.config) - .offset_left(self.offset) - .map(|s| s.visual_indent(0)) + get_visual_style_child_shape( + context, + shape, + self.offset, + // TODO(calebcartwright): self.shared.permissibly_overflowing_parent, + false, + ) } fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> { - for item in &self.shared.children[..self.shared.children.len() - 1] { - let rewrite = item.rewrite(context, child_shape)?; - self.shared.rewrites.push(rewrite); - } - Some(()) + self.shared.format_children(context, child_shape) } fn format_last_child( From 662702eb54b12f16729d6559ce0478b00ef153a8 Mon Sep 17 00:00:00 2001 From: alexey semenyuk Date: Sun, 7 Aug 2022 02:53:03 +0300 Subject: [PATCH 026/500] Fix typos (#5486) * Fix typos * Fix typos --- CHANGELOG.md | 2 +- Processes.md | 2 +- src/bin/main.rs | 2 +- src/config/mod.rs | 2 +- src/imports.rs | 4 ++-- tests/mod-resolver/issue-5198/lib/c/d/explanation.txt | 2 +- tests/mod-resolver/issue-5198/lib/explanation.txt | 2 +- tests/source/cfg_if/detect/arch/x86.rs | 2 +- tests/source/enum.rs | 2 +- tests/source/tuple.rs | 2 +- .../wrap_comments_should_not_imply_format_doc_comments.rs | 2 +- tests/target/cfg_if/detect/arch/x86.rs | 2 +- tests/target/enum.rs | 2 +- tests/target/tuple.rs | 2 +- .../wrap_comments_should_not_imply_format_doc_comments.rs | 2 +- 15 files changed, 16 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c1893bf8c387..e9ce930dabc68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -840,7 +840,7 @@ from formatting an attribute #3665 - Fix formatting of raw string literals #2983 - Handle chain with try operators with spaces #2986 - Use correct shape in Visual tuple rewriting #2987 -- Impove formatting of arguments with `visual_style = "Visual"` option #2988 +- Improve formatting of arguments with `visual_style = "Visual"` option #2988 - Change `print_diff` to output the correct line number 992b179 - Propagate errors about failing to rewrite a macro 6f318e3 - Handle formatting of long function signature #3010 diff --git a/Processes.md b/Processes.md index 9d86d52b122d8..334414702b159 100644 --- a/Processes.md +++ b/Processes.md @@ -2,7 +2,7 @@ This document outlines processes regarding management of rustfmt. # Stabilising an Option -In this Section, we describe how to stabilise an option of the rustfmt's configration. +In this Section, we describe how to stabilise an option of the rustfmt's configuration. ## Conditions diff --git a/src/bin/main.rs b/src/bin/main.rs index 8e871e61f2683..be64559e87745 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -136,7 +136,7 @@ fn make_opts() -> Options { "l", "files-with-diff", "Prints the names of mismatched files that were formatted. Prints the names of \ - files that would be formated when used with `--check` mode. ", + files that would be formatted when used with `--check` mode. ", ); opts.optmulti( "", diff --git a/src/config/mod.rs b/src/config/mod.rs index 5492519f3894a..4ec7e924bf621 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -182,7 +182,7 @@ create_config! { make_backup: bool, false, false, "Backup changed files"; print_misformatted_file_names: bool, false, true, "Prints the names of mismatched files that were formatted. Prints the names of \ - files that would be formated when used with `--check` mode. "; + files that would be formatted when used with `--check` mode. "; } #[derive(Error, Debug)] diff --git a/src/imports.rs b/src/imports.rs index 8d41c881589e5..140d8953abc90 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -251,8 +251,8 @@ fn flatten_use_trees( use_trees: Vec, import_granularity: ImportGranularity, ) -> Vec { - // Return non-sorted single occurance of the use-trees text string; - // order is by first occurance of the use-tree. + // Return non-sorted single occurrence of the use-trees text string; + // order is by first occurrence of the use-tree. use_trees .into_iter() .flat_map(|tree| tree.flatten(import_granularity)) diff --git a/tests/mod-resolver/issue-5198/lib/c/d/explanation.txt b/tests/mod-resolver/issue-5198/lib/c/d/explanation.txt index 92c9e3021431f..254102ebabdc2 100644 --- a/tests/mod-resolver/issue-5198/lib/c/d/explanation.txt +++ b/tests/mod-resolver/issue-5198/lib/c/d/explanation.txt @@ -9,7 +9,7 @@ The directory name './lib/c/d/' conflicts with the './lib/c/d.rs' file name. * mod g; Module resolution will fail if we look for './lib/c/d/e.rs' or './lib/c/d/e/mod.rs', -so we should fall back to looking for './lib/c/e.rs', which correctly finds the modlue, that +so we should fall back to looking for './lib/c/e.rs', which correctly finds the module, that rustfmt should format. './lib/c/d/f.rs' and './lib/c/d/g/mod.rs' exist at the default submodule paths so we should be able diff --git a/tests/mod-resolver/issue-5198/lib/explanation.txt b/tests/mod-resolver/issue-5198/lib/explanation.txt index d436a8076cd71..90464def8ebcc 100644 --- a/tests/mod-resolver/issue-5198/lib/explanation.txt +++ b/tests/mod-resolver/issue-5198/lib/explanation.txt @@ -9,7 +9,7 @@ The directory name './lib' conflicts with the './lib.rs' file name. * mod c; Module resolution will fail if we look for './lib/a.rs' or './lib/a/mod.rs', -so we should fall back to looking for './a.rs', which correctly finds the modlue that +so we should fall back to looking for './a.rs', which correctly finds the module that rustfmt should format. './lib/b.rs' and './lib/c/mod.rs' exist at the default submodule paths so we should be able diff --git a/tests/source/cfg_if/detect/arch/x86.rs b/tests/source/cfg_if/detect/arch/x86.rs index d26f4ee894fad..131cbb855f163 100644 --- a/tests/source/cfg_if/detect/arch/x86.rs +++ b/tests/source/cfg_if/detect/arch/x86.rs @@ -329,7 +329,7 @@ pub enum Feature { tbm, /// POPCNT (Population Count) popcnt, - /// FXSR (Floating-point context fast save and restor) + /// FXSR (Floating-point context fast save and restore) fxsr, /// XSAVE (Save Processor Extended States) xsave, diff --git a/tests/source/enum.rs b/tests/source/enum.rs index 0ed9651abe722..a7b9616929cb0 100644 --- a/tests/source/enum.rs +++ b/tests/source/enum.rs @@ -36,7 +36,7 @@ enum StructLikeVariants { Normal(u32, String, ), StructLike { x: i32, // Test comment // Pre-comment - #[Attr50] y: SomeType, // Aanother Comment + #[Attr50] y: SomeType, // Another Comment }, SL { a: A } } diff --git a/tests/source/tuple.rs b/tests/source/tuple.rs index 9a0f979fbca38..5189a7454f3a7 100644 --- a/tests/source/tuple.rs +++ b/tests/source/tuple.rs @@ -1,4 +1,4 @@ -// Test tuple litterals +// Test tuple literals fn foo() { let a = (a, a, a, a, a); diff --git a/tests/source/wrap_comments_should_not_imply_format_doc_comments.rs b/tests/source/wrap_comments_should_not_imply_format_doc_comments.rs index 78b3ce146f289..56064e4a4cccf 100644 --- a/tests/source/wrap_comments_should_not_imply_format_doc_comments.rs +++ b/tests/source/wrap_comments_should_not_imply_format_doc_comments.rs @@ -11,6 +11,6 @@ /// fn foo() {} -/// A long commment for wrapping +/// A long comment for wrapping /// This is a long long long long long long long long long long long long long long long long long long long long sentence. fn bar() {} diff --git a/tests/target/cfg_if/detect/arch/x86.rs b/tests/target/cfg_if/detect/arch/x86.rs index 02d5eed1c2923..47210cae2aaa0 100644 --- a/tests/target/cfg_if/detect/arch/x86.rs +++ b/tests/target/cfg_if/detect/arch/x86.rs @@ -314,7 +314,7 @@ pub enum Feature { tbm, /// POPCNT (Population Count) popcnt, - /// FXSR (Floating-point context fast save and restor) + /// FXSR (Floating-point context fast save and restore) fxsr, /// XSAVE (Save Processor Extended States) xsave, diff --git a/tests/target/enum.rs b/tests/target/enum.rs index 9a25126b44ecb..70fc8ab376ccd 100644 --- a/tests/target/enum.rs +++ b/tests/target/enum.rs @@ -43,7 +43,7 @@ enum StructLikeVariants { x: i32, // Test comment // Pre-comment #[Attr50] - y: SomeType, // Aanother Comment + y: SomeType, // Another Comment }, SL { a: A, diff --git a/tests/target/tuple.rs b/tests/target/tuple.rs index 68bb2f3bc2850..24fcf8cfd7cf3 100644 --- a/tests/target/tuple.rs +++ b/tests/target/tuple.rs @@ -1,4 +1,4 @@ -// Test tuple litterals +// Test tuple literals fn foo() { let a = (a, a, a, a, a); diff --git a/tests/target/wrap_comments_should_not_imply_format_doc_comments.rs b/tests/target/wrap_comments_should_not_imply_format_doc_comments.rs index d61d4d7c216a3..6ccecc7e0bbe6 100644 --- a/tests/target/wrap_comments_should_not_imply_format_doc_comments.rs +++ b/tests/target/wrap_comments_should_not_imply_format_doc_comments.rs @@ -10,7 +10,7 @@ /// ``` fn foo() {} -/// A long commment for wrapping +/// A long comment for wrapping /// This is a long long long long long long long long long long long long long /// long long long long long long long sentence. fn bar() {} From 5a1ef3c7bc1f81f4a21da493f8e352d7316c7351 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sat, 6 Aug 2022 19:48:55 -0500 Subject: [PATCH 027/500] chore: bump toolchain --- rust-toolchain | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain b/rust-toolchain index 2640a9e0ecc28..f8ed76d2e6f9e 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-06-21" +channel = "nightly-2022-08-06" components = ["rustc-dev"] From 437de8d17fc39231cc8424069579855a94e8c245 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sat, 6 Aug 2022 19:59:52 -0500 Subject: [PATCH 028/500] chore: disable unreachable pub lint on config items --- src/config/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/config/mod.rs b/src/config/mod.rs index 4ec7e924bf621..1fc6d033541c6 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -20,9 +20,11 @@ pub use crate::config::options::*; #[macro_use] pub(crate) mod config_type; #[macro_use] +#[allow(unreachable_pub)] pub(crate) mod options; pub(crate) mod file_lines; +#[allow(unreachable_pub)] pub(crate) mod lists; pub(crate) mod macro_names; From c78ef92add17c545c387bee12428d3dd51d90003 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sat, 6 Aug 2022 20:29:46 -0500 Subject: [PATCH 029/500] chore: fix another config unreachable-pub --- src/config/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/mod.rs b/src/config/mod.rs index 1fc6d033541c6..14f27f3f8b692 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -422,7 +422,7 @@ mod test { use rustfmt_config_proc_macro::config_type; #[config_type] - pub enum PartiallyUnstableOption { + pub(crate) enum PartiallyUnstableOption { V1, V2, #[unstable_variant] From a67d909627b7ec93e315bfe1c66895904055c75c Mon Sep 17 00:00:00 2001 From: alex-semenyuk Date: Mon, 8 Aug 2022 15:23:41 +0300 Subject: [PATCH 030/500] Fix some clippy issues --- src/cargo-fmt/main.rs | 12 +++++------- src/cargo-fmt/test/mod.rs | 4 ++-- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index 9031d29b45f7f..2b714b68df00e 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -198,12 +198,10 @@ fn convert_message_format_to_rustfmt_args( Ok(()) } "human" => Ok(()), - _ => { - return Err(format!( - "invalid --message-format value: {}. Allowed values are: short|json|human", - message_format - )); - } + _ => Err(format!( + "invalid --message-format value: {}. Allowed values are: short|json|human", + message_format + )), } } @@ -215,7 +213,7 @@ fn print_usage_to_stderr(reason: &str) { .expect("failed to write to stderr"); } -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Verbosity { Verbose, Normal, diff --git a/src/cargo-fmt/test/mod.rs b/src/cargo-fmt/test/mod.rs index 56e52fbabb68b..696326e4f9406 100644 --- a/src/cargo-fmt/test/mod.rs +++ b/src/cargo-fmt/test/mod.rs @@ -70,9 +70,9 @@ fn mandatory_separator() { .is_err() ); assert!( - !Opts::command() + Opts::command() .try_get_matches_from(&["test", "--", "--emit"]) - .is_err() + .is_ok() ); } From ea017d7f84e218c4a8048d2ecd9d63bbda014209 Mon Sep 17 00:00:00 2001 From: David Bar-On <61089727+davidBar-On@users.noreply.github.com> Date: Tue, 9 Aug 2022 16:30:49 +0300 Subject: [PATCH 031/500] Backport PR #4730 (#5390) * Backport PR #4730 that fix issue #4689 * Test files for each Verion One and Two * Simplify per review comment - use defer and matches! * Changes per reviewer comments for reducing indentations --- src/types.rs | 43 +++++++++- tests/source/issue-4689/one.rs | 149 ++++++++++++++++++++++++++++++++ tests/source/issue-4689/two.rs | 149 ++++++++++++++++++++++++++++++++ tests/target/issue-4689/one.rs | 150 ++++++++++++++++++++++++++++++++ tests/target/issue-4689/two.rs | 152 +++++++++++++++++++++++++++++++++ 5 files changed, 639 insertions(+), 4 deletions(-) create mode 100644 tests/source/issue-4689/one.rs create mode 100644 tests/source/issue-4689/two.rs create mode 100644 tests/target/issue-4689/one.rs create mode 100644 tests/target/issue-4689/two.rs diff --git a/src/types.rs b/src/types.rs index 2627886db109d..25ad587ba856b 100644 --- a/src/types.rs +++ b/src/types.rs @@ -941,6 +941,28 @@ fn join_bounds_inner( ast::GenericBound::Trait(..) => last_line_extendable(s), }; + // Whether a GenericBound item is a PathSegment segment that includes internal array + // that contains more than one item + let is_item_with_multi_items_array = |item: &ast::GenericBound| match item { + ast::GenericBound::Trait(ref poly_trait_ref, ..) => { + let segments = &poly_trait_ref.trait_ref.path.segments; + if segments.len() > 1 { + true + } else { + if let Some(args_in) = &segments[0].args { + matches!( + args_in.deref(), + ast::GenericArgs::AngleBracketed(bracket_args) + if bracket_args.args.len() > 1 + ) + } else { + false + } + } + } + _ => false, + }; + let result = items.iter().enumerate().try_fold( (String::new(), None, false), |(strs, prev_trailing_span, prev_extendable), (i, item)| { @@ -1035,10 +1057,23 @@ fn join_bounds_inner( }, )?; - if !force_newline - && items.len() > 1 - && (result.0.contains('\n') || result.0.len() > shape.width) - { + // Whether retry the function with forced newline is needed: + // Only if result is not already multiline and did not exceed line width, + // and either there is more than one item; + // or the single item is of type `Trait`, + // and any of the internal arrays contains more than one item; + let retry_with_force_newline = + if force_newline || (!result.0.contains('\n') && result.0.len() <= shape.width) { + false + } else { + if items.len() > 1 { + true + } else { + is_item_with_multi_items_array(&items[0]) + } + }; + + if retry_with_force_newline { join_bounds_inner(context, shape, items, need_indent, true) } else { Some(result.0) diff --git a/tests/source/issue-4689/one.rs b/tests/source/issue-4689/one.rs new file mode 100644 index 0000000000000..d048eb10fb15c --- /dev/null +++ b/tests/source/issue-4689/one.rs @@ -0,0 +1,149 @@ +// rustfmt-version: One + +// Based on the issue description +pub trait PrettyPrinter<'tcx>: +Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> +{ +// +} +pub trait PrettyPrinter<'tcx>: +Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> + fmt::Write +{ +// +} +pub trait PrettyPrinter<'tcx>: +Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> + fmt::Write1 + fmt::Write2 +{ +// +} +pub trait PrettyPrinter<'tcx>: +fmt::Write + Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> +{ +// +} +pub trait PrettyPrinter<'tcx>: +fmt::Write + Printer1< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> + Printer2< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> +{ +// +} + +// Some test cases to ensure other cases formatting were not changed +fn f() -> Box< +FnMut() -> Thing< +WithType = LongItemName, +Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, +>, +> { +} +fn f() -> Box< +FnMut() -> Thing< +WithType = LongItemName, +Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, +> + fmt::Write1 ++ fmt::Write2, +> { +} + +fn foo(foo2: F) +where +F: Fn( +// this comment is deleted +) +{ +} +fn foo(foo2: F) +where +F: Fn( +// this comment is deleted +) + fmt::Write +{ +} + +fn elaborate_bounds(mut mk_cand: F) +where +F: for<> FnMut( +&mut ProbeContext<>, +ty::PolyTraitRefffffffffffffffffffffffffffffffff<>, +tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, +), +{ +} +fn elaborate_bounds(mut mk_cand: F) +where +F: for<> FnMut( +&mut ProbeContext<>, +ty::PolyTraitRefffffffffffffffffffffffffffffffff<>, +tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, +) + fmt::Write, +{ +} + +fn build_sorted_static_get_entry_names( +mut entries: entryyyyyyyy, +) -> ( +impl Fn( +AlphabeticalTraversal, +Seconddddddddddddddddddddddddddddddddddd +) -> Parammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm ++ Sendddddddddddddddddddddddddddddddddddddddddddd +) { +} + +pub trait SomeTrait: +Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ++ Eqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq +{ +} + +trait B = where +for<'b> &'b Self: Send ++ Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ++ Copyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy; diff --git a/tests/source/issue-4689/two.rs b/tests/source/issue-4689/two.rs new file mode 100644 index 0000000000000..ea7feda825d46 --- /dev/null +++ b/tests/source/issue-4689/two.rs @@ -0,0 +1,149 @@ +// rustfmt-version: Two + +// Based on the issue description +pub trait PrettyPrinter<'tcx>: +Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> +{ +// +} +pub trait PrettyPrinter<'tcx>: +Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> + fmt::Write +{ +// +} +pub trait PrettyPrinter<'tcx>: +Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> + fmt::Write1 + fmt::Write2 +{ +// +} +pub trait PrettyPrinter<'tcx>: +fmt::Write + Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> +{ +// +} +pub trait PrettyPrinter<'tcx>: +fmt::Write + Printer1< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> + Printer2< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> +{ +// +} + +// Some test cases to ensure other cases formatting were not changed +fn f() -> Box< +FnMut() -> Thing< +WithType = LongItemName, +Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, +>, +> { +} +fn f() -> Box< +FnMut() -> Thing< +WithType = LongItemName, +Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, +> + fmt::Write1 ++ fmt::Write2, +> { +} + +fn foo(foo2: F) +where +F: Fn( +// this comment is deleted +) +{ +} +fn foo(foo2: F) +where +F: Fn( +// this comment is deleted +) + fmt::Write +{ +} + +fn elaborate_bounds(mut mk_cand: F) +where +F: for<> FnMut( +&mut ProbeContext<>, +ty::PolyTraitRefffffffffffffffffffffffffffffffff<>, +tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, +), +{ +} +fn elaborate_bounds(mut mk_cand: F) +where +F: for<> FnMut( +&mut ProbeContext<>, +ty::PolyTraitRefffffffffffffffffffffffffffffffff<>, +tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, +) + fmt::Write, +{ +} + +fn build_sorted_static_get_entry_names( +mut entries: entryyyyyyyy, +) -> ( +impl Fn( +AlphabeticalTraversal, +Seconddddddddddddddddddddddddddddddddddd +) -> Parammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm ++ Sendddddddddddddddddddddddddddddddddddddddddddd +) { +} + +pub trait SomeTrait: +Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ++ Eqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq +{ +} + +trait B = where +for<'b> &'b Self: Send ++ Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ++ Copyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy; diff --git a/tests/target/issue-4689/one.rs b/tests/target/issue-4689/one.rs new file mode 100644 index 0000000000000..df1a507bc1da9 --- /dev/null +++ b/tests/target/issue-4689/one.rs @@ -0,0 +1,150 @@ +// rustfmt-version: One + +// Based on the issue description +pub trait PrettyPrinter<'tcx>: + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > +{ + // +} +pub trait PrettyPrinter<'tcx>: + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > + fmt::Write +{ + // +} +pub trait PrettyPrinter<'tcx>: + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > + fmt::Write1 + + fmt::Write2 +{ + // +} +pub trait PrettyPrinter<'tcx>: + fmt::Write + + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > +{ + // +} +pub trait PrettyPrinter<'tcx>: + fmt::Write + + Printer1< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > + Printer2< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > +{ + // +} + +// Some test cases to ensure other cases formatting were not changed +fn f() -> Box< + FnMut() -> Thing< + WithType = LongItemName, + Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, + >, +> { +} +fn f() -> Box< + FnMut() -> Thing< + WithType = LongItemName, + Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, + > + fmt::Write1 + + fmt::Write2, +> { +} + +fn foo(foo2: F) +where + F: Fn( + // this comment is deleted + ), +{ +} +fn foo(foo2: F) +where + F: Fn( + // this comment is deleted + ) + fmt::Write, +{ +} + +fn elaborate_bounds(mut mk_cand: F) +where + F: FnMut( + &mut ProbeContext, + ty::PolyTraitRefffffffffffffffffffffffffffffffff, + tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, + ), +{ +} +fn elaborate_bounds(mut mk_cand: F) +where + F: FnMut( + &mut ProbeContext, + ty::PolyTraitRefffffffffffffffffffffffffffffffff, + tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, + ) + fmt::Write, +{ +} + +fn build_sorted_static_get_entry_names( + mut entries: entryyyyyyyy, +) -> (impl Fn( + AlphabeticalTraversal, + Seconddddddddddddddddddddddddddddddddddd, +) -> Parammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + + Sendddddddddddddddddddddddddddddddddddddddddddd) { +} + +pub trait SomeTrait: + Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee + + Eqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq +{ +} + +trait B = where + for<'b> &'b Self: Send + + Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee + + Copyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy; diff --git a/tests/target/issue-4689/two.rs b/tests/target/issue-4689/two.rs new file mode 100644 index 0000000000000..e3b5cd22810ba --- /dev/null +++ b/tests/target/issue-4689/two.rs @@ -0,0 +1,152 @@ +// rustfmt-version: Two + +// Based on the issue description +pub trait PrettyPrinter<'tcx>: + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > +{ + // +} +pub trait PrettyPrinter<'tcx>: + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > + fmt::Write +{ + // +} +pub trait PrettyPrinter<'tcx>: + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > + fmt::Write1 + + fmt::Write2 +{ + // +} +pub trait PrettyPrinter<'tcx>: + fmt::Write + + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > +{ + // +} +pub trait PrettyPrinter<'tcx>: + fmt::Write + + Printer1< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > + Printer2< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > +{ + // +} + +// Some test cases to ensure other cases formatting were not changed +fn f() -> Box< + FnMut() -> Thing< + WithType = LongItemName, + Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, + >, +> { +} +fn f() -> Box< + FnMut() -> Thing< + WithType = LongItemName, + Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, + > + fmt::Write1 + + fmt::Write2, +> { +} + +fn foo(foo2: F) +where + F: Fn( + // this comment is deleted + ), +{ +} +fn foo(foo2: F) +where + F: Fn( + // this comment is deleted + ) + fmt::Write, +{ +} + +fn elaborate_bounds(mut mk_cand: F) +where + F: FnMut( + &mut ProbeContext, + ty::PolyTraitRefffffffffffffffffffffffffffffffff, + tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, + ), +{ +} +fn elaborate_bounds(mut mk_cand: F) +where + F: FnMut( + &mut ProbeContext, + ty::PolyTraitRefffffffffffffffffffffffffffffffff, + tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, + ) + fmt::Write, +{ +} + +fn build_sorted_static_get_entry_names( + mut entries: entryyyyyyyy, +) -> ( + impl Fn( + AlphabeticalTraversal, + Seconddddddddddddddddddddddddddddddddddd, + ) -> Parammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + + Sendddddddddddddddddddddddddddddddddddddddddddd +) { +} + +pub trait SomeTrait: + Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee + + Eqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq +{ +} + +trait B = where + for<'b> &'b Self: Send + + Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee + + Copyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy; From 76be14b5cadd56e18af721c830c5592621b19cb7 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 7 Aug 2022 15:21:11 +0200 Subject: [PATCH 032/500] Do not consider method call receiver as an argument in AST. --- src/chains.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index e26e24ec55ad6..fcc02eca42987 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -145,7 +145,7 @@ impl ChainItemKind { fn from_ast(context: &RewriteContext<'_>, expr: &ast::Expr) -> (ChainItemKind, Span) { let (kind, span) = match expr.kind { - ast::ExprKind::MethodCall(ref segment, ref expressions, _) => { + ast::ExprKind::MethodCall(ref segment, ref receiver, ref expressions, _) => { let types = if let Some(ref generic_args) = segment.args { if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args { data.args @@ -163,7 +163,7 @@ impl ChainItemKind { } else { vec![] }; - let span = mk_sp(expressions[0].span.hi(), expr.span.hi()); + let span = mk_sp(receiver.span.hi(), expr.span.hi()); let kind = ChainItemKind::MethodCall(segment.clone(), types, expressions.clone()); (kind, span) } @@ -253,7 +253,7 @@ impl ChainItem { format!("::<{}>", type_list.join(", ")) }; let callee_str = format!(".{}{}", rewrite_ident(context, method_name), type_str); - rewrite_call(context, &callee_str, &args[1..], span, shape) + rewrite_call(context, &callee_str, &args, span, shape) } } @@ -400,8 +400,8 @@ impl Chain { // is a try! macro, we'll convert it to shorthand when the option is set. fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext<'_>) -> Option { match expr.kind { - ast::ExprKind::MethodCall(_, ref expressions, _) => { - Some(Self::convert_try(&expressions[0], context)) + ast::ExprKind::MethodCall(_, ref receiver, _, _) => { + Some(Self::convert_try(&receiver, context)) } ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) From 949da529d7a0b348376f67e77676a8722ad21899 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Mon, 1 Aug 2022 00:29:32 -0400 Subject: [PATCH 033/500] Add GitHub Action to test master rustfmt formatting vs a feature branch This new action is intended to help us maintainers determine when feature branches cause breaking formatting changes by running rustfmt (master) and the feature branch on various rust repositories. Over time I expect the list of checked projects to increase. With this action in place we can more easily test that a new feature or bug fix doesn't introduce breaking changes. Although this action needs to be manually triggered right now, we might consider adding it to our CI runs in the future. --- .github/workflows/check_diff.yml | 33 +++++ ci/check_diff.sh | 199 +++++++++++++++++++++++++++++++ 2 files changed, 232 insertions(+) create mode 100644 .github/workflows/check_diff.yml create mode 100755 ci/check_diff.sh diff --git a/.github/workflows/check_diff.yml b/.github/workflows/check_diff.yml new file mode 100644 index 0000000000000..8bfb5834519cd --- /dev/null +++ b/.github/workflows/check_diff.yml @@ -0,0 +1,33 @@ +name: Diff Check +on: + workflow_dispatch: + inputs: + clone_url: + description: 'Git url of a rustfmt fork to compare against the latest master rustfmt' + required: true + branch_name: + description: 'Name of the feature branch on the forked repo' + required: true + commit_hash: + description: 'Optional commit hash from the feature branch' + required: false + rustfmt_configs: + description: 'Optional comma separated list of rustfmt config options to pass when running the feature branch' + required: false + +jobs: + diff_check: + runs-on: ubuntu-latest + + steps: + - name: checkout + uses: actions/checkout@v3 + + - name: install rustup + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rustup-init.sh + sh rustup-init.sh -y --default-toolchain none + rustup target add x86_64-unknown-linux-gnu + + - name: check diff + run: bash ${GITHUB_WORKSPACE}/ci/check_diff.sh ${{ github.event.inputs.clone_url }} ${{ github.event.inputs.branch_name }} ${{ github.event.inputs.commit_hash }} ${{ github.event.inputs.rustfmt_configs }} diff --git a/ci/check_diff.sh b/ci/check_diff.sh new file mode 100755 index 0000000000000..062c2dd8673ab --- /dev/null +++ b/ci/check_diff.sh @@ -0,0 +1,199 @@ +#!/bin/bash + +function print_usage() { + echo "usage check_diff REMOTE_REPO FEATURE_BRANCH [COMMIT_HASH] [OPTIONAL_RUSTFMT_CONFIGS]" +} + +if [ $# -le 1 ]; then + print_usage + exit 1 +fi + +REMOTE_REPO=$1 +FEATURE_BRANCH=$2 +OPTIONAL_COMMIT_HASH=$3 +OPTIONAL_RUSTFMT_CONFIGS=$4 + +# OUTPUT array used to collect all the status of running diffs on various repos +STATUSES=() + +# Clone a git repository and cd into it. +# +# Parameters: +# $1: git clone url +# $2: directory where the repo should be cloned +function clone_repo() { + GIT_TERMINAL_PROMPT=0 git clone --quiet $1 --depth 1 $2 && cd $2 +} + +# Initialize Git submoduels for the repo. +# +# Parameters +# $1: list of directories to initialize +function init_submodules() { + git submodule update --init $1 +} + +# Run rusfmt with the --check flag to see if a diff is produced. +# +# Parameters: +# $1: Path to a rustfmt binary +# $2: Output file path for the diff +# $3: Any additional configuration options to pass to rustfmt +# +# Globlas: +# $OPTIONAL_RUSTFMT_CONFIGS: Optional configs passed to the script from $4 +function create_diff() { + local config; + if [ -z "$3" ]; then + config="--config=error_on_line_overflow=false,error_on_unformatted=false" + else + config="--config=error_on_line_overflow=false,error_on_unformatted=false,$OPTIONAL_RUSTFMT_CONFIGS" + fi + + for i in `find . | grep "\.rs$"` + do + $1 --unstable-features --skip-children --check --color=always $config $i >> $2 2>/dev/null + done +} + +# Run the master rustfmt binary and the feature branch binary in the current directory and compare the diffs +# +# Parameters +# $1: Name of the repository (used for logging) +# +# Globlas: +# $RUSFMT_BIN: Path to the rustfmt master binary. Created when running `compile_rustfmt` +# $FEATURE_BIN: Path to the rustfmt feature binary. Created when running `compile_rustfmt` +# $OPTIONAL_RUSTFMT_CONFIGS: Optional configs passed to the script from $4 +function check_diff() { + echo "running rustfmt (master) on $1" + create_diff $RUSFMT_BIN rustfmt_diff.txt + + echo "running rustfmt (feature) on $1" + create_diff $FEATURE_BIN feature_diff.txt $OPTIONAL_RUSTFMT_CONFIGS + + echo "checking diff" + local diff; + # we don't add color to the diff since we added color when running rustfmt --check. + # tail -n + 6 removes the git diff header info + # cut -c 2- removes the leading diff characters("+","-"," ") from running git diff. + # Again, the diff output we care about was already added when we ran rustfmt --check + diff=$( + git --no-pager diff --color=never \ + --unified=0 --no-index rustfmt_diff.txt feature_diff.txt 2>&1 | tail -n +6 | cut -c 2- + ) + + if [ -z "$diff" ]; then + echo "no diff detected between rustfmt and the feture branch" + return 0 + else + echo "$diff" + return 1 + fi +} + +# Compiles and produces two rustfmt binaries. +# One for the current master, and another for the feature branch +# +# Parameters: +# $1: Directory where rustfmt will be cloned +# +# Globlas: +# $REMOTE_REPO: Clone URL to the rustfmt fork that we want to test +# $FEATURE_BRANCH: Name of the feature branch +# $OPTIONAL_COMMIT_HASH: Optional commit hash that will be checked out if provided +function compile_rustfmt() { + RUSTFMT_REPO="https://github.com/rust-lang/rustfmt.git" + clone_repo $RUSTFMT_REPO $1 + git remote add feature $REMOTE_REPO + git fetch feature $FEATURE_BRANCH + + cargo build --release --bin rustfmt && cp target/release/rustfmt $1/rustfmt + if [ -z "$OPTIONAL_COMMIT_HASH" ]; then + git switch $FEATURE_BRANCH + else + git switch $OPTIONAL_COMMIT_HASH --detach + fi + cargo build --release --bin rustfmt && cp target/release/rustfmt $1/feature_rustfmt + RUSFMT_BIN=$1/rustfmt + FEATURE_BIN=$1/feature_rustfmt +} + +# Check the diff for running rustfmt and the feature branch on all the .rs files in the repo. +# +# Parameters +# $1: Clone URL for the repo +# $2: Name of the repo (mostly used for logging) +# $3: Path to any submodules that should be initialized +function check_repo() { + WORKDIR=$(pwd) + REPO_URL=$1 + REPO_NAME=$2 + SUBMODULES=$3 + + local tmp_dir; + tmp_dir=$(mktemp -d -t $REPO_NAME-XXXXXXXX) + clone_repo $REPO_URL $tmp_dir + + if [ ! -z "$SUBMODULES" ]; then + init_submodules $SUBMODULES + fi + + check_diff $REPO_NAME + # append the status of running `check_diff` to the STATUSES array + STATUSES+=($?) + + echo "removing tmp_dir $tmp_dir" + rm -rf $tmp_dir + cd $WORKDIR +} + +function main() { + tmp_dir=$(mktemp -d -t rustfmt-XXXXXXXX) + echo Created tmp_dir $tmp_dir + + compile_rustfmt $tmp_dir + + # run checks + check_repo "https://github.com/rust-lang/rust.git" rust-lang-rust + check_repo "https://github.com/rust-lang/cargo.git" cargo + check_repo "https://github.com/rust-lang/miri.git" miri + check_repo "https://github.com/rust-lang/rust-analyzer.git" rust-analyzer + check_repo "https://github.com/bitflags/bitflags.git" bitflags + check_repo "https://github.com/rust-lang/log.git" log + check_repo "https://github.com/rust-lang/mdBook.git" mdBook + check_repo "https://github.com/rust-lang/packed_simd.git" packed_simd + check_repo "https://github.com/rust-lang/rust-semverver.git" check_repo + check_repo "https://github.com/Stebalien/tempfile.git" tempfile + check_repo "https://github.com/rust-lang/futures-rs.git" futures-rs + check_repo "https://github.com/dtolnay/anyhow.git" anyhow + check_repo "https://github.com/dtolnay/thiserror.git" thiserror + check_repo "https://github.com/dtolnay/syn.git" syn + check_repo "https://github.com/serde-rs/serde.git" serde + check_repo "https://github.com/rust-lang/rustlings.git" rustlings + check_repo "https://github.com/rust-lang/rustup.git" rustup + check_repo "https://github.com/SergioBenitez/Rocket.git" Rocket + check_repo "https://github.com/rustls/rustls.git" rustls + check_repo "https://github.com/rust-lang/rust-bindgen.git" rust-bindgen + check_repo "https://github.com/hyperium/hyper.git" hyper + check_repo "https://github.com/actix/actix.git" actix + check_repo "https://github.com/denoland/deno.git" denoland_deno + + # cleanup temp dir + echo removing tmp_dir $tmp_dir + rm -rf $tmp_dir + + # figure out the exit code + for status in ${STATUSES[@]} + do + if [ $status -eq 1 ]; then + echo "formatting diff found 💔" + return 1 + fi + done + + echo "no diff found 😊" +} + +main From edb616df3372e75bb501b871906901b834821106 Mon Sep 17 00:00:00 2001 From: David Wood Date: Wed, 10 Aug 2022 17:30:47 +0100 Subject: [PATCH 034/500] errors: move translation logic into module Just moving code around so that triagebot can ping relevant parties when translation logic is modified. Signed-off-by: David Wood --- src/parse/session.rs | 52 ++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/src/parse/session.rs b/src/parse/session.rs index 23db542191036..6efeee98fea6c 100644 --- a/src/parse/session.rs +++ b/src/parse/session.rs @@ -3,6 +3,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use rustc_data_structures::sync::{Lrc, Send}; use rustc_errors::emitter::{Emitter, EmitterWriter}; +use rustc_errors::translation::Translate; use rustc_errors::{ColorConfig, Diagnostic, Handler, Level as DiagnosticLevel}; use rustc_session::parse::ParseSess as RawParseSess; use rustc_span::{ @@ -28,19 +29,24 @@ pub(crate) struct ParseSess { /// Emitter which discards every error. struct SilentEmitter; -impl Emitter for SilentEmitter { - fn source_map(&self) -> Option<&Lrc> { - None - } - fn emit_diagnostic(&mut self, _db: &Diagnostic) {} +impl Translate for SilentEmitter { fn fluent_bundle(&self) -> Option<&Lrc> { None } + fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { panic!("silent emitter attempted to translate a diagnostic"); } } +impl Emitter for SilentEmitter { + fn source_map(&self) -> Option<&Lrc> { + None + } + + fn emit_diagnostic(&mut self, _db: &Diagnostic) {} +} + fn silent_emitter() -> Box { Box::new(SilentEmitter {}) } @@ -62,10 +68,21 @@ impl SilentOnIgnoredFilesEmitter { } } +impl Translate for SilentOnIgnoredFilesEmitter { + fn fluent_bundle(&self) -> Option<&Lrc> { + self.emitter.fluent_bundle() + } + + fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { + self.emitter.fallback_fluent_bundle() + } +} + impl Emitter for SilentOnIgnoredFilesEmitter { fn source_map(&self) -> Option<&Lrc> { None } + fn emit_diagnostic(&mut self, db: &Diagnostic) { if db.level() == DiagnosticLevel::Fatal { return self.handle_non_ignoreable_error(db); @@ -88,14 +105,6 @@ impl Emitter for SilentOnIgnoredFilesEmitter { } self.handle_non_ignoreable_error(db); } - - fn fluent_bundle(&self) -> Option<&Lrc> { - self.emitter.fluent_bundle() - } - - fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { - self.emitter.fallback_fluent_bundle() - } } fn default_handler( @@ -340,19 +349,24 @@ mod tests { num_emitted_errors: Lrc, } + impl Translate for TestEmitter { + fn fluent_bundle(&self) -> Option<&Lrc> { + None + } + + fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { + panic!("test emitter attempted to translate a diagnostic"); + } + } + impl Emitter for TestEmitter { fn source_map(&self) -> Option<&Lrc> { None } + fn emit_diagnostic(&mut self, _db: &Diagnostic) { self.num_emitted_errors.fetch_add(1, Ordering::Release); } - fn fluent_bundle(&self) -> Option<&Lrc> { - None - } - fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { - panic!("test emitter attempted to translate a diagnostic"); - } } fn build_diagnostic(level: DiagnosticLevel, span: Option) -> Diagnostic { From e97825ed5ef3975ff6b138e16147802979df4ef3 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 11 Aug 2022 21:06:11 +1000 Subject: [PATCH 035/500] Shrink `ast::Attribute`. --- src/skip.rs | 4 ++-- src/visitor.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/skip.rs b/src/skip.rs index 0fdc097efc23f..032922d421df7 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -58,8 +58,8 @@ fn get_skip_names(kind: &str, attrs: &[ast::Attribute]) -> Vec { for attr in attrs { // rustc_ast::ast::Path is implemented partialEq // but it is designed for segments.len() == 1 - if let ast::AttrKind::Normal(attr_item, _) = &attr.kind { - if pprust::path_to_string(&attr_item.path) != path { + if let ast::AttrKind::Normal(normal) = &attr.kind { + if pprust::path_to_string(&normal.item.path) != path { continue; } } diff --git a/src/visitor.rs b/src/visitor.rs index 9a0e0752c12f5..7bb745eeb8b9b 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -811,8 +811,8 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ); } else { match &attr.kind { - ast::AttrKind::Normal(ref attribute_item, _) - if self.is_unknown_rustfmt_attr(&attribute_item.path.segments) => + ast::AttrKind::Normal(ref normal) + if self.is_unknown_rustfmt_attr(&normal.item.path.segments) => { let file_name = self.parse_sess.span_to_filename(attr.span); self.report.append( From e5b5f56d4329159961095bdaca3f608fc097f930 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 1 Aug 2022 16:46:08 +1000 Subject: [PATCH 036/500] Rename some things related to literals. - Rename `ast::Lit::token` as `ast::Lit::token_lit`, because its type is `token::Lit`, which is not a token. (This has been confusing me for a long time.) reasonable because we have an `ast::token::Lit` inside an `ast::Lit`. - Rename `LitKind::{from,to}_lit_token` as `LitKind::{from,to}_token_lit`, to match the above change and `token::Lit`. --- src/expr.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/expr.rs b/src/expr.rs index a7b73ba78c59e..3105882e2d308 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -79,7 +79,7 @@ pub(crate) fn format_expr( if let Some(expr_rw) = rewrite_literal(context, l, shape) { Some(expr_rw) } else { - if let LitKind::StrRaw(_) = l.token.kind { + if let LitKind::StrRaw(_) = l.token_lit.kind { Some(context.snippet(l.span).trim().into()) } else { None @@ -1226,7 +1226,7 @@ fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) -> Option { let span = lit.span; - let symbol = lit.token.symbol.as_str(); + let symbol = lit.token_lit.symbol.as_str(); if let Some(symbol_stripped) = symbol.strip_prefix("0x") { let hex_lit = match context.config.hex_literal_case() { @@ -1239,7 +1239,9 @@ fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) - format!( "0x{}{}", hex_lit, - lit.token.suffix.map_or(String::new(), |s| s.to_string()) + lit.token_lit + .suffix + .map_or(String::new(), |s| s.to_string()) ), context.config.max_width(), shape, From 38659ec6ad5f341cf8eb3139725bf695872c6de7 Mon Sep 17 00:00:00 2001 From: A-Walrus <58790821+A-Walrus@users.noreply.github.com> Date: Fri, 19 Aug 2022 02:44:29 +0300 Subject: [PATCH 037/500] Unicode comment align (#5505) * Fix comment alignment with unicode Also added tests for this behaviour * Simplify tests * Improve tests --- src/lists.rs | 16 ++-- tests/source/comments_unicode.rs | 140 +++++++++++++++++++++++++++++++ tests/target/comments_unicode.rs | 140 +++++++++++++++++++++++++++++++ 3 files changed, 288 insertions(+), 8 deletions(-) create mode 100644 tests/source/comments_unicode.rs create mode 100644 tests/target/comments_unicode.rs diff --git a/src/lists.rs b/src/lists.rs index e87850507824f..a878e6cf9b2fc 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -297,9 +297,9 @@ where } else { inner_item.as_ref() }; - let mut item_last_line_width = item_last_line.len() + item_sep_len; + let mut item_last_line_width = unicode_str_width(item_last_line) + item_sep_len; if item_last_line.starts_with(&**indent_str) { - item_last_line_width -= indent_str.len(); + item_last_line_width -= unicode_str_width(indent_str); } if !item.is_substantial() { @@ -449,7 +449,7 @@ where } else if starts_with_newline(comment) { false } else { - comment.trim().contains('\n') || comment.trim().len() > width + comment.trim().contains('\n') || unicode_str_width(comment.trim()) > width }; rewrite_comment( @@ -465,7 +465,7 @@ where if !starts_with_newline(comment) { if formatting.align_comments { let mut comment_alignment = - post_comment_alignment(item_max_width, inner_item.len()); + post_comment_alignment(item_max_width, unicode_str_width(inner_item)); if first_line_width(&formatted_comment) + last_line_width(&result) + comment_alignment @@ -475,7 +475,7 @@ where item_max_width = None; formatted_comment = rewrite_post_comment(&mut item_max_width)?; comment_alignment = - post_comment_alignment(item_max_width, inner_item.len()); + post_comment_alignment(item_max_width, unicode_str_width(inner_item)); } for _ in 0..=comment_alignment { result.push(' '); @@ -533,7 +533,7 @@ where let mut first = true; for item in items.clone().into_iter().skip(i) { let item = item.as_ref(); - let inner_item_width = item.inner_as_ref().len(); + let inner_item_width = unicode_str_width(item.inner_as_ref()); if !first && (item.is_different_group() || item.post_comment.is_none() @@ -552,8 +552,8 @@ where max_width } -fn post_comment_alignment(item_max_width: Option, inner_item_len: usize) -> usize { - item_max_width.unwrap_or(0).saturating_sub(inner_item_len) +fn post_comment_alignment(item_max_width: Option, inner_item_width: usize) -> usize { + item_max_width.unwrap_or(0).saturating_sub(inner_item_width) } pub(crate) struct ListItems<'a, I, F1, F2, F3> diff --git a/tests/source/comments_unicode.rs b/tests/source/comments_unicode.rs new file mode 100644 index 0000000000000..e65a245ba9343 --- /dev/null +++ b/tests/source/comments_unicode.rs @@ -0,0 +1,140 @@ +impl Default for WhitespaceCharacters { + fn default() -> Self { + Self { + space: '·', // U+00B7 + nbsp: '⍽', // U+237D + tab: '→', // U+2192 + newline: '⏎', // U+23CE + } + } +} + +const RAINBOWS: &[&str] = &[ + "rаinЬοѡ", // hue: 0 + "raіnЬοw", // hue: 2 + "rаіɴЬow", // hue: 2 + "raіɴЬoѡ", // hue: 8 + "ʀainЬow", // hue: 8 + "ʀaіɴboѡ", // hue: 8 + "ʀаіnbοw", // hue: 11 + "rainЬoѡ", // hue: 14 + "raіɴbow", // hue: 14 + "rаiɴЬow", // hue: 20 + "raіnЬow", // hue: 26 + "ʀaiɴbοw", // hue: 32 + "raіɴboѡ", // hue: 35 + "rаiɴbow", // hue: 35 + "rаіnbοw", // hue: 38 + "rаinЬow", // hue: 47 + "ʀaіnboѡ", // hue: 47 + "ʀaіnЬoѡ", // hue: 47 + "ʀаіɴbοw", // hue: 53 + "ʀaіnЬοѡ", // hue: 57 + "raiɴЬoѡ", // hue: 68 + "ʀainbοѡ", // hue: 68 + "ʀаinboѡ", // hue: 68 + "ʀаiɴbοw", // hue: 68 + "ʀаіnbow", // hue: 68 + "rаіnЬοѡ", // hue: 69 + "ʀainЬοw", // hue: 71 + "raiɴbow", // hue: 73 + "raіnЬoѡ", // hue: 74 + "rаіɴbοw", // hue: 77 + "raіnЬοѡ", // hue: 81 + "raiɴЬow", // hue: 83 + "ʀainbοw", // hue: 83 + "ʀаinbow", // hue: 83 + "ʀаiɴbοѡ", // hue: 83 + "ʀаіnboѡ", // hue: 83 + "ʀаіɴЬοѡ", // hue: 84 + "rainЬow", // hue: 85 + "ʀаiɴЬοw", // hue: 86 + "ʀаіnbοѡ", // hue: 89 + "ʀаіnЬοw", // hue: 92 + "rаiɴbοw", // hue: 95 + "ʀаіɴbοѡ", // hue: 98 + "ʀаiɴЬοѡ", // hue: 99 + "raіnbοw", // hue: 101 + "ʀаіɴЬοw", // hue: 101 + "ʀaiɴboѡ", // hue: 104 + "ʀаinbοѡ", // hue: 104 + "rаiɴbοѡ", // hue: 107 + "ʀаinЬοw", // hue: 107 + "rаiɴЬοw", // hue: 110 + "rаіnboѡ", // hue: 110 + "rаіnbοѡ", // hue: 113 + "ʀainЬοѡ", // hue: 114 + "rаіnЬοw", // hue: 116 + "ʀaіɴЬow", // hue: 116 + "rаinbοw", // hue: 122 + "ʀаіɴboѡ", // hue: 125 + "rаinbοѡ", // hue: 131 + "rainbow", // hue: 134 + "rаinЬοw", // hue: 134 + "ʀаiɴboѡ", // hue: 140 + "rainЬοѡ", // hue: 141 + "raіɴЬow", // hue: 143 + "ʀainЬoѡ", // hue: 143 + "ʀaіɴbow", // hue: 143 + "ʀainbow", // hue: 148 + "rаіɴboѡ", // hue: 149 + "ʀainboѡ", // hue: 155 + "ʀaіnbow", // hue: 155 + "ʀaіnЬow", // hue: 155 + "raiɴbοw", // hue: 158 + "ʀаiɴЬoѡ", // hue: 158 + "rainbοw", // hue: 160 + "rаinbow", // hue: 160 + "ʀaіɴbοѡ", // hue: 164 + "ʀаiɴbow", // hue: 164 + "ʀаіnЬoѡ", // hue: 164 + "ʀaiɴЬοѡ", // hue: 165 + "rаiɴboѡ", // hue: 167 + "ʀaіɴЬοw", // hue: 167 + "ʀaіɴЬοѡ", // hue: 171 + "raіnboѡ", // hue: 173 + "ʀаіɴЬoѡ", // hue: 173 + "rаіɴbοѡ", // hue: 176 + "ʀаinЬow", // hue: 176 + "rаiɴЬοѡ", // hue: 177 + "rаіɴЬοw", // hue: 179 + "ʀаinЬoѡ", // hue: 179 + "ʀаіɴbow", // hue: 179 + "rаiɴЬoѡ", // hue: 182 + "raіɴbοѡ", // hue: 188 + "rаіnЬoѡ", // hue: 188 + "raiɴЬοѡ", // hue: 189 + "raіɴЬοw", // hue: 191 + "ʀaіɴbοw", // hue: 191 + "ʀаіnЬow", // hue: 191 + "rainbοѡ", // hue: 194 + "rаinboѡ", // hue: 194 + "rаіnbow", // hue: 194 + "rainЬοw", // hue: 197 + "rаinЬoѡ", // hue: 206 + "rаіɴbow", // hue: 206 + "rаіɴЬοѡ", // hue: 210 + "ʀaiɴЬow", // hue: 212 + "raіɴbοw", // hue: 218 + "rаіnЬow", // hue: 218 + "ʀaiɴbοѡ", // hue: 221 + "ʀaiɴЬοw", // hue: 224 + "ʀaіnbοѡ", // hue: 227 + "raiɴboѡ", // hue: 230 + "ʀaіnbοw", // hue: 230 + "ʀaіnЬοw", // hue: 230 + "ʀаinЬοѡ", // hue: 231 + "rainboѡ", // hue: 232 + "raіnbow", // hue: 232 + "ʀаіɴЬow", // hue: 233 + "ʀaіɴЬoѡ", // hue: 239 + "ʀаіnЬοѡ", // hue: 246 + "raiɴbοѡ", // hue: 248 + "ʀаiɴЬow", // hue: 248 + "raіɴЬοѡ", // hue: 249 + "raiɴЬοw", // hue: 251 + "rаіɴЬoѡ", // hue: 251 + "ʀaiɴbow", // hue: 251 + "ʀаinbοw", // hue: 251 + "raіnbοѡ", // hue: 254 +]; diff --git a/tests/target/comments_unicode.rs b/tests/target/comments_unicode.rs new file mode 100644 index 0000000000000..3e1b6b0a28fe4 --- /dev/null +++ b/tests/target/comments_unicode.rs @@ -0,0 +1,140 @@ +impl Default for WhitespaceCharacters { + fn default() -> Self { + Self { + space: '·', // U+00B7 + nbsp: '⍽', // U+237D + tab: '→', // U+2192 + newline: '⏎', // U+23CE + } + } +} + +const RAINBOWS: &[&str] = &[ + "rаinЬοѡ", // hue: 0 + "raіnЬοw", // hue: 2 + "rаіɴЬow", // hue: 2 + "raіɴЬoѡ", // hue: 8 + "ʀainЬow", // hue: 8 + "ʀaіɴboѡ", // hue: 8 + "ʀаіnbοw", // hue: 11 + "rainЬoѡ", // hue: 14 + "raіɴbow", // hue: 14 + "rаiɴЬow", // hue: 20 + "raіnЬow", // hue: 26 + "ʀaiɴbοw", // hue: 32 + "raіɴboѡ", // hue: 35 + "rаiɴbow", // hue: 35 + "rаіnbοw", // hue: 38 + "rаinЬow", // hue: 47 + "ʀaіnboѡ", // hue: 47 + "ʀaіnЬoѡ", // hue: 47 + "ʀаіɴbοw", // hue: 53 + "ʀaіnЬοѡ", // hue: 57 + "raiɴЬoѡ", // hue: 68 + "ʀainbοѡ", // hue: 68 + "ʀаinboѡ", // hue: 68 + "ʀаiɴbοw", // hue: 68 + "ʀаіnbow", // hue: 68 + "rаіnЬοѡ", // hue: 69 + "ʀainЬοw", // hue: 71 + "raiɴbow", // hue: 73 + "raіnЬoѡ", // hue: 74 + "rаіɴbοw", // hue: 77 + "raіnЬοѡ", // hue: 81 + "raiɴЬow", // hue: 83 + "ʀainbοw", // hue: 83 + "ʀаinbow", // hue: 83 + "ʀаiɴbοѡ", // hue: 83 + "ʀаіnboѡ", // hue: 83 + "ʀаіɴЬοѡ", // hue: 84 + "rainЬow", // hue: 85 + "ʀаiɴЬοw", // hue: 86 + "ʀаіnbοѡ", // hue: 89 + "ʀаіnЬοw", // hue: 92 + "rаiɴbοw", // hue: 95 + "ʀаіɴbοѡ", // hue: 98 + "ʀаiɴЬοѡ", // hue: 99 + "raіnbοw", // hue: 101 + "ʀаіɴЬοw", // hue: 101 + "ʀaiɴboѡ", // hue: 104 + "ʀаinbοѡ", // hue: 104 + "rаiɴbοѡ", // hue: 107 + "ʀаinЬοw", // hue: 107 + "rаiɴЬοw", // hue: 110 + "rаіnboѡ", // hue: 110 + "rаіnbοѡ", // hue: 113 + "ʀainЬοѡ", // hue: 114 + "rаіnЬοw", // hue: 116 + "ʀaіɴЬow", // hue: 116 + "rаinbοw", // hue: 122 + "ʀаіɴboѡ", // hue: 125 + "rаinbοѡ", // hue: 131 + "rainbow", // hue: 134 + "rаinЬοw", // hue: 134 + "ʀаiɴboѡ", // hue: 140 + "rainЬοѡ", // hue: 141 + "raіɴЬow", // hue: 143 + "ʀainЬoѡ", // hue: 143 + "ʀaіɴbow", // hue: 143 + "ʀainbow", // hue: 148 + "rаіɴboѡ", // hue: 149 + "ʀainboѡ", // hue: 155 + "ʀaіnbow", // hue: 155 + "ʀaіnЬow", // hue: 155 + "raiɴbοw", // hue: 158 + "ʀаiɴЬoѡ", // hue: 158 + "rainbοw", // hue: 160 + "rаinbow", // hue: 160 + "ʀaіɴbοѡ", // hue: 164 + "ʀаiɴbow", // hue: 164 + "ʀаіnЬoѡ", // hue: 164 + "ʀaiɴЬοѡ", // hue: 165 + "rаiɴboѡ", // hue: 167 + "ʀaіɴЬοw", // hue: 167 + "ʀaіɴЬοѡ", // hue: 171 + "raіnboѡ", // hue: 173 + "ʀаіɴЬoѡ", // hue: 173 + "rаіɴbοѡ", // hue: 176 + "ʀаinЬow", // hue: 176 + "rаiɴЬοѡ", // hue: 177 + "rаіɴЬοw", // hue: 179 + "ʀаinЬoѡ", // hue: 179 + "ʀаіɴbow", // hue: 179 + "rаiɴЬoѡ", // hue: 182 + "raіɴbοѡ", // hue: 188 + "rаіnЬoѡ", // hue: 188 + "raiɴЬοѡ", // hue: 189 + "raіɴЬοw", // hue: 191 + "ʀaіɴbοw", // hue: 191 + "ʀаіnЬow", // hue: 191 + "rainbοѡ", // hue: 194 + "rаinboѡ", // hue: 194 + "rаіnbow", // hue: 194 + "rainЬοw", // hue: 197 + "rаinЬoѡ", // hue: 206 + "rаіɴbow", // hue: 206 + "rаіɴЬοѡ", // hue: 210 + "ʀaiɴЬow", // hue: 212 + "raіɴbοw", // hue: 218 + "rаіnЬow", // hue: 218 + "ʀaiɴbοѡ", // hue: 221 + "ʀaiɴЬοw", // hue: 224 + "ʀaіnbοѡ", // hue: 227 + "raiɴboѡ", // hue: 230 + "ʀaіnbοw", // hue: 230 + "ʀaіnЬοw", // hue: 230 + "ʀаinЬοѡ", // hue: 231 + "rainboѡ", // hue: 232 + "raіnbow", // hue: 232 + "ʀаіɴЬow", // hue: 233 + "ʀaіɴЬoѡ", // hue: 239 + "ʀаіnЬοѡ", // hue: 246 + "raiɴbοѡ", // hue: 248 + "ʀаiɴЬow", // hue: 248 + "raіɴЬοѡ", // hue: 249 + "raiɴЬοw", // hue: 251 + "rаіɴЬoѡ", // hue: 251 + "ʀaiɴbow", // hue: 251 + "ʀаinbοw", // hue: 251 + "raіnbοѡ", // hue: 254 +]; From 05a0dfe8cd4db51a08d11ab24cc1586c833e2df1 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 17 Aug 2022 12:34:33 +1000 Subject: [PATCH 038/500] Use `AttrVec` in more places. In some places we use `Vec` and some places we use `ThinVec` (a.k.a. `AttrVec`). This results in various points where we have to convert between `Vec` and `ThinVec`. This commit changes the places that use `Vec` to use `AttrVec`. A lot of this is mechanical and boring, but there are some interesting parts: - It adds a few new methods to `ThinVec`. - It implements `MapInPlace` for `ThinVec`, and introduces a macro to avoid the repetition of this trait for `Vec`, `SmallVec`, and `ThinVec`. Overall, it makes the code a little nicer, and has little effect on performance. But it is a precursor to removing `rustc_data_structures::thin_vec::ThinVec` and replacing it with `thin_vec::ThinVec`, which is implemented more efficiently. --- src/attr.rs | 5 +---- src/imports.rs | 4 ++-- src/modules.rs | 8 ++++---- src/parse/parser.rs | 2 +- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index 41ba9a847e67a..f5c1ee5fdd121 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -49,10 +49,7 @@ pub(crate) fn get_span_without_attrs(stmt: &ast::Stmt) -> Span { } /// Returns attributes that are within `outer_span`. -pub(crate) fn filter_inline_attrs( - attrs: &[ast::Attribute], - outer_span: Span, -) -> Vec { +pub(crate) fn filter_inline_attrs(attrs: &[ast::Attribute], outer_span: Span) -> ast::AttrVec { attrs .iter() .filter(|a| outer_span.lo() <= a.span.lo() && a.span.hi() <= outer_span.hi()) diff --git a/src/imports.rs b/src/imports.rs index 8d41c881589e5..b6530c69243ed 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -116,7 +116,7 @@ pub(crate) struct UseTree { // Additional fields for top level use items. // Should we have another struct for top-level use items rather than reusing this? visibility: Option, - attrs: Option>, + attrs: Option, } impl PartialEq for UseTree { @@ -417,7 +417,7 @@ impl UseTree { list_item: Option, visibility: Option, opt_lo: Option, - attrs: Option>, + attrs: Option, ) -> UseTree { let span = if let Some(lo) = opt_lo { mk_sp(lo, a.span.hi()) diff --git a/src/modules.rs b/src/modules.rs index 81da724329f02..7a0d1736c59a6 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -26,7 +26,7 @@ type FileModMap<'ast> = BTreeMap>; pub(crate) struct Module<'a> { ast_mod_kind: Option>, pub(crate) items: Cow<'a, Vec>>, - inner_attr: Vec, + inner_attr: ast::AttrVec, pub(crate) span: Span, } @@ -35,7 +35,7 @@ impl<'a> Module<'a> { mod_span: Span, ast_mod_kind: Option>, mod_items: Cow<'a, Vec>>, - mod_attrs: Cow<'a, Vec>, + mod_attrs: Cow<'a, ast::AttrVec>, ) -> Self { let inner_attr = mod_attrs .iter() @@ -158,7 +158,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { module_item.item.span, Some(Cow::Owned(sub_mod_kind.clone())), Cow::Owned(vec![]), - Cow::Owned(vec![]), + Cow::Owned(ast::AttrVec::new()), ), )?; } @@ -185,7 +185,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { span, Some(Cow::Owned(sub_mod_kind.clone())), Cow::Owned(vec![]), - Cow::Owned(vec![]), + Cow::Owned(ast::AttrVec::new()), ), )?; } diff --git a/src/parse/parser.rs b/src/parse/parser.rs index 268c72649a65a..e0bd065518b3d 100644 --- a/src/parse/parser.rs +++ b/src/parse/parser.rs @@ -109,7 +109,7 @@ impl<'a> Parser<'a> { sess: &'a ParseSess, path: &Path, span: Span, - ) -> Result<(Vec, Vec>, Span), ParserError> { + ) -> Result<(ast::AttrVec, Vec>, Span), ParserError> { let result = catch_unwind(AssertUnwindSafe(|| { let mut parser = new_parser_from_file(sess.inner(), path, Some(span)); match parser.parse_mod(&TokenKind::Eof) { From 7852b8808b1691f956d8928b3f9ca140cf93feb8 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Thu, 14 Jul 2022 08:30:38 -0500 Subject: [PATCH 039/500] Stabilize `#![feature(label_break_value)]` # Stabilization proposal The feature was implemented in https://github.com/rust-lang/rust/pull/50045 by est31 and has been in nightly since 2018-05-16 (over 4 years now). There are [no open issues][issue-label] other than the tracking issue. There is a strong consensus that `break` is the right keyword and we should not use `return`. There have been several concerns raised about this feature on the tracking issue (other than the one about tests, which has been fixed, and an interaction with try blocks, which has been fixed). 1. nrc's original comment about cost-benefit analysis: https://github.com/rust-lang/rust/issues/48594#issuecomment-422235234 2. joshtriplett's comments about seeing use cases: https://github.com/rust-lang/rust/issues/48594#issuecomment-422281176 3. withoutboats's comments that Rust does not need more control flow constructs: https://github.com/rust-lang/rust/issues/48594#issuecomment-450050630 Many different examples of code that's simpler using this feature have been provided: - A lexer by rpjohnst which must repeat code without label-break-value: https://github.com/rust-lang/rust/issues/48594#issuecomment-422502014 - A snippet by SergioBenitez which avoids using a new function and adding several new return points to a function: https://github.com/rust-lang/rust/issues/48594#issuecomment-427628251. This particular case would also work if `try` blocks were stabilized (at the cost of making the code harder to optimize). - Several examples by JohnBSmith: https://github.com/rust-lang/rust/issues/48594#issuecomment-434651395 - Several examples by Centril: https://github.com/rust-lang/rust/issues/48594#issuecomment-440154733 - An example by petrochenkov where this is used in the compiler itself to avoid duplicating error checking code: https://github.com/rust-lang/rust/issues/48594#issuecomment-443557569 - Amanieu recently provided another example related to complex conditions, where try blocks would not have helped: https://github.com/rust-lang/rust/issues/48594#issuecomment-1184213006 Additionally, petrochenkov notes that this is strictly more powerful than labelled loops due to macros which accidentally exit a loop instead of being consumed by the macro matchers: https://github.com/rust-lang/rust/issues/48594#issuecomment-450246249 nrc later resolved their concern, mostly because of the aforementioned macro problems. joshtriplett suggested that macros could be able to generate IR directly (https://github.com/rust-lang/rust/issues/48594#issuecomment-451685983) but there are no open RFCs, and the design space seems rather speculative. joshtriplett later resolved his concerns, due to a symmetry between this feature and existing labelled break: https://github.com/rust-lang/rust/issues/48594#issuecomment-632960804 withoutboats has regrettably left the language team. joshtriplett later posted that the lang team would consider starting an FCP given a stabilization report: https://github.com/rust-lang/rust/issues/48594#issuecomment-1111269353 [issue-label]: https://github.com/rust-lang/rust/issues?q=is%3Aissue+is%3Aopen+label%3AF-label_break_value+ ## Report + Feature gate: - https://github.com/rust-lang/rust/blob/d695a497bbf4b20d2580b75075faa80230d41667/src/test/ui/feature-gates/feature-gate-label_break_value.rs + Diagnostics: - https://github.com/rust-lang/rust/blob/6b2d3d5f3cd1e553d87b5496632132565b6779d3/compiler/rustc_parse/src/parser/diagnostics.rs#L2629 - https://github.com/rust-lang/rust/blob/f65bf0b2bb1a99f73095c01a118f3c37d3ee614c/compiler/rustc_resolve/src/diagnostics.rs#L749 - https://github.com/rust-lang/rust/blob/f65bf0b2bb1a99f73095c01a118f3c37d3ee614c/compiler/rustc_resolve/src/diagnostics.rs#L1001 - https://github.com/rust-lang/rust/blob/111df9e6eda1d752233482c1309d00d20a4bbf98/compiler/rustc_passes/src/loops.rs#L254 - https://github.com/rust-lang/rust/blob/d695a497bbf4b20d2580b75075faa80230d41667/compiler/rustc_parse/src/parser/expr.rs#L2079 - https://github.com/rust-lang/rust/blob/d695a497bbf4b20d2580b75075faa80230d41667/compiler/rustc_parse/src/parser/expr.rs#L1569 + Tests: - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_continue.rs - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_unlabeled_break.rs - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_illegal_uses.rs - https://github.com/rust-lang/rust/blob/master/src/test/ui/lint/unused_labels.rs - https://github.com/rust-lang/rust/blob/master/src/test/ui/run-pass/for-loop-while/label_break_value.rs ## Interactions with other features Labels follow the hygiene of local variables. label-break-value is permitted within `try` blocks: ```rust let _: Result<(), ()> = try { 'foo: { Err(())?; break 'foo; } }; ``` label-break-value is disallowed within closures, generators, and async blocks: ```rust 'a: { || break 'a //~^ ERROR use of unreachable label `'a` //~| ERROR `break` inside of a closure } ``` label-break-value is disallowed on [_BlockExpression_]; it can only occur as a [_LoopExpression_]: ```rust fn labeled_match() { match false 'b: { //~ ERROR block label not supported here _ => {} } } macro_rules! m { ($b:block) => { 'lab: $b; //~ ERROR cannot use a `block` macro fragment here unsafe $b; //~ ERROR cannot use a `block` macro fragment here |x: u8| -> () $b; //~ ERROR cannot use a `block` macro fragment here } } fn foo() { m!({}); } ``` [_BlockExpression_]: https://doc.rust-lang.org/nightly/reference/expressions/block-expr.html [_LoopExpression_]: https://doc.rust-lang.org/nightly/reference/expressions/loop-expr.html --- tests/source/issue-3217.rs | 2 -- tests/target/issue-3217.rs | 2 -- 2 files changed, 4 deletions(-) diff --git a/tests/source/issue-3217.rs b/tests/source/issue-3217.rs index 176c702002a28..e68ca2c5907fc 100644 --- a/tests/source/issue-3217.rs +++ b/tests/source/issue-3217.rs @@ -1,5 +1,3 @@ -#![feature(label_break_value)] - fn main() { let mut res = 0; 's_39: { if res == 0i32 { println!("Hello, world!"); } } diff --git a/tests/target/issue-3217.rs b/tests/target/issue-3217.rs index 5121320a0975b..403bf4c340a4e 100644 --- a/tests/target/issue-3217.rs +++ b/tests/target/issue-3217.rs @@ -1,5 +1,3 @@ -#![feature(label_break_value)] - fn main() { let mut res = 0; 's_39: { From ddda7bbe5dfc3884857a90efe9dfd4dfc3eb85e1 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Sat, 20 Aug 2022 21:19:43 -0700 Subject: [PATCH 040/500] Sunset RLS --- Processes.md | 4 ---- README.md | 2 +- atom.md | 4 ++-- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/Processes.md b/Processes.md index 9d86d52b122d8..f763b5714ce2c 100644 --- a/Processes.md +++ b/Processes.md @@ -51,7 +51,3 @@ git tag -s v1.2.3 -m "Release 1.2.3" `cargo publish` ## 5. Create a PR to rust-lang/rust to update the rustfmt submodule - -Note that if you are updating `rustc-ap-*` crates, then you need to update **every** submodules in the rust-lang/rust repository that depend on the crates to use the same version of those. - -As of 2019/05, there are two such crates: `rls` and `racer` (`racer` depends on `rustc-ap-syntax` and `rls` depends on `racer`, and `rls` is one of submodules of the rust-lang/rust repository). diff --git a/README.md b/README.md index b3a968f0c043e..0f9652aecf9c2 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ completed without error (whether or not changes were made). * [Emacs](https://github.com/rust-lang/rust-mode) * [Sublime Text 3](https://packagecontrol.io/packages/RustFmt) * [Atom](atom.md) -* Visual Studio Code using [vscode-rust](https://github.com/editor-rs/vscode-rust), [vsc-rustfmt](https://github.com/Connorcpu/vsc-rustfmt) or [rls_vscode](https://github.com/jonathandturner/rls_vscode) through RLS. +* [Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer) * [IntelliJ or CLion](intellij.md) diff --git a/atom.md b/atom.md index f77ac1490721d..c7e3a991a5f03 100644 --- a/atom.md +++ b/atom.md @@ -1,8 +1,8 @@ # Running Rustfmt from Atom -## RLS +## rust-analyzer -Rustfmt is included with the Rust Language Server, itself provided by [ide-rust](https://atom.io/packages/ide-rust). +Rustfmt can be utilized from [rust-analyzer](https://rust-analyzer.github.io/) which is provided by [ide-rust](https://atom.io/packages/ide-rust). `apm install ide-rust` From 748b031056f109b0e2e58ab1e2f0189b83c32f3e Mon Sep 17 00:00:00 2001 From: Jack Huey <31162821+jackh726@users.noreply.github.com> Date: Wed, 4 May 2022 10:22:19 -0400 Subject: [PATCH 041/500] Stabilize GATs --- tests/source/issue_4257.rs | 3 --- tests/source/issue_4911.rs | 1 - tests/source/issue_4943.rs | 2 -- tests/target/issue_4257.rs | 3 --- tests/target/issue_4911.rs | 1 - tests/target/issue_4943.rs | 2 -- 6 files changed, 12 deletions(-) diff --git a/tests/source/issue_4257.rs b/tests/source/issue_4257.rs index 2b887fadb621c..9482512efca0a 100644 --- a/tests/source/issue_4257.rs +++ b/tests/source/issue_4257.rs @@ -1,6 +1,3 @@ -#![feature(generic_associated_types)] -#![allow(incomplete_features)] - trait Trait { type Type<'a> where T: 'a; fn foo(x: &T) -> Self::Type<'_>; diff --git a/tests/source/issue_4911.rs b/tests/source/issue_4911.rs index 21ef6c6c491ac..c254db7b509cc 100644 --- a/tests/source/issue_4911.rs +++ b/tests/source/issue_4911.rs @@ -1,4 +1,3 @@ -#![feature(generic_associated_types)] #![feature(min_type_alias_impl_trait)] impl SomeTrait for SomeType { diff --git a/tests/source/issue_4943.rs b/tests/source/issue_4943.rs index 0793b7b4fe1cc..307d9a4a1aba1 100644 --- a/tests/source/issue_4943.rs +++ b/tests/source/issue_4943.rs @@ -1,5 +1,3 @@ -#![feature(generic_associated_types)] - impl SomeStruct { fn process(v: T) -> ::R where Self: GAT = T> diff --git a/tests/target/issue_4257.rs b/tests/target/issue_4257.rs index 1ebaaf2b60018..309a66c8dc3cc 100644 --- a/tests/target/issue_4257.rs +++ b/tests/target/issue_4257.rs @@ -1,6 +1,3 @@ -#![feature(generic_associated_types)] -#![allow(incomplete_features)] - trait Trait { type Type<'a> where diff --git a/tests/target/issue_4911.rs b/tests/target/issue_4911.rs index 890a62267ce64..0f64aa7f766fd 100644 --- a/tests/target/issue_4911.rs +++ b/tests/target/issue_4911.rs @@ -1,4 +1,3 @@ -#![feature(generic_associated_types)] #![feature(min_type_alias_impl_trait)] impl SomeTrait for SomeType { diff --git a/tests/target/issue_4943.rs b/tests/target/issue_4943.rs index 318f7ebed6e06..bc8f1a366da29 100644 --- a/tests/target/issue_4943.rs +++ b/tests/target/issue_4943.rs @@ -1,5 +1,3 @@ -#![feature(generic_associated_types)] - impl SomeStruct { fn process(v: T) -> ::R where From e40972ebf86040de884d5b5b54e3345af504c140 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Tue, 30 Aug 2022 17:39:36 -0500 Subject: [PATCH 042/500] rustfmt: BindingAnnotation change --- src/patterns.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/patterns.rs b/src/patterns.rs index 9b74b35f31413..e2fe92b28f23e 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -1,4 +1,6 @@ -use rustc_ast::ast::{self, BindingMode, Pat, PatField, PatKind, RangeEnd, RangeSyntax}; +use rustc_ast::ast::{ + self, BindingAnnotation, ByRef, Pat, PatField, PatKind, RangeEnd, RangeSyntax, +}; use rustc_ast::ptr; use rustc_span::{BytePos, Span}; @@ -99,10 +101,10 @@ impl Rewrite for Pat { write_list(&items, &fmt) } PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape), - PatKind::Ident(binding_mode, ident, ref sub_pat) => { - let (prefix, mutability) = match binding_mode { - BindingMode::ByRef(mutability) => ("ref", mutability), - BindingMode::ByValue(mutability) => ("", mutability), + PatKind::Ident(BindingAnnotation(by_ref, mutability), ident, ref sub_pat) => { + let prefix = match by_ref { + ByRef::Yes => "ref", + ByRef::No => "", }; let mut_infix = format_mutability(mutability).trim(); let id_str = rewrite_ident(context, ident); From ef91154250977b3b5d05448dafbca524a1168b47 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Mon, 19 Sep 2022 17:58:37 -0500 Subject: [PATCH 043/500] docs: expand behavior of imports_granularity re: groups (#5543) --- Configurations.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Configurations.md b/Configurations.md index e066553dc63f3..400ad8c5d3bfe 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1857,13 +1857,16 @@ pub enum Foo {} ## `imports_granularity` -How imports should be grouped into `use` statements. Imports will be merged or split to the configured level of granularity. +Controls how imports are structured in `use` statements. Imports will be merged or split to the configured level of granularity. + +Similar to other `import` related configuration options, this option operates within the bounds of user-defined groups of imports. See [`group_imports`](#group_imports) for more information on import groups. + +Note that rustfmt will not modify the granularity of imports containing comments if doing so could potentially lose or misplace said comments. - **Default value**: `Preserve` - **Possible values**: `Preserve`, `Crate`, `Module`, `Item`, `One` - **Stable**: No (tracking issue: [#4991](https://github.com/rust-lang/rustfmt/issues/4991)) -Note that rustfmt will not modify the granularity of imports containing comments if doing so could potentially lose or misplace said comments. #### `Preserve` (default): From d71413cbfae7a8c7fb7d2534f7240915161ce46a Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 10 Oct 2022 02:05:24 +0000 Subject: [PATCH 044/500] Rename AssocItemKind::TyAlias to AssocItemKind::Type --- src/items.rs | 12 ++++++------ src/visitor.rs | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/items.rs b/src/items.rs index 8f35068e35f04..a2a73f0a5fb3a 100644 --- a/src/items.rs +++ b/src/items.rs @@ -594,7 +594,7 @@ impl<'a> FmtVisitor<'a> { let both_type = |l: &TyOpt, r: &TyOpt| is_type(l) && is_type(r); let both_opaque = |l: &TyOpt, r: &TyOpt| is_opaque(l) && is_opaque(r); let need_empty_line = |a: &ast::AssocItemKind, b: &ast::AssocItemKind| match (a, b) { - (TyAlias(lty), TyAlias(rty)) + (Type(lty), Type(rty)) if both_type(<y.ty, &rty.ty) || both_opaque(<y.ty, &rty.ty) => { false @@ -612,7 +612,7 @@ impl<'a> FmtVisitor<'a> { } buffer.sort_by(|(_, a), (_, b)| match (&a.kind, &b.kind) { - (TyAlias(lty), TyAlias(rty)) + (Type(lty), Type(rty)) if both_type(<y.ty, &rty.ty) || both_opaque(<y.ty, &rty.ty) => { a.ident.as_str().cmp(b.ident.as_str()) @@ -621,10 +621,10 @@ impl<'a> FmtVisitor<'a> { a.ident.as_str().cmp(b.ident.as_str()) } (Fn(..), Fn(..)) => a.span.lo().cmp(&b.span.lo()), - (TyAlias(ty), _) if is_type(&ty.ty) => Ordering::Less, - (_, TyAlias(ty)) if is_type(&ty.ty) => Ordering::Greater, - (TyAlias(..), _) => Ordering::Less, - (_, TyAlias(..)) => Ordering::Greater, + (Type(ty), _) if is_type(&ty.ty) => Ordering::Less, + (_, Type(ty)) if is_type(&ty.ty) => Ordering::Greater, + (Type(..), _) => Ordering::Less, + (_, Type(..)) => Ordering::Greater, (Const(..), _) => Ordering::Less, (_, Const(..)) => Ordering::Greater, (MacCall(..), _) => Ordering::Less, diff --git a/src/visitor.rs b/src/visitor.rs index 7bb745eeb8b9b..9c3cc7820d299 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -660,7 +660,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.push_rewrite(ai.span, rewrite); } } - (ast::AssocItemKind::TyAlias(ref ty_alias), _) => { + (ast::AssocItemKind::Type(ref ty_alias), _) => { self.visit_ty_alias_kind(ty_alias, visitor_kind, ai.span); } (ast::AssocItemKind::MacCall(ref mac), _) => { From 7cc303fbf62f6a058064fc07026231a8a5ee533f Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 10 Oct 2022 18:29:17 +0200 Subject: [PATCH 045/500] Fix unclosed HTML tag in rustfmt doc --- src/config/config_type.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/config_type.rs b/src/config/config_type.rs index e37ed798cb559..c5e61658ad1ed 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -4,7 +4,7 @@ use crate::config::options::{IgnoreList, WidthHeuristics}; /// Trait for types that can be used in `Config`. pub(crate) trait ConfigType: Sized { /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a - /// pipe-separated list of variants; for other types it returns "". + /// pipe-separated list of variants; for other types it returns ``. fn doc_hint() -> String; } From 657dcf21d8e13265513451f354511a53ea2c3b04 Mon Sep 17 00:00:00 2001 From: mejrs <> Date: Wed, 19 Oct 2022 00:08:20 +0200 Subject: [PATCH 046/500] Implement -Ztrack-diagnostics --- src/parse/session.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/parse/session.rs b/src/parse/session.rs index 6efeee98fea6c..6bfec79cd7030 100644 --- a/src/parse/session.rs +++ b/src/parse/session.rs @@ -134,6 +134,7 @@ fn default_handler( false, None, false, + false, )) }; Handler::with_emitter( From eb07a5ea417f4fb54cbfaa0a74992208c0435bad Mon Sep 17 00:00:00 2001 From: Yuki Okushi Date: Mon, 24 Oct 2022 20:13:47 +0900 Subject: [PATCH 047/500] Remove `failure` integration test Signed-off-by: Yuki Okushi --- .github/workflows/integration.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 4d8899b434bbe..314ce0e84c61b 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -27,7 +27,6 @@ jobs: tempdir, futures-rs, rust-clippy, - failure, ] include: # Allowed Failures @@ -63,9 +62,6 @@ jobs: # Original comment was: temporal build failure due to breaking changes in the nightly compiler - integration: rust-semverver allow-failure: true - # Can be moved back to include section after https://github.com/rust-lang-nursery/failure/pull/298 is merged - - integration: failure - allow-failure: true steps: - name: checkout From ad9fb89c3009282a55582f1c478d215d0c6005b0 Mon Sep 17 00:00:00 2001 From: Yuki Okushi Date: Mon, 24 Oct 2022 20:21:44 +0900 Subject: [PATCH 048/500] Update Git repo URLs Signed-off-by: Yuki Okushi --- ci/integration.sh | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/ci/integration.sh b/ci/integration.sh index 562d5d70c70ba..19d502bc5c7bd 100755 --- a/ci/integration.sh +++ b/ci/integration.sh @@ -91,14 +91,28 @@ case ${INTEGRATION} in cd - ;; crater) - git clone --depth=1 https://github.com/rust-lang-nursery/${INTEGRATION}.git + git clone --depth=1 https://github.com/rust-lang/${INTEGRATION}.git cd ${INTEGRATION} show_head check_fmt_with_lib_tests cd - ;; + bitflags) + git clone --depth=1 https://github.com/bitflags/${INTEGRATION}.git + cd ${INTEGRATION} + show_head + check_fmt_with_all_tests + cd - + ;; + error-chain | tempdir) + git clone --depth=1 https://github.com/rust-lang-deprecated/${INTEGRATION}.git + cd ${INTEGRATION} + show_head + check_fmt_with_all_tests + cd - + ;; *) - git clone --depth=1 https://github.com/rust-lang-nursery/${INTEGRATION}.git + git clone --depth=1 https://github.com/rust-lang/${INTEGRATION}.git cd ${INTEGRATION} show_head check_fmt_with_all_tests From ee2bed96d60fd7e46b1fb868f6a8f27e3a8058d0 Mon Sep 17 00:00:00 2001 From: Alex Touchet Date: Sat, 5 Nov 2022 21:39:56 -0700 Subject: [PATCH 049/500] Fix spacing --- Configurations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Configurations.md b/Configurations.md index 400ad8c5d3bfe..49e7e4e64892a 100644 --- a/Configurations.md +++ b/Configurations.md @@ -425,7 +425,7 @@ fn example() { ## `comment_width` -Maximum length of comments. No effect unless`wrap_comments = true`. +Maximum length of comments. No effect unless `wrap_comments = true`. - **Default value**: `80` - **Possible values**: any positive integer From 660e53512f1c25f03f6cf34fb620a7c0ed11d120 Mon Sep 17 00:00:00 2001 From: clubby789 Date: Mon, 31 Oct 2022 18:30:09 +0000 Subject: [PATCH 050/500] Introduce `ExprKind::IncludedBytes` --- src/expr.rs | 1 + src/utils.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/expr.rs b/src/expr.rs index 3105882e2d308..7750df0fff3af 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -399,6 +399,7 @@ pub(crate) fn format_expr( } } ast::ExprKind::Underscore => Some("_".to_owned()), + ast::ExprKind::IncludedBytes(..) => unreachable!(), ast::ExprKind::Err => None, }; diff --git a/src/utils.rs b/src/utils.rs index cd852855602e8..c47b3b314dd4b 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -496,6 +496,7 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Continue(..) | ast::ExprKind::Err | ast::ExprKind::Field(..) + | ast::ExprKind::IncludedBytes(..) | ast::ExprKind::InlineAsm(..) | ast::ExprKind::Let(..) | ast::ExprKind::Path(..) From 826fb78bebc757acf138e86bd755e1d81c1d08bc Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 10 Oct 2022 13:40:56 +1100 Subject: [PATCH 051/500] Use `token::Lit` in `ast::ExprKind::Lit`. Instead of `ast::Lit`. Literal lowering now happens at two different times. Expression literals are lowered when HIR is crated. Attribute literals are lowered during parsing. This commit changes the language very slightly. Some programs that used to not compile now will compile. This is because some invalid literals that are removed by `cfg` or attribute macros will no longer trigger errors. See this comment for more details: https://github.com/rust-lang/rust/pull/102944#issuecomment-1277476773 --- src/attr.rs | 6 ++++-- src/expr.rs | 41 ++++++++++++++++++++++------------------- 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index f5c1ee5fdd121..ccc2fd0d5f589 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -260,7 +260,9 @@ impl Rewrite for ast::NestedMetaItem { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { match self { ast::NestedMetaItem::MetaItem(ref meta_item) => meta_item.rewrite(context, shape), - ast::NestedMetaItem::Literal(ref l) => rewrite_literal(context, l, shape), + ast::NestedMetaItem::Literal(ref l) => { + rewrite_literal(context, l.token_lit, l.span, shape) + } } } } @@ -318,7 +320,7 @@ impl Rewrite for ast::MetaItem { // we might be better off ignoring the fact that the attribute // is longer than the max width and continue on formatting. // See #2479 for example. - let value = rewrite_literal(context, literal, lit_shape) + let value = rewrite_literal(context, literal.token_lit, literal.span, lit_shape) .unwrap_or_else(|| context.snippet(literal.span).to_owned()); format!("{} = {}", path, value) } diff --git a/src/expr.rs b/src/expr.rs index 7750df0fff3af..b4f1a178dbf44 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -3,7 +3,7 @@ use std::cmp::min; use itertools::Itertools; use rustc_ast::token::{Delimiter, LitKind}; -use rustc_ast::{ast, ptr}; +use rustc_ast::{ast, ptr, token}; use rustc_span::{BytePos, Span}; use crate::chains::rewrite_chain; @@ -75,12 +75,12 @@ pub(crate) fn format_expr( choose_separator_tactic(context, expr.span), None, ), - ast::ExprKind::Lit(ref l) => { - if let Some(expr_rw) = rewrite_literal(context, l, shape) { + ast::ExprKind::Lit(token_lit) => { + if let Some(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) { Some(expr_rw) } else { - if let LitKind::StrRaw(_) = l.token_lit.kind { - Some(context.snippet(l.span).trim().into()) + if let LitKind::StrRaw(_) = token_lit.kind { + Some(context.snippet(expr.span).trim().into()) } else { None } @@ -274,9 +274,9 @@ pub(crate) fn format_expr( fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool { match lhs.kind { - ast::ExprKind::Lit(ref lit) => match lit.kind { - ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => { - context.snippet(lit.span).ends_with('.') + ast::ExprKind::Lit(token_lit) => match token_lit.kind { + token::LitKind::Float if token_lit.suffix.is_none() => { + context.snippet(lhs.span).ends_with('.') } _ => false, }, @@ -1185,14 +1185,15 @@ pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool { pub(crate) fn rewrite_literal( context: &RewriteContext<'_>, - l: &ast::Lit, + token_lit: token::Lit, + span: Span, shape: Shape, ) -> Option { - match l.kind { - ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape), - ast::LitKind::Int(..) => rewrite_int_lit(context, l, shape), + match token_lit.kind { + token::LitKind::Str => rewrite_string_lit(context, span, shape), + token::LitKind::Integer => rewrite_int_lit(context, token_lit, span, shape), _ => wrap_str( - context.snippet(l.span).to_owned(), + context.snippet(span).to_owned(), context.config.max_width(), shape, ), @@ -1225,9 +1226,13 @@ fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> ) } -fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) -> Option { - let span = lit.span; - let symbol = lit.token_lit.symbol.as_str(); +fn rewrite_int_lit( + context: &RewriteContext<'_>, + token_lit: token::Lit, + span: Span, + shape: Shape, +) -> Option { + let symbol = token_lit.symbol.as_str(); if let Some(symbol_stripped) = symbol.strip_prefix("0x") { let hex_lit = match context.config.hex_literal_case() { @@ -1240,9 +1245,7 @@ fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) - format!( "0x{}{}", hex_lit, - lit.token_lit - .suffix - .map_or(String::new(), |s| s.to_string()) + token_lit.suffix.map_or(String::new(), |s| s.to_string()) ), context.config.max_width(), shape, From 4a4addc5980e95e4f7883f2d56aedcd08626ba73 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 8 Sep 2022 10:52:51 +1000 Subject: [PATCH 052/500] Box `ExprKind::{Closure,MethodCall}`, and `QSelf` in expressions, types, and patterns. --- src/attr.rs | 6 +++--- src/chains.rs | 12 +++++------- src/closures.rs | 30 +++++++++++++++++++----------- src/expr.rs | 26 +++++++++++++------------- src/patterns.rs | 9 ++++----- src/types.rs | 8 ++++---- src/utils.rs | 2 +- 7 files changed, 49 insertions(+), 44 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index ccc2fd0d5f589..23f55db773e6c 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -290,10 +290,10 @@ impl Rewrite for ast::MetaItem { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { Some(match self.kind { ast::MetaItemKind::Word => { - rewrite_path(context, PathContext::Type, None, &self.path, shape)? + rewrite_path(context, PathContext::Type, &None, &self.path, shape)? } ast::MetaItemKind::List(ref list) => { - let path = rewrite_path(context, PathContext::Type, None, &self.path, shape)?; + let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?; let has_trailing_comma = crate::expr::span_ends_with_comma(context, self.span); overflow::rewrite_with_parens( context, @@ -311,7 +311,7 @@ impl Rewrite for ast::MetaItem { )? } ast::MetaItemKind::NameValue(ref literal) => { - let path = rewrite_path(context, PathContext::Type, None, &self.path, shape)?; + let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?; // 3 = ` = ` let lit_shape = shape.shrink_left(path.len() + 3)?; // `rewrite_literal` returns `None` when `literal` exceeds max diff --git a/src/chains.rs b/src/chains.rs index fcc02eca42987..a1a73cf4bd570 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -145,8 +145,8 @@ impl ChainItemKind { fn from_ast(context: &RewriteContext<'_>, expr: &ast::Expr) -> (ChainItemKind, Span) { let (kind, span) = match expr.kind { - ast::ExprKind::MethodCall(ref segment, ref receiver, ref expressions, _) => { - let types = if let Some(ref generic_args) = segment.args { + ast::ExprKind::MethodCall(ref call) => { + let types = if let Some(ref generic_args) = call.seg.args { if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args { data.args .iter() @@ -163,8 +163,8 @@ impl ChainItemKind { } else { vec![] }; - let span = mk_sp(receiver.span.hi(), expr.span.hi()); - let kind = ChainItemKind::MethodCall(segment.clone(), types, expressions.clone()); + let span = mk_sp(call.receiver.span.hi(), expr.span.hi()); + let kind = ChainItemKind::MethodCall(call.seg.clone(), types, call.args.clone()); (kind, span) } ast::ExprKind::Field(ref nested, field) => { @@ -400,9 +400,7 @@ impl Chain { // is a try! macro, we'll convert it to shorthand when the option is set. fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext<'_>) -> Option { match expr.kind { - ast::ExprKind::MethodCall(_, ref receiver, _, _) => { - Some(Self::convert_try(&receiver, context)) - } + ast::ExprKind::MethodCall(ref call) => Some(Self::convert_try(&call.receiver, context)), ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) | ast::ExprKind::Await(ref subexpr) => Some(Self::convert_try(subexpr, context)), diff --git a/src/closures.rs b/src/closures.rs index 88a6bebb68c84..423c3a997f53d 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -326,16 +326,16 @@ pub(crate) fn rewrite_last_closure( expr: &ast::Expr, shape: Shape, ) -> Option { - if let ast::ExprKind::Closure( - ref binder, - capture, - ref is_async, - movability, - ref fn_decl, - ref body, - _, - ) = expr.kind - { + if let ast::ExprKind::Closure(ref closure) = expr.kind { + let ast::Closure { + ref binder, + capture_clause, + ref asyncness, + movability, + ref fn_decl, + ref body, + fn_decl_span: _, + } = **closure; let body = match body.kind { ast::ExprKind::Block(ref block, _) if !is_unsafe_block(block) @@ -347,7 +347,15 @@ pub(crate) fn rewrite_last_closure( _ => body, }; let (prefix, extra_offset) = rewrite_closure_fn_decl( - binder, capture, is_async, movability, fn_decl, body, expr.span, context, shape, + binder, + capture_clause, + asyncness, + movability, + fn_decl, + body, + expr.span, + context, + shape, )?; // If the closure goes multi line before its body, do not overflow the closure. if prefix.contains('\n') { diff --git a/src/expr.rs b/src/expr.rs index b4f1a178dbf44..aba1c484bf1dd 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -116,7 +116,7 @@ pub(crate) fn format_expr( rewrite_struct_lit( context, path, - qself.as_ref(), + qself, fields, rest, &expr.attrs, @@ -169,7 +169,7 @@ pub(crate) fn format_expr( rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs) } ast::ExprKind::Path(ref qself, ref path) => { - rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape) + rewrite_path(context, PathContext::Expr, qself, path, shape) } ast::ExprKind::Assign(ref lhs, ref rhs, _) => { rewrite_assignment(context, lhs, rhs, None, shape) @@ -203,16 +203,16 @@ pub(crate) fn format_expr( Some("yield".to_string()) } } - ast::ExprKind::Closure( - ref binder, - capture, - ref is_async, - movability, - ref fn_decl, - ref body, - _, - ) => closures::rewrite_closure( - binder, capture, is_async, movability, fn_decl, body, expr.span, context, shape, + ast::ExprKind::Closure(ref cl) => closures::rewrite_closure( + &cl.binder, + cl.capture_clause, + &cl.asyncness, + cl.movability, + &cl.fn_decl, + &cl.body, + expr.span, + context, + shape, ), ast::ExprKind::Try(..) | ast::ExprKind::Field(..) @@ -1537,7 +1537,7 @@ fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool fn rewrite_struct_lit<'a>( context: &RewriteContext<'_>, path: &ast::Path, - qself: Option<&ast::QSelf>, + qself: &Option>, fields: &'a [ast::ExprField], struct_rest: &ast::StructRest, attrs: &[ast::Attribute], diff --git a/src/patterns.rs b/src/patterns.rs index e2fe92b28f23e..3f335172590ec 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -227,11 +227,10 @@ impl Rewrite for Pat { } PatKind::Tuple(ref items) => rewrite_tuple_pat(items, None, self.span, context, shape), PatKind::Path(ref q_self, ref path) => { - rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape) + rewrite_path(context, PathContext::Expr, q_self, path, shape) } PatKind::TupleStruct(ref q_self, ref path, ref pat_vec) => { - let path_str = - rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)?; + let path_str = rewrite_path(context, PathContext::Expr, q_self, path, shape)?; rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape) } PatKind::Lit(ref expr) => expr.rewrite(context, shape), @@ -271,7 +270,7 @@ impl Rewrite for Pat { } fn rewrite_struct_pat( - qself: &Option, + qself: &Option>, path: &ast::Path, fields: &[ast::PatField], ellipsis: bool, @@ -281,7 +280,7 @@ fn rewrite_struct_pat( ) -> Option { // 2 = ` {` let path_shape = shape.sub_width(2)?; - let path_str = rewrite_path(context, PathContext::Expr, qself.as_ref(), path, path_shape)?; + let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?; if fields.is_empty() && !ellipsis { return Some(format!("{} {{}}", path_str)); diff --git a/src/types.rs b/src/types.rs index 2627886db109d..d5177a2057b8a 100644 --- a/src/types.rs +++ b/src/types.rs @@ -38,11 +38,11 @@ pub(crate) enum PathContext { pub(crate) fn rewrite_path( context: &RewriteContext<'_>, path_context: PathContext, - qself: Option<&ast::QSelf>, + qself: &Option>, path: &ast::Path, shape: Shape, ) -> Option { - let skip_count = qself.map_or(0, |x| x.position); + let skip_count = qself.as_ref().map_or(0, |x| x.position); let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import { "::".to_owned() @@ -655,7 +655,7 @@ impl Rewrite for ast::PolyTraitRef { impl Rewrite for ast::TraitRef { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { - rewrite_path(context, PathContext::Type, None, &self.path, shape) + rewrite_path(context, PathContext::Type, &None, &self.path, shape) } } @@ -800,7 +800,7 @@ impl Rewrite for ast::Ty { rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1) } ast::TyKind::Path(ref q_self, ref path) => { - rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape) + rewrite_path(context, PathContext::Type, q_self, path, shape) } ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair( &**ty, diff --git a/src/utils.rs b/src/utils.rs index c47b3b314dd4b..136a2c7fce24a 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -479,9 +479,9 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Binary(_, _, ref expr) | ast::ExprKind::Index(_, ref expr) | ast::ExprKind::Unary(_, ref expr) - | ast::ExprKind::Closure(_, _, _, _, _, ref expr, _) | ast::ExprKind::Try(ref expr) | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr), + ast::ExprKind::Closure(ref closure) => is_block_expr(context, &closure.body, repr), // This can only be a string lit ast::ExprKind::Lit(_) => { repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces() From 1343ffd564fbaed96e800a125e3d2b43de09beea Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 18 Nov 2022 11:24:21 +1100 Subject: [PATCH 053/500] Split `MacArgs` in two. `MacArgs` is an enum with three variants: `Empty`, `Delimited`, and `Eq`. It's used in two ways: - For representing attribute macro arguments (e.g. in `AttrItem`), where all three variants are used. - For representing function-like macros (e.g. in `MacCall` and `MacroDef`), where only the `Delimited` variant is used. In other words, `MacArgs` is used in two quite different places due to them having partial overlap. I find this makes the code hard to read. It also leads to various unreachable code paths, and allows invalid values (such as accidentally using `MacArgs::Empty` in a `MacCall`). This commit splits `MacArgs` in two: - `DelimArgs` is a new struct just for the "delimited arguments" case. It is now used in `MacCall` and `MacroDef`. - `AttrArgs` is a renaming of the old `MacArgs` enum for the attribute macro case. Its `Delimited` variant now contains a `DelimArgs`. Various other related things are renamed as well. These changes make the code clearer, avoids several unreachable paths, and disallows the invalid values. --- src/expr.rs | 2 +- src/macros.rs | 6 +++--- src/parse/macros/asm.rs | 2 +- src/parse/macros/cfg_if.rs | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/expr.rs b/src/expr.rs index aba1c484bf1dd..d5611082f0103 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1341,7 +1341,7 @@ pub(crate) fn can_be_overflowed_expr( } ast::ExprKind::MacCall(ref mac) => { match ( - rustc_ast::ast::MacDelimiter::from_token(mac.args.delim().unwrap()), + rustc_ast::ast::MacDelimiter::from_token(mac.args.delim.to_token()), context.config.overflow_delimited_expr(), ) { (Some(ast::MacDelimiter::Bracket), true) diff --git a/src/macros.rs b/src/macros.rs index 3a641fab5d647..df94938803788 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -208,7 +208,7 @@ fn rewrite_macro_inner( original_style }; - let ts = mac.args.inner_tokens(); + let ts = mac.args.tokens.clone(); let has_comment = contains_comment(context.snippet(mac.span())); if ts.is_empty() && !has_comment { return match style { @@ -392,7 +392,7 @@ pub(crate) fn rewrite_macro_def( return snippet; } - let ts = def.body.inner_tokens(); + let ts = def.body.tokens.clone(); let mut parser = MacroParser::new(ts.into_trees()); let parsed_def = match parser.parse() { Some(def) => def, @@ -1087,7 +1087,7 @@ pub(crate) fn convert_try_mac( ) -> Option { let path = &pprust::path_to_string(&mac.path); if path == "try" || path == "r#try" { - let ts = mac.args.inner_tokens(); + let ts = mac.args.tokens.clone(); Some(ast::Expr { id: ast::NodeId::root(), // dummy value diff --git a/src/parse/macros/asm.rs b/src/parse/macros/asm.rs index cc9fb5072ce1e..01edfab36547c 100644 --- a/src/parse/macros/asm.rs +++ b/src/parse/macros/asm.rs @@ -5,7 +5,7 @@ use crate::rewrite::RewriteContext; #[allow(dead_code)] pub(crate) fn parse_asm(context: &RewriteContext<'_>, mac: &ast::MacCall) -> Option { - let ts = mac.args.inner_tokens(); + let ts = mac.args.tokens.clone(); let mut parser = super::build_parser(context, ts); parse_asm_args(&mut parser, context.parse_sess.inner(), mac.span(), false).ok() } diff --git a/src/parse/macros/cfg_if.rs b/src/parse/macros/cfg_if.rs index 09b3e32df312d..ace1a76b3fe7d 100644 --- a/src/parse/macros/cfg_if.rs +++ b/src/parse/macros/cfg_if.rs @@ -23,7 +23,7 @@ fn parse_cfg_if_inner<'a>( sess: &'a ParseSess, mac: &'a ast::MacCall, ) -> Result, &'static str> { - let ts = mac.args.inner_tokens(); + let ts = mac.args.tokens.clone(); let mut parser = build_stream_parser(sess.inner(), ts); let mut items = vec![]; From 3d44530eb081d6ffb45124bb25feb2738f6f09ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 3 Nov 2022 14:22:35 -0700 Subject: [PATCH 054/500] Fix rustfmt --- src/expr.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/expr.rs b/src/expr.rs index d5611082f0103..414e767690bd0 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -660,7 +660,7 @@ fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option { Some(ControlFlow::new_for(pat, cond, block, label, expr.span)) } - ast::ExprKind::Loop(ref block, label) => { + ast::ExprKind::Loop(ref block, label, _) => { Some(ControlFlow::new_loop(block, label, expr.span)) } ast::ExprKind::While(ref cond, ref block, label) => { From cdff11ce94a6d70873920a4347de41adc5763d03 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 23 Nov 2022 15:39:42 +1100 Subject: [PATCH 055/500] Rename `ast::Lit` as `ast::MetaItemLit`. --- src/attr.rs | 11 ++++++++--- src/modules/visitor.rs | 12 ++++++++---- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index 23f55db773e6c..8cba2a850e5bc 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -527,14 +527,19 @@ pub(crate) trait MetaVisitor<'ast> { fn visit_meta_word(&mut self, _meta_item: &'ast ast::MetaItem) {} - fn visit_meta_name_value(&mut self, _meta_item: &'ast ast::MetaItem, _lit: &'ast ast::Lit) {} + fn visit_meta_name_value( + &mut self, + _meta_item: &'ast ast::MetaItem, + _lit: &'ast ast::MetaItemLit, + ) { + } fn visit_nested_meta_item(&mut self, nm: &'ast ast::NestedMetaItem) { match nm { ast::NestedMetaItem::MetaItem(ref meta_item) => self.visit_meta_item(meta_item), - ast::NestedMetaItem::Literal(ref lit) => self.visit_literal(lit), + ast::NestedMetaItem::Literal(ref lit) => self.visit_meta_item_lit(lit), } } - fn visit_literal(&mut self, _lit: &'ast ast::Lit) {} + fn visit_meta_item_lit(&mut self, _lit: &'ast ast::MetaItemLit) {} } diff --git a/src/modules/visitor.rs b/src/modules/visitor.rs index ea67977c17a2b..48431693332a6 100644 --- a/src/modules/visitor.rs +++ b/src/modules/visitor.rs @@ -84,15 +84,19 @@ impl PathVisitor { } impl<'ast> MetaVisitor<'ast> for PathVisitor { - fn visit_meta_name_value(&mut self, meta_item: &'ast ast::MetaItem, lit: &'ast ast::Lit) { + fn visit_meta_name_value( + &mut self, + meta_item: &'ast ast::MetaItem, + lit: &'ast ast::MetaItemLit, + ) { if meta_item.has_name(Symbol::intern("path")) && lit.kind.is_str() { - self.paths.push(lit_to_str(lit)); + self.paths.push(meta_item_lit_to_str(lit)); } } } #[cfg(not(windows))] -fn lit_to_str(lit: &ast::Lit) -> String { +fn meta_item_lit_to_str(lit: &ast::MetaItemLit) -> String { match lit.kind { ast::LitKind::Str(symbol, ..) => symbol.to_string(), _ => unreachable!(), @@ -100,7 +104,7 @@ fn lit_to_str(lit: &ast::Lit) -> String { } #[cfg(windows)] -fn lit_to_str(lit: &ast::Lit) -> String { +fn meta_item_lit_to_str(lit: &ast::MetaItemLit) -> String { match lit.kind { ast::LitKind::Str(symbol, ..) => symbol.as_str().replace("/", "\\"), _ => unreachable!(), From c7e4abd44469d20fad3033608d7ece501609ed34 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 24 Nov 2022 15:00:09 +1100 Subject: [PATCH 056/500] Rename `NestedMetaItem::[Ll]iteral` as `NestedMetaItem::[Ll]it`. We already use a mix of `Literal` and `Lit`. The latter is better because it is shorter without causing any ambiguity. --- src/attr.rs | 6 ++---- src/overflow.rs | 4 ++-- src/utils.rs | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index 8cba2a850e5bc..2ac703b957b86 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -260,9 +260,7 @@ impl Rewrite for ast::NestedMetaItem { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { match self { ast::NestedMetaItem::MetaItem(ref meta_item) => meta_item.rewrite(context, shape), - ast::NestedMetaItem::Literal(ref l) => { - rewrite_literal(context, l.token_lit, l.span, shape) - } + ast::NestedMetaItem::Lit(ref l) => rewrite_literal(context, l.token_lit, l.span, shape), } } } @@ -537,7 +535,7 @@ pub(crate) trait MetaVisitor<'ast> { fn visit_nested_meta_item(&mut self, nm: &'ast ast::NestedMetaItem) { match nm { ast::NestedMetaItem::MetaItem(ref meta_item) => self.visit_meta_item(meta_item), - ast::NestedMetaItem::Literal(ref lit) => self.visit_meta_item_lit(lit), + ast::NestedMetaItem::Lit(ref lit) => self.visit_meta_item_lit(lit), } } diff --git a/src/overflow.rs b/src/overflow.rs index 6bf8cd0c70be0..af0b95430a197 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -125,7 +125,7 @@ impl<'a> OverflowableItem<'a> { OverflowableItem::MacroArg(MacroArg::Keyword(..)) => true, OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_simple_expr(expr), OverflowableItem::NestedMetaItem(nested_meta_item) => match nested_meta_item { - ast::NestedMetaItem::Literal(..) => true, + ast::NestedMetaItem::Lit(..) => true, ast::NestedMetaItem::MetaItem(ref meta_item) => { matches!(meta_item.kind, ast::MetaItemKind::Word) } @@ -169,7 +169,7 @@ impl<'a> OverflowableItem<'a> { }, OverflowableItem::NestedMetaItem(nested_meta_item) if len == 1 => { match nested_meta_item { - ast::NestedMetaItem::Literal(..) => false, + ast::NestedMetaItem::Lit(..) => false, ast::NestedMetaItem::MetaItem(..) => true, } } diff --git a/src/utils.rs b/src/utils.rs index 136a2c7fce24a..3e884419f1a32 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -263,7 +263,7 @@ fn is_skip(meta_item: &MetaItem) -> bool { fn is_skip_nested(meta_item: &NestedMetaItem) -> bool { match meta_item { NestedMetaItem::MetaItem(ref mi) => is_skip(mi), - NestedMetaItem::Literal(_) => false, + NestedMetaItem::Lit(_) => false, } } From 749c816faec774e7e7cae8ebad01d7ca0464b541 Mon Sep 17 00:00:00 2001 From: Sarthak Singh Date: Wed, 9 Nov 2022 20:39:28 +0530 Subject: [PATCH 057/500] Keep track of the start of the argument block of a closure --- src/closures.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/closures.rs b/src/closures.rs index 423c3a997f53d..244d4427c5623 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -335,6 +335,7 @@ pub(crate) fn rewrite_last_closure( ref fn_decl, ref body, fn_decl_span: _, + fn_arg_span: _, } = **closure; let body = match body.kind { ast::ExprKind::Block(ref block, _) From 46f0b38eb5f4965bd3230ceeba4a3ed7d0e5f68e Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 1 Dec 2022 18:51:20 +0300 Subject: [PATCH 058/500] rustc_ast_lowering: Stop lowering imports into multiple items Lower them into a single item with multiple resolutions instead. This also allows to remove additional `NodId`s and `DefId`s related to those additional items. --- src/imports.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/imports.rs b/src/imports.rs index b6530c69243ed..d9dc8d004aff4 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -490,7 +490,7 @@ impl UseTree { ); result.path.push(UseSegment { kind, version }); } - UseTreeKind::Simple(ref rename, ..) => { + UseTreeKind::Simple(ref rename) => { // If the path has leading double colons and is composed of only 2 segments, then we // bypass the call to path_to_imported_ident which would get only the ident and // lose the path root, e.g., `that` in `::that`. From c91dd22870d40315c3e0e5b45077516286e918fd Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 29 Nov 2022 13:36:00 +1100 Subject: [PATCH 059/500] Remove `token::Lit` from `ast::MetaItemLit`. `token::Lit` contains a `kind` field that indicates what kind of literal it is. `ast::MetaItemLit` currently wraps a `token::Lit` but also has its own `kind` field. This means that `ast::MetaItemLit` encodes the literal kind in two different ways. This commit changes `ast::MetaItemLit` so it no longer wraps `token::Lit`. It now contains the `symbol` and `suffix` fields from `token::Lit`, but not the `kind` field, eliminating the redundancy. --- src/attr.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index 2ac703b957b86..c503eeeb9b3b9 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -260,7 +260,9 @@ impl Rewrite for ast::NestedMetaItem { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { match self { ast::NestedMetaItem::MetaItem(ref meta_item) => meta_item.rewrite(context, shape), - ast::NestedMetaItem::Lit(ref l) => rewrite_literal(context, l.token_lit, l.span, shape), + ast::NestedMetaItem::Lit(ref l) => { + rewrite_literal(context, l.as_token_lit(), l.span, shape) + } } } } @@ -308,18 +310,18 @@ impl Rewrite for ast::MetaItem { }), )? } - ast::MetaItemKind::NameValue(ref literal) => { + ast::MetaItemKind::NameValue(ref lit) => { let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?; // 3 = ` = ` let lit_shape = shape.shrink_left(path.len() + 3)?; - // `rewrite_literal` returns `None` when `literal` exceeds max + // `rewrite_literal` returns `None` when `lit` exceeds max // width. Since a literal is basically unformattable unless it // is a string literal (and only if `format_strings` is set), // we might be better off ignoring the fact that the attribute // is longer than the max width and continue on formatting. // See #2479 for example. - let value = rewrite_literal(context, literal.token_lit, literal.span, lit_shape) - .unwrap_or_else(|| context.snippet(literal.span).to_owned()); + let value = rewrite_literal(context, lit.as_token_lit(), lit.span, lit_shape) + .unwrap_or_else(|| context.snippet(lit.span).to_owned()); format!("{} = {}", path, value) } }) From 67b711af7fe4d00af20eca55518d0e8f3d3e39a1 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Mon, 12 Dec 2022 15:47:32 +0100 Subject: [PATCH 060/500] Rename `assert_uninit_valid` intrinsic It's not about "uninit" anymore but about "filling with 0x01 bytes" so the name should at least try to reflect that. --- src/intrinsics/mod.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/intrinsics/mod.rs b/src/intrinsics/mod.rs index 0302b843aa226..e4a27f1bb6d40 100644 --- a/src/intrinsics/mod.rs +++ b/src/intrinsics/mod.rs @@ -713,7 +713,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let res = CValue::by_val(swap(&mut fx.bcx, val), arg.layout()); ret.write_cvalue(fx, res); } - sym::assert_inhabited | sym::assert_zero_valid | sym::assert_uninit_valid => { + sym::assert_inhabited | sym::assert_zero_valid | sym::assert_mem_uninitialized_valid => { intrinsic_args!(fx, args => (); intrinsic); let layout = fx.layout_of(substs.type_at(0)); @@ -742,7 +742,9 @@ fn codegen_regular_intrinsic_call<'tcx>( return; } - if intrinsic == sym::assert_uninit_valid && !fx.tcx.permits_uninit_init(layout) { + if intrinsic == sym::assert_mem_uninitialized_valid + && !fx.tcx.permits_uninit_init(layout) + { with_no_trimmed_paths!({ crate::base::codegen_panic( fx, From 98a276b5895697a862b48bcaf07b423de0b0deef Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Wed, 14 Dec 2022 19:30:46 +0100 Subject: [PATCH 061/500] Merge commit '2bb3996244cf1b89878da9e39841e9f6bf061602' into sync_cg_clif-2022-12-14 --- .cirrus.yml | 2 - .github/workflows/main.yml | 52 ++- .github/workflows/nightly-cranelift.yml | 2 +- .github/workflows/rustc.yml | 16 +- .gitignore | 1 + .vscode/settings.json | 35 +- Cargo.lock | 125 ++++-- Cargo.toml | 20 +- Readme.md | 2 +- build_sysroot/Cargo.lock | 57 +-- build_system/abi_cafe.rs | 20 +- build_system/build_backend.rs | 13 +- build_system/build_sysroot.rs | 98 +++-- build_system/mod.rs | 91 ++-- build_system/path.rs | 70 +++ build_system/prepare.rs | 154 +++---- build_system/rustc_info.rs | 20 + build_system/tests.rs | 553 +++++++++++++----------- build_system/utils.rs | 145 ++++++- clean_all.sh | 2 +- config.txt | 1 + docs/usage.md | 12 +- example/issue-72793.rs | 24 + example/mini_core.rs | 7 +- example/mini_core_hello_world.rs | 2 - example/std_example.rs | 2 + rust-toolchain | 2 +- rustfmt.toml | 2 + scripts/filter_profile.rs | 2 +- scripts/rustdoc-clif.rs | 36 ++ scripts/setup_rust_fork.sh | 22 +- scripts/test_rustc_tests.sh | 14 +- src/abi/mod.rs | 29 +- src/allocator.rs | 4 +- src/base.rs | 12 +- src/cast.rs | 2 +- src/common.rs | 11 +- src/constant.rs | 82 ++-- src/debuginfo/unwind.rs | 4 +- src/discriminant.rs | 207 +++++++-- src/driver/jit.rs | 12 +- src/driver/mod.rs | 3 +- src/intrinsics/llvm.rs | 176 +------- src/intrinsics/llvm_aarch64.rs | 222 ++++++++++ src/intrinsics/llvm_x86.rs | 197 +++++++++ src/intrinsics/mod.rs | 96 +--- src/intrinsics/simd.rs | 7 +- src/main_shim.rs | 6 +- src/num.rs | 6 +- src/optimize/peephole.rs | 20 - src/value_and_place.rs | 15 +- test.sh | 2 +- y.rs | 2 +- 53 files changed, 1691 insertions(+), 1028 deletions(-) create mode 100644 build_system/path.rs create mode 100644 example/issue-72793.rs create mode 100644 scripts/rustdoc-clif.rs create mode 100644 src/intrinsics/llvm_aarch64.rs create mode 100644 src/intrinsics/llvm_x86.rs diff --git a/.cirrus.yml b/.cirrus.yml index 732edd66196d7..d627c2ee09c4e 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -12,8 +12,6 @@ task: folder: target prepare_script: - . $HOME/.cargo/env - - git config --global user.email "user@example.com" - - git config --global user.name "User" - ./y.rs prepare test_script: - . $HOME/.cargo/env diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5061010c86cd3..a6bb12a66a247 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -19,6 +19,7 @@ jobs: - name: Rustfmt run: | cargo fmt --check + rustfmt --check build_system/mod.rs build: runs-on: ${{ matrix.os }} @@ -28,7 +29,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-20.04 # FIXME switch to ubuntu-22.04 once #1303 is fixed env: TARGET_TRIPLE: x86_64-unknown-linux-gnu - os: macos-latest @@ -41,18 +42,22 @@ jobs: - os: ubuntu-latest env: TARGET_TRIPLE: aarch64-unknown-linux-gnu + # s390x requires QEMU 6.1 or greater, we could build it from source, but ubuntu 22.04 comes with 6.2 by default + - os: ubuntu-latest + env: + TARGET_TRIPLE: s390x-unknown-linux-gnu steps: - uses: actions/checkout@v3 - name: Cache cargo installed crates - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ~/.cargo/bin key: ${{ runner.os }}-cargo-installed-crates - name: Cache cargo registry and index - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: | ~/.cargo/registry @@ -60,9 +65,9 @@ jobs: key: ${{ runner.os }}-cargo-registry-and-index-${{ hashFiles('**/Cargo.lock') }} - name: Cache cargo target dir - uses: actions/cache@v2 + uses: actions/cache@v3 with: - path: target + path: build/cg_clif key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }} - name: Install MinGW toolchain and wine @@ -78,11 +83,14 @@ jobs: sudo apt-get update sudo apt-get install -y gcc-aarch64-linux-gnu qemu-user - - name: Prepare dependencies + - name: Install s390x toolchain and qemu + if: matrix.env.TARGET_TRIPLE == 's390x-unknown-linux-gnu' run: | - git config --global user.email "user@example.com" - git config --global user.name "User" - ./y.rs prepare + sudo apt-get update + sudo apt-get install -y gcc-s390x-linux-gnu qemu-user + + - name: Prepare dependencies + run: ./y.rs prepare - name: Build without unstable features env: @@ -110,7 +118,7 @@ jobs: ./y.rs test - name: Package prebuilt cg_clif - run: tar cvfJ cg_clif.tar.xz build + run: tar cvfJ cg_clif.tar.xz dist - name: Upload prebuilt cg_clif if: matrix.env.TARGET_TRIPLE != 'x86_64-pc-windows-gnu' @@ -121,7 +129,7 @@ jobs: - name: Upload prebuilt cg_clif (cross compile) if: matrix.env.TARGET_TRIPLE == 'x86_64-pc-windows-gnu' - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: name: cg_clif-${{ runner.os }}-cross-x86_64-mingw path: cg_clif.tar.xz @@ -147,13 +155,13 @@ jobs: - uses: actions/checkout@v3 - name: Cache cargo installed crates - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ~/.cargo/bin key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-installed-crates - name: Cache cargo registry and index - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: | ~/.cargo/registry @@ -161,9 +169,9 @@ jobs: key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-registry-and-index-${{ hashFiles('**/Cargo.lock') }} - name: Cache cargo target dir - uses: actions/cache@v2 + uses: actions/cache@v3 with: - path: target + path: build/cg_clif key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }} - name: Set MinGW as the default toolchain @@ -172,8 +180,6 @@ jobs: - name: Prepare dependencies run: | - git config --global user.email "user@example.com" - git config --global user.name "User" git config --global core.autocrlf false rustc y.rs -o y.exe -g ./y.exe prepare @@ -198,24 +204,24 @@ jobs: # Enable extra checks $Env:CG_CLIF_ENABLE_VERIFIER=1 - + # WIP Disable some tests - + # This fails due to some weird argument handling by hyperfine, not an actual regression # more of a build system issue (Get-Content config.txt) -replace '(bench.simple-raytracer)', '# $1' | Out-File config.txt - - # This fails with a different output than expected + + # This fails with a different output than expected (Get-Content config.txt) -replace '(test.regex-shootout-regex-dna)', '# $1' | Out-File config.txt ./y.exe test - name: Package prebuilt cg_clif # don't use compression as xzip isn't supported by tar on windows and bzip2 hangs - run: tar cvf cg_clif.tar build + run: tar cvf cg_clif.tar dist - name: Upload prebuilt cg_clif - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: name: cg_clif-${{ matrix.env.TARGET_TRIPLE }} path: cg_clif.tar diff --git a/.github/workflows/nightly-cranelift.yml b/.github/workflows/nightly-cranelift.yml index 0a3e7ca073b45..d0d58d2a7eacb 100644 --- a/.github/workflows/nightly-cranelift.yml +++ b/.github/workflows/nightly-cranelift.yml @@ -14,7 +14,7 @@ jobs: - uses: actions/checkout@v3 - name: Cache cargo installed crates - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ~/.cargo/bin key: ubuntu-latest-cargo-installed-crates diff --git a/.github/workflows/rustc.yml b/.github/workflows/rustc.yml index b8a98b83ebe5e..bef806318efa8 100644 --- a/.github/workflows/rustc.yml +++ b/.github/workflows/rustc.yml @@ -11,13 +11,13 @@ jobs: - uses: actions/checkout@v3 - name: Cache cargo installed crates - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ~/.cargo/bin key: ${{ runner.os }}-cargo-installed-crates - name: Cache cargo registry and index - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: | ~/.cargo/registry @@ -25,9 +25,9 @@ jobs: key: ${{ runner.os }}-cargo-registry-and-index-${{ hashFiles('**/Cargo.lock') }} - name: Cache cargo target dir - uses: actions/cache@v2 + uses: actions/cache@v3 with: - path: target + path: build/cg_clif key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }} - name: Prepare dependencies @@ -49,13 +49,13 @@ jobs: - uses: actions/checkout@v3 - name: Cache cargo installed crates - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ~/.cargo/bin key: ${{ runner.os }}-cargo-installed-crates - name: Cache cargo registry and index - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: | ~/.cargo/registry @@ -63,9 +63,9 @@ jobs: key: ${{ runner.os }}-cargo-registry-and-index-${{ hashFiles('**/Cargo.lock') }} - name: Cache cargo target dir - uses: actions/cache@v2 + uses: actions/cache@v3 with: - path: target + path: build/cg_clif key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }} - name: Prepare dependencies diff --git a/.gitignore b/.gitignore index fae09592c6ac0..b443fd58a1b98 100644 --- a/.gitignore +++ b/.gitignore @@ -14,5 +14,6 @@ perf.data.old /build_sysroot/sysroot_src /build_sysroot/compiler-builtins /build_sysroot/rustc_version +/dist /rust /download diff --git a/.vscode/settings.json b/.vscode/settings.json index 13301bf20a5ed..bc914e37d2b51 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -4,16 +4,10 @@ "rust-analyzer.imports.granularity.enforce": true, "rust-analyzer.imports.granularity.group": "module", "rust-analyzer.imports.prefix": "crate", - "rust-analyzer.cargo.features": ["unstable-features"], + "rust-analyzer.cargo.features": ["unstable-features", "__check_build_system_using_ra"], "rust-analyzer.linkedProjects": [ "./Cargo.toml", - //"./build_sysroot/sysroot_src/library/std/Cargo.toml", { - "roots": [ - "./example/mini_core.rs", - "./example/mini_core_hello_world.rs", - "./example/mod_bench.rs" - ], "crates": [ { "root_module": "./example/mini_core.rs", @@ -36,34 +30,11 @@ ] }, { - "roots": ["./example/std_example.rs"], + "sysroot_src": "./build_sysroot/sysroot_src/library", "crates": [ { "root_module": "./example/std_example.rs", - "edition": "2018", - "deps": [{ "crate": 1, "name": "std" }], - "cfg": [], - }, - { - "root_module": "./build_sysroot/sysroot_src/library/std/src/lib.rs", - "edition": "2018", - "deps": [], - "cfg": [], - }, - ] - }, - { - "roots": ["./y.rs"], - "crates": [ - { - "root_module": "./y.rs", - "edition": "2018", - "deps": [{ "crate": 1, "name": "std" }], - "cfg": [], - }, - { - "root_module": "./build_sysroot/sysroot_src/library/std/src/lib.rs", - "edition": "2018", + "edition": "2015", "deps": [], "cfg": [], }, diff --git a/Cargo.lock b/Cargo.lock index 3b406036c356e..e4d3e9ca5ae0a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15,9 +15,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.60" +version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c794e162a5eff65c72ef524dfe393eb923c354e350bb78b9c7383df13f3bc142" +checksum = "216261ddc8289130e551ddcd5ce8a064710c0d064a4d2895c67151c92b5443f6" [[package]] name = "arrayvec" @@ -39,9 +39,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bumpalo" -version = "3.11.0" +version = "3.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1ad822118d20d2c234f427000d5acc36eabe1e29a348c89b63dd60b13f28e5d" +checksum = "572f695136211188308f16ad2ca5c851a712c464060ae6974944458eb83880ba" [[package]] name = "byteorder" @@ -57,24 +57,25 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cranelift-bforest" -version = "0.88.1" +version = "0.90.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44409ccf2d0f663920cab563d2b79fcd6b2e9a2bcc6e929fef76c8f82ad6c17a" +checksum = "b62c772976416112fa4484cbd688cb6fb35fd430005c1c586224fc014018abad" dependencies = [ "cranelift-entity", ] [[package]] name = "cranelift-codegen" -version = "0.88.1" +version = "0.90.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98de2018ad96eb97f621f7d6b900a0cc661aec8d02ea4a50e56ecb48e5a2fcaf" +checksum = "9b40ed2dd13c2ac7e24f88a3090c68ad3414eb1d066a95f8f1f7b3b819cb4e46" dependencies = [ "arrayvec", "bumpalo", "cranelift-bforest", "cranelift-codegen-meta", "cranelift-codegen-shared", + "cranelift-egraph", "cranelift-entity", "cranelift-isle", "gimli", @@ -86,30 +87,44 @@ dependencies = [ [[package]] name = "cranelift-codegen-meta" -version = "0.88.1" +version = "0.90.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5287ce36e6c4758fbaf298bd1a8697ad97a4f2375a3d1b61142ea538db4877e5" +checksum = "bb927a8f1c27c34ee3759b6b0ffa528d2330405d5cc4511f0cab33fe2279f4b5" dependencies = [ "cranelift-codegen-shared", ] [[package]] name = "cranelift-codegen-shared" -version = "0.88.1" +version = "0.90.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2855c24219e2f08827f3f4ffb2da92e134ae8d8ecc185b11ec8f9878cf5f588e" +checksum = "43dfa417b884a9ab488d95fd6b93b25e959321fe7bfd7a0a960ba5d7fb7ab927" + +[[package]] +name = "cranelift-egraph" +version = "0.90.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0a66b39785efd8513d2cca967ede56d6cc57c8d7986a595c7c47d0c78de8dce" +dependencies = [ + "cranelift-entity", + "fxhash", + "hashbrown", + "indexmap", + "log", + "smallvec", +] [[package]] name = "cranelift-entity" -version = "0.88.1" +version = "0.90.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b65673279d75d34bf11af9660ae2dbd1c22e6d28f163f5c72f4e1dc56d56103" +checksum = "0637ffde963cb5d759bc4d454cfa364b6509e6c74cdaa21298add0ed9276f346" [[package]] name = "cranelift-frontend" -version = "0.88.1" +version = "0.90.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed2b3d7a4751163f6c4a349205ab1b7d9c00eecf19dcea48592ef1f7688eefc" +checksum = "fb72b8342685e850cb037350418f62cc4fc55d6c2eb9c7ca01b82f9f1a6f3d56" dependencies = [ "cranelift-codegen", "log", @@ -119,15 +134,15 @@ dependencies = [ [[package]] name = "cranelift-isle" -version = "0.88.1" +version = "0.90.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be64cecea9d90105fc6a2ba2d003e98c867c1d6c4c86cc878f97ad9fb916293" +checksum = "850579cb9e4b448f7c301f1e6e6cbad99abe3f1f1d878a4994cb66e33c6db8cd" [[package]] name = "cranelift-jit" -version = "0.88.1" +version = "0.90.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f98ed42a70a0c9c388e34ec9477f57fc7300f541b1e5136a0e2ea02b1fac6015" +checksum = "9add822ad66dcbe152b5ab57de10240a2df4505099f2f6c27159acb711890bd4" dependencies = [ "anyhow", "cranelift-codegen", @@ -138,14 +153,15 @@ dependencies = [ "log", "region", "target-lexicon", + "wasmtime-jit-icache-coherence", "windows-sys", ] [[package]] name = "cranelift-module" -version = "0.88.1" +version = "0.90.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d658ac7f156708bfccb647216cc8b9387469f50d352ba4ad80150541e4ae2d49" +checksum = "406b772626fc2664864cf947f3895a23b619895c7fff635f3622e2d857f4492f" dependencies = [ "anyhow", "cranelift-codegen", @@ -153,9 +169,9 @@ dependencies = [ [[package]] name = "cranelift-native" -version = "0.88.1" +version = "0.90.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4a03a6ac1b063e416ca4b93f6247978c991475e8271465340caa6f92f3c16a4" +checksum = "2d0a279e5bcba3e0466c734d8d8eb6bfc1ad29e95c37f3e4955b492b5616335e" dependencies = [ "cranelift-codegen", "libc", @@ -164,9 +180,9 @@ dependencies = [ [[package]] name = "cranelift-object" -version = "0.88.1" +version = "0.90.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eef0b4119b645b870a43a036d76c0ada3a076b1f82e8b8487659304c8b09049b" +checksum = "39793c550f0c1d7db96c2fc1324583670c8143befe6edbfbaf1c68aba53be983" dependencies = [ "anyhow", "cranelift-codegen", @@ -185,6 +201,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + [[package]] name = "fxhash" version = "0.2.1" @@ -196,9 +218,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" +checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" dependencies = [ "cfg-if", "libc", @@ -211,7 +233,9 @@ version = "0.26.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d" dependencies = [ + "fallible-iterator", "indexmap", + "stable_deref_trait", ] [[package]] @@ -225,9 +249,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "1.9.1" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e" +checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399" dependencies = [ "autocfg", "hashbrown", @@ -235,15 +259,15 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.127" +version = "0.2.138" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "505e71a4706fa491e9b1b55f51b95d4037d0821ee40131190475f692b35b009b" +checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8" [[package]] name = "libloading" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efbc0f03f9a775e9f6aed295c6a1ba2253c5757a9e03d55c6caa46a681abcddd" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" dependencies = [ "cfg-if", "winapi", @@ -287,15 +311,15 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.13.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" +checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" [[package]] name = "regalloc2" -version = "0.3.2" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43a209257d978ef079f3d446331d0f1794f5e0fc19b306a199983857833a779" +checksum = "91b2eab54204ea0117fe9a060537e0b07a4e72f7c7d182361ecc346cab2240e5" dependencies = [ "fxhash", "log", @@ -342,15 +366,21 @@ checksum = "03b634d87b960ab1a38c4fe143b508576f075e7c978bfad18217645ebfdfa2ec" [[package]] name = "smallvec" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fd0db749597d91ff862fd1d55ea87f7855a744a8425a64695b6fca237d1dad1" +checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" + +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" [[package]] name = "target-lexicon" -version = "0.12.4" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c02424087780c9b71cc96799eaeddff35af2bc513278cda5c99fc1f5d026d3c1" +checksum = "9410d0f6853b1d94f0e519fb95df60f29d2c1eff2d921ffdf01a4c8a3b54f12d" [[package]] name = "version_check" @@ -364,6 +394,17 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "wasmtime-jit-icache-coherence" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6bbabb309c06cc238ee91b1455b748c45f0bdcab0dda2c2db85b0a1e69fcb66" +dependencies = [ + "cfg-if", + "libc", + "windows-sys", +] + [[package]] name = "winapi" version = "0.3.9" diff --git a/Cargo.toml b/Cargo.toml index 0fdd5de118ccb..2b216ca072f00 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,17 +3,24 @@ name = "rustc_codegen_cranelift" version = "0.1.0" edition = "2021" +[[bin]] +# This is used just to teach rust-analyzer how to check the build system. required-features is used +# to disable it for regular builds. +name = "y" +path = "./y.rs" +required-features = ["__check_build_system_using_ra"] + [lib] crate-type = ["dylib"] [dependencies] # These have to be in sync with each other -cranelift-codegen = { version = "0.88.1", features = ["unwind", "all-arch"] } -cranelift-frontend = "0.88.1" -cranelift-module = "0.88.1" -cranelift-native = "0.88.1" -cranelift-jit = { version = "0.88.1", optional = true } -cranelift-object = "0.88.1" +cranelift-codegen = { version = "0.90.1", features = ["unwind", "all-arch"] } +cranelift-frontend = "0.90.1" +cranelift-module = "0.90.1" +cranelift-native = "0.90.1" +cranelift-jit = { version = "0.90.1", optional = true } +cranelift-object = "0.90.1" target-lexicon = "0.12.0" gimli = { version = "0.26.0", default-features = false, features = ["write"]} object = { version = "0.29.0", default-features = false, features = ["std", "read_core", "write", "archive", "coff", "elf", "macho", "pe"] } @@ -39,6 +46,7 @@ smallvec = "1.8.1" unstable-features = ["jit", "inline_asm"] jit = ["cranelift-jit", "libloading"] inline_asm = [] +__check_build_system_using_ra = [] [package.metadata.rust-analyzer] rustc_private = true diff --git a/Readme.md b/Readme.md index 1e84c7fa3657b..0e9c77244d4cc 100644 --- a/Readme.md +++ b/Readme.md @@ -37,7 +37,7 @@ Assuming `$cg_clif_dir` is the directory you cloned this repo into and you follo In the directory with your project (where you can do the usual `cargo build`), run: ```bash -$ $cg_clif_dir/build/cargo-clif build +$ $cg_clif_dir/dist/cargo-clif build ``` This will build your project with rustc_codegen_cranelift instead of the usual LLVM backend. diff --git a/build_sysroot/Cargo.lock b/build_sysroot/Cargo.lock index f6a9cb67290c7..bba3210536ef7 100644 --- a/build_sysroot/Cargo.lock +++ b/build_sysroot/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.16.0" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61f2b7f93d2c7d2b08263acaa4a363b3e276806c68af6134c44f523bf1aacd" +checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" dependencies = [ "compiler_builtins", "gimli", @@ -32,27 +32,11 @@ dependencies = [ "core", ] -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - [[package]] name = "cc" -version = "1.0.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" - -[[package]] -name = "cfg-if" -version = "0.1.10" +version = "1.0.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] +checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4" [[package]] name = "cfg-if" @@ -66,9 +50,9 @@ dependencies = [ [[package]] name = "compiler_builtins" -version = "0.1.82" +version = "0.1.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18cd7635fea7bb481ea543b392789844c1ad581299da70184c7175ce3af76603" +checksum = "13e81c6cd7ab79f51a0c927d22858d61ad12bd0b3865f0b13ece02a4486aeabb" dependencies = [ "rustc-std-workspace-core", ] @@ -111,9 +95,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.25.0" +version = "0.26.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0a01e0497841a3b2db4f8afa483cce65f7e96a3498bd6c541734792aeac8fe7" +checksum = "22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d" dependencies = [ "compiler_builtins", "rustc-std-workspace-alloc", @@ -145,9 +129,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.135" +version = "0.2.138" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68783febc7782c6c5cb401fbda4de5a9898be1762314da0bb2c10ced61f18b0c" +checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8" dependencies = [ "rustc-std-workspace-core", ] @@ -164,12 +148,11 @@ dependencies = [ [[package]] name = "miniz_oxide" -version = "0.4.4" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" +checksum = "96590ba8f175222643a85693f33d26e9c8a015f599c216509b1a6894af675d34" dependencies = [ "adler", - "autocfg", "compiler_builtins", "rustc-std-workspace-alloc", "rustc-std-workspace-core", @@ -177,9 +160,9 @@ dependencies = [ [[package]] name = "object" -version = "0.26.2" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39f37e50073ccad23b6d09bcb5b263f4e76d3bb6038e4a3c08e52162ffa8abc2" +checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53" dependencies = [ "compiler_builtins", "memchr", @@ -192,7 +175,7 @@ name = "panic_abort" version = "0.0.0" dependencies = [ "alloc", - "cfg-if 0.1.10", + "cfg-if", "compiler_builtins", "core", "libc", @@ -203,7 +186,7 @@ name = "panic_unwind" version = "0.0.0" dependencies = [ "alloc", - "cfg-if 0.1.10", + "cfg-if", "compiler_builtins", "core", "libc", @@ -255,7 +238,7 @@ version = "0.0.0" dependencies = [ "addr2line", "alloc", - "cfg-if 1.0.0", + "cfg-if", "compiler_builtins", "core", "dlmalloc", @@ -277,7 +260,7 @@ dependencies = [ name = "std_detect" version = "0.1.5" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "compiler_builtins", "libc", "rustc-std-workspace-alloc", @@ -299,7 +282,7 @@ dependencies = [ name = "test" version = "0.0.0" dependencies = [ - "cfg-if 0.1.10", + "cfg-if", "core", "getopts", "libc", @@ -325,7 +308,7 @@ name = "unwind" version = "0.0.0" dependencies = [ "cc", - "cfg-if 0.1.10", + "cfg-if", "compiler_builtins", "core", "libc", diff --git a/build_system/abi_cafe.rs b/build_system/abi_cafe.rs index fae5b27163680..a081fdaa1c7e6 100644 --- a/build_system/abi_cafe.rs +++ b/build_system/abi_cafe.rs @@ -1,16 +1,21 @@ -use std::env; use std::path::Path; use super::build_sysroot; use super::config; -use super::prepare; -use super::utils::{cargo_command, spawn_and_wait}; +use super::path::Dirs; +use super::prepare::GitRepo; +use super::utils::{spawn_and_wait, CargoProject, Compiler}; use super::SysrootKind; +pub(crate) static ABI_CAFE_REPO: GitRepo = + GitRepo::github("Gankra", "abi-cafe", "4c6dc8c9c687e2b3a760ff2176ce236872b37212", "abi-cafe"); + +static ABI_CAFE: CargoProject = CargoProject::new(&ABI_CAFE_REPO.source_dir(), "abi_cafe"); + pub(crate) fn run( channel: &str, sysroot_kind: SysrootKind, - target_dir: &Path, + dirs: &Dirs, cg_clif_dylib: &Path, host_triple: &str, target_triple: &str, @@ -27,26 +32,25 @@ pub(crate) fn run( eprintln!("Building sysroot for abi-cafe"); build_sysroot::build_sysroot( + dirs, channel, sysroot_kind, - target_dir, cg_clif_dylib, host_triple, target_triple, ); eprintln!("Running abi-cafe"); - let abi_cafe_path = prepare::ABI_CAFE.source_dir(); - env::set_current_dir(abi_cafe_path.clone()).unwrap(); let pairs = ["rustc_calls_cgclif", "cgclif_calls_rustc", "cgclif_calls_cc", "cc_calls_cgclif"]; - let mut cmd = cargo_command("cargo", "run", Some(target_triple), &abi_cafe_path); + let mut cmd = ABI_CAFE.run(&Compiler::host(), dirs); cmd.arg("--"); cmd.arg("--pairs"); cmd.args(pairs); cmd.arg("--add-rustc-codegen-backend"); cmd.arg(format!("cgclif:{}", cg_clif_dylib.display())); + cmd.current_dir(ABI_CAFE.source_dir(dirs)); spawn_and_wait(cmd); } diff --git a/build_system/build_backend.rs b/build_system/build_backend.rs index cda468bcfa2df..fde8ef424ccc5 100644 --- a/build_system/build_backend.rs +++ b/build_system/build_backend.rs @@ -1,16 +1,19 @@ use std::env; use std::path::PathBuf; +use super::path::{Dirs, RelPath}; use super::rustc_info::get_file_name; -use super::utils::{cargo_command, is_ci}; +use super::utils::{is_ci, CargoProject, Compiler}; + +static CG_CLIF: CargoProject = CargoProject::new(&RelPath::SOURCE, "cg_clif"); pub(crate) fn build_backend( + dirs: &Dirs, channel: &str, host_triple: &str, use_unstable_features: bool, ) -> PathBuf { - let source_dir = std::env::current_dir().unwrap(); - let mut cmd = cargo_command("cargo", "build", Some(host_triple), &source_dir); + let mut cmd = CG_CLIF.build(&Compiler::host(), dirs); cmd.env("CARGO_BUILD_INCREMENTAL", "true"); // Force incr comp even in release mode @@ -41,8 +44,8 @@ pub(crate) fn build_backend( eprintln!("[BUILD] rustc_codegen_cranelift"); super::utils::spawn_and_wait(cmd); - source_dir - .join("target") + CG_CLIF + .target_dir(dirs) .join(host_triple) .join(channel) .join(get_file_name("rustc_codegen_cranelift", "dylib")) diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index 856aecc49fd1c..cbbf09b9b97b8 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -1,57 +1,60 @@ use std::fs; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::{self, Command}; +use super::path::{Dirs, RelPath}; use super::rustc_info::{get_file_name, get_rustc_version, get_wrapper_file_name}; -use super::utils::{cargo_command, spawn_and_wait, try_hard_link}; +use super::utils::{spawn_and_wait, try_hard_link, CargoProject, Compiler}; use super::SysrootKind; +static DIST_DIR: RelPath = RelPath::DIST; +static BIN_DIR: RelPath = RelPath::DIST.join("bin"); +static LIB_DIR: RelPath = RelPath::DIST.join("lib"); +static RUSTLIB_DIR: RelPath = LIB_DIR.join("rustlib"); + pub(crate) fn build_sysroot( + dirs: &Dirs, channel: &str, sysroot_kind: SysrootKind, - target_dir: &Path, cg_clif_dylib_src: &Path, host_triple: &str, target_triple: &str, ) { eprintln!("[BUILD] sysroot {:?}", sysroot_kind); - if target_dir.exists() { - fs::remove_dir_all(target_dir).unwrap(); - } - fs::create_dir_all(target_dir.join("bin")).unwrap(); - fs::create_dir_all(target_dir.join("lib")).unwrap(); + DIST_DIR.ensure_fresh(dirs); + BIN_DIR.ensure_exists(dirs); + LIB_DIR.ensure_exists(dirs); // Copy the backend - let cg_clif_dylib_path = target_dir - .join(if cfg!(windows) { - // Windows doesn't have rpath support, so the cg_clif dylib needs to be next to the - // binaries. - "bin" - } else { - "lib" - }) - .join(get_file_name("rustc_codegen_cranelift", "dylib")); + let cg_clif_dylib_path = if cfg!(windows) { + // Windows doesn't have rpath support, so the cg_clif dylib needs to be next to the + // binaries. + BIN_DIR + } else { + LIB_DIR + } + .to_path(dirs) + .join(get_file_name("rustc_codegen_cranelift", "dylib")); try_hard_link(cg_clif_dylib_src, &cg_clif_dylib_path); // Build and copy rustc and cargo wrappers - for wrapper in ["rustc-clif", "cargo-clif"] { + for wrapper in ["rustc-clif", "rustdoc-clif", "cargo-clif"] { let wrapper_name = get_wrapper_file_name(wrapper, "bin"); let mut build_cargo_wrapper_cmd = Command::new("rustc"); build_cargo_wrapper_cmd - .arg(PathBuf::from("scripts").join(format!("{wrapper}.rs"))) + .arg(RelPath::SCRIPTS.to_path(dirs).join(&format!("{wrapper}.rs"))) .arg("-o") - .arg(target_dir.join(wrapper_name)) + .arg(DIST_DIR.to_path(dirs).join(wrapper_name)) .arg("-g"); spawn_and_wait(build_cargo_wrapper_cmd); } let default_sysroot = super::rustc_info::get_default_sysroot(); - let rustlib = target_dir.join("lib").join("rustlib"); - let host_rustlib_lib = rustlib.join(host_triple).join("lib"); - let target_rustlib_lib = rustlib.join(target_triple).join("lib"); + let host_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(host_triple).join("lib"); + let target_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(target_triple).join("lib"); fs::create_dir_all(&host_rustlib_lib).unwrap(); fs::create_dir_all(&target_rustlib_lib).unwrap(); @@ -112,24 +115,18 @@ pub(crate) fn build_sysroot( } } SysrootKind::Clif => { - build_clif_sysroot_for_triple( - channel, - target_dir, - host_triple, - &cg_clif_dylib_path, - None, - ); + build_clif_sysroot_for_triple(dirs, channel, host_triple, &cg_clif_dylib_path, None); if host_triple != target_triple { // When cross-compiling it is often necessary to manually pick the right linker - let linker = if target_triple == "aarch64-unknown-linux-gnu" { - Some("aarch64-linux-gnu-gcc") - } else { - None + let linker = match target_triple { + "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu-gcc"), + "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu-gcc"), + _ => None, }; build_clif_sysroot_for_triple( + dirs, channel, - target_dir, target_triple, &cg_clif_dylib_path, linker, @@ -142,21 +139,26 @@ pub(crate) fn build_sysroot( let file = file.unwrap().path(); let filename = file.file_name().unwrap().to_str().unwrap(); if filename.contains("std-") && !filename.contains(".rlib") { - try_hard_link(&file, target_dir.join("lib").join(file.file_name().unwrap())); + try_hard_link(&file, LIB_DIR.to_path(dirs).join(file.file_name().unwrap())); } } } } } +// FIXME move to download/ or dist/ +pub(crate) static SYSROOT_RUSTC_VERSION: RelPath = RelPath::BUILD_SYSROOT.join("rustc_version"); +pub(crate) static SYSROOT_SRC: RelPath = RelPath::BUILD_SYSROOT.join("sysroot_src"); +static STANDARD_LIBRARY: CargoProject = CargoProject::new(&RelPath::BUILD_SYSROOT, "build_sysroot"); + fn build_clif_sysroot_for_triple( + dirs: &Dirs, channel: &str, - target_dir: &Path, triple: &str, cg_clif_dylib_path: &Path, linker: Option<&str>, ) { - match fs::read_to_string(Path::new("build_sysroot").join("rustc_version")) { + match fs::read_to_string(SYSROOT_RUSTC_VERSION.to_path(dirs)) { Err(e) => { eprintln!("Failed to get rustc version for patched sysroot source: {}", e); eprintln!("Hint: Try `./y.rs prepare` to patch the sysroot source"); @@ -174,7 +176,7 @@ fn build_clif_sysroot_for_triple( } } - let build_dir = Path::new("build_sysroot").join("target").join(triple).join(channel); + let build_dir = STANDARD_LIBRARY.target_dir(dirs).join(triple).join(channel); if !super::config::get_bool("keep_sysroot") { // Cleanup the deps dir, but keep build scripts and the incremental cache for faster @@ -185,27 +187,27 @@ fn build_clif_sysroot_for_triple( } // Build sysroot - let mut build_cmd = cargo_command("cargo", "build", Some(triple), Path::new("build_sysroot")); let mut rustflags = "-Zforce-unstable-if-unmarked -Cpanic=abort".to_string(); rustflags.push_str(&format!(" -Zcodegen-backend={}", cg_clif_dylib_path.to_str().unwrap())); - rustflags.push_str(&format!(" --sysroot={}", target_dir.to_str().unwrap())); + rustflags.push_str(&format!(" --sysroot={}", DIST_DIR.to_path(dirs).to_str().unwrap())); if channel == "release" { - build_cmd.arg("--release"); rustflags.push_str(" -Zmir-opt-level=3"); } if let Some(linker) = linker { use std::fmt::Write; write!(rustflags, " -Clinker={}", linker).unwrap(); } - build_cmd.env("RUSTFLAGS", rustflags); + let mut compiler = Compiler::with_triple(triple.to_owned()); + compiler.rustflags = rustflags; + let mut build_cmd = STANDARD_LIBRARY.build(&compiler, dirs); + if channel == "release" { + build_cmd.arg("--release"); + } build_cmd.env("__CARGO_DEFAULT_LIB_METADATA", "cg_clif"); spawn_and_wait(build_cmd); // Copy all relevant files to the sysroot - for entry in - fs::read_dir(Path::new("build_sysroot/target").join(triple).join(channel).join("deps")) - .unwrap() - { + for entry in fs::read_dir(build_dir.join("deps")).unwrap() { let entry = entry.unwrap(); if let Some(ext) = entry.path().extension() { if ext == "rmeta" || ext == "d" || ext == "dSYM" || ext == "clif" { @@ -216,7 +218,7 @@ fn build_clif_sysroot_for_triple( }; try_hard_link( entry.path(), - target_dir.join("lib").join("rustlib").join(triple).join("lib").join(entry.file_name()), + RUSTLIB_DIR.to_path(dirs).join(triple).join("lib").join(entry.file_name()), ); } } diff --git a/build_system/mod.rs b/build_system/mod.rs index b25270d832ceb..1afc9a55c73b5 100644 --- a/build_system/mod.rs +++ b/build_system/mod.rs @@ -8,20 +8,37 @@ mod abi_cafe; mod build_backend; mod build_sysroot; mod config; +mod path; mod prepare; mod rustc_info; mod tests; mod utils; +const USAGE: &str = r#"The build system of cg_clif. + +USAGE: + ./y.rs prepare [--out-dir DIR] + ./y.rs build [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] + ./y.rs test [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] + +OPTIONS: + --sysroot none|clif|llvm + Which sysroot libraries to use: + `none` will not include any standard library in the sysroot. + `clif` will build the standard library using Cranelift. + `llvm` will use the pre-compiled standard library of rustc which is compiled with LLVM. + + --out-dir DIR + Specify the directory in which the download, build and dist directories are stored. + By default this is the working directory. + + --no-unstable-features + fSome features are not yet ready for production usage. This option will disable these + features. This includes the JIT mode and inline assembly support. +"#; + fn usage() { - eprintln!("Usage:"); - eprintln!(" ./y.rs prepare"); - eprintln!( - " ./y.rs build [--debug] [--sysroot none|clif|llvm] [--target-dir DIR] [--no-unstable-features]" - ); - eprintln!( - " ./y.rs test [--debug] [--sysroot none|clif|llvm] [--target-dir DIR] [--no-unstable-features]" - ); + eprintln!("{USAGE}"); } macro_rules! arg_error { @@ -34,6 +51,7 @@ macro_rules! arg_error { #[derive(PartialEq, Debug)] enum Command { + Prepare, Build, Test, } @@ -48,8 +66,6 @@ pub(crate) enum SysrootKind { pub fn main() { env::set_var("CG_CLIF_DISPLAY_CG_TIME", "1"); env::set_var("CG_CLIF_DISABLE_INCR_CACHE", "1"); - // The target dir is expected in the default location. Guard against the user changing it. - env::set_var("CARGO_TARGET_DIR", "target"); if is_ci() { // Disabling incr comp reduces cache size and incr comp doesn't save as much on CI anyway @@ -58,13 +74,7 @@ pub fn main() { let mut args = env::args().skip(1); let command = match args.next().as_deref() { - Some("prepare") => { - if args.next().is_some() { - arg_error!("./y.rs prepare doesn't expect arguments"); - } - prepare::prepare(); - process::exit(0); - } + Some("prepare") => Command::Prepare, Some("build") => Command::Build, Some("test") => Command::Test, Some(flag) if flag.starts_with('-') => arg_error!("Expected command found flag {}", flag), @@ -75,15 +85,15 @@ pub fn main() { } }; - let mut target_dir = PathBuf::from("build"); + let mut out_dir = PathBuf::from("."); let mut channel = "release"; let mut sysroot_kind = SysrootKind::Clif; let mut use_unstable_features = true; while let Some(arg) = args.next().as_deref() { match arg { - "--target-dir" => { - target_dir = PathBuf::from(args.next().unwrap_or_else(|| { - arg_error!("--target-dir requires argument"); + "--out-dir" => { + out_dir = PathBuf::from(args.next().unwrap_or_else(|| { + arg_error!("--out-dir requires argument"); })) } "--debug" => channel = "debug", @@ -101,7 +111,6 @@ pub fn main() { arg => arg_error!("Unexpected argument {}", arg), } } - target_dir = std::env::current_dir().unwrap().join(target_dir); let host_triple = if let Ok(host_triple) = std::env::var("HOST_TRIPLE") { host_triple @@ -122,13 +131,43 @@ pub fn main() { host_triple.clone() }; - let cg_clif_dylib = build_backend::build_backend(channel, &host_triple, use_unstable_features); + // FIXME allow changing the location of these dirs using cli arguments + let current_dir = std::env::current_dir().unwrap(); + out_dir = current_dir.join(out_dir); + let dirs = path::Dirs { + source_dir: current_dir.clone(), + download_dir: out_dir.join("download"), + build_dir: out_dir.join("build"), + dist_dir: out_dir.join("dist"), + }; + + path::RelPath::BUILD.ensure_exists(&dirs); + + { + // Make sure we always explicitly specify the target dir + let target = + path::RelPath::BUILD.join("target_dir_should_be_set_explicitly").to_path(&dirs); + env::set_var("CARGO_TARGET_DIR", &target); + let _ = std::fs::remove_file(&target); + std::fs::File::create(target).unwrap(); + } + + if command == Command::Prepare { + prepare::prepare(&dirs); + process::exit(0); + } + + let cg_clif_dylib = + build_backend::build_backend(&dirs, channel, &host_triple, use_unstable_features); match command { + Command::Prepare => { + // Handled above + } Command::Test => { tests::run_tests( + &dirs, channel, sysroot_kind, - &target_dir, &cg_clif_dylib, &host_triple, &target_triple, @@ -137,7 +176,7 @@ pub fn main() { abi_cafe::run( channel, sysroot_kind, - &target_dir, + &dirs, &cg_clif_dylib, &host_triple, &target_triple, @@ -145,9 +184,9 @@ pub fn main() { } Command::Build => { build_sysroot::build_sysroot( + &dirs, channel, sysroot_kind, - &target_dir, &cg_clif_dylib, &host_triple, &target_triple, diff --git a/build_system/path.rs b/build_system/path.rs new file mode 100644 index 0000000000000..e93981f1d64d3 --- /dev/null +++ b/build_system/path.rs @@ -0,0 +1,70 @@ +use std::fs; +use std::path::PathBuf; + +#[derive(Debug, Clone)] +pub(crate) struct Dirs { + pub(crate) source_dir: PathBuf, + pub(crate) download_dir: PathBuf, + pub(crate) build_dir: PathBuf, + pub(crate) dist_dir: PathBuf, +} + +#[doc(hidden)] +#[derive(Debug, Copy, Clone)] +pub(crate) enum PathBase { + Source, + Download, + Build, + Dist, +} + +impl PathBase { + fn to_path(self, dirs: &Dirs) -> PathBuf { + match self { + PathBase::Source => dirs.source_dir.clone(), + PathBase::Download => dirs.download_dir.clone(), + PathBase::Build => dirs.build_dir.clone(), + PathBase::Dist => dirs.dist_dir.clone(), + } + } +} + +#[derive(Debug, Copy, Clone)] +pub(crate) enum RelPath { + Base(PathBase), + Join(&'static RelPath, &'static str), +} + +impl RelPath { + pub(crate) const SOURCE: RelPath = RelPath::Base(PathBase::Source); + pub(crate) const DOWNLOAD: RelPath = RelPath::Base(PathBase::Download); + pub(crate) const BUILD: RelPath = RelPath::Base(PathBase::Build); + pub(crate) const DIST: RelPath = RelPath::Base(PathBase::Dist); + + pub(crate) const SCRIPTS: RelPath = RelPath::SOURCE.join("scripts"); + pub(crate) const BUILD_SYSROOT: RelPath = RelPath::SOURCE.join("build_sysroot"); + pub(crate) const PATCHES: RelPath = RelPath::SOURCE.join("patches"); + + pub(crate) const fn join(&'static self, suffix: &'static str) -> RelPath { + RelPath::Join(self, suffix) + } + + pub(crate) fn to_path(&self, dirs: &Dirs) -> PathBuf { + match self { + RelPath::Base(base) => base.to_path(dirs), + RelPath::Join(base, suffix) => base.to_path(dirs).join(suffix), + } + } + + pub(crate) fn ensure_exists(&self, dirs: &Dirs) { + fs::create_dir_all(self.to_path(dirs)).unwrap(); + } + + pub(crate) fn ensure_fresh(&self, dirs: &Dirs) { + let path = self.to_path(dirs); + if path.exists() { + fs::remove_dir_all(&path).unwrap(); + } + fs::create_dir_all(path).unwrap(); + } +} diff --git a/build_system/prepare.rs b/build_system/prepare.rs index 3111f62f6c215..8ac67e8f94228 100644 --- a/build_system/prepare.rs +++ b/build_system/prepare.rs @@ -1,92 +1,75 @@ -use std::env; use std::ffi::OsStr; use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; +use super::build_sysroot::{SYSROOT_RUSTC_VERSION, SYSROOT_SRC}; +use super::path::{Dirs, RelPath}; use super::rustc_info::{get_file_name, get_rustc_path, get_rustc_version}; -use super::utils::{cargo_command, copy_dir_recursively, spawn_and_wait}; - -pub(crate) const ABI_CAFE: GitRepo = - GitRepo::github("Gankra", "abi-cafe", "4c6dc8c9c687e2b3a760ff2176ce236872b37212", "abi-cafe"); - -pub(crate) const RAND: GitRepo = - GitRepo::github("rust-random", "rand", "0f933f9c7176e53b2a3c7952ded484e1783f0bf1", "rand"); - -pub(crate) const REGEX: GitRepo = - GitRepo::github("rust-lang", "regex", "341f207c1071f7290e3f228c710817c280c8dca1", "regex"); - -pub(crate) const PORTABLE_SIMD: GitRepo = GitRepo::github( - "rust-lang", - "portable-simd", - "d5cd4a8112d958bd3a252327e0d069a6363249bd", - "portable-simd", -); - -pub(crate) const SIMPLE_RAYTRACER: GitRepo = GitRepo::github( - "ebobby", - "simple-raytracer", - "804a7a21b9e673a482797aa289a18ed480e4d813", - "", -); - -pub(crate) fn prepare() { - if Path::new("download").exists() { - std::fs::remove_dir_all(Path::new("download")).unwrap(); +use super::utils::{copy_dir_recursively, spawn_and_wait, Compiler}; + +pub(crate) fn prepare(dirs: &Dirs) { + if RelPath::DOWNLOAD.to_path(dirs).exists() { + std::fs::remove_dir_all(RelPath::DOWNLOAD.to_path(dirs)).unwrap(); } - std::fs::create_dir_all(Path::new("download")).unwrap(); + std::fs::create_dir_all(RelPath::DOWNLOAD.to_path(dirs)).unwrap(); - prepare_sysroot(); + prepare_sysroot(dirs); // FIXME maybe install this only locally? eprintln!("[INSTALL] hyperfine"); - Command::new("cargo").arg("install").arg("hyperfine").spawn().unwrap().wait().unwrap(); + Command::new("cargo") + .arg("install") + .arg("hyperfine") + .env_remove("CARGO_TARGET_DIR") + .spawn() + .unwrap() + .wait() + .unwrap(); - ABI_CAFE.fetch(); - RAND.fetch(); - REGEX.fetch(); - PORTABLE_SIMD.fetch(); - SIMPLE_RAYTRACER.fetch(); + super::abi_cafe::ABI_CAFE_REPO.fetch(dirs); + super::tests::RAND_REPO.fetch(dirs); + super::tests::REGEX_REPO.fetch(dirs); + super::tests::PORTABLE_SIMD_REPO.fetch(dirs); + super::tests::SIMPLE_RAYTRACER_REPO.fetch(dirs); eprintln!("[LLVM BUILD] simple-raytracer"); - let build_cmd = cargo_command("cargo", "build", None, &SIMPLE_RAYTRACER.source_dir()); + let host_compiler = Compiler::host(); + let build_cmd = super::tests::SIMPLE_RAYTRACER.build(&host_compiler, dirs); spawn_and_wait(build_cmd); fs::copy( - SIMPLE_RAYTRACER - .source_dir() - .join("target") + super::tests::SIMPLE_RAYTRACER + .target_dir(dirs) + .join(&host_compiler.triple) .join("debug") .join(get_file_name("main", "bin")), - SIMPLE_RAYTRACER.source_dir().join(get_file_name("raytracer_cg_llvm", "bin")), + RelPath::BUILD.to_path(dirs).join(get_file_name("raytracer_cg_llvm", "bin")), ) .unwrap(); } -fn prepare_sysroot() { +fn prepare_sysroot(dirs: &Dirs) { let rustc_path = get_rustc_path(); let sysroot_src_orig = rustc_path.parent().unwrap().join("../lib/rustlib/src/rust"); - let sysroot_src = env::current_dir().unwrap().join("build_sysroot").join("sysroot_src"); + let sysroot_src = SYSROOT_SRC; assert!(sysroot_src_orig.exists()); - if sysroot_src.exists() { - fs::remove_dir_all(&sysroot_src).unwrap(); - } - fs::create_dir_all(sysroot_src.join("library")).unwrap(); + sysroot_src.ensure_fresh(dirs); + fs::create_dir_all(sysroot_src.to_path(dirs).join("library")).unwrap(); eprintln!("[COPY] sysroot src"); - copy_dir_recursively(&sysroot_src_orig.join("library"), &sysroot_src.join("library")); + copy_dir_recursively( + &sysroot_src_orig.join("library"), + &sysroot_src.to_path(dirs).join("library"), + ); let rustc_version = get_rustc_version(); - fs::write(Path::new("build_sysroot").join("rustc_version"), &rustc_version).unwrap(); + fs::write(SYSROOT_RUSTC_VERSION.to_path(dirs), &rustc_version).unwrap(); eprintln!("[GIT] init"); - let mut git_init_cmd = Command::new("git"); - git_init_cmd.arg("init").arg("-q").current_dir(&sysroot_src); - spawn_and_wait(git_init_cmd); - - init_git_repo(&sysroot_src); + init_git_repo(&sysroot_src.to_path(dirs)); - apply_patches("sysroot", &sysroot_src); + apply_patches(dirs, "sysroot", &sysroot_src.to_path(dirs)); } pub(crate) struct GitRepo { @@ -100,7 +83,7 @@ enum GitRepoUrl { } impl GitRepo { - const fn github( + pub(crate) const fn github( user: &'static str, repo: &'static str, rev: &'static str, @@ -109,21 +92,25 @@ impl GitRepo { GitRepo { url: GitRepoUrl::Github { user, repo }, rev, patch_name } } - pub(crate) fn source_dir(&self) -> PathBuf { + pub(crate) const fn source_dir(&self) -> RelPath { match self.url { - GitRepoUrl::Github { user: _, repo } => { - std::env::current_dir().unwrap().join("download").join(repo) - } + GitRepoUrl::Github { user: _, repo } => RelPath::DOWNLOAD.join(repo), } } - fn fetch(&self) { + fn fetch(&self, dirs: &Dirs) { match self.url { GitRepoUrl::Github { user, repo } => { - clone_repo_shallow_github(&self.source_dir(), user, repo, self.rev); + clone_repo_shallow_github( + dirs, + &self.source_dir().to_path(dirs), + user, + repo, + self.rev, + ); } } - apply_patches(self.patch_name, &self.source_dir()); + apply_patches(dirs, self.patch_name, &self.source_dir().to_path(dirs)); } } @@ -142,18 +129,16 @@ fn clone_repo(download_dir: &Path, repo: &str, rev: &str) { spawn_and_wait(checkout_cmd); } -fn clone_repo_shallow_github(download_dir: &Path, user: &str, repo: &str, rev: &str) { +fn clone_repo_shallow_github(dirs: &Dirs, download_dir: &Path, user: &str, repo: &str, rev: &str) { if cfg!(windows) { // Older windows doesn't have tar or curl by default. Fall back to using git. clone_repo(download_dir, &format!("https://github.com/{}/{}.git", user, repo), rev); return; } - let downloads_dir = std::env::current_dir().unwrap().join("download"); - let archive_url = format!("https://github.com/{}/{}/archive/{}.tar.gz", user, repo, rev); - let archive_file = downloads_dir.join(format!("{}.tar.gz", rev)); - let archive_dir = downloads_dir.join(format!("{}-{}", repo, rev)); + let archive_file = RelPath::DOWNLOAD.to_path(dirs).join(format!("{}.tar.gz", rev)); + let archive_dir = RelPath::DOWNLOAD.to_path(dirs).join(format!("{}-{}", repo, rev)); eprintln!("[DOWNLOAD] {}/{} from {}", user, repo, archive_url); @@ -169,7 +154,7 @@ fn clone_repo_shallow_github(download_dir: &Path, user: &str, repo: &str, rev: & // Unpack tar archive let mut unpack_cmd = Command::new("tar"); - unpack_cmd.arg("xf").arg(&archive_file).current_dir(downloads_dir); + unpack_cmd.arg("xf").arg(&archive_file).current_dir(RelPath::DOWNLOAD.to_path(dirs)); spawn_and_wait(unpack_cmd); // Rename unpacked dir to the expected name @@ -191,12 +176,21 @@ fn init_git_repo(repo_dir: &Path) { spawn_and_wait(git_add_cmd); let mut git_commit_cmd = Command::new("git"); - git_commit_cmd.arg("commit").arg("-m").arg("Initial commit").arg("-q").current_dir(repo_dir); + git_commit_cmd + .arg("-c") + .arg("user.name=Dummy") + .arg("-c") + .arg("user.email=dummy@example.com") + .arg("commit") + .arg("-m") + .arg("Initial commit") + .arg("-q") + .current_dir(repo_dir); spawn_and_wait(git_commit_cmd); } -fn get_patches(source_dir: &Path, crate_name: &str) -> Vec { - let mut patches: Vec<_> = fs::read_dir(source_dir.join("patches")) +fn get_patches(dirs: &Dirs, crate_name: &str) -> Vec { + let mut patches: Vec<_> = fs::read_dir(RelPath::PATCHES.to_path(dirs)) .unwrap() .map(|entry| entry.unwrap().path()) .filter(|path| path.extension() == Some(OsStr::new("patch"))) @@ -215,19 +209,27 @@ fn get_patches(source_dir: &Path, crate_name: &str) -> Vec { patches } -fn apply_patches(crate_name: &str, target_dir: &Path) { +fn apply_patches(dirs: &Dirs, crate_name: &str, target_dir: &Path) { if crate_name == "" { return; } - for patch in get_patches(&std::env::current_dir().unwrap(), crate_name) { + for patch in get_patches(dirs, crate_name) { eprintln!( "[PATCH] {:?} <- {:?}", target_dir.file_name().unwrap(), patch.file_name().unwrap() ); let mut apply_patch_cmd = Command::new("git"); - apply_patch_cmd.arg("am").arg(patch).arg("-q").current_dir(target_dir); + apply_patch_cmd + .arg("-c") + .arg("user.name=Dummy") + .arg("-c") + .arg("user.email=dummy@example.com") + .arg("am") + .arg(patch) + .arg("-q") + .current_dir(target_dir); spawn_and_wait(apply_patch_cmd); } } diff --git a/build_system/rustc_info.rs b/build_system/rustc_info.rs index 3c08b6fa3894d..8e5ab688e131b 100644 --- a/build_system/rustc_info.rs +++ b/build_system/rustc_info.rs @@ -23,6 +23,16 @@ pub(crate) fn get_host_triple() -> String { .to_owned() } +pub(crate) fn get_cargo_path() -> PathBuf { + let cargo_path = Command::new("rustup") + .stderr(Stdio::inherit()) + .args(&["which", "cargo"]) + .output() + .unwrap() + .stdout; + Path::new(String::from_utf8(cargo_path).unwrap().trim()).to_owned() +} + pub(crate) fn get_rustc_path() -> PathBuf { let rustc_path = Command::new("rustup") .stderr(Stdio::inherit()) @@ -33,6 +43,16 @@ pub(crate) fn get_rustc_path() -> PathBuf { Path::new(String::from_utf8(rustc_path).unwrap().trim()).to_owned() } +pub(crate) fn get_rustdoc_path() -> PathBuf { + let rustc_path = Command::new("rustup") + .stderr(Stdio::inherit()) + .args(&["which", "rustdoc"]) + .output() + .unwrap() + .stdout; + Path::new(String::from_utf8(rustc_path).unwrap().trim()).to_owned() +} + pub(crate) fn get_default_sysroot() -> PathBuf { let default_sysroot = Command::new("rustc") .stderr(Stdio::inherit()) diff --git a/build_system/tests.rs b/build_system/tests.rs index a414b60f4e06b..1c372736ed65d 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -1,15 +1,20 @@ use super::build_sysroot; use super::config; -use super::prepare; -use super::rustc_info::get_wrapper_file_name; -use super::utils::{cargo_command, hyperfine_command, spawn_and_wait, spawn_and_wait_with_input}; -use build_system::SysrootKind; +use super::path::{Dirs, RelPath}; +use super::prepare::GitRepo; +use super::rustc_info::{get_cargo_path, get_wrapper_file_name}; +use super::utils::{ + hyperfine_command, spawn_and_wait, spawn_and_wait_with_input, CargoProject, Compiler, +}; +use super::SysrootKind; use std::env; use std::ffi::OsStr; use std::fs; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::Command; +static BUILD_EXAMPLE_OUT_DIR: RelPath = RelPath::BUILD.join("example"); + struct TestCase { config: &'static str, func: &'static dyn Fn(&TestRunner), @@ -30,7 +35,7 @@ const NO_SYSROOT_SUITE: &[TestCase] = &[ "--crate-type", "lib,dylib", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); }), TestCase::new("build.example", &|runner| { @@ -39,7 +44,7 @@ const NO_SYSROOT_SUITE: &[TestCase] = &[ "--crate-type", "lib", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); }), TestCase::new("jit.mini_core_hello_world", &|runner| { @@ -51,7 +56,7 @@ const NO_SYSROOT_SUITE: &[TestCase] = &[ "--cfg", "jit", "--target", - &runner.host_triple, + &runner.target_compiler.triple, ]); jit_cmd.env("CG_CLIF_JIT_ARGS", "abc bcd"); spawn_and_wait(jit_cmd); @@ -65,7 +70,7 @@ const NO_SYSROOT_SUITE: &[TestCase] = &[ "--cfg", "jit", "--target", - &runner.host_triple, + &runner.target_compiler.triple, ]); jit_cmd.env("CG_CLIF_JIT_ARGS", "abc bcd"); spawn_and_wait(jit_cmd); @@ -79,7 +84,7 @@ const NO_SYSROOT_SUITE: &[TestCase] = &[ "bin", "-g", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); runner.run_out_command("mini_core_hello_world", ["abc", "bcd"]); }), @@ -94,7 +99,7 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "--crate-type", "bin", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); runner.run_out_command("arbitrary_self_types_pointers_and_wrappers", []); }), @@ -106,7 +111,7 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "--crate-type", "bin", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); runner.run_out_command("issue_91827_extern_types", []); }), @@ -116,7 +121,7 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "--crate-type", "lib", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); }), TestCase::new("aot.alloc_example", &|runner| { @@ -125,7 +130,7 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "--crate-type", "bin", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); runner.run_out_command("alloc_example", []); }), @@ -136,7 +141,7 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "-Cprefer-dynamic", "example/std_example.rs", "--target", - &runner.host_triple, + &runner.target_compiler.triple, ]); eprintln!("[JIT-lazy] std_example"); @@ -146,7 +151,7 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "-Cprefer-dynamic", "example/std_example.rs", "--target", - &runner.host_triple, + &runner.target_compiler.triple, ]); }), TestCase::new("aot.std_example", &|runner| { @@ -155,7 +160,7 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "--crate-type", "bin", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); runner.run_out_command("std_example", ["arg"]); }), @@ -167,7 +172,7 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "--crate-type", "bin", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); runner.run_out_command("dst_field_align", []); }), @@ -178,7 +183,7 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "bin", "-Cpanic=abort", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); runner.run_out_command("subslice-patterns-const-eval", []); }), @@ -189,7 +194,7 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "bin", "-Cpanic=abort", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); runner.run_out_command("track-caller-attribute", []); }), @@ -200,7 +205,7 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "bin", "-Cpanic=abort", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); runner.run_out_command("float-minmax-pass", []); }), @@ -210,205 +215,252 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "--crate-type", "bin", "--target", - &runner.target_triple, + &runner.target_compiler.triple, ]); runner.run_out_command("mod_bench", []); }), + TestCase::new("aot.issue-72793", &|runner| { + runner.run_rustc([ + "example/issue-72793.rs", + "--crate-type", + "bin", + "--target", + &runner.target_compiler.triple, + ]); + runner.run_out_command("issue-72793", []); + }), ]; +pub(crate) static RAND_REPO: GitRepo = + GitRepo::github("rust-random", "rand", "0f933f9c7176e53b2a3c7952ded484e1783f0bf1", "rand"); + +static RAND: CargoProject = CargoProject::new(&RAND_REPO.source_dir(), "rand"); + +pub(crate) static REGEX_REPO: GitRepo = + GitRepo::github("rust-lang", "regex", "341f207c1071f7290e3f228c710817c280c8dca1", "regex"); + +static REGEX: CargoProject = CargoProject::new(®EX_REPO.source_dir(), "regex"); + +pub(crate) static PORTABLE_SIMD_REPO: GitRepo = GitRepo::github( + "rust-lang", + "portable-simd", + "d5cd4a8112d958bd3a252327e0d069a6363249bd", + "portable-simd", +); + +static PORTABLE_SIMD: CargoProject = + CargoProject::new(&PORTABLE_SIMD_REPO.source_dir(), "portable_simd"); + +pub(crate) static SIMPLE_RAYTRACER_REPO: GitRepo = GitRepo::github( + "ebobby", + "simple-raytracer", + "804a7a21b9e673a482797aa289a18ed480e4d813", + "", +); + +pub(crate) static SIMPLE_RAYTRACER: CargoProject = + CargoProject::new(&SIMPLE_RAYTRACER_REPO.source_dir(), "simple_raytracer"); + +static LIBCORE_TESTS: CargoProject = + CargoProject::new(&RelPath::BUILD_SYSROOT.join("sysroot_src/library/core/tests"), "core_tests"); + const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ TestCase::new("test.rust-random/rand", &|runner| { - runner.in_dir(prepare::RAND.source_dir(), |runner| { - runner.run_cargo("clean", []); - - if runner.host_triple == runner.target_triple { - eprintln!("[TEST] rust-random/rand"); - runner.run_cargo("test", ["--workspace"]); - } else { - eprintln!("[AOT] rust-random/rand"); - runner.run_cargo("build", ["--workspace", "--tests"]); - } - }); + spawn_and_wait(RAND.clean(&runner.target_compiler.cargo, &runner.dirs)); + + if runner.is_native { + eprintln!("[TEST] rust-random/rand"); + let mut test_cmd = RAND.test(&runner.target_compiler, &runner.dirs); + test_cmd.arg("--workspace"); + spawn_and_wait(test_cmd); + } else { + eprintln!("[AOT] rust-random/rand"); + let mut build_cmd = RAND.build(&runner.target_compiler, &runner.dirs); + build_cmd.arg("--workspace").arg("--tests"); + spawn_and_wait(build_cmd); + } }), TestCase::new("bench.simple-raytracer", &|runner| { - runner.in_dir(prepare::SIMPLE_RAYTRACER.source_dir(), |runner| { - let run_runs = env::var("RUN_RUNS").unwrap_or("10".to_string()).parse().unwrap(); - - if runner.host_triple == runner.target_triple { - eprintln!("[BENCH COMPILE] ebobby/simple-raytracer"); - let prepare = runner.cargo_command("clean", []); - - let llvm_build_cmd = cargo_command("cargo", "build", None, Path::new(".")); - - let cargo_clif = runner - .root_dir - .clone() - .join("build") - .join(get_wrapper_file_name("cargo-clif", "bin")); - let clif_build_cmd = cargo_command(cargo_clif, "build", None, Path::new(".")); - - let bench_compile = - hyperfine_command(1, run_runs, Some(prepare), llvm_build_cmd, clif_build_cmd); - - spawn_and_wait(bench_compile); - - eprintln!("[BENCH RUN] ebobby/simple-raytracer"); - fs::copy(PathBuf::from("./target/debug/main"), PathBuf::from("raytracer_cg_clif")) - .unwrap(); - - let bench_run = hyperfine_command( - 0, - run_runs, - None, - Command::new("./raytracer_cg_llvm"), - Command::new("./raytracer_cg_clif"), - ); - spawn_and_wait(bench_run); - } else { - runner.run_cargo("clean", []); - eprintln!("[BENCH COMPILE] ebobby/simple-raytracer (skipped)"); - eprintln!("[COMPILE] ebobby/simple-raytracer"); - runner.run_cargo("build", []); - eprintln!("[BENCH RUN] ebobby/simple-raytracer (skipped)"); - } - }); + let run_runs = env::var("RUN_RUNS").unwrap_or("10".to_string()).parse().unwrap(); + + if runner.is_native { + eprintln!("[BENCH COMPILE] ebobby/simple-raytracer"); + let cargo_clif = RelPath::DIST + .to_path(&runner.dirs) + .join(get_wrapper_file_name("cargo-clif", "bin")); + let manifest_path = SIMPLE_RAYTRACER.manifest_path(&runner.dirs); + let target_dir = SIMPLE_RAYTRACER.target_dir(&runner.dirs); + + let clean_cmd = format!( + "cargo clean --manifest-path {manifest_path} --target-dir {target_dir}", + manifest_path = manifest_path.display(), + target_dir = target_dir.display(), + ); + let llvm_build_cmd = format!( + "cargo build --manifest-path {manifest_path} --target-dir {target_dir}", + manifest_path = manifest_path.display(), + target_dir = target_dir.display(), + ); + let clif_build_cmd = format!( + "{cargo_clif} build --manifest-path {manifest_path} --target-dir {target_dir}", + cargo_clif = cargo_clif.display(), + manifest_path = manifest_path.display(), + target_dir = target_dir.display(), + ); + + let bench_compile = + hyperfine_command(1, run_runs, Some(&clean_cmd), &llvm_build_cmd, &clif_build_cmd); + + spawn_and_wait(bench_compile); + + eprintln!("[BENCH RUN] ebobby/simple-raytracer"); + fs::copy( + target_dir.join("debug").join("main"), + RelPath::BUILD.to_path(&runner.dirs).join("raytracer_cg_clif"), + ) + .unwrap(); + + let mut bench_run = + hyperfine_command(0, run_runs, None, "./raytracer_cg_llvm", "./raytracer_cg_clif"); + bench_run.current_dir(RelPath::BUILD.to_path(&runner.dirs)); + spawn_and_wait(bench_run); + } else { + spawn_and_wait(SIMPLE_RAYTRACER.clean(&runner.target_compiler.cargo, &runner.dirs)); + eprintln!("[BENCH COMPILE] ebobby/simple-raytracer (skipped)"); + eprintln!("[COMPILE] ebobby/simple-raytracer"); + spawn_and_wait(SIMPLE_RAYTRACER.build(&runner.target_compiler, &runner.dirs)); + eprintln!("[BENCH RUN] ebobby/simple-raytracer (skipped)"); + } }), TestCase::new("test.libcore", &|runner| { - runner.in_dir( - std::env::current_dir() - .unwrap() - .join("build_sysroot") - .join("sysroot_src") - .join("library") - .join("core") - .join("tests"), - |runner| { - runner.run_cargo("clean", []); - - if runner.host_triple == runner.target_triple { - runner.run_cargo("test", []); - } else { - eprintln!("Cross-Compiling: Not running tests"); - runner.run_cargo("build", ["--tests"]); - } - }, - ); + spawn_and_wait(LIBCORE_TESTS.clean(&runner.host_compiler.cargo, &runner.dirs)); + + if runner.is_native { + spawn_and_wait(LIBCORE_TESTS.test(&runner.target_compiler, &runner.dirs)); + } else { + eprintln!("Cross-Compiling: Not running tests"); + let mut build_cmd = LIBCORE_TESTS.build(&runner.target_compiler, &runner.dirs); + build_cmd.arg("--tests"); + spawn_and_wait(build_cmd); + } }), TestCase::new("test.regex-shootout-regex-dna", &|runner| { - runner.in_dir(prepare::REGEX.source_dir(), |runner| { - runner.run_cargo("clean", []); - - // newer aho_corasick versions throw a deprecation warning - let lint_rust_flags = format!("{} --cap-lints warn", runner.rust_flags); - - let mut build_cmd = runner.cargo_command("build", ["--example", "shootout-regex-dna"]); - build_cmd.env("RUSTFLAGS", lint_rust_flags.clone()); - spawn_and_wait(build_cmd); - - if runner.host_triple == runner.target_triple { - let mut run_cmd = runner.cargo_command("run", ["--example", "shootout-regex-dna"]); - run_cmd.env("RUSTFLAGS", lint_rust_flags); - - let input = - fs::read_to_string(PathBuf::from("examples/regexdna-input.txt")).unwrap(); - let expected_path = PathBuf::from("examples/regexdna-output.txt"); - let expected = fs::read_to_string(&expected_path).unwrap(); - - let output = spawn_and_wait_with_input(run_cmd, input); - // Make sure `[codegen mono items] start` doesn't poison the diff - let output = output - .lines() - .filter(|line| !line.contains("codegen mono items")) - .chain(Some("")) // This just adds the trailing newline - .collect::>() - .join("\r\n"); - - let output_matches = expected.lines().eq(output.lines()); - if !output_matches { - let res_path = PathBuf::from("res.txt"); - fs::write(&res_path, &output).unwrap(); - - if cfg!(windows) { - println!("Output files don't match!"); - println!("Expected Output:\n{}", expected); - println!("Actual Output:\n{}", output); - } else { - let mut diff = Command::new("diff"); - diff.arg("-u"); - diff.arg(res_path); - diff.arg(expected_path); - spawn_and_wait(diff); - } - - std::process::exit(1); + spawn_and_wait(REGEX.clean(&runner.target_compiler.cargo, &runner.dirs)); + + // newer aho_corasick versions throw a deprecation warning + let lint_rust_flags = format!("{} --cap-lints warn", runner.target_compiler.rustflags); + + let mut build_cmd = REGEX.build(&runner.target_compiler, &runner.dirs); + build_cmd.arg("--example").arg("shootout-regex-dna"); + build_cmd.env("RUSTFLAGS", lint_rust_flags.clone()); + spawn_and_wait(build_cmd); + + if runner.is_native { + let mut run_cmd = REGEX.run(&runner.target_compiler, &runner.dirs); + run_cmd.arg("--example").arg("shootout-regex-dna"); + run_cmd.env("RUSTFLAGS", lint_rust_flags); + + let input = fs::read_to_string( + REGEX.source_dir(&runner.dirs).join("examples").join("regexdna-input.txt"), + ) + .unwrap(); + let expected_path = + REGEX.source_dir(&runner.dirs).join("examples").join("regexdna-output.txt"); + let expected = fs::read_to_string(&expected_path).unwrap(); + + let output = spawn_and_wait_with_input(run_cmd, input); + // Make sure `[codegen mono items] start` doesn't poison the diff + let output = output + .lines() + .filter(|line| !line.contains("codegen mono items")) + .chain(Some("")) // This just adds the trailing newline + .collect::>() + .join("\r\n"); + + let output_matches = expected.lines().eq(output.lines()); + if !output_matches { + let res_path = REGEX.source_dir(&runner.dirs).join("res.txt"); + fs::write(&res_path, &output).unwrap(); + + if cfg!(windows) { + println!("Output files don't match!"); + println!("Expected Output:\n{}", expected); + println!("Actual Output:\n{}", output); + } else { + let mut diff = Command::new("diff"); + diff.arg("-u"); + diff.arg(res_path); + diff.arg(expected_path); + spawn_and_wait(diff); } + + std::process::exit(1); } - }); + } }), TestCase::new("test.regex", &|runner| { - runner.in_dir(prepare::REGEX.source_dir(), |runner| { - runner.run_cargo("clean", []); - - // newer aho_corasick versions throw a deprecation warning - let lint_rust_flags = format!("{} --cap-lints warn", runner.rust_flags); - - if runner.host_triple == runner.target_triple { - let mut run_cmd = runner.cargo_command( - "test", - [ - "--tests", - "--", - "--exclude-should-panic", - "--test-threads", - "1", - "-Zunstable-options", - "-q", - ], - ); - run_cmd.env("RUSTFLAGS", lint_rust_flags); - spawn_and_wait(run_cmd); - } else { - eprintln!("Cross-Compiling: Not running tests"); - let mut build_cmd = - runner.cargo_command("build", ["--tests", "--target", &runner.target_triple]); - build_cmd.env("RUSTFLAGS", lint_rust_flags.clone()); - spawn_and_wait(build_cmd); - } - }); + spawn_and_wait(REGEX.clean(&runner.host_compiler.cargo, &runner.dirs)); + + // newer aho_corasick versions throw a deprecation warning + let lint_rust_flags = format!("{} --cap-lints warn", runner.target_compiler.rustflags); + + if runner.is_native { + let mut run_cmd = REGEX.test(&runner.target_compiler, &runner.dirs); + run_cmd.args([ + "--tests", + "--", + "--exclude-should-panic", + "--test-threads", + "1", + "-Zunstable-options", + "-q", + ]); + run_cmd.env("RUSTFLAGS", lint_rust_flags); + spawn_and_wait(run_cmd); + } else { + eprintln!("Cross-Compiling: Not running tests"); + let mut build_cmd = REGEX.build(&runner.target_compiler, &runner.dirs); + build_cmd.arg("--tests"); + build_cmd.env("RUSTFLAGS", lint_rust_flags.clone()); + spawn_and_wait(build_cmd); + } }), TestCase::new("test.portable-simd", &|runner| { - runner.in_dir(prepare::PORTABLE_SIMD.source_dir(), |runner| { - runner.run_cargo("clean", []); - runner.run_cargo("build", ["--all-targets", "--target", &runner.target_triple]); + spawn_and_wait(PORTABLE_SIMD.clean(&runner.host_compiler.cargo, &runner.dirs)); - if runner.host_triple == runner.target_triple { - runner.run_cargo("test", ["-q"]); - } - }); + let mut build_cmd = PORTABLE_SIMD.build(&runner.target_compiler, &runner.dirs); + build_cmd.arg("--all-targets"); + spawn_and_wait(build_cmd); + + if runner.is_native { + let mut test_cmd = PORTABLE_SIMD.test(&runner.target_compiler, &runner.dirs); + test_cmd.arg("-q"); + spawn_and_wait(test_cmd); + } }), ]; pub(crate) fn run_tests( + dirs: &Dirs, channel: &str, sysroot_kind: SysrootKind, - target_dir: &Path, cg_clif_dylib: &Path, host_triple: &str, target_triple: &str, ) { - let runner = TestRunner::new(host_triple.to_string(), target_triple.to_string()); + let runner = TestRunner::new(dirs.clone(), host_triple.to_string(), target_triple.to_string()); if config::get_bool("testsuite.no_sysroot") { build_sysroot::build_sysroot( + dirs, channel, SysrootKind::None, - &target_dir, cg_clif_dylib, &host_triple, &target_triple, ); - let _ = fs::remove_dir_all(Path::new("target").join("out")); + BUILD_EXAMPLE_OUT_DIR.ensure_fresh(dirs); runner.run_testsuite(NO_SYSROOT_SUITE); } else { eprintln!("[SKIP] no_sysroot tests"); @@ -419,9 +471,9 @@ pub(crate) fn run_tests( if run_base_sysroot || run_extended_sysroot { build_sysroot::build_sysroot( + dirs, channel, sysroot_kind, - &target_dir, cg_clif_dylib, &host_triple, &target_triple, @@ -442,40 +494,50 @@ pub(crate) fn run_tests( } struct TestRunner { - root_dir: PathBuf, - out_dir: PathBuf, + is_native: bool, jit_supported: bool, - rust_flags: String, - run_wrapper: Vec, - host_triple: String, - target_triple: String, + dirs: Dirs, + host_compiler: Compiler, + target_compiler: Compiler, } impl TestRunner { - pub fn new(host_triple: String, target_triple: String) -> Self { - let root_dir = env::current_dir().unwrap(); - - let mut out_dir = root_dir.clone(); - out_dir.push("target"); - out_dir.push("out"); - + pub fn new(dirs: Dirs, host_triple: String, target_triple: String) -> Self { let is_native = host_triple == target_triple; let jit_supported = target_triple.contains("x86_64") && is_native && !host_triple.contains("windows"); - let mut rust_flags = env::var("RUSTFLAGS").ok().unwrap_or("".to_string()); - let mut run_wrapper = Vec::new(); + let rustc_clif = + RelPath::DIST.to_path(&dirs).join(get_wrapper_file_name("rustc-clif", "bin")); + let rustdoc_clif = + RelPath::DIST.to_path(&dirs).join(get_wrapper_file_name("rustdoc-clif", "bin")); + + let mut rustflags = env::var("RUSTFLAGS").ok().unwrap_or("".to_string()); + let mut runner = vec![]; if !is_native { match target_triple.as_str() { "aarch64-unknown-linux-gnu" => { // We are cross-compiling for aarch64. Use the correct linker and run tests in qemu. - rust_flags = format!("-Clinker=aarch64-linux-gnu-gcc{}", rust_flags); - run_wrapper = vec!["qemu-aarch64", "-L", "/usr/aarch64-linux-gnu"]; + rustflags = format!("-Clinker=aarch64-linux-gnu-gcc{}", rustflags); + runner = vec![ + "qemu-aarch64".to_owned(), + "-L".to_owned(), + "/usr/aarch64-linux-gnu".to_owned(), + ]; + } + "s390x-unknown-linux-gnu" => { + // We are cross-compiling for s390x. Use the correct linker and run tests in qemu. + rustflags = format!("-Clinker=s390x-linux-gnu-gcc{}", rustflags); + runner = vec![ + "qemu-s390x".to_owned(), + "-L".to_owned(), + "/usr/s390x-linux-gnu".to_owned(), + ]; } "x86_64-pc-windows-gnu" => { // We are cross-compiling for Windows. Run tests in wine. - run_wrapper = vec!["wine"]; + runner = vec!["wine".to_owned()]; } _ => { println!("Unknown non-native platform"); @@ -484,19 +546,31 @@ impl TestRunner { } // FIXME fix `#[linkage = "extern_weak"]` without this - if host_triple.contains("darwin") { - rust_flags = format!("{} -Clink-arg=-undefined -Clink-arg=dynamic_lookup", rust_flags); + if target_triple.contains("darwin") { + rustflags = format!("{} -Clink-arg=-undefined -Clink-arg=dynamic_lookup", rustflags); } - Self { - root_dir, - out_dir, - jit_supported, - rust_flags, - run_wrapper: run_wrapper.iter().map(|s| s.to_string()).collect(), - host_triple, - target_triple, - } + let host_compiler = Compiler { + cargo: get_cargo_path(), + rustc: rustc_clif.clone(), + rustdoc: rustdoc_clif.clone(), + rustflags: String::new(), + rustdocflags: String::new(), + triple: host_triple, + runner: vec![], + }; + + let target_compiler = Compiler { + cargo: get_cargo_path(), + rustc: rustc_clif, + rustdoc: rustdoc_clif, + rustflags: rustflags.clone(), + rustdocflags: rustflags, + triple: target_triple, + runner, + }; + + Self { is_native, jit_supported, dirs, host_compiler, target_compiler } } pub fn run_testsuite(&self, tests: &[TestCase]) { @@ -516,29 +590,18 @@ impl TestRunner { } } - fn in_dir(&self, new: impl AsRef, callback: impl FnOnce(&TestRunner)) { - let current = env::current_dir().unwrap(); - - env::set_current_dir(new).unwrap(); - callback(self); - env::set_current_dir(current).unwrap(); - } - + #[must_use] fn rustc_command(&self, args: I) -> Command where I: IntoIterator, S: AsRef, { - let mut rustc_clif = self.root_dir.clone(); - rustc_clif.push("build"); - rustc_clif.push(get_wrapper_file_name("rustc-clif", "bin")); - - let mut cmd = Command::new(rustc_clif); - cmd.args(self.rust_flags.split_whitespace()); + let mut cmd = Command::new(&self.target_compiler.rustc); + cmd.args(self.target_compiler.rustflags.split_whitespace()); cmd.arg("-L"); - cmd.arg(format!("crate={}", self.out_dir.display())); + cmd.arg(format!("crate={}", BUILD_EXAMPLE_OUT_DIR.to_path(&self.dirs).display())); cmd.arg("--out-dir"); - cmd.arg(format!("{}", self.out_dir.display())); + cmd.arg(format!("{}", BUILD_EXAMPLE_OUT_DIR.to_path(&self.dirs).display())); cmd.arg("-Cdebuginfo=2"); cmd.args(args); cmd @@ -559,15 +622,13 @@ impl TestRunner { let mut full_cmd = vec![]; // Prepend the RUN_WRAPPER's - if !self.run_wrapper.is_empty() { - full_cmd.extend(self.run_wrapper.iter().cloned()); + if !self.target_compiler.runner.is_empty() { + full_cmd.extend(self.target_compiler.runner.iter().cloned()); } - full_cmd.push({ - let mut out_path = self.out_dir.clone(); - out_path.push(name); - out_path.to_str().unwrap().to_string() - }); + full_cmd.push( + BUILD_EXAMPLE_OUT_DIR.to_path(&self.dirs).join(name).to_str().unwrap().to_string(), + ); for arg in args.into_iter() { full_cmd.push(arg.to_string()); @@ -581,30 +642,4 @@ impl TestRunner { spawn_and_wait(cmd); } - - fn cargo_command<'a, I>(&self, subcommand: &str, args: I) -> Command - where - I: IntoIterator, - { - let mut cargo_clif = self.root_dir.clone(); - cargo_clif.push("build"); - cargo_clif.push(get_wrapper_file_name("cargo-clif", "bin")); - - let mut cmd = cargo_command( - cargo_clif, - subcommand, - if subcommand == "clean" { None } else { Some(&self.target_triple) }, - Path::new("."), - ); - cmd.args(args); - cmd.env("RUSTFLAGS", &self.rust_flags); - cmd - } - - fn run_cargo<'a, I>(&self, subcommand: &str, args: I) - where - I: IntoIterator, - { - spawn_and_wait(self.cargo_command(subcommand, args)); - } } diff --git a/build_system/utils.rs b/build_system/utils.rs index c627af4e62fe1..2be70e8e421b2 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -1,35 +1,138 @@ use std::env; use std::fs; use std::io::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{self, Command, Stdio}; -pub(crate) fn cargo_command( - cargo: impl AsRef, - subcommand: &str, - triple: Option<&str>, - source_dir: &Path, -) -> Command { - let mut cmd = Command::new(cargo.as_ref()); - cmd.arg(subcommand) - .arg("--manifest-path") - .arg(source_dir.join("Cargo.toml")) - .arg("--target-dir") - .arg(source_dir.join("target")); +use super::path::{Dirs, RelPath}; +use super::rustc_info::{get_cargo_path, get_host_triple, get_rustc_path, get_rustdoc_path}; + +pub(crate) struct Compiler { + pub(crate) cargo: PathBuf, + pub(crate) rustc: PathBuf, + pub(crate) rustdoc: PathBuf, + pub(crate) rustflags: String, + pub(crate) rustdocflags: String, + pub(crate) triple: String, + pub(crate) runner: Vec, +} + +impl Compiler { + pub(crate) fn host() -> Compiler { + Compiler { + cargo: get_cargo_path(), + rustc: get_rustc_path(), + rustdoc: get_rustdoc_path(), + rustflags: String::new(), + rustdocflags: String::new(), + triple: get_host_triple(), + runner: vec![], + } + } + + pub(crate) fn with_triple(triple: String) -> Compiler { + Compiler { + cargo: get_cargo_path(), + rustc: get_rustc_path(), + rustdoc: get_rustdoc_path(), + rustflags: String::new(), + rustdocflags: String::new(), + triple, + runner: vec![], + } + } +} + +pub(crate) struct CargoProject { + source: &'static RelPath, + target: &'static str, +} + +impl CargoProject { + pub(crate) const fn new(path: &'static RelPath, target: &'static str) -> CargoProject { + CargoProject { source: path, target } + } + + pub(crate) fn source_dir(&self, dirs: &Dirs) -> PathBuf { + self.source.to_path(dirs) + } + + pub(crate) fn manifest_path(&self, dirs: &Dirs) -> PathBuf { + self.source_dir(dirs).join("Cargo.toml") + } + + pub(crate) fn target_dir(&self, dirs: &Dirs) -> PathBuf { + RelPath::BUILD.join(self.target).to_path(dirs) + } - if let Some(triple) = triple { - cmd.arg("--target").arg(triple); + fn base_cmd(&self, command: &str, cargo: &Path, dirs: &Dirs) -> Command { + let mut cmd = Command::new(cargo); + + cmd.arg(command) + .arg("--manifest-path") + .arg(self.manifest_path(dirs)) + .arg("--target-dir") + .arg(self.target_dir(dirs)); + + cmd + } + + fn build_cmd(&self, command: &str, compiler: &Compiler, dirs: &Dirs) -> Command { + let mut cmd = self.base_cmd(command, &compiler.cargo, dirs); + + cmd.arg("--target").arg(&compiler.triple); + + cmd.env("RUSTC", &compiler.rustc); + cmd.env("RUSTDOC", &compiler.rustdoc); + cmd.env("RUSTFLAGS", &compiler.rustflags); + cmd.env("RUSTDOCFLAGS", &compiler.rustdocflags); + if !compiler.runner.is_empty() { + cmd.env( + format!("CARGO_TARGET_{}_RUNNER", compiler.triple.to_uppercase().replace('-', "_")), + compiler.runner.join(" "), + ); + } + + cmd } - cmd + #[must_use] + pub(crate) fn fetch(&self, cargo: impl AsRef, dirs: &Dirs) -> Command { + let mut cmd = Command::new(cargo.as_ref()); + + cmd.arg("fetch").arg("--manifest-path").arg(self.manifest_path(dirs)); + + cmd + } + + #[must_use] + pub(crate) fn clean(&self, cargo: &Path, dirs: &Dirs) -> Command { + self.base_cmd("clean", cargo, dirs) + } + + #[must_use] + pub(crate) fn build(&self, compiler: &Compiler, dirs: &Dirs) -> Command { + self.build_cmd("build", compiler, dirs) + } + + #[must_use] + pub(crate) fn test(&self, compiler: &Compiler, dirs: &Dirs) -> Command { + self.build_cmd("test", compiler, dirs) + } + + #[must_use] + pub(crate) fn run(&self, compiler: &Compiler, dirs: &Dirs) -> Command { + self.build_cmd("run", compiler, dirs) + } } +#[must_use] pub(crate) fn hyperfine_command( warmup: u64, runs: u64, - prepare: Option, - a: Command, - b: Command, + prepare: Option<&str>, + a: &str, + b: &str, ) -> Command { let mut bench = Command::new("hyperfine"); @@ -42,10 +145,10 @@ pub(crate) fn hyperfine_command( } if let Some(prepare) = prepare { - bench.arg("--prepare").arg(format!("{:?}", prepare)); + bench.arg("--prepare").arg(prepare); } - bench.arg(format!("{:?}", a)).arg(format!("{:?}", b)); + bench.arg(a).arg(b); bench } diff --git a/clean_all.sh b/clean_all.sh index fedab2433aa05..1760e5836ecce 100755 --- a/clean_all.sh +++ b/clean_all.sh @@ -2,7 +2,7 @@ set -e rm -rf build_sysroot/{sysroot_src/,target/,compiler-builtins/,rustc_version} -rm -rf target/ build/ perf.data{,.old} y.bin +rm -rf target/ build/ dist/ perf.data{,.old} y.bin rm -rf download/ # Kept for now in case someone updates their checkout of cg_clif before running clean_all.sh diff --git a/config.txt b/config.txt index 0d539191b12f9..258b67e931476 100644 --- a/config.txt +++ b/config.txt @@ -40,6 +40,7 @@ aot.subslice-patterns-const-eval aot.track-caller-attribute aot.float-minmax-pass aot.mod_bench +aot.issue-72793 testsuite.extended_sysroot test.rust-random/rand diff --git a/docs/usage.md b/docs/usage.md index 33f146e7ba27a..4c2b0fa170498 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -9,7 +9,7 @@ Assuming `$cg_clif_dir` is the directory you cloned this repo into and you follo In the directory with your project (where you can do the usual `cargo build`), run: ```bash -$ $cg_clif_dir/build/cargo-clif build +$ $cg_clif_dir/dist/cargo-clif build ``` This will build your project with rustc_codegen_cranelift instead of the usual LLVM backend. @@ -19,7 +19,7 @@ This will build your project with rustc_codegen_cranelift instead of the usual L > You should prefer using the Cargo method. ```bash -$ $cg_clif_dir/build/rustc-clif my_crate.rs +$ $cg_clif_dir/dist/rustc-clif my_crate.rs ``` ## Jit mode @@ -32,20 +32,20 @@ In jit mode cg_clif will immediately execute your code without creating an execu > The jit mode will probably need cargo integration to make this possible. ```bash -$ $cg_clif_dir/build/cargo-clif jit +$ $cg_clif_dir/dist/cargo-clif jit ``` or ```bash -$ $cg_clif_dir/build/rustc-clif -Zunstable-features -Cllvm-args=mode=jit -Cprefer-dynamic my_crate.rs +$ $cg_clif_dir/dist/rustc-clif -Zunstable-features -Cllvm-args=mode=jit -Cprefer-dynamic my_crate.rs ``` There is also an experimental lazy jit mode. In this mode functions are only compiled once they are first called. ```bash -$ $cg_clif_dir/build/cargo-clif lazy-jit +$ $cg_clif_dir/dist/cargo-clif lazy-jit ``` ## Shell @@ -54,7 +54,7 @@ These are a few functions that allow you to easily run rust code from the shell ```bash function jit_naked() { - echo "$@" | $cg_clif_dir/build/rustc-clif - -Zunstable-features -Cllvm-args=mode=jit -Cprefer-dynamic + echo "$@" | $cg_clif_dir/dist/rustc-clif - -Zunstable-features -Cllvm-args=mode=jit -Cprefer-dynamic } function jit() { diff --git a/example/issue-72793.rs b/example/issue-72793.rs new file mode 100644 index 0000000000000..b1bb9b8e1e730 --- /dev/null +++ b/example/issue-72793.rs @@ -0,0 +1,24 @@ +// Adapted from rustc ui test suite (ui/type-alias-impl-trait/issue-72793.rs) + +#![feature(type_alias_impl_trait)] + +trait T { type Item; } + +type Alias<'a> = impl T; + +struct S; +impl<'a> T for &'a S { + type Item = &'a (); +} + +fn filter_positive<'a>() -> Alias<'a> { + &S +} + +fn with_positive(fun: impl Fn(Alias<'_>)) { + fun(filter_positive()); +} + +fn main() { + with_positive(|_| ()); +} diff --git a/example/mini_core.rs b/example/mini_core.rs index 7f85b52f083a7..1f9db1eb2a97a 100644 --- a/example/mini_core.rs +++ b/example/mini_core.rs @@ -19,6 +19,9 @@ pub trait Sized {} #[lang = "destruct"] pub trait Destruct {} +#[lang = "tuple_trait"] +pub trait Tuple {} + #[lang = "unsize"] pub trait Unsize {} @@ -443,7 +446,7 @@ pub struct PhantomData; #[lang = "fn_once"] #[rustc_paren_sugar] -pub trait FnOnce { +pub trait FnOnce { #[lang = "fn_once_output"] type Output; @@ -452,7 +455,7 @@ pub trait FnOnce { #[lang = "fn_mut"] #[rustc_paren_sugar] -pub trait FnMut: FnOnce { +pub trait FnMut: FnOnce { extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output; } diff --git a/example/mini_core_hello_world.rs b/example/mini_core_hello_world.rs index 215d3556a17ca..c00f8a2e0cdad 100644 --- a/example/mini_core_hello_world.rs +++ b/example/mini_core_hello_world.rs @@ -171,8 +171,6 @@ fn main() { assert_eq!(slice_ptr as usize % 4, 0); - //return; - unsafe { printf("Hello %s\n\0" as *const str as *const i8, "printf\0" as *const str as *const i8); diff --git a/example/std_example.rs b/example/std_example.rs index ad108c34992e3..8481d9c39a3cf 100644 --- a/example/std_example.rs +++ b/example/std_example.rs @@ -164,6 +164,8 @@ unsafe fn test_simd() { let cmp_eq = _mm_cmpeq_epi8(y, y); let cmp_lt = _mm_cmplt_epi8(y, y); + let (zero0, zero1) = std::mem::transmute::<_, (u64, u64)>(x); + assert_eq!((zero0, zero1), (0, 0)); assert_eq!(std::mem::transmute::<_, [u16; 8]>(or), [7, 7, 7, 7, 7, 7, 7, 7]); assert_eq!(std::mem::transmute::<_, [u16; 8]>(cmp_eq), [0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff]); assert_eq!(std::mem::transmute::<_, [u16; 8]>(cmp_lt), [0, 0, 0, 0, 0, 0, 0, 0]); diff --git a/rust-toolchain b/rust-toolchain index c0a2e7a7883fc..d8f28dbcc15c8 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-10-23" +channel = "nightly-2022-12-13" components = ["rust-src", "rustc-dev", "llvm-tools-preview"] diff --git a/rustfmt.toml b/rustfmt.toml index 2bd8f7d1bc15d..ebeca8662a519 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,3 +1,5 @@ +ignore = ["y.rs"] + # Matches rustfmt.toml of rustc version = "Two" use_small_heuristics = "Max" diff --git a/scripts/filter_profile.rs b/scripts/filter_profile.rs index e6f60d1c0cb23..f782671fe36f9 100755 --- a/scripts/filter_profile.rs +++ b/scripts/filter_profile.rs @@ -2,7 +2,7 @@ #![forbid(unsafe_code)]/* This line is ignored by bash # This block is ignored by rustc pushd $(dirname "$0")/../ -RUSTC="$(pwd)/build/rustc-clif" +RUSTC="$(pwd)/dist/rustc-clif" popd PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0 #*/ diff --git a/scripts/rustdoc-clif.rs b/scripts/rustdoc-clif.rs new file mode 100644 index 0000000000000..a19d72acfa83e --- /dev/null +++ b/scripts/rustdoc-clif.rs @@ -0,0 +1,36 @@ +use std::env; +use std::ffi::OsString; +#[cfg(unix)] +use std::os::unix::process::CommandExt; +use std::path::PathBuf; +use std::process::Command; + +fn main() { + let sysroot = PathBuf::from(env::current_exe().unwrap().parent().unwrap()); + + let cg_clif_dylib_path = sysroot.join(if cfg!(windows) { "bin" } else { "lib" }).join( + env::consts::DLL_PREFIX.to_string() + "rustc_codegen_cranelift" + env::consts::DLL_SUFFIX, + ); + + let mut args = std::env::args_os().skip(1).collect::>(); + args.push(OsString::from("-Cpanic=abort")); + args.push(OsString::from("-Zpanic-abort-tests")); + let mut codegen_backend_arg = OsString::from("-Zcodegen-backend="); + codegen_backend_arg.push(cg_clif_dylib_path); + args.push(codegen_backend_arg); + if !args.contains(&OsString::from("--sysroot")) { + args.push(OsString::from("--sysroot")); + args.push(OsString::from(sysroot.to_str().unwrap())); + } + + // Ensure that the right toolchain is used + env::set_var("RUSTUP_TOOLCHAIN", env!("RUSTUP_TOOLCHAIN")); + + #[cfg(unix)] + Command::new("rustdoc").args(args).exec(); + + #[cfg(not(unix))] + std::process::exit( + Command::new("rustdoc").args(args).spawn().unwrap().wait().unwrap().code().unwrap_or(1), + ); +} diff --git a/scripts/setup_rust_fork.sh b/scripts/setup_rust_fork.sh index d6a37789599fe..6c64b7de7daa1 100644 --- a/scripts/setup_rust_fork.sh +++ b/scripts/setup_rust_fork.sh @@ -27,24 +27,6 @@ index d95b5b7f17f..00b6f0e3635 100644 [dev-dependencies] rand = "0.7" rand_xorshift = "0.2" -diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs -index 8431aa7b818..a3ff7e68ce5 100644 ---- a/src/tools/compiletest/src/runtest.rs -+++ b/src/tools/compiletest/src/runtest.rs -@@ -3489,12 +3489,7 @@ fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> S - let compiler_src_dir = base_dir.join("compiler"); - normalize_path(&compiler_src_dir, "$(echo '$COMPILER_DIR')"); - -- if let Some(virtual_rust_source_base_dir) = -- option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR").map(PathBuf::from) -- { -- normalize_path(&virtual_rust_source_base_dir.join("library"), "$(echo '$SRC_DIR')"); -- normalize_path(&virtual_rust_source_base_dir.join("compiler"), "$(echo '$COMPILER_DIR')"); -- } -+ normalize_path(&Path::new("$(cd ../build_sysroot/sysroot_src/library; pwd)"), "$(echo '$SRC_DIR')"); - - // Paths into the build directory - let test_build_dir = &self.config.build_base; EOF cat > config.toml < CallCon pub(crate) fn get_function_sig<'tcx>( tcx: TyCtxt<'tcx>, - triple: &target_lexicon::Triple, + default_call_conv: CallConv, inst: Instance<'tcx>, ) -> Signature { assert!(!inst.substs.needs_infer()); clif_sig_from_fn_abi( tcx, - CallConv::triple_default(triple), + default_call_conv, &RevealAllLayoutCx(tcx).fn_abi_of_instance(inst, ty::List::empty()), ) } @@ -74,7 +74,7 @@ pub(crate) fn import_function<'tcx>( inst: Instance<'tcx>, ) -> FuncId { let name = tcx.symbol_name(inst).name; - let sig = get_function_sig(tcx, module.isa().triple(), inst); + let sig = get_function_sig(tcx, module.target_config().default_call_conv, inst); match module.declare_function(name, Linkage::Import, &sig) { Ok(func_id) => func_id, Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!( @@ -341,14 +341,13 @@ pub(crate) fn codegen_terminator_call<'tcx>( destination: Place<'tcx>, target: Option, ) { - let fn_ty = fx.monomorphize(func.ty(fx.mir, fx.tcx)); - let fn_sig = - fx.tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), fn_ty.fn_sig(fx.tcx)); + let func = codegen_operand(fx, func); + let fn_sig = func.layout().ty.fn_sig(fx.tcx); let ret_place = codegen_place(fx, destination); // Handle special calls like intrinsics and empty drop glue. - let instance = if let ty::FnDef(def_id, substs) = *fn_ty.kind() { + let instance = if let ty::FnDef(def_id, substs) = *func.layout().ty.kind() { let instance = ty::Instance::expect_resolve(fx.tcx, ty::ParamEnv::reveal_all(), def_id, substs) .polymorphize(fx.tcx); @@ -390,17 +389,17 @@ pub(crate) fn codegen_terminator_call<'tcx>( None }; - let extra_args = &args[fn_sig.inputs().len()..]; + let extra_args = &args[fn_sig.inputs().skip_binder().len()..]; let extra_args = fx .tcx .mk_type_list(extra_args.iter().map(|op_arg| fx.monomorphize(op_arg.ty(fx.mir, fx.tcx)))); let fn_abi = if let Some(instance) = instance { RevealAllLayoutCx(fx.tcx).fn_abi_of_instance(instance, extra_args) } else { - RevealAllLayoutCx(fx.tcx).fn_abi_of_fn_ptr(fn_ty.fn_sig(fx.tcx), extra_args) + RevealAllLayoutCx(fx.tcx).fn_abi_of_fn_ptr(fn_sig, extra_args) }; - let is_cold = if fn_sig.abi == Abi::RustCold { + let is_cold = if fn_sig.abi() == Abi::RustCold { true } else { instance @@ -417,7 +416,7 @@ pub(crate) fn codegen_terminator_call<'tcx>( } // Unpack arguments tuple for closures - let mut args = if fn_sig.abi == Abi::RustCall { + let mut args = if fn_sig.abi() == Abi::RustCall { assert_eq!(args.len(), 2, "rust-call abi requires two arguments"); let self_arg = codegen_call_argument_operand(fx, &args[0]); let pack_arg = codegen_call_argument_operand(fx, &args[1]); @@ -485,7 +484,7 @@ pub(crate) fn codegen_terminator_call<'tcx>( fx.add_comment(nop_inst, "indirect call"); } - let func = codegen_operand(fx, func).load_scalar(fx); + let func = func.load_scalar(fx); let sig = clif_sig_from_fn_abi(fx.tcx, fx.target_config.default_call_conv, &fn_abi); let sig = fx.bcx.import_signature(sig); @@ -516,11 +515,11 @@ pub(crate) fn codegen_terminator_call<'tcx>( }; // FIXME find a cleaner way to support varargs - if fn_sig.c_variadic { - if !matches!(fn_sig.abi, Abi::C { .. }) { + if fn_sig.c_variadic() { + if !matches!(fn_sig.abi(), Abi::C { .. }) { fx.tcx.sess.span_fatal( source_info.span, - &format!("Variadic call for non-C abi {:?}", fn_sig.abi), + &format!("Variadic call for non-C abi {:?}", fn_sig.abi()), ); } let sig_ref = fx.bcx.func.dfg.call_signature(call_inst).unwrap(); diff --git a/src/allocator.rs b/src/allocator.rs index 12bb00d346db4..8508227179ac6 100644 --- a/src/allocator.rs +++ b/src/allocator.rs @@ -66,7 +66,7 @@ fn codegen_inner( }; let sig = Signature { - call_conv: CallConv::triple_default(module.isa().triple()), + call_conv: module.target_config().default_call_conv, params: arg_tys.iter().cloned().map(AbiParam::new).collect(), returns: output.into_iter().map(AbiParam::new).collect(), }; @@ -104,7 +104,7 @@ fn codegen_inner( } let sig = Signature { - call_conv: CallConv::triple_default(module.isa().triple()), + call_conv: module.target_config().default_call_conv, params: vec![AbiParam::new(usize_ty), AbiParam::new(usize_ty)], returns: vec![], }; diff --git a/src/base.rs b/src/base.rs index 06813d7ec953f..89d955e8bf2e1 100644 --- a/src/base.rs +++ b/src/base.rs @@ -59,7 +59,7 @@ pub(crate) fn codegen_fn<'tcx>( // Declare function let symbol_name = tcx.symbol_name(instance).name.to_string(); - let sig = get_function_sig(tcx, module.isa().triple(), instance); + let sig = get_function_sig(tcx, module.target_config().default_call_conv, instance); let func_id = module.declare_function(&symbol_name, Linkage::Local, &sig).unwrap(); // Make the FunctionBuilder @@ -390,11 +390,9 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) { _ => unreachable!("{:?}", targets), }; - let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr); let (discr, is_inverted) = crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr); let test_zero = if is_inverted { !test_zero } else { test_zero }; - let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr); if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken( &fx.bcx, discr, test_zero, ) { @@ -571,7 +569,7 @@ fn codegen_stmt<'tcx>( UnOp::Not => match layout.ty.kind() { ty::Bool => { let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0); - CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout) + CValue::by_val(res, layout) } ty::Uint(_) | ty::Int(_) => { CValue::by_val(fx.bcx.ins().bnot(val), layout) @@ -579,12 +577,6 @@ fn codegen_stmt<'tcx>( _ => unreachable!("un op Not for {:?}", layout.ty), }, UnOp::Neg => match layout.ty.kind() { - ty::Int(IntTy::I128) => { - // FIXME remove this case once ineg.i128 works - let zero = - CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size)); - crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand) - } ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout), ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout), _ => unreachable!("un op Neg for {:?}", layout.ty), diff --git a/src/cast.rs b/src/cast.rs index bad5d1f08a9cf..5091c5a9fedac 100644 --- a/src/cast.rs +++ b/src/cast.rs @@ -149,7 +149,7 @@ pub(crate) fn clif_int_or_float_cast( } let is_not_nan = fx.bcx.ins().fcmp(FloatCC::Equal, from, from); - let zero = fx.bcx.ins().iconst(to_ty, 0); + let zero = type_zero_value(&mut fx.bcx, to_ty); fx.bcx.ins().select(is_not_nan, val, zero) } else if from_ty.is_float() && to_ty.is_float() { // float -> float diff --git a/src/common.rs b/src/common.rs index 589594465783e..2dcd42fbd8f43 100644 --- a/src/common.rs +++ b/src/common.rs @@ -162,11 +162,20 @@ pub(crate) fn codegen_icmp_imm( } } } else { - let rhs = i64::try_from(rhs).expect("codegen_icmp_imm rhs out of range for <128bit int"); + let rhs = rhs as i64; // Truncates on purpose in case rhs is actually an unsigned value fx.bcx.ins().icmp_imm(intcc, lhs, rhs) } } +pub(crate) fn type_zero_value(bcx: &mut FunctionBuilder<'_>, ty: Type) -> Value { + if ty == types::I128 { + let zero = bcx.ins().iconst(types::I64, 0); + bcx.ins().iconcat(zero, zero) + } else { + bcx.ins().iconst(ty, 0) + } +} + pub(crate) fn type_min_max_value( bcx: &mut FunctionBuilder<'_>, ty: Type, diff --git a/src/constant.rs b/src/constant.rs index a6bde88408497..dee6fb5b5130d 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -28,9 +28,7 @@ impl ConstantCx { } pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) { - //println!("todo {:?}", self.todo); define_all_allocs(tcx, module, &mut self); - //println!("done {:?}", self.done); self.done.clear(); } } @@ -268,16 +266,7 @@ fn data_id_for_static( def_id: DefId, definition: bool, ) -> DataId { - let rlinkage = tcx.codegen_fn_attrs(def_id).linkage; - let linkage = if definition { - crate::linkage::get_static_linkage(tcx, def_id) - } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak) - || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny) - { - Linkage::Preemptible - } else { - Linkage::Import - }; + let attrs = tcx.codegen_fn_attrs(def_id); let instance = Instance::mono(tcx, def_id).polymorphize(tcx); let symbol_name = tcx.symbol_name(instance).name; @@ -289,22 +278,30 @@ fn data_id_for_static( }; let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes(); - let attrs = tcx.codegen_fn_attrs(def_id); + if let Some(import_linkage) = attrs.import_linkage { + assert!(!definition); - let data_id = match module.declare_data( - &*symbol_name, - linkage, - is_mutable, - attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL), - ) { - Ok(data_id) => data_id, - Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!( - "attempt to declare `{symbol_name}` as static, but it was already declared as function" - )), - Err(err) => Err::<_, _>(err).unwrap(), - }; + let linkage = if import_linkage == rustc_middle::mir::mono::Linkage::ExternalWeak + || import_linkage == rustc_middle::mir::mono::Linkage::WeakAny + { + Linkage::Preemptible + } else { + Linkage::Import + }; + + let data_id = match module.declare_data( + &*symbol_name, + linkage, + is_mutable, + attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL), + ) { + Ok(data_id) => data_id, + Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!( + "attempt to declare `{symbol_name}` as static, but it was already declared as function" + )), + Err(err) => Err::<_, _>(err).unwrap(), + }; - if rlinkage.is_some() { // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141 // Declare an internal global `extern_with_linkage_foo` which // is initialized with the address of `foo`. If `foo` is @@ -326,10 +323,34 @@ fn data_id_for_static( Err(ModuleError::DuplicateDefinition(_)) => {} res => res.unwrap(), } - ref_data_id - } else { - data_id + + return ref_data_id; } + + let linkage = if definition { + crate::linkage::get_static_linkage(tcx, def_id) + } else if attrs.linkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak) + || attrs.linkage == Some(rustc_middle::mir::mono::Linkage::WeakAny) + { + Linkage::Preemptible + } else { + Linkage::Import + }; + + let data_id = match module.declare_data( + &*symbol_name, + linkage, + is_mutable, + attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL), + ) { + Ok(data_id) => data_id, + Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!( + "attempt to declare `{symbol_name}` as static, but it was already declared as function" + )), + Err(err) => Err::<_, _>(err).unwrap(), + }; + + data_id } fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) { @@ -348,8 +369,6 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant (data_id, alloc, None) } TodoItem::Static(def_id) => { - //println!("static {:?}", def_id); - let section_name = tcx.codegen_fn_attrs(def_id).link_section; let alloc = tcx.eval_static_initializer(def_id).unwrap(); @@ -359,7 +378,6 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant } }; - //("data_id {}", data_id); if cx.done.contains(&data_id) { continue; } diff --git a/src/debuginfo/unwind.rs b/src/debuginfo/unwind.rs index d26392c4913b5..493359c743f11 100644 --- a/src/debuginfo/unwind.rs +++ b/src/debuginfo/unwind.rs @@ -39,7 +39,9 @@ impl UnwindContext { } pub(crate) fn add_function(&mut self, func_id: FuncId, context: &Context, isa: &dyn TargetIsa) { - let unwind_info = if let Some(unwind_info) = context.create_unwind_info(isa).unwrap() { + let unwind_info = if let Some(unwind_info) = + context.compiled_code().unwrap().create_unwind_info(isa).unwrap() + { unwind_info } else { return; diff --git a/src/discriminant.rs b/src/discriminant.rs index 97b395bcd0518..3cbf313adf0df 100644 --- a/src/discriminant.rs +++ b/src/discriminant.rs @@ -1,6 +1,7 @@ //! Handling of enum discriminants //! -//! Adapted from +//! Adapted from +//! () use rustc_target::abi::{Int, TagEncoding, Variants}; @@ -47,13 +48,19 @@ pub(crate) fn codegen_set_discriminant<'tcx>( } => { if variant_index != untagged_variant { let niche = place.place_field(fx, mir::Field::new(tag_field)); + let niche_type = fx.clif_type(niche.layout().ty).unwrap(); let niche_value = variant_index.as_u32() - niche_variants.start().as_u32(); - let niche_value = ty::ScalarInt::try_from_uint( - u128::from(niche_value).wrapping_add(niche_start), - niche.layout().size, - ) - .unwrap(); - let niche_llval = CValue::const_val(fx, niche.layout(), niche_value); + let niche_value = (niche_value as u128).wrapping_add(niche_start); + let niche_value = match niche_type { + types::I128 => { + let lsb = fx.bcx.ins().iconst(types::I64, niche_value as u64 as i64); + let msb = + fx.bcx.ins().iconst(types::I64, (niche_value >> 64) as u64 as i64); + fx.bcx.ins().iconcat(lsb, msb) + } + ty => fx.bcx.ins().iconst(ty, niche_value as i64), + }; + let niche_llval = CValue::by_val(niche_value, niche.layout()); niche.write_cvalue(fx, niche_llval); } } @@ -96,6 +103,7 @@ pub(crate) fn codegen_get_discriminant<'tcx>( } }; + let cast_to_size = dest_layout.layout.size(); let cast_to = fx.clif_type(dest_layout.ty).unwrap(); // Read the tag/niche-encoded discriminant from memory. @@ -114,21 +122,128 @@ pub(crate) fn codegen_get_discriminant<'tcx>( dest.write_cvalue(fx, res); } TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => { - // Rebase from niche values to discriminants, and check - // whether the result is in range for the niche variants. - - // We first compute the "relative discriminant" (wrt `niche_variants`), - // that is, if `n = niche_variants.end() - niche_variants.start()`, - // we remap `niche_start..=niche_start + n` (which may wrap around) - // to (non-wrap-around) `0..=n`, to be able to check whether the - // discriminant corresponds to a niche variant with one comparison. - // We also can't go directly to the (variant index) discriminant - // and check that it is in the range `niche_variants`, because - // that might not fit in the same type, on top of needing an extra - // comparison (see also the comment on `let niche_discr`). - let relative_discr = if niche_start == 0 { - tag + let tag_size = tag_scalar.size(fx); + let max_unsigned = tag_size.unsigned_int_max(); + let max_signed = tag_size.signed_int_max() as u128; + let min_signed = max_signed + 1; + let relative_max = niche_variants.end().as_u32() - niche_variants.start().as_u32(); + let niche_end = niche_start.wrapping_add(relative_max as u128) & max_unsigned; + let range = tag_scalar.valid_range(fx); + + let sle = |lhs: u128, rhs: u128| -> bool { + // Signed and unsigned comparisons give the same results, + // except that in signed comparisons an integer with the + // sign bit set is less than one with the sign bit clear. + // Toggle the sign bit to do a signed comparison. + (lhs ^ min_signed) <= (rhs ^ min_signed) + }; + + // We have a subrange `niche_start..=niche_end` inside `range`. + // If the value of the tag is inside this subrange, it's a + // "niche value", an increment of the discriminant. Otherwise it + // indicates the untagged variant. + // A general algorithm to extract the discriminant from the tag + // is: + // relative_tag = tag - niche_start + // is_niche = relative_tag <= (ule) relative_max + // discr = if is_niche { + // cast(relative_tag) + niche_variants.start() + // } else { + // untagged_variant + // } + // However, we will likely be able to emit simpler code. + + // Find the least and greatest values in `range`, considered + // both as signed and unsigned. + let (low_unsigned, high_unsigned) = + if range.start <= range.end { (range.start, range.end) } else { (0, max_unsigned) }; + let (low_signed, high_signed) = if sle(range.start, range.end) { + (range.start, range.end) } else { + (min_signed, max_signed) + }; + + let niches_ule = niche_start <= niche_end; + let niches_sle = sle(niche_start, niche_end); + let cast_smaller = cast_to_size <= tag_size; + + // In the algorithm above, we can change + // cast(relative_tag) + niche_variants.start() + // into + // cast(tag + (niche_variants.start() - niche_start)) + // if either the casted type is no larger than the original + // type, or if the niche values are contiguous (in either the + // signed or unsigned sense). + let can_incr = cast_smaller || niches_ule || niches_sle; + + let data_for_boundary_niche = || -> Option<(IntCC, u128)> { + if !can_incr { + None + } else if niche_start == low_unsigned { + Some((IntCC::UnsignedLessThanOrEqual, niche_end)) + } else if niche_end == high_unsigned { + Some((IntCC::UnsignedGreaterThanOrEqual, niche_start)) + } else if niche_start == low_signed { + Some((IntCC::SignedLessThanOrEqual, niche_end)) + } else if niche_end == high_signed { + Some((IntCC::SignedGreaterThanOrEqual, niche_start)) + } else { + None + } + }; + + let (is_niche, tagged_discr, delta) = if relative_max == 0 { + // Best case scenario: only one tagged variant. This will + // likely become just a comparison and a jump. + // The algorithm is: + // is_niche = tag == niche_start + // discr = if is_niche { + // niche_start + // } else { + // untagged_variant + // } + let is_niche = codegen_icmp_imm(fx, IntCC::Equal, tag, niche_start as i128); + let tagged_discr = + fx.bcx.ins().iconst(cast_to, niche_variants.start().as_u32() as i64); + (is_niche, tagged_discr, 0) + } else if let Some((predicate, constant)) = data_for_boundary_niche() { + // The niche values are either the lowest or the highest in + // `range`. We can avoid the first subtraction in the + // algorithm. + // The algorithm is now this: + // is_niche = tag <= niche_end + // discr = if is_niche { + // cast(tag + (niche_variants.start() - niche_start)) + // } else { + // untagged_variant + // } + // (the first line may instead be tag >= niche_start, + // and may be a signed or unsigned comparison) + // The arithmetic must be done before the cast, so we can + // have the correct wrapping behavior. See issue #104519 for + // the consequences of getting this wrong. + let is_niche = codegen_icmp_imm(fx, predicate, tag, constant as i128); + let delta = (niche_variants.start().as_u32() as u128).wrapping_sub(niche_start); + let incr_tag = if delta == 0 { + tag + } else { + let delta = match fx.bcx.func.dfg.value_type(tag) { + types::I128 => { + let lsb = fx.bcx.ins().iconst(types::I64, delta as u64 as i64); + let msb = fx.bcx.ins().iconst(types::I64, (delta >> 64) as u64 as i64); + fx.bcx.ins().iconcat(lsb, msb) + } + ty => fx.bcx.ins().iconst(ty, delta as i64), + }; + fx.bcx.ins().iadd(tag, delta) + }; + + let cast_tag = clif_intcast(fx, incr_tag, cast_to, !niches_ule); + + (is_niche, cast_tag, 0) + } else { + // The special cases don't apply, so we'll have to go with + // the general algorithm. let niche_start = match fx.bcx.func.dfg.value_type(tag) { types::I128 => { let lsb = fx.bcx.ins().iconst(types::I64, niche_start as u64 as i64); @@ -138,40 +253,40 @@ pub(crate) fn codegen_get_discriminant<'tcx>( } ty => fx.bcx.ins().iconst(ty, niche_start as i64), }; - fx.bcx.ins().isub(tag, niche_start) - }; - let relative_max = niche_variants.end().as_u32() - niche_variants.start().as_u32(); - let is_niche = { - codegen_icmp_imm( + let relative_discr = fx.bcx.ins().isub(tag, niche_start); + let cast_tag = clif_intcast(fx, relative_discr, cast_to, false); + let is_niche = crate::common::codegen_icmp_imm( fx, IntCC::UnsignedLessThanOrEqual, relative_discr, i128::from(relative_max), - ) + ); + (is_niche, cast_tag, niche_variants.start().as_u32() as u128) }; - // NOTE(eddyb) this addition needs to be performed on the final - // type, in case the niche itself can't represent all variant - // indices (e.g. `u8` niche with more than `256` variants, - // but enough uninhabited variants so that the remaining variants - // fit in the niche). - // In other words, `niche_variants.end - niche_variants.start` - // is representable in the niche, but `niche_variants.end` - // might not be, in extreme cases. - let niche_discr = { - let relative_discr = if relative_max == 0 { - // HACK(eddyb) since we have only one niche, we know which - // one it is, and we can avoid having a dynamic value here. - fx.bcx.ins().iconst(cast_to, 0) - } else { - clif_intcast(fx, relative_discr, cast_to, false) + let tagged_discr = if delta == 0 { + tagged_discr + } else { + let delta = match cast_to { + types::I128 => { + let lsb = fx.bcx.ins().iconst(types::I64, delta as u64 as i64); + let msb = fx.bcx.ins().iconst(types::I64, (delta >> 64) as u64 as i64); + fx.bcx.ins().iconcat(lsb, msb) + } + ty => fx.bcx.ins().iconst(ty, delta as i64), }; - fx.bcx.ins().iadd_imm(relative_discr, i64::from(niche_variants.start().as_u32())) + fx.bcx.ins().iadd(tagged_discr, delta) }; - let untagged_variant = - fx.bcx.ins().iconst(cast_to, i64::from(untagged_variant.as_u32())); - let discr = fx.bcx.ins().select(is_niche, niche_discr, untagged_variant); + let untagged_variant = if cast_to == types::I128 { + let zero = fx.bcx.ins().iconst(types::I64, 0); + let untagged_variant = + fx.bcx.ins().iconst(types::I64, i64::from(untagged_variant.as_u32())); + fx.bcx.ins().iconcat(untagged_variant, zero) + } else { + fx.bcx.ins().iconst(cast_to, i64::from(untagged_variant.as_u32())) + }; + let discr = fx.bcx.ins().select(is_niche, tagged_discr, untagged_variant); let res = CValue::by_val(discr, dest_layout); dest.write_cvalue(fx, res); } diff --git a/src/driver/jit.rs b/src/driver/jit.rs index 6a430b5215e36..be1b8c9ead3bf 100644 --- a/src/driver/jit.rs +++ b/src/driver/jit.rs @@ -159,7 +159,7 @@ pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! { tcx.sess.abort_if_errors(); - jit_module.finalize_definitions(); + jit_module.finalize_definitions().unwrap(); unsafe { cx.unwind_context.register_jit(&jit_module) }; println!( @@ -245,7 +245,11 @@ fn jit_fn(instance_ptr: *const Instance<'static>, trampoline_ptr: *const u8) -> let backend_config = lazy_jit_state.backend_config.clone(); let name = tcx.symbol_name(instance).name; - let sig = crate::abi::get_function_sig(tcx, jit_module.isa().triple(), instance); + let sig = crate::abi::get_function_sig( + tcx, + jit_module.target_config().default_call_conv, + instance, + ); let func_id = jit_module.declare_function(name, Linkage::Export, &sig).unwrap(); let current_ptr = jit_module.read_got_entry(func_id); @@ -278,7 +282,7 @@ fn jit_fn(instance_ptr: *const Instance<'static>, trampoline_ptr: *const u8) -> }); assert!(cx.global_asm.is_empty()); - jit_module.finalize_definitions(); + jit_module.finalize_definitions().unwrap(); unsafe { cx.unwind_context.register_jit(&jit_module) }; jit_module.get_finalized_function(func_id) }) @@ -344,7 +348,7 @@ fn codegen_shim<'tcx>( let pointer_type = module.target_config().pointer_type(); let name = tcx.symbol_name(inst).name; - let sig = crate::abi::get_function_sig(tcx, module.isa().triple(), inst); + let sig = crate::abi::get_function_sig(tcx, module.target_config().default_call_conv, inst); let func_id = module.declare_function(name, Linkage::Export, &sig).unwrap(); let instance_ptr = Box::into_raw(Box::new(inst)); diff --git a/src/driver/mod.rs b/src/driver/mod.rs index 8f5714ecb4177..6e925cea27707 100644 --- a/src/driver/mod.rs +++ b/src/driver/mod.rs @@ -24,7 +24,8 @@ fn predefine_mono_items<'tcx>( MonoItem::Fn(instance) => { let name = tcx.symbol_name(instance).name; let _inst_guard = crate::PrintOnPanic(|| format!("{:?} {}", instance, name)); - let sig = get_function_sig(tcx, module.isa().triple(), instance); + let sig = + get_function_sig(tcx, module.target_config().default_call_conv, instance); let linkage = crate::linkage::get_clif_linkage( mono_item, linkage, diff --git a/src/intrinsics/llvm.rs b/src/intrinsics/llvm.rs index 783d426c30bcc..f722e52284fe8 100644 --- a/src/intrinsics/llvm.rs +++ b/src/intrinsics/llvm.rs @@ -8,135 +8,37 @@ use rustc_middle::ty::subst::SubstsRef; pub(crate) fn codegen_llvm_intrinsic_call<'tcx>( fx: &mut FunctionCx<'_, '_, 'tcx>, intrinsic: &str, - _substs: SubstsRef<'tcx>, + substs: SubstsRef<'tcx>, args: &[mir::Operand<'tcx>], ret: CPlace<'tcx>, target: Option, ) { - match intrinsic { - "llvm.x86.sse2.pause" | "llvm.aarch64.isb" => { - // Spin loop hint - } + if intrinsic.starts_with("llvm.aarch64") { + return llvm_aarch64::codegen_aarch64_llvm_intrinsic_call( + fx, intrinsic, substs, args, ret, target, + ); + } + if intrinsic.starts_with("llvm.x86") { + return llvm_x86::codegen_x86_llvm_intrinsic_call(fx, intrinsic, substs, args, ret, target); + } - // Used by `_mm_movemask_epi8` and `_mm256_movemask_epi8` - "llvm.x86.sse2.pmovmskb.128" | "llvm.x86.avx2.pmovmskb" | "llvm.x86.sse2.movmsk.pd" => { + match intrinsic { + _ if intrinsic.starts_with("llvm.ctlz.v") => { intrinsic_args!(fx, args => (a); intrinsic); - let (lane_count, lane_ty) = a.layout().ty.simd_size_and_type(fx.tcx); - let lane_ty = fx.clif_type(lane_ty).unwrap(); - assert!(lane_count <= 32); - - let mut res = fx.bcx.ins().iconst(types::I32, 0); - - for lane in (0..lane_count).rev() { - let a_lane = a.value_lane(fx, lane).load_scalar(fx); - - // cast float to int - let a_lane = match lane_ty { - types::F32 => fx.bcx.ins().bitcast(types::I32, a_lane), - types::F64 => fx.bcx.ins().bitcast(types::I64, a_lane), - _ => a_lane, - }; - - // extract sign bit of an int - let a_lane_sign = fx.bcx.ins().ushr_imm(a_lane, i64::from(lane_ty.bits() - 1)); - - // shift sign bit into result - let a_lane_sign = clif_intcast(fx, a_lane_sign, types::I32, false); - res = fx.bcx.ins().ishl_imm(res, 1); - res = fx.bcx.ins().bor(res, a_lane_sign); - } - - let res = CValue::by_val(res, fx.layout_of(fx.tcx.types.i32)); - ret.write_cvalue(fx, res); - } - "llvm.x86.sse2.cmp.ps" | "llvm.x86.sse2.cmp.pd" => { - let (x, y, kind) = match args { - [x, y, kind] => (x, y, kind), - _ => bug!("wrong number of args for intrinsic {intrinsic}"), - }; - let x = codegen_operand(fx, x); - let y = codegen_operand(fx, y); - let kind = crate::constant::mir_operand_get_const_val(fx, kind) - .expect("llvm.x86.sse2.cmp.* kind not const"); - - let flt_cc = match kind - .try_to_bits(Size::from_bytes(1)) - .unwrap_or_else(|| panic!("kind not scalar: {:?}", kind)) - { - 0 => FloatCC::Equal, - 1 => FloatCC::LessThan, - 2 => FloatCC::LessThanOrEqual, - 7 => FloatCC::Ordered, - 3 => FloatCC::Unordered, - 4 => FloatCC::NotEqual, - 5 => FloatCC::UnorderedOrGreaterThanOrEqual, - 6 => FloatCC::UnorderedOrGreaterThan, - kind => unreachable!("kind {:?}", kind), - }; - - simd_pair_for_each_lane(fx, x, y, ret, &|fx, lane_ty, res_lane_ty, x_lane, y_lane| { - let res_lane = match lane_ty.kind() { - ty::Float(_) => fx.bcx.ins().fcmp(flt_cc, x_lane, y_lane), - _ => unreachable!("{:?}", lane_ty), - }; - bool_to_zero_or_max_uint(fx, res_lane_ty, res_lane) + simd_for_each_lane(fx, a, ret, &|fx, _lane_ty, _res_lane_ty, lane| { + fx.bcx.ins().clz(lane) }); } - "llvm.x86.sse2.psrli.d" => { - let (a, imm8) = match args { - [a, imm8] => (a, imm8), - _ => bug!("wrong number of args for intrinsic {intrinsic}"), - }; - let a = codegen_operand(fx, a); - let imm8 = crate::constant::mir_operand_get_const_val(fx, imm8) - .expect("llvm.x86.sse2.psrli.d imm8 not const"); - simd_for_each_lane(fx, a, ret, &|fx, _lane_ty, _res_lane_ty, lane| match imm8 - .try_to_bits(Size::from_bytes(4)) - .unwrap_or_else(|| panic!("imm8 not scalar: {:?}", imm8)) - { - imm8 if imm8 < 32 => fx.bcx.ins().ushr_imm(lane, i64::from(imm8 as u8)), - _ => fx.bcx.ins().iconst(types::I32, 0), - }); - } - "llvm.x86.sse2.pslli.d" => { - let (a, imm8) = match args { - [a, imm8] => (a, imm8), - _ => bug!("wrong number of args for intrinsic {intrinsic}"), - }; - let a = codegen_operand(fx, a); - let imm8 = crate::constant::mir_operand_get_const_val(fx, imm8) - .expect("llvm.x86.sse2.psrli.d imm8 not const"); + _ if intrinsic.starts_with("llvm.ctpop.v") => { + intrinsic_args!(fx, args => (a); intrinsic); - simd_for_each_lane(fx, a, ret, &|fx, _lane_ty, _res_lane_ty, lane| match imm8 - .try_to_bits(Size::from_bytes(4)) - .unwrap_or_else(|| panic!("imm8 not scalar: {:?}", imm8)) - { - imm8 if imm8 < 32 => fx.bcx.ins().ishl_imm(lane, i64::from(imm8 as u8)), - _ => fx.bcx.ins().iconst(types::I32, 0), + simd_for_each_lane(fx, a, ret, &|fx, _lane_ty, _res_lane_ty, lane| { + fx.bcx.ins().popcnt(lane) }); } - "llvm.x86.sse2.storeu.dq" => { - intrinsic_args!(fx, args => (mem_addr, a); intrinsic); - let mem_addr = mem_addr.load_scalar(fx); - - // FIXME correctly handle the unalignment - let dest = CPlace::for_ptr(Pointer::new(mem_addr), a.layout()); - dest.write_cvalue(fx, a); - } - "llvm.x86.addcarry.64" => { - intrinsic_args!(fx, args => (c_in, a, b); intrinsic); - let c_in = c_in.load_scalar(fx); - - llvm_add_sub(fx, BinOp::Add, ret, c_in, a, b); - } - "llvm.x86.subborrow.64" => { - intrinsic_args!(fx, args => (b_in, a, b); intrinsic); - let b_in = b_in.load_scalar(fx); - llvm_add_sub(fx, BinOp::Sub, ret, b_in, a, b); - } _ => { fx.tcx .sess @@ -150,47 +52,3 @@ pub(crate) fn codegen_llvm_intrinsic_call<'tcx>( let ret_block = fx.get_block(dest); fx.bcx.ins().jump(ret_block, &[]); } - -// llvm.x86.avx2.vperm2i128 -// llvm.x86.ssse3.pshuf.b.128 -// llvm.x86.avx2.pshuf.b -// llvm.x86.avx2.psrli.w -// llvm.x86.sse2.psrli.w - -fn llvm_add_sub<'tcx>( - fx: &mut FunctionCx<'_, '_, 'tcx>, - bin_op: BinOp, - ret: CPlace<'tcx>, - cb_in: Value, - a: CValue<'tcx>, - b: CValue<'tcx>, -) { - assert_eq!( - a.layout().ty, - fx.tcx.types.u64, - "llvm.x86.addcarry.64/llvm.x86.subborrow.64 second operand must be u64" - ); - assert_eq!( - b.layout().ty, - fx.tcx.types.u64, - "llvm.x86.addcarry.64/llvm.x86.subborrow.64 third operand must be u64" - ); - - // c + carry -> c + first intermediate carry or borrow respectively - let int0 = crate::num::codegen_checked_int_binop(fx, bin_op, a, b); - let c = int0.value_field(fx, mir::Field::new(0)); - let cb0 = int0.value_field(fx, mir::Field::new(1)).load_scalar(fx); - - // c + carry -> c + second intermediate carry or borrow respectively - let cb_in_as_u64 = fx.bcx.ins().uextend(types::I64, cb_in); - let cb_in_as_u64 = CValue::by_val(cb_in_as_u64, fx.layout_of(fx.tcx.types.u64)); - let int1 = crate::num::codegen_checked_int_binop(fx, bin_op, c, cb_in_as_u64); - let (c, cb1) = int1.load_scalar_pair(fx); - - // carry0 | carry1 -> carry or borrow respectively - let cb_out = fx.bcx.ins().bor(cb0, cb1); - - let layout = fx.layout_of(fx.tcx.mk_tup([fx.tcx.types.u8, fx.tcx.types.u64].iter())); - let val = CValue::by_val_pair(cb_out, c, layout); - ret.write_cvalue(fx, val); -} diff --git a/src/intrinsics/llvm_aarch64.rs b/src/intrinsics/llvm_aarch64.rs new file mode 100644 index 0000000000000..b431158d2690f --- /dev/null +++ b/src/intrinsics/llvm_aarch64.rs @@ -0,0 +1,222 @@ +//! Emulate AArch64 LLVM intrinsics + +use crate::intrinsics::*; +use crate::prelude::*; + +use rustc_middle::ty::subst::SubstsRef; + +pub(crate) fn codegen_aarch64_llvm_intrinsic_call<'tcx>( + fx: &mut FunctionCx<'_, '_, 'tcx>, + intrinsic: &str, + _substs: SubstsRef<'tcx>, + args: &[mir::Operand<'tcx>], + ret: CPlace<'tcx>, + target: Option, +) { + // llvm.aarch64.neon.sqshl.v*i* + + match intrinsic { + "llvm.aarch64.isb" => { + fx.bcx.ins().fence(); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.abs.v") => { + intrinsic_args!(fx, args => (a); intrinsic); + + simd_for_each_lane(fx, a, ret, &|fx, _lane_ty, _res_lane_ty, lane| { + fx.bcx.ins().iabs(lane) + }); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.cls.v") => { + intrinsic_args!(fx, args => (a); intrinsic); + + simd_for_each_lane(fx, a, ret, &|fx, _lane_ty, _res_lane_ty, lane| { + fx.bcx.ins().cls(lane) + }); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.rbit.v") => { + intrinsic_args!(fx, args => (a); intrinsic); + + simd_for_each_lane(fx, a, ret, &|fx, _lane_ty, _res_lane_ty, lane| { + fx.bcx.ins().bitrev(lane) + }); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.sqadd.v") => { + intrinsic_args!(fx, args => (x, y); intrinsic); + + simd_pair_for_each_lane_typed(fx, x, y, ret, &|fx, x_lane, y_lane| { + crate::num::codegen_saturating_int_binop(fx, BinOp::Add, x_lane, y_lane) + }); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.sqsub.v") => { + intrinsic_args!(fx, args => (x, y); intrinsic); + + simd_pair_for_each_lane_typed(fx, x, y, ret, &|fx, x_lane, y_lane| { + crate::num::codegen_saturating_int_binop(fx, BinOp::Sub, x_lane, y_lane) + }); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.smax.v") => { + intrinsic_args!(fx, args => (x, y); intrinsic); + + simd_pair_for_each_lane( + fx, + x, + y, + ret, + &|fx, _lane_ty, _res_lane_ty, x_lane, y_lane| { + let gt = fx.bcx.ins().icmp(IntCC::SignedGreaterThan, x_lane, y_lane); + fx.bcx.ins().select(gt, x_lane, y_lane) + }, + ); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.umax.v") => { + intrinsic_args!(fx, args => (x, y); intrinsic); + + simd_pair_for_each_lane( + fx, + x, + y, + ret, + &|fx, _lane_ty, _res_lane_ty, x_lane, y_lane| { + let gt = fx.bcx.ins().icmp(IntCC::UnsignedGreaterThan, x_lane, y_lane); + fx.bcx.ins().select(gt, x_lane, y_lane) + }, + ); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.smaxv.i") => { + intrinsic_args!(fx, args => (v); intrinsic); + + simd_reduce(fx, v, None, ret, &|fx, _ty, a, b| { + let gt = fx.bcx.ins().icmp(IntCC::SignedGreaterThan, a, b); + fx.bcx.ins().select(gt, a, b) + }); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.umaxv.i") => { + intrinsic_args!(fx, args => (v); intrinsic); + + simd_reduce(fx, v, None, ret, &|fx, _ty, a, b| { + let gt = fx.bcx.ins().icmp(IntCC::UnsignedGreaterThan, a, b); + fx.bcx.ins().select(gt, a, b) + }); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.smin.v") => { + intrinsic_args!(fx, args => (x, y); intrinsic); + + simd_pair_for_each_lane( + fx, + x, + y, + ret, + &|fx, _lane_ty, _res_lane_ty, x_lane, y_lane| { + let gt = fx.bcx.ins().icmp(IntCC::SignedLessThan, x_lane, y_lane); + fx.bcx.ins().select(gt, x_lane, y_lane) + }, + ); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.umin.v") => { + intrinsic_args!(fx, args => (x, y); intrinsic); + + simd_pair_for_each_lane( + fx, + x, + y, + ret, + &|fx, _lane_ty, _res_lane_ty, x_lane, y_lane| { + let gt = fx.bcx.ins().icmp(IntCC::UnsignedLessThan, x_lane, y_lane); + fx.bcx.ins().select(gt, x_lane, y_lane) + }, + ); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.sminv.i") => { + intrinsic_args!(fx, args => (v); intrinsic); + + simd_reduce(fx, v, None, ret, &|fx, _ty, a, b| { + let gt = fx.bcx.ins().icmp(IntCC::SignedLessThan, a, b); + fx.bcx.ins().select(gt, a, b) + }); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.uminv.i") => { + intrinsic_args!(fx, args => (v); intrinsic); + + simd_reduce(fx, v, None, ret, &|fx, _ty, a, b| { + let gt = fx.bcx.ins().icmp(IntCC::UnsignedLessThan, a, b); + fx.bcx.ins().select(gt, a, b) + }); + } + + /* + _ if intrinsic.starts_with("llvm.aarch64.neon.sshl.v") + || intrinsic.starts_with("llvm.aarch64.neon.sqshl.v") + // FIXME split this one out once saturating is implemented + || intrinsic.starts_with("llvm.aarch64.neon.sqshlu.v") => + { + intrinsic_args!(fx, args => (a, b); intrinsic); + + simd_pair_for_each_lane(fx, a, b, ret, &|fx, _lane_ty, _res_lane_ty, a, b| { + // FIXME saturate? + fx.bcx.ins().ishl(a, b) + }); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.sqshrn.v") => { + let (a, imm32) = match args { + [a, imm32] => (a, imm32), + _ => bug!("wrong number of args for intrinsic {intrinsic}"), + }; + let a = codegen_operand(fx, a); + let imm32 = crate::constant::mir_operand_get_const_val(fx, imm32) + .expect("llvm.aarch64.neon.sqshrn.v* imm32 not const"); + + simd_for_each_lane(fx, a, ret, &|fx, _lane_ty, _res_lane_ty, lane| match imm32 + .try_to_bits(Size::from_bytes(4)) + .unwrap_or_else(|| panic!("imm32 not scalar: {:?}", imm32)) + { + imm32 if imm32 < 32 => fx.bcx.ins().sshr_imm(lane, i64::from(imm32 as u8)), + _ => fx.bcx.ins().iconst(types::I32, 0), + }); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.sqshrun.v") => { + let (a, imm32) = match args { + [a, imm32] => (a, imm32), + _ => bug!("wrong number of args for intrinsic {intrinsic}"), + }; + let a = codegen_operand(fx, a); + let imm32 = crate::constant::mir_operand_get_const_val(fx, imm32) + .expect("llvm.aarch64.neon.sqshrn.v* imm32 not const"); + + simd_for_each_lane(fx, a, ret, &|fx, _lane_ty, _res_lane_ty, lane| match imm32 + .try_to_bits(Size::from_bytes(4)) + .unwrap_or_else(|| panic!("imm32 not scalar: {:?}", imm32)) + { + imm32 if imm32 < 32 => fx.bcx.ins().ushr_imm(lane, i64::from(imm32 as u8)), + _ => fx.bcx.ins().iconst(types::I32, 0), + }); + } + */ + _ => { + fx.tcx.sess.warn(&format!( + "unsupported AArch64 llvm intrinsic {}; replacing with trap", + intrinsic + )); + crate::trap::trap_unimplemented(fx, intrinsic); + return; + } + } + + let dest = target.expect("all llvm intrinsics used by stdlib should return"); + let ret_block = fx.get_block(dest); + fx.bcx.ins().jump(ret_block, &[]); +} diff --git a/src/intrinsics/llvm_x86.rs b/src/intrinsics/llvm_x86.rs new file mode 100644 index 0000000000000..7bc161fbe5523 --- /dev/null +++ b/src/intrinsics/llvm_x86.rs @@ -0,0 +1,197 @@ +//! Emulate x86 LLVM intrinsics + +use crate::intrinsics::*; +use crate::prelude::*; + +use rustc_middle::ty::subst::SubstsRef; + +pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( + fx: &mut FunctionCx<'_, '_, 'tcx>, + intrinsic: &str, + _substs: SubstsRef<'tcx>, + args: &[mir::Operand<'tcx>], + ret: CPlace<'tcx>, + target: Option, +) { + match intrinsic { + "llvm.x86.sse2.pause" | "llvm.aarch64.isb" => { + // Spin loop hint + } + + // Used by `_mm_movemask_epi8` and `_mm256_movemask_epi8` + "llvm.x86.sse2.pmovmskb.128" | "llvm.x86.avx2.pmovmskb" | "llvm.x86.sse2.movmsk.pd" => { + intrinsic_args!(fx, args => (a); intrinsic); + + let (lane_count, lane_ty) = a.layout().ty.simd_size_and_type(fx.tcx); + let lane_ty = fx.clif_type(lane_ty).unwrap(); + assert!(lane_count <= 32); + + let mut res = fx.bcx.ins().iconst(types::I32, 0); + + for lane in (0..lane_count).rev() { + let a_lane = a.value_lane(fx, lane).load_scalar(fx); + + // cast float to int + let a_lane = match lane_ty { + types::F32 => fx.bcx.ins().bitcast(types::I32, a_lane), + types::F64 => fx.bcx.ins().bitcast(types::I64, a_lane), + _ => a_lane, + }; + + // extract sign bit of an int + let a_lane_sign = fx.bcx.ins().ushr_imm(a_lane, i64::from(lane_ty.bits() - 1)); + + // shift sign bit into result + let a_lane_sign = clif_intcast(fx, a_lane_sign, types::I32, false); + res = fx.bcx.ins().ishl_imm(res, 1); + res = fx.bcx.ins().bor(res, a_lane_sign); + } + + let res = CValue::by_val(res, fx.layout_of(fx.tcx.types.i32)); + ret.write_cvalue(fx, res); + } + "llvm.x86.sse2.cmp.ps" | "llvm.x86.sse2.cmp.pd" => { + let (x, y, kind) = match args { + [x, y, kind] => (x, y, kind), + _ => bug!("wrong number of args for intrinsic {intrinsic}"), + }; + let x = codegen_operand(fx, x); + let y = codegen_operand(fx, y); + let kind = crate::constant::mir_operand_get_const_val(fx, kind) + .expect("llvm.x86.sse2.cmp.* kind not const"); + + let flt_cc = match kind + .try_to_bits(Size::from_bytes(1)) + .unwrap_or_else(|| panic!("kind not scalar: {:?}", kind)) + { + 0 => FloatCC::Equal, + 1 => FloatCC::LessThan, + 2 => FloatCC::LessThanOrEqual, + 7 => FloatCC::Ordered, + 3 => FloatCC::Unordered, + 4 => FloatCC::NotEqual, + 5 => FloatCC::UnorderedOrGreaterThanOrEqual, + 6 => FloatCC::UnorderedOrGreaterThan, + kind => unreachable!("kind {:?}", kind), + }; + + simd_pair_for_each_lane(fx, x, y, ret, &|fx, lane_ty, res_lane_ty, x_lane, y_lane| { + let res_lane = match lane_ty.kind() { + ty::Float(_) => fx.bcx.ins().fcmp(flt_cc, x_lane, y_lane), + _ => unreachable!("{:?}", lane_ty), + }; + bool_to_zero_or_max_uint(fx, res_lane_ty, res_lane) + }); + } + "llvm.x86.sse2.psrli.d" => { + let (a, imm8) = match args { + [a, imm8] => (a, imm8), + _ => bug!("wrong number of args for intrinsic {intrinsic}"), + }; + let a = codegen_operand(fx, a); + let imm8 = crate::constant::mir_operand_get_const_val(fx, imm8) + .expect("llvm.x86.sse2.psrli.d imm8 not const"); + + simd_for_each_lane(fx, a, ret, &|fx, _lane_ty, _res_lane_ty, lane| match imm8 + .try_to_bits(Size::from_bytes(4)) + .unwrap_or_else(|| panic!("imm8 not scalar: {:?}", imm8)) + { + imm8 if imm8 < 32 => fx.bcx.ins().ushr_imm(lane, i64::from(imm8 as u8)), + _ => fx.bcx.ins().iconst(types::I32, 0), + }); + } + "llvm.x86.sse2.pslli.d" => { + let (a, imm8) = match args { + [a, imm8] => (a, imm8), + _ => bug!("wrong number of args for intrinsic {intrinsic}"), + }; + let a = codegen_operand(fx, a); + let imm8 = crate::constant::mir_operand_get_const_val(fx, imm8) + .expect("llvm.x86.sse2.psrli.d imm8 not const"); + + simd_for_each_lane(fx, a, ret, &|fx, _lane_ty, _res_lane_ty, lane| match imm8 + .try_to_bits(Size::from_bytes(4)) + .unwrap_or_else(|| panic!("imm8 not scalar: {:?}", imm8)) + { + imm8 if imm8 < 32 => fx.bcx.ins().ishl_imm(lane, i64::from(imm8 as u8)), + _ => fx.bcx.ins().iconst(types::I32, 0), + }); + } + "llvm.x86.sse2.storeu.dq" => { + intrinsic_args!(fx, args => (mem_addr, a); intrinsic); + let mem_addr = mem_addr.load_scalar(fx); + + // FIXME correctly handle the unalignment + let dest = CPlace::for_ptr(Pointer::new(mem_addr), a.layout()); + dest.write_cvalue(fx, a); + } + "llvm.x86.addcarry.64" => { + intrinsic_args!(fx, args => (c_in, a, b); intrinsic); + let c_in = c_in.load_scalar(fx); + + llvm_add_sub(fx, BinOp::Add, ret, c_in, a, b); + } + "llvm.x86.subborrow.64" => { + intrinsic_args!(fx, args => (b_in, a, b); intrinsic); + let b_in = b_in.load_scalar(fx); + + llvm_add_sub(fx, BinOp::Sub, ret, b_in, a, b); + } + _ => { + fx.tcx.sess.warn(&format!( + "unsupported x86 llvm intrinsic {}; replacing with trap", + intrinsic + )); + crate::trap::trap_unimplemented(fx, intrinsic); + return; + } + } + + let dest = target.expect("all llvm intrinsics used by stdlib should return"); + let ret_block = fx.get_block(dest); + fx.bcx.ins().jump(ret_block, &[]); +} + +// llvm.x86.avx2.vperm2i128 +// llvm.x86.ssse3.pshuf.b.128 +// llvm.x86.avx2.pshuf.b +// llvm.x86.avx2.psrli.w +// llvm.x86.sse2.psrli.w + +fn llvm_add_sub<'tcx>( + fx: &mut FunctionCx<'_, '_, 'tcx>, + bin_op: BinOp, + ret: CPlace<'tcx>, + cb_in: Value, + a: CValue<'tcx>, + b: CValue<'tcx>, +) { + assert_eq!( + a.layout().ty, + fx.tcx.types.u64, + "llvm.x86.addcarry.64/llvm.x86.subborrow.64 second operand must be u64" + ); + assert_eq!( + b.layout().ty, + fx.tcx.types.u64, + "llvm.x86.addcarry.64/llvm.x86.subborrow.64 third operand must be u64" + ); + + // c + carry -> c + first intermediate carry or borrow respectively + let int0 = crate::num::codegen_checked_int_binop(fx, bin_op, a, b); + let c = int0.value_field(fx, mir::Field::new(0)); + let cb0 = int0.value_field(fx, mir::Field::new(1)).load_scalar(fx); + + // c + carry -> c + second intermediate carry or borrow respectively + let cb_in_as_u64 = fx.bcx.ins().uextend(types::I64, cb_in); + let cb_in_as_u64 = CValue::by_val(cb_in_as_u64, fx.layout_of(fx.tcx.types.u64)); + let int1 = crate::num::codegen_checked_int_binop(fx, bin_op, c, cb_in_as_u64); + let (c, cb1) = int1.load_scalar_pair(fx); + + // carry0 | carry1 -> carry or borrow respectively + let cb_out = fx.bcx.ins().bor(cb0, cb1); + + let layout = fx.layout_of(fx.tcx.mk_tup([fx.tcx.types.u8, fx.tcx.types.u64].iter())); + let val = CValue::by_val_pair(cb_out, c, layout); + ret.write_cvalue(fx, val); +} diff --git a/src/intrinsics/mod.rs b/src/intrinsics/mod.rs index 0302b843aa226..7a380acf79857 100644 --- a/src/intrinsics/mod.rs +++ b/src/intrinsics/mod.rs @@ -14,6 +14,8 @@ macro_rules! intrinsic_args { mod cpuid; mod llvm; +mod llvm_aarch64; +mod llvm_x86; mod simd; pub(crate) use cpuid::codegen_cpuid_call; @@ -195,8 +197,7 @@ fn bool_to_zero_or_max_uint<'tcx>( ty => ty, }; - let val = fx.bcx.ins().bint(int_ty, val); - let mut res = fx.bcx.ins().ineg(val); + let mut res = fx.bcx.ins().bmask(int_ty, val); if ty.is_float() { res = fx.bcx.ins().bitcast(ty, res); @@ -632,85 +633,15 @@ fn codegen_regular_intrinsic_call<'tcx>( ret.write_cvalue(fx, res); } sym::bswap => { - // FIXME(CraneStation/cranelift#794) add bswap instruction to cranelift - fn swap(bcx: &mut FunctionBuilder<'_>, v: Value) -> Value { - match bcx.func.dfg.value_type(v) { - types::I8 => v, - - // https://code.woboq.org/gcc/include/bits/byteswap.h.html - types::I16 => { - let tmp1 = bcx.ins().ishl_imm(v, 8); - let n1 = bcx.ins().band_imm(tmp1, 0xFF00); - - let tmp2 = bcx.ins().ushr_imm(v, 8); - let n2 = bcx.ins().band_imm(tmp2, 0x00FF); - - bcx.ins().bor(n1, n2) - } - types::I32 => { - let tmp1 = bcx.ins().ishl_imm(v, 24); - let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000); - - let tmp2 = bcx.ins().ishl_imm(v, 8); - let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000); - - let tmp3 = bcx.ins().ushr_imm(v, 8); - let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00); - - let tmp4 = bcx.ins().ushr_imm(v, 24); - let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF); - - let or_tmp1 = bcx.ins().bor(n1, n2); - let or_tmp2 = bcx.ins().bor(n3, n4); - bcx.ins().bor(or_tmp1, or_tmp2) - } - types::I64 => { - let tmp1 = bcx.ins().ishl_imm(v, 56); - let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000_0000_0000u64 as i64); - - let tmp2 = bcx.ins().ishl_imm(v, 40); - let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000_0000_0000u64 as i64); - - let tmp3 = bcx.ins().ishl_imm(v, 24); - let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00_0000_0000u64 as i64); - - let tmp4 = bcx.ins().ishl_imm(v, 8); - let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF_0000_0000u64 as i64); - - let tmp5 = bcx.ins().ushr_imm(v, 8); - let n5 = bcx.ins().band_imm(tmp5, 0x0000_0000_FF00_0000u64 as i64); - - let tmp6 = bcx.ins().ushr_imm(v, 24); - let n6 = bcx.ins().band_imm(tmp6, 0x0000_0000_00FF_0000u64 as i64); - - let tmp7 = bcx.ins().ushr_imm(v, 40); - let n7 = bcx.ins().band_imm(tmp7, 0x0000_0000_0000_FF00u64 as i64); - - let tmp8 = bcx.ins().ushr_imm(v, 56); - let n8 = bcx.ins().band_imm(tmp8, 0x0000_0000_0000_00FFu64 as i64); - - let or_tmp1 = bcx.ins().bor(n1, n2); - let or_tmp2 = bcx.ins().bor(n3, n4); - let or_tmp3 = bcx.ins().bor(n5, n6); - let or_tmp4 = bcx.ins().bor(n7, n8); - - let or_tmp5 = bcx.ins().bor(or_tmp1, or_tmp2); - let or_tmp6 = bcx.ins().bor(or_tmp3, or_tmp4); - bcx.ins().bor(or_tmp5, or_tmp6) - } - types::I128 => { - let (lo, hi) = bcx.ins().isplit(v); - let lo = swap(bcx, lo); - let hi = swap(bcx, hi); - bcx.ins().iconcat(hi, lo) - } - ty => unreachable!("bswap {}", ty), - } - } intrinsic_args!(fx, args => (arg); intrinsic); let val = arg.load_scalar(fx); - let res = CValue::by_val(swap(&mut fx.bcx, val), arg.layout()); + let res = if fx.bcx.func.dfg.value_type(val) == types::I8 { + val + } else { + fx.bcx.ins().bswap(val) + }; + let res = CValue::by_val(res, arg.layout()); ret.write_cvalue(fx, res); } sym::assert_inhabited | sym::assert_zero_valid | sym::assert_uninit_valid => { @@ -936,8 +867,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let old = fx.bcx.ins().atomic_cas(MemFlags::trusted(), ptr, test_old, new); let is_eq = fx.bcx.ins().icmp(IntCC::Equal, old, test_old); - let ret_val = - CValue::by_val_pair(old, fx.bcx.ins().bint(types::I8, is_eq), ret.layout()); + let ret_val = CValue::by_val_pair(old, is_eq, ret.layout()); ret.write_cvalue(fx, ret_val) } @@ -1259,8 +1189,7 @@ fn codegen_regular_intrinsic_call<'tcx>( flags.set_notrap(); let lhs_val = fx.bcx.ins().load(clty, flags, lhs_ref, 0); let rhs_val = fx.bcx.ins().load(clty, flags, rhs_ref, 0); - let eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_val, rhs_val); - fx.bcx.ins().bint(types::I8, eq) + fx.bcx.ins().icmp(IntCC::Equal, lhs_val, rhs_val) } else { // Just call `memcmp` (like slices do in core) when the // size is too large or it's not a power-of-two. @@ -1270,8 +1199,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let returns = vec![AbiParam::new(types::I32)]; let args = &[lhs_ref, rhs_ref, bytes_val]; let cmp = fx.lib_call("memcmp", params, returns, args)[0]; - let eq = fx.bcx.ins().icmp_imm(IntCC::Equal, cmp, 0); - fx.bcx.ins().bint(types::I8, eq) + fx.bcx.ins().icmp_imm(IntCC::Equal, cmp, 0) }; ret.write_cvalue(fx, CValue::by_val(is_eq_value, ret.layout())); } diff --git a/src/intrinsics/simd.rs b/src/intrinsics/simd.rs index 51fce8c854bdb..14f5e9187399f 100644 --- a/src/intrinsics/simd.rs +++ b/src/intrinsics/simd.rs @@ -112,10 +112,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( _ => unreachable!(), }; - let ty = fx.clif_type(res_lane_ty).unwrap(); - - let res_lane = fx.bcx.ins().bint(ty, res_lane); - fx.bcx.ins().ineg(res_lane) + bool_to_zero_or_max_uint(fx, res_lane_ty, res_lane) }); } @@ -716,7 +713,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( let res_type = Type::int_with_byte_size(u16::try_from(expected_bytes).unwrap()).unwrap(); - let mut res = fx.bcx.ins().iconst(res_type, 0); + let mut res = type_zero_value(&mut fx.bcx, res_type); let lanes = match fx.tcx.sess.target.endian { Endian::Big => Box::new(0..lane_count) as Box>, diff --git a/src/main_shim.rs b/src/main_shim.rs index f7434633ea442..c10054e7f0d2c 100644 --- a/src/main_shim.rs +++ b/src/main_shim.rs @@ -65,7 +65,7 @@ pub(crate) fn maybe_create_entry_wrapper( returns: vec![AbiParam::new(m.target_config().pointer_type() /*isize*/)], call_conv: crate::conv_to_call_conv( tcx.sess.target.options.entry_abi, - CallConv::triple_default(m.isa().triple()), + m.target_config().default_call_conv, ), }; @@ -75,7 +75,7 @@ pub(crate) fn maybe_create_entry_wrapper( let instance = Instance::mono(tcx, rust_main_def_id).polymorphize(tcx); let main_name = tcx.symbol_name(instance).name; - let main_sig = get_function_sig(tcx, m.isa().triple(), instance); + let main_sig = get_function_sig(tcx, m.target_config().default_call_conv, instance); let main_func_id = m.declare_function(main_name, Linkage::Import, &main_sig).unwrap(); let mut ctx = Context::new(); @@ -119,7 +119,7 @@ pub(crate) fn maybe_create_entry_wrapper( .polymorphize(tcx); let report_name = tcx.symbol_name(report).name; - let report_sig = get_function_sig(tcx, m.isa().triple(), report); + let report_sig = get_function_sig(tcx, m.target_config().default_call_conv, report); let report_func_id = m.declare_function(report_name, Linkage::Import, &report_sig).unwrap(); let report_func_ref = m.declare_func_in_func(report_func_id, &mut bcx.func); diff --git a/src/num.rs b/src/num.rs index ecbab408ded97..afacbec644582 100644 --- a/src/num.rs +++ b/src/num.rs @@ -49,7 +49,6 @@ fn codegen_compare_bin_op<'tcx>( ) -> CValue<'tcx> { let intcc = crate::num::bin_op_to_intcc(bin_op, signed).unwrap(); let val = fx.bcx.ins().icmp(intcc, lhs, rhs); - let val = fx.bcx.ins().bint(types::I8, val); CValue::by_val(val, fx.layout_of(fx.tcx.types.bool)) } @@ -290,8 +289,6 @@ pub(crate) fn codegen_checked_int_binop<'tcx>( _ => bug!("binop {:?} on checked int/uint lhs: {:?} rhs: {:?}", bin_op, in_lhs, in_rhs), }; - let has_overflow = fx.bcx.ins().bint(types::I8, has_overflow); - let out_layout = fx.layout_of(fx.tcx.mk_tup([in_lhs.layout().ty, fx.tcx.types.bool].iter())); CValue::by_val_pair(res, has_overflow, out_layout) } @@ -368,7 +365,6 @@ pub(crate) fn codegen_float_binop<'tcx>( _ => unreachable!(), }; let val = fx.bcx.ins().fcmp(fltcc, lhs, rhs); - let val = fx.bcx.ins().bint(types::I8, val); return CValue::by_val(val, fx.layout_of(fx.tcx.types.bool)); } _ => unreachable!("{:?}({:?}, {:?})", bin_op, in_lhs, in_rhs), @@ -440,7 +436,7 @@ pub(crate) fn codegen_ptr_binop<'tcx>( _ => panic!("bin_op {:?} on ptr", bin_op), }; - CValue::by_val(fx.bcx.ins().bint(types::I8, res), fx.layout_of(fx.tcx.types.bool)) + CValue::by_val(res, fx.layout_of(fx.tcx.types.bool)) } } diff --git a/src/optimize/peephole.rs b/src/optimize/peephole.rs index d637b4d89293c..7f45bbd8f2813 100644 --- a/src/optimize/peephole.rs +++ b/src/optimize/peephole.rs @@ -3,19 +3,6 @@ use cranelift_codegen::ir::{condcodes::IntCC, InstructionData, Opcode, Value, ValueDef}; use cranelift_frontend::FunctionBuilder; -/// If the given value was produced by a `bint` instruction, return it's input, otherwise return the -/// given value. -pub(crate) fn maybe_unwrap_bint(bcx: &mut FunctionBuilder<'_>, arg: Value) -> Value { - if let ValueDef::Result(arg_inst, 0) = bcx.func.dfg.value_def(arg) { - match bcx.func.dfg[arg_inst] { - InstructionData::Unary { opcode: Opcode::Bint, arg } => arg, - _ => arg, - } - } else { - arg - } -} - /// If the given value was produced by the lowering of `Rvalue::Not` return the input and true, /// otherwise return the given value and false. pub(crate) fn maybe_unwrap_bool_not(bcx: &mut FunctionBuilder<'_>, arg: Value) -> (Value, bool) { @@ -48,13 +35,6 @@ pub(crate) fn maybe_known_branch_taken( }; match bcx.func.dfg[arg_inst] { - InstructionData::UnaryBool { opcode: Opcode::Bconst, imm } => { - if test_zero { - Some(!imm) - } else { - Some(imm) - } - } InstructionData::UnaryImm { opcode: Opcode::Iconst, imm } => { if test_zero { Some(imm.bits() == 0) diff --git a/src/value_and_place.rs b/src/value_and_place.rs index 34746ff6b6645..fe8af21ac6de5 100644 --- a/src/value_and_place.rs +++ b/src/value_and_place.rs @@ -392,7 +392,7 @@ impl<'tcx> CPlace<'tcx> { local: Local, layout: TyAndLayout<'tcx>, ) -> CPlace<'tcx> { - let var = Variable::with_u32(fx.next_ssa_var); + let var = Variable::from_u32(fx.next_ssa_var); fx.next_ssa_var += 1; fx.bcx.declare_var(var, fx.clif_type(layout.ty).unwrap()); CPlace { inner: CPlaceInner::Var(local, var), layout } @@ -403,9 +403,9 @@ impl<'tcx> CPlace<'tcx> { local: Local, layout: TyAndLayout<'tcx>, ) -> CPlace<'tcx> { - let var1 = Variable::with_u32(fx.next_ssa_var); + let var1 = Variable::from_u32(fx.next_ssa_var); fx.next_ssa_var += 1; - let var2 = Variable::with_u32(fx.next_ssa_var); + let var2 = Variable::from_u32(fx.next_ssa_var); fx.next_ssa_var += 1; let (ty1, ty2) = fx.clif_pair_type(layout.ty).unwrap(); @@ -515,9 +515,7 @@ impl<'tcx> CPlace<'tcx> { | (types::F32, types::I32) | (types::I64, types::F64) | (types::F64, types::I64) => fx.bcx.ins().bitcast(dst_ty, data), - _ if src_ty.is_vector() && dst_ty.is_vector() => { - fx.bcx.ins().raw_bitcast(dst_ty, data) - } + _ if src_ty.is_vector() && dst_ty.is_vector() => fx.bcx.ins().bitcast(dst_ty, data), _ if src_ty.is_vector() || dst_ty.is_vector() => { // FIXME do something more efficient for transmutes between vectors and integers. let stack_slot = fx.bcx.create_sized_stack_slot(StackSlotData { @@ -590,7 +588,10 @@ impl<'tcx> CPlace<'tcx> { return; } CPlaceInner::VarPair(_local, var1, var2) => { - let (data1, data2) = CValue(from.0, dst_layout).load_scalar_pair(fx); + let (ptr, meta) = from.force_stack(fx); + assert!(meta.is_none()); + let (data1, data2) = + CValue(CValueInner::ByRef(ptr, None), dst_layout).load_scalar_pair(fx); let (dst_ty1, dst_ty2) = fx.clif_pair_type(self.layout().ty).unwrap(); transmute_value(fx, var1, data1, dst_ty1); transmute_value(fx, var2, data2, dst_ty2); diff --git a/test.sh b/test.sh index 3d929a1d50ce2..13e7784539d5a 100755 --- a/test.sh +++ b/test.sh @@ -1,2 +1,2 @@ #!/usr/bin/env bash -exec ./y.rs test +exec ./y.rs test "$@" diff --git a/y.rs b/y.rs index f177b91c2c487..02e1e21ade1de 100755 --- a/y.rs +++ b/y.rs @@ -3,7 +3,7 @@ # This block is ignored by rustc set -e echo "[BUILD] y.rs" 1>&2 -rustc $0 -o ${0/.rs/.bin} -Cdebuginfo=1 +rustc $0 -o ${0/.rs/.bin} -Cdebuginfo=1 --edition 2021 exec ${0/.rs/.bin} $@ */ From 808cba2251aba868a97b67ad7d5d7cecc9024f93 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 10:28:53 +0000 Subject: [PATCH 062/500] Extract Compiler creation from tests.rs --- build_system/tests.rs | 31 ++++++------------------------- build_system/utils.rs | 21 ++++++++++++++++++++- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/build_system/tests.rs b/build_system/tests.rs index 1c372736ed65d..7a12c1a54d46c 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -2,7 +2,7 @@ use super::build_sysroot; use super::config; use super::path::{Dirs, RelPath}; use super::prepare::GitRepo; -use super::rustc_info::{get_cargo_path, get_wrapper_file_name}; +use super::rustc_info::get_wrapper_file_name; use super::utils::{ hyperfine_command, spawn_and_wait, spawn_and_wait_with_input, CargoProject, Compiler, }; @@ -507,11 +507,6 @@ impl TestRunner { let jit_supported = target_triple.contains("x86_64") && is_native && !host_triple.contains("windows"); - let rustc_clif = - RelPath::DIST.to_path(&dirs).join(get_wrapper_file_name("rustc-clif", "bin")); - let rustdoc_clif = - RelPath::DIST.to_path(&dirs).join(get_wrapper_file_name("rustdoc-clif", "bin")); - let mut rustflags = env::var("RUSTFLAGS").ok().unwrap_or("".to_string()); let mut runner = vec![]; @@ -550,25 +545,11 @@ impl TestRunner { rustflags = format!("{} -Clink-arg=-undefined -Clink-arg=dynamic_lookup", rustflags); } - let host_compiler = Compiler { - cargo: get_cargo_path(), - rustc: rustc_clif.clone(), - rustdoc: rustdoc_clif.clone(), - rustflags: String::new(), - rustdocflags: String::new(), - triple: host_triple, - runner: vec![], - }; - - let target_compiler = Compiler { - cargo: get_cargo_path(), - rustc: rustc_clif, - rustdoc: rustdoc_clif, - rustflags: rustflags.clone(), - rustdocflags: rustflags, - triple: target_triple, - runner, - }; + let host_compiler = Compiler::clif_with_triple(&dirs, host_triple); + + let mut target_compiler = Compiler::clif_with_triple(&dirs, target_triple); + target_compiler.rustflags = rustflags; + target_compiler.runner = runner; Self { is_native, jit_supported, dirs, host_compiler, target_compiler } } diff --git a/build_system/utils.rs b/build_system/utils.rs index 2be70e8e421b2..995918ee1430b 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -5,7 +5,9 @@ use std::path::{Path, PathBuf}; use std::process::{self, Command, Stdio}; use super::path::{Dirs, RelPath}; -use super::rustc_info::{get_cargo_path, get_host_triple, get_rustc_path, get_rustdoc_path}; +use super::rustc_info::{ + get_cargo_path, get_host_triple, get_rustc_path, get_rustdoc_path, get_wrapper_file_name, +}; pub(crate) struct Compiler { pub(crate) cargo: PathBuf, @@ -41,6 +43,23 @@ impl Compiler { runner: vec![], } } + + pub(crate) fn clif_with_triple(dirs: &Dirs, triple: String) -> Compiler { + let rustc_clif = + RelPath::DIST.to_path(&dirs).join(get_wrapper_file_name("rustc-clif", "bin")); + let rustdoc_clif = + RelPath::DIST.to_path(&dirs).join(get_wrapper_file_name("rustdoc-clif", "bin")); + + Compiler { + cargo: get_cargo_path(), + rustc: rustc_clif.clone(), + rustdoc: rustdoc_clif.clone(), + rustflags: String::new(), + rustdocflags: String::new(), + triple, + runner: vec![], + } + } } pub(crate) struct CargoProject { From f626185a5b792c171297d1e9a6b8d166348a5e53 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 11:09:45 +0000 Subject: [PATCH 063/500] Update portable-simd to 582239ac3b32007613df04d7ffa78dc30f4c5645 --- build_system/tests.rs | 2 +- ...table-simd-Disable-unsupported-tests.patch | 4 +-- src/intrinsics/simd.rs | 32 ++++++++++++++++++- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/build_system/tests.rs b/build_system/tests.rs index 7a12c1a54d46c..2131b88c23286 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -244,7 +244,7 @@ static REGEX: CargoProject = CargoProject::new(®EX_REPO.source_dir(), "regex" pub(crate) static PORTABLE_SIMD_REPO: GitRepo = GitRepo::github( "rust-lang", "portable-simd", - "d5cd4a8112d958bd3a252327e0d069a6363249bd", + "582239ac3b32007613df04d7ffa78dc30f4c5645", "portable-simd", ); diff --git a/patches/0001-portable-simd-Disable-unsupported-tests.patch b/patches/0001-portable-simd-Disable-unsupported-tests.patch index 89e2b61c1fc85..bdf727666bedf 100644 --- a/patches/0001-portable-simd-Disable-unsupported-tests.patch +++ b/patches/0001-portable-simd-Disable-unsupported-tests.patch @@ -24,8 +24,8 @@ index e8e8f68..7173c24 100644 /// If an index is out-of-bounds, the lane is instead selected from the `or` vector. /// @@ -473,6 +474,7 @@ where - // Cleared ☢️ *mut T Zone - } + // Safety: The caller is responsible for upholding all invariants + unsafe { intrinsics::simd_scatter(self, dest, enable.to_int()) } } + */ } diff --git a/src/intrinsics/simd.rs b/src/intrinsics/simd.rs index 14f5e9187399f..a6f5f70dc4cad 100644 --- a/src/intrinsics/simd.rs +++ b/src/intrinsics/simd.rs @@ -770,7 +770,37 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( }); } - // simd_arith_offset + sym::simd_expose_addr | sym::simd_from_exposed_addr | sym::simd_cast_ptr => { + intrinsic_args!(fx, args => (arg); intrinsic); + ret.write_cvalue_transmute(fx, arg); + } + + sym::simd_arith_offset => { + intrinsic_args!(fx, args => (ptr, offset); intrinsic); + + let (lane_count, ptr_lane_ty) = ptr.layout().ty.simd_size_and_type(fx.tcx); + let pointee_ty = ptr_lane_ty.builtin_deref(true).unwrap().ty; + let pointee_size = fx.layout_of(pointee_ty).size.bytes(); + let (ret_lane_count, ret_lane_ty) = ret.layout().ty.simd_size_and_type(fx.tcx); + let ret_lane_layout = fx.layout_of(ret_lane_ty); + assert_eq!(lane_count, ret_lane_count); + + for lane_idx in 0..lane_count { + let ptr_lane = ptr.value_lane(fx, lane_idx).load_scalar(fx); + let offset_lane = offset.value_lane(fx, lane_idx).load_scalar(fx); + + let ptr_diff = if pointee_size != 1 { + fx.bcx.ins().imul_imm(offset_lane, pointee_size as i64) + } else { + offset_lane + }; + let res_lane = fx.bcx.ins().iadd(ptr_lane, ptr_diff); + let res_lane = CValue::by_val(res_lane, ret_lane_layout); + + ret.place_lane(fx, lane_idx).write_cvalue(fx, res_lane); + } + } + // simd_scatter // simd_gather _ => { From 0865e5a45295b149757da230e7e8d5d4b7b7fc9c Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 11:41:06 +0000 Subject: [PATCH 064/500] Set RUSTDOCFLAGS again Was accidentally removed in 808cba2 --- build_system/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build_system/tests.rs b/build_system/tests.rs index 2131b88c23286..738a76ef4c55a 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -548,7 +548,8 @@ impl TestRunner { let host_compiler = Compiler::clif_with_triple(&dirs, host_triple); let mut target_compiler = Compiler::clif_with_triple(&dirs, target_triple); - target_compiler.rustflags = rustflags; + target_compiler.rustflags = rustflags.clone(); + target_compiler.rustdocflags = rustflags; target_compiler.runner = runner; Self { is_native, jit_supported, dirs, host_compiler, target_compiler } From 06be70e3d6dc5daea0c92f770028ef19a748f290 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 13:09:37 +0100 Subject: [PATCH 065/500] Implement simd_gather and simd_scatter (#1309) These are the last remaining platform intrinsics necessary for portable-simd. --- ...table-simd-Disable-unsupported-tests.patch | 35 --------- src/intrinsics/simd.rs | 76 ++++++++++++++++++- 2 files changed, 74 insertions(+), 37 deletions(-) delete mode 100644 patches/0001-portable-simd-Disable-unsupported-tests.patch diff --git a/patches/0001-portable-simd-Disable-unsupported-tests.patch b/patches/0001-portable-simd-Disable-unsupported-tests.patch deleted file mode 100644 index bdf727666bedf..0000000000000 --- a/patches/0001-portable-simd-Disable-unsupported-tests.patch +++ /dev/null @@ -1,35 +0,0 @@ -From b742f03694b920cc14400727d54424e8e1b60928 Mon Sep 17 00:00:00 2001 -From: bjorn3 -Date: Thu, 18 Nov 2021 19:28:40 +0100 -Subject: [PATCH] Disable unsupported tests - ---- - crates/core_simd/src/elements/int.rs | 8 ++++++++ - crates/core_simd/src/elements/uint.rs | 4 ++++ - crates/core_simd/src/masks/full_masks.rs | 6 ++++++ - crates/core_simd/src/vector.rs | 2 ++ - crates/core_simd/tests/masks.rs | 3 --- - 5 files changed, 20 insertions(+), 3 deletions(-) - -diff --git a/crates/core_simd/src/vector.rs b/crates/core_simd/src/vector.rs -index e8e8f68..7173c24 100644 ---- a/crates/core_simd/src/vector.rs -+++ b/crates/core_simd/src/vector.rs -@@ -250,6 +250,7 @@ where - unsafe { intrinsics::simd_cast(self) } - } - -+ /* - /// Reads from potentially discontiguous indices in `slice` to construct a SIMD vector. - /// If an index is out-of-bounds, the lane is instead selected from the `or` vector. - /// -@@ -473,6 +474,7 @@ where - // Safety: The caller is responsible for upholding all invariants - unsafe { intrinsics::simd_scatter(self, dest, enable.to_int()) } - } -+ */ - } - - impl Copy for Simd --- -2.25.1 diff --git a/src/intrinsics/simd.rs b/src/intrinsics/simd.rs index a6f5f70dc4cad..62ea2214ab44e 100644 --- a/src/intrinsics/simd.rs +++ b/src/intrinsics/simd.rs @@ -801,8 +801,80 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( } } - // simd_scatter - // simd_gather + sym::simd_gather => { + intrinsic_args!(fx, args => (val, ptr, mask); intrinsic); + + let (val_lane_count, val_lane_ty) = val.layout().ty.simd_size_and_type(fx.tcx); + let (ptr_lane_count, _ptr_lane_ty) = ptr.layout().ty.simd_size_and_type(fx.tcx); + let (mask_lane_count, _mask_lane_ty) = mask.layout().ty.simd_size_and_type(fx.tcx); + let (ret_lane_count, ret_lane_ty) = ret.layout().ty.simd_size_and_type(fx.tcx); + assert_eq!(val_lane_count, ptr_lane_count); + assert_eq!(val_lane_count, mask_lane_count); + assert_eq!(val_lane_count, ret_lane_count); + + let lane_clif_ty = fx.clif_type(val_lane_ty).unwrap(); + let ret_lane_layout = fx.layout_of(ret_lane_ty); + + for lane_idx in 0..ptr_lane_count { + let val_lane = val.value_lane(fx, lane_idx).load_scalar(fx); + let ptr_lane = ptr.value_lane(fx, lane_idx).load_scalar(fx); + let mask_lane = mask.value_lane(fx, lane_idx).load_scalar(fx); + + let if_enabled = fx.bcx.create_block(); + let if_disabled = fx.bcx.create_block(); + let next = fx.bcx.create_block(); + let res_lane = fx.bcx.append_block_param(next, lane_clif_ty); + + fx.bcx.ins().brnz(mask_lane, if_enabled, &[]); + fx.bcx.ins().jump(if_disabled, &[]); + fx.bcx.seal_block(if_enabled); + fx.bcx.seal_block(if_disabled); + + fx.bcx.switch_to_block(if_enabled); + let res = fx.bcx.ins().load(lane_clif_ty, MemFlags::trusted(), ptr_lane, 0); + fx.bcx.ins().jump(next, &[res]); + + fx.bcx.switch_to_block(if_disabled); + fx.bcx.ins().jump(next, &[val_lane]); + + fx.bcx.seal_block(next); + fx.bcx.switch_to_block(next); + + ret.place_lane(fx, lane_idx) + .write_cvalue(fx, CValue::by_val(res_lane, ret_lane_layout)); + } + } + + sym::simd_scatter => { + intrinsic_args!(fx, args => (val, ptr, mask); intrinsic); + + let (val_lane_count, _val_lane_ty) = val.layout().ty.simd_size_and_type(fx.tcx); + let (ptr_lane_count, _ptr_lane_ty) = ptr.layout().ty.simd_size_and_type(fx.tcx); + let (mask_lane_count, _mask_lane_ty) = mask.layout().ty.simd_size_and_type(fx.tcx); + assert_eq!(val_lane_count, ptr_lane_count); + assert_eq!(val_lane_count, mask_lane_count); + + for lane_idx in 0..ptr_lane_count { + let val_lane = val.value_lane(fx, lane_idx).load_scalar(fx); + let ptr_lane = ptr.value_lane(fx, lane_idx).load_scalar(fx); + let mask_lane = mask.value_lane(fx, lane_idx).load_scalar(fx); + + let if_enabled = fx.bcx.create_block(); + let next = fx.bcx.create_block(); + + fx.bcx.ins().brnz(mask_lane, if_enabled, &[]); + fx.bcx.ins().jump(next, &[]); + fx.bcx.seal_block(if_enabled); + + fx.bcx.switch_to_block(if_enabled); + fx.bcx.ins().store(MemFlags::trusted(), val_lane, ptr_lane, 0); + fx.bcx.ins().jump(next, &[]); + + fx.bcx.seal_block(next); + fx.bcx.switch_to_block(next); + } + } + _ => { fx.tcx.sess.span_fatal(span, &format!("Unknown SIMD intrinsic {}", intrinsic)); } From e2a273934183becd362ec7ce6a86ec944db04636 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 12:20:39 +0000 Subject: [PATCH 066/500] Update not yet supported section of the readme --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0e9c77244d4cc..55b107e4efbca 100644 --- a/Readme.md +++ b/Readme.md @@ -53,7 +53,8 @@ configuration options. * Inline assembly ([no cranelift support](https://github.com/bytecodealliance/wasmtime/issues/1041)) * On UNIX there is support for invoking an external assembler for `global_asm!` and `asm!`. -* SIMD ([tracked here](https://github.com/bjorn3/rustc_codegen_cranelift/issues/171), some basic things work) +* SIMD ([tracked here](https://github.com/bjorn3/rustc_codegen_cranelift/issues/171), `std::simd` fully works, `std::arch` is partially supported) +* Unwinding on panics ([no cranelift support](https://github.com/bytecodealliance/wasmtime/issues/1677), `-Cpanic=abort` is enabled by default) ## License From d74e5b6cc7d7b015362e68ae2be88cfc3415ce3a Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 12:22:57 +0000 Subject: [PATCH 067/500] Update actions/upload-artifact to v3 v2 depends on Node.js 12 which will be removed from GHA in the near future --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index a6bb12a66a247..010979c9c33e4 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -122,7 +122,7 @@ jobs: - name: Upload prebuilt cg_clif if: matrix.env.TARGET_TRIPLE != 'x86_64-pc-windows-gnu' - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: name: cg_clif-${{ matrix.env.TARGET_TRIPLE }} path: cg_clif.tar.xz From d841f93855f94cafaf3c1a5933b6a0b1c88fa9d3 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 13:57:13 +0000 Subject: [PATCH 068/500] Add .comment section with producer name Fixes #1211 --- src/debuginfo/mod.rs | 14 +++++++++----- src/driver/aot.rs | 14 +++++++++++++- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/debuginfo/mod.rs b/src/debuginfo/mod.rs index 2ba012a77b0a9..4cb556844b7e8 100644 --- a/src/debuginfo/mod.rs +++ b/src/debuginfo/mod.rs @@ -20,6 +20,14 @@ use indexmap::IndexSet; pub(crate) use emit::{DebugReloc, DebugRelocName}; pub(crate) use unwind::UnwindContext; +pub(crate) fn producer() -> String { + format!( + "cg_clif (rustc {}, cranelift {})", + rustc_interface::util::rustc_version_str().unwrap_or("unknown version"), + cranelift_codegen::VERSION, + ) +} + pub(crate) struct DebugContext { endian: RunTimeEndian, @@ -57,11 +65,7 @@ impl DebugContext { let mut dwarf = DwarfUnit::new(encoding); - let producer = format!( - "cg_clif (rustc {}, cranelift {})", - rustc_interface::util::rustc_version_str().unwrap_or("unknown version"), - cranelift_codegen::VERSION, - ); + let producer = producer(); let comp_dir = tcx .sess .opts diff --git a/src/driver/aot.rs b/src/driver/aot.rs index f873561c1713f..27cce7c15e1f7 100644 --- a/src/driver/aot.rs +++ b/src/driver/aot.rs @@ -169,10 +169,22 @@ fn emit_cgu( fn emit_module( output_filenames: &OutputFilenames, prof: &SelfProfilerRef, - object: cranelift_object::object::write::Object<'_>, + mut object: cranelift_object::object::write::Object<'_>, kind: ModuleKind, name: String, ) -> Result { + if object.format() == cranelift_object::object::BinaryFormat::Elf { + let comment_section = object.add_section( + Vec::new(), + b".comment".to_vec(), + cranelift_object::object::SectionKind::OtherString, + ); + let mut producer = vec![0]; + producer.extend(crate::debuginfo::producer().as_bytes()); + producer.push(0); + object.set_section_data(comment_section, producer, 1); + } + let tmp_file = output_filenames.temp_path(OutputType::Object, Some(&name)); let mut file = match File::create(&tmp_file) { Ok(file) => file, From e082eebb5f3fceac83b5cca666e601e5ce0a964b Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 13:59:29 +0000 Subject: [PATCH 069/500] Run verifier checks during rustc tests too Fixes #1219 --- .github/workflows/rustc.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/rustc.yml b/.github/workflows/rustc.yml index bef806318efa8..af34e10c7596d 100644 --- a/.github/workflows/rustc.yml +++ b/.github/workflows/rustc.yml @@ -41,6 +41,9 @@ jobs: # Enable backtraces for easier debugging export RUST_BACKTRACE=1 + # Enable extra checks + export CG_CLIF_ENABLE_VERIFIER=1 + ./scripts/test_bootstrap.sh rustc_test_suite: runs-on: ubuntu-latest @@ -79,4 +82,7 @@ jobs: # Enable backtraces for easier debugging export RUST_BACKTRACE=1 + # Enable extra checks + export CG_CLIF_ENABLE_VERIFIER=1 + ./scripts/test_rustc_tests.sh From cc3ac006a2fecc9a6543244798c9f13c73c3db8d Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 14:12:46 +0000 Subject: [PATCH 070/500] Move many env vars from CI configuration to the build system --- .cirrus.yml | 5 ----- .github/workflows/main.yml | 23 +---------------------- .github/workflows/nightly-cranelift.yml | 13 +------------ .github/workflows/rustc.yml | 18 ++---------------- build_system/mod.rs | 6 ++++++ build_system/tests.rs | 7 +++++-- 6 files changed, 15 insertions(+), 57 deletions(-) diff --git a/.cirrus.yml b/.cirrus.yml index d627c2ee09c4e..76b48d70ab7c7 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -15,9 +15,4 @@ task: - ./y.rs prepare test_script: - . $HOME/.cargo/env - - # Enable backtraces for easier debugging - - export RUST_BACKTRACE=1 - - # Reduce amount of benchmark runs as they are slow - - export COMPILE_RUNS=2 - - export RUN_RUNS=2 - ./y.rs test diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 010979c9c33e4..3492df72720bc 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -104,18 +104,7 @@ jobs: - name: Test env: TARGET_TRIPLE: ${{ matrix.env.TARGET_TRIPLE }} - run: | - # Enable backtraces for easier debugging - export RUST_BACKTRACE=1 - - # Reduce amount of benchmark runs as they are slow - export COMPILE_RUNS=2 - export RUN_RUNS=2 - - # Enable extra checks - export CG_CLIF_ENABLE_VERIFIER=1 - - ./y.rs test + run: ./y.rs test - name: Package prebuilt cg_clif run: tar cvfJ cg_clif.tar.xz dist @@ -195,16 +184,6 @@ jobs: - name: Test run: | - # Enable backtraces for easier debugging - $Env:RUST_BACKTRACE=1 - - # Reduce amount of benchmark runs as they are slow - $Env:COMPILE_RUNS=2 - $Env:RUN_RUNS=2 - - # Enable extra checks - $Env:CG_CLIF_ENABLE_VERIFIER=1 - # WIP Disable some tests # This fails due to some weird argument handling by hyperfine, not an actual regression diff --git a/.github/workflows/nightly-cranelift.yml b/.github/workflows/nightly-cranelift.yml index d0d58d2a7eacb..0565938ee3531 100644 --- a/.github/workflows/nightly-cranelift.yml +++ b/.github/workflows/nightly-cranelift.yml @@ -45,15 +45,4 @@ jobs: - name: Build run: ./y.rs build --sysroot none - name: Test - run: | - # Enable backtraces for easier debugging - export RUST_BACKTRACE=1 - - # Reduce amount of benchmark runs as they are slow - export COMPILE_RUNS=2 - export RUN_RUNS=2 - - # Enable extra checks - export CG_CLIF_ENABLE_VERIFIER=1 - - ./test.sh + run: ./test.sh diff --git a/.github/workflows/rustc.yml b/.github/workflows/rustc.yml index af34e10c7596d..bab81b9dc2a81 100644 --- a/.github/workflows/rustc.yml +++ b/.github/workflows/rustc.yml @@ -37,14 +37,7 @@ jobs: ./y.rs prepare - name: Test - run: | - # Enable backtraces for easier debugging - export RUST_BACKTRACE=1 - - # Enable extra checks - export CG_CLIF_ENABLE_VERIFIER=1 - - ./scripts/test_bootstrap.sh + run: ./scripts/test_bootstrap.sh rustc_test_suite: runs-on: ubuntu-latest @@ -78,11 +71,4 @@ jobs: ./y.rs prepare - name: Test - run: | - # Enable backtraces for easier debugging - export RUST_BACKTRACE=1 - - # Enable extra checks - export CG_CLIF_ENABLE_VERIFIER=1 - - ./scripts/test_rustc_tests.sh + run: ./scripts/test_rustc_tests.sh diff --git a/build_system/mod.rs b/build_system/mod.rs index 1afc9a55c73b5..2f311aed7c8db 100644 --- a/build_system/mod.rs +++ b/build_system/mod.rs @@ -64,12 +64,18 @@ pub(crate) enum SysrootKind { } pub fn main() { + if env::var("RUST_BACKTRACE").is_err() { + env::set_var("RUST_BACKTRACE", "1"); + } env::set_var("CG_CLIF_DISPLAY_CG_TIME", "1"); env::set_var("CG_CLIF_DISABLE_INCR_CACHE", "1"); if is_ci() { // Disabling incr comp reduces cache size and incr comp doesn't save as much on CI anyway env::set_var("CARGO_BUILD_INCREMENTAL", "false"); + + // Enable the Cranelift verifier + env::set_var("CG_CLIF_ENABLE_VERIFIER", "1"); } let mut args = env::args().skip(1); diff --git a/build_system/tests.rs b/build_system/tests.rs index 738a76ef4c55a..81993b9d337dd 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -4,7 +4,7 @@ use super::path::{Dirs, RelPath}; use super::prepare::GitRepo; use super::rustc_info::get_wrapper_file_name; use super::utils::{ - hyperfine_command, spawn_and_wait, spawn_and_wait_with_input, CargoProject, Compiler, + hyperfine_command, is_ci, spawn_and_wait, spawn_and_wait_with_input, CargoProject, Compiler, }; use super::SysrootKind; use std::env; @@ -281,7 +281,10 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ } }), TestCase::new("bench.simple-raytracer", &|runner| { - let run_runs = env::var("RUN_RUNS").unwrap_or("10".to_string()).parse().unwrap(); + let run_runs = env::var("RUN_RUNS") + .unwrap_or(if is_ci() { "2" } else { "10" }.to_string()) + .parse() + .unwrap(); if runner.is_native { eprintln!("[BENCH COMPILE] ebobby/simple-raytracer"); From 6c88b08adcda8761e91c17d3b3bee9b7b36c9a8c Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 15:09:17 +0000 Subject: [PATCH 071/500] Fix some build steps on Windows --- .github/workflows/main.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 3492df72720bc..3f9e779dfc164 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -177,10 +177,10 @@ jobs: env: TARGET_TRIPLE: ${{ matrix.env.TARGET_TRIPLE }} # This is the config rust-lang/rust uses for builds - run: ./y.rs build --no-unstable-features + run: ./y.exe build --no-unstable-features - name: Build - run: ./y.rs build --sysroot none + run: ./y.exe build --sysroot none - name: Test run: | From 1ca07b9a44a6de9c769a66ed98a5b165a42aee15 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 14:16:39 +0000 Subject: [PATCH 072/500] Fix running simple-raytracer benchmark on Windows --- .github/workflows/main.yml | 4 ---- build_system/tests.rs | 17 ++++++++++++----- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 3f9e779dfc164..d181bd1604e02 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -186,10 +186,6 @@ jobs: run: | # WIP Disable some tests - # This fails due to some weird argument handling by hyperfine, not an actual regression - # more of a build system issue - (Get-Content config.txt) -replace '(bench.simple-raytracer)', '# $1' | Out-File config.txt - # This fails with a different output than expected (Get-Content config.txt) -replace '(test.regex-shootout-regex-dna)', '# $1' | Out-File config.txt diff --git a/build_system/tests.rs b/build_system/tests.rs index 81993b9d337dd..37c35106af6d3 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -2,7 +2,7 @@ use super::build_sysroot; use super::config; use super::path::{Dirs, RelPath}; use super::prepare::GitRepo; -use super::rustc_info::get_wrapper_file_name; +use super::rustc_info::{get_file_name, get_wrapper_file_name}; use super::utils::{ hyperfine_command, is_ci, spawn_and_wait, spawn_and_wait_with_input, CargoProject, Compiler, }; @@ -318,13 +318,20 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ eprintln!("[BENCH RUN] ebobby/simple-raytracer"); fs::copy( - target_dir.join("debug").join("main"), - RelPath::BUILD.to_path(&runner.dirs).join("raytracer_cg_clif"), + target_dir.join("debug").join(get_file_name("main", "bin")), + RelPath::BUILD + .to_path(&runner.dirs) + .join(get_file_name("raytracer_cg_clif", "bin")), ) .unwrap(); - let mut bench_run = - hyperfine_command(0, run_runs, None, "./raytracer_cg_llvm", "./raytracer_cg_clif"); + let mut bench_run = hyperfine_command( + 0, + run_runs, + None, + Path::new(".").join(get_file_name("raytracer_cg_llvm", "bin")).to_str().unwrap(), + Path::new(".").join(get_file_name("raytracer_cg_clif", "bin")).to_str().unwrap(), + ); bench_run.current_dir(RelPath::BUILD.to_path(&runner.dirs)); spawn_and_wait(bench_run); } else { From 280fb2935b2bc4f4eb56671d21d7bc2b36faa81e Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 17:30:18 +0000 Subject: [PATCH 073/500] Start running regex-shootout-regex-dna on Windows again --- .github/workflows/main.yml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index d181bd1604e02..e381f7e6adaab 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -183,13 +183,7 @@ jobs: run: ./y.exe build --sysroot none - name: Test - run: | - # WIP Disable some tests - - # This fails with a different output than expected - (Get-Content config.txt) -replace '(test.regex-shootout-regex-dna)', '# $1' | Out-File config.txt - - ./y.exe test + run: ./y.exe test - name: Package prebuilt cg_clif # don't use compression as xzip isn't supported by tar on windows and bzip2 hangs From e735206f50af9754ab21171e4472cfbe1eecd92f Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 15 Dec 2022 17:58:27 +0000 Subject: [PATCH 074/500] Unify Windows and non-Windows CI --- .github/workflows/main.yml | 102 +++++++++---------------------------- 1 file changed, 25 insertions(+), 77 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index e381f7e6adaab..b79406879ff32 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -25,6 +25,10 @@ jobs: runs-on: ${{ matrix.os }} timeout-minutes: 60 + defaults: + run: + shell: bash + strategy: fail-fast: false matrix: @@ -46,6 +50,14 @@ jobs: - os: ubuntu-latest env: TARGET_TRIPLE: s390x-unknown-linux-gnu + # Native Windows build with MSVC + - os: windows-latest + env: + TARGET_TRIPLE: x86_64-pc-windows-msvc + # cross-compile from Windows to Windows MinGW + - os: windows-latest + env: + TARGET_TRIPLE: x86_64-pc-windows-gnu steps: - uses: actions/checkout@v3 @@ -54,7 +66,7 @@ jobs: uses: actions/cache@v3 with: path: ~/.cargo/bin - key: ${{ runner.os }}-cargo-installed-crates + key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-installed-crates - name: Cache cargo registry and index uses: actions/cache@v3 @@ -62,13 +74,17 @@ jobs: path: | ~/.cargo/registry ~/.cargo/git - key: ${{ runner.os }}-cargo-registry-and-index-${{ hashFiles('**/Cargo.lock') }} + key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-registry-and-index-${{ hashFiles('**/Cargo.lock') }} - name: Cache cargo target dir uses: actions/cache@v3 with: path: build/cg_clif - key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }} + key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }} + + - name: Set MinGW as the default toolchain + if: matrix.os == 'windows-latest' && matrix.env.TARGET_TRIPLE == 'x86_64-pc-windows-gnu' + run: rustup set default-host x86_64-pc-windows-gnu - name: Install MinGW toolchain and wine if: matrix.os == 'ubuntu-latest' && matrix.env.TARGET_TRIPLE == 'x86_64-pc-windows-gnu' @@ -89,6 +105,10 @@ jobs: sudo apt-get update sudo apt-get install -y gcc-s390x-linux-gnu qemu-user + - name: Windows setup + if: matrix.os == 'windows-latest' + run: git config --global core.autocrlf false + - name: Prepare dependencies run: ./y.rs prepare @@ -110,87 +130,15 @@ jobs: run: tar cvfJ cg_clif.tar.xz dist - name: Upload prebuilt cg_clif - if: matrix.env.TARGET_TRIPLE != 'x86_64-pc-windows-gnu' + if: matrix.os == 'windows-latest' || matrix.env.TARGET_TRIPLE != 'x86_64-pc-windows-gnu' uses: actions/upload-artifact@v3 with: name: cg_clif-${{ matrix.env.TARGET_TRIPLE }} path: cg_clif.tar.xz - name: Upload prebuilt cg_clif (cross compile) - if: matrix.env.TARGET_TRIPLE == 'x86_64-pc-windows-gnu' + if: matrix.os != 'windows-latest' && matrix.env.TARGET_TRIPLE == 'x86_64-pc-windows-gnu' uses: actions/upload-artifact@v3 with: name: cg_clif-${{ runner.os }}-cross-x86_64-mingw path: cg_clif.tar.xz - - windows: - runs-on: ${{ matrix.os }} - timeout-minutes: 60 - - strategy: - fail-fast: false - matrix: - include: - # Native Windows build with MSVC - - os: windows-latest - env: - TARGET_TRIPLE: x86_64-pc-windows-msvc - # cross-compile from Windows to Windows MinGW - - os: windows-latest - env: - TARGET_TRIPLE: x86_64-pc-windows-gnu - - steps: - - uses: actions/checkout@v3 - - - name: Cache cargo installed crates - uses: actions/cache@v3 - with: - path: ~/.cargo/bin - key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-installed-crates - - - name: Cache cargo registry and index - uses: actions/cache@v3 - with: - path: | - ~/.cargo/registry - ~/.cargo/git - key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-registry-and-index-${{ hashFiles('**/Cargo.lock') }} - - - name: Cache cargo target dir - uses: actions/cache@v3 - with: - path: build/cg_clif - key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }} - - - name: Set MinGW as the default toolchain - if: matrix.env.TARGET_TRIPLE == 'x86_64-pc-windows-gnu' - run: rustup set default-host x86_64-pc-windows-gnu - - - name: Prepare dependencies - run: | - git config --global core.autocrlf false - rustc y.rs -o y.exe -g - ./y.exe prepare - - - name: Build without unstable features - env: - TARGET_TRIPLE: ${{ matrix.env.TARGET_TRIPLE }} - # This is the config rust-lang/rust uses for builds - run: ./y.exe build --no-unstable-features - - - name: Build - run: ./y.exe build --sysroot none - - - name: Test - run: ./y.exe test - - - name: Package prebuilt cg_clif - # don't use compression as xzip isn't supported by tar on windows and bzip2 hangs - run: tar cvf cg_clif.tar dist - - - name: Upload prebuilt cg_clif - uses: actions/upload-artifact@v3 - with: - name: cg_clif-${{ matrix.env.TARGET_TRIPLE }} - path: cg_clif.tar From 9ca82a9a3d987985aea5c87b3d4d1546cb5d04c9 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 16 Dec 2022 09:41:36 +0000 Subject: [PATCH 075/500] Fix ICE on unsized locals Fixes #1312 --- src/abi/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/abi/mod.rs b/src/abi/mod.rs index 65cc6b4376713..416bce4849824 100644 --- a/src/abi/mod.rs +++ b/src/abi/mod.rs @@ -161,6 +161,12 @@ fn make_local_place<'tcx>( layout: TyAndLayout<'tcx>, is_ssa: bool, ) -> CPlace<'tcx> { + if layout.is_unsized() { + fx.tcx.sess.span_fatal( + fx.mir.local_decls[local].source_info.span, + "unsized locals are not yet supported", + ); + } let place = if is_ssa { if let rustc_target::abi::Abi::ScalarPair(_, _) = layout.abi { CPlace::new_var_pair(fx, local, layout) From b5ac64b4cf33809b182a6f7c63a7c4e874fb3056 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 16 Dec 2022 09:44:28 +0000 Subject: [PATCH 076/500] Don't PrintOnPanic on fatal errors --- src/base.rs | 11 ++++++----- src/driver/mod.rs | 3 ++- src/lib.rs | 8 ++++---- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/base.rs b/src/base.rs index 89d955e8bf2e1..7df11cf4aede1 100644 --- a/src/base.rs +++ b/src/base.rs @@ -29,8 +29,9 @@ pub(crate) fn codegen_and_compile_fn<'tcx>( module: &mut dyn Module, instance: Instance<'tcx>, ) { - let _inst_guard = - crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name)); + let _inst_guard = crate::PrintOnPanic(Some(tcx.sess), || { + format!("{:?} {}", instance, tcx.symbol_name(instance).name) + }); let cached_func = std::mem::replace(&mut cached_context.func, Function::new()); let codegened_func = codegen_fn(tcx, cx, cached_func, module, instance); @@ -48,7 +49,7 @@ pub(crate) fn codegen_fn<'tcx>( debug_assert!(!instance.substs.needs_infer()); let mir = tcx.instance_mir(instance.def); - let _mir_guard = crate::PrintOnPanic(|| { + let _mir_guard = crate::PrintOnPanic(Some(tcx.sess), || { let mut buf = Vec::new(); with_no_trimmed_paths!({ rustc_middle::mir::pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut buf) @@ -176,7 +177,7 @@ pub(crate) fn compile_fn( write!(clif, " {}", isa_flag).unwrap(); } writeln!(clif, "\n").unwrap(); - crate::PrintOnPanic(move || { + crate::PrintOnPanic(None, move || { let mut clif = clif.clone(); ::cranelift_codegen::write::decorate_function( &mut &clif_comments_clone, @@ -497,7 +498,7 @@ fn codegen_stmt<'tcx>( #[allow(unused_variables)] cur_block: Block, stmt: &Statement<'tcx>, ) { - let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt)); + let _print_guard = crate::PrintOnPanic(Some(fx.tcx.sess), || format!("stmt {:?}", stmt)); fx.set_debug_loc(stmt.source_info); diff --git a/src/driver/mod.rs b/src/driver/mod.rs index 6e925cea27707..1ab4fdf61551b 100644 --- a/src/driver/mod.rs +++ b/src/driver/mod.rs @@ -23,7 +23,8 @@ fn predefine_mono_items<'tcx>( match mono_item { MonoItem::Fn(instance) => { let name = tcx.symbol_name(instance).name; - let _inst_guard = crate::PrintOnPanic(|| format!("{:?} {}", instance, name)); + let _inst_guard = + crate::PrintOnPanic(Some(tcx.sess), || format!("{:?} {}", instance, name)); let sig = get_function_sig(tcx, module.target_config().default_call_conv, instance); let linkage = crate::linkage::get_clif_linkage( diff --git a/src/lib.rs b/src/lib.rs index 629d79d501240..49b5dc32144d2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -113,11 +113,11 @@ mod prelude { pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue}; } -struct PrintOnPanic String>(F); -impl String> Drop for PrintOnPanic { +struct PrintOnPanic<'a, F: Fn() -> String>(Option<&'a Session>, F); +impl<'a, F: Fn() -> String> Drop for PrintOnPanic<'a, F> { fn drop(&mut self) { - if ::std::thread::panicking() { - println!("{}", (self.0)()); + if ::std::thread::panicking() && self.0.map_or(true, |sess| sess.has_errors().is_none()) { + println!("{}", (self.1)()); } } } From ec92c3e5dca69cf0ed02d11fb7a3bfae9f41c0ca Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 16 Dec 2022 09:55:27 +0000 Subject: [PATCH 077/500] Fix ICE on incompatible declarations of entry symbol Fixes #1313 --- src/main_shim.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/main_shim.rs b/src/main_shim.rs index c10054e7f0d2c..556d7b8e51a67 100644 --- a/src/main_shim.rs +++ b/src/main_shim.rs @@ -70,7 +70,13 @@ pub(crate) fn maybe_create_entry_wrapper( }; let entry_name = tcx.sess.target.options.entry_name.as_ref(); - let cmain_func_id = m.declare_function(entry_name, Linkage::Export, &cmain_sig).unwrap(); + let cmain_func_id = match m.declare_function(entry_name, Linkage::Export, &cmain_sig) { + Ok(func_id) => func_id, + Err(err) => { + tcx.sess + .fatal(&format!("entry symbol `{entry_name}` declared multiple times: {err}")); + } + }; let instance = Instance::mono(tcx, rust_main_def_id).polymorphize(tcx); @@ -162,7 +168,11 @@ pub(crate) fn maybe_create_entry_wrapper( bcx.seal_all_blocks(); bcx.finalize(); } - m.define_function(cmain_func_id, &mut ctx).unwrap(); + + if let Err(err) = m.define_function(cmain_func_id, &mut ctx) { + tcx.sess.fatal(&format!("entry symbol `{entry_name}` defined multiple times: {err}")); + } + unwind_context.add_function(cmain_func_id, &ctx, m.isa()); } } From 91655428f905b35c4a14d38562113eb768252fdf Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 16 Dec 2022 10:04:40 +0000 Subject: [PATCH 078/500] Ensure Cranelift errors are reported deterministically This may also have been the root cause of #1310. --- src/driver/aot.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/driver/aot.rs b/src/driver/aot.rs index 27cce7c15e1f7..d4494a9e45de4 100644 --- a/src/driver/aot.rs +++ b/src/driver/aot.rs @@ -108,6 +108,8 @@ impl OngoingCodegen { self.concurrency_limiter.finished(); + sess.abort_if_errors(); + ( CodegenResults { modules, @@ -411,8 +413,6 @@ pub(crate) fn run_aot( .collect::>() }); - tcx.sess.abort_if_errors(); - let mut allocator_module = make_module(tcx.sess, &backend_config, "allocator_shim".to_string()); let mut allocator_unwind_context = UnwindContext::new(allocator_module.isa(), true); let created_alloc_shim = From 14ca1df478ac9c0a7899530eb581362f37519ad3 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 16 Dec 2022 10:38:46 +0000 Subject: [PATCH 079/500] Enable debug assertions on CI Fixes #1314 --- build_system/build_backend.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/build_system/build_backend.rs b/build_system/build_backend.rs index fde8ef424ccc5..16b43c5fc852f 100644 --- a/build_system/build_backend.rs +++ b/build_system/build_backend.rs @@ -25,6 +25,8 @@ pub(crate) fn build_backend( // Disabling incr comp reduces cache size and incr comp doesn't save as much on CI anyway cmd.env("CARGO_BUILD_INCREMENTAL", "false"); + + cmd.env("CARGO_PROFILE_RELEASE_DEBUG_ASSERTIONS", "true"); } if use_unstable_features { From ab0e2aaed2098cecf5eb9e2c2ee196e794d79db9 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 16 Dec 2022 13:00:36 +0000 Subject: [PATCH 080/500] Revert "Don't PrintOnPanic on fatal errors" This reverts commit b5ac64b4cf33809b182a6f7c63a7c4e874fb3056. It entirely breaks PrintOnPanic as ICE seems to be considered a fatal error too. --- src/base.rs | 11 +++++------ src/driver/mod.rs | 3 +-- src/lib.rs | 8 ++++---- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/base.rs b/src/base.rs index 7df11cf4aede1..89d955e8bf2e1 100644 --- a/src/base.rs +++ b/src/base.rs @@ -29,9 +29,8 @@ pub(crate) fn codegen_and_compile_fn<'tcx>( module: &mut dyn Module, instance: Instance<'tcx>, ) { - let _inst_guard = crate::PrintOnPanic(Some(tcx.sess), || { - format!("{:?} {}", instance, tcx.symbol_name(instance).name) - }); + let _inst_guard = + crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name)); let cached_func = std::mem::replace(&mut cached_context.func, Function::new()); let codegened_func = codegen_fn(tcx, cx, cached_func, module, instance); @@ -49,7 +48,7 @@ pub(crate) fn codegen_fn<'tcx>( debug_assert!(!instance.substs.needs_infer()); let mir = tcx.instance_mir(instance.def); - let _mir_guard = crate::PrintOnPanic(Some(tcx.sess), || { + let _mir_guard = crate::PrintOnPanic(|| { let mut buf = Vec::new(); with_no_trimmed_paths!({ rustc_middle::mir::pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut buf) @@ -177,7 +176,7 @@ pub(crate) fn compile_fn( write!(clif, " {}", isa_flag).unwrap(); } writeln!(clif, "\n").unwrap(); - crate::PrintOnPanic(None, move || { + crate::PrintOnPanic(move || { let mut clif = clif.clone(); ::cranelift_codegen::write::decorate_function( &mut &clif_comments_clone, @@ -498,7 +497,7 @@ fn codegen_stmt<'tcx>( #[allow(unused_variables)] cur_block: Block, stmt: &Statement<'tcx>, ) { - let _print_guard = crate::PrintOnPanic(Some(fx.tcx.sess), || format!("stmt {:?}", stmt)); + let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt)); fx.set_debug_loc(stmt.source_info); diff --git a/src/driver/mod.rs b/src/driver/mod.rs index 1ab4fdf61551b..6e925cea27707 100644 --- a/src/driver/mod.rs +++ b/src/driver/mod.rs @@ -23,8 +23,7 @@ fn predefine_mono_items<'tcx>( match mono_item { MonoItem::Fn(instance) => { let name = tcx.symbol_name(instance).name; - let _inst_guard = - crate::PrintOnPanic(Some(tcx.sess), || format!("{:?} {}", instance, name)); + let _inst_guard = crate::PrintOnPanic(|| format!("{:?} {}", instance, name)); let sig = get_function_sig(tcx, module.target_config().default_call_conv, instance); let linkage = crate::linkage::get_clif_linkage( diff --git a/src/lib.rs b/src/lib.rs index 49b5dc32144d2..629d79d501240 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -113,11 +113,11 @@ mod prelude { pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue}; } -struct PrintOnPanic<'a, F: Fn() -> String>(Option<&'a Session>, F); -impl<'a, F: Fn() -> String> Drop for PrintOnPanic<'a, F> { +struct PrintOnPanic String>(F); +impl String> Drop for PrintOnPanic { fn drop(&mut self) { - if ::std::thread::panicking() && self.0.map_or(true, |sess| sess.has_errors().is_none()) { - println!("{}", (self.1)()); + if ::std::thread::panicking() { + println!("{}", (self.0)()); } } } From 1c724ee6d0e1023a5cd9b8b5c0bf324b45d429c5 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 16 Dec 2022 13:29:26 +0000 Subject: [PATCH 081/500] Re-enable some rustc tests --- scripts/test_rustc_tests.sh | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/scripts/test_rustc_tests.sh b/scripts/test_rustc_tests.sh index 04ad77ec97eac..b3d6dae515359 100755 --- a/scripts/test_rustc_tests.sh +++ b/scripts/test_rustc_tests.sh @@ -37,15 +37,7 @@ rm -r src/test/run-make/test-benches rm src/test/ui/sse2.rs # cpuid not supported, so sse2 not detected rm src/test/ui/intrinsics/const-eval-select-x86_64.rs # requires x86_64 vendor intrinsics rm src/test/ui/simd/array-type.rs # "Index argument for `simd_insert` is not a constant" -rm src/test/ui/simd/intrinsic/generic-bitmask-pass.rs # simd_bitmask unimplemented -rm src/test/ui/simd/intrinsic/generic-as.rs # simd_as unimplemented -rm src/test/ui/simd/intrinsic/generic-arithmetic-saturating-pass.rs # simd_saturating_add unimplemented rm src/test/ui/simd/intrinsic/float-math-pass.rs # simd_fcos unimplemented -rm src/test/ui/simd/intrinsic/generic-gather-pass.rs # simd_gather unimplemented -rm src/test/ui/simd/intrinsic/generic-select-pass.rs # simd_select_bitmask unimplemented -rm src/test/ui/simd/issue-85915-simd-ptrs.rs # simd_gather unimplemented -rm src/test/ui/simd/issue-89193.rs # simd_gather unimplemented -rm src/test/ui/simd/simd-bitmask.rs # simd_bitmask unimplemented # exotic linkages rm src/test/ui/issues/issue-33992.rs # unsupported linkages @@ -102,13 +94,11 @@ rm -r src/test/ui/consts/missing_span_in_backtrace.rs # expects sysroot source t # ============ rm src/test/incremental/spike-neg1.rs # errors out for some reason rm src/test/incremental/spike-neg2.rs # same -rm src/test/ui/issues/issue-74564-if-expr-stack-overflow.rs # gives a stackoverflow before the backend runs -rm src/test/ui/mir/ssa-analysis-regression-50041.rs # produces ICE -rm src/test/ui/type-alias-impl-trait/assoc-projection-ice.rs # produces ICE rm src/test/ui/simd/intrinsic/generic-reduction-pass.rs # simd_reduce_add_unordered doesn't accept an accumulator for integer vectors -rm src/test/ui/runtime/out-of-stack.rs # SIGSEGV instead of SIGABRT for some reason (#1301) +rm src/test/ui/simd/intrinsic/generic-as.rs # crash when accessing vector type filed (#1318) +rm src/test/ui/simd/simd-bitmask.rs # crash # bugs in the test suite # ====================== From dffa6acf731c6019a39d0175e242b821a3423915 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 16 Dec 2022 14:15:59 +0000 Subject: [PATCH 082/500] Fix crash after simd type validation error Fixes part of #1319 --- src/intrinsics/mod.rs | 3 +-- src/intrinsics/simd.rs | 12 ++++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/intrinsics/mod.rs b/src/intrinsics/mod.rs index 7a380acf79857..548a6bf45842b 100644 --- a/src/intrinsics/mod.rs +++ b/src/intrinsics/mod.rs @@ -240,10 +240,9 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( substs, args, destination, + target, source_info.span, ); - let ret_block = fx.get_block(target); - fx.bcx.ins().jump(ret_block, &[]); } else if codegen_float_intrinsic_call(fx, intrinsic, args, destination) { let ret_block = fx.get_block(target); fx.bcx.ins().jump(ret_block, &[]); diff --git a/src/intrinsics/simd.rs b/src/intrinsics/simd.rs index 62ea2214ab44e..791ff5cfcf3c6 100644 --- a/src/intrinsics/simd.rs +++ b/src/intrinsics/simd.rs @@ -24,6 +24,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( _substs: SubstsRef<'tcx>, args: &[mir::Operand<'tcx>], ret: CPlace<'tcx>, + target: BasicBlock, span: Span, ) { match intrinsic { @@ -277,16 +278,15 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( } else { fx.tcx.sess.span_warn(span, "Index argument for `simd_extract` is not a constant"); let trap_block = fx.bcx.create_block(); - let dummy_block = fx.bcx.create_block(); let true_ = fx.bcx.ins().iconst(types::I8, 1); fx.bcx.ins().brnz(true_, trap_block, &[]); - fx.bcx.ins().jump(dummy_block, &[]); + let ret_block = fx.get_block(target); + fx.bcx.ins().jump(ret_block, &[]); fx.bcx.switch_to_block(trap_block); crate::trap::trap_unimplemented( fx, "Index argument for `simd_extract` is not a constant", ); - fx.bcx.switch_to_block(dummy_block); return; }; @@ -876,7 +876,11 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( } _ => { - fx.tcx.sess.span_fatal(span, &format!("Unknown SIMD intrinsic {}", intrinsic)); + fx.tcx.sess.span_err(span, &format!("Unknown SIMD intrinsic {}", intrinsic)); + // Prevent verifier error + fx.bcx.ins().trap(TrapCode::UnreachableCodeReached); } } + let ret_block = fx.get_block(target); + fx.bcx.ins().jump(ret_block, &[]); } From ee05e4d5ab76a94f46705e9afb01357d138fd519 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 16 Dec 2022 15:41:52 +0000 Subject: [PATCH 083/500] Don't ICE on unimplemented call convs --- src/abi/mod.rs | 27 +++++++++++++++++---------- src/main_shim.rs | 1 + 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/abi/mod.rs b/src/abi/mod.rs index 416bce4849824..90ec8ec3685e3 100644 --- a/src/abi/mod.rs +++ b/src/abi/mod.rs @@ -7,6 +7,7 @@ mod returning; use cranelift_module::ModuleError; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::ty::layout::FnAbiOf; +use rustc_session::Session; use rustc_target::abi::call::{Conv, FnAbi}; use rustc_target::spec::abi::Abi; @@ -22,7 +23,7 @@ fn clif_sig_from_fn_abi<'tcx>( default_call_conv: CallConv, fn_abi: &FnAbi<'tcx, Ty<'tcx>>, ) -> Signature { - let call_conv = conv_to_call_conv(fn_abi.conv, default_call_conv); + let call_conv = conv_to_call_conv(tcx.sess, fn_abi.conv, default_call_conv); let inputs = fn_abi.args.iter().map(|arg_abi| arg_abi.get_abi_param(tcx).into_iter()).flatten(); @@ -33,24 +34,30 @@ fn clif_sig_from_fn_abi<'tcx>( Signature { params, returns, call_conv } } -pub(crate) fn conv_to_call_conv(c: Conv, default_call_conv: CallConv) -> CallConv { +pub(crate) fn conv_to_call_conv(sess: &Session, c: Conv, default_call_conv: CallConv) -> CallConv { match c { Conv::Rust | Conv::C => default_call_conv, Conv::RustCold => CallConv::Cold, Conv::X86_64SysV => CallConv::SystemV, Conv::X86_64Win64 => CallConv::WindowsFastcall, - Conv::ArmAapcs - | Conv::CCmseNonSecureCall + + // Should already get a back compat warning + Conv::X86Fastcall | Conv::X86Stdcall | Conv::X86ThisCall | Conv::X86VectorCall => { + default_call_conv + } + + Conv::X86Intr => sess.fatal("x86-interrupt call conv not yet implemented"), + + Conv::ArmAapcs => sess.fatal("aapcs call conv not yet implemented"), + + Conv::CCmseNonSecureCall | Conv::Msp430Intr | Conv::PtxKernel - | Conv::X86Fastcall - | Conv::X86Intr - | Conv::X86Stdcall - | Conv::X86ThisCall - | Conv::X86VectorCall | Conv::AmdGpuKernel | Conv::AvrInterrupt - | Conv::AvrNonBlockingInterrupt => todo!("{:?}", c), + | Conv::AvrNonBlockingInterrupt => { + unreachable!("tried to use {c:?} call conv which only exists on an unsupported target"); + } } } diff --git a/src/main_shim.rs b/src/main_shim.rs index 556d7b8e51a67..fd45362548c0d 100644 --- a/src/main_shim.rs +++ b/src/main_shim.rs @@ -64,6 +64,7 @@ pub(crate) fn maybe_create_entry_wrapper( ], returns: vec![AbiParam::new(m.target_config().pointer_type() /*isize*/)], call_conv: crate::conv_to_call_conv( + tcx.sess, tcx.sess.target.options.entry_abi, m.target_config().default_call_conv, ), From 8b478012086f4df5c21e4ec0016631fac163133f Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 16 Dec 2022 15:45:07 +0000 Subject: [PATCH 084/500] Don't ICE on C-cmse-nonsecure-call either --- src/abi/mod.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/abi/mod.rs b/src/abi/mod.rs index 90ec8ec3685e3..3c34585d4191e 100644 --- a/src/abi/mod.rs +++ b/src/abi/mod.rs @@ -49,9 +49,11 @@ pub(crate) fn conv_to_call_conv(sess: &Session, c: Conv, default_call_conv: Call Conv::X86Intr => sess.fatal("x86-interrupt call conv not yet implemented"), Conv::ArmAapcs => sess.fatal("aapcs call conv not yet implemented"), + Conv::CCmseNonSecureCall => { + sess.fatal("C-cmse-nonsecure-call call conv is not yet implemented"); + } - Conv::CCmseNonSecureCall - | Conv::Msp430Intr + Conv::Msp430Intr | Conv::PtxKernel | Conv::AmdGpuKernel | Conv::AvrInterrupt From debd45cc7be97c8a7c50c2822593471d04d87366 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Tue, 13 Dec 2022 18:34:08 +0100 Subject: [PATCH 085/500] Update to cranelift 0.91 Closes #1307 --- Cargo.lock | 94 ++++++++++++++++++++++---------------- Cargo.toml | 12 ++--- src/base.rs | 5 +- src/common.rs | 9 ++++ src/intrinsics/llvm_x86.rs | 4 +- src/intrinsics/mod.rs | 2 +- src/value_and_place.rs | 4 +- 7 files changed, 76 insertions(+), 54 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e4d3e9ca5ae0a..3bc2bf31d666d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -57,18 +57,18 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cranelift-bforest" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b62c772976416112fa4484cbd688cb6fb35fd430005c1c586224fc014018abad" +checksum = "fc952b310b24444fc14ab8b9cbe3fafd7e7329e3eec84c3a9b11d2b5cf6f3be1" dependencies = [ "cranelift-entity", ] [[package]] name = "cranelift-codegen" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b40ed2dd13c2ac7e24f88a3090c68ad3414eb1d066a95f8f1f7b3b819cb4e46" +checksum = "e73470419b33011e50dbf0f6439cbccbaabe9381de172da4e1b6efcda4bb8fa7" dependencies = [ "arrayvec", "bumpalo", @@ -87,24 +87,24 @@ dependencies = [ [[package]] name = "cranelift-codegen-meta" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb927a8f1c27c34ee3759b6b0ffa528d2330405d5cc4511f0cab33fe2279f4b5" +checksum = "911a1872464108a11ac9965c2b079e61bbdf1bc2e0b9001264264add2e12a38f" dependencies = [ "cranelift-codegen-shared", ] [[package]] name = "cranelift-codegen-shared" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43dfa417b884a9ab488d95fd6b93b25e959321fe7bfd7a0a960ba5d7fb7ab927" +checksum = "e036f3f07adb24a86fb46e977e8fe03b18bb16b1eada949cf2c48283e5f8a862" [[package]] name = "cranelift-egraph" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0a66b39785efd8513d2cca967ede56d6cc57c8d7986a595c7c47d0c78de8dce" +checksum = "2d6c623f4b5d2a6bad32c403f03765d4484a827eb93ee78f8cb6219ef118fd59" dependencies = [ "cranelift-entity", "fxhash", @@ -116,15 +116,15 @@ dependencies = [ [[package]] name = "cranelift-entity" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0637ffde963cb5d759bc4d454cfa364b6509e6c74cdaa21298add0ed9276f346" +checksum = "74385eb5e405b3562f0caa7bcc4ab9a93c7958dd5bcd0e910bffb7765eacd6fc" [[package]] name = "cranelift-frontend" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb72b8342685e850cb037350418f62cc4fc55d6c2eb9c7ca01b82f9f1a6f3d56" +checksum = "8a4ac920422ee36bff2c66257fec861765e3d95a125cdf58d8c0f3bba7e40e61" dependencies = [ "cranelift-codegen", "log", @@ -134,15 +134,15 @@ dependencies = [ [[package]] name = "cranelift-isle" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "850579cb9e4b448f7c301f1e6e6cbad99abe3f1f1d878a4994cb66e33c6db8cd" +checksum = "c541263fb37ad2baa53ec8c37218ee5d02fa0984670d9419dedd8002ea68ff08" [[package]] name = "cranelift-jit" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9add822ad66dcbe152b5ab57de10240a2df4505099f2f6c27159acb711890bd4" +checksum = "48a844e3500d313b69f3eec4b4e15bf9cdbd529756add06a468e0e281c0f6bee" dependencies = [ "anyhow", "cranelift-codegen", @@ -159,9 +159,9 @@ dependencies = [ [[package]] name = "cranelift-module" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "406b772626fc2664864cf947f3895a23b619895c7fff635f3622e2d857f4492f" +checksum = "0699ea5fc6ca943456ba80ad49f80212bd6e2b846b992ec59f0f2b912a1d25fa" dependencies = [ "anyhow", "cranelift-codegen", @@ -169,9 +169,9 @@ dependencies = [ [[package]] name = "cranelift-native" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d0a279e5bcba3e0466c734d8d8eb6bfc1ad29e95c37f3e4955b492b5616335e" +checksum = "1de5d7a063e8563d670aaca38de16591a9b70dc66cbad4d49a7b4ae8395fd1ce" dependencies = [ "cranelift-codegen", "libc", @@ -180,9 +180,9 @@ dependencies = [ [[package]] name = "cranelift-object" -version = "0.90.1" +version = "0.91.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39793c550f0c1d7db96c2fc1324583670c8143befe6edbfbaf1c68aba53be983" +checksum = "307735148f6a556388aabf1ea31f46ccd378ed0739f3e9bdda2029639d701ab7" dependencies = [ "anyhow", "cranelift-codegen", @@ -317,9 +317,9 @@ checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" [[package]] name = "regalloc2" -version = "0.4.2" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91b2eab54204ea0117fe9a060537e0b07a4e72f7c7d182361ecc346cab2240e5" +checksum = "300d4fbfb40c1c66a78ba3ddd41c1110247cf52f97b87d0f2fc9209bd49b030c" dependencies = [ "fxhash", "log", @@ -396,9 +396,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasmtime-jit-icache-coherence" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6bbabb309c06cc238ee91b1455b748c45f0bdcab0dda2c2db85b0a1e69fcb66" +checksum = "22d9c2e92b0fc124d2cad6cb497a4c840580a7dd2414a37109e8c7cfe699c0ea" dependencies = [ "cfg-if", "libc", @@ -429,43 +429,57 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" -version = "0.36.1" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" +checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" dependencies = [ + "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_msvc", "windows_x86_64_gnu", + "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e" + [[package]] name = "windows_aarch64_msvc" -version = "0.36.1" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" +checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4" [[package]] name = "windows_i686_gnu" -version = "0.36.1" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" +checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7" [[package]] name = "windows_i686_msvc" -version = "0.36.1" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" +checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246" [[package]] name = "windows_x86_64_gnu" -version = "0.36.1" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" +checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028" [[package]] name = "windows_x86_64_msvc" -version = "0.36.1" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" +checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" diff --git a/Cargo.toml b/Cargo.toml index 2b216ca072f00..f03cc34a81081 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,12 +15,12 @@ crate-type = ["dylib"] [dependencies] # These have to be in sync with each other -cranelift-codegen = { version = "0.90.1", features = ["unwind", "all-arch"] } -cranelift-frontend = "0.90.1" -cranelift-module = "0.90.1" -cranelift-native = "0.90.1" -cranelift-jit = { version = "0.90.1", optional = true } -cranelift-object = "0.90.1" +cranelift-codegen = { version = "0.91", features = ["unwind", "all-arch"] } +cranelift-frontend = "0.91" +cranelift-module = "0.91" +cranelift-native = "0.91" +cranelift-jit = { version = "0.91", optional = true } +cranelift-object = "0.91" target-lexicon = "0.12.0" gimli = { version = "0.26.0", default-features = false, features = ["write"]} object = { version = "0.29.0", default-features = false, features = ["std", "read_core", "write", "archive", "coff", "elf", "macho", "pe"] } diff --git a/src/base.rs b/src/base.rs index 89d955e8bf2e1..0df3ffc4bd890 100644 --- a/src/base.rs +++ b/src/base.rs @@ -113,6 +113,8 @@ pub(crate) fn codegen_fn<'tcx>( }; tcx.sess.time("codegen clif ir", || codegen_fn_body(&mut fx, start_block)); + fx.bcx.seal_all_blocks(); + fx.bcx.finalize(); // Recover all necessary data from fx, before accessing func will prevent future access to it. let symbol_name = fx.symbol_name; @@ -487,9 +489,6 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) { } }; } - - fx.bcx.seal_all_blocks(); - fx.bcx.finalize(); } fn codegen_stmt<'tcx>( diff --git a/src/common.rs b/src/common.rs index 2dcd42fbd8f43..869977104e361 100644 --- a/src/common.rs +++ b/src/common.rs @@ -167,6 +167,15 @@ pub(crate) fn codegen_icmp_imm( } } +pub(crate) fn codegen_bitcast(fx: &mut FunctionCx<'_, '_, '_>, dst_ty: Type, val: Value) -> Value { + let mut flags = MemFlags::new(); + flags.set_endianness(match fx.tcx.data_layout.endian { + rustc_target::abi::Endian::Big => cranelift_codegen::ir::Endianness::Big, + rustc_target::abi::Endian::Little => cranelift_codegen::ir::Endianness::Little, + }); + fx.bcx.ins().bitcast(dst_ty, flags, val) +} + pub(crate) fn type_zero_value(bcx: &mut FunctionBuilder<'_>, ty: Type) -> Value { if ty == types::I128 { let zero = bcx.ins().iconst(types::I64, 0); diff --git a/src/intrinsics/llvm_x86.rs b/src/intrinsics/llvm_x86.rs index 7bc161fbe5523..d2ae6978ca2a8 100644 --- a/src/intrinsics/llvm_x86.rs +++ b/src/intrinsics/llvm_x86.rs @@ -33,8 +33,8 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( // cast float to int let a_lane = match lane_ty { - types::F32 => fx.bcx.ins().bitcast(types::I32, a_lane), - types::F64 => fx.bcx.ins().bitcast(types::I64, a_lane), + types::F32 => codegen_bitcast(fx, types::I32, a_lane), + types::F64 => codegen_bitcast(fx, types::I64, a_lane), _ => a_lane, }; diff --git a/src/intrinsics/mod.rs b/src/intrinsics/mod.rs index 548a6bf45842b..3681154e7888f 100644 --- a/src/intrinsics/mod.rs +++ b/src/intrinsics/mod.rs @@ -200,7 +200,7 @@ fn bool_to_zero_or_max_uint<'tcx>( let mut res = fx.bcx.ins().bmask(int_ty, val); if ty.is_float() { - res = fx.bcx.ins().bitcast(ty, res); + res = codegen_bitcast(fx, ty, res); } res diff --git a/src/value_and_place.rs b/src/value_and_place.rs index fe8af21ac6de5..fa06d6c3ba7f3 100644 --- a/src/value_and_place.rs +++ b/src/value_and_place.rs @@ -514,8 +514,8 @@ impl<'tcx> CPlace<'tcx> { (types::I32, types::F32) | (types::F32, types::I32) | (types::I64, types::F64) - | (types::F64, types::I64) => fx.bcx.ins().bitcast(dst_ty, data), - _ if src_ty.is_vector() && dst_ty.is_vector() => fx.bcx.ins().bitcast(dst_ty, data), + | (types::F64, types::I64) => codegen_bitcast(fx, dst_ty, data), + _ if src_ty.is_vector() && dst_ty.is_vector() => codegen_bitcast(fx, dst_ty, data), _ if src_ty.is_vector() || dst_ty.is_vector() => { // FIXME do something more efficient for transmutes between vectors and integers. let stack_slot = fx.bcx.create_sized_stack_slot(StackSlotData { From 97e2213c3c31909de388943ac3b1cb024decd6c2 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 22 Dec 2022 14:02:41 +0000 Subject: [PATCH 086/500] Enable inline stack probes on AArch64 Fixes #661 --- src/lib.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 629d79d501240..70d0cc339a80c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -278,12 +278,14 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Box Date: Fri, 23 Dec 2022 20:02:34 -0600 Subject: [PATCH 087/500] Pass `branch.{branch}.remote=origin` to `git submodule update` This works around a bug in git itself; see https://github.com/rust-lang/rust/issues/101144. --- src/bootstrap/lib.rs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index f84fcd21cfcfe..5cdd841cd6ed0 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -110,7 +110,7 @@ use std::fs::{self, File}; use std::io; use std::io::ErrorKind; use std::path::{Path, PathBuf}; -use std::process::Command; +use std::process::{Command, Stdio}; use std::str; use channel::GitInfo; @@ -661,12 +661,32 @@ impl Build { // Try passing `--progress` to start, then run git again without if that fails. let update = |progress: bool| { - let mut git = Command::new("git"); + // Git is buggy and will try to fetch submodules from the tracking branch for *this* repository, + // even though that has no relation to the upstream for the submodule. + let current_branch = { + let output = self + .config + .git() + .args(["symbolic-ref", "--short", "HEAD"]) + .stderr(Stdio::inherit()) + .output(); + let output = t!(output); + if output.status.success() { + Some(String::from_utf8(output.stdout).unwrap().trim().to_owned()) + } else { + None + } + }; + + let mut git = self.config.git(); + if let Some(branch) = current_branch { + git.arg("-c").arg(format!("branch.{branch}.remote=origin")); + } git.args(&["submodule", "update", "--init", "--recursive", "--depth=1"]); if progress { git.arg("--progress"); } - git.arg(relative_path).current_dir(&self.config.src); + git.arg(relative_path); git }; // NOTE: doesn't use `try_run` because this shouldn't print an error if it fails. From ac8eaa1ba7a5e6887b45bbd84d9a583fac6e39c9 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Wed, 28 Dec 2022 18:06:11 +0100 Subject: [PATCH 088/500] Rename `Rptr` to `Ref` in AST and HIR The name makes a lot more sense, and `ty::TyKind` calls it `Ref` already as well. --- src/types.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/types.rs b/src/types.rs index d5177a2057b8a..c1991e8d2c808 100644 --- a/src/types.rs +++ b/src/types.rs @@ -688,7 +688,7 @@ impl Rewrite for ast::Ty { rewrite_unary_prefix(context, prefix, &*mt.ty, shape) } - ast::TyKind::Rptr(ref lifetime, ref mt) => { + ast::TyKind::Ref(ref lifetime, ref mt) => { let mut_str = format_mutability(mt.mutbl); let mut_len = mut_str.len(); let mut result = String::with_capacity(128); @@ -1059,7 +1059,7 @@ pub(crate) fn can_be_overflowed_type( ) -> bool { match ty.kind { ast::TyKind::Tup(..) => context.use_block_indent() && len == 1, - ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => { + ast::TyKind::Ref(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => { can_be_overflowed_type(context, &*mutty.ty, len) } _ => false, From a53872388e03b4712a6c3d8a865e8cb214dab532 Mon Sep 17 00:00:00 2001 From: Yann Simon Date: Fri, 16 Dec 2022 16:39:40 +0100 Subject: [PATCH 089/500] update stdarch This will allow using miri on simd instructions https://github.com/rust-lang/stdarch/issues/1347#issuecomment-1353664361 --- library/stdarch | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/stdarch b/library/stdarch index 790411f93c4b5..a0c30f3e3c75a 160000 --- a/library/stdarch +++ b/library/stdarch @@ -1 +1 @@ -Subproject commit 790411f93c4b5eada3c23abb4c9a063fb0b24d99 +Subproject commit a0c30f3e3c75adcd6ee7efc94014ebcead61c507 From d7fa2ee3e6eae1a7fe4526249ce61caaa3d448d4 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Mon, 12 Dec 2022 19:37:28 +0000 Subject: [PATCH 090/500] Add missing extern crate rustc_driver --- src/lib.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 1d1ef525f23fa..0c27bcacfb83c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -24,6 +24,11 @@ extern crate rustc_parse; extern crate rustc_session; extern crate rustc_span; +// Necessary to pull in object code as the rest of the rustc crates are shipped only as rmeta +// files. +#[allow(unused_extern_crates)] +extern crate rustc_driver; + use std::cell::RefCell; use std::collections::HashMap; use std::fmt; From 571405deea18bc71c1376db2625f66301def846e Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Wed, 4 Jan 2023 14:45:19 +0000 Subject: [PATCH 091/500] Enable some fixed rustc tests cc #381 --- scripts/test_rustc_tests.sh | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/scripts/test_rustc_tests.sh b/scripts/test_rustc_tests.sh index b3d6dae515359..ca07c59c3925b 100755 --- a/scripts/test_rustc_tests.sh +++ b/scripts/test_rustc_tests.sh @@ -11,7 +11,7 @@ pushd rust command -v rg >/dev/null 2>&1 || cargo install ripgrep rm -r src/test/ui/{extern/,unsized-locals/,lto/,linkage*} || true -for test in $(rg --files-with-matches "lto|// needs-asm-support|// needs-unwind" src/test/{ui,incremental}); do +for test in $(rg --files-with-matches "lto|// needs-asm-support|// needs-unwind" src/test/{codegen-units,ui,incremental}); do rm $test done @@ -32,6 +32,7 @@ rm src/test/incremental/issue-80691-bad-eval-cache.rs # -Cpanic=abort causes abo # requires compiling with -Cpanic=unwind rm -r src/test/ui/macros/rfc-2011-nicer-assert-messages/ rm -r src/test/run-make/test-benches +rm src/test/ui/test-attrs/test-type.rs # vendor intrinsics rm src/test/ui/sse2.rs # cpuid not supported, so sse2 not detected @@ -56,10 +57,7 @@ rm src/test/ui/intrinsics/intrinsic-nearby.rs # unimplemented nearbyintf32 and n rm src/test/ui/target-feature/missing-plusminus.rs # error not implemented rm src/test/ui/fn/dyn-fn-alignment.rs # wants a 256 byte alignment rm -r src/test/run-make/emit-named-files # requires full --emit support -rm src/test/ui/abi/stack-probes.rs # stack probes not yet implemented -rm src/test/ui/simd/intrinsic/ptr-cast.rs # simd_expose_addr intrinsic unimplemented rm -r src/test/run-make/repr128-dwarf # debuginfo test -rm src/test/codegen-units/item-collection/asm-sym.rs # requires support for sym in asm!() # optimization tests # ================== @@ -104,9 +102,6 @@ rm src/test/ui/simd/simd-bitmask.rs # crash # ====================== rm src/test/ui/backtrace.rs # TODO warning rm src/test/ui/simple_global_asm.rs # TODO add needs-asm-support -rm src/test/ui/test-attrs/test-type.rs # TODO panic message on stderr. correct stdout -# not sure if this is actually a bug in the test suite, but the symbol list shows the function without leading _ for some reason -rm -r src/test/run-make/native-link-modifier-bundle rm src/test/ui/process/nofile-limit.rs # TODO some AArch64 linking issue rm src/test/ui/dyn-star/dispatch-on-pin-mut.rs # TODO failed assertion in vtable::get_ptr_and_method_ref From 4c97569a546c1f1d9bbfbb6f2e6a75466cd9faad Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 5 Jan 2023 17:26:54 +0000 Subject: [PATCH 092/500] Move patched sysroot from build_sysroot/ to download/ --- .gitignore | 5 +---- build_system/build_sysroot.rs | 9 +++++---- build_system/path.rs | 1 - build_system/prepare.rs | 24 +++++++++++++----------- build_system/tests.rs | 4 +++- clean_all.sh | 5 ++--- scripts/rustup.sh | 2 +- scripts/setup_rust_fork.sh | 2 +- 8 files changed, 26 insertions(+), 26 deletions(-) diff --git a/.gitignore b/.gitignore index b443fd58a1b98..8012e93f6a90e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -target +/target **/*.rs.bk *.rlib *.o @@ -11,9 +11,6 @@ perf.data.old /y.exe /y.pdb /build -/build_sysroot/sysroot_src -/build_sysroot/compiler-builtins -/build_sysroot/rustc_version /dist /rust /download diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index cbbf09b9b97b8..711d4ccc55bfb 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -146,10 +146,11 @@ pub(crate) fn build_sysroot( } } -// FIXME move to download/ or dist/ -pub(crate) static SYSROOT_RUSTC_VERSION: RelPath = RelPath::BUILD_SYSROOT.join("rustc_version"); -pub(crate) static SYSROOT_SRC: RelPath = RelPath::BUILD_SYSROOT.join("sysroot_src"); -static STANDARD_LIBRARY: CargoProject = CargoProject::new(&RelPath::BUILD_SYSROOT, "build_sysroot"); +pub(crate) static ORIG_BUILD_SYSROOT: RelPath = RelPath::SOURCE.join("build_sysroot"); +pub(crate) static BUILD_SYSROOT: RelPath = RelPath::DOWNLOAD.join("sysroot"); +pub(crate) static SYSROOT_RUSTC_VERSION: RelPath = BUILD_SYSROOT.join("rustc_version"); +pub(crate) static SYSROOT_SRC: RelPath = BUILD_SYSROOT.join("sysroot_src"); +static STANDARD_LIBRARY: CargoProject = CargoProject::new(&BUILD_SYSROOT, "build_sysroot"); fn build_clif_sysroot_for_triple( dirs: &Dirs, diff --git a/build_system/path.rs b/build_system/path.rs index e93981f1d64d3..35ab6f111fef4 100644 --- a/build_system/path.rs +++ b/build_system/path.rs @@ -42,7 +42,6 @@ impl RelPath { pub(crate) const DIST: RelPath = RelPath::Base(PathBase::Dist); pub(crate) const SCRIPTS: RelPath = RelPath::SOURCE.join("scripts"); - pub(crate) const BUILD_SYSROOT: RelPath = RelPath::SOURCE.join("build_sysroot"); pub(crate) const PATCHES: RelPath = RelPath::SOURCE.join("patches"); pub(crate) const fn join(&'static self, suffix: &'static str) -> RelPath { diff --git a/build_system/prepare.rs b/build_system/prepare.rs index 8ac67e8f94228..f9ef29849eb7e 100644 --- a/build_system/prepare.rs +++ b/build_system/prepare.rs @@ -3,9 +3,11 @@ use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; -use super::build_sysroot::{SYSROOT_RUSTC_VERSION, SYSROOT_SRC}; +use crate::build_system::rustc_info::get_default_sysroot; + +use super::build_sysroot::{BUILD_SYSROOT, ORIG_BUILD_SYSROOT, SYSROOT_RUSTC_VERSION, SYSROOT_SRC}; use super::path::{Dirs, RelPath}; -use super::rustc_info::{get_file_name, get_rustc_path, get_rustc_version}; +use super::rustc_info::{get_file_name, get_rustc_version}; use super::utils::{copy_dir_recursively, spawn_and_wait, Compiler}; pub(crate) fn prepare(dirs: &Dirs) { @@ -49,27 +51,27 @@ pub(crate) fn prepare(dirs: &Dirs) { } fn prepare_sysroot(dirs: &Dirs) { - let rustc_path = get_rustc_path(); - let sysroot_src_orig = rustc_path.parent().unwrap().join("../lib/rustlib/src/rust"); - let sysroot_src = SYSROOT_SRC; - + let sysroot_src_orig = get_default_sysroot().join("lib/rustlib/src/rust"); assert!(sysroot_src_orig.exists()); - sysroot_src.ensure_fresh(dirs); - fs::create_dir_all(sysroot_src.to_path(dirs).join("library")).unwrap(); eprintln!("[COPY] sysroot src"); + + BUILD_SYSROOT.ensure_fresh(dirs); + copy_dir_recursively(&ORIG_BUILD_SYSROOT.to_path(dirs), &BUILD_SYSROOT.to_path(dirs)); + + fs::create_dir_all(SYSROOT_SRC.to_path(dirs).join("library")).unwrap(); copy_dir_recursively( &sysroot_src_orig.join("library"), - &sysroot_src.to_path(dirs).join("library"), + &SYSROOT_SRC.to_path(dirs).join("library"), ); let rustc_version = get_rustc_version(); fs::write(SYSROOT_RUSTC_VERSION.to_path(dirs), &rustc_version).unwrap(); eprintln!("[GIT] init"); - init_git_repo(&sysroot_src.to_path(dirs)); + init_git_repo(&SYSROOT_SRC.to_path(dirs)); - apply_patches(dirs, "sysroot", &sysroot_src.to_path(dirs)); + apply_patches(dirs, "sysroot", &SYSROOT_SRC.to_path(dirs)); } pub(crate) struct GitRepo { diff --git a/build_system/tests.rs b/build_system/tests.rs index 37c35106af6d3..bc112910ce6be 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -1,3 +1,5 @@ +use crate::build_system::build_sysroot::SYSROOT_SRC; + use super::build_sysroot; use super::config; use super::path::{Dirs, RelPath}; @@ -262,7 +264,7 @@ pub(crate) static SIMPLE_RAYTRACER: CargoProject = CargoProject::new(&SIMPLE_RAYTRACER_REPO.source_dir(), "simple_raytracer"); static LIBCORE_TESTS: CargoProject = - CargoProject::new(&RelPath::BUILD_SYSROOT.join("sysroot_src/library/core/tests"), "core_tests"); + CargoProject::new(&SYSROOT_SRC.join("library/core/tests"), "core_tests"); const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ TestCase::new("test.rust-random/rand", &|runner| { diff --git a/clean_all.sh b/clean_all.sh index 1760e5836ecce..34cb081e37537 100755 --- a/clean_all.sh +++ b/clean_all.sh @@ -1,10 +1,9 @@ #!/usr/bin/env bash set -e -rm -rf build_sysroot/{sysroot_src/,target/,compiler-builtins/,rustc_version} -rm -rf target/ build/ dist/ perf.data{,.old} y.bin -rm -rf download/ +rm -rf target/ download/ build/ dist/ y.bin y.exe # Kept for now in case someone updates their checkout of cg_clif before running clean_all.sh # FIXME remove at some point in the future rm -rf rand/ regex/ simple-raytracer/ portable-simd/ abi-checker/ abi-cafe/ +rm -rf build_sysroot/{sysroot_src/,target/,compiler-builtins/,rustc_version} diff --git a/scripts/rustup.sh b/scripts/rustup.sh index bc4c06ed7d298..6111c20544463 100755 --- a/scripts/rustup.sh +++ b/scripts/rustup.sh @@ -17,10 +17,10 @@ case $1 in done ./clean_all.sh - ./y.rs prepare (cd build_sysroot && cargo update) + ./y.rs prepare ;; "commit") git add rust-toolchain build_sysroot/Cargo.lock diff --git a/scripts/setup_rust_fork.sh b/scripts/setup_rust_fork.sh index 6c64b7de7daa1..88bc64455030e 100644 --- a/scripts/setup_rust_fork.sh +++ b/scripts/setup_rust_fork.sh @@ -51,7 +51,7 @@ popd # FIXME remove once inline asm is fully supported export RUSTFLAGS="$RUSTFLAGS --cfg=rustix_use_libc" -export CFG_VIRTUAL_RUST_SOURCE_BASE_DIR="$(cd build_sysroot/sysroot_src; pwd)" +export CFG_VIRTUAL_RUST_SOURCE_BASE_DIR="$(cd download/sysroot/sysroot_src; pwd)" # Allow the testsuite to use llvm tools host_triple=$(rustc -vV | grep host | cut -d: -f2 | tr -d " ") From da37e16c2366a47b6599600d6b69d0f89480857d Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 5 Jan 2023 17:28:23 +0000 Subject: [PATCH 093/500] Remove debuginfo files for compiled y.rs in clean_all.sh --- clean_all.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clean_all.sh b/clean_all.sh index 34cb081e37537..cdfc2e143e674 100755 --- a/clean_all.sh +++ b/clean_all.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -e -rm -rf target/ download/ build/ dist/ y.bin y.exe +rm -rf target/ download/ build/ dist/ y.bin y.bin.dSYM y.exe y.pdb # Kept for now in case someone updates their checkout of cg_clif before running clean_all.sh # FIXME remove at some point in the future From e14e5c2af1a028a2ad23508ee3d6d5ffda0ebdf0 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 5 Jan 2023 17:57:35 +0000 Subject: [PATCH 094/500] Don't use hyperfine during testing A new command ./y.rs bench is introduced for benchmarking. This change allows skipping hyperfine installation in ./y.rs prepare and thus avoids writing to ~/.cargo/bin. --- .cirrus.yml | 2 - .github/workflows/main.yml | 6 -- .github/workflows/nightly-cranelift.yml | 6 -- .github/workflows/rustc.yml | 12 ---- .vscode/settings.json | 2 +- build_system/bench.rs | 79 +++++++++++++++++++++++ build_system/mod.rs | 17 ++++- build_system/prepare.rs | 6 +- build_system/tests.rs | 84 ++----------------------- config.txt | 2 +- 10 files changed, 106 insertions(+), 110 deletions(-) create mode 100644 build_system/bench.rs diff --git a/.cirrus.yml b/.cirrus.yml index 76b48d70ab7c7..7c966aa1ab9a9 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -6,8 +6,6 @@ task: - pkg install -y curl git bash - curl https://sh.rustup.rs -sSf --output rustup.sh - sh rustup.sh --default-toolchain none -y --profile=minimal - cargo_bin_cache: - folder: ~/.cargo/bin target_cache: folder: target prepare_script: diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index b79406879ff32..cc9ae19afded6 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -62,12 +62,6 @@ jobs: steps: - uses: actions/checkout@v3 - - name: Cache cargo installed crates - uses: actions/cache@v3 - with: - path: ~/.cargo/bin - key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-installed-crates - - name: Cache cargo registry and index uses: actions/cache@v3 with: diff --git a/.github/workflows/nightly-cranelift.yml b/.github/workflows/nightly-cranelift.yml index 0565938ee3531..968cd43efd15d 100644 --- a/.github/workflows/nightly-cranelift.yml +++ b/.github/workflows/nightly-cranelift.yml @@ -13,12 +13,6 @@ jobs: steps: - uses: actions/checkout@v3 - - name: Cache cargo installed crates - uses: actions/cache@v3 - with: - path: ~/.cargo/bin - key: ubuntu-latest-cargo-installed-crates - - name: Prepare dependencies run: | git config --global user.email "user@example.com" diff --git a/.github/workflows/rustc.yml b/.github/workflows/rustc.yml index bab81b9dc2a81..2c7de86f9b907 100644 --- a/.github/workflows/rustc.yml +++ b/.github/workflows/rustc.yml @@ -10,12 +10,6 @@ jobs: steps: - uses: actions/checkout@v3 - - name: Cache cargo installed crates - uses: actions/cache@v3 - with: - path: ~/.cargo/bin - key: ${{ runner.os }}-cargo-installed-crates - - name: Cache cargo registry and index uses: actions/cache@v3 with: @@ -44,12 +38,6 @@ jobs: steps: - uses: actions/checkout@v3 - - name: Cache cargo installed crates - uses: actions/cache@v3 - with: - path: ~/.cargo/bin - key: ${{ runner.os }}-cargo-installed-crates - - name: Cache cargo registry and index uses: actions/cache@v3 with: diff --git a/.vscode/settings.json b/.vscode/settings.json index bc914e37d2b51..d8650d1e387d2 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -30,7 +30,7 @@ ] }, { - "sysroot_src": "./build_sysroot/sysroot_src/library", + "sysroot_src": "./download/sysroot/sysroot_src/library", "crates": [ { "root_module": "./example/std_example.rs", diff --git a/build_system/bench.rs b/build_system/bench.rs new file mode 100644 index 0000000000000..0ad8863223de6 --- /dev/null +++ b/build_system/bench.rs @@ -0,0 +1,79 @@ +use std::env; +use std::fs; +use std::path::Path; + +use super::path::{Dirs, RelPath}; +use super::prepare::GitRepo; +use super::rustc_info::{get_file_name, get_wrapper_file_name}; +use super::utils::{hyperfine_command, is_ci, spawn_and_wait, CargoProject}; + +pub(crate) static SIMPLE_RAYTRACER_REPO: GitRepo = GitRepo::github( + "ebobby", + "simple-raytracer", + "804a7a21b9e673a482797aa289a18ed480e4d813", + "", +); + +pub(crate) static SIMPLE_RAYTRACER: CargoProject = + CargoProject::new(&SIMPLE_RAYTRACER_REPO.source_dir(), "simple_raytracer"); + +pub(crate) fn benchmark(dirs: &Dirs) { + benchmark_simple_raytracer(dirs); +} + +fn benchmark_simple_raytracer(dirs: &Dirs) { + if std::process::Command::new("hyperfine").output().is_err() { + eprintln!("Hyperfine not installed"); + eprintln!("Hint: Try `cargo install hyperfine` to install hyperfine"); + std::process::exit(1); + } + + let run_runs = env::var("RUN_RUNS") + .unwrap_or(if is_ci() { "2" } else { "10" }.to_string()) + .parse() + .unwrap(); + + eprintln!("[BENCH COMPILE] ebobby/simple-raytracer"); + let cargo_clif = RelPath::DIST.to_path(dirs).join(get_wrapper_file_name("cargo-clif", "bin")); + let manifest_path = SIMPLE_RAYTRACER.manifest_path(dirs); + let target_dir = SIMPLE_RAYTRACER.target_dir(dirs); + + let clean_cmd = format!( + "cargo clean --manifest-path {manifest_path} --target-dir {target_dir}", + manifest_path = manifest_path.display(), + target_dir = target_dir.display(), + ); + let llvm_build_cmd = format!( + "cargo build --manifest-path {manifest_path} --target-dir {target_dir}", + manifest_path = manifest_path.display(), + target_dir = target_dir.display(), + ); + let clif_build_cmd = format!( + "{cargo_clif} build --manifest-path {manifest_path} --target-dir {target_dir}", + cargo_clif = cargo_clif.display(), + manifest_path = manifest_path.display(), + target_dir = target_dir.display(), + ); + + let bench_compile = + hyperfine_command(1, run_runs, Some(&clean_cmd), &llvm_build_cmd, &clif_build_cmd); + + spawn_and_wait(bench_compile); + + eprintln!("[BENCH RUN] ebobby/simple-raytracer"); + fs::copy( + target_dir.join("debug").join(get_file_name("main", "bin")), + RelPath::BUILD.to_path(dirs).join(get_file_name("raytracer_cg_clif", "bin")), + ) + .unwrap(); + + let mut bench_run = hyperfine_command( + 0, + run_runs, + None, + Path::new(".").join(get_file_name("raytracer_cg_llvm", "bin")).to_str().unwrap(), + Path::new(".").join(get_file_name("raytracer_cg_clif", "bin")).to_str().unwrap(), + ); + bench_run.current_dir(RelPath::BUILD.to_path(dirs)); + spawn_and_wait(bench_run); +} diff --git a/build_system/mod.rs b/build_system/mod.rs index 2f311aed7c8db..76d1d013b0dbc 100644 --- a/build_system/mod.rs +++ b/build_system/mod.rs @@ -5,6 +5,7 @@ use std::process; use self::utils::is_ci; mod abi_cafe; +mod bench; mod build_backend; mod build_sysroot; mod config; @@ -20,6 +21,7 @@ USAGE: ./y.rs prepare [--out-dir DIR] ./y.rs build [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] ./y.rs test [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] + ./y.rs bench [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] OPTIONS: --sysroot none|clif|llvm @@ -54,6 +56,7 @@ enum Command { Prepare, Build, Test, + Bench, } #[derive(Copy, Clone, Debug)] @@ -67,7 +70,7 @@ pub fn main() { if env::var("RUST_BACKTRACE").is_err() { env::set_var("RUST_BACKTRACE", "1"); } - env::set_var("CG_CLIF_DISPLAY_CG_TIME", "1"); + env::set_var("CG_CLIF_DISPLAY_CG_TIME", "1"); // FIXME disable this by default env::set_var("CG_CLIF_DISABLE_INCR_CACHE", "1"); if is_ci() { @@ -83,6 +86,7 @@ pub fn main() { Some("prepare") => Command::Prepare, Some("build") => Command::Build, Some("test") => Command::Test, + Some("bench") => Command::Bench, Some(flag) if flag.starts_with('-') => arg_error!("Expected command found flag {}", flag), Some(command) => arg_error!("Unknown command {}", command), None => { @@ -198,5 +202,16 @@ pub fn main() { &target_triple, ); } + Command::Bench => { + build_sysroot::build_sysroot( + &dirs, + channel, + sysroot_kind, + &cg_clif_dylib, + &host_triple, + &target_triple, + ); + bench::benchmark(&dirs); + } } } diff --git a/build_system/prepare.rs b/build_system/prepare.rs index f9ef29849eb7e..9ad4ddc92c5af 100644 --- a/build_system/prepare.rs +++ b/build_system/prepare.rs @@ -33,14 +33,14 @@ pub(crate) fn prepare(dirs: &Dirs) { super::tests::RAND_REPO.fetch(dirs); super::tests::REGEX_REPO.fetch(dirs); super::tests::PORTABLE_SIMD_REPO.fetch(dirs); - super::tests::SIMPLE_RAYTRACER_REPO.fetch(dirs); + super::bench::SIMPLE_RAYTRACER_REPO.fetch(dirs); eprintln!("[LLVM BUILD] simple-raytracer"); let host_compiler = Compiler::host(); - let build_cmd = super::tests::SIMPLE_RAYTRACER.build(&host_compiler, dirs); + let build_cmd = super::bench::SIMPLE_RAYTRACER.build(&host_compiler, dirs); spawn_and_wait(build_cmd); fs::copy( - super::tests::SIMPLE_RAYTRACER + super::bench::SIMPLE_RAYTRACER .target_dir(dirs) .join(&host_compiler.triple) .join("debug") diff --git a/build_system/tests.rs b/build_system/tests.rs index bc112910ce6be..5b8b6f2df1066 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -1,13 +1,9 @@ -use crate::build_system::build_sysroot::SYSROOT_SRC; - -use super::build_sysroot; +use super::bench::SIMPLE_RAYTRACER; +use super::build_sysroot::{self, SYSROOT_SRC}; use super::config; use super::path::{Dirs, RelPath}; use super::prepare::GitRepo; -use super::rustc_info::{get_file_name, get_wrapper_file_name}; -use super::utils::{ - hyperfine_command, is_ci, spawn_and_wait, spawn_and_wait_with_input, CargoProject, Compiler, -}; +use super::utils::{spawn_and_wait, spawn_and_wait_with_input, CargoProject, Compiler}; use super::SysrootKind; use std::env; use std::ffi::OsStr; @@ -253,16 +249,6 @@ pub(crate) static PORTABLE_SIMD_REPO: GitRepo = GitRepo::github( static PORTABLE_SIMD: CargoProject = CargoProject::new(&PORTABLE_SIMD_REPO.source_dir(), "portable_simd"); -pub(crate) static SIMPLE_RAYTRACER_REPO: GitRepo = GitRepo::github( - "ebobby", - "simple-raytracer", - "804a7a21b9e673a482797aa289a18ed480e4d813", - "", -); - -pub(crate) static SIMPLE_RAYTRACER: CargoProject = - CargoProject::new(&SIMPLE_RAYTRACER_REPO.source_dir(), "simple_raytracer"); - static LIBCORE_TESTS: CargoProject = CargoProject::new(&SYSROOT_SRC.join("library/core/tests"), "core_tests"); @@ -282,67 +268,9 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ spawn_and_wait(build_cmd); } }), - TestCase::new("bench.simple-raytracer", &|runner| { - let run_runs = env::var("RUN_RUNS") - .unwrap_or(if is_ci() { "2" } else { "10" }.to_string()) - .parse() - .unwrap(); - - if runner.is_native { - eprintln!("[BENCH COMPILE] ebobby/simple-raytracer"); - let cargo_clif = RelPath::DIST - .to_path(&runner.dirs) - .join(get_wrapper_file_name("cargo-clif", "bin")); - let manifest_path = SIMPLE_RAYTRACER.manifest_path(&runner.dirs); - let target_dir = SIMPLE_RAYTRACER.target_dir(&runner.dirs); - - let clean_cmd = format!( - "cargo clean --manifest-path {manifest_path} --target-dir {target_dir}", - manifest_path = manifest_path.display(), - target_dir = target_dir.display(), - ); - let llvm_build_cmd = format!( - "cargo build --manifest-path {manifest_path} --target-dir {target_dir}", - manifest_path = manifest_path.display(), - target_dir = target_dir.display(), - ); - let clif_build_cmd = format!( - "{cargo_clif} build --manifest-path {manifest_path} --target-dir {target_dir}", - cargo_clif = cargo_clif.display(), - manifest_path = manifest_path.display(), - target_dir = target_dir.display(), - ); - - let bench_compile = - hyperfine_command(1, run_runs, Some(&clean_cmd), &llvm_build_cmd, &clif_build_cmd); - - spawn_and_wait(bench_compile); - - eprintln!("[BENCH RUN] ebobby/simple-raytracer"); - fs::copy( - target_dir.join("debug").join(get_file_name("main", "bin")), - RelPath::BUILD - .to_path(&runner.dirs) - .join(get_file_name("raytracer_cg_clif", "bin")), - ) - .unwrap(); - - let mut bench_run = hyperfine_command( - 0, - run_runs, - None, - Path::new(".").join(get_file_name("raytracer_cg_llvm", "bin")).to_str().unwrap(), - Path::new(".").join(get_file_name("raytracer_cg_clif", "bin")).to_str().unwrap(), - ); - bench_run.current_dir(RelPath::BUILD.to_path(&runner.dirs)); - spawn_and_wait(bench_run); - } else { - spawn_and_wait(SIMPLE_RAYTRACER.clean(&runner.target_compiler.cargo, &runner.dirs)); - eprintln!("[BENCH COMPILE] ebobby/simple-raytracer (skipped)"); - eprintln!("[COMPILE] ebobby/simple-raytracer"); - spawn_and_wait(SIMPLE_RAYTRACER.build(&runner.target_compiler, &runner.dirs)); - eprintln!("[BENCH RUN] ebobby/simple-raytracer (skipped)"); - } + TestCase::new("test.simple-raytracer", &|runner| { + spawn_and_wait(SIMPLE_RAYTRACER.clean(&runner.host_compiler.cargo, &runner.dirs)); + spawn_and_wait(SIMPLE_RAYTRACER.build(&runner.target_compiler, &runner.dirs)); }), TestCase::new("test.libcore", &|runner| { spawn_and_wait(LIBCORE_TESTS.clean(&runner.host_compiler.cargo, &runner.dirs)); diff --git a/config.txt b/config.txt index 258b67e931476..d9912a8158f67 100644 --- a/config.txt +++ b/config.txt @@ -44,7 +44,7 @@ aot.issue-72793 testsuite.extended_sysroot test.rust-random/rand -bench.simple-raytracer +test.simple-raytracer test.libcore test.regex-shootout-regex-dna test.regex From 664c60a18eb594ef22a31b7fa3a0dfb367cdd442 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 5 Jan 2023 21:29:36 +0000 Subject: [PATCH 095/500] Detect closures assigned to binding in block Fix #58497. --- tests/target/issue_4110.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/target/issue_4110.rs b/tests/target/issue_4110.rs index 4a58c3946e12d..d3734e90b7ffa 100644 --- a/tests/target/issue_4110.rs +++ b/tests/target/issue_4110.rs @@ -20,6 +20,7 @@ fn bindings() { category, span, &format!("`{}`", name), + "function", ), ( ref name, From 92aa5f6b272bcdc020a34f8d90f9ef851b5b4504 Mon Sep 17 00:00:00 2001 From: John Millikin Date: Mon, 9 Jan 2023 13:54:21 +0900 Subject: [PATCH 096/500] Disable `linux_ext` in wasm32 and fortanix rustdoc builds. The `std::os::unix` module is stubbed out when building docs for these target platforms. The introduction of Linux-specific extension traits caused `std::os::net` to depend on sub-modules of `std::os::unix`, which broke rustdoc for the `wasm32-unknown-unknown` target. Adding an additional `#[cfg]` guard solves that rustdoc failure by not declaring `linux_ext` on targets with a stubbed `std::os::unix`. --- library/std/src/os/net/mod.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/library/std/src/os/net/mod.rs b/library/std/src/os/net/mod.rs index 5ec267c41e97c..b7046dd7c598c 100644 --- a/library/std/src/os/net/mod.rs +++ b/library/std/src/os/net/mod.rs @@ -1,4 +1,13 @@ //! OS-specific networking functionality. +// See cfg macros in `library/std/src/os/mod.rs` for why these platforms must +// be special-cased during rustdoc generation. +#[cfg(not(all( + doc, + any( + all(target_arch = "wasm32", not(target_os = "wasi")), + all(target_vendor = "fortanix", target_env = "sgx") + ) +)))] #[cfg(any(target_os = "linux", target_os = "android", doc))] pub(super) mod linux_ext; From 1a7ef02dcb65ee4aa9e7679ad0ce7e8a42bee6bf Mon Sep 17 00:00:00 2001 From: koka Date: Mon, 9 Jan 2023 18:49:46 +0900 Subject: [PATCH 097/500] Fix fp in unnecessary_safety_comment --- clippy_lints/src/undocumented_unsafe_blocks.rs | 12 ++++++++++++ tests/ui/unnecessary_safety_comment.rs | 17 +++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/clippy_lints/src/undocumented_unsafe_blocks.rs b/clippy_lints/src/undocumented_unsafe_blocks.rs index 2e1b6d8d4ea7f..2920684ade33c 100644 --- a/clippy_lints/src/undocumented_unsafe_blocks.rs +++ b/clippy_lints/src/undocumented_unsafe_blocks.rs @@ -263,6 +263,18 @@ fn expr_has_unnecessary_safety_comment<'tcx>( expr: &'tcx hir::Expr<'tcx>, comment_pos: BytePos, ) -> Option { + if cx.tcx.hir().parent_iter(expr.hir_id).any(|(_, ref node)| { + matches!( + node, + Node::Block(&Block { + rules: BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided), + .. + }), + ) + }) { + return None; + } + // this should roughly be the reverse of `block_parents_have_safety_comment` if for_each_expr_with_closures(cx, expr, |expr| match expr.kind { hir::ExprKind::Block( diff --git a/tests/ui/unnecessary_safety_comment.rs b/tests/ui/unnecessary_safety_comment.rs index 7fefea7051d69..89fedb145f88b 100644 --- a/tests/ui/unnecessary_safety_comment.rs +++ b/tests/ui/unnecessary_safety_comment.rs @@ -48,4 +48,21 @@ fn unnecessary_on_stmt_and_expr() -> u32 { 24 } +mod issue_10084 { + unsafe fn bar() -> i32 { + 42 + } + + macro_rules! foo { + () => { + // SAFETY: This is necessary + unsafe { bar() } + }; + } + + fn main() { + foo!(); + } +} + fn main() {} From 9f5a933f00e0aba526edac2cf1804b4360059e55 Mon Sep 17 00:00:00 2001 From: Arpad Borsos Date: Mon, 9 Jan 2023 09:31:34 +0100 Subject: [PATCH 098/500] Remove backwards compat for LLVM 12 coverage format --- .../src/coverageinfo/mapgen.rs | 45 +++++++------------ compiler/rustc_codegen_llvm/src/errors.rs | 4 -- .../locales/en-US/codegen_llvm.ftl | 3 -- 3 files changed, 17 insertions(+), 35 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index 393bf30e9f834..ca49c862324a0 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -1,6 +1,5 @@ use crate::common::CodegenCx; use crate::coverageinfo; -use crate::errors::InstrumentCoverageRequiresLLVM12; use crate::llvm; use llvm::coverageinfo::CounterMappingRegion; @@ -19,8 +18,8 @@ use std::ffi::CString; /// Generates and exports the Coverage Map. /// -/// Rust Coverage Map generation supports LLVM Coverage Mapping Format versions -/// 5 (LLVM 12, only) and 6 (zero-based encoded as 4 and 5, respectively), as defined at +/// Rust Coverage Map generation supports LLVM Coverage Mapping Format version +/// 6 (zero-based encoded as 5), as defined at /// [LLVM Code Coverage Mapping Format](https://github.com/rust-lang/llvm-project/blob/rustc/13.0-2021-09-30/llvm/docs/CoverageMappingFormat.rst#llvm-code-coverage-mapping-format). /// These versions are supported by the LLVM coverage tools (`llvm-profdata` and `llvm-cov`) /// bundled with Rust's fork of LLVM. @@ -33,13 +32,10 @@ use std::ffi::CString; pub fn finalize(cx: &CodegenCx<'_, '_>) { let tcx = cx.tcx; - // Ensure the installed version of LLVM supports at least Coverage Map - // Version 5 (encoded as a zero-based value: 4), which was introduced with - // LLVM 12. + // Ensure the installed version of LLVM supports Coverage Map Version 6 + // (encoded as a zero-based value: 5), which was introduced with LLVM 13. let version = coverageinfo::mapping_version(); - if version < 4 { - tcx.sess.emit_fatal(InstrumentCoverageRequiresLLVM12); - } + assert_eq!(version, 5, "The `CoverageMappingVersion` exposed by `llvm-wrapper` is out of sync"); debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name()); @@ -61,7 +57,7 @@ pub fn finalize(cx: &CodegenCx<'_, '_>) { return; } - let mut mapgen = CoverageMapGenerator::new(tcx, version); + let mut mapgen = CoverageMapGenerator::new(tcx); // Encode coverage mappings and generate function records let mut function_data = Vec::new(); @@ -124,25 +120,18 @@ struct CoverageMapGenerator { } impl CoverageMapGenerator { - fn new(tcx: TyCtxt<'_>, version: u32) -> Self { + fn new(tcx: TyCtxt<'_>) -> Self { let mut filenames = FxIndexSet::default(); - if version >= 5 { - // LLVM Coverage Mapping Format version 6 (zero-based encoded as 5) - // requires setting the first filename to the compilation directory. - // Since rustc generates coverage maps with relative paths, the - // compilation directory can be combined with the relative paths - // to get absolute paths, if needed. - let working_dir = tcx - .sess - .opts - .working_dir - .remapped_path_if_available() - .to_string_lossy() - .to_string(); - let c_filename = - CString::new(working_dir).expect("null error converting filename to C string"); - filenames.insert(c_filename); - } + // LLVM Coverage Mapping Format version 6 (zero-based encoded as 5) + // requires setting the first filename to the compilation directory. + // Since rustc generates coverage maps with relative paths, the + // compilation directory can be combined with the relative paths + // to get absolute paths, if needed. + let working_dir = + tcx.sess.opts.working_dir.remapped_path_if_available().to_string_lossy().to_string(); + let c_filename = + CString::new(working_dir).expect("null error converting filename to C string"); + filenames.insert(c_filename); Self { filenames } } diff --git a/compiler/rustc_codegen_llvm/src/errors.rs b/compiler/rustc_codegen_llvm/src/errors.rs index b46209972421f..001d1ce93d8b4 100644 --- a/compiler/rustc_codegen_llvm/src/errors.rs +++ b/compiler/rustc_codegen_llvm/src/errors.rs @@ -39,10 +39,6 @@ pub(crate) struct ErrorCreatingImportLibrary<'a> { pub error: String, } -#[derive(Diagnostic)] -#[diag(codegen_llvm_instrument_coverage_requires_llvm_12)] -pub(crate) struct InstrumentCoverageRequiresLLVM12; - #[derive(Diagnostic)] #[diag(codegen_llvm_symbol_already_defined)] pub(crate) struct SymbolAlreadyDefined<'a> { diff --git a/compiler/rustc_error_messages/locales/en-US/codegen_llvm.ftl b/compiler/rustc_error_messages/locales/en-US/codegen_llvm.ftl index 860212b051f39..b82c903290b9a 100644 --- a/compiler/rustc_error_messages/locales/en-US/codegen_llvm.ftl +++ b/compiler/rustc_error_messages/locales/en-US/codegen_llvm.ftl @@ -11,9 +11,6 @@ codegen_llvm_unknown_ctarget_feature_prefix = codegen_llvm_error_creating_import_library = Error creating import library for {$lib_name}: {$error} -codegen_llvm_instrument_coverage_requires_llvm_12 = - rustc option `-C instrument-coverage` requires LLVM 12 or higher. - codegen_llvm_symbol_already_defined = symbol `{$symbol_name}` is already defined From 96e306843eb7236c67b41c7647d4cd56c43e153a Mon Sep 17 00:00:00 2001 From: dswij Date: Wed, 11 Jan 2023 06:51:52 +0800 Subject: [PATCH 099/500] tests: add case for multiple semis --- tests/ui/needless_return.fixed | 10 +++ tests/ui/needless_return.rs | 10 +++ tests/ui/needless_return.stderr | 110 ++++++++++++++++++-------------- 3 files changed, 83 insertions(+), 47 deletions(-) diff --git a/tests/ui/needless_return.fixed b/tests/ui/needless_return.fixed index ab1c0e590bbc7..079e3531def1b 100644 --- a/tests/ui/needless_return.fixed +++ b/tests/ui/needless_return.fixed @@ -31,6 +31,16 @@ fn test_no_semicolon() -> bool { true } +#[rustfmt::skip] +fn test_multiple_semicolon() -> bool { + true +} + +#[rustfmt::skip] +fn test_multiple_semicolon_with_spaces() -> bool { + true +} + fn test_if_block() -> bool { if true { true diff --git a/tests/ui/needless_return.rs b/tests/ui/needless_return.rs index abed338bb9b29..c1c48284f0869 100644 --- a/tests/ui/needless_return.rs +++ b/tests/ui/needless_return.rs @@ -31,6 +31,16 @@ fn test_no_semicolon() -> bool { return true; } +#[rustfmt::skip] +fn test_multiple_semicolon() -> bool { + return true;;; +} + +#[rustfmt::skip] +fn test_multiple_semicolon_with_spaces() -> bool { + return true;; ; ; +} + fn test_if_block() -> bool { if true { return true; diff --git a/tests/ui/needless_return.stderr b/tests/ui/needless_return.stderr index 52eabf6e1370d..08b04bfe9d8bf 100644 --- a/tests/ui/needless_return.stderr +++ b/tests/ui/needless_return.stderr @@ -16,7 +16,23 @@ LL | return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:36:9 + --> $DIR/needless_return.rs:36:5 + | +LL | return true;;; + | ^^^^^^^^^^^ + | + = help: remove `return` + +error: unneeded `return` statement + --> $DIR/needless_return.rs:41:5 + | +LL | return true;; ; ; + | ^^^^^^^^^^^ + | + = help: remove `return` + +error: unneeded `return` statement + --> $DIR/needless_return.rs:46:9 | LL | return true; | ^^^^^^^^^^^ @@ -24,7 +40,7 @@ LL | return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:38:9 + --> $DIR/needless_return.rs:48:9 | LL | return false; | ^^^^^^^^^^^^ @@ -32,7 +48,7 @@ LL | return false; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:44:17 + --> $DIR/needless_return.rs:54:17 | LL | true => return false, | ^^^^^^^^^^^^ @@ -40,7 +56,7 @@ LL | true => return false, = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:46:13 + --> $DIR/needless_return.rs:56:13 | LL | return true; | ^^^^^^^^^^^ @@ -48,7 +64,7 @@ LL | return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:53:9 + --> $DIR/needless_return.rs:63:9 | LL | return true; | ^^^^^^^^^^^ @@ -56,7 +72,7 @@ LL | return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:55:16 + --> $DIR/needless_return.rs:65:16 | LL | let _ = || return true; | ^^^^^^^^^^^ @@ -64,7 +80,7 @@ LL | let _ = || return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:59:5 + --> $DIR/needless_return.rs:69:5 | LL | return the_answer!(); | ^^^^^^^^^^^^^^^^^^^^ @@ -72,7 +88,7 @@ LL | return the_answer!(); = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:62:21 + --> $DIR/needless_return.rs:72:21 | LL | fn test_void_fun() { | _____________________^ @@ -82,7 +98,7 @@ LL | | return; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:67:11 + --> $DIR/needless_return.rs:77:11 | LL | if b { | ___________^ @@ -92,7 +108,7 @@ LL | | return; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:69:13 + --> $DIR/needless_return.rs:79:13 | LL | } else { | _____________^ @@ -102,7 +118,7 @@ LL | | return; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:77:14 + --> $DIR/needless_return.rs:87:14 | LL | _ => return, | ^^^^^^ @@ -110,7 +126,7 @@ LL | _ => return, = help: replace `return` with a unit value error: unneeded `return` statement - --> $DIR/needless_return.rs:85:24 + --> $DIR/needless_return.rs:95:24 | LL | let _ = 42; | ________________________^ @@ -120,7 +136,7 @@ LL | | return; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:88:14 + --> $DIR/needless_return.rs:98:14 | LL | _ => return, | ^^^^^^ @@ -128,7 +144,7 @@ LL | _ => return, = help: replace `return` with a unit value error: unneeded `return` statement - --> $DIR/needless_return.rs:101:9 + --> $DIR/needless_return.rs:111:9 | LL | return String::from("test"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -136,7 +152,7 @@ LL | return String::from("test"); = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:103:9 + --> $DIR/needless_return.rs:113:9 | LL | return String::new(); | ^^^^^^^^^^^^^^^^^^^^ @@ -144,7 +160,7 @@ LL | return String::new(); = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:125:32 + --> $DIR/needless_return.rs:135:32 | LL | bar.unwrap_or_else(|_| return) | ^^^^^^ @@ -152,7 +168,7 @@ LL | bar.unwrap_or_else(|_| return) = help: replace `return` with an empty block error: unneeded `return` statement - --> $DIR/needless_return.rs:129:21 + --> $DIR/needless_return.rs:139:21 | LL | let _ = || { | _____________________^ @@ -162,7 +178,7 @@ LL | | return; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:132:20 + --> $DIR/needless_return.rs:142:20 | LL | let _ = || return; | ^^^^^^ @@ -170,7 +186,7 @@ LL | let _ = || return; = help: replace `return` with an empty block error: unneeded `return` statement - --> $DIR/needless_return.rs:138:32 + --> $DIR/needless_return.rs:148:32 | LL | res.unwrap_or_else(|_| return Foo) | ^^^^^^^^^^ @@ -178,7 +194,7 @@ LL | res.unwrap_or_else(|_| return Foo) = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:147:5 + --> $DIR/needless_return.rs:157:5 | LL | return true; | ^^^^^^^^^^^ @@ -186,7 +202,7 @@ LL | return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:151:5 + --> $DIR/needless_return.rs:161:5 | LL | return true; | ^^^^^^^^^^^ @@ -194,7 +210,7 @@ LL | return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:156:9 + --> $DIR/needless_return.rs:166:9 | LL | return true; | ^^^^^^^^^^^ @@ -202,7 +218,7 @@ LL | return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:158:9 + --> $DIR/needless_return.rs:168:9 | LL | return false; | ^^^^^^^^^^^^ @@ -210,7 +226,7 @@ LL | return false; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:164:17 + --> $DIR/needless_return.rs:174:17 | LL | true => return false, | ^^^^^^^^^^^^ @@ -218,7 +234,7 @@ LL | true => return false, = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:166:13 + --> $DIR/needless_return.rs:176:13 | LL | return true; | ^^^^^^^^^^^ @@ -226,7 +242,7 @@ LL | return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:173:9 + --> $DIR/needless_return.rs:183:9 | LL | return true; | ^^^^^^^^^^^ @@ -234,7 +250,7 @@ LL | return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:175:16 + --> $DIR/needless_return.rs:185:16 | LL | let _ = || return true; | ^^^^^^^^^^^ @@ -242,7 +258,7 @@ LL | let _ = || return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:179:5 + --> $DIR/needless_return.rs:189:5 | LL | return the_answer!(); | ^^^^^^^^^^^^^^^^^^^^ @@ -250,7 +266,7 @@ LL | return the_answer!(); = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:182:33 + --> $DIR/needless_return.rs:192:33 | LL | async fn async_test_void_fun() { | _________________________________^ @@ -260,7 +276,7 @@ LL | | return; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:187:11 + --> $DIR/needless_return.rs:197:11 | LL | if b { | ___________^ @@ -270,7 +286,7 @@ LL | | return; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:189:13 + --> $DIR/needless_return.rs:199:13 | LL | } else { | _____________^ @@ -280,7 +296,7 @@ LL | | return; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:197:14 + --> $DIR/needless_return.rs:207:14 | LL | _ => return, | ^^^^^^ @@ -288,7 +304,7 @@ LL | _ => return, = help: replace `return` with a unit value error: unneeded `return` statement - --> $DIR/needless_return.rs:210:9 + --> $DIR/needless_return.rs:220:9 | LL | return String::from("test"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -296,7 +312,7 @@ LL | return String::from("test"); = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:212:9 + --> $DIR/needless_return.rs:222:9 | LL | return String::new(); | ^^^^^^^^^^^^^^^^^^^^ @@ -304,7 +320,7 @@ LL | return String::new(); = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:228:5 + --> $DIR/needless_return.rs:238:5 | LL | return format!("Hello {}", "world!"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -312,7 +328,7 @@ LL | return format!("Hello {}", "world!"); = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:239:9 + --> $DIR/needless_return.rs:249:9 | LL | return true; | ^^^^^^^^^^^ @@ -320,7 +336,7 @@ LL | return true; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:241:9 + --> $DIR/needless_return.rs:251:9 | LL | return false; | ^^^^^^^^^^^^ @@ -328,7 +344,7 @@ LL | return false; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:248:13 + --> $DIR/needless_return.rs:258:13 | LL | return 10; | ^^^^^^^^^ @@ -336,7 +352,7 @@ LL | return 10; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:251:13 + --> $DIR/needless_return.rs:261:13 | LL | return 100; | ^^^^^^^^^^ @@ -344,7 +360,7 @@ LL | return 100; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:259:9 + --> $DIR/needless_return.rs:269:9 | LL | return 0; | ^^^^^^^^ @@ -352,7 +368,7 @@ LL | return 0; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:266:13 + --> $DIR/needless_return.rs:276:13 | LL | return *(x as *const isize); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -360,7 +376,7 @@ LL | return *(x as *const isize); = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:268:13 + --> $DIR/needless_return.rs:278:13 | LL | return !*(x as *const isize); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -368,7 +384,7 @@ LL | return !*(x as *const isize); = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:275:20 + --> $DIR/needless_return.rs:285:20 | LL | let _ = 42; | ____________________^ @@ -379,7 +395,7 @@ LL | | return; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:282:20 + --> $DIR/needless_return.rs:292:20 | LL | let _ = 42; return; | ^^^^^^^ @@ -387,7 +403,7 @@ LL | let _ = 42; return; = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:294:9 + --> $DIR/needless_return.rs:304:9 | LL | return Ok(format!("ok!")); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -395,12 +411,12 @@ LL | return Ok(format!("ok!")); = help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:296:9 + --> $DIR/needless_return.rs:306:9 | LL | return Err(format!("err!")); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: remove `return` -error: aborting due to 48 previous errors +error: aborting due to 50 previous errors From d73adea465726944815eb62d373abf6e87dc3b12 Mon Sep 17 00:00:00 2001 From: dswij Date: Wed, 11 Jan 2023 06:52:22 +0800 Subject: [PATCH 100/500] `needless_return`: remove multiple semis on suggestion --- clippy_lints/src/returns.rs | 26 ++++++++++++++------------ clippy_utils/src/lib.rs | 4 ++++ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/clippy_lints/src/returns.rs b/clippy_lints/src/returns.rs index bbbd9e4989e97..42c51d7d07102 100644 --- a/clippy_lints/src/returns.rs +++ b/clippy_lints/src/returns.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::{span_lint_and_then, span_lint_hir_and_then}; use clippy_utils::source::{snippet_opt, snippet_with_context}; use clippy_utils::visitors::{for_each_expr, Descend}; -use clippy_utils::{fn_def_id, path_to_local_id}; +use clippy_utils::{fn_def_id, path_to_local_id, span_find_starting_semi}; use core::ops::ControlFlow; use if_chain::if_chain; use rustc_errors::Applicability; @@ -151,7 +151,7 @@ impl<'tcx> LateLintPass<'tcx> for Return { kind: FnKind<'tcx>, _: &'tcx FnDecl<'tcx>, body: &'tcx Body<'tcx>, - _: Span, + sp: Span, _: HirId, ) { match kind { @@ -166,14 +166,14 @@ impl<'tcx> LateLintPass<'tcx> for Return { check_final_expr(cx, body.value, vec![], replacement); }, FnKind::ItemFn(..) | FnKind::Method(..) => { - check_block_return(cx, &body.value.kind, vec![]); + check_block_return(cx, &body.value.kind, sp, vec![]); }, } } } // if `expr` is a block, check if there are needless returns in it -fn check_block_return<'tcx>(cx: &LateContext<'tcx>, expr_kind: &ExprKind<'tcx>, semi_spans: Vec) { +fn check_block_return<'tcx>(cx: &LateContext<'tcx>, expr_kind: &ExprKind<'tcx>, sp: Span, mut semi_spans: Vec) { if let ExprKind::Block(block, _) = expr_kind { if let Some(block_expr) = block.expr { check_final_expr(cx, block_expr, semi_spans, RetReplacement::Empty); @@ -183,12 +183,14 @@ fn check_block_return<'tcx>(cx: &LateContext<'tcx>, expr_kind: &ExprKind<'tcx>, check_final_expr(cx, expr, semi_spans, RetReplacement::Empty); }, StmtKind::Semi(semi_expr) => { - let mut semi_spans_and_this_one = semi_spans; - // we only want the span containing the semicolon so we can remove it later. From `entry.rs:382` - if let Some(semicolon_span) = stmt.span.trim_start(semi_expr.span) { - semi_spans_and_this_one.push(semicolon_span); - check_final_expr(cx, semi_expr, semi_spans_and_this_one, RetReplacement::Empty); + // Remove ending semicolons and any whitespace ' ' in between. + // Without `return`, the suggestion might not compile if the semicolon is retained + if let Some(semi_span) = stmt.span.trim_start(semi_expr.span) { + let semi_span_to_remove = + span_find_starting_semi(cx.sess().source_map(), semi_span.with_hi(sp.hi())); + semi_spans.push(semi_span_to_remove); } + check_final_expr(cx, semi_expr, semi_spans, RetReplacement::Empty); }, _ => (), } @@ -231,9 +233,9 @@ fn check_final_expr<'tcx>( emit_return_lint(cx, ret_span, semi_spans, inner.as_ref().map(|i| i.span), replacement); }, ExprKind::If(_, then, else_clause_opt) => { - check_block_return(cx, &then.kind, semi_spans.clone()); + check_block_return(cx, &then.kind, peeled_drop_expr.span, semi_spans.clone()); if let Some(else_clause) = else_clause_opt { - check_block_return(cx, &else_clause.kind, semi_spans); + check_block_return(cx, &else_clause.kind, peeled_drop_expr.span, semi_spans); } }, // a match expr, check all arms @@ -246,7 +248,7 @@ fn check_final_expr<'tcx>( } }, // if it's a whole block, check it - other_expr_kind => check_block_return(cx, other_expr_kind, semi_spans), + other_expr_kind => check_block_return(cx, other_expr_kind, peeled_drop_expr.span, semi_spans), } } diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index 1dc68be31d923..76f406abf1c7b 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -2488,6 +2488,10 @@ pub fn span_extract_comment(sm: &SourceMap, span: Span) -> String { comments_buf.join("\n") } +pub fn span_find_starting_semi(sm: &SourceMap, span: Span) -> Span { + sm.span_take_while(span, |&ch| ch == ' ' || ch == ';') +} + macro_rules! op_utils { ($($name:ident $assign:ident)*) => { /// Binary operation traits like `LangItem::Add` From 8c8aa3873f1c7177d532a6093da5e9836611ed4c Mon Sep 17 00:00:00 2001 From: Albert Larsan <74931857+albertlarsan68@users.noreply.github.com> Date: Thu, 5 Jan 2023 09:45:44 +0100 Subject: [PATCH 101/500] Change `src/test` to `tests` in source files, fix tidy and tests --- tests/source/issue-2445.rs | 4 ++-- tests/target/issue-2445.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/source/issue-2445.rs b/tests/source/issue-2445.rs index 84ce6e647b83c..deef429dbee08 100644 --- a/tests/source/issue-2445.rs +++ b/tests/source/issue-2445.rs @@ -1,6 +1,6 @@ test!(RunPassPretty { // comment - path: "src/test/run-pass/pretty", + path: "tests/run-pass/pretty", mode: "pretty", suite: "run-pass", default: false, @@ -9,7 +9,7 @@ test!(RunPassPretty { test!(RunPassPretty { // comment - path: "src/test/run-pass/pretty", + path: "tests/run-pass/pretty", mode: "pretty", suite: "run-pass", default: false, diff --git a/tests/target/issue-2445.rs b/tests/target/issue-2445.rs index 1bc7752fd1619..463c5d4957686 100644 --- a/tests/target/issue-2445.rs +++ b/tests/target/issue-2445.rs @@ -1,6 +1,6 @@ test!(RunPassPretty { // comment - path: "src/test/run-pass/pretty", + path: "tests/run-pass/pretty", mode: "pretty", suite: "run-pass", default: false, @@ -9,7 +9,7 @@ test!(RunPassPretty { test!(RunPassPretty { // comment - path: "src/test/run-pass/pretty", + path: "tests/run-pass/pretty", mode: "pretty", suite: "run-pass", default: false, From 4e47bd0464ce119a903e95b2dc20260258776d8e Mon Sep 17 00:00:00 2001 From: Albert Larsan <74931857+albertlarsan68@users.noreply.github.com> Date: Thu, 5 Jan 2023 09:45:44 +0100 Subject: [PATCH 102/500] Change `src/test` to `tests` in source files, fix tidy and tests --- scripts/test_rustc_tests.sh | 132 ++++++++++++++++++------------------ 1 file changed, 66 insertions(+), 66 deletions(-) diff --git a/scripts/test_rustc_tests.sh b/scripts/test_rustc_tests.sh index 04ad77ec97eac..12ecb8cf4e17d 100755 --- a/scripts/test_rustc_tests.sh +++ b/scripts/test_rustc_tests.sh @@ -10,118 +10,118 @@ pushd rust command -v rg >/dev/null 2>&1 || cargo install ripgrep -rm -r src/test/ui/{extern/,unsized-locals/,lto/,linkage*} || true -for test in $(rg --files-with-matches "lto|// needs-asm-support|// needs-unwind" src/test/{ui,incremental}); do +rm -r tests/ui/{extern/,unsized-locals/,lto/,linkage*} || true +for test in $(rg --files-with-matches "lto|// needs-asm-support|// needs-unwind" tests/{ui,incremental}); do rm $test done -for test in $(rg -i --files-with-matches "//(\[\w+\])?~[^\|]*\s*ERR|// error-pattern:|// build-fail|// run-fail|-Cllvm-args" src/test/ui); do +for test in $(rg -i --files-with-matches "//(\[\w+\])?~[^\|]*\s*ERR|// error-pattern:|// build-fail|// run-fail|-Cllvm-args" tests/ui); do rm $test done -git checkout -- src/test/ui/issues/auxiliary/issue-3136-a.rs # contains //~ERROR, but shouldn't be removed -git checkout -- src/test/ui/proc-macro/pretty-print-hack/ +git checkout -- tests/ui/issues/auxiliary/issue-3136-a.rs # contains //~ERROR, but shouldn't be removed +git checkout -- tests/ui/proc-macro/pretty-print-hack/ # missing features # ================ # requires stack unwinding -rm src/test/incremental/change_crate_dep_kind.rs -rm src/test/incremental/issue-80691-bad-eval-cache.rs # -Cpanic=abort causes abort instead of exit(101) +rm tests/incremental/change_crate_dep_kind.rs +rm tests/incremental/issue-80691-bad-eval-cache.rs # -Cpanic=abort causes abort instead of exit(101) # requires compiling with -Cpanic=unwind -rm -r src/test/ui/macros/rfc-2011-nicer-assert-messages/ -rm -r src/test/run-make/test-benches +rm -r tests/ui/macros/rfc-2011-nicer-assert-messages/ +rm -r tests/run-make/test-benches # vendor intrinsics -rm src/test/ui/sse2.rs # cpuid not supported, so sse2 not detected -rm src/test/ui/intrinsics/const-eval-select-x86_64.rs # requires x86_64 vendor intrinsics -rm src/test/ui/simd/array-type.rs # "Index argument for `simd_insert` is not a constant" -rm src/test/ui/simd/intrinsic/generic-bitmask-pass.rs # simd_bitmask unimplemented -rm src/test/ui/simd/intrinsic/generic-as.rs # simd_as unimplemented -rm src/test/ui/simd/intrinsic/generic-arithmetic-saturating-pass.rs # simd_saturating_add unimplemented -rm src/test/ui/simd/intrinsic/float-math-pass.rs # simd_fcos unimplemented -rm src/test/ui/simd/intrinsic/generic-gather-pass.rs # simd_gather unimplemented -rm src/test/ui/simd/intrinsic/generic-select-pass.rs # simd_select_bitmask unimplemented -rm src/test/ui/simd/issue-85915-simd-ptrs.rs # simd_gather unimplemented -rm src/test/ui/simd/issue-89193.rs # simd_gather unimplemented -rm src/test/ui/simd/simd-bitmask.rs # simd_bitmask unimplemented +rm tests/ui/sse2.rs # cpuid not supported, so sse2 not detected +rm tests/ui/intrinsics/const-eval-select-x86_64.rs # requires x86_64 vendor intrinsics +rm tests/ui/simd/array-type.rs # "Index argument for `simd_insert` is not a constant" +rm tests/ui/simd/intrinsic/generic-bitmask-pass.rs # simd_bitmask unimplemented +rm tests/ui/simd/intrinsic/generic-as.rs # simd_as unimplemented +rm tests/ui/simd/intrinsic/generic-arithmetic-saturating-pass.rs # simd_saturating_add unimplemented +rm tests/ui/simd/intrinsic/float-math-pass.rs # simd_fcos unimplemented +rm tests/ui/simd/intrinsic/generic-gather-pass.rs # simd_gather unimplemented +rm tests/ui/simd/intrinsic/generic-select-pass.rs # simd_select_bitmask unimplemented +rm tests/ui/simd/issue-85915-simd-ptrs.rs # simd_gather unimplemented +rm tests/ui/simd/issue-89193.rs # simd_gather unimplemented +rm tests/ui/simd/simd-bitmask.rs # simd_bitmask unimplemented # exotic linkages -rm src/test/ui/issues/issue-33992.rs # unsupported linkages -rm src/test/incremental/hashes/function_interfaces.rs # same -rm src/test/incremental/hashes/statics.rs # same +rm tests/ui/issues/issue-33992.rs # unsupported linkages +rm tests/incremental/hashes/function_interfaces.rs # same +rm tests/incremental/hashes/statics.rs # same # variadic arguments -rm src/test/ui/abi/mir/mir_codegen_calls_variadic.rs # requires float varargs -rm src/test/ui/abi/variadic-ffi.rs # requires callee side vararg support +rm tests/ui/abi/mir/mir_codegen_calls_variadic.rs # requires float varargs +rm tests/ui/abi/variadic-ffi.rs # requires callee side vararg support # unsized locals -rm -r src/test/run-pass-valgrind/unsized-locals +rm -r tests/run-pass-valgrind/unsized-locals # misc unimplemented things -rm src/test/ui/intrinsics/intrinsic-nearby.rs # unimplemented nearbyintf32 and nearbyintf64 intrinsics -rm src/test/ui/target-feature/missing-plusminus.rs # error not implemented -rm src/test/ui/fn/dyn-fn-alignment.rs # wants a 256 byte alignment -rm -r src/test/run-make/emit-named-files # requires full --emit support -rm src/test/ui/abi/stack-probes.rs # stack probes not yet implemented -rm src/test/ui/simd/intrinsic/ptr-cast.rs # simd_expose_addr intrinsic unimplemented -rm -r src/test/run-make/repr128-dwarf # debuginfo test -rm src/test/codegen-units/item-collection/asm-sym.rs # requires support for sym in asm!() +rm tests/ui/intrinsics/intrinsic-nearby.rs # unimplemented nearbyintf32 and nearbyintf64 intrinsics +rm tests/ui/target-feature/missing-plusminus.rs # error not implemented +rm tests/ui/fn/dyn-fn-alignment.rs # wants a 256 byte alignment +rm -r tests/run-make/emit-named-files # requires full --emit support +rm tests/ui/abi/stack-probes.rs # stack probes not yet implemented +rm tests/ui/simd/intrinsic/ptr-cast.rs # simd_expose_addr intrinsic unimplemented +rm -r tests/run-make/repr128-dwarf # debuginfo test +rm tests/codegen-units/item-collection/asm-sym.rs # requires support for sym in asm!() # optimization tests # ================== -rm src/test/ui/codegen/issue-28950.rs # depends on stack size optimizations -rm src/test/ui/codegen/init-large-type.rs # same -rm src/test/ui/issues/issue-40883.rs # same -rm -r src/test/run-make/fmt-write-bloat/ # tests an optimization +rm tests/ui/codegen/issue-28950.rs # depends on stack size optimizations +rm tests/ui/codegen/init-large-type.rs # same +rm tests/ui/issues/issue-40883.rs # same +rm -r tests/run-make/fmt-write-bloat/ # tests an optimization # backend specific tests # ====================== -rm src/test/incremental/thinlto/cgu_invalidated_when_import_{added,removed}.rs # requires LLVM -rm src/test/ui/abi/stack-protector.rs # requires stack protector support +rm tests/incremental/thinlto/cgu_invalidated_when_import_{added,removed}.rs # requires LLVM +rm tests/ui/abi/stack-protector.rs # requires stack protector support # giving different but possibly correct results # ============================================= -rm src/test/ui/mir/mir_misc_casts.rs # depends on deduplication of constants -rm src/test/ui/mir/mir_raw_fat_ptr.rs # same -rm src/test/ui/consts/issue-33537.rs # same -rm src/test/ui/layout/valid_range_oob.rs # different ICE message +rm tests/ui/mir/mir_misc_casts.rs # depends on deduplication of constants +rm tests/ui/mir/mir_raw_fat_ptr.rs # same +rm tests/ui/consts/issue-33537.rs # same +rm tests/ui/layout/valid_range_oob.rs # different ICE message # doesn't work due to the way the rustc test suite is invoked. # should work when using ./x.py test the way it is intended # ============================================================ -rm -r src/test/run-make/emit-shared-files # requires the rustdoc executable in dist/bin/ -rm -r src/test/run-make/unstable-flag-required # same -rm -r src/test/run-make/rustdoc-* # same -rm -r src/test/run-make/issue-88756-default-output # same -rm -r src/test/run-make/remap-path-prefix-dwarf # requires llvm-dwarfdump -rm -r src/test/ui/consts/missing_span_in_backtrace.rs # expects sysroot source to be elsewhere +rm -r tests/run-make/emit-shared-files # requires the rustdoc executable in dist/bin/ +rm -r tests/run-make/unstable-flag-required # same +rm -r tests/run-make/rustdoc-* # same +rm -r tests/run-make/issue-88756-default-output # same +rm -r tests/run-make/remap-path-prefix-dwarf # requires llvm-dwarfdump +rm -r tests/ui/consts/missing_span_in_backtrace.rs # expects sysroot source to be elsewhere # genuine bugs # ============ -rm src/test/incremental/spike-neg1.rs # errors out for some reason -rm src/test/incremental/spike-neg2.rs # same -rm src/test/ui/issues/issue-74564-if-expr-stack-overflow.rs # gives a stackoverflow before the backend runs -rm src/test/ui/mir/ssa-analysis-regression-50041.rs # produces ICE -rm src/test/ui/type-alias-impl-trait/assoc-projection-ice.rs # produces ICE +rm tests/incremental/spike-neg1.rs # errors out for some reason +rm tests/incremental/spike-neg2.rs # same +rm tests/ui/issues/issue-74564-if-expr-stack-overflow.rs # gives a stackoverflow before the backend runs +rm tests/ui/mir/ssa-analysis-regression-50041.rs # produces ICE +rm tests/ui/type-alias-impl-trait/assoc-projection-ice.rs # produces ICE -rm src/test/ui/simd/intrinsic/generic-reduction-pass.rs # simd_reduce_add_unordered doesn't accept an accumulator for integer vectors +rm tests/ui/simd/intrinsic/generic-reduction-pass.rs # simd_reduce_add_unordered doesn't accept an accumulator for integer vectors -rm src/test/ui/runtime/out-of-stack.rs # SIGSEGV instead of SIGABRT for some reason (#1301) +rm tests/ui/runtime/out-of-stack.rs # SIGSEGV instead of SIGABRT for some reason (#1301) # bugs in the test suite # ====================== -rm src/test/ui/backtrace.rs # TODO warning -rm src/test/ui/simple_global_asm.rs # TODO add needs-asm-support -rm src/test/ui/test-attrs/test-type.rs # TODO panic message on stderr. correct stdout +rm tests/ui/backtrace.rs # TODO warning +rm tests/ui/simple_global_asm.rs # TODO add needs-asm-support +rm tests/ui/test-attrs/test-type.rs # TODO panic message on stderr. correct stdout # not sure if this is actually a bug in the test suite, but the symbol list shows the function without leading _ for some reason -rm -r src/test/run-make/native-link-modifier-bundle -rm src/test/ui/process/nofile-limit.rs # TODO some AArch64 linking issue -rm src/test/ui/dyn-star/dispatch-on-pin-mut.rs # TODO failed assertion in vtable::get_ptr_and_method_ref +rm -r tests/run-make/native-link-modifier-bundle +rm tests/ui/process/nofile-limit.rs # TODO some AArch64 linking issue +rm tests/ui/dyn-star/dispatch-on-pin-mut.rs # TODO failed assertion in vtable::get_ptr_and_method_ref -rm src/test/ui/stdio-is-blocking.rs # really slow with unoptimized libstd +rm tests/ui/stdio-is-blocking.rs # really slow with unoptimized libstd echo "[TEST] rustc test suite" -RUST_TEST_NOCAPTURE=1 COMPILETEST_FORCE_STAGE0=1 ./x.py test --stage 0 src/test/{codegen-units,run-make,run-pass-valgrind,ui,incremental} +RUST_TEST_NOCAPTURE=1 COMPILETEST_FORCE_STAGE0=1 ./x.py test --stage 0 tests/{codegen-units,run-make,run-pass-valgrind,ui,incremental} popd From fb788e375ad110fdcf6b0333745bf2cab29054ee Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Wed, 11 Jan 2023 13:59:14 +0000 Subject: [PATCH 103/500] Don't install hyperfine in y.rs prepare Missed in #1338 Part of #1290 --- build_system/prepare.rs | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/build_system/prepare.rs b/build_system/prepare.rs index 9ad4ddc92c5af..7c10b9b0c0f7f 100644 --- a/build_system/prepare.rs +++ b/build_system/prepare.rs @@ -18,17 +18,6 @@ pub(crate) fn prepare(dirs: &Dirs) { prepare_sysroot(dirs); - // FIXME maybe install this only locally? - eprintln!("[INSTALL] hyperfine"); - Command::new("cargo") - .arg("install") - .arg("hyperfine") - .env_remove("CARGO_TARGET_DIR") - .spawn() - .unwrap() - .wait() - .unwrap(); - super::abi_cafe::ABI_CAFE_REPO.fetch(dirs); super::tests::RAND_REPO.fetch(dirs); super::tests::REGEX_REPO.fetch(dirs); From caacef29e6ad63d6b588715e809e78286d29db3f Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Wed, 11 Jan 2023 14:14:14 +0000 Subject: [PATCH 104/500] Retry downloads on network failure Fixes #1280 --- build_system/prepare.rs | 20 +++++++++++++++++--- build_system/utils.rs | 16 ++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/build_system/prepare.rs b/build_system/prepare.rs index 7c10b9b0c0f7f..106b06296b4b9 100644 --- a/build_system/prepare.rs +++ b/build_system/prepare.rs @@ -8,7 +8,7 @@ use crate::build_system::rustc_info::get_default_sysroot; use super::build_sysroot::{BUILD_SYSROOT, ORIG_BUILD_SYSROOT, SYSROOT_RUSTC_VERSION, SYSROOT_SRC}; use super::path::{Dirs, RelPath}; use super::rustc_info::{get_file_name, get_rustc_version}; -use super::utils::{copy_dir_recursively, spawn_and_wait, Compiler}; +use super::utils::{copy_dir_recursively, retry_spawn_and_wait, spawn_and_wait, Compiler}; pub(crate) fn prepare(dirs: &Dirs) { if RelPath::DOWNLOAD.to_path(dirs).exists() { @@ -140,8 +140,22 @@ fn clone_repo_shallow_github(dirs: &Dirs, download_dir: &Path, user: &str, repo: // Download zip archive let mut download_cmd = Command::new("curl"); - download_cmd.arg("--location").arg("--output").arg(&archive_file).arg(archive_url); - spawn_and_wait(download_cmd); + download_cmd + .arg("--max-time") + .arg("600") + .arg("-y") + .arg("30") + .arg("-Y") + .arg("10") + .arg("--connect-timeout") + .arg("30") + .arg("--continue-at") + .arg("-") + .arg("--location") + .arg("--output") + .arg(&archive_file) + .arg(archive_url); + retry_spawn_and_wait(5, download_cmd); // Unpack tar archive let mut unpack_cmd = Command::new("tar"); diff --git a/build_system/utils.rs b/build_system/utils.rs index 995918ee1430b..3c27af0196e7f 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -188,6 +188,22 @@ pub(crate) fn spawn_and_wait(mut cmd: Command) { } } +// Based on the retry function in rust's src/ci/shared.sh +#[track_caller] +pub(crate) fn retry_spawn_and_wait(tries: u64, mut cmd: Command) { + for i in 1..tries+1 { + if i != 1 { + println!("Command failed. Attempt {i}/{tries}:"); + } + if cmd.spawn().unwrap().wait().unwrap().success() { + return; + } + std::thread::sleep(std::time::Duration::from_secs(i * 5)); + } + println!("The command has failed after {tries} attempts."); + process::exit(1); +} + #[track_caller] pub(crate) fn spawn_and_wait_with_input(mut cmd: Command, input: String) -> String { let mut child = cmd From 868638393eb79bf53ba00be6000930f9ecf8751e Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Wed, 11 Jan 2023 15:23:15 +0000 Subject: [PATCH 105/500] Rustfmt --- build_system/utils.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build_system/utils.rs b/build_system/utils.rs index 3c27af0196e7f..3d6617d445843 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -191,7 +191,7 @@ pub(crate) fn spawn_and_wait(mut cmd: Command) { // Based on the retry function in rust's src/ci/shared.sh #[track_caller] pub(crate) fn retry_spawn_and_wait(tries: u64, mut cmd: Command) { - for i in 1..tries+1 { + for i in 1..tries + 1 { if i != 1 { println!("Command failed. Attempt {i}/{tries}:"); } From 43105c10d22cb1943d73b38423336e9441c47f6d Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 11 Jan 2023 21:35:46 +0100 Subject: [PATCH 106/500] Add some helper functions to LoweringContext. --- compiler/rustc_ast_lowering/src/expr.rs | 73 ++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 14f082be9ba8c..e21082894bde2 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -16,7 +16,7 @@ use rustc_hir::def::Res; use rustc_hir::definitions::DefPathData; use rustc_session::errors::report_lit_error; use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned}; -use rustc_span::symbol::{sym, Ident}; +use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::DUMMY_SP; use thin_vec::thin_vec; @@ -1757,6 +1757,43 @@ impl<'hir> LoweringContext<'_, 'hir> { self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]))) } + pub(super) fn expr_usize(&mut self, sp: Span, value: usize) -> hir::Expr<'hir> { + self.expr( + sp, + hir::ExprKind::Lit(hir::Lit { + span: sp, + node: ast::LitKind::Int( + value as u128, + ast::LitIntType::Unsigned(ast::UintTy::Usize), + ), + }), + ) + } + + pub(super) fn expr_u32(&mut self, sp: Span, value: u32) -> hir::Expr<'hir> { + self.expr( + sp, + hir::ExprKind::Lit(hir::Lit { + span: sp, + node: ast::LitKind::Int(value.into(), ast::LitIntType::Unsigned(ast::UintTy::U32)), + }), + ) + } + + pub(super) fn expr_char(&mut self, sp: Span, value: char) -> hir::Expr<'hir> { + self.expr(sp, hir::ExprKind::Lit(hir::Lit { span: sp, node: ast::LitKind::Char(value) })) + } + + pub(super) fn expr_str(&mut self, sp: Span, value: Symbol) -> hir::Expr<'hir> { + self.expr( + sp, + hir::ExprKind::Lit(hir::Lit { + span: sp, + node: ast::LitKind::Str(value, ast::StrStyle::Cooked), + }), + ) + } + fn expr_call_mut( &mut self, span: Span, @@ -1808,6 +1845,27 @@ impl<'hir> LoweringContext<'_, 'hir> { ) } + /// `::name` + pub(super) fn expr_lang_item_type_relative( + &mut self, + span: Span, + lang_item: hir::LangItem, + name: Symbol, + ) -> hir::Expr<'hir> { + let path = hir::ExprKind::Path(hir::QPath::TypeRelative( + self.arena.alloc(self.ty( + span, + hir::TyKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), None)), + )), + self.arena.alloc(hir::PathSegment::new( + Ident::new(name, span), + self.next_id(), + Res::Err, + )), + )); + self.expr(span, path) + } + pub(super) fn expr_ident( &mut self, sp: Span, @@ -1866,6 +1924,19 @@ impl<'hir> LoweringContext<'_, 'hir> { self.expr(b.span, hir::ExprKind::Block(b, None)) } + pub(super) fn expr_array_ref( + &mut self, + span: Span, + elements: &'hir [hir::Expr<'hir>], + ) -> hir::Expr<'hir> { + let addrof = hir::ExprKind::AddrOf( + hir::BorrowKind::Ref, + hir::Mutability::Not, + self.arena.alloc(self.expr(span, hir::ExprKind::Array(elements))), + ); + self.expr(span, addrof) + } + pub(super) fn expr(&mut self, span: Span, kind: hir::ExprKind<'hir>) -> hir::Expr<'hir> { let hir_id = self.next_id(); hir::Expr { hir_id, kind, span: self.lower_span(span) } From 3c4517659213c67e3ca6f3ef50ef9065385dca54 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 11 Jan 2023 21:41:34 +0100 Subject: [PATCH 107/500] Expose some LoweringContext methods. --- compiler/rustc_ast_lowering/src/expr.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index e21082894bde2..51f290bc587e9 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -1729,7 +1729,7 @@ impl<'hir> LoweringContext<'_, 'hir> { self.expr(span, hir::ExprKind::DropTemps(expr)) } - fn expr_match( + pub(super) fn expr_match( &mut self, span: Span, arg: &'hir hir::Expr<'hir>, @@ -1794,7 +1794,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ) } - fn expr_call_mut( + pub(super) fn expr_call_mut( &mut self, span: Span, e: &'hir hir::Expr<'hir>, @@ -1803,7 +1803,7 @@ impl<'hir> LoweringContext<'_, 'hir> { self.expr(span, hir::ExprKind::Call(e, args)) } - fn expr_call( + pub(super) fn expr_call( &mut self, span: Span, e: &'hir hir::Expr<'hir>, @@ -1942,7 +1942,7 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::Expr { hir_id, kind, span: self.lower_span(span) } } - fn expr_field( + pub(super) fn expr_field( &mut self, ident: Ident, expr: &'hir hir::Expr<'hir>, @@ -1957,7 +1957,11 @@ impl<'hir> LoweringContext<'_, 'hir> { } } - fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> { + pub(super) fn arm( + &mut self, + pat: &'hir hir::Pat<'hir>, + expr: &'hir hir::Expr<'hir>, + ) -> hir::Arm<'hir> { hir::Arm { hir_id: self.next_id(), pat, From bebf9fe0635ad58bff020b754cd0f24c35291d51 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 11 Jan 2023 21:36:46 +0100 Subject: [PATCH 108/500] Turn format arguments types into lang items. --- compiler/rustc_hir/src/lang_items.rs | 8 ++++++++ compiler/rustc_span/src/symbol.rs | 6 ++++++ library/core/src/fmt/mod.rs | 4 +++- library/core/src/fmt/rt/v1.rs | 4 ++++ 4 files changed, 21 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_hir/src/lang_items.rs b/compiler/rustc_hir/src/lang_items.rs index 3474fab34f00b..cb62317909c4c 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -244,6 +244,14 @@ language_item_table! { /// libstd panic entry point. Necessary for const eval to be able to catch it BeginPanic, sym::begin_panic, begin_panic_fn, Target::Fn, GenericRequirement::None; + // Lang items needed for `format_args!()`. + FormatAlignment, sym::format_alignment, format_alignment, Target::Enum, GenericRequirement::None; + FormatArgument, sym::format_argument, format_argument, Target::Struct, GenericRequirement::None; + FormatArguments, sym::format_arguments, format_arguments, Target::Struct, GenericRequirement::None; + FormatCount, sym::format_count, format_count, Target::Enum, GenericRequirement::None; + FormatPlaceholder, sym::format_placeholder, format_placeholder, Target::Struct, GenericRequirement::None; + FormatUnsafeArg, sym::format_unsafe_arg, format_unsafe_arg, Target::Struct, GenericRequirement::None; + ExchangeMalloc, sym::exchange_malloc, exchange_malloc_fn, Target::Fn, GenericRequirement::None; BoxFree, sym::box_free, box_free_fn, Target::Fn, GenericRequirement::Minimum(1); DropInPlace, sym::drop_in_place, drop_in_place_fn, Target::Fn, GenericRequirement::Minimum(1); diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index fbb12701d96ab..f8cd5ba03dbe0 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -721,11 +721,17 @@ symbols! { forbid, forget, format, + format_alignment, format_args, format_args_capture, format_args_macro, format_args_nl, + format_argument, + format_arguments, + format_count, format_macro, + format_placeholder, + format_unsafe_arg, freeze, freg, frem_fast, diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index 51e6a76cea848..ae2f7f049b64e 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -262,6 +262,7 @@ extern "C" { /// family of functions. It contains a function to format the given value. At /// compile time it is ensured that the function and the value have the correct /// types, and then this struct is used to canonicalize arguments to one type. +#[cfg_attr(not(bootstrap), lang = "format_argument")] #[derive(Copy, Clone)] #[allow(missing_debug_implementations)] #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")] @@ -274,6 +275,7 @@ pub struct ArgumentV1<'a> { /// This struct represents the unsafety of constructing an `Arguments`. /// It exists, rather than an unsafe function, in order to simplify the expansion /// of `format_args!(..)` and reduce the scope of the `unsafe` block. +#[cfg_attr(not(bootstrap), lang = "format_unsafe_arg")] #[allow(missing_debug_implementations)] #[doc(hidden)] #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")] @@ -468,8 +470,8 @@ impl<'a> Arguments<'a> { /// ``` /// /// [`format()`]: ../../std/fmt/fn.format.html +#[cfg_attr(not(bootstrap), lang = "format_arguments")] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "Arguments")] #[derive(Copy, Clone)] pub struct Arguments<'a> { // Format string pieces to print. diff --git a/library/core/src/fmt/rt/v1.rs b/library/core/src/fmt/rt/v1.rs index 37202b2774dc6..8a3de89e18b76 100644 --- a/library/core/src/fmt/rt/v1.rs +++ b/library/core/src/fmt/rt/v1.rs @@ -5,7 +5,9 @@ //! these can be statically allocated and are slightly optimized for the runtime #![allow(missing_debug_implementations)] +#[cfg_attr(not(bootstrap), lang = "format_placeholder")] #[derive(Copy, Clone)] +// FIXME: Rename this to Placeholder pub struct Argument { pub position: usize, pub format: FormatSpec, @@ -21,6 +23,7 @@ pub struct FormatSpec { } /// Possible alignments that can be requested as part of a formatting directive. +#[cfg_attr(not(bootstrap), lang = "format_alignment")] #[derive(Copy, Clone, PartialEq, Eq)] pub enum Alignment { /// Indication that contents should be left-aligned. @@ -34,6 +37,7 @@ pub enum Alignment { } /// Used by [width](https://doc.rust-lang.org/std/fmt/#width) and [precision](https://doc.rust-lang.org/std/fmt/#precision) specifiers. +#[cfg_attr(not(bootstrap), lang = "format_count")] #[derive(Copy, Clone)] pub enum Count { /// Specified with a literal number, stores the value From e83945150f65eaf8b644a4042229fcac4c82596b Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 11 Jan 2023 21:37:27 +0100 Subject: [PATCH 109/500] Add new fn to core::fmt::rt::v1::Argument. --- library/core/src/fmt/rt/v1.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/library/core/src/fmt/rt/v1.rs b/library/core/src/fmt/rt/v1.rs index 8a3de89e18b76..e61b89fad5d3b 100644 --- a/library/core/src/fmt/rt/v1.rs +++ b/library/core/src/fmt/rt/v1.rs @@ -22,6 +22,19 @@ pub struct FormatSpec { pub width: Count, } +impl Argument { + pub fn new( + position: usize, + fill: char, + align: Alignment, + flags: u32, + precision: Count, + width: Count, + ) -> Self { + Self { position, format: FormatSpec { fill, align, flags, precision, width } } + } +} + /// Possible alignments that can be requested as part of a formatting directive. #[cfg_attr(not(bootstrap), lang = "format_alignment")] #[derive(Copy, Clone, PartialEq, Eq)] From c31944031184ebcd4704280db7233e306eba6967 Mon Sep 17 00:00:00 2001 From: asquared31415 <34665709+asquared31415@users.noreply.github.com> Date: Fri, 23 Dec 2022 13:54:14 -0500 Subject: [PATCH 110/500] add checks for the signature of the lang item --- tests/ui/def_id_nocore.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/ui/def_id_nocore.rs b/tests/ui/def_id_nocore.rs index a7da8f89aa3d4..1af77d1a25b2d 100644 --- a/tests/ui/def_id_nocore.rs +++ b/tests/ui/def_id_nocore.rs @@ -15,7 +15,7 @@ pub trait Copy {} pub unsafe trait Freeze {} #[lang = "start"] -fn start(_main: fn() -> T, _argc: isize, _argv: *const *const u8) -> isize { +fn start(_main: fn() -> T, _argc: isize, _argv: *const *const u8, _sigpipe: u8) -> isize { 0 } From f92000816e0cf8bdfe6ad422464ce0fa6144b496 Mon Sep 17 00:00:00 2001 From: mejrs <> Date: Tue, 3 Jan 2023 14:08:20 +0100 Subject: [PATCH 111/500] Improve proc macro attribute diagnostics --- .../locales/en-US/passes.ftl | 21 +++ compiler/rustc_passes/src/check_attr.rs | 130 +++++++++++++++++- compiler/rustc_passes/src/errors.rs | 50 +++++++ compiler/rustc_span/src/symbol.rs | 1 + library/proc_macro/src/lib.rs | 1 + tests/ui/proc-macro/proc-macro-abi.rs | 28 ++++ tests/ui/proc-macro/proc-macro-abi.stderr | 20 +++ .../signature-proc-macro-attribute.rs | 29 ++++ .../signature-proc-macro-attribute.stderr | 42 ++++++ .../proc-macro/signature-proc-macro-derive.rs | 28 ++++ .../signature-proc-macro-derive.stderr | 40 ++++++ tests/ui/proc-macro/signature-proc-macro.rs | 28 ++++ .../ui/proc-macro/signature-proc-macro.stderr | 40 ++++++ tests/ui/proc-macro/signature.rs | 6 +- tests/ui/proc-macro/signature.stderr | 46 +++++-- 15 files changed, 488 insertions(+), 22 deletions(-) create mode 100644 tests/ui/proc-macro/proc-macro-abi.rs create mode 100644 tests/ui/proc-macro/proc-macro-abi.stderr create mode 100644 tests/ui/proc-macro/signature-proc-macro-attribute.rs create mode 100644 tests/ui/proc-macro/signature-proc-macro-attribute.stderr create mode 100644 tests/ui/proc-macro/signature-proc-macro-derive.rs create mode 100644 tests/ui/proc-macro/signature-proc-macro-derive.stderr create mode 100644 tests/ui/proc-macro/signature-proc-macro.rs create mode 100644 tests/ui/proc-macro/signature-proc-macro.stderr diff --git a/compiler/rustc_error_messages/locales/en-US/passes.ftl b/compiler/rustc_error_messages/locales/en-US/passes.ftl index 001e53d1d0e4c..63db6b6837b47 100644 --- a/compiler/rustc_error_messages/locales/en-US/passes.ftl +++ b/compiler/rustc_error_messages/locales/en-US/passes.ftl @@ -707,3 +707,24 @@ passes_ignored_derived_impls = [one] trait {$trait_list}, but this is *[other] traits {$trait_list}, but these are } intentionally ignored during dead code analysis + +passes_proc_macro_typeerror = mismatched {$kind} signature + .label = found {$found}, expected type `proc_macro::TokenStream` + .note = {$kind}s must have a signature of `{$expected_signature}` + +passes_proc_macro_diff_arg_count = mismatched {$kind} signature + .label = found unexpected {$count -> + [one] argument + *[other] arguments + } + .note = {$kind}s must have a signature of `{$expected_signature}` + +passes_proc_macro_missing_args = mismatched {$kind} signature + .label = {$kind} must have {$expected_input_count -> + [one] one argument + *[other] two arguments + } of type `proc_macro::TokenStream` + +passes_proc_macro_invalid_abi = proc macro functions may not be `extern "{$abi}"` + +passes_proc_macro_unsafe = proc macro functions may not be `unsafe` diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index c59c06ac31ed7..517bf2533c5e6 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -6,11 +6,12 @@ use crate::errors::{ self, AttrApplication, DebugVisualizerUnreadable, InvalidAttrAtCrateLevel, ObjectLifetimeErr, - OnlyHasEffectOn, TransparentIncompatible, UnrecognizedReprHint, + OnlyHasEffectOn, ProcMacroDiffArguments, ProcMacroInvalidAbi, ProcMacroMissingArguments, + ProcMacroTypeError, ProcMacroUnsafe, TransparentIncompatible, UnrecognizedReprHint, }; use rustc_ast::{ast, AttrStyle, Attribute, LitKind, MetaItemKind, MetaItemLit, NestedMetaItem}; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::{fluent, Applicability, MultiSpan}; +use rustc_errors::{fluent, Applicability, IntoDiagnosticArg, MultiSpan}; use rustc_expand::base::resolve_path; use rustc_feature::{AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP}; use rustc_hir as hir; @@ -19,11 +20,11 @@ use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{ self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID, }; -use rustc_hir::{MethodKind, Target}; +use rustc_hir::{MethodKind, Target, Unsafety}; use rustc_middle::hir::nested_filter; use rustc_middle::middle::resolve_lifetime::ObjectLifetimeDefault; use rustc_middle::ty::query::Providers; -use rustc_middle::ty::TyCtxt; +use rustc_middle::ty::{ParamEnv, TyCtxt}; use rustc_session::lint::builtin::{ CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES, }; @@ -31,6 +32,7 @@ use rustc_session::parse::feature_err; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::{Span, DUMMY_SP}; use rustc_target::spec::abi::Abi; +use std::cell::Cell; use std::collections::hash_map::Entry; pub(crate) fn target_from_impl_item<'tcx>( @@ -62,8 +64,27 @@ enum ItemLike<'tcx> { ForeignItem, } +#[derive(Copy, Clone)] +pub(crate) enum ProcMacroKind { + FunctionLike, + Derive, + Attribute, +} + +impl IntoDiagnosticArg for ProcMacroKind { + fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> { + match self { + ProcMacroKind::Attribute => "attribute proc macro", + ProcMacroKind::Derive => "derive proc macro", + ProcMacroKind::FunctionLike => "function-like proc macro", + } + .into_diagnostic_arg() + } +} + struct CheckAttrVisitor<'tcx> { tcx: TyCtxt<'tcx>, + abort: Cell, } impl CheckAttrVisitor<'_> { @@ -172,7 +193,7 @@ impl CheckAttrVisitor<'_> { sym::path => self.check_generic_attr(hir_id, attr, target, Target::Mod), sym::plugin_registrar => self.check_plugin_registrar(hir_id, attr, target), sym::macro_export => self.check_macro_export(hir_id, attr, target), - sym::ignore | sym::should_panic | sym::proc_macro_derive => { + sym::ignore | sym::should_panic => { self.check_generic_attr(hir_id, attr, target, Target::Fn) } sym::automatically_derived => { @@ -182,6 +203,16 @@ impl CheckAttrVisitor<'_> { self.check_generic_attr(hir_id, attr, target, Target::Mod) } sym::rustc_object_lifetime_default => self.check_object_lifetime_default(hir_id), + sym::proc_macro => { + self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike) + } + sym::proc_macro_attribute => { + self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute); + } + sym::proc_macro_derive => { + self.check_generic_attr(hir_id, attr, target, Target::Fn); + self.check_proc_macro(hir_id, target, ProcMacroKind::Derive) + } _ => {} } @@ -2052,6 +2083,90 @@ impl CheckAttrVisitor<'_> { errors::Unused { attr_span: attr.span, note }, ); } + + fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) { + let expected_input_count = match kind { + ProcMacroKind::Attribute => 2, + ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1, + }; + + let expected_signature = match kind { + ProcMacroKind::Attribute => "fn(TokenStream, TokenStream) -> TokenStream", + ProcMacroKind::Derive | ProcMacroKind::FunctionLike => "fn(TokenStream) -> TokenStream", + }; + + let tcx = self.tcx; + if target == Target::Fn { + let Some(tokenstream) = tcx.get_diagnostic_item(sym::TokenStream) else {return}; + let tokenstream = tcx.type_of(tokenstream); + + let id = hir_id.expect_owner(); + let hir_sig = tcx.hir().fn_sig_by_hir_id(hir_id).unwrap(); + + let sig = tcx.fn_sig(id); + + if sig.abi() != Abi::Rust { + tcx.sess + .emit_err(ProcMacroInvalidAbi { span: hir_sig.span, abi: sig.abi().name() }); + self.abort.set(true); + } + + if sig.unsafety() == Unsafety::Unsafe { + tcx.sess.emit_err(ProcMacroUnsafe { span: hir_sig.span }); + self.abort.set(true); + } + + let output = sig.output().skip_binder(); + + // Typecheck the output + if tcx.normalize_erasing_regions(ParamEnv::empty(), output) != tokenstream { + tcx.sess.emit_err(ProcMacroTypeError { + span: hir_sig.decl.output.span(), + found: output, + kind, + expected_signature, + }); + self.abort.set(true); + } + + // Typecheck "expected_input_count" inputs, emitting + // `ProcMacroMissingArguments` if there are not enough. + if let Some(args) = sig.inputs().skip_binder().get(0..expected_input_count) { + for (arg, input) in args.iter().zip(hir_sig.decl.inputs) { + if tcx.normalize_erasing_regions(ParamEnv::empty(), *arg) != tokenstream { + tcx.sess.emit_err(ProcMacroTypeError { + span: input.span, + found: *arg, + kind, + expected_signature, + }); + self.abort.set(true); + } + } + } else { + tcx.sess.emit_err(ProcMacroMissingArguments { + expected_input_count, + span: hir_sig.span, + kind, + expected_signature, + }); + self.abort.set(true); + } + + // Check that there are not too many arguments + let body_id = tcx.hir().body_owned_by(id.def_id); + let excess = tcx.hir().body(body_id).params.get(expected_input_count..); + if let Some(excess @ [begin @ end] | excess @ [begin, .., end]) = excess { + tcx.sess.emit_err(ProcMacroDiffArguments { + span: begin.span.to(end.span), + count: excess.len(), + kind, + expected_signature, + }); + self.abort.set(true); + } + } + } } impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> { @@ -2214,12 +2329,15 @@ fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) } fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { - let check_attr_visitor = &mut CheckAttrVisitor { tcx }; + let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) }; tcx.hir().visit_item_likes_in_module(module_def_id, check_attr_visitor); if module_def_id.is_top_level_module() { check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None); check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs()); } + if check_attr_visitor.abort.get() { + tcx.sess.abort_if_errors() + } } pub(crate) fn provide(providers: &mut Providers) { diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index c6cd69add28a0..68103608ec9d9 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -12,6 +12,7 @@ use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::{MainDefinition, Ty}; use rustc_span::{Span, Symbol, DUMMY_SP}; +use crate::check_attr::ProcMacroKind; use crate::lang_items::Duplicate; #[derive(LintDiagnostic)] @@ -1508,3 +1509,52 @@ pub struct ChangeFieldsToBeOfUnitType { #[suggestion_part(code = "()")] pub spans: Vec, } + +#[derive(Diagnostic)] +#[diag(passes_proc_macro_typeerror)] +#[note] +pub(crate) struct ProcMacroTypeError<'tcx> { + #[primary_span] + #[label] + pub span: Span, + pub found: Ty<'tcx>, + pub kind: ProcMacroKind, + pub expected_signature: &'static str, +} + +#[derive(Diagnostic)] +#[diag(passes_proc_macro_diff_arg_count)] +pub(crate) struct ProcMacroDiffArguments { + #[primary_span] + #[label] + pub span: Span, + pub count: usize, + pub kind: ProcMacroKind, + pub expected_signature: &'static str, +} + +#[derive(Diagnostic)] +#[diag(passes_proc_macro_missing_args)] +pub(crate) struct ProcMacroMissingArguments { + #[primary_span] + #[label] + pub span: Span, + pub expected_input_count: usize, + pub kind: ProcMacroKind, + pub expected_signature: &'static str, +} + +#[derive(Diagnostic)] +#[diag(passes_proc_macro_invalid_abi)] +pub(crate) struct ProcMacroInvalidAbi { + #[primary_span] + pub span: Span, + pub abi: &'static str, +} + +#[derive(Diagnostic)] +#[diag(passes_proc_macro_unsafe)] +pub(crate) struct ProcMacroUnsafe { + #[primary_span] + pub span: Span, +} diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index fbb12701d96ab..0cc9567d4d672 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -287,6 +287,7 @@ symbols! { Target, ToOwned, ToString, + TokenStream, Try, TryCaptureGeneric, TryCapturePrintable, diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index f0e4f5d8a8013..8bff40c279aaa 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -74,6 +74,7 @@ pub fn is_available() -> bool { /// /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]` /// and `#[proc_macro_derive]` definitions. +#[rustc_diagnostic_item = "TokenStream"] #[stable(feature = "proc_macro_lib", since = "1.15.0")] #[derive(Clone)] pub struct TokenStream(Option); diff --git a/tests/ui/proc-macro/proc-macro-abi.rs b/tests/ui/proc-macro/proc-macro-abi.rs new file mode 100644 index 0000000000000..2a40ddd496ce8 --- /dev/null +++ b/tests/ui/proc-macro/proc-macro-abi.rs @@ -0,0 +1,28 @@ +#![crate_type = "proc-macro"] +#![allow(warnings)] + +extern crate proc_macro; +use proc_macro::TokenStream; + +#[proc_macro] +pub extern "C" fn abi(a: TokenStream) -> TokenStream { + //~^ ERROR proc macro functions may not be `extern + a +} + +#[proc_macro] +pub extern "system" fn abi2(a: TokenStream) -> TokenStream { + //~^ ERROR proc macro functions may not be `extern + a +} + +#[proc_macro] +pub extern fn abi3(a: TokenStream) -> TokenStream { + //~^ ERROR proc macro functions may not be `extern + a +} + +#[proc_macro] +pub extern "Rust" fn abi4(a: TokenStream) -> TokenStream { + a +} diff --git a/tests/ui/proc-macro/proc-macro-abi.stderr b/tests/ui/proc-macro/proc-macro-abi.stderr new file mode 100644 index 0000000000000..fa5f5dc098998 --- /dev/null +++ b/tests/ui/proc-macro/proc-macro-abi.stderr @@ -0,0 +1,20 @@ +error: proc macro functions may not be `extern "C"` + --> $DIR/proc-macro-abi.rs:8:1 + | +LL | pub extern "C" fn abi(a: TokenStream) -> TokenStream { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: proc macro functions may not be `extern "system"` + --> $DIR/proc-macro-abi.rs:14:1 + | +LL | pub extern "system" fn abi2(a: TokenStream) -> TokenStream { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: proc macro functions may not be `extern "C"` + --> $DIR/proc-macro-abi.rs:20:1 + | +LL | pub extern fn abi3(a: TokenStream) -> TokenStream { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 3 previous errors + diff --git a/tests/ui/proc-macro/signature-proc-macro-attribute.rs b/tests/ui/proc-macro/signature-proc-macro-attribute.rs new file mode 100644 index 0000000000000..fb17710950106 --- /dev/null +++ b/tests/ui/proc-macro/signature-proc-macro-attribute.rs @@ -0,0 +1,29 @@ +#![crate_type = "proc-macro"] + +extern crate proc_macro; +use proc_macro::TokenStream; + +#[proc_macro_attribute] +pub fn bad_input(input: String) -> TokenStream { + //~^ ERROR mismatched attribute proc macro signature + ::proc_macro::TokenStream::new() +} + +#[proc_macro_attribute] +pub fn bad_output(input: TokenStream) -> String { + //~^ ERROR mismatched attribute proc macro signature + //~| ERROR mismatched attribute proc macro signature + String::from("blah") +} + +#[proc_macro_attribute] +pub fn bad_everything(input: String) -> String { + //~^ ERROR mismatched attribute proc macro signature + //~| ERROR mismatched attribute proc macro signature + input +} + +#[proc_macro_attribute] +pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { + //~^ ERROR mismatched attribute proc macro signature +} diff --git a/tests/ui/proc-macro/signature-proc-macro-attribute.stderr b/tests/ui/proc-macro/signature-proc-macro-attribute.stderr new file mode 100644 index 0000000000000..ecfd2b06e109c --- /dev/null +++ b/tests/ui/proc-macro/signature-proc-macro-attribute.stderr @@ -0,0 +1,42 @@ +error: mismatched attribute proc macro signature + --> $DIR/signature-proc-macro-attribute.rs:7:1 + | +LL | pub fn bad_input(input: String) -> TokenStream { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ attribute proc macro must have two arguments of type `proc_macro::TokenStream` + +error: mismatched attribute proc macro signature + --> $DIR/signature-proc-macro-attribute.rs:13:42 + | +LL | pub fn bad_output(input: TokenStream) -> String { + | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` + | + = note: attribute proc macros must have a signature of `fn(TokenStream, TokenStream) -> TokenStream` + +error: mismatched attribute proc macro signature + --> $DIR/signature-proc-macro-attribute.rs:13:1 + | +LL | pub fn bad_output(input: TokenStream) -> String { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ attribute proc macro must have two arguments of type `proc_macro::TokenStream` + +error: mismatched attribute proc macro signature + --> $DIR/signature-proc-macro-attribute.rs:20:41 + | +LL | pub fn bad_everything(input: String) -> String { + | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` + | + = note: attribute proc macros must have a signature of `fn(TokenStream, TokenStream) -> TokenStream` + +error: mismatched attribute proc macro signature + --> $DIR/signature-proc-macro-attribute.rs:20:1 + | +LL | pub fn bad_everything(input: String) -> String { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ attribute proc macro must have two arguments of type `proc_macro::TokenStream` + +error: mismatched attribute proc macro signature + --> $DIR/signature-proc-macro-attribute.rs:27:49 + | +LL | pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { + | ^^^^^^^^^ found unexpected argument + +error: aborting due to 6 previous errors + diff --git a/tests/ui/proc-macro/signature-proc-macro-derive.rs b/tests/ui/proc-macro/signature-proc-macro-derive.rs new file mode 100644 index 0000000000000..a079157538fb6 --- /dev/null +++ b/tests/ui/proc-macro/signature-proc-macro-derive.rs @@ -0,0 +1,28 @@ +#![crate_type = "proc-macro"] + +extern crate proc_macro; +use proc_macro::TokenStream; + +#[proc_macro_derive(Blah)] +pub fn bad_input(input: String) -> TokenStream { + //~^ ERROR mismatched derive proc macro signature + TokenStream::new() +} + +#[proc_macro_derive(Bleh)] +pub fn bad_output(input: TokenStream) -> String { + //~^ ERROR mismatched derive proc macro signature + String::from("blah") +} + +#[proc_macro_derive(Bluh)] +pub fn bad_everything(input: String) -> String { + //~^ ERROR mismatched derive proc macro signature + //~| ERROR mismatched derive proc macro signature + input +} + +#[proc_macro_derive(Blih)] +pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { + //~^ ERROR mismatched derive proc macro signature +} diff --git a/tests/ui/proc-macro/signature-proc-macro-derive.stderr b/tests/ui/proc-macro/signature-proc-macro-derive.stderr new file mode 100644 index 0000000000000..bb2bd9a93d24b --- /dev/null +++ b/tests/ui/proc-macro/signature-proc-macro-derive.stderr @@ -0,0 +1,40 @@ +error: mismatched derive proc macro signature + --> $DIR/signature-proc-macro-derive.rs:7:25 + | +LL | pub fn bad_input(input: String) -> TokenStream { + | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` + | + = note: derive proc macros must have a signature of `fn(TokenStream) -> TokenStream` + +error: mismatched derive proc macro signature + --> $DIR/signature-proc-macro-derive.rs:13:42 + | +LL | pub fn bad_output(input: TokenStream) -> String { + | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` + | + = note: derive proc macros must have a signature of `fn(TokenStream) -> TokenStream` + +error: mismatched derive proc macro signature + --> $DIR/signature-proc-macro-derive.rs:19:41 + | +LL | pub fn bad_everything(input: String) -> String { + | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` + | + = note: derive proc macros must have a signature of `fn(TokenStream) -> TokenStream` + +error: mismatched derive proc macro signature + --> $DIR/signature-proc-macro-derive.rs:19:30 + | +LL | pub fn bad_everything(input: String) -> String { + | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` + | + = note: derive proc macros must have a signature of `fn(TokenStream) -> TokenStream` + +error: mismatched derive proc macro signature + --> $DIR/signature-proc-macro-derive.rs:26:33 + | +LL | pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { + | ^^^^^^^^^^^^^^^^^^^^^^^^^ found unexpected arguments + +error: aborting due to 5 previous errors + diff --git a/tests/ui/proc-macro/signature-proc-macro.rs b/tests/ui/proc-macro/signature-proc-macro.rs new file mode 100644 index 0000000000000..35d5be2171283 --- /dev/null +++ b/tests/ui/proc-macro/signature-proc-macro.rs @@ -0,0 +1,28 @@ +#![crate_type = "proc-macro"] + +extern crate proc_macro; +use proc_macro::TokenStream; + +#[proc_macro] +pub fn bad_input(input: String) -> TokenStream { + //~^ ERROR mismatched function-like proc macro signature + ::proc_macro::TokenStream::new() +} + +#[proc_macro] +pub fn bad_output(input: TokenStream) -> String { + //~^ ERROR mismatched function-like proc macro signature + String::from("blah") +} + +#[proc_macro] +pub fn bad_everything(input: String) -> String { + //~^ ERROR mismatched function-like proc macro signature + //~| ERROR mismatched function-like proc macro signature + input +} + +#[proc_macro] +pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { + //~^ ERROR mismatched function-like proc macro signature +} diff --git a/tests/ui/proc-macro/signature-proc-macro.stderr b/tests/ui/proc-macro/signature-proc-macro.stderr new file mode 100644 index 0000000000000..32241e1b9e00a --- /dev/null +++ b/tests/ui/proc-macro/signature-proc-macro.stderr @@ -0,0 +1,40 @@ +error: mismatched function-like proc macro signature + --> $DIR/signature-proc-macro.rs:7:25 + | +LL | pub fn bad_input(input: String) -> TokenStream { + | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` + | + = note: function-like proc macros must have a signature of `fn(TokenStream) -> TokenStream` + +error: mismatched function-like proc macro signature + --> $DIR/signature-proc-macro.rs:13:42 + | +LL | pub fn bad_output(input: TokenStream) -> String { + | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` + | + = note: function-like proc macros must have a signature of `fn(TokenStream) -> TokenStream` + +error: mismatched function-like proc macro signature + --> $DIR/signature-proc-macro.rs:19:41 + | +LL | pub fn bad_everything(input: String) -> String { + | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` + | + = note: function-like proc macros must have a signature of `fn(TokenStream) -> TokenStream` + +error: mismatched function-like proc macro signature + --> $DIR/signature-proc-macro.rs:19:30 + | +LL | pub fn bad_everything(input: String) -> String { + | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` + | + = note: function-like proc macros must have a signature of `fn(TokenStream) -> TokenStream` + +error: mismatched function-like proc macro signature + --> $DIR/signature-proc-macro.rs:26:33 + | +LL | pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { + | ^^^^^^^^^^^^^^^^^^^^^^^^^ found unexpected arguments + +error: aborting due to 5 previous errors + diff --git a/tests/ui/proc-macro/signature.rs b/tests/ui/proc-macro/signature.rs index 2302238253e82..11187aa31bd80 100644 --- a/tests/ui/proc-macro/signature.rs +++ b/tests/ui/proc-macro/signature.rs @@ -8,6 +8,10 @@ extern crate proc_macro; #[proc_macro_derive(A)] pub unsafe extern "C" fn foo(a: i32, b: u32) -> u32 { - //~^ ERROR: expected a `Fn<(proc_macro::TokenStream,)>` closure, found `unsafe extern "C" fn + //~^ ERROR: mismatched derive proc macro signature + //~| mismatched derive proc macro signature + //~| mismatched derive proc macro signature + //~| proc macro functions may not be `extern + //~| proc macro functions may not be `unsafe loop {} } diff --git a/tests/ui/proc-macro/signature.stderr b/tests/ui/proc-macro/signature.stderr index 79f2001da0055..3dbe3f22a0df8 100644 --- a/tests/ui/proc-macro/signature.stderr +++ b/tests/ui/proc-macro/signature.stderr @@ -1,20 +1,36 @@ -error[E0277]: expected a `Fn<(proc_macro::TokenStream,)>` closure, found `unsafe extern "C" fn(i32, u32) -> u32 {foo}` +error: proc macro functions may not be `extern "C"` --> $DIR/signature.rs:10:1 | -LL | / pub unsafe extern "C" fn foo(a: i32, b: u32) -> u32 { -LL | | -LL | | loop {} -LL | | } - | | ^ - | | | - | |_call the function in a closure: `|| unsafe { /* code */ }` - | required by a bound introduced by this call +LL | pub unsafe extern "C" fn foo(a: i32, b: u32) -> u32 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: proc macro functions may not be `unsafe` + --> $DIR/signature.rs:10:1 + | +LL | pub unsafe extern "C" fn foo(a: i32, b: u32) -> u32 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: mismatched derive proc macro signature + --> $DIR/signature.rs:10:49 + | +LL | pub unsafe extern "C" fn foo(a: i32, b: u32) -> u32 { + | ^^^ found u32, expected type `proc_macro::TokenStream` + | + = note: derive proc macros must have a signature of `fn(TokenStream) -> TokenStream` + +error: mismatched derive proc macro signature + --> $DIR/signature.rs:10:33 + | +LL | pub unsafe extern "C" fn foo(a: i32, b: u32) -> u32 { + | ^^^ found i32, expected type `proc_macro::TokenStream` + | + = note: derive proc macros must have a signature of `fn(TokenStream) -> TokenStream` + +error: mismatched derive proc macro signature + --> $DIR/signature.rs:10:38 | - = help: the trait `Fn<(proc_macro::TokenStream,)>` is not implemented for fn item `unsafe extern "C" fn(i32, u32) -> u32 {foo}` - = note: unsafe function cannot be called generically without an unsafe block -note: required by a bound in `ProcMacro::custom_derive` - --> $SRC_DIR/proc_macro/src/bridge/client.rs:LL:COL +LL | pub unsafe extern "C" fn foo(a: i32, b: u32) -> u32 { + | ^^^^^^ found unexpected argument -error: aborting due to previous error +error: aborting due to 5 previous errors -For more information about this error, try `rustc --explain E0277`. From a8e3abd04cf85080d921c2d1875e0094b2db5155 Mon Sep 17 00:00:00 2001 From: mejrs <> Date: Sun, 8 Jan 2023 01:37:22 +0100 Subject: [PATCH 112/500] Address feedback --- compiler/rustc_passes/src/check_attr.rs | 56 +++++++++++++++-------- tests/ui/proc-macro/allowed-signatures.rs | 24 ++++++++++ tests/ui/proc-macro/proc-macro-abi.rs | 6 +-- 3 files changed, 63 insertions(+), 23 deletions(-) create mode 100644 tests/ui/proc-macro/allowed-signatures.rs diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 517bf2533c5e6..c2ce46d965cf3 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -23,6 +23,7 @@ use rustc_hir::{ use rustc_hir::{MethodKind, Target, Unsafety}; use rustc_middle::hir::nested_filter; use rustc_middle::middle::resolve_lifetime::ObjectLifetimeDefault; +use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams}; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{ParamEnv, TyCtxt}; use rustc_session::lint::builtin::{ @@ -84,6 +85,8 @@ impl IntoDiagnosticArg for ProcMacroKind { struct CheckAttrVisitor<'tcx> { tcx: TyCtxt<'tcx>, + + // Whether or not this visitor should abort after finding errors abort: Cell, } @@ -2084,6 +2087,9 @@ impl CheckAttrVisitor<'_> { ); } + /// A best effort attempt to create an error for a mismatching proc macro signature. + /// + /// If this best effort goes wrong, it will just emit a worse error later (see #102923) fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) { let expected_input_count = match kind { ProcMacroKind::Attribute => 2, @@ -2103,23 +2109,30 @@ impl CheckAttrVisitor<'_> { let id = hir_id.expect_owner(); let hir_sig = tcx.hir().fn_sig_by_hir_id(hir_id).unwrap(); - let sig = tcx.fn_sig(id); + let sig = tcx.liberate_late_bound_regions(id.to_def_id(), tcx.fn_sig(id)); + let sig = tcx.normalize_erasing_regions(ParamEnv::empty(), sig); + + // We don't currently require that the function signature is equal to + // `fn(TokenStream) -> TokenStream`, but instead monomorphizes to + // `fn(TokenStream) -> TokenStream` after some substitution of generic arguments. + // + // Properly checking this means pulling in additional `rustc` crates, so we don't. + let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsInfer }; - if sig.abi() != Abi::Rust { - tcx.sess - .emit_err(ProcMacroInvalidAbi { span: hir_sig.span, abi: sig.abi().name() }); + if sig.abi != Abi::Rust { + tcx.sess.emit_err(ProcMacroInvalidAbi { span: hir_sig.span, abi: sig.abi.name() }); self.abort.set(true); } - if sig.unsafety() == Unsafety::Unsafe { + if sig.unsafety == Unsafety::Unsafe { tcx.sess.emit_err(ProcMacroUnsafe { span: hir_sig.span }); self.abort.set(true); } - let output = sig.output().skip_binder(); + let output = sig.output(); // Typecheck the output - if tcx.normalize_erasing_regions(ParamEnv::empty(), output) != tokenstream { + if !drcx.types_may_unify(output, tokenstream) { tcx.sess.emit_err(ProcMacroTypeError { span: hir_sig.decl.output.span(), found: output, @@ -2129,11 +2142,22 @@ impl CheckAttrVisitor<'_> { self.abort.set(true); } - // Typecheck "expected_input_count" inputs, emitting - // `ProcMacroMissingArguments` if there are not enough. - if let Some(args) = sig.inputs().skip_binder().get(0..expected_input_count) { - for (arg, input) in args.iter().zip(hir_sig.decl.inputs) { - if tcx.normalize_erasing_regions(ParamEnv::empty(), *arg) != tokenstream { + if sig.inputs().len() < expected_input_count { + tcx.sess.emit_err(ProcMacroMissingArguments { + expected_input_count, + span: hir_sig.span, + kind, + expected_signature, + }); + self.abort.set(true); + } + + // Check that the inputs are correct, if there are enough. + if sig.inputs().len() >= expected_input_count { + for (arg, input) in + sig.inputs().iter().zip(hir_sig.decl.inputs).take(expected_input_count) + { + if !drcx.types_may_unify(*arg, tokenstream) { tcx.sess.emit_err(ProcMacroTypeError { span: input.span, found: *arg, @@ -2143,14 +2167,6 @@ impl CheckAttrVisitor<'_> { self.abort.set(true); } } - } else { - tcx.sess.emit_err(ProcMacroMissingArguments { - expected_input_count, - span: hir_sig.span, - kind, - expected_signature, - }); - self.abort.set(true); } // Check that there are not too many arguments diff --git a/tests/ui/proc-macro/allowed-signatures.rs b/tests/ui/proc-macro/allowed-signatures.rs new file mode 100644 index 0000000000000..03c6ef86632df --- /dev/null +++ b/tests/ui/proc-macro/allowed-signatures.rs @@ -0,0 +1,24 @@ +// check-pass + +#![crate_type = "proc-macro"] +#![allow(private_in_public)] +extern crate proc_macro; +use proc_macro::TokenStream; + +#[proc_macro] +pub fn foo(t: T) -> TokenStream { + TokenStream::new() +} + +trait Project { + type Assoc; +} + +impl Project for () { + type Assoc = TokenStream; +} + +#[proc_macro] +pub fn uwu(_input: <() as Project>::Assoc) -> <() as Project>::Assoc { + TokenStream::new() +} diff --git a/tests/ui/proc-macro/proc-macro-abi.rs b/tests/ui/proc-macro/proc-macro-abi.rs index 2a40ddd496ce8..8e9d50d7832d5 100644 --- a/tests/ui/proc-macro/proc-macro-abi.rs +++ b/tests/ui/proc-macro/proc-macro-abi.rs @@ -6,19 +6,19 @@ use proc_macro::TokenStream; #[proc_macro] pub extern "C" fn abi(a: TokenStream) -> TokenStream { - //~^ ERROR proc macro functions may not be `extern + //~^ ERROR proc macro functions may not be `extern "C"` a } #[proc_macro] pub extern "system" fn abi2(a: TokenStream) -> TokenStream { - //~^ ERROR proc macro functions may not be `extern + //~^ ERROR proc macro functions may not be `extern "system"` a } #[proc_macro] pub extern fn abi3(a: TokenStream) -> TokenStream { - //~^ ERROR proc macro functions may not be `extern + //~^ ERROR proc macro functions may not be `extern "C"` a } From a4dbcb525b2f36f66c89df6919a7506cd99041cc Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 11 Jan 2023 21:41:13 +0100 Subject: [PATCH 113/500] Expand format_args!() in rust_ast_lowering. --- Cargo.lock | 1 + compiler/rustc_ast/src/ast.rs | 5 + .../format/ast.rs => rustc_ast/src/format.rs} | 36 +- compiler/rustc_ast/src/lib.rs | 2 + compiler/rustc_ast/src/mut_visit.rs | 14 + compiler/rustc_ast/src/util/parser.rs | 4 +- compiler/rustc_ast/src/visit.rs | 13 + compiler/rustc_ast_lowering/src/expr.rs | 1 + compiler/rustc_ast_lowering/src/format.rs | 356 ++++++++++++++++++ compiler/rustc_ast_lowering/src/lib.rs | 1 + compiler/rustc_ast_pretty/Cargo.toml | 3 +- .../rustc_ast_pretty/src/pprust/state/expr.rs | 102 +++++ .../src/assert/context.rs | 1 + compiler/rustc_builtin_macros/src/format.rs | 14 +- .../rustc_builtin_macros/src/format/expand.rs | 353 ----------------- compiler/rustc_hir/src/hir.rs | 3 + .../src/thir/pattern/check_match.rs | 6 +- compiler/rustc_passes/src/check_const.rs | 2 +- compiler/rustc_passes/src/hir_stats.rs | 2 +- 19 files changed, 535 insertions(+), 384 deletions(-) rename compiler/{rustc_builtin_macros/src/format/ast.rs => rustc_ast/src/format.rs} (87%) create mode 100644 compiler/rustc_ast_lowering/src/format.rs delete mode 100644 compiler/rustc_builtin_macros/src/format/expand.rs diff --git a/Cargo.lock b/Cargo.lock index 2a88152b5194a..faf4fd05c354f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3699,6 +3699,7 @@ name = "rustc_ast_pretty" version = "0.0.0" dependencies = [ "rustc_ast", + "rustc_parse_format", "rustc_span", ] diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index e656fb3740bbd..5b1722dffb90e 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -18,6 +18,7 @@ //! - [`Attribute`]: Metadata associated with item. //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators. +pub use crate::format::*; pub use crate::util::parser::ExprPrecedence; pub use GenericArgs::*; pub use UnsafeSource::*; @@ -1269,6 +1270,7 @@ impl Expr { ExprKind::Try(..) => ExprPrecedence::Try, ExprKind::Yield(..) => ExprPrecedence::Yield, ExprKind::Yeet(..) => ExprPrecedence::Yeet, + ExprKind::FormatArgs(..) => ExprPrecedence::FormatArgs, ExprKind::Err => ExprPrecedence::Err, } } @@ -1498,6 +1500,9 @@ pub enum ExprKind { /// with a `ByteStr` literal. IncludedBytes(Lrc<[u8]>), + /// A `format_args!()` expression. + FormatArgs(P), + /// Placeholder for an expression that wasn't syntactically well formed in some way. Err, } diff --git a/compiler/rustc_builtin_macros/src/format/ast.rs b/compiler/rustc_ast/src/format.rs similarity index 87% rename from compiler/rustc_builtin_macros/src/format/ast.rs rename to compiler/rustc_ast/src/format.rs index 01dbffa21b8aa..ce99c2b58b570 100644 --- a/compiler/rustc_builtin_macros/src/format/ast.rs +++ b/compiler/rustc_ast/src/format.rs @@ -1,5 +1,5 @@ -use rustc_ast::ptr::P; -use rustc_ast::Expr; +use crate::ptr::P; +use crate::Expr; use rustc_data_structures::fx::FxHashMap; use rustc_span::symbol::{Ident, Symbol}; use rustc_span::Span; @@ -39,7 +39,7 @@ use rustc_span::Span; /// Basically the "AST" for a complete `format_args!()`. /// /// E.g., `format_args!("hello {name}");`. -#[derive(Clone, Debug)] +#[derive(Clone, Encodable, Decodable, Debug)] pub struct FormatArgs { pub span: Span, pub template: Vec, @@ -49,7 +49,7 @@ pub struct FormatArgs { /// A piece of a format template string. /// /// E.g. "hello" or "{name}". -#[derive(Clone, Debug)] +#[derive(Clone, Encodable, Decodable, Debug)] pub enum FormatArgsPiece { Literal(Symbol), Placeholder(FormatPlaceholder), @@ -59,7 +59,7 @@ pub enum FormatArgsPiece { /// /// E.g. `1, 2, name="ferris", n=3`, /// but also implicit captured arguments like `x` in `format_args!("{x}")`. -#[derive(Clone, Debug)] +#[derive(Clone, Encodable, Decodable, Debug)] pub struct FormatArguments { arguments: Vec, num_unnamed_args: usize, @@ -121,18 +121,22 @@ impl FormatArguments { &self.arguments[..self.num_explicit_args] } - pub fn into_vec(self) -> Vec { - self.arguments + pub fn all_args(&self) -> &[FormatArgument] { + &self.arguments[..] + } + + pub fn all_args_mut(&mut self) -> &mut [FormatArgument] { + &mut self.arguments[..] } } -#[derive(Clone, Debug)] +#[derive(Clone, Encodable, Decodable, Debug)] pub struct FormatArgument { pub kind: FormatArgumentKind, pub expr: P, } -#[derive(Clone, Debug)] +#[derive(Clone, Encodable, Decodable, Debug)] pub enum FormatArgumentKind { /// `format_args(…, arg)` Normal, @@ -152,7 +156,7 @@ impl FormatArgumentKind { } } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq)] pub struct FormatPlaceholder { /// Index into [`FormatArgs::arguments`]. pub argument: FormatArgPosition, @@ -164,7 +168,7 @@ pub struct FormatPlaceholder { pub format_options: FormatOptions, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq)] pub struct FormatArgPosition { /// Which argument this position refers to (Ok), /// or would've referred to if it existed (Err). @@ -175,7 +179,7 @@ pub struct FormatArgPosition { pub span: Option, } -#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[derive(Copy, Clone, Encodable, Decodable, Debug, PartialEq, Eq)] pub enum FormatArgPositionKind { /// `{}` or `{:.*}` Implicit, @@ -185,7 +189,7 @@ pub enum FormatArgPositionKind { Named, } -#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] +#[derive(Copy, Clone, Encodable, Decodable, Debug, PartialEq, Eq, Hash)] pub enum FormatTrait { /// `{}` Display, @@ -207,7 +211,7 @@ pub enum FormatTrait { UpperHex, } -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Encodable, Decodable, Default, Debug, PartialEq, Eq)] pub struct FormatOptions { /// The width. E.g. `{:5}` or `{:width$}`. pub width: Option, @@ -221,7 +225,7 @@ pub struct FormatOptions { pub flags: u32, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Copy, Clone, Encodable, Decodable, Debug, PartialEq, Eq)] pub enum FormatAlignment { /// `{:<}` Left, @@ -231,7 +235,7 @@ pub enum FormatAlignment { Center, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq)] pub enum FormatCount { /// `{:5}` or `{:.5}` Literal(usize), diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs index 9c1dfeb1a6142..0f8ebcfdc1508 100644 --- a/compiler/rustc_ast/src/lib.rs +++ b/compiler/rustc_ast/src/lib.rs @@ -42,6 +42,7 @@ pub mod ast_traits; pub mod attr; pub mod entry; pub mod expand; +pub mod format; pub mod mut_visit; pub mod node_id; pub mod ptr; @@ -51,6 +52,7 @@ pub mod visit; pub use self::ast::*; pub use self::ast_traits::{AstDeref, AstNodeWrapper, HasAttrs, HasNodeId, HasSpan, HasTokens}; +pub use self::format::*; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index c572171e8f443..561274cc6f919 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -297,6 +297,10 @@ pub trait MutVisitor: Sized { fn visit_inline_asm_sym(&mut self, sym: &mut InlineAsmSym) { noop_visit_inline_asm_sym(sym, self) } + + fn visit_format_args(&mut self, fmt: &mut FormatArgs) { + noop_visit_format_args(fmt, self) + } } /// Use a map-style function (`FnOnce(T) -> T`) to overwrite a `&mut T`. Useful @@ -1284,6 +1288,15 @@ pub fn noop_visit_inline_asm_sym( vis.visit_path(path); } +pub fn noop_visit_format_args(fmt: &mut FormatArgs, vis: &mut T) { + for arg in fmt.arguments.all_args_mut() { + if let FormatArgumentKind::Named(name) = &mut arg.kind { + vis.visit_ident(name); + } + vis.visit_expr(&mut arg.expr); + } +} + pub fn noop_visit_expr( Expr { kind, id, span, attrs, tokens }: &mut Expr, vis: &mut T, @@ -1423,6 +1436,7 @@ pub fn noop_visit_expr( visit_opt(expr, |expr| vis.visit_expr(expr)); } ExprKind::InlineAsm(asm) => vis.visit_inline_asm(asm), + ExprKind::FormatArgs(fmt) => vis.visit_format_args(fmt), ExprKind::MacCall(mac) => vis.visit_mac_call(mac), ExprKind::Struct(se) => { let StructExpr { qself, path, fields, rest } = se.deref_mut(); diff --git a/compiler/rustc_ast/src/util/parser.rs b/compiler/rustc_ast/src/util/parser.rs index 819f1884a0692..2db2ab5e81157 100644 --- a/compiler/rustc_ast/src/util/parser.rs +++ b/compiler/rustc_ast/src/util/parser.rs @@ -271,6 +271,7 @@ pub enum ExprPrecedence { Try, InlineAsm, Mac, + FormatArgs, Array, Repeat, @@ -335,7 +336,8 @@ impl ExprPrecedence { | ExprPrecedence::Index | ExprPrecedence::Try | ExprPrecedence::InlineAsm - | ExprPrecedence::Mac => PREC_POSTFIX, + | ExprPrecedence::Mac + | ExprPrecedence::FormatArgs => PREC_POSTFIX, // Never need parens ExprPrecedence::Array diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index df7145a722a46..cb5c17084ec2a 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -242,6 +242,9 @@ pub trait Visitor<'ast>: Sized { fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) { walk_inline_asm(self, asm) } + fn visit_format_args(&mut self, fmt: &'ast FormatArgs) { + walk_format_args(self, fmt) + } fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) { walk_inline_asm_sym(self, sym) } @@ -756,6 +759,15 @@ pub fn walk_inline_asm_sym<'a, V: Visitor<'a>>(visitor: &mut V, sym: &'a InlineA visitor.visit_path(&sym.path, sym.id); } +pub fn walk_format_args<'a, V: Visitor<'a>>(visitor: &mut V, fmt: &'a FormatArgs) { + for arg in fmt.arguments.all_args() { + if let FormatArgumentKind::Named(name) = arg.kind { + visitor.visit_ident(name); + } + visitor.visit_expr(&arg.expr); + } +} + pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) { walk_list!(visitor, visit_attribute, expression.attrs.iter()); @@ -895,6 +907,7 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) { ExprKind::MacCall(mac) => visitor.visit_mac_call(mac), ExprKind::Paren(subexpression) => visitor.visit_expr(subexpression), ExprKind::InlineAsm(asm) => visitor.visit_inline_asm(asm), + ExprKind::FormatArgs(f) => visitor.visit_format_args(f), ExprKind::Yield(optional_expression) => { walk_list!(visitor, visit_expr, optional_expression); } diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 51f290bc587e9..5e0f1b9b61ffc 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -292,6 +292,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::InlineAsm(asm) => { hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm)) } + ExprKind::FormatArgs(fmt) => self.lower_format_args(e.span, fmt), ExprKind::Struct(se) => { let rest = match &se.rest { StructRest::Base(e) => Some(self.lower_expr(e)), diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs new file mode 100644 index 0000000000000..f8ed164b356f1 --- /dev/null +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -0,0 +1,356 @@ +use super::LoweringContext; +use rustc_ast as ast; +use rustc_ast::visit::{self, Visitor}; +use rustc_ast::*; +use rustc_data_structures::fx::FxIndexSet; +use rustc_hir as hir; +use rustc_span::{ + sym, + symbol::{kw, Ident}, + Span, +}; + +impl<'hir> LoweringContext<'_, 'hir> { + pub(crate) fn lower_format_args(&mut self, sp: Span, fmt: &FormatArgs) -> hir::ExprKind<'hir> { + expand_format_args(self, sp, fmt) + } +} + +#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] +enum ArgumentType { + Format(FormatTrait), + Usize, +} + +fn make_argument<'hir>( + ctx: &mut LoweringContext<'_, 'hir>, + sp: Span, + arg: &'hir hir::Expr<'hir>, + ty: ArgumentType, +) -> hir::Expr<'hir> { + // Generate: + // ::core::fmt::ArgumentV1::new_…(arg) + use ArgumentType::*; + use FormatTrait::*; + let new_fn = ctx.arena.alloc(ctx.expr_lang_item_type_relative( + sp, + hir::LangItem::FormatArgument, + match ty { + Format(Display) => sym::new_display, + Format(Debug) => sym::new_debug, + Format(LowerExp) => sym::new_lower_exp, + Format(UpperExp) => sym::new_upper_exp, + Format(Octal) => sym::new_octal, + Format(Pointer) => sym::new_pointer, + Format(Binary) => sym::new_binary, + Format(LowerHex) => sym::new_lower_hex, + Format(UpperHex) => sym::new_upper_hex, + Usize => sym::from_usize, + }, + )); + ctx.expr_call_mut(sp, new_fn, std::slice::from_ref(arg)) +} + +fn make_count<'hir>( + ctx: &mut LoweringContext<'_, 'hir>, + sp: Span, + count: &Option, + argmap: &mut FxIndexSet<(usize, ArgumentType)>, +) -> hir::Expr<'hir> { + // Generate: + // ::core::fmt::rt::v1::Count::…(…) + match count { + Some(FormatCount::Literal(n)) => { + let count_is = ctx.arena.alloc(ctx.expr_lang_item_type_relative( + sp, + hir::LangItem::FormatCount, + sym::Is, + )); + let value = ctx.arena.alloc_from_iter([ctx.expr_usize(sp, *n)]); + ctx.expr_call_mut(sp, count_is, value) + } + Some(FormatCount::Argument(arg)) => { + if let Ok(arg_index) = arg.index { + let (i, _) = argmap.insert_full((arg_index, ArgumentType::Usize)); + let count_param = ctx.arena.alloc(ctx.expr_lang_item_type_relative( + sp, + hir::LangItem::FormatCount, + sym::Param, + )); + let value = ctx.arena.alloc_from_iter([ctx.expr_usize(sp, i)]); + ctx.expr_call_mut(sp, count_param, value) + } else { + ctx.expr(sp, hir::ExprKind::Err) + } + } + None => ctx.expr_lang_item_type_relative(sp, hir::LangItem::FormatCount, sym::Implied), + } +} + +fn make_format_spec<'hir>( + ctx: &mut LoweringContext<'_, 'hir>, + sp: Span, + placeholder: &FormatPlaceholder, + argmap: &mut FxIndexSet<(usize, ArgumentType)>, +) -> hir::Expr<'hir> { + // Generate: + // ::core::fmt::rt::v1::Argument { + // position: 0usize, + // format: ::core::fmt::rt::v1::FormatSpec { + // fill: ' ', + // align: ::core::fmt::rt::v1::Alignment::Unknown, + // flags: 0u32, + // precision: ::core::fmt::rt::v1::Count::Implied, + // width: ::core::fmt::rt::v1::Count::Implied, + // }, + // } + let position = match placeholder.argument.index { + Ok(arg_index) => { + let (i, _) = + argmap.insert_full((arg_index, ArgumentType::Format(placeholder.format_trait))); + ctx.expr_usize(sp, i) + } + Err(_) => ctx.expr(sp, hir::ExprKind::Err), + }; + let fill = ctx.expr_char(sp, placeholder.format_options.fill.unwrap_or(' ')); + let align = ctx.expr_lang_item_type_relative( + sp, + hir::LangItem::FormatAlignment, + match placeholder.format_options.alignment { + Some(FormatAlignment::Left) => sym::Left, + Some(FormatAlignment::Right) => sym::Right, + Some(FormatAlignment::Center) => sym::Center, + None => sym::Unknown, + }, + ); + let flags = ctx.expr_u32(sp, placeholder.format_options.flags); + let prec = make_count(ctx, sp, &placeholder.format_options.precision, argmap); + let width = make_count(ctx, sp, &placeholder.format_options.width, argmap); + let format_placeholder_new = ctx.arena.alloc(ctx.expr_lang_item_type_relative( + sp, + hir::LangItem::FormatPlaceholder, + sym::new, + )); + let args = ctx.arena.alloc_from_iter([position, fill, align, flags, prec, width]); + ctx.expr_call_mut(sp, format_placeholder_new, args) +} + +fn expand_format_args<'hir>( + ctx: &mut LoweringContext<'_, 'hir>, + macsp: Span, + fmt: &FormatArgs, +) -> hir::ExprKind<'hir> { + let lit_pieces = + ctx.arena.alloc_from_iter(fmt.template.iter().enumerate().filter_map(|(i, piece)| { + match piece { + &FormatArgsPiece::Literal(s) => Some(ctx.expr_str(fmt.span, s)), + &FormatArgsPiece::Placeholder(_) => { + // Inject empty string before placeholders when not already preceded by a literal piece. + if i == 0 || matches!(fmt.template[i - 1], FormatArgsPiece::Placeholder(_)) { + Some(ctx.expr_str(fmt.span, kw::Empty)) + } else { + None + } + } + } + })); + let lit_pieces = ctx.expr_array_ref(fmt.span, lit_pieces); + + // Whether we'll use the `Arguments::new_v1_formatted` form (true), + // or the `Arguments::new_v1` form (false). + let mut use_format_options = false; + + // Create a list of all _unique_ (argument, format trait) combinations. + // E.g. "{0} {0:x} {0} {1}" -> [(0, Display), (0, LowerHex), (1, Display)] + let mut argmap = FxIndexSet::default(); + for piece in &fmt.template { + let FormatArgsPiece::Placeholder(placeholder) = piece else { continue }; + if placeholder.format_options != Default::default() { + // Can't use basic form if there's any formatting options. + use_format_options = true; + } + if let Ok(index) = placeholder.argument.index { + if !argmap.insert((index, ArgumentType::Format(placeholder.format_trait))) { + // Duplicate (argument, format trait) combination, + // which we'll only put once in the args array. + use_format_options = true; + } + } + } + + let format_options = use_format_options.then(|| { + // Generate: + // &[format_spec_0, format_spec_1, format_spec_2] + let elements: Vec<_> = fmt + .template + .iter() + .filter_map(|piece| { + let FormatArgsPiece::Placeholder(placeholder) = piece else { return None }; + Some(make_format_spec(ctx, macsp, placeholder, &mut argmap)) + }) + .collect(); + ctx.expr_array_ref(macsp, ctx.arena.alloc_from_iter(elements)) + }); + + let arguments = fmt.arguments.all_args(); + + // If the args array contains exactly all the original arguments once, + // in order, we can use a simple array instead of a `match` construction. + // However, if there's a yield point in any argument except the first one, + // we don't do this, because an ArgumentV1 cannot be kept across yield points. + let use_simple_array = argmap.len() == arguments.len() + && argmap.iter().enumerate().all(|(i, &(j, _))| i == j) + && arguments.iter().skip(1).all(|arg| !may_contain_yield_point(&arg.expr)); + + let args = if use_simple_array { + // Generate: + // &[ + // ::core::fmt::ArgumentV1::new_display(&arg0), + // ::core::fmt::ArgumentV1::new_lower_hex(&arg1), + // ::core::fmt::ArgumentV1::new_debug(&arg2), + // ] + let elements: Vec<_> = arguments + .iter() + .zip(argmap) + .map(|(arg, (_, ty))| { + let sp = arg.expr.span.with_ctxt(macsp.ctxt()); + let arg = ctx.lower_expr(&arg.expr); + let ref_arg = ctx.arena.alloc(ctx.expr( + sp, + hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, arg), + )); + make_argument(ctx, sp, ref_arg, ty) + }) + .collect(); + ctx.expr_array_ref(macsp, ctx.arena.alloc_from_iter(elements)) + } else { + // Generate: + // &match (&arg0, &arg1, &arg2) { + // args => [ + // ::core::fmt::ArgumentV1::new_display(args.0), + // ::core::fmt::ArgumentV1::new_lower_hex(args.1), + // ::core::fmt::ArgumentV1::new_debug(args.0), + // ] + // } + let args_ident = Ident::new(sym::args, macsp); + let (args_pat, args_hir_id) = ctx.pat_ident(macsp, args_ident); + let args = ctx.arena.alloc_from_iter(argmap.iter().map(|&(arg_index, ty)| { + if let Some(arg) = arguments.get(arg_index) { + let sp = arg.expr.span.with_ctxt(macsp.ctxt()); + let args_ident_expr = ctx.expr_ident(macsp, args_ident, args_hir_id); + let arg = ctx.arena.alloc(ctx.expr( + sp, + hir::ExprKind::Field( + args_ident_expr, + Ident::new(sym::integer(arg_index), macsp), + ), + )); + make_argument(ctx, sp, arg, ty) + } else { + ctx.expr(macsp, hir::ExprKind::Err) + } + })); + let elements: Vec<_> = arguments + .iter() + .map(|arg| { + let arg_expr = ctx.lower_expr(&arg.expr); + ctx.expr( + arg.expr.span.with_ctxt(macsp.ctxt()), + hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, arg_expr), + ) + }) + .collect(); + let args_tuple = ctx + .arena + .alloc(ctx.expr(macsp, hir::ExprKind::Tup(ctx.arena.alloc_from_iter(elements)))); + let array = ctx.arena.alloc(ctx.expr(macsp, hir::ExprKind::Array(args))); + let match_arms = ctx.arena.alloc_from_iter([ctx.arm(args_pat, array)]); + let match_expr = ctx.arena.alloc(ctx.expr_match( + macsp, + args_tuple, + match_arms, + hir::MatchSource::FormatArgs, + )); + ctx.expr( + macsp, + hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, match_expr), + ) + }; + + if let Some(format_options) = format_options { + // Generate: + // ::core::fmt::Arguments::new_v1_formatted( + // lit_pieces, + // args, + // format_options, + // unsafe { ::core::fmt::UnsafeArg::new() } + // ) + let new_v1_formatted = ctx.arena.alloc(ctx.expr_lang_item_type_relative( + macsp, + hir::LangItem::FormatArguments, + sym::new_v1_formatted, + )); + let unsafe_arg_new = ctx.arena.alloc(ctx.expr_lang_item_type_relative( + macsp, + hir::LangItem::FormatUnsafeArg, + sym::new, + )); + let unsafe_arg_new_call = ctx.expr_call(macsp, unsafe_arg_new, &[]); + let hir_id = ctx.next_id(); + let unsafe_arg = ctx.expr_block(ctx.arena.alloc(hir::Block { + stmts: &[], + expr: Some(unsafe_arg_new_call), + hir_id, + rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated), + span: macsp, + targeted_by_break: false, + })); + let args = ctx.arena.alloc_from_iter([lit_pieces, args, format_options, unsafe_arg]); + hir::ExprKind::Call(new_v1_formatted, args) + } else { + // Generate: + // ::core::fmt::Arguments::new_v1( + // lit_pieces, + // args, + // ) + let new_v1 = ctx.arena.alloc(ctx.expr_lang_item_type_relative( + macsp, + hir::LangItem::FormatArguments, + sym::new_v1, + )); + let new_args = ctx.arena.alloc_from_iter([lit_pieces, args]); + hir::ExprKind::Call(new_v1, new_args) + } +} + +fn may_contain_yield_point(e: &ast::Expr) -> bool { + struct MayContainYieldPoint(bool); + + impl Visitor<'_> for MayContainYieldPoint { + fn visit_expr(&mut self, e: &ast::Expr) { + if let ast::ExprKind::Await(_) | ast::ExprKind::Yield(_) = e.kind { + self.0 = true; + } else { + visit::walk_expr(self, e); + } + } + + fn visit_mac_call(&mut self, _: &ast::MacCall) { + self.0 = true; + } + + fn visit_attribute(&mut self, _: &ast::Attribute) { + // Conservatively assume this may be a proc macro attribute in + // expression position. + self.0 = true; + } + + fn visit_item(&mut self, _: &ast::Item) { + // Do not recurse into nested items. + } + } + + let mut visitor = MayContainYieldPoint(false); + visitor.visit_expr(e); + visitor.0 +} diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 2e135aafb1e0f..01aba94fe39f4 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -80,6 +80,7 @@ mod asm; mod block; mod errors; mod expr; +mod format; mod index; mod item; mod lifetime_collector; diff --git a/compiler/rustc_ast_pretty/Cargo.toml b/compiler/rustc_ast_pretty/Cargo.toml index a3e3e823b08eb..b4900dc39a8af 100644 --- a/compiler/rustc_ast_pretty/Cargo.toml +++ b/compiler/rustc_ast_pretty/Cargo.toml @@ -6,5 +6,6 @@ edition = "2021" [lib] [dependencies] -rustc_span = { path = "../rustc_span" } rustc_ast = { path = "../rustc_ast" } +rustc_parse_format = { path = "../rustc_parse_format" } +rustc_span = { path = "../rustc_span" } diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs index 3b17f6dd627eb..03beae3a45bb1 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -6,6 +6,8 @@ use rustc_ast::token; use rustc_ast::util::literal::escape_byte_str_symbol; use rustc_ast::util::parser::{self, AssocOp, Fixity}; use rustc_ast::{self as ast, BlockCheckMode}; +use rustc_ast::{FormatAlignment, FormatArgPosition, FormatArgsPiece, FormatCount, FormatTrait}; +use std::fmt::Write; impl<'a> State<'a> { fn print_else(&mut self, els: Option<&ast::Expr>) { @@ -528,6 +530,18 @@ impl<'a> State<'a> { self.word("asm!"); self.print_inline_asm(a); } + ast::ExprKind::FormatArgs(fmt) => { + self.word("format_args!"); + self.popen(); + self.rbox(0, Inconsistent); + self.word(reconstruct_format_args_template_string(&fmt.template)); + for arg in fmt.arguments.all_args() { + self.word_space(","); + self.print_expr(&arg.expr); + } + self.end(); + self.pclose(); + } ast::ExprKind::MacCall(m) => self.print_mac(m), ast::ExprKind::Paren(e) => { self.popen(); @@ -627,3 +641,91 @@ impl<'a> State<'a> { } } } + +pub fn reconstruct_format_args_template_string(pieces: &[FormatArgsPiece]) -> String { + let mut template = "\"".to_string(); + for piece in pieces { + match piece { + FormatArgsPiece::Literal(s) => { + for c in s.as_str().escape_debug() { + template.push(c); + if let '{' | '}' = c { + template.push(c); + } + } + } + FormatArgsPiece::Placeholder(p) => { + template.push('{'); + let (Ok(n) | Err(n)) = p.argument.index; + write!(template, "{n}").unwrap(); + if p.format_options != Default::default() || p.format_trait != FormatTrait::Display + { + template.push_str(":"); + } + if let Some(fill) = p.format_options.fill { + template.push(fill); + } + match p.format_options.alignment { + Some(FormatAlignment::Left) => template.push_str("<"), + Some(FormatAlignment::Right) => template.push_str(">"), + Some(FormatAlignment::Center) => template.push_str("^"), + None => {} + } + let flags = p.format_options.flags; + if flags >> (rustc_parse_format::FlagSignPlus as usize) & 1 != 0 { + template.push('+'); + } + if flags >> (rustc_parse_format::FlagSignMinus as usize) & 1 != 0 { + template.push('-'); + } + if flags >> (rustc_parse_format::FlagAlternate as usize) & 1 != 0 { + template.push('#'); + } + if flags >> (rustc_parse_format::FlagSignAwareZeroPad as usize) & 1 != 0 { + template.push('0'); + } + if let Some(width) = &p.format_options.width { + match width { + FormatCount::Literal(n) => write!(template, "{n}").unwrap(), + FormatCount::Argument(FormatArgPosition { + index: Ok(n) | Err(n), .. + }) => { + write!(template, "{n}$").unwrap(); + } + } + } + if let Some(precision) = &p.format_options.precision { + template.push('.'); + match precision { + FormatCount::Literal(n) => write!(template, "{n}").unwrap(), + FormatCount::Argument(FormatArgPosition { + index: Ok(n) | Err(n), .. + }) => { + write!(template, "{n}$").unwrap(); + } + } + } + if flags >> (rustc_parse_format::FlagDebugLowerHex as usize) & 1 != 0 { + template.push('X'); + } + if flags >> (rustc_parse_format::FlagDebugUpperHex as usize) & 1 != 0 { + template.push('x'); + } + template.push_str(match p.format_trait { + FormatTrait::Display => "", + FormatTrait::Debug => "?", + FormatTrait::LowerExp => "e", + FormatTrait::UpperExp => "E", + FormatTrait::Octal => "o", + FormatTrait::Pointer => "p", + FormatTrait::Binary => "b", + FormatTrait::LowerHex => "x", + FormatTrait::UpperHex => "X", + }); + template.push('}'); + } + } + } + template.push('"'); + template +} diff --git a/compiler/rustc_builtin_macros/src/assert/context.rs b/compiler/rustc_builtin_macros/src/assert/context.rs index 93b07801e035d..342b1735661df 100644 --- a/compiler/rustc_builtin_macros/src/assert/context.rs +++ b/compiler/rustc_builtin_macros/src/assert/context.rs @@ -297,6 +297,7 @@ impl<'cx, 'a> Context<'cx, 'a> { | ExprKind::Continue(_) | ExprKind::Err | ExprKind::Field(_, _) + | ExprKind::FormatArgs(_) | ExprKind::ForLoop(_, _, _, _) | ExprKind::If(_, _, _) | ExprKind::IncludedBytes(..) diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index b2b7b9d75bd37..47b63a7fa122f 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -1,7 +1,11 @@ use rustc_ast::ptr::P; use rustc_ast::token; use rustc_ast::tokenstream::TokenStream; -use rustc_ast::Expr; +use rustc_ast::{ + Expr, ExprKind, FormatAlignment, FormatArgPosition, FormatArgPositionKind, FormatArgs, + FormatArgsPiece, FormatArgument, FormatArgumentKind, FormatArguments, FormatCount, + FormatOptions, FormatPlaceholder, FormatTrait, +}; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{pluralize, Applicability, MultiSpan, PResult}; use rustc_expand::base::{self, *}; @@ -12,12 +16,6 @@ use rustc_span::{BytePos, InnerSpan, Span}; use rustc_lint_defs::builtin::NAMED_ARGUMENTS_USED_POSITIONALLY; use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, LintId}; -mod ast; -use ast::*; - -mod expand; -use expand::expand_parsed_format_args; - // The format_args!() macro is expanded in three steps: // 1. First, `parse_args` will parse the `(literal, arg, arg, name=arg, name=arg)` syntax, // but doesn't parse the template (the literal) itself. @@ -850,7 +848,7 @@ fn expand_format_args_impl<'cx>( match parse_args(ecx, sp, tts) { Ok((efmt, args)) => { if let Ok(format_args) = make_format_args(ecx, efmt, args, nl) { - MacEager::expr(expand_parsed_format_args(ecx, format_args)) + MacEager::expr(ecx.expr(sp, ExprKind::FormatArgs(P(format_args)))) } else { MacEager::expr(DummyResult::raw_expr(sp, true)) } diff --git a/compiler/rustc_builtin_macros/src/format/expand.rs b/compiler/rustc_builtin_macros/src/format/expand.rs deleted file mode 100644 index 9dde5efcb28b7..0000000000000 --- a/compiler/rustc_builtin_macros/src/format/expand.rs +++ /dev/null @@ -1,353 +0,0 @@ -use super::*; -use rustc_ast as ast; -use rustc_ast::visit::{self, Visitor}; -use rustc_ast::{BlockCheckMode, UnsafeSource}; -use rustc_data_structures::fx::FxIndexSet; -use rustc_span::{sym, symbol::kw}; - -#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] -enum ArgumentType { - Format(FormatTrait), - Usize, -} - -fn make_argument(ecx: &ExtCtxt<'_>, sp: Span, arg: P, ty: ArgumentType) -> P { - // Generate: - // ::core::fmt::ArgumentV1::new_…(arg) - use ArgumentType::*; - use FormatTrait::*; - ecx.expr_call_global( - sp, - ecx.std_path(&[ - sym::fmt, - sym::ArgumentV1, - match ty { - Format(Display) => sym::new_display, - Format(Debug) => sym::new_debug, - Format(LowerExp) => sym::new_lower_exp, - Format(UpperExp) => sym::new_upper_exp, - Format(Octal) => sym::new_octal, - Format(Pointer) => sym::new_pointer, - Format(Binary) => sym::new_binary, - Format(LowerHex) => sym::new_lower_hex, - Format(UpperHex) => sym::new_upper_hex, - Usize => sym::from_usize, - }, - ]), - vec![arg], - ) -} - -fn make_count( - ecx: &ExtCtxt<'_>, - sp: Span, - count: &Option, - argmap: &mut FxIndexSet<(usize, ArgumentType)>, -) -> P { - // Generate: - // ::core::fmt::rt::v1::Count::…(…) - match count { - Some(FormatCount::Literal(n)) => ecx.expr_call_global( - sp, - ecx.std_path(&[sym::fmt, sym::rt, sym::v1, sym::Count, sym::Is]), - vec![ecx.expr_usize(sp, *n)], - ), - Some(FormatCount::Argument(arg)) => { - if let Ok(arg_index) = arg.index { - let (i, _) = argmap.insert_full((arg_index, ArgumentType::Usize)); - ecx.expr_call_global( - sp, - ecx.std_path(&[sym::fmt, sym::rt, sym::v1, sym::Count, sym::Param]), - vec![ecx.expr_usize(sp, i)], - ) - } else { - DummyResult::raw_expr(sp, true) - } - } - None => ecx.expr_path(ecx.path_global( - sp, - ecx.std_path(&[sym::fmt, sym::rt, sym::v1, sym::Count, sym::Implied]), - )), - } -} - -fn make_format_spec( - ecx: &ExtCtxt<'_>, - sp: Span, - placeholder: &FormatPlaceholder, - argmap: &mut FxIndexSet<(usize, ArgumentType)>, -) -> P { - // Generate: - // ::core::fmt::rt::v1::Argument { - // position: 0usize, - // format: ::core::fmt::rt::v1::FormatSpec { - // fill: ' ', - // align: ::core::fmt::rt::v1::Alignment::Unknown, - // flags: 0u32, - // precision: ::core::fmt::rt::v1::Count::Implied, - // width: ::core::fmt::rt::v1::Count::Implied, - // }, - // } - let position = match placeholder.argument.index { - Ok(arg_index) => { - let (i, _) = - argmap.insert_full((arg_index, ArgumentType::Format(placeholder.format_trait))); - ecx.expr_usize(sp, i) - } - Err(_) => DummyResult::raw_expr(sp, true), - }; - let fill = ecx.expr_char(sp, placeholder.format_options.fill.unwrap_or(' ')); - let align = ecx.expr_path(ecx.path_global( - sp, - ecx.std_path(&[ - sym::fmt, - sym::rt, - sym::v1, - sym::Alignment, - match placeholder.format_options.alignment { - Some(FormatAlignment::Left) => sym::Left, - Some(FormatAlignment::Right) => sym::Right, - Some(FormatAlignment::Center) => sym::Center, - None => sym::Unknown, - }, - ]), - )); - let flags = ecx.expr_u32(sp, placeholder.format_options.flags); - let prec = make_count(ecx, sp, &placeholder.format_options.precision, argmap); - let width = make_count(ecx, sp, &placeholder.format_options.width, argmap); - ecx.expr_struct( - sp, - ecx.path_global(sp, ecx.std_path(&[sym::fmt, sym::rt, sym::v1, sym::Argument])), - vec![ - ecx.field_imm(sp, Ident::new(sym::position, sp), position), - ecx.field_imm( - sp, - Ident::new(sym::format, sp), - ecx.expr_struct( - sp, - ecx.path_global( - sp, - ecx.std_path(&[sym::fmt, sym::rt, sym::v1, sym::FormatSpec]), - ), - vec![ - ecx.field_imm(sp, Ident::new(sym::fill, sp), fill), - ecx.field_imm(sp, Ident::new(sym::align, sp), align), - ecx.field_imm(sp, Ident::new(sym::flags, sp), flags), - ecx.field_imm(sp, Ident::new(sym::precision, sp), prec), - ecx.field_imm(sp, Ident::new(sym::width, sp), width), - ], - ), - ), - ], - ) -} - -pub fn expand_parsed_format_args(ecx: &mut ExtCtxt<'_>, fmt: FormatArgs) -> P { - let macsp = ecx.with_def_site_ctxt(ecx.call_site()); - - let lit_pieces = ecx.expr_array_ref( - fmt.span, - fmt.template - .iter() - .enumerate() - .filter_map(|(i, piece)| match piece { - &FormatArgsPiece::Literal(s) => Some(ecx.expr_str(fmt.span, s)), - &FormatArgsPiece::Placeholder(_) => { - // Inject empty string before placeholders when not already preceded by a literal piece. - if i == 0 || matches!(fmt.template[i - 1], FormatArgsPiece::Placeholder(_)) { - Some(ecx.expr_str(fmt.span, kw::Empty)) - } else { - None - } - } - }) - .collect(), - ); - - // Whether we'll use the `Arguments::new_v1_formatted` form (true), - // or the `Arguments::new_v1` form (false). - let mut use_format_options = false; - - // Create a list of all _unique_ (argument, format trait) combinations. - // E.g. "{0} {0:x} {0} {1}" -> [(0, Display), (0, LowerHex), (1, Display)] - let mut argmap = FxIndexSet::default(); - for piece in &fmt.template { - let FormatArgsPiece::Placeholder(placeholder) = piece else { continue }; - if placeholder.format_options != Default::default() { - // Can't use basic form if there's any formatting options. - use_format_options = true; - } - if let Ok(index) = placeholder.argument.index { - if !argmap.insert((index, ArgumentType::Format(placeholder.format_trait))) { - // Duplicate (argument, format trait) combination, - // which we'll only put once in the args array. - use_format_options = true; - } - } - } - - let format_options = use_format_options.then(|| { - // Generate: - // &[format_spec_0, format_spec_1, format_spec_2] - ecx.expr_array_ref( - macsp, - fmt.template - .iter() - .filter_map(|piece| { - let FormatArgsPiece::Placeholder(placeholder) = piece else { return None }; - Some(make_format_spec(ecx, macsp, placeholder, &mut argmap)) - }) - .collect(), - ) - }); - - let arguments = fmt.arguments.into_vec(); - - // If the args array contains exactly all the original arguments once, - // in order, we can use a simple array instead of a `match` construction. - // However, if there's a yield point in any argument except the first one, - // we don't do this, because an ArgumentV1 cannot be kept across yield points. - let use_simple_array = argmap.len() == arguments.len() - && argmap.iter().enumerate().all(|(i, &(j, _))| i == j) - && arguments.iter().skip(1).all(|arg| !may_contain_yield_point(&arg.expr)); - - let args = if use_simple_array { - // Generate: - // &[ - // ::core::fmt::ArgumentV1::new_display(&arg0), - // ::core::fmt::ArgumentV1::new_lower_hex(&arg1), - // ::core::fmt::ArgumentV1::new_debug(&arg2), - // ] - ecx.expr_array_ref( - macsp, - arguments - .into_iter() - .zip(argmap) - .map(|(arg, (_, ty))| { - let sp = arg.expr.span.with_ctxt(macsp.ctxt()); - make_argument(ecx, sp, ecx.expr_addr_of(sp, arg.expr), ty) - }) - .collect(), - ) - } else { - // Generate: - // match (&arg0, &arg1, &arg2) { - // args => &[ - // ::core::fmt::ArgumentV1::new_display(args.0), - // ::core::fmt::ArgumentV1::new_lower_hex(args.1), - // ::core::fmt::ArgumentV1::new_debug(args.0), - // ] - // } - let args_ident = Ident::new(sym::args, macsp); - let args = argmap - .iter() - .map(|&(arg_index, ty)| { - if let Some(arg) = arguments.get(arg_index) { - let sp = arg.expr.span.with_ctxt(macsp.ctxt()); - make_argument( - ecx, - sp, - ecx.expr_field( - sp, - ecx.expr_ident(macsp, args_ident), - Ident::new(sym::integer(arg_index), macsp), - ), - ty, - ) - } else { - DummyResult::raw_expr(macsp, true) - } - }) - .collect(); - ecx.expr_addr_of( - macsp, - ecx.expr_match( - macsp, - ecx.expr_tuple( - macsp, - arguments - .into_iter() - .map(|arg| { - ecx.expr_addr_of(arg.expr.span.with_ctxt(macsp.ctxt()), arg.expr) - }) - .collect(), - ), - vec![ecx.arm(macsp, ecx.pat_ident(macsp, args_ident), ecx.expr_array(macsp, args))], - ), - ) - }; - - if let Some(format_options) = format_options { - // Generate: - // ::core::fmt::Arguments::new_v1_formatted( - // lit_pieces, - // args, - // format_options, - // unsafe { ::core::fmt::UnsafeArg::new() } - // ) - ecx.expr_call_global( - macsp, - ecx.std_path(&[sym::fmt, sym::Arguments, sym::new_v1_formatted]), - vec![ - lit_pieces, - args, - format_options, - ecx.expr_block(P(ast::Block { - stmts: vec![ecx.stmt_expr(ecx.expr_call_global( - macsp, - ecx.std_path(&[sym::fmt, sym::UnsafeArg, sym::new]), - Vec::new(), - ))], - id: ast::DUMMY_NODE_ID, - rules: BlockCheckMode::Unsafe(UnsafeSource::CompilerGenerated), - span: macsp, - tokens: None, - could_be_bare_literal: false, - })), - ], - ) - } else { - // Generate: - // ::core::fmt::Arguments::new_v1( - // lit_pieces, - // args, - // ) - ecx.expr_call_global( - macsp, - ecx.std_path(&[sym::fmt, sym::Arguments, sym::new_v1]), - vec![lit_pieces, args], - ) - } -} - -fn may_contain_yield_point(e: &ast::Expr) -> bool { - struct MayContainYieldPoint(bool); - - impl Visitor<'_> for MayContainYieldPoint { - fn visit_expr(&mut self, e: &ast::Expr) { - if let ast::ExprKind::Await(_) | ast::ExprKind::Yield(_) = e.kind { - self.0 = true; - } else { - visit::walk_expr(self, e); - } - } - - fn visit_mac_call(&mut self, _: &ast::MacCall) { - self.0 = true; - } - - fn visit_attribute(&mut self, _: &ast::Attribute) { - // Conservatively assume this may be a proc macro attribute in - // expression position. - self.0 = true; - } - - fn visit_item(&mut self, _: &ast::Item) { - // Do not recurse into nested items. - } - } - - let mut visitor = MayContainYieldPoint(false); - visitor.visit_expr(e); - visitor.0 -} diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index bc897ed8112e5..c827600179def 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2108,6 +2108,8 @@ pub enum MatchSource { TryDesugar, /// A desugared `.await`. AwaitDesugar, + /// A desugared `format_args!()`. + FormatArgs, } impl MatchSource { @@ -2119,6 +2121,7 @@ impl MatchSource { ForLoopDesugar => "for", TryDesugar => "?", AwaitDesugar => ".await", + FormatArgs => "format_args!()", } } } diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index e7ee0d9e908e0..2b52c410ecd2a 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -208,9 +208,9 @@ impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> { // Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }` // when the iterator is an uninhabited type. unreachable_code will trigger instead. hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {} - hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => { - report_arm_reachability(&cx, &report) - } + hir::MatchSource::ForLoopDesugar + | hir::MatchSource::Normal + | hir::MatchSource::FormatArgs => report_arm_reachability(&cx, &report), // Unreachable patterns in try and await expressions occur when one of // the arms are an uninhabited type. Which is OK. hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {} diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index aa726d6cd92aa..dd8c646a43c82 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -48,7 +48,7 @@ impl NonConstExpr { Self::Match(TryDesugar) => &[sym::const_try], // All other expressions are allowed. - Self::Loop(Loop | While) | Self::Match(Normal) => &[], + Self::Loop(Loop | While) | Self::Match(Normal | FormatArgs) => &[], }; Some(gates) diff --git a/compiler/rustc_passes/src/hir_stats.rs b/compiler/rustc_passes/src/hir_stats.rs index b86d2316820ce..d1b896e940e6e 100644 --- a/compiler/rustc_passes/src/hir_stats.rs +++ b/compiler/rustc_passes/src/hir_stats.rs @@ -567,7 +567,7 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { Box, Array, ConstBlock, Call, MethodCall, Tup, Binary, Unary, Lit, Cast, Type, Let, If, While, ForLoop, Loop, Match, Closure, Block, Async, Await, TryBlock, Assign, AssignOp, Field, Index, Range, Underscore, Path, AddrOf, Break, Continue, Ret, - InlineAsm, MacCall, Struct, Repeat, Paren, Try, Yield, Yeet, IncludedBytes, Err + InlineAsm, FormatArgs, MacCall, Struct, Repeat, Paren, Try, Yield, Yeet, IncludedBytes, Err ] ); ast_visit::walk_expr(self, e) From 525b0bb77a6d0bf88772a47b13275a553e625797 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 11 Jan 2023 21:41:58 +0100 Subject: [PATCH 114/500] Bless tests. --- .../ui/attributes/key-value-expansion.stderr | 7 +--- ...ming-methods-have-optimized-codegen.stdout | 36 +++++++++---------- 2 files changed, 19 insertions(+), 24 deletions(-) diff --git a/tests/ui/attributes/key-value-expansion.stderr b/tests/ui/attributes/key-value-expansion.stderr index 1b776322aaa64..aaa8b169583fd 100644 --- a/tests/ui/attributes/key-value-expansion.stderr +++ b/tests/ui/attributes/key-value-expansion.stderr @@ -15,12 +15,7 @@ LL | bug!(); | = note: this error originates in the macro `bug` (in Nightly builds, run with -Z macro-backtrace for more info) -error: unexpected expression: `{ - let res = - ::alloc::fmt::format(::core::fmt::Arguments::new_v1(&[""], - &[::core::fmt::ArgumentV1::new_display(&"u8")])); - res - }.as_str()` +error: unexpected expression: `{ let res = ::alloc::fmt::format(format_args!("{0}", "u8")); res }.as_str()` --> $DIR/key-value-expansion.rs:48:23 | LL | doc_comment! {format!("{coor}", coor = stringify!($t1)).as_str()} diff --git a/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout b/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout index 90f858f80e6b5..ad97f7a4a7540 100644 --- a/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout +++ b/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout @@ -25,8 +25,8 @@ fn arbitrary_consuming_method_for_demonstration_purposes() { { - ::std::rt::panic_fmt(::core::fmt::Arguments::new_v1(&["Assertion failed: elem as usize\nWith captures:\n elem = ", - "\n"], &[::core::fmt::ArgumentV1::new_debug(&__capture0)])) + ::std::rt::panic_fmt(format_args!("Assertion failed: elem as usize\nWith captures:\n elem = {0:?}\n", + __capture0)) } } }; @@ -41,8 +41,8 @@ fn addr_of() { if ::core::intrinsics::unlikely(!&*__local_bind0) { (&::core::asserting::Wrapper(__local_bind0)).try_capture(&mut __capture0); { - ::std::rt::panic_fmt(::core::fmt::Arguments::new_v1(&["Assertion failed: &elem\nWith captures:\n elem = ", - "\n"], &[::core::fmt::ArgumentV1::new_debug(&__capture0)])) + ::std::rt::panic_fmt(format_args!("Assertion failed: &elem\nWith captures:\n elem = {0:?}\n", + __capture0)) } } }; @@ -57,8 +57,8 @@ fn binary() { if ::core::intrinsics::unlikely(!(*__local_bind0 == 1)) { (&::core::asserting::Wrapper(__local_bind0)).try_capture(&mut __capture0); { - ::std::rt::panic_fmt(::core::fmt::Arguments::new_v1(&["Assertion failed: elem == 1\nWith captures:\n elem = ", - "\n"], &[::core::fmt::ArgumentV1::new_debug(&__capture0)])) + ::std::rt::panic_fmt(format_args!("Assertion failed: elem == 1\nWith captures:\n elem = {0:?}\n", + __capture0)) } } }; @@ -70,8 +70,8 @@ fn binary() { if ::core::intrinsics::unlikely(!(*__local_bind0 >= 1)) { (&::core::asserting::Wrapper(__local_bind0)).try_capture(&mut __capture0); { - ::std::rt::panic_fmt(::core::fmt::Arguments::new_v1(&["Assertion failed: elem >= 1\nWith captures:\n elem = ", - "\n"], &[::core::fmt::ArgumentV1::new_debug(&__capture0)])) + ::std::rt::panic_fmt(format_args!("Assertion failed: elem >= 1\nWith captures:\n elem = {0:?}\n", + __capture0)) } } }; @@ -83,8 +83,8 @@ fn binary() { if ::core::intrinsics::unlikely(!(*__local_bind0 > 0)) { (&::core::asserting::Wrapper(__local_bind0)).try_capture(&mut __capture0); { - ::std::rt::panic_fmt(::core::fmt::Arguments::new_v1(&["Assertion failed: elem > 0\nWith captures:\n elem = ", - "\n"], &[::core::fmt::ArgumentV1::new_debug(&__capture0)])) + ::std::rt::panic_fmt(format_args!("Assertion failed: elem > 0\nWith captures:\n elem = {0:?}\n", + __capture0)) } } }; @@ -96,8 +96,8 @@ fn binary() { if ::core::intrinsics::unlikely(!(*__local_bind0 < 3)) { (&::core::asserting::Wrapper(__local_bind0)).try_capture(&mut __capture0); { - ::std::rt::panic_fmt(::core::fmt::Arguments::new_v1(&["Assertion failed: elem < 3\nWith captures:\n elem = ", - "\n"], &[::core::fmt::ArgumentV1::new_debug(&__capture0)])) + ::std::rt::panic_fmt(format_args!("Assertion failed: elem < 3\nWith captures:\n elem = {0:?}\n", + __capture0)) } } }; @@ -109,8 +109,8 @@ fn binary() { if ::core::intrinsics::unlikely(!(*__local_bind0 <= 3)) { (&::core::asserting::Wrapper(__local_bind0)).try_capture(&mut __capture0); { - ::std::rt::panic_fmt(::core::fmt::Arguments::new_v1(&["Assertion failed: elem <= 3\nWith captures:\n elem = ", - "\n"], &[::core::fmt::ArgumentV1::new_debug(&__capture0)])) + ::std::rt::panic_fmt(format_args!("Assertion failed: elem <= 3\nWith captures:\n elem = {0:?}\n", + __capture0)) } } }; @@ -122,8 +122,8 @@ fn binary() { if ::core::intrinsics::unlikely(!(*__local_bind0 != 3)) { (&::core::asserting::Wrapper(__local_bind0)).try_capture(&mut __capture0); { - ::std::rt::panic_fmt(::core::fmt::Arguments::new_v1(&["Assertion failed: elem != 3\nWith captures:\n elem = ", - "\n"], &[::core::fmt::ArgumentV1::new_debug(&__capture0)])) + ::std::rt::panic_fmt(format_args!("Assertion failed: elem != 3\nWith captures:\n elem = {0:?}\n", + __capture0)) } } }; @@ -138,8 +138,8 @@ fn unary() { if ::core::intrinsics::unlikely(!**__local_bind0) { (&::core::asserting::Wrapper(__local_bind0)).try_capture(&mut __capture0); { - ::std::rt::panic_fmt(::core::fmt::Arguments::new_v1(&["Assertion failed: *elem\nWith captures:\n elem = ", - "\n"], &[::core::fmt::ArgumentV1::new_debug(&__capture0)])) + ::std::rt::panic_fmt(format_args!("Assertion failed: *elem\nWith captures:\n elem = {0:?}\n", + __capture0)) } } }; From c878caf835e8b8da1dc8cc2eb03d553e8fc5374f Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 11 Jan 2023 21:42:08 +0100 Subject: [PATCH 115/500] Make clippy compile. --- src/tools/clippy/clippy_utils/src/sugg.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/tools/clippy/clippy_utils/src/sugg.rs b/src/tools/clippy/clippy_utils/src/sugg.rs index e7879bb196e42..2d1044af17e8c 100644 --- a/src/tools/clippy/clippy_utils/src/sugg.rs +++ b/src/tools/clippy/clippy_utils/src/sugg.rs @@ -219,6 +219,7 @@ impl<'a> Sugg<'a> { | ast::ExprKind::Repeat(..) | ast::ExprKind::Ret(..) | ast::ExprKind::Yeet(..) + | ast::ExprKind::FormatArgs(..) | ast::ExprKind::Struct(..) | ast::ExprKind::Try(..) | ast::ExprKind::TryBlock(..) From a1725fa1d51d92b427edb1e92e62badcfe7787dd Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 11 Jan 2023 22:25:29 +0100 Subject: [PATCH 116/500] Update rustfmt for ast::ExprKind::FormatArgs. Rustfmt doesn't expand macros, so that's easy: FormatArgs nodes do not occur in the unexpanded AST. --- src/tools/rustfmt/src/expr.rs | 5 ++++- src/tools/rustfmt/src/utils.rs | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/tools/rustfmt/src/expr.rs b/src/tools/rustfmt/src/expr.rs index 414e767690bd0..cdbdcedd58fea 100644 --- a/src/tools/rustfmt/src/expr.rs +++ b/src/tools/rustfmt/src/expr.rs @@ -399,7 +399,10 @@ pub(crate) fn format_expr( } } ast::ExprKind::Underscore => Some("_".to_owned()), - ast::ExprKind::IncludedBytes(..) => unreachable!(), + ast::ExprKind::FormatArgs(..) | ast::ExprKind::IncludedBytes(..) => { + // These do not occur in the AST because macros aren't expanded. + unreachable!() + } ast::ExprKind::Err => None, }; diff --git a/src/tools/rustfmt/src/utils.rs b/src/tools/rustfmt/src/utils.rs index 3e884419f1a32..80dce525e3957 100644 --- a/src/tools/rustfmt/src/utils.rs +++ b/src/tools/rustfmt/src/utils.rs @@ -462,6 +462,7 @@ pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool { pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool { match expr.kind { ast::ExprKind::MacCall(..) + | ast::ExprKind::FormatArgs(..) | ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Array(..) From 7a3d5fe8422242af734766c4a5001ad6e14059a7 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 11 Jan 2023 22:33:13 +0100 Subject: [PATCH 117/500] Bless pretty tests. --- tests/pretty/dollar-crate.pp | 4 +--- tests/pretty/issue-4264.pp | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/tests/pretty/dollar-crate.pp b/tests/pretty/dollar-crate.pp index 3af37955f2380..60fddb630d964 100644 --- a/tests/pretty/dollar-crate.pp +++ b/tests/pretty/dollar-crate.pp @@ -8,6 +8,4 @@ // pretty-mode:expanded // pp-exact:dollar-crate.pp -fn main() { - { ::std::io::_print(::core::fmt::Arguments::new_v1(&["rust\n"], &[])); }; -} +fn main() { { ::std::io::_print(format_args!("rust\n")); }; } diff --git a/tests/pretty/issue-4264.pp b/tests/pretty/issue-4264.pp index 18e6d75b1d5ad..44d21625a2d10 100644 --- a/tests/pretty/issue-4264.pp +++ b/tests/pretty/issue-4264.pp @@ -32,7 +32,7 @@ ({ let res = ((::alloc::fmt::format as - for<'a> fn(Arguments<'a>) -> String {format})(((::core::fmt::Arguments::new_v1 + for<'a> fn(Arguments<'a>) -> String {format})(((<#[lang = "format_arguments"]>::new_v1 as fn(&[&'static str], &[ArgumentV1<'_>]) -> Arguments<'_> {Arguments::<'_>::new_v1})((&([("test" as &str)] as [&str; 1]) as &[&str; 1]), From dd168838b9d353229dc6c9dfb25f3caa66a1d5b2 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 11 Jan 2023 21:42:08 +0100 Subject: [PATCH 118/500] Make clippy compile. --- clippy_utils/src/sugg.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/clippy_utils/src/sugg.rs b/clippy_utils/src/sugg.rs index e7879bb196e42..2d1044af17e8c 100644 --- a/clippy_utils/src/sugg.rs +++ b/clippy_utils/src/sugg.rs @@ -219,6 +219,7 @@ impl<'a> Sugg<'a> { | ast::ExprKind::Repeat(..) | ast::ExprKind::Ret(..) | ast::ExprKind::Yeet(..) + | ast::ExprKind::FormatArgs(..) | ast::ExprKind::Struct(..) | ast::ExprKind::Try(..) | ast::ExprKind::TryBlock(..) From 36fe3b971dbf23bbb362f79006f7c8571818eb5d Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 12 Jan 2023 00:25:09 +0100 Subject: [PATCH 119/500] Update clippy for new format_args!() lang items. --- .../clippy/clippy_lints/src/format_args.rs | 6 +-- src/tools/clippy/clippy_utils/src/macros.rs | 54 +++++++++++-------- 2 files changed, 35 insertions(+), 25 deletions(-) diff --git a/src/tools/clippy/clippy_lints/src/format_args.rs b/src/tools/clippy/clippy_lints/src/format_args.rs index 043112bbc9596..70a80d40f464b 100644 --- a/src/tools/clippy/clippy_lints/src/format_args.rs +++ b/src/tools/clippy/clippy_lints/src/format_args.rs @@ -7,14 +7,14 @@ use clippy_utils::macros::{ }; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::source::snippet_opt; -use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; +use clippy_utils::ty::{implements_trait, is_type_lang_item}; use if_chain::if_chain; use itertools::Itertools; use rustc_errors::{ Applicability, SuggestionStyle::{CompletelyHidden, ShowCode}, }; -use rustc_hir::{Expr, ExprKind, HirId, QPath}; +use rustc_hir::{Expr, ExprKind, HirId, LangItem, QPath}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::ty::adjustment::{Adjust, Adjustment}; use rustc_middle::ty::Ty; @@ -237,7 +237,7 @@ fn check_unused_format_specifier(cx: &LateContext<'_>, arg: &FormatArg<'_>) { ); } - if is_type_diagnostic_item(cx, param_ty, sym::Arguments) && !arg.format.is_default_for_trait() { + if is_type_lang_item(cx, param_ty, LangItem::FormatArguments) && !arg.format.is_default_for_trait() { span_lint_and_then( cx, UNUSED_FORMAT_SPECS, diff --git a/src/tools/clippy/clippy_utils/src/macros.rs b/src/tools/clippy/clippy_utils/src/macros.rs index 77c5f1155423c..a8f8da67b5171 100644 --- a/src/tools/clippy/clippy_utils/src/macros.rs +++ b/src/tools/clippy/clippy_utils/src/macros.rs @@ -1,6 +1,5 @@ #![allow(clippy::similar_names)] // `expr` and `expn` -use crate::is_path_diagnostic_item; use crate::source::snippet_opt; use crate::visitors::{for_each_expr, Descend}; @@ -8,7 +7,7 @@ use arrayvec::ArrayVec; use itertools::{izip, Either, Itertools}; use rustc_ast::ast::LitKind; use rustc_hir::intravisit::{walk_expr, Visitor}; -use rustc_hir::{self as hir, Expr, ExprField, ExprKind, HirId, Node, QPath}; +use rustc_hir::{self as hir, Expr, ExprField, ExprKind, HirId, LangItem, Node, QPath, TyKind}; use rustc_lexer::unescape::unescape_literal; use rustc_lexer::{tokenize, unescape, LiteralKind, TokenKind}; use rustc_lint::LateContext; @@ -439,8 +438,7 @@ impl<'tcx> FormatArgsValues<'tcx> { // ArgumentV1::from_usize() if let ExprKind::Call(callee, [val]) = expr.kind && let ExprKind::Path(QPath::TypeRelative(ty, _)) = callee.kind - && let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind - && path.segments.last().unwrap().ident.name == sym::ArgumentV1 + && let TyKind::Path(QPath::LangItem(LangItem::FormatArgument, _, _)) = ty.kind { let val_idx = if val.span.ctxt() == expr.span.ctxt() && let ExprKind::Field(_, field) = val.kind @@ -486,20 +484,6 @@ struct ParamPosition { impl<'tcx> Visitor<'tcx> for ParamPosition { fn visit_expr_field(&mut self, field: &'tcx ExprField<'tcx>) { - fn parse_count(expr: &Expr<'_>) -> Option { - // ::core::fmt::rt::v1::Count::Param(1usize), - if let ExprKind::Call(ctor, [val]) = expr.kind - && let ExprKind::Path(QPath::Resolved(_, path)) = ctor.kind - && path.segments.last()?.ident.name == sym::Param - && let ExprKind::Lit(lit) = &val.kind - && let LitKind::Int(pos, _) = lit.node - { - Some(pos as usize) - } else { - None - } - } - match field.ident.name { sym::position => { if let ExprKind::Lit(lit) = &field.expr.kind @@ -519,15 +503,41 @@ impl<'tcx> Visitor<'tcx> for ParamPosition { } } +fn parse_count(expr: &Expr<'_>) -> Option { + // <::core::fmt::rt::v1::Count>::Param(1usize), + if let ExprKind::Call(ctor, [val]) = expr.kind + && let ExprKind::Path(QPath::TypeRelative(_, path)) = ctor.kind + && path.ident.name == sym::Param + && let ExprKind::Lit(lit) = &val.kind + && let LitKind::Int(pos, _) = lit.node + { + Some(pos as usize) + } else { + None + } +} + /// Parses the `fmt` arg of `Arguments::new_v1_formatted(pieces, args, fmt, _)` fn parse_rt_fmt<'tcx>(fmt_arg: &'tcx Expr<'tcx>) -> Option + 'tcx> { if let ExprKind::AddrOf(.., array) = fmt_arg.kind && let ExprKind::Array(specs) = array.kind { Some(specs.iter().map(|spec| { - let mut position = ParamPosition::default(); - position.visit_expr(spec); - position + if let ExprKind::Call(f, args) = spec.kind + && let ExprKind::Path(QPath::TypeRelative(ty, f)) = f.kind + && let TyKind::Path(QPath::LangItem(LangItem::FormatPlaceholder, _, _)) = ty.kind + && f.ident.name == sym::new + && let [position, _fill, _align, _flags, precision, width] = args + && let ExprKind::Lit(position) = &position.kind + && let LitKind::Int(position, _) = position.node { + ParamPosition { + value: position as usize, + width: parse_count(width), + precision: parse_count(precision), + } + } else { + ParamPosition::default() + } })) } else { None @@ -890,7 +900,7 @@ impl<'tcx> FormatArgsExpn<'tcx> { // ::core::fmt::Arguments::new_v1_formatted(pieces, args, fmt, _unsafe_arg) if let ExprKind::Call(callee, [pieces, args, rest @ ..]) = expr.kind && let ExprKind::Path(QPath::TypeRelative(ty, seg)) = callee.kind - && is_path_diagnostic_item(cx, ty, sym::Arguments) + && let TyKind::Path(QPath::LangItem(LangItem::FormatArguments, _, _)) = ty.kind && matches!(seg.ident.as_str(), "new_v1" | "new_v1_formatted") { let format_string = FormatString::new(cx, pieces)?; From 2bcd697e2d89d0f9f80682fdaaf5bbdd5adbb0ba Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 12 Jan 2023 00:25:09 +0100 Subject: [PATCH 120/500] Update clippy for new format_args!() lang items. --- clippy_lints/src/format_args.rs | 6 ++-- clippy_utils/src/macros.rs | 54 +++++++++++++++++++-------------- 2 files changed, 35 insertions(+), 25 deletions(-) diff --git a/clippy_lints/src/format_args.rs b/clippy_lints/src/format_args.rs index 043112bbc9596..70a80d40f464b 100644 --- a/clippy_lints/src/format_args.rs +++ b/clippy_lints/src/format_args.rs @@ -7,14 +7,14 @@ use clippy_utils::macros::{ }; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::source::snippet_opt; -use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; +use clippy_utils::ty::{implements_trait, is_type_lang_item}; use if_chain::if_chain; use itertools::Itertools; use rustc_errors::{ Applicability, SuggestionStyle::{CompletelyHidden, ShowCode}, }; -use rustc_hir::{Expr, ExprKind, HirId, QPath}; +use rustc_hir::{Expr, ExprKind, HirId, LangItem, QPath}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::ty::adjustment::{Adjust, Adjustment}; use rustc_middle::ty::Ty; @@ -237,7 +237,7 @@ fn check_unused_format_specifier(cx: &LateContext<'_>, arg: &FormatArg<'_>) { ); } - if is_type_diagnostic_item(cx, param_ty, sym::Arguments) && !arg.format.is_default_for_trait() { + if is_type_lang_item(cx, param_ty, LangItem::FormatArguments) && !arg.format.is_default_for_trait() { span_lint_and_then( cx, UNUSED_FORMAT_SPECS, diff --git a/clippy_utils/src/macros.rs b/clippy_utils/src/macros.rs index 77c5f1155423c..a8f8da67b5171 100644 --- a/clippy_utils/src/macros.rs +++ b/clippy_utils/src/macros.rs @@ -1,6 +1,5 @@ #![allow(clippy::similar_names)] // `expr` and `expn` -use crate::is_path_diagnostic_item; use crate::source::snippet_opt; use crate::visitors::{for_each_expr, Descend}; @@ -8,7 +7,7 @@ use arrayvec::ArrayVec; use itertools::{izip, Either, Itertools}; use rustc_ast::ast::LitKind; use rustc_hir::intravisit::{walk_expr, Visitor}; -use rustc_hir::{self as hir, Expr, ExprField, ExprKind, HirId, Node, QPath}; +use rustc_hir::{self as hir, Expr, ExprField, ExprKind, HirId, LangItem, Node, QPath, TyKind}; use rustc_lexer::unescape::unescape_literal; use rustc_lexer::{tokenize, unescape, LiteralKind, TokenKind}; use rustc_lint::LateContext; @@ -439,8 +438,7 @@ impl<'tcx> FormatArgsValues<'tcx> { // ArgumentV1::from_usize() if let ExprKind::Call(callee, [val]) = expr.kind && let ExprKind::Path(QPath::TypeRelative(ty, _)) = callee.kind - && let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind - && path.segments.last().unwrap().ident.name == sym::ArgumentV1 + && let TyKind::Path(QPath::LangItem(LangItem::FormatArgument, _, _)) = ty.kind { let val_idx = if val.span.ctxt() == expr.span.ctxt() && let ExprKind::Field(_, field) = val.kind @@ -486,20 +484,6 @@ struct ParamPosition { impl<'tcx> Visitor<'tcx> for ParamPosition { fn visit_expr_field(&mut self, field: &'tcx ExprField<'tcx>) { - fn parse_count(expr: &Expr<'_>) -> Option { - // ::core::fmt::rt::v1::Count::Param(1usize), - if let ExprKind::Call(ctor, [val]) = expr.kind - && let ExprKind::Path(QPath::Resolved(_, path)) = ctor.kind - && path.segments.last()?.ident.name == sym::Param - && let ExprKind::Lit(lit) = &val.kind - && let LitKind::Int(pos, _) = lit.node - { - Some(pos as usize) - } else { - None - } - } - match field.ident.name { sym::position => { if let ExprKind::Lit(lit) = &field.expr.kind @@ -519,15 +503,41 @@ impl<'tcx> Visitor<'tcx> for ParamPosition { } } +fn parse_count(expr: &Expr<'_>) -> Option { + // <::core::fmt::rt::v1::Count>::Param(1usize), + if let ExprKind::Call(ctor, [val]) = expr.kind + && let ExprKind::Path(QPath::TypeRelative(_, path)) = ctor.kind + && path.ident.name == sym::Param + && let ExprKind::Lit(lit) = &val.kind + && let LitKind::Int(pos, _) = lit.node + { + Some(pos as usize) + } else { + None + } +} + /// Parses the `fmt` arg of `Arguments::new_v1_formatted(pieces, args, fmt, _)` fn parse_rt_fmt<'tcx>(fmt_arg: &'tcx Expr<'tcx>) -> Option + 'tcx> { if let ExprKind::AddrOf(.., array) = fmt_arg.kind && let ExprKind::Array(specs) = array.kind { Some(specs.iter().map(|spec| { - let mut position = ParamPosition::default(); - position.visit_expr(spec); - position + if let ExprKind::Call(f, args) = spec.kind + && let ExprKind::Path(QPath::TypeRelative(ty, f)) = f.kind + && let TyKind::Path(QPath::LangItem(LangItem::FormatPlaceholder, _, _)) = ty.kind + && f.ident.name == sym::new + && let [position, _fill, _align, _flags, precision, width] = args + && let ExprKind::Lit(position) = &position.kind + && let LitKind::Int(position, _) = position.node { + ParamPosition { + value: position as usize, + width: parse_count(width), + precision: parse_count(precision), + } + } else { + ParamPosition::default() + } })) } else { None @@ -890,7 +900,7 @@ impl<'tcx> FormatArgsExpn<'tcx> { // ::core::fmt::Arguments::new_v1_formatted(pieces, args, fmt, _unsafe_arg) if let ExprKind::Call(callee, [pieces, args, rest @ ..]) = expr.kind && let ExprKind::Path(QPath::TypeRelative(ty, seg)) = callee.kind - && is_path_diagnostic_item(cx, ty, sym::Arguments) + && let TyKind::Path(QPath::LangItem(LangItem::FormatArguments, _, _)) = ty.kind && matches!(seg.ident.as_str(), "new_v1" | "new_v1_formatted") { let format_string = FormatString::new(cx, pieces)?; From 9e6785430b2253315a4ce31d03464a30c250ac38 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 12 Jan 2023 00:31:17 +0100 Subject: [PATCH 121/500] Make core::fmt::rt::v1::Argument::new const+inline. --- library/core/src/fmt/rt/v1.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/core/src/fmt/rt/v1.rs b/library/core/src/fmt/rt/v1.rs index e61b89fad5d3b..11a50951a75da 100644 --- a/library/core/src/fmt/rt/v1.rs +++ b/library/core/src/fmt/rt/v1.rs @@ -23,7 +23,8 @@ pub struct FormatSpec { } impl Argument { - pub fn new( + #[inline(always)] + pub const fn new( position: usize, fill: char, align: Alignment, From bcf388f4ac3261d1cc0490415a81d5e4939c7915 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 12 Jan 2023 00:39:46 +0100 Subject: [PATCH 122/500] Update outdated comment. --- compiler/rustc_ast_lowering/src/format.rs | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index f8ed164b356f1..f21c0f23bc114 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -94,16 +94,14 @@ fn make_format_spec<'hir>( argmap: &mut FxIndexSet<(usize, ArgumentType)>, ) -> hir::Expr<'hir> { // Generate: - // ::core::fmt::rt::v1::Argument { - // position: 0usize, - // format: ::core::fmt::rt::v1::FormatSpec { - // fill: ' ', - // align: ::core::fmt::rt::v1::Alignment::Unknown, - // flags: 0u32, - // precision: ::core::fmt::rt::v1::Count::Implied, - // width: ::core::fmt::rt::v1::Count::Implied, - // }, - // } + // ::core::fmt::rt::v1::Argument::new( + // 0usize, // position + // ' ', // fill + // ::core::fmt::rt::v1::Alignment::Unknown, + // 0u32, // flags + // ::core::fmt::rt::v1::Count::Implied, // width + // ::core::fmt::rt::v1::Count::Implied, // precision + // ) let position = match placeholder.argument.index { Ok(arg_index) => { let (i, _) = From 56593104acef6afc0f3d29c765801bb44ec02c65 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 12 Jan 2023 00:45:29 +0100 Subject: [PATCH 123/500] Update comment explaining format_args!() expansion. --- compiler/rustc_builtin_macros/src/format.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index 47b63a7fa122f..a246aefc806a2 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -20,11 +20,11 @@ use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, LintId}; // 1. First, `parse_args` will parse the `(literal, arg, arg, name=arg, name=arg)` syntax, // but doesn't parse the template (the literal) itself. // 2. Second, `make_format_args` will parse the template, the format options, resolve argument references, -// produce diagnostics, and turn the whole thing into a `FormatArgs` structure. -// 3. Finally, `expand_parsed_format_args` will turn that `FormatArgs` structure -// into the expression that the macro expands to. +// produce diagnostics, and turn the whole thing into a `FormatArgs` AST node. +// 3. Much later, in AST lowering (rustc_ast_lowering), that `FormatArgs` structure will be turned +// into the expression of type `core::fmt::Arguments`. -// See format/ast.rs for the FormatArgs structure and glossary. +// See rustc_ast/src/format.rs for the FormatArgs structure and glossary. // Only used in parse_args and report_invalid_references, // to indicate how a referred argument was used. From 19c2286d5c0fe45765cb6bd182b32722173b0942 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Tue, 20 Dec 2022 16:15:55 +0000 Subject: [PATCH 124/500] parse const closures --- src/closures.rs | 19 ++++++++++++++++--- src/expr.rs | 1 + 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/closures.rs b/src/closures.rs index 244d4427c5623..8fd0fcf8f5c2c 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -26,6 +26,7 @@ use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt}; pub(crate) fn rewrite_closure( binder: &ast::ClosureBinder, + constness: ast::Const, capture: ast::CaptureBy, is_async: &ast::Async, movability: ast::Movability, @@ -38,7 +39,7 @@ pub(crate) fn rewrite_closure( debug!("rewrite_closure {:?}", body); let (prefix, extra_offset) = rewrite_closure_fn_decl( - binder, capture, is_async, movability, fn_decl, body, span, context, shape, + binder, constness, capture, is_async, movability, fn_decl, body, span, context, shape, )?; // 1 = space between `|...|` and body. let body_shape = shape.offset_left(extra_offset)?; @@ -230,6 +231,7 @@ fn rewrite_closure_block( // Return type is (prefix, extra_offset) fn rewrite_closure_fn_decl( binder: &ast::ClosureBinder, + constness: ast::Const, capture: ast::CaptureBy, asyncness: &ast::Async, movability: ast::Movability, @@ -250,6 +252,12 @@ fn rewrite_closure_fn_decl( ast::ClosureBinder::NotPresent => "".to_owned(), }; + let const_ = if matches!(constness, ast::Const::Yes(_)) { + "const " + } else { + "" + }; + let immovable = if movability == ast::Movability::Static { "static " } else { @@ -264,7 +272,7 @@ fn rewrite_closure_fn_decl( // 4 = "|| {".len(), which is overconservative when the closure consists of // a single expression. let nested_shape = shape - .shrink_left(binder.len() + immovable.len() + is_async.len() + mover.len())? + .shrink_left(binder.len() + const_.len() + immovable.len() + is_async.len() + mover.len())? .sub_width(4)?; // 1 = | @@ -302,7 +310,10 @@ fn rewrite_closure_fn_decl( .tactic(tactic) .preserve_newline(true); let list_str = write_list(&item_vec, &fmt)?; - let mut prefix = format!("{}{}{}{}|{}|", binder, immovable, is_async, mover, list_str); + let mut prefix = format!( + "{}{}{}{}{}|{}|", + binder, const_, immovable, is_async, mover, list_str + ); if !ret_str.is_empty() { if prefix.contains('\n') { @@ -329,6 +340,7 @@ pub(crate) fn rewrite_last_closure( if let ast::ExprKind::Closure(ref closure) = expr.kind { let ast::Closure { ref binder, + constness, capture_clause, ref asyncness, movability, @@ -349,6 +361,7 @@ pub(crate) fn rewrite_last_closure( }; let (prefix, extra_offset) = rewrite_closure_fn_decl( binder, + constness, capture_clause, asyncness, movability, diff --git a/src/expr.rs b/src/expr.rs index 414e767690bd0..868ff045ab78b 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -205,6 +205,7 @@ pub(crate) fn format_expr( } ast::ExprKind::Closure(ref cl) => closures::rewrite_closure( &cl.binder, + cl.constness, cl.capture_clause, &cl.asyncness, cl.movability, From 0a03d1c9cafde0ada19b4fab0f3d6892cb154fd8 Mon Sep 17 00:00:00 2001 From: Collin Baker Date: Thu, 12 Jan 2023 05:36:04 -0500 Subject: [PATCH 125/500] Allow setting CFG_DISABLE_UNSTABLE_FEATURES to 0 Two locations check whether this build-time environment variable is defined. Allowing it to be explicitly disabled with a "0" value is useful, especially for integrating with external build systems. --- compiler/rustc_feature/src/lib.rs | 3 ++- library/test/src/cli.rs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_feature/src/lib.rs b/compiler/rustc_feature/src/lib.rs index 8e2a13a6c0ab1..93d1671634691 100644 --- a/compiler/rustc_feature/src/lib.rs +++ b/compiler/rustc_feature/src/lib.rs @@ -83,7 +83,8 @@ impl UnstableFeatures { /// Otherwise, only `RUSTC_BOOTSTRAP=1` will work. pub fn from_environment(krate: Option<&str>) -> Self { // `true` if this is a feature-staged build, i.e., on the beta or stable channel. - let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some(); + let disable_unstable_features = + option_env!("CFG_DISABLE_UNSTABLE_FEATURES").map(|s| s != "0").unwrap_or(false); // Returns whether `krate` should be counted as unstable let is_unstable_crate = |var: &str| { krate.map_or(false, |name| var.split(',').any(|new_krate| new_krate == name)) diff --git a/library/test/src/cli.rs b/library/test/src/cli.rs index 796796e07a9c1..9d22ebbee873b 100644 --- a/library/test/src/cli.rs +++ b/library/test/src/cli.rs @@ -309,7 +309,8 @@ fn parse_opts_impl(matches: getopts::Matches) -> OptRes { // FIXME: Copied from librustc_ast until linkage errors are resolved. Issue #47566 fn is_nightly() -> bool { // Whether this is a feature-staged build, i.e., on the beta or stable channel - let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some(); + let disable_unstable_features = + option_env!("CFG_DISABLE_UNSTABLE_FEATURES").map(|s| s != "0").unwrap_or(false); // Whether we should enable unstable features for bootstrapping let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok(); From 51aaba6e8cf50289d55f53ac85aab4c95d601439 Mon Sep 17 00:00:00 2001 From: navh Date: Tue, 6 Dec 2022 19:05:22 +0100 Subject: [PATCH 126/500] `cast_possible_truncation` Suggest TryFrom when truncation possible --- .../src/casts/cast_possible_truncation.rs | 24 ++++- clippy_lints/src/casts/mod.rs | 2 +- tests/ui/cast.stderr | 95 +++++++++++++++++++ tests/ui/cast_size.stderr | 53 +++++++++++ 4 files changed, 170 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/casts/cast_possible_truncation.rs b/clippy_lints/src/casts/cast_possible_truncation.rs index a6376484914ba..d9898aeb92c4d 100644 --- a/clippy_lints/src/casts/cast_possible_truncation.rs +++ b/clippy_lints/src/casts/cast_possible_truncation.rs @@ -1,7 +1,11 @@ use clippy_utils::consts::{constant, Constant}; -use clippy_utils::diagnostics::span_lint; +use clippy_utils::diagnostics::{span_lint, span_lint_and_then}; use clippy_utils::expr_or_init; +use clippy_utils::source::snippet; use clippy_utils::ty::{get_discriminant_value, is_isize_or_usize}; +use rustc_ast::ast; +use rustc_attr::IntType; +use rustc_errors::{Applicability, SuggestionStyle}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::LateContext; @@ -139,7 +143,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, ); return; } - format!("casting `{cast_from}` to `{cast_to}` may truncate the value{suffix}",) + format!("casting `{cast_from}` to `{cast_to}` may truncate the value{suffix}") }, (ty::Float(_), true) => { @@ -153,5 +157,19 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, _ => return, }; - span_lint(cx, CAST_POSSIBLE_TRUNCATION, expr.span, &msg); + let snippet = snippet(cx, expr.span, "x"); + let name_of_cast_from = snippet.split(" as").next().unwrap_or("x"); + let suggestion = format!("{cast_to}::try_from({name_of_cast_from})"); + + span_lint_and_then(cx, CAST_POSSIBLE_TRUNCATION, expr.span, &msg, |diag| { + diag.help("if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ..."); + diag.span_suggestion_with_style( + expr.span, + "... or use `try_from` and handle the error accordingly", + suggestion, + Applicability::Unspecified, + // always show the suggestion in a separate line + SuggestionStyle::ShowAlways, + ); + }); } diff --git a/clippy_lints/src/casts/mod.rs b/clippy_lints/src/casts/mod.rs index 161e3a698e9ea..38b1c5c1c7e7e 100644 --- a/clippy_lints/src/casts/mod.rs +++ b/clippy_lints/src/casts/mod.rs @@ -85,7 +85,7 @@ declare_clippy_lint! { /// ### Why is this bad? /// In some problem domains, it is good practice to avoid /// truncation. This lint can be activated to help assess where additional - /// checks could be beneficial. + /// checks could be beneficial, and suggests implementing TryFrom trait. /// /// ### Example /// ```rust diff --git a/tests/ui/cast.stderr b/tests/ui/cast.stderr index 0c63b4af30865..eceb135d62ba6 100644 --- a/tests/ui/cast.stderr +++ b/tests/ui/cast.stderr @@ -42,13 +42,24 @@ error: casting `f32` to `i32` may truncate the value LL | 1f32 as i32; | ^^^^^^^^^^^ | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... = note: `-D clippy::cast-possible-truncation` implied by `-D warnings` +help: ... or use `try_from` and handle the error accordingly + | +LL | i32::try_from(1f32); + | ~~~~~~~~~~~~~~~~~~~ error: casting `f32` to `u32` may truncate the value --> $DIR/cast.rs:25:5 | LL | 1f32 as u32; | ^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | u32::try_from(1f32); + | ~~~~~~~~~~~~~~~~~~~ error: casting `f32` to `u32` may lose the sign of the value --> $DIR/cast.rs:25:5 @@ -63,30 +74,60 @@ error: casting `f64` to `f32` may truncate the value | LL | 1f64 as f32; | ^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | f32::try_from(1f64); + | ~~~~~~~~~~~~~~~~~~~ error: casting `i32` to `i8` may truncate the value --> $DIR/cast.rs:27:5 | LL | 1i32 as i8; | ^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | i8::try_from(1i32); + | ~~~~~~~~~~~~~~~~~~ error: casting `i32` to `u8` may truncate the value --> $DIR/cast.rs:28:5 | LL | 1i32 as u8; | ^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | u8::try_from(1i32); + | ~~~~~~~~~~~~~~~~~~ error: casting `f64` to `isize` may truncate the value --> $DIR/cast.rs:29:5 | LL | 1f64 as isize; | ^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | isize::try_from(1f64); + | ~~~~~~~~~~~~~~~~~~~~~ error: casting `f64` to `usize` may truncate the value --> $DIR/cast.rs:30:5 | LL | 1f64 as usize; | ^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | usize::try_from(1f64); + | ~~~~~~~~~~~~~~~~~~~~~ error: casting `f64` to `usize` may lose the sign of the value --> $DIR/cast.rs:30:5 @@ -143,18 +184,36 @@ error: casting `i64` to `i8` may truncate the value | LL | (-99999999999i64).min(1) as i8; // should be linted because signed | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | i8::try_from((-99999999999i64).min(1)); // should be linted because signed + | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: casting `u64` to `u8` may truncate the value --> $DIR/cast.rs:120:5 | LL | 999999u64.clamp(0, 256) as u8; // should still be linted | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | u8::try_from(999999u64.clamp(0, 256)); // should still be linted + | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: casting `main::E2` to `u8` may truncate the value --> $DIR/cast.rs:141:21 | LL | let _ = self as u8; | ^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | let _ = u8::try_from(self); + | ~~~~~~~~~~~~~~~~~~ error: casting `main::E2::B` to `u8` will truncate the value --> $DIR/cast.rs:142:21 @@ -169,6 +228,12 @@ error: casting `main::E5` to `i8` may truncate the value | LL | let _ = self as i8; | ^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | let _ = i8::try_from(self); + | ~~~~~~~~~~~~~~~~~~ error: casting `main::E5::A` to `i8` will truncate the value --> $DIR/cast.rs:179:21 @@ -181,30 +246,60 @@ error: casting `main::E6` to `i16` may truncate the value | LL | let _ = self as i16; | ^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | let _ = i16::try_from(self); + | ~~~~~~~~~~~~~~~~~~~ error: casting `main::E7` to `usize` may truncate the value on targets with 32-bit wide pointers --> $DIR/cast.rs:208:21 | LL | let _ = self as usize; | ^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | let _ = usize::try_from(self); + | ~~~~~~~~~~~~~~~~~~~~~ error: casting `main::E10` to `u16` may truncate the value --> $DIR/cast.rs:249:21 | LL | let _ = self as u16; | ^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | let _ = u16::try_from(self); + | ~~~~~~~~~~~~~~~~~~~ error: casting `u32` to `u8` may truncate the value --> $DIR/cast.rs:257:13 | LL | let c = (q >> 16) as u8; | ^^^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | let c = u8::try_from((q >> 16)); + | ~~~~~~~~~~~~~~~~~~~~~~~ error: casting `u32` to `u8` may truncate the value --> $DIR/cast.rs:260:13 | LL | let c = (q / 1000) as u8; | ^^^^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | let c = u8::try_from((q / 1000)); + | ~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to 33 previous errors diff --git a/tests/ui/cast_size.stderr b/tests/ui/cast_size.stderr index 95552f2e28539..8acf26049f4d1 100644 --- a/tests/ui/cast_size.stderr +++ b/tests/ui/cast_size.stderr @@ -4,7 +4,12 @@ error: casting `isize` to `i8` may truncate the value LL | 1isize as i8; | ^^^^^^^^^^^^ | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... = note: `-D clippy::cast-possible-truncation` implied by `-D warnings` +help: ... or use `try_from` and handle the error accordingly + | +LL | i8::try_from(1isize); + | ~~~~~~~~~~~~~~~~~~~~ error: casting `isize` to `f64` causes a loss of precision on targets with 64-bit wide pointers (`isize` is 64 bits wide, but `f64`'s mantissa is only 52 bits wide) --> $DIR/cast_size.rs:15:5 @@ -37,24 +42,48 @@ error: casting `isize` to `i32` may truncate the value on targets with 64-bit wi | LL | 1isize as i32; | ^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | i32::try_from(1isize); + | ~~~~~~~~~~~~~~~~~~~~~ error: casting `isize` to `u32` may truncate the value on targets with 64-bit wide pointers --> $DIR/cast_size.rs:20:5 | LL | 1isize as u32; | ^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | u32::try_from(1isize); + | ~~~~~~~~~~~~~~~~~~~~~ error: casting `usize` to `u32` may truncate the value on targets with 64-bit wide pointers --> $DIR/cast_size.rs:21:5 | LL | 1usize as u32; | ^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | u32::try_from(1usize); + | ~~~~~~~~~~~~~~~~~~~~~ error: casting `usize` to `i32` may truncate the value on targets with 64-bit wide pointers --> $DIR/cast_size.rs:22:5 | LL | 1usize as i32; | ^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | i32::try_from(1usize); + | ~~~~~~~~~~~~~~~~~~~~~ error: casting `usize` to `i32` may wrap around the value on targets with 32-bit wide pointers --> $DIR/cast_size.rs:22:5 @@ -69,18 +98,36 @@ error: casting `i64` to `isize` may truncate the value on targets with 32-bit wi | LL | 1i64 as isize; | ^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | isize::try_from(1i64); + | ~~~~~~~~~~~~~~~~~~~~~ error: casting `i64` to `usize` may truncate the value on targets with 32-bit wide pointers --> $DIR/cast_size.rs:25:5 | LL | 1i64 as usize; | ^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | usize::try_from(1i64); + | ~~~~~~~~~~~~~~~~~~~~~ error: casting `u64` to `isize` may truncate the value on targets with 32-bit wide pointers --> $DIR/cast_size.rs:26:5 | LL | 1u64 as isize; | ^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | isize::try_from(1u64); + | ~~~~~~~~~~~~~~~~~~~~~ error: casting `u64` to `isize` may wrap around the value on targets with 64-bit wide pointers --> $DIR/cast_size.rs:26:5 @@ -93,6 +140,12 @@ error: casting `u64` to `usize` may truncate the value on targets with 32-bit wi | LL | 1u64 as usize; | ^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | usize::try_from(1u64); + | ~~~~~~~~~~~~~~~~~~~~~ error: casting `u32` to `isize` may wrap around the value on targets with 32-bit wide pointers --> $DIR/cast_size.rs:28:5 From fcdd08badf90665832939ccd30dc6df3194dd8a4 Mon Sep 17 00:00:00 2001 From: navh Date: Tue, 6 Dec 2022 19:05:49 +0100 Subject: [PATCH 127/500] update `cast_possible_truncation` documentation --- clippy_lints/src/casts/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/casts/mod.rs b/clippy_lints/src/casts/mod.rs index 38b1c5c1c7e7e..a9618ca06d64a 100644 --- a/clippy_lints/src/casts/mod.rs +++ b/clippy_lints/src/casts/mod.rs @@ -80,12 +80,13 @@ declare_clippy_lint! { /// ### What it does /// Checks for casts between numerical types that may /// truncate large values. This is expected behavior, so the cast is `Allow` by - /// default. + /// default. It suggests user either explicitly ignore the lint, + /// or use `try_from()` and handle the truncation, default, or panic explicitly. /// /// ### Why is this bad? /// In some problem domains, it is good practice to avoid /// truncation. This lint can be activated to help assess where additional - /// checks could be beneficial, and suggests implementing TryFrom trait. + /// checks could be beneficial. /// /// ### Example /// ```rust From e6948c4117b608585c5aa22a7f95b6cfdc88dc48 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Tue, 6 Dec 2022 19:07:18 +0100 Subject: [PATCH 128/500] Last PR adjustments --- .../src/casts/cast_possible_truncation.rs | 6 ++---- clippy_lints/src/casts/mod.rs | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/casts/cast_possible_truncation.rs b/clippy_lints/src/casts/cast_possible_truncation.rs index d9898aeb92c4d..7a6450ffaa5ec 100644 --- a/clippy_lints/src/casts/cast_possible_truncation.rs +++ b/clippy_lints/src/casts/cast_possible_truncation.rs @@ -3,8 +3,6 @@ use clippy_utils::diagnostics::{span_lint, span_lint_and_then}; use clippy_utils::expr_or_init; use clippy_utils::source::snippet; use clippy_utils::ty::{get_discriminant_value, is_isize_or_usize}; -use rustc_ast::ast; -use rustc_attr::IntType; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{BinOpKind, Expr, ExprKind}; @@ -157,8 +155,8 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, _ => return, }; - let snippet = snippet(cx, expr.span, "x"); - let name_of_cast_from = snippet.split(" as").next().unwrap_or("x"); + let snippet = snippet(cx, expr.span, ".."); + let name_of_cast_from = snippet.split(" as").next().unwrap_or(".."); let suggestion = format!("{cast_to}::try_from({name_of_cast_from})"); span_lint_and_then(cx, CAST_POSSIBLE_TRUNCATION, expr.span, &msg, |diag| { diff --git a/clippy_lints/src/casts/mod.rs b/clippy_lints/src/casts/mod.rs index a9618ca06d64a..64dbe6c224c7d 100644 --- a/clippy_lints/src/casts/mod.rs +++ b/clippy_lints/src/casts/mod.rs @@ -94,6 +94,21 @@ declare_clippy_lint! { /// x as u8 /// } /// ``` + /// Use instead: + /// ``` + /// fn as_u8(x: u64) -> u8 { + /// if let Ok(x) = u8::try_from(x) { + /// x + /// } else { + /// todo!(); + /// } + /// } + /// // Or + /// #[allow(clippy::cast_possible_truncation)] + /// fn as_u16(x: u64) -> u16 { + /// x as u16 + /// } + /// ``` #[clippy::version = "pre 1.29.0"] pub CAST_POSSIBLE_TRUNCATION, pedantic, From 5cb6246c3e7ccae640eafbc238a293918b552116 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Thu, 12 Jan 2023 12:35:29 +0100 Subject: [PATCH 129/500] Address PR reivew --- .../src/casts/cast_possible_truncation.rs | 16 +++-- clippy_lints/src/casts/mod.rs | 2 +- tests/ui/cast.rs | 1 + tests/ui/cast.stderr | 68 +++++++++++++------ 4 files changed, 63 insertions(+), 24 deletions(-) diff --git a/clippy_lints/src/casts/cast_possible_truncation.rs b/clippy_lints/src/casts/cast_possible_truncation.rs index 7a6450ffaa5ec..f3f8b8d87982e 100644 --- a/clippy_lints/src/casts/cast_possible_truncation.rs +++ b/clippy_lints/src/casts/cast_possible_truncation.rs @@ -8,6 +8,7 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::LateContext; use rustc_middle::ty::{self, FloatTy, Ty}; +use rustc_span::Span; use rustc_target::abi::IntegerType; use super::{utils, CAST_ENUM_TRUNCATION, CAST_POSSIBLE_TRUNCATION}; @@ -76,7 +77,14 @@ fn apply_reductions(cx: &LateContext<'_>, nbits: u64, expr: &Expr<'_>, signed: b } } -pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) { +pub(super) fn check( + cx: &LateContext<'_>, + expr: &Expr<'_>, + cast_expr: &Expr<'_>, + cast_from: Ty<'_>, + cast_to: Ty<'_>, + cast_to_span: Span, +) { let msg = match (cast_from.kind(), cast_to.is_integral()) { (ty::Int(_) | ty::Uint(_), true) => { let from_nbits = apply_reductions( @@ -155,9 +163,9 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, _ => return, }; - let snippet = snippet(cx, expr.span, ".."); - let name_of_cast_from = snippet.split(" as").next().unwrap_or(".."); - let suggestion = format!("{cast_to}::try_from({name_of_cast_from})"); + let name_of_cast_from = snippet(cx, cast_expr.span, ".."); + let cast_to_snip = snippet(cx, cast_to_span, ".."); + let suggestion = format!("{cast_to_snip}::try_from({name_of_cast_from})"); span_lint_and_then(cx, CAST_POSSIBLE_TRUNCATION, expr.span, &msg, |diag| { diag.help("if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ..."); diff --git a/clippy_lints/src/casts/mod.rs b/clippy_lints/src/casts/mod.rs index 64dbe6c224c7d..362f70d12d185 100644 --- a/clippy_lints/src/casts/mod.rs +++ b/clippy_lints/src/casts/mod.rs @@ -728,7 +728,7 @@ impl<'tcx> LateLintPass<'tcx> for Casts { fn_to_numeric_cast_with_truncation::check(cx, expr, cast_expr, cast_from, cast_to); if cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) { - cast_possible_truncation::check(cx, expr, cast_expr, cast_from, cast_to); + cast_possible_truncation::check(cx, expr, cast_expr, cast_from, cast_to, cast_to_hir.span); if cast_from.is_numeric() { cast_possible_wrap::check(cx, expr, cast_from, cast_to); cast_precision_loss::check(cx, expr, cast_from, cast_to); diff --git a/tests/ui/cast.rs b/tests/ui/cast.rs index e6031e9adaeb6..8b2673c2a7fdb 100644 --- a/tests/ui/cast.rs +++ b/tests/ui/cast.rs @@ -28,6 +28,7 @@ fn main() { 1i32 as u8; 1f64 as isize; 1f64 as usize; + 1f32 as u32 as u16; // Test clippy::cast_possible_wrap 1u8 as i8; 1u16 as i16; diff --git a/tests/ui/cast.stderr b/tests/ui/cast.stderr index eceb135d62ba6..4af1de9aa38d3 100644 --- a/tests/ui/cast.stderr +++ b/tests/ui/cast.stderr @@ -135,8 +135,38 @@ error: casting `f64` to `usize` may lose the sign of the value LL | 1f64 as usize; | ^^^^^^^^^^^^^ +error: casting `u32` to `u16` may truncate the value + --> $DIR/cast.rs:31:5 + | +LL | 1f32 as u32 as u16; + | ^^^^^^^^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | u16::try_from(1f32 as u32); + | ~~~~~~~~~~~~~~~~~~~~~~~~~~ + +error: casting `f32` to `u32` may truncate the value + --> $DIR/cast.rs:31:5 + | +LL | 1f32 as u32 as u16; + | ^^^^^^^^^^^ + | + = help: if this is intentional allow the lint with `#[allow(clippy::cast_precision_loss)]` ... +help: ... or use `try_from` and handle the error accordingly + | +LL | u32::try_from(1f32) as u16; + | ~~~~~~~~~~~~~~~~~~~ + +error: casting `f32` to `u32` may lose the sign of the value + --> $DIR/cast.rs:31:5 + | +LL | 1f32 as u32 as u16; + | ^^^^^^^^^^^ + error: casting `u8` to `i8` may wrap around the value - --> $DIR/cast.rs:32:5 + --> $DIR/cast.rs:33:5 | LL | 1u8 as i8; | ^^^^^^^^^ @@ -144,43 +174,43 @@ LL | 1u8 as i8; = note: `-D clippy::cast-possible-wrap` implied by `-D warnings` error: casting `u16` to `i16` may wrap around the value - --> $DIR/cast.rs:33:5 + --> $DIR/cast.rs:34:5 | LL | 1u16 as i16; | ^^^^^^^^^^^ error: casting `u32` to `i32` may wrap around the value - --> $DIR/cast.rs:34:5 + --> $DIR/cast.rs:35:5 | LL | 1u32 as i32; | ^^^^^^^^^^^ error: casting `u64` to `i64` may wrap around the value - --> $DIR/cast.rs:35:5 + --> $DIR/cast.rs:36:5 | LL | 1u64 as i64; | ^^^^^^^^^^^ error: casting `usize` to `isize` may wrap around the value - --> $DIR/cast.rs:36:5 + --> $DIR/cast.rs:37:5 | LL | 1usize as isize; | ^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> $DIR/cast.rs:39:5 + --> $DIR/cast.rs:40:5 | LL | -1i32 as u32; | ^^^^^^^^^^^^ error: casting `isize` to `usize` may lose the sign of the value - --> $DIR/cast.rs:41:5 + --> $DIR/cast.rs:42:5 | LL | -1isize as usize; | ^^^^^^^^^^^^^^^^ error: casting `i64` to `i8` may truncate the value - --> $DIR/cast.rs:108:5 + --> $DIR/cast.rs:109:5 | LL | (-99999999999i64).min(1) as i8; // should be linted because signed | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -192,7 +222,7 @@ LL | i8::try_from((-99999999999i64).min(1)); // should be linted because sig | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: casting `u64` to `u8` may truncate the value - --> $DIR/cast.rs:120:5 + --> $DIR/cast.rs:121:5 | LL | 999999u64.clamp(0, 256) as u8; // should still be linted | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -204,7 +234,7 @@ LL | u8::try_from(999999u64.clamp(0, 256)); // should still be linted | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: casting `main::E2` to `u8` may truncate the value - --> $DIR/cast.rs:141:21 + --> $DIR/cast.rs:142:21 | LL | let _ = self as u8; | ^^^^^^^^^^ @@ -216,7 +246,7 @@ LL | let _ = u8::try_from(self); | ~~~~~~~~~~~~~~~~~~ error: casting `main::E2::B` to `u8` will truncate the value - --> $DIR/cast.rs:142:21 + --> $DIR/cast.rs:143:21 | LL | let _ = Self::B as u8; | ^^^^^^^^^^^^^ @@ -224,7 +254,7 @@ LL | let _ = Self::B as u8; = note: `-D clippy::cast-enum-truncation` implied by `-D warnings` error: casting `main::E5` to `i8` may truncate the value - --> $DIR/cast.rs:178:21 + --> $DIR/cast.rs:179:21 | LL | let _ = self as i8; | ^^^^^^^^^^ @@ -236,13 +266,13 @@ LL | let _ = i8::try_from(self); | ~~~~~~~~~~~~~~~~~~ error: casting `main::E5::A` to `i8` will truncate the value - --> $DIR/cast.rs:179:21 + --> $DIR/cast.rs:180:21 | LL | let _ = Self::A as i8; | ^^^^^^^^^^^^^ error: casting `main::E6` to `i16` may truncate the value - --> $DIR/cast.rs:193:21 + --> $DIR/cast.rs:194:21 | LL | let _ = self as i16; | ^^^^^^^^^^^ @@ -254,7 +284,7 @@ LL | let _ = i16::try_from(self); | ~~~~~~~~~~~~~~~~~~~ error: casting `main::E7` to `usize` may truncate the value on targets with 32-bit wide pointers - --> $DIR/cast.rs:208:21 + --> $DIR/cast.rs:209:21 | LL | let _ = self as usize; | ^^^^^^^^^^^^^ @@ -266,7 +296,7 @@ LL | let _ = usize::try_from(self); | ~~~~~~~~~~~~~~~~~~~~~ error: casting `main::E10` to `u16` may truncate the value - --> $DIR/cast.rs:249:21 + --> $DIR/cast.rs:250:21 | LL | let _ = self as u16; | ^^^^^^^^^^^ @@ -278,7 +308,7 @@ LL | let _ = u16::try_from(self); | ~~~~~~~~~~~~~~~~~~~ error: casting `u32` to `u8` may truncate the value - --> $DIR/cast.rs:257:13 + --> $DIR/cast.rs:258:13 | LL | let c = (q >> 16) as u8; | ^^^^^^^^^^^^^^^ @@ -290,7 +320,7 @@ LL | let c = u8::try_from((q >> 16)); | ~~~~~~~~~~~~~~~~~~~~~~~ error: casting `u32` to `u8` may truncate the value - --> $DIR/cast.rs:260:13 + --> $DIR/cast.rs:261:13 | LL | let c = (q / 1000) as u8; | ^^^^^^^^^^^^^^^^ @@ -301,5 +331,5 @@ help: ... or use `try_from` and handle the error accordingly LL | let c = u8::try_from((q / 1000)); | ~~~~~~~~~~~~~~~~~~~~~~~~ -error: aborting due to 33 previous errors +error: aborting due to 36 previous errors From cfe8849a622c6308eaee333e8adba6c5bc3f457e Mon Sep 17 00:00:00 2001 From: Tyler Weaver Date: Thu, 12 Jan 2023 06:43:17 -0700 Subject: [PATCH 130/500] Document extending list type configs Signed-off-by: Tyler Weaver --- README.md | 9 +++++++++ book/src/configuration.md | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/README.md b/README.md index 81254ba8b8b8f..f7e03ca4cd8c4 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,15 @@ cognitive-complexity-threshold = 30 See the [list of configurable lints](https://rust-lang.github.io/rust-clippy/master/index.html#Configuration), the lint descriptions contain the names and meanings of these configuration variables. +For configurations that are a list type with default values such as +[disallowed-names](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_names), +you can use the unique value `".."` to extend the default values instead of replacing them. + +```toml +# default of disallowed-names is ["foo", "baz", "quux"] +disallowed-names = ["bar", ".."] # -> ["bar", "foo", "baz", "quux"] +``` + > **Note** > > `clippy.toml` or `.clippy.toml` cannot be used to allow/deny lints. diff --git a/book/src/configuration.md b/book/src/configuration.md index 430ff8b739ae8..bbe1081ccad9a 100644 --- a/book/src/configuration.md +++ b/book/src/configuration.md @@ -14,6 +14,15 @@ cognitive-complexity-threshold = 30 See the [list of configurable lints](https://rust-lang.github.io/rust-clippy/master/index.html#Configuration), the lint descriptions contain the names and meanings of these configuration variables. +For configurations that are a list type with default values such as +[disallowed-names](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_names), +you can use the unique value `".."` to extend the default values instead of replacing them. + +```toml +# default of disallowed-names is ["foo", "baz", "quux"] +disallowed-names = ["bar", ".."] # -> ["bar", "foo", "baz", "quux"] +``` + To deactivate the "for further information visit *lint-link*" message you can define the `CLIPPY_DISABLE_DOCS_LINKS` environment variable. From 0c48b5a223a0cb8ef431eda4e57a172f678ec12d Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 5 Dec 2022 17:52:17 +0000 Subject: [PATCH 131/500] Feed the `features_query` instead of grabbing it from the session lazily --- clippy_lints/src/attrs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/attrs.rs b/clippy_lints/src/attrs.rs index 0710ac0bb0a72..751c262673b1c 100644 --- a/clippy_lints/src/attrs.rs +++ b/clippy_lints/src/attrs.rs @@ -472,7 +472,7 @@ fn check_clippy_lint_names(cx: &LateContext<'_>, name: Symbol, items: &[NestedMe fn check_lint_reason(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem], attr: &'_ Attribute) { // Check for the feature - if !cx.tcx.sess.features_untracked().lint_reasons { + if !cx.tcx.features().lint_reasons { return; } From 6155b9a772c944702f931ce5940d6c19cb7ced07 Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Thu, 12 Jan 2023 18:47:05 +0000 Subject: [PATCH 132/500] Avoid __cxa_thread_atexit_impl on Emscripten - Fixes https://github.com/rust-lang/rust/issues/91628. - Fixes https://github.com/emscripten-core/emscripten/issues/15722. See discussion in both issues. The TL;DR is that weak linkage causes LLVM to produce broken Wasm, presumably due to pointer mismatch. The code is casting a void pointer to a function pointer with specific signature, but Wasm is very strict about function pointer compatibility, so the resulting code is invalid. Ideally LLVM should catch this earlier in the process rather than emit invalid Wasm, but it currently doesn't and this is an easy and valid fix, given that Emcripten doesn't have `__cxa_thread_atexit_impl` these days anyway. Unfortunately, I can't add a regression test as even after looking into this issue for a long time, I couldn't reproduce it with any minimal Rust example, only with extracted LLVM IR or on a large project involving Rust + C++. r? @alexcrichton --- library/std/src/sys/unix/thread_local_dtor.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/library/std/src/sys/unix/thread_local_dtor.rs b/library/std/src/sys/unix/thread_local_dtor.rs index d7fd2130f7cce..aa4df00063208 100644 --- a/library/std/src/sys/unix/thread_local_dtor.rs +++ b/library/std/src/sys/unix/thread_local_dtor.rs @@ -11,13 +11,7 @@ // Note, however, that we run on lots older linuxes, as well as cross // compiling from a newer linux to an older linux, so we also have a // fallback implementation to use as well. -#[cfg(any( - target_os = "linux", - target_os = "fuchsia", - target_os = "redox", - target_os = "emscripten" -))] -#[cfg_attr(target_family = "wasm", allow(unused))] // might remain unused depending on target details (e.g. wasm32-unknown-emscripten) +#[cfg(any(target_os = "linux", target_os = "fuchsia", target_os = "redox"))] pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { use crate::mem; use crate::sys_common::thread_local_dtor::register_dtor_fallback; @@ -94,7 +88,7 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { } } -#[cfg(any(target_os = "vxworks", target_os = "horizon"))] +#[cfg(any(target_os = "vxworks", target_os = "horizon", target_os = "emscripten"))] pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { use crate::sys_common::thread_local_dtor::register_dtor_fallback; register_dtor_fallback(t, dtor); From d21616737b56681fdf19cdf9a9f8db16d0e87961 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Thu, 12 Jan 2023 19:48:13 +0100 Subject: [PATCH 133/500] Merge commit '7f27e2e74ef957baa382dc05cf08df6368165c74' into clippyup --- .github/driver.sh | 7 + CHANGELOG.md | 1 + book/src/installation.md | 2 +- clippy_dev/src/lib.rs | 3 + clippy_lints/src/box_default.rs | 4 +- clippy_lints/src/copies.rs | 6 +- clippy_lints/src/dbg_macro.rs | 10 +- clippy_lints/src/declared_lints.rs | 2 +- clippy_lints/src/default.rs | 7 +- clippy_lints/src/dereference.rs | 8 +- clippy_lints/src/derivable_impls.rs | 161 ++++-- clippy_lints/src/derive.rs | 31 +- clippy_lints/src/drop_forget_ref.rs | 2 +- .../src/empty_structs_with_brackets.rs | 2 +- clippy_lints/src/lib.rs | 2 +- clippy_lints/src/loops/needless_range_loop.rs | 4 +- clippy_lints/src/loops/single_element_loop.rs | 2 + ...se_sensitive_file_extension_comparisons.rs | 46 +- clippy_lints/src/methods/clone_on_copy.rs | 14 +- clippy_lints/src/methods/filter_map.rs | 174 +++---- clippy_lints/src/methods/iter_kv_map.rs | 22 +- .../src/methods/suspicious_to_owned.rs | 6 +- clippy_lints/src/mutex_atomic.rs | 10 +- .../src/operators/arithmetic_side_effects.rs | 11 +- clippy_lints/src/ranges.rs | 2 +- clippy_lints/src/redundant_clone.rs | 4 +- clippy_lints/src/renamed_lints.rs | 1 + clippy_lints/src/returns.rs | 33 +- clippy_lints/src/types/mod.rs | 2 +- clippy_lints/src/unused_self.rs | 21 +- .../internal_lints/metadata_collector.rs | 2 +- clippy_utils/src/lib.rs | 37 +- clippy_utils/src/mir/possible_borrower.rs | 270 ++++------ clippy_utils/src/msrvs.rs | 4 +- clippy_utils/src/paths.rs | 1 - clippy_utils/src/visitors.rs | 11 + rust-toolchain | 2 +- src/driver.rs | 5 +- tests/integration.rs | 9 + .../arithmetic_side_effects_allowed.rs | 2 +- tests/ui-toml/dbg_macro/dbg_macro.stderr | 36 +- tests/ui/arithmetic_side_effects.rs | 225 ++++++-- tests/ui/arithmetic_side_effects.stderr | 480 ++++++++++++++---- tests/ui/box_default.fixed | 18 +- tests/ui/box_default.rs | 10 + tests/ui/box_default.stderr | 16 +- ...sensitive_file_extension_comparisons.fixed | 67 +++ ...se_sensitive_file_extension_comparisons.rs | 13 +- ...ensitive_file_extension_comparisons.stderr | 66 ++- tests/ui/clone_on_copy.stderr | 2 +- tests/ui/dbg_macro.stderr | 52 +- tests/ui/default_trait_access.fixed | 8 +- tests/ui/default_trait_access.stderr | 16 +- tests/ui/derivable_impls.fixed | 21 + tests/ui/derivable_impls.rs | 23 + tests/ui/derivable_impls.stderr | 23 +- tests/ui/derive.rs | 11 + tests/ui/derive_hash_xor_eq.stderr | 59 --- ...r_eq.rs => derived_hash_with_manual_eq.rs} | 21 +- tests/ui/derived_hash_with_manual_eq.stderr | 29 ++ tests/ui/drop_ref.rs | 23 + tests/ui/drop_ref.stderr | 38 +- tests/ui/field_reassign_with_default.rs | 21 + tests/ui/iter_kv_map.fixed | 35 +- tests/ui/iter_kv_map.rs | 39 +- tests/ui/iter_kv_map.stderr | 114 ++++- tests/ui/needless_borrow.fixed | 13 +- tests/ui/needless_borrow.rs | 13 +- tests/ui/needless_borrow.stderr | 8 +- tests/ui/needless_return.fixed | 10 + tests/ui/needless_return.rs | 10 + tests/ui/needless_return.stderr | 18 +- tests/ui/redundant_clone.fixed | 6 - tests/ui/redundant_clone.rs | 6 - tests/ui/redundant_clone.stderr | 14 +- tests/ui/rename.fixed | 2 + tests/ui/rename.rs | 2 + tests/ui/rename.stderr | 90 ++-- tests/ui/single_element_loop.fixed | 27 + tests/ui/single_element_loop.rs | 26 + tests/ui/single_element_loop.stderr | 29 +- tests/ui/suspicious_to_owned.stderr | 8 +- tests/ui/unnecessary_clone.stderr | 10 +- tests/ui/unused_self.rs | 10 + tests/ui/unused_self.stderr | 18 +- 85 files changed, 1879 insertions(+), 850 deletions(-) create mode 100644 tests/ui/case_sensitive_file_extension_comparisons.fixed delete mode 100644 tests/ui/derive_hash_xor_eq.stderr rename tests/ui/{derive_hash_xor_eq.rs => derived_hash_with_manual_eq.rs} (62%) create mode 100644 tests/ui/derived_hash_with_manual_eq.stderr diff --git a/.github/driver.sh b/.github/driver.sh index 6ff189fc85926..798782340ee7d 100644 --- a/.github/driver.sh +++ b/.github/driver.sh @@ -17,6 +17,13 @@ test "$sysroot" = $desired_sysroot sysroot=$(SYSROOT=$desired_sysroot ./target/debug/clippy-driver --print sysroot) test "$sysroot" = $desired_sysroot +# Check that the --sysroot argument is only passed once (SYSROOT is ignored) +( + cd rustc_tools_util + touch src/lib.rs + SYSROOT=/tmp RUSTFLAGS="--sysroot=$(rustc --print sysroot)" ../target/debug/cargo-clippy clippy --verbose +) + # Make sure this isn't set - clippy-driver should cope without it unset CARGO_MANIFEST_DIR diff --git a/CHANGELOG.md b/CHANGELOG.md index 02f3188f8be08..8e31e8f0d9815 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4137,6 +4137,7 @@ Released 2018-09-13 [`derive_hash_xor_eq`]: https://rust-lang.github.io/rust-clippy/master/index.html#derive_hash_xor_eq [`derive_ord_xor_partial_ord`]: https://rust-lang.github.io/rust-clippy/master/index.html#derive_ord_xor_partial_ord [`derive_partial_eq_without_eq`]: https://rust-lang.github.io/rust-clippy/master/index.html#derive_partial_eq_without_eq +[`derived_hash_with_manual_eq`]: https://rust-lang.github.io/rust-clippy/master/index.html#derived_hash_with_manual_eq [`disallowed_macros`]: https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_macros [`disallowed_method`]: https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_method [`disallowed_methods`]: https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_methods diff --git a/book/src/installation.md b/book/src/installation.md index b2a28d0be622f..cce888b17d4d3 100644 --- a/book/src/installation.md +++ b/book/src/installation.md @@ -1,6 +1,6 @@ # Installation -If you're using `rustup` to install and manage you're Rust toolchains, Clippy is +If you're using `rustup` to install and manage your Rust toolchains, Clippy is usually **already installed**. In that case you can skip this chapter and go to the [Usage] chapter. diff --git a/clippy_dev/src/lib.rs b/clippy_dev/src/lib.rs index 80bb83af43b19..e70488165b99b 100644 --- a/clippy_dev/src/lib.rs +++ b/clippy_dev/src/lib.rs @@ -5,6 +5,9 @@ // warn on lints, that are included in `rust-lang/rust`s bootstrap #![warn(rust_2018_idioms, unused_lifetimes)] +// The `rustc_driver` crate seems to be required in order to use the `rust_lexer` crate. +#[allow(unused_extern_crates)] +extern crate rustc_driver; extern crate rustc_lexer; use std::path::PathBuf; diff --git a/clippy_lints/src/box_default.rs b/clippy_lints/src/box_default.rs index 91900542af833..9d98a6bab7107 100644 --- a/clippy_lints/src/box_default.rs +++ b/clippy_lints/src/box_default.rs @@ -8,7 +8,7 @@ use rustc_hir::{ Block, Expr, ExprKind, Local, Node, QPath, TyKind, }; use rustc_lint::{LateContext, LateLintPass, LintContext}; -use rustc_middle::lint::in_external_macro; +use rustc_middle::{lint::in_external_macro, ty::print::with_forced_trimmed_paths}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::sym; @@ -59,7 +59,7 @@ impl LateLintPass<'_> for BoxDefault { if is_plain_default(arg_path) || given_type(cx, expr) { "Box::default()".into() } else { - format!("Box::<{arg_ty}>::default()") + with_forced_trimmed_paths!(format!("Box::<{arg_ty}>::default()")) }, Applicability::MachineApplicable ); diff --git a/clippy_lints/src/copies.rs b/clippy_lints/src/copies.rs index 0e3d9317590f3..f10c35cde52a1 100644 --- a/clippy_lints/src/copies.rs +++ b/clippy_lints/src/copies.rs @@ -525,7 +525,11 @@ fn check_for_warn_of_moved_symbol(cx: &LateContext<'_>, symbols: &[(HirId, Symbo .iter() .filter(|&&(_, name)| !name.as_str().starts_with('_')) .any(|&(_, name)| { - let mut walker = ContainsName { name, result: false }; + let mut walker = ContainsName { + name, + result: false, + cx, + }; // Scan block block diff --git a/clippy_lints/src/dbg_macro.rs b/clippy_lints/src/dbg_macro.rs index fe9f4f9ae3cb9..799e71e847a9f 100644 --- a/clippy_lints/src/dbg_macro.rs +++ b/clippy_lints/src/dbg_macro.rs @@ -10,11 +10,11 @@ use rustc_span::sym; declare_clippy_lint! { /// ### What it does - /// Checks for usage of dbg!() macro. + /// Checks for usage of the [`dbg!`](https://doc.rust-lang.org/std/macro.dbg.html) macro. /// /// ### Why is this bad? - /// `dbg!` macro is intended as a debugging tool. It - /// should not be in version control. + /// The `dbg!` macro is intended as a debugging tool. It should not be present in released + /// software or committed to a version control system. /// /// ### Example /// ```rust,ignore @@ -91,8 +91,8 @@ impl LateLintPass<'_> for DbgMacro { cx, DBG_MACRO, macro_call.span, - "`dbg!` macro is intended as a debugging tool", - "ensure to avoid having uses of it in version control", + "the `dbg!` macro is intended as a debugging tool", + "remove the invocation before committing it to a version control system", suggestion, applicability, ); diff --git a/clippy_lints/src/declared_lints.rs b/clippy_lints/src/declared_lints.rs index 2982460c9cfa4..91ca73633f062 100644 --- a/clippy_lints/src/declared_lints.rs +++ b/clippy_lints/src/declared_lints.rs @@ -111,7 +111,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[ crate::dereference::NEEDLESS_BORROW_INFO, crate::dereference::REF_BINDING_TO_REFERENCE_INFO, crate::derivable_impls::DERIVABLE_IMPLS_INFO, - crate::derive::DERIVE_HASH_XOR_EQ_INFO, + crate::derive::DERIVED_HASH_WITH_MANUAL_EQ_INFO, crate::derive::DERIVE_ORD_XOR_PARTIAL_ORD_INFO, crate::derive::DERIVE_PARTIAL_EQ_WITHOUT_EQ_INFO, crate::derive::EXPL_IMPL_CLONE_ON_COPY_INFO, diff --git a/clippy_lints/src/default.rs b/clippy_lints/src/default.rs index 7f937de1dd312..a04693f4637ab 100644 --- a/clippy_lints/src/default.rs +++ b/clippy_lints/src/default.rs @@ -11,6 +11,7 @@ use rustc_hir::def::Res; use rustc_hir::{Block, Expr, ExprKind, PatKind, QPath, Stmt, StmtKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; +use rustc_middle::ty::print::with_forced_trimmed_paths; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::symbol::{Ident, Symbol}; use rustc_span::Span; @@ -98,9 +99,7 @@ impl<'tcx> LateLintPass<'tcx> for Default { if let ty::Adt(def, ..) = expr_ty.kind(); if !is_from_proc_macro(cx, expr); then { - // TODO: Work out a way to put "whatever the imported way of referencing - // this type in this file" rather than a fully-qualified type. - let replacement = format!("{}::default()", cx.tcx.def_path_str(def.did())); + let replacement = with_forced_trimmed_paths!(format!("{}::default()", cx.tcx.def_path_str(def.did()))); span_lint_and_sugg( cx, DEFAULT_TRAIT_ACCESS, @@ -170,7 +169,7 @@ impl<'tcx> LateLintPass<'tcx> for Default { // find out if and which field was set by this `consecutive_statement` if let Some((field_ident, assign_rhs)) = field_reassigned_by_stmt(consecutive_statement, binding_name) { // interrupt and cancel lint if assign_rhs references the original binding - if contains_name(binding_name, assign_rhs) { + if contains_name(binding_name, assign_rhs, cx) { cancel_lint = true; break; } diff --git a/clippy_lints/src/dereference.rs b/clippy_lints/src/dereference.rs index f327c9a71b3c1..05f2b92c03709 100644 --- a/clippy_lints/src/dereference.rs +++ b/clippy_lints/src/dereference.rs @@ -1282,10 +1282,10 @@ fn referent_used_exactly_once<'tcx>( possible_borrowers.push((body_owner_local_def_id, PossibleBorrowerMap::new(cx, mir))); } let possible_borrower = &mut possible_borrowers.last_mut().unwrap().1; - // If `place.local` were not included here, the `copyable_iterator::warn` test would fail. The - // reason is that `PossibleBorrowerVisitor::visit_terminator` considers `place.local` a possible - // borrower of itself. See the comment in that method for an explanation as to why. - possible_borrower.at_most_borrowers(cx, &[local, place.local], place.local, location) + // If `only_borrowers` were used here, the `copyable_iterator::warn` test would fail. The reason is + // that `PossibleBorrowerVisitor::visit_terminator` considers `place.local` a possible borrower of + // itself. See the comment in that method for an explanation as to why. + possible_borrower.bounded_borrowers(&[local], &[local, place.local], place.local, location) && used_exactly_once(mir, place.local).unwrap_or(false) } else { false diff --git a/clippy_lints/src/derivable_impls.rs b/clippy_lints/src/derivable_impls.rs index ae8f6b794499f..bc18e2e5ed5fd 100644 --- a/clippy_lints/src/derivable_impls.rs +++ b/clippy_lints/src/derivable_impls.rs @@ -1,12 +1,15 @@ use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::msrvs::{self, Msrv}; +use clippy_utils::source::indent_of; use clippy_utils::{is_default_equivalent, peel_blocks}; use rustc_errors::Applicability; use rustc_hir::{ - def::{DefKind, Res}, - Body, Expr, ExprKind, GenericArg, Impl, ImplItemKind, Item, ItemKind, Node, PathSegment, QPath, TyKind, + def::{CtorKind, CtorOf, DefKind, Res}, + Body, Expr, ExprKind, GenericArg, Impl, ImplItemKind, Item, ItemKind, Node, PathSegment, QPath, Ty, TyKind, }; use rustc_lint::{LateContext, LateLintPass}; -use rustc_session::{declare_lint_pass, declare_tool_lint}; +use rustc_middle::ty::{AdtDef, DefIdTree}; +use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::sym; declare_clippy_lint! { @@ -51,7 +54,18 @@ declare_clippy_lint! { "manual implementation of the `Default` trait which is equal to a derive" } -declare_lint_pass!(DerivableImpls => [DERIVABLE_IMPLS]); +pub struct DerivableImpls { + msrv: Msrv, +} + +impl DerivableImpls { + #[must_use] + pub fn new(msrv: Msrv) -> Self { + DerivableImpls { msrv } + } +} + +impl_lint_pass!(DerivableImpls => [DERIVABLE_IMPLS]); fn is_path_self(e: &Expr<'_>) -> bool { if let ExprKind::Path(QPath::Resolved(_, p)) = e.kind { @@ -61,6 +75,98 @@ fn is_path_self(e: &Expr<'_>) -> bool { } } +fn check_struct<'tcx>( + cx: &LateContext<'tcx>, + item: &'tcx Item<'_>, + self_ty: &Ty<'_>, + func_expr: &Expr<'_>, + adt_def: AdtDef<'_>, +) { + if let TyKind::Path(QPath::Resolved(_, p)) = self_ty.kind { + if let Some(PathSegment { args: Some(a), .. }) = p.segments.last() { + for arg in a.args { + if !matches!(arg, GenericArg::Lifetime(_)) { + return; + } + } + } + } + let should_emit = match peel_blocks(func_expr).kind { + ExprKind::Tup(fields) => fields.iter().all(|e| is_default_equivalent(cx, e)), + ExprKind::Call(callee, args) if is_path_self(callee) => args.iter().all(|e| is_default_equivalent(cx, e)), + ExprKind::Struct(_, fields, _) => fields.iter().all(|ef| is_default_equivalent(cx, ef.expr)), + _ => false, + }; + + if should_emit { + let struct_span = cx.tcx.def_span(adt_def.did()); + span_lint_and_then(cx, DERIVABLE_IMPLS, item.span, "this `impl` can be derived", |diag| { + diag.span_suggestion_hidden( + item.span, + "remove the manual implementation...", + String::new(), + Applicability::MachineApplicable, + ); + diag.span_suggestion( + struct_span.shrink_to_lo(), + "...and instead derive it", + "#[derive(Default)]\n".to_string(), + Applicability::MachineApplicable, + ); + }); + } +} + +fn check_enum<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>, func_expr: &Expr<'_>, adt_def: AdtDef<'_>) { + if_chain! { + if let ExprKind::Path(QPath::Resolved(None, p)) = &peel_blocks(func_expr).kind; + if let Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Const), id) = p.res; + if let variant_id = cx.tcx.parent(id); + if let Some(variant_def) = adt_def.variants().iter().find(|v| v.def_id == variant_id); + if variant_def.fields.is_empty(); + if !variant_def.is_field_list_non_exhaustive(); + + then { + let enum_span = cx.tcx.def_span(adt_def.did()); + let indent_enum = indent_of(cx, enum_span).unwrap_or(0); + let variant_span = cx.tcx.def_span(variant_def.def_id); + let indent_variant = indent_of(cx, variant_span).unwrap_or(0); + span_lint_and_then( + cx, + DERIVABLE_IMPLS, + item.span, + "this `impl` can be derived", + |diag| { + diag.span_suggestion_hidden( + item.span, + "remove the manual implementation...", + String::new(), + Applicability::MachineApplicable + ); + diag.span_suggestion( + enum_span.shrink_to_lo(), + "...and instead derive it...", + format!( + "#[derive(Default)]\n{indent}", + indent = " ".repeat(indent_enum), + ), + Applicability::MachineApplicable + ); + diag.span_suggestion( + variant_span.shrink_to_lo(), + "...and mark the default variant", + format!( + "#[default]\n{indent}", + indent = " ".repeat(indent_variant), + ), + Applicability::MachineApplicable + ); + } + ); + } + } +} + impl<'tcx> LateLintPass<'tcx> for DerivableImpls { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { if_chain! { @@ -83,49 +189,16 @@ impl<'tcx> LateLintPass<'tcx> for DerivableImpls { if !attrs.iter().any(|attr| attr.doc_str().is_some()); if let child_attrs = cx.tcx.hir().attrs(impl_item_hir); if !child_attrs.iter().any(|attr| attr.doc_str().is_some()); - if adt_def.is_struct(); - then { - if let TyKind::Path(QPath::Resolved(_, p)) = self_ty.kind { - if let Some(PathSegment { args: Some(a), .. }) = p.segments.last() { - for arg in a.args { - if !matches!(arg, GenericArg::Lifetime(_)) { - return; - } - } - } - } - let should_emit = match peel_blocks(func_expr).kind { - ExprKind::Tup(fields) => fields.iter().all(|e| is_default_equivalent(cx, e)), - ExprKind::Call(callee, args) - if is_path_self(callee) => args.iter().all(|e| is_default_equivalent(cx, e)), - ExprKind::Struct(_, fields, _) => fields.iter().all(|ef| is_default_equivalent(cx, ef.expr)), - _ => false, - }; - if should_emit { - let struct_span = cx.tcx.def_span(adt_def.did()); - span_lint_and_then( - cx, - DERIVABLE_IMPLS, - item.span, - "this `impl` can be derived", - |diag| { - diag.span_suggestion_hidden( - item.span, - "remove the manual implementation...", - String::new(), - Applicability::MachineApplicable - ); - diag.span_suggestion( - struct_span.shrink_to_lo(), - "...and instead derive it", - "#[derive(Default)]\n".to_string(), - Applicability::MachineApplicable - ); - } - ); + then { + if adt_def.is_struct() { + check_struct(cx, item, self_ty, func_expr, adt_def); + } else if adt_def.is_enum() && self.msrv.meets(msrvs::DEFAULT_ENUM_ATTRIBUTE) { + check_enum(cx, item, func_expr, adt_def); } } } } + + extract_msrv_attr!(LateContext); } diff --git a/clippy_lints/src/derive.rs b/clippy_lints/src/derive.rs index cf3483d4c00b1..f4b15e0916dbf 100644 --- a/clippy_lints/src/derive.rs +++ b/clippy_lints/src/derive.rs @@ -14,8 +14,8 @@ use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::nested_filter; use rustc_middle::traits::Reveal; use rustc_middle::ty::{ - self, Binder, BoundConstness, Clause, GenericParamDefKind, ImplPolarity, ParamEnv, PredicateKind, TraitPredicate, - Ty, TyCtxt, + self, Binder, BoundConstness, Clause, GenericArgKind, GenericParamDefKind, ImplPolarity, ParamEnv, PredicateKind, + TraitPredicate, Ty, TyCtxt, }; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Span; @@ -46,7 +46,7 @@ declare_clippy_lint! { /// } /// ``` #[clippy::version = "pre 1.29.0"] - pub DERIVE_HASH_XOR_EQ, + pub DERIVED_HASH_WITH_MANUAL_EQ, correctness, "deriving `Hash` but implementing `PartialEq` explicitly" } @@ -197,7 +197,7 @@ declare_clippy_lint! { declare_lint_pass!(Derive => [ EXPL_IMPL_CLONE_ON_COPY, - DERIVE_HASH_XOR_EQ, + DERIVED_HASH_WITH_MANUAL_EQ, DERIVE_ORD_XOR_PARTIAL_ORD, UNSAFE_DERIVE_DESERIALIZE, DERIVE_PARTIAL_EQ_WITHOUT_EQ @@ -226,7 +226,7 @@ impl<'tcx> LateLintPass<'tcx> for Derive { } } -/// Implementation of the `DERIVE_HASH_XOR_EQ` lint. +/// Implementation of the `DERIVED_HASH_WITH_MANUAL_EQ` lint. fn check_hash_peq<'tcx>( cx: &LateContext<'tcx>, span: Span, @@ -243,7 +243,7 @@ fn check_hash_peq<'tcx>( cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| { let peq_is_automatically_derived = cx.tcx.has_attr(impl_id, sym::automatically_derived); - if peq_is_automatically_derived == hash_is_automatically_derived { + if !hash_is_automatically_derived || peq_is_automatically_derived { return; } @@ -252,17 +252,11 @@ fn check_hash_peq<'tcx>( // Only care about `impl PartialEq for Foo` // For `impl PartialEq for A, input_types is [A, B] if trait_ref.substs.type_at(1) == ty { - let mess = if peq_is_automatically_derived { - "you are implementing `Hash` explicitly but have derived `PartialEq`" - } else { - "you are deriving `Hash` but have implemented `PartialEq` explicitly" - }; - span_lint_and_then( cx, - DERIVE_HASH_XOR_EQ, + DERIVED_HASH_WITH_MANUAL_EQ, span, - mess, + "you are deriving `Hash` but have implemented `PartialEq` explicitly", |diag| { if let Some(local_def_id) = impl_id.as_local() { let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id); @@ -366,6 +360,15 @@ fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &h if ty_subs.types().any(|ty| !implements_trait(cx, ty, clone_id, &[])) { return; } + // `#[repr(packed)]` structs with type/const parameters can't derive `Clone`. + // https://github.com/rust-lang/rust-clippy/issues/10188 + if ty_adt.repr().packed() + && ty_subs + .iter() + .any(|arg| matches!(arg.unpack(), GenericArgKind::Type(_) | GenericArgKind::Const(_))) + { + return; + } span_lint_and_note( cx, diff --git a/clippy_lints/src/drop_forget_ref.rs b/clippy_lints/src/drop_forget_ref.rs index 4721a7b370567..11e1bcdf12d1e 100644 --- a/clippy_lints/src/drop_forget_ref.rs +++ b/clippy_lints/src/drop_forget_ref.rs @@ -206,7 +206,7 @@ impl<'tcx> LateLintPass<'tcx> for DropForgetRef { let is_copy = is_copy(cx, arg_ty); let drop_is_single_call_in_arm = is_single_call_in_arm(cx, arg, expr); let (lint, msg) = match fn_name { - sym::mem_drop if arg_ty.is_ref() => (DROP_REF, DROP_REF_SUMMARY), + sym::mem_drop if arg_ty.is_ref() && !drop_is_single_call_in_arm => (DROP_REF, DROP_REF_SUMMARY), sym::mem_forget if arg_ty.is_ref() => (FORGET_REF, FORGET_REF_SUMMARY), sym::mem_drop if is_copy && !drop_is_single_call_in_arm => (DROP_COPY, DROP_COPY_SUMMARY), sym::mem_forget if is_copy => (FORGET_COPY, FORGET_COPY_SUMMARY), diff --git a/clippy_lints/src/empty_structs_with_brackets.rs b/clippy_lints/src/empty_structs_with_brackets.rs index 08bf80a422900..c3a020433de85 100644 --- a/clippy_lints/src/empty_structs_with_brackets.rs +++ b/clippy_lints/src/empty_structs_with_brackets.rs @@ -45,7 +45,7 @@ impl EarlyLintPass for EmptyStructsWithBrackets { span_after_ident, "remove the brackets", ";", - Applicability::MachineApplicable); + Applicability::Unspecified); }, ); } diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index dcd8ca81ae872..d8e2ae02c5a65 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -639,7 +639,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_late_pass(|_| Box::new(panic_unimplemented::PanicUnimplemented)); store.register_late_pass(|_| Box::new(strings::StringLitAsBytes)); store.register_late_pass(|_| Box::new(derive::Derive)); - store.register_late_pass(|_| Box::new(derivable_impls::DerivableImpls)); + store.register_late_pass(move |_| Box::new(derivable_impls::DerivableImpls::new(msrv()))); store.register_late_pass(|_| Box::new(drop_forget_ref::DropForgetRef)); store.register_late_pass(|_| Box::new(empty_enum::EmptyEnum)); store.register_late_pass(|_| Box::new(invalid_upcast_comparisons::InvalidUpcastComparisons)); diff --git a/clippy_lints/src/loops/needless_range_loop.rs b/clippy_lints/src/loops/needless_range_loop.rs index 27ba27202bf7e..3bca93d80aa7f 100644 --- a/clippy_lints/src/loops/needless_range_loop.rs +++ b/clippy_lints/src/loops/needless_range_loop.rs @@ -81,7 +81,7 @@ pub(super) fn check<'tcx>( let skip = if starts_at_zero { String::new() - } else if visitor.indexed_mut.contains(&indexed) && contains_name(indexed, start) { + } else if visitor.indexed_mut.contains(&indexed) && contains_name(indexed, start, cx) { return; } else { format!(".skip({})", snippet(cx, start.span, "..")) @@ -109,7 +109,7 @@ pub(super) fn check<'tcx>( if is_len_call(end, indexed) || is_end_eq_array_len(cx, end, limits, indexed_ty) { String::new() - } else if visitor.indexed_mut.contains(&indexed) && contains_name(indexed, take_expr) { + } else if visitor.indexed_mut.contains(&indexed) && contains_name(indexed, take_expr, cx) { return; } else { match limits { diff --git a/clippy_lints/src/loops/single_element_loop.rs b/clippy_lints/src/loops/single_element_loop.rs index f4b47808dfaa3..744fd61bd135c 100644 --- a/clippy_lints/src/loops/single_element_loop.rs +++ b/clippy_lints/src/loops/single_element_loop.rs @@ -1,6 +1,7 @@ use super::SINGLE_ELEMENT_LOOP; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::{indent_of, snippet_with_applicability}; +use clippy_utils::visitors::contains_break_or_continue; use if_chain::if_chain; use rustc_ast::util::parser::PREC_PREFIX; use rustc_ast::Mutability; @@ -67,6 +68,7 @@ pub(super) fn check<'tcx>( if_chain! { if let ExprKind::Block(block, _) = body.kind; if !block.stmts.is_empty(); + if !contains_break_or_continue(body); then { let mut applicability = Applicability::MachineApplicable; let pat_snip = snippet_with_applicability(cx, pat.span, "..", &mut applicability); diff --git a/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs b/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs index d226c0bba6593..0b3bf22743fae 100644 --- a/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs +++ b/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs @@ -1,7 +1,10 @@ -use clippy_utils::diagnostics::span_lint_and_help; +use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::source::snippet_opt; +use clippy_utils::source::{indent_of, reindent_multiline}; use clippy_utils::ty::is_type_lang_item; use if_chain::if_chain; use rustc_ast::ast::LitKind; +use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, LangItem}; use rustc_lint::LateContext; use rustc_span::{source_map::Spanned, Span}; @@ -15,6 +18,15 @@ pub(super) fn check<'tcx>( recv: &'tcx Expr<'_>, arg: &'tcx Expr<'_>, ) { + if let ExprKind::MethodCall(path_segment, ..) = recv.kind { + if matches!( + path_segment.ident.name.as_str(), + "to_lowercase" | "to_uppercase" | "to_ascii_lowercase" | "to_ascii_uppercase" + ) { + return; + } + } + if_chain! { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(method_id); @@ -28,13 +40,37 @@ pub(super) fn check<'tcx>( let recv_ty = cx.typeck_results().expr_ty(recv).peel_refs(); if recv_ty.is_str() || is_type_lang_item(cx, recv_ty, LangItem::String); then { - span_lint_and_help( + span_lint_and_then( cx, CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS, - call_span, + recv.span.to(call_span), "case-sensitive file extension comparison", - None, - "consider using a case-insensitive comparison instead", + |diag| { + diag.help("consider using a case-insensitive comparison instead"); + if let Some(mut recv_source) = snippet_opt(cx, recv.span) { + + if !cx.typeck_results().expr_ty(recv).is_ref() { + recv_source = format!("&{recv_source}"); + } + + let suggestion_source = reindent_multiline( + format!( + "std::path::Path::new({}) + .extension() + .map_or(false, |ext| ext.eq_ignore_ascii_case(\"{}\"))", + recv_source, ext_str.strip_prefix('.').unwrap()).into(), + true, + Some(indent_of(cx, call_span).unwrap_or(0) + 4) + ); + + diag.span_suggestion( + recv.span.to(call_span), + "use std::path::Path", + suggestion_source, + Applicability::MaybeIncorrect, + ); + } + } ); } } diff --git a/clippy_lints/src/methods/clone_on_copy.rs b/clippy_lints/src/methods/clone_on_copy.rs index 7c7938dd2e8b0..3795c0ec25098 100644 --- a/clippy_lints/src/methods/clone_on_copy.rs +++ b/clippy_lints/src/methods/clone_on_copy.rs @@ -6,7 +6,7 @@ use clippy_utils::ty::is_copy; use rustc_errors::Applicability; use rustc_hir::{BindingAnnotation, ByRef, Expr, ExprKind, MatchSource, Node, PatKind, QPath}; use rustc_lint::LateContext; -use rustc_middle::ty::{self, adjustment::Adjust}; +use rustc_middle::ty::{self, adjustment::Adjust, print::with_forced_trimmed_paths}; use rustc_span::symbol::{sym, Symbol}; use super::CLONE_DOUBLE_REF; @@ -47,10 +47,10 @@ pub(super) fn check( cx, CLONE_DOUBLE_REF, expr.span, - &format!( + &with_forced_trimmed_paths!(format!( "using `clone` on a double-reference; \ this will copy the reference of type `{ty}` instead of cloning the inner type" - ), + )), |diag| { if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) { let mut ty = innermost; @@ -61,11 +61,11 @@ pub(super) fn check( } let refs = "&".repeat(n + 1); let derefs = "*".repeat(n); - let explicit = format!("<{refs}{ty}>::clone({snip})"); + let explicit = with_forced_trimmed_paths!(format!("<{refs}{ty}>::clone({snip})")); diag.span_suggestion( expr.span, "try dereferencing it", - format!("{refs}({derefs}{}).clone()", snip.deref()), + with_forced_trimmed_paths!(format!("{refs}({derefs}{}).clone()", snip.deref())), Applicability::MaybeIncorrect, ); diag.span_suggestion( @@ -129,7 +129,9 @@ pub(super) fn check( cx, CLONE_ON_COPY, expr.span, - &format!("using `clone` on type `{ty}` which implements the `Copy` trait"), + &with_forced_trimmed_paths!(format!( + "using `clone` on type `{ty}` which implements the `Copy` trait" + )), help, sugg, app, diff --git a/clippy_lints/src/methods/filter_map.rs b/clippy_lints/src/methods/filter_map.rs index f888c58a72de9..fc80f2eeae015 100644 --- a/clippy_lints/src/methods/filter_map.rs +++ b/clippy_lints/src/methods/filter_map.rs @@ -30,12 +30,12 @@ fn is_method(cx: &LateContext<'_>, expr: &hir::Expr<'_>, method_name: Symbol) -> match closure_expr.kind { hir::ExprKind::MethodCall(hir::PathSegment { ident, .. }, receiver, ..) => { if_chain! { - if ident.name == method_name; - if let hir::ExprKind::Path(path) = &receiver.kind; - if let Res::Local(ref local) = cx.qpath_res(path, receiver.hir_id); - then { - return arg_id == *local - } + if ident.name == method_name; + if let hir::ExprKind::Path(path) = &receiver.kind; + if let Res::Local(ref local) = cx.qpath_res(path, receiver.hir_id); + then { + return arg_id == *local + } } false }, @@ -92,92 +92,92 @@ pub(super) fn check( } if_chain! { - if is_trait_method(cx, map_recv, sym::Iterator); - - // filter(|x| ...is_some())... - if let ExprKind::Closure(&Closure { body: filter_body_id, .. }) = filter_arg.kind; - let filter_body = cx.tcx.hir().body(filter_body_id); - if let [filter_param] = filter_body.params; - // optional ref pattern: `filter(|&x| ..)` - let (filter_pat, is_filter_param_ref) = if let PatKind::Ref(ref_pat, _) = filter_param.pat.kind { - (ref_pat, true) - } else { - (filter_param.pat, false) + if is_trait_method(cx, map_recv, sym::Iterator); + + // filter(|x| ...is_some())... + if let ExprKind::Closure(&Closure { body: filter_body_id, .. }) = filter_arg.kind; + let filter_body = cx.tcx.hir().body(filter_body_id); + if let [filter_param] = filter_body.params; + // optional ref pattern: `filter(|&x| ..)` + let (filter_pat, is_filter_param_ref) = if let PatKind::Ref(ref_pat, _) = filter_param.pat.kind { + (ref_pat, true) + } else { + (filter_param.pat, false) + }; + // closure ends with is_some() or is_ok() + if let PatKind::Binding(_, filter_param_id, _, None) = filter_pat.kind; + if let ExprKind::MethodCall(path, filter_arg, [], _) = filter_body.value.kind; + if let Some(opt_ty) = cx.typeck_results().expr_ty(filter_arg).peel_refs().ty_adt_def(); + if let Some(is_result) = if cx.tcx.is_diagnostic_item(sym::Option, opt_ty.did()) { + Some(false) + } else if cx.tcx.is_diagnostic_item(sym::Result, opt_ty.did()) { + Some(true) + } else { + None + }; + if path.ident.name.as_str() == if is_result { "is_ok" } else { "is_some" }; + + // ...map(|x| ...unwrap()) + if let ExprKind::Closure(&Closure { body: map_body_id, .. }) = map_arg.kind; + let map_body = cx.tcx.hir().body(map_body_id); + if let [map_param] = map_body.params; + if let PatKind::Binding(_, map_param_id, map_param_ident, None) = map_param.pat.kind; + // closure ends with expect() or unwrap() + if let ExprKind::MethodCall(seg, map_arg, ..) = map_body.value.kind; + if matches!(seg.ident.name, sym::expect | sym::unwrap | sym::unwrap_or); + + // .filter(..).map(|y| f(y).copied().unwrap()) + // ~~~~ + let map_arg_peeled = match map_arg.kind { + ExprKind::MethodCall(method, original_arg, [], _) if acceptable_methods(method) => { + original_arg + }, + _ => map_arg, + }; + + // .filter(|x| x.is_some()).map(|y| y[.acceptable_method()].unwrap()) + let simple_equal = path_to_local_id(filter_arg, filter_param_id) + && path_to_local_id(map_arg_peeled, map_param_id); + + let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| { + // in `filter(|x| ..)`, replace `*x` with `x` + let a_path = if_chain! { + if !is_filter_param_ref; + if let ExprKind::Unary(UnOp::Deref, expr_path) = a.kind; + then { expr_path } else { a } }; - // closure ends with is_some() or is_ok() - if let PatKind::Binding(_, filter_param_id, _, None) = filter_pat.kind; - if let ExprKind::MethodCall(path, filter_arg, [], _) = filter_body.value.kind; - if let Some(opt_ty) = cx.typeck_results().expr_ty(filter_arg).peel_refs().ty_adt_def(); - if let Some(is_result) = if cx.tcx.is_diagnostic_item(sym::Option, opt_ty.did()) { - Some(false) - } else if cx.tcx.is_diagnostic_item(sym::Result, opt_ty.did()) { - Some(true) + // let the filter closure arg and the map closure arg be equal + path_to_local_id(a_path, filter_param_id) + && path_to_local_id(b, map_param_id) + && cx.typeck_results().expr_ty_adjusted(a) == cx.typeck_results().expr_ty_adjusted(b) + }; + + if simple_equal || SpanlessEq::new(cx).expr_fallback(eq_fallback).eq_expr(filter_arg, map_arg_peeled); + then { + let span = filter_span.with_hi(expr.span.hi()); + let (filter_name, lint) = if is_find { + ("find", MANUAL_FIND_MAP) } else { - None - }; - if path.ident.name.as_str() == if is_result { "is_ok" } else { "is_some" }; - - // ...map(|x| ...unwrap()) - if let ExprKind::Closure(&Closure { body: map_body_id, .. }) = map_arg.kind; - let map_body = cx.tcx.hir().body(map_body_id); - if let [map_param] = map_body.params; - if let PatKind::Binding(_, map_param_id, map_param_ident, None) = map_param.pat.kind; - // closure ends with expect() or unwrap() - if let ExprKind::MethodCall(seg, map_arg, ..) = map_body.value.kind; - if matches!(seg.ident.name, sym::expect | sym::unwrap | sym::unwrap_or); - - // .filter(..).map(|y| f(y).copied().unwrap()) - // ~~~~ - let map_arg_peeled = match map_arg.kind { - ExprKind::MethodCall(method, original_arg, [], _) if acceptable_methods(method) => { - original_arg - }, - _ => map_arg, + ("filter", MANUAL_FILTER_MAP) }; + let msg = format!("`{filter_name}(..).map(..)` can be simplified as `{filter_name}_map(..)`"); + let (to_opt, deref) = if is_result { + (".ok()", String::new()) + } else { + let derefs = cx.typeck_results() + .expr_adjustments(map_arg) + .iter() + .filter(|adj| matches!(adj.kind, Adjust::Deref(_))) + .count(); - // .filter(|x| x.is_some()).map(|y| y[.acceptable_method()].unwrap()) - let simple_equal = path_to_local_id(filter_arg, filter_param_id) - && path_to_local_id(map_arg_peeled, map_param_id); - - let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| { - // in `filter(|x| ..)`, replace `*x` with `x` - let a_path = if_chain! { - if !is_filter_param_ref; - if let ExprKind::Unary(UnOp::Deref, expr_path) = a.kind; - then { expr_path } else { a } - }; - // let the filter closure arg and the map closure arg be equal - path_to_local_id(a_path, filter_param_id) - && path_to_local_id(b, map_param_id) - && cx.typeck_results().expr_ty_adjusted(a) == cx.typeck_results().expr_ty_adjusted(b) + ("", "*".repeat(derefs)) }; - - if simple_equal || SpanlessEq::new(cx).expr_fallback(eq_fallback).eq_expr(filter_arg, map_arg_peeled); - then { - let span = filter_span.with_hi(expr.span.hi()); - let (filter_name, lint) = if is_find { - ("find", MANUAL_FIND_MAP) - } else { - ("filter", MANUAL_FILTER_MAP) - }; - let msg = format!("`{filter_name}(..).map(..)` can be simplified as `{filter_name}_map(..)`"); - let (to_opt, deref) = if is_result { - (".ok()", String::new()) - } else { - let derefs = cx.typeck_results() - .expr_adjustments(map_arg) - .iter() - .filter(|adj| matches!(adj.kind, Adjust::Deref(_))) - .count(); - - ("", "*".repeat(derefs)) - }; - let sugg = format!( - "{filter_name}_map(|{map_param_ident}| {deref}{}{to_opt})", - snippet(cx, map_arg.span, ".."), - ); - span_lint_and_sugg(cx, lint, span, &msg, "try", sugg, Applicability::MachineApplicable); - } + let sugg = format!( + "{filter_name}_map(|{map_param_ident}| {deref}{}{to_opt})", + snippet(cx, map_arg.span, ".."), + ); + span_lint_and_sugg(cx, lint, span, &msg, "try", sugg, Applicability::MachineApplicable); + } } } diff --git a/clippy_lints/src/methods/iter_kv_map.rs b/clippy_lints/src/methods/iter_kv_map.rs index 2244ebfb12927..c87f5daab6f24 100644 --- a/clippy_lints/src/methods/iter_kv_map.rs +++ b/clippy_lints/src/methods/iter_kv_map.rs @@ -6,7 +6,7 @@ use clippy_utils::source::{snippet, snippet_with_applicability}; use clippy_utils::sugg; use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::visitors::is_local_used; -use rustc_hir::{BindingAnnotation, Body, BorrowKind, Expr, ExprKind, Mutability, Pat, PatKind}; +use rustc_hir::{BindingAnnotation, Body, BorrowKind, ByRef, Expr, ExprKind, Mutability, Pat, PatKind}; use rustc_lint::{LateContext, LintContext}; use rustc_middle::ty; use rustc_span::sym; @@ -30,9 +30,9 @@ pub(super) fn check<'tcx>( if let Body {params: [p], value: body_expr, generator_kind: _ } = cx.tcx.hir().body(c.body); if let PatKind::Tuple([key_pat, val_pat], _) = p.pat.kind; - let (replacement_kind, binded_ident) = match (&key_pat.kind, &val_pat.kind) { - (key, PatKind::Binding(_, _, value, _)) if pat_is_wild(cx, key, m_arg) => ("value", value), - (PatKind::Binding(_, _, key, _), value) if pat_is_wild(cx, value, m_arg) => ("key", key), + let (replacement_kind, annotation, bound_ident) = match (&key_pat.kind, &val_pat.kind) { + (key, PatKind::Binding(ann, _, value, _)) if pat_is_wild(cx, key, m_arg) => ("value", ann, value), + (PatKind::Binding(ann, _, key, _), value) if pat_is_wild(cx, value, m_arg) => ("key", ann, key), _ => return, }; @@ -47,7 +47,7 @@ pub(super) fn check<'tcx>( if_chain! { if let ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) = body_expr.kind; if let [local_ident] = path.segments; - if local_ident.ident.as_str() == binded_ident.as_str(); + if local_ident.ident.as_str() == bound_ident.as_str(); then { span_lint_and_sugg( @@ -60,13 +60,23 @@ pub(super) fn check<'tcx>( applicability, ); } else { + let ref_annotation = if annotation.0 == ByRef::Yes { + "ref " + } else { + "" + }; + let mut_annotation = if annotation.1 == Mutability::Mut { + "mut " + } else { + "" + }; span_lint_and_sugg( cx, ITER_KV_MAP, expr.span, &format!("iterating on a map's {replacement_kind}s"), "try", - format!("{recv_snippet}.{into_prefix}{replacement_kind}s().map(|{binded_ident}| {})", + format!("{recv_snippet}.{into_prefix}{replacement_kind}s().map(|{ref_annotation}{mut_annotation}{bound_ident}| {})", snippet_with_applicability(cx, body_expr.span, "/* body */", &mut applicability)), applicability, ); diff --git a/clippy_lints/src/methods/suspicious_to_owned.rs b/clippy_lints/src/methods/suspicious_to_owned.rs index 15c1c618c5137..fe88fa41fd91e 100644 --- a/clippy_lints/src/methods/suspicious_to_owned.rs +++ b/clippy_lints/src/methods/suspicious_to_owned.rs @@ -5,7 +5,7 @@ use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; -use rustc_middle::ty; +use rustc_middle::ty::{self, print::with_forced_trimmed_paths}; use rustc_span::sym; use super::SUSPICIOUS_TO_OWNED; @@ -24,7 +24,9 @@ pub fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>) - cx, SUSPICIOUS_TO_OWNED, expr.span, - &format!("this `to_owned` call clones the {input_type} itself and does not cause the {input_type} contents to become owned"), + &with_forced_trimmed_paths!(format!( + "this `to_owned` call clones the {input_type} itself and does not cause the {input_type} contents to become owned" + )), "consider using, depending on intent", format!("{recv_snip}.clone()` or `{recv_snip}.into_owned()"), app, diff --git a/clippy_lints/src/mutex_atomic.rs b/clippy_lints/src/mutex_atomic.rs index 09cb53331763d..dc866ab6373bb 100644 --- a/clippy_lints/src/mutex_atomic.rs +++ b/clippy_lints/src/mutex_atomic.rs @@ -1,6 +1,6 @@ //! Checks for uses of mutex where an atomic value could be used //! -//! This lint is **warn** by default +//! This lint is **allow** by default use clippy_utils::diagnostics::span_lint; use clippy_utils::ty::is_type_diagnostic_item; @@ -20,6 +20,10 @@ declare_clippy_lint! { /// `std::sync::atomic::AtomicBool` and `std::sync::atomic::AtomicPtr` are leaner and /// faster. /// + /// On the other hand, `Mutex`es are, in general, easier to + /// verify correctness. An atomic does not behave the same as + /// an equivalent mutex. See [this issue](https://github.com/rust-lang/rust-clippy/issues/4295)'s commentary for more details. + /// /// ### Known problems /// This lint cannot detect if the mutex is actually used /// for waiting before a critical section. @@ -39,8 +43,8 @@ declare_clippy_lint! { /// ``` #[clippy::version = "pre 1.29.0"] pub MUTEX_ATOMIC, - nursery, - "using a mutex where an atomic value could be used instead" + restriction, + "using a mutex where an atomic value could be used instead." } declare_clippy_lint! { diff --git a/clippy_lints/src/operators/arithmetic_side_effects.rs b/clippy_lints/src/operators/arithmetic_side_effects.rs index 4fbc8398e3734..cff82b875f11a 100644 --- a/clippy_lints/src/operators/arithmetic_side_effects.rs +++ b/clippy_lints/src/operators/arithmetic_side_effects.rs @@ -2,7 +2,7 @@ use super::ARITHMETIC_SIDE_EFFECTS; use clippy_utils::{ consts::{constant, constant_simple}, diagnostics::span_lint, - peel_hir_expr_refs, + peel_hir_expr_refs, peel_hir_expr_unary, }; use rustc_ast as ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; @@ -98,8 +98,11 @@ impl ArithmeticSideEffects { } /// If `expr` is not a literal integer like `1`, returns `None`. + /// + /// Returns the absolute value of the expression, if this is an integer literal. fn literal_integer(expr: &hir::Expr<'_>) -> Option { - if let hir::ExprKind::Lit(ref lit) = expr.kind && let ast::LitKind::Int(n, _) = lit.node { + let actual = peel_hir_expr_unary(expr).0; + if let hir::ExprKind::Lit(ref lit) = actual.kind && let ast::LitKind::Int(n, _) = lit.node { Some(n) } else { @@ -123,12 +126,12 @@ impl ArithmeticSideEffects { if !matches!( op.node, hir::BinOpKind::Add - | hir::BinOpKind::Sub - | hir::BinOpKind::Mul | hir::BinOpKind::Div + | hir::BinOpKind::Mul | hir::BinOpKind::Rem | hir::BinOpKind::Shl | hir::BinOpKind::Shr + | hir::BinOpKind::Sub ) { return; }; diff --git a/clippy_lints/src/ranges.rs b/clippy_lints/src/ranges.rs index 0a1b9d173cf94..fc655fe2d0bb3 100644 --- a/clippy_lints/src/ranges.rs +++ b/clippy_lints/src/ranges.rs @@ -103,7 +103,7 @@ declare_clippy_lint! { declare_clippy_lint! { /// ### What it does /// Checks for range expressions `x..y` where both `x` and `y` - /// are constant and `x` is greater or equal to `y`. + /// are constant and `x` is greater to `y`. Also triggers if `x` is equal to `y` when they are conditions to a `for` loop. /// /// ### Why is this bad? /// Empty ranges yield no values so iterating them is a no-op. diff --git a/clippy_lints/src/redundant_clone.rs b/clippy_lints/src/redundant_clone.rs index 0e7c5cca7240b..c1677fb3da1c4 100644 --- a/clippy_lints/src/redundant_clone.rs +++ b/clippy_lints/src/redundant_clone.rs @@ -131,7 +131,7 @@ impl<'tcx> LateLintPass<'tcx> for RedundantClone { // `res = clone(arg)` can be turned into `res = move arg;` // if `arg` is the only borrow of `cloned` at this point. - if cannot_move_out || !possible_borrower.at_most_borrowers(cx, &[arg], cloned, loc) { + if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) { continue; } @@ -178,7 +178,7 @@ impl<'tcx> LateLintPass<'tcx> for RedundantClone { // StorageDead(pred_arg); // res = to_path_buf(cloned); // ``` - if cannot_move_out || !possible_borrower.at_most_borrowers(cx, &[arg, cloned], local, loc) { + if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) { continue; } diff --git a/clippy_lints/src/renamed_lints.rs b/clippy_lints/src/renamed_lints.rs index 72c25592609ba..9f487dedb8cb6 100644 --- a/clippy_lints/src/renamed_lints.rs +++ b/clippy_lints/src/renamed_lints.rs @@ -9,6 +9,7 @@ pub static RENAMED_LINTS: &[(&str, &str)] = &[ ("clippy::box_vec", "clippy::box_collection"), ("clippy::const_static_lifetime", "clippy::redundant_static_lifetimes"), ("clippy::cyclomatic_complexity", "clippy::cognitive_complexity"), + ("clippy::derive_hash_xor_eq", "clippy::derived_hash_with_manual_eq"), ("clippy::disallowed_method", "clippy::disallowed_methods"), ("clippy::disallowed_type", "clippy::disallowed_types"), ("clippy::eval_order_dependence", "clippy::mixed_read_write_in_expression"), diff --git a/clippy_lints/src/returns.rs b/clippy_lints/src/returns.rs index d4d506605206b..bbbd9e4989e97 100644 --- a/clippy_lints/src/returns.rs +++ b/clippy_lints/src/returns.rs @@ -210,22 +210,25 @@ fn check_final_expr<'tcx>( // if desugar of `do yeet`, don't lint if let Some(inner_expr) = inner && let ExprKind::Call(path_expr, _) = inner_expr.kind - && let ExprKind::Path(QPath::LangItem(LangItem::TryTraitFromYeet, _, _)) = path_expr.kind { - return; + && let ExprKind::Path(QPath::LangItem(LangItem::TryTraitFromYeet, _, _)) = path_expr.kind + { + return; } - if cx.tcx.hir().attrs(expr.hir_id).is_empty() { - let borrows = inner.map_or(false, |inner| last_statement_borrows(cx, inner)); - if !borrows { - // check if expr return nothing - let ret_span = if inner.is_none() && replacement == RetReplacement::Empty { - extend_span_to_previous_non_ws(cx, peeled_drop_expr.span) - } else { - peeled_drop_expr.span - }; - - emit_return_lint(cx, ret_span, semi_spans, inner.as_ref().map(|i| i.span), replacement); - } + if !cx.tcx.hir().attrs(expr.hir_id).is_empty() { + return; + } + let borrows = inner.map_or(false, |inner| last_statement_borrows(cx, inner)); + if borrows { + return; } + // check if expr return nothing + let ret_span = if inner.is_none() && replacement == RetReplacement::Empty { + extend_span_to_previous_non_ws(cx, peeled_drop_expr.span) + } else { + peeled_drop_expr.span + }; + + emit_return_lint(cx, ret_span, semi_spans, inner.as_ref().map(|i| i.span), replacement); }, ExprKind::If(_, then, else_clause_opt) => { check_block_return(cx, &then.kind, semi_spans.clone()); @@ -292,7 +295,7 @@ fn last_statement_borrows<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { ControlFlow::Break(()) } else { - ControlFlow::Continue(Descend::from(!expr.span.from_expansion())) + ControlFlow::Continue(Descend::from(!e.span.from_expansion())) } }) .is_some() diff --git a/clippy_lints/src/types/mod.rs b/clippy_lints/src/types/mod.rs index c14f056a1f2de..229478b7ce3c9 100644 --- a/clippy_lints/src/types/mod.rs +++ b/clippy_lints/src/types/mod.rs @@ -127,7 +127,7 @@ declare_clippy_lint! { /// `Vec` or a `VecDeque` (formerly called `RingBuf`). /// /// ### Why is this bad? - /// Gankro says: + /// Gankra says: /// /// > The TL;DR of `LinkedList` is that it's built on a massive amount of /// pointers and indirection. diff --git a/clippy_lints/src/unused_self.rs b/clippy_lints/src/unused_self.rs index 42bccc7212b30..f864c520302e4 100644 --- a/clippy_lints/src/unused_self.rs +++ b/clippy_lints/src/unused_self.rs @@ -1,9 +1,11 @@ use clippy_utils::diagnostics::span_lint_and_help; +use clippy_utils::macros::root_macro_call_first_node; use clippy_utils::visitors::is_local_used; use if_chain::if_chain; -use rustc_hir::{Impl, ImplItem, ImplItemKind, ItemKind}; +use rustc_hir::{Body, Impl, ImplItem, ImplItemKind, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_tool_lint, impl_lint_pass}; +use std::ops::ControlFlow; declare_clippy_lint! { /// ### What it does @@ -57,6 +59,20 @@ impl<'tcx> LateLintPass<'tcx> for UnusedSelf { let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id; let parent_item = cx.tcx.hir().expect_item(parent); let assoc_item = cx.tcx.associated_item(impl_item.owner_id); + let contains_todo = |cx, body: &'_ Body<'_>| -> bool { + clippy_utils::visitors::for_each_expr(body.value, |e| { + if let Some(macro_call) = root_macro_call_first_node(cx, e) { + if cx.tcx.item_name(macro_call.def_id).as_str() == "todo" { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + } else { + ControlFlow::Continue(()) + } + }) + .is_some() + }; if_chain! { if let ItemKind::Impl(Impl { of_trait: None, .. }) = parent_item.kind; if assoc_item.fn_has_self_parameter; @@ -65,6 +81,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedSelf { let body = cx.tcx.hir().body(*body_id); if let [self_param, ..] = body.params; if !is_local_used(cx, body, self_param.pat.hir_id); + if !contains_todo(cx, body); then { span_lint_and_help( cx, @@ -72,7 +89,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedSelf { self_param.span, "unused `self` argument", None, - "consider refactoring to a associated function", + "consider refactoring to an associated function", ); } } diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index c86f24cbd3780..c4d8c28f06061 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -1058,7 +1058,7 @@ fn get_parent_local<'hir>(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) - fn get_parent_local_hir_id<'hir>(cx: &LateContext<'hir>, hir_id: hir::HirId) -> Option<&'hir hir::Local<'hir>> { let map = cx.tcx.hir(); - match map.find_parent((hir_id)) { + match map.find_parent(hir_id) { Some(hir::Node::Local(local)) => Some(local), Some(hir::Node::Pat(pattern)) => get_parent_local_hir_id(cx, pattern.hir_id), _ => None, diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index 8290fe9ecb4c6..7a4a9036dd363 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -22,6 +22,9 @@ extern crate rustc_ast; extern crate rustc_ast_pretty; extern crate rustc_attr; extern crate rustc_data_structures; +// The `rustc_driver` crate seems to be required in order to use the `rust_ast` crate. +#[allow(unused_extern_crates)] +extern crate rustc_driver; extern crate rustc_errors; extern crate rustc_hir; extern crate rustc_hir_typeck; @@ -116,6 +119,8 @@ use crate::consts::{constant, Constant}; use crate::ty::{can_partially_move_ty, expr_sig, is_copy, is_recursively_primitive_type, ty_is_fn_once_param}; use crate::visitors::for_each_expr; +use rustc_middle::hir::nested_filter; + #[macro_export] macro_rules! extract_msrv_attr { ($context:ident) => { @@ -1253,22 +1258,33 @@ pub fn get_item_name(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option { } } -pub struct ContainsName { +pub struct ContainsName<'a, 'tcx> { + pub cx: &'a LateContext<'tcx>, pub name: Symbol, pub result: bool, } -impl<'tcx> Visitor<'tcx> for ContainsName { +impl<'a, 'tcx> Visitor<'tcx> for ContainsName<'a, 'tcx> { + type NestedFilter = nested_filter::OnlyBodies; + fn visit_name(&mut self, name: Symbol) { if self.name == name { self.result = true; } } + + fn nested_visit_map(&mut self) -> Self::Map { + self.cx.tcx.hir() + } } /// Checks if an `Expr` contains a certain name. -pub fn contains_name(name: Symbol, expr: &Expr<'_>) -> bool { - let mut cn = ContainsName { name, result: false }; +pub fn contains_name<'tcx>(name: Symbol, expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> bool { + let mut cn = ContainsName { + name, + result: false, + cx, + }; cn.visit_expr(expr); cn.result } @@ -1304,6 +1320,7 @@ pub fn get_parent_expr_for_hir<'tcx>(cx: &LateContext<'tcx>, hir_id: hir::HirId) } } +/// Gets the enclosing block, if any. pub fn get_enclosing_block<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> { let map = &cx.tcx.hir(); let enclosing_node = map @@ -2244,6 +2261,18 @@ pub fn peel_n_hir_expr_refs<'a>(expr: &'a Expr<'a>, count: usize) -> (&'a Expr<' (e, count - remaining) } +/// Peels off all unary operators of an expression. Returns the underlying expression and the number +/// of operators removed. +pub fn peel_hir_expr_unary<'a>(expr: &'a Expr<'a>) -> (&'a Expr<'a>, usize) { + let mut count: usize = 0; + let mut curr_expr = expr; + while let ExprKind::Unary(_, local_expr) = curr_expr.kind { + count = count.wrapping_add(1); + curr_expr = local_expr; + } + (curr_expr, count) +} + /// Peels off all references on the expression. Returns the underlying expression and the number of /// references removed. pub fn peel_hir_expr_refs<'a>(expr: &'a Expr<'a>) -> (&'a Expr<'a>, usize) { diff --git a/clippy_utils/src/mir/possible_borrower.rs b/clippy_utils/src/mir/possible_borrower.rs index 395d46e7a2f8a..9adae77338945 100644 --- a/clippy_utils/src/mir/possible_borrower.rs +++ b/clippy_utils/src/mir/possible_borrower.rs @@ -1,16 +1,11 @@ -use super::possible_origin::PossibleOriginVisitor; +use super::{possible_origin::PossibleOriginVisitor, transitive_relation::TransitiveRelation}; use crate::ty::is_copy; -use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; +use rustc_data_structures::fx::FxHashMap; use rustc_index::bit_set::{BitSet, HybridBitSet}; use rustc_lint::LateContext; -use rustc_middle::mir::{ - self, visit::Visitor as _, BasicBlock, Local, Location, Mutability, Statement, StatementKind, Terminator, -}; -use rustc_middle::ty::{self, visit::TypeVisitor, TyCtxt}; -use rustc_mir_dataflow::{ - fmt::DebugWithContext, impls::MaybeStorageLive, lattice::JoinSemiLattice, Analysis, AnalysisDomain, - CallReturnPlaces, ResultsCursor, -}; +use rustc_middle::mir::{self, visit::Visitor as _, Mutability}; +use rustc_middle::ty::{self, visit::TypeVisitor}; +use rustc_mir_dataflow::{impls::MaybeStorageLive, Analysis, ResultsCursor}; use std::borrow::Cow; use std::ops::ControlFlow; @@ -18,120 +13,78 @@ use std::ops::ControlFlow; /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c` /// possible borrowers of `a`. #[allow(clippy::module_name_repetitions)] -struct PossibleBorrowerAnalysis<'b, 'tcx> { - tcx: TyCtxt<'tcx>, +struct PossibleBorrowerVisitor<'a, 'b, 'tcx> { + possible_borrower: TransitiveRelation, body: &'b mir::Body<'tcx>, + cx: &'a LateContext<'tcx>, possible_origin: FxHashMap>, } -#[derive(Clone, Debug, Eq, PartialEq)] -struct PossibleBorrowerState { - map: FxIndexMap>, - domain_size: usize, -} - -impl PossibleBorrowerState { - fn new(domain_size: usize) -> Self { +impl<'a, 'b, 'tcx> PossibleBorrowerVisitor<'a, 'b, 'tcx> { + fn new( + cx: &'a LateContext<'tcx>, + body: &'b mir::Body<'tcx>, + possible_origin: FxHashMap>, + ) -> Self { Self { - map: FxIndexMap::default(), - domain_size, + possible_borrower: TransitiveRelation::default(), + cx, + body, + possible_origin, } } - #[allow(clippy::similar_names)] - fn add(&mut self, borrowed: Local, borrower: Local) { - self.map - .entry(borrowed) - .or_insert(BitSet::new_empty(self.domain_size)) - .insert(borrower); - } -} - -impl DebugWithContext for PossibleBorrowerState { - fn fmt_with(&self, _ctxt: &C, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - <_ as std::fmt::Debug>::fmt(self, f) - } - fn fmt_diff_with(&self, _old: &Self, _ctxt: &C, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - unimplemented!() - } -} + fn into_map( + self, + cx: &'a LateContext<'tcx>, + maybe_live: ResultsCursor<'b, 'tcx, MaybeStorageLive<'tcx>>, + ) -> PossibleBorrowerMap<'b, 'tcx> { + let mut map = FxHashMap::default(); + for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) { + if is_copy(cx, self.body.local_decls[row].ty) { + continue; + } -impl JoinSemiLattice for PossibleBorrowerState { - fn join(&mut self, other: &Self) -> bool { - let mut changed = false; - for (&borrowed, borrowers) in other.map.iter() { + let mut borrowers = self.possible_borrower.reachable_from(row, self.body.local_decls.len()); + borrowers.remove(mir::Local::from_usize(0)); if !borrowers.is_empty() { - changed |= self - .map - .entry(borrowed) - .or_insert(BitSet::new_empty(self.domain_size)) - .union(borrowers); + map.insert(row, borrowers); } } - changed - } -} - -impl<'b, 'tcx> AnalysisDomain<'tcx> for PossibleBorrowerAnalysis<'b, 'tcx> { - type Domain = PossibleBorrowerState; - - const NAME: &'static str = "possible_borrower"; - - fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain { - PossibleBorrowerState::new(body.local_decls.len()) - } - - fn initialize_start_block(&self, _body: &mir::Body<'tcx>, _entry_set: &mut Self::Domain) {} -} -impl<'b, 'tcx> PossibleBorrowerAnalysis<'b, 'tcx> { - fn new( - tcx: TyCtxt<'tcx>, - body: &'b mir::Body<'tcx>, - possible_origin: FxHashMap>, - ) -> Self { - Self { - tcx, - body, - possible_origin, + let bs = BitSet::new_empty(self.body.local_decls.len()); + PossibleBorrowerMap { + map, + maybe_live, + bitset: (bs.clone(), bs), } } } -impl<'b, 'tcx> Analysis<'tcx> for PossibleBorrowerAnalysis<'b, 'tcx> { - fn apply_call_return_effect( - &self, - _state: &mut Self::Domain, - _block: BasicBlock, - _return_places: CallReturnPlaces<'_, 'tcx>, - ) { - } - - fn apply_statement_effect(&self, state: &mut Self::Domain, statement: &Statement<'tcx>, _location: Location) { - if let StatementKind::Assign(box (place, rvalue)) = &statement.kind { - let lhs = place.local; - match rvalue { - mir::Rvalue::Ref(_, _, borrowed) => { - state.add(borrowed.local, lhs); - }, - other => { - if ContainsRegion - .visit_ty(place.ty(&self.body.local_decls, self.tcx).ty) - .is_continue() - { - return; +impl<'a, 'b, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'b, 'tcx> { + fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) { + let lhs = place.local; + match rvalue { + mir::Rvalue::Ref(_, _, borrowed) => { + self.possible_borrower.add(borrowed.local, lhs); + }, + other => { + if ContainsRegion + .visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty) + .is_continue() + { + return; + } + rvalue_locals(other, |rhs| { + if lhs != rhs { + self.possible_borrower.add(rhs, lhs); } - rvalue_locals(other, |rhs| { - if lhs != rhs { - state.add(rhs, lhs); - } - }); - }, - } + }); + }, } } - fn apply_terminator_effect(&self, state: &mut Self::Domain, terminator: &Terminator<'tcx>, _location: Location) { + fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) { if let mir::TerminatorKind::Call { args, destination: mir::Place { local: dest, .. }, @@ -171,10 +124,10 @@ impl<'b, 'tcx> Analysis<'tcx> for PossibleBorrowerAnalysis<'b, 'tcx> { for y in mutable_variables { for x in &immutable_borrowers { - state.add(*x, y); + self.possible_borrower.add(*x, y); } for x in &mutable_borrowers { - state.add(*x, y); + self.possible_borrower.add(*x, y); } } } @@ -210,98 +163,73 @@ fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) { } } -/// Result of `PossibleBorrowerAnalysis`. +/// Result of `PossibleBorrowerVisitor`. #[allow(clippy::module_name_repetitions)] pub struct PossibleBorrowerMap<'b, 'tcx> { - body: &'b mir::Body<'tcx>, - possible_borrower: ResultsCursor<'b, 'tcx, PossibleBorrowerAnalysis<'b, 'tcx>>, - maybe_live: ResultsCursor<'b, 'tcx, MaybeStorageLive<'b>>, - pushed: BitSet, - stack: Vec, + /// Mapping `Local -> its possible borrowers` + pub map: FxHashMap>, + maybe_live: ResultsCursor<'b, 'tcx, MaybeStorageLive<'tcx>>, + // Caches to avoid allocation of `BitSet` on every query + pub bitset: (BitSet, BitSet), } -impl<'b, 'tcx> PossibleBorrowerMap<'b, 'tcx> { - pub fn new(cx: &LateContext<'tcx>, mir: &'b mir::Body<'tcx>) -> Self { +impl<'a, 'b, 'tcx> PossibleBorrowerMap<'b, 'tcx> { + pub fn new(cx: &'a LateContext<'tcx>, mir: &'b mir::Body<'tcx>) -> Self { let possible_origin = { let mut vis = PossibleOriginVisitor::new(mir); vis.visit_body(mir); vis.into_map(cx) }; - let possible_borrower = PossibleBorrowerAnalysis::new(cx.tcx, mir, possible_origin) + let maybe_storage_live_result = MaybeStorageLive::new(Cow::Owned(BitSet::new_empty(mir.local_decls.len()))) .into_engine(cx.tcx, mir) - .pass_name("possible_borrower") + .pass_name("redundant_clone") .iterate_to_fixpoint() .into_results_cursor(mir); - let maybe_live = MaybeStorageLive::new(Cow::Owned(BitSet::new_empty(mir.local_decls.len()))) - .into_engine(cx.tcx, mir) - .pass_name("possible_borrower") - .iterate_to_fixpoint() - .into_results_cursor(mir); - PossibleBorrowerMap { - body: mir, - possible_borrower, - maybe_live, - pushed: BitSet::new_empty(mir.local_decls.len()), - stack: Vec::with_capacity(mir.local_decls.len()), - } + let mut vis = PossibleBorrowerVisitor::new(cx, mir, possible_origin); + vis.visit_body(mir); + vis.into_map(cx, maybe_storage_live_result) } - /// Returns true if the set of borrowers of `borrowed` living at `at` includes no more than - /// `borrowers`. - /// Notes: - /// 1. It would be nice if `PossibleBorrowerMap` could store `cx` so that `at_most_borrowers` - /// would not require it to be passed in. But a `PossibleBorrowerMap` is stored in `LintPass` - /// `Dereferencing`, which outlives any `LateContext`. - /// 2. In all current uses of `at_most_borrowers`, `borrowers` is a slice of at most two - /// elements. Thus, `borrowers.contains(...)` is effectively a constant-time operation. If - /// `at_most_borrowers`'s uses were to expand beyond this, its implementation might have to be - /// adjusted. - pub fn at_most_borrowers( + /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`. + pub fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool { + self.bounded_borrowers(borrowers, borrowers, borrowed, at) + } + + /// Returns true if the set of borrowers of `borrowed` living at `at` includes at least `below` + /// but no more than `above`. + pub fn bounded_borrowers( &mut self, - cx: &LateContext<'tcx>, - borrowers: &[mir::Local], + below: &[mir::Local], + above: &[mir::Local], borrowed: mir::Local, at: mir::Location, ) -> bool { - if is_copy(cx, self.body.local_decls[borrowed].ty) { - return true; - } - - self.possible_borrower.seek_before_primary_effect(at); - self.maybe_live.seek_before_primary_effect(at); - - let possible_borrower = &self.possible_borrower.get().map; - let maybe_live = &self.maybe_live; - - self.pushed.clear(); - self.stack.clear(); + self.maybe_live.seek_after_primary_effect(at); - if let Some(borrowers) = possible_borrower.get(&borrowed) { - for b in borrowers.iter() { - if self.pushed.insert(b) { - self.stack.push(b); - } + self.bitset.0.clear(); + let maybe_live = &mut self.maybe_live; + if let Some(bitset) = self.map.get(&borrowed) { + for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) { + self.bitset.0.insert(b); } } else { - // Nothing borrows `borrowed` at `at`. - return true; + return false; } - while let Some(borrower) = self.stack.pop() { - if maybe_live.contains(borrower) && !borrowers.contains(&borrower) { - return false; - } + self.bitset.1.clear(); + for b in below { + self.bitset.1.insert(*b); + } - if let Some(borrowers) = possible_borrower.get(&borrower) { - for b in borrowers.iter() { - if self.pushed.insert(b) { - self.stack.push(b); - } - } - } + if !self.bitset.0.superset(&self.bitset.1) { + return false; + } + + for b in above { + self.bitset.0.remove(*b); } - true + self.bitset.0.is_empty() } pub fn local_is_alive_at(&mut self, local: mir::Local, at: mir::Location) -> bool { diff --git a/clippy_utils/src/msrvs.rs b/clippy_utils/src/msrvs.rs index ba5bc9c3135da..dbf9f3b621d7a 100644 --- a/clippy_utils/src/msrvs.rs +++ b/clippy_utils/src/msrvs.rs @@ -20,8 +20,9 @@ macro_rules! msrv_aliases { // names may refer to stabilized feature flags or library items msrv_aliases! { 1,65,0 { LET_ELSE } - 1,62,0 { BOOL_THEN_SOME } + 1,62,0 { BOOL_THEN_SOME, DEFAULT_ENUM_ATTRIBUTE } 1,58,0 { FORMAT_ARGS_CAPTURE, PATTERN_TRAIT_CHAR_ARRAY } + 1,55,0 { SEEK_REWIND } 1,53,0 { OR_PATTERNS, MANUAL_BITS, BTREE_MAP_RETAIN, BTREE_SET_RETAIN, ARRAY_INTO_ITERATOR } 1,52,0 { STR_SPLIT_ONCE, REM_EUCLID_CONST } 1,51,0 { BORROW_AS_PTR, SEEK_FROM_CURRENT, UNSIGNED_ABS } @@ -45,7 +46,6 @@ msrv_aliases! { 1,18,0 { HASH_MAP_RETAIN, HASH_SET_RETAIN } 1,17,0 { FIELD_INIT_SHORTHAND, STATIC_IN_CONST, EXPECT_ERR } 1,16,0 { STR_REPEAT } - 1,55,0 { SEEK_REWIND } } fn parse_msrv(msrv: &str, sess: Option<&Session>, span: Option) -> Option { diff --git a/clippy_utils/src/paths.rs b/clippy_utils/src/paths.rs index 9ca50105ae57d..95eebab756776 100644 --- a/clippy_utils/src/paths.rs +++ b/clippy_utils/src/paths.rs @@ -47,7 +47,6 @@ pub const IDENT: [&str; 3] = ["rustc_span", "symbol", "Ident"]; #[cfg(feature = "internal")] pub const IDENT_AS_STR: [&str; 4] = ["rustc_span", "symbol", "Ident", "as_str"]; pub const INSERT_STR: [&str; 4] = ["alloc", "string", "String", "insert_str"]; -pub const ITER_COUNT: [&str; 6] = ["core", "iter", "traits", "iterator", "Iterator", "count"]; pub const ITER_EMPTY: [&str; 5] = ["core", "iter", "sources", "empty", "Empty"]; pub const ITERTOOLS_NEXT_TUPLE: [&str; 3] = ["itertools", "Itertools", "next_tuple"]; #[cfg(feature = "internal")] diff --git a/clippy_utils/src/visitors.rs b/clippy_utils/src/visitors.rs index 863fb60fcfca1..14c01a60b4c32 100644 --- a/clippy_utils/src/visitors.rs +++ b/clippy_utils/src/visitors.rs @@ -724,3 +724,14 @@ pub fn for_each_local_assignment<'tcx, B>( ControlFlow::Continue(()) } } + +pub fn contains_break_or_continue(expr: &Expr<'_>) -> bool { + for_each_expr(expr, |e| { + if matches!(e.kind, ExprKind::Break(..) | ExprKind::Continue(..)) { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }) + .is_some() +} diff --git a/rust-toolchain b/rust-toolchain index 9399d422036d4..40a6f47095ec2 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-12-29" +channel = "nightly-2023-01-12" components = ["cargo", "llvm-tools", "rust-src", "rust-std", "rustc", "rustc-dev", "rustfmt"] diff --git a/src/driver.rs b/src/driver.rs index bcc096c570e1b..d521e8d883983 100644 --- a/src/driver.rs +++ b/src/driver.rs @@ -256,11 +256,14 @@ pub fn main() { LazyLock::force(&ICE_HOOK); exit(rustc_driver::catch_with_exit_code(move || { let mut orig_args: Vec = env::args().collect(); + let has_sysroot_arg = arg_value(&orig_args, "--sysroot", |_| true).is_some(); let sys_root_env = std::env::var("SYSROOT").ok(); let pass_sysroot_env_if_given = |args: &mut Vec, sys_root_env| { if let Some(sys_root) = sys_root_env { - args.extend(vec!["--sysroot".into(), sys_root]); + if !has_sysroot_arg { + args.extend(vec!["--sysroot".into(), sys_root]); + } }; }; diff --git a/tests/integration.rs b/tests/integration.rs index 818ff70b33f4d..a771d8b87c81a 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -1,3 +1,12 @@ +//! This test is meant to only be run in CI. To run it locally use: +//! +//! `env INTEGRATION=rust-lang/log cargo test --test integration --features=integration` +//! +//! You can use a different `INTEGRATION` value to test different repositories. +//! +//! This test will clone the specified repository and run Clippy on it. The test succeeds, if +//! Clippy doesn't produce an ICE. Lint warnings are ignored by this test. + #![cfg(feature = "integration")] #![cfg_attr(feature = "deny-warnings", deny(warnings))] #![warn(rust_2018_idioms, unused_lifetimes)] diff --git a/tests/ui-toml/arithmetic_side_effects_allowed/arithmetic_side_effects_allowed.rs b/tests/ui-toml/arithmetic_side_effects_allowed/arithmetic_side_effects_allowed.rs index 36db9e54a2288..fb5b1b193f841 100644 --- a/tests/ui-toml/arithmetic_side_effects_allowed/arithmetic_side_effects_allowed.rs +++ b/tests/ui-toml/arithmetic_side_effects_allowed/arithmetic_side_effects_allowed.rs @@ -107,7 +107,7 @@ fn rhs_is_different() { fn unary() { // is explicitly on the list let _ = -OutOfNames; - // is specifically on the list + // is explicitly on the list let _ = -Foo; // not on the list let _ = -Bar; diff --git a/tests/ui-toml/dbg_macro/dbg_macro.stderr b/tests/ui-toml/dbg_macro/dbg_macro.stderr index 46efb86dcfc5f..859383a71194f 100644 --- a/tests/ui-toml/dbg_macro/dbg_macro.stderr +++ b/tests/ui-toml/dbg_macro/dbg_macro.stderr @@ -1,99 +1,99 @@ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:5:22 | LL | if let Some(n) = dbg!(n.checked_sub(4)) { n } else { n } | ^^^^^^^^^^^^^^^^^^^^^^ | = note: `-D clippy::dbg-macro` implied by `-D warnings` -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | if let Some(n) = n.checked_sub(4) { n } else { n } | ~~~~~~~~~~~~~~~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:9:8 | LL | if dbg!(n <= 1) { | ^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | if n <= 1 { | ~~~~~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:10:9 | LL | dbg!(1) | ^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | 1 | -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:12:9 | LL | dbg!(n * factorial(n - 1)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | n * factorial(n - 1) | -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:17:5 | LL | dbg!(42); | ^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | 42; | ~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:18:5 | LL | dbg!(dbg!(dbg!(42))); | ^^^^^^^^^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | dbg!(dbg!(42)); | ~~~~~~~~~~~~~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:19:14 | LL | foo(3) + dbg!(factorial(4)); | ^^^^^^^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | foo(3) + factorial(4); | ~~~~~~~~~~~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:20:5 | LL | dbg!(1, 2, dbg!(3, 4)); | ^^^^^^^^^^^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | (1, 2, dbg!(3, 4)); | ~~~~~~~~~~~~~~~~~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:21:5 | LL | dbg!(1, 2, 3, 4, 5); | ^^^^^^^^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | (1, 2, 3, 4, 5); | ~~~~~~~~~~~~~~~ diff --git a/tests/ui/arithmetic_side_effects.rs b/tests/ui/arithmetic_side_effects.rs index b5ed8988a518f..918cf81c600af 100644 --- a/tests/ui/arithmetic_side_effects.rs +++ b/tests/ui/arithmetic_side_effects.rs @@ -2,6 +2,7 @@ clippy::assign_op_pattern, clippy::erasing_op, clippy::identity_op, + clippy::no_effect, clippy::op_ref, clippy::unnecessary_owned_empty_strings, arithmetic_overflow, @@ -12,31 +13,95 @@ use core::num::{Saturating, Wrapping}; +#[derive(Clone, Copy)] pub struct Custom; macro_rules! impl_arith { - ( $( $_trait:ident, $ty:ty, $method:ident; )* ) => { + ( $( $_trait:ident, $lhs:ty, $rhs:ty, $method:ident; )* ) => { $( - impl core::ops::$_trait<$ty> for Custom { - type Output = Self; - fn $method(self, _: $ty) -> Self::Output { Self } + impl core::ops::$_trait<$lhs> for $rhs { + type Output = Custom; + fn $method(self, _: $lhs) -> Self::Output { todo!() } + } + )* + } +} + +macro_rules! impl_assign_arith { + ( $( $_trait:ident, $lhs:ty, $rhs:ty, $method:ident; )* ) => { + $( + impl core::ops::$_trait<$lhs> for $rhs { + fn $method(&mut self, _: $lhs) {} } )* } } impl_arith!( - Add, i32, add; - Div, i32, div; - Mul, i32, mul; - Sub, i32, sub; - - Add, f64, add; - Div, f64, div; - Mul, f64, mul; - Sub, f64, sub; + Add, Custom, Custom, add; + Div, Custom, Custom, div; + Mul, Custom, Custom, mul; + Rem, Custom, Custom, rem; + Sub, Custom, Custom, sub; + + Add, Custom, &Custom, add; + Div, Custom, &Custom, div; + Mul, Custom, &Custom, mul; + Rem, Custom, &Custom, rem; + Sub, Custom, &Custom, sub; + + Add, &Custom, Custom, add; + Div, &Custom, Custom, div; + Mul, &Custom, Custom, mul; + Rem, &Custom, Custom, rem; + Sub, &Custom, Custom, sub; + + Add, &Custom, &Custom, add; + Div, &Custom, &Custom, div; + Mul, &Custom, &Custom, mul; + Rem, &Custom, &Custom, rem; + Sub, &Custom, &Custom, sub; +); + +impl_assign_arith!( + AddAssign, Custom, Custom, add_assign; + DivAssign, Custom, Custom, div_assign; + MulAssign, Custom, Custom, mul_assign; + RemAssign, Custom, Custom, rem_assign; + SubAssign, Custom, Custom, sub_assign; + + AddAssign, Custom, &Custom, add_assign; + DivAssign, Custom, &Custom, div_assign; + MulAssign, Custom, &Custom, mul_assign; + RemAssign, Custom, &Custom, rem_assign; + SubAssign, Custom, &Custom, sub_assign; + + AddAssign, &Custom, Custom, add_assign; + DivAssign, &Custom, Custom, div_assign; + MulAssign, &Custom, Custom, mul_assign; + RemAssign, &Custom, Custom, rem_assign; + SubAssign, &Custom, Custom, sub_assign; + + AddAssign, &Custom, &Custom, add_assign; + DivAssign, &Custom, &Custom, div_assign; + MulAssign, &Custom, &Custom, mul_assign; + RemAssign, &Custom, &Custom, rem_assign; + SubAssign, &Custom, &Custom, sub_assign; ); +impl core::ops::Neg for Custom { + type Output = Custom; + fn neg(self) -> Self::Output { + todo!() + } +} +impl core::ops::Neg for &Custom { + type Output = Custom; + fn neg(self) -> Self::Output { + todo!() + } +} + pub fn association_with_structures_should_not_trigger_the_lint() { enum Foo { Bar = -2, @@ -125,6 +190,18 @@ pub fn non_overflowing_ops_or_ops_already_handled_by_the_compiler_should_not_tri _n *= &0; _n *= 1; _n *= &1; + _n += -0; + _n += &-0; + _n -= -0; + _n -= &-0; + _n /= -99; + _n /= &-99; + _n %= -99; + _n %= &-99; + _n *= -0; + _n *= &-0; + _n *= -1; + _n *= &-1; // Binary _n = _n + 0; @@ -158,8 +235,9 @@ pub fn non_overflowing_ops_or_ops_already_handled_by_the_compiler_should_not_tri _n = -&i32::MIN; } -pub fn runtime_ops() { +pub fn unknown_ops_or_runtime_ops_that_can_overflow() { let mut _n = i32::MAX; + let mut _custom = Custom; // Assign _n += 1; @@ -172,6 +250,36 @@ pub fn runtime_ops() { _n %= &0; _n *= 2; _n *= &2; + _n += -1; + _n += &-1; + _n -= -1; + _n -= &-1; + _n /= -0; + _n /= &-0; + _n %= -0; + _n %= &-0; + _n *= -2; + _n *= &-2; + _custom += Custom; + _custom += &Custom; + _custom -= Custom; + _custom -= &Custom; + _custom /= Custom; + _custom /= &Custom; + _custom %= Custom; + _custom %= &Custom; + _custom *= Custom; + _custom *= &Custom; + _custom += -Custom; + _custom += &-Custom; + _custom -= -Custom; + _custom -= &-Custom; + _custom /= -Custom; + _custom /= &-Custom; + _custom %= -Custom; + _custom %= &-Custom; + _custom *= -Custom; + _custom *= &-Custom; // Binary _n = _n + 1; @@ -193,36 +301,73 @@ pub fn runtime_ops() { _n = 23 + &85; _n = &23 + 85; _n = &23 + &85; - - // Custom - let _ = Custom + 0; - let _ = Custom + 1; - let _ = Custom + 2; - let _ = Custom + 0.0; - let _ = Custom + 1.0; - let _ = Custom + 2.0; - let _ = Custom - 0; - let _ = Custom - 1; - let _ = Custom - 2; - let _ = Custom - 0.0; - let _ = Custom - 1.0; - let _ = Custom - 2.0; - let _ = Custom / 0; - let _ = Custom / 1; - let _ = Custom / 2; - let _ = Custom / 0.0; - let _ = Custom / 1.0; - let _ = Custom / 2.0; - let _ = Custom * 0; - let _ = Custom * 1; - let _ = Custom * 2; - let _ = Custom * 0.0; - let _ = Custom * 1.0; - let _ = Custom * 2.0; + _custom = _custom + _custom; + _custom = _custom + &_custom; + _custom = Custom + _custom; + _custom = &Custom + _custom; + _custom = _custom - Custom; + _custom = _custom - &Custom; + _custom = Custom - _custom; + _custom = &Custom - _custom; + _custom = _custom / Custom; + _custom = _custom / &Custom; + _custom = _custom % Custom; + _custom = _custom % &Custom; + _custom = _custom * Custom; + _custom = _custom * &Custom; + _custom = Custom * _custom; + _custom = &Custom * _custom; + _custom = Custom + &Custom; + _custom = &Custom + Custom; + _custom = &Custom + &Custom; // Unary _n = -_n; _n = -&_n; + _custom = -_custom; + _custom = -&_custom; +} + +// Copied and pasted from the `integer_arithmetic` lint for comparison. +pub fn integer_arithmetic() { + let mut i = 1i32; + let mut var1 = 0i32; + let mut var2 = -1i32; + + 1 + i; + i * 2; + 1 % i / 2; + i - 2 + 2 - i; + -i; + i >> 1; + i << 1; + + -1; + -(-1); + + i & 1; + i | 1; + i ^ 1; + + i += 1; + i -= 1; + i *= 2; + i /= 2; + i /= 0; + i /= -1; + i /= var1; + i /= var2; + i %= 2; + i %= 0; + i %= -1; + i %= var1; + i %= var2; + i <<= 3; + i >>= 2; + + i |= 1; + i &= 1; + i ^= i; } fn main() {} diff --git a/tests/ui/arithmetic_side_effects.stderr b/tests/ui/arithmetic_side_effects.stderr index 9fe4b7cf28d8d..5e349f6b497cd 100644 --- a/tests/ui/arithmetic_side_effects.stderr +++ b/tests/ui/arithmetic_side_effects.stderr @@ -1,5 +1,5 @@ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:165:5 + --> $DIR/arithmetic_side_effects.rs:243:5 | LL | _n += 1; | ^^^^^^^ @@ -7,328 +7,592 @@ LL | _n += 1; = note: `-D clippy::arithmetic-side-effects` implied by `-D warnings` error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:166:5 + --> $DIR/arithmetic_side_effects.rs:244:5 | LL | _n += &1; | ^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:167:5 + --> $DIR/arithmetic_side_effects.rs:245:5 | LL | _n -= 1; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:168:5 + --> $DIR/arithmetic_side_effects.rs:246:5 | LL | _n -= &1; | ^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:169:5 + --> $DIR/arithmetic_side_effects.rs:247:5 | LL | _n /= 0; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:170:5 + --> $DIR/arithmetic_side_effects.rs:248:5 | LL | _n /= &0; | ^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:171:5 + --> $DIR/arithmetic_side_effects.rs:249:5 | LL | _n %= 0; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:172:5 + --> $DIR/arithmetic_side_effects.rs:250:5 | LL | _n %= &0; | ^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:173:5 + --> $DIR/arithmetic_side_effects.rs:251:5 | LL | _n *= 2; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:174:5 + --> $DIR/arithmetic_side_effects.rs:252:5 | LL | _n *= &2; | ^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:177:10 + --> $DIR/arithmetic_side_effects.rs:253:5 + | +LL | _n += -1; + | ^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:254:5 + | +LL | _n += &-1; + | ^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:255:5 + | +LL | _n -= -1; + | ^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:256:5 + | +LL | _n -= &-1; + | ^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:257:5 + | +LL | _n /= -0; + | ^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:258:5 + | +LL | _n /= &-0; + | ^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:259:5 + | +LL | _n %= -0; + | ^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:260:5 + | +LL | _n %= &-0; + | ^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:261:5 + | +LL | _n *= -2; + | ^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:262:5 + | +LL | _n *= &-2; + | ^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:263:5 + | +LL | _custom += Custom; + | ^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:264:5 + | +LL | _custom += &Custom; + | ^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:265:5 + | +LL | _custom -= Custom; + | ^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:266:5 + | +LL | _custom -= &Custom; + | ^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:267:5 + | +LL | _custom /= Custom; + | ^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:268:5 + | +LL | _custom /= &Custom; + | ^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:269:5 + | +LL | _custom %= Custom; + | ^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:270:5 + | +LL | _custom %= &Custom; + | ^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:271:5 + | +LL | _custom *= Custom; + | ^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:272:5 + | +LL | _custom *= &Custom; + | ^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:273:5 + | +LL | _custom += -Custom; + | ^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:274:5 + | +LL | _custom += &-Custom; + | ^^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:275:5 + | +LL | _custom -= -Custom; + | ^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:276:5 + | +LL | _custom -= &-Custom; + | ^^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:277:5 + | +LL | _custom /= -Custom; + | ^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:278:5 + | +LL | _custom /= &-Custom; + | ^^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:279:5 + | +LL | _custom %= -Custom; + | ^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:280:5 + | +LL | _custom %= &-Custom; + | ^^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:281:5 + | +LL | _custom *= -Custom; + | ^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:282:5 + | +LL | _custom *= &-Custom; + | ^^^^^^^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:285:10 | LL | _n = _n + 1; | ^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:178:10 + --> $DIR/arithmetic_side_effects.rs:286:10 | LL | _n = _n + &1; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:179:10 + --> $DIR/arithmetic_side_effects.rs:287:10 | LL | _n = 1 + _n; | ^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:180:10 + --> $DIR/arithmetic_side_effects.rs:288:10 | LL | _n = &1 + _n; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:181:10 + --> $DIR/arithmetic_side_effects.rs:289:10 | LL | _n = _n - 1; | ^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:182:10 + --> $DIR/arithmetic_side_effects.rs:290:10 | LL | _n = _n - &1; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:183:10 + --> $DIR/arithmetic_side_effects.rs:291:10 | LL | _n = 1 - _n; | ^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:184:10 + --> $DIR/arithmetic_side_effects.rs:292:10 | LL | _n = &1 - _n; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:185:10 + --> $DIR/arithmetic_side_effects.rs:293:10 | LL | _n = _n / 0; | ^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:186:10 + --> $DIR/arithmetic_side_effects.rs:294:10 | LL | _n = _n / &0; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:187:10 + --> $DIR/arithmetic_side_effects.rs:295:10 | LL | _n = _n % 0; | ^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:188:10 + --> $DIR/arithmetic_side_effects.rs:296:10 | LL | _n = _n % &0; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:189:10 + --> $DIR/arithmetic_side_effects.rs:297:10 | LL | _n = _n * 2; | ^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:190:10 + --> $DIR/arithmetic_side_effects.rs:298:10 | LL | _n = _n * &2; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:191:10 + --> $DIR/arithmetic_side_effects.rs:299:10 | LL | _n = 2 * _n; | ^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:192:10 + --> $DIR/arithmetic_side_effects.rs:300:10 | LL | _n = &2 * _n; | ^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:193:10 + --> $DIR/arithmetic_side_effects.rs:301:10 | LL | _n = 23 + &85; | ^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:194:10 + --> $DIR/arithmetic_side_effects.rs:302:10 | LL | _n = &23 + 85; | ^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:195:10 + --> $DIR/arithmetic_side_effects.rs:303:10 | LL | _n = &23 + &85; | ^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:198:13 + --> $DIR/arithmetic_side_effects.rs:304:15 | -LL | let _ = Custom + 0; - | ^^^^^^^^^^ +LL | _custom = _custom + _custom; + | ^^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:199:13 + --> $DIR/arithmetic_side_effects.rs:305:15 | -LL | let _ = Custom + 1; - | ^^^^^^^^^^ +LL | _custom = _custom + &_custom; + | ^^^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:200:13 + --> $DIR/arithmetic_side_effects.rs:306:15 | -LL | let _ = Custom + 2; - | ^^^^^^^^^^ +LL | _custom = Custom + _custom; + | ^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:201:13 + --> $DIR/arithmetic_side_effects.rs:307:15 | -LL | let _ = Custom + 0.0; - | ^^^^^^^^^^^^ +LL | _custom = &Custom + _custom; + | ^^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:202:13 + --> $DIR/arithmetic_side_effects.rs:308:15 | -LL | let _ = Custom + 1.0; - | ^^^^^^^^^^^^ +LL | _custom = _custom - Custom; + | ^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:203:13 + --> $DIR/arithmetic_side_effects.rs:309:15 | -LL | let _ = Custom + 2.0; - | ^^^^^^^^^^^^ +LL | _custom = _custom - &Custom; + | ^^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:204:13 + --> $DIR/arithmetic_side_effects.rs:310:15 | -LL | let _ = Custom - 0; - | ^^^^^^^^^^ +LL | _custom = Custom - _custom; + | ^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:205:13 + --> $DIR/arithmetic_side_effects.rs:311:15 | -LL | let _ = Custom - 1; - | ^^^^^^^^^^ +LL | _custom = &Custom - _custom; + | ^^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:206:13 + --> $DIR/arithmetic_side_effects.rs:312:15 | -LL | let _ = Custom - 2; - | ^^^^^^^^^^ +LL | _custom = _custom / Custom; + | ^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:207:13 + --> $DIR/arithmetic_side_effects.rs:313:15 | -LL | let _ = Custom - 0.0; - | ^^^^^^^^^^^^ +LL | _custom = _custom / &Custom; + | ^^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:208:13 + --> $DIR/arithmetic_side_effects.rs:314:15 | -LL | let _ = Custom - 1.0; - | ^^^^^^^^^^^^ +LL | _custom = _custom % Custom; + | ^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:209:13 + --> $DIR/arithmetic_side_effects.rs:315:15 | -LL | let _ = Custom - 2.0; - | ^^^^^^^^^^^^ +LL | _custom = _custom % &Custom; + | ^^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:210:13 + --> $DIR/arithmetic_side_effects.rs:316:15 | -LL | let _ = Custom / 0; - | ^^^^^^^^^^ +LL | _custom = _custom * Custom; + | ^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:211:13 + --> $DIR/arithmetic_side_effects.rs:317:15 | -LL | let _ = Custom / 1; - | ^^^^^^^^^^ +LL | _custom = _custom * &Custom; + | ^^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:212:13 + --> $DIR/arithmetic_side_effects.rs:318:15 | -LL | let _ = Custom / 2; - | ^^^^^^^^^^ +LL | _custom = Custom * _custom; + | ^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:213:13 + --> $DIR/arithmetic_side_effects.rs:319:15 | -LL | let _ = Custom / 0.0; - | ^^^^^^^^^^^^ +LL | _custom = &Custom * _custom; + | ^^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:214:13 + --> $DIR/arithmetic_side_effects.rs:320:15 | -LL | let _ = Custom / 1.0; - | ^^^^^^^^^^^^ +LL | _custom = Custom + &Custom; + | ^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:215:13 + --> $DIR/arithmetic_side_effects.rs:321:15 | -LL | let _ = Custom / 2.0; - | ^^^^^^^^^^^^ +LL | _custom = &Custom + Custom; + | ^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:216:13 + --> $DIR/arithmetic_side_effects.rs:322:15 | -LL | let _ = Custom * 0; - | ^^^^^^^^^^ +LL | _custom = &Custom + &Custom; + | ^^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:217:13 + --> $DIR/arithmetic_side_effects.rs:325:10 | -LL | let _ = Custom * 1; - | ^^^^^^^^^^ +LL | _n = -_n; + | ^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:218:13 + --> $DIR/arithmetic_side_effects.rs:326:10 | -LL | let _ = Custom * 2; - | ^^^^^^^^^^ +LL | _n = -&_n; + | ^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:219:13 + --> $DIR/arithmetic_side_effects.rs:327:15 | -LL | let _ = Custom * 0.0; - | ^^^^^^^^^^^^ +LL | _custom = -_custom; + | ^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:220:13 + --> $DIR/arithmetic_side_effects.rs:328:15 | -LL | let _ = Custom * 1.0; - | ^^^^^^^^^^^^ +LL | _custom = -&_custom; + | ^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:221:13 + --> $DIR/arithmetic_side_effects.rs:337:5 | -LL | let _ = Custom * 2.0; - | ^^^^^^^^^^^^ +LL | 1 + i; + | ^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:224:10 + --> $DIR/arithmetic_side_effects.rs:338:5 | -LL | _n = -_n; - | ^^^ +LL | i * 2; + | ^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> $DIR/arithmetic_side_effects.rs:225:10 + --> $DIR/arithmetic_side_effects.rs:340:5 | -LL | _n = -&_n; - | ^^^^ +LL | i - 2 + 2 - i; + | ^^^^^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:341:5 + | +LL | -i; + | ^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:342:5 + | +LL | i >> 1; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:343:5 + | +LL | i << 1; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:352:5 + | +LL | i += 1; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:353:5 + | +LL | i -= 1; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:354:5 + | +LL | i *= 2; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:356:5 + | +LL | i /= 0; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:358:5 + | +LL | i /= var1; + | ^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:359:5 + | +LL | i /= var2; + | ^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:361:5 + | +LL | i %= 0; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:363:5 + | +LL | i %= var1; + | ^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:364:5 + | +LL | i %= var2; + | ^^^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:365:5 + | +LL | i <<= 3; + | ^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:366:5 + | +LL | i >>= 2; + | ^^^^^^^ -error: aborting due to 55 previous errors +error: aborting due to 99 previous errors diff --git a/tests/ui/box_default.fixed b/tests/ui/box_default.fixed index 911fa856aa0a3..7e9f074fdcabd 100644 --- a/tests/ui/box_default.fixed +++ b/tests/ui/box_default.fixed @@ -21,16 +21,16 @@ macro_rules! outer { fn main() { let _string: Box = Box::default(); let _byte = Box::::default(); - let _vec = Box::>::default(); + let _vec = Box::>::default(); let _impl = Box::::default(); let _impl2 = Box::::default(); let _impl3: Box = Box::default(); let _own = Box::new(OwnDefault::default()); // should not lint - let _in_macro = outer!(Box::::default()); - let _string_default = outer!(Box::::default()); + let _in_macro = outer!(Box::::default()); + let _string_default = outer!(Box::::default()); let _vec2: Box> = Box::default(); let _vec3: Box> = Box::default(); - let _vec4: Box<_> = Box::>::default(); + let _vec4: Box<_> = Box::>::default(); let _more = ret_ty_fn(); call_ty_fn(Box::default()); } @@ -54,4 +54,14 @@ impl Read for ImplementsDefault { fn issue_9621_dyn_trait() { let _: Box = Box::::default(); + issue_10089(); +} + +fn issue_10089() { + let _closure = || { + #[derive(Default)] + struct WeirdPathed; + + let _ = Box::::default(); + }; } diff --git a/tests/ui/box_default.rs b/tests/ui/box_default.rs index 20019c2ee5a07..5c8d0b8354ccc 100644 --- a/tests/ui/box_default.rs +++ b/tests/ui/box_default.rs @@ -54,4 +54,14 @@ impl Read for ImplementsDefault { fn issue_9621_dyn_trait() { let _: Box = Box::new(ImplementsDefault::default()); + issue_10089(); +} + +fn issue_10089() { + let _closure = || { + #[derive(Default)] + struct WeirdPathed; + + let _ = Box::new(WeirdPathed::default()); + }; } diff --git a/tests/ui/box_default.stderr b/tests/ui/box_default.stderr index 5ea410331afb3..249eb340f96cb 100644 --- a/tests/ui/box_default.stderr +++ b/tests/ui/box_default.stderr @@ -16,7 +16,7 @@ error: `Box::new(_)` of default value --> $DIR/box_default.rs:24:16 | LL | let _vec = Box::new(Vec::::new()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::>::default()` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::>::default()` error: `Box::new(_)` of default value --> $DIR/box_default.rs:25:17 @@ -40,13 +40,13 @@ error: `Box::new(_)` of default value --> $DIR/box_default.rs:29:28 | LL | let _in_macro = outer!(Box::new(String::new())); - | ^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::::default()` + | ^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::::default()` error: `Box::new(_)` of default value --> $DIR/box_default.rs:30:34 | LL | let _string_default = outer!(Box::new(String::from(""))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::::default()` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::::default()` error: `Box::new(_)` of default value --> $DIR/box_default.rs:31:46 @@ -64,7 +64,7 @@ error: `Box::new(_)` of default value --> $DIR/box_default.rs:33:25 | LL | let _vec4: Box<_> = Box::new(Vec::from([false; 0])); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::>::default()` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::>::default()` error: `Box::new(_)` of default value --> $DIR/box_default.rs:35:16 @@ -84,5 +84,11 @@ error: `Box::new(_)` of default value LL | let _: Box = Box::new(ImplementsDefault::default()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::::default()` -error: aborting due to 14 previous errors +error: `Box::new(_)` of default value + --> $DIR/box_default.rs:65:17 + | +LL | let _ = Box::new(WeirdPathed::default()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::::default()` + +error: aborting due to 15 previous errors diff --git a/tests/ui/case_sensitive_file_extension_comparisons.fixed b/tests/ui/case_sensitive_file_extension_comparisons.fixed new file mode 100644 index 0000000000000..5fbaa64db39ed --- /dev/null +++ b/tests/ui/case_sensitive_file_extension_comparisons.fixed @@ -0,0 +1,67 @@ +// run-rustfix +#![warn(clippy::case_sensitive_file_extension_comparisons)] + +use std::string::String; + +struct TestStruct; + +impl TestStruct { + fn ends_with(self, _arg: &str) {} +} + +#[allow(dead_code)] +fn is_rust_file(filename: &str) -> bool { + std::path::Path::new(filename) + .extension() + .map_or(false, |ext| ext.eq_ignore_ascii_case("rs")) +} + +fn main() { + // std::string::String and &str should trigger the lint failure with .ext12 + let _ = std::path::Path::new(&String::new()) + .extension() + .map_or(false, |ext| ext.eq_ignore_ascii_case("ext12")); + let _ = std::path::Path::new("str") + .extension() + .map_or(false, |ext| ext.eq_ignore_ascii_case("ext12")); + + // The fixup should preserve the indentation level + { + let _ = std::path::Path::new("str") + .extension() + .map_or(false, |ext| ext.eq_ignore_ascii_case("ext12")); + } + + // The test struct should not trigger the lint failure with .ext12 + TestStruct {}.ends_with(".ext12"); + + // std::string::String and &str should trigger the lint failure with .EXT12 + let _ = std::path::Path::new(&String::new()) + .extension() + .map_or(false, |ext| ext.eq_ignore_ascii_case("EXT12")); + let _ = std::path::Path::new("str") + .extension() + .map_or(false, |ext| ext.eq_ignore_ascii_case("EXT12")); + + // Should not trigger the lint failure because of the calls to to_lowercase and to_uppercase + let _ = String::new().to_lowercase().ends_with(".EXT12"); + let _ = String::new().to_uppercase().ends_with(".EXT12"); + + // The test struct should not trigger the lint failure with .EXT12 + TestStruct {}.ends_with(".EXT12"); + + // Should not trigger the lint failure with .eXT12 + let _ = String::new().ends_with(".eXT12"); + let _ = "str".ends_with(".eXT12"); + TestStruct {}.ends_with(".eXT12"); + + // Should not trigger the lint failure with .EXT123 (too long) + let _ = String::new().ends_with(".EXT123"); + let _ = "str".ends_with(".EXT123"); + TestStruct {}.ends_with(".EXT123"); + + // Shouldn't fail if it doesn't start with a dot + let _ = String::new().ends_with("a.ext"); + let _ = "str".ends_with("a.extA"); + TestStruct {}.ends_with("a.ext"); +} diff --git a/tests/ui/case_sensitive_file_extension_comparisons.rs b/tests/ui/case_sensitive_file_extension_comparisons.rs index 6f0485b5279b1..3c0d4821f9f3a 100644 --- a/tests/ui/case_sensitive_file_extension_comparisons.rs +++ b/tests/ui/case_sensitive_file_extension_comparisons.rs @@ -1,3 +1,4 @@ +// run-rustfix #![warn(clippy::case_sensitive_file_extension_comparisons)] use std::string::String; @@ -5,9 +6,10 @@ use std::string::String; struct TestStruct; impl TestStruct { - fn ends_with(self, arg: &str) {} + fn ends_with(self, _arg: &str) {} } +#[allow(dead_code)] fn is_rust_file(filename: &str) -> bool { filename.ends_with(".rs") } @@ -17,6 +19,11 @@ fn main() { let _ = String::new().ends_with(".ext12"); let _ = "str".ends_with(".ext12"); + // The fixup should preserve the indentation level + { + let _ = "str".ends_with(".ext12"); + } + // The test struct should not trigger the lint failure with .ext12 TestStruct {}.ends_with(".ext12"); @@ -24,6 +31,10 @@ fn main() { let _ = String::new().ends_with(".EXT12"); let _ = "str".ends_with(".EXT12"); + // Should not trigger the lint failure because of the calls to to_lowercase and to_uppercase + let _ = String::new().to_lowercase().ends_with(".EXT12"); + let _ = String::new().to_uppercase().ends_with(".EXT12"); + // The test struct should not trigger the lint failure with .EXT12 TestStruct {}.ends_with(".EXT12"); diff --git a/tests/ui/case_sensitive_file_extension_comparisons.stderr b/tests/ui/case_sensitive_file_extension_comparisons.stderr index a28dd8bd5ad3f..44c8e3fdf7403 100644 --- a/tests/ui/case_sensitive_file_extension_comparisons.stderr +++ b/tests/ui/case_sensitive_file_extension_comparisons.stderr @@ -1,43 +1,87 @@ error: case-sensitive file extension comparison - --> $DIR/case_sensitive_file_extension_comparisons.rs:12:14 + --> $DIR/case_sensitive_file_extension_comparisons.rs:14:5 | LL | filename.ends_with(".rs") - | ^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider using a case-insensitive comparison instead = note: `-D clippy::case-sensitive-file-extension-comparisons` implied by `-D warnings` +help: use std::path::Path + | +LL ~ std::path::Path::new(filename) +LL + .extension() +LL + .map_or(false, |ext| ext.eq_ignore_ascii_case("rs")) + | error: case-sensitive file extension comparison - --> $DIR/case_sensitive_file_extension_comparisons.rs:17:27 + --> $DIR/case_sensitive_file_extension_comparisons.rs:19:13 | LL | let _ = String::new().ends_with(".ext12"); - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider using a case-insensitive comparison instead +help: use std::path::Path + | +LL ~ let _ = std::path::Path::new(&String::new()) +LL + .extension() +LL ~ .map_or(false, |ext| ext.eq_ignore_ascii_case("ext12")); + | error: case-sensitive file extension comparison - --> $DIR/case_sensitive_file_extension_comparisons.rs:18:19 + --> $DIR/case_sensitive_file_extension_comparisons.rs:20:13 | LL | let _ = "str".ends_with(".ext12"); - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider using a case-insensitive comparison instead +help: use std::path::Path + | +LL ~ let _ = std::path::Path::new("str") +LL + .extension() +LL ~ .map_or(false, |ext| ext.eq_ignore_ascii_case("ext12")); + | error: case-sensitive file extension comparison - --> $DIR/case_sensitive_file_extension_comparisons.rs:24:27 + --> $DIR/case_sensitive_file_extension_comparisons.rs:24:17 + | +LL | let _ = "str".ends_with(".ext12"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using a case-insensitive comparison instead +help: use std::path::Path + | +LL ~ let _ = std::path::Path::new("str") +LL + .extension() +LL ~ .map_or(false, |ext| ext.eq_ignore_ascii_case("ext12")); + | + +error: case-sensitive file extension comparison + --> $DIR/case_sensitive_file_extension_comparisons.rs:31:13 | LL | let _ = String::new().ends_with(".EXT12"); - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider using a case-insensitive comparison instead +help: use std::path::Path + | +LL ~ let _ = std::path::Path::new(&String::new()) +LL + .extension() +LL ~ .map_or(false, |ext| ext.eq_ignore_ascii_case("EXT12")); + | error: case-sensitive file extension comparison - --> $DIR/case_sensitive_file_extension_comparisons.rs:25:19 + --> $DIR/case_sensitive_file_extension_comparisons.rs:32:13 | LL | let _ = "str".ends_with(".EXT12"); - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider using a case-insensitive comparison instead +help: use std::path::Path + | +LL ~ let _ = std::path::Path::new("str") +LL + .extension() +LL ~ .map_or(false, |ext| ext.eq_ignore_ascii_case("EXT12")); + | -error: aborting due to 5 previous errors +error: aborting due to 6 previous errors diff --git a/tests/ui/clone_on_copy.stderr b/tests/ui/clone_on_copy.stderr index 42ae227777c70..862234d204be3 100644 --- a/tests/ui/clone_on_copy.stderr +++ b/tests/ui/clone_on_copy.stderr @@ -48,7 +48,7 @@ error: using `clone` on type `i32` which implements the `Copy` trait LL | vec.push(42.clone()); | ^^^^^^^^^^ help: try removing the `clone` call: `42` -error: using `clone` on type `std::option::Option` which implements the `Copy` trait +error: using `clone` on type `Option` which implements the `Copy` trait --> $DIR/clone_on_copy.rs:77:17 | LL | let value = opt.clone()?; // operator precedence needed (*opt)? diff --git a/tests/ui/dbg_macro.stderr b/tests/ui/dbg_macro.stderr index e6a65b46d975c..ddb5f1342e994 100644 --- a/tests/ui/dbg_macro.stderr +++ b/tests/ui/dbg_macro.stderr @@ -1,143 +1,143 @@ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:5:22 | LL | if let Some(n) = dbg!(n.checked_sub(4)) { n } else { n } | ^^^^^^^^^^^^^^^^^^^^^^ | = note: `-D clippy::dbg-macro` implied by `-D warnings` -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | if let Some(n) = n.checked_sub(4) { n } else { n } | ~~~~~~~~~~~~~~~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:9:8 | LL | if dbg!(n <= 1) { | ^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | if n <= 1 { | ~~~~~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:10:9 | LL | dbg!(1) | ^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | 1 | -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:12:9 | LL | dbg!(n * factorial(n - 1)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | n * factorial(n - 1) | -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:17:5 | LL | dbg!(42); | ^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | 42; | ~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:18:5 | LL | dbg!(dbg!(dbg!(42))); | ^^^^^^^^^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | dbg!(dbg!(42)); | ~~~~~~~~~~~~~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:19:14 | LL | foo(3) + dbg!(factorial(4)); | ^^^^^^^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | foo(3) + factorial(4); | ~~~~~~~~~~~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:20:5 | LL | dbg!(1, 2, dbg!(3, 4)); | ^^^^^^^^^^^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | (1, 2, dbg!(3, 4)); | ~~~~~~~~~~~~~~~~~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:21:5 | LL | dbg!(1, 2, 3, 4, 5); | ^^^^^^^^^^^^^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | (1, 2, 3, 4, 5); | ~~~~~~~~~~~~~~~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:41:9 | LL | dbg!(2); | ^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | 2; | ~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:47:5 | LL | dbg!(1); | ^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | 1; | ~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:52:5 | LL | dbg!(1); | ^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | 1; | ~ -error: `dbg!` macro is intended as a debugging tool +error: the `dbg!` macro is intended as a debugging tool --> $DIR/dbg_macro.rs:58:9 | LL | dbg!(1); | ^^^^^^^ | -help: ensure to avoid having uses of it in version control +help: remove the invocation before committing it to a version control system | LL | 1; | ~ diff --git a/tests/ui/default_trait_access.fixed b/tests/ui/default_trait_access.fixed index eedd43619392d..5640599d48ae8 100644 --- a/tests/ui/default_trait_access.fixed +++ b/tests/ui/default_trait_access.fixed @@ -12,17 +12,17 @@ use std::default::Default as D2; use std::string; fn main() { - let s1: String = std::string::String::default(); + let s1: String = String::default(); let s2 = String::default(); - let s3: String = std::string::String::default(); + let s3: String = String::default(); - let s4: String = std::string::String::default(); + let s4: String = String::default(); let s5 = string::String::default(); - let s6: String = std::string::String::default(); + let s6: String = String::default(); let s7 = std::string::String::default(); diff --git a/tests/ui/default_trait_access.stderr b/tests/ui/default_trait_access.stderr index 49b2dde3f1e8c..e4f73c08d190a 100644 --- a/tests/ui/default_trait_access.stderr +++ b/tests/ui/default_trait_access.stderr @@ -1,8 +1,8 @@ -error: calling `std::string::String::default()` is more clear than this expression +error: calling `String::default()` is more clear than this expression --> $DIR/default_trait_access.rs:15:22 | LL | let s1: String = Default::default(); - | ^^^^^^^^^^^^^^^^^^ help: try: `std::string::String::default()` + | ^^^^^^^^^^^^^^^^^^ help: try: `String::default()` | note: the lint level is defined here --> $DIR/default_trait_access.rs:3:9 @@ -10,23 +10,23 @@ note: the lint level is defined here LL | #![deny(clippy::default_trait_access)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: calling `std::string::String::default()` is more clear than this expression +error: calling `String::default()` is more clear than this expression --> $DIR/default_trait_access.rs:19:22 | LL | let s3: String = D2::default(); - | ^^^^^^^^^^^^^ help: try: `std::string::String::default()` + | ^^^^^^^^^^^^^ help: try: `String::default()` -error: calling `std::string::String::default()` is more clear than this expression +error: calling `String::default()` is more clear than this expression --> $DIR/default_trait_access.rs:21:22 | LL | let s4: String = std::default::Default::default(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `std::string::String::default()` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `String::default()` -error: calling `std::string::String::default()` is more clear than this expression +error: calling `String::default()` is more clear than this expression --> $DIR/default_trait_access.rs:25:22 | LL | let s6: String = default::Default::default(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `std::string::String::default()` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `String::default()` error: calling `GenericDerivedDefault::default()` is more clear than this expression --> $DIR/default_trait_access.rs:35:46 diff --git a/tests/ui/derivable_impls.fixed b/tests/ui/derivable_impls.fixed index 7dcdfb0937e89..ee8456f5deb8a 100644 --- a/tests/ui/derivable_impls.fixed +++ b/tests/ui/derivable_impls.fixed @@ -210,4 +210,25 @@ impl Default for IntOrString { } } +#[derive(Default)] +pub enum SimpleEnum { + Foo, + #[default] + Bar, +} + + + +pub enum NonExhaustiveEnum { + Foo, + #[non_exhaustive] + Bar, +} + +impl Default for NonExhaustiveEnum { + fn default() -> Self { + NonExhaustiveEnum::Bar + } +} + fn main() {} diff --git a/tests/ui/derivable_impls.rs b/tests/ui/derivable_impls.rs index 625cbcdde230a..14af419bcad14 100644 --- a/tests/ui/derivable_impls.rs +++ b/tests/ui/derivable_impls.rs @@ -244,4 +244,27 @@ impl Default for IntOrString { } } +pub enum SimpleEnum { + Foo, + Bar, +} + +impl Default for SimpleEnum { + fn default() -> Self { + SimpleEnum::Bar + } +} + +pub enum NonExhaustiveEnum { + Foo, + #[non_exhaustive] + Bar, +} + +impl Default for NonExhaustiveEnum { + fn default() -> Self { + NonExhaustiveEnum::Bar + } +} + fn main() {} diff --git a/tests/ui/derivable_impls.stderr b/tests/ui/derivable_impls.stderr index c1db5a58b1f51..81963c3be5b5d 100644 --- a/tests/ui/derivable_impls.stderr +++ b/tests/ui/derivable_impls.stderr @@ -113,5 +113,26 @@ help: ...and instead derive it LL | #[derive(Default)] | -error: aborting due to 7 previous errors +error: this `impl` can be derived + --> $DIR/derivable_impls.rs:252:1 + | +LL | / impl Default for SimpleEnum { +LL | | fn default() -> Self { +LL | | SimpleEnum::Bar +LL | | } +LL | | } + | |_^ + | + = help: remove the manual implementation... +help: ...and instead derive it... + | +LL | #[derive(Default)] + | +help: ...and mark the default variant + | +LL ~ #[default] +LL ~ Bar, + | + +error: aborting due to 8 previous errors diff --git a/tests/ui/derive.rs b/tests/ui/derive.rs index b276c384c04ea..6e0ce55f57d93 100644 --- a/tests/ui/derive.rs +++ b/tests/ui/derive.rs @@ -86,4 +86,15 @@ impl Clone for GenericRef<'_, T, U> { } } +// https://github.com/rust-lang/rust-clippy/issues/10188 +#[repr(packed)] +#[derive(Copy)] +struct Packed(T); + +impl Clone for Packed { + fn clone(&self) -> Self { + *self + } +} + fn main() {} diff --git a/tests/ui/derive_hash_xor_eq.stderr b/tests/ui/derive_hash_xor_eq.stderr deleted file mode 100644 index 16c92397804e5..0000000000000 --- a/tests/ui/derive_hash_xor_eq.stderr +++ /dev/null @@ -1,59 +0,0 @@ -error: you are deriving `Hash` but have implemented `PartialEq` explicitly - --> $DIR/derive_hash_xor_eq.rs:12:10 - | -LL | #[derive(Hash)] - | ^^^^ - | -note: `PartialEq` implemented here - --> $DIR/derive_hash_xor_eq.rs:15:1 - | -LL | impl PartialEq for Bar { - | ^^^^^^^^^^^^^^^^^^^^^^ - = note: `#[deny(clippy::derive_hash_xor_eq)]` on by default - = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: you are deriving `Hash` but have implemented `PartialEq` explicitly - --> $DIR/derive_hash_xor_eq.rs:21:10 - | -LL | #[derive(Hash)] - | ^^^^ - | -note: `PartialEq` implemented here - --> $DIR/derive_hash_xor_eq.rs:24:1 - | -LL | impl PartialEq for Baz { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: you are implementing `Hash` explicitly but have derived `PartialEq` - --> $DIR/derive_hash_xor_eq.rs:33:1 - | -LL | / impl std::hash::Hash for Bah { -LL | | fn hash(&self, _: &mut H) {} -LL | | } - | |_^ - | -note: `PartialEq` implemented here - --> $DIR/derive_hash_xor_eq.rs:30:10 - | -LL | #[derive(PartialEq)] - | ^^^^^^^^^ - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: you are implementing `Hash` explicitly but have derived `PartialEq` - --> $DIR/derive_hash_xor_eq.rs:51:5 - | -LL | / impl Hash for Foo3 { -LL | | fn hash(&self, _: &mut H) {} -LL | | } - | |_____^ - | -note: `PartialEq` implemented here - --> $DIR/derive_hash_xor_eq.rs:48:14 - | -LL | #[derive(PartialEq)] - | ^^^^^^^^^ - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: aborting due to 4 previous errors - diff --git a/tests/ui/derive_hash_xor_eq.rs b/tests/ui/derived_hash_with_manual_eq.rs similarity index 62% rename from tests/ui/derive_hash_xor_eq.rs rename to tests/ui/derived_hash_with_manual_eq.rs index 813ddc5664642..8ad09a8de43d5 100644 --- a/tests/ui/derive_hash_xor_eq.rs +++ b/tests/ui/derived_hash_with_manual_eq.rs @@ -27,6 +27,8 @@ impl PartialEq for Baz { } } +// Implementing `Hash` with a derived `PartialEq` is fine. See #2627 + #[derive(PartialEq)] struct Bah; @@ -34,23 +36,4 @@ impl std::hash::Hash for Bah { fn hash(&self, _: &mut H) {} } -#[derive(PartialEq)] -struct Foo2; - -trait Hash {} - -// We don't want to lint on user-defined traits called `Hash` -impl Hash for Foo2 {} - -mod use_hash { - use std::hash::{Hash, Hasher}; - - #[derive(PartialEq)] - struct Foo3; - - impl Hash for Foo3 { - fn hash(&self, _: &mut H) {} - } -} - fn main() {} diff --git a/tests/ui/derived_hash_with_manual_eq.stderr b/tests/ui/derived_hash_with_manual_eq.stderr new file mode 100644 index 0000000000000..230940f25fb60 --- /dev/null +++ b/tests/ui/derived_hash_with_manual_eq.stderr @@ -0,0 +1,29 @@ +error: you are deriving `Hash` but have implemented `PartialEq` explicitly + --> $DIR/derived_hash_with_manual_eq.rs:12:10 + | +LL | #[derive(Hash)] + | ^^^^ + | +note: `PartialEq` implemented here + --> $DIR/derived_hash_with_manual_eq.rs:15:1 + | +LL | impl PartialEq for Bar { + | ^^^^^^^^^^^^^^^^^^^^^^ + = note: `#[deny(clippy::derived_hash_with_manual_eq)]` on by default + = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: you are deriving `Hash` but have implemented `PartialEq` explicitly + --> $DIR/derived_hash_with_manual_eq.rs:21:10 + | +LL | #[derive(Hash)] + | ^^^^ + | +note: `PartialEq` implemented here + --> $DIR/derived_hash_with_manual_eq.rs:24:1 + | +LL | impl PartialEq for Baz { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 2 previous errors + diff --git a/tests/ui/drop_ref.rs b/tests/ui/drop_ref.rs index 7de0b0bbdf9ae..10044e65f1156 100644 --- a/tests/ui/drop_ref.rs +++ b/tests/ui/drop_ref.rs @@ -72,3 +72,26 @@ fn test_owl_result_2() -> Result { produce_half_owl_ok().map(drop)?; Ok(1) } + +#[allow(unused)] +#[allow(clippy::unit_cmp)] +fn issue10122(x: u8) { + // This is a function which returns a reference and has a side-effect, which means + // that calling drop() on the function is considered an idiomatic way of achieving the side-effect + // in a match arm. + fn println_and(t: &T) -> &T { + println!("foo"); + t + } + + match x { + 0 => drop(println_and(&12)), // Don't lint (copy type), we only care about side-effects + 1 => drop(println_and(&String::new())), // Don't lint (no copy type), we only care about side-effects + 2 => { + drop(println_and(&13)); // Lint, even if we only care about the side-effect, it's already in a block + }, + 3 if drop(println_and(&14)) == () => (), // Lint, idiomatic use is only in body of `Arm` + 4 => drop(&2), // Lint, not a fn/method call + _ => (), + } +} diff --git a/tests/ui/drop_ref.stderr b/tests/ui/drop_ref.stderr index 4743cf79b5d3c..293b9f6de832d 100644 --- a/tests/ui/drop_ref.stderr +++ b/tests/ui/drop_ref.stderr @@ -107,5 +107,41 @@ note: argument has type `&SomeStruct` LL | std::mem::drop(&SomeStruct); | ^^^^^^^^^^^ -error: aborting due to 9 previous errors +error: calls to `std::mem::drop` with a reference instead of an owned value. Dropping a reference does nothing + --> $DIR/drop_ref.rs:91:13 + | +LL | drop(println_and(&13)); // Lint, even if we only care about the side-effect, it's already in a block + | ^^^^^^^^^^^^^^^^^^^^^^ + | +note: argument has type `&i32` + --> $DIR/drop_ref.rs:91:18 + | +LL | drop(println_and(&13)); // Lint, even if we only care about the side-effect, it's already in a block + | ^^^^^^^^^^^^^^^^ + +error: calls to `std::mem::drop` with a reference instead of an owned value. Dropping a reference does nothing + --> $DIR/drop_ref.rs:93:14 + | +LL | 3 if drop(println_and(&14)) == () => (), // Lint, idiomatic use is only in body of `Arm` + | ^^^^^^^^^^^^^^^^^^^^^^ + | +note: argument has type `&i32` + --> $DIR/drop_ref.rs:93:19 + | +LL | 3 if drop(println_and(&14)) == () => (), // Lint, idiomatic use is only in body of `Arm` + | ^^^^^^^^^^^^^^^^ + +error: calls to `std::mem::drop` with a reference instead of an owned value. Dropping a reference does nothing + --> $DIR/drop_ref.rs:94:14 + | +LL | 4 => drop(&2), // Lint, not a fn/method call + | ^^^^^^^^ + | +note: argument has type `&i32` + --> $DIR/drop_ref.rs:94:19 + | +LL | 4 => drop(&2), // Lint, not a fn/method call + | ^^ + +error: aborting due to 12 previous errors diff --git a/tests/ui/field_reassign_with_default.rs b/tests/ui/field_reassign_with_default.rs index 7367910eaa126..1f989bb122052 100644 --- a/tests/ui/field_reassign_with_default.rs +++ b/tests/ui/field_reassign_with_default.rs @@ -247,3 +247,24 @@ mod issue6312 { } } } + +struct Collection { + items: Vec, + len: usize, +} + +impl Default for Collection { + fn default() -> Self { + Self { + items: vec![1, 2, 3], + len: 0, + } + } +} + +#[allow(clippy::redundant_closure_call)] +fn issue10136() { + let mut c = Collection::default(); + // don't lint, since c.items was used to calculate this value + c.len = (|| c.items.len())(); +} diff --git a/tests/ui/iter_kv_map.fixed b/tests/ui/iter_kv_map.fixed index 83fee04080fa7..f2a4c284cb16d 100644 --- a/tests/ui/iter_kv_map.fixed +++ b/tests/ui/iter_kv_map.fixed @@ -1,14 +1,15 @@ // run-rustfix #![warn(clippy::iter_kv_map)] -#![allow(clippy::redundant_clone)] -#![allow(clippy::suspicious_map)] -#![allow(clippy::map_identity)] +#![allow(unused_mut, clippy::redundant_clone, clippy::suspicious_map, clippy::map_identity)] use std::collections::{BTreeMap, HashMap}; fn main() { let get_key = |(key, _val)| key; + fn ref_acceptor(v: &u32) -> u32 { + *v + } let map: HashMap = HashMap::new(); @@ -36,6 +37,20 @@ fn main() { let _ = map.keys().map(|key| key * 9).count(); let _ = map.values().map(|value| value * 17).count(); + // Preserve the ref in the fix. + let _ = map.clone().into_values().map(|ref val| ref_acceptor(val)).count(); + + // Preserve the mut in the fix. + let _ = map + .clone().into_values().map(|mut val| { + val += 2; + val + }) + .count(); + + // Don't let a mut interfere. + let _ = map.clone().into_values().count(); + let map: BTreeMap = BTreeMap::new(); let _ = map.keys().collect::>(); @@ -61,4 +76,18 @@ fn main() { // Lint let _ = map.keys().map(|key| key * 9).count(); let _ = map.values().map(|value| value * 17).count(); + + // Preserve the ref in the fix. + let _ = map.clone().into_values().map(|ref val| ref_acceptor(val)).count(); + + // Preserve the mut in the fix. + let _ = map + .clone().into_values().map(|mut val| { + val += 2; + val + }) + .count(); + + // Don't let a mut interfere. + let _ = map.clone().into_values().count(); } diff --git a/tests/ui/iter_kv_map.rs b/tests/ui/iter_kv_map.rs index 7a1f1fb0198c7..ad6564df40846 100644 --- a/tests/ui/iter_kv_map.rs +++ b/tests/ui/iter_kv_map.rs @@ -1,14 +1,15 @@ // run-rustfix #![warn(clippy::iter_kv_map)] -#![allow(clippy::redundant_clone)] -#![allow(clippy::suspicious_map)] -#![allow(clippy::map_identity)] +#![allow(unused_mut, clippy::redundant_clone, clippy::suspicious_map, clippy::map_identity)] use std::collections::{BTreeMap, HashMap}; fn main() { let get_key = |(key, _val)| key; + fn ref_acceptor(v: &u32) -> u32 { + *v + } let map: HashMap = HashMap::new(); @@ -36,6 +37,22 @@ fn main() { let _ = map.iter().map(|(key, _value)| key * 9).count(); let _ = map.iter().map(|(_key, value)| value * 17).count(); + // Preserve the ref in the fix. + let _ = map.clone().into_iter().map(|(_, ref val)| ref_acceptor(val)).count(); + + // Preserve the mut in the fix. + let _ = map + .clone() + .into_iter() + .map(|(_, mut val)| { + val += 2; + val + }) + .count(); + + // Don't let a mut interfere. + let _ = map.clone().into_iter().map(|(_, mut val)| val).count(); + let map: BTreeMap = BTreeMap::new(); let _ = map.iter().map(|(key, _)| key).collect::>(); @@ -61,4 +78,20 @@ fn main() { // Lint let _ = map.iter().map(|(key, _value)| key * 9).count(); let _ = map.iter().map(|(_key, value)| value * 17).count(); + + // Preserve the ref in the fix. + let _ = map.clone().into_iter().map(|(_, ref val)| ref_acceptor(val)).count(); + + // Preserve the mut in the fix. + let _ = map + .clone() + .into_iter() + .map(|(_, mut val)| { + val += 2; + val + }) + .count(); + + // Don't let a mut interfere. + let _ = map.clone().into_iter().map(|(_, mut val)| val).count(); } diff --git a/tests/ui/iter_kv_map.stderr b/tests/ui/iter_kv_map.stderr index 9b9b04c97d81e..e00da223b4dd2 100644 --- a/tests/ui/iter_kv_map.stderr +++ b/tests/ui/iter_kv_map.stderr @@ -1,5 +1,5 @@ error: iterating on a map's keys - --> $DIR/iter_kv_map.rs:15:13 + --> $DIR/iter_kv_map.rs:16:13 | LL | let _ = map.iter().map(|(key, _)| key).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys()` @@ -7,130 +7,198 @@ LL | let _ = map.iter().map(|(key, _)| key).collect::>(); = note: `-D clippy::iter-kv-map` implied by `-D warnings` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:16:13 + --> $DIR/iter_kv_map.rs:17:13 | LL | let _ = map.iter().map(|(_, value)| value).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values()` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:17:13 + --> $DIR/iter_kv_map.rs:18:13 | LL | let _ = map.iter().map(|(_, v)| v + 2).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values().map(|v| v + 2)` error: iterating on a map's keys - --> $DIR/iter_kv_map.rs:19:13 + --> $DIR/iter_kv_map.rs:20:13 | LL | let _ = map.clone().into_iter().map(|(key, _)| key).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_keys()` error: iterating on a map's keys - --> $DIR/iter_kv_map.rs:20:13 + --> $DIR/iter_kv_map.rs:21:13 | LL | let _ = map.clone().into_iter().map(|(key, _)| key + 2).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_keys().map(|key| key + 2)` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:22:13 + --> $DIR/iter_kv_map.rs:23:13 | LL | let _ = map.clone().into_iter().map(|(_, val)| val).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values()` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:23:13 + --> $DIR/iter_kv_map.rs:24:13 | LL | let _ = map.clone().into_iter().map(|(_, val)| val + 2).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values().map(|val| val + 2)` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:25:13 + --> $DIR/iter_kv_map.rs:26:13 | LL | let _ = map.clone().iter().map(|(_, val)| val).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().values()` error: iterating on a map's keys - --> $DIR/iter_kv_map.rs:26:13 + --> $DIR/iter_kv_map.rs:27:13 | LL | let _ = map.iter().map(|(key, _)| key).filter(|x| *x % 2 == 0).count(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys()` error: iterating on a map's keys - --> $DIR/iter_kv_map.rs:36:13 + --> $DIR/iter_kv_map.rs:37:13 | LL | let _ = map.iter().map(|(key, _value)| key * 9).count(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys().map(|key| key * 9)` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:37:13 + --> $DIR/iter_kv_map.rs:38:13 | LL | let _ = map.iter().map(|(_key, value)| value * 17).count(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values().map(|value| value * 17)` -error: iterating on a map's keys +error: iterating on a map's values --> $DIR/iter_kv_map.rs:41:13 | +LL | let _ = map.clone().into_iter().map(|(_, ref val)| ref_acceptor(val)).count(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values().map(|ref val| ref_acceptor(val))` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:44:13 + | +LL | let _ = map + | _____________^ +LL | | .clone() +LL | | .into_iter() +LL | | .map(|(_, mut val)| { +LL | | val += 2; +LL | | val +LL | | }) + | |__________^ + | +help: try + | +LL ~ let _ = map +LL + .clone().into_values().map(|mut val| { +LL + val += 2; +LL + val +LL + }) + | + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:54:13 + | +LL | let _ = map.clone().into_iter().map(|(_, mut val)| val).count(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values()` + +error: iterating on a map's keys + --> $DIR/iter_kv_map.rs:58:13 + | LL | let _ = map.iter().map(|(key, _)| key).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys()` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:42:13 + --> $DIR/iter_kv_map.rs:59:13 | LL | let _ = map.iter().map(|(_, value)| value).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values()` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:43:13 + --> $DIR/iter_kv_map.rs:60:13 | LL | let _ = map.iter().map(|(_, v)| v + 2).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values().map(|v| v + 2)` error: iterating on a map's keys - --> $DIR/iter_kv_map.rs:45:13 + --> $DIR/iter_kv_map.rs:62:13 | LL | let _ = map.clone().into_iter().map(|(key, _)| key).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_keys()` error: iterating on a map's keys - --> $DIR/iter_kv_map.rs:46:13 + --> $DIR/iter_kv_map.rs:63:13 | LL | let _ = map.clone().into_iter().map(|(key, _)| key + 2).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_keys().map(|key| key + 2)` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:48:13 + --> $DIR/iter_kv_map.rs:65:13 | LL | let _ = map.clone().into_iter().map(|(_, val)| val).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values()` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:49:13 + --> $DIR/iter_kv_map.rs:66:13 | LL | let _ = map.clone().into_iter().map(|(_, val)| val + 2).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values().map(|val| val + 2)` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:51:13 + --> $DIR/iter_kv_map.rs:68:13 | LL | let _ = map.clone().iter().map(|(_, val)| val).collect::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().values()` error: iterating on a map's keys - --> $DIR/iter_kv_map.rs:52:13 + --> $DIR/iter_kv_map.rs:69:13 | LL | let _ = map.iter().map(|(key, _)| key).filter(|x| *x % 2 == 0).count(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys()` error: iterating on a map's keys - --> $DIR/iter_kv_map.rs:62:13 + --> $DIR/iter_kv_map.rs:79:13 | LL | let _ = map.iter().map(|(key, _value)| key * 9).count(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys().map(|key| key * 9)` error: iterating on a map's values - --> $DIR/iter_kv_map.rs:63:13 + --> $DIR/iter_kv_map.rs:80:13 | LL | let _ = map.iter().map(|(_key, value)| value * 17).count(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values().map(|value| value * 17)` -error: aborting due to 22 previous errors +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:83:13 + | +LL | let _ = map.clone().into_iter().map(|(_, ref val)| ref_acceptor(val)).count(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values().map(|ref val| ref_acceptor(val))` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:86:13 + | +LL | let _ = map + | _____________^ +LL | | .clone() +LL | | .into_iter() +LL | | .map(|(_, mut val)| { +LL | | val += 2; +LL | | val +LL | | }) + | |__________^ + | +help: try + | +LL ~ let _ = map +LL + .clone().into_values().map(|mut val| { +LL + val += 2; +LL + val +LL + }) + | + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:96:13 + | +LL | let _ = map.clone().into_iter().map(|(_, mut val)| val).count(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values()` + +error: aborting due to 28 previous errors diff --git a/tests/ui/needless_borrow.fixed b/tests/ui/needless_borrow.fixed index 31e1cb6c3d7f7..4cb7f6b687f11 100644 --- a/tests/ui/needless_borrow.fixed +++ b/tests/ui/needless_borrow.fixed @@ -1,5 +1,5 @@ // run-rustfix -#![feature(custom_inner_attributes, lint_reasons, rustc_private)] +#![feature(lint_reasons)] #![allow( unused, clippy::uninlined_format_args, @@ -491,14 +491,3 @@ mod issue_9782_method_variant { S.foo::<&[u8; 100]>(&a); } } - -extern crate rustc_lint; -extern crate rustc_span; - -#[allow(dead_code)] -mod span_lint { - use rustc_lint::{LateContext, Lint, LintContext}; - fn foo(cx: &LateContext<'_>, lint: &'static Lint) { - cx.struct_span_lint(lint, rustc_span::Span::default(), "", |diag| diag.note(String::new())); - } -} diff --git a/tests/ui/needless_borrow.rs b/tests/ui/needless_borrow.rs index 55c2738fcf273..9a01190ed8dbd 100644 --- a/tests/ui/needless_borrow.rs +++ b/tests/ui/needless_borrow.rs @@ -1,5 +1,5 @@ // run-rustfix -#![feature(custom_inner_attributes, lint_reasons, rustc_private)] +#![feature(lint_reasons)] #![allow( unused, clippy::uninlined_format_args, @@ -491,14 +491,3 @@ mod issue_9782_method_variant { S.foo::<&[u8; 100]>(&a); } } - -extern crate rustc_lint; -extern crate rustc_span; - -#[allow(dead_code)] -mod span_lint { - use rustc_lint::{LateContext, Lint, LintContext}; - fn foo(cx: &LateContext<'_>, lint: &'static Lint) { - cx.struct_span_lint(lint, rustc_span::Span::default(), "", |diag| diag.note(&String::new())); - } -} diff --git a/tests/ui/needless_borrow.stderr b/tests/ui/needless_borrow.stderr index 98a48d68317b4..d26c317124b8d 100644 --- a/tests/ui/needless_borrow.stderr +++ b/tests/ui/needless_borrow.stderr @@ -216,11 +216,5 @@ error: the borrowed expression implements the required traits LL | foo(&a); | ^^ help: change this to: `a` -error: the borrowed expression implements the required traits - --> $DIR/needless_borrow.rs:502:85 - | -LL | cx.struct_span_lint(lint, rustc_span::Span::default(), "", |diag| diag.note(&String::new())); - | ^^^^^^^^^^^^^^ help: change this to: `String::new()` - -error: aborting due to 37 previous errors +error: aborting due to 36 previous errors diff --git a/tests/ui/needless_return.fixed b/tests/ui/needless_return.fixed index d451be1f389a7..ab1c0e590bbc7 100644 --- a/tests/ui/needless_return.fixed +++ b/tests/ui/needless_return.fixed @@ -277,4 +277,14 @@ fn issue9947() -> Result<(), String> { do yeet "hello"; } +// without anyhow, but triggers the same bug I believe +#[expect(clippy::useless_format)] +fn issue10051() -> Result { + if true { + Ok(format!("ok!")) + } else { + Err(format!("err!")) + } +} + fn main() {} diff --git a/tests/ui/needless_return.rs b/tests/ui/needless_return.rs index e1a1bea2c0b85..abed338bb9b29 100644 --- a/tests/ui/needless_return.rs +++ b/tests/ui/needless_return.rs @@ -287,4 +287,14 @@ fn issue9947() -> Result<(), String> { do yeet "hello"; } +// without anyhow, but triggers the same bug I believe +#[expect(clippy::useless_format)] +fn issue10051() -> Result { + if true { + return Ok(format!("ok!")); + } else { + return Err(format!("err!")); + } +} + fn main() {} diff --git a/tests/ui/needless_return.stderr b/tests/ui/needless_return.stderr index ca2253e658637..52eabf6e1370d 100644 --- a/tests/ui/needless_return.stderr +++ b/tests/ui/needless_return.stderr @@ -386,5 +386,21 @@ LL | let _ = 42; return; | = help: remove `return` -error: aborting due to 46 previous errors +error: unneeded `return` statement + --> $DIR/needless_return.rs:294:9 + | +LL | return Ok(format!("ok!")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: remove `return` + +error: unneeded `return` statement + --> $DIR/needless_return.rs:296:9 + | +LL | return Err(format!("err!")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: remove `return` + +error: aborting due to 48 previous errors diff --git a/tests/ui/redundant_clone.fixed b/tests/ui/redundant_clone.fixed index a157b6a6f9adb..00b427450935d 100644 --- a/tests/ui/redundant_clone.fixed +++ b/tests/ui/redundant_clone.fixed @@ -239,9 +239,3 @@ fn false_negative_5707() { let _z = x.clone(); // pr 7346 can't lint on `x` drop(y); } - -#[allow(unused, clippy::manual_retain)] -fn possible_borrower_improvements() { - let mut s = String::from("foobar"); - s = s.chars().filter(|&c| c != 'o').collect(); -} diff --git a/tests/ui/redundant_clone.rs b/tests/ui/redundant_clone.rs index 430672e8b8df2..f899127db8d04 100644 --- a/tests/ui/redundant_clone.rs +++ b/tests/ui/redundant_clone.rs @@ -239,9 +239,3 @@ fn false_negative_5707() { let _z = x.clone(); // pr 7346 can't lint on `x` drop(y); } - -#[allow(unused, clippy::manual_retain)] -fn possible_borrower_improvements() { - let mut s = String::from("foobar"); - s = s.chars().filter(|&c| c != 'o').to_owned().collect(); -} diff --git a/tests/ui/redundant_clone.stderr b/tests/ui/redundant_clone.stderr index 1bacc2c76af15..782590034d051 100644 --- a/tests/ui/redundant_clone.stderr +++ b/tests/ui/redundant_clone.stderr @@ -179,17 +179,5 @@ note: this value is dropped without further use LL | foo(&x.clone(), move || { | ^ -error: redundant clone - --> $DIR/redundant_clone.rs:246:40 - | -LL | s = s.chars().filter(|&c| c != 'o').to_owned().collect(); - | ^^^^^^^^^^^ help: remove this - | -note: this value is dropped without further use - --> $DIR/redundant_clone.rs:246:9 - | -LL | s = s.chars().filter(|&c| c != 'o').to_owned().collect(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to 16 previous errors +error: aborting due to 15 previous errors diff --git a/tests/ui/rename.fixed b/tests/ui/rename.fixed index 2f76b57529607..5076f61334d67 100644 --- a/tests/ui/rename.fixed +++ b/tests/ui/rename.fixed @@ -10,6 +10,7 @@ #![allow(clippy::box_collection)] #![allow(clippy::redundant_static_lifetimes)] #![allow(clippy::cognitive_complexity)] +#![allow(clippy::derived_hash_with_manual_eq)] #![allow(clippy::disallowed_methods)] #![allow(clippy::disallowed_types)] #![allow(clippy::mixed_read_write_in_expression)] @@ -45,6 +46,7 @@ #![warn(clippy::box_collection)] #![warn(clippy::redundant_static_lifetimes)] #![warn(clippy::cognitive_complexity)] +#![warn(clippy::derived_hash_with_manual_eq)] #![warn(clippy::disallowed_methods)] #![warn(clippy::disallowed_types)] #![warn(clippy::mixed_read_write_in_expression)] diff --git a/tests/ui/rename.rs b/tests/ui/rename.rs index 699c0ff464e9f..64bc1ca7116c5 100644 --- a/tests/ui/rename.rs +++ b/tests/ui/rename.rs @@ -10,6 +10,7 @@ #![allow(clippy::box_collection)] #![allow(clippy::redundant_static_lifetimes)] #![allow(clippy::cognitive_complexity)] +#![allow(clippy::derived_hash_with_manual_eq)] #![allow(clippy::disallowed_methods)] #![allow(clippy::disallowed_types)] #![allow(clippy::mixed_read_write_in_expression)] @@ -45,6 +46,7 @@ #![warn(clippy::box_vec)] #![warn(clippy::const_static_lifetime)] #![warn(clippy::cyclomatic_complexity)] +#![warn(clippy::derive_hash_xor_eq)] #![warn(clippy::disallowed_method)] #![warn(clippy::disallowed_type)] #![warn(clippy::eval_order_dependence)] diff --git a/tests/ui/rename.stderr b/tests/ui/rename.stderr index 9af58dc75a68f..27a0263292ef1 100644 --- a/tests/ui/rename.stderr +++ b/tests/ui/rename.stderr @@ -1,5 +1,5 @@ error: lint `clippy::almost_complete_letter_range` has been renamed to `clippy::almost_complete_range` - --> $DIR/rename.rs:41:9 + --> $DIR/rename.rs:42:9 | LL | #![warn(clippy::almost_complete_letter_range)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::almost_complete_range` @@ -7,244 +7,250 @@ LL | #![warn(clippy::almost_complete_letter_range)] = note: `-D renamed-and-removed-lints` implied by `-D warnings` error: lint `clippy::blacklisted_name` has been renamed to `clippy::disallowed_names` - --> $DIR/rename.rs:42:9 + --> $DIR/rename.rs:43:9 | LL | #![warn(clippy::blacklisted_name)] | ^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::disallowed_names` error: lint `clippy::block_in_if_condition_expr` has been renamed to `clippy::blocks_in_if_conditions` - --> $DIR/rename.rs:43:9 + --> $DIR/rename.rs:44:9 | LL | #![warn(clippy::block_in_if_condition_expr)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::blocks_in_if_conditions` error: lint `clippy::block_in_if_condition_stmt` has been renamed to `clippy::blocks_in_if_conditions` - --> $DIR/rename.rs:44:9 + --> $DIR/rename.rs:45:9 | LL | #![warn(clippy::block_in_if_condition_stmt)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::blocks_in_if_conditions` error: lint `clippy::box_vec` has been renamed to `clippy::box_collection` - --> $DIR/rename.rs:45:9 + --> $DIR/rename.rs:46:9 | LL | #![warn(clippy::box_vec)] | ^^^^^^^^^^^^^^^ help: use the new name: `clippy::box_collection` error: lint `clippy::const_static_lifetime` has been renamed to `clippy::redundant_static_lifetimes` - --> $DIR/rename.rs:46:9 + --> $DIR/rename.rs:47:9 | LL | #![warn(clippy::const_static_lifetime)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::redundant_static_lifetimes` error: lint `clippy::cyclomatic_complexity` has been renamed to `clippy::cognitive_complexity` - --> $DIR/rename.rs:47:9 + --> $DIR/rename.rs:48:9 | LL | #![warn(clippy::cyclomatic_complexity)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::cognitive_complexity` +error: lint `clippy::derive_hash_xor_eq` has been renamed to `clippy::derived_hash_with_manual_eq` + --> $DIR/rename.rs:49:9 + | +LL | #![warn(clippy::derive_hash_xor_eq)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::derived_hash_with_manual_eq` + error: lint `clippy::disallowed_method` has been renamed to `clippy::disallowed_methods` - --> $DIR/rename.rs:48:9 + --> $DIR/rename.rs:50:9 | LL | #![warn(clippy::disallowed_method)] | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::disallowed_methods` error: lint `clippy::disallowed_type` has been renamed to `clippy::disallowed_types` - --> $DIR/rename.rs:49:9 + --> $DIR/rename.rs:51:9 | LL | #![warn(clippy::disallowed_type)] | ^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::disallowed_types` error: lint `clippy::eval_order_dependence` has been renamed to `clippy::mixed_read_write_in_expression` - --> $DIR/rename.rs:50:9 + --> $DIR/rename.rs:52:9 | LL | #![warn(clippy::eval_order_dependence)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::mixed_read_write_in_expression` error: lint `clippy::identity_conversion` has been renamed to `clippy::useless_conversion` - --> $DIR/rename.rs:51:9 + --> $DIR/rename.rs:53:9 | LL | #![warn(clippy::identity_conversion)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::useless_conversion` error: lint `clippy::if_let_some_result` has been renamed to `clippy::match_result_ok` - --> $DIR/rename.rs:52:9 + --> $DIR/rename.rs:54:9 | LL | #![warn(clippy::if_let_some_result)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::match_result_ok` error: lint `clippy::logic_bug` has been renamed to `clippy::overly_complex_bool_expr` - --> $DIR/rename.rs:53:9 + --> $DIR/rename.rs:55:9 | LL | #![warn(clippy::logic_bug)] | ^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::overly_complex_bool_expr` error: lint `clippy::new_without_default_derive` has been renamed to `clippy::new_without_default` - --> $DIR/rename.rs:54:9 + --> $DIR/rename.rs:56:9 | LL | #![warn(clippy::new_without_default_derive)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::new_without_default` error: lint `clippy::option_and_then_some` has been renamed to `clippy::bind_instead_of_map` - --> $DIR/rename.rs:55:9 + --> $DIR/rename.rs:57:9 | LL | #![warn(clippy::option_and_then_some)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::bind_instead_of_map` error: lint `clippy::option_expect_used` has been renamed to `clippy::expect_used` - --> $DIR/rename.rs:56:9 + --> $DIR/rename.rs:58:9 | LL | #![warn(clippy::option_expect_used)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::expect_used` error: lint `clippy::option_map_unwrap_or` has been renamed to `clippy::map_unwrap_or` - --> $DIR/rename.rs:57:9 + --> $DIR/rename.rs:59:9 | LL | #![warn(clippy::option_map_unwrap_or)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::map_unwrap_or` error: lint `clippy::option_map_unwrap_or_else` has been renamed to `clippy::map_unwrap_or` - --> $DIR/rename.rs:58:9 + --> $DIR/rename.rs:60:9 | LL | #![warn(clippy::option_map_unwrap_or_else)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::map_unwrap_or` error: lint `clippy::option_unwrap_used` has been renamed to `clippy::unwrap_used` - --> $DIR/rename.rs:59:9 + --> $DIR/rename.rs:61:9 | LL | #![warn(clippy::option_unwrap_used)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::unwrap_used` error: lint `clippy::ref_in_deref` has been renamed to `clippy::needless_borrow` - --> $DIR/rename.rs:60:9 + --> $DIR/rename.rs:62:9 | LL | #![warn(clippy::ref_in_deref)] | ^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::needless_borrow` error: lint `clippy::result_expect_used` has been renamed to `clippy::expect_used` - --> $DIR/rename.rs:61:9 + --> $DIR/rename.rs:63:9 | LL | #![warn(clippy::result_expect_used)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::expect_used` error: lint `clippy::result_map_unwrap_or_else` has been renamed to `clippy::map_unwrap_or` - --> $DIR/rename.rs:62:9 + --> $DIR/rename.rs:64:9 | LL | #![warn(clippy::result_map_unwrap_or_else)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::map_unwrap_or` error: lint `clippy::result_unwrap_used` has been renamed to `clippy::unwrap_used` - --> $DIR/rename.rs:63:9 + --> $DIR/rename.rs:65:9 | LL | #![warn(clippy::result_unwrap_used)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::unwrap_used` error: lint `clippy::single_char_push_str` has been renamed to `clippy::single_char_add_str` - --> $DIR/rename.rs:64:9 + --> $DIR/rename.rs:66:9 | LL | #![warn(clippy::single_char_push_str)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::single_char_add_str` error: lint `clippy::stutter` has been renamed to `clippy::module_name_repetitions` - --> $DIR/rename.rs:65:9 + --> $DIR/rename.rs:67:9 | LL | #![warn(clippy::stutter)] | ^^^^^^^^^^^^^^^ help: use the new name: `clippy::module_name_repetitions` error: lint `clippy::to_string_in_display` has been renamed to `clippy::recursive_format_impl` - --> $DIR/rename.rs:66:9 + --> $DIR/rename.rs:68:9 | LL | #![warn(clippy::to_string_in_display)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::recursive_format_impl` error: lint `clippy::zero_width_space` has been renamed to `clippy::invisible_characters` - --> $DIR/rename.rs:67:9 + --> $DIR/rename.rs:69:9 | LL | #![warn(clippy::zero_width_space)] | ^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::invisible_characters` error: lint `clippy::drop_bounds` has been renamed to `drop_bounds` - --> $DIR/rename.rs:68:9 + --> $DIR/rename.rs:70:9 | LL | #![warn(clippy::drop_bounds)] | ^^^^^^^^^^^^^^^^^^^ help: use the new name: `drop_bounds` error: lint `clippy::for_loop_over_option` has been renamed to `for_loops_over_fallibles` - --> $DIR/rename.rs:69:9 + --> $DIR/rename.rs:71:9 | LL | #![warn(clippy::for_loop_over_option)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `for_loops_over_fallibles` error: lint `clippy::for_loop_over_result` has been renamed to `for_loops_over_fallibles` - --> $DIR/rename.rs:70:9 + --> $DIR/rename.rs:72:9 | LL | #![warn(clippy::for_loop_over_result)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `for_loops_over_fallibles` error: lint `clippy::for_loops_over_fallibles` has been renamed to `for_loops_over_fallibles` - --> $DIR/rename.rs:71:9 + --> $DIR/rename.rs:73:9 | LL | #![warn(clippy::for_loops_over_fallibles)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `for_loops_over_fallibles` error: lint `clippy::into_iter_on_array` has been renamed to `array_into_iter` - --> $DIR/rename.rs:72:9 + --> $DIR/rename.rs:74:9 | LL | #![warn(clippy::into_iter_on_array)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `array_into_iter` error: lint `clippy::invalid_atomic_ordering` has been renamed to `invalid_atomic_ordering` - --> $DIR/rename.rs:73:9 + --> $DIR/rename.rs:75:9 | LL | #![warn(clippy::invalid_atomic_ordering)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `invalid_atomic_ordering` error: lint `clippy::invalid_ref` has been renamed to `invalid_value` - --> $DIR/rename.rs:74:9 + --> $DIR/rename.rs:76:9 | LL | #![warn(clippy::invalid_ref)] | ^^^^^^^^^^^^^^^^^^^ help: use the new name: `invalid_value` error: lint `clippy::let_underscore_drop` has been renamed to `let_underscore_drop` - --> $DIR/rename.rs:75:9 + --> $DIR/rename.rs:77:9 | LL | #![warn(clippy::let_underscore_drop)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `let_underscore_drop` error: lint `clippy::mem_discriminant_non_enum` has been renamed to `enum_intrinsics_non_enums` - --> $DIR/rename.rs:76:9 + --> $DIR/rename.rs:78:9 | LL | #![warn(clippy::mem_discriminant_non_enum)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `enum_intrinsics_non_enums` error: lint `clippy::panic_params` has been renamed to `non_fmt_panics` - --> $DIR/rename.rs:77:9 + --> $DIR/rename.rs:79:9 | LL | #![warn(clippy::panic_params)] | ^^^^^^^^^^^^^^^^^^^^ help: use the new name: `non_fmt_panics` error: lint `clippy::positional_named_format_parameters` has been renamed to `named_arguments_used_positionally` - --> $DIR/rename.rs:78:9 + --> $DIR/rename.rs:80:9 | LL | #![warn(clippy::positional_named_format_parameters)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `named_arguments_used_positionally` error: lint `clippy::temporary_cstring_as_ptr` has been renamed to `temporary_cstring_as_ptr` - --> $DIR/rename.rs:79:9 + --> $DIR/rename.rs:81:9 | LL | #![warn(clippy::temporary_cstring_as_ptr)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `temporary_cstring_as_ptr` error: lint `clippy::unknown_clippy_lints` has been renamed to `unknown_lints` - --> $DIR/rename.rs:80:9 + --> $DIR/rename.rs:82:9 | LL | #![warn(clippy::unknown_clippy_lints)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `unknown_lints` error: lint `clippy::unused_label` has been renamed to `unused_labels` - --> $DIR/rename.rs:81:9 + --> $DIR/rename.rs:83:9 | LL | #![warn(clippy::unused_label)] | ^^^^^^^^^^^^^^^^^^^^ help: use the new name: `unused_labels` -error: aborting due to 41 previous errors +error: aborting due to 42 previous errors diff --git a/tests/ui/single_element_loop.fixed b/tests/ui/single_element_loop.fixed index 63d31ff83f9b5..a0dcc0172e8b0 100644 --- a/tests/ui/single_element_loop.fixed +++ b/tests/ui/single_element_loop.fixed @@ -33,4 +33,31 @@ fn main() { let item = 0..5; dbg!(item); } + + // should not lint (issue #10018) + for e in [42] { + if e > 0 { + continue; + } + } + + // should not lint (issue #10018) + for e in [42] { + if e > 0 { + break; + } + } + + // should lint (issue #10018) + { + let _ = 42; + let _f = |n: u32| { + for i in 0..n { + if i > 10 { + dbg!(i); + break; + } + } + }; + } } diff --git a/tests/ui/single_element_loop.rs b/tests/ui/single_element_loop.rs index 2cda5a329d254..bc014035c98a5 100644 --- a/tests/ui/single_element_loop.rs +++ b/tests/ui/single_element_loop.rs @@ -27,4 +27,30 @@ fn main() { for item in [0..5].into_iter() { dbg!(item); } + + // should not lint (issue #10018) + for e in [42] { + if e > 0 { + continue; + } + } + + // should not lint (issue #10018) + for e in [42] { + if e > 0 { + break; + } + } + + // should lint (issue #10018) + for _ in [42] { + let _f = |n: u32| { + for i in 0..n { + if i > 10 { + dbg!(i); + break; + } + } + }; + } } diff --git a/tests/ui/single_element_loop.stderr b/tests/ui/single_element_loop.stderr index 0aeb8da1a2e23..14437a59745e0 100644 --- a/tests/ui/single_element_loop.stderr +++ b/tests/ui/single_element_loop.stderr @@ -95,5 +95,32 @@ LL + dbg!(item); LL + } | -error: aborting due to 6 previous errors +error: for loop over a single element + --> $DIR/single_element_loop.rs:46:5 + | +LL | / for _ in [42] { +LL | | let _f = |n: u32| { +LL | | for i in 0..n { +LL | | if i > 10 { +... | +LL | | }; +LL | | } + | |_____^ + | +help: try + | +LL ~ { +LL + let _ = 42; +LL + let _f = |n: u32| { +LL + for i in 0..n { +LL + if i > 10 { +LL + dbg!(i); +LL + break; +LL + } +LL + } +LL + }; +LL + } + | + +error: aborting due to 7 previous errors diff --git a/tests/ui/suspicious_to_owned.stderr b/tests/ui/suspicious_to_owned.stderr index ae1aec34d82e0..dec3f50d6f1b6 100644 --- a/tests/ui/suspicious_to_owned.stderr +++ b/tests/ui/suspicious_to_owned.stderr @@ -1,4 +1,4 @@ -error: this `to_owned` call clones the std::borrow::Cow<'_, str> itself and does not cause the std::borrow::Cow<'_, str> contents to become owned +error: this `to_owned` call clones the Cow<'_, str> itself and does not cause the Cow<'_, str> contents to become owned --> $DIR/suspicious_to_owned.rs:16:13 | LL | let _ = cow.to_owned(); @@ -6,19 +6,19 @@ LL | let _ = cow.to_owned(); | = note: `-D clippy::suspicious-to-owned` implied by `-D warnings` -error: this `to_owned` call clones the std::borrow::Cow<'_, [char; 3]> itself and does not cause the std::borrow::Cow<'_, [char; 3]> contents to become owned +error: this `to_owned` call clones the Cow<'_, [char; 3]> itself and does not cause the Cow<'_, [char; 3]> contents to become owned --> $DIR/suspicious_to_owned.rs:26:13 | LL | let _ = cow.to_owned(); | ^^^^^^^^^^^^^^ help: consider using, depending on intent: `cow.clone()` or `cow.into_owned()` -error: this `to_owned` call clones the std::borrow::Cow<'_, std::vec::Vec> itself and does not cause the std::borrow::Cow<'_, std::vec::Vec> contents to become owned +error: this `to_owned` call clones the Cow<'_, Vec> itself and does not cause the Cow<'_, Vec> contents to become owned --> $DIR/suspicious_to_owned.rs:36:13 | LL | let _ = cow.to_owned(); | ^^^^^^^^^^^^^^ help: consider using, depending on intent: `cow.clone()` or `cow.into_owned()` -error: this `to_owned` call clones the std::borrow::Cow<'_, str> itself and does not cause the std::borrow::Cow<'_, str> contents to become owned +error: this `to_owned` call clones the Cow<'_, str> itself and does not cause the Cow<'_, str> contents to become owned --> $DIR/suspicious_to_owned.rs:46:13 | LL | let _ = cow.to_owned(); diff --git a/tests/ui/unnecessary_clone.stderr b/tests/ui/unnecessary_clone.stderr index 94cc7777acacd..6022d9fa4c5c3 100644 --- a/tests/ui/unnecessary_clone.stderr +++ b/tests/ui/unnecessary_clone.stderr @@ -38,13 +38,13 @@ LL | t.clone(); | = note: `-D clippy::clone-on-copy` implied by `-D warnings` -error: using `clone` on type `std::option::Option` which implements the `Copy` trait +error: using `clone` on type `Option` which implements the `Copy` trait --> $DIR/unnecessary_clone.rs:42:5 | LL | Some(t).clone(); | ^^^^^^^^^^^^^^^ help: try removing the `clone` call: `Some(t)` -error: using `clone` on a double-reference; this will copy the reference of type `&std::vec::Vec` instead of cloning the inner type +error: using `clone` on a double-reference; this will copy the reference of type `&Vec` instead of cloning the inner type --> $DIR/unnecessary_clone.rs:48:22 | LL | let z: &Vec<_> = y.clone(); @@ -57,10 +57,10 @@ LL | let z: &Vec<_> = &(*y).clone(); | ~~~~~~~~~~~~~ help: or try being explicit if you are sure, that you want to clone a reference | -LL | let z: &Vec<_> = <&std::vec::Vec>::clone(y); - | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +LL | let z: &Vec<_> = <&Vec>::clone(y); + | ~~~~~~~~~~~~~~~~~~~~~ -error: using `clone` on type `many_derefs::E` which implements the `Copy` trait +error: using `clone` on type `E` which implements the `Copy` trait --> $DIR/unnecessary_clone.rs:84:20 | LL | let _: E = a.clone(); diff --git a/tests/ui/unused_self.rs b/tests/ui/unused_self.rs index 92e8e1dba69dd..55bd5607185c6 100644 --- a/tests/ui/unused_self.rs +++ b/tests/ui/unused_self.rs @@ -60,6 +60,16 @@ mod unused_self_allow { // shouldn't trigger for public methods pub fn unused_self_move(self) {} } + + pub struct E; + + impl E { + // shouldn't trigger if body contains todo!() + pub fn unused_self_todo(self) { + let x = 42; + todo!() + } + } } pub use unused_self_allow::D; diff --git a/tests/ui/unused_self.stderr b/tests/ui/unused_self.stderr index 23186122a9af7..919f9b6efdab8 100644 --- a/tests/ui/unused_self.stderr +++ b/tests/ui/unused_self.stderr @@ -4,7 +4,7 @@ error: unused `self` argument LL | fn unused_self_move(self) {} | ^^^^ | - = help: consider refactoring to a associated function + = help: consider refactoring to an associated function = note: `-D clippy::unused-self` implied by `-D warnings` error: unused `self` argument @@ -13,7 +13,7 @@ error: unused `self` argument LL | fn unused_self_ref(&self) {} | ^^^^^ | - = help: consider refactoring to a associated function + = help: consider refactoring to an associated function error: unused `self` argument --> $DIR/unused_self.rs:13:32 @@ -21,7 +21,7 @@ error: unused `self` argument LL | fn unused_self_mut_ref(&mut self) {} | ^^^^^^^^^ | - = help: consider refactoring to a associated function + = help: consider refactoring to an associated function error: unused `self` argument --> $DIR/unused_self.rs:14:32 @@ -29,7 +29,7 @@ error: unused `self` argument LL | fn unused_self_pin_ref(self: Pin<&Self>) {} | ^^^^ | - = help: consider refactoring to a associated function + = help: consider refactoring to an associated function error: unused `self` argument --> $DIR/unused_self.rs:15:36 @@ -37,7 +37,7 @@ error: unused `self` argument LL | fn unused_self_pin_mut_ref(self: Pin<&mut Self>) {} | ^^^^ | - = help: consider refactoring to a associated function + = help: consider refactoring to an associated function error: unused `self` argument --> $DIR/unused_self.rs:16:35 @@ -45,7 +45,7 @@ error: unused `self` argument LL | fn unused_self_pin_nested(self: Pin>) {} | ^^^^ | - = help: consider refactoring to a associated function + = help: consider refactoring to an associated function error: unused `self` argument --> $DIR/unused_self.rs:17:28 @@ -53,7 +53,7 @@ error: unused `self` argument LL | fn unused_self_box(self: Box) {} | ^^^^ | - = help: consider refactoring to a associated function + = help: consider refactoring to an associated function error: unused `self` argument --> $DIR/unused_self.rs:18:40 @@ -61,7 +61,7 @@ error: unused `self` argument LL | fn unused_with_other_used_args(&self, x: u8, y: u8) -> u8 { | ^^^^^ | - = help: consider refactoring to a associated function + = help: consider refactoring to an associated function error: unused `self` argument --> $DIR/unused_self.rs:21:37 @@ -69,7 +69,7 @@ error: unused `self` argument LL | fn unused_self_class_method(&self) { | ^^^^^ | - = help: consider refactoring to a associated function + = help: consider refactoring to an associated function error: aborting due to 9 previous errors From 298e160dc88dab90a83799973e121a18fed2ea38 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 12 Jan 2023 19:58:49 +0100 Subject: [PATCH 134/500] Assume there are no macros left in ast lowering. --- compiler/rustc_ast_lowering/src/format.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index f21c0f23bc114..693b9a399cfb4 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -334,13 +334,8 @@ fn may_contain_yield_point(e: &ast::Expr) -> bool { } fn visit_mac_call(&mut self, _: &ast::MacCall) { - self.0 = true; - } - - fn visit_attribute(&mut self, _: &ast::Attribute) { - // Conservatively assume this may be a proc macro attribute in - // expression position. - self.0 = true; + // Macros should be expanded at this point. + unreachable!("unexpanded macro in ast lowering"); } fn visit_item(&mut self, _: &ast::Item) { From 0a1934a32c51609be92259dca32af394087989d3 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 12 Jan 2023 19:59:03 +0100 Subject: [PATCH 135/500] Add FIXME comments about asm and format_args ast_pretty. --- compiler/rustc_ast_pretty/src/pprust/state/expr.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs index 03beae3a45bb1..500dc9da8aef8 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -527,10 +527,12 @@ impl<'a> State<'a> { } } ast::ExprKind::InlineAsm(a) => { + // FIXME: This should have its own syntax, distinct from a macro invocation. self.word("asm!"); self.print_inline_asm(a); } ast::ExprKind::FormatArgs(fmt) => { + // FIXME: This should have its own syntax, distinct from a macro invocation. self.word("format_args!"); self.popen(); self.rbox(0, Inconsistent); From 8a23ad17f8fa4f11335eb51215234af95cb9821d Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 12 Jan 2023 20:06:38 +0100 Subject: [PATCH 136/500] Update comments in rustc_ast_lowering/src/format.rs. --- compiler/rustc_ast_lowering/src/format.rs | 73 ++++++++++++++++------- 1 file changed, 51 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index 693b9a399cfb4..d5da1a666f90f 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -22,14 +22,19 @@ enum ArgumentType { Usize, } +/// Generate a hir expression representing an argument to a format_args invocation. +/// +/// Generates: +/// +/// ```text +/// ::new_…(arg) +/// ``` fn make_argument<'hir>( ctx: &mut LoweringContext<'_, 'hir>, sp: Span, arg: &'hir hir::Expr<'hir>, ty: ArgumentType, ) -> hir::Expr<'hir> { - // Generate: - // ::core::fmt::ArgumentV1::new_…(arg) use ArgumentType::*; use FormatTrait::*; let new_fn = ctx.arena.alloc(ctx.expr_lang_item_type_relative( @@ -51,14 +56,31 @@ fn make_argument<'hir>( ctx.expr_call_mut(sp, new_fn, std::slice::from_ref(arg)) } +/// Generate a hir expression for a format_args Count. +/// +/// Generates: +/// +/// ```text +/// ::Is(…) +/// ``` +/// +/// or +/// +/// ```text +/// ::Param(…) +/// ``` +/// +/// or +/// +/// ```text +/// ::Implied +/// ``` fn make_count<'hir>( ctx: &mut LoweringContext<'_, 'hir>, sp: Span, count: &Option, argmap: &mut FxIndexSet<(usize, ArgumentType)>, ) -> hir::Expr<'hir> { - // Generate: - // ::core::fmt::rt::v1::Count::…(…) match count { Some(FormatCount::Literal(n)) => { let count_is = ctx.arena.alloc(ctx.expr_lang_item_type_relative( @@ -87,21 +109,26 @@ fn make_count<'hir>( } } +/// Generate a hir expression for a format_args placeholder specification. +/// +/// Generates +/// +/// ```text +/// ::…, // alignment +/// …u32, // flags +/// , // width +/// , // precision +/// ) +/// ``` fn make_format_spec<'hir>( ctx: &mut LoweringContext<'_, 'hir>, sp: Span, placeholder: &FormatPlaceholder, argmap: &mut FxIndexSet<(usize, ArgumentType)>, ) -> hir::Expr<'hir> { - // Generate: - // ::core::fmt::rt::v1::Argument::new( - // 0usize, // position - // ' ', // fill - // ::core::fmt::rt::v1::Alignment::Unknown, - // 0u32, // flags - // ::core::fmt::rt::v1::Count::Implied, // width - // ::core::fmt::rt::v1::Count::Implied, // precision - // ) let position = match placeholder.argument.index { Ok(arg_index) => { let (i, _) = @@ -203,9 +230,10 @@ fn expand_format_args<'hir>( let args = if use_simple_array { // Generate: // &[ - // ::core::fmt::ArgumentV1::new_display(&arg0), - // ::core::fmt::ArgumentV1::new_lower_hex(&arg1), - // ::core::fmt::ArgumentV1::new_debug(&arg2), + // ::new_display(&arg0), + // ::new_lower_hex(&arg1), + // ::new_debug(&arg2), + // … // ] let elements: Vec<_> = arguments .iter() @@ -223,11 +251,12 @@ fn expand_format_args<'hir>( ctx.expr_array_ref(macsp, ctx.arena.alloc_from_iter(elements)) } else { // Generate: - // &match (&arg0, &arg1, &arg2) { + // &match (&arg0, &arg1, &…) { // args => [ - // ::core::fmt::ArgumentV1::new_display(args.0), - // ::core::fmt::ArgumentV1::new_lower_hex(args.1), - // ::core::fmt::ArgumentV1::new_debug(args.0), + // ::new_display(args.0), + // ::new_lower_hex(args.1), + // ::new_debug(args.0), + // … // ] // } let args_ident = Ident::new(sym::args, macsp); @@ -277,7 +306,7 @@ fn expand_format_args<'hir>( if let Some(format_options) = format_options { // Generate: - // ::core::fmt::Arguments::new_v1_formatted( + // ::new_v1_formatted( // lit_pieces, // args, // format_options, @@ -307,7 +336,7 @@ fn expand_format_args<'hir>( hir::ExprKind::Call(new_v1_formatted, args) } else { // Generate: - // ::core::fmt::Arguments::new_v1( + // ::new_v1( // lit_pieces, // args, // ) From cd8ec6c787e147667e3bf43145873dd8e27755d0 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 12 Jan 2023 20:14:31 +0100 Subject: [PATCH 137/500] Add note on optimization in format args ast lowering. --- compiler/rustc_ast_lowering/src/format.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index d5da1a666f90f..8985f8ad85daf 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -223,6 +223,9 @@ fn expand_format_args<'hir>( // in order, we can use a simple array instead of a `match` construction. // However, if there's a yield point in any argument except the first one, // we don't do this, because an ArgumentV1 cannot be kept across yield points. + // + // This is an optimization, speeding up compilation about 1-2% in some cases. + // See https://perf.rust-lang.org/compare.html?start=5dbee4d3a6728eb4530fb66c9775834438ecec74&end=e36affffe97378a0027b4bcfbb18d27356164ed0&stat=instructions:u let use_simple_array = argmap.len() == arguments.len() && argmap.iter().enumerate().all(|(i, &(j, _))| i == j) && arguments.iter().skip(1).all(|arg| !may_contain_yield_point(&arg.expr)); From b38848d8f740a7ada6b2ba14acf08c5e57c94002 Mon Sep 17 00:00:00 2001 From: Jason Newcomb Date: Thu, 12 Jan 2023 13:00:03 -0500 Subject: [PATCH 138/500] Fix suggestion in `transmutes_expressible_as_ptr_casts` when the source type is a borrow. --- clippy_lints/src/transmute/mod.rs | 7 ++- .../transmutes_expressible_as_ptr_casts.rs | 58 ++++++++++++------- clippy_lints/src/transmute/utils.rs | 24 ++------ .../transmutes_expressible_as_ptr_casts.fixed | 2 + .../ui/transmutes_expressible_as_ptr_casts.rs | 2 + ...transmutes_expressible_as_ptr_casts.stderr | 10 +++- 6 files changed, 60 insertions(+), 43 deletions(-) diff --git a/clippy_lints/src/transmute/mod.rs b/clippy_lints/src/transmute/mod.rs index 691d759d7739d..c0d290b5adc42 100644 --- a/clippy_lints/src/transmute/mod.rs +++ b/clippy_lints/src/transmute/mod.rs @@ -479,7 +479,10 @@ impl<'tcx> LateLintPass<'tcx> for Transmute { // - char conversions (https://github.com/rust-lang/rust/issues/89259) let const_context = in_constant(cx, e.hir_id); - let from_ty = cx.typeck_results().expr_ty_adjusted(arg); + let (from_ty, from_ty_adjusted) = match cx.typeck_results().expr_adjustments(arg) { + [] => (cx.typeck_results().expr_ty(arg), false), + [.., a] => (a.target, true), + }; // Adjustments for `to_ty` happen after the call to `transmute`, so don't use them. let to_ty = cx.typeck_results().expr_ty(e); @@ -506,7 +509,7 @@ impl<'tcx> LateLintPass<'tcx> for Transmute { ); if !linted { - transmutes_expressible_as_ptr_casts::check(cx, e, from_ty, to_ty, arg); + transmutes_expressible_as_ptr_casts::check(cx, e, from_ty, from_ty_adjusted, to_ty, arg); } } } diff --git a/clippy_lints/src/transmute/transmutes_expressible_as_ptr_casts.rs b/clippy_lints/src/transmute/transmutes_expressible_as_ptr_casts.rs index b79d4e915a271..8530b43243fa3 100644 --- a/clippy_lints/src/transmute/transmutes_expressible_as_ptr_casts.rs +++ b/clippy_lints/src/transmute/transmutes_expressible_as_ptr_casts.rs @@ -1,11 +1,11 @@ -use super::utils::can_be_expressed_as_pointer_cast; +use super::utils::check_cast; use super::TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS; -use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::sugg; +use clippy_utils::diagnostics::span_lint_and_sugg; +use clippy_utils::sugg::Sugg; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; -use rustc_middle::ty::Ty; +use rustc_middle::ty::{cast::CastKind, Ty}; /// Checks for `transmutes_expressible_as_ptr_casts` lint. /// Returns `true` if it's triggered, otherwise returns `false`. @@ -13,24 +13,40 @@ pub(super) fn check<'tcx>( cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, + from_ty_adjusted: bool, to_ty: Ty<'tcx>, arg: &'tcx Expr<'_>, ) -> bool { - if can_be_expressed_as_pointer_cast(cx, e, from_ty, to_ty) { - span_lint_and_then( - cx, - TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS, - e.span, - &format!("transmute from `{from_ty}` to `{to_ty}` which could be expressed as a pointer cast instead"), - |diag| { - if let Some(arg) = sugg::Sugg::hir_opt(cx, arg) { - let sugg = arg.as_ty(to_ty.to_string()).to_string(); - diag.span_suggestion(e.span, "try", sugg, Applicability::MachineApplicable); - } - }, - ); - true - } else { - false - } + use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast}; + let mut app = Applicability::MachineApplicable; + let sugg = match check_cast(cx, e, from_ty, to_ty) { + Some(PtrPtrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast) => { + Sugg::hir_with_context(cx, arg, e.span.ctxt(), "..", &mut app) + .as_ty(to_ty.to_string()) + .to_string() + }, + Some(PtrAddrCast) if !from_ty_adjusted => Sugg::hir_with_context(cx, arg, e.span.ctxt(), "..", &mut app) + .as_ty(to_ty.to_string()) + .to_string(), + + // The only adjustments here would be ref-to-ptr and unsize coercions. The result of an unsize coercions can't + // be transmuted to a usize. For ref-to-ptr coercions, borrows need to be cast to a pointer before being cast to + // a usize. + Some(PtrAddrCast) => format!( + "{} as {to_ty}", + Sugg::hir_with_context(cx, arg, e.span.ctxt(), "..", &mut app).as_ty(from_ty) + ), + _ => return false, + }; + + span_lint_and_sugg( + cx, + TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS, + e.span, + &format!("transmute from `{from_ty}` to `{to_ty}` which could be expressed as a pointer cast instead"), + "try", + sugg, + app, + ); + true } diff --git a/clippy_lints/src/transmute/utils.rs b/clippy_lints/src/transmute/utils.rs index 49d863ec03f1d..c93f047f5da26 100644 --- a/clippy_lints/src/transmute/utils.rs +++ b/clippy_lints/src/transmute/utils.rs @@ -20,28 +20,16 @@ pub(super) fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx } } -/// Check if the type conversion can be expressed as a pointer cast, instead of -/// a transmute. In certain cases, including some invalid casts from array -/// references to pointers, this may cause additional errors to be emitted and/or -/// ICE error messages. This function will panic if that occurs. -pub(super) fn can_be_expressed_as_pointer_cast<'tcx>( - cx: &LateContext<'tcx>, - e: &'tcx Expr<'_>, - from_ty: Ty<'tcx>, - to_ty: Ty<'tcx>, -) -> bool { - use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast}; - matches!( - check_cast(cx, e, from_ty, to_ty), - Some(PtrPtrCast | PtrAddrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast) - ) -} - /// If a cast from `from_ty` to `to_ty` is valid, returns an Ok containing the kind of /// the cast. In certain cases, including some invalid casts from array references /// to pointers, this may cause additional errors to be emitted and/or ICE error /// messages. This function will panic if that occurs. -fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option { +pub(super) fn check_cast<'tcx>( + cx: &LateContext<'tcx>, + e: &'tcx Expr<'_>, + from_ty: Ty<'tcx>, + to_ty: Ty<'tcx>, +) -> Option { let hir_id = e.hir_id; let local_def_id = hir_id.owner.def_id; diff --git a/tests/ui/transmutes_expressible_as_ptr_casts.fixed b/tests/ui/transmutes_expressible_as_ptr_casts.fixed index 7263abac15dfb..55307506eb3c7 100644 --- a/tests/ui/transmutes_expressible_as_ptr_casts.fixed +++ b/tests/ui/transmutes_expressible_as_ptr_casts.fixed @@ -51,6 +51,8 @@ fn main() { // e is a function pointer type and U is an integer; fptr-addr-cast let _usize_from_fn_ptr_transmute = unsafe { foo as usize }; let _usize_from_fn_ptr = foo as *const usize; + + let _usize_from_ref = unsafe { &1u32 as *const u32 as usize }; } // If a ref-to-ptr cast of this form where the pointer type points to a type other diff --git a/tests/ui/transmutes_expressible_as_ptr_casts.rs b/tests/ui/transmutes_expressible_as_ptr_casts.rs index d8e4421d4c18e..e7360f3f9dcba 100644 --- a/tests/ui/transmutes_expressible_as_ptr_casts.rs +++ b/tests/ui/transmutes_expressible_as_ptr_casts.rs @@ -51,6 +51,8 @@ fn main() { // e is a function pointer type and U is an integer; fptr-addr-cast let _usize_from_fn_ptr_transmute = unsafe { transmute:: u8, usize>(foo) }; let _usize_from_fn_ptr = foo as *const usize; + + let _usize_from_ref = unsafe { transmute::<*const u32, usize>(&1u32) }; } // If a ref-to-ptr cast of this form where the pointer type points to a type other diff --git a/tests/ui/transmutes_expressible_as_ptr_casts.stderr b/tests/ui/transmutes_expressible_as_ptr_casts.stderr index de9418c8d1adc..e862fcb67a4a0 100644 --- a/tests/ui/transmutes_expressible_as_ptr_casts.stderr +++ b/tests/ui/transmutes_expressible_as_ptr_casts.stderr @@ -46,11 +46,17 @@ error: transmute from `fn(usize) -> u8` to `usize` which could be expressed as a LL | let _usize_from_fn_ptr_transmute = unsafe { transmute:: u8, usize>(foo) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `foo as usize` +error: transmute from `*const u32` to `usize` which could be expressed as a pointer cast instead + --> $DIR/transmutes_expressible_as_ptr_casts.rs:55:36 + | +LL | let _usize_from_ref = unsafe { transmute::<*const u32, usize>(&1u32) }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&1u32 as *const u32 as usize` + error: transmute from a reference to a pointer - --> $DIR/transmutes_expressible_as_ptr_casts.rs:64:14 + --> $DIR/transmutes_expressible_as_ptr_casts.rs:66:14 | LL | unsafe { transmute::<&[i32; 1], *const u8>(in_param) } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `in_param as *const [i32; 1] as *const u8` -error: aborting due to 8 previous errors +error: aborting due to 9 previous errors From 2253646395c70c525368c29399fb4bb91fb95438 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 8 Jan 2023 23:27:22 +0000 Subject: [PATCH 139/500] Don't suggest dyn as parameter to add --- tests/ui/crashes/ice-6252.stderr | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/ui/crashes/ice-6252.stderr b/tests/ui/crashes/ice-6252.stderr index 638e4a5484932..efdd56dd47d39 100644 --- a/tests/ui/crashes/ice-6252.stderr +++ b/tests/ui/crashes/ice-6252.stderr @@ -17,9 +17,12 @@ error[E0412]: cannot find type `VAL` in this scope --> $DIR/ice-6252.rs:10:63 | LL | impl TypeVal for Multiply where N: TypeVal {} - | - ^^^ not found in this scope - | | - | help: you might be missing a type parameter: `, VAL` + | ^^^ not found in this scope + | +help: you might be missing a type parameter + | +LL | impl TypeVal for Multiply where N: TypeVal {} + | +++++ error[E0046]: not all trait items implemented, missing: `VAL` --> $DIR/ice-6252.rs:10:1 From 295225e9cdb69fa29986cd07d38fd54a16ca2aa0 Mon Sep 17 00:00:00 2001 From: Alex Macleod Date: Fri, 13 Jan 2023 00:04:28 +0000 Subject: [PATCH 140/500] Move `unchecked_duration_subtraction` to pedantic --- clippy_lints/src/instant_subtraction.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/instant_subtraction.rs b/clippy_lints/src/instant_subtraction.rs index dd1b23e7d9d29..9f6e89405713c 100644 --- a/clippy_lints/src/instant_subtraction.rs +++ b/clippy_lints/src/instant_subtraction.rs @@ -61,7 +61,7 @@ declare_clippy_lint! { /// [`Instant::now()`]: std::time::Instant::now; #[clippy::version = "1.65.0"] pub UNCHECKED_DURATION_SUBTRACTION, - suspicious, + pedantic, "finds unchecked subtraction of a 'Duration' from an 'Instant'" } From fcbc12eae35296841b0ddd3bacbb43e1d0ae654e Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Thu, 12 Jan 2023 22:39:25 -0800 Subject: [PATCH 141/500] Implement `signum` with `Ord` --- library/core/src/num/int_macros.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index 21518a3f55180..ba89553f65a81 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -2574,12 +2574,13 @@ macro_rules! int_impl { #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline(always)] + #[rustc_allow_const_fn_unstable(const_cmp)] pub const fn signum(self) -> Self { - match self { - n if n > 0 => 1, - 0 => 0, - _ => -1, - } + // Picking the right way to phrase this is complicated + // () + // so delegate it to `Ord` which is already producing -1/0/+1 + // exactly like we need and can be the place to deal with the complexity. + self.cmp(&0) as _ } /// Returns `true` if `self` is positive and `false` if the number is zero or From dbfbb29717dbaf94b3e83a30e4b9104241471dca Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 11:41:40 +0000 Subject: [PATCH 142/500] Move LLVM simple-raytracer build to ./y.rs bench cc #1290 --- build_system/bench.rs | 20 +++++++++++++++++++- build_system/prepare.rs | 18 ++---------------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/build_system/bench.rs b/build_system/bench.rs index 0ad8863223de6..e0956cb44bad3 100644 --- a/build_system/bench.rs +++ b/build_system/bench.rs @@ -5,7 +5,7 @@ use std::path::Path; use super::path::{Dirs, RelPath}; use super::prepare::GitRepo; use super::rustc_info::{get_file_name, get_wrapper_file_name}; -use super::utils::{hyperfine_command, is_ci, spawn_and_wait, CargoProject}; +use super::utils::{hyperfine_command, is_ci, spawn_and_wait, CargoProject, Compiler}; pub(crate) static SIMPLE_RAYTRACER_REPO: GitRepo = GitRepo::github( "ebobby", @@ -14,6 +14,10 @@ pub(crate) static SIMPLE_RAYTRACER_REPO: GitRepo = GitRepo::github( "", ); +// Use a separate target dir for the initial LLVM build to reduce unnecessary recompiles +pub(crate) static SIMPLE_RAYTRACER_LLVM: CargoProject = + CargoProject::new(&SIMPLE_RAYTRACER_REPO.source_dir(), "simple_raytracer_llvm"); + pub(crate) static SIMPLE_RAYTRACER: CargoProject = CargoProject::new(&SIMPLE_RAYTRACER_REPO.source_dir(), "simple_raytracer"); @@ -28,6 +32,20 @@ fn benchmark_simple_raytracer(dirs: &Dirs) { std::process::exit(1); } + eprintln!("[LLVM BUILD] simple-raytracer"); + let host_compiler = Compiler::host(); + let build_cmd = SIMPLE_RAYTRACER_LLVM.build(&host_compiler, dirs); + spawn_and_wait(build_cmd); + fs::copy( + SIMPLE_RAYTRACER_LLVM + .target_dir(dirs) + .join(&host_compiler.triple) + .join("debug") + .join(get_file_name("main", "bin")), + RelPath::BUILD.to_path(dirs).join(get_file_name("raytracer_cg_llvm", "bin")), + ) + .unwrap(); + let run_runs = env::var("RUN_RUNS") .unwrap_or(if is_ci() { "2" } else { "10" }.to_string()) .parse() diff --git a/build_system/prepare.rs b/build_system/prepare.rs index 106b06296b4b9..4c92987ba5bf1 100644 --- a/build_system/prepare.rs +++ b/build_system/prepare.rs @@ -7,8 +7,8 @@ use crate::build_system::rustc_info::get_default_sysroot; use super::build_sysroot::{BUILD_SYSROOT, ORIG_BUILD_SYSROOT, SYSROOT_RUSTC_VERSION, SYSROOT_SRC}; use super::path::{Dirs, RelPath}; -use super::rustc_info::{get_file_name, get_rustc_version}; -use super::utils::{copy_dir_recursively, retry_spawn_and_wait, spawn_and_wait, Compiler}; +use super::rustc_info::get_rustc_version; +use super::utils::{copy_dir_recursively, retry_spawn_and_wait, spawn_and_wait}; pub(crate) fn prepare(dirs: &Dirs) { if RelPath::DOWNLOAD.to_path(dirs).exists() { @@ -23,20 +23,6 @@ pub(crate) fn prepare(dirs: &Dirs) { super::tests::REGEX_REPO.fetch(dirs); super::tests::PORTABLE_SIMD_REPO.fetch(dirs); super::bench::SIMPLE_RAYTRACER_REPO.fetch(dirs); - - eprintln!("[LLVM BUILD] simple-raytracer"); - let host_compiler = Compiler::host(); - let build_cmd = super::bench::SIMPLE_RAYTRACER.build(&host_compiler, dirs); - spawn_and_wait(build_cmd); - fs::copy( - super::bench::SIMPLE_RAYTRACER - .target_dir(dirs) - .join(&host_compiler.triple) - .join("debug") - .join(get_file_name("main", "bin")), - RelPath::BUILD.to_path(dirs).join(get_file_name("raytracer_cg_llvm", "bin")), - ) - .unwrap(); } fn prepare_sysroot(dirs: &Dirs) { From cf22470de71180e54defc35e71edfd8558685fb4 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 11:42:02 +0000 Subject: [PATCH 143/500] Disable CG_CLIF_DISPLAY_CG_TIME by default It is a lot of noise without much benefit --- build_system/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/build_system/mod.rs b/build_system/mod.rs index 76d1d013b0dbc..1c25c515e6b34 100644 --- a/build_system/mod.rs +++ b/build_system/mod.rs @@ -70,7 +70,6 @@ pub fn main() { if env::var("RUST_BACKTRACE").is_err() { env::set_var("RUST_BACKTRACE", "1"); } - env::set_var("CG_CLIF_DISPLAY_CG_TIME", "1"); // FIXME disable this by default env::set_var("CG_CLIF_DISABLE_INCR_CACHE", "1"); if is_ci() { From 70a1cb9e62df17fbba0d30c884c7d98edf2ef780 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 12:16:11 +0000 Subject: [PATCH 144/500] Pass around Compiler instead of target triples --- build_system/abi_cafe.rs | 14 +++------ build_system/bench.rs | 9 +++--- build_system/build_backend.rs | 6 ++-- build_system/build_sysroot.rs | 35 ++++++++++++++--------- build_system/mod.rs | 54 ++++++++++++++--------------------- build_system/tests.rs | 11 +++---- build_system/utils.rs | 19 ++---------- 7 files changed, 64 insertions(+), 84 deletions(-) diff --git a/build_system/abi_cafe.rs b/build_system/abi_cafe.rs index a081fdaa1c7e6..5f20a377329f5 100644 --- a/build_system/abi_cafe.rs +++ b/build_system/abi_cafe.rs @@ -17,34 +17,28 @@ pub(crate) fn run( sysroot_kind: SysrootKind, dirs: &Dirs, cg_clif_dylib: &Path, - host_triple: &str, - target_triple: &str, + host_compiler: &Compiler, ) { if !config::get_bool("testsuite.abi-cafe") { eprintln!("[SKIP] abi-cafe"); return; } - if host_triple != target_triple { - eprintln!("[SKIP] abi-cafe (cross-compilation not supported)"); - return; - } - eprintln!("Building sysroot for abi-cafe"); build_sysroot::build_sysroot( dirs, channel, sysroot_kind, cg_clif_dylib, - host_triple, - target_triple, + host_compiler, + &host_compiler.triple, ); eprintln!("Running abi-cafe"); let pairs = ["rustc_calls_cgclif", "cgclif_calls_rustc", "cgclif_calls_cc", "cc_calls_cgclif"]; - let mut cmd = ABI_CAFE.run(&Compiler::host(), dirs); + let mut cmd = ABI_CAFE.run(host_compiler, dirs); cmd.arg("--"); cmd.arg("--pairs"); cmd.args(pairs); diff --git a/build_system/bench.rs b/build_system/bench.rs index e0956cb44bad3..f5c5d92cb3286 100644 --- a/build_system/bench.rs +++ b/build_system/bench.rs @@ -21,11 +21,11 @@ pub(crate) static SIMPLE_RAYTRACER_LLVM: CargoProject = pub(crate) static SIMPLE_RAYTRACER: CargoProject = CargoProject::new(&SIMPLE_RAYTRACER_REPO.source_dir(), "simple_raytracer"); -pub(crate) fn benchmark(dirs: &Dirs) { - benchmark_simple_raytracer(dirs); +pub(crate) fn benchmark(dirs: &Dirs, host_compiler: &Compiler) { + benchmark_simple_raytracer(dirs, host_compiler); } -fn benchmark_simple_raytracer(dirs: &Dirs) { +fn benchmark_simple_raytracer(dirs: &Dirs, host_compiler: &Compiler) { if std::process::Command::new("hyperfine").output().is_err() { eprintln!("Hyperfine not installed"); eprintln!("Hint: Try `cargo install hyperfine` to install hyperfine"); @@ -33,8 +33,7 @@ fn benchmark_simple_raytracer(dirs: &Dirs) { } eprintln!("[LLVM BUILD] simple-raytracer"); - let host_compiler = Compiler::host(); - let build_cmd = SIMPLE_RAYTRACER_LLVM.build(&host_compiler, dirs); + let build_cmd = SIMPLE_RAYTRACER_LLVM.build(host_compiler, dirs); spawn_and_wait(build_cmd); fs::copy( SIMPLE_RAYTRACER_LLVM diff --git a/build_system/build_backend.rs b/build_system/build_backend.rs index 16b43c5fc852f..00d9a6ddea8ab 100644 --- a/build_system/build_backend.rs +++ b/build_system/build_backend.rs @@ -10,10 +10,10 @@ static CG_CLIF: CargoProject = CargoProject::new(&RelPath::SOURCE, "cg_clif"); pub(crate) fn build_backend( dirs: &Dirs, channel: &str, - host_triple: &str, + host_compiler: &Compiler, use_unstable_features: bool, ) -> PathBuf { - let mut cmd = CG_CLIF.build(&Compiler::host(), dirs); + let mut cmd = CG_CLIF.build(&host_compiler, dirs); cmd.env("CARGO_BUILD_INCREMENTAL", "true"); // Force incr comp even in release mode @@ -48,7 +48,7 @@ pub(crate) fn build_backend( CG_CLIF .target_dir(dirs) - .join(host_triple) + .join(&host_compiler.triple) .join(channel) .join(get_file_name("rustc_codegen_cranelift", "dylib")) } diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index 711d4ccc55bfb..f7bdf517976a3 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -17,7 +17,7 @@ pub(crate) fn build_sysroot( channel: &str, sysroot_kind: SysrootKind, cg_clif_dylib_src: &Path, - host_triple: &str, + host_compiler: &Compiler, target_triple: &str, ) { eprintln!("[BUILD] sysroot {:?}", sysroot_kind); @@ -53,7 +53,7 @@ pub(crate) fn build_sysroot( let default_sysroot = super::rustc_info::get_default_sysroot(); - let host_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(host_triple).join("lib"); + let host_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(&host_compiler.triple).join("lib"); let target_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(target_triple).join("lib"); fs::create_dir_all(&host_rustlib_lib).unwrap(); fs::create_dir_all(&target_rustlib_lib).unwrap(); @@ -83,7 +83,7 @@ pub(crate) fn build_sysroot( SysrootKind::None => {} // Nothing to do SysrootKind::Llvm => { for file in fs::read_dir( - default_sysroot.join("lib").join("rustlib").join(host_triple).join("lib"), + default_sysroot.join("lib").join("rustlib").join(&host_compiler.triple).join("lib"), ) .unwrap() { @@ -103,7 +103,7 @@ pub(crate) fn build_sysroot( try_hard_link(&file, host_rustlib_lib.join(file.file_name().unwrap())); } - if target_triple != host_triple { + if target_triple != host_compiler.triple { for file in fs::read_dir( default_sysroot.join("lib").join("rustlib").join(target_triple).join("lib"), ) @@ -115,9 +115,15 @@ pub(crate) fn build_sysroot( } } SysrootKind::Clif => { - build_clif_sysroot_for_triple(dirs, channel, host_triple, &cg_clif_dylib_path, None); + build_clif_sysroot_for_triple( + dirs, + channel, + host_compiler.clone(), + &cg_clif_dylib_path, + None, + ); - if host_triple != target_triple { + if host_compiler.triple != target_triple { // When cross-compiling it is often necessary to manually pick the right linker let linker = match target_triple { "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu-gcc"), @@ -127,7 +133,11 @@ pub(crate) fn build_sysroot( build_clif_sysroot_for_triple( dirs, channel, - target_triple, + { + let mut target_compiler = host_compiler.clone(); + target_compiler.triple = target_triple.to_owned(); + target_compiler + }, &cg_clif_dylib_path, linker, ); @@ -155,7 +165,7 @@ static STANDARD_LIBRARY: CargoProject = CargoProject::new(&BUILD_SYSROOT, "build fn build_clif_sysroot_for_triple( dirs: &Dirs, channel: &str, - triple: &str, + mut compiler: Compiler, cg_clif_dylib_path: &Path, linker: Option<&str>, ) { @@ -177,7 +187,7 @@ fn build_clif_sysroot_for_triple( } } - let build_dir = STANDARD_LIBRARY.target_dir(dirs).join(triple).join(channel); + let build_dir = STANDARD_LIBRARY.target_dir(dirs).join(&compiler.triple).join(channel); if !super::config::get_bool("keep_sysroot") { // Cleanup the deps dir, but keep build scripts and the incremental cache for faster @@ -188,7 +198,7 @@ fn build_clif_sysroot_for_triple( } // Build sysroot - let mut rustflags = "-Zforce-unstable-if-unmarked -Cpanic=abort".to_string(); + let mut rustflags = " -Zforce-unstable-if-unmarked -Cpanic=abort".to_string(); rustflags.push_str(&format!(" -Zcodegen-backend={}", cg_clif_dylib_path.to_str().unwrap())); rustflags.push_str(&format!(" --sysroot={}", DIST_DIR.to_path(dirs).to_str().unwrap())); if channel == "release" { @@ -198,8 +208,7 @@ fn build_clif_sysroot_for_triple( use std::fmt::Write; write!(rustflags, " -Clinker={}", linker).unwrap(); } - let mut compiler = Compiler::with_triple(triple.to_owned()); - compiler.rustflags = rustflags; + compiler.rustflags += &rustflags; let mut build_cmd = STANDARD_LIBRARY.build(&compiler, dirs); if channel == "release" { build_cmd.arg("--release"); @@ -219,7 +228,7 @@ fn build_clif_sysroot_for_triple( }; try_hard_link( entry.path(), - RUSTLIB_DIR.to_path(dirs).join(triple).join("lib").join(entry.file_name()), + RUSTLIB_DIR.to_path(dirs).join(&compiler.triple).join("lib").join(entry.file_name()), ); } } diff --git a/build_system/mod.rs b/build_system/mod.rs index 1c25c515e6b34..f2de07cf5eb85 100644 --- a/build_system/mod.rs +++ b/build_system/mod.rs @@ -2,7 +2,7 @@ use std::env; use std::path::PathBuf; use std::process; -use self::utils::is_ci; +use self::utils::{is_ci, Compiler}; mod abi_cafe; mod bench; @@ -121,24 +121,16 @@ pub fn main() { } } - let host_triple = if let Ok(host_triple) = std::env::var("HOST_TRIPLE") { - host_triple - } else if let Some(host_triple) = config::get_value("host") { - host_triple - } else { - rustc_info::get_host_triple() - }; - let target_triple = if let Ok(target_triple) = std::env::var("TARGET_TRIPLE") { - if target_triple != "" { - target_triple - } else { - host_triple.clone() // Empty target triple can happen on GHA - } - } else if let Some(target_triple) = config::get_value("target") { - target_triple - } else { - host_triple.clone() - }; + let host_compiler = Compiler::llvm_with_triple( + std::env::var("HOST_TRIPLE") + .ok() + .or_else(|| config::get_value("host")) + .unwrap_or_else(|| rustc_info::get_host_triple()), + ); + let target_triple = std::env::var("TARGET_TRIPLE") + .ok() + .or_else(|| config::get_value("target")) + .unwrap_or_else(|| host_compiler.triple.clone()); // FIXME allow changing the location of these dirs using cli arguments let current_dir = std::env::current_dir().unwrap(); @@ -167,7 +159,7 @@ pub fn main() { } let cg_clif_dylib = - build_backend::build_backend(&dirs, channel, &host_triple, use_unstable_features); + build_backend::build_backend(&dirs, channel, &host_compiler, use_unstable_features); match command { Command::Prepare => { // Handled above @@ -178,18 +170,16 @@ pub fn main() { channel, sysroot_kind, &cg_clif_dylib, - &host_triple, + &host_compiler, &target_triple, ); - abi_cafe::run( - channel, - sysroot_kind, - &dirs, - &cg_clif_dylib, - &host_triple, - &target_triple, - ); + if host_compiler.triple == target_triple { + abi_cafe::run(channel, sysroot_kind, &dirs, &cg_clif_dylib, &host_compiler); + } else { + eprintln!("[SKIP] abi-cafe (cross-compilation not supported)"); + return; + } } Command::Build => { build_sysroot::build_sysroot( @@ -197,7 +187,7 @@ pub fn main() { channel, sysroot_kind, &cg_clif_dylib, - &host_triple, + &host_compiler, &target_triple, ); } @@ -207,10 +197,10 @@ pub fn main() { channel, sysroot_kind, &cg_clif_dylib, - &host_triple, + &host_compiler, &target_triple, ); - bench::benchmark(&dirs); + bench::benchmark(&dirs, &host_compiler); } } } diff --git a/build_system/tests.rs b/build_system/tests.rs index 5b8b6f2df1066..9139b3ccecc1c 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -385,10 +385,11 @@ pub(crate) fn run_tests( channel: &str, sysroot_kind: SysrootKind, cg_clif_dylib: &Path, - host_triple: &str, + host_compiler: &Compiler, target_triple: &str, ) { - let runner = TestRunner::new(dirs.clone(), host_triple.to_string(), target_triple.to_string()); + let runner = + TestRunner::new(dirs.clone(), host_compiler.triple.clone(), target_triple.to_string()); if config::get_bool("testsuite.no_sysroot") { build_sysroot::build_sysroot( @@ -396,7 +397,7 @@ pub(crate) fn run_tests( channel, SysrootKind::None, cg_clif_dylib, - &host_triple, + host_compiler, &target_triple, ); @@ -415,7 +416,7 @@ pub(crate) fn run_tests( channel, sysroot_kind, cg_clif_dylib, - &host_triple, + host_compiler, &target_triple, ); } @@ -445,7 +446,7 @@ impl TestRunner { pub fn new(dirs: Dirs, host_triple: String, target_triple: String) -> Self { let is_native = host_triple == target_triple; let jit_supported = - target_triple.contains("x86_64") && is_native && !host_triple.contains("windows"); + is_native && host_triple.contains("x86_64") && !host_triple.contains("windows"); let mut rustflags = env::var("RUSTFLAGS").ok().unwrap_or("".to_string()); let mut runner = vec![]; diff --git a/build_system/utils.rs b/build_system/utils.rs index 3d6617d445843..d244da1b2e04e 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -5,10 +5,9 @@ use std::path::{Path, PathBuf}; use std::process::{self, Command, Stdio}; use super::path::{Dirs, RelPath}; -use super::rustc_info::{ - get_cargo_path, get_host_triple, get_rustc_path, get_rustdoc_path, get_wrapper_file_name, -}; +use super::rustc_info::{get_cargo_path, get_rustc_path, get_rustdoc_path, get_wrapper_file_name}; +#[derive(Clone, Debug)] pub(crate) struct Compiler { pub(crate) cargo: PathBuf, pub(crate) rustc: PathBuf, @@ -20,19 +19,7 @@ pub(crate) struct Compiler { } impl Compiler { - pub(crate) fn host() -> Compiler { - Compiler { - cargo: get_cargo_path(), - rustc: get_rustc_path(), - rustdoc: get_rustdoc_path(), - rustflags: String::new(), - rustdocflags: String::new(), - triple: get_host_triple(), - runner: vec![], - } - } - - pub(crate) fn with_triple(triple: String) -> Compiler { + pub(crate) fn llvm_with_triple(triple: String) -> Compiler { Compiler { cargo: get_cargo_path(), rustc: get_rustc_path(), From f311ef5a2ebbb520da3fb1333a1df70b31b9a66a Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 12:32:20 +0000 Subject: [PATCH 145/500] Share cross-compilation code between building and testing --- build_system/build_sysroot.rs | 14 +--------- build_system/tests.rs | 51 +++++++++-------------------------- build_system/utils.rs | 32 ++++++++++++++++++++++ 3 files changed, 46 insertions(+), 51 deletions(-) diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index f7bdf517976a3..3ec00e08ef797 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -120,26 +120,19 @@ pub(crate) fn build_sysroot( channel, host_compiler.clone(), &cg_clif_dylib_path, - None, ); if host_compiler.triple != target_triple { - // When cross-compiling it is often necessary to manually pick the right linker - let linker = match target_triple { - "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu-gcc"), - "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu-gcc"), - _ => None, - }; build_clif_sysroot_for_triple( dirs, channel, { let mut target_compiler = host_compiler.clone(); target_compiler.triple = target_triple.to_owned(); + target_compiler.set_cross_linker_and_runner(); target_compiler }, &cg_clif_dylib_path, - linker, ); } @@ -167,7 +160,6 @@ fn build_clif_sysroot_for_triple( channel: &str, mut compiler: Compiler, cg_clif_dylib_path: &Path, - linker: Option<&str>, ) { match fs::read_to_string(SYSROOT_RUSTC_VERSION.to_path(dirs)) { Err(e) => { @@ -204,10 +196,6 @@ fn build_clif_sysroot_for_triple( if channel == "release" { rustflags.push_str(" -Zmir-opt-level=3"); } - if let Some(linker) = linker { - use std::fmt::Write; - write!(rustflags, " -Clinker={}", linker).unwrap(); - } compiler.rustflags += &rustflags; let mut build_cmd = STANDARD_LIBRARY.build(&compiler, dirs); if channel == "release" { diff --git a/build_system/tests.rs b/build_system/tests.rs index 9139b3ccecc1c..6993fdee40524 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -448,51 +448,26 @@ impl TestRunner { let jit_supported = is_native && host_triple.contains("x86_64") && !host_triple.contains("windows"); - let mut rustflags = env::var("RUSTFLAGS").ok().unwrap_or("".to_string()); - let mut runner = vec![]; + let host_compiler = Compiler::clif_with_triple(&dirs, host_triple); + let mut target_compiler = Compiler::clif_with_triple(&dirs, target_triple); if !is_native { - match target_triple.as_str() { - "aarch64-unknown-linux-gnu" => { - // We are cross-compiling for aarch64. Use the correct linker and run tests in qemu. - rustflags = format!("-Clinker=aarch64-linux-gnu-gcc{}", rustflags); - runner = vec![ - "qemu-aarch64".to_owned(), - "-L".to_owned(), - "/usr/aarch64-linux-gnu".to_owned(), - ]; - } - "s390x-unknown-linux-gnu" => { - // We are cross-compiling for s390x. Use the correct linker and run tests in qemu. - rustflags = format!("-Clinker=s390x-linux-gnu-gcc{}", rustflags); - runner = vec![ - "qemu-s390x".to_owned(), - "-L".to_owned(), - "/usr/s390x-linux-gnu".to_owned(), - ]; - } - "x86_64-pc-windows-gnu" => { - // We are cross-compiling for Windows. Run tests in wine. - runner = vec!["wine".to_owned()]; - } - _ => { - println!("Unknown non-native platform"); - } - } + target_compiler.set_cross_linker_and_runner(); + } + if let Ok(rustflags) = env::var("RUSTFLAGS") { + target_compiler.rustflags.push(' '); + target_compiler.rustflags.push_str(&rustflags); + } + if let Ok(rustdocflags) = env::var("RUSTDOCFLAGS") { + target_compiler.rustdocflags.push(' '); + target_compiler.rustdocflags.push_str(&rustdocflags); } // FIXME fix `#[linkage = "extern_weak"]` without this - if target_triple.contains("darwin") { - rustflags = format!("{} -Clink-arg=-undefined -Clink-arg=dynamic_lookup", rustflags); + if target_compiler.triple.contains("darwin") { + target_compiler.rustflags.push_str(" -Clink-arg=-undefined -Clink-arg=dynamic_lookup"); } - let host_compiler = Compiler::clif_with_triple(&dirs, host_triple); - - let mut target_compiler = Compiler::clif_with_triple(&dirs, target_triple); - target_compiler.rustflags = rustflags.clone(); - target_compiler.rustdocflags = rustflags; - target_compiler.runner = runner; - Self { is_native, jit_supported, dirs, host_compiler, target_compiler } } diff --git a/build_system/utils.rs b/build_system/utils.rs index d244da1b2e04e..77cbf9b26fdc0 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -47,6 +47,38 @@ impl Compiler { runner: vec![], } } + + pub(crate) fn set_cross_linker_and_runner(&mut self) { + match self.triple.as_str() { + "aarch64-unknown-linux-gnu" => { + // We are cross-compiling for aarch64. Use the correct linker and run tests in qemu. + self.rustflags += " -Clinker=aarch64-linux-gnu-gcc"; + self.rustdocflags += " -Clinker=aarch64-linux-gnu-gcc"; + self.runner = vec![ + "qemu-aarch64".to_owned(), + "-L".to_owned(), + "/usr/aarch64-linux-gnu".to_owned(), + ]; + } + "s390x-unknown-linux-gnu" => { + // We are cross-compiling for s390x. Use the correct linker and run tests in qemu. + self.rustflags += " -Clinker=s390x-linux-gnu-gcc"; + self.rustdocflags += " -Clinker=s390x-linux-gnu-gcc"; + self.runner = vec![ + "qemu-s390x".to_owned(), + "-L".to_owned(), + "/usr/s390x-linux-gnu".to_owned(), + ]; + } + "x86_64-pc-windows-gnu" => { + // We are cross-compiling for Windows. Run tests in wine. + self.runner = vec!["wine".to_owned()]; + } + _ => { + println!("Unknown non-native platform"); + } + } + } } pub(crate) struct CargoProject { From bb7ab8242a2b17d90ab7735efbbf2c5b905e196e Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 12:52:29 +0000 Subject: [PATCH 146/500] Remove a lot of redundant rustc arguments for tests --- build_system/tests.rs | 141 ++++++------------------------------------ 1 file changed, 19 insertions(+), 122 deletions(-) diff --git a/build_system/tests.rs b/build_system/tests.rs index 6993fdee40524..364c4d93e4f3c 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -26,24 +26,10 @@ impl TestCase { const NO_SYSROOT_SUITE: &[TestCase] = &[ TestCase::new("build.mini_core", &|runner| { - runner.run_rustc([ - "example/mini_core.rs", - "--crate-name", - "mini_core", - "--crate-type", - "lib,dylib", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/mini_core.rs", "--crate-type", "lib,dylib"]); }), TestCase::new("build.example", &|runner| { - runner.run_rustc([ - "example/example.rs", - "--crate-type", - "lib", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/example.rs", "--crate-type", "lib"]); }), TestCase::new("jit.mini_core_hello_world", &|runner| { let mut jit_cmd = runner.rustc_command([ @@ -53,8 +39,6 @@ const NO_SYSROOT_SUITE: &[TestCase] = &[ "example/mini_core_hello_world.rs", "--cfg", "jit", - "--target", - &runner.target_compiler.triple, ]); jit_cmd.env("CG_CLIF_JIT_ARGS", "abc bcd"); spawn_and_wait(jit_cmd); @@ -67,69 +51,30 @@ const NO_SYSROOT_SUITE: &[TestCase] = &[ "example/mini_core_hello_world.rs", "--cfg", "jit", - "--target", - &runner.target_compiler.triple, ]); jit_cmd.env("CG_CLIF_JIT_ARGS", "abc bcd"); spawn_and_wait(jit_cmd); }), TestCase::new("aot.mini_core_hello_world", &|runner| { - runner.run_rustc([ - "example/mini_core_hello_world.rs", - "--crate-name", - "mini_core_hello_world", - "--crate-type", - "bin", - "-g", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/mini_core_hello_world.rs"]); runner.run_out_command("mini_core_hello_world", ["abc", "bcd"]); }), ]; const BASE_SYSROOT_SUITE: &[TestCase] = &[ TestCase::new("aot.arbitrary_self_types_pointers_and_wrappers", &|runner| { - runner.run_rustc([ - "example/arbitrary_self_types_pointers_and_wrappers.rs", - "--crate-name", - "arbitrary_self_types_pointers_and_wrappers", - "--crate-type", - "bin", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/arbitrary_self_types_pointers_and_wrappers.rs"]); runner.run_out_command("arbitrary_self_types_pointers_and_wrappers", []); }), TestCase::new("aot.issue_91827_extern_types", &|runner| { - runner.run_rustc([ - "example/issue-91827-extern-types.rs", - "--crate-name", - "issue_91827_extern_types", - "--crate-type", - "bin", - "--target", - &runner.target_compiler.triple, - ]); - runner.run_out_command("issue_91827_extern_types", []); + runner.run_rustc(["example/issue-91827-extern-types.rs"]); + runner.run_out_command("issue-91827-extern-types", []); }), TestCase::new("build.alloc_system", &|runner| { - runner.run_rustc([ - "example/alloc_system.rs", - "--crate-type", - "lib", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/alloc_system.rs", "--crate-type", "lib"]); }), TestCase::new("aot.alloc_example", &|runner| { - runner.run_rustc([ - "example/alloc_example.rs", - "--crate-type", - "bin", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/alloc_example.rs"]); runner.run_out_command("alloc_example", []); }), TestCase::new("jit.std_example", &|runner| { @@ -138,8 +83,6 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "-Cllvm-args=mode=jit", "-Cprefer-dynamic", "example/std_example.rs", - "--target", - &runner.target_compiler.triple, ]); eprintln!("[JIT-lazy] std_example"); @@ -148,83 +91,34 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ "-Cllvm-args=mode=jit-lazy", "-Cprefer-dynamic", "example/std_example.rs", - "--target", - &runner.target_compiler.triple, ]); }), TestCase::new("aot.std_example", &|runner| { - runner.run_rustc([ - "example/std_example.rs", - "--crate-type", - "bin", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/std_example.rs"]); runner.run_out_command("std_example", ["arg"]); }), TestCase::new("aot.dst_field_align", &|runner| { - runner.run_rustc([ - "example/dst-field-align.rs", - "--crate-name", - "dst_field_align", - "--crate-type", - "bin", - "--target", - &runner.target_compiler.triple, - ]); - runner.run_out_command("dst_field_align", []); + runner.run_rustc(["example/dst-field-align.rs"]); + runner.run_out_command("dst-field-align", []); }), TestCase::new("aot.subslice-patterns-const-eval", &|runner| { - runner.run_rustc([ - "example/subslice-patterns-const-eval.rs", - "--crate-type", - "bin", - "-Cpanic=abort", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/subslice-patterns-const-eval.rs"]); runner.run_out_command("subslice-patterns-const-eval", []); }), TestCase::new("aot.track-caller-attribute", &|runner| { - runner.run_rustc([ - "example/track-caller-attribute.rs", - "--crate-type", - "bin", - "-Cpanic=abort", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/track-caller-attribute.rs"]); runner.run_out_command("track-caller-attribute", []); }), TestCase::new("aot.float-minmax-pass", &|runner| { - runner.run_rustc([ - "example/float-minmax-pass.rs", - "--crate-type", - "bin", - "-Cpanic=abort", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/float-minmax-pass.rs"]); runner.run_out_command("float-minmax-pass", []); }), TestCase::new("aot.mod_bench", &|runner| { - runner.run_rustc([ - "example/mod_bench.rs", - "--crate-type", - "bin", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/mod_bench.rs"]); runner.run_out_command("mod_bench", []); }), TestCase::new("aot.issue-72793", &|runner| { - runner.run_rustc([ - "example/issue-72793.rs", - "--crate-type", - "bin", - "--target", - &runner.target_compiler.triple, - ]); + runner.run_rustc(["example/issue-72793.rs"]); runner.run_out_command("issue-72793", []); }), ]; @@ -501,6 +395,9 @@ impl TestRunner { cmd.arg("--out-dir"); cmd.arg(format!("{}", BUILD_EXAMPLE_OUT_DIR.to_path(&self.dirs).display())); cmd.arg("-Cdebuginfo=2"); + cmd.arg("--target"); + cmd.arg(&self.target_compiler.triple); + cmd.arg("-Cpanic=abort"); cmd.args(args); cmd } From af99a369c448c4b81c1a75437dc17779f6301020 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 13:44:40 +0000 Subject: [PATCH 147/500] Use sparse cargo registry --- .github/workflows/main.yml | 15 ++++++------- .github/workflows/nightly-cranelift.yml | 7 ++++++ .github/workflows/rustc.yml | 30 ++++++++++++------------- 3 files changed, 28 insertions(+), 24 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index cc9ae19afded6..7dbc8e76efdff 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -62,14 +62,6 @@ jobs: steps: - uses: actions/checkout@v3 - - name: Cache cargo registry and index - uses: actions/cache@v3 - with: - path: | - ~/.cargo/registry - ~/.cargo/git - key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-registry-and-index-${{ hashFiles('**/Cargo.lock') }} - - name: Cache cargo target dir uses: actions/cache@v3 with: @@ -103,6 +95,13 @@ jobs: if: matrix.os == 'windows-latest' run: git config --global core.autocrlf false + - name: Use sparse cargo registry + run: | + cat >> ~/.cargo/config.toml <> ~/.cargo/config.toml <> ~/.cargo/config.toml <> ~/.cargo/config.toml < Date: Fri, 13 Jan 2023 13:51:51 +0000 Subject: [PATCH 148/500] Don't require git user to be configured for testing rust --- .github/workflows/nightly-cranelift.yml | 5 +---- .github/workflows/rustc.yml | 10 ++-------- scripts/setup_rust_fork.sh | 2 +- 3 files changed, 4 insertions(+), 13 deletions(-) diff --git a/.github/workflows/nightly-cranelift.yml b/.github/workflows/nightly-cranelift.yml index 32a8ba9bcc992..8b3bfab7071ce 100644 --- a/.github/workflows/nightly-cranelift.yml +++ b/.github/workflows/nightly-cranelift.yml @@ -21,10 +21,7 @@ jobs: EOF - name: Prepare dependencies - run: | - git config --global user.email "user@example.com" - git config --global user.name "User" - ./y.rs prepare + run: ./y.rs prepare - name: Patch Cranelift run: | diff --git a/.github/workflows/rustc.yml b/.github/workflows/rustc.yml index 8844874ecb01f..5faa8f0540451 100644 --- a/.github/workflows/rustc.yml +++ b/.github/workflows/rustc.yml @@ -24,10 +24,7 @@ jobs: EOF - name: Prepare dependencies - run: | - git config --global user.email "user@example.com" - git config --global user.name "User" - ./y.rs prepare + run: ./y.rs prepare - name: Test run: ./scripts/test_bootstrap.sh @@ -51,10 +48,7 @@ jobs: EOF - name: Prepare dependencies - run: | - git config --global user.email "user@example.com" - git config --global user.name "User" - ./y.rs prepare + run: ./y.rs prepare - name: Test run: ./scripts/test_rustc_tests.sh diff --git a/scripts/setup_rust_fork.sh b/scripts/setup_rust_fork.sh index 88bc64455030e..ce0d7e9fe07da 100644 --- a/scripts/setup_rust_fork.sh +++ b/scripts/setup_rust_fork.sh @@ -10,7 +10,7 @@ git fetch git checkout -- . git checkout "$(rustc -V | cut -d' ' -f3 | tr -d '(')" -git am ../patches/*-sysroot-*.patch +git -c user.name=Dummy -c user.email=dummy@example.com am ../patches/*-sysroot-*.patch git apply - < Date: Fri, 13 Jan 2023 14:19:54 +0000 Subject: [PATCH 149/500] Introduce helpers for common test case commands --- build_system/tests.rs | 226 ++++++++++++++++++++++-------------------- 1 file changed, 117 insertions(+), 109 deletions(-) diff --git a/build_system/tests.rs b/build_system/tests.rs index 364c4d93e4f3c..8bef6f733800a 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -15,112 +15,83 @@ static BUILD_EXAMPLE_OUT_DIR: RelPath = RelPath::BUILD.join("example"); struct TestCase { config: &'static str, - func: &'static dyn Fn(&TestRunner), + cmd: TestCaseCmd, +} + +enum TestCaseCmd { + Custom { func: &'static dyn Fn(&TestRunner) }, + BuildLib { source: &'static str, crate_types: &'static str }, + BuildBinAndRun { source: &'static str, args: &'static [&'static str] }, + JitBin { source: &'static str, args: &'static str }, } impl TestCase { - const fn new(config: &'static str, func: &'static dyn Fn(&TestRunner)) -> Self { - Self { config, func } + // FIXME reduce usage of custom test case commands + const fn custom(config: &'static str, func: &'static dyn Fn(&TestRunner)) -> Self { + Self { config, cmd: TestCaseCmd::Custom { func } } + } + + const fn build_lib( + config: &'static str, + source: &'static str, + crate_types: &'static str, + ) -> Self { + Self { config, cmd: TestCaseCmd::BuildLib { source, crate_types } } + } + + const fn build_bin_and_run( + config: &'static str, + source: &'static str, + args: &'static [&'static str], + ) -> Self { + Self { config, cmd: TestCaseCmd::BuildBinAndRun { source, args } } + } + + const fn jit_bin(config: &'static str, source: &'static str, args: &'static str) -> Self { + Self { config, cmd: TestCaseCmd::JitBin { source, args } } } } const NO_SYSROOT_SUITE: &[TestCase] = &[ - TestCase::new("build.mini_core", &|runner| { - runner.run_rustc(["example/mini_core.rs", "--crate-type", "lib,dylib"]); - }), - TestCase::new("build.example", &|runner| { - runner.run_rustc(["example/example.rs", "--crate-type", "lib"]); - }), - TestCase::new("jit.mini_core_hello_world", &|runner| { - let mut jit_cmd = runner.rustc_command([ - "-Zunstable-options", - "-Cllvm-args=mode=jit", - "-Cprefer-dynamic", - "example/mini_core_hello_world.rs", - "--cfg", - "jit", - ]); - jit_cmd.env("CG_CLIF_JIT_ARGS", "abc bcd"); - spawn_and_wait(jit_cmd); - - eprintln!("[JIT-lazy] mini_core_hello_world"); - let mut jit_cmd = runner.rustc_command([ - "-Zunstable-options", - "-Cllvm-args=mode=jit-lazy", - "-Cprefer-dynamic", - "example/mini_core_hello_world.rs", - "--cfg", - "jit", - ]); - jit_cmd.env("CG_CLIF_JIT_ARGS", "abc bcd"); - spawn_and_wait(jit_cmd); - }), - TestCase::new("aot.mini_core_hello_world", &|runner| { - runner.run_rustc(["example/mini_core_hello_world.rs"]); - runner.run_out_command("mini_core_hello_world", ["abc", "bcd"]); - }), + TestCase::build_lib("build.mini_core", "example/mini_core.rs", "lib,dylib"), + TestCase::build_lib("build.example", "example/example.rs", "lib"), + TestCase::jit_bin("jit.mini_core_hello_world", "example/mini_core_hello_world.rs", "abc bcd"), + TestCase::build_bin_and_run( + "aot.mini_core_hello_world", + "example/mini_core_hello_world.rs", + &["abc", "bcd"], + ), ]; const BASE_SYSROOT_SUITE: &[TestCase] = &[ - TestCase::new("aot.arbitrary_self_types_pointers_and_wrappers", &|runner| { - runner.run_rustc(["example/arbitrary_self_types_pointers_and_wrappers.rs"]); - runner.run_out_command("arbitrary_self_types_pointers_and_wrappers", []); - }), - TestCase::new("aot.issue_91827_extern_types", &|runner| { - runner.run_rustc(["example/issue-91827-extern-types.rs"]); - runner.run_out_command("issue-91827-extern-types", []); - }), - TestCase::new("build.alloc_system", &|runner| { - runner.run_rustc(["example/alloc_system.rs", "--crate-type", "lib"]); - }), - TestCase::new("aot.alloc_example", &|runner| { - runner.run_rustc(["example/alloc_example.rs"]); - runner.run_out_command("alloc_example", []); - }), - TestCase::new("jit.std_example", &|runner| { - runner.run_rustc([ - "-Zunstable-options", - "-Cllvm-args=mode=jit", - "-Cprefer-dynamic", - "example/std_example.rs", - ]); - - eprintln!("[JIT-lazy] std_example"); - runner.run_rustc([ - "-Zunstable-options", - "-Cllvm-args=mode=jit-lazy", - "-Cprefer-dynamic", - "example/std_example.rs", - ]); - }), - TestCase::new("aot.std_example", &|runner| { - runner.run_rustc(["example/std_example.rs"]); - runner.run_out_command("std_example", ["arg"]); - }), - TestCase::new("aot.dst_field_align", &|runner| { - runner.run_rustc(["example/dst-field-align.rs"]); - runner.run_out_command("dst-field-align", []); - }), - TestCase::new("aot.subslice-patterns-const-eval", &|runner| { - runner.run_rustc(["example/subslice-patterns-const-eval.rs"]); - runner.run_out_command("subslice-patterns-const-eval", []); - }), - TestCase::new("aot.track-caller-attribute", &|runner| { - runner.run_rustc(["example/track-caller-attribute.rs"]); - runner.run_out_command("track-caller-attribute", []); - }), - TestCase::new("aot.float-minmax-pass", &|runner| { - runner.run_rustc(["example/float-minmax-pass.rs"]); - runner.run_out_command("float-minmax-pass", []); - }), - TestCase::new("aot.mod_bench", &|runner| { - runner.run_rustc(["example/mod_bench.rs"]); - runner.run_out_command("mod_bench", []); - }), - TestCase::new("aot.issue-72793", &|runner| { - runner.run_rustc(["example/issue-72793.rs"]); - runner.run_out_command("issue-72793", []); - }), + TestCase::build_bin_and_run( + "aot.arbitrary_self_types_pointers_and_wrappers", + "example/arbitrary_self_types_pointers_and_wrappers.rs", + &[], + ), + TestCase::build_bin_and_run( + "aot.issue_91827_extern_types", + "example/issue-91827-extern-types.rs", + &[], + ), + TestCase::build_lib("build.alloc_system", "example/alloc_system.rs", "lib"), + TestCase::build_bin_and_run("aot.alloc_example", "example/alloc_example.rs", &[]), + TestCase::jit_bin("jit.std_example", "example/std_example.rs", ""), + TestCase::build_bin_and_run("aot.std_example", "example/std_example.rs", &["arg"]), + TestCase::build_bin_and_run("aot.dst_field_align", "example/dst-field-align.rs", &[]), + TestCase::build_bin_and_run( + "aot.subslice-patterns-const-eval", + "example/subslice-patterns-const-eval.rs", + &[], + ), + TestCase::build_bin_and_run( + "aot.track-caller-attribute", + "example/track-caller-attribute.rs", + &[], + ), + TestCase::build_bin_and_run("aot.float-minmax-pass", "example/float-minmax-pass.rs", &[]), + TestCase::build_bin_and_run("aot.mod_bench", "example/mod_bench.rs", &[]), + TestCase::build_bin_and_run("aot.issue-72793", "example/issue-72793.rs", &[]), ]; pub(crate) static RAND_REPO: GitRepo = @@ -147,7 +118,7 @@ static LIBCORE_TESTS: CargoProject = CargoProject::new(&SYSROOT_SRC.join("library/core/tests"), "core_tests"); const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ - TestCase::new("test.rust-random/rand", &|runner| { + TestCase::custom("test.rust-random/rand", &|runner| { spawn_and_wait(RAND.clean(&runner.target_compiler.cargo, &runner.dirs)); if runner.is_native { @@ -162,11 +133,11 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ spawn_and_wait(build_cmd); } }), - TestCase::new("test.simple-raytracer", &|runner| { + TestCase::custom("test.simple-raytracer", &|runner| { spawn_and_wait(SIMPLE_RAYTRACER.clean(&runner.host_compiler.cargo, &runner.dirs)); spawn_and_wait(SIMPLE_RAYTRACER.build(&runner.target_compiler, &runner.dirs)); }), - TestCase::new("test.libcore", &|runner| { + TestCase::custom("test.libcore", &|runner| { spawn_and_wait(LIBCORE_TESTS.clean(&runner.host_compiler.cargo, &runner.dirs)); if runner.is_native { @@ -178,7 +149,7 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ spawn_and_wait(build_cmd); } }), - TestCase::new("test.regex-shootout-regex-dna", &|runner| { + TestCase::custom("test.regex-shootout-regex-dna", &|runner| { spawn_and_wait(REGEX.clean(&runner.target_compiler.cargo, &runner.dirs)); // newer aho_corasick versions throw a deprecation warning @@ -232,7 +203,7 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ } } }), - TestCase::new("test.regex", &|runner| { + TestCase::custom("test.regex", &|runner| { spawn_and_wait(REGEX.clean(&runner.host_compiler.cargo, &runner.dirs)); // newer aho_corasick versions throw a deprecation warning @@ -259,7 +230,7 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ spawn_and_wait(build_cmd); } }), - TestCase::new("test.portable-simd", &|runner| { + TestCase::custom("test.portable-simd", &|runner| { spawn_and_wait(PORTABLE_SIMD.clean(&runner.host_compiler.cargo, &runner.dirs)); let mut build_cmd = PORTABLE_SIMD.build(&runner.target_compiler, &runner.dirs); @@ -366,7 +337,7 @@ impl TestRunner { } pub fn run_testsuite(&self, tests: &[TestCase]) { - for &TestCase { config, func } in tests { + for TestCase { config, cmd } in tests { let (tag, testname) = config.split_once('.').unwrap(); let tag = tag.to_uppercase(); let is_jit_test = tag == "JIT"; @@ -378,7 +349,47 @@ impl TestRunner { eprintln!("[{tag}] {testname}"); } - func(self); + match *cmd { + TestCaseCmd::Custom { func } => func(self), + TestCaseCmd::BuildLib { source, crate_types } => { + self.run_rustc([source, "--crate-type", crate_types]); + } + TestCaseCmd::BuildBinAndRun { source, args } => { + self.run_rustc([source]); + self.run_out_command( + source.split('/').last().unwrap().split('.').next().unwrap(), + args, + ); + } + TestCaseCmd::JitBin { source, args } => { + let mut jit_cmd = self.rustc_command([ + "-Zunstable-options", + "-Cllvm-args=mode=jit", + "-Cprefer-dynamic", + source, + "--cfg", + "jit", + ]); + if !args.is_empty() { + jit_cmd.env("CG_CLIF_JIT_ARGS", args); + } + spawn_and_wait(jit_cmd); + + eprintln!("[JIT-lazy] {testname}"); + let mut jit_cmd = self.rustc_command([ + "-Zunstable-options", + "-Cllvm-args=mode=jit-lazy", + "-Cprefer-dynamic", + source, + "--cfg", + "jit", + ]); + if !args.is_empty() { + jit_cmd.env("CG_CLIF_JIT_ARGS", args); + } + spawn_and_wait(jit_cmd); + } + } } } @@ -410,10 +421,7 @@ impl TestRunner { spawn_and_wait(self.rustc_command(args)); } - fn run_out_command<'a, I>(&self, name: &str, args: I) - where - I: IntoIterator, - { + fn run_out_command<'a>(&self, name: &str, args: &[&str]) { let mut full_cmd = vec![]; // Prepend the RUN_WRAPPER's @@ -425,7 +433,7 @@ impl TestRunner { BUILD_EXAMPLE_OUT_DIR.to_path(&self.dirs).join(name).to_str().unwrap().to_string(), ); - for arg in args.into_iter() { + for arg in args { full_cmd.push(arg.to_string()); } From 40745694a014bf59fa90f92ba097015c550da38f Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 14:33:14 +0000 Subject: [PATCH 150/500] Add fixme --- build_system/prepare.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/build_system/prepare.rs b/build_system/prepare.rs index 4c92987ba5bf1..21ef599cec9d2 100644 --- a/build_system/prepare.rs +++ b/build_system/prepare.rs @@ -31,6 +31,7 @@ fn prepare_sysroot(dirs: &Dirs) { eprintln!("[COPY] sysroot src"); + // FIXME ensure builds error out or update the copy if any of the files copied here change BUILD_SYSROOT.ensure_fresh(dirs); copy_dir_recursively(&ORIG_BUILD_SYSROOT.to_path(dirs), &BUILD_SYSROOT.to_path(dirs)); From 9a15db6dd0baba5423455012cf170d0f3ca89c26 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 14:39:12 +0000 Subject: [PATCH 151/500] Add git_command helper --- build_system/prepare.rs | 45 +++++++++++++---------------------------- build_system/utils.rs | 12 +++++++++++ 2 files changed, 26 insertions(+), 31 deletions(-) diff --git a/build_system/prepare.rs b/build_system/prepare.rs index 21ef599cec9d2..c3faacd9244c8 100644 --- a/build_system/prepare.rs +++ b/build_system/prepare.rs @@ -8,7 +8,7 @@ use crate::build_system::rustc_info::get_default_sysroot; use super::build_sysroot::{BUILD_SYSROOT, ORIG_BUILD_SYSROOT, SYSROOT_RUSTC_VERSION, SYSROOT_SRC}; use super::path::{Dirs, RelPath}; use super::rustc_info::get_rustc_version; -use super::utils::{copy_dir_recursively, retry_spawn_and_wait, spawn_and_wait}; +use super::utils::{copy_dir_recursively, git_command, retry_spawn_and_wait, spawn_and_wait}; pub(crate) fn prepare(dirs: &Dirs) { if RelPath::DOWNLOAD.to_path(dirs).exists() { @@ -96,14 +96,14 @@ impl GitRepo { fn clone_repo(download_dir: &Path, repo: &str, rev: &str) { eprintln!("[CLONE] {}", repo); // Ignore exit code as the repo may already have been checked out - Command::new("git").arg("clone").arg(repo).arg(&download_dir).spawn().unwrap().wait().unwrap(); + git_command(None, "clone").arg(repo).arg(download_dir).spawn().unwrap().wait().unwrap(); - let mut clean_cmd = Command::new("git"); - clean_cmd.arg("checkout").arg("--").arg(".").current_dir(&download_dir); + let mut clean_cmd = git_command(download_dir, "checkout"); + clean_cmd.arg("--").arg("."); spawn_and_wait(clean_cmd); - let mut checkout_cmd = Command::new("git"); - checkout_cmd.arg("checkout").arg("-q").arg(rev).current_dir(download_dir); + let mut checkout_cmd = git_command(download_dir, "checkout"); + checkout_cmd.arg("-q").arg(rev); spawn_and_wait(checkout_cmd); } @@ -159,25 +159,16 @@ fn clone_repo_shallow_github(dirs: &Dirs, download_dir: &Path, user: &str, repo: } fn init_git_repo(repo_dir: &Path) { - let mut git_init_cmd = Command::new("git"); - git_init_cmd.arg("init").arg("-q").current_dir(repo_dir); + let mut git_init_cmd = git_command(repo_dir, "init"); + git_init_cmd.arg("-q"); spawn_and_wait(git_init_cmd); - let mut git_add_cmd = Command::new("git"); - git_add_cmd.arg("add").arg(".").current_dir(repo_dir); + let mut git_add_cmd = git_command(repo_dir, "add"); + git_add_cmd.arg("."); spawn_and_wait(git_add_cmd); - let mut git_commit_cmd = Command::new("git"); - git_commit_cmd - .arg("-c") - .arg("user.name=Dummy") - .arg("-c") - .arg("user.email=dummy@example.com") - .arg("commit") - .arg("-m") - .arg("Initial commit") - .arg("-q") - .current_dir(repo_dir); + let mut git_commit_cmd = git_command(repo_dir, "commit"); + git_commit_cmd.arg("-m").arg("Initial commit").arg("-q"); spawn_and_wait(git_commit_cmd); } @@ -212,16 +203,8 @@ fn apply_patches(dirs: &Dirs, crate_name: &str, target_dir: &Path) { target_dir.file_name().unwrap(), patch.file_name().unwrap() ); - let mut apply_patch_cmd = Command::new("git"); - apply_patch_cmd - .arg("-c") - .arg("user.name=Dummy") - .arg("-c") - .arg("user.email=dummy@example.com") - .arg("am") - .arg(patch) - .arg("-q") - .current_dir(target_dir); + let mut apply_patch_cmd = git_command(target_dir, "am"); + apply_patch_cmd.arg(patch).arg("-q"); spawn_and_wait(apply_patch_cmd); } } diff --git a/build_system/utils.rs b/build_system/utils.rs index 77cbf9b26fdc0..6d0d9b56514ae 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -103,6 +103,7 @@ impl CargoProject { RelPath::BUILD.join(self.target).to_path(dirs) } + #[must_use] fn base_cmd(&self, command: &str, cargo: &Path, dirs: &Dirs) -> Command { let mut cmd = Command::new(cargo); @@ -115,6 +116,7 @@ impl CargoProject { cmd } + #[must_use] fn build_cmd(&self, command: &str, compiler: &Compiler, dirs: &Dirs) -> Command { let mut cmd = self.base_cmd(command, &compiler.cargo, dirs); @@ -191,6 +193,16 @@ pub(crate) fn hyperfine_command( bench } +#[must_use] +pub(crate) fn git_command<'a>(repo_dir: impl Into>, cmd: &str) -> Command { + let mut git_cmd = Command::new("git"); + git_cmd.arg("-c").arg("user.name=Dummy").arg("-c").arg("user.email=dummy@example.com").arg(cmd); + if let Some(repo_dir) = repo_dir.into() { + git_cmd.current_dir(repo_dir); + } + git_cmd +} + #[track_caller] pub(crate) fn try_hard_link(src: impl AsRef, dst: impl AsRef) { let src = src.as_ref(); From 890c61216a726a6ecad41e1f8146c169aa91812d Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 14:41:07 +0000 Subject: [PATCH 152/500] Set core.autocrlf=false in the build system instead of CI config --- .github/workflows/main.yml | 4 ---- build_system/utils.rs | 9 ++++++++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 7dbc8e76efdff..f1badb792cd13 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -91,10 +91,6 @@ jobs: sudo apt-get update sudo apt-get install -y gcc-s390x-linux-gnu qemu-user - - name: Windows setup - if: matrix.os == 'windows-latest' - run: git config --global core.autocrlf false - - name: Use sparse cargo registry run: | cat >> ~/.cargo/config.toml <(repo_dir: impl Into>, cmd: &str) -> Command { let mut git_cmd = Command::new("git"); - git_cmd.arg("-c").arg("user.name=Dummy").arg("-c").arg("user.email=dummy@example.com").arg(cmd); + git_cmd + .arg("-c") + .arg("user.name=Dummy") + .arg("-c") + .arg("user.email=dummy@example.com") + .arg("-c") + .arg("core.autocrlf=false") + .arg(cmd); if let Some(repo_dir) = repo_dir.into() { git_cmd.current_dir(repo_dir); } From 1a89507d7c4fa7d8cfa87872578cc833d52f88f8 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 15:14:04 +0000 Subject: [PATCH 153/500] Don't use the diff command in regex test The output is small enough that getting a pretty diff isn't important. In addition this reduces the amount of commands the build system depends on. --- build_system/tests.rs | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/build_system/tests.rs b/build_system/tests.rs index 8bef6f733800a..25c2457785e30 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -169,9 +169,10 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ REGEX.source_dir(&runner.dirs).join("examples").join("regexdna-input.txt"), ) .unwrap(); - let expected_path = - REGEX.source_dir(&runner.dirs).join("examples").join("regexdna-output.txt"); - let expected = fs::read_to_string(&expected_path).unwrap(); + let expected = fs::read_to_string( + REGEX.source_dir(&runner.dirs).join("examples").join("regexdna-output.txt"), + ) + .unwrap(); let output = spawn_and_wait_with_input(run_cmd, input); // Make sure `[codegen mono items] start` doesn't poison the diff @@ -184,20 +185,9 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ let output_matches = expected.lines().eq(output.lines()); if !output_matches { - let res_path = REGEX.source_dir(&runner.dirs).join("res.txt"); - fs::write(&res_path, &output).unwrap(); - - if cfg!(windows) { - println!("Output files don't match!"); - println!("Expected Output:\n{}", expected); - println!("Actual Output:\n{}", output); - } else { - let mut diff = Command::new("diff"); - diff.arg("-u"); - diff.arg(res_path); - diff.arg(expected_path); - spawn_and_wait(diff); - } + println!("Output files don't match!"); + println!("Expected Output:\n{}", expected); + println!("Actual Output:\n{}", output); std::process::exit(1); } From 957d78c47936a82164803470b97bf7a50efd9fc5 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 15:40:22 +0000 Subject: [PATCH 154/500] Fetch all cargo dependencies in ./y.rs prepare --- build_system/abi_cafe.rs | 2 +- build_system/build_backend.rs | 2 +- build_system/build_sysroot.rs | 2 +- build_system/prepare.rs | 9 +++++++++ build_system/tests.rs | 8 ++++---- 5 files changed, 16 insertions(+), 7 deletions(-) diff --git a/build_system/abi_cafe.rs b/build_system/abi_cafe.rs index 5f20a377329f5..3f93c14a0fb49 100644 --- a/build_system/abi_cafe.rs +++ b/build_system/abi_cafe.rs @@ -10,7 +10,7 @@ use super::SysrootKind; pub(crate) static ABI_CAFE_REPO: GitRepo = GitRepo::github("Gankra", "abi-cafe", "4c6dc8c9c687e2b3a760ff2176ce236872b37212", "abi-cafe"); -static ABI_CAFE: CargoProject = CargoProject::new(&ABI_CAFE_REPO.source_dir(), "abi_cafe"); +pub(crate) static ABI_CAFE: CargoProject = CargoProject::new(&ABI_CAFE_REPO.source_dir(), "abi_cafe"); pub(crate) fn run( channel: &str, diff --git a/build_system/build_backend.rs b/build_system/build_backend.rs index 00d9a6ddea8ab..6ab39e48f214f 100644 --- a/build_system/build_backend.rs +++ b/build_system/build_backend.rs @@ -5,7 +5,7 @@ use super::path::{Dirs, RelPath}; use super::rustc_info::get_file_name; use super::utils::{is_ci, CargoProject, Compiler}; -static CG_CLIF: CargoProject = CargoProject::new(&RelPath::SOURCE, "cg_clif"); +pub(crate) static CG_CLIF: CargoProject = CargoProject::new(&RelPath::SOURCE, "cg_clif"); pub(crate) fn build_backend( dirs: &Dirs, diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index 3ec00e08ef797..c7d80789f8a2e 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -153,7 +153,7 @@ pub(crate) static ORIG_BUILD_SYSROOT: RelPath = RelPath::SOURCE.join("build_sysr pub(crate) static BUILD_SYSROOT: RelPath = RelPath::DOWNLOAD.join("sysroot"); pub(crate) static SYSROOT_RUSTC_VERSION: RelPath = BUILD_SYSROOT.join("rustc_version"); pub(crate) static SYSROOT_SRC: RelPath = BUILD_SYSROOT.join("sysroot_src"); -static STANDARD_LIBRARY: CargoProject = CargoProject::new(&BUILD_SYSROOT, "build_sysroot"); +pub(crate) static STANDARD_LIBRARY: CargoProject = CargoProject::new(&BUILD_SYSROOT, "build_sysroot"); fn build_clif_sysroot_for_triple( dirs: &Dirs, diff --git a/build_system/prepare.rs b/build_system/prepare.rs index c3faacd9244c8..4e898b30b7cce 100644 --- a/build_system/prepare.rs +++ b/build_system/prepare.rs @@ -16,13 +16,22 @@ pub(crate) fn prepare(dirs: &Dirs) { } std::fs::create_dir_all(RelPath::DOWNLOAD.to_path(dirs)).unwrap(); + spawn_and_wait(super::build_backend::CG_CLIF.fetch("cargo", dirs)); + prepare_sysroot(dirs); + spawn_and_wait(super::build_sysroot::STANDARD_LIBRARY.fetch("cargo", dirs)); + spawn_and_wait(super::tests::LIBCORE_TESTS.fetch("cargo", dirs)); super::abi_cafe::ABI_CAFE_REPO.fetch(dirs); + spawn_and_wait(super::abi_cafe::ABI_CAFE.fetch("cargo", dirs)); super::tests::RAND_REPO.fetch(dirs); + spawn_and_wait(super::tests::RAND.fetch("cargo", dirs)); super::tests::REGEX_REPO.fetch(dirs); + spawn_and_wait(super::tests::REGEX.fetch("cargo", dirs)); super::tests::PORTABLE_SIMD_REPO.fetch(dirs); + spawn_and_wait(super::tests::PORTABLE_SIMD.fetch("cargo", dirs)); super::bench::SIMPLE_RAYTRACER_REPO.fetch(dirs); + spawn_and_wait(super::bench::SIMPLE_RAYTRACER.fetch("cargo", dirs)); } fn prepare_sysroot(dirs: &Dirs) { diff --git a/build_system/tests.rs b/build_system/tests.rs index 25c2457785e30..4d638a4eced10 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -97,12 +97,12 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[ pub(crate) static RAND_REPO: GitRepo = GitRepo::github("rust-random", "rand", "0f933f9c7176e53b2a3c7952ded484e1783f0bf1", "rand"); -static RAND: CargoProject = CargoProject::new(&RAND_REPO.source_dir(), "rand"); +pub(crate) static RAND: CargoProject = CargoProject::new(&RAND_REPO.source_dir(), "rand"); pub(crate) static REGEX_REPO: GitRepo = GitRepo::github("rust-lang", "regex", "341f207c1071f7290e3f228c710817c280c8dca1", "regex"); -static REGEX: CargoProject = CargoProject::new(®EX_REPO.source_dir(), "regex"); +pub(crate) static REGEX: CargoProject = CargoProject::new(®EX_REPO.source_dir(), "regex"); pub(crate) static PORTABLE_SIMD_REPO: GitRepo = GitRepo::github( "rust-lang", @@ -111,10 +111,10 @@ pub(crate) static PORTABLE_SIMD_REPO: GitRepo = GitRepo::github( "portable-simd", ); -static PORTABLE_SIMD: CargoProject = +pub(crate) static PORTABLE_SIMD: CargoProject = CargoProject::new(&PORTABLE_SIMD_REPO.source_dir(), "portable_simd"); -static LIBCORE_TESTS: CargoProject = +pub(crate) static LIBCORE_TESTS: CargoProject = CargoProject::new(&SYSROOT_SRC.join("library/core/tests"), "core_tests"); const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ From d43dce14d5eb7af1656d730bfbb5918c84addbca Mon Sep 17 00:00:00 2001 From: Tyler Weaver Date: Fri, 13 Jan 2023 08:59:00 -0700 Subject: [PATCH 155/500] Remove cognitive-complexity-threshold from docs --- README.md | 1 - book/src/configuration.md | 1 - 2 files changed, 2 deletions(-) diff --git a/README.md b/README.md index f7e03ca4cd8c4..c78ae06765d37 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,6 @@ value` mapping e.g. ```toml avoid-breaking-exported-api = false disallowed-names = ["toto", "tata", "titi"] -cognitive-complexity-threshold = 30 ``` See the [list of configurable lints](https://rust-lang.github.io/rust-clippy/master/index.html#Configuration), diff --git a/book/src/configuration.md b/book/src/configuration.md index bbe1081ccad9a..fac3e438c543e 100644 --- a/book/src/configuration.md +++ b/book/src/configuration.md @@ -8,7 +8,6 @@ basic `variable = value` mapping eg. ```toml avoid-breaking-exported-api = false disallowed-names = ["toto", "tata", "titi"] -cognitive-complexity-threshold = 30 ``` See the [list of configurable lints](https://rust-lang.github.io/rust-clippy/master/index.html#Configuration), From be8f656fac6e2ec8325707b88952c913883b2867 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 15:44:33 +0000 Subject: [PATCH 156/500] Pass --frozen to cargo to ensure ./y.rs prepare fetches all deps --- .github/workflows/nightly-cranelift.yml | 2 ++ build_system/utils.rs | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/nightly-cranelift.yml b/.github/workflows/nightly-cranelift.yml index 8b3bfab7071ce..c3dd7445fd8b9 100644 --- a/.github/workflows/nightly-cranelift.yml +++ b/.github/workflows/nightly-cranelift.yml @@ -36,6 +36,8 @@ jobs: cat Cargo.toml + cargo fetch + - name: Build without unstable features # This is the config rust-lang/rust uses for builds run: ./y.rs build --no-unstable-features diff --git a/build_system/utils.rs b/build_system/utils.rs index afbb1b0e5be4d..f2b1fecedc16b 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -111,7 +111,8 @@ impl CargoProject { .arg("--manifest-path") .arg(self.manifest_path(dirs)) .arg("--target-dir") - .arg(self.target_dir(dirs)); + .arg(self.target_dir(dirs)) + .arg("--frozen"); cmd } From 288c0678632b3a36e595c1a21f546b2559e028f5 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 15:55:17 +0000 Subject: [PATCH 157/500] Set panic=abort for the build system This saves about 60ms of build time --- y.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/y.rs b/y.rs index 02e1e21ade1de..fd825d02e355c 100755 --- a/y.rs +++ b/y.rs @@ -3,7 +3,7 @@ # This block is ignored by rustc set -e echo "[BUILD] y.rs" 1>&2 -rustc $0 -o ${0/.rs/.bin} -Cdebuginfo=1 --edition 2021 +rustc $0 -o ${0/.rs/.bin} -Cdebuginfo=1 --edition 2021 -Cpanic=abort exec ${0/.rs/.bin} $@ */ From a3468770e3ee0b357df1c0f5ec194b0fea425da1 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 15:58:39 +0000 Subject: [PATCH 158/500] Rustfmt --- build_system/abi_cafe.rs | 3 ++- build_system/build_sysroot.rs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/build_system/abi_cafe.rs b/build_system/abi_cafe.rs index 3f93c14a0fb49..63f2efd8e1ef7 100644 --- a/build_system/abi_cafe.rs +++ b/build_system/abi_cafe.rs @@ -10,7 +10,8 @@ use super::SysrootKind; pub(crate) static ABI_CAFE_REPO: GitRepo = GitRepo::github("Gankra", "abi-cafe", "4c6dc8c9c687e2b3a760ff2176ce236872b37212", "abi-cafe"); -pub(crate) static ABI_CAFE: CargoProject = CargoProject::new(&ABI_CAFE_REPO.source_dir(), "abi_cafe"); +pub(crate) static ABI_CAFE: CargoProject = + CargoProject::new(&ABI_CAFE_REPO.source_dir(), "abi_cafe"); pub(crate) fn run( channel: &str, diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index c7d80789f8a2e..b7228968f6313 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -153,7 +153,8 @@ pub(crate) static ORIG_BUILD_SYSROOT: RelPath = RelPath::SOURCE.join("build_sysr pub(crate) static BUILD_SYSROOT: RelPath = RelPath::DOWNLOAD.join("sysroot"); pub(crate) static SYSROOT_RUSTC_VERSION: RelPath = BUILD_SYSROOT.join("rustc_version"); pub(crate) static SYSROOT_SRC: RelPath = BUILD_SYSROOT.join("sysroot_src"); -pub(crate) static STANDARD_LIBRARY: CargoProject = CargoProject::new(&BUILD_SYSROOT, "build_sysroot"); +pub(crate) static STANDARD_LIBRARY: CargoProject = + CargoProject::new(&BUILD_SYSROOT, "build_sysroot"); fn build_clif_sysroot_for_triple( dirs: &Dirs, From 3a27253289b4340a464206ea52534ef07e017efe Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 15:59:43 +0000 Subject: [PATCH 159/500] Enable VSCode formatOnSave --- .vscode/settings.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.vscode/settings.json b/.vscode/settings.json index d8650d1e387d2..7c8703cba505c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,6 @@ { + "editor.formatOnSave": true, + // source for rustc_* is not included in the rust-src component; disable the errors about this "rust-analyzer.diagnostics.disabled": ["unresolved-extern-crate", "unresolved-macro-call"], "rust-analyzer.imports.granularity.enforce": true, From bdcbf47df3b2f4e7dc12930a861c689b75a66c3f Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 16:34:43 +0000 Subject: [PATCH 160/500] Improve readme and build system help message --- Readme.md | 11 +++++------ build_system/mod.rs | 26 +------------------------- build_system/usage.txt | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 31 deletions(-) create mode 100644 build_system/usage.txt diff --git a/Readme.md b/Readme.md index 55b107e4efbca..b87a9dc51e8d0 100644 --- a/Readme.md +++ b/Readme.md @@ -8,9 +8,9 @@ If not please open an issue. ## Building and testing ```bash -$ git clone https://github.com/bjorn3/rustc_codegen_cranelift.git +$ git clone https://github.com/bjorn3/rustc_codegen_cranelift $ cd rustc_codegen_cranelift -$ ./y.rs prepare # download and patch sysroot src and install hyperfine for benchmarking +$ ./y.rs prepare $ ./y.rs build ``` @@ -20,13 +20,12 @@ To run the test suite replace the last command with: $ ./test.sh ``` -This will implicitly build cg_clif too. Both `y.rs build` and `test.sh` accept a `--debug` argument to -build in debug mode. +For more docs on how to build and test see [build_system/usage.txt](build_system/usage.txt) or the help message of `./y.rs`. -Alternatively you can download a pre built version from [GHA]. It is listed in the artifacts section +Alternatively you can download a pre built version from [Github Actions]. It is listed in the artifacts section of workflow runs. Unfortunately due to GHA restrictions you need to be logged in to access it. -[GHA]: https://github.com/bjorn3/rustc_codegen_cranelift/actions?query=branch%3Amaster+event%3Apush+is%3Asuccess +[Github Actions]: https://github.com/bjorn3/rustc_codegen_cranelift/actions?query=branch%3Amaster+event%3Apush+is%3Asuccess ## Usage diff --git a/build_system/mod.rs b/build_system/mod.rs index f2de07cf5eb85..d1932549ee675 100644 --- a/build_system/mod.rs +++ b/build_system/mod.rs @@ -15,32 +15,8 @@ mod rustc_info; mod tests; mod utils; -const USAGE: &str = r#"The build system of cg_clif. - -USAGE: - ./y.rs prepare [--out-dir DIR] - ./y.rs build [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] - ./y.rs test [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] - ./y.rs bench [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] - -OPTIONS: - --sysroot none|clif|llvm - Which sysroot libraries to use: - `none` will not include any standard library in the sysroot. - `clif` will build the standard library using Cranelift. - `llvm` will use the pre-compiled standard library of rustc which is compiled with LLVM. - - --out-dir DIR - Specify the directory in which the download, build and dist directories are stored. - By default this is the working directory. - - --no-unstable-features - fSome features are not yet ready for production usage. This option will disable these - features. This includes the JIT mode and inline assembly support. -"#; - fn usage() { - eprintln!("{USAGE}"); + eprintln!("{}", include_str!("usage.txt")); } macro_rules! arg_error { diff --git a/build_system/usage.txt b/build_system/usage.txt new file mode 100644 index 0000000000000..9185255155426 --- /dev/null +++ b/build_system/usage.txt @@ -0,0 +1,34 @@ +The build system of cg_clif. + +USAGE: + ./y.rs prepare [--out-dir DIR] + ./y.rs build [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] + ./y.rs test [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] + ./y.rs bench [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] + +OPTIONS: + --debug + Build cg_clif and the standard library in debug mode rather than release mode. + Warning: An unoptimized cg_clif is very slow. + + --sysroot none|clif|llvm + Which sysroot libraries to use: + `none` will not include any standard library in the sysroot. + `clif` will build the standard library using Cranelift. + `llvm` will use the pre-compiled standard library of rustc which is compiled with LLVM. + + --out-dir DIR + Specify the directory in which the download, build and dist directories are stored. + By default this is the working directory. + + --no-unstable-features + Some features are not yet ready for production usage. This option will disable these + features. This includes the JIT mode and inline assembly support. + +REQUIREMENTS: + * Rustup: The build system has a hard coded dependency on rustup to install the right nightly + version and make sure it is used where necessary. + * Git: `./y.rs prepare` uses git for applying patches and on Windows for downloading test repos. + * Curl and tar (non-Windows only): Used by `./y.rs prepare` to download a single commit for + repos. Git will be used to clone the whole repo when using Windows. + * [Hyperfine](https://github.com/sharkdp/hyperfine/): Used for benchmarking with `./y.rs bench`. From 8af4eacc8c6e8daad185cffef90ecad6919e34c1 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 13 Jan 2023 18:16:47 +0000 Subject: [PATCH 161/500] Update FreeBSD to 13.1 This fixes the certificate error --- .cirrus.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.cirrus.yml b/.cirrus.yml index 7c966aa1ab9a9..7886cae42a15a 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -1,7 +1,7 @@ task: name: freebsd freebsd_instance: - image: freebsd-12-1-release-amd64 + image: freebsd-13-1-release-amd64 setup_rust_script: - pkg install -y curl git bash - curl https://sh.rustup.rs -sSf --output rustup.sh From 2e2ae68d5a3ef0b8c0c968fd6ec4e859c77ed2f1 Mon Sep 17 00:00:00 2001 From: Tyler Weaver Date: Fri, 13 Jan 2023 11:38:34 -0700 Subject: [PATCH 162/500] Document lint configuration values in Clippy's book Signed-off-by: Tyler Weaver --- .github/workflows/remark.yml | 3 + README.md | 3 + book/src/SUMMARY.md | 1 + book/src/configuration.md | 3 + book/src/lint_configuration.md | 52 ++++++++++++++++ .../internal_lints/metadata_collector.rs | 62 +++++++++++++++++-- 6 files changed, 118 insertions(+), 6 deletions(-) create mode 100644 book/src/lint_configuration.md diff --git a/.github/workflows/remark.yml b/.github/workflows/remark.yml index 81ef072bbb07f..22925a753dfe7 100644 --- a/.github/workflows/remark.yml +++ b/.github/workflows/remark.yml @@ -33,6 +33,9 @@ jobs: echo `pwd`/mdbook >> $GITHUB_PATH # Run + - name: cargo collect-metadata + run: cargo collect-metadata + - name: Check *.md files run: git ls-files -z '*.md' | xargs -0 -n 1 -I {} ./node_modules/.bin/remark {} -u lint -f > /dev/null diff --git a/README.md b/README.md index c78ae06765d37..2ba095368ebf0 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,9 @@ disallowed-names = ["toto", "tata", "titi"] See the [list of configurable lints](https://rust-lang.github.io/rust-clippy/master/index.html#Configuration), the lint descriptions contain the names and meanings of these configuration variables. +See [table of lint configurations](https://doc.rust-lang.org/nightly/clippy/lint_configuration.html) +to see what configuration options you can set and the lints they configure. + For configurations that are a list type with default values such as [disallowed-names](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_names), you can use the unique value `".."` to extend the default values instead of replacing them. diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index 1f0b8db28a152..0649f7a631df4 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -5,6 +5,7 @@ - [Installation](installation.md) - [Usage](usage.md) - [Configuration](configuration.md) + - [Lint Configuration](lint_configuration.md) - [Clippy's Lints](lints.md) - [Continuous Integration](continuous_integration/README.md) - [GitHub Actions](continuous_integration/github_actions.md) diff --git a/book/src/configuration.md b/book/src/configuration.md index fac3e438c543e..e68f30be43cd0 100644 --- a/book/src/configuration.md +++ b/book/src/configuration.md @@ -13,6 +13,9 @@ disallowed-names = ["toto", "tata", "titi"] See the [list of configurable lints](https://rust-lang.github.io/rust-clippy/master/index.html#Configuration), the lint descriptions contain the names and meanings of these configuration variables. +See [table of lint configurations](./lint_configuration.md) +to see what configuration options you can set and the lints they configure. + For configurations that are a list type with default values such as [disallowed-names](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_names), you can use the unique value `".."` to extend the default values instead of replacing them. diff --git a/book/src/lint_configuration.md b/book/src/lint_configuration.md new file mode 100644 index 0000000000000..102ed7ad2cead --- /dev/null +++ b/book/src/lint_configuration.md @@ -0,0 +1,52 @@ +## Configuration Options + +| Option | Default | Description | Lints | +|--|--|--|--| +| arithmetic-side-effects-allowed | `{}` | Suppress checking of the passed type names in all types of operations | [arithmetic_side_effects](https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects) | +| arithmetic-side-effects-allowed-binary | `[]` | Suppress checking of the passed type pair names in binary operations like addition or multiplication | [arithmetic_side_effects](https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects) | +| arithmetic-side-effects-allowed-unary | `{}` | Suppress checking of the passed type names in unary operations like "negation" (`-`) | [arithmetic_side_effects](https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects) | +| avoid-breaking-exported-api | `true` | Suppress lints whenever the suggested change would cause breakage for other crates | [enum_variant_names](https://rust-lang.github.io/rust-clippy/master/index.html#enum_variant_names) [large_types_passed_by_value](https://rust-lang.github.io/rust-clippy/master/index.html#large_types_passed_by_value) [trivially_copy_pass_by_ref](https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref) [unnecessary_wraps](https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_wraps) [unused_self](https://rust-lang.github.io/rust-clippy/master/index.html#unused_self) [upper_case_acronyms](https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms) [wrong_self_convention](https://rust-lang.github.io/rust-clippy/master/index.html#wrong_self_convention) [box_collection](https://rust-lang.github.io/rust-clippy/master/index.html#box_collection) [redundant_allocation](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_allocation) [rc_buffer](https://rust-lang.github.io/rust-clippy/master/index.html#rc_buffer) [vec_box](https://rust-lang.github.io/rust-clippy/master/index.html#vec_box) [option_option](https://rust-lang.github.io/rust-clippy/master/index.html#option_option) [linkedlist](https://rust-lang.github.io/rust-clippy/master/index.html#linkedlist) [rc_mutex](https://rust-lang.github.io/rust-clippy/master/index.html#rc_mutex) | +| msrv | `None` | The minimum rust version that the project supports | [manual_split_once](https://rust-lang.github.io/rust-clippy/master/index.html#manual_split_once) [manual_str_repeat](https://rust-lang.github.io/rust-clippy/master/index.html#manual_str_repeat) [cloned_instead_of_copied](https://rust-lang.github.io/rust-clippy/master/index.html#cloned_instead_of_copied) [redundant_field_names](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_field_names) [redundant_static_lifetimes](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_static_lifetimes) [filter_map_next](https://rust-lang.github.io/rust-clippy/master/index.html#filter_map_next) [checked_conversions](https://rust-lang.github.io/rust-clippy/master/index.html#checked_conversions) [manual_range_contains](https://rust-lang.github.io/rust-clippy/master/index.html#manual_range_contains) [use_self](https://rust-lang.github.io/rust-clippy/master/index.html#use_self) [mem_replace_with_default](https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_with_default) [manual_non_exhaustive](https://rust-lang.github.io/rust-clippy/master/index.html#manual_non_exhaustive) [option_as_ref_deref](https://rust-lang.github.io/rust-clippy/master/index.html#option_as_ref_deref) [map_unwrap_or](https://rust-lang.github.io/rust-clippy/master/index.html#map_unwrap_or) [match_like_matches_macro](https://rust-lang.github.io/rust-clippy/master/index.html#match_like_matches_macro) [manual_strip](https://rust-lang.github.io/rust-clippy/master/index.html#manual_strip) [missing_const_for_fn](https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn) [unnested_or_patterns](https://rust-lang.github.io/rust-clippy/master/index.html#unnested_or_patterns) [from_over_into](https://rust-lang.github.io/rust-clippy/master/index.html#from_over_into) [ptr_as_ptr](https://rust-lang.github.io/rust-clippy/master/index.html#ptr_as_ptr) [if_then_some_else_none](https://rust-lang.github.io/rust-clippy/master/index.html#if_then_some_else_none) [approx_constant](https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant) [deprecated_cfg_attr](https://rust-lang.github.io/rust-clippy/master/index.html#deprecated_cfg_attr) [index_refutable_slice](https://rust-lang.github.io/rust-clippy/master/index.html#index_refutable_slice) [map_clone](https://rust-lang.github.io/rust-clippy/master/index.html#map_clone) [borrow_as_ptr](https://rust-lang.github.io/rust-clippy/master/index.html#borrow_as_ptr) [manual_bits](https://rust-lang.github.io/rust-clippy/master/index.html#manual_bits) [err_expect](https://rust-lang.github.io/rust-clippy/master/index.html#err_expect) [cast_abs_to_unsigned](https://rust-lang.github.io/rust-clippy/master/index.html#cast_abs_to_unsigned) [uninlined_format_args](https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args) [manual_clamp](https://rust-lang.github.io/rust-clippy/master/index.html#manual_clamp) [manual_let_else](https://rust-lang.github.io/rust-clippy/master/index.html#manual_let_else) [unchecked_duration_subtraction](https://rust-lang.github.io/rust-clippy/master/index.html#unchecked_duration_subtraction) | +| cognitive-complexity-threshold | `25` | The maximum cognitive complexity a function can have | [cognitive_complexity](https://rust-lang.github.io/rust-clippy/master/index.html#cognitive_complexity) | +| disallowed-names | `["foo", "baz", "quux"]` | The list of disallowed names to lint about | [disallowed_names](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_names) | +| doc-valid-idents | `["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "DirectX", "ECMAScript", "GPLv2", "GPLv3", "GitHub", "GitLab", "IPv4", "IPv6", "ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript", "NaN", "NaNs", "OAuth", "GraphQL", "OCaml", "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenDNS", "WebGL", "TensorFlow", "TrueType", "iOS", "macOS", "FreeBSD", "TeX", "LaTeX", "BibTeX", "BibLaTeX", "MinGW", "CamelCase"]` | The list of words this lint should not consider as identifiers needing ticks | [doc_markdown](https://rust-lang.github.io/rust-clippy/master/index.html#doc_markdown) | +| too-many-arguments-threshold | `7` | The maximum number of argument a function or method can have | [too_many_arguments](https://rust-lang.github.io/rust-clippy/master/index.html#too_many_arguments) | +| type-complexity-threshold | `250` | The maximum complexity a type can have | [type_complexity](https://rust-lang.github.io/rust-clippy/master/index.html#type_complexity) | +| single-char-binding-names-threshold | `4` | The maximum number of single char bindings a scope may have | [many_single_char_names](https://rust-lang.github.io/rust-clippy/master/index.html#many_single_char_names) | +| too-large-for-stack | `200` | The maximum size of objects (in bytes) that will be linted | [boxed_local](https://rust-lang.github.io/rust-clippy/master/index.html#boxed_local) [useless_vec](https://rust-lang.github.io/rust-clippy/master/index.html#useless_vec) | +| enum-variant-name-threshold | `3` | The minimum number of enum variants for the lints about variant names to trigger | [enum_variant_names](https://rust-lang.github.io/rust-clippy/master/index.html#enum_variant_names) | +| enum-variant-size-threshold | `200` | The maximum size of an enum's variant to avoid box suggestion | [large_enum_variant](https://rust-lang.github.io/rust-clippy/master/index.html#large_enum_variant) | +| verbose-bit-mask-threshold | `1` | The maximum allowed size of a bit mask before suggesting to use 'trailing_zeros' | [verbose_bit_mask](https://rust-lang.github.io/rust-clippy/master/index.html#verbose_bit_mask) | +| literal-representation-threshold | `16384` | The lower bound for linting decimal literals | [decimal_literal_representation](https://rust-lang.github.io/rust-clippy/master/index.html#decimal_literal_representation) | +| trivial-copy-size-limit | `None` | The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by reference | [trivially_copy_pass_by_ref](https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref) | +| pass-by-value-size-limit | `256` | The minimum size (in bytes) to consider a type for passing by reference instead of by value | [large_type_pass_by_move](https://rust-lang.github.io/rust-clippy/master/index.html#large_type_pass_by_move) | +| too-many-lines-threshold | `100` | The maximum number of lines a function or method can have | [too_many_lines](https://rust-lang.github.io/rust-clippy/master/index.html#too_many_lines) | +| array-size-threshold | `512000` | The maximum allowed size for arrays on the stack | [large_stack_arrays](https://rust-lang.github.io/rust-clippy/master/index.html#large_stack_arrays) [large_const_arrays](https://rust-lang.github.io/rust-clippy/master/index.html#large_const_arrays) | +| vec-box-size-threshold | `4096` | The size of the boxed type in bytes, where boxing in a `Vec` is allowed | [vec_box](https://rust-lang.github.io/rust-clippy/master/index.html#vec_box) | +| max-trait-bounds | `3` | The maximum number of bounds a trait can have to be linted | [type_repetition_in_bounds](https://rust-lang.github.io/rust-clippy/master/index.html#type_repetition_in_bounds) | +| max-struct-bools | `3` | The maximum number of bool fields a struct can have | [struct_excessive_bools](https://rust-lang.github.io/rust-clippy/master/index.html#struct_excessive_bools) | +| max-fn-params-bools | `3` | The maximum number of bool parameters a function can have | [fn_params_excessive_bools](https://rust-lang.github.io/rust-clippy/master/index.html#fn_params_excessive_bools) | +| warn-on-all-wildcard-imports | `false` | Whether to allow certain wildcard imports (prelude, super in tests) | [wildcard_imports](https://rust-lang.github.io/rust-clippy/master/index.html#wildcard_imports) | +| disallowed-macros | `[]` | The list of disallowed macros, written as fully qualified paths | [disallowed_macros](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_macros) | +| disallowed-methods | `[]` | The list of disallowed methods, written as fully qualified paths | [disallowed_methods](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_methods) | +| disallowed-types | `[]` | The list of disallowed types, written as fully qualified paths | [disallowed_types](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_types) | +| unreadable-literal-lint-fractions | `true` | Should the fraction of a decimal be linted to include separators | [unreadable_literal](https://rust-lang.github.io/rust-clippy/master/index.html#unreadable_literal) | +| upper-case-acronyms-aggressive | `false` | Enables verbose mode | [upper_case_acronyms](https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms) | +| matches-for-let-else | `WellKnownTypes` | Whether the matches should be considered by the lint, and whether there should be filtering for common types | [manual_let_else](https://rust-lang.github.io/rust-clippy/master/index.html#manual_let_else) | +| cargo-ignore-publish | `false` | For internal testing only, ignores the current `publish` settings in the Cargo manifest | [_cargo_common_metadata](https://rust-lang.github.io/rust-clippy/master/index.html#_cargo_common_metadata) | +| standard-macro-braces | `[]` | Enforce the named macros always use the braces specified | [nonstandard_macro_braces](https://rust-lang.github.io/rust-clippy/master/index.html#nonstandard_macro_braces) | +| enforced-import-renames | `[]` | The list of imports to always rename, a fully qualified path followed by the rename | [missing_enforced_import_renames](https://rust-lang.github.io/rust-clippy/master/index.html#missing_enforced_import_renames) | +| allowed-scripts | `["Latin"]` | The list of unicode scripts allowed to be used in the scope | [disallowed_script_idents](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_script_idents) | +| enable-raw-pointer-heuristic-for-send | `true` | Whether to apply the raw pointer heuristic to determine if a type is `Send` | [non_send_fields_in_send_ty](https://rust-lang.github.io/rust-clippy/master/index.html#non_send_fields_in_send_ty) | +| max-suggested-slice-pattern-length | `3` | When Clippy suggests using a slice pattern, this is the maximum number of elements allowed in the slice pattern that is suggested | [index_refutable_slice](https://rust-lang.github.io/rust-clippy/master/index.html#index_refutable_slice) | +| await-holding-invalid-types | `[]` | [ERROR] MALFORMED DOC COMMENT | | +| max-include-file-size | `1000000` | The maximum size of a file included via `include_bytes!()` or `include_str!()`, in bytes | [large_include_file](https://rust-lang.github.io/rust-clippy/master/index.html#large_include_file) | +| allow-expect-in-tests | `false` | Whether `expect` should be allowed within `#[cfg(test)]` | [expect_used](https://rust-lang.github.io/rust-clippy/master/index.html#expect_used) | +| allow-unwrap-in-tests | `false` | Whether `unwrap` should be allowed in test cfg | [unwrap_used](https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used) | +| allow-dbg-in-tests | `false` | Whether `dbg!` should be allowed in test functions | [dbg_macro](https://rust-lang.github.io/rust-clippy/master/index.html#dbg_macro) | +| allow-print-in-tests | `false` | Whether print macros (ex | [print_stdout](https://rust-lang.github.io/rust-clippy/master/index.html#print_stdout) [print_stderr](https://rust-lang.github.io/rust-clippy/master/index.html#print_stderr) | +| large-error-threshold | `128` | The maximum size of the `Err`-variant in a `Result` returned from a function | [result_large_err](https://rust-lang.github.io/rust-clippy/master/index.html#result_large_err) | +| ignore-interior-mutability | `["bytes::Bytes"]` | A list of paths to types that should be treated like `Arc`, i | [mutable_key](https://rust-lang.github.io/rust-clippy/master/index.html#mutable_key) | +| allow-mixed-uninlined-format-args | `true` | Whether to allow mixed uninlined format args, e | [uninlined_format_args](https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args) | +| suppress-restriction-lint-in-const | `false` | In same cases the restructured operation might not be unavoidable, as the suggested counterparts are unavailable in constant code | [indexing_slicing](https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicing) | + diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index 929544cd69d5b..c74f3b6e3ad6f 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -14,6 +14,7 @@ use clippy_utils::diagnostics::span_lint; use clippy_utils::ty::{match_type, walk_ptrs_ty_depth}; use clippy_utils::{last_path_segment, match_def_path, match_function_call, match_path, paths}; use if_chain::if_chain; +use itertools::Itertools; use rustc_ast as ast; use rustc_data_structures::fx::FxHashMap; use rustc_hir::{ @@ -34,8 +35,10 @@ use std::path::Path; use std::path::PathBuf; use std::process::Command; -/// This is the output file of the lint collector. -const OUTPUT_FILE: &str = "../util/gh-pages/lints.json"; +/// This is the json output file of the lint collector. +const JSON_OUTPUT_FILE: &str = "../util/gh-pages/lints.json"; +/// This is the markdown output file of the lint collector. +const MARKDOWN_OUTPUT_FILE: &str = "../book/src/lint_configuration.md"; /// These lints are excluded from the export. const BLACK_LISTED_LINTS: &[&str] = &["lint_author", "dump_hir", "internal_metadata_collector"]; /// These groups will be ignored by the lint group matcher. This is useful for collections like @@ -176,6 +179,14 @@ This lint has the following configuration variables: ) }) } + + fn get_markdown_table(&self) -> String { + self.config + .iter() + .filter(|config| config.deprecation_reason.is_none()) + .map(ClippyConfiguration::to_markdown_table_entry) + .join("\n") + } } impl Drop for MetadataCollector { @@ -199,12 +210,32 @@ impl Drop for MetadataCollector { collect_renames(&mut lints); - // Outputting - if Path::new(OUTPUT_FILE).exists() { - fs::remove_file(OUTPUT_FILE).unwrap(); + // Outputting json + if Path::new(JSON_OUTPUT_FILE).exists() { + fs::remove_file(JSON_OUTPUT_FILE).unwrap(); } - let mut file = OpenOptions::new().write(true).create(true).open(OUTPUT_FILE).unwrap(); + let mut file = OpenOptions::new() + .write(true) + .create(true) + .open(JSON_OUTPUT_FILE) + .unwrap(); writeln!(file, "{}", serde_json::to_string_pretty(&lints).unwrap()).unwrap(); + + // Outputting markdown + if Path::new(MARKDOWN_OUTPUT_FILE).exists() { + fs::remove_file(MARKDOWN_OUTPUT_FILE).unwrap(); + } + let mut file = OpenOptions::new() + .write(true) + .create(true) + .open(MARKDOWN_OUTPUT_FILE) + .unwrap(); + writeln!( + file, + "## Lint Configuration\n\n| Option | Default | Description | Lints |\n|--|--|--|--|\n{}\n", + self.get_markdown_table() + ) + .unwrap(); } } @@ -505,6 +536,25 @@ impl ClippyConfiguration { deprecation_reason, } } + + fn to_markdown_table_entry(&self) -> String { + format!( + "| {} | `{}` | {} | {} |", + self.name, + self.default, + self.doc + .split('.') + .next() + .unwrap_or("") + .replace('|', "\\|") + .replace("\n ", " "), + self.lints + .iter() + .map(|name| name.to_string().split_whitespace().next().unwrap().to_string()) + .map(|name| format!("[{name}](https://rust-lang.github.io/rust-clippy/master/index.html#{name})")) + .join(" ") + ) + } } fn collect_configs() -> Vec { From 9f2ba59647b2cc70ce9467f2731e707459bf388f Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Fri, 13 Jan 2023 22:23:59 +0100 Subject: [PATCH 163/500] Change not-so-permanent link to a more permanent link. --- compiler/rustc_ast_lowering/src/format.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index 8985f8ad85daf..776b532b0de86 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -225,7 +225,7 @@ fn expand_format_args<'hir>( // we don't do this, because an ArgumentV1 cannot be kept across yield points. // // This is an optimization, speeding up compilation about 1-2% in some cases. - // See https://perf.rust-lang.org/compare.html?start=5dbee4d3a6728eb4530fb66c9775834438ecec74&end=e36affffe97378a0027b4bcfbb18d27356164ed0&stat=instructions:u + // See https://github.com/rust-lang/rust/pull/106770#issuecomment-1380790609 let use_simple_array = argmap.len() == arguments.len() && argmap.iter().enumerate().all(|(i, &(j, _))| i == j) && arguments.iter().skip(1).all(|arg| !may_contain_yield_point(&arg.expr)); From a37b4842220a647902a25fcfe68a7d52cda056ad Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Fri, 13 Jan 2023 19:45:26 +0100 Subject: [PATCH 164/500] Allow fmt::Arguments::as_str() to return more Some(_). --- library/core/src/fmt/mod.rs | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index 51e6a76cea848..2dacdfd7a0237 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -484,9 +484,26 @@ pub struct Arguments<'a> { } impl<'a> Arguments<'a> { - /// Get the formatted string, if it has no arguments to be formatted. + /// Get the formatted string, if it has no arguments to be formatted at runtime. /// - /// This can be used to avoid allocations in the most trivial case. + /// This can be used to avoid allocations in some cases. + /// + /// # Guarantees + /// + /// For `format_args!("just a literal")`, this function is guaranteed to + /// return `Some("just a literal")`. + /// + /// For most cases with placeholders, this function will return `None`. + /// + /// However, the compiler may perform optimizations that can cause this + /// function to return `Some(_)` even if the format string contains + /// placeholders. For example, `format_args!("Hello, {}!", "world")` may be + /// optimized to `format_args!("Hello, world!")`, such that `as_str()` + /// returns `Some("Hello, world!")`. + /// + /// The behavior for anything but the trivial case (without placeholders) + /// is not guaranteed, and should not be relied upon for anything other + /// than optimization. /// /// # Examples /// @@ -507,7 +524,7 @@ impl<'a> Arguments<'a> { /// ```rust /// assert_eq!(format_args!("hello").as_str(), Some("hello")); /// assert_eq!(format_args!("").as_str(), Some("")); - /// assert_eq!(format_args!("{}", 1).as_str(), None); + /// assert_eq!(format_args!("{:?}", std::env::current_dir()).as_str(), None); /// ``` #[stable(feature = "fmt_as_str", since = "1.52.0")] #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "103900")] From 93d0f470640de319c9cad441509cfd0f55d84172 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 30 Nov 2022 20:41:02 +0000 Subject: [PATCH 165/500] Check ADT fields for copy implementations considering regions --- clippy_lints/src/needless_pass_by_value.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/needless_pass_by_value.rs b/clippy_lints/src/needless_pass_by_value.rs index 1249db5dc4792..8c9d4c5cfe66f 100644 --- a/clippy_lints/src/needless_pass_by_value.rs +++ b/clippy_lints/src/needless_pass_by_value.rs @@ -24,7 +24,7 @@ use rustc_span::symbol::kw; use rustc_span::{sym, Span}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits; -use rustc_trait_selection::traits::misc::can_type_implement_copy; +use rustc_trait_selection::traits::misc::type_allowed_to_implement_copy; use std::borrow::Cow; declare_clippy_lint! { @@ -200,7 +200,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { let sugg = |diag: &mut Diagnostic| { if let ty::Adt(def, ..) = ty.kind() { if let Some(span) = cx.tcx.hir().span_if_local(def.did()) { - if can_type_implement_copy( + if type_allowed_to_implement_copy( cx.tcx, cx.param_env, ty, From 93f602f1cf324e89ec1312583cb033eeb977fa73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maria=20Jos=C3=A9=20Solano?= Date: Fri, 13 Jan 2023 15:21:49 -0800 Subject: [PATCH 166/500] Add missing arguments to cargo lint example --- book/src/development/adding_lints.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book/src/development/adding_lints.md b/book/src/development/adding_lints.md index 8b4eee8c9d94d..145b393b75356 100644 --- a/book/src/development/adding_lints.md +++ b/book/src/development/adding_lints.md @@ -146,7 +146,7 @@ For cargo lints, the process of testing differs in that we are interested in the manifest. If our new lint is named e.g. `foo_categories`, after running `cargo dev -new_lint` we will find by default two new crates, each with its manifest file: +new_lint --name=foo_categories --type=cargo --category=cargo` we will find by default two new crates, each with its manifest file: * `tests/ui-cargo/foo_categories/fail/Cargo.toml`: this file should cause the new lint to raise an error. From 7d1609dce356b9b603702f1ba0011f2fee949787 Mon Sep 17 00:00:00 2001 From: Tyler Weaver Date: Fri, 13 Jan 2023 15:32:04 -0700 Subject: [PATCH 167/500] Document configurations in table and paragraphs Signed-off-by: Tyler Weaver --- README.md | 9 +- book/src/configuration.md | 9 +- book/src/lint_configuration.md | 568 ++++++++++++++++-- clippy_lints/src/utils/conf.rs | 3 +- .../internal_lints/metadata_collector.rs | 43 +- 5 files changed, 552 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index 2ba095368ebf0..ab44db694835f 100644 --- a/README.md +++ b/README.md @@ -196,11 +196,10 @@ avoid-breaking-exported-api = false disallowed-names = ["toto", "tata", "titi"] ``` -See the [list of configurable lints](https://rust-lang.github.io/rust-clippy/master/index.html#Configuration), -the lint descriptions contain the names and meanings of these configuration variables. - -See [table of lint configurations](https://doc.rust-lang.org/nightly/clippy/lint_configuration.html) -to see what configuration options you can set and the lints they configure. +The [table of configurations](https://doc.rust-lang.org/nightly/clippy/lint_configuration.html) +contains all config values, their default, and a list of lints they affect. +Each [configurable lint](https://rust-lang.github.io/rust-clippy/master/index.html#Configuration) +, also contains information about these values. For configurations that are a list type with default values such as [disallowed-names](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_names), diff --git a/book/src/configuration.md b/book/src/configuration.md index e68f30be43cd0..87f4a697af9fd 100644 --- a/book/src/configuration.md +++ b/book/src/configuration.md @@ -10,11 +10,10 @@ avoid-breaking-exported-api = false disallowed-names = ["toto", "tata", "titi"] ``` -See the [list of configurable lints](https://rust-lang.github.io/rust-clippy/master/index.html#Configuration), -the lint descriptions contain the names and meanings of these configuration variables. - -See [table of lint configurations](./lint_configuration.md) -to see what configuration options you can set and the lints they configure. +The [table of configurations](./lint_configuration.md) +contains all config values, their default, and a list of lints they affect. +Each [configurable lint](https://rust-lang.github.io/rust-clippy/master/index.html#Configuration) +, also contains information about these values. For configurations that are a list type with default values such as [disallowed-names](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_names), diff --git a/book/src/lint_configuration.md b/book/src/lint_configuration.md index 102ed7ad2cead..cfaaefe3ea18e 100644 --- a/book/src/lint_configuration.md +++ b/book/src/lint_configuration.md @@ -1,52 +1,518 @@ -## Configuration Options - -| Option | Default | Description | Lints | -|--|--|--|--| -| arithmetic-side-effects-allowed | `{}` | Suppress checking of the passed type names in all types of operations | [arithmetic_side_effects](https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects) | -| arithmetic-side-effects-allowed-binary | `[]` | Suppress checking of the passed type pair names in binary operations like addition or multiplication | [arithmetic_side_effects](https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects) | -| arithmetic-side-effects-allowed-unary | `{}` | Suppress checking of the passed type names in unary operations like "negation" (`-`) | [arithmetic_side_effects](https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects) | -| avoid-breaking-exported-api | `true` | Suppress lints whenever the suggested change would cause breakage for other crates | [enum_variant_names](https://rust-lang.github.io/rust-clippy/master/index.html#enum_variant_names) [large_types_passed_by_value](https://rust-lang.github.io/rust-clippy/master/index.html#large_types_passed_by_value) [trivially_copy_pass_by_ref](https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref) [unnecessary_wraps](https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_wraps) [unused_self](https://rust-lang.github.io/rust-clippy/master/index.html#unused_self) [upper_case_acronyms](https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms) [wrong_self_convention](https://rust-lang.github.io/rust-clippy/master/index.html#wrong_self_convention) [box_collection](https://rust-lang.github.io/rust-clippy/master/index.html#box_collection) [redundant_allocation](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_allocation) [rc_buffer](https://rust-lang.github.io/rust-clippy/master/index.html#rc_buffer) [vec_box](https://rust-lang.github.io/rust-clippy/master/index.html#vec_box) [option_option](https://rust-lang.github.io/rust-clippy/master/index.html#option_option) [linkedlist](https://rust-lang.github.io/rust-clippy/master/index.html#linkedlist) [rc_mutex](https://rust-lang.github.io/rust-clippy/master/index.html#rc_mutex) | -| msrv | `None` | The minimum rust version that the project supports | [manual_split_once](https://rust-lang.github.io/rust-clippy/master/index.html#manual_split_once) [manual_str_repeat](https://rust-lang.github.io/rust-clippy/master/index.html#manual_str_repeat) [cloned_instead_of_copied](https://rust-lang.github.io/rust-clippy/master/index.html#cloned_instead_of_copied) [redundant_field_names](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_field_names) [redundant_static_lifetimes](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_static_lifetimes) [filter_map_next](https://rust-lang.github.io/rust-clippy/master/index.html#filter_map_next) [checked_conversions](https://rust-lang.github.io/rust-clippy/master/index.html#checked_conversions) [manual_range_contains](https://rust-lang.github.io/rust-clippy/master/index.html#manual_range_contains) [use_self](https://rust-lang.github.io/rust-clippy/master/index.html#use_self) [mem_replace_with_default](https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_with_default) [manual_non_exhaustive](https://rust-lang.github.io/rust-clippy/master/index.html#manual_non_exhaustive) [option_as_ref_deref](https://rust-lang.github.io/rust-clippy/master/index.html#option_as_ref_deref) [map_unwrap_or](https://rust-lang.github.io/rust-clippy/master/index.html#map_unwrap_or) [match_like_matches_macro](https://rust-lang.github.io/rust-clippy/master/index.html#match_like_matches_macro) [manual_strip](https://rust-lang.github.io/rust-clippy/master/index.html#manual_strip) [missing_const_for_fn](https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn) [unnested_or_patterns](https://rust-lang.github.io/rust-clippy/master/index.html#unnested_or_patterns) [from_over_into](https://rust-lang.github.io/rust-clippy/master/index.html#from_over_into) [ptr_as_ptr](https://rust-lang.github.io/rust-clippy/master/index.html#ptr_as_ptr) [if_then_some_else_none](https://rust-lang.github.io/rust-clippy/master/index.html#if_then_some_else_none) [approx_constant](https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant) [deprecated_cfg_attr](https://rust-lang.github.io/rust-clippy/master/index.html#deprecated_cfg_attr) [index_refutable_slice](https://rust-lang.github.io/rust-clippy/master/index.html#index_refutable_slice) [map_clone](https://rust-lang.github.io/rust-clippy/master/index.html#map_clone) [borrow_as_ptr](https://rust-lang.github.io/rust-clippy/master/index.html#borrow_as_ptr) [manual_bits](https://rust-lang.github.io/rust-clippy/master/index.html#manual_bits) [err_expect](https://rust-lang.github.io/rust-clippy/master/index.html#err_expect) [cast_abs_to_unsigned](https://rust-lang.github.io/rust-clippy/master/index.html#cast_abs_to_unsigned) [uninlined_format_args](https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args) [manual_clamp](https://rust-lang.github.io/rust-clippy/master/index.html#manual_clamp) [manual_let_else](https://rust-lang.github.io/rust-clippy/master/index.html#manual_let_else) [unchecked_duration_subtraction](https://rust-lang.github.io/rust-clippy/master/index.html#unchecked_duration_subtraction) | -| cognitive-complexity-threshold | `25` | The maximum cognitive complexity a function can have | [cognitive_complexity](https://rust-lang.github.io/rust-clippy/master/index.html#cognitive_complexity) | -| disallowed-names | `["foo", "baz", "quux"]` | The list of disallowed names to lint about | [disallowed_names](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_names) | -| doc-valid-idents | `["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "DirectX", "ECMAScript", "GPLv2", "GPLv3", "GitHub", "GitLab", "IPv4", "IPv6", "ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript", "NaN", "NaNs", "OAuth", "GraphQL", "OCaml", "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenDNS", "WebGL", "TensorFlow", "TrueType", "iOS", "macOS", "FreeBSD", "TeX", "LaTeX", "BibTeX", "BibLaTeX", "MinGW", "CamelCase"]` | The list of words this lint should not consider as identifiers needing ticks | [doc_markdown](https://rust-lang.github.io/rust-clippy/master/index.html#doc_markdown) | -| too-many-arguments-threshold | `7` | The maximum number of argument a function or method can have | [too_many_arguments](https://rust-lang.github.io/rust-clippy/master/index.html#too_many_arguments) | -| type-complexity-threshold | `250` | The maximum complexity a type can have | [type_complexity](https://rust-lang.github.io/rust-clippy/master/index.html#type_complexity) | -| single-char-binding-names-threshold | `4` | The maximum number of single char bindings a scope may have | [many_single_char_names](https://rust-lang.github.io/rust-clippy/master/index.html#many_single_char_names) | -| too-large-for-stack | `200` | The maximum size of objects (in bytes) that will be linted | [boxed_local](https://rust-lang.github.io/rust-clippy/master/index.html#boxed_local) [useless_vec](https://rust-lang.github.io/rust-clippy/master/index.html#useless_vec) | -| enum-variant-name-threshold | `3` | The minimum number of enum variants for the lints about variant names to trigger | [enum_variant_names](https://rust-lang.github.io/rust-clippy/master/index.html#enum_variant_names) | -| enum-variant-size-threshold | `200` | The maximum size of an enum's variant to avoid box suggestion | [large_enum_variant](https://rust-lang.github.io/rust-clippy/master/index.html#large_enum_variant) | -| verbose-bit-mask-threshold | `1` | The maximum allowed size of a bit mask before suggesting to use 'trailing_zeros' | [verbose_bit_mask](https://rust-lang.github.io/rust-clippy/master/index.html#verbose_bit_mask) | -| literal-representation-threshold | `16384` | The lower bound for linting decimal literals | [decimal_literal_representation](https://rust-lang.github.io/rust-clippy/master/index.html#decimal_literal_representation) | -| trivial-copy-size-limit | `None` | The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by reference | [trivially_copy_pass_by_ref](https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref) | -| pass-by-value-size-limit | `256` | The minimum size (in bytes) to consider a type for passing by reference instead of by value | [large_type_pass_by_move](https://rust-lang.github.io/rust-clippy/master/index.html#large_type_pass_by_move) | -| too-many-lines-threshold | `100` | The maximum number of lines a function or method can have | [too_many_lines](https://rust-lang.github.io/rust-clippy/master/index.html#too_many_lines) | -| array-size-threshold | `512000` | The maximum allowed size for arrays on the stack | [large_stack_arrays](https://rust-lang.github.io/rust-clippy/master/index.html#large_stack_arrays) [large_const_arrays](https://rust-lang.github.io/rust-clippy/master/index.html#large_const_arrays) | -| vec-box-size-threshold | `4096` | The size of the boxed type in bytes, where boxing in a `Vec` is allowed | [vec_box](https://rust-lang.github.io/rust-clippy/master/index.html#vec_box) | -| max-trait-bounds | `3` | The maximum number of bounds a trait can have to be linted | [type_repetition_in_bounds](https://rust-lang.github.io/rust-clippy/master/index.html#type_repetition_in_bounds) | -| max-struct-bools | `3` | The maximum number of bool fields a struct can have | [struct_excessive_bools](https://rust-lang.github.io/rust-clippy/master/index.html#struct_excessive_bools) | -| max-fn-params-bools | `3` | The maximum number of bool parameters a function can have | [fn_params_excessive_bools](https://rust-lang.github.io/rust-clippy/master/index.html#fn_params_excessive_bools) | -| warn-on-all-wildcard-imports | `false` | Whether to allow certain wildcard imports (prelude, super in tests) | [wildcard_imports](https://rust-lang.github.io/rust-clippy/master/index.html#wildcard_imports) | -| disallowed-macros | `[]` | The list of disallowed macros, written as fully qualified paths | [disallowed_macros](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_macros) | -| disallowed-methods | `[]` | The list of disallowed methods, written as fully qualified paths | [disallowed_methods](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_methods) | -| disallowed-types | `[]` | The list of disallowed types, written as fully qualified paths | [disallowed_types](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_types) | -| unreadable-literal-lint-fractions | `true` | Should the fraction of a decimal be linted to include separators | [unreadable_literal](https://rust-lang.github.io/rust-clippy/master/index.html#unreadable_literal) | -| upper-case-acronyms-aggressive | `false` | Enables verbose mode | [upper_case_acronyms](https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms) | -| matches-for-let-else | `WellKnownTypes` | Whether the matches should be considered by the lint, and whether there should be filtering for common types | [manual_let_else](https://rust-lang.github.io/rust-clippy/master/index.html#manual_let_else) | -| cargo-ignore-publish | `false` | For internal testing only, ignores the current `publish` settings in the Cargo manifest | [_cargo_common_metadata](https://rust-lang.github.io/rust-clippy/master/index.html#_cargo_common_metadata) | -| standard-macro-braces | `[]` | Enforce the named macros always use the braces specified | [nonstandard_macro_braces](https://rust-lang.github.io/rust-clippy/master/index.html#nonstandard_macro_braces) | -| enforced-import-renames | `[]` | The list of imports to always rename, a fully qualified path followed by the rename | [missing_enforced_import_renames](https://rust-lang.github.io/rust-clippy/master/index.html#missing_enforced_import_renames) | -| allowed-scripts | `["Latin"]` | The list of unicode scripts allowed to be used in the scope | [disallowed_script_idents](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_script_idents) | -| enable-raw-pointer-heuristic-for-send | `true` | Whether to apply the raw pointer heuristic to determine if a type is `Send` | [non_send_fields_in_send_ty](https://rust-lang.github.io/rust-clippy/master/index.html#non_send_fields_in_send_ty) | -| max-suggested-slice-pattern-length | `3` | When Clippy suggests using a slice pattern, this is the maximum number of elements allowed in the slice pattern that is suggested | [index_refutable_slice](https://rust-lang.github.io/rust-clippy/master/index.html#index_refutable_slice) | -| await-holding-invalid-types | `[]` | [ERROR] MALFORMED DOC COMMENT | | -| max-include-file-size | `1000000` | The maximum size of a file included via `include_bytes!()` or `include_str!()`, in bytes | [large_include_file](https://rust-lang.github.io/rust-clippy/master/index.html#large_include_file) | -| allow-expect-in-tests | `false` | Whether `expect` should be allowed within `#[cfg(test)]` | [expect_used](https://rust-lang.github.io/rust-clippy/master/index.html#expect_used) | -| allow-unwrap-in-tests | `false` | Whether `unwrap` should be allowed in test cfg | [unwrap_used](https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used) | -| allow-dbg-in-tests | `false` | Whether `dbg!` should be allowed in test functions | [dbg_macro](https://rust-lang.github.io/rust-clippy/master/index.html#dbg_macro) | -| allow-print-in-tests | `false` | Whether print macros (ex | [print_stdout](https://rust-lang.github.io/rust-clippy/master/index.html#print_stdout) [print_stderr](https://rust-lang.github.io/rust-clippy/master/index.html#print_stderr) | -| large-error-threshold | `128` | The maximum size of the `Err`-variant in a `Result` returned from a function | [result_large_err](https://rust-lang.github.io/rust-clippy/master/index.html#result_large_err) | -| ignore-interior-mutability | `["bytes::Bytes"]` | A list of paths to types that should be treated like `Arc`, i | [mutable_key](https://rust-lang.github.io/rust-clippy/master/index.html#mutable_key) | -| allow-mixed-uninlined-format-args | `true` | Whether to allow mixed uninlined format args, e | [uninlined_format_args](https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args) | -| suppress-restriction-lint-in-const | `false` | In same cases the restructured operation might not be unavoidable, as the suggested counterparts are unavailable in constant code | [indexing_slicing](https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicing) | +## Lint Configuration Options +|
Option
| Default Value | +|--|--| +| [arithmetic-side-effects-allowed](#arithmetic-side-effects-allowed) | `{}` | +| [arithmetic-side-effects-allowed-binary](#arithmetic-side-effects-allowed-binary) | `[]` | +| [arithmetic-side-effects-allowed-unary](#arithmetic-side-effects-allowed-unary) | `{}` | +| [avoid-breaking-exported-api](#avoid-breaking-exported-api) | `true` | +| [msrv](#msrv) | `None` | +| [cognitive-complexity-threshold](#cognitive-complexity-threshold) | `25` | +| [disallowed-names](#disallowed-names) | `["foo", "baz", "quux"]` | +| [doc-valid-idents](#doc-valid-idents) | `["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "DirectX", "ECMAScript", "GPLv2", "GPLv3", "GitHub", "GitLab", "IPv4", "IPv6", "ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript", "NaN", "NaNs", "OAuth", "GraphQL", "OCaml", "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenDNS", "WebGL", "TensorFlow", "TrueType", "iOS", "macOS", "FreeBSD", "TeX", "LaTeX", "BibTeX", "BibLaTeX", "MinGW", "CamelCase"]` | +| [too-many-arguments-threshold](#too-many-arguments-threshold) | `7` | +| [type-complexity-threshold](#type-complexity-threshold) | `250` | +| [single-char-binding-names-threshold](#single-char-binding-names-threshold) | `4` | +| [too-large-for-stack](#too-large-for-stack) | `200` | +| [enum-variant-name-threshold](#enum-variant-name-threshold) | `3` | +| [enum-variant-size-threshold](#enum-variant-size-threshold) | `200` | +| [verbose-bit-mask-threshold](#verbose-bit-mask-threshold) | `1` | +| [literal-representation-threshold](#literal-representation-threshold) | `16384` | +| [trivial-copy-size-limit](#trivial-copy-size-limit) | `None` | +| [pass-by-value-size-limit](#pass-by-value-size-limit) | `256` | +| [too-many-lines-threshold](#too-many-lines-threshold) | `100` | +| [array-size-threshold](#array-size-threshold) | `512000` | +| [vec-box-size-threshold](#vec-box-size-threshold) | `4096` | +| [max-trait-bounds](#max-trait-bounds) | `3` | +| [max-struct-bools](#max-struct-bools) | `3` | +| [max-fn-params-bools](#max-fn-params-bools) | `3` | +| [warn-on-all-wildcard-imports](#warn-on-all-wildcard-imports) | `false` | +| [disallowed-macros](#disallowed-macros) | `[]` | +| [disallowed-methods](#disallowed-methods) | `[]` | +| [disallowed-types](#disallowed-types) | `[]` | +| [unreadable-literal-lint-fractions](#unreadable-literal-lint-fractions) | `true` | +| [upper-case-acronyms-aggressive](#upper-case-acronyms-aggressive) | `false` | +| [matches-for-let-else](#matches-for-let-else) | `WellKnownTypes` | +| [cargo-ignore-publish](#cargo-ignore-publish) | `false` | +| [standard-macro-braces](#standard-macro-braces) | `[]` | +| [enforced-import-renames](#enforced-import-renames) | `[]` | +| [allowed-scripts](#allowed-scripts) | `["Latin"]` | +| [enable-raw-pointer-heuristic-for-send](#enable-raw-pointer-heuristic-for-send) | `true` | +| [max-suggested-slice-pattern-length](#max-suggested-slice-pattern-length) | `3` | +| [max-include-file-size](#max-include-file-size) | `1000000` | +| [allow-expect-in-tests](#allow-expect-in-tests) | `false` | +| [allow-unwrap-in-tests](#allow-unwrap-in-tests) | `false` | +| [allow-dbg-in-tests](#allow-dbg-in-tests) | `false` | +| [allow-print-in-tests](#allow-print-in-tests) | `false` | +| [large-error-threshold](#large-error-threshold) | `128` | +| [ignore-interior-mutability](#ignore-interior-mutability) | `["bytes::Bytes"]` | +| [allow-mixed-uninlined-format-args](#allow-mixed-uninlined-format-args) | `true` | +| [suppress-restriction-lint-in-const](#suppress-restriction-lint-in-const) | `false` | + +### arithmetic-side-effects-allowed +Suppress checking of the passed type names in all types of operations. + +If a specific operation is desired, consider using `arithmetic_side_effects_allowed_binary` or `arithmetic_side_effects_allowed_unary` instead. + +#### Example + +```toml +arithmetic-side-effects-allowed = ["SomeType", "AnotherType"] +``` + +#### Noteworthy + +A type, say `SomeType`, listed in this configuration has the same behavior of +`["SomeType" , "*"], ["*", "SomeType"]` in `arithmetic_side_effects_allowed_binary`. + +**Default Value:** `{}` (`rustc_data_structures::fx::FxHashSet`) + +* [arithmetic_side_effects](https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects) + + +### arithmetic-side-effects-allowed-binary +Suppress checking of the passed type pair names in binary operations like addition or +multiplication. + +Supports the "*" wildcard to indicate that a certain type won't trigger the lint regardless +of the involved counterpart. For example, `["SomeType", "*"]` or `["*", "AnotherType"]`. + +Pairs are asymmetric, which means that `["SomeType", "AnotherType"]` is not the same as +`["AnotherType", "SomeType"]`. + +#### Example + +```toml +arithmetic-side-effects-allowed-binary = [["SomeType" , "f32"], ["AnotherType", "*"]] +``` + +**Default Value:** `[]` (`Vec<[String; 2]>`) + +* [arithmetic_side_effects](https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects) + + +### arithmetic-side-effects-allowed-unary +Suppress checking of the passed type names in unary operations like "negation" (`-`). + +#### Example + +```toml +arithmetic-side-effects-allowed-unary = ["SomeType", "AnotherType"] +``` + +**Default Value:** `{}` (`rustc_data_structures::fx::FxHashSet`) + +* [arithmetic_side_effects](https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects) + + +### avoid-breaking-exported-api +Suppress lints whenever the suggested change would cause breakage for other crates. + +**Default Value:** `true` (`bool`) + +* [enum_variant_names](https://rust-lang.github.io/rust-clippy/master/index.html#enum_variant_names) +* [large_types_passed_by_value](https://rust-lang.github.io/rust-clippy/master/index.html#large_types_passed_by_value) +* [trivially_copy_pass_by_ref](https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref) +* [unnecessary_wraps](https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_wraps) +* [unused_self](https://rust-lang.github.io/rust-clippy/master/index.html#unused_self) +* [upper_case_acronyms](https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms) +* [wrong_self_convention](https://rust-lang.github.io/rust-clippy/master/index.html#wrong_self_convention) +* [box_collection](https://rust-lang.github.io/rust-clippy/master/index.html#box_collection) +* [redundant_allocation](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_allocation) +* [rc_buffer](https://rust-lang.github.io/rust-clippy/master/index.html#rc_buffer) +* [vec_box](https://rust-lang.github.io/rust-clippy/master/index.html#vec_box) +* [option_option](https://rust-lang.github.io/rust-clippy/master/index.html#option_option) +* [linkedlist](https://rust-lang.github.io/rust-clippy/master/index.html#linkedlist) +* [rc_mutex](https://rust-lang.github.io/rust-clippy/master/index.html#rc_mutex) + + +### msrv +The minimum rust version that the project supports + +**Default Value:** `None` (`Option`) + +* [manual_split_once](https://rust-lang.github.io/rust-clippy/master/index.html#manual_split_once) +* [manual_str_repeat](https://rust-lang.github.io/rust-clippy/master/index.html#manual_str_repeat) +* [cloned_instead_of_copied](https://rust-lang.github.io/rust-clippy/master/index.html#cloned_instead_of_copied) +* [redundant_field_names](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_field_names) +* [redundant_static_lifetimes](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_static_lifetimes) +* [filter_map_next](https://rust-lang.github.io/rust-clippy/master/index.html#filter_map_next) +* [checked_conversions](https://rust-lang.github.io/rust-clippy/master/index.html#checked_conversions) +* [manual_range_contains](https://rust-lang.github.io/rust-clippy/master/index.html#manual_range_contains) +* [use_self](https://rust-lang.github.io/rust-clippy/master/index.html#use_self) +* [mem_replace_with_default](https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_with_default) +* [manual_non_exhaustive](https://rust-lang.github.io/rust-clippy/master/index.html#manual_non_exhaustive) +* [option_as_ref_deref](https://rust-lang.github.io/rust-clippy/master/index.html#option_as_ref_deref) +* [map_unwrap_or](https://rust-lang.github.io/rust-clippy/master/index.html#map_unwrap_or) +* [match_like_matches_macro](https://rust-lang.github.io/rust-clippy/master/index.html#match_like_matches_macro) +* [manual_strip](https://rust-lang.github.io/rust-clippy/master/index.html#manual_strip) +* [missing_const_for_fn](https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn) +* [unnested_or_patterns](https://rust-lang.github.io/rust-clippy/master/index.html#unnested_or_patterns) +* [from_over_into](https://rust-lang.github.io/rust-clippy/master/index.html#from_over_into) +* [ptr_as_ptr](https://rust-lang.github.io/rust-clippy/master/index.html#ptr_as_ptr) +* [if_then_some_else_none](https://rust-lang.github.io/rust-clippy/master/index.html#if_then_some_else_none) +* [approx_constant](https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant) +* [deprecated_cfg_attr](https://rust-lang.github.io/rust-clippy/master/index.html#deprecated_cfg_attr) +* [index_refutable_slice](https://rust-lang.github.io/rust-clippy/master/index.html#index_refutable_slice) +* [map_clone](https://rust-lang.github.io/rust-clippy/master/index.html#map_clone) +* [borrow_as_ptr](https://rust-lang.github.io/rust-clippy/master/index.html#borrow_as_ptr) +* [manual_bits](https://rust-lang.github.io/rust-clippy/master/index.html#manual_bits) +* [err_expect](https://rust-lang.github.io/rust-clippy/master/index.html#err_expect) +* [cast_abs_to_unsigned](https://rust-lang.github.io/rust-clippy/master/index.html#cast_abs_to_unsigned) +* [uninlined_format_args](https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args) +* [manual_clamp](https://rust-lang.github.io/rust-clippy/master/index.html#manual_clamp) +* [manual_let_else](https://rust-lang.github.io/rust-clippy/master/index.html#manual_let_else) +* [unchecked_duration_subtraction](https://rust-lang.github.io/rust-clippy/master/index.html#unchecked_duration_subtraction) + + +### cognitive-complexity-threshold +The maximum cognitive complexity a function can have + +**Default Value:** `25` (`u64`) + +* [cognitive_complexity](https://rust-lang.github.io/rust-clippy/master/index.html#cognitive_complexity) + + +### disallowed-names +The list of disallowed names to lint about. NB: `bar` is not here since it has legitimate uses. The value +`".."` can be used as part of the list to indicate, that the configured values should be appended to the +default configuration of Clippy. By default any configuration will replace the default value. + +**Default Value:** `["foo", "baz", "quux"]` (`Vec`) + +* [disallowed_names](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_names) + + +### doc-valid-idents +The list of words this lint should not consider as identifiers needing ticks. The value +`".."` can be used as part of the list to indicate, that the configured values should be appended to the +default configuration of Clippy. By default any configuraction will replace the default value. For example: +* `doc-valid-idents = ["ClipPy"]` would replace the default list with `["ClipPy"]`. +* `doc-valid-idents = ["ClipPy", ".."]` would append `ClipPy` to the default list. + +Default list: + +**Default Value:** `["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "DirectX", "ECMAScript", "GPLv2", "GPLv3", "GitHub", "GitLab", "IPv4", "IPv6", "ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript", "NaN", "NaNs", "OAuth", "GraphQL", "OCaml", "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenDNS", "WebGL", "TensorFlow", "TrueType", "iOS", "macOS", "FreeBSD", "TeX", "LaTeX", "BibTeX", "BibLaTeX", "MinGW", "CamelCase"]` (`Vec`) + +* [doc_markdown](https://rust-lang.github.io/rust-clippy/master/index.html#doc_markdown) + + +### too-many-arguments-threshold +The maximum number of argument a function or method can have + +**Default Value:** `7` (`u64`) + +* [too_many_arguments](https://rust-lang.github.io/rust-clippy/master/index.html#too_many_arguments) + + +### type-complexity-threshold +The maximum complexity a type can have + +**Default Value:** `250` (`u64`) + +* [type_complexity](https://rust-lang.github.io/rust-clippy/master/index.html#type_complexity) + + +### single-char-binding-names-threshold +The maximum number of single char bindings a scope may have + +**Default Value:** `4` (`u64`) + +* [many_single_char_names](https://rust-lang.github.io/rust-clippy/master/index.html#many_single_char_names) + + +### too-large-for-stack +The maximum size of objects (in bytes) that will be linted. Larger objects are ok on the heap + +**Default Value:** `200` (`u64`) + +* [boxed_local](https://rust-lang.github.io/rust-clippy/master/index.html#boxed_local) +* [useless_vec](https://rust-lang.github.io/rust-clippy/master/index.html#useless_vec) + + +### enum-variant-name-threshold +The minimum number of enum variants for the lints about variant names to trigger + +**Default Value:** `3` (`u64`) + +* [enum_variant_names](https://rust-lang.github.io/rust-clippy/master/index.html#enum_variant_names) + + +### enum-variant-size-threshold +The maximum size of an enum's variant to avoid box suggestion + +**Default Value:** `200` (`u64`) + +* [large_enum_variant](https://rust-lang.github.io/rust-clippy/master/index.html#large_enum_variant) + + +### verbose-bit-mask-threshold +The maximum allowed size of a bit mask before suggesting to use 'trailing_zeros' + +**Default Value:** `1` (`u64`) + +* [verbose_bit_mask](https://rust-lang.github.io/rust-clippy/master/index.html#verbose_bit_mask) + + +### literal-representation-threshold +The lower bound for linting decimal literals + +**Default Value:** `16384` (`u64`) + +* [decimal_literal_representation](https://rust-lang.github.io/rust-clippy/master/index.html#decimal_literal_representation) + + +### trivial-copy-size-limit +The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by reference. + +**Default Value:** `None` (`Option`) + +* [trivially_copy_pass_by_ref](https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref) + + +### pass-by-value-size-limit +The minimum size (in bytes) to consider a type for passing by reference instead of by value. + +**Default Value:** `256` (`u64`) + +* [large_type_pass_by_move](https://rust-lang.github.io/rust-clippy/master/index.html#large_type_pass_by_move) + + +### too-many-lines-threshold +The maximum number of lines a function or method can have + +**Default Value:** `100` (`u64`) + +* [too_many_lines](https://rust-lang.github.io/rust-clippy/master/index.html#too_many_lines) + + +### array-size-threshold +The maximum allowed size for arrays on the stack + +**Default Value:** `512000` (`u128`) + +* [large_stack_arrays](https://rust-lang.github.io/rust-clippy/master/index.html#large_stack_arrays) +* [large_const_arrays](https://rust-lang.github.io/rust-clippy/master/index.html#large_const_arrays) + + +### vec-box-size-threshold +The size of the boxed type in bytes, where boxing in a `Vec` is allowed + +**Default Value:** `4096` (`u64`) + +* [vec_box](https://rust-lang.github.io/rust-clippy/master/index.html#vec_box) + + +### max-trait-bounds +The maximum number of bounds a trait can have to be linted + +**Default Value:** `3` (`u64`) + +* [type_repetition_in_bounds](https://rust-lang.github.io/rust-clippy/master/index.html#type_repetition_in_bounds) + + +### max-struct-bools +The maximum number of bool fields a struct can have + +**Default Value:** `3` (`u64`) + +* [struct_excessive_bools](https://rust-lang.github.io/rust-clippy/master/index.html#struct_excessive_bools) + + +### max-fn-params-bools +The maximum number of bool parameters a function can have + +**Default Value:** `3` (`u64`) + +* [fn_params_excessive_bools](https://rust-lang.github.io/rust-clippy/master/index.html#fn_params_excessive_bools) + + +### warn-on-all-wildcard-imports +Whether to allow certain wildcard imports (prelude, super in tests). + +**Default Value:** `false` (`bool`) + +* [wildcard_imports](https://rust-lang.github.io/rust-clippy/master/index.html#wildcard_imports) + + +### disallowed-macros +The list of disallowed macros, written as fully qualified paths. + +**Default Value:** `[]` (`Vec`) + +* [disallowed_macros](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_macros) + + +### disallowed-methods +The list of disallowed methods, written as fully qualified paths. + +**Default Value:** `[]` (`Vec`) + +* [disallowed_methods](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_methods) + + +### disallowed-types +The list of disallowed types, written as fully qualified paths. + +**Default Value:** `[]` (`Vec`) + +* [disallowed_types](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_types) + + +### unreadable-literal-lint-fractions +Should the fraction of a decimal be linted to include separators. + +**Default Value:** `true` (`bool`) + +* [unreadable_literal](https://rust-lang.github.io/rust-clippy/master/index.html#unreadable_literal) + + +### upper-case-acronyms-aggressive +Enables verbose mode. Triggers if there is more than one uppercase char next to each other + +**Default Value:** `false` (`bool`) + +* [upper_case_acronyms](https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms) + + +### matches-for-let-else +Whether the matches should be considered by the lint, and whether there should +be filtering for common types. + +**Default Value:** `WellKnownTypes` (`crate::manual_let_else::MatchLintBehaviour`) + +* [manual_let_else](https://rust-lang.github.io/rust-clippy/master/index.html#manual_let_else) + + +### cargo-ignore-publish +For internal testing only, ignores the current `publish` settings in the Cargo manifest. + +**Default Value:** `false` (`bool`) + +* [_cargo_common_metadata](https://rust-lang.github.io/rust-clippy/master/index.html#_cargo_common_metadata) + + +### standard-macro-braces +Enforce the named macros always use the braces specified. + +A `MacroMatcher` can be added like so `{ name = "macro_name", brace = "(" }`. If the macro +is could be used with a full path two `MacroMatcher`s have to be added one with the full path +`crate_name::macro_name` and one with just the macro name. + +**Default Value:** `[]` (`Vec`) + +* [nonstandard_macro_braces](https://rust-lang.github.io/rust-clippy/master/index.html#nonstandard_macro_braces) + + +### enforced-import-renames +The list of imports to always rename, a fully qualified path followed by the rename. + +**Default Value:** `[]` (`Vec`) + +* [missing_enforced_import_renames](https://rust-lang.github.io/rust-clippy/master/index.html#missing_enforced_import_renames) + + +### allowed-scripts +The list of unicode scripts allowed to be used in the scope. + +**Default Value:** `["Latin"]` (`Vec`) + +* [disallowed_script_idents](https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_script_idents) + + +### enable-raw-pointer-heuristic-for-send +Whether to apply the raw pointer heuristic to determine if a type is `Send`. + +**Default Value:** `true` (`bool`) + +* [non_send_fields_in_send_ty](https://rust-lang.github.io/rust-clippy/master/index.html#non_send_fields_in_send_ty) + + +### max-suggested-slice-pattern-length +When Clippy suggests using a slice pattern, this is the maximum number of elements allowed in +the slice pattern that is suggested. If more elements would be necessary, the lint is suppressed. +For example, `[_, _, _, e, ..]` is a slice pattern with 4 elements. + +**Default Value:** `3` (`u64`) + +* [index_refutable_slice](https://rust-lang.github.io/rust-clippy/master/index.html#index_refutable_slice) + + +### max-include-file-size +The maximum size of a file included via `include_bytes!()` or `include_str!()`, in bytes + +**Default Value:** `1000000` (`u64`) + +* [large_include_file](https://rust-lang.github.io/rust-clippy/master/index.html#large_include_file) + + +### allow-expect-in-tests +Whether `expect` should be allowed within `#[cfg(test)]` + +**Default Value:** `false` (`bool`) + +* [expect_used](https://rust-lang.github.io/rust-clippy/master/index.html#expect_used) + + +### allow-unwrap-in-tests +Whether `unwrap` should be allowed in test cfg + +**Default Value:** `false` (`bool`) + +* [unwrap_used](https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used) + + +### allow-dbg-in-tests +Whether `dbg!` should be allowed in test functions + +**Default Value:** `false` (`bool`) + +* [dbg_macro](https://rust-lang.github.io/rust-clippy/master/index.html#dbg_macro) + + +### allow-print-in-tests +Whether print macros (ex. `println!`) should be allowed in test functions + +**Default Value:** `false` (`bool`) + +* [print_stdout](https://rust-lang.github.io/rust-clippy/master/index.html#print_stdout) +* [print_stderr](https://rust-lang.github.io/rust-clippy/master/index.html#print_stderr) + + +### large-error-threshold +The maximum size of the `Err`-variant in a `Result` returned from a function + +**Default Value:** `128` (`u64`) + +* [result_large_err](https://rust-lang.github.io/rust-clippy/master/index.html#result_large_err) + + +### ignore-interior-mutability +A list of paths to types that should be treated like `Arc`, i.e. ignored but +for the generic parameters for determining interior mutability + +**Default Value:** `["bytes::Bytes"]` (`Vec`) + +* [mutable_key](https://rust-lang.github.io/rust-clippy/master/index.html#mutable_key) + + +### allow-mixed-uninlined-format-args +Whether to allow mixed uninlined format args, e.g. `format!("{} {}", a, foo.bar)` + +**Default Value:** `true` (`bool`) + +* [uninlined_format_args](https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args) + + +### suppress-restriction-lint-in-const +In same +cases the restructured operation might not be unavoidable, as the +suggested counterparts are unavailable in constant code. This +configuration will cause restriction lints to trigger even +if no suggestion can be made. + +**Default Value:** `false` (`bool`) + +* [indexing_slicing](https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicing) + + diff --git a/clippy_lints/src/utils/conf.rs b/clippy_lints/src/utils/conf.rs index c1589c771c462..f48be27592b7e 100644 --- a/clippy_lints/src/utils/conf.rs +++ b/clippy_lints/src/utils/conf.rs @@ -219,7 +219,8 @@ define_Conf! { /// /// #### Noteworthy /// - /// A type, say `SomeType`, listed in this configuration has the same behavior of `["SomeType" , "*"], ["*", "SomeType"]` in `arithmetic_side_effects_allowed_binary`. + /// A type, say `SomeType`, listed in this configuration has the same behavior of + /// `["SomeType" , "*"], ["*", "SomeType"]` in `arithmetic_side_effects_allowed_binary`. (arithmetic_side_effects_allowed: rustc_data_structures::fx::FxHashSet = <_>::default()), /// Lint: ARITHMETIC_SIDE_EFFECTS. /// diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index c74f3b6e3ad6f..47604f6933b42 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -180,13 +180,22 @@ This lint has the following configuration variables: }) } - fn get_markdown_table(&self) -> String { + fn configs_to_markdown(&self, map_fn: fn(&ClippyConfiguration) -> String) -> String { self.config .iter() .filter(|config| config.deprecation_reason.is_none()) - .map(ClippyConfiguration::to_markdown_table_entry) + .filter(|config| !config.lints.is_empty()) + .map(map_fn) .join("\n") } + + fn get_markdown_docs(&self) -> String { + format!( + "## Lint Configuration Options\n|
Option
| Default Value |\n|--|--|\n{}\n\n{}\n", + self.configs_to_markdown(ClippyConfiguration::to_markdown_table_entry), + self.configs_to_markdown(ClippyConfiguration::to_markdown_paragraph), + ) + } } impl Drop for MetadataCollector { @@ -230,12 +239,7 @@ impl Drop for MetadataCollector { .create(true) .open(MARKDOWN_OUTPUT_FILE) .unwrap(); - writeln!( - file, - "## Lint Configuration\n\n| Option | Default | Description | Lints |\n|--|--|--|--|\n{}\n", - self.get_markdown_table() - ) - .unwrap(); + writeln!(file, "{}", self.get_markdown_docs(),).unwrap(); } } @@ -537,24 +541,27 @@ impl ClippyConfiguration { } } - fn to_markdown_table_entry(&self) -> String { + fn to_markdown_paragraph(&self) -> String { format!( - "| {} | `{}` | {} | {} |", + "### {}\n{}\n\n**Default Value:** `{}` (`{}`)\n\n{}\n\n", self.name, - self.default, self.doc - .split('.') - .next() - .unwrap_or("") - .replace('|', "\\|") - .replace("\n ", " "), + .lines() + .map(|line| line.strip_prefix(" ").unwrap_or(line)) + .join("\n"), + self.default, + self.config_type, self.lints .iter() .map(|name| name.to_string().split_whitespace().next().unwrap().to_string()) - .map(|name| format!("[{name}](https://rust-lang.github.io/rust-clippy/master/index.html#{name})")) - .join(" ") + .map(|name| format!("* [{name}](https://rust-lang.github.io/rust-clippy/master/index.html#{name})")) + .join("\n"), ) } + + fn to_markdown_table_entry(&self) -> String { + format!("| [{}](#{}) | `{}` |", self.name, self.name, self.default) + } } fn collect_configs() -> Vec { From a7db92574cf191444f5bbfdfcb89af5655e280c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maria=20Jos=C3=A9=20Solano?= Date: Fri, 13 Jan 2023 18:57:04 -0800 Subject: [PATCH 168/500] Split long line --- book/src/development/adding_lints.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/book/src/development/adding_lints.md b/book/src/development/adding_lints.md index 145b393b75356..c6be394bd7d72 100644 --- a/book/src/development/adding_lints.md +++ b/book/src/development/adding_lints.md @@ -146,7 +146,8 @@ For cargo lints, the process of testing differs in that we are interested in the manifest. If our new lint is named e.g. `foo_categories`, after running `cargo dev -new_lint --name=foo_categories --type=cargo --category=cargo` we will find by default two new crates, each with its manifest file: +new_lint --name=foo_categories --type=cargo --category=cargo` we will find by +default two new crates, each with its manifest file: * `tests/ui-cargo/foo_categories/fail/Cargo.toml`: this file should cause the new lint to raise an error. From ab20f8d5ba164510a4a782bcf305b7005bc88b15 Mon Sep 17 00:00:00 2001 From: Ibraheem Ahmed Date: Sat, 14 Jan 2023 00:29:48 -0500 Subject: [PATCH 169/500] remove optimistic spinning from `mpsc::SyncSender` --- library/std/src/sync/mpmc/array.rs | 18 +++++------------- library/std/src/sync/mpmc/utils.rs | 12 ++---------- 2 files changed, 7 insertions(+), 23 deletions(-) diff --git a/library/std/src/sync/mpmc/array.rs b/library/std/src/sync/mpmc/array.rs index c1e3e48b04468..c6bb09b0417f3 100644 --- a/library/std/src/sync/mpmc/array.rs +++ b/library/std/src/sync/mpmc/array.rs @@ -319,19 +319,10 @@ impl Channel { ) -> Result<(), SendTimeoutError> { let token = &mut Token::default(); loop { - // Try sending a message several times. - let backoff = Backoff::new(); - loop { - if self.start_send(token) { - let res = unsafe { self.write(token, msg) }; - return res.map_err(SendTimeoutError::Disconnected); - } - - if backoff.is_completed() { - break; - } else { - backoff.spin_light(); - } + // Try sending a message. + if self.start_send(token) { + let res = unsafe { self.write(token, msg) }; + return res.map_err(SendTimeoutError::Disconnected); } if let Some(d) = deadline { @@ -379,6 +370,7 @@ impl Channel { pub(crate) fn recv(&self, deadline: Option) -> Result { let token = &mut Token::default(); loop { + // Try receiving a message. if self.start_recv(token) { let res = unsafe { self.read(token) }; return res.map_err(|_| RecvTimeoutError::Disconnected); diff --git a/library/std/src/sync/mpmc/utils.rs b/library/std/src/sync/mpmc/utils.rs index cfe42750d5239..d053d69e26eee 100644 --- a/library/std/src/sync/mpmc/utils.rs +++ b/library/std/src/sync/mpmc/utils.rs @@ -105,10 +105,8 @@ impl Backoff { /// Backs off using lightweight spinning. /// - /// This method should be used for: - /// - Retrying an operation because another thread made progress. i.e. on CAS failure. - /// - Waiting for an operation to complete by spinning optimistically for a few iterations - /// before falling back to parking the thread (see `Backoff::is_completed`). + /// This method should be used for retrying an operation because another thread made + /// progress. i.e. on CAS failure. #[inline] pub fn spin_light(&self) { let step = self.step.get().min(SPIN_LIMIT); @@ -134,10 +132,4 @@ impl Backoff { self.step.set(self.step.get() + 1); } - - /// Returns `true` if quadratic backoff has completed and parking the thread is advised. - #[inline] - pub fn is_completed(&self) -> bool { - self.step.get() > SPIN_LIMIT - } } From a160ce3a48c626bc30894ca50a2b1024c8f1d672 Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Tue, 10 Jan 2023 14:22:52 -0700 Subject: [PATCH 170/500] change usages of impl_trait_ref to bound_impl_trait_ref --- clippy_lints/src/derive.rs | 8 ++++---- clippy_lints/src/fallible_impl_from.rs | 4 ++-- clippy_lints/src/from_over_into.rs | 2 +- clippy_lints/src/implicit_saturating_sub.rs | 4 ++-- clippy_lints/src/methods/implicit_clone.rs | 2 +- clippy_lints/src/methods/suspicious_splitn.rs | 2 +- clippy_lints/src/missing_doc.rs | 2 +- clippy_lints/src/missing_inline.rs | 2 +- clippy_lints/src/non_send_fields_in_send_ty.rs | 4 ++-- clippy_lints/src/only_used_in_recursion.rs | 2 +- clippy_lints/src/use_self.rs | 4 ++-- 11 files changed, 18 insertions(+), 18 deletions(-) diff --git a/clippy_lints/src/derive.rs b/clippy_lints/src/derive.rs index f4b15e0916dbf..6b2b18fff76e0 100644 --- a/clippy_lints/src/derive.rs +++ b/clippy_lints/src/derive.rs @@ -247,11 +247,11 @@ fn check_hash_peq<'tcx>( return; } - let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation"); + let trait_ref = cx.tcx.bound_impl_trait_ref(impl_id).expect("must be a trait implementation"); // Only care about `impl PartialEq for Foo` // For `impl PartialEq for A, input_types is [A, B] - if trait_ref.substs.type_at(1) == ty { + if trait_ref.subst_identity().substs.type_at(1) == ty { span_lint_and_then( cx, DERIVED_HASH_WITH_MANUAL_EQ, @@ -295,11 +295,11 @@ fn check_ord_partial_ord<'tcx>( return; } - let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation"); + let trait_ref = cx.tcx.bound_impl_trait_ref(impl_id).expect("must be a trait implementation"); // Only care about `impl PartialOrd for Foo` // For `impl PartialOrd for A, input_types is [A, B] - if trait_ref.substs.type_at(1) == ty { + if trait_ref.subst_identity().substs.type_at(1) == ty { let mess = if partial_ord_is_automatically_derived { "you are implementing `Ord` explicitly but have derived `PartialOrd`" } else { diff --git a/clippy_lints/src/fallible_impl_from.rs b/clippy_lints/src/fallible_impl_from.rs index 9a1058470e18e..a8085122ccf95 100644 --- a/clippy_lints/src/fallible_impl_from.rs +++ b/clippy_lints/src/fallible_impl_from.rs @@ -55,8 +55,8 @@ impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom { // check for `impl From for ..` if_chain! { if let hir::ItemKind::Impl(impl_) = &item.kind; - if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.owner_id); - if cx.tcx.is_diagnostic_item(sym::From, impl_trait_ref.def_id); + if let Some(impl_trait_ref) = cx.tcx.bound_impl_trait_ref(item.owner_id.to_def_id()); + if cx.tcx.is_diagnostic_item(sym::From, impl_trait_ref.skip_binder().def_id); then { lint_impl_body(cx, item.span, impl_.items); } diff --git a/clippy_lints/src/from_over_into.rs b/clippy_lints/src/from_over_into.rs index a92f7548ff254..97d414bfa95e4 100644 --- a/clippy_lints/src/from_over_into.rs +++ b/clippy_lints/src/from_over_into.rs @@ -76,7 +76,7 @@ impl<'tcx> LateLintPass<'tcx> for FromOverInto { && let Some(into_trait_seg) = hir_trait_ref.path.segments.last() // `impl Into for self_ty` && let Some(GenericArgs { args: [GenericArg::Type(target_ty)], .. }) = into_trait_seg.args - && let Some(middle_trait_ref) = cx.tcx.impl_trait_ref(item.owner_id) + && let Some(middle_trait_ref) = cx.tcx.bound_impl_trait_ref(item.owner_id.to_def_id()).map(ty::EarlyBinder::subst_identity) && cx.tcx.is_diagnostic_item(sym::Into, middle_trait_ref.def_id) && !matches!(middle_trait_ref.substs.type_at(1).kind(), ty::Alias(ty::Opaque, _)) { diff --git a/clippy_lints/src/implicit_saturating_sub.rs b/clippy_lints/src/implicit_saturating_sub.rs index 29d59c26d92c4..37e33529a9a60 100644 --- a/clippy_lints/src/implicit_saturating_sub.rs +++ b/clippy_lints/src/implicit_saturating_sub.rs @@ -101,7 +101,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub { if name.ident.as_str() == "MIN"; if let Some(const_id) = cx.typeck_results().type_dependent_def_id(cond_num_val.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(const_id); - if let None = cx.tcx.impl_trait_ref(impl_id); // An inherent impl + if let None = cx.tcx.bound_impl_trait_ref(impl_id); // An inherent impl if cx.tcx.type_of(impl_id).is_integral(); then { print_lint_and_sugg(cx, var_name, expr) @@ -114,7 +114,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub { if name.ident.as_str() == "min_value"; if let Some(func_id) = cx.typeck_results().type_dependent_def_id(func.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(func_id); - if let None = cx.tcx.impl_trait_ref(impl_id); // An inherent impl + if let None = cx.tcx.bound_impl_trait_ref(impl_id); // An inherent impl if cx.tcx.type_of(impl_id).is_integral(); then { print_lint_and_sugg(cx, var_name, expr) diff --git a/clippy_lints/src/methods/implicit_clone.rs b/clippy_lints/src/methods/implicit_clone.rs index 06ecbce4e70e9..16a25a98800de 100644 --- a/clippy_lints/src/methods/implicit_clone.rs +++ b/clippy_lints/src/methods/implicit_clone.rs @@ -53,7 +53,7 @@ pub fn is_clone_like(cx: &LateContext<'_>, method_name: &str, method_def_id: hir "to_vec" => cx .tcx .impl_of_method(method_def_id) - .filter(|&impl_did| cx.tcx.type_of(impl_did).is_slice() && cx.tcx.impl_trait_ref(impl_did).is_none()) + .filter(|&impl_did| cx.tcx.type_of(impl_did).is_slice() && cx.tcx.bound_impl_trait_ref(impl_did).is_none()) .is_some(), _ => false, } diff --git a/clippy_lints/src/methods/suspicious_splitn.rs b/clippy_lints/src/methods/suspicious_splitn.rs index 219a9edd65768..dba0663467b7d 100644 --- a/clippy_lints/src/methods/suspicious_splitn.rs +++ b/clippy_lints/src/methods/suspicious_splitn.rs @@ -12,7 +12,7 @@ pub(super) fn check(cx: &LateContext<'_>, method_name: &str, expr: &Expr<'_>, se if count <= 1; if let Some(call_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(call_id); - if cx.tcx.impl_trait_ref(impl_id).is_none(); + if cx.tcx.bound_impl_trait_ref(impl_id).is_none(); let self_ty = cx.tcx.type_of(impl_id); if self_ty.is_slice() || self_ty.is_str(); then { diff --git a/clippy_lints/src/missing_doc.rs b/clippy_lints/src/missing_doc.rs index 6fd100762b49d..d0c99b352452f 100644 --- a/clippy_lints/src/missing_doc.rs +++ b/clippy_lints/src/missing_doc.rs @@ -175,7 +175,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) { // If the method is an impl for a trait, don't doc. if let Some(cid) = cx.tcx.associated_item(impl_item.owner_id).impl_container(cx.tcx) { - if cx.tcx.impl_trait_ref(cid).is_some() { + if cx.tcx.bound_impl_trait_ref(cid).is_some() { return; } } else { diff --git a/clippy_lints/src/missing_inline.rs b/clippy_lints/src/missing_inline.rs index 758ce47cf114b..0594fb175458d 100644 --- a/clippy_lints/src/missing_inline.rs +++ b/clippy_lints/src/missing_inline.rs @@ -155,7 +155,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { let container_id = assoc_item.container_id(cx.tcx); let trait_def_id = match assoc_item.container { TraitContainer => Some(container_id), - ImplContainer => cx.tcx.impl_trait_ref(container_id).map(|t| t.def_id), + ImplContainer => cx.tcx.bound_impl_trait_ref(container_id).map(|t| t.skip_binder().def_id), }; if let Some(trait_def_id) = trait_def_id { diff --git a/clippy_lints/src/non_send_fields_in_send_ty.rs b/clippy_lints/src/non_send_fields_in_send_ty.rs index 714c0ff227bf8..9c112ade948ff 100644 --- a/clippy_lints/src/non_send_fields_in_send_ty.rs +++ b/clippy_lints/src/non_send_fields_in_send_ty.rs @@ -89,8 +89,8 @@ impl<'tcx> LateLintPass<'tcx> for NonSendFieldInSendTy { if let Some(trait_id) = trait_ref.trait_def_id(); if send_trait == trait_id; if hir_impl.polarity == ImplPolarity::Positive; - if let Some(ty_trait_ref) = cx.tcx.impl_trait_ref(item.owner_id); - if let self_ty = ty_trait_ref.self_ty(); + if let Some(ty_trait_ref) = cx.tcx.bound_impl_trait_ref(item.owner_id.to_def_id()); + if let self_ty = ty_trait_ref.subst_identity().self_ty(); if let ty::Adt(adt_def, impl_trait_substs) = self_ty.kind(); then { let mut non_send_fields = Vec::new(); diff --git a/clippy_lints/src/only_used_in_recursion.rs b/clippy_lints/src/only_used_in_recursion.rs index 7722a476d7b4e..82b1716a216e6 100644 --- a/clippy_lints/src/only_used_in_recursion.rs +++ b/clippy_lints/src/only_used_in_recursion.rs @@ -244,7 +244,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { })) => { #[allow(trivial_casts)] if let Some(Node::Item(item)) = get_parent_node(cx.tcx, owner_id.into()) - && let Some(trait_ref) = cx.tcx.impl_trait_ref(item.owner_id) + && let Some(trait_ref) = cx.tcx.bound_impl_trait_ref(item.owner_id.to_def_id()).map(|t| t.subst_identity()) && let Some(trait_item_id) = cx.tcx.associated_item(owner_id).trait_item_def_id { ( diff --git a/clippy_lints/src/use_self.rs b/clippy_lints/src/use_self.rs index 4c755d812a0e0..9f31a13aa984b 100644 --- a/clippy_lints/src/use_self.rs +++ b/clippy_lints/src/use_self.rs @@ -133,11 +133,11 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { ref mut types_to_skip, .. }) = self.stack.last_mut(); - if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_id); + if let Some(impl_trait_ref) = cx.tcx.bound_impl_trait_ref(impl_id.to_def_id()); then { // `self_ty` is the semantic self type of `impl for `. This cannot be // `Self`. - let self_ty = impl_trait_ref.self_ty(); + let self_ty = impl_trait_ref.subst_identity().self_ty(); // `trait_method_sig` is the signature of the function, how it is declared in the // trait, not in the impl of the trait. From b92d90211e9d4ac8275912d6a913969d6a9b7913 Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Tue, 10 Jan 2023 14:57:22 -0700 Subject: [PATCH 171/500] change impl_trait_ref query to return EarlyBinder; remove bound_impl_trait_ref query; add EarlyBinder to impl_trait_ref in metadata --- clippy_lints/src/derive.rs | 4 ++-- clippy_lints/src/fallible_impl_from.rs | 2 +- clippy_lints/src/from_over_into.rs | 2 +- clippy_lints/src/implicit_saturating_sub.rs | 4 ++-- clippy_lints/src/methods/implicit_clone.rs | 2 +- clippy_lints/src/methods/suspicious_splitn.rs | 2 +- clippy_lints/src/missing_doc.rs | 2 +- clippy_lints/src/missing_inline.rs | 2 +- clippy_lints/src/non_send_fields_in_send_ty.rs | 2 +- clippy_lints/src/only_used_in_recursion.rs | 2 +- clippy_lints/src/use_self.rs | 2 +- 11 files changed, 13 insertions(+), 13 deletions(-) diff --git a/clippy_lints/src/derive.rs b/clippy_lints/src/derive.rs index 6b2b18fff76e0..248d738841067 100644 --- a/clippy_lints/src/derive.rs +++ b/clippy_lints/src/derive.rs @@ -247,7 +247,7 @@ fn check_hash_peq<'tcx>( return; } - let trait_ref = cx.tcx.bound_impl_trait_ref(impl_id).expect("must be a trait implementation"); + let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation"); // Only care about `impl PartialEq for Foo` // For `impl PartialEq for A, input_types is [A, B] @@ -295,7 +295,7 @@ fn check_ord_partial_ord<'tcx>( return; } - let trait_ref = cx.tcx.bound_impl_trait_ref(impl_id).expect("must be a trait implementation"); + let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation"); // Only care about `impl PartialOrd for Foo` // For `impl PartialOrd for A, input_types is [A, B] diff --git a/clippy_lints/src/fallible_impl_from.rs b/clippy_lints/src/fallible_impl_from.rs index a8085122ccf95..2ef547526d4f7 100644 --- a/clippy_lints/src/fallible_impl_from.rs +++ b/clippy_lints/src/fallible_impl_from.rs @@ -55,7 +55,7 @@ impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom { // check for `impl From for ..` if_chain! { if let hir::ItemKind::Impl(impl_) = &item.kind; - if let Some(impl_trait_ref) = cx.tcx.bound_impl_trait_ref(item.owner_id.to_def_id()); + if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.owner_id); if cx.tcx.is_diagnostic_item(sym::From, impl_trait_ref.skip_binder().def_id); then { lint_impl_body(cx, item.span, impl_.items); diff --git a/clippy_lints/src/from_over_into.rs b/clippy_lints/src/from_over_into.rs index 97d414bfa95e4..bd66ace4500a8 100644 --- a/clippy_lints/src/from_over_into.rs +++ b/clippy_lints/src/from_over_into.rs @@ -76,7 +76,7 @@ impl<'tcx> LateLintPass<'tcx> for FromOverInto { && let Some(into_trait_seg) = hir_trait_ref.path.segments.last() // `impl Into for self_ty` && let Some(GenericArgs { args: [GenericArg::Type(target_ty)], .. }) = into_trait_seg.args - && let Some(middle_trait_ref) = cx.tcx.bound_impl_trait_ref(item.owner_id.to_def_id()).map(ty::EarlyBinder::subst_identity) + && let Some(middle_trait_ref) = cx.tcx.impl_trait_ref(item.owner_id).map(ty::EarlyBinder::subst_identity) && cx.tcx.is_diagnostic_item(sym::Into, middle_trait_ref.def_id) && !matches!(middle_trait_ref.substs.type_at(1).kind(), ty::Alias(ty::Opaque, _)) { diff --git a/clippy_lints/src/implicit_saturating_sub.rs b/clippy_lints/src/implicit_saturating_sub.rs index 37e33529a9a60..29d59c26d92c4 100644 --- a/clippy_lints/src/implicit_saturating_sub.rs +++ b/clippy_lints/src/implicit_saturating_sub.rs @@ -101,7 +101,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub { if name.ident.as_str() == "MIN"; if let Some(const_id) = cx.typeck_results().type_dependent_def_id(cond_num_val.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(const_id); - if let None = cx.tcx.bound_impl_trait_ref(impl_id); // An inherent impl + if let None = cx.tcx.impl_trait_ref(impl_id); // An inherent impl if cx.tcx.type_of(impl_id).is_integral(); then { print_lint_and_sugg(cx, var_name, expr) @@ -114,7 +114,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub { if name.ident.as_str() == "min_value"; if let Some(func_id) = cx.typeck_results().type_dependent_def_id(func.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(func_id); - if let None = cx.tcx.bound_impl_trait_ref(impl_id); // An inherent impl + if let None = cx.tcx.impl_trait_ref(impl_id); // An inherent impl if cx.tcx.type_of(impl_id).is_integral(); then { print_lint_and_sugg(cx, var_name, expr) diff --git a/clippy_lints/src/methods/implicit_clone.rs b/clippy_lints/src/methods/implicit_clone.rs index 16a25a98800de..06ecbce4e70e9 100644 --- a/clippy_lints/src/methods/implicit_clone.rs +++ b/clippy_lints/src/methods/implicit_clone.rs @@ -53,7 +53,7 @@ pub fn is_clone_like(cx: &LateContext<'_>, method_name: &str, method_def_id: hir "to_vec" => cx .tcx .impl_of_method(method_def_id) - .filter(|&impl_did| cx.tcx.type_of(impl_did).is_slice() && cx.tcx.bound_impl_trait_ref(impl_did).is_none()) + .filter(|&impl_did| cx.tcx.type_of(impl_did).is_slice() && cx.tcx.impl_trait_ref(impl_did).is_none()) .is_some(), _ => false, } diff --git a/clippy_lints/src/methods/suspicious_splitn.rs b/clippy_lints/src/methods/suspicious_splitn.rs index dba0663467b7d..219a9edd65768 100644 --- a/clippy_lints/src/methods/suspicious_splitn.rs +++ b/clippy_lints/src/methods/suspicious_splitn.rs @@ -12,7 +12,7 @@ pub(super) fn check(cx: &LateContext<'_>, method_name: &str, expr: &Expr<'_>, se if count <= 1; if let Some(call_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(call_id); - if cx.tcx.bound_impl_trait_ref(impl_id).is_none(); + if cx.tcx.impl_trait_ref(impl_id).is_none(); let self_ty = cx.tcx.type_of(impl_id); if self_ty.is_slice() || self_ty.is_str(); then { diff --git a/clippy_lints/src/missing_doc.rs b/clippy_lints/src/missing_doc.rs index d0c99b352452f..6fd100762b49d 100644 --- a/clippy_lints/src/missing_doc.rs +++ b/clippy_lints/src/missing_doc.rs @@ -175,7 +175,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) { // If the method is an impl for a trait, don't doc. if let Some(cid) = cx.tcx.associated_item(impl_item.owner_id).impl_container(cx.tcx) { - if cx.tcx.bound_impl_trait_ref(cid).is_some() { + if cx.tcx.impl_trait_ref(cid).is_some() { return; } } else { diff --git a/clippy_lints/src/missing_inline.rs b/clippy_lints/src/missing_inline.rs index 0594fb175458d..5a459548153aa 100644 --- a/clippy_lints/src/missing_inline.rs +++ b/clippy_lints/src/missing_inline.rs @@ -155,7 +155,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { let container_id = assoc_item.container_id(cx.tcx); let trait_def_id = match assoc_item.container { TraitContainer => Some(container_id), - ImplContainer => cx.tcx.bound_impl_trait_ref(container_id).map(|t| t.skip_binder().def_id), + ImplContainer => cx.tcx.impl_trait_ref(container_id).map(|t| t.skip_binder().def_id), }; if let Some(trait_def_id) = trait_def_id { diff --git a/clippy_lints/src/non_send_fields_in_send_ty.rs b/clippy_lints/src/non_send_fields_in_send_ty.rs index 9c112ade948ff..839c3a3815c29 100644 --- a/clippy_lints/src/non_send_fields_in_send_ty.rs +++ b/clippy_lints/src/non_send_fields_in_send_ty.rs @@ -89,7 +89,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSendFieldInSendTy { if let Some(trait_id) = trait_ref.trait_def_id(); if send_trait == trait_id; if hir_impl.polarity == ImplPolarity::Positive; - if let Some(ty_trait_ref) = cx.tcx.bound_impl_trait_ref(item.owner_id.to_def_id()); + if let Some(ty_trait_ref) = cx.tcx.impl_trait_ref(item.owner_id); if let self_ty = ty_trait_ref.subst_identity().self_ty(); if let ty::Adt(adt_def, impl_trait_substs) = self_ty.kind(); then { diff --git a/clippy_lints/src/only_used_in_recursion.rs b/clippy_lints/src/only_used_in_recursion.rs index 82b1716a216e6..7b1d974f2f877 100644 --- a/clippy_lints/src/only_used_in_recursion.rs +++ b/clippy_lints/src/only_used_in_recursion.rs @@ -244,7 +244,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { })) => { #[allow(trivial_casts)] if let Some(Node::Item(item)) = get_parent_node(cx.tcx, owner_id.into()) - && let Some(trait_ref) = cx.tcx.bound_impl_trait_ref(item.owner_id.to_def_id()).map(|t| t.subst_identity()) + && let Some(trait_ref) = cx.tcx.impl_trait_ref(item.owner_id).map(|t| t.subst_identity()) && let Some(trait_item_id) = cx.tcx.associated_item(owner_id).trait_item_def_id { ( diff --git a/clippy_lints/src/use_self.rs b/clippy_lints/src/use_self.rs index 9f31a13aa984b..6ae9d9d635380 100644 --- a/clippy_lints/src/use_self.rs +++ b/clippy_lints/src/use_self.rs @@ -133,7 +133,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { ref mut types_to_skip, .. }) = self.stack.last_mut(); - if let Some(impl_trait_ref) = cx.tcx.bound_impl_trait_ref(impl_id.to_def_id()); + if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_id); then { // `self_ty` is the semantic self type of `impl for `. This cannot be // `Self`. From a41c5f9c381aeb6cb29afd1a0ca79f31d257cd6c Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Sat, 14 Jan 2023 12:29:41 +0000 Subject: [PATCH 172/500] Re-add #[allow(unused)] attr --- library/std/src/sys/unix/thread_local_dtor.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/library/std/src/sys/unix/thread_local_dtor.rs b/library/std/src/sys/unix/thread_local_dtor.rs index aa4df00063208..6810e197df8bb 100644 --- a/library/std/src/sys/unix/thread_local_dtor.rs +++ b/library/std/src/sys/unix/thread_local_dtor.rs @@ -89,6 +89,7 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { } #[cfg(any(target_os = "vxworks", target_os = "horizon", target_os = "emscripten"))] +#[cfg_attr(target_family = "wasm", allow(unused))] // might remain unused depending on target details (e.g. wasm32-unknown-emscripten) pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { use crate::sys_common::thread_local_dtor::register_dtor_fallback; register_dtor_fallback(t, dtor); From 7b077307fd156275001ce5ca7a53e250eabcb0b6 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Sat, 14 Jan 2023 14:16:26 +0100 Subject: [PATCH 173/500] Fix ast_pretty for format_args for {:x?} and {:X?}. They were accidentally swapped. --- compiler/rustc_ast_pretty/src/pprust/state/expr.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs index 500dc9da8aef8..5cc66ff54eda5 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -708,10 +708,10 @@ pub fn reconstruct_format_args_template_string(pieces: &[FormatArgsPiece]) -> St } } if flags >> (rustc_parse_format::FlagDebugLowerHex as usize) & 1 != 0 { - template.push('X'); + template.push('x'); } if flags >> (rustc_parse_format::FlagDebugUpperHex as usize) & 1 != 0 { - template.push('x'); + template.push('X'); } template.push_str(match p.format_trait { FormatTrait::Display => "", From 651e8734620a07d25acab4a594e23e33b4d91f50 Mon Sep 17 00:00:00 2001 From: Michal Rostecki Date: Sat, 14 Jan 2023 21:33:42 +0800 Subject: [PATCH 174/500] BPF: Disable atomic CAS Enabling CAS for BPF targets (#105708) breaks the build of core library. The failure occurs both when building rustc for BPF targets and when building crates for BPF targets with the current nightly. The LLVM BPF backend does not correctly lower all `atomicrmw` operations and crashes for unsupported ones. Before we can enable CAS for BPF in Rust, we need to fix the LLVM BPF backend first. Fixes #106795 Signed-off-by: Michal Rostecki --- compiler/rustc_target/src/spec/bpf_base.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_target/src/spec/bpf_base.rs b/compiler/rustc_target/src/spec/bpf_base.rs index 2b00cda44b511..4d03747d0165f 100644 --- a/compiler/rustc_target/src/spec/bpf_base.rs +++ b/compiler/rustc_target/src/spec/bpf_base.rs @@ -6,7 +6,7 @@ pub fn opts(endian: Endian) -> TargetOptions { allow_asm: true, endian, linker_flavor: LinkerFlavor::Bpf, - atomic_cas: true, + atomic_cas: false, dynamic_linking: true, no_builtins: true, panic_strategy: PanicStrategy::Abort, From 395eaa1538a18aff0c433b683625b7decf3c9235 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 14:17:43 +0000 Subject: [PATCH 175/500] Remove Test nightly Cranelift workflow Cranelift makes api breaking changes often enough that this workflow fails half of the time. As such in practice I completely ignore it's result and push an update to a branch after Cranelift branches to test everything on CI. In this update I immediately fix the fallout of api breaking changes. --- .github/workflows/nightly-cranelift.yml | 48 ------------------------- 1 file changed, 48 deletions(-) delete mode 100644 .github/workflows/nightly-cranelift.yml diff --git a/.github/workflows/nightly-cranelift.yml b/.github/workflows/nightly-cranelift.yml deleted file mode 100644 index c3dd7445fd8b9..0000000000000 --- a/.github/workflows/nightly-cranelift.yml +++ /dev/null @@ -1,48 +0,0 @@ -name: Test nightly Cranelift - -on: - push: - schedule: - - cron: '17 1 * * *' # At 01:17 UTC every day. - -jobs: - build: - runs-on: ubuntu-latest - timeout-minutes: 60 - - steps: - - uses: actions/checkout@v3 - - - name: Use sparse cargo registry - run: | - cat >> ~/.cargo/config.toml < Date: Sat, 14 Jan 2023 12:14:19 +0000 Subject: [PATCH 176/500] Minor consistency improvement --- build_system/abi_cafe.rs | 2 +- build_system/mod.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build_system/abi_cafe.rs b/build_system/abi_cafe.rs index 63f2efd8e1ef7..1b4c7c9da2140 100644 --- a/build_system/abi_cafe.rs +++ b/build_system/abi_cafe.rs @@ -21,7 +21,7 @@ pub(crate) fn run( host_compiler: &Compiler, ) { if !config::get_bool("testsuite.abi-cafe") { - eprintln!("[SKIP] abi-cafe"); + eprintln!("[RUN] abi-cafe (skipped)"); return; } diff --git a/build_system/mod.rs b/build_system/mod.rs index d1932549ee675..f0cde968ae7b8 100644 --- a/build_system/mod.rs +++ b/build_system/mod.rs @@ -153,7 +153,7 @@ pub fn main() { if host_compiler.triple == target_triple { abi_cafe::run(channel, sysroot_kind, &dirs, &cg_clif_dylib, &host_compiler); } else { - eprintln!("[SKIP] abi-cafe (cross-compilation not supported)"); + eprintln!("[RUN] abi-cafe (skipped, cross-compilation not supported)"); return; } } From a09712e0d2e2a17c6d11377e9d14e080b75ac952 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 12:36:56 +0000 Subject: [PATCH 177/500] Use fs::remove_dir_all instead of cargo clean --- build_system/tests.rs | 17 +++++++---------- build_system/utils.rs | 5 ++--- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/build_system/tests.rs b/build_system/tests.rs index 4d638a4eced10..4203a3859e1a1 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -119,7 +119,7 @@ pub(crate) static LIBCORE_TESTS: CargoProject = const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ TestCase::custom("test.rust-random/rand", &|runner| { - spawn_and_wait(RAND.clean(&runner.target_compiler.cargo, &runner.dirs)); + RAND.clean(&runner.dirs); if runner.is_native { eprintln!("[TEST] rust-random/rand"); @@ -134,11 +134,11 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ } }), TestCase::custom("test.simple-raytracer", &|runner| { - spawn_and_wait(SIMPLE_RAYTRACER.clean(&runner.host_compiler.cargo, &runner.dirs)); + SIMPLE_RAYTRACER.clean(&runner.dirs); spawn_and_wait(SIMPLE_RAYTRACER.build(&runner.target_compiler, &runner.dirs)); }), TestCase::custom("test.libcore", &|runner| { - spawn_and_wait(LIBCORE_TESTS.clean(&runner.host_compiler.cargo, &runner.dirs)); + LIBCORE_TESTS.clean(&runner.dirs); if runner.is_native { spawn_and_wait(LIBCORE_TESTS.test(&runner.target_compiler, &runner.dirs)); @@ -150,7 +150,7 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ } }), TestCase::custom("test.regex-shootout-regex-dna", &|runner| { - spawn_and_wait(REGEX.clean(&runner.target_compiler.cargo, &runner.dirs)); + REGEX.clean(&runner.dirs); // newer aho_corasick versions throw a deprecation warning let lint_rust_flags = format!("{} --cap-lints warn", runner.target_compiler.rustflags); @@ -194,7 +194,7 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ } }), TestCase::custom("test.regex", &|runner| { - spawn_and_wait(REGEX.clean(&runner.host_compiler.cargo, &runner.dirs)); + REGEX.clean(&runner.dirs); // newer aho_corasick versions throw a deprecation warning let lint_rust_flags = format!("{} --cap-lints warn", runner.target_compiler.rustflags); @@ -221,7 +221,7 @@ const EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ } }), TestCase::custom("test.portable-simd", &|runner| { - spawn_and_wait(PORTABLE_SIMD.clean(&runner.host_compiler.cargo, &runner.dirs)); + PORTABLE_SIMD.clean(&runner.dirs); let mut build_cmd = PORTABLE_SIMD.build(&runner.target_compiler, &runner.dirs); build_cmd.arg("--all-targets"); @@ -293,7 +293,6 @@ struct TestRunner { is_native: bool, jit_supported: bool, dirs: Dirs, - host_compiler: Compiler, target_compiler: Compiler, } @@ -303,8 +302,6 @@ impl TestRunner { let jit_supported = is_native && host_triple.contains("x86_64") && !host_triple.contains("windows"); - let host_compiler = Compiler::clif_with_triple(&dirs, host_triple); - let mut target_compiler = Compiler::clif_with_triple(&dirs, target_triple); if !is_native { target_compiler.set_cross_linker_and_runner(); @@ -323,7 +320,7 @@ impl TestRunner { target_compiler.rustflags.push_str(" -Clink-arg=-undefined -Clink-arg=dynamic_lookup"); } - Self { is_native, jit_supported, dirs, host_compiler, target_compiler } + Self { is_native, jit_supported, dirs, target_compiler } } pub fn run_testsuite(&self, tests: &[TestCase]) { diff --git a/build_system/utils.rs b/build_system/utils.rs index f2b1fecedc16b..935177a00ba87 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -146,9 +146,8 @@ impl CargoProject { cmd } - #[must_use] - pub(crate) fn clean(&self, cargo: &Path, dirs: &Dirs) -> Command { - self.base_cmd("clean", cargo, dirs) + pub(crate) fn clean(&self, dirs: &Dirs) { + let _ = fs::remove_dir_all(self.target_dir(dirs)); } #[must_use] From 5e452ba616ab416e1444882ffe52648ae1fbac09 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 12:41:07 +0000 Subject: [PATCH 178/500] Set RUSTC and RUSTDOC env vars to invalid values to catch forgetting to set them --- build_system/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/build_system/mod.rs b/build_system/mod.rs index f0cde968ae7b8..265416c48fcca 100644 --- a/build_system/mod.rs +++ b/build_system/mod.rs @@ -134,6 +134,9 @@ pub fn main() { process::exit(0); } + env::set_var("RUSTC", "rustc_should_be_set_explicitly"); + env::set_var("RUSTDOC", "rustdoc_should_be_set_explicitly"); + let cg_clif_dylib = build_backend::build_backend(&dirs, channel, &host_compiler, use_unstable_features); match command { From fd1e824d88e9927326e5a2b4242c53e83b264d07 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 12:44:39 +0000 Subject: [PATCH 179/500] Minor changes to the TestRunner::new signature --- build_system/tests.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/build_system/tests.rs b/build_system/tests.rs index 4203a3859e1a1..6c4d0e2e35e7d 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -243,8 +243,11 @@ pub(crate) fn run_tests( host_compiler: &Compiler, target_triple: &str, ) { - let runner = - TestRunner::new(dirs.clone(), host_compiler.triple.clone(), target_triple.to_string()); + let runner = TestRunner::new( + dirs.clone(), + target_triple.to_owned(), + host_compiler.triple == target_triple, + ); if config::get_bool("testsuite.no_sysroot") { build_sysroot::build_sysroot( @@ -297,11 +300,7 @@ struct TestRunner { } impl TestRunner { - pub fn new(dirs: Dirs, host_triple: String, target_triple: String) -> Self { - let is_native = host_triple == target_triple; - let jit_supported = - is_native && host_triple.contains("x86_64") && !host_triple.contains("windows"); - + pub fn new(dirs: Dirs, target_triple: String, is_native: bool) -> Self { let mut target_compiler = Compiler::clif_with_triple(&dirs, target_triple); if !is_native { target_compiler.set_cross_linker_and_runner(); @@ -320,6 +319,10 @@ impl TestRunner { target_compiler.rustflags.push_str(" -Clink-arg=-undefined -Clink-arg=dynamic_lookup"); } + let jit_supported = is_native + && target_compiler.triple.contains("x86_64") + && !target_compiler.triple.contains("windows"); + Self { is_native, jit_supported, dirs, target_compiler } } From bbb7a3b9b9790d3abc62157f3f6daae9af94d841 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 12:53:33 +0000 Subject: [PATCH 180/500] Rename Compiler variables for clarity --- build_system/abi_cafe.rs | 8 ++++---- build_system/bench.rs | 10 +++++----- build_system/build_backend.rs | 6 +++--- build_system/build_sysroot.rs | 25 +++++++++++++++---------- build_system/mod.rs | 30 ++++++++++++++++++++---------- build_system/tests.rs | 14 ++++++-------- build_system/utils.rs | 2 +- 7 files changed, 54 insertions(+), 41 deletions(-) diff --git a/build_system/abi_cafe.rs b/build_system/abi_cafe.rs index 1b4c7c9da2140..8352c1a965a75 100644 --- a/build_system/abi_cafe.rs +++ b/build_system/abi_cafe.rs @@ -18,7 +18,7 @@ pub(crate) fn run( sysroot_kind: SysrootKind, dirs: &Dirs, cg_clif_dylib: &Path, - host_compiler: &Compiler, + bootstrap_host_compiler: &Compiler, ) { if !config::get_bool("testsuite.abi-cafe") { eprintln!("[RUN] abi-cafe (skipped)"); @@ -31,15 +31,15 @@ pub(crate) fn run( channel, sysroot_kind, cg_clif_dylib, - host_compiler, - &host_compiler.triple, + bootstrap_host_compiler, + &bootstrap_host_compiler.triple, ); eprintln!("Running abi-cafe"); let pairs = ["rustc_calls_cgclif", "cgclif_calls_rustc", "cgclif_calls_cc", "cc_calls_cgclif"]; - let mut cmd = ABI_CAFE.run(host_compiler, dirs); + let mut cmd = ABI_CAFE.run(bootstrap_host_compiler, dirs); cmd.arg("--"); cmd.arg("--pairs"); cmd.args(pairs); diff --git a/build_system/bench.rs b/build_system/bench.rs index f5c5d92cb3286..1e83f21ba577b 100644 --- a/build_system/bench.rs +++ b/build_system/bench.rs @@ -21,11 +21,11 @@ pub(crate) static SIMPLE_RAYTRACER_LLVM: CargoProject = pub(crate) static SIMPLE_RAYTRACER: CargoProject = CargoProject::new(&SIMPLE_RAYTRACER_REPO.source_dir(), "simple_raytracer"); -pub(crate) fn benchmark(dirs: &Dirs, host_compiler: &Compiler) { - benchmark_simple_raytracer(dirs, host_compiler); +pub(crate) fn benchmark(dirs: &Dirs, bootstrap_host_compiler: &Compiler) { + benchmark_simple_raytracer(dirs, bootstrap_host_compiler); } -fn benchmark_simple_raytracer(dirs: &Dirs, host_compiler: &Compiler) { +fn benchmark_simple_raytracer(dirs: &Dirs, bootstrap_host_compiler: &Compiler) { if std::process::Command::new("hyperfine").output().is_err() { eprintln!("Hyperfine not installed"); eprintln!("Hint: Try `cargo install hyperfine` to install hyperfine"); @@ -33,12 +33,12 @@ fn benchmark_simple_raytracer(dirs: &Dirs, host_compiler: &Compiler) { } eprintln!("[LLVM BUILD] simple-raytracer"); - let build_cmd = SIMPLE_RAYTRACER_LLVM.build(host_compiler, dirs); + let build_cmd = SIMPLE_RAYTRACER_LLVM.build(bootstrap_host_compiler, dirs); spawn_and_wait(build_cmd); fs::copy( SIMPLE_RAYTRACER_LLVM .target_dir(dirs) - .join(&host_compiler.triple) + .join(&bootstrap_host_compiler.triple) .join("debug") .join(get_file_name("main", "bin")), RelPath::BUILD.to_path(dirs).join(get_file_name("raytracer_cg_llvm", "bin")), diff --git a/build_system/build_backend.rs b/build_system/build_backend.rs index 6ab39e48f214f..514404305a3fa 100644 --- a/build_system/build_backend.rs +++ b/build_system/build_backend.rs @@ -10,10 +10,10 @@ pub(crate) static CG_CLIF: CargoProject = CargoProject::new(&RelPath::SOURCE, "c pub(crate) fn build_backend( dirs: &Dirs, channel: &str, - host_compiler: &Compiler, + bootstrap_host_compiler: &Compiler, use_unstable_features: bool, ) -> PathBuf { - let mut cmd = CG_CLIF.build(&host_compiler, dirs); + let mut cmd = CG_CLIF.build(&bootstrap_host_compiler, dirs); cmd.env("CARGO_BUILD_INCREMENTAL", "true"); // Force incr comp even in release mode @@ -48,7 +48,7 @@ pub(crate) fn build_backend( CG_CLIF .target_dir(dirs) - .join(&host_compiler.triple) + .join(&bootstrap_host_compiler.triple) .join(channel) .join(get_file_name("rustc_codegen_cranelift", "dylib")) } diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index b7228968f6313..92d01750fab00 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -17,7 +17,7 @@ pub(crate) fn build_sysroot( channel: &str, sysroot_kind: SysrootKind, cg_clif_dylib_src: &Path, - host_compiler: &Compiler, + bootstrap_host_compiler: &Compiler, target_triple: &str, ) { eprintln!("[BUILD] sysroot {:?}", sysroot_kind); @@ -53,7 +53,8 @@ pub(crate) fn build_sysroot( let default_sysroot = super::rustc_info::get_default_sysroot(); - let host_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(&host_compiler.triple).join("lib"); + let host_rustlib_lib = + RUSTLIB_DIR.to_path(dirs).join(&bootstrap_host_compiler.triple).join("lib"); let target_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(target_triple).join("lib"); fs::create_dir_all(&host_rustlib_lib).unwrap(); fs::create_dir_all(&target_rustlib_lib).unwrap(); @@ -83,7 +84,11 @@ pub(crate) fn build_sysroot( SysrootKind::None => {} // Nothing to do SysrootKind::Llvm => { for file in fs::read_dir( - default_sysroot.join("lib").join("rustlib").join(&host_compiler.triple).join("lib"), + default_sysroot + .join("lib") + .join("rustlib") + .join(&bootstrap_host_compiler.triple) + .join("lib"), ) .unwrap() { @@ -103,7 +108,7 @@ pub(crate) fn build_sysroot( try_hard_link(&file, host_rustlib_lib.join(file.file_name().unwrap())); } - if target_triple != host_compiler.triple { + if target_triple != bootstrap_host_compiler.triple { for file in fs::read_dir( default_sysroot.join("lib").join("rustlib").join(target_triple).join("lib"), ) @@ -118,19 +123,19 @@ pub(crate) fn build_sysroot( build_clif_sysroot_for_triple( dirs, channel, - host_compiler.clone(), + bootstrap_host_compiler.clone(), &cg_clif_dylib_path, ); - if host_compiler.triple != target_triple { + if bootstrap_host_compiler.triple != target_triple { build_clif_sysroot_for_triple( dirs, channel, { - let mut target_compiler = host_compiler.clone(); - target_compiler.triple = target_triple.to_owned(); - target_compiler.set_cross_linker_and_runner(); - target_compiler + let mut bootstrap_target_compiler = bootstrap_host_compiler.clone(); + bootstrap_target_compiler.triple = target_triple.to_owned(); + bootstrap_target_compiler.set_cross_linker_and_runner(); + bootstrap_target_compiler }, &cg_clif_dylib_path, ); diff --git a/build_system/mod.rs b/build_system/mod.rs index 265416c48fcca..910213be85e2c 100644 --- a/build_system/mod.rs +++ b/build_system/mod.rs @@ -97,7 +97,7 @@ pub fn main() { } } - let host_compiler = Compiler::llvm_with_triple( + let bootstrap_host_compiler = Compiler::bootstrap_with_triple( std::env::var("HOST_TRIPLE") .ok() .or_else(|| config::get_value("host")) @@ -106,7 +106,7 @@ pub fn main() { let target_triple = std::env::var("TARGET_TRIPLE") .ok() .or_else(|| config::get_value("target")) - .unwrap_or_else(|| host_compiler.triple.clone()); + .unwrap_or_else(|| bootstrap_host_compiler.triple.clone()); // FIXME allow changing the location of these dirs using cli arguments let current_dir = std::env::current_dir().unwrap(); @@ -137,8 +137,12 @@ pub fn main() { env::set_var("RUSTC", "rustc_should_be_set_explicitly"); env::set_var("RUSTDOC", "rustdoc_should_be_set_explicitly"); - let cg_clif_dylib = - build_backend::build_backend(&dirs, channel, &host_compiler, use_unstable_features); + let cg_clif_dylib = build_backend::build_backend( + &dirs, + channel, + &bootstrap_host_compiler, + use_unstable_features, + ); match command { Command::Prepare => { // Handled above @@ -149,12 +153,18 @@ pub fn main() { channel, sysroot_kind, &cg_clif_dylib, - &host_compiler, + &bootstrap_host_compiler, &target_triple, ); - if host_compiler.triple == target_triple { - abi_cafe::run(channel, sysroot_kind, &dirs, &cg_clif_dylib, &host_compiler); + if bootstrap_host_compiler.triple == target_triple { + abi_cafe::run( + channel, + sysroot_kind, + &dirs, + &cg_clif_dylib, + &bootstrap_host_compiler, + ); } else { eprintln!("[RUN] abi-cafe (skipped, cross-compilation not supported)"); return; @@ -166,7 +176,7 @@ pub fn main() { channel, sysroot_kind, &cg_clif_dylib, - &host_compiler, + &bootstrap_host_compiler, &target_triple, ); } @@ -176,10 +186,10 @@ pub fn main() { channel, sysroot_kind, &cg_clif_dylib, - &host_compiler, + &bootstrap_host_compiler, &target_triple, ); - bench::benchmark(&dirs, &host_compiler); + bench::benchmark(&dirs, &bootstrap_host_compiler); } } } diff --git a/build_system/tests.rs b/build_system/tests.rs index 6c4d0e2e35e7d..e915ed2a381d5 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -3,6 +3,7 @@ use super::build_sysroot::{self, SYSROOT_SRC}; use super::config; use super::path::{Dirs, RelPath}; use super::prepare::GitRepo; +use super::rustc_info::get_host_triple; use super::utils::{spawn_and_wait, spawn_and_wait_with_input, CargoProject, Compiler}; use super::SysrootKind; use std::env; @@ -240,14 +241,11 @@ pub(crate) fn run_tests( channel: &str, sysroot_kind: SysrootKind, cg_clif_dylib: &Path, - host_compiler: &Compiler, + bootstrap_host_compiler: &Compiler, target_triple: &str, ) { - let runner = TestRunner::new( - dirs.clone(), - target_triple.to_owned(), - host_compiler.triple == target_triple, - ); + let runner = + TestRunner::new(dirs.clone(), target_triple.to_owned(), get_host_triple() == target_triple); if config::get_bool("testsuite.no_sysroot") { build_sysroot::build_sysroot( @@ -255,7 +253,7 @@ pub(crate) fn run_tests( channel, SysrootKind::None, cg_clif_dylib, - host_compiler, + bootstrap_host_compiler, &target_triple, ); @@ -274,7 +272,7 @@ pub(crate) fn run_tests( channel, sysroot_kind, cg_clif_dylib, - host_compiler, + bootstrap_host_compiler, &target_triple, ); } diff --git a/build_system/utils.rs b/build_system/utils.rs index 935177a00ba87..07ea482fbbeaa 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -19,7 +19,7 @@ pub(crate) struct Compiler { } impl Compiler { - pub(crate) fn llvm_with_triple(triple: String) -> Compiler { + pub(crate) fn bootstrap_with_triple(triple: String) -> Compiler { Compiler { cargo: get_cargo_path(), rustc: get_rustc_path(), From 4dbafefe74f32ca7f76009e6ce3136348a017b3a Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 13:04:40 +0000 Subject: [PATCH 181/500] Return Compiler from build_sysroot --- build_system/abi_cafe.rs | 2 +- build_system/build_sysroot.rs | 26 +++++++++++++------- build_system/mod.rs | 6 ++--- build_system/tests.rs | 45 +++++++++++++++++------------------ 4 files changed, 43 insertions(+), 36 deletions(-) diff --git a/build_system/abi_cafe.rs b/build_system/abi_cafe.rs index 8352c1a965a75..8742389f33227 100644 --- a/build_system/abi_cafe.rs +++ b/build_system/abi_cafe.rs @@ -32,7 +32,7 @@ pub(crate) fn run( sysroot_kind, cg_clif_dylib, bootstrap_host_compiler, - &bootstrap_host_compiler.triple, + bootstrap_host_compiler.triple.clone(), ); eprintln!("Running abi-cafe"); diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index 92d01750fab00..7902c7005e017 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -18,14 +18,16 @@ pub(crate) fn build_sysroot( sysroot_kind: SysrootKind, cg_clif_dylib_src: &Path, bootstrap_host_compiler: &Compiler, - target_triple: &str, -) { + target_triple: String, +) -> Compiler { eprintln!("[BUILD] sysroot {:?}", sysroot_kind); DIST_DIR.ensure_fresh(dirs); BIN_DIR.ensure_exists(dirs); LIB_DIR.ensure_exists(dirs); + let is_native = bootstrap_host_compiler.triple == target_triple; + // Copy the backend let cg_clif_dylib_path = if cfg!(windows) { // Windows doesn't have rpath support, so the cg_clif dylib needs to be next to the @@ -55,12 +57,12 @@ pub(crate) fn build_sysroot( let host_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(&bootstrap_host_compiler.triple).join("lib"); - let target_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(target_triple).join("lib"); + let target_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(&target_triple).join("lib"); fs::create_dir_all(&host_rustlib_lib).unwrap(); fs::create_dir_all(&target_rustlib_lib).unwrap(); if target_triple == "x86_64-pc-windows-gnu" { - if !default_sysroot.join("lib").join("rustlib").join(target_triple).join("lib").exists() { + if !default_sysroot.join("lib").join("rustlib").join(&target_triple).join("lib").exists() { eprintln!( "The x86_64-pc-windows-gnu target needs to be installed first before it is possible \ to compile a sysroot for it.", @@ -68,7 +70,7 @@ pub(crate) fn build_sysroot( process::exit(1); } for file in fs::read_dir( - default_sysroot.join("lib").join("rustlib").join(target_triple).join("lib"), + default_sysroot.join("lib").join("rustlib").join(&target_triple).join("lib"), ) .unwrap() { @@ -108,9 +110,9 @@ pub(crate) fn build_sysroot( try_hard_link(&file, host_rustlib_lib.join(file.file_name().unwrap())); } - if target_triple != bootstrap_host_compiler.triple { + if !is_native { for file in fs::read_dir( - default_sysroot.join("lib").join("rustlib").join(target_triple).join("lib"), + default_sysroot.join("lib").join("rustlib").join(&target_triple).join("lib"), ) .unwrap() { @@ -127,13 +129,13 @@ pub(crate) fn build_sysroot( &cg_clif_dylib_path, ); - if bootstrap_host_compiler.triple != target_triple { + if !is_native { build_clif_sysroot_for_triple( dirs, channel, { let mut bootstrap_target_compiler = bootstrap_host_compiler.clone(); - bootstrap_target_compiler.triple = target_triple.to_owned(); + bootstrap_target_compiler.triple = target_triple.clone(); bootstrap_target_compiler.set_cross_linker_and_runner(); bootstrap_target_compiler }, @@ -152,6 +154,12 @@ pub(crate) fn build_sysroot( } } } + + let mut target_compiler = Compiler::clif_with_triple(&dirs, target_triple); + if !is_native { + target_compiler.set_cross_linker_and_runner(); + } + target_compiler } pub(crate) static ORIG_BUILD_SYSROOT: RelPath = RelPath::SOURCE.join("build_sysroot"); diff --git a/build_system/mod.rs b/build_system/mod.rs index 910213be85e2c..6f388cd605fce 100644 --- a/build_system/mod.rs +++ b/build_system/mod.rs @@ -154,7 +154,7 @@ pub fn main() { sysroot_kind, &cg_clif_dylib, &bootstrap_host_compiler, - &target_triple, + target_triple.clone(), ); if bootstrap_host_compiler.triple == target_triple { @@ -177,7 +177,7 @@ pub fn main() { sysroot_kind, &cg_clif_dylib, &bootstrap_host_compiler, - &target_triple, + target_triple, ); } Command::Bench => { @@ -187,7 +187,7 @@ pub fn main() { sysroot_kind, &cg_clif_dylib, &bootstrap_host_compiler, - &target_triple, + target_triple, ); bench::benchmark(&dirs, &bootstrap_host_compiler); } diff --git a/build_system/tests.rs b/build_system/tests.rs index e915ed2a381d5..dcfadd737566e 100644 --- a/build_system/tests.rs +++ b/build_system/tests.rs @@ -242,21 +242,21 @@ pub(crate) fn run_tests( sysroot_kind: SysrootKind, cg_clif_dylib: &Path, bootstrap_host_compiler: &Compiler, - target_triple: &str, + target_triple: String, ) { - let runner = - TestRunner::new(dirs.clone(), target_triple.to_owned(), get_host_triple() == target_triple); - if config::get_bool("testsuite.no_sysroot") { - build_sysroot::build_sysroot( + let target_compiler = build_sysroot::build_sysroot( dirs, channel, SysrootKind::None, cg_clif_dylib, bootstrap_host_compiler, - &target_triple, + target_triple.clone(), ); + let runner = + TestRunner::new(dirs.clone(), target_compiler, get_host_triple() == target_triple); + BUILD_EXAMPLE_OUT_DIR.ensure_fresh(dirs); runner.run_testsuite(NO_SYSROOT_SUITE); } else { @@ -267,26 +267,29 @@ pub(crate) fn run_tests( let run_extended_sysroot = config::get_bool("testsuite.extended_sysroot"); if run_base_sysroot || run_extended_sysroot { - build_sysroot::build_sysroot( + let target_compiler = build_sysroot::build_sysroot( dirs, channel, sysroot_kind, cg_clif_dylib, bootstrap_host_compiler, - &target_triple, + target_triple.clone(), ); - } - if run_base_sysroot { - runner.run_testsuite(BASE_SYSROOT_SUITE); - } else { - eprintln!("[SKIP] base_sysroot tests"); - } + let runner = + TestRunner::new(dirs.clone(), target_compiler, get_host_triple() == target_triple); - if run_extended_sysroot { - runner.run_testsuite(EXTENDED_SYSROOT_SUITE); - } else { - eprintln!("[SKIP] extended_sysroot tests"); + if run_base_sysroot { + runner.run_testsuite(BASE_SYSROOT_SUITE); + } else { + eprintln!("[SKIP] base_sysroot tests"); + } + + if run_extended_sysroot { + runner.run_testsuite(EXTENDED_SYSROOT_SUITE); + } else { + eprintln!("[SKIP] extended_sysroot tests"); + } } } @@ -298,11 +301,7 @@ struct TestRunner { } impl TestRunner { - pub fn new(dirs: Dirs, target_triple: String, is_native: bool) -> Self { - let mut target_compiler = Compiler::clif_with_triple(&dirs, target_triple); - if !is_native { - target_compiler.set_cross_linker_and_runner(); - } + pub fn new(dirs: Dirs, mut target_compiler: Compiler, is_native: bool) -> Self { if let Ok(rustflags) = env::var("RUSTFLAGS") { target_compiler.rustflags.push(' '); target_compiler.rustflags.push_str(&rustflags); From 22c5249f68676f7ba8852fd59cd222c49a1523a2 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 13:08:55 +0000 Subject: [PATCH 182/500] Don't hard-code rustc path in get_rustc_version and get_default_sysroot --- build_system/build_sysroot.rs | 4 ++-- build_system/prepare.rs | 4 ++-- build_system/rustc_info.rs | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index 7902c7005e017..15a5e030193db 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -53,7 +53,7 @@ pub(crate) fn build_sysroot( spawn_and_wait(build_cargo_wrapper_cmd); } - let default_sysroot = super::rustc_info::get_default_sysroot(); + let default_sysroot = super::rustc_info::get_default_sysroot(&bootstrap_host_compiler.rustc); let host_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(&bootstrap_host_compiler.triple).join("lib"); @@ -182,7 +182,7 @@ fn build_clif_sysroot_for_triple( process::exit(1); } Ok(source_version) => { - let rustc_version = get_rustc_version(); + let rustc_version = get_rustc_version(&compiler.rustc); if source_version != rustc_version { eprintln!("The patched sysroot source is outdated"); eprintln!("Source version: {}", source_version.trim()); diff --git a/build_system/prepare.rs b/build_system/prepare.rs index 4e898b30b7cce..bc6c3223dc234 100644 --- a/build_system/prepare.rs +++ b/build_system/prepare.rs @@ -35,7 +35,7 @@ pub(crate) fn prepare(dirs: &Dirs) { } fn prepare_sysroot(dirs: &Dirs) { - let sysroot_src_orig = get_default_sysroot().join("lib/rustlib/src/rust"); + let sysroot_src_orig = get_default_sysroot(Path::new("rustc")).join("lib/rustlib/src/rust"); assert!(sysroot_src_orig.exists()); eprintln!("[COPY] sysroot src"); @@ -50,7 +50,7 @@ fn prepare_sysroot(dirs: &Dirs) { &SYSROOT_SRC.to_path(dirs).join("library"), ); - let rustc_version = get_rustc_version(); + let rustc_version = get_rustc_version(Path::new("rustc")); fs::write(SYSROOT_RUSTC_VERSION.to_path(dirs), &rustc_version).unwrap(); eprintln!("[GIT] init"); diff --git a/build_system/rustc_info.rs b/build_system/rustc_info.rs index 8e5ab688e131b..6959d1e323cd6 100644 --- a/build_system/rustc_info.rs +++ b/build_system/rustc_info.rs @@ -1,9 +1,9 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -pub(crate) fn get_rustc_version() -> String { +pub(crate) fn get_rustc_version(rustc: &Path) -> String { let version_info = - Command::new("rustc").stderr(Stdio::inherit()).args(&["-V"]).output().unwrap().stdout; + Command::new(rustc).stderr(Stdio::inherit()).args(&["-V"]).output().unwrap().stdout; String::from_utf8(version_info).unwrap() } @@ -53,8 +53,8 @@ pub(crate) fn get_rustdoc_path() -> PathBuf { Path::new(String::from_utf8(rustc_path).unwrap().trim()).to_owned() } -pub(crate) fn get_default_sysroot() -> PathBuf { - let default_sysroot = Command::new("rustc") +pub(crate) fn get_default_sysroot(rustc: &Path) -> PathBuf { + let default_sysroot = Command::new(rustc) .stderr(Stdio::inherit()) .args(&["--print", "sysroot"]) .output() From 629eab79c16a6659a241c0b50ea986780934a65d Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 14:08:23 +0000 Subject: [PATCH 183/500] Avoid hard-coded rustc when building wrappers --- build_system/build_sysroot.rs | 7 +++++-- build_system/rustc_info.rs | 10 ++++++++++ scripts/cargo-clif.rs | 2 +- scripts/rustc-clif.rs | 2 +- scripts/rustdoc-clif.rs | 2 +- 5 files changed, 18 insertions(+), 5 deletions(-) diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index 15a5e030193db..9eebcf95505d9 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -3,7 +3,9 @@ use std::path::Path; use std::process::{self, Command}; use super::path::{Dirs, RelPath}; -use super::rustc_info::{get_file_name, get_rustc_version, get_wrapper_file_name}; +use super::rustc_info::{ + get_file_name, get_rustc_version, get_toolchain_name, get_wrapper_file_name, +}; use super::utils::{spawn_and_wait, try_hard_link, CargoProject, Compiler}; use super::SysrootKind; @@ -44,8 +46,9 @@ pub(crate) fn build_sysroot( for wrapper in ["rustc-clif", "rustdoc-clif", "cargo-clif"] { let wrapper_name = get_wrapper_file_name(wrapper, "bin"); - let mut build_cargo_wrapper_cmd = Command::new("rustc"); + let mut build_cargo_wrapper_cmd = Command::new(&bootstrap_host_compiler.rustc); build_cargo_wrapper_cmd + .env("TOOLCHAIN_NAME", get_toolchain_name()) .arg(RelPath::SCRIPTS.to_path(dirs).join(&format!("{wrapper}.rs"))) .arg("-o") .arg(DIST_DIR.to_path(dirs).join(wrapper_name)) diff --git a/build_system/rustc_info.rs b/build_system/rustc_info.rs index 6959d1e323cd6..8a7e1c472dd10 100644 --- a/build_system/rustc_info.rs +++ b/build_system/rustc_info.rs @@ -23,6 +23,16 @@ pub(crate) fn get_host_triple() -> String { .to_owned() } +pub(crate) fn get_toolchain_name() -> String { + let active_toolchain = Command::new("rustup") + .stderr(Stdio::inherit()) + .args(&["show", "active-toolchain"]) + .output() + .unwrap() + .stdout; + String::from_utf8(active_toolchain).unwrap().trim().split_once(' ').unwrap().0.to_owned() +} + pub(crate) fn get_cargo_path() -> PathBuf { let cargo_path = Command::new("rustup") .stderr(Stdio::inherit()) diff --git a/scripts/cargo-clif.rs b/scripts/cargo-clif.rs index 9362b47fa6d83..c993430b830b6 100644 --- a/scripts/cargo-clif.rs +++ b/scripts/cargo-clif.rs @@ -26,7 +26,7 @@ fn main() { env::set_var("RUSTDOCFLAGS", env::var("RUSTDOCFLAGS").unwrap_or(String::new()) + &rustflags); // Ensure that the right toolchain is used - env::set_var("RUSTUP_TOOLCHAIN", env!("RUSTUP_TOOLCHAIN")); + env::set_var("RUSTUP_TOOLCHAIN", env!("TOOLCHAIN_NAME")); let args: Vec<_> = match env::args().nth(1).as_deref() { Some("jit") => { diff --git a/scripts/rustc-clif.rs b/scripts/rustc-clif.rs index 3abfcd8ddc824..c187f54a60e77 100644 --- a/scripts/rustc-clif.rs +++ b/scripts/rustc-clif.rs @@ -24,7 +24,7 @@ fn main() { } // Ensure that the right toolchain is used - env::set_var("RUSTUP_TOOLCHAIN", env!("RUSTUP_TOOLCHAIN")); + env::set_var("RUSTUP_TOOLCHAIN", env!("TOOLCHAIN_NAME")); #[cfg(unix)] Command::new("rustc").args(args).exec(); diff --git a/scripts/rustdoc-clif.rs b/scripts/rustdoc-clif.rs index a19d72acfa83e..a6528ac41aee0 100644 --- a/scripts/rustdoc-clif.rs +++ b/scripts/rustdoc-clif.rs @@ -24,7 +24,7 @@ fn main() { } // Ensure that the right toolchain is used - env::set_var("RUSTUP_TOOLCHAIN", env!("RUSTUP_TOOLCHAIN")); + env::set_var("RUSTUP_TOOLCHAIN", env!("TOOLCHAIN_NAME")); #[cfg(unix)] Command::new("rustdoc").args(args).exec(); From dc5ce488e7e14e2cebb90d9c1cd189c970ee415f Mon Sep 17 00:00:00 2001 From: Tyler Weaver Date: Sat, 14 Jan 2023 07:38:29 -0700 Subject: [PATCH 184/500] Move CI tests for collect-metadata to clippy_bors.yml --- .github/workflows/clippy_bors.yml | 5 +++++ .github/workflows/remark.yml | 3 --- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clippy_bors.yml b/.github/workflows/clippy_bors.yml index 1bc457a947936..24e677ce8e170 100644 --- a/.github/workflows/clippy_bors.yml +++ b/.github/workflows/clippy_bors.yml @@ -157,6 +157,11 @@ jobs: - name: Test metadata collection run: cargo collect-metadata + - name: Test lint_configuration.md is up-to-date + run: | + echo "run \`cargo collect-metadata\` if this fails" + git update-index --refresh + integration_build: needs: changelog runs-on: ubuntu-latest diff --git a/.github/workflows/remark.yml b/.github/workflows/remark.yml index 22925a753dfe7..81ef072bbb07f 100644 --- a/.github/workflows/remark.yml +++ b/.github/workflows/remark.yml @@ -33,9 +33,6 @@ jobs: echo `pwd`/mdbook >> $GITHUB_PATH # Run - - name: cargo collect-metadata - run: cargo collect-metadata - - name: Check *.md files run: git ls-files -z '*.md' | xargs -0 -n 1 -I {} ./node_modules/.bin/remark {} -u lint -f > /dev/null From d950279a039b5a598c87b347ba5d2f151a071a98 Mon Sep 17 00:00:00 2001 From: Tyler Weaver Date: Sat, 14 Jan 2023 07:39:49 -0700 Subject: [PATCH 185/500] Document generating lint config docs for adding configuration --- book/src/development/adding_lints.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/book/src/development/adding_lints.md b/book/src/development/adding_lints.md index 8b4eee8c9d94d..fd6e1f5aef20e 100644 --- a/book/src/development/adding_lints.md +++ b/book/src/development/adding_lints.md @@ -699,6 +699,10 @@ for some users. Adding a configuration is done in the following steps: `clippy.toml` file with the configuration value and a rust file that should be linted by Clippy. The test can otherwise be written as usual. +5. Update [Lint Configuration](../lint_configuration.md) + + Run `cargo collect-metadata` to generate documentation changes for the book. + [`clippy_lints::utils::conf`]: https://github.com/rust-lang/rust-clippy/blob/master/clippy_lints/src/utils/conf.rs [`clippy_lints` lib file]: https://github.com/rust-lang/rust-clippy/blob/master/clippy_lints/src/lib.rs [`tests/ui`]: https://github.com/rust-lang/rust-clippy/blob/master/tests/ui From c950f2265ef898ff760219d16298bd96fecb7155 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 17:02:21 +0000 Subject: [PATCH 186/500] Build rtstartup for MinGW from scratch Rather than copying it from an existing sysroot --- .github/workflows/main.yml | 1 - build_system/build_sysroot.rs | 34 ++++++++++++++++------------------ 2 files changed, 16 insertions(+), 19 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f1badb792cd13..1181c935b8389 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -77,7 +77,6 @@ jobs: run: | sudo apt-get update sudo apt-get install -y gcc-mingw-w64-x86-64 wine-stable - rustup target add x86_64-pc-windows-gnu - name: Install AArch64 toolchain and qemu if: matrix.os == 'ubuntu-latest' && matrix.env.TARGET_TRIPLE == 'aarch64-unknown-linux-gnu' diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index 9eebcf95505d9..413aa3444a54b 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -64,24 +64,21 @@ pub(crate) fn build_sysroot( fs::create_dir_all(&host_rustlib_lib).unwrap(); fs::create_dir_all(&target_rustlib_lib).unwrap(); - if target_triple == "x86_64-pc-windows-gnu" { - if !default_sysroot.join("lib").join("rustlib").join(&target_triple).join("lib").exists() { - eprintln!( - "The x86_64-pc-windows-gnu target needs to be installed first before it is possible \ - to compile a sysroot for it.", - ); - process::exit(1); - } - for file in fs::read_dir( - default_sysroot.join("lib").join("rustlib").join(&target_triple).join("lib"), - ) - .unwrap() - { - let file = file.unwrap().path(); - if file.extension().map_or(true, |ext| ext.to_str().unwrap() != "o") { - continue; // only copy object files - } - try_hard_link(&file, target_rustlib_lib.join(file.file_name().unwrap())); + if target_triple.ends_with("windows-gnu") { + eprintln!("[BUILD] rtstartup for {target_triple}"); + + let rtstartup_src = SYSROOT_SRC.to_path(dirs).join("library").join("rtstartup"); + + for file in ["rsbegin", "rsend"] { + let mut build_rtstartup_cmd = Command::new(&bootstrap_host_compiler.rustc); + build_rtstartup_cmd + .arg("--target") + .arg(&target_triple) + .arg("--emit=obj") + .arg("-o") + .arg(target_rustlib_lib.join(format!("{file}.o"))) + .arg(rtstartup_src.join(format!("{file}.rs"))); + spawn_and_wait(build_rtstartup_cmd); } } @@ -209,6 +206,7 @@ fn build_clif_sysroot_for_triple( // Build sysroot let mut rustflags = " -Zforce-unstable-if-unmarked -Cpanic=abort".to_string(); rustflags.push_str(&format!(" -Zcodegen-backend={}", cg_clif_dylib_path.to_str().unwrap())); + // Necessary for MinGW to find rsbegin.o and rsend.o rustflags.push_str(&format!(" --sysroot={}", DIST_DIR.to_path(dirs).to_str().unwrap())); if channel == "release" { rustflags.push_str(" -Zmir-opt-level=3"); From 6f1e1775d3586d0f82bd202de461e4de27a0fe1c Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 17:40:16 +0000 Subject: [PATCH 187/500] Introduce SysrootTarget --- build_system/build_sysroot.rs | 69 +++++++++++++++++++++++------------ 1 file changed, 46 insertions(+), 23 deletions(-) diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index 413aa3444a54b..218db67a0eced 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -1,5 +1,5 @@ use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{self, Command}; use super::path::{Dirs, RelPath}; @@ -56,35 +56,40 @@ pub(crate) fn build_sysroot( spawn_and_wait(build_cargo_wrapper_cmd); } - let default_sysroot = super::rustc_info::get_default_sysroot(&bootstrap_host_compiler.rustc); - - let host_rustlib_lib = - RUSTLIB_DIR.to_path(dirs).join(&bootstrap_host_compiler.triple).join("lib"); - let target_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(&target_triple).join("lib"); - fs::create_dir_all(&host_rustlib_lib).unwrap(); - fs::create_dir_all(&target_rustlib_lib).unwrap(); - if target_triple.ends_with("windows-gnu") { eprintln!("[BUILD] rtstartup for {target_triple}"); let rtstartup_src = SYSROOT_SRC.to_path(dirs).join("library").join("rtstartup"); + let mut target_libs = SysrootTarget { triple: target_triple.clone(), libs: vec![] }; for file in ["rsbegin", "rsend"] { + let obj = RelPath::BUILD.to_path(dirs).join(format!("{file}.o")); let mut build_rtstartup_cmd = Command::new(&bootstrap_host_compiler.rustc); build_rtstartup_cmd .arg("--target") .arg(&target_triple) .arg("--emit=obj") .arg("-o") - .arg(target_rustlib_lib.join(format!("{file}.o"))) + .arg(&obj) .arg(rtstartup_src.join(format!("{file}.rs"))); spawn_and_wait(build_rtstartup_cmd); + target_libs.libs.push(obj); } - } + target_libs.install_into_sysroot(&DIST_DIR.to_path(dirs)) + } match sysroot_kind { SysrootKind::None => {} // Nothing to do SysrootKind::Llvm => { + let default_sysroot = + super::rustc_info::get_default_sysroot(&bootstrap_host_compiler.rustc); + + let host_rustlib_lib = + RUSTLIB_DIR.to_path(dirs).join(&bootstrap_host_compiler.triple).join("lib"); + let target_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(&target_triple).join("lib"); + fs::create_dir_all(&host_rustlib_lib).unwrap(); + fs::create_dir_all(&target_rustlib_lib).unwrap(); + for file in fs::read_dir( default_sysroot .join("lib") @@ -122,12 +127,13 @@ pub(crate) fn build_sysroot( } } SysrootKind::Clif => { - build_clif_sysroot_for_triple( + let host = build_clif_sysroot_for_triple( dirs, channel, bootstrap_host_compiler.clone(), &cg_clif_dylib_path, ); + host.install_into_sysroot(&DIST_DIR.to_path(dirs)); if !is_native { build_clif_sysroot_for_triple( @@ -140,16 +146,16 @@ pub(crate) fn build_sysroot( bootstrap_target_compiler }, &cg_clif_dylib_path, - ); + ) + .install_into_sysroot(&DIST_DIR.to_path(dirs)); } // Copy std for the host to the lib dir. This is necessary for the jit mode to find // libstd. - for file in fs::read_dir(host_rustlib_lib).unwrap() { - let file = file.unwrap().path(); - let filename = file.file_name().unwrap().to_str().unwrap(); + for lib in host.libs { + let filename = lib.file_name().unwrap().to_str().unwrap(); if filename.contains("std-") && !filename.contains(".rlib") { - try_hard_link(&file, LIB_DIR.to_path(dirs).join(file.file_name().unwrap())); + try_hard_link(&lib, LIB_DIR.to_path(dirs).join(lib.file_name().unwrap())); } } } @@ -162,6 +168,22 @@ pub(crate) fn build_sysroot( target_compiler } +struct SysrootTarget { + triple: String, + libs: Vec, +} + +impl SysrootTarget { + fn install_into_sysroot(&self, sysroot: &Path) { + let target_rustlib_lib = sysroot.join("lib").join("rustlib").join(&self.triple).join("lib"); + fs::create_dir_all(&target_rustlib_lib).unwrap(); + + for lib in &self.libs { + try_hard_link(lib, target_rustlib_lib.join(lib.file_name().unwrap())); + } + } +} + pub(crate) static ORIG_BUILD_SYSROOT: RelPath = RelPath::SOURCE.join("build_sysroot"); pub(crate) static BUILD_SYSROOT: RelPath = RelPath::DOWNLOAD.join("sysroot"); pub(crate) static SYSROOT_RUSTC_VERSION: RelPath = BUILD_SYSROOT.join("rustc_version"); @@ -169,12 +191,13 @@ pub(crate) static SYSROOT_SRC: RelPath = BUILD_SYSROOT.join("sysroot_src"); pub(crate) static STANDARD_LIBRARY: CargoProject = CargoProject::new(&BUILD_SYSROOT, "build_sysroot"); +#[must_use] fn build_clif_sysroot_for_triple( dirs: &Dirs, channel: &str, mut compiler: Compiler, cg_clif_dylib_path: &Path, -) { +) -> SysrootTarget { match fs::read_to_string(SYSROOT_RUSTC_VERSION.to_path(dirs)) { Err(e) => { eprintln!("Failed to get rustc version for patched sysroot source: {}", e); @@ -219,7 +242,8 @@ fn build_clif_sysroot_for_triple( build_cmd.env("__CARGO_DEFAULT_LIB_METADATA", "cg_clif"); spawn_and_wait(build_cmd); - // Copy all relevant files to the sysroot + let mut target_libs = SysrootTarget { triple: compiler.triple, libs: vec![] }; + for entry in fs::read_dir(build_dir.join("deps")).unwrap() { let entry = entry.unwrap(); if let Some(ext) = entry.path().extension() { @@ -229,9 +253,8 @@ fn build_clif_sysroot_for_triple( } else { continue; }; - try_hard_link( - entry.path(), - RUSTLIB_DIR.to_path(dirs).join(&compiler.triple).join("lib").join(entry.file_name()), - ); + target_libs.libs.push(entry.path()); } + + target_libs } From 0ac4456351b3767c0bd46af312cf6635cc98f6ef Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 17:51:54 +0000 Subject: [PATCH 188/500] Move rtstartup build to build_clif_sysroot_for_triple Also pass build/rtstartup as sysroot when building the standard library --- build_system/build_sysroot.rs | 57 ++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index 218db67a0eced..e8c45643765f4 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -56,28 +56,6 @@ pub(crate) fn build_sysroot( spawn_and_wait(build_cargo_wrapper_cmd); } - if target_triple.ends_with("windows-gnu") { - eprintln!("[BUILD] rtstartup for {target_triple}"); - - let rtstartup_src = SYSROOT_SRC.to_path(dirs).join("library").join("rtstartup"); - let mut target_libs = SysrootTarget { triple: target_triple.clone(), libs: vec![] }; - - for file in ["rsbegin", "rsend"] { - let obj = RelPath::BUILD.to_path(dirs).join(format!("{file}.o")); - let mut build_rtstartup_cmd = Command::new(&bootstrap_host_compiler.rustc); - build_rtstartup_cmd - .arg("--target") - .arg(&target_triple) - .arg("--emit=obj") - .arg("-o") - .arg(&obj) - .arg(rtstartup_src.join(format!("{file}.rs"))); - spawn_and_wait(build_rtstartup_cmd); - target_libs.libs.push(obj); - } - - target_libs.install_into_sysroot(&DIST_DIR.to_path(dirs)) - } match sysroot_kind { SysrootKind::None => {} // Nothing to do SysrootKind::Llvm => { @@ -190,6 +168,7 @@ pub(crate) static SYSROOT_RUSTC_VERSION: RelPath = BUILD_SYSROOT.join("rustc_ver pub(crate) static SYSROOT_SRC: RelPath = BUILD_SYSROOT.join("sysroot_src"); pub(crate) static STANDARD_LIBRARY: CargoProject = CargoProject::new(&BUILD_SYSROOT, "build_sysroot"); +pub(crate) static RTSTARTUP_SYSROOT: RelPath = RelPath::BUILD.join("rtstartup"); #[must_use] fn build_clif_sysroot_for_triple( @@ -216,6 +195,35 @@ fn build_clif_sysroot_for_triple( } } + let mut target_libs = SysrootTarget { triple: compiler.triple.clone(), libs: vec![] }; + + if compiler.triple.ends_with("windows-gnu") { + eprintln!("[BUILD] rtstartup for {}", compiler.triple); + + RTSTARTUP_SYSROOT.ensure_fresh(dirs); + + let rtstartup_src = SYSROOT_SRC.to_path(dirs).join("library").join("rtstartup"); + let mut rtstartup_target_libs = + SysrootTarget { triple: compiler.triple.clone(), libs: vec![] }; + + for file in ["rsbegin", "rsend"] { + let obj = RTSTARTUP_SYSROOT.to_path(dirs).join(format!("{file}.o")); + let mut build_rtstartup_cmd = Command::new(&compiler.rustc); + build_rtstartup_cmd + .arg("--target") + .arg(&compiler.triple) + .arg("--emit=obj") + .arg("-o") + .arg(&obj) + .arg(rtstartup_src.join(format!("{file}.rs"))); + spawn_and_wait(build_rtstartup_cmd); + rtstartup_target_libs.libs.push(obj.clone()); + target_libs.libs.push(obj); + } + + rtstartup_target_libs.install_into_sysroot(&RTSTARTUP_SYSROOT.to_path(dirs)); + } + let build_dir = STANDARD_LIBRARY.target_dir(dirs).join(&compiler.triple).join(channel); if !super::config::get_bool("keep_sysroot") { @@ -230,7 +238,8 @@ fn build_clif_sysroot_for_triple( let mut rustflags = " -Zforce-unstable-if-unmarked -Cpanic=abort".to_string(); rustflags.push_str(&format!(" -Zcodegen-backend={}", cg_clif_dylib_path.to_str().unwrap())); // Necessary for MinGW to find rsbegin.o and rsend.o - rustflags.push_str(&format!(" --sysroot={}", DIST_DIR.to_path(dirs).to_str().unwrap())); + rustflags + .push_str(&format!(" --sysroot={}", RTSTARTUP_SYSROOT.to_path(dirs).to_str().unwrap())); if channel == "release" { rustflags.push_str(" -Zmir-opt-level=3"); } @@ -242,8 +251,6 @@ fn build_clif_sysroot_for_triple( build_cmd.env("__CARGO_DEFAULT_LIB_METADATA", "cg_clif"); spawn_and_wait(build_cmd); - let mut target_libs = SysrootTarget { triple: compiler.triple, libs: vec![] }; - for entry in fs::read_dir(build_dir.join("deps")).unwrap() { let entry = entry.unwrap(); if let Some(ext) = entry.path().extension() { From c0da8acb72529fdfc156b006e9ee5d2f18f1a730 Mon Sep 17 00:00:00 2001 From: Tyler Weaver Date: Sat, 14 Jan 2023 11:10:40 -0700 Subject: [PATCH 189/500] Comment that lint_configuration.md is machine generated --- book/src/lint_configuration.md | 5 +++++ .../src/utils/internal_lints/metadata_collector.rs | 12 +++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/book/src/lint_configuration.md b/book/src/lint_configuration.md index cfaaefe3ea18e..f79dbb50ff490 100644 --- a/book/src/lint_configuration.md +++ b/book/src/lint_configuration.md @@ -1,3 +1,8 @@ + + ## Lint Configuration Options |
Option
| Default Value | |--|--| diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index 47604f6933b42..1995c373835bd 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -239,7 +239,17 @@ impl Drop for MetadataCollector { .create(true) .open(MARKDOWN_OUTPUT_FILE) .unwrap(); - writeln!(file, "{}", self.get_markdown_docs(),).unwrap(); + writeln!( + file, + " + +{}", + self.get_markdown_docs(), + ) + .unwrap(); } } From fd83b2794536514ba5fb46f51ba76ea2a82c6841 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 18:25:43 +0000 Subject: [PATCH 190/500] Port llvm sysroot building to SysrootTarget too and dedup some code --- build_system/build_sysroot.rs | 159 +++++++++++++++++----------------- 1 file changed, 80 insertions(+), 79 deletions(-) diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index e8c45643765f4..3f52721a4698e 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -12,7 +12,6 @@ use super::SysrootKind; static DIST_DIR: RelPath = RelPath::DIST; static BIN_DIR: RelPath = RelPath::DIST.join("bin"); static LIB_DIR: RelPath = RelPath::DIST.join("lib"); -static RUSTLIB_DIR: RelPath = LIB_DIR.join("rustlib"); pub(crate) fn build_sysroot( dirs: &Dirs, @@ -56,86 +55,37 @@ pub(crate) fn build_sysroot( spawn_and_wait(build_cargo_wrapper_cmd); } - match sysroot_kind { - SysrootKind::None => {} // Nothing to do - SysrootKind::Llvm => { - let default_sysroot = - super::rustc_info::get_default_sysroot(&bootstrap_host_compiler.rustc); - - let host_rustlib_lib = - RUSTLIB_DIR.to_path(dirs).join(&bootstrap_host_compiler.triple).join("lib"); - let target_rustlib_lib = RUSTLIB_DIR.to_path(dirs).join(&target_triple).join("lib"); - fs::create_dir_all(&host_rustlib_lib).unwrap(); - fs::create_dir_all(&target_rustlib_lib).unwrap(); - - for file in fs::read_dir( - default_sysroot - .join("lib") - .join("rustlib") - .join(&bootstrap_host_compiler.triple) - .join("lib"), - ) - .unwrap() - { - let file = file.unwrap().path(); - let file_name_str = file.file_name().unwrap().to_str().unwrap(); - if (file_name_str.contains("rustc_") - && !file_name_str.contains("rustc_std_workspace_") - && !file_name_str.contains("rustc_demangle")) - || file_name_str.contains("chalk") - || file_name_str.contains("tracing") - || file_name_str.contains("regex") - { - // These are large crates that are part of the rustc-dev component and are not - // necessary to run regular programs. - continue; - } - try_hard_link(&file, host_rustlib_lib.join(file.file_name().unwrap())); - } + let host = build_sysroot_for_triple( + dirs, + channel, + bootstrap_host_compiler.clone(), + &cg_clif_dylib_path, + sysroot_kind, + ); + host.install_into_sysroot(&DIST_DIR.to_path(dirs)); - if !is_native { - for file in fs::read_dir( - default_sysroot.join("lib").join("rustlib").join(&target_triple).join("lib"), - ) - .unwrap() - { - let file = file.unwrap().path(); - try_hard_link(&file, target_rustlib_lib.join(file.file_name().unwrap())); - } - } - } - SysrootKind::Clif => { - let host = build_clif_sysroot_for_triple( - dirs, - channel, - bootstrap_host_compiler.clone(), - &cg_clif_dylib_path, - ); - host.install_into_sysroot(&DIST_DIR.to_path(dirs)); - - if !is_native { - build_clif_sysroot_for_triple( - dirs, - channel, - { - let mut bootstrap_target_compiler = bootstrap_host_compiler.clone(); - bootstrap_target_compiler.triple = target_triple.clone(); - bootstrap_target_compiler.set_cross_linker_and_runner(); - bootstrap_target_compiler - }, - &cg_clif_dylib_path, - ) - .install_into_sysroot(&DIST_DIR.to_path(dirs)); - } + if !is_native { + build_sysroot_for_triple( + dirs, + channel, + { + let mut bootstrap_target_compiler = bootstrap_host_compiler.clone(); + bootstrap_target_compiler.triple = target_triple.clone(); + bootstrap_target_compiler.set_cross_linker_and_runner(); + bootstrap_target_compiler + }, + &cg_clif_dylib_path, + sysroot_kind, + ) + .install_into_sysroot(&DIST_DIR.to_path(dirs)); + } - // Copy std for the host to the lib dir. This is necessary for the jit mode to find - // libstd. - for lib in host.libs { - let filename = lib.file_name().unwrap().to_str().unwrap(); - if filename.contains("std-") && !filename.contains(".rlib") { - try_hard_link(&lib, LIB_DIR.to_path(dirs).join(lib.file_name().unwrap())); - } - } + // Copy std for the host to the lib dir. This is necessary for the jit mode to find + // libstd. + for lib in host.libs { + let filename = lib.file_name().unwrap().to_str().unwrap(); + if filename.contains("std-") && !filename.contains(".rlib") { + try_hard_link(&lib, LIB_DIR.to_path(dirs).join(lib.file_name().unwrap())); } } @@ -170,6 +120,57 @@ pub(crate) static STANDARD_LIBRARY: CargoProject = CargoProject::new(&BUILD_SYSROOT, "build_sysroot"); pub(crate) static RTSTARTUP_SYSROOT: RelPath = RelPath::BUILD.join("rtstartup"); +#[must_use] +fn build_sysroot_for_triple( + dirs: &Dirs, + channel: &str, + compiler: Compiler, + cg_clif_dylib_path: &Path, + sysroot_kind: SysrootKind, +) -> SysrootTarget { + match sysroot_kind { + SysrootKind::None => SysrootTarget { triple: compiler.triple, libs: vec![] }, + SysrootKind::Llvm => build_llvm_sysroot_for_triple(compiler), + SysrootKind::Clif => { + build_clif_sysroot_for_triple(dirs, channel, compiler, &cg_clif_dylib_path) + } + } +} + +#[must_use] +fn build_llvm_sysroot_for_triple(compiler: Compiler) -> SysrootTarget { + let default_sysroot = super::rustc_info::get_default_sysroot(&compiler.rustc); + + let mut target_libs = SysrootTarget { triple: compiler.triple, libs: vec![] }; + + for entry in fs::read_dir( + default_sysroot.join("lib").join("rustlib").join(&target_libs.triple).join("lib"), + ) + .unwrap() + { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_dir() { + continue; + } + let file = entry.path(); + let file_name_str = file.file_name().unwrap().to_str().unwrap(); + if (file_name_str.contains("rustc_") + && !file_name_str.contains("rustc_std_workspace_") + && !file_name_str.contains("rustc_demangle")) + || file_name_str.contains("chalk") + || file_name_str.contains("tracing") + || file_name_str.contains("regex") + { + // These are large crates that are part of the rustc-dev component and are not + // necessary to run regular programs. + continue; + } + target_libs.libs.push(file); + } + + target_libs +} + #[must_use] fn build_clif_sysroot_for_triple( dirs: &Dirs, From 280dffd82cba287bdac74cc23a0ea8359d7cd4e8 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 18:32:19 +0000 Subject: [PATCH 191/500] Build rtstartup for none sysroot too Even mini_core needs it --- build_system/build_sysroot.rs | 57 ++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index 3f52721a4698e..f92841ab993d1 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -129,7 +129,8 @@ fn build_sysroot_for_triple( sysroot_kind: SysrootKind, ) -> SysrootTarget { match sysroot_kind { - SysrootKind::None => SysrootTarget { triple: compiler.triple, libs: vec![] }, + SysrootKind::None => build_rtstartup(dirs, &compiler) + .unwrap_or(SysrootTarget { triple: compiler.triple, libs: vec![] }), SysrootKind::Llvm => build_llvm_sysroot_for_triple(compiler), SysrootKind::Clif => { build_clif_sysroot_for_triple(dirs, channel, compiler, &cg_clif_dylib_path) @@ -198,31 +199,10 @@ fn build_clif_sysroot_for_triple( let mut target_libs = SysrootTarget { triple: compiler.triple.clone(), libs: vec![] }; - if compiler.triple.ends_with("windows-gnu") { - eprintln!("[BUILD] rtstartup for {}", compiler.triple); - - RTSTARTUP_SYSROOT.ensure_fresh(dirs); - - let rtstartup_src = SYSROOT_SRC.to_path(dirs).join("library").join("rtstartup"); - let mut rtstartup_target_libs = - SysrootTarget { triple: compiler.triple.clone(), libs: vec![] }; - - for file in ["rsbegin", "rsend"] { - let obj = RTSTARTUP_SYSROOT.to_path(dirs).join(format!("{file}.o")); - let mut build_rtstartup_cmd = Command::new(&compiler.rustc); - build_rtstartup_cmd - .arg("--target") - .arg(&compiler.triple) - .arg("--emit=obj") - .arg("-o") - .arg(&obj) - .arg(rtstartup_src.join(format!("{file}.rs"))); - spawn_and_wait(build_rtstartup_cmd); - rtstartup_target_libs.libs.push(obj.clone()); - target_libs.libs.push(obj); - } - + if let Some(rtstartup_target_libs) = build_rtstartup(dirs, &compiler) { rtstartup_target_libs.install_into_sysroot(&RTSTARTUP_SYSROOT.to_path(dirs)); + + target_libs.libs.extend(rtstartup_target_libs.libs); } let build_dir = STANDARD_LIBRARY.target_dir(dirs).join(&compiler.triple).join(channel); @@ -266,3 +246,30 @@ fn build_clif_sysroot_for_triple( target_libs } + +fn build_rtstartup(dirs: &Dirs, compiler: &Compiler) -> Option { + if !compiler.triple.ends_with("windows-gnu") { + return None; + } + + RTSTARTUP_SYSROOT.ensure_fresh(dirs); + + let rtstartup_src = SYSROOT_SRC.to_path(dirs).join("library").join("rtstartup"); + let mut target_libs = SysrootTarget { triple: compiler.triple.clone(), libs: vec![] }; + + for file in ["rsbegin", "rsend"] { + let obj = RTSTARTUP_SYSROOT.to_path(dirs).join(format!("{file}.o")); + let mut build_rtstartup_cmd = Command::new(&compiler.rustc); + build_rtstartup_cmd + .arg("--target") + .arg(&compiler.triple) + .arg("--emit=obj") + .arg("-o") + .arg(&obj) + .arg(rtstartup_src.join(format!("{file}.rs"))); + spawn_and_wait(build_rtstartup_cmd); + target_libs.libs.push(obj.clone()); + } + + Some(target_libs) +} From 13197322ec78820cdd3214d8001f81fa4773918b Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 14 Jan 2023 18:45:47 +0000 Subject: [PATCH 192/500] Skip creating sysroot target dir if it will be empty --- build_system/build_sysroot.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index f92841ab993d1..d3bc7ec01286a 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -103,6 +103,10 @@ struct SysrootTarget { impl SysrootTarget { fn install_into_sysroot(&self, sysroot: &Path) { + if self.libs.is_empty() { + return; + } + let target_rustlib_lib = sysroot.join("lib").join("rustlib").join(&self.triple).join("lib"); fs::create_dir_all(&target_rustlib_lib).unwrap(); From 11e002a001348e7ea035c0cb2665be806e2a832e Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sat, 14 Jan 2023 13:49:00 -0800 Subject: [PATCH 193/500] Make stage2 rustdoc and proc-macro-srv disableable in x.py install --- config.toml.example | 23 ++++++++++++++++++----- src/bootstrap/dist.rs | 22 ++++++++++++++++------ src/bootstrap/tool.rs | 6 ++++++ 3 files changed, 40 insertions(+), 11 deletions(-) diff --git a/config.toml.example b/config.toml.example index 5e1d2f2e314ff..299bfd779e57a 100644 --- a/config.toml.example +++ b/config.toml.example @@ -285,11 +285,24 @@ changelog-seen = 2 # be built if `extended = true`. #extended = false -# Installs chosen set of extended tools if `extended = true`. By default builds -# all extended tools except `rust-demangler`, unless the target is also being -# built with `profiler = true`. If chosen tool failed to build the installation -# fails. If `extended = false`, this option is ignored. -#tools = ["cargo", "rls", "clippy", "rustfmt", "analysis", "src"] # + "rust-demangler" if `profiler` +# Set of tools to be included in the installation. +# +# If `extended = false`, the only one of these built by default is rustdoc. +# +# If `extended = true`, they're all included, with the exception of +# rust-demangler which additionally requires `profiler = true` to be set. +# +# If any enabled tool fails to build, the installation fails. +#tools = [ +# "cargo", +# "clippy", +# "rustdoc", +# "rustfmt", +# "rust-analyzer", +# "analysis", +# "src", +# "rust-demangler", # if profiler = true +#] # Verbosity level: 0 == not verbose, 1 == verbose, 2 == very verbose #verbose = 0 diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 68215790bed17..2bff0f21b5370 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -392,19 +392,29 @@ impl Step for Rustc { t!(fs::create_dir_all(image.join("bin"))); builder.cp_r(&src.join("bin"), &image.join("bin")); - builder.install(&builder.rustdoc(compiler), &image.join("bin"), 0o755); + if builder + .config + .tools + .as_ref() + .map_or(true, |tools| tools.iter().any(|tool| tool == "rustdoc")) + { + let rustdoc = builder.rustdoc(compiler); + builder.install(&rustdoc, &image.join("bin"), 0o755); + } - let ra_proc_macro_srv = builder - .ensure(tool::RustAnalyzerProcMacroSrv { + if let Some(ra_proc_macro_srv) = builder.ensure_if_default( + tool::RustAnalyzerProcMacroSrv { compiler: builder.compiler_for( compiler.stage, builder.config.build, compiler.host, ), target: compiler.host, - }) - .expect("rust-analyzer-proc-macro-server always builds"); - builder.install(&ra_proc_macro_srv, &image.join("libexec"), 0o755); + }, + builder.kind, + ) { + builder.install(&ra_proc_macro_srv, &image.join("libexec"), 0o755); + } let libdir_relative = builder.libdir_relative(compiler); diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index 9a2100c2fb785..ca5f500f93bc4 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -765,9 +765,15 @@ impl Step for RustAnalyzerProcMacroSrv { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { + let builder = run.builder; // Allow building `rust-analyzer-proc-macro-srv` both as part of the `rust-analyzer` and as a stand-alone tool. run.path("src/tools/rust-analyzer") .path("src/tools/rust-analyzer/crates/proc-macro-srv-cli") + .default_condition(builder.config.tools.as_ref().map_or(true, |tools| { + tools + .iter() + .any(|tool| tool == "rust-analyzer" || tool == "rust-analyzer-proc-macro-srv") + })) } fn make_run(run: RunConfig<'_>) { From 2883148e60603ce42ed296b9d9f1913083748f3a Mon Sep 17 00:00:00 2001 From: clubby789 Date: Fri, 28 Oct 2022 00:06:01 +0100 Subject: [PATCH 194/500] Special case deriving `PartialOrd` for certain enum layouts --- .../src/deriving/cmp/partial_ord.rs | 82 +++++++++++++++++-- tests/ui/deriving/deriving-all-codegen.stdout | 51 ++++++------ 2 files changed, 96 insertions(+), 37 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs index 5c4e5b7f81675..be247d415c7fe 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs @@ -1,7 +1,7 @@ use crate::deriving::generic::ty::*; use crate::deriving::generic::*; use crate::deriving::{path_std, pathvec_std}; -use rustc_ast::MetaItem; +use rustc_ast::{ExprKind, ItemKind, MetaItem, PatKind}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; @@ -21,6 +21,27 @@ pub fn expand_deriving_partial_ord( let attrs = thin_vec![cx.attr_word(sym::inline, span)]; + // Order in which to perform matching + let tag_then_data = if let Annotatable::Item(item) = item + && let ItemKind::Enum(def, _) = &item.kind { + let dataful: Vec = def.variants.iter().map(|v| !v.data.fields().is_empty()).collect(); + match dataful.iter().filter(|&&b| b).count() { + // No data, placing the tag check first makes codegen simpler + 0 => true, + 1..=2 => false, + _ => { + (0..dataful.len()-1).any(|i| { + if dataful[i] && let Some(idx) = dataful[i+1..].iter().position(|v| *v) { + idx >= 2 + } else { + false + } + }) + } + } + } else { + true + }; let partial_cmp_def = MethodDef { name: sym::partial_cmp, generics: Bounds::empty(), @@ -30,7 +51,7 @@ pub fn expand_deriving_partial_ord( attributes: attrs, unify_fieldless_variants: true, combine_substructure: combine_substructure(Box::new(|cx, span, substr| { - cs_partial_cmp(cx, span, substr) + cs_partial_cmp(cx, span, substr, tag_then_data) })), }; @@ -47,7 +68,12 @@ pub fn expand_deriving_partial_ord( trait_def.expand(cx, mitem, item, push) } -pub fn cs_partial_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> BlockOrExpr { +fn cs_partial_cmp( + cx: &mut ExtCtxt<'_>, + span: Span, + substr: &Substructure<'_>, + tag_then_data: bool, +) -> BlockOrExpr { let test_id = Ident::new(sym::cmp, span); let equal_path = cx.path_global(span, cx.std_path(&[sym::cmp, sym::Ordering, sym::Equal])); let partial_cmp_path = cx.std_path(&[sym::cmp, sym::PartialOrd, sym::partial_cmp]); @@ -74,12 +100,50 @@ pub fn cs_partial_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_ let args = vec![field.self_expr.clone(), other_expr.clone()]; cx.expr_call_global(field.span, partial_cmp_path.clone(), args) } - CsFold::Combine(span, expr1, expr2) => { - let eq_arm = - cx.arm(span, cx.pat_some(span, cx.pat_path(span, equal_path.clone())), expr1); - let neq_arm = - cx.arm(span, cx.pat_ident(span, test_id), cx.expr_ident(span, test_id)); - cx.expr_match(span, expr2, vec![eq_arm, neq_arm]) + CsFold::Combine(span, mut expr1, expr2) => { + // When the item is an enum, this expands to + // ``` + // match (expr2) { + // Some(Ordering::Equal) => expr1, + // cmp => cmp + // } + // ``` + // where `expr2` is `partial_cmp(self_tag, other_tag)`, and `expr1` is a `match` + // against the enum variants. This means that we begin by comparing the enum tags, + // before either inspecting their contents (if they match), or returning + // the `cmp::Ordering` of comparing the enum tags. + // ``` + // match partial_cmp(self_tag, other_tag) { + // Some(Ordering::Equal) => match (self, other) { + // (Self::A(self_0), Self::A(other_0)) => partial_cmp(self_0, other_0), + // (Self::B(self_0), Self::B(other_0)) => partial_cmp(self_0, other_0), + // _ => Some(Ordering::Equal) + // } + // cmp => cmp + // } + // ``` + // If we have any certain enum layouts, flipping this results in better codegen + // ``` + // match (self, other) { + // (Self::A(self_0), Self::A(other_0)) => partial_cmp(self_0, other_0), + // _ => partial_cmp(self_tag, other_tag) + // } + // ``` + // Reference: https://github.com/rust-lang/rust/pull/103659#issuecomment-1328126354 + + if !tag_then_data + && let ExprKind::Match(_, arms) = &mut expr1.kind + && let Some(last) = arms.last_mut() + && let PatKind::Wild = last.pat.kind { + last.body = expr2; + expr1 + } else { + let eq_arm = + cx.arm(span, cx.pat_some(span, cx.pat_path(span, equal_path.clone())), expr1); + let neq_arm = + cx.arm(span, cx.pat_ident(span, test_id), cx.expr_ident(span, test_id)); + cx.expr_match(span, expr2, vec![eq_arm, neq_arm]) + } } CsFold::Fieldless => cx.expr_some(span, cx.expr_path(equal_path.clone())), }, diff --git a/tests/ui/deriving/deriving-all-codegen.stdout b/tests/ui/deriving/deriving-all-codegen.stdout index a63cbd4ca7ede..49671be18c587 100644 --- a/tests/ui/deriving/deriving-all-codegen.stdout +++ b/tests/ui/deriving/deriving-all-codegen.stdout @@ -888,23 +888,20 @@ impl ::core::cmp::PartialOrd for Mixed { -> ::core::option::Option<::core::cmp::Ordering> { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); - match ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag) { - ::core::option::Option::Some(::core::cmp::Ordering::Equal) => - match (self, other) { - (Mixed::R(__self_0), Mixed::R(__arg1_0)) => - ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0), - (Mixed::S { d1: __self_0, d2: __self_1 }, Mixed::S { - d1: __arg1_0, d2: __arg1_1 }) => - match ::core::cmp::PartialOrd::partial_cmp(__self_0, - __arg1_0) { - ::core::option::Option::Some(::core::cmp::Ordering::Equal) - => ::core::cmp::PartialOrd::partial_cmp(__self_1, __arg1_1), - cmp => cmp, - }, - _ => - ::core::option::Option::Some(::core::cmp::Ordering::Equal), + match (self, other) { + (Mixed::R(__self_0), Mixed::R(__arg1_0)) => + ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0), + (Mixed::S { d1: __self_0, d2: __self_1 }, Mixed::S { + d1: __arg1_0, d2: __arg1_1 }) => + match ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0) + { + ::core::option::Option::Some(::core::cmp::Ordering::Equal) + => ::core::cmp::PartialOrd::partial_cmp(__self_1, __arg1_1), + cmp => cmp, }, - cmp => cmp, + _ => + ::core::cmp::PartialOrd::partial_cmp(&__self_tag, + &__arg1_tag), } } } @@ -1018,18 +1015,16 @@ impl ::core::cmp::PartialOrd for Fielded { -> ::core::option::Option<::core::cmp::Ordering> { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); - match ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag) { - ::core::option::Option::Some(::core::cmp::Ordering::Equal) => - match (self, other) { - (Fielded::X(__self_0), Fielded::X(__arg1_0)) => - ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0), - (Fielded::Y(__self_0), Fielded::Y(__arg1_0)) => - ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0), - (Fielded::Z(__self_0), Fielded::Z(__arg1_0)) => - ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0), - _ => unsafe { ::core::intrinsics::unreachable() } - }, - cmp => cmp, + match (self, other) { + (Fielded::X(__self_0), Fielded::X(__arg1_0)) => + ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0), + (Fielded::Y(__self_0), Fielded::Y(__arg1_0)) => + ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0), + (Fielded::Z(__self_0), Fielded::Z(__arg1_0)) => + ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0), + _ => + ::core::cmp::PartialOrd::partial_cmp(&__self_tag, + &__arg1_tag), } } } From abcff71bec1ef1614041e59ea4f947bb0a13267c Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sun, 15 Jan 2023 14:14:13 +0000 Subject: [PATCH 195/500] Significantly speed up assembling of sysroots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit By avoiding some redundant rustc calls and stripping debuginfo for wrappers. ./y.rs build --sysroot none now runs 44% faster. Benchmark 1: ./y_before.bin build --sysroot none Time (mean ± σ): 2.200 s ± 0.038 s [User: 2.140 s, System: 0.653 s] Range (min … max): 2.171 s … 2.303 s 10 runs Benchmark 2: ./y_after.bin build --sysroot none Time (mean ± σ): 1.528 s ± 0.020 s [User: 1.388 s, System: 0.490 s] Range (min … max): 1.508 s … 1.580 s 10 runs Summary './y_after.bin build --sysroot none' ran 1.44 ± 0.03 times faster than './y_before.bin build --sysroot none' --- build_system/bench.rs | 5 +++-- build_system/build_sysroot.rs | 27 +++++++++++++++++++++------ build_system/rustc_info.rs | 9 --------- build_system/utils.rs | 19 +------------------ 4 files changed, 25 insertions(+), 35 deletions(-) diff --git a/build_system/bench.rs b/build_system/bench.rs index 1e83f21ba577b..01d44dafbdd17 100644 --- a/build_system/bench.rs +++ b/build_system/bench.rs @@ -4,7 +4,7 @@ use std::path::Path; use super::path::{Dirs, RelPath}; use super::prepare::GitRepo; -use super::rustc_info::{get_file_name, get_wrapper_file_name}; +use super::rustc_info::get_file_name; use super::utils::{hyperfine_command, is_ci, spawn_and_wait, CargoProject, Compiler}; pub(crate) static SIMPLE_RAYTRACER_REPO: GitRepo = GitRepo::github( @@ -51,7 +51,8 @@ fn benchmark_simple_raytracer(dirs: &Dirs, bootstrap_host_compiler: &Compiler) { .unwrap(); eprintln!("[BENCH COMPILE] ebobby/simple-raytracer"); - let cargo_clif = RelPath::DIST.to_path(dirs).join(get_wrapper_file_name("cargo-clif", "bin")); + let cargo_clif = + RelPath::DIST.to_path(dirs).join(get_file_name("cargo_clif", "bin").replace('_', "-")); let manifest_path = SIMPLE_RAYTRACER.manifest_path(dirs); let target_dir = SIMPLE_RAYTRACER.target_dir(dirs); diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index d3bc7ec01286a..cbc58365e6974 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -3,9 +3,7 @@ use std::path::{Path, PathBuf}; use std::process::{self, Command}; use super::path::{Dirs, RelPath}; -use super::rustc_info::{ - get_file_name, get_rustc_version, get_toolchain_name, get_wrapper_file_name, -}; +use super::rustc_info::{get_cargo_path, get_file_name, get_rustc_version, get_toolchain_name}; use super::utils::{spawn_and_wait, try_hard_link, CargoProject, Compiler}; use super::SysrootKind; @@ -42,8 +40,9 @@ pub(crate) fn build_sysroot( try_hard_link(cg_clif_dylib_src, &cg_clif_dylib_path); // Build and copy rustc and cargo wrappers + let wrapper_base_name = get_file_name("____", "bin"); for wrapper in ["rustc-clif", "rustdoc-clif", "cargo-clif"] { - let wrapper_name = get_wrapper_file_name(wrapper, "bin"); + let wrapper_name = wrapper_base_name.replace("____", wrapper); let mut build_cargo_wrapper_cmd = Command::new(&bootstrap_host_compiler.rustc); build_cargo_wrapper_cmd @@ -51,7 +50,7 @@ pub(crate) fn build_sysroot( .arg(RelPath::SCRIPTS.to_path(dirs).join(&format!("{wrapper}.rs"))) .arg("-o") .arg(DIST_DIR.to_path(dirs).join(wrapper_name)) - .arg("-g"); + .arg("-Cstrip=debuginfo"); spawn_and_wait(build_cargo_wrapper_cmd); } @@ -89,7 +88,23 @@ pub(crate) fn build_sysroot( } } - let mut target_compiler = Compiler::clif_with_triple(&dirs, target_triple); + let mut target_compiler = { + let dirs: &Dirs = &dirs; + let rustc_clif = + RelPath::DIST.to_path(&dirs).join(wrapper_base_name.replace("____", "rustc-clif")); + let rustdoc_clif = + RelPath::DIST.to_path(&dirs).join(wrapper_base_name.replace("____", "rustdoc-clif")); + + Compiler { + cargo: get_cargo_path(), + rustc: rustc_clif.clone(), + rustdoc: rustdoc_clif.clone(), + rustflags: String::new(), + rustdocflags: String::new(), + triple: target_triple, + runner: vec![], + } + }; if !is_native { target_compiler.set_cross_linker_and_runner(); } diff --git a/build_system/rustc_info.rs b/build_system/rustc_info.rs index 8a7e1c472dd10..a70453b442289 100644 --- a/build_system/rustc_info.rs +++ b/build_system/rustc_info.rs @@ -93,12 +93,3 @@ pub(crate) fn get_file_name(crate_name: &str, crate_type: &str) -> String { assert!(file_name.contains(crate_name)); file_name } - -/// Similar to `get_file_name`, but converts any dashes (`-`) in the `crate_name` to -/// underscores (`_`). This is specially made for the rustc and cargo wrappers -/// which have a dash in the name, and that is not allowed in a crate name. -pub(crate) fn get_wrapper_file_name(crate_name: &str, crate_type: &str) -> String { - let crate_name = crate_name.replace('-', "_"); - let wrapper_name = get_file_name(&crate_name, crate_type); - wrapper_name.replace('_', "-") -} diff --git a/build_system/utils.rs b/build_system/utils.rs index 07ea482fbbeaa..21bfb1b1f00f5 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf}; use std::process::{self, Command, Stdio}; use super::path::{Dirs, RelPath}; -use super::rustc_info::{get_cargo_path, get_rustc_path, get_rustdoc_path, get_wrapper_file_name}; +use super::rustc_info::{get_cargo_path, get_rustc_path, get_rustdoc_path}; #[derive(Clone, Debug)] pub(crate) struct Compiler { @@ -31,23 +31,6 @@ impl Compiler { } } - pub(crate) fn clif_with_triple(dirs: &Dirs, triple: String) -> Compiler { - let rustc_clif = - RelPath::DIST.to_path(&dirs).join(get_wrapper_file_name("rustc-clif", "bin")); - let rustdoc_clif = - RelPath::DIST.to_path(&dirs).join(get_wrapper_file_name("rustdoc-clif", "bin")); - - Compiler { - cargo: get_cargo_path(), - rustc: rustc_clif.clone(), - rustdoc: rustdoc_clif.clone(), - rustflags: String::new(), - rustdocflags: String::new(), - triple, - runner: vec![], - } - } - pub(crate) fn set_cross_linker_and_runner(&mut self) { match self.triple.as_str() { "aarch64-unknown-linux-gnu" => { From 0f4df8fb0e56f7ac157fba4c4209f520ba7fba79 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sun, 15 Jan 2023 14:38:22 +0000 Subject: [PATCH 196/500] Eliminate a couple of extra calls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is an additional 17% improvement on ./y.rs compile --sysroot none Benchmark 1: ./y_before.bin build --sysroot none Time (mean ± σ): 1.533 s ± 0.022 s [User: 1.411 s, System: 0.471 s] Range (min … max): 1.517 s … 1.589 s 10 runs Benchmark 2: ./y_after.bin build --sysroot none Time (mean ± σ): 1.311 s ± 0.020 s [User: 1.232 s, System: 0.428 s] Range (min … max): 1.298 s … 1.366 s 10 runs Summary './y_after.bin build --sysroot none' ran 1.17 ± 0.02 times faster than './y_before.bin build --sysroot none' --- build_system/build_sysroot.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index cbc58365e6974..f52d34ffcd63f 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use std::process::{self, Command}; use super::path::{Dirs, RelPath}; -use super::rustc_info::{get_cargo_path, get_file_name, get_rustc_version, get_toolchain_name}; +use super::rustc_info::{get_file_name, get_rustc_version, get_toolchain_name}; use super::utils::{spawn_and_wait, try_hard_link, CargoProject, Compiler}; use super::SysrootKind; @@ -36,17 +36,18 @@ pub(crate) fn build_sysroot( LIB_DIR } .to_path(dirs) - .join(get_file_name("rustc_codegen_cranelift", "dylib")); + .join(cg_clif_dylib_src.file_name().unwrap()); try_hard_link(cg_clif_dylib_src, &cg_clif_dylib_path); // Build and copy rustc and cargo wrappers let wrapper_base_name = get_file_name("____", "bin"); + let toolchain_name = get_toolchain_name(); for wrapper in ["rustc-clif", "rustdoc-clif", "cargo-clif"] { let wrapper_name = wrapper_base_name.replace("____", wrapper); let mut build_cargo_wrapper_cmd = Command::new(&bootstrap_host_compiler.rustc); build_cargo_wrapper_cmd - .env("TOOLCHAIN_NAME", get_toolchain_name()) + .env("TOOLCHAIN_NAME", toolchain_name.clone()) .arg(RelPath::SCRIPTS.to_path(dirs).join(&format!("{wrapper}.rs"))) .arg("-o") .arg(DIST_DIR.to_path(dirs).join(wrapper_name)) @@ -96,7 +97,7 @@ pub(crate) fn build_sysroot( RelPath::DIST.to_path(&dirs).join(wrapper_base_name.replace("____", "rustdoc-clif")); Compiler { - cargo: get_cargo_path(), + cargo: bootstrap_host_compiler.cargo.clone(), rustc: rustc_clif.clone(), rustdoc: rustdoc_clif.clone(), rustflags: String::new(), From 2b99b9fd25df59eb8b483e9809185f28d28199ed Mon Sep 17 00:00:00 2001 From: Kyle Huey Date: Sun, 15 Jan 2023 09:40:46 -0800 Subject: [PATCH 197/500] Preserve split DWARF files when building archives. The optimization that removes artifacts when building libraries is correct from the compiler's perspective but not from a debugger's perspective. Unpacked split debuginfo is referred to by filename and debuggers need the artifact that contains debuginfo to continue to exist at that path. Ironically the test expects the correct behavior but it was not running. --- compiler/rustc_codegen_ssa/src/back/link.rs | 6 ------ compiler/rustc_session/src/config.rs | 12 ------------ tests/run-make-fulldeps/split-debuginfo/Makefile | 4 ++-- 3 files changed, 2 insertions(+), 20 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 342abf81f6a7c..5715bcf1f11d5 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -1300,12 +1300,6 @@ fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) { return (false, false); } - // If we're only producing artifacts that are archives, no need to preserve - // the objects as they're losslessly contained inside the archives. - if sess.crate_types().iter().all(|&x| x.is_archive()) { - return (false, false); - } - match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) { // If there is no split debuginfo then do not preserve objects. (SplitDebuginfo::Off, _) => (false, false), diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 55576b4e0d19d..46ae9b56a48f9 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -846,18 +846,6 @@ pub enum CrateType { ProcMacro, } -impl CrateType { - /// When generated, is this crate type an archive? - pub fn is_archive(&self) -> bool { - match *self { - CrateType::Rlib | CrateType::Staticlib => true, - CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro => { - false - } - } - } -} - #[derive(Clone, Hash, Debug, PartialEq, Eq)] pub enum Passes { Some(Vec), diff --git a/tests/run-make-fulldeps/split-debuginfo/Makefile b/tests/run-make-fulldeps/split-debuginfo/Makefile index 1831ab38fab49..44cda0d3d117f 100644 --- a/tests/run-make-fulldeps/split-debuginfo/Makefile +++ b/tests/run-make-fulldeps/split-debuginfo/Makefile @@ -254,12 +254,12 @@ unpacked-remapped-single: $(RUSTC) $(UNSTABLEOPTS) -C split-debuginfo=unpacked -C debuginfo=2 \ -Z split-dwarf-kind=single --remap-path-prefix $(TMPDIR)=/a foo.rs -g objdump -Wi $(TMPDIR)/foo | grep DW_AT_GNU_dwo_name | (! grep $(TMPDIR)) || exit 1 - ls $(TMPDIR)/*.o + rm $(TMPDIR)/*.o ls $(TMPDIR)/*.dwo && exit 1 || exit 0 ls $(TMPDIR)/*.dwp && exit 1 || exit 0 rm $(TMPDIR)/$(call BIN,foo) -unpacked-crosscrate: packed-crosscrate-split packed-crosscrate-single +unpacked-crosscrate: unpacked-crosscrate-split unpacked-crosscrate-single # - Debuginfo in `.dwo` files # - (bar) `.rlib` file created, contains `.dwo` From 656db98bd99caf7e5c5e81ad11ed8922e28c46fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 15 Jan 2023 03:06:44 +0000 Subject: [PATCH 198/500] Tweak E0597 CC #99430 --- .../rustc_borrowck/src/borrowck_errors.rs | 6 +- .../src/diagnostics/conflict_errors.rs | 2 +- .../src/diagnostics/explain_borrow.rs | 28 +++++ .../src/diagnostics/move_errors.rs | 2 +- .../src/traits/error_reporting/mod.rs | 2 +- tests/ui/asm/type-check-4.stderr | 6 +- .../associated-types-outlives.stderr | 3 + ...sue-74072-lifetime-name-annotations.stderr | 16 +-- .../issue-75785-confusing-named-region.stderr | 4 +- .../multiple-lifetimes/ret-ref.stderr | 12 +- tests/ui/augmented-assignments.rs | 2 +- tests/ui/augmented-assignments.stderr | 2 + tests/ui/binop/binop-move-semantics.stderr | 5 + .../borrowck-anon-fields-variant.stderr | 4 +- tests/ui/borrowck/borrowck-assign-comp.stderr | 12 +- ...ck-assign-to-andmut-in-borrowed-loc.stderr | 6 +- .../borrowck-closures-mut-and-imm.stderr | 16 +-- .../borrowck/borrowck-describe-lvalue.stderr | 42 +++---- ...m-ref-to-mut-rec-field-issue-3162-c.stderr | 4 +- tests/ui/borrowck/borrowck-issue-14498.stderr | 32 +++--- .../borrowck/borrowck-lend-flow-match.stderr | 4 +- .../borrowck-loan-blocks-move-cc.stderr | 4 + .../borrowck/borrowck-loan-blocks-move.stderr | 2 + ...wck-loan-of-static-data-issue-27616.stderr | 4 +- .../borrowck-loan-rcvr-overloaded-op.stderr | 2 +- .../borrowck-match-already-borrowed.stderr | 8 +- .../borrowck/borrowck-move-by-capture.stderr | 2 +- ...-move-from-subpath-of-borrowed-path.stderr | 2 + .../borrowck-move-subcomponent.stderr | 2 + .../borrowck-multiple-captures.stderr | 6 + ...erloaded-index-and-overloaded-deref.stderr | 4 +- ...borrowck-overloaded-index-autoderef.stderr | 16 +-- ...orrowck-overloaded-index-move-index.stderr | 4 + .../borrowck-pat-reassign-binding.stderr | 4 +- .../borrowck-union-borrow-nested.stderr | 2 +- .../ui/borrowck/borrowck-union-borrow.stderr | 20 ++-- .../borrowck/borrowck-use-mut-borrow.stderr | 18 +-- .../borrowck-vec-pattern-move-tail.stderr | 4 +- .../borrowck/borrowck-vec-pattern-nesting.rs | 8 +- .../borrowck-vec-pattern-nesting.stderr | 8 +- tests/ui/borrowck/issue-25793.stderr | 2 +- tests/ui/borrowck/issue-52713-bug.stderr | 4 +- ...issue-58776-borrowck-scans-children.stderr | 4 +- tests/ui/borrowck/issue-81365-1.stderr | 4 +- tests/ui/borrowck/issue-81365-10.stderr | 4 +- tests/ui/borrowck/issue-81365-11.stderr | 4 +- tests/ui/borrowck/issue-81365-2.stderr | 4 +- tests/ui/borrowck/issue-81365-3.stderr | 4 +- tests/ui/borrowck/issue-81365-4.stderr | 4 +- tests/ui/borrowck/issue-81365-5.stderr | 4 +- tests/ui/borrowck/issue-81365-6.stderr | 4 +- tests/ui/borrowck/issue-81365-7.stderr | 4 +- tests/ui/borrowck/issue-81365-8.stderr | 4 +- tests/ui/borrowck/issue-81365-9.stderr | 4 +- ...ccess-during-reservation.nll_target.stderr | 4 +- .../two-phase-surprise-no-conflict.stderr | 2 +- tests/ui/btreemap/btreemap_dropck.stderr | 2 + tests/ui/c-variadic/variadic-ffi-4.stderr | 4 +- .../diagnostics/arrays.stderr | 14 +-- .../diagnostics/box.stderr | 8 +- .../diagnostics/union.rs | 4 +- .../diagnostics/union.stderr | 4 +- .../coerce-overloaded-autoderef-fail.stderr | 4 +- tests/ui/consts/promote_const_let.stderr | 1 + .../dropck-eyepatch-extern-crate.stderr | 6 + .../ui/dropck/dropck-eyepatch-reorder.stderr | 6 + tests/ui/dropck/dropck-eyepatch.stderr | 6 + tests/ui/dropck/dropck-union.stderr | 2 + .../dropck/dropck_trait_cycle_checked.stderr | 12 +- tests/ui/dst/dst-bad-coerce3.stderr | 10 +- tests/ui/error-codes/E0503.stderr | 2 +- tests/ui/error-codes/E0504.stderr | 2 + tests/ui/error-codes/E0505.stderr | 3 + tests/ui/error-codes/E0506.stderr | 4 +- tests/ui/error-codes/E0597.stderr | 2 + ...ied-bounds-unnorm-associated-type-4.stderr | 2 + ...plied-bounds-unnorm-associated-type.stderr | 2 + .../issue-74684-1.stderr | 1 + .../hrtb-identity-fn-borrows.stderr | 4 +- .../feature-self-return-type.stderr | 3 + .../assoc-ty-wf-used-to-get-assoc-ty.stderr | 2 + .../const-expr-lifetime-err.stderr | 1 + tests/ui/issues/issue-40288.stderr | 4 +- tests/ui/issues/issue-45697-1.stderr | 6 +- tests/ui/issues/issue-45697.stderr | 6 +- tests/ui/issues/issue-46471-1.stderr | 7 +- ...600-expected-return-static-indirect.stderr | 2 + .../mut-pattern-internal-mutability.stderr | 4 +- tests/ui/nll/borrowed-local-error.stderr | 1 + .../ui/nll/borrowed-match-issue-45045.stderr | 2 +- tests/ui/nll/capture-ref-in-struct.stderr | 3 + tests/ui/nll/closure-access-spans.stderr | 4 +- tests/ui/nll/closure-borrow-spans.stderr | 14 +-- .../escape-argument.stderr | 3 + ...er-to-static-comparing-against-free.stderr | 2 + tests/ui/nll/closure-use-spans.stderr | 12 +- ...ignore-lifetime-bounds-in-copy-proj.stderr | 2 + ...-not-ignore-lifetime-bounds-in-copy.stderr | 2 + tests/ui/nll/dont-print-desugared.stderr | 1 + tests/ui/nll/drop-no-may-dangle.stderr | 8 +- tests/ui/nll/guarantor-issue-46974.stderr | 4 +- ...issue-27282-move-ref-mut-into-guard.stderr | 4 +- .../nll/issue-27282-mutation-in-guard.stderr | 4 +- tests/ui/nll/issue-27868.stderr | 4 +- tests/ui/nll/issue-46036.stderr | 2 + tests/ui/nll/issue-48803.stderr | 4 +- tests/ui/nll/issue-52534-2.stderr | 2 + tests/ui/nll/issue-52663-trait-object.stderr | 2 + ...sue-54382-use-span-of-tail-of-block.stderr | 3 + tests/ui/nll/issue-54556-stephaneyfx.stderr | 2 + ...ssue-54556-temps-in-tail-diagnostic.stderr | 3 + .../issue-54556-used-vs-unused-tails.stderr | 103 ++++++++++-------- tests/ui/nll/issue-54556-wrap-it-up.stderr | 4 +- tests/ui/nll/issue-55511.stderr | 2 + tests/ui/nll/issue-57989.stderr | 4 +- tests/ui/nll/issue-68550.stderr | 4 +- tests/ui/nll/issue-69114-static-mut-ty.stderr | 6 + tests/ui/nll/issue-69114-static-ty.stderr | 2 + tests/ui/nll/loan_ends_mid_block_pair.stderr | 4 +- .../nll/local-outlives-static-via-hrtb.stderr | 5 + tests/ui/nll/match-cfg-fake-edges2.stderr | 2 +- .../ui/nll/match-guards-always-borrow.stderr | 4 +- .../nll/match-guards-partially-borrow.stderr | 8 +- tests/ui/nll/match-on-borrowed.stderr | 6 +- ...ialized-drop-implicit-fragment-drop.stderr | 4 +- ...aybe-initialized-drop-with-fragment.stderr | 4 +- ...d-drop-with-uninitialized-fragments.stderr | 4 +- tests/ui/nll/maybe-initialized-drop.stderr | 4 +- .../nll/polonius/polonius-smoke-test.stderr | 2 +- tests/ui/nll/promoted-bounds.stderr | 1 + ...erence-carried-through-struct-field.stderr | 2 +- .../nll/relate_tys/var-appears-twice.stderr | 3 + .../user-annotations/adt-brace-enums.stderr | 3 + .../user-annotations/adt-brace-structs.stderr | 3 + .../user-annotations/adt-nullary-enums.stderr | 6 +- .../user-annotations/adt-tuple-enums.stderr | 3 + .../adt-tuple-struct-calls.stderr | 7 +- .../user-annotations/adt-tuple-struct.stderr | 3 + .../cast_static_lifetime.stderr | 2 + .../constant-in-expr-inherent-2.stderr | 11 ++ tests/ui/nll/user-annotations/fns.stderr | 3 + .../nll/user-annotations/method-call.stderr | 4 + .../nll/user-annotations/method-ufcs-1.stderr | 5 + .../nll/user-annotations/method-ufcs-2.stderr | 8 +- .../nll/user-annotations/method-ufcs-3.stderr | 4 + .../method-ufcs-inherent-1.stderr | 1 + .../method-ufcs-inherent-2.stderr | 2 + .../method-ufcs-inherent-3.stderr | 1 + .../method-ufcs-inherent-4.stderr | 2 + .../nll/user-annotations/normalization.stderr | 4 + ...attern_substs_on_brace_enum_variant.stderr | 4 + .../pattern_substs_on_brace_struct.stderr | 4 + ...attern_substs_on_tuple_enum_variant.stderr | 4 + .../pattern_substs_on_tuple_struct.stderr | 4 + tests/ui/nll/user-annotations/patterns.stderr | 24 ++++ .../promoted-annotation.stderr | 1 + .../type_ascription_static_lifetime.stderr | 2 + .../borrowck-move-ref-pattern.stderr | 2 + ...suggest-adding-bound-to-opaque-type.stderr | 2 + tests/ui/regions/regions-addr-of-arg.stderr | 2 + ...egions-free-region-ordering-caller1.stderr | 2 + .../regions-infer-proc-static-upvar.stderr | 2 + tests/ui/regions/regions-nested-fns.stderr | 2 + .../regions-pattern-typing-issue-19552.stderr | 2 + .../regions-pattern-typing-issue-19997.stderr | 4 +- .../borrowck-non-exhaustive.stderr | 2 +- .../lifetime-update.stderr | 3 + tests/ui/self/issue-61882-2.stderr | 2 + ...borrowck-call-is-borrow-issue-12224.stderr | 3 + tests/ui/span/dropck_arr_cycle_checked.stderr | 9 ++ .../span/dropck_direct_cycle_with_drop.stderr | 5 + tests/ui/span/dropck_misc_variants.stderr | 6 + tests/ui/span/dropck_vec_cycle_checked.stderr | 9 ++ ...5-dropck-child-has-items-via-parent.stderr | 3 + .../issue-24805-dropck-trait-has-items.stderr | 9 ++ .../span/issue-24895-copy-clone-dropck.stderr | 3 + tests/ui/span/issue-25199.stderr | 2 + tests/ui/span/issue-26656.stderr | 3 + tests/ui/span/issue-29106.stderr | 6 + tests/ui/span/issue-36537.stderr | 2 + tests/ui/span/issue-40157.stderr | 8 +- .../issue28498-reject-lifetime-param.stderr | 3 + .../issue28498-reject-passed-to-fn.stderr | 3 + .../span/issue28498-reject-trait-bound.stderr | 3 + tests/ui/span/mut-ptr-cant-outlive-ref.stderr | 2 + tests/ui/span/range-2.stderr | 8 +- .../regionck-unboxed-closure-lifetimes.stderr | 2 + ...regions-close-over-type-parameter-2.stderr | 2 + .../regions-escape-loop-via-variable.stderr | 4 +- .../span/regions-escape-loop-via-vec.stderr | 13 +-- .../send-is-not-static-ensures-scoping.stderr | 1 + .../span/send-is-not-static-std-sync-2.stderr | 6 +- .../span/send-is-not-static-std-sync.stderr | 6 + .../vec-must-not-hide-type-from-dropck.stderr | 6 + .../vec_refs_data_with_early_death.stderr | 6 + .../span/wf-method-late-bound-regions.stderr | 1 + tests/ui/static/static-lifetime-bound.stderr | 2 + .../suggestions/borrow-for-loop-head.stderr | 2 + .../suggestions/option-content-move2.stderr | 2 +- .../check-trait-object-bounds-3.stderr | 2 + .../ui/traits/coercion-generic-regions.stderr | 2 + tests/ui/traits/vtable/issue-97381.stderr | 3 + .../try-block/try-block-bad-lifetime.stderr | 9 +- .../try-block-maybe-bad-lifetime.stderr | 8 +- .../unboxed-closures-borrow-conflict.stderr | 2 +- ...oxed-closures-failed-recursive-fn-1.stderr | 8 +- tests/ui/unop-move-semantics.stderr | 5 + tests/ui/variance/variance-issue-20533.stderr | 6 + 208 files changed, 772 insertions(+), 349 deletions(-) diff --git a/compiler/rustc_borrowck/src/borrowck_errors.rs b/compiler/rustc_borrowck/src/borrowck_errors.rs index a4943d112042d..2bbb9618dbf09 100644 --- a/compiler/rustc_borrowck/src/borrowck_errors.rs +++ b/compiler/rustc_borrowck/src/borrowck_errors.rs @@ -37,7 +37,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { desc, ); - err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_desc)); + err.span_label(borrow_span, format!("{} is borrowed here", borrow_desc)); err.span_label(span, format!("use of borrowed {}", borrow_desc)); err } @@ -250,8 +250,8 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { desc, ); - err.span_label(borrow_span, format!("borrow of {} occurs here", desc)); - err.span_label(span, format!("assignment to borrowed {} occurs here", desc)); + err.span_label(borrow_span, format!("{} is borrowed here", desc)); + err.span_label(span, format!("{} is assigned to here but it was already borrowed", desc)); err } diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 968c1f49b95c0..0ab8aabd63bd0 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -1742,7 +1742,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &self.local_names, &mut err, "", - None, + Some(borrow_span), None, ); } diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index 2095747097b76..e4f45c53aefe5 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -1,6 +1,8 @@ //! Print diagnostics to explain why values are borrowed. use rustc_errors::{Applicability, Diagnostic}; +use rustc_hir as hir; +use rustc_hir::intravisit::Visitor; use rustc_index::vec::IndexVec; use rustc_infer::infer::NllRegionVariableOrigin; use rustc_middle::mir::{ @@ -11,6 +13,7 @@ use rustc_middle::ty::adjustment::PointerCast; use rustc_middle::ty::{self, RegionVid, TyCtxt}; use rustc_span::symbol::{kw, Symbol}; use rustc_span::{sym, DesugaringKind, Span}; +use rustc_trait_selection::traits::error_reporting::FindExprBySpan; use crate::region_infer::{BlameConstraint, ExtraConstraintInfo}; use crate::{ @@ -63,6 +66,31 @@ impl<'tcx> BorrowExplanation<'tcx> { borrow_span: Option, multiple_borrow_span: Option<(Span, Span)>, ) { + if let Some(span) = borrow_span { + let def_id = body.source.def_id(); + if let Some(node) = tcx.hir().get_if_local(def_id) + && let Some(body_id) = node.body_id() + { + let body = tcx.hir().body(body_id); + let mut expr_finder = FindExprBySpan::new(span); + expr_finder.visit_expr(body.value); + if let Some(mut expr) = expr_finder.result { + while let hir::ExprKind::AddrOf(_, _, inner) = &expr.kind { + expr = inner; + } + if let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind + && let [hir::PathSegment { ident, args: None, .. }] = p.segments + && let hir::def::Res::Local(hir_id) = p.res + && let Some(hir::Node::Pat(pat)) = tcx.hir().find(hir_id) + { + err.span_label( + pat.span, + &format!("binding `{ident}` declared here"), + ); + } + } + } + } match *self { BorrowExplanation::UsedLater(later_use_kind, var_or_use_span, path_span) => { let message = match later_use_kind { diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 6db3c858ae714..ea58ad5ae3e34 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -448,7 +448,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { }; self.note_type_does_not_implement_copy(err, &place_desc, place_ty, Some(span), ""); - use_spans.args_span_label(err, format!("move out of {place_desc} occurs here")); + use_spans.args_span_label(err, format!("{place_desc} is moved here")); } } } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index edd187b8dec3b..c3d097b5d7559 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -2827,7 +2827,7 @@ pub struct FindExprBySpan<'hir> { } impl<'hir> FindExprBySpan<'hir> { - fn new(span: Span) -> Self { + pub fn new(span: Span) -> Self { Self { span, result: None, ty_result: None } } } diff --git a/tests/ui/asm/type-check-4.stderr b/tests/ui/asm/type-check-4.stderr index c97cd171b1e38..b5ecb3e1b56fb 100644 --- a/tests/ui/asm/type-check-4.stderr +++ b/tests/ui/asm/type-check-4.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `a` because it is borrowed --> $DIR/type-check-4.rs:14:9 | LL | let p = &a; - | -- borrow of `a` occurs here + | -- `a` is borrowed here LL | asm!("{}", out(reg) a); - | ^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `a` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^ `a` is assigned to here but it was already borrowed LL | LL | println!("{}", p); | - borrow later used here @@ -13,7 +13,7 @@ error[E0503]: cannot use `a` because it was mutably borrowed --> $DIR/type-check-4.rs:22:28 | LL | let p = &mut a; - | ------ borrow of `a` occurs here + | ------ `a` is borrowed here LL | asm!("{}", in(reg) a); | ^ use of borrowed `a` LL | diff --git a/tests/ui/associated-types/associated-types-outlives.stderr b/tests/ui/associated-types/associated-types-outlives.stderr index 840e33b4b8a8e..2fe3f2d4a0250 100644 --- a/tests/ui/associated-types/associated-types-outlives.stderr +++ b/tests/ui/associated-types/associated-types-outlives.stderr @@ -1,6 +1,9 @@ error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/associated-types-outlives.rs:22:14 | +LL | F: for<'a> FnOnce(>::Bar)>(x: T, f: F) { + | - binding `x` declared here +... LL | 's: loop { y = denormalise(&x); break } | -- borrow of `x` occurs here LL | drop(x); diff --git a/tests/ui/async-await/issue-74072-lifetime-name-annotations.stderr b/tests/ui/async-await/issue-74072-lifetime-name-annotations.stderr index b96cab9f0f51a..628ba1a481893 100644 --- a/tests/ui/async-await/issue-74072-lifetime-name-annotations.stderr +++ b/tests/ui/async-await/issue-74072-lifetime-name-annotations.stderr @@ -4,9 +4,9 @@ error[E0506]: cannot assign to `*x` because it is borrowed LL | pub async fn async_fn(x: &mut i32) -> &i32 { | - let's call the lifetime of this reference `'1` LL | let y = &*x; - | --- borrow of `*x` occurs here + | --- `*x` is borrowed here LL | *x += 1; - | ^^^^^^^ assignment to borrowed `*x` occurs here + | ^^^^^^^ `*x` is assigned to here but it was already borrowed LL | y | - returning this value requires that `*x` is borrowed for `'1` @@ -14,9 +14,9 @@ error[E0506]: cannot assign to `*x` because it is borrowed --> $DIR/issue-74072-lifetime-name-annotations.rs:16:9 | LL | let y = &*x; - | --- borrow of `*x` occurs here + | --- `*x` is borrowed here LL | *x += 1; - | ^^^^^^^ assignment to borrowed `*x` occurs here + | ^^^^^^^ `*x` is assigned to here but it was already borrowed LL | y | - returning this value requires that `*x` is borrowed for `'1` LL | })() @@ -28,9 +28,9 @@ error[E0506]: cannot assign to `*x` because it is borrowed LL | (async move || -> &i32 { | - let's call the lifetime of this reference `'1` LL | let y = &*x; - | --- borrow of `*x` occurs here + | --- `*x` is borrowed here LL | *x += 1; - | ^^^^^^^ assignment to borrowed `*x` occurs here + | ^^^^^^^ `*x` is assigned to here but it was already borrowed LL | y | - returning this value requires that `*x` is borrowed for `'1` @@ -38,9 +38,9 @@ error[E0506]: cannot assign to `*x` because it is borrowed --> $DIR/issue-74072-lifetime-name-annotations.rs:32:9 | LL | let y = &*x; - | --- borrow of `*x` occurs here + | --- `*x` is borrowed here LL | *x += 1; - | ^^^^^^^ assignment to borrowed `*x` occurs here + | ^^^^^^^ `*x` is assigned to here but it was already borrowed LL | y | - returning this value requires that `*x` is borrowed for `'1` LL | } diff --git a/tests/ui/async-await/issue-75785-confusing-named-region.stderr b/tests/ui/async-await/issue-75785-confusing-named-region.stderr index 3b731d9c60a6a..b69033a0eda0b 100644 --- a/tests/ui/async-await/issue-75785-confusing-named-region.stderr +++ b/tests/ui/async-await/issue-75785-confusing-named-region.stderr @@ -4,9 +4,9 @@ error[E0506]: cannot assign to `*x` because it is borrowed LL | pub async fn async_fn(x: &mut i32) -> (&i32, &i32) { | - let's call the lifetime of this reference `'1` LL | let y = &*x; - | --- borrow of `*x` occurs here + | --- `*x` is borrowed here LL | *x += 1; - | ^^^^^^^ assignment to borrowed `*x` occurs here + | ^^^^^^^ `*x` is assigned to here but it was already borrowed LL | (&32, y) | -------- returning this value requires that `*x` is borrowed for `'1` diff --git a/tests/ui/async-await/multiple-lifetimes/ret-ref.stderr b/tests/ui/async-await/multiple-lifetimes/ret-ref.stderr index d86e84033b8cd..a599ac1d92f83 100644 --- a/tests/ui/async-await/multiple-lifetimes/ret-ref.stderr +++ b/tests/ui/async-await/multiple-lifetimes/ret-ref.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `a` because it is borrowed --> $DIR/ret-ref.rs:16:5 | LL | let future = multiple_named_lifetimes(&a, &b); - | -- borrow of `a` occurs here + | -- `a` is borrowed here LL | a += 1; - | ^^^^^^ assignment to borrowed `a` occurs here + | ^^^^^^ `a` is assigned to here but it was already borrowed LL | b += 1; LL | let p = future.await; | ------ borrow later used here @@ -13,10 +13,10 @@ error[E0506]: cannot assign to `b` because it is borrowed --> $DIR/ret-ref.rs:17:5 | LL | let future = multiple_named_lifetimes(&a, &b); - | -- borrow of `b` occurs here + | -- `b` is borrowed here LL | a += 1; LL | b += 1; - | ^^^^^^ assignment to borrowed `b` occurs here + | ^^^^^^ `b` is assigned to here but it was already borrowed LL | let p = future.await; | ------ borrow later used here @@ -24,10 +24,10 @@ error[E0506]: cannot assign to `a` because it is borrowed --> $DIR/ret-ref.rs:28:5 | LL | let future = multiple_named_lifetimes(&a, &b); - | -- borrow of `a` occurs here + | -- `a` is borrowed here LL | let p = future.await; LL | a += 1; - | ^^^^^^ assignment to borrowed `a` occurs here + | ^^^^^^ `a` is assigned to here but it was already borrowed LL | b += 1; LL | drop(p); | - borrow later used here diff --git a/tests/ui/augmented-assignments.rs b/tests/ui/augmented-assignments.rs index 20c7fb3a98395..bd2435a78bf22 100644 --- a/tests/ui/augmented-assignments.rs +++ b/tests/ui/augmented-assignments.rs @@ -9,7 +9,7 @@ impl AddAssign for Int { } fn main() { - let mut x = Int(1); + let mut x = Int(1); //~ NOTE binding `x` declared here x //~^ NOTE borrow of `x` occurs here += diff --git a/tests/ui/augmented-assignments.stderr b/tests/ui/augmented-assignments.stderr index 2910c910d5524..d1096aea2794e 100644 --- a/tests/ui/augmented-assignments.stderr +++ b/tests/ui/augmented-assignments.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/augmented-assignments.rs:16:5 | +LL | let mut x = Int(1); + | ----- binding `x` declared here LL | x | - borrow of `x` occurs here ... diff --git a/tests/ui/binop/binop-move-semantics.stderr b/tests/ui/binop/binop-move-semantics.stderr index dae267da05d17..8645169b98ac9 100644 --- a/tests/ui/binop/binop-move-semantics.stderr +++ b/tests/ui/binop/binop-move-semantics.stderr @@ -41,6 +41,8 @@ LL | fn move_then_borrow + Clone + Copy>(x: T) { error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/binop-move-semantics.rs:21:5 | +LL | fn move_borrowed>(x: T, mut y: T) { + | - binding `x` declared here LL | let m = &x; | -- borrow of `x` occurs here ... @@ -53,6 +55,9 @@ LL | use_mut(n); use_imm(m); error[E0505]: cannot move out of `y` because it is borrowed --> $DIR/binop-move-semantics.rs:23:5 | +LL | fn move_borrowed>(x: T, mut y: T) { + | ----- binding `y` declared here +LL | let m = &x; LL | let n = &mut y; | ------ borrow of `y` occurs here ... diff --git a/tests/ui/borrowck/borrowck-anon-fields-variant.stderr b/tests/ui/borrowck/borrowck-anon-fields-variant.stderr index 98f6f00a7d48b..c1d668f74efb9 100644 --- a/tests/ui/borrowck/borrowck-anon-fields-variant.stderr +++ b/tests/ui/borrowck/borrowck-anon-fields-variant.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `y` because it was mutably borrowed --> $DIR/borrowck-anon-fields-variant.rs:16:19 | LL | Foo::Y(ref mut a, _) => a, - | --------- borrow of `y.0` occurs here + | --------- `y.0` is borrowed here ... LL | let b = match y { | ^ use of borrowed `y.0` @@ -14,7 +14,7 @@ error[E0503]: cannot use `y` because it was mutably borrowed --> $DIR/borrowck-anon-fields-variant.rs:34:19 | LL | Foo::Y(ref mut a, _) => a, - | --------- borrow of `y.0` occurs here + | --------- `y.0` is borrowed here ... LL | let b = match y { | ^ use of borrowed `y.0` diff --git a/tests/ui/borrowck/borrowck-assign-comp.stderr b/tests/ui/borrowck/borrowck-assign-comp.stderr index 2b7cef7b3253b..d35f2331a76f4 100644 --- a/tests/ui/borrowck/borrowck-assign-comp.stderr +++ b/tests/ui/borrowck/borrowck-assign-comp.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `p.x` because it is borrowed --> $DIR/borrowck-assign-comp.rs:10:5 | LL | let q = &p; - | -- borrow of `p.x` occurs here + | -- `p.x` is borrowed here ... LL | p.x = 5; - | ^^^^^^^ assignment to borrowed `p.x` occurs here + | ^^^^^^^ `p.x` is assigned to here but it was already borrowed LL | q.x; | --- borrow later used here @@ -13,9 +13,9 @@ error[E0506]: cannot assign to `p` because it is borrowed --> $DIR/borrowck-assign-comp.rs:20:5 | LL | let q = &p.y; - | ---- borrow of `p` occurs here + | ---- `p` is borrowed here LL | p = Point {x: 5, y: 7}; - | ^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `p` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^ `p` is assigned to here but it was already borrowed LL | p.x; // silence warning LL | *q; // stretch loan | -- borrow later used here @@ -24,9 +24,9 @@ error[E0506]: cannot assign to `p.y` because it is borrowed --> $DIR/borrowck-assign-comp.rs:31:5 | LL | let q = &p.y; - | ---- borrow of `p.y` occurs here + | ---- `p.y` is borrowed here LL | p.y = 5; - | ^^^^^^^ assignment to borrowed `p.y` occurs here + | ^^^^^^^ `p.y` is assigned to here but it was already borrowed LL | *q; | -- borrow later used here diff --git a/tests/ui/borrowck/borrowck-assign-to-andmut-in-borrowed-loc.stderr b/tests/ui/borrowck/borrowck-assign-to-andmut-in-borrowed-loc.stderr index 0b21d113f74ee..8c0a8efcc1828 100644 --- a/tests/ui/borrowck/borrowck-assign-to-andmut-in-borrowed-loc.stderr +++ b/tests/ui/borrowck/borrowck-assign-to-andmut-in-borrowed-loc.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `*y.pointer` because it was mutably borrowed --> $DIR/borrowck-assign-to-andmut-in-borrowed-loc.rs:18:9 | LL | let z = copy_borrowed_ptr(&mut y); - | ------ borrow of `y` occurs here + | ------ `y` is borrowed here LL | *y.pointer += 1; | ^^^^^^^^^^^^^^^ use of borrowed `y` ... @@ -13,9 +13,9 @@ error[E0506]: cannot assign to `*y.pointer` because it is borrowed --> $DIR/borrowck-assign-to-andmut-in-borrowed-loc.rs:18:9 | LL | let z = copy_borrowed_ptr(&mut y); - | ------ borrow of `*y.pointer` occurs here + | ------ `*y.pointer` is borrowed here LL | *y.pointer += 1; - | ^^^^^^^^^^^^^^^ assignment to borrowed `*y.pointer` occurs here + | ^^^^^^^^^^^^^^^ `*y.pointer` is assigned to here but it was already borrowed ... LL | *z.pointer += 1; | --------------- borrow later used here diff --git a/tests/ui/borrowck/borrowck-closures-mut-and-imm.stderr b/tests/ui/borrowck/borrowck-closures-mut-and-imm.stderr index fadcd11a592aa..8a7870e0c44af 100644 --- a/tests/ui/borrowck/borrowck-closures-mut-and-imm.stderr +++ b/tests/ui/borrowck/borrowck-closures-mut-and-imm.stderr @@ -49,9 +49,9 @@ error[E0506]: cannot assign to `x` because it is borrowed LL | let c2 = || x * 5; | -- - borrow occurs due to use in closure | | - | borrow of `x` occurs here + | `x` is borrowed here LL | x = 5; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | LL | drop(c2); | -- borrow later used here @@ -62,9 +62,9 @@ error[E0506]: cannot assign to `x` because it is borrowed LL | let c1 = || get(&x); | -- - borrow occurs due to use in closure | | - | borrow of `x` occurs here + | `x` is borrowed here LL | x = 5; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | LL | drop(c1); | -- borrow later used here @@ -75,9 +75,9 @@ error[E0506]: cannot assign to `*x` because it is borrowed LL | let c1 = || get(&*x); | -- -- borrow occurs due to use in closure | | - | borrow of `*x` occurs here + | `*x` is borrowed here LL | *x = 5; - | ^^^^^^ assignment to borrowed `*x` occurs here + | ^^^^^^ `*x` is assigned to here but it was already borrowed LL | LL | drop(c1); | -- borrow later used here @@ -88,9 +88,9 @@ error[E0506]: cannot assign to `*x.f` because it is borrowed LL | let c1 = || get(&*x.f); | -- ---- borrow occurs due to use in closure | | - | borrow of `*x.f` occurs here + | `*x.f` is borrowed here LL | *x.f = 5; - | ^^^^^^^^ assignment to borrowed `*x.f` occurs here + | ^^^^^^^^ `*x.f` is assigned to here but it was already borrowed LL | LL | drop(c1); | -- borrow later used here diff --git a/tests/ui/borrowck/borrowck-describe-lvalue.stderr b/tests/ui/borrowck/borrowck-describe-lvalue.stderr index 2c1b9c10d4660..cb29c9fdac3c6 100644 --- a/tests/ui/borrowck/borrowck-describe-lvalue.stderr +++ b/tests/ui/borrowck/borrowck-describe-lvalue.stderr @@ -45,7 +45,7 @@ error[E0503]: cannot use `f.x` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:37:9 | LL | let x = f.x(); - | ----- borrow of `f` occurs here + | ----- `f` is borrowed here LL | f.x; | ^^^ use of borrowed `f` LL | drop(x); @@ -55,7 +55,7 @@ error[E0503]: cannot use `g.0` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:44:9 | LL | let x = g.x(); - | ----- borrow of `g` occurs here + | ----- `g` is borrowed here LL | g.0; | ^^^ use of borrowed `g` LL | drop(x); @@ -65,7 +65,7 @@ error[E0503]: cannot use `h.0` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:51:9 | LL | let x = &mut h.0; - | -------- borrow of `h.0` occurs here + | -------- `h.0` is borrowed here LL | h.0; | ^^^ use of borrowed `h.0` LL | drop(x); @@ -75,7 +75,7 @@ error[E0503]: cannot use `e.0` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:59:20 | LL | let x = e.x(); - | ----- borrow of `e` occurs here + | ----- `e` is borrowed here LL | match e { LL | Baz::X(value) => value | ^^^^^ use of borrowed `e` @@ -87,7 +87,7 @@ error[E0503]: cannot use `u.a` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:67:9 | LL | let x = &mut u.a; - | -------- borrow of `u.a` occurs here + | -------- `u.a` is borrowed here LL | u.a; | ^^^ use of borrowed `u.a` LL | drop(x); @@ -97,7 +97,7 @@ error[E0503]: cannot use `f.x` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:74:9 | LL | let x = f.x(); - | ----- borrow of `*f` occurs here + | ----- `*f` is borrowed here LL | f.x; | ^^^ use of borrowed `*f` LL | drop(x); @@ -107,7 +107,7 @@ error[E0503]: cannot use `g.0` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:81:9 | LL | let x = g.x(); - | ----- borrow of `*g` occurs here + | ----- `*g` is borrowed here LL | g.0; | ^^^ use of borrowed `*g` LL | drop(x); @@ -117,7 +117,7 @@ error[E0503]: cannot use `h.0` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:88:9 | LL | let x = &mut h.0; - | -------- borrow of `h.0` occurs here + | -------- `h.0` is borrowed here LL | h.0; | ^^^ use of borrowed `h.0` LL | drop(x); @@ -127,7 +127,7 @@ error[E0503]: cannot use `e.0` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:96:20 | LL | let x = e.x(); - | ----- borrow of `*e` occurs here + | ----- `*e` is borrowed here LL | match *e { LL | Baz::X(value) => value | ^^^^^ use of borrowed `*e` @@ -139,7 +139,7 @@ error[E0503]: cannot use `u.a` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:105:9 | LL | let x = &mut u.a; - | -------- borrow of `u.a` occurs here + | -------- `u.a` is borrowed here LL | u.a; | ^^^ use of borrowed `u.a` LL | drop(x); @@ -149,7 +149,7 @@ error[E0503]: cannot use `v[..]` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:113:15 | LL | let x = &mut v; - | ------ borrow of `v` occurs here + | ------ `v` is borrowed here LL | match v { LL | &[x, _, .., _, _] => println!("{}", x), | ^ use of borrowed `v` @@ -161,7 +161,7 @@ error[E0503]: cannot use `v[..]` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:118:18 | LL | let x = &mut v; - | ------ borrow of `v` occurs here + | ------ `v` is borrowed here ... LL | &[_, x, .., _, _] => println!("{}", x), | ^ use of borrowed `v` @@ -173,7 +173,7 @@ error[E0503]: cannot use `v[..]` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:123:25 | LL | let x = &mut v; - | ------ borrow of `v` occurs here + | ------ `v` is borrowed here ... LL | &[_, _, .., x, _] => println!("{}", x), | ^ use of borrowed `v` @@ -185,7 +185,7 @@ error[E0503]: cannot use `v[..]` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:128:28 | LL | let x = &mut v; - | ------ borrow of `v` occurs here + | ------ `v` is borrowed here ... LL | &[_, _, .., _, x] => println!("{}", x), | ^ use of borrowed `v` @@ -197,7 +197,7 @@ error[E0503]: cannot use `v[..]` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:139:15 | LL | let x = &mut v; - | ------ borrow of `v` occurs here + | ------ `v` is borrowed here LL | match v { LL | &[x @ ..] => println!("{:?}", x), | ^ use of borrowed `v` @@ -209,7 +209,7 @@ error[E0503]: cannot use `v[..]` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:144:18 | LL | let x = &mut v; - | ------ borrow of `v` occurs here + | ------ `v` is borrowed here ... LL | &[_, x @ ..] => println!("{:?}", x), | ^ use of borrowed `v` @@ -221,7 +221,7 @@ error[E0503]: cannot use `v[..]` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:149:15 | LL | let x = &mut v; - | ------ borrow of `v` occurs here + | ------ `v` is borrowed here ... LL | &[x @ .., _] => println!("{:?}", x), | ^ use of borrowed `v` @@ -233,7 +233,7 @@ error[E0503]: cannot use `v[..]` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:154:18 | LL | let x = &mut v; - | ------ borrow of `v` occurs here + | ------ `v` is borrowed here ... LL | &[_, x @ .., _] => println!("{:?}", x), | ^ use of borrowed `v` @@ -245,7 +245,7 @@ error[E0503]: cannot use `e` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:166:15 | LL | let x = &mut e; - | ------ borrow of `e` occurs here + | ------ `e` is borrowed here LL | match e { | ^ use of borrowed `e` ... @@ -304,7 +304,7 @@ error[E0503]: cannot use `*v` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:232:9 | LL | let x = &mut v; - | ------ borrow of `v` occurs here + | ------ `v` is borrowed here LL | v[0].y; | ^^^^ use of borrowed `v` ... @@ -315,7 +315,7 @@ error[E0503]: cannot use `v[_].y` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:232:9 | LL | let x = &mut v; - | ------ borrow of `v` occurs here + | ------ `v` is borrowed here LL | v[0].y; | ^^^^^^ use of borrowed `v` ... diff --git a/tests/ui/borrowck/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.stderr b/tests/ui/borrowck/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.stderr index a66db05ccc5fc..1a20ec85fc00f 100644 --- a/tests/ui/borrowck/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.stderr +++ b/tests/ui/borrowck/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `_a` because it is borrowed --> $DIR/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.rs:6:9 | LL | let b = &mut _a; - | ------- borrow of `_a` occurs here + | ------- `_a` is borrowed here ... LL | _a = 4; - | ^^^^^^ assignment to borrowed `_a` occurs here + | ^^^^^^ `_a` is assigned to here but it was already borrowed ... LL | drop(b); | - borrow later used here diff --git a/tests/ui/borrowck/borrowck-issue-14498.stderr b/tests/ui/borrowck/borrowck-issue-14498.stderr index 42a55b7a854ba..374c5ee3ed27b 100644 --- a/tests/ui/borrowck/borrowck-issue-14498.stderr +++ b/tests/ui/borrowck/borrowck-issue-14498.stderr @@ -13,10 +13,10 @@ error[E0506]: cannot assign to `**y` because it is borrowed --> $DIR/borrowck-issue-14498.rs:25:5 | LL | let p = &y; - | -- borrow of `**y` occurs here + | -- `**y` is borrowed here LL | let q = &***p; LL | **y = 2; - | ^^^^^^^ assignment to borrowed `**y` occurs here + | ^^^^^^^ `**y` is assigned to here but it was already borrowed LL | drop(p); | - borrow later used here @@ -24,10 +24,10 @@ error[E0506]: cannot assign to `**y` because it is borrowed --> $DIR/borrowck-issue-14498.rs:35:5 | LL | let p = &y; - | -- borrow of `**y` occurs here + | -- `**y` is borrowed here LL | let q = &***p; LL | **y = 2; - | ^^^^^^^ assignment to borrowed `**y` occurs here + | ^^^^^^^ `**y` is assigned to here but it was already borrowed LL | drop(p); | - borrow later used here @@ -35,10 +35,10 @@ error[E0506]: cannot assign to `**y` because it is borrowed --> $DIR/borrowck-issue-14498.rs:45:5 | LL | let p = &y; - | -- borrow of `**y` occurs here + | -- `**y` is borrowed here LL | let q = &***p; LL | **y = 2; - | ^^^^^^^ assignment to borrowed `**y` occurs here + | ^^^^^^^ `**y` is assigned to here but it was already borrowed LL | drop(p); | - borrow later used here @@ -46,10 +46,10 @@ error[E0506]: cannot assign to `**y` because it is borrowed --> $DIR/borrowck-issue-14498.rs:55:5 | LL | let p = &y; - | -- borrow of `**y` occurs here + | -- `**y` is borrowed here LL | let q = &***p; LL | **y = 2; - | ^^^^^^^ assignment to borrowed `**y` occurs here + | ^^^^^^^ `**y` is assigned to here but it was already borrowed LL | drop(p); | - borrow later used here @@ -57,10 +57,10 @@ error[E0506]: cannot assign to `**y.a` because it is borrowed --> $DIR/borrowck-issue-14498.rs:65:5 | LL | let p = &y.a; - | ---- borrow of `**y.a` occurs here + | ---- `**y.a` is borrowed here LL | let q = &***p; LL | **y.a = 2; - | ^^^^^^^^^ assignment to borrowed `**y.a` occurs here + | ^^^^^^^^^ `**y.a` is assigned to here but it was already borrowed LL | drop(p); | - borrow later used here @@ -68,10 +68,10 @@ error[E0506]: cannot assign to `**y.a` because it is borrowed --> $DIR/borrowck-issue-14498.rs:75:5 | LL | let p = &y.a; - | ---- borrow of `**y.a` occurs here + | ---- `**y.a` is borrowed here LL | let q = &***p; LL | **y.a = 2; - | ^^^^^^^^^ assignment to borrowed `**y.a` occurs here + | ^^^^^^^^^ `**y.a` is assigned to here but it was already borrowed LL | drop(p); | - borrow later used here @@ -79,10 +79,10 @@ error[E0506]: cannot assign to `**y.a` because it is borrowed --> $DIR/borrowck-issue-14498.rs:85:5 | LL | let p = &y.a; - | ---- borrow of `**y.a` occurs here + | ---- `**y.a` is borrowed here LL | let q = &***p; LL | **y.a = 2; - | ^^^^^^^^^ assignment to borrowed `**y.a` occurs here + | ^^^^^^^^^ `**y.a` is assigned to here but it was already borrowed LL | drop(p); | - borrow later used here @@ -90,10 +90,10 @@ error[E0506]: cannot assign to `**y.a` because it is borrowed --> $DIR/borrowck-issue-14498.rs:95:5 | LL | let p = &y.a; - | ---- borrow of `**y.a` occurs here + | ---- `**y.a` is borrowed here LL | let q = &***p; LL | **y.a = 2; - | ^^^^^^^^^ assignment to borrowed `**y.a` occurs here + | ^^^^^^^^^ `**y.a` is assigned to here but it was already borrowed LL | drop(p); | - borrow later used here diff --git a/tests/ui/borrowck/borrowck-lend-flow-match.stderr b/tests/ui/borrowck/borrowck-lend-flow-match.stderr index 66f1cd9bd5664..6cdce7bee8897 100644 --- a/tests/ui/borrowck/borrowck-lend-flow-match.stderr +++ b/tests/ui/borrowck/borrowck-lend-flow-match.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/borrowck-lend-flow-match.rs:12:13 | LL | Some(ref r) => { - | ----- borrow of `x` occurs here + | ----- `x` is borrowed here LL | x = Some(1); - | ^^^^^^^^^^^ assignment to borrowed `x` occurs here + | ^^^^^^^^^^^ `x` is assigned to here but it was already borrowed LL | drop(r); | - borrow later used here diff --git a/tests/ui/borrowck/borrowck-loan-blocks-move-cc.stderr b/tests/ui/borrowck/borrowck-loan-blocks-move-cc.stderr index 3548da35b6139..6eabfff9054c4 100644 --- a/tests/ui/borrowck/borrowck-loan-blocks-move-cc.stderr +++ b/tests/ui/borrowck/borrowck-loan-blocks-move-cc.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `v` because it is borrowed --> $DIR/borrowck-loan-blocks-move-cc.rs:14:19 | +LL | let v: Box<_> = Box::new(3); + | - binding `v` declared here LL | let w = &v; | -- borrow of `v` occurs here LL | thread::spawn(move|| { @@ -15,6 +17,8 @@ LL | w.use_ref(); error[E0505]: cannot move out of `v` because it is borrowed --> $DIR/borrowck-loan-blocks-move-cc.rs:24:19 | +LL | let v: Box<_> = Box::new(3); + | - binding `v` declared here LL | let w = &v; | -- borrow of `v` occurs here LL | thread::spawn(move|| { diff --git a/tests/ui/borrowck/borrowck-loan-blocks-move.stderr b/tests/ui/borrowck/borrowck-loan-blocks-move.stderr index b5c6b101f765c..38e06fa018786 100644 --- a/tests/ui/borrowck/borrowck-loan-blocks-move.stderr +++ b/tests/ui/borrowck/borrowck-loan-blocks-move.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `v` because it is borrowed --> $DIR/borrowck-loan-blocks-move.rs:11:10 | +LL | let v = Box::new(3); + | - binding `v` declared here LL | let w = &v; | -- borrow of `v` occurs here LL | take(v); diff --git a/tests/ui/borrowck/borrowck-loan-of-static-data-issue-27616.stderr b/tests/ui/borrowck/borrowck-loan-of-static-data-issue-27616.stderr index 6994c837dfcbe..311369a260d76 100644 --- a/tests/ui/borrowck/borrowck-loan-of-static-data-issue-27616.stderr +++ b/tests/ui/borrowck/borrowck-loan-of-static-data-issue-27616.stderr @@ -2,12 +2,12 @@ error[E0506]: cannot assign to `*s` because it is borrowed --> $DIR/borrowck-loan-of-static-data-issue-27616.rs:16:5 | LL | let alias: &'static mut String = s; - | ------------------- - borrow of `*s` occurs here + | ------------------- - `*s` is borrowed here | | | type annotation requires that `*s` is borrowed for `'static` ... LL | *s = String::new(); - | ^^ assignment to borrowed `*s` occurs here + | ^^ `*s` is assigned to here but it was already borrowed error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-loan-rcvr-overloaded-op.stderr b/tests/ui/borrowck/borrowck-loan-rcvr-overloaded-op.stderr index 24cc4933ef1b0..f1640d3b7776f 100644 --- a/tests/ui/borrowck/borrowck-loan-rcvr-overloaded-op.stderr +++ b/tests/ui/borrowck/borrowck-loan-rcvr-overloaded-op.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `p` because it was mutably borrowed --> $DIR/borrowck-loan-rcvr-overloaded-op.rs:38:5 | LL | let q = &mut p; - | ------ borrow of `p` occurs here + | ------ `p` is borrowed here LL | LL | p + 3; | ^ use of borrowed `p` diff --git a/tests/ui/borrowck/borrowck-match-already-borrowed.stderr b/tests/ui/borrowck/borrowck-match-already-borrowed.stderr index 39047be9de670..e5c0ec960a4a7 100644 --- a/tests/ui/borrowck/borrowck-match-already-borrowed.stderr +++ b/tests/ui/borrowck/borrowck-match-already-borrowed.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `foo` because it was mutably borrowed --> $DIR/borrowck-match-already-borrowed.rs:9:19 | LL | let p = &mut foo; - | -------- borrow of `foo` occurs here + | -------- `foo` is borrowed here LL | let _ = match foo { | ^^^ use of borrowed `foo` ... @@ -13,7 +13,7 @@ error[E0503]: cannot use `foo.0` because it was mutably borrowed --> $DIR/borrowck-match-already-borrowed.rs:12:16 | LL | let p = &mut foo; - | -------- borrow of `foo` occurs here + | -------- `foo` is borrowed here ... LL | Foo::A(x) => x | ^ use of borrowed `foo` @@ -25,7 +25,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/borrowck-match-already-borrowed.rs:22:9 | LL | let r = &mut x; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | let _ = match x { LL | x => x + 1, | ^ use of borrowed `x` @@ -37,7 +37,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/borrowck-match-already-borrowed.rs:23:9 | LL | let r = &mut x; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here ... LL | y => y + 2, | ^ use of borrowed `x` diff --git a/tests/ui/borrowck/borrowck-move-by-capture.stderr b/tests/ui/borrowck/borrowck-move-by-capture.stderr index 8ddc48b2a99cd..6eaa1fa316932 100644 --- a/tests/ui/borrowck/borrowck-move-by-capture.stderr +++ b/tests/ui/borrowck/borrowck-move-by-capture.stderr @@ -10,7 +10,7 @@ LL | let _h = to_fn_once(move || -> isize { *bar }); | | | | | variable moved due to use in closure | | move occurs because `bar` has type `Box`, which does not implement the `Copy` trait - | move out of `bar` occurs here + | `bar` is moved here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-move-from-subpath-of-borrowed-path.stderr b/tests/ui/borrowck/borrowck-move-from-subpath-of-borrowed-path.stderr index f833abcc02acf..bd94f1a4299b8 100644 --- a/tests/ui/borrowck/borrowck-move-from-subpath-of-borrowed-path.stderr +++ b/tests/ui/borrowck/borrowck-move-from-subpath-of-borrowed-path.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `*a` because it is borrowed --> $DIR/borrowck-move-from-subpath-of-borrowed-path.rs:12:13 | +LL | let a: Box> = Box::new(Box::new(2)); + | - binding `a` declared here LL | let b = &a; | -- borrow of `a` occurs here LL | diff --git a/tests/ui/borrowck/borrowck-move-subcomponent.stderr b/tests/ui/borrowck/borrowck-move-subcomponent.stderr index 8c9083fcf1356..341146bd18fd9 100644 --- a/tests/ui/borrowck/borrowck-move-subcomponent.stderr +++ b/tests/ui/borrowck/borrowck-move-subcomponent.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `a.x` because it is borrowed --> $DIR/borrowck-move-subcomponent.rs:15:14 | +LL | let a : S = S { x : Box::new(1) }; + | - binding `a` declared here LL | let pb = &a; | -- borrow of `a` occurs here LL | let S { x: ax } = a; diff --git a/tests/ui/borrowck/borrowck-multiple-captures.stderr b/tests/ui/borrowck/borrowck-multiple-captures.stderr index f94cbc30db421..70abe7b346e1a 100644 --- a/tests/ui/borrowck/borrowck-multiple-captures.stderr +++ b/tests/ui/borrowck/borrowck-multiple-captures.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `x1` because it is borrowed --> $DIR/borrowck-multiple-captures.rs:12:19 | +LL | let x1: Box<_> = Box::new(1); + | -- binding `x1` declared here LL | let p1 = &x1; | --- borrow of `x1` occurs here ... @@ -16,6 +18,8 @@ LL | borrow(&*p1); error[E0505]: cannot move out of `x2` because it is borrowed --> $DIR/borrowck-multiple-captures.rs:12:19 | +LL | let x2: Box<_> = Box::new(2); + | -- binding `x2` declared here LL | let p2 = &x2; | --- borrow of `x2` occurs here LL | thread::spawn(move|| { @@ -77,6 +81,8 @@ LL | drop(x); error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/borrowck-multiple-captures.rs:38:19 | +LL | let x: Box<_> = Box::new(1); + | - binding `x` declared here LL | let p = &x; | -- borrow of `x` occurs here LL | thread::spawn(move|| { diff --git a/tests/ui/borrowck/borrowck-overloaded-index-and-overloaded-deref.stderr b/tests/ui/borrowck/borrowck-overloaded-index-and-overloaded-deref.stderr index 5d52e49191831..7f42becd21c2a 100644 --- a/tests/ui/borrowck/borrowck-overloaded-index-and-overloaded-deref.stderr +++ b/tests/ui/borrowck/borrowck-overloaded-index-and-overloaded-deref.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `v` because it is borrowed --> $DIR/borrowck-overloaded-index-and-overloaded-deref.rs:31:5 | LL | let i = &v[0].f; - | - borrow of `v` occurs here + | - `v` is borrowed here LL | v = MyVec { x: MyPtr { x: Foo { f: 23 } } }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `v` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `v` is assigned to here but it was already borrowed LL | LL | read(*i); | -- borrow later used here diff --git a/tests/ui/borrowck/borrowck-overloaded-index-autoderef.stderr b/tests/ui/borrowck/borrowck-overloaded-index-autoderef.stderr index 087f2ac799eeb..fb7af50bcb565 100644 --- a/tests/ui/borrowck/borrowck-overloaded-index-autoderef.stderr +++ b/tests/ui/borrowck/borrowck-overloaded-index-autoderef.stderr @@ -42,9 +42,9 @@ error[E0506]: cannot assign to `f.foo` because it is borrowed --> $DIR/borrowck-overloaded-index-autoderef.rs:71:5 | LL | let p = &f.foo[&s]; - | ----- borrow of `f.foo` occurs here + | ----- `f.foo` is borrowed here LL | f.foo = g; - | ^^^^^^^^^ assignment to borrowed `f.foo` occurs here + | ^^^^^^^^^ `f.foo` is assigned to here but it was already borrowed LL | p.use_ref(); | ----------- borrow later used here @@ -52,9 +52,9 @@ error[E0506]: cannot assign to `*f` because it is borrowed --> $DIR/borrowck-overloaded-index-autoderef.rs:77:5 | LL | let p = &f.foo[&s]; - | ----- borrow of `*f` occurs here + | ----- `*f` is borrowed here LL | *f = g; - | ^^^^^^ assignment to borrowed `*f` occurs here + | ^^^^^^ `*f` is assigned to here but it was already borrowed LL | p.use_ref(); | ----------- borrow later used here @@ -62,9 +62,9 @@ error[E0506]: cannot assign to `f.foo` because it is borrowed --> $DIR/borrowck-overloaded-index-autoderef.rs:83:5 | LL | let p = &mut f.foo[&s]; - | ----- borrow of `f.foo` occurs here + | ----- `f.foo` is borrowed here LL | f.foo = g; - | ^^^^^^^^^ assignment to borrowed `f.foo` occurs here + | ^^^^^^^^^ `f.foo` is assigned to here but it was already borrowed LL | p.use_mut(); | ----------- borrow later used here @@ -72,9 +72,9 @@ error[E0506]: cannot assign to `*f` because it is borrowed --> $DIR/borrowck-overloaded-index-autoderef.rs:89:5 | LL | let p = &mut f.foo[&s]; - | ----- borrow of `*f` occurs here + | ----- `*f` is borrowed here LL | *f = g; - | ^^^^^^ assignment to borrowed `*f` occurs here + | ^^^^^^ `*f` is assigned to here but it was already borrowed LL | p.use_mut(); | ----------- borrow later used here diff --git a/tests/ui/borrowck/borrowck-overloaded-index-move-index.stderr b/tests/ui/borrowck/borrowck-overloaded-index-move-index.stderr index fb0e274c2919a..7f8cc74a7157a 100644 --- a/tests/ui/borrowck/borrowck-overloaded-index-move-index.stderr +++ b/tests/ui/borrowck/borrowck-overloaded-index-move-index.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `s` because it is borrowed --> $DIR/borrowck-overloaded-index-move-index.rs:50:22 | +LL | let mut s = "hello".to_string(); + | ----- binding `s` declared here LL | let rs = &mut s; | ------ borrow of `s` occurs here LL | @@ -13,6 +15,8 @@ LL | use_mut(rs); error[E0505]: cannot move out of `s` because it is borrowed --> $DIR/borrowck-overloaded-index-move-index.rs:53:7 | +LL | let mut s = "hello".to_string(); + | ----- binding `s` declared here LL | let rs = &mut s; | ------ borrow of `s` occurs here ... diff --git a/tests/ui/borrowck/borrowck-pat-reassign-binding.stderr b/tests/ui/borrowck/borrowck-pat-reassign-binding.stderr index 9e65ccf5a1913..b86a8693881a9 100644 --- a/tests/ui/borrowck/borrowck-pat-reassign-binding.stderr +++ b/tests/ui/borrowck/borrowck-pat-reassign-binding.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/borrowck-pat-reassign-binding.rs:10:11 | LL | Some(ref i) => { - | ----- borrow of `x` occurs here + | ----- `x` is borrowed here LL | // But on this branch, `i` is an outstanding borrow LL | x = Some(*i+1); - | ^^^^^^^^^^^^^^ assignment to borrowed `x` occurs here + | ^^^^^^^^^^^^^^ `x` is assigned to here but it was already borrowed LL | drop(i); | - borrow later used here diff --git a/tests/ui/borrowck/borrowck-union-borrow-nested.stderr b/tests/ui/borrowck/borrowck-union-borrow-nested.stderr index 4bd7d54cffeda..a87a14e7cabd8 100644 --- a/tests/ui/borrowck/borrowck-union-borrow-nested.stderr +++ b/tests/ui/borrowck/borrowck-union-borrow-nested.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `u.c` because it was mutably borrowed --> $DIR/borrowck-union-borrow-nested.rs:24:21 | LL | let ra = &mut u.s.a; - | ---------- borrow of `u.s.a` occurs here + | ---------- `u.s.a` is borrowed here LL | let b = u.c; | ^^^ use of borrowed `u.s.a` LL | ra.use_mut(); diff --git a/tests/ui/borrowck/borrowck-union-borrow.stderr b/tests/ui/borrowck/borrowck-union-borrow.stderr index 090c7b6b51a31..11a28f6744b70 100644 --- a/tests/ui/borrowck/borrowck-union-borrow.stderr +++ b/tests/ui/borrowck/borrowck-union-borrow.stderr @@ -12,9 +12,9 @@ error[E0506]: cannot assign to `u.a` because it is borrowed --> $DIR/borrowck-union-borrow.rs:28:13 | LL | let ra = &u.a; - | ---- borrow of `u.a` occurs here + | ---- `u.a` is borrowed here LL | u.a = 1; - | ^^^^^^^ assignment to borrowed `u.a` occurs here + | ^^^^^^^ `u.a` is assigned to here but it was already borrowed LL | drop(ra); | -- borrow later used here @@ -34,9 +34,9 @@ error[E0506]: cannot assign to `u.b` because it is borrowed --> $DIR/borrowck-union-borrow.rs:49:13 | LL | let ra = &u.a; - | ---- borrow of `u.b` occurs here + | ---- `u.b` is borrowed here LL | u.b = 1; - | ^^^^^^^ assignment to borrowed `u.b` occurs here + | ^^^^^^^ `u.b` is assigned to here but it was already borrowed LL | drop(ra); | -- borrow later used here @@ -54,7 +54,7 @@ error[E0503]: cannot use `u.a` because it was mutably borrowed --> $DIR/borrowck-union-borrow.rs:60:21 | LL | let ra = &mut u.a; - | -------- borrow of `u.a` occurs here + | -------- `u.a` is borrowed here LL | let a = u.a; | ^^^ use of borrowed `u.a` LL | drop(ra); @@ -74,9 +74,9 @@ error[E0506]: cannot assign to `u.a` because it is borrowed --> $DIR/borrowck-union-borrow.rs:70:13 | LL | let rma = &mut u.a; - | -------- borrow of `u.a` occurs here + | -------- `u.a` is borrowed here LL | u.a = 1; - | ^^^^^^^ assignment to borrowed `u.a` occurs here + | ^^^^^^^ `u.a` is assigned to here but it was already borrowed LL | drop(rma); | --- borrow later used here @@ -96,7 +96,7 @@ error[E0503]: cannot use `u.b` because it was mutably borrowed --> $DIR/borrowck-union-borrow.rs:81:21 | LL | let ra = &mut u.a; - | -------- borrow of `u.a` occurs here + | -------- `u.a` is borrowed here LL | let b = u.b; | ^^^ use of borrowed `u.a` LL | @@ -119,9 +119,9 @@ error[E0506]: cannot assign to `u.b` because it is borrowed --> $DIR/borrowck-union-borrow.rs:92:13 | LL | let rma = &mut u.a; - | -------- borrow of `u.b` occurs here + | -------- `u.b` is borrowed here LL | u.b = 1; - | ^^^^^^^ assignment to borrowed `u.b` occurs here + | ^^^^^^^ `u.b` is assigned to here but it was already borrowed LL | drop(rma); | --- borrow later used here diff --git a/tests/ui/borrowck/borrowck-use-mut-borrow.stderr b/tests/ui/borrowck/borrowck-use-mut-borrow.stderr index 91d69c51e8180..4d300ae3c527b 100644 --- a/tests/ui/borrowck/borrowck-use-mut-borrow.stderr +++ b/tests/ui/borrowck/borrowck-use-mut-borrow.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/borrowck-use-mut-borrow.rs:11:10 | LL | let p = &mut x; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | drop(x); | ^ use of borrowed `x` LL | *p = 2; @@ -12,7 +12,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/borrowck-use-mut-borrow.rs:18:10 | LL | let p = &mut x.a; - | -------- borrow of `x.a` occurs here + | -------- `x.a` is borrowed here LL | drop(x); | ^ use of borrowed `x.a` LL | *p = 3; @@ -22,7 +22,7 @@ error[E0503]: cannot use `x.a` because it was mutably borrowed --> $DIR/borrowck-use-mut-borrow.rs:25:10 | LL | let p = &mut x; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | drop(x.a); | ^^^ use of borrowed `x` LL | p.a = 3; @@ -32,7 +32,7 @@ error[E0503]: cannot use `x.a` because it was mutably borrowed --> $DIR/borrowck-use-mut-borrow.rs:32:10 | LL | let p = &mut x.a; - | -------- borrow of `x.a` occurs here + | -------- `x.a` is borrowed here LL | drop(x.a); | ^^^ use of borrowed `x.a` LL | *p = 3; @@ -42,7 +42,7 @@ error[E0503]: cannot use `x.a` because it was mutably borrowed --> $DIR/borrowck-use-mut-borrow.rs:39:13 | LL | let p = &mut x; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | let y = A { b: 3, .. x }; | ^^^^^^^^^^^^^^^^ use of borrowed `x` LL | drop(y); @@ -53,7 +53,7 @@ error[E0503]: cannot use `x.a` because it was mutably borrowed --> $DIR/borrowck-use-mut-borrow.rs:47:13 | LL | let p = &mut x.a; - | -------- borrow of `x.a` occurs here + | -------- `x.a` is borrowed here LL | let y = A { b: 3, .. x }; | ^^^^^^^^^^^^^^^^ use of borrowed `x.a` LL | drop(y); @@ -64,7 +64,7 @@ error[E0503]: cannot use `*x` because it was mutably borrowed --> $DIR/borrowck-use-mut-borrow.rs:55:10 | LL | let p = &mut x; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | drop(*x); | ^^ use of borrowed `x` LL | **p = 2; @@ -74,7 +74,7 @@ error[E0503]: cannot use `*x.b` because it was mutably borrowed --> $DIR/borrowck-use-mut-borrow.rs:62:10 | LL | let p = &mut x; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | drop(*x.b); | ^^^^ use of borrowed `x` LL | p.a = 3; @@ -84,7 +84,7 @@ error[E0503]: cannot use `*x.b` because it was mutably borrowed --> $DIR/borrowck-use-mut-borrow.rs:69:10 | LL | let p = &mut x.b; - | -------- borrow of `x.b` occurs here + | -------- `x.b` is borrowed here LL | drop(*x.b); | ^^^^ use of borrowed `x.b` LL | **p = 3; diff --git a/tests/ui/borrowck/borrowck-vec-pattern-move-tail.stderr b/tests/ui/borrowck/borrowck-vec-pattern-move-tail.stderr index 0ac7df944d781..494d8c351a152 100644 --- a/tests/ui/borrowck/borrowck-vec-pattern-move-tail.stderr +++ b/tests/ui/borrowck/borrowck-vec-pattern-move-tail.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `a[_]` because it is borrowed --> $DIR/borrowck-vec-pattern-move-tail.rs:8:5 | LL | [1, 2, ref tail @ ..] => tail, - | -------- borrow of `a[_]` occurs here + | -------- `a[_]` is borrowed here ... LL | a[2] = 0; - | ^^^^^^^^ assignment to borrowed `a[_]` occurs here + | ^^^^^^^^ `a[_]` is assigned to here but it was already borrowed LL | println!("t[0]: {}", t[0]); | ---- borrow later used here diff --git a/tests/ui/borrowck/borrowck-vec-pattern-nesting.rs b/tests/ui/borrowck/borrowck-vec-pattern-nesting.rs index 0e9284a2cadd2..1bda7a4971375 100644 --- a/tests/ui/borrowck/borrowck-vec-pattern-nesting.rs +++ b/tests/ui/borrowck/borrowck-vec-pattern-nesting.rs @@ -5,9 +5,9 @@ fn a() { let mut vec = [Box::new(1), Box::new(2), Box::new(3)]; match vec { [box ref _a, _, _] => { - //~^ NOTE borrow of `vec[_]` occurs here + //~^ NOTE `vec[_]` is borrowed here vec[0] = Box::new(4); //~ ERROR cannot assign - //~^ NOTE assignment to borrowed `vec[_]` occurs here + //~^ NOTE `vec[_]` is assigned to here _a.use_ref(); //~^ NOTE borrow later used here } @@ -19,9 +19,9 @@ fn b() { let vec: &mut [Box] = &mut vec; match vec { &mut [ref _b @ ..] => { - //~^ borrow of `vec[_]` occurs here + //~^ `vec[_]` is borrowed here vec[0] = Box::new(4); //~ ERROR cannot assign - //~^ NOTE assignment to borrowed `vec[_]` occurs here + //~^ NOTE `vec[_]` is assigned to here _b.use_ref(); //~^ NOTE borrow later used here } diff --git a/tests/ui/borrowck/borrowck-vec-pattern-nesting.stderr b/tests/ui/borrowck/borrowck-vec-pattern-nesting.stderr index 0dc5e64e4ff30..70b9e4f4433b3 100644 --- a/tests/ui/borrowck/borrowck-vec-pattern-nesting.stderr +++ b/tests/ui/borrowck/borrowck-vec-pattern-nesting.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `vec[_]` because it is borrowed --> $DIR/borrowck-vec-pattern-nesting.rs:9:13 | LL | [box ref _a, _, _] => { - | ------ borrow of `vec[_]` occurs here + | ------ `vec[_]` is borrowed here LL | LL | vec[0] = Box::new(4); - | ^^^^^^ assignment to borrowed `vec[_]` occurs here + | ^^^^^^ `vec[_]` is assigned to here but it was already borrowed LL | LL | _a.use_ref(); | ------------ borrow later used here @@ -14,10 +14,10 @@ error[E0506]: cannot assign to `vec[_]` because it is borrowed --> $DIR/borrowck-vec-pattern-nesting.rs:23:13 | LL | &mut [ref _b @ ..] => { - | ------ borrow of `vec[_]` occurs here + | ------ `vec[_]` is borrowed here LL | LL | vec[0] = Box::new(4); - | ^^^^^^ assignment to borrowed `vec[_]` occurs here + | ^^^^^^ `vec[_]` is assigned to here but it was already borrowed LL | LL | _b.use_ref(); | ------------ borrow later used here diff --git a/tests/ui/borrowck/issue-25793.stderr b/tests/ui/borrowck/issue-25793.stderr index da3412f112d7a..27dab53e48fd5 100644 --- a/tests/ui/borrowck/issue-25793.stderr +++ b/tests/ui/borrowck/issue-25793.stderr @@ -5,7 +5,7 @@ LL | $this.width.unwrap() | ^^^^^^^^^^^ use of borrowed `*self` ... LL | let r = &mut *self; - | ---------- borrow of `*self` occurs here + | ---------- `*self` is borrowed here LL | r.get_size(width!(self)) | -------- ------------ in this macro invocation | | diff --git a/tests/ui/borrowck/issue-52713-bug.stderr b/tests/ui/borrowck/issue-52713-bug.stderr index 4abb6fb2c7186..3f7715645e60c 100644 --- a/tests/ui/borrowck/issue-52713-bug.stderr +++ b/tests/ui/borrowck/issue-52713-bug.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/issue-52713-bug.rs:12:5 | LL | let y = &x; - | -- borrow of `x` occurs here + | -- `x` is borrowed here ... LL | x += 1; - | ^^^^^^ assignment to borrowed `x` occurs here + | ^^^^^^ `x` is assigned to here but it was already borrowed LL | println!("{}", y); | - borrow later used here diff --git a/tests/ui/borrowck/issue-58776-borrowck-scans-children.stderr b/tests/ui/borrowck/issue-58776-borrowck-scans-children.stderr index 57803247ba8d0..0870b4237690e 100644 --- a/tests/ui/borrowck/issue-58776-borrowck-scans-children.stderr +++ b/tests/ui/borrowck/issue-58776-borrowck-scans-children.stderr @@ -4,10 +4,10 @@ error[E0506]: cannot assign to `greeting` because it is borrowed LL | let res = (|| (|| &greeting)())(); | -- -------- borrow occurs due to use in closure | | - | borrow of `greeting` occurs here + | `greeting` is borrowed here LL | LL | greeting = "DEALLOCATED".to_string(); - | ^^^^^^^^ assignment to borrowed `greeting` occurs here + | ^^^^^^^^ `greeting` is assigned to here but it was already borrowed ... LL | println!("thread result: {:?}", res); | --- borrow later used here diff --git a/tests/ui/borrowck/issue-81365-1.stderr b/tests/ui/borrowck/issue-81365-1.stderr index d79394834dcad..0d803b0427ace 100644 --- a/tests/ui/borrowck/issue-81365-1.stderr +++ b/tests/ui/borrowck/issue-81365-1.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `self.container_field` because it is borrowed --> $DIR/issue-81365-1.rs:21:9 | LL | let first = &self.target_field; - | ---- borrow of `self.container_field` occurs here + | ---- `self.container_field` is borrowed here LL | self.container_field = true; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.container_field` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.container_field` is assigned to here but it was already borrowed LL | first; | ----- borrow later used here | diff --git a/tests/ui/borrowck/issue-81365-10.stderr b/tests/ui/borrowck/issue-81365-10.stderr index 27123ef2be1ef..d0986e9f922e6 100644 --- a/tests/ui/borrowck/issue-81365-10.stderr +++ b/tests/ui/borrowck/issue-81365-10.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `self.container_field` because it is borrowed --> $DIR/issue-81365-10.rs:21:9 | LL | let first = &self.deref().target_field; - | ------------ borrow of `self.container_field` occurs here + | ------------ `self.container_field` is borrowed here LL | self.container_field = true; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.container_field` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.container_field` is assigned to here but it was already borrowed LL | first; | ----- borrow later used here diff --git a/tests/ui/borrowck/issue-81365-11.stderr b/tests/ui/borrowck/issue-81365-11.stderr index 0770c136632db..5f7e86f11dcd1 100644 --- a/tests/ui/borrowck/issue-81365-11.stderr +++ b/tests/ui/borrowck/issue-81365-11.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `self.container_field` because it is borrowed --> $DIR/issue-81365-11.rs:27:9 | LL | let first = &mut self.target_field; - | ---- borrow of `self.container_field` occurs here + | ---- `self.container_field` is borrowed here LL | self.container_field = true; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.container_field` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.container_field` is assigned to here but it was already borrowed LL | first; | ----- borrow later used here diff --git a/tests/ui/borrowck/issue-81365-2.stderr b/tests/ui/borrowck/issue-81365-2.stderr index 764eaaa7cc7b4..d9aeaf15f2002 100644 --- a/tests/ui/borrowck/issue-81365-2.stderr +++ b/tests/ui/borrowck/issue-81365-2.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `self.container.container_field` because it is bo --> $DIR/issue-81365-2.rs:25:9 | LL | let first = &self.container.target_field; - | -------------- borrow of `self.container.container_field` occurs here + | -------------- `self.container.container_field` is borrowed here LL | self.container.container_field = true; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.container.container_field` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.container.container_field` is assigned to here but it was already borrowed LL | first; | ----- borrow later used here | diff --git a/tests/ui/borrowck/issue-81365-3.stderr b/tests/ui/borrowck/issue-81365-3.stderr index 9447174fd21ea..0c0d1994baff2 100644 --- a/tests/ui/borrowck/issue-81365-3.stderr +++ b/tests/ui/borrowck/issue-81365-3.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `self.container.container_field` because it is bo --> $DIR/issue-81365-3.rs:32:9 | LL | let first = &self.target_field; - | ---- borrow of `self.container.container_field` occurs here + | ---- `self.container.container_field` is borrowed here LL | self.container.container_field = true; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.container.container_field` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.container.container_field` is assigned to here but it was already borrowed LL | first; | ----- borrow later used here | diff --git a/tests/ui/borrowck/issue-81365-4.stderr b/tests/ui/borrowck/issue-81365-4.stderr index 0ab3fa92706b0..98093daa94520 100644 --- a/tests/ui/borrowck/issue-81365-4.stderr +++ b/tests/ui/borrowck/issue-81365-4.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `self.outer_field` because it is borrowed --> $DIR/issue-81365-4.rs:33:9 | LL | let first = &self.target_field; - | ---- borrow of `self.outer_field` occurs here + | ---- `self.outer_field` is borrowed here LL | self.outer_field = true; - | ^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.outer_field` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^ `self.outer_field` is assigned to here but it was already borrowed LL | first; | ----- borrow later used here | diff --git a/tests/ui/borrowck/issue-81365-5.stderr b/tests/ui/borrowck/issue-81365-5.stderr index 20ff229ffe7dd..c00e48288ba07 100644 --- a/tests/ui/borrowck/issue-81365-5.stderr +++ b/tests/ui/borrowck/issue-81365-5.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `self.container_field` because it is borrowed --> $DIR/issue-81365-5.rs:28:9 | LL | let first = self.get(); - | ---------- borrow of `self.container_field` occurs here + | ---------- `self.container_field` is borrowed here LL | self.container_field = true; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.container_field` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.container_field` is assigned to here but it was already borrowed LL | first; | ----- borrow later used here | diff --git a/tests/ui/borrowck/issue-81365-6.stderr b/tests/ui/borrowck/issue-81365-6.stderr index 575aed73b4663..e61dc95ecc8fa 100644 --- a/tests/ui/borrowck/issue-81365-6.stderr +++ b/tests/ui/borrowck/issue-81365-6.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `self.container_field` because it is borrowed --> $DIR/issue-81365-6.rs:18:9 | LL | let first = &self[0]; - | ---- borrow of `self.container_field` occurs here + | ---- `self.container_field` is borrowed here LL | self.container_field = true; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.container_field` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.container_field` is assigned to here but it was already borrowed LL | first; | ----- borrow later used here | diff --git a/tests/ui/borrowck/issue-81365-7.stderr b/tests/ui/borrowck/issue-81365-7.stderr index 52d2d9e75a951..0565127e3875b 100644 --- a/tests/ui/borrowck/issue-81365-7.stderr +++ b/tests/ui/borrowck/issue-81365-7.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `c.container_field` because it is borrowed --> $DIR/issue-81365-7.rs:20:5 | LL | let first = &c.target_field; - | - borrow of `c.container_field` occurs here + | - `c.container_field` is borrowed here LL | c.container_field = true; - | ^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `c.container_field` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^ `c.container_field` is assigned to here but it was already borrowed LL | first; | ----- borrow later used here | diff --git a/tests/ui/borrowck/issue-81365-8.stderr b/tests/ui/borrowck/issue-81365-8.stderr index fd83e10a295dc..0ca732ff2ae43 100644 --- a/tests/ui/borrowck/issue-81365-8.stderr +++ b/tests/ui/borrowck/issue-81365-8.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `self.container_field` because it is borrowed --> $DIR/issue-81365-8.rs:21:9 | LL | let first = &(*self).target_field; - | ------- borrow of `self.container_field` occurs here + | ------- `self.container_field` is borrowed here LL | self.container_field = true; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.container_field` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.container_field` is assigned to here but it was already borrowed LL | first; | ----- borrow later used here | diff --git a/tests/ui/borrowck/issue-81365-9.stderr b/tests/ui/borrowck/issue-81365-9.stderr index c7d48214fd4a8..4d305268a0b33 100644 --- a/tests/ui/borrowck/issue-81365-9.stderr +++ b/tests/ui/borrowck/issue-81365-9.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `self.container_field` because it is borrowed --> $DIR/issue-81365-9.rs:21:9 | LL | let first = &Deref::deref(self).target_field; - | ---- borrow of `self.container_field` occurs here + | ---- `self.container_field` is borrowed here LL | self.container_field = true; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.container_field` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.container_field` is assigned to here but it was already borrowed LL | first; | ----- borrow later used here diff --git a/tests/ui/borrowck/two-phase-allow-access-during-reservation.nll_target.stderr b/tests/ui/borrowck/two-phase-allow-access-during-reservation.nll_target.stderr index a57ceb8473945..1356c80493cdb 100644 --- a/tests/ui/borrowck/two-phase-allow-access-during-reservation.nll_target.stderr +++ b/tests/ui/borrowck/two-phase-allow-access-during-reservation.nll_target.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `i` because it was mutably borrowed --> $DIR/two-phase-allow-access-during-reservation.rs:26:19 | LL | /*1*/ let p = &mut i; // (reservation of `i` starts here) - | ------ borrow of `i` occurs here + | ------ `i` is borrowed here LL | LL | /*2*/ let j = i; // OK: `i` is only reserved here | ^ use of borrowed `i` @@ -14,7 +14,7 @@ error[E0503]: cannot use `i` because it was mutably borrowed --> $DIR/two-phase-allow-access-during-reservation.rs:31:19 | LL | /*1*/ let p = &mut i; // (reservation of `i` starts here) - | ------ borrow of `i` occurs here + | ------ `i` is borrowed here ... LL | /*4*/ let k = i; | ^ use of borrowed `i` diff --git a/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr b/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr index 5a240d90011e4..e75094d4f1309 100644 --- a/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr +++ b/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `self.cx` because it was mutably borrowed --> $DIR/two-phase-surprise-no-conflict.rs:21:23 | LL | let _mut_borrow = &mut *self; - | ---------- borrow of `*self` occurs here + | ---------- `*self` is borrowed here LL | let _access = self.cx; | ^^^^^^^ use of borrowed `*self` LL | diff --git a/tests/ui/btreemap/btreemap_dropck.stderr b/tests/ui/btreemap/btreemap_dropck.stderr index e953e7ae82bb8..d405e465aaeea 100644 --- a/tests/ui/btreemap/btreemap_dropck.stderr +++ b/tests/ui/btreemap/btreemap_dropck.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `s` because it is borrowed --> $DIR/btreemap_dropck.rs:15:10 | +LL | let s = String::from("Hello World!"); + | - binding `s` declared here LL | let _map = BTreeMap::from_iter([((), PrintOnDrop(&s))]); | -- borrow of `s` occurs here LL | drop(s); diff --git a/tests/ui/c-variadic/variadic-ffi-4.stderr b/tests/ui/c-variadic/variadic-ffi-4.stderr index 6f8e53298ace2..c9d90d73dea31 100644 --- a/tests/ui/c-variadic/variadic-ffi-4.stderr +++ b/tests/ui/c-variadic/variadic-ffi-4.stderr @@ -107,7 +107,9 @@ error[E0597]: `ap1` does not live long enough --> $DIR/variadic-ffi-4.rs:28:11 | LL | pub unsafe extern "C" fn no_escape4(_: usize, mut ap0: &mut VaListImpl, mut ap1: ...) { - | - let's call the lifetime of this reference `'3` + | - ------- binding `ap1` declared here + | | + | let's call the lifetime of this reference `'3` LL | ap0 = &mut ap1; | ------^^^^^^^^ | | | diff --git a/tests/ui/closures/2229_closure_analysis/diagnostics/arrays.stderr b/tests/ui/closures/2229_closure_analysis/diagnostics/arrays.stderr index 4f41060dc9842..9e5200ef34b54 100644 --- a/tests/ui/closures/2229_closure_analysis/diagnostics/arrays.stderr +++ b/tests/ui/closures/2229_closure_analysis/diagnostics/arrays.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `arr` because it was mutably borrowed --> $DIR/arrays.rs:14:5 | LL | let mut c = || { - | -- borrow of `arr` occurs here + | -- `arr` is borrowed here LL | arr[0] += 10; | --- borrow occurs due to use of `arr` in closure ... @@ -16,7 +16,7 @@ error[E0503]: cannot use `arr[_]` because it was mutably borrowed --> $DIR/arrays.rs:14:5 | LL | let mut c = || { - | -- borrow of `arr` occurs here + | -- `arr` is borrowed here LL | arr[0] += 10; | --- borrow occurs due to use of `arr` in closure ... @@ -30,12 +30,12 @@ error[E0506]: cannot assign to `arr[_]` because it is borrowed --> $DIR/arrays.rs:29:5 | LL | let c = || { - | -- borrow of `arr[_]` occurs here + | -- `arr[_]` is borrowed here LL | println!("{:#?}", &arr[3..4]); | --- borrow occurs due to use in closure ... LL | arr[1] += 10; - | ^^^^^^^^^^^^ assignment to borrowed `arr[_]` occurs here + | ^^^^^^^^^^^^ `arr[_]` is assigned to here but it was already borrowed LL | LL | c(); | - borrow later used here @@ -44,12 +44,12 @@ error[E0506]: cannot assign to `arr[_]` because it is borrowed --> $DIR/arrays.rs:43:5 | LL | let c = || { - | -- borrow of `arr[_]` occurs here + | -- `arr[_]` is borrowed here LL | println!("{}", arr[3]); | --- borrow occurs due to use in closure ... LL | arr[1] += 10; - | ^^^^^^^^^^^^ assignment to borrowed `arr[_]` occurs here + | ^^^^^^^^^^^^ `arr[_]` is assigned to here but it was already borrowed LL | LL | c(); | - borrow later used here @@ -58,7 +58,7 @@ error[E0503]: cannot use `arr` because it was mutably borrowed --> $DIR/arrays.rs:57:20 | LL | let mut c = || { - | -- borrow of `arr` occurs here + | -- `arr` is borrowed here LL | arr[1] += 10; | --- borrow occurs due to use of `arr` in closure ... diff --git a/tests/ui/closures/2229_closure_analysis/diagnostics/box.stderr b/tests/ui/closures/2229_closure_analysis/diagnostics/box.stderr index f8b178752351a..2e3259e640596 100644 --- a/tests/ui/closures/2229_closure_analysis/diagnostics/box.stderr +++ b/tests/ui/closures/2229_closure_analysis/diagnostics/box.stderr @@ -2,12 +2,12 @@ error[E0506]: cannot assign to `e.0.0.m.x` because it is borrowed --> $DIR/box.rs:21:5 | LL | let mut c = || { - | -- borrow of `e.0.0.m.x` occurs here + | -- `e.0.0.m.x` is borrowed here LL | e.0.0.m.x = format!("not-x"); | --------- borrow occurs due to use in closure ... LL | e.0.0.m.x = format!("not-x"); - | ^^^^^^^^^ assignment to borrowed `e.0.0.m.x` occurs here + | ^^^^^^^^^ `e.0.0.m.x` is assigned to here but it was already borrowed LL | LL | c(); | - borrow later used here @@ -32,12 +32,12 @@ error[E0506]: cannot assign to `e.0.0.m.x` because it is borrowed --> $DIR/box.rs:55:5 | LL | let c = || { - | -- borrow of `e.0.0.m.x` occurs here + | -- `e.0.0.m.x` is borrowed here LL | println!("{}", e.0.0.m.x); | --------- borrow occurs due to use in closure ... LL | e.0.0.m.x = format!("not-x"); - | ^^^^^^^^^ assignment to borrowed `e.0.0.m.x` occurs here + | ^^^^^^^^^ `e.0.0.m.x` is assigned to here but it was already borrowed LL | LL | c(); | - borrow later used here diff --git a/tests/ui/closures/2229_closure_analysis/diagnostics/union.rs b/tests/ui/closures/2229_closure_analysis/diagnostics/union.rs index 46b54846e32eb..695337ea82cf9 100644 --- a/tests/ui/closures/2229_closure_analysis/diagnostics/union.rs +++ b/tests/ui/closures/2229_closure_analysis/diagnostics/union.rs @@ -11,7 +11,7 @@ union A { fn main() { let mut a = A { y: 1 }; let mut c = || { - //~^ borrow of `a.y` occurs here + //~^ `a.y` is borrowed here let _ = unsafe { &a.y }; let _ = &mut a; //~^ borrow occurs due to use in closure @@ -19,7 +19,7 @@ fn main() { }; a.y = 1; //~^ cannot assign to `a.y` because it is borrowed [E0506] - //~| assignment to borrowed `a.y` occurs here + //~| `a.y` is assigned to here c(); //~^ borrow later used here } diff --git a/tests/ui/closures/2229_closure_analysis/diagnostics/union.stderr b/tests/ui/closures/2229_closure_analysis/diagnostics/union.stderr index 7c34e2336c867..17834e6123628 100644 --- a/tests/ui/closures/2229_closure_analysis/diagnostics/union.stderr +++ b/tests/ui/closures/2229_closure_analysis/diagnostics/union.stderr @@ -2,13 +2,13 @@ error[E0506]: cannot assign to `a.y` because it is borrowed --> $DIR/union.rs:20:5 | LL | let mut c = || { - | -- borrow of `a.y` occurs here + | -- `a.y` is borrowed here ... LL | let _ = &mut a; | - borrow occurs due to use in closure ... LL | a.y = 1; - | ^^^^^^^ assignment to borrowed `a.y` occurs here + | ^^^^^^^ `a.y` is assigned to here but it was already borrowed ... LL | c(); | - borrow later used here diff --git a/tests/ui/coercion/coerce-overloaded-autoderef-fail.stderr b/tests/ui/coercion/coerce-overloaded-autoderef-fail.stderr index d067c3b3a1805..d412b8b08b79a 100644 --- a/tests/ui/coercion/coerce-overloaded-autoderef-fail.stderr +++ b/tests/ui/coercion/coerce-overloaded-autoderef-fail.stderr @@ -13,10 +13,10 @@ error[E0506]: cannot assign to `**x` because it is borrowed --> $DIR/coerce-overloaded-autoderef-fail.rs:17:5 | LL | let y = borrow(x); - | - borrow of `**x` occurs here + | - `**x` is borrowed here LL | let z = borrow(x); LL | **x += 1; - | ^^^^^^^^ assignment to borrowed `**x` occurs here + | ^^^^^^^^ `**x` is assigned to here but it was already borrowed LL | LL | drop((y, z)); | - borrow later used here diff --git a/tests/ui/consts/promote_const_let.stderr b/tests/ui/consts/promote_const_let.stderr index 975a235a6495b..6e0349a4773cd 100644 --- a/tests/ui/consts/promote_const_let.stderr +++ b/tests/ui/consts/promote_const_let.stderr @@ -4,6 +4,7 @@ error[E0597]: `y` does not live long enough LL | let x: &'static u32 = { | ------------ type annotation requires that `y` is borrowed for `'static` LL | let y = 42; + | - binding `y` declared here LL | &y | ^^ borrowed value does not live long enough LL | }; diff --git a/tests/ui/dropck/dropck-eyepatch-extern-crate.stderr b/tests/ui/dropck/dropck-eyepatch-extern-crate.stderr index 5d53405579d9d..23d57634e8fd2 100644 --- a/tests/ui/dropck/dropck-eyepatch-extern-crate.stderr +++ b/tests/ui/dropck/dropck-eyepatch-extern-crate.stderr @@ -1,6 +1,9 @@ error[E0597]: `c_shortest` does not live long enough --> $DIR/dropck-eyepatch-extern-crate.rs:46:23 | +LL | let (mut dt, mut dr, c_shortest): (Dt<_>, Dr<_>, Cell<_>); + | ---------- binding `c_shortest` declared here +... LL | dt = Dt("dt", &c_shortest); | ^^^^^^^^^^^ borrowed value does not live long enough ... @@ -15,6 +18,9 @@ LL | } error[E0597]: `c_shortest` does not live long enough --> $DIR/dropck-eyepatch-extern-crate.rs:68:32 | +LL | let (mut pt, mut pr, c_shortest): (Pt<_, _>, Pr<_>, Cell<_>); + | ---------- binding `c_shortest` declared here +... LL | pt = Pt("pt", &c_long, &c_shortest); | ^^^^^^^^^^^ borrowed value does not live long enough ... diff --git a/tests/ui/dropck/dropck-eyepatch-reorder.stderr b/tests/ui/dropck/dropck-eyepatch-reorder.stderr index 5055cdd8b2bf9..a5d5136b5c578 100644 --- a/tests/ui/dropck/dropck-eyepatch-reorder.stderr +++ b/tests/ui/dropck/dropck-eyepatch-reorder.stderr @@ -1,6 +1,9 @@ error[E0597]: `c_shortest` does not live long enough --> $DIR/dropck-eyepatch-reorder.rs:64:23 | +LL | let (mut dt, mut dr, c_shortest): (Dt<_>, Dr<_>, Cell<_>); + | ---------- binding `c_shortest` declared here +... LL | dt = Dt("dt", &c_shortest); | ^^^^^^^^^^^ borrowed value does not live long enough ... @@ -15,6 +18,9 @@ LL | } error[E0597]: `c_shortest` does not live long enough --> $DIR/dropck-eyepatch-reorder.rs:86:32 | +LL | let (mut pt, mut pr, c_shortest): (Pt<_, _>, Pr<_>, Cell<_>); + | ---------- binding `c_shortest` declared here +... LL | pt = Pt("pt", &c_long, &c_shortest); | ^^^^^^^^^^^ borrowed value does not live long enough ... diff --git a/tests/ui/dropck/dropck-eyepatch.stderr b/tests/ui/dropck/dropck-eyepatch.stderr index 21295e6c6019e..dc3f8c05e7396 100644 --- a/tests/ui/dropck/dropck-eyepatch.stderr +++ b/tests/ui/dropck/dropck-eyepatch.stderr @@ -1,6 +1,9 @@ error[E0597]: `c_shortest` does not live long enough --> $DIR/dropck-eyepatch.rs:88:23 | +LL | let (mut dt, mut dr, c_shortest): (Dt<_>, Dr<_>, Cell<_>); + | ---------- binding `c_shortest` declared here +... LL | dt = Dt("dt", &c_shortest); | ^^^^^^^^^^^ borrowed value does not live long enough ... @@ -15,6 +18,9 @@ LL | } error[E0597]: `c_shortest` does not live long enough --> $DIR/dropck-eyepatch.rs:110:32 | +LL | let (mut pt, mut pr, c_shortest): (Pt<_, _>, Pr<_>, Cell<_>); + | ---------- binding `c_shortest` declared here +... LL | pt = Pt("pt", &c_long, &c_shortest); | ^^^^^^^^^^^ borrowed value does not live long enough ... diff --git a/tests/ui/dropck/dropck-union.stderr b/tests/ui/dropck/dropck-union.stderr index 854e29385a81b..7d48e9fdcee31 100644 --- a/tests/ui/dropck/dropck-union.stderr +++ b/tests/ui/dropck/dropck-union.stderr @@ -1,6 +1,8 @@ error[E0597]: `v` does not live long enough --> $DIR/dropck-union.rs:37:18 | +LL | let v : Wrap = Wrap::new(C(Cell::new(None))); + | - binding `v` declared here LL | v.0.set(Some(&v)); | ^^ borrowed value does not live long enough LL | } diff --git a/tests/ui/dropck/dropck_trait_cycle_checked.stderr b/tests/ui/dropck/dropck_trait_cycle_checked.stderr index dc3fbed593b79..4d4f7b9df1179 100644 --- a/tests/ui/dropck/dropck_trait_cycle_checked.stderr +++ b/tests/ui/dropck/dropck_trait_cycle_checked.stderr @@ -2,7 +2,7 @@ error[E0597]: `o2` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:111:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -------- cast requires that `o2` is borrowed for `'static` + | -- binding `o2` declared here -------- cast requires that `o2` is borrowed for `'static` LL | o1.set0(&o2); | ^^^ borrowed value does not live long enough ... @@ -13,7 +13,7 @@ error[E0597]: `o3` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:112:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -------- cast requires that `o3` is borrowed for `'static` + | -- binding `o3` declared here -------- cast requires that `o3` is borrowed for `'static` LL | o1.set0(&o2); LL | o1.set1(&o3); | ^^^ borrowed value does not live long enough @@ -25,7 +25,7 @@ error[E0597]: `o2` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:113:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -------- cast requires that `o2` is borrowed for `'static` + | -- binding `o2` declared here -------- cast requires that `o2` is borrowed for `'static` ... LL | o2.set0(&o2); | ^^^ borrowed value does not live long enough @@ -37,7 +37,7 @@ error[E0597]: `o3` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:114:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -------- cast requires that `o3` is borrowed for `'static` + | -- binding `o3` declared here -------- cast requires that `o3` is borrowed for `'static` ... LL | o2.set1(&o3); | ^^^ borrowed value does not live long enough @@ -49,7 +49,7 @@ error[E0597]: `o1` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:115:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -------- cast requires that `o1` is borrowed for `'static` + | -- binding `o1` declared here -------- cast requires that `o1` is borrowed for `'static` ... LL | o3.set0(&o1); | ^^^ borrowed value does not live long enough @@ -61,7 +61,7 @@ error[E0597]: `o2` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:116:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -------- cast requires that `o2` is borrowed for `'static` + | -- binding `o2` declared here -------- cast requires that `o2` is borrowed for `'static` ... LL | o3.set1(&o2); | ^^^ borrowed value does not live long enough diff --git a/tests/ui/dst/dst-bad-coerce3.stderr b/tests/ui/dst/dst-bad-coerce3.stderr index 957e98bbeee96..1254250bcbd85 100644 --- a/tests/ui/dst/dst-bad-coerce3.stderr +++ b/tests/ui/dst/dst-bad-coerce3.stderr @@ -3,7 +3,9 @@ error[E0597]: `f1` does not live long enough | LL | fn baz<'a>() { | -- lifetime `'a` defined here -... +LL | // With a vec of ints. +LL | let f1 = Fat { ptr: [1, 2, 3] }; + | -- binding `f1` declared here LL | let f2: &Fat<[isize; 3]> = &f1; | ^^^ borrowed value does not live long enough LL | let f3: &'a Fat<[isize]> = f2; @@ -18,6 +20,8 @@ error[E0597]: `f1` does not live long enough LL | fn baz<'a>() { | -- lifetime `'a` defined here ... +LL | let f1 = Fat { ptr: Foo }; + | -- binding `f1` declared here LL | let f2: &Fat = &f1; | ^^^ borrowed value does not live long enough LL | let f3: &'a Fat = f2; @@ -32,6 +36,8 @@ error[E0597]: `f1` does not live long enough LL | fn baz<'a>() { | -- lifetime `'a` defined here ... +LL | let f1 = ([1, 2, 3],); + | -- binding `f1` declared here LL | let f2: &([isize; 3],) = &f1; | ^^^ borrowed value does not live long enough LL | let f3: &'a ([isize],) = f2; @@ -46,6 +52,8 @@ error[E0597]: `f1` does not live long enough LL | fn baz<'a>() { | -- lifetime `'a` defined here ... +LL | let f1 = (Foo,); + | -- binding `f1` declared here LL | let f2: &(Foo,) = &f1; | ^^^ borrowed value does not live long enough LL | let f3: &'a (dyn Bar,) = f2; diff --git a/tests/ui/error-codes/E0503.stderr b/tests/ui/error-codes/E0503.stderr index fafe363eb47a6..2f02e3b1a6138 100644 --- a/tests/ui/error-codes/E0503.stderr +++ b/tests/ui/error-codes/E0503.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `value` because it was mutably borrowed --> $DIR/E0503.rs:4:16 | LL | let _borrow = &mut value; - | ---------- borrow of `value` occurs here + | ---------- `value` is borrowed here LL | let _sum = value + 1; | ^^^^^ use of borrowed `value` LL | _borrow.use_mut(); diff --git a/tests/ui/error-codes/E0504.stderr b/tests/ui/error-codes/E0504.stderr index e677e89161542..20e16a5381061 100644 --- a/tests/ui/error-codes/E0504.stderr +++ b/tests/ui/error-codes/E0504.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `fancy_num` because it is borrowed --> $DIR/E0504.rs:9:13 | +LL | let fancy_num = FancyNum { num: 5 }; + | --------- binding `fancy_num` declared here LL | let fancy_ref = &fancy_num; | ---------- borrow of `fancy_num` occurs here LL | diff --git a/tests/ui/error-codes/E0505.stderr b/tests/ui/error-codes/E0505.stderr index bd3f37f54e0a8..2ecb4a75c4382 100644 --- a/tests/ui/error-codes/E0505.stderr +++ b/tests/ui/error-codes/E0505.stderr @@ -1,6 +1,9 @@ error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/E0505.rs:9:13 | +LL | let x = Value{}; + | - binding `x` declared here +LL | { LL | let _ref_to_val: &Value = &x; | -- borrow of `x` occurs here LL | eat(x); diff --git a/tests/ui/error-codes/E0506.stderr b/tests/ui/error-codes/E0506.stderr index d70406b750afc..17ad7c611f824 100644 --- a/tests/ui/error-codes/E0506.stderr +++ b/tests/ui/error-codes/E0506.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `fancy_num` because it is borrowed --> $DIR/E0506.rs:8:5 | LL | let fancy_ref = &fancy_num; - | ---------- borrow of `fancy_num` occurs here + | ---------- `fancy_num` is borrowed here LL | fancy_num = FancyNum { num: 6 }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `fancy_num` occurs here + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `fancy_num` is assigned to here but it was already borrowed LL | LL | println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num); | ------------- borrow later used here diff --git a/tests/ui/error-codes/E0597.stderr b/tests/ui/error-codes/E0597.stderr index b4a1180ad546c..82e3481b65a59 100644 --- a/tests/ui/error-codes/E0597.stderr +++ b/tests/ui/error-codes/E0597.stderr @@ -1,6 +1,8 @@ error[E0597]: `y` does not live long enough --> $DIR/E0597.rs:8:16 | +LL | let y = 0; + | - binding `y` declared here LL | x.x = Some(&y); | ^^ borrowed value does not live long enough LL | diff --git a/tests/ui/fn/implied-bounds-unnorm-associated-type-4.stderr b/tests/ui/fn/implied-bounds-unnorm-associated-type-4.stderr index fcbaa91d19f82..4df639232a332 100644 --- a/tests/ui/fn/implied-bounds-unnorm-associated-type-4.stderr +++ b/tests/ui/fn/implied-bounds-unnorm-associated-type-4.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/implied-bounds-unnorm-associated-type-4.rs:21:10 | +LL | let x = String::from("Hello World!"); + | - binding `x` declared here LL | let y = f(&x, ()); | -- borrow of `x` occurs here LL | drop(x); diff --git a/tests/ui/fn/implied-bounds-unnorm-associated-type.stderr b/tests/ui/fn/implied-bounds-unnorm-associated-type.stderr index e35f46e4439a9..d417f28839368 100644 --- a/tests/ui/fn/implied-bounds-unnorm-associated-type.stderr +++ b/tests/ui/fn/implied-bounds-unnorm-associated-type.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/implied-bounds-unnorm-associated-type.rs:20:10 | +LL | let x = String::from("Hello World!"); + | - binding `x` declared here LL | let y = f(&x, ()); | -- borrow of `x` occurs here LL | drop(x); diff --git a/tests/ui/generic-associated-types/issue-74684-1.stderr b/tests/ui/generic-associated-types/issue-74684-1.stderr index cacc973077ce7..b93ee37987f27 100644 --- a/tests/ui/generic-associated-types/issue-74684-1.stderr +++ b/tests/ui/generic-associated-types/issue-74684-1.stderr @@ -4,6 +4,7 @@ error[E0597]: `a` does not live long enough LL | fn bug<'a, T: ?Sized + Fun = [u8]>>(_ : Box) -> &'static T::F<'a> { | -- lifetime `'a` defined here LL | let a = [0; 1]; + | - binding `a` declared here LL | let _x = T::identity(&a); | ------------^^- | | | diff --git a/tests/ui/higher-rank-trait-bounds/hrtb-identity-fn-borrows.stderr b/tests/ui/higher-rank-trait-bounds/hrtb-identity-fn-borrows.stderr index 4886a3c8bad62..25af011e3fc41 100644 --- a/tests/ui/higher-rank-trait-bounds/hrtb-identity-fn-borrows.stderr +++ b/tests/ui/higher-rank-trait-bounds/hrtb-identity-fn-borrows.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/hrtb-identity-fn-borrows.rs:14:5 | LL | let y = f.call(&x); - | -- borrow of `x` occurs here + | -- `x` is borrowed here LL | x = 5; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed ... LL | drop(y); | - borrow later used here diff --git a/tests/ui/impl-trait/feature-self-return-type.stderr b/tests/ui/impl-trait/feature-self-return-type.stderr index 601e53b769459..b9b8d00ce308b 100644 --- a/tests/ui/impl-trait/feature-self-return-type.stderr +++ b/tests/ui/impl-trait/feature-self-return-type.stderr @@ -4,6 +4,7 @@ error[E0597]: `bar` does not live long enough LL | let x = { | - borrow later stored here LL | let bar = 22; + | --- binding `bar` declared here LL | Foo::new(&bar).into() | ^^^^ borrowed value does not live long enough LL | @@ -16,6 +17,7 @@ error[E0597]: `y` does not live long enough LL | let x = { | - borrow later stored here LL | let y = (); + | - binding `y` declared here LL | foo(&y) | ^^ borrowed value does not live long enough LL | @@ -28,6 +30,7 @@ error[E0597]: `y` does not live long enough LL | let x = { | - borrow later stored here LL | let y = (); + | - binding `y` declared here LL | foo(&y) | ^^ borrowed value does not live long enough LL | diff --git a/tests/ui/implied-bounds/assoc-ty-wf-used-to-get-assoc-ty.stderr b/tests/ui/implied-bounds/assoc-ty-wf-used-to-get-assoc-ty.stderr index d0249e74f39e9..307899297bc01 100644 --- a/tests/ui/implied-bounds/assoc-ty-wf-used-to-get-assoc-ty.stderr +++ b/tests/ui/implied-bounds/assoc-ty-wf-used-to-get-assoc-ty.stderr @@ -1,6 +1,8 @@ error[E0597]: `x` does not live long enough --> $DIR/assoc-ty-wf-used-to-get-assoc-ty.rs:24:31 | +LL | let x: u8 = 3; + | - binding `x` declared here LL | let _: &'static u8 = test(&x, &&3); | -----^^------ | | | diff --git a/tests/ui/inline-const/const-expr-lifetime-err.stderr b/tests/ui/inline-const/const-expr-lifetime-err.stderr index a23f7c9a796c5..443fcf89c4e11 100644 --- a/tests/ui/inline-const/const-expr-lifetime-err.stderr +++ b/tests/ui/inline-const/const-expr-lifetime-err.stderr @@ -4,6 +4,7 @@ error[E0597]: `y` does not live long enough LL | fn foo<'a>() { | -- lifetime `'a` defined here LL | let y = (); + | - binding `y` declared here LL | equate(InvariantRef::new(&y), const { InvariantRef::<'a>::NEW }); | ------------------^^- | | | diff --git a/tests/ui/issues/issue-40288.stderr b/tests/ui/issues/issue-40288.stderr index fb4ecab362db1..db5d064379a76 100644 --- a/tests/ui/issues/issue-40288.stderr +++ b/tests/ui/issues/issue-40288.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `*refr` because it is borrowed --> $DIR/issue-40288.rs:16:5 | LL | save_ref(&*refr, &mut out); - | ------ borrow of `*refr` occurs here + | ------ `*refr` is borrowed here ... LL | *refr = 3; - | ^^^^^^^^^ assignment to borrowed `*refr` occurs here + | ^^^^^^^^^ `*refr` is assigned to here but it was already borrowed ... LL | println!("{:?}", out[0]); | ------ borrow later used here diff --git a/tests/ui/issues/issue-45697-1.stderr b/tests/ui/issues/issue-45697-1.stderr index 30c69f19658c8..474313398e2bc 100644 --- a/tests/ui/issues/issue-45697-1.stderr +++ b/tests/ui/issues/issue-45697-1.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `*y.pointer` because it was mutably borrowed --> $DIR/issue-45697-1.rs:20:9 | LL | let z = copy_borrowed_ptr(&mut y); - | ------ borrow of `y` occurs here + | ------ `y` is borrowed here LL | *y.pointer += 1; | ^^^^^^^^^^^^^^^ use of borrowed `y` ... @@ -13,9 +13,9 @@ error[E0506]: cannot assign to `*y.pointer` because it is borrowed --> $DIR/issue-45697-1.rs:20:9 | LL | let z = copy_borrowed_ptr(&mut y); - | ------ borrow of `*y.pointer` occurs here + | ------ `*y.pointer` is borrowed here LL | *y.pointer += 1; - | ^^^^^^^^^^^^^^^ assignment to borrowed `*y.pointer` occurs here + | ^^^^^^^^^^^^^^^ `*y.pointer` is assigned to here but it was already borrowed ... LL | *z.pointer += 1; | --------------- borrow later used here diff --git a/tests/ui/issues/issue-45697.stderr b/tests/ui/issues/issue-45697.stderr index 26749d36f0b7b..7986fd5c9df2e 100644 --- a/tests/ui/issues/issue-45697.stderr +++ b/tests/ui/issues/issue-45697.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `*y.pointer` because it was mutably borrowed --> $DIR/issue-45697.rs:20:9 | LL | let z = copy_borrowed_ptr(&mut y); - | ------ borrow of `y` occurs here + | ------ `y` is borrowed here LL | *y.pointer += 1; | ^^^^^^^^^^^^^^^ use of borrowed `y` ... @@ -13,9 +13,9 @@ error[E0506]: cannot assign to `*y.pointer` because it is borrowed --> $DIR/issue-45697.rs:20:9 | LL | let z = copy_borrowed_ptr(&mut y); - | ------ borrow of `*y.pointer` occurs here + | ------ `*y.pointer` is borrowed here LL | *y.pointer += 1; - | ^^^^^^^^^^^^^^^ assignment to borrowed `*y.pointer` occurs here + | ^^^^^^^^^^^^^^^ `*y.pointer` is assigned to here but it was already borrowed ... LL | *z.pointer += 1; | --------------- borrow later used here diff --git a/tests/ui/issues/issue-46471-1.stderr b/tests/ui/issues/issue-46471-1.stderr index b09f31729a5fd..2ae6e709d5ad5 100644 --- a/tests/ui/issues/issue-46471-1.stderr +++ b/tests/ui/issues/issue-46471-1.stderr @@ -1,11 +1,10 @@ error[E0597]: `z` does not live long enough --> $DIR/issue-46471-1.rs:4:9 | +LL | let mut z = 0; + | ----- binding `z` declared here LL | &mut z - | ^^^^^^ - | | - | borrowed value does not live long enough - | borrow later used here + | ^^^^^^ borrowed value does not live long enough LL | }; | - `z` dropped here while still borrowed diff --git a/tests/ui/lifetimes/issue-90600-expected-return-static-indirect.stderr b/tests/ui/lifetimes/issue-90600-expected-return-static-indirect.stderr index 99e1e7217b45c..3602de8dd9577 100644 --- a/tests/ui/lifetimes/issue-90600-expected-return-static-indirect.stderr +++ b/tests/ui/lifetimes/issue-90600-expected-return-static-indirect.stderr @@ -1,6 +1,8 @@ error[E0597]: `foo` does not live long enough --> $DIR/issue-90600-expected-return-static-indirect.rs:7:32 | +LL | fn inner(mut foo: &[u8]) { + | ------- binding `foo` declared here LL | let refcell = RefCell::new(&mut foo); | ^^^^^^^^ borrowed value does not live long enough LL | diff --git a/tests/ui/mut/mut-pattern-internal-mutability.stderr b/tests/ui/mut/mut-pattern-internal-mutability.stderr index 6583546aa5c1f..5f2074edb1240 100644 --- a/tests/ui/mut/mut-pattern-internal-mutability.stderr +++ b/tests/ui/mut/mut-pattern-internal-mutability.stderr @@ -13,9 +13,9 @@ error[E0506]: cannot assign to `*foo` because it is borrowed --> $DIR/mut-pattern-internal-mutability.rs:13:5 | LL | let &mut ref x = foo; - | ----- borrow of `*foo` occurs here + | ----- `*foo` is borrowed here LL | *foo += 1; - | ^^^^^^^^^ assignment to borrowed `*foo` occurs here + | ^^^^^^^^^ `*foo` is assigned to here but it was already borrowed LL | drop(x); | - borrow later used here diff --git a/tests/ui/nll/borrowed-local-error.stderr b/tests/ui/nll/borrowed-local-error.stderr index d629caa435319..1cca4077d825a 100644 --- a/tests/ui/nll/borrowed-local-error.stderr +++ b/tests/ui/nll/borrowed-local-error.stderr @@ -4,6 +4,7 @@ error[E0597]: `v` does not live long enough LL | let x = gimme({ | ----- borrow later used by call LL | let v = (22,); + | - binding `v` declared here LL | &v | ^^ borrowed value does not live long enough LL | diff --git a/tests/ui/nll/borrowed-match-issue-45045.stderr b/tests/ui/nll/borrowed-match-issue-45045.stderr index 9d4682667dddd..33e3eb797969e 100644 --- a/tests/ui/nll/borrowed-match-issue-45045.stderr +++ b/tests/ui/nll/borrowed-match-issue-45045.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `e` because it was mutably borrowed --> $DIR/borrowed-match-issue-45045.rs:12:11 | LL | let f = &mut e; - | ------ borrow of `e` occurs here + | ------ `e` is borrowed here LL | let g = f; LL | match e { | ^ use of borrowed `e` diff --git a/tests/ui/nll/capture-ref-in-struct.stderr b/tests/ui/nll/capture-ref-in-struct.stderr index cdfe7f6db82a9..84b7ecf2f7da8 100644 --- a/tests/ui/nll/capture-ref-in-struct.stderr +++ b/tests/ui/nll/capture-ref-in-struct.stderr @@ -1,6 +1,9 @@ error[E0597]: `y` does not live long enough --> $DIR/capture-ref-in-struct.rs:18:16 | +LL | let y = 22; + | - binding `y` declared here +... LL | y: &y, | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/nll/closure-access-spans.stderr b/tests/ui/nll/closure-access-spans.stderr index 0a09353b8ec0a..035dd5a561096 100644 --- a/tests/ui/nll/closure-access-spans.stderr +++ b/tests/ui/nll/closure-access-spans.stderr @@ -38,7 +38,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/closure-access-spans.rs:23:13 | LL | let r = &mut x; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | move || x; | ^ use of borrowed `x` LL | r.use_ref(); @@ -47,6 +47,8 @@ LL | r.use_ref(); error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/closure-access-spans.rs:29:5 | +LL | fn closure_move_capture_conflict(mut x: String) { + | ----- binding `x` declared here LL | let r = &x; | -- borrow of `x` occurs here LL | || x; diff --git a/tests/ui/nll/closure-borrow-spans.stderr b/tests/ui/nll/closure-borrow-spans.stderr index bada4e1b84b52..cf0df5834cc0d 100644 --- a/tests/ui/nll/closure-borrow-spans.stderr +++ b/tests/ui/nll/closure-borrow-spans.stderr @@ -40,9 +40,9 @@ error[E0506]: cannot assign to `x` because it is borrowed LL | let f = || x; | -- - borrow occurs due to use in closure | | - | borrow of `x` occurs here + | `x` is borrowed here LL | x = 1; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | f.use_ref(); | ----------- borrow later used here @@ -52,7 +52,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed LL | let f = || x = 0; | -- - borrow occurs due to use of `x` in closure | | - | borrow of `x` occurs here + | `x` is borrowed here LL | let y = x; | ^ use of borrowed `x` LL | f.use_ref(); @@ -100,9 +100,9 @@ error[E0506]: cannot assign to `x` because it is borrowed LL | let f = || x = 0; | -- - borrow occurs due to use in closure | | - | borrow of `x` occurs here + | `x` is borrowed here LL | x = 1; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | f.use_ref(); | ----------- borrow later used here @@ -160,9 +160,9 @@ error[E0506]: cannot assign to `*x` because it is borrowed LL | let f = || *x = 0; | -- -- borrow occurs due to use in closure | | - | borrow of `*x` occurs here + | `*x` is borrowed here LL | *x = 1; - | ^^^^^^ assignment to borrowed `*x` occurs here + | ^^^^^^ `*x` is assigned to here but it was already borrowed LL | f.use_ref(); | ----------- borrow later used here diff --git a/tests/ui/nll/closure-requirements/escape-argument.stderr b/tests/ui/nll/closure-requirements/escape-argument.stderr index f67c312b94688..5a8462d4dc56e 100644 --- a/tests/ui/nll/closure-requirements/escape-argument.stderr +++ b/tests/ui/nll/closure-requirements/escape-argument.stderr @@ -21,6 +21,9 @@ LL | fn test() { error[E0597]: `y` does not live long enough --> $DIR/escape-argument.rs:27:25 | +LL | let y = 22; + | - binding `y` declared here +LL | let mut closure = expect_sig(|p, y| *p = y); LL | closure(&mut p, &y); | ^^ borrowed value does not live long enough LL | diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr index 7991abeb7a800..721cd45ded98e 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr @@ -53,6 +53,8 @@ LL | fn case2() { error[E0597]: `a` does not live long enough --> $DIR/propagate-approximated-shorter-to-static-comparing-against-free.rs:30:26 | +LL | let a = 0; + | - binding `a` declared here LL | let cell = Cell::new(&a); | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/nll/closure-use-spans.stderr b/tests/ui/nll/closure-use-spans.stderr index ad928f1bbc984..0e27e5f5f7c16 100644 --- a/tests/ui/nll/closure-use-spans.stderr +++ b/tests/ui/nll/closure-use-spans.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/closure-use-spans.rs:5:5 | LL | let y = &x; - | -- borrow of `x` occurs here + | -- `x` is borrowed here LL | x = 0; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | || *y; | -- borrow later captured here by closure @@ -12,9 +12,9 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/closure-use-spans.rs:11:5 | LL | let y = &mut x; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | x = 0; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | || *y = 1; | -- borrow later captured here by closure @@ -22,9 +22,9 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/closure-use-spans.rs:17:5 | LL | let y = &x; - | -- borrow of `x` occurs here + | -- `x` is borrowed here LL | x = 0; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | move || *y; | -- borrow later captured here by closure diff --git a/tests/ui/nll/do-not-ignore-lifetime-bounds-in-copy-proj.stderr b/tests/ui/nll/do-not-ignore-lifetime-bounds-in-copy-proj.stderr index 65be3b37e0e3b..862c925b468fd 100644 --- a/tests/ui/nll/do-not-ignore-lifetime-bounds-in-copy-proj.stderr +++ b/tests/ui/nll/do-not-ignore-lifetime-bounds-in-copy-proj.stderr @@ -1,6 +1,8 @@ error[E0597]: `s` does not live long enough --> $DIR/do-not-ignore-lifetime-bounds-in-copy-proj.rs:9:18 | +LL | let s = 2; + | - binding `s` declared here LL | let a = (Foo(&s),); | ^^ borrowed value does not live long enough LL | drop(a.0); diff --git a/tests/ui/nll/do-not-ignore-lifetime-bounds-in-copy.stderr b/tests/ui/nll/do-not-ignore-lifetime-bounds-in-copy.stderr index b811ba4fd0cd2..ebaf6d1244d7d 100644 --- a/tests/ui/nll/do-not-ignore-lifetime-bounds-in-copy.stderr +++ b/tests/ui/nll/do-not-ignore-lifetime-bounds-in-copy.stderr @@ -1,6 +1,8 @@ error[E0597]: `s` does not live long enough --> $DIR/do-not-ignore-lifetime-bounds-in-copy.rs:8:17 | +LL | let s = 2; + | - binding `s` declared here LL | let a = Foo(&s); | ^^ borrowed value does not live long enough LL | drop(a); diff --git a/tests/ui/nll/dont-print-desugared.stderr b/tests/ui/nll/dont-print-desugared.stderr index fad6121cbca52..289b246e663e1 100644 --- a/tests/ui/nll/dont-print-desugared.stderr +++ b/tests/ui/nll/dont-print-desugared.stderr @@ -10,6 +10,7 @@ error[E0597]: `y` does not live long enough LL | for ref mut d in v { | - a temporary with access to the borrow is created here ... LL | let y = (); + | - binding `y` declared here LL | *d = D(&y); | ^^ borrowed value does not live long enough LL | } diff --git a/tests/ui/nll/drop-no-may-dangle.stderr b/tests/ui/nll/drop-no-may-dangle.stderr index cb28088095004..0ddb7adbb3822 100644 --- a/tests/ui/nll/drop-no-may-dangle.stderr +++ b/tests/ui/nll/drop-no-may-dangle.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `v[_]` because it is borrowed --> $DIR/drop-no-may-dangle.rs:18:9 | LL | let p: WrapMayNotDangle<&usize> = WrapMayNotDangle { value: &v[0] }; - | ----- borrow of `v[_]` occurs here + | ----- `v[_]` is borrowed here ... LL | v[0] += 1; - | ^^^^^^^^^ assignment to borrowed `v[_]` occurs here + | ^^^^^^^^^ `v[_]` is assigned to here but it was already borrowed ... LL | } | - borrow might be used here, when `p` is dropped and runs the `Drop` code for type `WrapMayNotDangle` @@ -14,10 +14,10 @@ error[E0506]: cannot assign to `v[_]` because it is borrowed --> $DIR/drop-no-may-dangle.rs:21:5 | LL | let p: WrapMayNotDangle<&usize> = WrapMayNotDangle { value: &v[0] }; - | ----- borrow of `v[_]` occurs here + | ----- `v[_]` is borrowed here ... LL | v[0] += 1; - | ^^^^^^^^^ assignment to borrowed `v[_]` occurs here + | ^^^^^^^^^ `v[_]` is assigned to here but it was already borrowed LL | } | - borrow might be used here, when `p` is dropped and runs the `Drop` code for type `WrapMayNotDangle` diff --git a/tests/ui/nll/guarantor-issue-46974.stderr b/tests/ui/nll/guarantor-issue-46974.stderr index 8854dd8d68c9d..7edc3dcc5cde3 100644 --- a/tests/ui/nll/guarantor-issue-46974.stderr +++ b/tests/ui/nll/guarantor-issue-46974.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `*s` because it is borrowed --> $DIR/guarantor-issue-46974.rs:7:5 | LL | let t = &mut *s; // this borrow should last for the entire function - | ------- borrow of `*s` occurs here + | ------- `*s` is borrowed here LL | let x = &t.0; LL | *s = (2,); - | ^^^^^^^^^ assignment to borrowed `*s` occurs here + | ^^^^^^^^^ `*s` is assigned to here but it was already borrowed LL | *x | -- borrow later used here diff --git a/tests/ui/nll/issue-27282-move-ref-mut-into-guard.stderr b/tests/ui/nll/issue-27282-move-ref-mut-into-guard.stderr index 45119018d4e60..4a512560c8751 100644 --- a/tests/ui/nll/issue-27282-move-ref-mut-into-guard.stderr +++ b/tests/ui/nll/issue-27282-move-ref-mut-into-guard.stderr @@ -4,7 +4,7 @@ error[E0507]: cannot move out of `foo` in pattern guard LL | if { (|| { let bar = foo; bar.take() })(); false } => {}, | ^^ --- move occurs because `foo` has type `&mut Option<&i32>`, which does not implement the `Copy` trait | | - | move out of `foo` occurs here + | `foo` is moved here | = note: variables bound in patterns cannot be moved from until after the end of the pattern guard @@ -14,7 +14,7 @@ error[E0507]: cannot move out of `foo` in pattern guard LL | if let Some(()) = { (|| { let bar = foo; bar.take() })(); None } => {}, | ^^ --- move occurs because `foo` has type `&mut Option<&i32>`, which does not implement the `Copy` trait | | - | move out of `foo` occurs here + | `foo` is moved here | = note: variables bound in patterns cannot be moved from until after the end of the pattern guard diff --git a/tests/ui/nll/issue-27282-mutation-in-guard.stderr b/tests/ui/nll/issue-27282-mutation-in-guard.stderr index 1ba696593afff..0b5d723172c76 100644 --- a/tests/ui/nll/issue-27282-mutation-in-guard.stderr +++ b/tests/ui/nll/issue-27282-mutation-in-guard.stderr @@ -4,7 +4,7 @@ error[E0507]: cannot move out of `foo` in pattern guard LL | (|| { let bar = foo; bar.take() })(); | ^^ --- move occurs because `foo` has type `&mut Option<&i32>`, which does not implement the `Copy` trait | | - | move out of `foo` occurs here + | `foo` is moved here | = note: variables bound in patterns cannot be moved from until after the end of the pattern guard @@ -14,7 +14,7 @@ error[E0507]: cannot move out of `foo` in pattern guard LL | (|| { let bar = foo; bar.take() })(); | ^^ --- move occurs because `foo` has type `&mut Option<&i32>`, which does not implement the `Copy` trait | | - | move out of `foo` occurs here + | `foo` is moved here | = note: variables bound in patterns cannot be moved from until after the end of the pattern guard diff --git a/tests/ui/nll/issue-27868.stderr b/tests/ui/nll/issue-27868.stderr index e0b3b5494d0a5..204eda3d26796 100644 --- a/tests/ui/nll/issue-27868.stderr +++ b/tests/ui/nll/issue-27868.stderr @@ -4,10 +4,10 @@ error[E0506]: cannot assign to `vecvec` because it is borrowed LL | vecvec[0] += { | ------ | | - | _____borrow of `vecvec` occurs here + | _____`vecvec` is borrowed here | | LL | | vecvec = vec![]; - | | ^^^^^^ assignment to borrowed `vecvec` occurs here + | | ^^^^^^ `vecvec` is assigned to here but it was already borrowed LL | | LL | | 0 LL | | }; diff --git a/tests/ui/nll/issue-46036.stderr b/tests/ui/nll/issue-46036.stderr index e6e95ee613647..f337e23455070 100644 --- a/tests/ui/nll/issue-46036.stderr +++ b/tests/ui/nll/issue-46036.stderr @@ -1,6 +1,8 @@ error[E0597]: `a` does not live long enough --> $DIR/issue-46036.rs:8:24 | +LL | let a = 3; + | - binding `a` declared here LL | let foo = Foo { x: &a }; | ^^ | | diff --git a/tests/ui/nll/issue-48803.stderr b/tests/ui/nll/issue-48803.stderr index 2f94039c0c3a9..e24606e0b53e8 100644 --- a/tests/ui/nll/issue-48803.stderr +++ b/tests/ui/nll/issue-48803.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/issue-48803.rs:10:5 | LL | let y = &x; - | -- borrow of `x` occurs here + | -- `x` is borrowed here ... LL | x = "modified"; - | ^^^^^^^^^^^^^^ assignment to borrowed `x` occurs here + | ^^^^^^^^^^^^^^ `x` is assigned to here but it was already borrowed LL | LL | println!("{}", w); // prints "modified" | - borrow later used here diff --git a/tests/ui/nll/issue-52534-2.stderr b/tests/ui/nll/issue-52534-2.stderr index ac385e056b9f8..35d39bb6e908d 100644 --- a/tests/ui/nll/issue-52534-2.stderr +++ b/tests/ui/nll/issue-52534-2.stderr @@ -1,6 +1,8 @@ error[E0597]: `x` does not live long enough --> $DIR/issue-52534-2.rs:6:13 | +LL | let x = 32; + | - binding `x` declared here LL | y = &x | ^^ borrowed value does not live long enough LL | diff --git a/tests/ui/nll/issue-52663-trait-object.stderr b/tests/ui/nll/issue-52663-trait-object.stderr index 5cedea6e66520..338f64841321f 100644 --- a/tests/ui/nll/issue-52663-trait-object.stderr +++ b/tests/ui/nll/issue-52663-trait-object.stderr @@ -1,6 +1,8 @@ error[E0597]: `tmp0` does not live long enough --> $DIR/issue-52663-trait-object.rs:12:20 | +LL | let tmp0 = 3; + | ---- binding `tmp0` declared here LL | let tmp1 = &tmp0; | ^^^^^ borrowed value does not live long enough LL | Box::new(tmp1) as Box diff --git a/tests/ui/nll/issue-54382-use-span-of-tail-of-block.stderr b/tests/ui/nll/issue-54382-use-span-of-tail-of-block.stderr index d8f43cbc92a1e..4a32c777a86f1 100644 --- a/tests/ui/nll/issue-54382-use-span-of-tail-of-block.stderr +++ b/tests/ui/nll/issue-54382-use-span-of-tail-of-block.stderr @@ -1,6 +1,9 @@ error[E0597]: `_thing1` does not live long enough --> $DIR/issue-54382-use-span-of-tail-of-block.rs:7:29 | +LL | let mut _thing1 = D(Box::new("thing1")); + | ----------- binding `_thing1` declared here +... LL | D("other").next(&_thing1) | ----------------^^^^^^^^- | | | diff --git a/tests/ui/nll/issue-54556-stephaneyfx.stderr b/tests/ui/nll/issue-54556-stephaneyfx.stderr index 036a7a0abfdcc..f9e82cb003fc2 100644 --- a/tests/ui/nll/issue-54556-stephaneyfx.stderr +++ b/tests/ui/nll/issue-54556-stephaneyfx.stderr @@ -1,6 +1,8 @@ error[E0597]: `stmt` does not live long enough --> $DIR/issue-54556-stephaneyfx.rs:27:21 | +LL | let stmt = Statement; + | ---- binding `stmt` declared here LL | let rows = Rows(&stmt); | ^^^^^ borrowed value does not live long enough LL | rows.map(|row| row).next() diff --git a/tests/ui/nll/issue-54556-temps-in-tail-diagnostic.stderr b/tests/ui/nll/issue-54556-temps-in-tail-diagnostic.stderr index 92f5ffdf388ed..4eae9fdcde0d2 100644 --- a/tests/ui/nll/issue-54556-temps-in-tail-diagnostic.stderr +++ b/tests/ui/nll/issue-54556-temps-in-tail-diagnostic.stderr @@ -1,6 +1,9 @@ error[E0597]: `_thing1` does not live long enough --> $DIR/issue-54556-temps-in-tail-diagnostic.rs:5:11 | +LL | let mut _thing1 = D(Box::new("thing1")); + | ----------- binding `_thing1` declared here +LL | // D("other").next(&_thing1).end() LL | D(&_thing1).end() | --^^^^^^^^- | | | diff --git a/tests/ui/nll/issue-54556-used-vs-unused-tails.stderr b/tests/ui/nll/issue-54556-used-vs-unused-tails.stderr index 25226e2967353..a2a7a8486545c 100644 --- a/tests/ui/nll/issue-54556-used-vs-unused-tails.stderr +++ b/tests/ui/nll/issue-54556-used-vs-unused-tails.stderr @@ -2,11 +2,12 @@ error[E0597]: `_t1` does not live long enough --> $DIR/issue-54556-used-vs-unused-tails.rs:10:55 | LL | { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // suggest `;` - | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` - | | | | - | | | `_t1` dropped here while still borrowed - | | borrowed value does not live long enough - | a temporary with access to the borrow is created here ... + | ------- --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` + | | | | | + | | | | `_t1` dropped here while still borrowed + | | | borrowed value does not live long enough + | | a temporary with access to the borrow is created here ... + | binding `_t1` declared here | help: consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped | @@ -17,11 +18,12 @@ error[E0597]: `_t1` does not live long enough --> $DIR/issue-54556-used-vs-unused-tails.rs:13:55 | LL | { { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } } ; // suggest `;` - | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` - | | | | - | | | `_t1` dropped here while still borrowed - | | borrowed value does not live long enough - | a temporary with access to the borrow is created here ... + | ------- --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` + | | | | | + | | | | `_t1` dropped here while still borrowed + | | | borrowed value does not live long enough + | | a temporary with access to the borrow is created here ... + | binding `_t1` declared here | help: consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped | @@ -32,11 +34,12 @@ error[E0597]: `_t1` does not live long enough --> $DIR/issue-54556-used-vs-unused-tails.rs:16:55 | LL | { { let mut _t1 = D(Box::new("t1")); D(&_t1).end() }; } // suggest `;` - | --^^^^- -- ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` - | | | | - | | | `_t1` dropped here while still borrowed - | | borrowed value does not live long enough - | a temporary with access to the borrow is created here ... + | ------- --^^^^- -- ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` + | | | | | + | | | | `_t1` dropped here while still borrowed + | | | borrowed value does not live long enough + | | a temporary with access to the borrow is created here ... + | binding `_t1` declared here | help: consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped | @@ -47,11 +50,12 @@ error[E0597]: `_t1` does not live long enough --> $DIR/issue-54556-used-vs-unused-tails.rs:19:55 | LL | let _ = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // suggest `;` - | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` - | | | | - | | | `_t1` dropped here while still borrowed - | | borrowed value does not live long enough - | a temporary with access to the borrow is created here ... + | ------- --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` + | | | | | + | | | | `_t1` dropped here while still borrowed + | | | borrowed value does not live long enough + | | a temporary with access to the borrow is created here ... + | binding `_t1` declared here | help: consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped | @@ -62,11 +66,12 @@ error[E0597]: `_t1` does not live long enough --> $DIR/issue-54556-used-vs-unused-tails.rs:22:55 | LL | let _u = { let mut _t1 = D(Box::new("t1")); D(&_t1).unit() } ; // suggest `;` - | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` - | | | | - | | | `_t1` dropped here while still borrowed - | | borrowed value does not live long enough - | a temporary with access to the borrow is created here ... + | ------- --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` + | | | | | + | | | | `_t1` dropped here while still borrowed + | | | borrowed value does not live long enough + | | a temporary with access to the borrow is created here ... + | binding `_t1` declared here | help: consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped | @@ -77,11 +82,12 @@ error[E0597]: `_t1` does not live long enough --> $DIR/issue-54556-used-vs-unused-tails.rs:25:55 | LL | let _x = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // `let x = ...; x` - | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` - | | | | - | | | `_t1` dropped here while still borrowed - | | borrowed value does not live long enough - | a temporary with access to the borrow is created here ... + | ------- --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` + | | | | | + | | | | `_t1` dropped here while still borrowed + | | | borrowed value does not live long enough + | | a temporary with access to the borrow is created here ... + | binding `_t1` declared here | = note: the temporary is part of an expression at the end of a block; consider forcing this temporary to be dropped sooner, before the block's local variables are dropped @@ -94,11 +100,12 @@ error[E0597]: `_t1` does not live long enough --> $DIR/issue-54556-used-vs-unused-tails.rs:30:55 | LL | _y = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // `let x = ...; x` - | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` - | | | | - | | | `_t1` dropped here while still borrowed - | | borrowed value does not live long enough - | a temporary with access to the borrow is created here ... + | ------- --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` + | | | | | + | | | | `_t1` dropped here while still borrowed + | | | borrowed value does not live long enough + | | a temporary with access to the borrow is created here ... + | binding `_t1` declared here | = note: the temporary is part of an expression at the end of a block; consider forcing this temporary to be dropped sooner, before the block's local variables are dropped @@ -111,12 +118,13 @@ error[E0597]: `_t1` does not live long enough --> $DIR/issue-54556-used-vs-unused-tails.rs:37:55 | LL | fn f_local_ref() { let mut _t1 = D(Box::new("t1")); D(&_t1).unit() } // suggest `;` - | --^^^^- - - | | | | - | | | `_t1` dropped here while still borrowed - | | | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` - | | borrowed value does not live long enough - | a temporary with access to the borrow is created here ... + | ------- --^^^^- - + | | | | | + | | | | `_t1` dropped here while still borrowed + | | | | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` + | | | borrowed value does not live long enough + | | a temporary with access to the borrow is created here ... + | binding `_t1` declared here | help: consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped | @@ -127,12 +135,13 @@ error[E0597]: `_t1` does not live long enough --> $DIR/issue-54556-used-vs-unused-tails.rs:40:55 | LL | fn f() -> String { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } // `let x = ...; x` - | --^^^^- - - | | | | - | | | `_t1` dropped here while still borrowed - | | | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` - | | borrowed value does not live long enough - | a temporary with access to the borrow is created here ... + | ------- --^^^^- - + | | | | | + | | | | `_t1` dropped here while still borrowed + | | | | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` + | | | borrowed value does not live long enough + | | a temporary with access to the borrow is created here ... + | binding `_t1` declared here | = note: the temporary is part of an expression at the end of a block; consider forcing this temporary to be dropped sooner, before the block's local variables are dropped diff --git a/tests/ui/nll/issue-54556-wrap-it-up.stderr b/tests/ui/nll/issue-54556-wrap-it-up.stderr index 9f27fac15a7f6..adc419ae51562 100644 --- a/tests/ui/nll/issue-54556-wrap-it-up.stderr +++ b/tests/ui/nll/issue-54556-wrap-it-up.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/issue-54556-wrap-it-up.rs:27:5 | LL | let wrap = Wrap { p: &mut x }; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here ... LL | x = 1; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | } | - borrow might be used here, when `foo` is dropped and runs the destructor for type `Foo<'_>` diff --git a/tests/ui/nll/issue-55511.stderr b/tests/ui/nll/issue-55511.stderr index bf3e58e8cdb19..ecb9ef0aef96e 100644 --- a/tests/ui/nll/issue-55511.stderr +++ b/tests/ui/nll/issue-55511.stderr @@ -1,6 +1,8 @@ error[E0597]: `a` does not live long enough --> $DIR/issue-55511.rs:13:28 | +LL | let a = 22; + | - binding `a` declared here LL | let b = Some(Cell::new(&a)); | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/nll/issue-57989.stderr b/tests/ui/nll/issue-57989.stderr index 31f40d8252ed6..d5effd6f346d1 100644 --- a/tests/ui/nll/issue-57989.stderr +++ b/tests/ui/nll/issue-57989.stderr @@ -13,9 +13,9 @@ error[E0506]: cannot assign to `*x` because it is borrowed --> $DIR/issue-57989.rs:5:5 | LL | let g = &x; - | -- borrow of `*x` occurs here + | -- `*x` is borrowed here LL | *x = 0; - | ^^^^^^ assignment to borrowed `*x` occurs here + | ^^^^^^ `*x` is assigned to here but it was already borrowed LL | LL | g; | - borrow later used here diff --git a/tests/ui/nll/issue-68550.stderr b/tests/ui/nll/issue-68550.stderr index e234ebb04e16a..851e3628748f2 100644 --- a/tests/ui/nll/issue-68550.stderr +++ b/tests/ui/nll/issue-68550.stderr @@ -2,7 +2,9 @@ error[E0597]: `x` does not live long enough --> $DIR/issue-68550.rs:12:20 | LL | fn run<'a, A>(x: A) - | -- lifetime `'a` defined here + | -- - binding `x` declared here + | | + | lifetime `'a` defined here ... LL | let _: &'a A = &x; | ----- ^^ borrowed value does not live long enough diff --git a/tests/ui/nll/issue-69114-static-mut-ty.stderr b/tests/ui/nll/issue-69114-static-mut-ty.stderr index 5e55cb502caa9..1b41230d7ba39 100644 --- a/tests/ui/nll/issue-69114-static-mut-ty.stderr +++ b/tests/ui/nll/issue-69114-static-mut-ty.stderr @@ -1,6 +1,9 @@ error[E0597]: `n` does not live long enough --> $DIR/issue-69114-static-mut-ty.rs:19:15 | +LL | let n = 42; + | - binding `n` declared here +LL | unsafe { LL | BAR = &n; | ------^^ | | | @@ -13,6 +16,9 @@ LL | } error[E0597]: `n` does not live long enough --> $DIR/issue-69114-static-mut-ty.rs:27:22 | +LL | let n = 42; + | - binding `n` declared here +LL | unsafe { LL | BAR_ELIDED = &n; | -------------^^ | | | diff --git a/tests/ui/nll/issue-69114-static-ty.stderr b/tests/ui/nll/issue-69114-static-ty.stderr index 0815e74b5537d..9215e850f7d8f 100644 --- a/tests/ui/nll/issue-69114-static-ty.stderr +++ b/tests/ui/nll/issue-69114-static-ty.stderr @@ -1,6 +1,8 @@ error[E0597]: `n` does not live long enough --> $DIR/issue-69114-static-ty.rs:7:9 | +LL | let n = 42; + | - binding `n` declared here LL | FOO(&n); | ----^^- | | | diff --git a/tests/ui/nll/loan_ends_mid_block_pair.stderr b/tests/ui/nll/loan_ends_mid_block_pair.stderr index eb8442b31d7c7..58e378ab02118 100644 --- a/tests/ui/nll/loan_ends_mid_block_pair.stderr +++ b/tests/ui/nll/loan_ends_mid_block_pair.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `data.0` because it is borrowed --> $DIR/loan_ends_mid_block_pair.rs:12:5 | LL | let c = &mut data.0; - | ----------- borrow of `data.0` occurs here + | ----------- `data.0` is borrowed here LL | capitalize(c); LL | data.0 = 'e'; - | ^^^^^^^^^^^^ assignment to borrowed `data.0` occurs here + | ^^^^^^^^^^^^ `data.0` is assigned to here but it was already borrowed ... LL | capitalize(c); | - borrow later used here diff --git a/tests/ui/nll/local-outlives-static-via-hrtb.stderr b/tests/ui/nll/local-outlives-static-via-hrtb.stderr index f5c10f3ddea0e..a6b3328b5a294 100644 --- a/tests/ui/nll/local-outlives-static-via-hrtb.stderr +++ b/tests/ui/nll/local-outlives-static-via-hrtb.stderr @@ -1,6 +1,8 @@ error[E0597]: `local` does not live long enough --> $DIR/local-outlives-static-via-hrtb.rs:24:28 | +LL | let local = 0; + | ----- binding `local` declared here LL | assert_static_via_hrtb(&local); | -----------------------^^^^^^- | | | @@ -19,6 +21,9 @@ LL | fn assert_static_via_hrtb(_: G) where for<'a> G: Outlives<'a> {} error[E0597]: `local` does not live long enough --> $DIR/local-outlives-static-via-hrtb.rs:25:45 | +LL | let local = 0; + | ----- binding `local` declared here +LL | assert_static_via_hrtb(&local); LL | assert_static_via_hrtb_with_assoc_type(&&local); | ----------------------------------------^^^^^^- | | | diff --git a/tests/ui/nll/match-cfg-fake-edges2.stderr b/tests/ui/nll/match-cfg-fake-edges2.stderr index c6d15a936d819..36f2cd0b85d1c 100644 --- a/tests/ui/nll/match-cfg-fake-edges2.stderr +++ b/tests/ui/nll/match-cfg-fake-edges2.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `y.1` because it was mutably borrowed --> $DIR/match-cfg-fake-edges2.rs:8:5 | LL | let r = &mut y.1; - | -------- borrow of `y.1` occurs here + | -------- `y.1` is borrowed here ... LL | match y { | ^^^^^^^ use of borrowed `y.1` diff --git a/tests/ui/nll/match-guards-always-borrow.stderr b/tests/ui/nll/match-guards-always-borrow.stderr index fa01d3a6fd1e0..afd853c403ee3 100644 --- a/tests/ui/nll/match-guards-always-borrow.stderr +++ b/tests/ui/nll/match-guards-always-borrow.stderr @@ -4,7 +4,7 @@ error[E0507]: cannot move out of `foo` in pattern guard LL | (|| { let bar = foo; bar.take() })(); | ^^ --- move occurs because `foo` has type `&mut Option<&i32>`, which does not implement the `Copy` trait | | - | move out of `foo` occurs here + | `foo` is moved here | = note: variables bound in patterns cannot be moved from until after the end of the pattern guard @@ -14,7 +14,7 @@ error[E0507]: cannot move out of `foo` in pattern guard LL | (|| { let bar = foo; bar.take() })(); | ^^ --- move occurs because `foo` has type `&mut Option<&i32>`, which does not implement the `Copy` trait | | - | move out of `foo` occurs here + | `foo` is moved here | = note: variables bound in patterns cannot be moved from until after the end of the pattern guard diff --git a/tests/ui/nll/match-guards-partially-borrow.stderr b/tests/ui/nll/match-guards-partially-borrow.stderr index 60b8dee71a863..7bdcbcb9c6ef6 100644 --- a/tests/ui/nll/match-guards-partially-borrow.stderr +++ b/tests/ui/nll/match-guards-partially-borrow.stderr @@ -74,9 +74,9 @@ error[E0506]: cannot assign to `t` because it is borrowed --> $DIR/match-guards-partially-borrow.rs:225:13 | LL | s if { - | - borrow of `t` occurs here + | - `t` is borrowed here LL | t = !t; - | ^^^^^^ assignment to borrowed `t` occurs here + | ^^^^^^ `t` is assigned to here but it was already borrowed LL | false LL | } => (), // What value should `s` have in the arm? | - borrow later used here @@ -85,9 +85,9 @@ error[E0506]: cannot assign to `t` because it is borrowed --> $DIR/match-guards-partially-borrow.rs:235:13 | LL | s if let Some(()) = { - | - borrow of `t` occurs here + | - `t` is borrowed here LL | t = !t; - | ^^^^^^ assignment to borrowed `t` occurs here + | ^^^^^^ `t` is assigned to here but it was already borrowed LL | None LL | } => (), // What value should `s` have in the arm? | - borrow later used here diff --git a/tests/ui/nll/match-on-borrowed.stderr b/tests/ui/nll/match-on-borrowed.stderr index 32666529f3f95..9273484565a19 100644 --- a/tests/ui/nll/match-on-borrowed.stderr +++ b/tests/ui/nll/match-on-borrowed.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `e` because it was mutably borrowed --> $DIR/match-on-borrowed.rs:47:11 | LL | E::V(ref mut x, _) => x, - | --------- borrow of `e.0` occurs here + | --------- `e.0` is borrowed here ... LL | match e { // Don't know that E uses a tag for its discriminant | ^ use of borrowed `e.0` @@ -14,7 +14,7 @@ error[E0503]: cannot use `*f` because it was mutably borrowed --> $DIR/match-on-borrowed.rs:61:11 | LL | E::V(ref mut x, _) => x, - | --------- borrow of `f.0` occurs here + | --------- `f.0` is borrowed here ... LL | match f { // Don't know that E uses a tag for its discriminant | ^ use of borrowed `f.0` @@ -26,7 +26,7 @@ error[E0503]: cannot use `t` because it was mutably borrowed --> $DIR/match-on-borrowed.rs:81:5 | LL | let x = &mut t; - | ------ borrow of `t` occurs here + | ------ `t` is borrowed here LL | match t { | ^^^^^^^ use of borrowed `t` ... diff --git a/tests/ui/nll/maybe-initialized-drop-implicit-fragment-drop.stderr b/tests/ui/nll/maybe-initialized-drop-implicit-fragment-drop.stderr index 80e297807465d..55646b9dca986 100644 --- a/tests/ui/nll/maybe-initialized-drop-implicit-fragment-drop.stderr +++ b/tests/ui/nll/maybe-initialized-drop-implicit-fragment-drop.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/maybe-initialized-drop-implicit-fragment-drop.rs:17:5 | LL | let wrap = Wrap { p: &mut x }; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here ... LL | x = 1; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | // FIXME ^ Should not error in the future with implicit dtors, only manually implemented ones LL | } | - borrow might be used here, when `foo` is dropped and runs the destructor for type `Foo<'_>` diff --git a/tests/ui/nll/maybe-initialized-drop-with-fragment.stderr b/tests/ui/nll/maybe-initialized-drop-with-fragment.stderr index 14074472eaf88..c89f94a7894f0 100644 --- a/tests/ui/nll/maybe-initialized-drop-with-fragment.stderr +++ b/tests/ui/nll/maybe-initialized-drop-with-fragment.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/maybe-initialized-drop-with-fragment.rs:19:5 | LL | let wrap = Wrap { p: &mut x }; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here ... LL | x = 1; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | } | - borrow might be used here, when `foo` is dropped and runs the destructor for type `Foo<'_>` diff --git a/tests/ui/nll/maybe-initialized-drop-with-uninitialized-fragments.stderr b/tests/ui/nll/maybe-initialized-drop-with-uninitialized-fragments.stderr index 91c0afc1dbaa1..90db13bc57849 100644 --- a/tests/ui/nll/maybe-initialized-drop-with-uninitialized-fragments.stderr +++ b/tests/ui/nll/maybe-initialized-drop-with-uninitialized-fragments.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/maybe-initialized-drop-with-uninitialized-fragments.rs:20:5 | LL | let wrap = Wrap { p: &mut x }; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here ... LL | x = 1; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | // FIXME ^ This currently errors and it should not. LL | } | - borrow might be used here, when `foo` is dropped and runs the destructor for type `Foo<'_>` diff --git a/tests/ui/nll/maybe-initialized-drop.stderr b/tests/ui/nll/maybe-initialized-drop.stderr index 9825ba4611b7d..15a53a09af8c2 100644 --- a/tests/ui/nll/maybe-initialized-drop.stderr +++ b/tests/ui/nll/maybe-initialized-drop.stderr @@ -2,9 +2,9 @@ error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/maybe-initialized-drop.rs:14:5 | LL | let wrap = Wrap { p: &mut x }; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | x = 1; - | ^^^^^ assignment to borrowed `x` occurs here + | ^^^^^ `x` is assigned to here but it was already borrowed LL | } | - borrow might be used here, when `wrap` is dropped and runs the `Drop` code for type `Wrap` diff --git a/tests/ui/nll/polonius/polonius-smoke-test.stderr b/tests/ui/nll/polonius/polonius-smoke-test.stderr index fa1a6a9c95786..789d202f73a7b 100644 --- a/tests/ui/nll/polonius/polonius-smoke-test.stderr +++ b/tests/ui/nll/polonius/polonius-smoke-test.stderr @@ -8,7 +8,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/polonius-smoke-test.rs:12:13 | LL | let y = &mut x; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | let z = x; | ^ use of borrowed `x` LL | let w = y; diff --git a/tests/ui/nll/promoted-bounds.stderr b/tests/ui/nll/promoted-bounds.stderr index df347f4e7f0fe..d111256b8454f 100644 --- a/tests/ui/nll/promoted-bounds.stderr +++ b/tests/ui/nll/promoted-bounds.stderr @@ -4,6 +4,7 @@ error[E0597]: `l` does not live long enough LL | let ptr = { | --- borrow later stored here LL | let l = 3; + | - binding `l` declared here LL | let b = &l; | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/nll/reference-carried-through-struct-field.stderr b/tests/ui/nll/reference-carried-through-struct-field.stderr index 56d878e43033b..5672b9cd7e9cc 100644 --- a/tests/ui/nll/reference-carried-through-struct-field.stderr +++ b/tests/ui/nll/reference-carried-through-struct-field.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/reference-carried-through-struct-field.rs:6:5 | LL | let wrapper = Wrap { w: &mut x }; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | x += 1; | ^^^^^^ use of borrowed `x` LL | *wrapper.w += 1; diff --git a/tests/ui/nll/relate_tys/var-appears-twice.stderr b/tests/ui/nll/relate_tys/var-appears-twice.stderr index d032ce6f2132c..ff6ea598ff46f 100644 --- a/tests/ui/nll/relate_tys/var-appears-twice.stderr +++ b/tests/ui/nll/relate_tys/var-appears-twice.stderr @@ -1,6 +1,9 @@ error[E0597]: `b` does not live long enough --> $DIR/var-appears-twice.rs:20:38 | +LL | let b = 44; + | - binding `b` declared here +... LL | let x: DoubleCell<_> = make_cell(&b); | ------------- ^^ borrowed value does not live long enough | | diff --git a/tests/ui/nll/user-annotations/adt-brace-enums.stderr b/tests/ui/nll/user-annotations/adt-brace-enums.stderr index 253e382511045..9e94fd5a7826e 100644 --- a/tests/ui/nll/user-annotations/adt-brace-enums.stderr +++ b/tests/ui/nll/user-annotations/adt-brace-enums.stderr @@ -1,6 +1,8 @@ error[E0597]: `c` does not live long enough --> $DIR/adt-brace-enums.rs:25:48 | +LL | let c = 66; + | - binding `c` declared here LL | SomeEnum::SomeVariant::<&'static u32> { t: &c }; | ^^ | | @@ -15,6 +17,7 @@ error[E0597]: `c` does not live long enough LL | fn annot_reference_named_lifetime<'a>(_d: &'a u32) { | -- lifetime `'a` defined here LL | let c = 66; + | - binding `c` declared here LL | SomeEnum::SomeVariant::<&'a u32> { t: &c }; | ^^ | | diff --git a/tests/ui/nll/user-annotations/adt-brace-structs.stderr b/tests/ui/nll/user-annotations/adt-brace-structs.stderr index 8b9d1705df6ad..cbb7f6a55a989 100644 --- a/tests/ui/nll/user-annotations/adt-brace-structs.stderr +++ b/tests/ui/nll/user-annotations/adt-brace-structs.stderr @@ -1,6 +1,8 @@ error[E0597]: `c` does not live long enough --> $DIR/adt-brace-structs.rs:23:37 | +LL | let c = 66; + | - binding `c` declared here LL | SomeStruct::<&'static u32> { t: &c }; | ^^ | | @@ -15,6 +17,7 @@ error[E0597]: `c` does not live long enough LL | fn annot_reference_named_lifetime<'a>(_d: &'a u32) { | -- lifetime `'a` defined here LL | let c = 66; + | - binding `c` declared here LL | SomeStruct::<&'a u32> { t: &c }; | ^^ | | diff --git a/tests/ui/nll/user-annotations/adt-nullary-enums.stderr b/tests/ui/nll/user-annotations/adt-nullary-enums.stderr index 3326fa521fc9c..bca85a90d1908 100644 --- a/tests/ui/nll/user-annotations/adt-nullary-enums.stderr +++ b/tests/ui/nll/user-annotations/adt-nullary-enums.stderr @@ -1,6 +1,8 @@ error[E0597]: `c` does not live long enough --> $DIR/adt-nullary-enums.rs:33:41 | +LL | let c = 66; + | - binding `c` declared here LL | / combine( LL | | SomeEnum::SomeVariant(Cell::new(&c)), | | ^^ borrowed value does not live long enough @@ -15,7 +17,9 @@ error[E0597]: `c` does not live long enough | LL | fn annot_reference_named_lifetime<'a>(_d: &'a u32) { | -- lifetime `'a` defined here -... +LL | let c = 66; + | - binding `c` declared here +LL | combine( LL | SomeEnum::SomeVariant(Cell::new(&c)), | ----------^^- | | | diff --git a/tests/ui/nll/user-annotations/adt-tuple-enums.stderr b/tests/ui/nll/user-annotations/adt-tuple-enums.stderr index 2fa7042631d21..d2d85ec2b9b0f 100644 --- a/tests/ui/nll/user-annotations/adt-tuple-enums.stderr +++ b/tests/ui/nll/user-annotations/adt-tuple-enums.stderr @@ -1,6 +1,8 @@ error[E0597]: `c` does not live long enough --> $DIR/adt-tuple-enums.rs:28:43 | +LL | let c = 66; + | - binding `c` declared here LL | SomeEnum::SomeVariant::<&'static u32>(&c); | ^^ | | @@ -15,6 +17,7 @@ error[E0597]: `c` does not live long enough LL | fn annot_reference_named_lifetime<'a>(_d: &'a u32) { | -- lifetime `'a` defined here LL | let c = 66; + | - binding `c` declared here LL | SomeEnum::SomeVariant::<&'a u32>(&c); | ^^ | | diff --git a/tests/ui/nll/user-annotations/adt-tuple-struct-calls.stderr b/tests/ui/nll/user-annotations/adt-tuple-struct-calls.stderr index 9664fb9f54831..b7bc2a10b7040 100644 --- a/tests/ui/nll/user-annotations/adt-tuple-struct-calls.stderr +++ b/tests/ui/nll/user-annotations/adt-tuple-struct-calls.stderr @@ -1,6 +1,9 @@ error[E0597]: `c` does not live long enough --> $DIR/adt-tuple-struct-calls.rs:27:7 | +LL | let c = 66; + | - binding `c` declared here +LL | let f = SomeStruct::<&'static u32>; LL | f(&c); | --^^- | | | @@ -14,7 +17,9 @@ error[E0597]: `c` does not live long enough | LL | fn annot_reference_named_lifetime<'a>(_d: &'a u32) { | -- lifetime `'a` defined here -... +LL | let c = 66; + | - binding `c` declared here +LL | let f = SomeStruct::<&'a u32>; LL | f(&c); | --^^- | | | diff --git a/tests/ui/nll/user-annotations/adt-tuple-struct.stderr b/tests/ui/nll/user-annotations/adt-tuple-struct.stderr index 76b5252258c7b..97d39da265fe3 100644 --- a/tests/ui/nll/user-annotations/adt-tuple-struct.stderr +++ b/tests/ui/nll/user-annotations/adt-tuple-struct.stderr @@ -1,6 +1,8 @@ error[E0597]: `c` does not live long enough --> $DIR/adt-tuple-struct.rs:23:32 | +LL | let c = 66; + | - binding `c` declared here LL | SomeStruct::<&'static u32>(&c); | ^^ | | @@ -15,6 +17,7 @@ error[E0597]: `c` does not live long enough LL | fn annot_reference_named_lifetime<'a>(_d: &'a u32) { | -- lifetime `'a` defined here LL | let c = 66; + | - binding `c` declared here LL | SomeStruct::<&'a u32>(&c); | ^^ | | diff --git a/tests/ui/nll/user-annotations/cast_static_lifetime.stderr b/tests/ui/nll/user-annotations/cast_static_lifetime.stderr index 4599d04e7e230..3b9363c41f20f 100644 --- a/tests/ui/nll/user-annotations/cast_static_lifetime.stderr +++ b/tests/ui/nll/user-annotations/cast_static_lifetime.stderr @@ -1,6 +1,8 @@ error[E0597]: `x` does not live long enough --> $DIR/cast_static_lifetime.rs:5:19 | +LL | let x = 22_u32; + | - binding `x` declared here LL | let y: &u32 = (&x) as &'static u32; | ^^^^---------------- | | diff --git a/tests/ui/nll/user-annotations/constant-in-expr-inherent-2.stderr b/tests/ui/nll/user-annotations/constant-in-expr-inherent-2.stderr index 12065a85aa4a0..f164255ef305f 100644 --- a/tests/ui/nll/user-annotations/constant-in-expr-inherent-2.stderr +++ b/tests/ui/nll/user-annotations/constant-in-expr-inherent-2.stderr @@ -1,6 +1,8 @@ error[E0597]: `x` does not live long enough --> $DIR/constant-in-expr-inherent-2.rs:23:9 | +LL | let x = (); + | - binding `x` declared here LL | FUN(&x); | ----^^- | | | @@ -13,6 +15,9 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/constant-in-expr-inherent-2.rs:24:23 | +LL | let x = (); + | - binding `x` declared here +LL | FUN(&x); LL | A::ASSOCIATED_FUN(&x); | ------------------^^- | | | @@ -25,6 +30,9 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/constant-in-expr-inherent-2.rs:25:28 | +LL | let x = (); + | - binding `x` declared here +... LL | B::ALSO_ASSOCIATED_FUN(&x); | -----------------------^^- | | | @@ -37,6 +45,9 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/constant-in-expr-inherent-2.rs:26:31 | +LL | let x = (); + | - binding `x` declared here +... LL | <_>::TRAIT_ASSOCIATED_FUN(&x); | --------------------------^^- | | | diff --git a/tests/ui/nll/user-annotations/fns.stderr b/tests/ui/nll/user-annotations/fns.stderr index e0640da39e2b6..8b53e138d9bd0 100644 --- a/tests/ui/nll/user-annotations/fns.stderr +++ b/tests/ui/nll/user-annotations/fns.stderr @@ -1,6 +1,8 @@ error[E0597]: `c` does not live long enough --> $DIR/fns.rs:23:29 | +LL | let c = 66; + | - binding `c` declared here LL | some_fn::<&'static u32>(&c); | ------------------------^^- | | | @@ -15,6 +17,7 @@ error[E0597]: `c` does not live long enough LL | fn annot_reference_named_lifetime<'a>(_d: &'a u32) { | -- lifetime `'a` defined here LL | let c = 66; + | - binding `c` declared here LL | some_fn::<&'a u32>(&c); | -------------------^^- | | | diff --git a/tests/ui/nll/user-annotations/method-call.stderr b/tests/ui/nll/user-annotations/method-call.stderr index 10447e45a6d42..3803cbf776b67 100644 --- a/tests/ui/nll/user-annotations/method-call.stderr +++ b/tests/ui/nll/user-annotations/method-call.stderr @@ -1,6 +1,8 @@ error[E0597]: `c` does not live long enough --> $DIR/method-call.rs:36:34 | +LL | let c = 66; + | - binding `c` declared here LL | a.method::<&'static u32>(b, &c); | -----------------------------^^- | | | @@ -15,6 +17,8 @@ error[E0597]: `c` does not live long enough LL | fn annot_reference_named_lifetime<'a>(_d: &'a u32) { | -- lifetime `'a` defined here ... +LL | let c = 66; + | - binding `c` declared here LL | a.method::<&'a u32>(b, &c); | ------------------------^^- | | | diff --git a/tests/ui/nll/user-annotations/method-ufcs-1.stderr b/tests/ui/nll/user-annotations/method-ufcs-1.stderr index 962ddfd2bd151..c7c08c948abdb 100644 --- a/tests/ui/nll/user-annotations/method-ufcs-1.stderr +++ b/tests/ui/nll/user-annotations/method-ufcs-1.stderr @@ -1,6 +1,9 @@ error[E0597]: `a` does not live long enough --> $DIR/method-ufcs-1.rs:30:7 | +LL | let a = 22; + | - binding `a` declared here +... LL | x(&a, b, c); | --^^------- | | | @@ -14,6 +17,8 @@ error[E0597]: `a` does not live long enough | LL | fn annot_reference_named_lifetime<'a>(_d: &'a u32) { | -- lifetime `'a` defined here +LL | let a = 22; + | - binding `a` declared here ... LL | <&'a u32 as Bazoom<_>>::method(&a, b, c); | -------------------------------^^------- diff --git a/tests/ui/nll/user-annotations/method-ufcs-2.stderr b/tests/ui/nll/user-annotations/method-ufcs-2.stderr index 63d59905e1c38..b7861a3bd069f 100644 --- a/tests/ui/nll/user-annotations/method-ufcs-2.stderr +++ b/tests/ui/nll/user-annotations/method-ufcs-2.stderr @@ -1,6 +1,9 @@ error[E0597]: `a` does not live long enough --> $DIR/method-ufcs-2.rs:30:7 | +LL | let a = 22; + | - binding `a` declared here +... LL | x(&a, b, c); | --^^------- | | | @@ -14,7 +17,10 @@ error[E0597]: `b` does not live long enough | LL | fn annot_reference_named_lifetime<'a>(_d: &'a u32) { | -- lifetime `'a` defined here -... +LL | let a = 22; +LL | let b = 44; + | - binding `b` declared here +LL | let c = 66; LL | <_ as Bazoom<&'a u32>>::method(a, &b, c); | ----------------------------------^^---- | | | diff --git a/tests/ui/nll/user-annotations/method-ufcs-3.stderr b/tests/ui/nll/user-annotations/method-ufcs-3.stderr index e7851833e93b2..8cb995a03ce2f 100644 --- a/tests/ui/nll/user-annotations/method-ufcs-3.stderr +++ b/tests/ui/nll/user-annotations/method-ufcs-3.stderr @@ -1,6 +1,8 @@ error[E0597]: `c` does not live long enough --> $DIR/method-ufcs-3.rs:36:53 | +LL | let c = 66; + | - binding `c` declared here LL | <_ as Bazoom<_>>::method::<&'static u32>(&a, b, &c); | ------------------------------------------------^^- | | | @@ -15,6 +17,8 @@ error[E0597]: `c` does not live long enough LL | fn annot_reference_named_lifetime<'a>(_d: &'a u32) { | -- lifetime `'a` defined here ... +LL | let c = 66; + | - binding `c` declared here LL | <_ as Bazoom<_>>::method::<&'a u32>(&a, b, &c); | -------------------------------------------^^- | | | diff --git a/tests/ui/nll/user-annotations/method-ufcs-inherent-1.stderr b/tests/ui/nll/user-annotations/method-ufcs-inherent-1.stderr index 94861babd6f32..fb26b8d09e179 100644 --- a/tests/ui/nll/user-annotations/method-ufcs-inherent-1.stderr +++ b/tests/ui/nll/user-annotations/method-ufcs-inherent-1.stderr @@ -4,6 +4,7 @@ error[E0597]: `v` does not live long enough LL | fn foo<'a>() { | -- lifetime `'a` defined here LL | let v = 22; + | - binding `v` declared here LL | let x = A::<'a>::new(&v, 22); | -------------^^----- | | | diff --git a/tests/ui/nll/user-annotations/method-ufcs-inherent-2.stderr b/tests/ui/nll/user-annotations/method-ufcs-inherent-2.stderr index 06f20d9b23559..03b97447e1aa0 100644 --- a/tests/ui/nll/user-annotations/method-ufcs-inherent-2.stderr +++ b/tests/ui/nll/user-annotations/method-ufcs-inherent-2.stderr @@ -4,6 +4,7 @@ error[E0597]: `v` does not live long enough LL | fn foo<'a>() { | -- lifetime `'a` defined here LL | let v = 22; + | - binding `v` declared here LL | let x = A::<'a>::new::<&'a u32>(&v, &v); | ------------------------^^----- | | | @@ -19,6 +20,7 @@ error[E0597]: `v` does not live long enough LL | fn foo<'a>() { | -- lifetime `'a` defined here LL | let v = 22; + | - binding `v` declared here LL | let x = A::<'a>::new::<&'a u32>(&v, &v); | ----------------------------^^- | | | diff --git a/tests/ui/nll/user-annotations/method-ufcs-inherent-3.stderr b/tests/ui/nll/user-annotations/method-ufcs-inherent-3.stderr index 4ad61dc81c493..69dd1d1aaae28 100644 --- a/tests/ui/nll/user-annotations/method-ufcs-inherent-3.stderr +++ b/tests/ui/nll/user-annotations/method-ufcs-inherent-3.stderr @@ -4,6 +4,7 @@ error[E0597]: `v` does not live long enough LL | fn foo<'a>() { | -- lifetime `'a` defined here LL | let v = 22; + | - binding `v` declared here LL | let x = >::new(&v, 22); | -------------^^----- | | | diff --git a/tests/ui/nll/user-annotations/method-ufcs-inherent-4.stderr b/tests/ui/nll/user-annotations/method-ufcs-inherent-4.stderr index 0f83e99cdfb92..66d82bb49dc68 100644 --- a/tests/ui/nll/user-annotations/method-ufcs-inherent-4.stderr +++ b/tests/ui/nll/user-annotations/method-ufcs-inherent-4.stderr @@ -4,6 +4,7 @@ error[E0597]: `v` does not live long enough LL | fn foo<'a>() { | -- lifetime `'a` defined here LL | let v = 22; + | - binding `v` declared here LL | let x = >::new::<&'a u32>(&v, &v); | ------------------------^^----- | | | @@ -19,6 +20,7 @@ error[E0597]: `v` does not live long enough LL | fn foo<'a>() { | -- lifetime `'a` defined here LL | let v = 22; + | - binding `v` declared here LL | let x = >::new::<&'a u32>(&v, &v); | ----------------------------^^- | | | diff --git a/tests/ui/nll/user-annotations/normalization.stderr b/tests/ui/nll/user-annotations/normalization.stderr index 975cb4b66d91d..acc3a1800f4fd 100644 --- a/tests/ui/nll/user-annotations/normalization.stderr +++ b/tests/ui/nll/user-annotations/normalization.stderr @@ -1,6 +1,8 @@ error[E0597]: `a` does not live long enough --> $DIR/normalization.rs:10:31 | +LL | let a = 22; + | - binding `a` declared here LL | let _: <() as Foo>::Out = &a; | ---------------- ^^ borrowed value does not live long enough | | @@ -12,6 +14,8 @@ LL | } error[E0597]: `a` does not live long enough --> $DIR/normalization.rs:13:40 | +LL | let a = 22; + | - binding `a` declared here LL | let _: <&'static () as Foo>::Out = &a; | ------------------------- ^^ borrowed value does not live long enough | | diff --git a/tests/ui/nll/user-annotations/pattern_substs_on_brace_enum_variant.stderr b/tests/ui/nll/user-annotations/pattern_substs_on_brace_enum_variant.stderr index a97e7a9fd46fc..3e7969e117934 100644 --- a/tests/ui/nll/user-annotations/pattern_substs_on_brace_enum_variant.stderr +++ b/tests/ui/nll/user-annotations/pattern_substs_on_brace_enum_variant.stderr @@ -1,6 +1,8 @@ error[E0597]: `y` does not live long enough --> $DIR/pattern_substs_on_brace_enum_variant.rs:7:33 | +LL | let y = 22; + | - binding `y` declared here LL | let foo = Foo::Bar { field: &y }; | ^^ borrowed value does not live long enough LL | @@ -12,6 +14,8 @@ LL | } error[E0597]: `y` does not live long enough --> $DIR/pattern_substs_on_brace_enum_variant.rs:14:33 | +LL | let y = 22; + | - binding `y` declared here LL | let foo = Foo::Bar { field: &y }; | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/nll/user-annotations/pattern_substs_on_brace_struct.stderr b/tests/ui/nll/user-annotations/pattern_substs_on_brace_struct.stderr index 408d7c2a5e2a5..89a1e9545e8af 100644 --- a/tests/ui/nll/user-annotations/pattern_substs_on_brace_struct.stderr +++ b/tests/ui/nll/user-annotations/pattern_substs_on_brace_struct.stderr @@ -1,6 +1,8 @@ error[E0597]: `y` does not live long enough --> $DIR/pattern_substs_on_brace_struct.rs:5:28 | +LL | let y = 22; + | - binding `y` declared here LL | let foo = Foo { field: &y }; | ^^ borrowed value does not live long enough LL | @@ -12,6 +14,8 @@ LL | } error[E0597]: `y` does not live long enough --> $DIR/pattern_substs_on_brace_struct.rs:12:28 | +LL | let y = 22; + | - binding `y` declared here LL | let foo = Foo { field: &y }; | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/nll/user-annotations/pattern_substs_on_tuple_enum_variant.stderr b/tests/ui/nll/user-annotations/pattern_substs_on_tuple_enum_variant.stderr index 920c906f63a58..8efeecc77098a 100644 --- a/tests/ui/nll/user-annotations/pattern_substs_on_tuple_enum_variant.stderr +++ b/tests/ui/nll/user-annotations/pattern_substs_on_tuple_enum_variant.stderr @@ -1,6 +1,8 @@ error[E0597]: `y` does not live long enough --> $DIR/pattern_substs_on_tuple_enum_variant.rs:7:24 | +LL | let y = 22; + | - binding `y` declared here LL | let foo = Foo::Bar(&y); | ^^ borrowed value does not live long enough LL | @@ -12,6 +14,8 @@ LL | } error[E0597]: `y` does not live long enough --> $DIR/pattern_substs_on_tuple_enum_variant.rs:14:24 | +LL | let y = 22; + | - binding `y` declared here LL | let foo = Foo::Bar(&y); | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/nll/user-annotations/pattern_substs_on_tuple_struct.stderr b/tests/ui/nll/user-annotations/pattern_substs_on_tuple_struct.stderr index 3f01638d84757..d7f1dac88a618 100644 --- a/tests/ui/nll/user-annotations/pattern_substs_on_tuple_struct.stderr +++ b/tests/ui/nll/user-annotations/pattern_substs_on_tuple_struct.stderr @@ -1,6 +1,8 @@ error[E0597]: `y` does not live long enough --> $DIR/pattern_substs_on_tuple_struct.rs:5:19 | +LL | let y = 22; + | - binding `y` declared here LL | let foo = Foo(&y); | ^^ borrowed value does not live long enough LL | @@ -12,6 +14,8 @@ LL | } error[E0597]: `y` does not live long enough --> $DIR/pattern_substs_on_tuple_struct.rs:12:19 | +LL | let y = 22; + | - binding `y` declared here LL | let foo = Foo(&y); | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/nll/user-annotations/patterns.stderr b/tests/ui/nll/user-annotations/patterns.stderr index de6f8f80fe252..8bb714f1d0cdc 100644 --- a/tests/ui/nll/user-annotations/patterns.stderr +++ b/tests/ui/nll/user-annotations/patterns.stderr @@ -1,6 +1,8 @@ error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:6:9 | +LL | let x = 22; + | - binding `x` declared here LL | let y: &'static u32; | ------------ type annotation requires that `x` is borrowed for `'static` LL | y = &x; @@ -11,6 +13,8 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:14:9 | +LL | let x = 22; + | - binding `x` declared here LL | let (y, z): (&'static u32, &'static u32); | ---------------------------- type annotation requires that `x` is borrowed for `'static` LL | y = &x; @@ -21,6 +25,8 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:20:13 | +LL | let x = 22; + | - binding `x` declared here LL | let y = &x; | ^^ borrowed value does not live long enough LL | let ref z: &'static u32 = y; @@ -32,6 +38,8 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:39:9 | +LL | let x = 22; + | - binding `x` declared here LL | let Single { value: y }: Single<&'static u32>; | -------------------- type annotation requires that `x` is borrowed for `'static` LL | y = &x; @@ -42,6 +50,8 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:51:10 | +LL | let x = 22; + | - binding `x` declared here LL | let Single2 { value: mut _y }: Single2; | ------------------ type annotation requires that `x` is borrowed for `'static` LL | _y = &x; @@ -52,6 +62,8 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:56:27 | +LL | let x = 22; + | - binding `x` declared here LL | let y: &'static u32 = &x; | ------------ ^^ borrowed value does not live long enough | | @@ -62,6 +74,8 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:61:27 | +LL | let x = 22; + | - binding `x` declared here LL | let _: &'static u32 = &x; | ------------ ^^ borrowed value does not live long enough | | @@ -100,6 +114,8 @@ LL | let (_a, b): (Vec<&'static String>, _) = (vec![&String::new()], 44); error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:75:40 | +LL | let x = 22; + | - binding `x` declared here LL | let (_, _): (&'static u32, u32) = (&x, 44); | ------------------- ^^ borrowed value does not live long enough | | @@ -110,6 +126,8 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:80:40 | +LL | let x = 22; + | - binding `x` declared here LL | let (y, _): (&'static u32, u32) = (&x, 44); | ------------------- ^^ borrowed value does not live long enough | | @@ -120,6 +138,8 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:85:69 | +LL | let x = 22; + | - binding `x` declared here LL | let Single { value: y }: Single<&'static u32> = Single { value: &x }; | -------------------- ^^ borrowed value does not live long enough | | @@ -130,6 +150,8 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:90:69 | +LL | let x = 22; + | - binding `x` declared here LL | let Single { value: _ }: Single<&'static u32> = Single { value: &x }; | -------------------- ^^ borrowed value does not live long enough | | @@ -140,6 +162,8 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/patterns.rs:98:17 | +LL | let x = 22; + | - binding `x` declared here LL | let Double { value1: _, value2: _ }: Double<&'static u32> = Double { | -------------------- type annotation requires that `x` is borrowed for `'static` LL | value1: &x, diff --git a/tests/ui/nll/user-annotations/promoted-annotation.stderr b/tests/ui/nll/user-annotations/promoted-annotation.stderr index cb99a6a369d0b..132a00ba41581 100644 --- a/tests/ui/nll/user-annotations/promoted-annotation.stderr +++ b/tests/ui/nll/user-annotations/promoted-annotation.stderr @@ -4,6 +4,7 @@ error[E0597]: `x` does not live long enough LL | fn foo<'a>() { | -- lifetime `'a` defined here LL | let x = 0; + | - binding `x` declared here LL | let f = &drop::<&'a i32>; | ---------------- assignment requires that `x` is borrowed for `'a` LL | f(&x); diff --git a/tests/ui/nll/user-annotations/type_ascription_static_lifetime.stderr b/tests/ui/nll/user-annotations/type_ascription_static_lifetime.stderr index ccbf3c1d927c6..766877f8835c4 100644 --- a/tests/ui/nll/user-annotations/type_ascription_static_lifetime.stderr +++ b/tests/ui/nll/user-annotations/type_ascription_static_lifetime.stderr @@ -1,6 +1,8 @@ error[E0597]: `x` does not live long enough --> $DIR/type_ascription_static_lifetime.rs:6:33 | +LL | let x = 22_u32; + | - binding `x` declared here LL | let y: &u32 = type_ascribe!(&x, &'static u32); | --------------^^--------------- | | | diff --git a/tests/ui/pattern/move-ref-patterns/borrowck-move-ref-pattern.stderr b/tests/ui/pattern/move-ref-patterns/borrowck-move-ref-pattern.stderr index 1b93267b39771..c7c7c074f7cd0 100644 --- a/tests/ui/pattern/move-ref-patterns/borrowck-move-ref-pattern.stderr +++ b/tests/ui/pattern/move-ref-patterns/borrowck-move-ref-pattern.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `arr[..]` because it is borrowed --> $DIR/borrowck-move-ref-pattern.rs:8:24 | +LL | let mut arr = [U, U, U, U, U]; + | ------- binding `arr` declared here LL | let hold_all = &arr; | ---- borrow of `arr` occurs here LL | let [ref _x0_hold, _x1, ref xs_hold @ ..] = arr; diff --git a/tests/ui/regions/do-not-suggest-adding-bound-to-opaque-type.stderr b/tests/ui/regions/do-not-suggest-adding-bound-to-opaque-type.stderr index 6ea238f302f3f..d76a83b025809 100644 --- a/tests/ui/regions/do-not-suggest-adding-bound-to-opaque-type.stderr +++ b/tests/ui/regions/do-not-suggest-adding-bound-to-opaque-type.stderr @@ -1,6 +1,8 @@ error[E0597]: `x` does not live long enough --> $DIR/do-not-suggest-adding-bound-to-opaque-type.rs:9:7 | +LL | let x = (); + | - binding `x` declared here LL | S(&x) | --^^- | | | diff --git a/tests/ui/regions/regions-addr-of-arg.stderr b/tests/ui/regions/regions-addr-of-arg.stderr index e77289287e536..99060a9c7f59f 100644 --- a/tests/ui/regions/regions-addr-of-arg.stderr +++ b/tests/ui/regions/regions-addr-of-arg.stderr @@ -1,6 +1,8 @@ error[E0597]: `a` does not live long enough --> $DIR/regions-addr-of-arg.rs:5:30 | +LL | fn foo(a: isize) { + | - binding `a` declared here LL | let _p: &'static isize = &a; | -------------- ^^ borrowed value does not live long enough | | diff --git a/tests/ui/regions/regions-free-region-ordering-caller1.stderr b/tests/ui/regions/regions-free-region-ordering-caller1.stderr index 8ef7e22536bf9..c83cfc1c987b6 100644 --- a/tests/ui/regions/regions-free-region-ordering-caller1.stderr +++ b/tests/ui/regions/regions-free-region-ordering-caller1.stderr @@ -18,6 +18,8 @@ error[E0597]: `y` does not live long enough LL | fn call1<'a>(x: &'a usize) { | -- lifetime `'a` defined here ... +LL | let y: usize = 3; + | - binding `y` declared here LL | let z: &'a & usize = &(&y); | ----------- ^^^^ borrowed value does not live long enough | | diff --git a/tests/ui/regions/regions-infer-proc-static-upvar.stderr b/tests/ui/regions/regions-infer-proc-static-upvar.stderr index 803d0d7449108..c8a33bbc52236 100644 --- a/tests/ui/regions/regions-infer-proc-static-upvar.stderr +++ b/tests/ui/regions/regions-infer-proc-static-upvar.stderr @@ -1,6 +1,8 @@ error[E0597]: `x` does not live long enough --> $DIR/regions-infer-proc-static-upvar.rs:10:13 | +LL | let x = 3; + | - binding `x` declared here LL | let y = &x; | ^^ borrowed value does not live long enough LL | / foo(move|| { diff --git a/tests/ui/regions/regions-nested-fns.stderr b/tests/ui/regions/regions-nested-fns.stderr index bb2740310f6a1..ee43f9fa5724d 100644 --- a/tests/ui/regions/regions-nested-fns.stderr +++ b/tests/ui/regions/regions-nested-fns.stderr @@ -13,6 +13,8 @@ LL | ay = z; error[E0597]: `y` does not live long enough --> $DIR/regions-nested-fns.rs:5:18 | +LL | let y = 3; + | - binding `y` declared here LL | let mut ay = &y; | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/regions/regions-pattern-typing-issue-19552.stderr b/tests/ui/regions/regions-pattern-typing-issue-19552.stderr index f77d94a24b88f..18aec29ad0b74 100644 --- a/tests/ui/regions/regions-pattern-typing-issue-19552.stderr +++ b/tests/ui/regions/regions-pattern-typing-issue-19552.stderr @@ -1,6 +1,8 @@ error[E0597]: `line` does not live long enough --> $DIR/regions-pattern-typing-issue-19552.rs:5:14 | +LL | let line = String::new(); + | ---- binding `line` declared here LL | match [&*line] { | ^^^^ borrowed value does not live long enough LL | [ word ] => { assert_static(word); } diff --git a/tests/ui/regions/regions-pattern-typing-issue-19997.stderr b/tests/ui/regions/regions-pattern-typing-issue-19997.stderr index ae60e3c0d5d67..0abe77a86977f 100644 --- a/tests/ui/regions/regions-pattern-typing-issue-19997.stderr +++ b/tests/ui/regions/regions-pattern-typing-issue-19997.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `a1` because it is borrowed --> $DIR/regions-pattern-typing-issue-19997.rs:7:13 | LL | match (&a1,) { - | --- borrow of `a1` occurs here + | --- `a1` is borrowed here LL | (&ref b0,) => { LL | a1 = &f; - | ^^^^^^^ assignment to borrowed `a1` occurs here + | ^^^^^^^ `a1` is assigned to here but it was already borrowed LL | drop(b0); | -- borrow later used here diff --git a/tests/ui/rfc-2008-non-exhaustive/borrowck-non-exhaustive.stderr b/tests/ui/rfc-2008-non-exhaustive/borrowck-non-exhaustive.stderr index de730ce1030f2..ad84ebe3a504c 100644 --- a/tests/ui/rfc-2008-non-exhaustive/borrowck-non-exhaustive.stderr +++ b/tests/ui/rfc-2008-non-exhaustive/borrowck-non-exhaustive.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/borrowck-non-exhaustive.rs:12:11 | LL | let y = &mut x; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | match x { | ^ use of borrowed `x` ... diff --git a/tests/ui/rfcs/rfc-2528-type-changing-struct-update/lifetime-update.stderr b/tests/ui/rfcs/rfc-2528-type-changing-struct-update/lifetime-update.stderr index 5f93ad6e0279e..1c26eb8803d7f 100644 --- a/tests/ui/rfcs/rfc-2528-type-changing-struct-update/lifetime-update.stderr +++ b/tests/ui/rfcs/rfc-2528-type-changing-struct-update/lifetime-update.stderr @@ -1,6 +1,9 @@ error[E0597]: `s` does not live long enough --> $DIR/lifetime-update.rs:20:17 | +LL | let s = String::from("hello"); + | - binding `s` declared here +... LL | lt_str: &s, | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/self/issue-61882-2.stderr b/tests/ui/self/issue-61882-2.stderr index 0b8e134c9662e..6faa4477d8c5d 100644 --- a/tests/ui/self/issue-61882-2.stderr +++ b/tests/ui/self/issue-61882-2.stderr @@ -1,6 +1,8 @@ error[E0597]: `x` does not live long enough --> $DIR/issue-61882-2.rs:6:14 | +LL | let x = 0; + | - binding `x` declared here LL | Self(&x); | ^^ | | diff --git a/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr b/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr index 48b42bc78253f..9711dad80785b 100644 --- a/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr +++ b/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr @@ -47,6 +47,9 @@ LL | foo(f); error[E0505]: cannot move out of `f` because it is borrowed --> $DIR/borrowck-call-is-borrow-issue-12224.rs:55:16 | +LL | let mut f = move |g: Box, b: isize| { + | ----- binding `f` declared here +... LL | f(Box::new(|a| { | - ^^^ move out of `f` occurs here | | diff --git a/tests/ui/span/dropck_arr_cycle_checked.stderr b/tests/ui/span/dropck_arr_cycle_checked.stderr index 068c779ae5267..23ebc8d598c67 100644 --- a/tests/ui/span/dropck_arr_cycle_checked.stderr +++ b/tests/ui/span/dropck_arr_cycle_checked.stderr @@ -1,6 +1,9 @@ error[E0597]: `b2` does not live long enough --> $DIR/dropck_arr_cycle_checked.rs:93:24 | +LL | let (b1, b2, b3); + | -- binding `b2` declared here +... LL | b1.a[0].v.set(Some(&b2)); | ^^^ borrowed value does not live long enough ... @@ -15,6 +18,9 @@ LL | } error[E0597]: `b3` does not live long enough --> $DIR/dropck_arr_cycle_checked.rs:95:24 | +LL | let (b1, b2, b3); + | -- binding `b3` declared here +... LL | b1.a[1].v.set(Some(&b3)); | ^^^ borrowed value does not live long enough ... @@ -29,6 +35,9 @@ LL | } error[E0597]: `b1` does not live long enough --> $DIR/dropck_arr_cycle_checked.rs:99:24 | +LL | let (b1, b2, b3); + | -- binding `b1` declared here +... LL | b3.a[0].v.set(Some(&b1)); | ^^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/dropck_direct_cycle_with_drop.stderr b/tests/ui/span/dropck_direct_cycle_with_drop.stderr index 07ae138ac71ea..1e75e3b2fa121 100644 --- a/tests/ui/span/dropck_direct_cycle_with_drop.stderr +++ b/tests/ui/span/dropck_direct_cycle_with_drop.stderr @@ -1,6 +1,8 @@ error[E0597]: `d2` does not live long enough --> $DIR/dropck_direct_cycle_with_drop.rs:36:19 | +LL | let (d1, d2) = (D::new(format!("d1")), D::new(format!("d2"))); + | -- binding `d2` declared here LL | d1.p.set(Some(&d2)); | ^^^ borrowed value does not live long enough ... @@ -15,6 +17,9 @@ LL | } error[E0597]: `d1` does not live long enough --> $DIR/dropck_direct_cycle_with_drop.rs:38:19 | +LL | let (d1, d2) = (D::new(format!("d1")), D::new(format!("d2"))); + | -- binding `d1` declared here +... LL | d2.p.set(Some(&d1)); | ^^^ borrowed value does not live long enough LL | diff --git a/tests/ui/span/dropck_misc_variants.stderr b/tests/ui/span/dropck_misc_variants.stderr index 76e90574cef44..24a2c9089f5b1 100644 --- a/tests/ui/span/dropck_misc_variants.stderr +++ b/tests/ui/span/dropck_misc_variants.stderr @@ -1,6 +1,9 @@ error[E0597]: `bomb` does not live long enough --> $DIR/dropck_misc_variants.rs:23:36 | +LL | let (_w, bomb); + | ---- binding `bomb` declared here +LL | bomb = vec![""]; LL | _w = Wrap::<&[&str]>(NoisyDrop(&bomb)); | ^^^^^ borrowed value does not live long enough LL | } @@ -14,6 +17,9 @@ LL | } error[E0597]: `v` does not live long enough --> $DIR/dropck_misc_variants.rs:31:27 | +LL | let (_w,v); + | - binding `v` declared here +... LL | let u = NoisyDrop(&v); | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/dropck_vec_cycle_checked.stderr b/tests/ui/span/dropck_vec_cycle_checked.stderr index 7ff991c0c3737..5817439c0d855 100644 --- a/tests/ui/span/dropck_vec_cycle_checked.stderr +++ b/tests/ui/span/dropck_vec_cycle_checked.stderr @@ -1,6 +1,9 @@ error[E0597]: `c2` does not live long enough --> $DIR/dropck_vec_cycle_checked.rs:98:24 | +LL | let (mut c1, mut c2, mut c3); + | ------ binding `c2` declared here +... LL | c1.v[0].v.set(Some(&c2)); | ^^^ borrowed value does not live long enough ... @@ -15,6 +18,9 @@ LL | } error[E0597]: `c3` does not live long enough --> $DIR/dropck_vec_cycle_checked.rs:100:24 | +LL | let (mut c1, mut c2, mut c3); + | ------ binding `c3` declared here +... LL | c1.v[1].v.set(Some(&c3)); | ^^^ borrowed value does not live long enough ... @@ -29,6 +35,9 @@ LL | } error[E0597]: `c1` does not live long enough --> $DIR/dropck_vec_cycle_checked.rs:104:24 | +LL | let (mut c1, mut c2, mut c3); + | ------ binding `c1` declared here +... LL | c3.v[0].v.set(Some(&c1)); | ^^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/issue-24805-dropck-child-has-items-via-parent.stderr b/tests/ui/span/issue-24805-dropck-child-has-items-via-parent.stderr index 809e60a8c8aac..c3b6d7580b4e0 100644 --- a/tests/ui/span/issue-24805-dropck-child-has-items-via-parent.stderr +++ b/tests/ui/span/issue-24805-dropck-child-has-items-via-parent.stderr @@ -1,6 +1,9 @@ error[E0597]: `d1` does not live long enough --> $DIR/issue-24805-dropck-child-has-items-via-parent.rs:28:18 | +LL | let (_d, d1); + | -- binding `d1` declared here +... LL | _d = D_Child(&d1); | ^^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/issue-24805-dropck-trait-has-items.stderr b/tests/ui/span/issue-24805-dropck-trait-has-items.stderr index 2e217066915d3..e52c57d9ab1f8 100644 --- a/tests/ui/span/issue-24805-dropck-trait-has-items.stderr +++ b/tests/ui/span/issue-24805-dropck-trait-has-items.stderr @@ -1,6 +1,9 @@ error[E0597]: `d1` does not live long enough --> $DIR/issue-24805-dropck-trait-has-items.rs:37:26 | +LL | let (_d, d1); + | -- binding `d1` declared here +LL | d1 = D_HasSelfMethod(1); LL | _d = D_HasSelfMethod(&d1); | ^^^ borrowed value does not live long enough LL | } @@ -14,6 +17,9 @@ LL | } error[E0597]: `d1` does not live long enough --> $DIR/issue-24805-dropck-trait-has-items.rs:43:33 | +LL | let (_d, d1); + | -- binding `d1` declared here +LL | d1 = D_HasMethodWithSelfArg(1); LL | _d = D_HasMethodWithSelfArg(&d1); | ^^^ borrowed value does not live long enough LL | } @@ -27,6 +33,9 @@ LL | } error[E0597]: `d1` does not live long enough --> $DIR/issue-24805-dropck-trait-has-items.rs:49:20 | +LL | let (_d, d1); + | -- binding `d1` declared here +LL | d1 = D_HasType(1); LL | _d = D_HasType(&d1); | ^^^ borrowed value does not live long enough LL | } diff --git a/tests/ui/span/issue-24895-copy-clone-dropck.stderr b/tests/ui/span/issue-24895-copy-clone-dropck.stderr index 18a3dc9e6defa..83db4d509d499 100644 --- a/tests/ui/span/issue-24895-copy-clone-dropck.stderr +++ b/tests/ui/span/issue-24895-copy-clone-dropck.stderr @@ -1,6 +1,9 @@ error[E0597]: `d1` does not live long enough --> $DIR/issue-24895-copy-clone-dropck.rs:27:14 | +LL | let (d2, d1); + | -- binding `d1` declared here +LL | d1 = D(34, "d1"); LL | d2 = D(S(&d1, "inner"), "d2"); | ^^^ borrowed value does not live long enough LL | } diff --git a/tests/ui/span/issue-25199.stderr b/tests/ui/span/issue-25199.stderr index d70a4afc1bf34..1e0276f0c3694 100644 --- a/tests/ui/span/issue-25199.stderr +++ b/tests/ui/span/issue-25199.stderr @@ -1,6 +1,8 @@ error[E0597]: `container` does not live long enough --> $DIR/issue-25199.rs:70:27 | +LL | let container = Container::new(); + | --------- binding `container` declared here LL | let test = Test{test: &container}; | ^^^^^^^^^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/issue-26656.stderr b/tests/ui/span/issue-26656.stderr index 1e939c484fb7b..fea6e001238b5 100644 --- a/tests/ui/span/issue-26656.stderr +++ b/tests/ui/span/issue-26656.stderr @@ -1,6 +1,9 @@ error[E0597]: `ticking` does not live long enough --> $DIR/issue-26656.rs:40:35 | +LL | let (mut zook, ticking); + | ------- binding `ticking` declared here +... LL | zook.button = B::BigRedButton(&ticking); | ^^^^^^^^ borrowed value does not live long enough LL | } diff --git a/tests/ui/span/issue-29106.stderr b/tests/ui/span/issue-29106.stderr index 71fbd60ee733b..28ee7acd90e8c 100644 --- a/tests/ui/span/issue-29106.stderr +++ b/tests/ui/span/issue-29106.stderr @@ -1,6 +1,9 @@ error[E0597]: `x` does not live long enough --> $DIR/issue-29106.rs:16:26 | +LL | let (y, x); + | - binding `x` declared here +LL | x = "alive".to_string(); LL | y = Arc::new(Foo(&x)); | ^^ borrowed value does not live long enough LL | } @@ -14,6 +17,9 @@ LL | } error[E0597]: `x` does not live long enough --> $DIR/issue-29106.rs:23:25 | +LL | let (y, x); + | - binding `x` declared here +LL | x = "alive".to_string(); LL | y = Rc::new(Foo(&x)); | ^^ borrowed value does not live long enough LL | } diff --git a/tests/ui/span/issue-36537.stderr b/tests/ui/span/issue-36537.stderr index 79a0ebaeb8db6..6c330c1a09475 100644 --- a/tests/ui/span/issue-36537.stderr +++ b/tests/ui/span/issue-36537.stderr @@ -1,6 +1,8 @@ error[E0597]: `a` does not live long enough --> $DIR/issue-36537.rs:5:13 | +LL | let a = 42; + | - binding `a` declared here LL | p = &a; | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/issue-40157.stderr b/tests/ui/span/issue-40157.stderr index 57f80214a4f83..e9b84de505989 100644 --- a/tests/ui/span/issue-40157.stderr +++ b/tests/ui/span/issue-40157.stderr @@ -2,11 +2,9 @@ error[E0597]: `foo` does not live long enough --> $DIR/issue-40157.rs:2:53 | LL | {println!("{:?}", match { let foo = vec![1, 2]; foo.get(1) } { x => x });} - | ------------------------^^^^^^^^^^-- - | | | | - | | | `foo` dropped here while still borrowed - | | borrowed value does not live long enough - | borrow later used here + | ^^^^^^^^^^ - `foo` dropped here while still borrowed + | | + | borrowed value does not live long enough error: aborting due to previous error diff --git a/tests/ui/span/issue28498-reject-lifetime-param.stderr b/tests/ui/span/issue28498-reject-lifetime-param.stderr index 3119ddd03cc26..94c450c7b1ece 100644 --- a/tests/ui/span/issue28498-reject-lifetime-param.stderr +++ b/tests/ui/span/issue28498-reject-lifetime-param.stderr @@ -1,6 +1,9 @@ error[E0597]: `first_dropped` does not live long enough --> $DIR/issue28498-reject-lifetime-param.rs:32:19 | +LL | let (foo1, first_dropped); + | ------------- binding `first_dropped` declared here +... LL | foo1 = Foo(1, &first_dropped); | ^^^^^^^^^^^^^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/issue28498-reject-passed-to-fn.stderr b/tests/ui/span/issue28498-reject-passed-to-fn.stderr index 60e8a648cd597..e133f75d57bb7 100644 --- a/tests/ui/span/issue28498-reject-passed-to-fn.stderr +++ b/tests/ui/span/issue28498-reject-passed-to-fn.stderr @@ -1,6 +1,9 @@ error[E0597]: `first_dropped` does not live long enough --> $DIR/issue28498-reject-passed-to-fn.rs:34:19 | +LL | let (foo1, first_dropped); + | ------------- binding `first_dropped` declared here +... LL | foo1 = Foo(1, &first_dropped, Box::new(callback)); | ^^^^^^^^^^^^^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/issue28498-reject-trait-bound.stderr b/tests/ui/span/issue28498-reject-trait-bound.stderr index 22e4a8205b617..9ab3cdd1343a1 100644 --- a/tests/ui/span/issue28498-reject-trait-bound.stderr +++ b/tests/ui/span/issue28498-reject-trait-bound.stderr @@ -1,6 +1,9 @@ error[E0597]: `first_dropped` does not live long enough --> $DIR/issue28498-reject-trait-bound.rs:34:19 | +LL | let (foo1, first_dropped); + | ------------- binding `first_dropped` declared here +... LL | foo1 = Foo(1, &first_dropped); | ^^^^^^^^^^^^^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/mut-ptr-cant-outlive-ref.stderr b/tests/ui/span/mut-ptr-cant-outlive-ref.stderr index 4d976a7bbfa47..be56f9489c770 100644 --- a/tests/ui/span/mut-ptr-cant-outlive-ref.stderr +++ b/tests/ui/span/mut-ptr-cant-outlive-ref.stderr @@ -1,6 +1,8 @@ error[E0597]: `b` does not live long enough --> $DIR/mut-ptr-cant-outlive-ref.rs:8:15 | +LL | let b = m.borrow(); + | - binding `b` declared here LL | p = &*b; | ^ borrowed value does not live long enough LL | } diff --git a/tests/ui/span/range-2.stderr b/tests/ui/span/range-2.stderr index 8ca8156b0830c..d7084b00ba402 100644 --- a/tests/ui/span/range-2.stderr +++ b/tests/ui/span/range-2.stderr @@ -3,7 +3,9 @@ error[E0597]: `a` does not live long enough | LL | let r = { | - borrow later stored here -... +LL | let a = 42; + | - binding `a` declared here +LL | let b = 42; LL | &a..&b | ^^ borrowed value does not live long enough LL | }; @@ -14,7 +16,9 @@ error[E0597]: `b` does not live long enough | LL | let r = { | - borrow later stored here -... +LL | let a = 42; +LL | let b = 42; + | - binding `b` declared here LL | &a..&b | ^^ borrowed value does not live long enough LL | }; diff --git a/tests/ui/span/regionck-unboxed-closure-lifetimes.stderr b/tests/ui/span/regionck-unboxed-closure-lifetimes.stderr index 0b985de609c26..fb3fad6ae9050 100644 --- a/tests/ui/span/regionck-unboxed-closure-lifetimes.stderr +++ b/tests/ui/span/regionck-unboxed-closure-lifetimes.stderr @@ -1,6 +1,8 @@ error[E0597]: `c` does not live long enough --> $DIR/regionck-unboxed-closure-lifetimes.rs:8:21 | +LL | let c = 1; + | - binding `c` declared here LL | let c_ref = &c; | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/regions-close-over-type-parameter-2.stderr b/tests/ui/span/regions-close-over-type-parameter-2.stderr index 2e584d9a884f1..fed40a4fdd2a5 100644 --- a/tests/ui/span/regions-close-over-type-parameter-2.stderr +++ b/tests/ui/span/regions-close-over-type-parameter-2.stderr @@ -1,6 +1,8 @@ error[E0597]: `tmp0` does not live long enough --> $DIR/regions-close-over-type-parameter-2.rs:23:20 | +LL | let tmp0 = 3; + | ---- binding `tmp0` declared here LL | let tmp1 = &tmp0; | ^^^^^ borrowed value does not live long enough LL | repeater3(tmp1) diff --git a/tests/ui/span/regions-escape-loop-via-variable.stderr b/tests/ui/span/regions-escape-loop-via-variable.stderr index 42df668529749..e5c7d8b26ab00 100644 --- a/tests/ui/span/regions-escape-loop-via-variable.stderr +++ b/tests/ui/span/regions-escape-loop-via-variable.stderr @@ -2,7 +2,9 @@ error[E0597]: `x` does not live long enough --> $DIR/regions-escape-loop-via-variable.rs:11:13 | LL | let x = 1 + *p; - | -- borrow later used here + | - -- borrow later used here + | | + | binding `x` declared here LL | p = &x; | ^^ borrowed value does not live long enough LL | } diff --git a/tests/ui/span/regions-escape-loop-via-vec.stderr b/tests/ui/span/regions-escape-loop-via-vec.stderr index 2b649307739f5..532ac3606c544 100644 --- a/tests/ui/span/regions-escape-loop-via-vec.stderr +++ b/tests/ui/span/regions-escape-loop-via-vec.stderr @@ -2,7 +2,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/regions-escape-loop-via-vec.rs:5:11 | LL | let mut _y = vec![&mut x]; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | while x < 10 { | ^ use of borrowed `x` LL | let mut z = x; @@ -13,7 +13,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/regions-escape-loop-via-vec.rs:6:21 | LL | let mut _y = vec![&mut x]; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here LL | while x < 10 { LL | let mut z = x; | ^ use of borrowed `x` @@ -23,11 +23,10 @@ LL | _y.push(&mut z); error[E0597]: `z` does not live long enough --> $DIR/regions-escape-loop-via-vec.rs:7:17 | +LL | let mut z = x; + | ----- binding `z` declared here LL | _y.push(&mut z); - | --------^^^^^^- - | | | - | | borrowed value does not live long enough - | borrow later used here + | ^^^^^^ borrowed value does not live long enough ... LL | } | - `z` dropped here while still borrowed @@ -36,7 +35,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/regions-escape-loop-via-vec.rs:9:9 | LL | let mut _y = vec![&mut x]; - | ------ borrow of `x` occurs here + | ------ `x` is borrowed here ... LL | _y.push(&mut z); | --------------- borrow later used here diff --git a/tests/ui/span/send-is-not-static-ensures-scoping.stderr b/tests/ui/span/send-is-not-static-ensures-scoping.stderr index 65d10c1305b8c..bae0befcacaa7 100644 --- a/tests/ui/span/send-is-not-static-ensures-scoping.stderr +++ b/tests/ui/span/send-is-not-static-ensures-scoping.stderr @@ -4,6 +4,7 @@ error[E0597]: `x` does not live long enough LL | let bad = { | --- borrow later stored here LL | let x = 1; + | - binding `x` declared here LL | let y = &x; | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/send-is-not-static-std-sync-2.stderr b/tests/ui/span/send-is-not-static-std-sync-2.stderr index bcd07e1164777..b0267fa6f43b0 100644 --- a/tests/ui/span/send-is-not-static-std-sync-2.stderr +++ b/tests/ui/span/send-is-not-static-std-sync-2.stderr @@ -4,6 +4,7 @@ error[E0597]: `x` does not live long enough LL | let lock = { | ---- borrow later stored here LL | let x = 1; + | - binding `x` declared here LL | Mutex::new(&x) | ^^ borrowed value does not live long enough LL | }; @@ -15,6 +16,7 @@ error[E0597]: `x` does not live long enough LL | let lock = { | ---- borrow later stored here LL | let x = 1; + | - binding `x` declared here LL | RwLock::new(&x) | ^^ borrowed value does not live long enough LL | }; @@ -25,7 +27,9 @@ error[E0597]: `x` does not live long enough | LL | let (_tx, rx) = { | --- borrow later used here -... +LL | let x = 1; + | - binding `x` declared here +LL | let (tx, rx) = mpsc::channel(); LL | let _ = tx.send(&x); | ^^ borrowed value does not live long enough LL | (tx, rx) diff --git a/tests/ui/span/send-is-not-static-std-sync.stderr b/tests/ui/span/send-is-not-static-std-sync.stderr index 5d493a3e4ee55..28b1c5fe7152a 100644 --- a/tests/ui/span/send-is-not-static-std-sync.stderr +++ b/tests/ui/span/send-is-not-static-std-sync.stderr @@ -12,6 +12,8 @@ LL | *lock.lock().unwrap() = &z; error[E0597]: `z` does not live long enough --> $DIR/send-is-not-static-std-sync.rs:16:33 | +LL | let z = 2; + | - binding `z` declared here LL | *lock.lock().unwrap() = &z; | ^^ borrowed value does not live long enough LL | } @@ -34,6 +36,8 @@ LL | *lock.write().unwrap() = &z; error[E0597]: `z` does not live long enough --> $DIR/send-is-not-static-std-sync.rs:30:34 | +LL | let z = 2; + | - binding `z` declared here LL | *lock.write().unwrap() = &z; | ^^ borrowed value does not live long enough LL | } @@ -56,6 +60,8 @@ LL | tx.send(&z).unwrap(); error[E0597]: `z` does not live long enough --> $DIR/send-is-not-static-std-sync.rs:46:17 | +LL | let z = 2; + | - binding `z` declared here LL | tx.send(&z).unwrap(); | ^^ borrowed value does not live long enough LL | } diff --git a/tests/ui/span/vec-must-not-hide-type-from-dropck.stderr b/tests/ui/span/vec-must-not-hide-type-from-dropck.stderr index f87c32d1ad0c6..f2fefca414ec4 100644 --- a/tests/ui/span/vec-must-not-hide-type-from-dropck.stderr +++ b/tests/ui/span/vec-must-not-hide-type-from-dropck.stderr @@ -1,6 +1,9 @@ error[E0597]: `c2` does not live long enough --> $DIR/vec-must-not-hide-type-from-dropck.rs:117:24 | +LL | let (mut c1, mut c2); + | ------ binding `c2` declared here +... LL | c1.v[0].v.set(Some(&c2)); | ^^^ borrowed value does not live long enough ... @@ -15,6 +18,9 @@ LL | } error[E0597]: `c1` does not live long enough --> $DIR/vec-must-not-hide-type-from-dropck.rs:119:24 | +LL | let (mut c1, mut c2); + | ------ binding `c1` declared here +... LL | c2.v[0].v.set(Some(&c1)); | ^^^ borrowed value does not live long enough LL | diff --git a/tests/ui/span/vec_refs_data_with_early_death.stderr b/tests/ui/span/vec_refs_data_with_early_death.stderr index 684e784531325..73f27144af423 100644 --- a/tests/ui/span/vec_refs_data_with_early_death.stderr +++ b/tests/ui/span/vec_refs_data_with_early_death.stderr @@ -1,6 +1,9 @@ error[E0597]: `x` does not live long enough --> $DIR/vec_refs_data_with_early_death.rs:17:12 | +LL | let x: i8 = 3; + | - binding `x` declared here +... LL | v.push(&x); | ^^ borrowed value does not live long enough ... @@ -15,6 +18,9 @@ LL | } error[E0597]: `y` does not live long enough --> $DIR/vec_refs_data_with_early_death.rs:19:12 | +LL | let y: i8 = 4; + | - binding `y` declared here +... LL | v.push(&y); | ^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/wf-method-late-bound-regions.stderr b/tests/ui/span/wf-method-late-bound-regions.stderr index 6b0b008208f17..64c2d0f160665 100644 --- a/tests/ui/span/wf-method-late-bound-regions.stderr +++ b/tests/ui/span/wf-method-late-bound-regions.stderr @@ -4,6 +4,7 @@ error[E0597]: `pointer` does not live long enough LL | let dangling = { | -------- borrow later stored here LL | let pointer = Box::new(42); + | ------- binding `pointer` declared here LL | f2.xmute(&pointer) | ^^^^^^^^ borrowed value does not live long enough LL | }; diff --git a/tests/ui/static/static-lifetime-bound.stderr b/tests/ui/static/static-lifetime-bound.stderr index ef07a89315f40..e22411b13b776 100644 --- a/tests/ui/static/static-lifetime-bound.stderr +++ b/tests/ui/static/static-lifetime-bound.stderr @@ -9,6 +9,8 @@ LL | fn f<'a: 'static>(_: &'a i32) {} error[E0597]: `x` does not live long enough --> $DIR/static-lifetime-bound.rs:5:7 | +LL | let x = 0; + | - binding `x` declared here LL | f(&x); | --^^- | | | diff --git a/tests/ui/suggestions/borrow-for-loop-head.stderr b/tests/ui/suggestions/borrow-for-loop-head.stderr index cbdb94877bdb7..0f179438a1263 100644 --- a/tests/ui/suggestions/borrow-for-loop-head.stderr +++ b/tests/ui/suggestions/borrow-for-loop-head.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `a` because it is borrowed --> $DIR/borrow-for-loop-head.rs:4:18 | +LL | let a = vec![1, 2, 3]; + | - binding `a` declared here LL | for i in &a { | -- borrow of `a` occurs here LL | for j in a { diff --git a/tests/ui/suggestions/option-content-move2.stderr b/tests/ui/suggestions/option-content-move2.stderr index 1d3dff3be3476..94acda73c4efe 100644 --- a/tests/ui/suggestions/option-content-move2.stderr +++ b/tests/ui/suggestions/option-content-move2.stderr @@ -7,7 +7,7 @@ LL | func(|| { | -- captured by this `FnMut` closure LL | // Shouldn't suggest `move ||.as_ref()` here LL | move || { - | ^^^^^^^ move out of `var` occurs here + | ^^^^^^^ `var` is moved here LL | LL | var = Some(NotCopyable); | --- diff --git a/tests/ui/traits/associated_type_bound/check-trait-object-bounds-3.stderr b/tests/ui/traits/associated_type_bound/check-trait-object-bounds-3.stderr index ade552c4bab41..c7af71a421438 100644 --- a/tests/ui/traits/associated_type_bound/check-trait-object-bounds-3.stderr +++ b/tests/ui/traits/associated_type_bound/check-trait-object-bounds-3.stderr @@ -1,6 +1,8 @@ error[E0597]: `s` does not live long enough --> $DIR/check-trait-object-bounds-3.rs:15:34 | +LL | let s = String::from("abcdef"); + | - binding `s` declared here LL | z = f::>(&s); | ---------------------^^- | | | diff --git a/tests/ui/traits/coercion-generic-regions.stderr b/tests/ui/traits/coercion-generic-regions.stderr index 5cfb64901233e..ae70202ab7ccd 100644 --- a/tests/ui/traits/coercion-generic-regions.stderr +++ b/tests/ui/traits/coercion-generic-regions.stderr @@ -1,6 +1,8 @@ error[E0597]: `person` does not live long enough --> $DIR/coercion-generic-regions.rs:17:24 | +LL | let person = "Fred".to_string(); + | ------ binding `person` declared here LL | let person: &str = &person; | ^^^^^^^ | | diff --git a/tests/ui/traits/vtable/issue-97381.stderr b/tests/ui/traits/vtable/issue-97381.stderr index c4f8294e26356..89360c44e78b4 100644 --- a/tests/ui/traits/vtable/issue-97381.stderr +++ b/tests/ui/traits/vtable/issue-97381.stderr @@ -1,6 +1,9 @@ error[E0505]: cannot move out of `v` because it is borrowed --> $DIR/issue-97381.rs:26:14 | +LL | let v = [1, 2, 3] + | - binding `v` declared here +... LL | let el = &v[0]; | - borrow of `v` occurs here LL | diff --git a/tests/ui/try-block/try-block-bad-lifetime.stderr b/tests/ui/try-block/try-block-bad-lifetime.stderr index ea079e30d9c39..28941cb0a9e40 100644 --- a/tests/ui/try-block/try-block-bad-lifetime.stderr +++ b/tests/ui/try-block/try-block-bad-lifetime.stderr @@ -4,6 +4,7 @@ error[E0597]: `my_string` does not live long enough LL | let result: Result<(), &str> = try { | ------ borrow later stored here LL | let my_string = String::from(""); + | --------- binding `my_string` declared here LL | let my_str: & str = & my_string; | ^^^^^^^^^^^ borrowed value does not live long enough ... @@ -14,10 +15,10 @@ error[E0506]: cannot assign to `i` because it is borrowed --> $DIR/try-block-bad-lifetime.rs:29:13 | LL | let k = &mut i; - | ------ borrow of `i` occurs here + | ------ `i` is borrowed here ... LL | i = 10; - | ^^^^^^ assignment to borrowed `i` occurs here + | ^^^^^^ `i` is assigned to here but it was already borrowed LL | }; LL | ::std::mem::drop(k); | - borrow later used here @@ -38,10 +39,10 @@ error[E0506]: cannot assign to `i` because it is borrowed --> $DIR/try-block-bad-lifetime.rs:32:9 | LL | let k = &mut i; - | ------ borrow of `i` occurs here + | ------ `i` is borrowed here ... LL | i = 40; - | ^^^^^^ assignment to borrowed `i` occurs here + | ^^^^^^ `i` is assigned to here but it was already borrowed LL | LL | let i_ptr = if let Err(i_ptr) = j { i_ptr } else { panic ! ("") }; | - borrow later used here diff --git a/tests/ui/try-block/try-block-maybe-bad-lifetime.stderr b/tests/ui/try-block/try-block-maybe-bad-lifetime.stderr index f738b03eed6b8..71c7e460c3992 100644 --- a/tests/ui/try-block/try-block-maybe-bad-lifetime.stderr +++ b/tests/ui/try-block/try-block-maybe-bad-lifetime.stderr @@ -2,10 +2,10 @@ error[E0506]: cannot assign to `i` because it is borrowed --> $DIR/try-block-maybe-bad-lifetime.rs:17:9 | LL | &i - | -- borrow of `i` occurs here + | -- `i` is borrowed here LL | }; LL | i = 0; - | ^^^^^ assignment to borrowed `i` occurs here + | ^^^^^ `i` is assigned to here but it was already borrowed LL | let _ = i; LL | do_something_with(x); | - borrow later used here @@ -32,10 +32,10 @@ error[E0506]: cannot assign to `i` because it is borrowed --> $DIR/try-block-maybe-bad-lifetime.rs:40:9 | LL | j = &i; - | -- borrow of `i` occurs here + | -- `i` is borrowed here LL | }; LL | i = 0; - | ^^^^^ assignment to borrowed `i` occurs here + | ^^^^^ `i` is assigned to here but it was already borrowed LL | let _ = i; LL | do_something_with(j); | - borrow later used here diff --git a/tests/ui/unboxed-closures/unboxed-closures-borrow-conflict.stderr b/tests/ui/unboxed-closures/unboxed-closures-borrow-conflict.stderr index 21d6b4fde7e90..98fe97c5c1814 100644 --- a/tests/ui/unboxed-closures/unboxed-closures-borrow-conflict.stderr +++ b/tests/ui/unboxed-closures/unboxed-closures-borrow-conflict.stderr @@ -4,7 +4,7 @@ error[E0503]: cannot use `x` because it was mutably borrowed LL | let f = || x += 1; | -- - borrow occurs due to use of `x` in closure | | - | borrow of `x` occurs here + | `x` is borrowed here LL | let _y = x; | ^ use of borrowed `x` LL | f; diff --git a/tests/ui/unboxed-closures/unboxed-closures-failed-recursive-fn-1.stderr b/tests/ui/unboxed-closures/unboxed-closures-failed-recursive-fn-1.stderr index cbdb4dd0fb5c8..23aa18d7156ac 100644 --- a/tests/ui/unboxed-closures/unboxed-closures-failed-recursive-fn-1.stderr +++ b/tests/ui/unboxed-closures/unboxed-closures-failed-recursive-fn-1.stderr @@ -16,14 +16,14 @@ error[E0506]: cannot assign to `factorial` because it is borrowed --> $DIR/unboxed-closures-failed-recursive-fn-1.rs:20:5 | LL | let f = |x: u32| -> u32 { - | --------------- borrow of `factorial` occurs here + | --------------- `factorial` is borrowed here LL | let g = factorial.as_ref().unwrap(); | --------- borrow occurs due to use in closure ... LL | factorial = Some(Box::new(f)); | ^^^^^^^^^ | | - | assignment to borrowed `factorial` occurs here + | `factorial` is assigned to here but it was already borrowed | borrow later used here error[E0597]: `factorial` does not live long enough @@ -47,12 +47,12 @@ LL | let mut factorial: Option u32 + 'static>> = None; | ----------------------------------------- type annotation requires that `factorial` is borrowed for `'static` LL | LL | let f = |x: u32| -> u32 { - | --------------- borrow of `factorial` occurs here + | --------------- `factorial` is borrowed here LL | let g = factorial.as_ref().unwrap(); | --------- borrow occurs due to use in closure ... LL | factorial = Some(Box::new(f)); - | ^^^^^^^^^ assignment to borrowed `factorial` occurs here + | ^^^^^^^^^ `factorial` is assigned to here but it was already borrowed error: aborting due to 4 previous errors diff --git a/tests/ui/unop-move-semantics.stderr b/tests/ui/unop-move-semantics.stderr index 2a3ca14433f62..e47785c465ac6 100644 --- a/tests/ui/unop-move-semantics.stderr +++ b/tests/ui/unop-move-semantics.stderr @@ -23,6 +23,8 @@ LL | fn move_then_borrow + Clone + Copy>(x: T) { error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/unop-move-semantics.rs:15:6 | +LL | fn move_borrowed>(x: T, mut y: T) { + | - binding `x` declared here LL | let m = &x; | -- borrow of `x` occurs here ... @@ -35,6 +37,9 @@ LL | use_mut(n); use_imm(m); error[E0505]: cannot move out of `y` because it is borrowed --> $DIR/unop-move-semantics.rs:17:6 | +LL | fn move_borrowed>(x: T, mut y: T) { + | ----- binding `y` declared here +LL | let m = &x; LL | let n = &mut y; | ------ borrow of `y` occurs here ... diff --git a/tests/ui/variance/variance-issue-20533.stderr b/tests/ui/variance/variance-issue-20533.stderr index 008e2a002bbb0..258f67db5ce4b 100644 --- a/tests/ui/variance/variance-issue-20533.stderr +++ b/tests/ui/variance/variance-issue-20533.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `a` because it is borrowed --> $DIR/variance-issue-20533.rs:28:14 | +LL | let a = AffineU32(1); + | - binding `a` declared here LL | let x = foo(&a); | -- borrow of `a` occurs here LL | drop(a); @@ -11,6 +13,8 @@ LL | drop(x); error[E0505]: cannot move out of `a` because it is borrowed --> $DIR/variance-issue-20533.rs:34:14 | +LL | let a = AffineU32(1); + | - binding `a` declared here LL | let x = bar(&a); | -- borrow of `a` occurs here LL | drop(a); @@ -21,6 +25,8 @@ LL | drop(x); error[E0505]: cannot move out of `a` because it is borrowed --> $DIR/variance-issue-20533.rs:40:14 | +LL | let a = AffineU32(1); + | - binding `a` declared here LL | let x = baz(&a); | -- borrow of `a` occurs here LL | drop(a); From e4f61afa779e01af24c6f20394de8e3950b368c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 15 Jan 2023 19:57:32 +0000 Subject: [PATCH 199/500] Fix fulldeps-ui tests --- tests/ui-fulldeps/dropck-tarena-cycle-checked.stderr | 2 ++ tests/ui-fulldeps/dropck-tarena-unsound-drop.stderr | 2 ++ 2 files changed, 4 insertions(+) diff --git a/tests/ui-fulldeps/dropck-tarena-cycle-checked.stderr b/tests/ui-fulldeps/dropck-tarena-cycle-checked.stderr index 4299688221a8b..47897dc003a43 100644 --- a/tests/ui-fulldeps/dropck-tarena-cycle-checked.stderr +++ b/tests/ui-fulldeps/dropck-tarena-cycle-checked.stderr @@ -1,6 +1,8 @@ error[E0597]: `arena` does not live long enough --> $DIR/dropck-tarena-cycle-checked.rs:116:7 | +LL | let arena = TypedArena::default(); + | ----- binding `arena` declared here LL | f(&arena); | ^^^^^^ borrowed value does not live long enough LL | } diff --git a/tests/ui-fulldeps/dropck-tarena-unsound-drop.stderr b/tests/ui-fulldeps/dropck-tarena-unsound-drop.stderr index ccffee9cdbda9..493d74b0bdec9 100644 --- a/tests/ui-fulldeps/dropck-tarena-unsound-drop.stderr +++ b/tests/ui-fulldeps/dropck-tarena-unsound-drop.stderr @@ -1,6 +1,8 @@ error[E0597]: `arena` does not live long enough --> $DIR/dropck-tarena-unsound-drop.rs:41:7 | +LL | let arena: TypedArena = TypedArena::default(); + | ----- binding `arena` declared here LL | f(&arena); | ^^^^^^ borrowed value does not live long enough LL | } From 662199f125005dca31bf9cdfa298bd5a7994e07c Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Sun, 11 Dec 2022 21:07:33 -0500 Subject: [PATCH 200/500] InstCombine away intrinsic validity assertions --- .../rustc_mir_transform/src/instcombine.rs | 79 ++++++++++++++++++- ...intrinsic_asserts.generic.InstCombine.diff | 42 ++++++++++ .../intrinsic_asserts.panics.InstCombine.diff | 47 +++++++++++ ...trinsic_asserts.removable.InstCombine.diff | 45 +++++++++++ tests/mir-opt/intrinsic_asserts.rs | 28 +++++++ 5 files changed, 239 insertions(+), 2 deletions(-) create mode 100644 tests/mir-opt/intrinsic_asserts.generic.InstCombine.diff create mode 100644 tests/mir-opt/intrinsic_asserts.panics.InstCombine.diff create mode 100644 tests/mir-opt/intrinsic_asserts.removable.InstCombine.diff create mode 100644 tests/mir-opt/intrinsic_asserts.rs diff --git a/compiler/rustc_mir_transform/src/instcombine.rs b/compiler/rustc_mir_transform/src/instcombine.rs index 2f3c65869ef3b..1b795479a928e 100644 --- a/compiler/rustc_mir_transform/src/instcombine.rs +++ b/compiler/rustc_mir_transform/src/instcombine.rs @@ -6,7 +6,8 @@ use rustc_middle::mir::{ BinOp, Body, Constant, ConstantKind, LocalDecls, Operand, Place, ProjectionElem, Rvalue, SourceInfo, Statement, StatementKind, Terminator, TerminatorKind, UnOp, }; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{self, layout::TyAndLayout, ParamEnv, SubstsRef, Ty, TyCtxt}; +use rustc_span::symbol::{sym, Symbol}; pub struct InstCombine; @@ -16,7 +17,11 @@ impl<'tcx> MirPass<'tcx> for InstCombine { } fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { - let ctx = InstCombineContext { tcx, local_decls: &body.local_decls }; + let ctx = InstCombineContext { + tcx, + local_decls: &body.local_decls, + param_env: tcx.param_env_reveal_all_normalized(body.source.def_id()), + }; for block in body.basic_blocks.as_mut() { for statement in block.statements.iter_mut() { match statement.kind { @@ -33,6 +38,10 @@ impl<'tcx> MirPass<'tcx> for InstCombine { &mut block.terminator.as_mut().unwrap(), &mut block.statements, ); + ctx.combine_intrinsic_assert( + &mut block.terminator.as_mut().unwrap(), + &mut block.statements, + ); } } } @@ -40,6 +49,7 @@ impl<'tcx> MirPass<'tcx> for InstCombine { struct InstCombineContext<'tcx, 'a> { tcx: TyCtxt<'tcx>, local_decls: &'a LocalDecls<'tcx>, + param_env: ParamEnv<'tcx>, } impl<'tcx> InstCombineContext<'tcx, '_> { @@ -200,4 +210,69 @@ impl<'tcx> InstCombineContext<'tcx, '_> { }); terminator.kind = TerminatorKind::Goto { target: destination_block }; } + + fn combine_intrinsic_assert( + &self, + terminator: &mut Terminator<'tcx>, + _statements: &mut Vec>, + ) { + let TerminatorKind::Call { func, target, .. } = &mut terminator.kind else { return; }; + let Some(target_block) = target else { return; }; + let func_ty = func.ty(self.local_decls, self.tcx); + let Some((intrinsic_name, substs)) = resolve_rust_intrinsic(self.tcx, func_ty) else { + return; + }; + // The intrinsics we are interested in have one generic parameter + if substs.is_empty() { + return; + } + let ty = substs.type_at(0); + + // Check this is a foldable intrinsic before we query the layout of our generic parameter + let Some(assert_panics) = intrinsic_assert_panics(intrinsic_name) else { return; }; + let Ok(layout) = self.tcx.layout_of(self.param_env.and(ty)) else { return; }; + if assert_panics(self.tcx, layout) { + // If we know the assert panics, indicate to later opts that the call diverges + *target = None; + } else { + // If we know the assert does not panic, turn the call into a Goto + terminator.kind = TerminatorKind::Goto { target: *target_block }; + } + } +} + +fn intrinsic_assert_panics<'tcx>( + intrinsic_name: Symbol, +) -> Option, TyAndLayout<'tcx>) -> bool> { + fn inhabited_predicate<'tcx>(_tcx: TyCtxt<'tcx>, layout: TyAndLayout<'tcx>) -> bool { + layout.abi.is_uninhabited() + } + fn zero_valid_predicate<'tcx>(tcx: TyCtxt<'tcx>, layout: TyAndLayout<'tcx>) -> bool { + !tcx.permits_zero_init(layout) + } + fn mem_uninitialized_valid_predicate<'tcx>( + tcx: TyCtxt<'tcx>, + layout: TyAndLayout<'tcx>, + ) -> bool { + !tcx.permits_uninit_init(layout) + } + + match intrinsic_name { + sym::assert_inhabited => Some(inhabited_predicate), + sym::assert_zero_valid => Some(zero_valid_predicate), + sym::assert_mem_uninitialized_valid => Some(mem_uninitialized_valid_predicate), + _ => None, + } +} + +fn resolve_rust_intrinsic<'tcx>( + tcx: TyCtxt<'tcx>, + func_ty: Ty<'tcx>, +) -> Option<(Symbol, SubstsRef<'tcx>)> { + if let ty::FnDef(def_id, substs) = *func_ty.kind() { + if tcx.is_intrinsic(def_id) { + return Some((tcx.item_name(def_id), substs)); + } + } + None } diff --git a/tests/mir-opt/intrinsic_asserts.generic.InstCombine.diff b/tests/mir-opt/intrinsic_asserts.generic.InstCombine.diff new file mode 100644 index 0000000000000..8ff64c1ea159c --- /dev/null +++ b/tests/mir-opt/intrinsic_asserts.generic.InstCombine.diff @@ -0,0 +1,42 @@ +- // MIR for `generic` before InstCombine ++ // MIR for `generic` after InstCombine + + fn generic() -> () { + let mut _0: (); // return place in scope 0 at $DIR/intrinsic_asserts.rs:+0:21: +0:21 + let _1: (); // in scope 0 at $DIR/intrinsic_asserts.rs:+1:5: +1:46 + let _2: (); // in scope 0 at $DIR/intrinsic_asserts.rs:+2:5: +2:47 + let _3: (); // in scope 0 at $DIR/intrinsic_asserts.rs:+3:5: +3:60 + + bb0: { + StorageLive(_1); // scope 0 at $DIR/intrinsic_asserts.rs:+1:5: +1:46 + _1 = assert_inhabited::() -> bb1; // scope 0 at $DIR/intrinsic_asserts.rs:+1:5: +1:46 + // mir::Constant + // + span: $DIR/intrinsic_asserts.rs:25:5: 25:44 + // + literal: Const { ty: extern "rust-intrinsic" fn() {assert_inhabited::}, val: Value() } + } + + bb1: { + StorageDead(_1); // scope 0 at $DIR/intrinsic_asserts.rs:+1:46: +1:47 + StorageLive(_2); // scope 0 at $DIR/intrinsic_asserts.rs:+2:5: +2:47 + _2 = assert_zero_valid::() -> bb2; // scope 0 at $DIR/intrinsic_asserts.rs:+2:5: +2:47 + // mir::Constant + // + span: $DIR/intrinsic_asserts.rs:26:5: 26:45 + // + literal: Const { ty: extern "rust-intrinsic" fn() {assert_zero_valid::}, val: Value() } + } + + bb2: { + StorageDead(_2); // scope 0 at $DIR/intrinsic_asserts.rs:+2:47: +2:48 + StorageLive(_3); // scope 0 at $DIR/intrinsic_asserts.rs:+3:5: +3:60 + _3 = assert_mem_uninitialized_valid::() -> bb3; // scope 0 at $DIR/intrinsic_asserts.rs:+3:5: +3:60 + // mir::Constant + // + span: $DIR/intrinsic_asserts.rs:27:5: 27:58 + // + literal: Const { ty: extern "rust-intrinsic" fn() {assert_mem_uninitialized_valid::}, val: Value() } + } + + bb3: { + StorageDead(_3); // scope 0 at $DIR/intrinsic_asserts.rs:+3:60: +3:61 + nop; // scope 0 at $DIR/intrinsic_asserts.rs:+0:21: +4:2 + return; // scope 0 at $DIR/intrinsic_asserts.rs:+4:2: +4:2 + } + } + diff --git a/tests/mir-opt/intrinsic_asserts.panics.InstCombine.diff b/tests/mir-opt/intrinsic_asserts.panics.InstCombine.diff new file mode 100644 index 0000000000000..ddc01590315c5 --- /dev/null +++ b/tests/mir-opt/intrinsic_asserts.panics.InstCombine.diff @@ -0,0 +1,47 @@ +- // MIR for `panics` before InstCombine ++ // MIR for `panics` after InstCombine + + fn panics() -> () { + let mut _0: (); // return place in scope 0 at $DIR/intrinsic_asserts.rs:+0:17: +0:17 + let _1: (); // in scope 0 at $DIR/intrinsic_asserts.rs:+1:5: +1:50 + let _2: (); // in scope 0 at $DIR/intrinsic_asserts.rs:+2:5: +2:49 + let _3: (); // in scope 0 at $DIR/intrinsic_asserts.rs:+3:5: +3:62 + + bb0: { + StorageLive(_1); // scope 0 at $DIR/intrinsic_asserts.rs:+1:5: +1:50 +- _1 = assert_inhabited::() -> bb1; // scope 0 at $DIR/intrinsic_asserts.rs:+1:5: +1:50 ++ _1 = assert_inhabited::(); // scope 0 at $DIR/intrinsic_asserts.rs:+1:5: +1:50 + // mir::Constant + // + span: $DIR/intrinsic_asserts.rs:17:5: 17:48 + // + literal: Const { ty: extern "rust-intrinsic" fn() {assert_inhabited::}, val: Value() } + } + + bb1: { + StorageDead(_1); // scope 0 at $DIR/intrinsic_asserts.rs:+1:50: +1:51 + StorageLive(_2); // scope 0 at $DIR/intrinsic_asserts.rs:+2:5: +2:49 +- _2 = assert_zero_valid::<&u8>() -> bb2; // scope 0 at $DIR/intrinsic_asserts.rs:+2:5: +2:49 ++ _2 = assert_zero_valid::<&u8>(); // scope 0 at $DIR/intrinsic_asserts.rs:+2:5: +2:49 + // mir::Constant + // + span: $DIR/intrinsic_asserts.rs:18:5: 18:47 + // + user_ty: UserType(0) + // + literal: Const { ty: extern "rust-intrinsic" fn() {assert_zero_valid::<&u8>}, val: Value() } + } + + bb2: { + StorageDead(_2); // scope 0 at $DIR/intrinsic_asserts.rs:+2:49: +2:50 + StorageLive(_3); // scope 0 at $DIR/intrinsic_asserts.rs:+3:5: +3:62 +- _3 = assert_mem_uninitialized_valid::<&u8>() -> bb3; // scope 0 at $DIR/intrinsic_asserts.rs:+3:5: +3:62 ++ _3 = assert_mem_uninitialized_valid::<&u8>(); // scope 0 at $DIR/intrinsic_asserts.rs:+3:5: +3:62 + // mir::Constant + // + span: $DIR/intrinsic_asserts.rs:19:5: 19:60 + // + user_ty: UserType(1) + // + literal: Const { ty: extern "rust-intrinsic" fn() {assert_mem_uninitialized_valid::<&u8>}, val: Value() } + } + + bb3: { + StorageDead(_3); // scope 0 at $DIR/intrinsic_asserts.rs:+3:62: +3:63 + nop; // scope 0 at $DIR/intrinsic_asserts.rs:+0:17: +4:2 + return; // scope 0 at $DIR/intrinsic_asserts.rs:+4:2: +4:2 + } + } + diff --git a/tests/mir-opt/intrinsic_asserts.removable.InstCombine.diff b/tests/mir-opt/intrinsic_asserts.removable.InstCombine.diff new file mode 100644 index 0000000000000..568fbf1a0d659 --- /dev/null +++ b/tests/mir-opt/intrinsic_asserts.removable.InstCombine.diff @@ -0,0 +1,45 @@ +- // MIR for `removable` before InstCombine ++ // MIR for `removable` after InstCombine + + fn removable() -> () { + let mut _0: (); // return place in scope 0 at $DIR/intrinsic_asserts.rs:+0:20: +0:20 + let _1: (); // in scope 0 at $DIR/intrinsic_asserts.rs:+1:5: +1:47 + let _2: (); // in scope 0 at $DIR/intrinsic_asserts.rs:+2:5: +2:48 + let _3: (); // in scope 0 at $DIR/intrinsic_asserts.rs:+3:5: +3:61 + + bb0: { + StorageLive(_1); // scope 0 at $DIR/intrinsic_asserts.rs:+1:5: +1:47 +- _1 = assert_inhabited::<()>() -> bb1; // scope 0 at $DIR/intrinsic_asserts.rs:+1:5: +1:47 +- // mir::Constant +- // + span: $DIR/intrinsic_asserts.rs:7:5: 7:45 +- // + literal: Const { ty: extern "rust-intrinsic" fn() {assert_inhabited::<()>}, val: Value() } ++ goto -> bb1; // scope 0 at $DIR/intrinsic_asserts.rs:+1:5: +1:47 + } + + bb1: { + StorageDead(_1); // scope 0 at $DIR/intrinsic_asserts.rs:+1:47: +1:48 + StorageLive(_2); // scope 0 at $DIR/intrinsic_asserts.rs:+2:5: +2:48 +- _2 = assert_zero_valid::() -> bb2; // scope 0 at $DIR/intrinsic_asserts.rs:+2:5: +2:48 +- // mir::Constant +- // + span: $DIR/intrinsic_asserts.rs:8:5: 8:46 +- // + literal: Const { ty: extern "rust-intrinsic" fn() {assert_zero_valid::}, val: Value() } ++ goto -> bb2; // scope 0 at $DIR/intrinsic_asserts.rs:+2:5: +2:48 + } + + bb2: { + StorageDead(_2); // scope 0 at $DIR/intrinsic_asserts.rs:+2:48: +2:49 + StorageLive(_3); // scope 0 at $DIR/intrinsic_asserts.rs:+3:5: +3:61 +- _3 = assert_mem_uninitialized_valid::() -> bb3; // scope 0 at $DIR/intrinsic_asserts.rs:+3:5: +3:61 +- // mir::Constant +- // + span: $DIR/intrinsic_asserts.rs:9:5: 9:59 +- // + literal: Const { ty: extern "rust-intrinsic" fn() {assert_mem_uninitialized_valid::}, val: Value() } ++ goto -> bb3; // scope 0 at $DIR/intrinsic_asserts.rs:+3:5: +3:61 + } + + bb3: { + StorageDead(_3); // scope 0 at $DIR/intrinsic_asserts.rs:+3:61: +3:62 + nop; // scope 0 at $DIR/intrinsic_asserts.rs:+0:20: +4:2 + return; // scope 0 at $DIR/intrinsic_asserts.rs:+4:2: +4:2 + } + } + diff --git a/tests/mir-opt/intrinsic_asserts.rs b/tests/mir-opt/intrinsic_asserts.rs new file mode 100644 index 0000000000000..8fb99cdf6e041 --- /dev/null +++ b/tests/mir-opt/intrinsic_asserts.rs @@ -0,0 +1,28 @@ +#![crate_type = "lib"] +#![feature(core_intrinsics)] + +// All these assertions pass, so all the intrinsic calls should be deleted. +// EMIT_MIR intrinsic_asserts.removable.InstCombine.diff +pub fn removable() { + core::intrinsics::assert_inhabited::<()>(); + core::intrinsics::assert_zero_valid::(); + core::intrinsics::assert_mem_uninitialized_valid::(); +} + +enum Never {} + +// These assertions all diverge, so their target blocks should become None. +// EMIT_MIR intrinsic_asserts.panics.InstCombine.diff +pub fn panics() { + core::intrinsics::assert_inhabited::(); + core::intrinsics::assert_zero_valid::<&u8>(); + core::intrinsics::assert_mem_uninitialized_valid::<&u8>(); +} + +// Whether or not these asserts pass isn't known, so they shouldn't be modified. +// EMIT_MIR intrinsic_asserts.generic.InstCombine.diff +pub fn generic() { + core::intrinsics::assert_inhabited::(); + core::intrinsics::assert_zero_valid::(); + core::intrinsics::assert_mem_uninitialized_valid::(); +} From 70957832684155dbe74a313d576028a5af5f89e9 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Mon, 16 Jan 2023 11:21:37 +0000 Subject: [PATCH 201/500] Only run abi-cafe on cg_clif's CI --- .github/workflows/main.yml | 8 ++++++++ build_system/abi_cafe.rs | 6 ------ build_system/mod.rs | 20 ++++++++------------ build_system/usage.txt | 1 + config.txt | 2 -- 5 files changed, 17 insertions(+), 20 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 1181c935b8389..90004b408c014 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -114,6 +114,14 @@ jobs: TARGET_TRIPLE: ${{ matrix.env.TARGET_TRIPLE }} run: ./y.rs test + - name: Test abi-cafe + env: + TARGET_TRIPLE: ${{ matrix.env.TARGET_TRIPLE }} + run: | + if [[ "$(rustc -vV | grep host | cut -d' ' -f2)" == "$TARGET_TRIPLE" ]]; then + ./y.rs abi-cafe + fi + - name: Package prebuilt cg_clif run: tar cvfJ cg_clif.tar.xz dist diff --git a/build_system/abi_cafe.rs b/build_system/abi_cafe.rs index 8742389f33227..dbee9be04eea6 100644 --- a/build_system/abi_cafe.rs +++ b/build_system/abi_cafe.rs @@ -1,7 +1,6 @@ use std::path::Path; use super::build_sysroot; -use super::config; use super::path::Dirs; use super::prepare::GitRepo; use super::utils::{spawn_and_wait, CargoProject, Compiler}; @@ -20,11 +19,6 @@ pub(crate) fn run( cg_clif_dylib: &Path, bootstrap_host_compiler: &Compiler, ) { - if !config::get_bool("testsuite.abi-cafe") { - eprintln!("[RUN] abi-cafe (skipped)"); - return; - } - eprintln!("Building sysroot for abi-cafe"); build_sysroot::build_sysroot( dirs, diff --git a/build_system/mod.rs b/build_system/mod.rs index 6f388cd605fce..8dcbe8de189b2 100644 --- a/build_system/mod.rs +++ b/build_system/mod.rs @@ -32,6 +32,7 @@ enum Command { Prepare, Build, Test, + AbiCafe, Bench, } @@ -61,6 +62,7 @@ pub fn main() { Some("prepare") => Command::Prepare, Some("build") => Command::Build, Some("test") => Command::Test, + Some("abi-cafe") => Command::AbiCafe, Some("bench") => Command::Bench, Some(flag) if flag.starts_with('-') => arg_error!("Expected command found flag {}", flag), Some(command) => arg_error!("Unknown command {}", command), @@ -156,19 +158,13 @@ pub fn main() { &bootstrap_host_compiler, target_triple.clone(), ); - - if bootstrap_host_compiler.triple == target_triple { - abi_cafe::run( - channel, - sysroot_kind, - &dirs, - &cg_clif_dylib, - &bootstrap_host_compiler, - ); - } else { - eprintln!("[RUN] abi-cafe (skipped, cross-compilation not supported)"); - return; + } + Command::AbiCafe => { + if bootstrap_host_compiler.triple != target_triple { + eprintln!("Abi-cafe doesn't support cross-compilation"); + process::exit(1); } + abi_cafe::run(channel, sysroot_kind, &dirs, &cg_clif_dylib, &bootstrap_host_compiler); } Command::Build => { build_sysroot::build_sysroot( diff --git a/build_system/usage.txt b/build_system/usage.txt index 9185255155426..ab98ccc35a58a 100644 --- a/build_system/usage.txt +++ b/build_system/usage.txt @@ -4,6 +4,7 @@ USAGE: ./y.rs prepare [--out-dir DIR] ./y.rs build [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] ./y.rs test [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] + ./y.rs abi-cafe [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] ./y.rs bench [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--no-unstable-features] OPTIONS: diff --git a/config.txt b/config.txt index d9912a8158f67..d49cc90791a5d 100644 --- a/config.txt +++ b/config.txt @@ -49,5 +49,3 @@ test.libcore test.regex-shootout-regex-dna test.regex test.portable-simd - -testsuite.abi-cafe From 08c7230989ff02471aeaf93aa4325a8ef6e9c30d Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Wed, 7 Dec 2022 09:24:00 +0000 Subject: [PATCH 202/500] Move compiler input and ouput paths into session --- src/debuginfo/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/debuginfo/mod.rs b/src/debuginfo/mod.rs index 2ba012a77b0a9..28fbcb15b2b58 100644 --- a/src/debuginfo/mod.rs +++ b/src/debuginfo/mod.rs @@ -68,7 +68,7 @@ impl DebugContext { .working_dir .to_string_lossy(FileNameDisplayPreference::Remapped) .into_owned(); - let (name, file_info) = match tcx.sess.local_crate_source_file.clone() { + let (name, file_info) = match tcx.sess.local_crate_source_file() { Some(path) => { let name = path.to_string_lossy().into_owned(); (name, None) From 25f0147db2ca7538ab9324d63bc1e0060f67f9c8 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Mon, 16 Jan 2023 11:41:19 -0800 Subject: [PATCH 203/500] implement Hash for proc_macro::LineColumn --- library/proc_macro/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index f0e4f5d8a8013..1699f0d55bc7e 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -581,7 +581,7 @@ impl fmt::Debug for Span { /// A line-column pair representing the start or end of a `Span`. #[unstable(feature = "proc_macro_span", issue = "54725")] -#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct LineColumn { /// The 1-indexed line in the source file on which the span starts or ends (inclusive). #[unstable(feature = "proc_macro_span", issue = "54725")] From cd92bca49d947db62586a59bfeaed4254080e3e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Mi=C4=85sko?= Date: Tue, 17 Jan 2023 00:00:00 +0000 Subject: [PATCH 204/500] Omit needless funclet partitioning --- compiler/rustc_codegen_ssa/src/mir/block.rs | 76 ++++++++++----------- compiler/rustc_codegen_ssa/src/mir/mod.rs | 7 +- 2 files changed, 40 insertions(+), 43 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 978aff511bfa7..ebb15376c69ff 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -39,7 +39,6 @@ enum MergingSucc { struct TerminatorCodegenHelper<'tcx> { bb: mir::BasicBlock, terminator: &'tcx mir::Terminator<'tcx>, - funclet_bb: Option, } impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { @@ -49,28 +48,24 @@ impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { &self, fx: &'b mut FunctionCx<'a, 'tcx, Bx>, ) -> Option<&'b Bx::Funclet> { - let funclet_bb = self.funclet_bb?; - if base::wants_msvc_seh(fx.cx.tcx().sess) { - // If `landing_pad_for` hasn't been called yet to create the `Funclet`, - // it has to be now. This may not seem necessary, as RPO should lead - // to all the unwind edges being visited (and so to `landing_pad_for` - // getting called for them), before building any of the blocks inside - // the funclet itself - however, if MIR contains edges that end up not - // being needed in the LLVM IR after monomorphization, the funclet may - // be unreachable, and we don't have yet a way to skip building it in - // such an eventuality (which may be a better solution than this). - if fx.funclets[funclet_bb].is_none() { - fx.landing_pad_for(funclet_bb); - } - - Some( - fx.funclets[funclet_bb] - .as_ref() - .expect("landing_pad_for didn't also create funclets entry"), - ) - } else { - None + let cleanup_kinds = (&fx.cleanup_kinds).as_ref()?; + let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?; + // If `landing_pad_for` hasn't been called yet to create the `Funclet`, + // it has to be now. This may not seem necessary, as RPO should lead + // to all the unwind edges being visited (and so to `landing_pad_for` + // getting called for them), before building any of the blocks inside + // the funclet itself - however, if MIR contains edges that end up not + // being needed in the LLVM IR after monomorphization, the funclet may + // be unreachable, and we don't have yet a way to skip building it in + // such an eventuality (which may be a better solution than this). + if fx.funclets[funclet_bb].is_none() { + fx.landing_pad_for(funclet_bb); } + Some( + fx.funclets[funclet_bb] + .as_ref() + .expect("landing_pad_for didn't also create funclets entry"), + ) } /// Get a basic block (creating it if necessary), possibly with cleanup @@ -104,23 +99,24 @@ impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { fx: &mut FunctionCx<'a, 'tcx, Bx>, target: mir::BasicBlock, ) -> (bool, bool) { - let target_funclet = fx.cleanup_kinds[target].funclet_bb(target); - let (needs_landing_pad, is_cleanupret) = match (self.funclet_bb, target_funclet) { - (None, None) => (false, false), - (None, Some(_)) => (true, false), - (Some(_), None) => { - let span = self.terminator.source_info.span; - span_bug!(span, "{:?} - jump out of cleanup?", self.terminator); - } - (Some(f), Some(t_f)) => { - if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) { - (false, false) - } else { - (true, true) + if let Some(ref cleanup_kinds) = fx.cleanup_kinds { + let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb); + let target_funclet = cleanup_kinds[target].funclet_bb(target); + let (needs_landing_pad, is_cleanupret) = match (funclet_bb, target_funclet) { + (None, None) => (false, false), + (None, Some(_)) => (true, false), + (Some(f), Some(t_f)) => (f != t_f, f != t_f), + (Some(_), None) => { + let span = self.terminator.source_info.span; + span_bug!(span, "{:?} - jump out of cleanup?", self.terminator); } - } - }; - (needs_landing_pad, is_cleanupret) + }; + (needs_landing_pad, is_cleanupret) + } else { + let needs_landing_pad = !fx.mir[self.bb].is_cleanup && fx.mir[target].is_cleanup; + let is_cleanupret = false; + (needs_landing_pad, is_cleanupret) + } } fn funclet_br>( @@ -1253,9 +1249,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { ) -> MergingSucc { debug!("codegen_terminator: {:?}", terminator); - // Create the cleanup bundle, if needed. - let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb); - let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb }; + let helper = TerminatorCodegenHelper { bb, terminator }; let mergeable_succ = || { // Note: any call to `switch_to_block` will invalidate a `true` value diff --git a/compiler/rustc_codegen_ssa/src/mir/mod.rs b/compiler/rustc_codegen_ssa/src/mir/mod.rs index 79c66a955e76d..bb265b8289ed9 100644 --- a/compiler/rustc_codegen_ssa/src/mir/mod.rs +++ b/compiler/rustc_codegen_ssa/src/mir/mod.rs @@ -1,3 +1,4 @@ +use crate::base; use crate::traits::*; use rustc_middle::mir; use rustc_middle::mir::interpret::ErrorHandled; @@ -58,7 +59,7 @@ pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> { cached_llbbs: IndexVec>, /// The funclet status of each basic block - cleanup_kinds: IndexVec, + cleanup_kinds: Option>, /// When targeting MSVC, this stores the cleanup info for each funclet BB. /// This is initialized at the same time as the `landing_pads` entry for the @@ -166,7 +167,9 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( start_bx.set_personality_fn(cx.eh_personality()); } - let cleanup_kinds = analyze::cleanup_kinds(&mir); + let cleanup_kinds = + if base::wants_msvc_seh(cx.tcx().sess) { Some(analyze::cleanup_kinds(&mir)) } else { None }; + let cached_llbbs: IndexVec> = mir.basic_blocks .indices() From 783caf3702fa28aeeaebd413eb9072399506eab1 Mon Sep 17 00:00:00 2001 From: Kyle Huey Date: Fri, 13 Jan 2023 06:29:46 -0800 Subject: [PATCH 205/500] Append .dwp to the binary filename instead of replacing the existing extension. gdb et al. expect to find the dwp file at .dwp, even if already has an extension (e.g. libfoo.so's dwp is expected to be at libfoo.so.dwp). --- compiler/rustc_codegen_ssa/src/back/link.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 8ca7103ed482c..06dbeac2850e7 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -599,7 +599,8 @@ fn link_dwarf_object<'a>( cg_results: &CodegenResults, executable_out_filename: &Path, ) { - let dwp_out_filename = executable_out_filename.with_extension("dwp"); + let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string(); + dwp_out_filename.push(".dwp"); debug!(?dwp_out_filename, ?executable_out_filename); #[derive(Default)] From 2d824206655bfb26cb5eed43490ee396542b153e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 15 Jan 2023 22:36:46 +0000 Subject: [PATCH 206/500] Teach parser to understand fake anonymous enum syntax Parse `-> Ty | OtherTy`. Parse type ascription in top level patterns. --- compiler/rustc_ast/src/ast.rs | 3 + compiler/rustc_ast/src/mut_visit.rs | 2 +- compiler/rustc_ast/src/visit.rs | 4 +- compiler/rustc_ast_lowering/src/lib.rs | 1 + compiler/rustc_ast_pretty/src/pprust/state.rs | 3 + .../rustc_parse/src/parser/diagnostics.rs | 50 +++++++++--- compiler/rustc_parse/src/parser/pat.rs | 3 +- compiler/rustc_parse/src/parser/ty.rs | 67 ++++++++++++++- compiler/rustc_passes/src/hir_stats.rs | 1 + src/tools/rustfmt/src/types.rs | 4 +- tests/ui/parser/anon-enums.rs | 19 +++++ tests/ui/parser/anon-enums.stderr | 81 +++++++++++++++++++ .../issues/issue-87086-colon-path-sep.stderr | 72 ++++++++++++----- 13 files changed, 270 insertions(+), 40 deletions(-) create mode 100644 tests/ui/parser/anon-enums.rs create mode 100644 tests/ui/parser/anon-enums.stderr diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 7de594719ddc4..3aad51325dcd6 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -2096,6 +2096,9 @@ pub enum TyKind { Err, /// Placeholder for a `va_list`. CVarArgs, + /// Placeholder for "anonymous enums", which don't exist, but keeping their + /// information around lets us produce better diagnostics. + AnonEnum(Vec>), } impl TyKind { diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index 77f342d1eb322..894885cf0fea7 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -470,7 +470,7 @@ pub fn noop_visit_ty(ty: &mut P, vis: &mut T) { vis.visit_fn_decl(decl); vis.visit_span(decl_span); } - TyKind::Tup(tys) => visit_vec(tys, |ty| vis.visit_ty(ty)), + TyKind::AnonEnum(tys) | TyKind::Tup(tys) => visit_vec(tys, |ty| vis.visit_ty(ty)), TyKind::Paren(ty) => vis.visit_ty(ty), TyKind::Path(qself, path) => { vis.visit_qself(qself); diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index e8823eff83afe..1ab70f0309c01 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -400,8 +400,8 @@ pub fn walk_ty<'a, V: Visitor<'a>>(visitor: &mut V, typ: &'a Ty) { walk_list!(visitor, visit_lifetime, opt_lifetime, LifetimeCtxt::Ref); visitor.visit_ty(&mutable_type.ty) } - TyKind::Tup(tuple_element_types) => { - walk_list!(visitor, visit_ty, tuple_element_types); + TyKind::AnonEnum(tys) | TyKind::Tup(tys) => { + walk_list!(visitor, visit_ty, tys); } TyKind::BareFn(function_declaration) => { walk_list!(visitor, visit_generic_param, &function_declaration.generic_params); diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 41d4a5679f1a0..a60d02002da33 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1235,6 +1235,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let kind = match &t.kind { TyKind::Infer => hir::TyKind::Infer, TyKind::Err => hir::TyKind::Err, + TyKind::AnonEnum(_) => hir::TyKind::Err, TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)), TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)), TyKind::Ref(region, mt) => { diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 6a8064b0e874e..3f9b96a6158a1 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -1041,6 +1041,9 @@ impl<'a> State<'a> { } self.pclose(); } + ast::TyKind::AnonEnum(elts) => { + self.strsep("|", false, Inconsistent, elts, |s, ty| s.print_type(ty)); + } ast::TyKind::Paren(typ) => { self.popen(); self.print_type(typ); diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 4c918c6702ed9..07bd76dc39ba9 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -2372,7 +2372,7 @@ impl<'a> Parser<'a> { /// Some special error handling for the "top-level" patterns in a match arm, /// `for` loop, `let`, &c. (in contrast to subpatterns within such). - pub(crate) fn maybe_recover_colon_colon_in_pat_typo( + pub(crate) fn maybe_recover_colon_colon_in_pat_typo_or_anon_enum( &mut self, mut first_pat: P, expected: Expected, @@ -2383,26 +2383,41 @@ impl<'a> Parser<'a> { if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..)) || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident()) { + let mut snapshot_type = self.create_snapshot_for_diagnostic(); + snapshot_type.bump(); // `:` + match snapshot_type.parse_ty() { + Err(inner_err) => { + inner_err.cancel(); + } + Ok(ty) => { + let Err(mut err) = self.expected_one_of_not_found(&[], &[]) else { + return first_pat; + }; + err.span_label(ty.span, "specifying the type of a pattern isn't supported"); + self.restore_snapshot(snapshot_type); + let span = first_pat.span.to(ty.span); + first_pat = self.mk_pat(span, PatKind::Wild); + err.emit(); + } + } return first_pat; } // The pattern looks like it might be a path with a `::` -> `:` typo: // `match foo { bar:baz => {} }` - let span = self.token.span; + let colon_span = self.token.span; // We only emit "unexpected `:`" error here if we can successfully parse the // whole pattern correctly in that case. - let snapshot = self.create_snapshot_for_diagnostic(); + let mut snapshot_pat = self.create_snapshot_for_diagnostic(); + let mut snapshot_type = self.create_snapshot_for_diagnostic(); // Create error for "unexpected `:`". match self.expected_one_of_not_found(&[], &[]) { Err(mut err) => { - self.bump(); // Skip the `:`. - match self.parse_pat_no_top_alt(expected) { + snapshot_pat.bump(); // Skip the `:`. + snapshot_type.bump(); // Skip the `:`. + match snapshot_pat.parse_pat_no_top_alt(expected) { Err(inner_err) => { - // Carry on as if we had not done anything, callers will emit a - // reasonable error. inner_err.cancel(); - err.cancel(); - self.restore_snapshot(snapshot); } Ok(mut pat) => { // We've parsed the rest of the pattern. @@ -2466,8 +2481,8 @@ impl<'a> Parser<'a> { _ => {} } if show_sugg { - err.span_suggestion( - span, + err.span_suggestion_verbose( + colon_span.until(self.look_ahead(1, |t| t.span)), "maybe write a path separator here", "::", Applicability::MaybeIncorrect, @@ -2475,13 +2490,22 @@ impl<'a> Parser<'a> { } else { first_pat = self.mk_pat(new_span, PatKind::Wild); } - err.emit(); + self.restore_snapshot(snapshot_pat); } } + match snapshot_type.parse_ty() { + Err(inner_err) => { + inner_err.cancel(); + } + Ok(ty) => { + err.span_label(ty.span, "specifying the type of a pattern isn't supported"); + self.restore_snapshot(snapshot_type); + } + } + err.emit(); } _ => { // Carry on as if we had not done anything. This should be unreachable. - self.restore_snapshot(snapshot); } }; first_pat diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index e73a17ced7deb..e5411538eea22 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -116,7 +116,8 @@ impl<'a> Parser<'a> { // Check if the user wrote `foo:bar` instead of `foo::bar`. if ra == RecoverColon::Yes { - first_pat = self.maybe_recover_colon_colon_in_pat_typo(first_pat, expected); + first_pat = + self.maybe_recover_colon_colon_in_pat_typo_or_anon_enum(first_pat, expected); } if let Some(leading_vert_span) = leading_vert_span { diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index a6f702e542869..72994df6f9f46 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -11,6 +11,7 @@ use rustc_ast::{ self as ast, BareFnTy, FnRetTy, GenericBound, GenericBounds, GenericParam, Generics, Lifetime, MacCall, MutTy, Mutability, PolyTraitRef, TraitBoundModifier, TraitObjectSyntax, Ty, TyKind, }; +use rustc_ast_pretty::pprust; use rustc_errors::{pluralize, struct_span_err, Applicability, PResult}; use rustc_span::source_map::Span; use rustc_span::symbol::{kw, sym, Ident}; @@ -43,17 +44,24 @@ pub(super) enum AllowPlus { No, } -#[derive(PartialEq)] +#[derive(PartialEq, Clone, Copy)] pub(super) enum RecoverQPath { Yes, No, } +#[derive(PartialEq, Clone, Copy)] pub(super) enum RecoverQuestionMark { Yes, No, } +#[derive(PartialEq, Clone, Copy)] +pub(super) enum RecoverAnonEnum { + Yes, + No, +} + /// Signals whether parsing a type should recover `->`. /// /// More specifically, when parsing a function like: @@ -86,7 +94,7 @@ impl RecoverReturnSign { } // Is `...` (`CVarArgs`) legal at this level of type parsing? -#[derive(PartialEq)] +#[derive(PartialEq, Clone, Copy)] enum AllowCVariadic { Yes, No, @@ -111,6 +119,7 @@ impl<'a> Parser<'a> { RecoverReturnSign::Yes, None, RecoverQuestionMark::Yes, + RecoverAnonEnum::No, ) } @@ -125,6 +134,7 @@ impl<'a> Parser<'a> { RecoverReturnSign::Yes, Some(ty_params), RecoverQuestionMark::Yes, + RecoverAnonEnum::No, ) } @@ -139,6 +149,7 @@ impl<'a> Parser<'a> { RecoverReturnSign::Yes, None, RecoverQuestionMark::Yes, + RecoverAnonEnum::Yes, ) } @@ -156,6 +167,7 @@ impl<'a> Parser<'a> { RecoverReturnSign::Yes, None, RecoverQuestionMark::Yes, + RecoverAnonEnum::No, ) } @@ -169,6 +181,7 @@ impl<'a> Parser<'a> { RecoverReturnSign::Yes, None, RecoverQuestionMark::No, + RecoverAnonEnum::No, ) } @@ -180,6 +193,7 @@ impl<'a> Parser<'a> { RecoverReturnSign::Yes, None, RecoverQuestionMark::No, + RecoverAnonEnum::No, ) } @@ -192,6 +206,7 @@ impl<'a> Parser<'a> { RecoverReturnSign::OnlyFatArrow, None, RecoverQuestionMark::Yes, + RecoverAnonEnum::No, ) } @@ -211,6 +226,7 @@ impl<'a> Parser<'a> { recover_return_sign, None, RecoverQuestionMark::Yes, + RecoverAnonEnum::Yes, )?; FnRetTy::Ty(ty) } else if recover_return_sign.can_recover(&self.token.kind) { @@ -232,6 +248,7 @@ impl<'a> Parser<'a> { recover_return_sign, None, RecoverQuestionMark::Yes, + RecoverAnonEnum::Yes, )?; FnRetTy::Ty(ty) } else { @@ -247,6 +264,7 @@ impl<'a> Parser<'a> { recover_return_sign: RecoverReturnSign, ty_generics: Option<&Generics>, recover_question_mark: RecoverQuestionMark, + recover_anon_enum: RecoverAnonEnum, ) -> PResult<'a, P> { let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes; maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery); @@ -325,14 +343,55 @@ impl<'a> Parser<'a> { let mut ty = self.mk_ty(span, kind); // Try to recover from use of `+` with incorrect priority. - if matches!(allow_plus, AllowPlus::Yes) { + if allow_plus == AllowPlus::Yes { self.maybe_recover_from_bad_type_plus(&ty)?; } else { self.maybe_report_ambiguous_plus(impl_dyn_multi, &ty); } - if let RecoverQuestionMark::Yes = recover_question_mark { + if RecoverQuestionMark::Yes == recover_question_mark { ty = self.maybe_recover_from_question_mark(ty); } + if recover_anon_enum == RecoverAnonEnum::Yes + && self.check_noexpect(&token::BinOp(token::Or)) + && self.look_ahead(1, |t| t.can_begin_type()) + { + let mut pipes = vec![self.token.span]; + let mut types = vec![ty]; + loop { + if !self.eat(&token::BinOp(token::Or)) { + break; + } + pipes.push(self.prev_token.span); + types.push(self.parse_ty_common( + allow_plus, + allow_c_variadic, + recover_qpath, + recover_return_sign, + ty_generics, + recover_question_mark, + RecoverAnonEnum::No, + )?); + } + let mut err = self.struct_span_err(pipes, "anonymous enums are not supported"); + for ty in &types { + err.span_label(ty.span, ""); + } + err.help(&format!( + "create a named `enum` and use it here instead:\nenum Name {{\n{}\n}}", + types + .iter() + .enumerate() + .map(|(i, t)| format!( + " Variant{}({}),", + i + 1, // Lets not confuse people with zero-indexing :) + pprust::to_string(|s| s.print_type(&t)), + )) + .collect::>() + .join("\n"), + )); + err.emit(); + return Ok(self.mk_ty(lo.to(self.prev_token.span), TyKind::AnonEnum(types))); + } if allow_qpath_recovery { self.maybe_recover_from_bad_qpath(ty) } else { Ok(ty) } } diff --git a/compiler/rustc_passes/src/hir_stats.rs b/compiler/rustc_passes/src/hir_stats.rs index b86d2316820ce..312bd8839e0d0 100644 --- a/compiler/rustc_passes/src/hir_stats.rs +++ b/compiler/rustc_passes/src/hir_stats.rs @@ -579,6 +579,7 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { [ Slice, Array, + AnonEnum, Ptr, Ref, BareFn, diff --git a/src/tools/rustfmt/src/types.rs b/src/tools/rustfmt/src/types.rs index c1991e8d2c808..f065ec680d724 100644 --- a/src/tools/rustfmt/src/types.rs +++ b/src/tools/rustfmt/src/types.rs @@ -839,7 +839,9 @@ impl Rewrite for ast::Ty { }) } ast::TyKind::CVarArgs => Some("...".to_owned()), - ast::TyKind::Err => Some(context.snippet(self.span).to_owned()), + ast::TyKind::AnonEnum(_) | ast::TyKind::Err => { + Some(context.snippet(self.span).to_owned()) + } ast::TyKind::Typeof(ref anon_const) => rewrite_call( context, "typeof", diff --git a/tests/ui/parser/anon-enums.rs b/tests/ui/parser/anon-enums.rs new file mode 100644 index 0000000000000..a8b5e8359d996 --- /dev/null +++ b/tests/ui/parser/anon-enums.rs @@ -0,0 +1,19 @@ +fn foo(x: bool | i32) -> i32 | f64 { +//~^ ERROR anonymous enums are not supported +//~| ERROR anonymous enums are not supported + match x { + x: i32 => x, //~ ERROR expected + //~^ ERROR failed to resolve + true => 42., + false => 0.333, + } +} + +fn main() { + match foo(true) { + 42: i32 => (), //~ ERROR expected + _: f64 => (), //~ ERROR expected + x: i32 => (), //~ ERROR expected + //~^ ERROR failed to resolve + } +} diff --git a/tests/ui/parser/anon-enums.stderr b/tests/ui/parser/anon-enums.stderr new file mode 100644 index 0000000000000..4febf2df0dc72 --- /dev/null +++ b/tests/ui/parser/anon-enums.stderr @@ -0,0 +1,81 @@ +error: anonymous enums are not supported + --> $DIR/anon-enums.rs:1:16 + | +LL | fn foo(x: bool | i32) -> i32 | f64 { + | ---- ^ --- + | + = help: create a named `enum` and use it here instead: + enum Name { + Variant1(bool), + Variant2(i32), + } + +error: anonymous enums are not supported + --> $DIR/anon-enums.rs:1:30 + | +LL | fn foo(x: bool | i32) -> i32 | f64 { + | --- ^ --- + | + = help: create a named `enum` and use it here instead: + enum Name { + Variant1(i32), + Variant2(f64), + } + +error: expected one of `@` or `|`, found `:` + --> $DIR/anon-enums.rs:5:10 + | +LL | x: i32 => x, + | ^ --- specifying the type of a pattern isn't supported + | | + | expected one of `@` or `|` + | +help: maybe write a path separator here + | +LL | x::i32 => x, + | ~~ + +error: expected one of `...`, `..=`, `..`, or `|`, found `:` + --> $DIR/anon-enums.rs:14:11 + | +LL | 42: i32 => (), + | ^ --- specifying the type of a pattern isn't supported + | | + | expected one of `...`, `..=`, `..`, or `|` + +error: expected `|`, found `:` + --> $DIR/anon-enums.rs:15:10 + | +LL | _: f64 => (), + | ^ --- specifying the type of a pattern isn't supported + | | + | expected `|` + +error: expected one of `@` or `|`, found `:` + --> $DIR/anon-enums.rs:16:10 + | +LL | x: i32 => (), + | ^ --- specifying the type of a pattern isn't supported + | | + | expected one of `@` or `|` + | +help: maybe write a path separator here + | +LL | x::i32 => (), + | ~~ + +error[E0433]: failed to resolve: use of undeclared crate or module `x` + --> $DIR/anon-enums.rs:5:9 + | +LL | x: i32 => x, + | ^ use of undeclared crate or module `x` + +error[E0433]: failed to resolve: use of undeclared crate or module `x` + --> $DIR/anon-enums.rs:16:9 + | +LL | x: i32 => (), + | ^ use of undeclared crate or module `x` + +error: aborting due to 8 previous errors + +For more information about this error, try `rustc --explain E0433`. diff --git a/tests/ui/parser/issues/issue-87086-colon-path-sep.stderr b/tests/ui/parser/issues/issue-87086-colon-path-sep.stderr index 2050a16beb349..ed05bfe8b0a32 100644 --- a/tests/ui/parser/issues/issue-87086-colon-path-sep.stderr +++ b/tests/ui/parser/issues/issue-87086-colon-path-sep.stderr @@ -2,82 +2,118 @@ error: expected one of `@` or `|`, found `:` --> $DIR/issue-87086-colon-path-sep.rs:17:12 | LL | Foo:Bar => {} - | ^ + | ^--- specifying the type of a pattern isn't supported | | | expected one of `@` or `|` - | help: maybe write a path separator here: `::` + | +help: maybe write a path separator here + | +LL | Foo::Bar => {} + | ~~ error: expected one of `!`, `(`, `...`, `..=`, `..`, `::`, `{`, or `|`, found `:` --> $DIR/issue-87086-colon-path-sep.rs:23:17 | LL | qux::Foo:Bar => {} - | ^ + | ^--- specifying the type of a pattern isn't supported | | | expected one of 8 possible tokens - | help: maybe write a path separator here: `::` + | +help: maybe write a path separator here + | +LL | qux::Foo::Bar => {} + | ~~ error: expected one of `@` or `|`, found `:` --> $DIR/issue-87086-colon-path-sep.rs:29:12 | LL | qux:Foo::Baz => {} - | ^ + | ^-------- specifying the type of a pattern isn't supported | | | expected one of `@` or `|` - | help: maybe write a path separator here: `::` + | +help: maybe write a path separator here + | +LL | qux::Foo::Baz => {} + | ~~ error: expected one of `@` or `|`, found `:` --> $DIR/issue-87086-colon-path-sep.rs:35:12 | LL | qux: Foo::Baz if true => {} - | ^ + | ^ -------- specifying the type of a pattern isn't supported | | | expected one of `@` or `|` - | help: maybe write a path separator here: `::` + | +help: maybe write a path separator here + | +LL | qux::Foo::Baz if true => {} + | ~~ error: expected one of `@` or `|`, found `:` --> $DIR/issue-87086-colon-path-sep.rs:40:15 | LL | if let Foo:Bar = f() { - | ^ + | ^--- specifying the type of a pattern isn't supported | | | expected one of `@` or `|` - | help: maybe write a path separator here: `::` + | +help: maybe write a path separator here + | +LL | if let Foo::Bar = f() { + | ~~ error: expected one of `@` or `|`, found `:` --> $DIR/issue-87086-colon-path-sep.rs:48:16 | LL | ref qux: Foo::Baz => {} - | ^ + | ^ -------- specifying the type of a pattern isn't supported | | | expected one of `@` or `|` - | help: maybe write a path separator here: `::` + | +help: maybe write a path separator here + | +LL | ref qux::Foo::Baz => {} + | ~~ error: expected one of `@` or `|`, found `:` --> $DIR/issue-87086-colon-path-sep.rs:57:16 | LL | mut qux: Foo::Baz => {} - | ^ + | ^ -------- specifying the type of a pattern isn't supported | | | expected one of `@` or `|` - | help: maybe write a path separator here: `::` + | +help: maybe write a path separator here + | +LL | mut qux::Foo::Baz => {} + | ~~ error: expected one of `@` or `|`, found `:` --> $DIR/issue-87086-colon-path-sep.rs:68:12 | LL | Foo:Bar::Baz => {} - | ^ + | ^-------- specifying the type of a pattern isn't supported | | | expected one of `@` or `|` - | help: maybe write a path separator here: `::` + | +help: maybe write a path separator here + | +LL | Foo::Bar::Baz => {} + | ~~ error: expected one of `@` or `|`, found `:` --> $DIR/issue-87086-colon-path-sep.rs:75:12 | LL | Foo:Bar => {} - | ^ + | ^--- specifying the type of a pattern isn't supported | | | expected one of `@` or `|` - | help: maybe write a path separator here: `::` + | +help: maybe write a path separator here + | +LL | Foo::Bar => {} + | ~~ error[E0433]: failed to resolve: `Bar` is a variant, not a module --> $DIR/issue-87086-colon-path-sep.rs:68:13 From c847a01a3b1f620c4fdb98c75805033e768975d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Tue, 17 Jan 2023 01:50:45 +0000 Subject: [PATCH 207/500] Emit fewer errors on patterns with possible type ascription --- .../rustc_parse/src/parser/diagnostics.rs | 2 ++ tests/ui/parser/anon-enums.rs | 2 -- tests/ui/parser/anon-enums.stderr | 21 ++++--------------- .../issues/issue-87086-colon-path-sep.rs | 1 - .../issues/issue-87086-colon-path-sep.stderr | 11 ++-------- 5 files changed, 8 insertions(+), 29 deletions(-) diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 07bd76dc39ba9..eda7046c748e5 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -2500,6 +2500,8 @@ impl<'a> Parser<'a> { Ok(ty) => { err.span_label(ty.span, "specifying the type of a pattern isn't supported"); self.restore_snapshot(snapshot_type); + let new_span = first_pat.span.to(ty.span); + first_pat = self.mk_pat(new_span, PatKind::Wild); } } err.emit(); diff --git a/tests/ui/parser/anon-enums.rs b/tests/ui/parser/anon-enums.rs index a8b5e8359d996..56b8a3d43bedf 100644 --- a/tests/ui/parser/anon-enums.rs +++ b/tests/ui/parser/anon-enums.rs @@ -3,7 +3,6 @@ fn foo(x: bool | i32) -> i32 | f64 { //~| ERROR anonymous enums are not supported match x { x: i32 => x, //~ ERROR expected - //~^ ERROR failed to resolve true => 42., false => 0.333, } @@ -14,6 +13,5 @@ fn main() { 42: i32 => (), //~ ERROR expected _: f64 => (), //~ ERROR expected x: i32 => (), //~ ERROR expected - //~^ ERROR failed to resolve } } diff --git a/tests/ui/parser/anon-enums.stderr b/tests/ui/parser/anon-enums.stderr index 4febf2df0dc72..8415822566091 100644 --- a/tests/ui/parser/anon-enums.stderr +++ b/tests/ui/parser/anon-enums.stderr @@ -36,7 +36,7 @@ LL | x::i32 => x, | ~~ error: expected one of `...`, `..=`, `..`, or `|`, found `:` - --> $DIR/anon-enums.rs:14:11 + --> $DIR/anon-enums.rs:13:11 | LL | 42: i32 => (), | ^ --- specifying the type of a pattern isn't supported @@ -44,7 +44,7 @@ LL | 42: i32 => (), | expected one of `...`, `..=`, `..`, or `|` error: expected `|`, found `:` - --> $DIR/anon-enums.rs:15:10 + --> $DIR/anon-enums.rs:14:10 | LL | _: f64 => (), | ^ --- specifying the type of a pattern isn't supported @@ -52,7 +52,7 @@ LL | _: f64 => (), | expected `|` error: expected one of `@` or `|`, found `:` - --> $DIR/anon-enums.rs:16:10 + --> $DIR/anon-enums.rs:15:10 | LL | x: i32 => (), | ^ --- specifying the type of a pattern isn't supported @@ -64,18 +64,5 @@ help: maybe write a path separator here LL | x::i32 => (), | ~~ -error[E0433]: failed to resolve: use of undeclared crate or module `x` - --> $DIR/anon-enums.rs:5:9 - | -LL | x: i32 => x, - | ^ use of undeclared crate or module `x` - -error[E0433]: failed to resolve: use of undeclared crate or module `x` - --> $DIR/anon-enums.rs:16:9 - | -LL | x: i32 => (), - | ^ use of undeclared crate or module `x` - -error: aborting due to 8 previous errors +error: aborting due to 6 previous errors -For more information about this error, try `rustc --explain E0433`. diff --git a/tests/ui/parser/issues/issue-87086-colon-path-sep.rs b/tests/ui/parser/issues/issue-87086-colon-path-sep.rs index 0b7b67496d6f3..e1ea38f2795df 100644 --- a/tests/ui/parser/issues/issue-87086-colon-path-sep.rs +++ b/tests/ui/parser/issues/issue-87086-colon-path-sep.rs @@ -68,7 +68,6 @@ fn main() { Foo:Bar::Baz => {} //~^ ERROR: expected one of //~| HELP: maybe write a path separator here - //~| ERROR: failed to resolve: `Bar` is a variant, not a module } match myfoo { Foo::Bar => {} diff --git a/tests/ui/parser/issues/issue-87086-colon-path-sep.stderr b/tests/ui/parser/issues/issue-87086-colon-path-sep.stderr index ed05bfe8b0a32..63b072ac4cdc6 100644 --- a/tests/ui/parser/issues/issue-87086-colon-path-sep.stderr +++ b/tests/ui/parser/issues/issue-87086-colon-path-sep.stderr @@ -103,7 +103,7 @@ LL | Foo::Bar::Baz => {} | ~~ error: expected one of `@` or `|`, found `:` - --> $DIR/issue-87086-colon-path-sep.rs:75:12 + --> $DIR/issue-87086-colon-path-sep.rs:74:12 | LL | Foo:Bar => {} | ^--- specifying the type of a pattern isn't supported @@ -115,12 +115,5 @@ help: maybe write a path separator here LL | Foo::Bar => {} | ~~ -error[E0433]: failed to resolve: `Bar` is a variant, not a module - --> $DIR/issue-87086-colon-path-sep.rs:68:13 - | -LL | Foo:Bar::Baz => {} - | ^^^ `Bar` is a variant, not a module - -error: aborting due to 10 previous errors +error: aborting due to 9 previous errors -For more information about this error, try `rustc --explain E0433`. From be2ec32b18f7ad858dc746b26eb3a91a62a2c360 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Tue, 17 Jan 2023 02:45:11 +0000 Subject: [PATCH 208/500] Account for `*` when looking for inner-most path in expression --- .../rustc_borrowck/src/diagnostics/explain_borrow.rs | 4 +++- tests/ui/borrowck/borrowck-bad-nested-calls-move.stderr | 5 +++++ tests/ui/borrowck/borrowck-move-mut-base-ptr.stderr | 2 ++ tests/ui/borrowck/borrowck-unary-move.stderr | 2 ++ tests/ui/nll/polonius/polonius-smoke-test.stderr | 6 +++++- tests/ui/span/dropck-object-cycle.stderr | 2 ++ .../span/regions-infer-borrow-scope-within-loop.stderr | 3 +++ tests/ui/span/send-is-not-static-std-sync.stderr | 9 +++++++++ 8 files changed, 31 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index e4f45c53aefe5..d60facb91b455 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -75,7 +75,9 @@ impl<'tcx> BorrowExplanation<'tcx> { let mut expr_finder = FindExprBySpan::new(span); expr_finder.visit_expr(body.value); if let Some(mut expr) = expr_finder.result { - while let hir::ExprKind::AddrOf(_, _, inner) = &expr.kind { + while let hir::ExprKind::AddrOf(_, _, inner) + | hir::ExprKind::Unary(hir::UnOp::Deref, inner) = &expr.kind + { expr = inner; } if let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind diff --git a/tests/ui/borrowck/borrowck-bad-nested-calls-move.stderr b/tests/ui/borrowck/borrowck-bad-nested-calls-move.stderr index 371bcf2b69cf8..e582ec605defe 100644 --- a/tests/ui/borrowck/borrowck-bad-nested-calls-move.stderr +++ b/tests/ui/borrowck/borrowck-bad-nested-calls-move.stderr @@ -1,6 +1,9 @@ error[E0505]: cannot move out of `a` because it is borrowed --> $DIR/borrowck-bad-nested-calls-move.rs:25:9 | +LL | let mut a: Box<_> = Box::new(1); + | ----- binding `a` declared here +... LL | add( | --- borrow later used by call LL | &*a, @@ -11,6 +14,8 @@ LL | a); error[E0505]: cannot move out of `a` because it is borrowed --> $DIR/borrowck-bad-nested-calls-move.rs:32:9 | +LL | let mut a: Box<_> = Box::new(1); + | ----- binding `a` declared here LL | add( | --- borrow later used by call LL | &*a, diff --git a/tests/ui/borrowck/borrowck-move-mut-base-ptr.stderr b/tests/ui/borrowck/borrowck-move-mut-base-ptr.stderr index d5ff0c501c4bd..cdad20c52bfaf 100644 --- a/tests/ui/borrowck/borrowck-move-mut-base-ptr.stderr +++ b/tests/ui/borrowck/borrowck-move-mut-base-ptr.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `t0` because it is borrowed --> $DIR/borrowck-move-mut-base-ptr.rs:10:14 | +LL | fn foo(t0: &mut isize) { + | -- binding `t0` declared here LL | let p: &isize = &*t0; // Freezes `*t0` | ---- borrow of `*t0` occurs here LL | let t1 = t0; diff --git a/tests/ui/borrowck/borrowck-unary-move.stderr b/tests/ui/borrowck/borrowck-unary-move.stderr index aab225ed4a429..f3b962059f5b4 100644 --- a/tests/ui/borrowck/borrowck-unary-move.stderr +++ b/tests/ui/borrowck/borrowck-unary-move.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/borrowck-unary-move.rs:3:10 | +LL | fn foo(x: Box) -> isize { + | - binding `x` declared here LL | let y = &*x; | --- borrow of `*x` occurs here LL | free(x); diff --git a/tests/ui/nll/polonius/polonius-smoke-test.stderr b/tests/ui/nll/polonius/polonius-smoke-test.stderr index 789d202f73a7b..534813b2d9f5a 100644 --- a/tests/ui/nll/polonius/polonius-smoke-test.stderr +++ b/tests/ui/nll/polonius/polonius-smoke-test.stderr @@ -18,7 +18,9 @@ error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/polonius-smoke-test.rs:18:13 | LL | pub fn use_while_mut_fr(x: &mut i32) -> &mut i32 { - | - let's call the lifetime of this reference `'1` + | - - let's call the lifetime of this reference `'1` + | | + | binding `x` declared here LL | let y = &mut *x; | ------- borrow of `*x` occurs here LL | let z = x; @@ -29,6 +31,8 @@ LL | y error[E0505]: cannot move out of `s` because it is borrowed --> $DIR/polonius-smoke-test.rs:42:5 | +LL | let s = &mut 1; + | - binding `s` declared here LL | let r = &mut *s; | ------- borrow of `*s` occurs here LL | let tmp = foo(&r); diff --git a/tests/ui/span/dropck-object-cycle.stderr b/tests/ui/span/dropck-object-cycle.stderr index 229d17e1cf903..097fb6219f1fd 100644 --- a/tests/ui/span/dropck-object-cycle.stderr +++ b/tests/ui/span/dropck-object-cycle.stderr @@ -1,6 +1,8 @@ error[E0597]: `*m` does not live long enough --> $DIR/dropck-object-cycle.rs:27:31 | +LL | let m : Box = make_val(); + | - binding `m` declared here LL | assert_eq!(object_invoke1(&*m), (4,5)); | ^^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/regions-infer-borrow-scope-within-loop.stderr b/tests/ui/span/regions-infer-borrow-scope-within-loop.stderr index fd67c65c4e917..47931db84cabe 100644 --- a/tests/ui/span/regions-infer-borrow-scope-within-loop.stderr +++ b/tests/ui/span/regions-infer-borrow-scope-within-loop.stderr @@ -1,6 +1,9 @@ error[E0597]: `*x` does not live long enough --> $DIR/regions-infer-borrow-scope-within-loop.rs:13:20 | +LL | let x = make_box(); + | - binding `x` declared here +... LL | y = borrow(&*x); | ^^^ borrowed value does not live long enough ... diff --git a/tests/ui/span/send-is-not-static-std-sync.stderr b/tests/ui/span/send-is-not-static-std-sync.stderr index 28b1c5fe7152a..7dfe94bca603f 100644 --- a/tests/ui/span/send-is-not-static-std-sync.stderr +++ b/tests/ui/span/send-is-not-static-std-sync.stderr @@ -1,6 +1,9 @@ error[E0505]: cannot move out of `y` because it is borrowed --> $DIR/send-is-not-static-std-sync.rs:13:10 | +LL | let y = Box::new(1); + | - binding `y` declared here +LL | let lock = Mutex::new(&x); LL | *lock.lock().unwrap() = &*y; | --- borrow of `*y` occurs here LL | drop(y); @@ -25,6 +28,9 @@ LL | lock.use_ref(); // (Mutex is #[may_dangle] so its dtor does not use `z` error[E0505]: cannot move out of `y` because it is borrowed --> $DIR/send-is-not-static-std-sync.rs:27:10 | +LL | let y = Box::new(1); + | - binding `y` declared here +LL | let lock = RwLock::new(&x); LL | *lock.write().unwrap() = &*y; | --- borrow of `*y` occurs here LL | drop(y); @@ -49,6 +55,9 @@ LL | lock.use_ref(); // (RwLock is #[may_dangle] so its dtor does not use `z error[E0505]: cannot move out of `y` because it is borrowed --> $DIR/send-is-not-static-std-sync.rs:43:10 | +LL | let y = Box::new(1); + | - binding `y` declared here +... LL | tx.send(&*y); | --- borrow of `*y` occurs here LL | drop(y); From c6111e8d232964f11eb3540ed7228de6e13782df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Tue, 17 Jan 2023 02:47:50 +0000 Subject: [PATCH 209/500] Account for field access when looking for inner-most path in expression --- compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs | 3 ++- tests/ui/borrowck/borrow-tuple-fields.stderr | 4 ++++ tests/ui/borrowck/borrowck-field-sensitivity.stderr | 4 ++++ .../borrowck-local-borrow-with-panic-outlives-fn.stderr | 2 ++ 4 files changed, 12 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index d60facb91b455..b6a676ef63690 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -76,7 +76,8 @@ impl<'tcx> BorrowExplanation<'tcx> { expr_finder.visit_expr(body.value); if let Some(mut expr) = expr_finder.result { while let hir::ExprKind::AddrOf(_, _, inner) - | hir::ExprKind::Unary(hir::UnOp::Deref, inner) = &expr.kind + | hir::ExprKind::Unary(hir::UnOp::Deref, inner) + | hir::ExprKind::Field(inner, _) = &expr.kind { expr = inner; } diff --git a/tests/ui/borrowck/borrow-tuple-fields.stderr b/tests/ui/borrowck/borrow-tuple-fields.stderr index befa751a6007b..d7d3efe492cef 100644 --- a/tests/ui/borrowck/borrow-tuple-fields.stderr +++ b/tests/ui/borrowck/borrow-tuple-fields.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/borrow-tuple-fields.rs:12:13 | +LL | let x: (Box<_>, _) = (Box::new(1), 2); + | - binding `x` declared here LL | let r = &x.0; | ---- borrow of `x.0` occurs here LL | let y = x; @@ -32,6 +34,8 @@ LL | a.use_ref(); error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/borrow-tuple-fields.rs:28:13 | +LL | let x = Foo(Box::new(1), 2); + | - binding `x` declared here LL | let r = &x.0; | ---- borrow of `x.0` occurs here LL | let y = x; diff --git a/tests/ui/borrowck/borrowck-field-sensitivity.stderr b/tests/ui/borrowck/borrowck-field-sensitivity.stderr index e009f5913edd0..11812847dd181 100644 --- a/tests/ui/borrowck/borrowck-field-sensitivity.stderr +++ b/tests/ui/borrowck/borrowck-field-sensitivity.stderr @@ -41,6 +41,8 @@ LL | let p = &x.b; error[E0505]: cannot move out of `x.b` because it is borrowed --> $DIR/borrowck-field-sensitivity.rs:34:10 | +LL | let x = A { a: 1, b: Box::new(2) }; + | - binding `x` declared here LL | let p = &x.b; | ---- borrow of `x.b` occurs here LL | drop(x.b); @@ -51,6 +53,8 @@ LL | drop(**p); error[E0505]: cannot move out of `x.b` because it is borrowed --> $DIR/borrowck-field-sensitivity.rs:41:14 | +LL | let x = A { a: 1, b: Box::new(2) }; + | - binding `x` declared here LL | let p = &x.b; | ---- borrow of `x.b` occurs here LL | let _y = A { a: 3, .. x }; diff --git a/tests/ui/borrowck/borrowck-local-borrow-with-panic-outlives-fn.stderr b/tests/ui/borrowck/borrowck-local-borrow-with-panic-outlives-fn.stderr index 6ea6951ad9665..0fdb1dabbc50c 100644 --- a/tests/ui/borrowck/borrowck-local-borrow-with-panic-outlives-fn.stderr +++ b/tests/ui/borrowck/borrowck-local-borrow-with-panic-outlives-fn.stderr @@ -1,6 +1,8 @@ error[E0597]: `z.1` does not live long enough --> $DIR/borrowck-local-borrow-with-panic-outlives-fn.rs:3:15 | +LL | let mut z = (0, 0); + | ----- binding `z` declared here LL | *x = Some(&mut z.1); | ----------^^^^^^^^- | | | From 7b8251e1886924dde68ff9b6a1c02e9973d0bd0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Tue, 17 Jan 2023 02:52:43 +0000 Subject: [PATCH 210/500] Account for method call and indexing when looking for inner-most path in expression --- .../rustc_borrowck/src/diagnostics/explain_borrow.rs | 4 +++- tests/ui/box/leak-alloc.stderr | 2 ++ tests/ui/dropck/drop-with-active-borrows-1.stderr | 2 ++ tests/ui/generator/dropck.stderr | 3 +++ .../ui/issues/issue-52126-assign-op-invariance.stderr | 2 ++ .../ui/macros/format-args-temporaries-in-write.stderr | 4 ++++ tests/ui/match/issue-74050-end-span.stderr | 1 + tests/ui/moves/move-fn-self-receiver.stderr | 2 ++ tests/ui/nll/issue-54556-niconii.stderr | 3 +++ tests/ui/span/borrowck-let-suggestion-suffixes.rs | 1 + tests/ui/span/borrowck-let-suggestion-suffixes.stderr | 11 +++++++---- tests/ui/span/destructor-restrictions.stderr | 2 ++ ...issue-23338-locals-die-before-temps-of-body.stderr | 4 ++++ tests/ui/span/issue-40157.stderr | 7 ++++--- 14 files changed, 40 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index b6a676ef63690..19855075ced80 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -77,7 +77,9 @@ impl<'tcx> BorrowExplanation<'tcx> { if let Some(mut expr) = expr_finder.result { while let hir::ExprKind::AddrOf(_, _, inner) | hir::ExprKind::Unary(hir::UnOp::Deref, inner) - | hir::ExprKind::Field(inner, _) = &expr.kind + | hir::ExprKind::Field(inner, _) + | hir::ExprKind::MethodCall(_, inner, _, _) + | hir::ExprKind::Index(inner, _) = &expr.kind { expr = inner; } diff --git a/tests/ui/box/leak-alloc.stderr b/tests/ui/box/leak-alloc.stderr index e8a6ad0995a0f..5140b58934a5c 100644 --- a/tests/ui/box/leak-alloc.stderr +++ b/tests/ui/box/leak-alloc.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `alloc` because it is borrowed --> $DIR/leak-alloc.rs:26:10 | +LL | let alloc = Alloc {}; + | ----- binding `alloc` declared here LL | let boxed = Box::new_in(10, alloc.by_ref()); | -------------- borrow of `alloc` occurs here LL | let theref = Box::leak(boxed); diff --git a/tests/ui/dropck/drop-with-active-borrows-1.stderr b/tests/ui/dropck/drop-with-active-borrows-1.stderr index 8d6a7f3721f0f..4585b22974cdb 100644 --- a/tests/ui/dropck/drop-with-active-borrows-1.stderr +++ b/tests/ui/dropck/drop-with-active-borrows-1.stderr @@ -1,6 +1,8 @@ error[E0505]: cannot move out of `a` because it is borrowed --> $DIR/drop-with-active-borrows-1.rs:4:10 | +LL | let a = "".to_string(); + | - binding `a` declared here LL | let b: Vec<&str> = a.lines().collect(); | --------- borrow of `a` occurs here LL | drop(a); diff --git a/tests/ui/generator/dropck.stderr b/tests/ui/generator/dropck.stderr index 7bb188352d7a2..b9a3a124acb61 100644 --- a/tests/ui/generator/dropck.stderr +++ b/tests/ui/generator/dropck.stderr @@ -1,6 +1,9 @@ error[E0597]: `*cell` does not live long enough --> $DIR/dropck.rs:10:40 | +LL | let (mut gen, cell); + | ---- binding `cell` declared here +LL | cell = Box::new(RefCell::new(0)); LL | let ref_ = Box::leak(Box::new(Some(cell.borrow_mut()))); | ^^^^^^^^^^^^^^^^^ borrowed value does not live long enough ... diff --git a/tests/ui/issues/issue-52126-assign-op-invariance.stderr b/tests/ui/issues/issue-52126-assign-op-invariance.stderr index d450675776268..2d3b48832c527 100644 --- a/tests/ui/issues/issue-52126-assign-op-invariance.stderr +++ b/tests/ui/issues/issue-52126-assign-op-invariance.stderr @@ -1,6 +1,8 @@ error[E0597]: `line` does not live long enough --> $DIR/issue-52126-assign-op-invariance.rs:34:28 | +LL | for line in vec!["123456789".to_string(), "12345678".to_string()] { + | ---- binding `line` declared here LL | let v: Vec<&str> = line.split_whitespace().collect(); | ^^^^^^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough ... diff --git a/tests/ui/macros/format-args-temporaries-in-write.stderr b/tests/ui/macros/format-args-temporaries-in-write.stderr index 287cd7d67044e..520b2ce50526f 100644 --- a/tests/ui/macros/format-args-temporaries-in-write.stderr +++ b/tests/ui/macros/format-args-temporaries-in-write.stderr @@ -1,6 +1,8 @@ error[E0597]: `mutex` does not live long enough --> $DIR/format-args-temporaries-in-write.rs:41:27 | +LL | let mutex = Mutex; + | ----- binding `mutex` declared here LL | write!(Out, "{}", mutex.lock()) /* no semicolon */ | ^^^^^^^^^^^^ | | @@ -16,6 +18,8 @@ LL | }; error[E0597]: `mutex` does not live long enough --> $DIR/format-args-temporaries-in-write.rs:47:29 | +LL | let mutex = Mutex; + | ----- binding `mutex` declared here LL | writeln!(Out, "{}", mutex.lock()) /* no semicolon */ | ^^^^^^^^^^^^ | | diff --git a/tests/ui/match/issue-74050-end-span.stderr b/tests/ui/match/issue-74050-end-span.stderr index 59c091e44eb87..0b3425f2b1a1c 100644 --- a/tests/ui/match/issue-74050-end-span.stderr +++ b/tests/ui/match/issue-74050-end-span.stderr @@ -4,6 +4,7 @@ error[E0597]: `arg` does not live long enough LL | let _arg = match args.next() { | ---- borrow later stored here LL | Some(arg) => { + | --- binding `arg` declared here LL | match arg.to_str() { | ^^^^^^^^^^^^ borrowed value does not live long enough ... diff --git a/tests/ui/moves/move-fn-self-receiver.stderr b/tests/ui/moves/move-fn-self-receiver.stderr index 7f69e5dcfb784..91d237b1d1a90 100644 --- a/tests/ui/moves/move-fn-self-receiver.stderr +++ b/tests/ui/moves/move-fn-self-receiver.stderr @@ -75,6 +75,8 @@ LL | fn use_pin_box_self(self: Pin>) {} error[E0505]: cannot move out of `mut_foo` because it is borrowed --> $DIR/move-fn-self-receiver.rs:50:5 | +LL | let mut mut_foo = Foo; + | ----------- binding `mut_foo` declared here LL | let ret = mut_foo.use_mut_self(); | ---------------------- borrow of `mut_foo` occurs here LL | mut_foo; diff --git a/tests/ui/nll/issue-54556-niconii.stderr b/tests/ui/nll/issue-54556-niconii.stderr index a8e1edc549742..d41d462f2bcb0 100644 --- a/tests/ui/nll/issue-54556-niconii.stderr +++ b/tests/ui/nll/issue-54556-niconii.stderr @@ -1,6 +1,9 @@ error[E0597]: `counter` does not live long enough --> $DIR/issue-54556-niconii.rs:22:20 | +LL | let counter = Mutex; + | ------- binding `counter` declared here +LL | LL | if let Ok(_) = counter.lock() { } | ^^^^^^^^^^^^^^ | | diff --git a/tests/ui/span/borrowck-let-suggestion-suffixes.rs b/tests/ui/span/borrowck-let-suggestion-suffixes.rs index 18abfb5c3fbec..ad556f281df12 100644 --- a/tests/ui/span/borrowck-let-suggestion-suffixes.rs +++ b/tests/ui/span/borrowck-let-suggestion-suffixes.rs @@ -8,6 +8,7 @@ fn f() { { let young = ['y']; // statement 3 + //~^ NOTE binding `young` declared here v2.push(&young[0]); // statement 4 //~^ ERROR `young[_]` does not live long enough diff --git a/tests/ui/span/borrowck-let-suggestion-suffixes.stderr b/tests/ui/span/borrowck-let-suggestion-suffixes.stderr index 2dc29a78d204d..545b235a552d1 100644 --- a/tests/ui/span/borrowck-let-suggestion-suffixes.stderr +++ b/tests/ui/span/borrowck-let-suggestion-suffixes.stderr @@ -1,6 +1,9 @@ error[E0597]: `young[_]` does not live long enough - --> $DIR/borrowck-let-suggestion-suffixes.rs:12:17 + --> $DIR/borrowck-let-suggestion-suffixes.rs:13:17 | +LL | let young = ['y']; // statement 3 + | ----- binding `young` declared here +... LL | v2.push(&young[0]); // statement 4 | ^^^^^^^^^ borrowed value does not live long enough ... @@ -11,7 +14,7 @@ LL | (v1, v2, v3, /* v4 is above. */ v5).use_ref(); | -- borrow later used here error[E0716]: temporary value dropped while borrowed - --> $DIR/borrowck-let-suggestion-suffixes.rs:19:14 + --> $DIR/borrowck-let-suggestion-suffixes.rs:20:14 | LL | v3.push(&id('x')); // statement 6 | ^^^^^^^ - temporary value is freed at the end of this statement @@ -28,7 +31,7 @@ LL ~ v3.push(&binding); // statement 6 | error[E0716]: temporary value dropped while borrowed - --> $DIR/borrowck-let-suggestion-suffixes.rs:29:18 + --> $DIR/borrowck-let-suggestion-suffixes.rs:30:18 | LL | v4.push(&id('y')); | ^^^^^^^ - temporary value is freed at the end of this statement @@ -41,7 +44,7 @@ LL | v4.use_ref(); = note: consider using a `let` binding to create a longer lived value error[E0716]: temporary value dropped while borrowed - --> $DIR/borrowck-let-suggestion-suffixes.rs:40:14 + --> $DIR/borrowck-let-suggestion-suffixes.rs:41:14 | LL | v5.push(&id('z')); | ^^^^^^^ - temporary value is freed at the end of this statement diff --git a/tests/ui/span/destructor-restrictions.stderr b/tests/ui/span/destructor-restrictions.stderr index 53c9404620f35..281248626c826 100644 --- a/tests/ui/span/destructor-restrictions.stderr +++ b/tests/ui/span/destructor-restrictions.stderr @@ -1,6 +1,8 @@ error[E0597]: `*a` does not live long enough --> $DIR/destructor-restrictions.rs:8:10 | +LL | let a = Box::new(RefCell::new(4)); + | - binding `a` declared here LL | *a.borrow() + 1 | ^^^^^^^^^^ | | diff --git a/tests/ui/span/issue-23338-locals-die-before-temps-of-body.stderr b/tests/ui/span/issue-23338-locals-die-before-temps-of-body.stderr index 3c2022748f094..e1a377203e296 100644 --- a/tests/ui/span/issue-23338-locals-die-before-temps-of-body.stderr +++ b/tests/ui/span/issue-23338-locals-die-before-temps-of-body.stderr @@ -1,6 +1,8 @@ error[E0597]: `y` does not live long enough --> $DIR/issue-23338-locals-die-before-temps-of-body.rs:10:5 | +LL | let y = x; + | - binding `y` declared here LL | y.borrow().clone() | ^^^^^^^^^^ | | @@ -22,6 +24,8 @@ LL | let x = y.borrow().clone(); x error[E0597]: `y` does not live long enough --> $DIR/issue-23338-locals-die-before-temps-of-body.rs:17:9 | +LL | let y = x; + | - binding `y` declared here LL | y.borrow().clone() | ^^^^^^^^^^ | | diff --git a/tests/ui/span/issue-40157.stderr b/tests/ui/span/issue-40157.stderr index e9b84de505989..a0afd33f7c7c4 100644 --- a/tests/ui/span/issue-40157.stderr +++ b/tests/ui/span/issue-40157.stderr @@ -2,9 +2,10 @@ error[E0597]: `foo` does not live long enough --> $DIR/issue-40157.rs:2:53 | LL | {println!("{:?}", match { let foo = vec![1, 2]; foo.get(1) } { x => x });} - | ^^^^^^^^^^ - `foo` dropped here while still borrowed - | | - | borrowed value does not live long enough + | --- ^^^^^^^^^^ - `foo` dropped here while still borrowed + | | | + | | borrowed value does not live long enough + | binding `foo` declared here error: aborting due to previous error From 1a6ab6c16a4902aef1e6d49ca188e1e112c677b7 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 17 Jan 2023 08:00:01 +0000 Subject: [PATCH 211/500] Empty regions don't exist anymore, remove them from fluent --- compiler/rustc_error_messages/locales/en-US/infer.ftl | 2 -- 1 file changed, 2 deletions(-) diff --git a/compiler/rustc_error_messages/locales/en-US/infer.ftl b/compiler/rustc_error_messages/locales/en-US/infer.ftl index ae0091b03736f..03a51142a3dfb 100644 --- a/compiler/rustc_error_messages/locales/en-US/infer.ftl +++ b/compiler/rustc_error_messages/locales/en-US/infer.ftl @@ -147,8 +147,6 @@ infer_region_explanation = {$pref_kind -> }{$desc_kind -> *[should_not_happen] [{$desc_kind}] [restatic] the static lifetime - [reempty] the empty lifetime - [reemptyuni] the empty lifetime in universe {$desc_arg} [revar] lifetime {$desc_arg} [as_defined] the lifetime `{$desc_arg}` as defined here From 49a9438681639ad9ca30bc2f69a4fd231cd35e09 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 16 Nov 2022 20:34:16 +0000 Subject: [PATCH 212/500] Remove double spaces after dots in comments --- src/constant.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/constant.rs b/src/constant.rs index dee6fb5b5130d..51450897bfc11 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -304,7 +304,7 @@ fn data_id_for_static( // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141 // Declare an internal global `extern_with_linkage_foo` which - // is initialized with the address of `foo`. If `foo` is + // is initialized with the address of `foo`. If `foo` is // discarded during linking (for example, if `foo` has weak // linkage and there are no definitions), then // `extern_with_linkage_foo` will instead be initialized to From 64e5f9129f6ffb382b458a255eed36f2581271c4 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 17 Jan 2023 08:21:34 +0000 Subject: [PATCH 213/500] Handle diagnostics customization on the fluent side --- .../src/region_infer/opaque_types.rs | 12 ------------ .../locales/en-US/borrowck.ftl | 5 ++++- compiler/rustc_error_messages/src/lib.rs | 15 +++++++++++++++ .../type-alias-impl-trait/bounds-are-checked.rs | 2 +- .../bounds-are-checked.stderr | 3 ++- .../generic_nondefining_use.rs | 2 +- .../generic_nondefining_use.stderr | 2 +- 7 files changed, 24 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs index 9d8812b7eeaac..f4d31cf1c34d7 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs @@ -368,18 +368,6 @@ fn check_opaque_type_parameter_valid( for (i, arg) in opaque_type_key.substs.iter().enumerate() { let arg_is_param = match arg.unpack() { GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Param(_)), - GenericArgKind::Lifetime(lt) if lt.is_static() => { - tcx.sess - .struct_span_err(span, "non-defining opaque type use in defining scope") - .span_label( - tcx.def_span(opaque_generics.param_at(i, tcx).def_id), - "cannot use static lifetime; use a bound lifetime \ - instead or remove the lifetime parameter from the \ - opaque type", - ) - .emit(); - return false; - } GenericArgKind::Lifetime(lt) => { matches!(*lt, ty::ReEarlyBound(_) | ty::ReFree(_)) } diff --git a/compiler/rustc_error_messages/locales/en-US/borrowck.ftl b/compiler/rustc_error_messages/locales/en-US/borrowck.ftl index 9e4332c428386..0021638c10268 100644 --- a/compiler/rustc_error_messages/locales/en-US/borrowck.ftl +++ b/compiler/rustc_error_messages/locales/en-US/borrowck.ftl @@ -123,4 +123,7 @@ borrowck_cannot_move_when_borrowed = borrowck_opaque_type_non_generic_param = expected generic {$kind} parameter, found `{$ty}` - .label = this generic parameter must be used with a generic {$kind} parameter + .label = {STREQ($ty, "'static") -> + [true] cannot use static lifetime; use a bound lifetime instead or remove the lifetime parameter from the opaque type + *[other] this generic parameter must be used with a generic {$kind} parameter + } diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index 37a51980a0888..f053bdc3809be 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -182,6 +182,9 @@ pub fn fluent_bundle( trace!(?locale); let mut bundle = new_bundle(vec![locale]); + // Add convenience functions available to ftl authors. + register_functions(&mut bundle); + // Fluent diagnostics can insert directionality isolation markers around interpolated variables // indicating that there may be a shift from right-to-left to left-to-right text (or // vice-versa). These are disabled because they are sometimes visible in the error output, but @@ -244,6 +247,15 @@ pub fn fluent_bundle( Ok(Some(bundle)) } +fn register_functions(bundle: &mut FluentBundle) { + bundle + .add_function("STREQ", |positional, _named| match positional { + [FluentValue::String(a), FluentValue::String(b)] => format!("{}", (a == b)).into(), + _ => FluentValue::Error, + }) + .expect("Failed to add a function to the bundle."); +} + /// Type alias for the result of `fallback_fluent_bundle` - a reference-counted pointer to a lazily /// evaluated fluent bundle. pub type LazyFallbackBundle = Lrc FluentBundle>>; @@ -256,6 +268,9 @@ pub fn fallback_fluent_bundle( ) -> LazyFallbackBundle { Lrc::new(Lazy::new(move || { let mut fallback_bundle = new_bundle(vec![langid!("en-US")]); + + register_functions(&mut fallback_bundle); + // See comment in `fluent_bundle`. fallback_bundle.set_use_isolating(with_directionality_markers); diff --git a/tests/ui/type-alias-impl-trait/bounds-are-checked.rs b/tests/ui/type-alias-impl-trait/bounds-are-checked.rs index 83d22161e4e75..eeb5dca07f06a 100644 --- a/tests/ui/type-alias-impl-trait/bounds-are-checked.rs +++ b/tests/ui/type-alias-impl-trait/bounds-are-checked.rs @@ -8,7 +8,7 @@ type X<'a> = impl Into<&'static str> + From<&'a str>; fn f<'a: 'static>(t: &'a str) -> X<'a> { //~^ WARNING unnecessary lifetime parameter t - //~^ ERROR non-defining opaque type use + //~^ ERROR expected generic lifetime parameter, found `'static` } fn extend_lt<'a>(o: &'a str) -> &'static str { diff --git a/tests/ui/type-alias-impl-trait/bounds-are-checked.stderr b/tests/ui/type-alias-impl-trait/bounds-are-checked.stderr index 920eef11da4b9..94882597a62e6 100644 --- a/tests/ui/type-alias-impl-trait/bounds-are-checked.stderr +++ b/tests/ui/type-alias-impl-trait/bounds-are-checked.stderr @@ -6,7 +6,7 @@ LL | fn f<'a: 'static>(t: &'a str) -> X<'a> { | = help: you can use the `'static` lifetime directly, in place of `'a` -error: non-defining opaque type use in defining scope +error[E0792]: expected generic lifetime parameter, found `'static` --> $DIR/bounds-are-checked.rs:10:5 | LL | type X<'a> = impl Into<&'static str> + From<&'a str>; @@ -17,3 +17,4 @@ LL | t error: aborting due to previous error; 1 warning emitted +For more information about this error, try `rustc --explain E0792`. diff --git a/tests/ui/type-alias-impl-trait/generic_nondefining_use.rs b/tests/ui/type-alias-impl-trait/generic_nondefining_use.rs index f5045d382aac4..e7b8567b9a217 100644 --- a/tests/ui/type-alias-impl-trait/generic_nondefining_use.rs +++ b/tests/ui/type-alias-impl-trait/generic_nondefining_use.rs @@ -19,7 +19,7 @@ fn concrete_ty() -> OneTy { fn concrete_lifetime() -> OneLifetime<'static> { 6u32 - //~^ ERROR non-defining opaque type use in defining scope + //~^ ERROR expected generic lifetime parameter, found `'static` } fn concrete_const() -> OneConst<{ 123 }> { diff --git a/tests/ui/type-alias-impl-trait/generic_nondefining_use.stderr b/tests/ui/type-alias-impl-trait/generic_nondefining_use.stderr index 564648630b161..966fe823f024d 100644 --- a/tests/ui/type-alias-impl-trait/generic_nondefining_use.stderr +++ b/tests/ui/type-alias-impl-trait/generic_nondefining_use.stderr @@ -7,7 +7,7 @@ LL | type OneTy = impl Debug; LL | 5u32 | ^^^^ -error: non-defining opaque type use in defining scope +error[E0792]: expected generic lifetime parameter, found `'static` --> $DIR/generic_nondefining_use.rs:21:5 | LL | type OneLifetime<'a> = impl Debug; From 6fe4cf795bb50e2168f9bc3f12391febc83a54c7 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Tue, 17 Jan 2023 13:48:43 +0100 Subject: [PATCH 214/500] Migrate mir_build's borrow conflicts --- .../locales/en-US/mir_build.ftl | 16 +- compiler/rustc_mir_build/src/errors.rs | 50 ++++-- .../src/thir/pattern/check_match.rs | 77 +++++----- ...atterns-slice-patterns-box-patterns.stderr | 8 +- ...can-live-while-the-other-survives-1.stderr | 8 +- .../borrowck-pat-at-and-box.stderr | 32 ++-- .../borrowck-pat-by-move-and-ref.stderr | 120 +++++++-------- .../borrowck-pat-ref-mut-and-ref.stderr | 144 +++++++++--------- .../borrowck-pat-ref-mut-twice.stderr | 96 ++++++------ ...inding-modes-both-sides-independent.stderr | 16 +- .../ui/suggestions/ref-pattern-binding.stderr | 8 +- 11 files changed, 302 insertions(+), 273 deletions(-) diff --git a/compiler/rustc_error_messages/locales/en-US/mir_build.ftl b/compiler/rustc_error_messages/locales/en-US/mir_build.ftl index a082c0b61fa7e..ec216de31d324 100644 --- a/compiler/rustc_error_messages/locales/en-US/mir_build.ftl +++ b/compiler/rustc_error_messages/locales/en-US/mir_build.ftl @@ -299,10 +299,18 @@ mir_build_borrow_of_moved_value = borrow of moved value .suggestion = borrow this binding in the pattern to avoid moving the value mir_build_multiple_mut_borrows = cannot borrow value as mutable more than once at a time - .label = first mutable borrow, by `{$name}`, occurs here - .mutable_borrow = another mutable borrow, by `{$name_mut}`, occurs here - .immutable_borrow = also borrowed as immutable, by `{$name_immut}`, here - .moved = also moved into `{$name_moved}` here + +mir_build_already_borrowed = cannot borrow value as mutable because it is also borrowed as immutable + +mir_build_already_mut_borrowed = cannot borrow value as immutable because it is also borrowed as mutable + +mir_build_moved_while_borrowed = cannot move out of value because it is borrowed + +mir_build_mutable_borrow = value is mutably borrowed by `{$name}` here + +mir_build_borrow = value is borrowed by `{$name}` here + +mir_build_moved = value is moved into `{$name}` here mir_build_union_pattern = cannot use unions in constant patterns diff --git a/compiler/rustc_mir_build/src/errors.rs b/compiler/rustc_mir_build/src/errors.rs index 06523b0a1de84..d3cd5f080ec9f 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -600,32 +600,56 @@ pub struct BorrowOfMovedValue<'tcx> { pub struct MultipleMutBorrows { #[primary_span] pub span: Span, - #[label] - pub binding_span: Span, #[subdiagnostic] - pub occurences: Vec, - pub name: Ident, + pub occurences: Vec, +} + +#[derive(Diagnostic)] +#[diag(mir_build_already_borrowed)] +pub struct AlreadyBorrowed { + #[primary_span] + pub span: Span, + #[subdiagnostic] + pub occurences: Vec, +} + +#[derive(Diagnostic)] +#[diag(mir_build_already_mut_borrowed)] +pub struct AlreadyMutBorrowed { + #[primary_span] + pub span: Span, + #[subdiagnostic] + pub occurences: Vec, +} + +#[derive(Diagnostic)] +#[diag(mir_build_moved_while_borrowed)] +pub struct MovedWhileBorrowed { + #[primary_span] + pub span: Span, + #[subdiagnostic] + pub occurences: Vec, } #[derive(Subdiagnostic)] -pub enum MultipleMutBorrowOccurence { - #[label(mutable_borrow)] - Mutable { +pub enum Conflict { + #[label(mir_build_mutable_borrow)] + Mut { #[primary_span] span: Span, - name_mut: Ident, + name: Ident, }, - #[label(immutable_borrow)] - Immutable { + #[label(mir_build_borrow)] + Ref { #[primary_span] span: Span, - name_immut: Ident, + name: Ident, }, - #[label(moved)] + #[label(mir_build_moved)] Moved { #[primary_span] span: Span, - name_moved: Ident, + name: Ident, }, } diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index e13c0662ef85f..1881eec174a17 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -914,58 +914,55 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_, '_>, pat: &Pa sub.each_binding(|_, hir_id, span, name| { match typeck_results.extract_binding_mode(sess, hir_id, span) { Some(ty::BindByReference(mut_inner)) => match (mut_outer, mut_inner) { - (Mutability::Not, Mutability::Not) => {} // Both sides are `ref`. - (Mutability::Mut, Mutability::Mut) => conflicts_mut_mut.push((span, name)), // 2x `ref mut`. - _ => conflicts_mut_ref.push((span, name)), // `ref` + `ref mut` in either direction. + // Both sides are `ref`. + (Mutability::Not, Mutability::Not) => {} + // 2x `ref mut`. + (Mutability::Mut, Mutability::Mut) => { + conflicts_mut_mut.push(Conflict::Mut { span, name }) + } + (Mutability::Not, Mutability::Mut) => { + conflicts_mut_ref.push(Conflict::Mut { span, name }) + } + (Mutability::Mut, Mutability::Not) => { + conflicts_mut_ref.push(Conflict::Ref { span, name }) + } }, Some(ty::BindByValue(_)) if is_binding_by_move(cx, hir_id) => { - conflicts_move.push((span, name)) // `ref mut?` + by-move conflict. + conflicts_move.push(Conflict::Moved { span, name }) // `ref mut?` + by-move conflict. } Some(ty::BindByValue(_)) | None => {} // `ref mut?` + by-copy is fine. } }); + let report_mut_mut = !conflicts_mut_mut.is_empty(); + let report_mut_ref = !conflicts_mut_ref.is_empty(); + let report_move_conflict = !conflicts_move.is_empty(); + + let mut occurences = match mut_outer { + Mutability::Mut => vec![Conflict::Mut { span: binding_span, name }], + Mutability::Not => vec![Conflict::Ref { span: binding_span, name }], + }; + occurences.extend(conflicts_mut_mut); + occurences.extend(conflicts_mut_ref); + occurences.extend(conflicts_move); + // Report errors if any. - if !conflicts_mut_mut.is_empty() { + if report_mut_mut { // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`. - let mut occurences = vec![]; - - for (span, name_mut) in conflicts_mut_mut { - occurences.push(MultipleMutBorrowOccurence::Mutable { span, name_mut }); - } - for (span, name_immut) in conflicts_mut_ref { - occurences.push(MultipleMutBorrowOccurence::Immutable { span, name_immut }); - } - for (span, name_moved) in conflicts_move { - occurences.push(MultipleMutBorrowOccurence::Moved { span, name_moved }); - } - sess.emit_err(MultipleMutBorrows { span: pat.span, binding_span, occurences, name }); - } else if !conflicts_mut_ref.is_empty() { + sess.emit_err(MultipleMutBorrows { span: pat.span, occurences }); + } else if report_mut_ref { // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse. - let (primary, also) = match mut_outer { - Mutability::Mut => ("mutable", "immutable"), - Mutability::Not => ("immutable", "mutable"), + match mut_outer { + Mutability::Mut => { + sess.emit_err(AlreadyMutBorrowed { span: pat.span, occurences }); + } + Mutability::Not => { + sess.emit_err(AlreadyBorrowed { span: pat.span, occurences }); + } }; - let msg = - format!("cannot borrow value as {} because it is also borrowed as {}", also, primary); - let mut err = sess.struct_span_err(pat.span, &msg); - err.span_label(binding_span, format!("{} borrow, by `{}`, occurs here", primary, name)); - for (span, name) in conflicts_mut_ref { - err.span_label(span, format!("{} borrow, by `{}`, occurs here", also, name)); - } - for (span, name) in conflicts_move { - err.span_label(span, format!("also moved into `{}` here", name)); - } - err.emit(); - } else if !conflicts_move.is_empty() { + } else if report_move_conflict { // Report by-ref and by-move conflicts, e.g. `ref x @ y`. - let mut err = - sess.struct_span_err(pat.span, "cannot move out of value because it is borrowed"); - err.span_label(binding_span, format!("value borrowed, by `{}`, here", name)); - for (span, name) in conflicts_move { - err.span_label(span, format!("value moved into `{}` here", name)); - } - err.emit(); + sess.emit_err(MovedWhileBorrowed { span: pat.span, occurences }); } } diff --git a/tests/ui/borrowck/bindings-after-at-or-patterns-slice-patterns-box-patterns.stderr b/tests/ui/borrowck/bindings-after-at-or-patterns-slice-patterns-box-patterns.stderr index 50eee1049db6e..5835f06753bb1 100644 --- a/tests/ui/borrowck/bindings-after-at-or-patterns-slice-patterns-box-patterns.stderr +++ b/tests/ui/borrowck/bindings-after-at-or-patterns-slice-patterns-box-patterns.stderr @@ -4,8 +4,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | ref foo @ [.., ref mut bar] => (), | -------^^^^^^^^-----------^ | | | - | | mutable borrow, by `bar`, occurs here - | immutable borrow, by `foo`, occurs here + | | value is mutably borrowed by `bar` here + | value is borrowed by `foo` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/bindings-after-at-or-patterns-slice-patterns-box-patterns.rs:120:9 @@ -13,8 +13,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | ref foo @ Some(box ref mut s) => (), | -------^^^^^^^^^^^^---------^ | | | - | | mutable borrow, by `s`, occurs here - | immutable borrow, by `foo`, occurs here + | | value is mutably borrowed by `s` here + | value is borrowed by `foo` here error[E0382]: borrow of moved value: `x` --> $DIR/bindings-after-at-or-patterns-slice-patterns-box-patterns.rs:18:5 diff --git a/tests/ui/pattern/bindings-after-at/bind-by-move-neither-can-live-while-the-other-survives-1.stderr b/tests/ui/pattern/bindings-after-at/bind-by-move-neither-can-live-while-the-other-survives-1.stderr index c8b45fd24d98c..29cd6c45c34b5 100644 --- a/tests/ui/pattern/bindings-after-at/bind-by-move-neither-can-live-while-the-other-survives-1.stderr +++ b/tests/ui/pattern/bindings-after-at/bind-by-move-neither-can-live-while-the-other-survives-1.stderr @@ -4,8 +4,8 @@ error: cannot move out of value because it is borrowed LL | Some(ref _y @ _z) => {} | ------^^^-- | | | - | | value moved into `_z` here - | value borrowed, by `_y`, here + | | value is moved into `_z` here + | value is borrowed by `_y` here error: borrow of moved value --> $DIR/bind-by-move-neither-can-live-while-the-other-survives-1.rs:19:14 @@ -28,8 +28,8 @@ error: cannot move out of value because it is borrowed LL | Some(ref mut _y @ _z) => {} | ----------^^^-- | | | - | | value moved into `_z` here - | value borrowed, by `_y`, here + | | value is moved into `_z` here + | value is mutably borrowed by `_y` here error: borrow of moved value --> $DIR/bind-by-move-neither-can-live-while-the-other-survives-1.rs:33:14 diff --git a/tests/ui/pattern/bindings-after-at/borrowck-pat-at-and-box.stderr b/tests/ui/pattern/bindings-after-at/borrowck-pat-at-and-box.stderr index f27df32ccfa5c..2c123b01e173e 100644 --- a/tests/ui/pattern/bindings-after-at/borrowck-pat-at-and-box.stderr +++ b/tests/ui/pattern/bindings-after-at/borrowck-pat-at-and-box.stderr @@ -4,8 +4,8 @@ error: cannot move out of value because it is borrowed LL | let ref a @ box b = Box::new(NC); | -----^^^^^^^- | | | - | | value moved into `b` here - | value borrowed, by `a`, here + | | value is moved into `b` here + | value is borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-at-and-box.rs:34:9 @@ -13,8 +13,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref a @ box ref mut b = Box::new(nc()); | -----^^^^^^^--------- | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-at-and-box.rs:36:9 @@ -22,8 +22,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref a @ box ref mut b = Box::new(NC); | -----^^^^^^^--------- | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-at-and-box.rs:38:9 @@ -31,8 +31,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref a @ box ref mut b = Box::new(NC); | -----^^^^^^^--------- | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-at-and-box.rs:42:9 @@ -40,8 +40,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref a @ box ref mut b = Box::new(NC); | -----^^^^^^^--------- | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-at-and-box.rs:48:9 @@ -49,8 +49,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | let ref mut a @ box ref b = Box::new(NC); | ---------^^^^^^^----- | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-at-and-box.rs:62:9 @@ -58,8 +58,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | ref mut a @ box ref b => { | ---------^^^^^^^----- | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-at-and-box.rs:54:11 @@ -67,8 +67,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | fn f5(ref mut a @ box ref b: Box) { | ---------^^^^^^^----- | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error[E0382]: borrow of moved value --> $DIR/borrowck-pat-at-and-box.rs:31:9 diff --git a/tests/ui/pattern/bindings-after-at/borrowck-pat-by-move-and-ref.stderr b/tests/ui/pattern/bindings-after-at/borrowck-pat-by-move-and-ref.stderr index 770bb89530cca..4f7fbc9e04b04 100644 --- a/tests/ui/pattern/bindings-after-at/borrowck-pat-by-move-and-ref.stderr +++ b/tests/ui/pattern/bindings-after-at/borrowck-pat-by-move-and-ref.stderr @@ -4,8 +4,8 @@ error: cannot move out of value because it is borrowed LL | let ref a @ b = U; | -----^^^- | | | - | | value moved into `b` here - | value borrowed, by `a`, here + | | value is moved into `b` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:26:9 @@ -13,9 +13,9 @@ error: cannot move out of value because it is borrowed LL | let ref a @ (ref b @ mut c, ref d @ e) = (U, U); | -----^^^^^^^^^^^^-----^^^^^^^^^^-^ | | | | - | | | value moved into `e` here - | | value moved into `c` here - | value borrowed, by `a`, here + | | | value is moved into `e` here + | | value is moved into `c` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:26:18 @@ -23,8 +23,8 @@ error: cannot move out of value because it is borrowed LL | let ref a @ (ref b @ mut c, ref d @ e) = (U, U); | -----^^^----- | | | - | | value moved into `c` here - | value borrowed, by `b`, here + | | value is moved into `c` here + | value is borrowed by `b` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:26:33 @@ -32,8 +32,8 @@ error: cannot move out of value because it is borrowed LL | let ref a @ (ref b @ mut c, ref d @ e) = (U, U); | -----^^^- | | | - | | value moved into `e` here - | value borrowed, by `d`, here + | | value is moved into `e` here + | value is borrowed by `d` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:30:9 @@ -41,9 +41,9 @@ error: cannot move out of value because it is borrowed LL | let ref mut a @ [b, mut c] = [U, U]; | ---------^^^^-^^-----^ | | | | - | | | value moved into `c` here - | | value moved into `b` here - | value borrowed, by `a`, here + | | | value is moved into `c` here + | | value is moved into `b` here + | value is mutably borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:33:9 @@ -51,8 +51,8 @@ error: cannot move out of value because it is borrowed LL | let ref a @ b = u(); | -----^^^- | | | - | | value moved into `b` here - | value borrowed, by `a`, here + | | value is moved into `b` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:36:9 @@ -60,9 +60,9 @@ error: cannot move out of value because it is borrowed LL | let ref a @ (ref b @ mut c, ref d @ e) = (u(), u()); | -----^^^^^^^^^^^^-----^^^^^^^^^^-^ | | | | - | | | value moved into `e` here - | | value moved into `c` here - | value borrowed, by `a`, here + | | | value is moved into `e` here + | | value is moved into `c` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:36:18 @@ -70,8 +70,8 @@ error: cannot move out of value because it is borrowed LL | let ref a @ (ref b @ mut c, ref d @ e) = (u(), u()); | -----^^^----- | | | - | | value moved into `c` here - | value borrowed, by `b`, here + | | value is moved into `c` here + | value is borrowed by `b` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:36:33 @@ -79,8 +79,8 @@ error: cannot move out of value because it is borrowed LL | let ref a @ (ref b @ mut c, ref d @ e) = (u(), u()); | -----^^^- | | | - | | value moved into `e` here - | value borrowed, by `d`, here + | | value is moved into `e` here + | value is borrowed by `d` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:42:9 @@ -88,9 +88,9 @@ error: cannot move out of value because it is borrowed LL | let ref mut a @ [b, mut c] = [u(), u()]; | ---------^^^^-^^-----^ | | | | - | | | value moved into `c` here - | | value moved into `b` here - | value borrowed, by `a`, here + | | | value is moved into `c` here + | | value is moved into `b` here + | value is mutably borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:47:9 @@ -98,8 +98,8 @@ error: cannot move out of value because it is borrowed LL | ref a @ Some(b) => {} | -----^^^^^^^^-^ | | | - | | value moved into `b` here - | value borrowed, by `a`, here + | | value is moved into `b` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:52:9 @@ -107,9 +107,9 @@ error: cannot move out of value because it is borrowed LL | ref a @ Some((ref b @ mut c, ref d @ e)) => {} | -----^^^^^^^^^^^^^^^^^-----^^^^^^^^^^-^^ | | | | - | | | value moved into `e` here - | | value moved into `c` here - | value borrowed, by `a`, here + | | | value is moved into `e` here + | | value is moved into `c` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:52:23 @@ -117,8 +117,8 @@ error: cannot move out of value because it is borrowed LL | ref a @ Some((ref b @ mut c, ref d @ e)) => {} | -----^^^----- | | | - | | value moved into `c` here - | value borrowed, by `b`, here + | | value is moved into `c` here + | value is borrowed by `b` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:52:38 @@ -126,8 +126,8 @@ error: cannot move out of value because it is borrowed LL | ref a @ Some((ref b @ mut c, ref d @ e)) => {} | -----^^^- | | | - | | value moved into `e` here - | value borrowed, by `d`, here + | | value is moved into `e` here + | value is borrowed by `d` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:59:9 @@ -135,9 +135,9 @@ error: cannot move out of value because it is borrowed LL | ref mut a @ Some([b, mut c]) => {} | ---------^^^^^^^^^-^^-----^^ | | | | - | | | value moved into `c` here - | | value moved into `b` here - | value borrowed, by `a`, here + | | | value is moved into `c` here + | | value is moved into `b` here + | value is mutably borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:64:9 @@ -145,8 +145,8 @@ error: cannot move out of value because it is borrowed LL | ref a @ Some(b) => {} | -----^^^^^^^^-^ | | | - | | value moved into `b` here - | value borrowed, by `a`, here + | | value is moved into `b` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:69:9 @@ -154,9 +154,9 @@ error: cannot move out of value because it is borrowed LL | ref a @ Some((ref b @ mut c, ref d @ e)) => {} | -----^^^^^^^^^^^^^^^^^-----^^^^^^^^^^-^^ | | | | - | | | value moved into `e` here - | | value moved into `c` here - | value borrowed, by `a`, here + | | | value is moved into `e` here + | | value is moved into `c` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:69:23 @@ -164,8 +164,8 @@ error: cannot move out of value because it is borrowed LL | ref a @ Some((ref b @ mut c, ref d @ e)) => {} | -----^^^----- | | | - | | value moved into `c` here - | value borrowed, by `b`, here + | | value is moved into `c` here + | value is borrowed by `b` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:69:38 @@ -173,8 +173,8 @@ error: cannot move out of value because it is borrowed LL | ref a @ Some((ref b @ mut c, ref d @ e)) => {} | -----^^^- | | | - | | value moved into `e` here - | value borrowed, by `d`, here + | | value is moved into `e` here + | value is borrowed by `d` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:78:9 @@ -182,9 +182,9 @@ error: cannot move out of value because it is borrowed LL | ref mut a @ Some([b, mut c]) => {} | ---------^^^^^^^^^-^^-----^^ | | | | - | | | value moved into `c` here - | | value moved into `b` here - | value borrowed, by `a`, here + | | | value is moved into `c` here + | | value is moved into `b` here + | value is mutably borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:11:11 @@ -192,8 +192,8 @@ error: cannot move out of value because it is borrowed LL | fn f1(ref a @ b: U) {} | -----^^^- | | | - | | value moved into `b` here - | value borrowed, by `a`, here + | | value is moved into `b` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:14:11 @@ -201,9 +201,9 @@ error: cannot move out of value because it is borrowed LL | fn f2(ref a @ (ref b @ mut c, ref d @ e): (U, U)) {} | -----^^^^^^^^^^^^-----^^^^^^^^^^-^ | | | | - | | | value moved into `e` here - | | value moved into `c` here - | value borrowed, by `a`, here + | | | value is moved into `e` here + | | value is moved into `c` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:14:20 @@ -211,8 +211,8 @@ error: cannot move out of value because it is borrowed LL | fn f2(ref a @ (ref b @ mut c, ref d @ e): (U, U)) {} | -----^^^----- | | | - | | value moved into `c` here - | value borrowed, by `b`, here + | | value is moved into `c` here + | value is borrowed by `b` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:14:35 @@ -220,8 +220,8 @@ error: cannot move out of value because it is borrowed LL | fn f2(ref a @ (ref b @ mut c, ref d @ e): (U, U)) {} | -----^^^- | | | - | | value moved into `e` here - | value borrowed, by `d`, here + | | value is moved into `e` here + | value is borrowed by `d` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-by-move-and-ref.rs:20:11 @@ -229,9 +229,9 @@ error: cannot move out of value because it is borrowed LL | fn f3(ref mut a @ [b, mut c]: [U; 2]) {} | ---------^^^^-^^-----^ | | | | - | | | value moved into `c` here - | | value moved into `b` here - | value borrowed, by `a`, here + | | | value is moved into `c` here + | | value is moved into `b` here + | value is mutably borrowed by `a` here error[E0382]: borrow of partially moved value --> $DIR/borrowck-pat-by-move-and-ref.rs:30:9 diff --git a/tests/ui/pattern/bindings-after-at/borrowck-pat-ref-mut-and-ref.stderr b/tests/ui/pattern/bindings-after-at/borrowck-pat-ref-mut-and-ref.stderr index 8546b4bb47734..f51b5041858c6 100644 --- a/tests/ui/pattern/bindings-after-at/borrowck-pat-ref-mut-and-ref.stderr +++ b/tests/ui/pattern/bindings-after-at/borrowck-pat-ref-mut-and-ref.stderr @@ -4,8 +4,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | ref mut z @ &mut Some(ref a) => { | ---------^^^^^^^^^^^^^-----^ | | | - | | immutable borrow, by `a`, occurs here - | mutable borrow, by `z`, occurs here + | | value is borrowed by `a` here + | value is mutably borrowed by `z` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-and-ref.rs:33:9 @@ -13,9 +13,9 @@ error: cannot borrow value as mutable more than once at a time LL | let ref mut a @ (ref b @ ref mut c) = u(); // sub-in-sub | ---------^^^^-----------------^ | | | | - | | | another mutable borrow, by `c`, occurs here - | | also borrowed as immutable, by `b`, here - | first mutable borrow, by `a`, occurs here + | | | value is mutably borrowed by `c` here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:33:22 @@ -23,8 +23,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref mut a @ (ref b @ ref mut c) = u(); // sub-in-sub | -----^^^--------- | | | - | | mutable borrow, by `c`, occurs here - | immutable borrow, by `b`, occurs here + | | value is mutably borrowed by `c` here + | value is borrowed by `b` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:37:9 @@ -32,8 +32,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref a @ ref mut b = U; | -----^^^--------- | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:39:9 @@ -41,8 +41,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | let ref mut a @ ref b = U; | ---------^^^----- | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:41:9 @@ -50,9 +50,9 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref a @ (ref mut b, ref mut c) = (U, U); | -----^^^^---------^^---------^ | | | | - | | | mutable borrow, by `c`, occurs here - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | | value is mutably borrowed by `c` here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:43:9 @@ -60,9 +60,9 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | let ref mut a @ (ref b, ref c) = (U, U); | ---------^^^^-----^^-----^ | | | | - | | | immutable borrow, by `c`, occurs here - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | | value is borrowed by `c` here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:46:9 @@ -70,8 +70,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | let ref mut a @ ref b = u(); | ---------^^^----- | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:51:9 @@ -79,8 +79,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref a @ ref mut b = u(); | -----^^^--------- | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:57:9 @@ -88,8 +88,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | let ref mut a @ ref b = U; | ---------^^^----- | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:61:9 @@ -97,8 +97,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref a @ ref mut b = U; | -----^^^--------- | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:67:9 @@ -106,8 +106,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | ref mut a @ Ok(ref b) | ref mut a @ Err(ref b) => { | ---------^^^^^^-----^ | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:67:33 @@ -115,8 +115,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | ref mut a @ Ok(ref b) | ref mut a @ Err(ref b) => { | ---------^^^^^^^-----^ | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:76:9 @@ -124,8 +124,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | ref a @ Ok(ref mut b) | ref a @ Err(ref mut b) => { | -----^^^^^^---------^ | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:76:33 @@ -133,8 +133,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | ref a @ Ok(ref mut b) | ref a @ Err(ref mut b) => { | -----^^^^^^^---------^ | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:87:9 @@ -142,8 +142,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | ref a @ Ok(ref mut b) | ref a @ Err(ref mut b) if { *b = U; false } => {} | -----^^^^^^---------^ | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:87:33 @@ -151,8 +151,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | ref a @ Ok(ref mut b) | ref a @ Err(ref mut b) if { *b = U; false } => {} | -----^^^^^^^---------^ | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:94:9 @@ -160,8 +160,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | ref mut a @ Ok(ref b) | ref mut a @ Err(ref b) if { *a = Err(U); false } => {} | ---------^^^^^^-----^ | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:94:33 @@ -169,8 +169,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | ref mut a @ Ok(ref b) | ref mut a @ Err(ref b) if { *a = Err(U); false } => {} | ---------^^^^^^^-----^ | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:101:9 @@ -178,8 +178,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | ref a @ Ok(ref mut b) | ref a @ Err(ref mut b) if { drop(b); false } => {} | -----^^^^^^---------^ | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:101:33 @@ -187,8 +187,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | ref a @ Ok(ref mut b) | ref a @ Err(ref mut b) if { drop(b); false } => {} | -----^^^^^^^---------^ | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:109:9 @@ -196,8 +196,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | ref mut a @ Ok(ref b) | ref mut a @ Err(ref b) if { drop(a); false } => {} | ---------^^^^^^-----^ | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:109:33 @@ -205,8 +205,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | ref mut a @ Ok(ref b) | ref mut a @ Err(ref b) if { drop(a); false } => {} | ---------^^^^^^^-----^ | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:117:9 @@ -214,9 +214,9 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref a @ (ref mut b, ref mut c) = (U, U); | -----^^^^---------^^---------^ | | | | - | | | mutable borrow, by `c`, occurs here - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | | value is mutably borrowed by `c` here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:123:9 @@ -224,9 +224,9 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref a @ (ref mut b, ref mut c) = (U, U); | -----^^^^---------^^---------^ | | | | - | | | mutable borrow, by `c`, occurs here - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | | value is mutably borrowed by `c` here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:129:9 @@ -234,9 +234,9 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | let ref a @ (ref mut b, ref mut c) = (U, U); | -----^^^^---------^^---------^ | | | | - | | | mutable borrow, by `c`, occurs here - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | | value is mutably borrowed by `c` here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:134:9 @@ -244,9 +244,9 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | let ref mut a @ (ref b, ref c) = (U, U); | ---------^^^^-----^^-----^ | | | | - | | | immutable borrow, by `c`, occurs here - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | | value is borrowed by `c` here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:22:11 @@ -254,8 +254,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | fn f1(ref a @ ref mut b: U) {} | -----^^^--------- | | | - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:24:11 @@ -263,8 +263,8 @@ error: cannot borrow value as immutable because it is also borrowed as mutable LL | fn f2(ref mut a @ ref b: U) {} | ---------^^^----- | | | - | | immutable borrow, by `b`, occurs here - | mutable borrow, by `a`, occurs here + | | value is borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:26:11 @@ -272,8 +272,8 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | fn f3(ref a @ [ref b, ref mut mid @ .., ref c]: [U; 4]) {} | -----^^^^^^^^^^^----------------^^^^^^^^ | | | - | | mutable borrow, by `mid`, occurs here - | immutable borrow, by `a`, occurs here + | | value is mutably borrowed by `mid` here + | value is borrowed by `a` here error: cannot borrow value as mutable because it is also borrowed as immutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:28:22 @@ -281,9 +281,9 @@ error: cannot borrow value as mutable because it is also borrowed as immutable LL | fn f4_also_moved(ref a @ ref mut b @ c: U) {} | -----^^^------------- | | | | - | | | also moved into `c` here - | | mutable borrow, by `b`, occurs here - | immutable borrow, by `a`, occurs here + | | | value is moved into `c` here + | | value is mutably borrowed by `b` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-ref-mut-and-ref.rs:28:30 @@ -291,8 +291,8 @@ error: cannot move out of value because it is borrowed LL | fn f4_also_moved(ref a @ ref mut b @ c: U) {} | ---------^^^- | | | - | | value moved into `c` here - | value borrowed, by `b`, here + | | value is moved into `c` here + | value is mutably borrowed by `b` here error[E0502]: cannot borrow value as immutable because it is also borrowed as mutable --> $DIR/borrowck-pat-ref-mut-and-ref.rs:8:31 diff --git a/tests/ui/pattern/bindings-after-at/borrowck-pat-ref-mut-twice.stderr b/tests/ui/pattern/bindings-after-at/borrowck-pat-ref-mut-twice.stderr index ad4ce7952ca74..a0cb04a064e06 100644 --- a/tests/ui/pattern/bindings-after-at/borrowck-pat-ref-mut-twice.stderr +++ b/tests/ui/pattern/bindings-after-at/borrowck-pat-ref-mut-twice.stderr @@ -4,8 +4,8 @@ error: cannot borrow value as mutable more than once at a time LL | let ref mut a @ ref mut b = U; | ---------^^^--------- | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:29:9 @@ -13,8 +13,8 @@ error: cannot borrow value as mutable more than once at a time LL | let ref mut a @ ref mut b = U; | ---------^^^--------- | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:33:9 @@ -22,8 +22,8 @@ error: cannot borrow value as mutable more than once at a time LL | let ref mut a @ ref mut b = U; | ---------^^^--------- | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:36:9 @@ -31,8 +31,8 @@ error: cannot borrow value as mutable more than once at a time LL | let ref mut a @ ref mut b = U; | ---------^^^--------- | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:39:9 @@ -40,8 +40,8 @@ error: cannot borrow value as mutable more than once at a time LL | let ref mut a @ ref mut b = U; | ---------^^^--------- | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:44:9 @@ -49,18 +49,18 @@ error: cannot borrow value as mutable more than once at a time LL | let ref mut a @ ( | ^-------- | | - | _________first mutable borrow, by `a`, occurs here + | _________value is mutably borrowed by `a` here | | LL | | LL | | ref mut b, - | | --------- another mutable borrow, by `b`, occurs here + | | --------- value is mutably borrowed by `b` here LL | | [ LL | | ref mut c, - | | --------- another mutable borrow, by `c`, occurs here + | | --------- value is mutably borrowed by `c` here LL | | ref mut d, - | | --------- another mutable borrow, by `d`, occurs here + | | --------- value is mutably borrowed by `d` here LL | | ref e, - | | ----- also borrowed as immutable, by `e`, here + | | ----- value is borrowed by `e` here LL | | ] LL | | ) = (U, [U, U, U]); | |_____^ @@ -71,18 +71,18 @@ error: cannot borrow value as mutable more than once at a time LL | let ref mut a @ ( | ^-------- | | - | _________first mutable borrow, by `a`, occurs here + | _________value is mutably borrowed by `a` here | | LL | | LL | | ref mut b, - | | --------- another mutable borrow, by `b`, occurs here + | | --------- value is mutably borrowed by `b` here LL | | [ LL | | ref mut c, - | | --------- another mutable borrow, by `c`, occurs here + | | --------- value is mutably borrowed by `c` here LL | | ref mut d, - | | --------- another mutable borrow, by `d`, occurs here + | | --------- value is mutably borrowed by `d` here LL | | ref e, - | | ----- also borrowed as immutable, by `e`, here + | | ----- value is borrowed by `e` here LL | | ] LL | | ) = (u(), [u(), u(), u()]); | |_________^ @@ -157,8 +157,8 @@ error: cannot borrow value as mutable more than once at a time LL | ref mut a @ Ok(ref mut b) | ref mut a @ Err(ref mut b) => { | ---------^^^^^^---------^ | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:76:37 @@ -166,8 +166,8 @@ error: cannot borrow value as mutable more than once at a time LL | ref mut a @ Ok(ref mut b) | ref mut a @ Err(ref mut b) => { | ---------^^^^^^^---------^ | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:82:9 @@ -175,8 +175,8 @@ error: cannot borrow value as mutable more than once at a time LL | ref mut a @ Ok(ref mut b) | ref mut a @ Err(ref mut b) => { | ---------^^^^^^---------^ | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:82:37 @@ -184,8 +184,8 @@ error: cannot borrow value as mutable more than once at a time LL | ref mut a @ Ok(ref mut b) | ref mut a @ Err(ref mut b) => { | ---------^^^^^^^---------^ | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:89:9 @@ -193,8 +193,8 @@ error: cannot borrow value as mutable more than once at a time LL | ref mut a @ Ok(ref mut b) | ref mut a @ Err(ref mut b) => { | ---------^^^^^^---------^ | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:89:37 @@ -202,8 +202,8 @@ error: cannot borrow value as mutable more than once at a time LL | ref mut a @ Ok(ref mut b) | ref mut a @ Err(ref mut b) => { | ---------^^^^^^^---------^ | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:101:9 @@ -211,8 +211,8 @@ error: cannot borrow value as mutable more than once at a time LL | ref mut a @ Ok(ref mut b) | ref mut a @ Err(ref mut b) => { | ---------^^^^^^---------^ | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:101:37 @@ -220,8 +220,8 @@ error: cannot borrow value as mutable more than once at a time LL | ref mut a @ Ok(ref mut b) | ref mut a @ Err(ref mut b) => { | ---------^^^^^^^---------^ | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:8:11 @@ -229,8 +229,8 @@ error: cannot borrow value as mutable more than once at a time LL | fn f1(ref mut a @ ref mut b: U) {} | ---------^^^--------- | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:10:11 @@ -238,8 +238,8 @@ error: cannot borrow value as mutable more than once at a time LL | fn f2(ref mut a @ ref mut b: U) {} | ---------^^^--------- | | | - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:13:9 @@ -247,13 +247,13 @@ error: cannot borrow value as mutable more than once at a time LL | ref mut a @ [ | ^-------- | | - | _________first mutable borrow, by `a`, occurs here + | _________value is mutably borrowed by `a` here | | LL | | LL | | [ref b @ .., _], - | | ---------- also borrowed as immutable, by `b`, here + | | ---------- value is borrowed by `b` here LL | | [_, ref mut mid @ ..], - | | ---------------- another mutable borrow, by `mid`, occurs here + | | ---------------- value is mutably borrowed by `mid` here LL | | .., LL | | [..], LL | | ] : [[U; 4]; 5] @@ -265,9 +265,9 @@ error: cannot borrow value as mutable more than once at a time LL | fn f4_also_moved(ref mut a @ ref mut b @ c: U) {} | ---------^^^------------- | | | | - | | | also moved into `c` here - | | another mutable borrow, by `b`, occurs here - | first mutable borrow, by `a`, occurs here + | | | value is moved into `c` here + | | value is mutably borrowed by `b` here + | value is mutably borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/borrowck-pat-ref-mut-twice.rs:21:34 @@ -275,8 +275,8 @@ error: cannot move out of value because it is borrowed LL | fn f4_also_moved(ref mut a @ ref mut b @ c: U) {} | ---------^^^- | | | - | | value moved into `c` here - | value borrowed, by `b`, here + | | value is moved into `c` here + | value is mutably borrowed by `b` here error[E0499]: cannot borrow value as mutable more than once at a time --> $DIR/borrowck-pat-ref-mut-twice.rs:29:9 diff --git a/tests/ui/pattern/bindings-after-at/default-binding-modes-both-sides-independent.stderr b/tests/ui/pattern/bindings-after-at/default-binding-modes-both-sides-independent.stderr index 638bdd6db7606..73ebbf48118da 100644 --- a/tests/ui/pattern/bindings-after-at/default-binding-modes-both-sides-independent.stderr +++ b/tests/ui/pattern/bindings-after-at/default-binding-modes-both-sides-independent.stderr @@ -4,8 +4,8 @@ error: cannot move out of value because it is borrowed LL | let ref a @ b = NotCopy; | -----^^^- | | | - | | value moved into `b` here - | value borrowed, by `a`, here + | | value is moved into `b` here + | value is borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/default-binding-modes-both-sides-independent.rs:29:9 @@ -13,8 +13,8 @@ error: cannot move out of value because it is borrowed LL | let ref mut a @ b = NotCopy; | ---------^^^- | | | - | | value moved into `b` here - | value borrowed, by `a`, here + | | value is moved into `b` here + | value is mutably borrowed by `a` here error: cannot move out of value because it is borrowed --> $DIR/default-binding-modes-both-sides-independent.rs:34:12 @@ -22,8 +22,8 @@ error: cannot move out of value because it is borrowed LL | Ok(ref a @ b) | Err(b @ ref a) => { | -----^^^- | | | - | | value moved into `b` here - | value borrowed, by `a`, here + | | value is moved into `b` here + | value is borrowed by `a` here error: borrow of moved value --> $DIR/default-binding-modes-both-sides-independent.rs:34:29 @@ -46,8 +46,8 @@ error: cannot move out of value because it is borrowed LL | ref a @ b => { | -----^^^- | | | - | | value moved into `b` here - | value borrowed, by `a`, here + | | value is moved into `b` here + | value is borrowed by `a` here error[E0382]: borrow of moved value --> $DIR/default-binding-modes-both-sides-independent.rs:29:9 diff --git a/tests/ui/suggestions/ref-pattern-binding.stderr b/tests/ui/suggestions/ref-pattern-binding.stderr index 10447ba7089ca..7b194259349b8 100644 --- a/tests/ui/suggestions/ref-pattern-binding.stderr +++ b/tests/ui/suggestions/ref-pattern-binding.stderr @@ -19,8 +19,8 @@ error: cannot move out of value because it is borrowed LL | let ref _moved @ _from = String::from("foo"); | ----------^^^----- | | | - | | value moved into `_from` here - | value borrowed, by `_moved`, here + | | value is moved into `_from` here + | value is borrowed by `_moved` here error: cannot move out of value because it is borrowed --> $DIR/ref-pattern-binding.rs:15:9 @@ -28,8 +28,8 @@ error: cannot move out of value because it is borrowed LL | let ref _moved @ S { f } = S { f: String::from("foo") }; | ----------^^^^^^^-^^ | | | - | | value moved into `f` here - | value borrowed, by `_moved`, here + | | value is moved into `f` here + | value is borrowed by `_moved` here error: borrow of moved value --> $DIR/ref-pattern-binding.rs:18:9 From 5dac27503f17181cb0fe71084d95825cfe706504 Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Mon, 16 Jan 2023 14:50:11 -0700 Subject: [PATCH 215/500] change usages of item_bounds query to bound_item_bounds --- clippy_utils/src/ty.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_utils/src/ty.rs b/clippy_utils/src/ty.rs index c8d56a3be5cf3..9525c78312b45 100644 --- a/clippy_utils/src/ty.rs +++ b/clippy_utils/src/ty.rs @@ -648,7 +648,7 @@ pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs), Some(id))), ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => { - sig_from_bounds(cx, ty, cx.tcx.item_bounds(def_id), cx.tcx.opt_parent(def_id)) + sig_from_bounds(cx, ty, cx.tcx.bound_item_bounds(def_id).subst_identity(), cx.tcx.opt_parent(def_id)) }, ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig, None)), ty::Dynamic(bounds, _, _) => { From a084d7908c1ff4489d5aa3100b83b85aebc67367 Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Mon, 16 Jan 2023 15:07:23 -0700 Subject: [PATCH 216/500] change item_bounds query to return EarlyBinder; remove bound_item_bounds query --- clippy_utils/src/ty.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_utils/src/ty.rs b/clippy_utils/src/ty.rs index 9525c78312b45..1d2a469ca6ca5 100644 --- a/clippy_utils/src/ty.rs +++ b/clippy_utils/src/ty.rs @@ -648,7 +648,7 @@ pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs), Some(id))), ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => { - sig_from_bounds(cx, ty, cx.tcx.bound_item_bounds(def_id).subst_identity(), cx.tcx.opt_parent(def_id)) + sig_from_bounds(cx, ty, cx.tcx.item_bounds(def_id).subst_identity(), cx.tcx.opt_parent(def_id)) }, ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig, None)), ty::Dynamic(bounds, _, _) => { From 2bfba8685d12e6cd22a62e32e5cbf370e2b0f516 Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Tue, 17 Jan 2023 08:54:07 -0700 Subject: [PATCH 217/500] fix missing subst in clippy utils --- clippy_utils/src/ty.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clippy_utils/src/ty.rs b/clippy_utils/src/ty.rs index 1d2a469ca6ca5..99fba4fe741a1 100644 --- a/clippy_utils/src/ty.rs +++ b/clippy_utils/src/ty.rs @@ -647,8 +647,8 @@ pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs), Some(id))), - ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => { - sig_from_bounds(cx, ty, cx.tcx.item_bounds(def_id).subst_identity(), cx.tcx.opt_parent(def_id)) + ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { + sig_from_bounds(cx, ty, cx.tcx.item_bounds(def_id).subst(cx.tcx, substs), cx.tcx.opt_parent(def_id)) }, ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig, None)), ty::Dynamic(bounds, _, _) => { From 12d18e403139eeeeb339e8611b2bed4910864edb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Tue, 17 Jan 2023 17:02:09 +0000 Subject: [PATCH 218/500] Ensure macros are not affected --- tests/ui/parser/fake-anon-enums-in-macros.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 tests/ui/parser/fake-anon-enums-in-macros.rs diff --git a/tests/ui/parser/fake-anon-enums-in-macros.rs b/tests/ui/parser/fake-anon-enums-in-macros.rs new file mode 100644 index 0000000000000..38fe8dee23829 --- /dev/null +++ b/tests/ui/parser/fake-anon-enums-in-macros.rs @@ -0,0 +1,20 @@ +// build-pass +macro_rules! check_ty { + ($Z:ty) => { compile_error!("triggered"); }; + ($X:ty | $Y:ty) => { $X }; +} + +macro_rules! check { + ($Z:ty) => { compile_error!("triggered"); }; + ($X:ty | $Y:ty) => { }; +} + +check! { i32 | u8 } + +fn foo(x: check_ty! { i32 | u8 }) -> check_ty! { i32 | u8 } { + x +} +fn main() { + let x: check_ty! { i32 | u8 } = 42; + let _: check_ty! { i32 | u8 } = foo(x); +} From 875e36f7e459776d3e51b7c089ab89b0821b6122 Mon Sep 17 00:00:00 2001 From: Niki4tap Date: Sun, 8 Jan 2023 06:52:22 +0300 Subject: [PATCH 219/500] Add `multiple_unsafe_ops_per_block` lint --- CHANGELOG.md | 1 + clippy_lints/src/declared_lints.rs | 1 + clippy_lints/src/lib.rs | 2 + .../src/multiple_unsafe_ops_per_block.rs | 185 ++++++++++++++++++ tests/ui/multiple_unsafe_ops_per_block.rs | 110 +++++++++++ tests/ui/multiple_unsafe_ops_per_block.stderr | 129 ++++++++++++ 6 files changed, 428 insertions(+) create mode 100644 clippy_lints/src/multiple_unsafe_ops_per_block.rs create mode 100644 tests/ui/multiple_unsafe_ops_per_block.rs create mode 100644 tests/ui/multiple_unsafe_ops_per_block.stderr diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e31e8f0d9815..84f4654f34e47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4383,6 +4383,7 @@ Released 2018-09-13 [`multi_assignments`]: https://rust-lang.github.io/rust-clippy/master/index.html#multi_assignments [`multiple_crate_versions`]: https://rust-lang.github.io/rust-clippy/master/index.html#multiple_crate_versions [`multiple_inherent_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#multiple_inherent_impl +[`multiple_unsafe_ops_per_block`]: https://rust-lang.github.io/rust-clippy/master/index.html#multiple_unsafe_ops_per_block [`must_use_candidate`]: https://rust-lang.github.io/rust-clippy/master/index.html#must_use_candidate [`must_use_unit`]: https://rust-lang.github.io/rust-clippy/master/index.html#must_use_unit [`mut_from_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#mut_from_ref diff --git a/clippy_lints/src/declared_lints.rs b/clippy_lints/src/declared_lints.rs index 91ca73633f062..36a366fc97474 100644 --- a/clippy_lints/src/declared_lints.rs +++ b/clippy_lints/src/declared_lints.rs @@ -422,6 +422,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[ crate::module_style::MOD_MODULE_FILES_INFO, crate::module_style::SELF_NAMED_MODULE_FILES_INFO, crate::multi_assignments::MULTI_ASSIGNMENTS_INFO, + crate::multiple_unsafe_ops_per_block::MULTIPLE_UNSAFE_OPS_PER_BLOCK_INFO, crate::mut_key::MUTABLE_KEY_TYPE_INFO, crate::mut_mut::MUT_MUT_INFO, crate::mut_reference::UNNECESSARY_MUT_PASSED_INFO, diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index d8e2ae02c5a65..5c4b604104417 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -198,6 +198,7 @@ mod missing_trait_methods; mod mixed_read_write_in_expression; mod module_style; mod multi_assignments; +mod multiple_unsafe_ops_per_block; mod mut_key; mod mut_mut; mod mut_reference; @@ -908,6 +909,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_late_pass(|_| Box::new(fn_null_check::FnNullCheck)); store.register_late_pass(|_| Box::new(permissions_set_readonly_false::PermissionsSetReadonlyFalse)); store.register_late_pass(|_| Box::new(size_of_ref::SizeOfRef)); + store.register_late_pass(|_| Box::new(multiple_unsafe_ops_per_block::MultipleUnsafeOpsPerBlock)); // add lints here, do not remove this comment, it's used in `new_lint` } diff --git a/clippy_lints/src/multiple_unsafe_ops_per_block.rs b/clippy_lints/src/multiple_unsafe_ops_per_block.rs new file mode 100644 index 0000000000000..18e61c75eece3 --- /dev/null +++ b/clippy_lints/src/multiple_unsafe_ops_per_block.rs @@ -0,0 +1,185 @@ +use clippy_utils::{ + diagnostics::span_lint_and_then, + visitors::{for_each_expr_with_closures, Descend, Visitable}, +}; +use core::ops::ControlFlow::Continue; +use hir::{ + def::{DefKind, Res}, + BlockCheckMode, ExprKind, QPath, UnOp, Unsafety, +}; +use rustc_ast::Mutability; +use rustc_hir as hir; +use rustc_lint::{LateContext, LateLintPass}; +use rustc_session::{declare_lint_pass, declare_tool_lint}; +use rustc_span::Span; + +declare_clippy_lint! { + /// ### What it does + /// Checks for `unsafe` blocks that contain more than one unsafe operation. + /// + /// ### Why is this bad? + /// Combined with `undocumented_unsafe_blocks`, + /// this lint ensures that each unsafe operation must be independently justified. + /// Combined with `unused_unsafe`, this lint also ensures + /// elimination of unnecessary unsafe blocks through refactoring. + /// + /// ### Example + /// ```rust + /// /// Reads a `char` from the given pointer. + /// /// + /// /// # Safety + /// /// + /// /// `ptr` must point to four consecutive, initialized bytes which + /// /// form a valid `char` when interpreted in the native byte order. + /// fn read_char(ptr: *const u8) -> char { + /// // SAFETY: The caller has guaranteed that the value pointed + /// // to by `bytes` is a valid `char`. + /// unsafe { char::from_u32_unchecked(*ptr.cast::()) } + /// } + /// ``` + /// Use instead: + /// ```rust + /// /// Reads a `char` from the given pointer. + /// /// + /// /// # Safety + /// /// + /// /// - `ptr` must be 4-byte aligned, point to four consecutive + /// /// initialized bytes, and be valid for reads of 4 bytes. + /// /// - The bytes pointed to by `ptr` must represent a valid + /// /// `char` when interpreted in the native byte order. + /// fn read_char(ptr: *const u8) -> char { + /// // SAFETY: `ptr` is 4-byte aligned, points to four consecutive + /// // initialized bytes, and is valid for reads of 4 bytes. + /// let int_value = unsafe { *ptr.cast::() }; + /// + /// // SAFETY: The caller has guaranteed that the four bytes + /// // pointed to by `bytes` represent a valid `char`. + /// unsafe { char::from_u32_unchecked(int_value) } + /// } + /// ``` + #[clippy::version = "1.68.0"] + pub MULTIPLE_UNSAFE_OPS_PER_BLOCK, + restriction, + "more than one unsafe operation per `unsafe` block" +} +declare_lint_pass!(MultipleUnsafeOpsPerBlock => [MULTIPLE_UNSAFE_OPS_PER_BLOCK]); + +impl<'tcx> LateLintPass<'tcx> for MultipleUnsafeOpsPerBlock { + fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) { + if !matches!(block.rules, BlockCheckMode::UnsafeBlock(_)) { + return; + } + let mut unsafe_ops = vec![]; + collect_unsafe_exprs(cx, block, &mut unsafe_ops); + if unsafe_ops.len() > 1 { + span_lint_and_then( + cx, + MULTIPLE_UNSAFE_OPS_PER_BLOCK, + block.span, + &format!( + "this `unsafe` block contains {} unsafe operations, expected only one", + unsafe_ops.len() + ), + |diag| { + for (msg, span) in unsafe_ops { + diag.span_note(span, msg); + } + }, + ); + } + } +} + +fn collect_unsafe_exprs<'tcx>( + cx: &LateContext<'tcx>, + node: impl Visitable<'tcx>, + unsafe_ops: &mut Vec<(&'static str, Span)>, +) { + for_each_expr_with_closures(cx, node, |expr| { + match expr.kind { + ExprKind::InlineAsm(_) => unsafe_ops.push(("inline assembly used here", expr.span)), + + ExprKind::Field(e, _) => { + if cx.typeck_results().expr_ty(e).is_union() { + unsafe_ops.push(("union field access occurs here", expr.span)); + } + }, + + ExprKind::Path(QPath::Resolved( + _, + hir::Path { + res: Res::Def(DefKind::Static(Mutability::Mut), _), + .. + }, + )) => { + unsafe_ops.push(("access of a mutable static occurs here", expr.span)); + }, + + ExprKind::Unary(UnOp::Deref, e) if cx.typeck_results().expr_ty_adjusted(e).is_unsafe_ptr() => { + unsafe_ops.push(("raw pointer dereference occurs here", expr.span)); + }, + + ExprKind::Call(path_expr, _) => match path_expr.kind { + ExprKind::Path(QPath::Resolved( + _, + hir::Path { + res: Res::Def(kind, def_id), + .. + }, + )) if kind.is_fn_like() => { + let sig = cx.tcx.bound_fn_sig(*def_id); + if sig.0.unsafety() == Unsafety::Unsafe { + unsafe_ops.push(("unsafe function call occurs here", expr.span)); + } + }, + + ExprKind::Path(QPath::TypeRelative(..)) => { + if let Some(sig) = cx + .typeck_results() + .type_dependent_def_id(path_expr.hir_id) + .map(|def_id| cx.tcx.bound_fn_sig(def_id)) + { + if sig.0.unsafety() == Unsafety::Unsafe { + unsafe_ops.push(("unsafe function call occurs here", expr.span)); + } + } + }, + + _ => {}, + }, + + ExprKind::MethodCall(..) => { + if let Some(sig) = cx + .typeck_results() + .type_dependent_def_id(expr.hir_id) + .map(|def_id| cx.tcx.bound_fn_sig(def_id)) + { + if sig.0.unsafety() == Unsafety::Unsafe { + unsafe_ops.push(("unsafe method call occurs here", expr.span)); + } + } + }, + + ExprKind::AssignOp(_, lhs, rhs) | ExprKind::Assign(lhs, rhs, _) => { + if matches!( + lhs.kind, + ExprKind::Path(QPath::Resolved( + _, + hir::Path { + res: Res::Def(DefKind::Static(Mutability::Mut), _), + .. + } + )) + ) { + unsafe_ops.push(("modification of a mutable static occurs here", expr.span)); + collect_unsafe_exprs(cx, rhs, unsafe_ops); + return Continue(Descend::No); + } + }, + + _ => {}, + }; + + Continue::<(), _>(Descend::Yes) + }); +} diff --git a/tests/ui/multiple_unsafe_ops_per_block.rs b/tests/ui/multiple_unsafe_ops_per_block.rs new file mode 100644 index 0000000000000..41263535df673 --- /dev/null +++ b/tests/ui/multiple_unsafe_ops_per_block.rs @@ -0,0 +1,110 @@ +#![allow(unused)] +#![allow(deref_nullptr)] +#![allow(clippy::unnecessary_operation)] +#![allow(clippy::drop_copy)] +#![warn(clippy::multiple_unsafe_ops_per_block)] + +use core::arch::asm; + +fn raw_ptr() -> *const () { + core::ptr::null() +} + +unsafe fn not_very_safe() {} + +struct Sample; + +impl Sample { + unsafe fn not_very_safe(&self) {} +} + +#[allow(non_upper_case_globals)] +const sample: Sample = Sample; + +union U { + i: i32, + u: u32, +} + +static mut STATIC: i32 = 0; + +fn test1() { + unsafe { + STATIC += 1; + not_very_safe(); + } +} + +fn test2() { + let u = U { i: 0 }; + + unsafe { + drop(u.u); + *raw_ptr(); + } +} + +fn test3() { + unsafe { + asm!("nop"); + sample.not_very_safe(); + STATIC = 0; + } +} + +fn test_all() { + let u = U { i: 0 }; + unsafe { + drop(u.u); + drop(STATIC); + sample.not_very_safe(); + not_very_safe(); + *raw_ptr(); + asm!("nop"); + } +} + +// no lint +fn correct1() { + unsafe { + STATIC += 1; + } +} + +// no lint +fn correct2() { + unsafe { + STATIC += 1; + } + + unsafe { + *raw_ptr(); + } +} + +// no lint +fn correct3() { + let u = U { u: 0 }; + + unsafe { + not_very_safe(); + } + + unsafe { + drop(u.i); + } +} + +// tests from the issue (https://github.com/rust-lang/rust-clippy/issues/10064) + +unsafe fn read_char_bad(ptr: *const u8) -> char { + unsafe { char::from_u32_unchecked(*ptr.cast::()) } +} + +// no lint +unsafe fn read_char_good(ptr: *const u8) -> char { + let int_value = unsafe { *ptr.cast::() }; + unsafe { core::char::from_u32_unchecked(int_value) } +} + +fn main() {} diff --git a/tests/ui/multiple_unsafe_ops_per_block.stderr b/tests/ui/multiple_unsafe_ops_per_block.stderr new file mode 100644 index 0000000000000..f6b8341795d23 --- /dev/null +++ b/tests/ui/multiple_unsafe_ops_per_block.stderr @@ -0,0 +1,129 @@ +error: this `unsafe` block contains 2 unsafe operations, expected only one + --> $DIR/multiple_unsafe_ops_per_block.rs:32:5 + | +LL | / unsafe { +LL | | STATIC += 1; +LL | | not_very_safe(); +LL | | } + | |_____^ + | +note: modification of a mutable static occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:33:9 + | +LL | STATIC += 1; + | ^^^^^^^^^^^ +note: unsafe function call occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:34:9 + | +LL | not_very_safe(); + | ^^^^^^^^^^^^^^^ + = note: `-D clippy::multiple-unsafe-ops-per-block` implied by `-D warnings` + +error: this `unsafe` block contains 2 unsafe operations, expected only one + --> $DIR/multiple_unsafe_ops_per_block.rs:41:5 + | +LL | / unsafe { +LL | | drop(u.u); +LL | | *raw_ptr(); +LL | | } + | |_____^ + | +note: union field access occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:42:14 + | +LL | drop(u.u); + | ^^^ +note: raw pointer dereference occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:43:9 + | +LL | *raw_ptr(); + | ^^^^^^^^^^ + +error: this `unsafe` block contains 3 unsafe operations, expected only one + --> $DIR/multiple_unsafe_ops_per_block.rs:48:5 + | +LL | / unsafe { +LL | | asm!("nop"); +LL | | sample.not_very_safe(); +LL | | STATIC = 0; +LL | | } + | |_____^ + | +note: inline assembly used here + --> $DIR/multiple_unsafe_ops_per_block.rs:49:9 + | +LL | asm!("nop"); + | ^^^^^^^^^^^ +note: unsafe method call occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:50:9 + | +LL | sample.not_very_safe(); + | ^^^^^^^^^^^^^^^^^^^^^^ +note: modification of a mutable static occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:51:9 + | +LL | STATIC = 0; + | ^^^^^^^^^^ + +error: this `unsafe` block contains 6 unsafe operations, expected only one + --> $DIR/multiple_unsafe_ops_per_block.rs:57:5 + | +LL | / unsafe { +LL | | drop(u.u); +LL | | drop(STATIC); +LL | | sample.not_very_safe(); +... | +LL | | asm!("nop"); +LL | | } + | |_____^ + | +note: union field access occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:58:14 + | +LL | drop(u.u); + | ^^^ +note: access of a mutable static occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:59:14 + | +LL | drop(STATIC); + | ^^^^^^ +note: unsafe method call occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:60:9 + | +LL | sample.not_very_safe(); + | ^^^^^^^^^^^^^^^^^^^^^^ +note: unsafe function call occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:61:9 + | +LL | not_very_safe(); + | ^^^^^^^^^^^^^^^ +note: raw pointer dereference occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:62:9 + | +LL | *raw_ptr(); + | ^^^^^^^^^^ +note: inline assembly used here + --> $DIR/multiple_unsafe_ops_per_block.rs:63:9 + | +LL | asm!("nop"); + | ^^^^^^^^^^^ + +error: this `unsafe` block contains 2 unsafe operations, expected only one + --> $DIR/multiple_unsafe_ops_per_block.rs:101:5 + | +LL | unsafe { char::from_u32_unchecked(*ptr.cast::()) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: unsafe function call occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:101:14 + | +LL | unsafe { char::from_u32_unchecked(*ptr.cast::()) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: raw pointer dereference occurs here + --> $DIR/multiple_unsafe_ops_per_block.rs:101:39 + | +LL | unsafe { char::from_u32_unchecked(*ptr.cast::()) } + | ^^^^^^^^^^^^^^^^^^ + +error: aborting due to 5 previous errors + From 3122db7d038734ab4b0d92d799763ce1ac43580d Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Tue, 17 Jan 2023 22:44:16 -0800 Subject: [PATCH 220/500] Implement `SpecOptionPartialEq` for `cmp::Ordering` --- library/core/src/option.rs | 10 +++++++++- tests/codegen/option-nonzero-eq.rs | 10 ++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 7cc00e3f8d1b7..4aeb707fa6788 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -551,7 +551,7 @@ use crate::marker::Destruct; use crate::panicking::{panic, panic_str}; use crate::pin::Pin; use crate::{ - convert, hint, mem, + cmp, convert, hint, mem, ops::{self, ControlFlow, Deref, DerefMut}, }; @@ -2146,6 +2146,14 @@ impl SpecOptionPartialEq for crate::ptr::NonNull { } } +#[stable(feature = "rust1", since = "1.0.0")] +impl SpecOptionPartialEq for cmp::Ordering { + #[inline] + fn eq(l: &Option, r: &Option) -> bool { + l.map_or(2, |x| x as i8) == r.map_or(2, |x| x as i8) + } +} + ///////////////////////////////////////////////////////////////////////////// // The Option Iterators ///////////////////////////////////////////////////////////////////////////// diff --git a/tests/codegen/option-nonzero-eq.rs b/tests/codegen/option-nonzero-eq.rs index 598dcc19b491b..835decd3e5f5e 100644 --- a/tests/codegen/option-nonzero-eq.rs +++ b/tests/codegen/option-nonzero-eq.rs @@ -3,6 +3,7 @@ #![crate_type = "lib"] extern crate core; +use core::cmp::Ordering; use core::num::{NonZeroU32, NonZeroI64}; use core::ptr::NonNull; @@ -32,3 +33,12 @@ pub fn non_null_eq(l: Option>, r: Option>) -> bool { // CHECK-NEXT: ret i1 l == r } + +// CHECK-lABEL: @ordering_eq +#[no_mangle] +pub fn ordering_eq(l: Option, r: Option) -> bool { + // CHECK: start: + // CHECK-NEXT: icmp eq i8 + // CHECK-NEXT: ret i1 + l == r +} From 31a053059e773f08bddca53bbc3c7ca204daaf40 Mon Sep 17 00:00:00 2001 From: Michael Woerister Date: Fri, 2 Dec 2022 16:27:25 +0100 Subject: [PATCH 221/500] Use UnordSet instead of FxHashSet in define_id_collections!(). --- clippy_lints/src/len_zero.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/len_zero.rs b/clippy_lints/src/len_zero.rs index 9eba46756299c..3c70c9cf19a51 100644 --- a/clippy_lints/src/len_zero.rs +++ b/clippy_lints/src/len_zero.rs @@ -219,7 +219,7 @@ fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items let is_empty = sym!(is_empty); let is_empty_method_found = current_and_super_traits - .iter() + .items() .flat_map(|&i| cx.tcx.associated_items(i).filter_by_name_unhygienic(is_empty)) .any(|i| { i.kind == ty::AssocKind::Fn From 465ed5bd46116e55d801a42a34659d558d00b0d7 Mon Sep 17 00:00:00 2001 From: Michael Woerister Date: Tue, 17 Jan 2023 12:05:01 +0100 Subject: [PATCH 222/500] Use UnordMap instead of FxHashMap in define_id_collections!(). --- clippy_lints/src/inherent_impl.rs | 26 +++++++++---------- .../src/loops/while_immutable_condition.rs | 2 +- clippy_lints/src/missing_trait_methods.rs | 26 ++++++++++--------- clippy_lints/src/pass_by_ref_or_value.rs | 4 +-- 4 files changed, 29 insertions(+), 29 deletions(-) diff --git a/clippy_lints/src/inherent_impl.rs b/clippy_lints/src/inherent_impl.rs index c5abcc462545c..81b37ce5dfc2d 100644 --- a/clippy_lints/src/inherent_impl.rs +++ b/clippy_lints/src/inherent_impl.rs @@ -52,21 +52,19 @@ impl<'tcx> LateLintPass<'tcx> for MultipleInherentImpl { // List of spans to lint. (lint_span, first_span) let mut lint_spans = Vec::new(); - for (_, impl_ids) in cx + let inherent_impls = cx .tcx - .crate_inherent_impls(()) - .inherent_impls - .iter() - .filter(|(&id, impls)| { - impls.len() > 1 - // Check for `#[allow]` on the type definition - && !is_lint_allowed( - cx, - MULTIPLE_INHERENT_IMPL, - cx.tcx.hir().local_def_id_to_hir_id(id), - ) - }) - { + .with_stable_hashing_context(|hcx| cx.tcx.crate_inherent_impls(()).inherent_impls.to_sorted(&hcx)); + + for (_, impl_ids) in inherent_impls.into_iter().filter(|(&id, impls)| { + impls.len() > 1 + // Check for `#[allow]` on the type definition + && !is_lint_allowed( + cx, + MULTIPLE_INHERENT_IMPL, + cx.tcx.hir().local_def_id_to_hir_id(id), + ) + }) { for impl_id in impl_ids.iter().map(|id| id.expect_local()) { match type_map.entry(cx.tcx.type_of(impl_id)) { Entry::Vacant(e) => { diff --git a/clippy_lints/src/loops/while_immutable_condition.rs b/clippy_lints/src/loops/while_immutable_condition.rs index a63422d2a36ac..d1a1f773f87b3 100644 --- a/clippy_lints/src/loops/while_immutable_condition.rs +++ b/clippy_lints/src/loops/while_immutable_condition.rs @@ -35,7 +35,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, cond: &'tcx Expr<'_>, expr: &' } else { return; }; - let mutable_static_in_cond = var_visitor.def_ids.iter().any(|(_, v)| *v); + let mutable_static_in_cond = var_visitor.def_ids.items().any(|(_, v)| *v); let mut has_break_or_return_visitor = HasBreakOrReturnVisitor { has_break_or_return: false, diff --git a/clippy_lints/src/missing_trait_methods.rs b/clippy_lints/src/missing_trait_methods.rs index 68af8a672f6ae..1c61c6e551c35 100644 --- a/clippy_lints/src/missing_trait_methods.rs +++ b/clippy_lints/src/missing_trait_methods.rs @@ -80,19 +80,21 @@ impl<'tcx> LateLintPass<'tcx> for MissingTraitMethods { } } - for assoc in provided.values() { - let source_map = cx.tcx.sess.source_map(); - let definition_span = source_map.guess_head_span(cx.tcx.def_span(assoc.def_id)); + cx.tcx.with_stable_hashing_context(|hcx| { + for assoc in provided.values_sorted(&hcx) { + let source_map = cx.tcx.sess.source_map(); + let definition_span = source_map.guess_head_span(cx.tcx.def_span(assoc.def_id)); - span_lint_and_help( - cx, - MISSING_TRAIT_METHODS, - source_map.guess_head_span(item.span), - &format!("missing trait method provided by default: `{}`", assoc.name), - Some(definition_span), - "implement the method", - ); - } + span_lint_and_help( + cx, + MISSING_TRAIT_METHODS, + source_map.guess_head_span(item.span), + &format!("missing trait method provided by default: `{}`", assoc.name), + Some(definition_span), + "implement the method", + ); + } + }) } } } diff --git a/clippy_lints/src/pass_by_ref_or_value.rs b/clippy_lints/src/pass_by_ref_or_value.rs index 870a1c7d88d53..2d21aaa4f7fdb 100644 --- a/clippy_lints/src/pass_by_ref_or_value.rs +++ b/clippy_lints/src/pass_by_ref_or_value.rs @@ -190,10 +190,10 @@ impl<'tcx> PassByRefOrValue { // Don't lint if an unsafe pointer is created. // TODO: Limit the check only to unsafe pointers to the argument (or part of the argument) // which escape the current function. - if typeck.node_types().iter().any(|(_, &ty)| ty.is_unsafe_ptr()) + if typeck.node_types().items().any(|(_, &ty)| ty.is_unsafe_ptr()) || typeck .adjustments() - .iter() + .items() .flat_map(|(_, a)| a) .any(|a| matches!(a.kind, Adjust::Pointer(PointerCast::UnsafeFnPointer))) { From c1b358945a4e1d4877b21c02fa52afc5ff2b39a7 Mon Sep 17 00:00:00 2001 From: Michael Woerister Date: Wed, 18 Jan 2023 10:47:31 +0100 Subject: [PATCH 223/500] Allow for more efficient sorting when exporting Unord collections. --- clippy_lints/src/inherent_impl.rs | 2 +- clippy_lints/src/missing_trait_methods.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/inherent_impl.rs b/clippy_lints/src/inherent_impl.rs index 81b37ce5dfc2d..e9b2e31a769ad 100644 --- a/clippy_lints/src/inherent_impl.rs +++ b/clippy_lints/src/inherent_impl.rs @@ -54,7 +54,7 @@ impl<'tcx> LateLintPass<'tcx> for MultipleInherentImpl { let inherent_impls = cx .tcx - .with_stable_hashing_context(|hcx| cx.tcx.crate_inherent_impls(()).inherent_impls.to_sorted(&hcx)); + .with_stable_hashing_context(|hcx| cx.tcx.crate_inherent_impls(()).inherent_impls.to_sorted(&hcx, true)); for (_, impl_ids) in inherent_impls.into_iter().filter(|(&id, impls)| { impls.len() > 1 diff --git a/clippy_lints/src/missing_trait_methods.rs b/clippy_lints/src/missing_trait_methods.rs index 1c61c6e551c35..3371b4cce32c1 100644 --- a/clippy_lints/src/missing_trait_methods.rs +++ b/clippy_lints/src/missing_trait_methods.rs @@ -81,7 +81,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingTraitMethods { } cx.tcx.with_stable_hashing_context(|hcx| { - for assoc in provided.values_sorted(&hcx) { + for assoc in provided.values_sorted(&hcx, true) { let source_map = cx.tcx.sess.source_map(); let definition_span = source_map.guess_head_span(cx.tcx.def_span(assoc.def_id)); From 11611b0440d563e26758f7f4481e4fb66f4fe73f Mon Sep 17 00:00:00 2001 From: Alex Macleod Date: Fri, 13 Jan 2023 00:04:28 +0000 Subject: [PATCH 224/500] Move `unchecked_duration_subtraction` to pedantic --- clippy_lints/src/instant_subtraction.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/instant_subtraction.rs b/clippy_lints/src/instant_subtraction.rs index dd1b23e7d9d29..9f6e89405713c 100644 --- a/clippy_lints/src/instant_subtraction.rs +++ b/clippy_lints/src/instant_subtraction.rs @@ -61,7 +61,7 @@ declare_clippy_lint! { /// [`Instant::now()`]: std::time::Instant::now; #[clippy::version = "1.65.0"] pub UNCHECKED_DURATION_SUBTRACTION, - suspicious, + pedantic, "finds unchecked subtraction of a 'Duration' from an 'Instant'" } From d9baced2b595d52d6927bb4696fa5067c1a427d1 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Thu, 19 Jan 2023 11:26:56 +0100 Subject: [PATCH 225/500] Improve the changelog update documentation - Make the clippy::version attribute instructions more prominent. - Mention the beta-accepted label. --- .../infrastructure/changelog_update.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/book/src/development/infrastructure/changelog_update.md b/book/src/development/infrastructure/changelog_update.md index 80a47affe30d0..d1ac7237b5e35 100644 --- a/book/src/development/infrastructure/changelog_update.md +++ b/book/src/development/infrastructure/changelog_update.md @@ -95,11 +95,23 @@ As section headers, we use: Please also be sure to update the Beta/Unreleased sections at the top with the relevant commit ranges. -If you have the time, it would be appreciated if you double-check, that the -`#[clippy::version]` attributes for the added lints contains the correct version. +#### 3.1 Include `beta-accepted` PRs + +Look for the [`beta-accepted`] label and make sure to also include the PRs with +that label in the changelog. If you can, remove the `beta-accepted` labels +**after** the changelog PR was merged. + +> _Note:_ Some of those PRs might even got backported to the previous `beta`. +> Those have to be included in the changelog of the _previous_ release. + +### 4. Update `clippy::version` attributes + +Next, make sure to check that the `#[clippy::version]` attributes for the added +lints contain the correct version. [changelog]: https://github.com/rust-lang/rust-clippy/blob/master/CHANGELOG.md [forge]: https://forge.rust-lang.org/ [rust_master_tools]: https://github.com/rust-lang/rust/tree/master/src/tools/clippy [rust_beta_tools]: https://github.com/rust-lang/rust/tree/beta/src/tools/clippy [rust_stable_tools]: https://github.com/rust-lang/rust/releases +[`beta-accepted`]: https://github.com/rust-lang/rust-clippy/issues?q=label%3Abeta-accepted+ From 0accf08e6b2b7a59147e9ca1c80ed969e82781fc Mon Sep 17 00:00:00 2001 From: lcnr Date: Thu, 19 Jan 2023 16:06:25 +0100 Subject: [PATCH 226/500] remove unnecessary check for opaque types --- compiler/rustc_const_eval/src/transform/validate.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/compiler/rustc_const_eval/src/transform/validate.rs b/compiler/rustc_const_eval/src/transform/validate.rs index dd168a9ac3cd3..3f83d40755ad8 100644 --- a/compiler/rustc_const_eval/src/transform/validate.rs +++ b/compiler/rustc_const_eval/src/transform/validate.rs @@ -13,7 +13,7 @@ use rustc_middle::mir::{ ProjectionElem, RetagKind, RuntimePhase, Rvalue, SourceScope, Statement, StatementKind, Terminator, TerminatorKind, UnOp, START_BLOCK, }; -use rustc_middle::ty::{self, InstanceDef, ParamEnv, Ty, TyCtxt, TypeVisitable}; +use rustc_middle::ty::{self, InstanceDef, ParamEnv, Ty, TyCtxt}; use rustc_mir_dataflow::impls::MaybeStorageLive; use rustc_mir_dataflow::storage::always_storage_live_locals; use rustc_mir_dataflow::{Analysis, ResultsCursor}; @@ -230,11 +230,6 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // Equal types, all is good. return true; } - // Normalization reveals opaque types, but we may be validating MIR while computing - // said opaque types, causing cycles. - if (src, dest).has_opaque_types() { - return true; - } crate::util::is_subtype(self.tcx, self.param_env, src, dest) } From 8e43414bce77cfe2030b875e365c77691897b95f Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 19 Jan 2023 16:31:50 +0100 Subject: [PATCH 227/500] Fix proc macro tests --- tests/ui/proc-macro/allowed-signatures.rs | 2 ++ tests/ui/proc-macro/proc-macro-abi.rs | 3 +++ tests/ui/proc-macro/proc-macro-abi.stderr | 6 +++--- .../ui/proc-macro/signature-proc-macro-attribute.rs | 3 +++ .../proc-macro/signature-proc-macro-attribute.stderr | 12 ++++++------ tests/ui/proc-macro/signature-proc-macro-derive.rs | 3 +++ .../ui/proc-macro/signature-proc-macro-derive.stderr | 10 +++++----- tests/ui/proc-macro/signature-proc-macro.rs | 3 +++ tests/ui/proc-macro/signature-proc-macro.stderr | 10 +++++----- 9 files changed, 33 insertions(+), 19 deletions(-) diff --git a/tests/ui/proc-macro/allowed-signatures.rs b/tests/ui/proc-macro/allowed-signatures.rs index 03c6ef86632df..8685087611248 100644 --- a/tests/ui/proc-macro/allowed-signatures.rs +++ b/tests/ui/proc-macro/allowed-signatures.rs @@ -1,4 +1,6 @@ // check-pass +// force-host +// no-prefer-dynamic #![crate_type = "proc-macro"] #![allow(private_in_public)] diff --git a/tests/ui/proc-macro/proc-macro-abi.rs b/tests/ui/proc-macro/proc-macro-abi.rs index 8e9d50d7832d5..873660a5b3ab9 100644 --- a/tests/ui/proc-macro/proc-macro-abi.rs +++ b/tests/ui/proc-macro/proc-macro-abi.rs @@ -1,3 +1,6 @@ +// force-host +// no-prefer-dynamic + #![crate_type = "proc-macro"] #![allow(warnings)] diff --git a/tests/ui/proc-macro/proc-macro-abi.stderr b/tests/ui/proc-macro/proc-macro-abi.stderr index fa5f5dc098998..9a781be0996dd 100644 --- a/tests/ui/proc-macro/proc-macro-abi.stderr +++ b/tests/ui/proc-macro/proc-macro-abi.stderr @@ -1,17 +1,17 @@ error: proc macro functions may not be `extern "C"` - --> $DIR/proc-macro-abi.rs:8:1 + --> $DIR/proc-macro-abi.rs:11:1 | LL | pub extern "C" fn abi(a: TokenStream) -> TokenStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: proc macro functions may not be `extern "system"` - --> $DIR/proc-macro-abi.rs:14:1 + --> $DIR/proc-macro-abi.rs:17:1 | LL | pub extern "system" fn abi2(a: TokenStream) -> TokenStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: proc macro functions may not be `extern "C"` - --> $DIR/proc-macro-abi.rs:20:1 + --> $DIR/proc-macro-abi.rs:23:1 | LL | pub extern fn abi3(a: TokenStream) -> TokenStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/proc-macro/signature-proc-macro-attribute.rs b/tests/ui/proc-macro/signature-proc-macro-attribute.rs index fb17710950106..51abc8e7d3edb 100644 --- a/tests/ui/proc-macro/signature-proc-macro-attribute.rs +++ b/tests/ui/proc-macro/signature-proc-macro-attribute.rs @@ -1,3 +1,6 @@ +// force-host +// no-prefer-dynamic + #![crate_type = "proc-macro"] extern crate proc_macro; diff --git a/tests/ui/proc-macro/signature-proc-macro-attribute.stderr b/tests/ui/proc-macro/signature-proc-macro-attribute.stderr index ecfd2b06e109c..abf7a6f3ce922 100644 --- a/tests/ui/proc-macro/signature-proc-macro-attribute.stderr +++ b/tests/ui/proc-macro/signature-proc-macro-attribute.stderr @@ -1,11 +1,11 @@ error: mismatched attribute proc macro signature - --> $DIR/signature-proc-macro-attribute.rs:7:1 + --> $DIR/signature-proc-macro-attribute.rs:10:1 | LL | pub fn bad_input(input: String) -> TokenStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ attribute proc macro must have two arguments of type `proc_macro::TokenStream` error: mismatched attribute proc macro signature - --> $DIR/signature-proc-macro-attribute.rs:13:42 + --> $DIR/signature-proc-macro-attribute.rs:16:42 | LL | pub fn bad_output(input: TokenStream) -> String { | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` @@ -13,13 +13,13 @@ LL | pub fn bad_output(input: TokenStream) -> String { = note: attribute proc macros must have a signature of `fn(TokenStream, TokenStream) -> TokenStream` error: mismatched attribute proc macro signature - --> $DIR/signature-proc-macro-attribute.rs:13:1 + --> $DIR/signature-proc-macro-attribute.rs:16:1 | LL | pub fn bad_output(input: TokenStream) -> String { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ attribute proc macro must have two arguments of type `proc_macro::TokenStream` error: mismatched attribute proc macro signature - --> $DIR/signature-proc-macro-attribute.rs:20:41 + --> $DIR/signature-proc-macro-attribute.rs:23:41 | LL | pub fn bad_everything(input: String) -> String { | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` @@ -27,13 +27,13 @@ LL | pub fn bad_everything(input: String) -> String { = note: attribute proc macros must have a signature of `fn(TokenStream, TokenStream) -> TokenStream` error: mismatched attribute proc macro signature - --> $DIR/signature-proc-macro-attribute.rs:20:1 + --> $DIR/signature-proc-macro-attribute.rs:23:1 | LL | pub fn bad_everything(input: String) -> String { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ attribute proc macro must have two arguments of type `proc_macro::TokenStream` error: mismatched attribute proc macro signature - --> $DIR/signature-proc-macro-attribute.rs:27:49 + --> $DIR/signature-proc-macro-attribute.rs:30:49 | LL | pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { | ^^^^^^^^^ found unexpected argument diff --git a/tests/ui/proc-macro/signature-proc-macro-derive.rs b/tests/ui/proc-macro/signature-proc-macro-derive.rs index a079157538fb6..f2fd824b675b6 100644 --- a/tests/ui/proc-macro/signature-proc-macro-derive.rs +++ b/tests/ui/proc-macro/signature-proc-macro-derive.rs @@ -1,3 +1,6 @@ +// force-host +// no-prefer-dynamic + #![crate_type = "proc-macro"] extern crate proc_macro; diff --git a/tests/ui/proc-macro/signature-proc-macro-derive.stderr b/tests/ui/proc-macro/signature-proc-macro-derive.stderr index bb2bd9a93d24b..a358ae277037f 100644 --- a/tests/ui/proc-macro/signature-proc-macro-derive.stderr +++ b/tests/ui/proc-macro/signature-proc-macro-derive.stderr @@ -1,5 +1,5 @@ error: mismatched derive proc macro signature - --> $DIR/signature-proc-macro-derive.rs:7:25 + --> $DIR/signature-proc-macro-derive.rs:10:25 | LL | pub fn bad_input(input: String) -> TokenStream { | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` @@ -7,7 +7,7 @@ LL | pub fn bad_input(input: String) -> TokenStream { = note: derive proc macros must have a signature of `fn(TokenStream) -> TokenStream` error: mismatched derive proc macro signature - --> $DIR/signature-proc-macro-derive.rs:13:42 + --> $DIR/signature-proc-macro-derive.rs:16:42 | LL | pub fn bad_output(input: TokenStream) -> String { | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` @@ -15,7 +15,7 @@ LL | pub fn bad_output(input: TokenStream) -> String { = note: derive proc macros must have a signature of `fn(TokenStream) -> TokenStream` error: mismatched derive proc macro signature - --> $DIR/signature-proc-macro-derive.rs:19:41 + --> $DIR/signature-proc-macro-derive.rs:22:41 | LL | pub fn bad_everything(input: String) -> String { | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` @@ -23,7 +23,7 @@ LL | pub fn bad_everything(input: String) -> String { = note: derive proc macros must have a signature of `fn(TokenStream) -> TokenStream` error: mismatched derive proc macro signature - --> $DIR/signature-proc-macro-derive.rs:19:30 + --> $DIR/signature-proc-macro-derive.rs:22:30 | LL | pub fn bad_everything(input: String) -> String { | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` @@ -31,7 +31,7 @@ LL | pub fn bad_everything(input: String) -> String { = note: derive proc macros must have a signature of `fn(TokenStream) -> TokenStream` error: mismatched derive proc macro signature - --> $DIR/signature-proc-macro-derive.rs:26:33 + --> $DIR/signature-proc-macro-derive.rs:29:33 | LL | pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^ found unexpected arguments diff --git a/tests/ui/proc-macro/signature-proc-macro.rs b/tests/ui/proc-macro/signature-proc-macro.rs index 35d5be2171283..54770aacd1a98 100644 --- a/tests/ui/proc-macro/signature-proc-macro.rs +++ b/tests/ui/proc-macro/signature-proc-macro.rs @@ -1,3 +1,6 @@ +// force-host +// no-prefer-dynamic + #![crate_type = "proc-macro"] extern crate proc_macro; diff --git a/tests/ui/proc-macro/signature-proc-macro.stderr b/tests/ui/proc-macro/signature-proc-macro.stderr index 32241e1b9e00a..4b14a54e67503 100644 --- a/tests/ui/proc-macro/signature-proc-macro.stderr +++ b/tests/ui/proc-macro/signature-proc-macro.stderr @@ -1,5 +1,5 @@ error: mismatched function-like proc macro signature - --> $DIR/signature-proc-macro.rs:7:25 + --> $DIR/signature-proc-macro.rs:10:25 | LL | pub fn bad_input(input: String) -> TokenStream { | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` @@ -7,7 +7,7 @@ LL | pub fn bad_input(input: String) -> TokenStream { = note: function-like proc macros must have a signature of `fn(TokenStream) -> TokenStream` error: mismatched function-like proc macro signature - --> $DIR/signature-proc-macro.rs:13:42 + --> $DIR/signature-proc-macro.rs:16:42 | LL | pub fn bad_output(input: TokenStream) -> String { | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` @@ -15,7 +15,7 @@ LL | pub fn bad_output(input: TokenStream) -> String { = note: function-like proc macros must have a signature of `fn(TokenStream) -> TokenStream` error: mismatched function-like proc macro signature - --> $DIR/signature-proc-macro.rs:19:41 + --> $DIR/signature-proc-macro.rs:22:41 | LL | pub fn bad_everything(input: String) -> String { | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` @@ -23,7 +23,7 @@ LL | pub fn bad_everything(input: String) -> String { = note: function-like proc macros must have a signature of `fn(TokenStream) -> TokenStream` error: mismatched function-like proc macro signature - --> $DIR/signature-proc-macro.rs:19:30 + --> $DIR/signature-proc-macro.rs:22:30 | LL | pub fn bad_everything(input: String) -> String { | ^^^^^^ found std::string::String, expected type `proc_macro::TokenStream` @@ -31,7 +31,7 @@ LL | pub fn bad_everything(input: String) -> String { = note: function-like proc macros must have a signature of `fn(TokenStream) -> TokenStream` error: mismatched function-like proc macro signature - --> $DIR/signature-proc-macro.rs:26:33 + --> $DIR/signature-proc-macro.rs:29:33 | LL | pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^ found unexpected arguments From 4e87f13054fa3cd9103b1b5ad9a2ed499fc542d5 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 19 Jan 2023 14:51:43 +0000 Subject: [PATCH 228/500] Fix a couple of TOCTOU occurences --- build_system/build_sysroot.rs | 6 ++---- build_system/path.rs | 6 +++--- build_system/prepare.rs | 9 ++------- build_system/utils.rs | 10 +++++++++- 4 files changed, 16 insertions(+), 15 deletions(-) diff --git a/build_system/build_sysroot.rs b/build_system/build_sysroot.rs index f52d34ffcd63f..bd04fdbe304a3 100644 --- a/build_system/build_sysroot.rs +++ b/build_system/build_sysroot.rs @@ -4,7 +4,7 @@ use std::process::{self, Command}; use super::path::{Dirs, RelPath}; use super::rustc_info::{get_file_name, get_rustc_version, get_toolchain_name}; -use super::utils::{spawn_and_wait, try_hard_link, CargoProject, Compiler}; +use super::utils::{remove_dir_if_exists, spawn_and_wait, try_hard_link, CargoProject, Compiler}; use super::SysrootKind; static DIST_DIR: RelPath = RelPath::DIST; @@ -230,9 +230,7 @@ fn build_clif_sysroot_for_triple( if !super::config::get_bool("keep_sysroot") { // Cleanup the deps dir, but keep build scripts and the incremental cache for faster // recompilation as they are not affected by changes in cg_clif. - if build_dir.join("deps").exists() { - fs::remove_dir_all(build_dir.join("deps")).unwrap(); - } + remove_dir_if_exists(&build_dir.join("deps")); } // Build sysroot diff --git a/build_system/path.rs b/build_system/path.rs index 35ab6f111fef4..3290723005dd9 100644 --- a/build_system/path.rs +++ b/build_system/path.rs @@ -1,6 +1,8 @@ use std::fs; use std::path::PathBuf; +use super::utils::remove_dir_if_exists; + #[derive(Debug, Clone)] pub(crate) struct Dirs { pub(crate) source_dir: PathBuf, @@ -61,9 +63,7 @@ impl RelPath { pub(crate) fn ensure_fresh(&self, dirs: &Dirs) { let path = self.to_path(dirs); - if path.exists() { - fs::remove_dir_all(&path).unwrap(); - } + remove_dir_if_exists(&path); fs::create_dir_all(path).unwrap(); } } diff --git a/build_system/prepare.rs b/build_system/prepare.rs index bc6c3223dc234..f25a81dc23459 100644 --- a/build_system/prepare.rs +++ b/build_system/prepare.rs @@ -3,18 +3,13 @@ use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; -use crate::build_system::rustc_info::get_default_sysroot; - use super::build_sysroot::{BUILD_SYSROOT, ORIG_BUILD_SYSROOT, SYSROOT_RUSTC_VERSION, SYSROOT_SRC}; use super::path::{Dirs, RelPath}; -use super::rustc_info::get_rustc_version; +use super::rustc_info::{get_default_sysroot, get_rustc_version}; use super::utils::{copy_dir_recursively, git_command, retry_spawn_and_wait, spawn_and_wait}; pub(crate) fn prepare(dirs: &Dirs) { - if RelPath::DOWNLOAD.to_path(dirs).exists() { - std::fs::remove_dir_all(RelPath::DOWNLOAD.to_path(dirs)).unwrap(); - } - std::fs::create_dir_all(RelPath::DOWNLOAD.to_path(dirs)).unwrap(); + RelPath::DOWNLOAD.ensure_fresh(dirs); spawn_and_wait(super::build_backend::CG_CLIF.fetch("cargo", dirs)); diff --git a/build_system/utils.rs b/build_system/utils.rs index 21bfb1b1f00f5..da2a94a0a4ff8 100644 --- a/build_system/utils.rs +++ b/build_system/utils.rs @@ -1,6 +1,6 @@ use std::env; use std::fs; -use std::io::Write; +use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::process::{self, Command, Stdio}; @@ -246,6 +246,14 @@ pub(crate) fn spawn_and_wait_with_input(mut cmd: Command, input: String) -> Stri String::from_utf8(output.stdout).unwrap() } +pub(crate) fn remove_dir_if_exists(path: &Path) { + match fs::remove_dir_all(&path) { + Ok(()) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => {} + Err(err) => panic!("Failed to remove {path}: {err}", path = path.display()), + } +} + pub(crate) fn copy_dir_recursively(from: &Path, to: &Path) { for entry in fs::read_dir(from).unwrap() { let entry = entry.unwrap(); From 66f60e550e3e0e7e3672291e12c2201e03f1e90f Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Thu, 19 Jan 2023 08:55:05 -0800 Subject: [PATCH 229/500] Update wording of invalid_doc_attributes docs. --- compiler/rustc_lint_defs/src/builtin.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 6cdf50970836a..d83a403dfdc88 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -3462,9 +3462,15 @@ declare_lint! { /// /// ### Explanation /// - /// Previously, there were very like checks being performed on `#[doc(..)]` - /// unlike the other attributes. It'll now catch all the issues that it - /// silently ignored previously. + /// Previously, incorrect usage of the `#[doc(..)]` attribute was not + /// being validated. Usually these should be rejected as a hard error, + /// but this lint was introduced to avoid breaking any existing + /// crates which included them. + /// + /// This is a [future-incompatible] lint to transition this to a hard + /// error in the future. See [issue #82730] for more details. + /// + /// [issue #82730]: https://github.com/rust-lang/rust/issues/82730 pub INVALID_DOC_ATTRIBUTES, Warn, "detects invalid `#[doc(...)]` attributes", From e1f630f23de2cbce1870e4a226fa0cb8312f106c Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Mon, 16 Jan 2023 18:50:45 +0100 Subject: [PATCH 230/500] Add `OnceCell: !Sync` impl for diagnostics --- library/core/src/cell/once.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/library/core/src/cell/once.rs b/library/core/src/cell/once.rs index 7757068a4f2b9..f74e563f1b9c0 100644 --- a/library/core/src/cell/once.rs +++ b/library/core/src/cell/once.rs @@ -298,3 +298,7 @@ impl const From for OnceCell { OnceCell { inner: UnsafeCell::new(Some(value)) } } } + +// Just like for `Cell` this isn't needed, but results in nicer error messages. +#[unstable(feature = "once_cell", issue = "74465")] +impl !Sync for OnceCell {} From 6d0c91fda35f7a78ff688ea623d1d2ee9b16cad7 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Mon, 16 Jan 2023 18:51:31 +0100 Subject: [PATCH 231/500] Add `rustc_on_unimplemented` on `Sync` for cell types Suggest using a lock instead. --- library/core/src/marker.rs | 56 ++++++++++++++++++ .../issue-68112.drop_tracking.stderr | 3 + .../issue-68112.no_drop_tracking.stderr | 3 + tests/ui/generator/issue-68112.rs | 2 + tests/ui/generator/issue-68112.stderr | 12 ++-- tests/ui/generator/not-send-sync.stderr | 2 + .../print/generator-print-verbose-1.stderr | 2 + .../print/generator-print-verbose-2.stderr | 2 + tests/ui/issues/issue-7364.stderr | 1 + tests/ui/stdlib-unit-tests/not-sync.stderr | 2 + tests/ui/{ => sync}/mutexguard-sync.rs | 0 tests/ui/{ => sync}/mutexguard-sync.stderr | 1 + tests/ui/sync/suggest-cell.rs | 31 ++++++++++ tests/ui/sync/suggest-cell.stderr | 59 +++++++++++++++++++ tests/ui/sync/suggest-once-cell.rs | 12 ++++ tests/ui/sync/suggest-once-cell.stderr | 17 ++++++ tests/ui/sync/suggest-ref-cell.rs | 12 ++++ tests/ui/sync/suggest-ref-cell.stderr | 17 ++++++ 18 files changed, 229 insertions(+), 5 deletions(-) rename tests/ui/{ => sync}/mutexguard-sync.rs (100%) rename tests/ui/{ => sync}/mutexguard-sync.stderr (83%) create mode 100644 tests/ui/sync/suggest-cell.rs create mode 100644 tests/ui/sync/suggest-cell.stderr create mode 100644 tests/ui/sync/suggest-once-cell.rs create mode 100644 tests/ui/sync/suggest-once-cell.stderr create mode 100644 tests/ui/sync/suggest-ref-cell.rs create mode 100644 tests/ui/sync/suggest-ref-cell.stderr diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index 1326fc9ab096f..74055602ec2e6 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -469,6 +469,62 @@ pub macro Copy($item:item) { #[cfg_attr(not(test), rustc_diagnostic_item = "Sync")] #[lang = "sync"] #[rustc_on_unimplemented( + on( + _Self = "std::cell::OnceCell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::OnceLock` instead" + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU8` instead", + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU16` instead", + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU32` instead", + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU64` instead", + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicUsize` instead", + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI8` instead", + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI16` instead", + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead", + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI64` instead", + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicIsize` instead", + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicBool` instead", + ), + on( + _Self = "std::cell::Cell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock`", + ), + on( + _Self = "std::cell::RefCell", + note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead", + ), message = "`{Self}` cannot be shared between threads safely", label = "`{Self}` cannot be shared between threads safely" )] diff --git a/tests/ui/async-await/issue-68112.drop_tracking.stderr b/tests/ui/async-await/issue-68112.drop_tracking.stderr index f2802698fd5b6..bd648de30672d 100644 --- a/tests/ui/async-await/issue-68112.drop_tracking.stderr +++ b/tests/ui/async-await/issue-68112.drop_tracking.stderr @@ -5,6 +5,7 @@ LL | require_send(send_fut); | ^^^^^^^^ future created by async block is not `Send` | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead note: future is not `Send` as it awaits another future which is not `Send` --> $DIR/issue-68112.rs:34:17 | @@ -23,6 +24,7 @@ LL | require_send(send_fut); | ^^^^^^^^ future created by async block is not `Send` | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead note: future is not `Send` as it awaits another future which is not `Send` --> $DIR/issue-68112.rs:43:17 | @@ -43,6 +45,7 @@ LL | require_send(send_fut); | required by a bound introduced by this call | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead = note: required for `Arc>` to implement `Send` note: required because it's used within this `async fn` body --> $DIR/issue-68112.rs:50:31 diff --git a/tests/ui/async-await/issue-68112.no_drop_tracking.stderr b/tests/ui/async-await/issue-68112.no_drop_tracking.stderr index 38eb85b302fd5..35b7341f63a4d 100644 --- a/tests/ui/async-await/issue-68112.no_drop_tracking.stderr +++ b/tests/ui/async-await/issue-68112.no_drop_tracking.stderr @@ -5,6 +5,7 @@ LL | require_send(send_fut); | ^^^^^^^^ future created by async block is not `Send` | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead note: future is not `Send` as it awaits another future which is not `Send` --> $DIR/issue-68112.rs:34:17 | @@ -23,6 +24,7 @@ LL | require_send(send_fut); | ^^^^^^^^ future created by async block is not `Send` | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead note: future is not `Send` as it awaits another future which is not `Send` --> $DIR/issue-68112.rs:43:17 | @@ -43,6 +45,7 @@ LL | require_send(send_fut); | required by a bound introduced by this call | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead = note: required for `Arc>` to implement `Send` note: required because it's used within this `async fn` body --> $DIR/issue-68112.rs:50:31 diff --git a/tests/ui/generator/issue-68112.rs b/tests/ui/generator/issue-68112.rs index 21026f45cb823..9def544e3d25c 100644 --- a/tests/ui/generator/issue-68112.rs +++ b/tests/ui/generator/issue-68112.rs @@ -40,6 +40,7 @@ fn test1() { require_send(send_gen); //~^ ERROR generator cannot be sent between threads //~| NOTE not `Send` + //~| NOTE use `std::sync::RwLock` instead } pub fn make_gen2(t: T) -> impl Generator { @@ -66,6 +67,7 @@ fn test2() { //~| NOTE required for //~| NOTE required by a bound introduced by this call //~| NOTE captures the following types + //~| NOTE use `std::sync::RwLock` instead } fn main() {} diff --git a/tests/ui/generator/issue-68112.stderr b/tests/ui/generator/issue-68112.stderr index eb99d42c92068..b42bc93d01f66 100644 --- a/tests/ui/generator/issue-68112.stderr +++ b/tests/ui/generator/issue-68112.stderr @@ -5,6 +5,7 @@ LL | require_send(send_gen); | ^^^^^^^^ generator is not `Send` | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead note: generator is not `Send` as this value is used across a yield --> $DIR/issue-68112.rs:36:9 | @@ -23,7 +24,7 @@ LL | fn require_send(_: impl Send) {} | ^^^^ required by this bound in `require_send` error[E0277]: `RefCell` cannot be shared between threads safely - --> $DIR/issue-68112.rs:63:18 + --> $DIR/issue-68112.rs:64:18 | LL | require_send(send_gen); | ------------ ^^^^^^^^ `RefCell` cannot be shared between threads safely @@ -31,25 +32,26 @@ LL | require_send(send_gen); | required by a bound introduced by this call | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead = note: required for `Arc>` to implement `Send` note: required because it's used within this generator - --> $DIR/issue-68112.rs:48:5 + --> $DIR/issue-68112.rs:49:5 | LL | || { | ^^ note: required because it appears within the type `impl Generator>>` - --> $DIR/issue-68112.rs:45:30 + --> $DIR/issue-68112.rs:46:30 | LL | pub fn make_gen2(t: T) -> impl Generator { | ^^^^^^^^^^^^^^^^^^^^^^^^^^ note: required because it appears within the type `impl Generator>>` - --> $DIR/issue-68112.rs:53:34 + --> $DIR/issue-68112.rs:54:34 | LL | fn make_non_send_generator2() -> impl Generator>> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required because it captures the following types: `impl Generator>>`, `()` note: required because it's used within this generator - --> $DIR/issue-68112.rs:59:20 + --> $DIR/issue-68112.rs:60:20 | LL | let send_gen = || { | ^^ diff --git a/tests/ui/generator/not-send-sync.stderr b/tests/ui/generator/not-send-sync.stderr index a821c57b923a0..1711df729b8c0 100644 --- a/tests/ui/generator/not-send-sync.stderr +++ b/tests/ui/generator/not-send-sync.stderr @@ -12,6 +12,7 @@ LL | | }); | |_____^ `Cell` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead = note: required for `&Cell` to implement `Send` note: required because it's used within this generator --> $DIR/not-send-sync.rs:16:17 @@ -36,6 +37,7 @@ LL | | }); | |_____^ generator is not `Sync` | = help: within `[generator@$DIR/not-send-sync.rs:9:17: 9:19]`, the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead note: generator is not `Sync` as this value is used across a yield --> $DIR/not-send-sync.rs:12:9 | diff --git a/tests/ui/generator/print/generator-print-verbose-1.stderr b/tests/ui/generator/print/generator-print-verbose-1.stderr index ebf35be581c60..45d018b8ebad5 100644 --- a/tests/ui/generator/print/generator-print-verbose-1.stderr +++ b/tests/ui/generator/print/generator-print-verbose-1.stderr @@ -5,6 +5,7 @@ LL | require_send(send_gen); | ^^^^^^^^ generator is not `Send` | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead note: generator is not `Send` as this value is used across a yield --> $DIR/generator-print-verbose-1.rs:35:9 | @@ -29,6 +30,7 @@ LL | require_send(send_gen); | required by a bound introduced by this call | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead = note: required for `Arc>` to implement `Send` note: required because it's used within this generator --> $DIR/generator-print-verbose-1.rs:42:5 diff --git a/tests/ui/generator/print/generator-print-verbose-2.stderr b/tests/ui/generator/print/generator-print-verbose-2.stderr index 909e49c38b8d1..59112ce0a79e6 100644 --- a/tests/ui/generator/print/generator-print-verbose-2.stderr +++ b/tests/ui/generator/print/generator-print-verbose-2.stderr @@ -12,6 +12,7 @@ LL | | }); | |_____^ `Cell` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead = note: required for `&'_#4r Cell` to implement `Send` note: required because it's used within this generator --> $DIR/generator-print-verbose-2.rs:19:17 @@ -36,6 +37,7 @@ LL | | }); | |_____^ generator is not `Sync` | = help: within `[main::{closure#0} upvar_tys=() {Cell, ()}]`, the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead note: generator is not `Sync` as this value is used across a yield --> $DIR/generator-print-verbose-2.rs:15:9 | diff --git a/tests/ui/issues/issue-7364.stderr b/tests/ui/issues/issue-7364.stderr index 5dc8c2b607e61..aee73380f15e7 100644 --- a/tests/ui/issues/issue-7364.stderr +++ b/tests/ui/issues/issue-7364.stderr @@ -5,6 +5,7 @@ LL | static boxed: Box> = Box::new(RefCell::new(0)); | ^^^^^^^^^^^^^^^^^^^ `RefCell` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead = note: required for `Unique>` to implement `Sync` = note: required because it appears within the type `Box>` = note: shared static variables must have a type that implements `Sync` diff --git a/tests/ui/stdlib-unit-tests/not-sync.stderr b/tests/ui/stdlib-unit-tests/not-sync.stderr index 1ee358ba8368e..4e34e10e37789 100644 --- a/tests/ui/stdlib-unit-tests/not-sync.stderr +++ b/tests/ui/stdlib-unit-tests/not-sync.stderr @@ -5,6 +5,7 @@ LL | test::>(); | ^^^^^^^^^ `Cell` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead note: required by a bound in `test` --> $DIR/not-sync.rs:5:12 | @@ -18,6 +19,7 @@ LL | test::>(); | ^^^^^^^^^^^^ `RefCell` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead note: required by a bound in `test` --> $DIR/not-sync.rs:5:12 | diff --git a/tests/ui/mutexguard-sync.rs b/tests/ui/sync/mutexguard-sync.rs similarity index 100% rename from tests/ui/mutexguard-sync.rs rename to tests/ui/sync/mutexguard-sync.rs diff --git a/tests/ui/mutexguard-sync.stderr b/tests/ui/sync/mutexguard-sync.stderr similarity index 83% rename from tests/ui/mutexguard-sync.stderr rename to tests/ui/sync/mutexguard-sync.stderr index 3fbb2ddf183d3..4dc5571196c14 100644 --- a/tests/ui/mutexguard-sync.stderr +++ b/tests/ui/sync/mutexguard-sync.stderr @@ -7,6 +7,7 @@ LL | test_sync(guard); | required by a bound introduced by this call | = help: the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead = note: required for `MutexGuard<'_, Cell>` to implement `Sync` note: required by a bound in `test_sync` --> $DIR/mutexguard-sync.rs:5:17 diff --git a/tests/ui/sync/suggest-cell.rs b/tests/ui/sync/suggest-cell.rs new file mode 100644 index 0000000000000..3284eae7be181 --- /dev/null +++ b/tests/ui/sync/suggest-cell.rs @@ -0,0 +1,31 @@ +fn require_sync() {} +//~^ NOTE required by this bound in `require_sync` +//~| NOTE required by this bound in `require_sync` +//~| NOTE required by this bound in `require_sync` +//~| NOTE required by this bound in `require_sync` +//~| NOTE required by a bound in `require_sync` +//~| NOTE required by a bound in `require_sync` +//~| NOTE required by a bound in `require_sync` +//~| NOTE required by a bound in `require_sync` + +fn main() { + require_sync::>(); + //~^ ERROR `Cell<()>` cannot be shared between threads safely + //~| NOTE `Cell<()>` cannot be shared between threads safely + //~| NOTE if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` + + require_sync::>(); + //~^ ERROR `Cell` cannot be shared between threads safely + //~| NOTE `Cell` cannot be shared between threads safely + //~| NOTE if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU8` instead + + require_sync::>(); + //~^ ERROR `Cell` cannot be shared between threads safely + //~| NOTE `Cell` cannot be shared between threads safely + //~| NOTE if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead + + require_sync::>(); + //~^ ERROR `Cell` cannot be shared between threads safely + //~| NOTE `Cell` cannot be shared between threads safely + //~| NOTE if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicBool` instead +} diff --git a/tests/ui/sync/suggest-cell.stderr b/tests/ui/sync/suggest-cell.stderr new file mode 100644 index 0000000000000..c232c1ccd53dd --- /dev/null +++ b/tests/ui/sync/suggest-cell.stderr @@ -0,0 +1,59 @@ +error[E0277]: `Cell<()>` cannot be shared between threads safely + --> $DIR/suggest-cell.rs:12:20 + | +LL | require_sync::>(); + | ^^^^^^^^^^^^^^^^^^^ `Cell<()>` cannot be shared between threads safely + | + = help: the trait `Sync` is not implemented for `Cell<()>` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` +note: required by a bound in `require_sync` + --> $DIR/suggest-cell.rs:1:20 + | +LL | fn require_sync() {} + | ^^^^ required by this bound in `require_sync` + +error[E0277]: `Cell` cannot be shared between threads safely + --> $DIR/suggest-cell.rs:17:20 + | +LL | require_sync::>(); + | ^^^^^^^^^^^^^^^^^^^ `Cell` cannot be shared between threads safely + | + = help: the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU8` instead +note: required by a bound in `require_sync` + --> $DIR/suggest-cell.rs:1:20 + | +LL | fn require_sync() {} + | ^^^^ required by this bound in `require_sync` + +error[E0277]: `Cell` cannot be shared between threads safely + --> $DIR/suggest-cell.rs:22:20 + | +LL | require_sync::>(); + | ^^^^^^^^^^^^^^^^^^^^ `Cell` cannot be shared between threads safely + | + = help: the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead +note: required by a bound in `require_sync` + --> $DIR/suggest-cell.rs:1:20 + | +LL | fn require_sync() {} + | ^^^^ required by this bound in `require_sync` + +error[E0277]: `Cell` cannot be shared between threads safely + --> $DIR/suggest-cell.rs:27:20 + | +LL | require_sync::>(); + | ^^^^^^^^^^^^^^^^^^^^^ `Cell` cannot be shared between threads safely + | + = help: the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicBool` instead +note: required by a bound in `require_sync` + --> $DIR/suggest-cell.rs:1:20 + | +LL | fn require_sync() {} + | ^^^^ required by this bound in `require_sync` + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/sync/suggest-once-cell.rs b/tests/ui/sync/suggest-once-cell.rs new file mode 100644 index 0000000000000..82fca45b1a47f --- /dev/null +++ b/tests/ui/sync/suggest-once-cell.rs @@ -0,0 +1,12 @@ +#![feature(once_cell)] + +fn require_sync() {} +//~^ NOTE required by this bound in `require_sync` +//~| NOTE required by a bound in `require_sync` + +fn main() { + require_sync::>(); + //~^ ERROR `OnceCell<()>` cannot be shared between threads safely + //~| NOTE `OnceCell<()>` cannot be shared between threads safely + //~| NOTE use `std::sync::OnceLock` instead +} diff --git a/tests/ui/sync/suggest-once-cell.stderr b/tests/ui/sync/suggest-once-cell.stderr new file mode 100644 index 0000000000000..fadf05374d8ca --- /dev/null +++ b/tests/ui/sync/suggest-once-cell.stderr @@ -0,0 +1,17 @@ +error[E0277]: `OnceCell<()>` cannot be shared between threads safely + --> $DIR/suggest-once-cell.rs:8:20 + | +LL | require_sync::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^ `OnceCell<()>` cannot be shared between threads safely + | + = help: the trait `Sync` is not implemented for `OnceCell<()>` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::OnceLock` instead +note: required by a bound in `require_sync` + --> $DIR/suggest-once-cell.rs:3:20 + | +LL | fn require_sync() {} + | ^^^^ required by this bound in `require_sync` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/sync/suggest-ref-cell.rs b/tests/ui/sync/suggest-ref-cell.rs new file mode 100644 index 0000000000000..6b972ae09622e --- /dev/null +++ b/tests/ui/sync/suggest-ref-cell.rs @@ -0,0 +1,12 @@ +#![feature(once_cell)] + +fn require_sync() {} +//~^ NOTE required by this bound in `require_sync` +//~| NOTE required by a bound in `require_sync` + +fn main() { + require_sync::>(); + //~^ ERROR `RefCell<()>` cannot be shared between threads safely + //~| NOTE `RefCell<()>` cannot be shared between threads safely + //~| NOTE use `std::sync::RwLock` instead +} diff --git a/tests/ui/sync/suggest-ref-cell.stderr b/tests/ui/sync/suggest-ref-cell.stderr new file mode 100644 index 0000000000000..9e8b8fcb42ed0 --- /dev/null +++ b/tests/ui/sync/suggest-ref-cell.stderr @@ -0,0 +1,17 @@ +error[E0277]: `RefCell<()>` cannot be shared between threads safely + --> $DIR/suggest-ref-cell.rs:8:20 + | +LL | require_sync::>(); + | ^^^^^^^^^^^^^^^^^^^^^^ `RefCell<()>` cannot be shared between threads safely + | + = help: the trait `Sync` is not implemented for `RefCell<()>` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead +note: required by a bound in `require_sync` + --> $DIR/suggest-ref-cell.rs:3:20 + | +LL | fn require_sync() {} + | ^^^^ required by this bound in `require_sync` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. From e3a09eca6d810af2105b4ed3af17048b318d25c4 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Thu, 19 Jan 2023 21:57:56 +0100 Subject: [PATCH 232/500] Update version attribute for 1.67 lints --- clippy_lints/src/doc.rs | 2 +- clippy_lints/src/from_raw_with_void_ptr.rs | 2 +- clippy_lints/src/instant_subtraction.rs | 2 +- clippy_lints/src/let_underscore.rs | 2 +- clippy_lints/src/manual_is_ascii_check.rs | 2 +- clippy_lints/src/methods/mod.rs | 4 ++-- clippy_lints/src/suspicious_xor_used_as_pow.rs | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/clippy_lints/src/doc.rs b/clippy_lints/src/doc.rs index cdc23a4d22739..f7a3d6d53f714 100644 --- a/clippy_lints/src/doc.rs +++ b/clippy_lints/src/doc.rs @@ -251,7 +251,7 @@ declare_clippy_lint! { /// unimplemented!(); /// } /// ``` - #[clippy::version = "1.66.0"] + #[clippy::version = "1.67.0"] pub UNNECESSARY_SAFETY_DOC, restriction, "`pub fn` or `pub trait` with `# Safety` docs" diff --git a/clippy_lints/src/from_raw_with_void_ptr.rs b/clippy_lints/src/from_raw_with_void_ptr.rs index 00f5ba56496ec..096508dc4f11e 100644 --- a/clippy_lints/src/from_raw_with_void_ptr.rs +++ b/clippy_lints/src/from_raw_with_void_ptr.rs @@ -31,7 +31,7 @@ declare_clippy_lint! { /// let _ = unsafe { Box::from_raw(ptr as *mut usize) }; /// ``` /// - #[clippy::version = "1.66.0"] + #[clippy::version = "1.67.0"] pub FROM_RAW_WITH_VOID_PTR, suspicious, "creating a `Box` from a void raw pointer" diff --git a/clippy_lints/src/instant_subtraction.rs b/clippy_lints/src/instant_subtraction.rs index 9f6e89405713c..668110c7cc081 100644 --- a/clippy_lints/src/instant_subtraction.rs +++ b/clippy_lints/src/instant_subtraction.rs @@ -59,7 +59,7 @@ declare_clippy_lint! { /// /// [`Duration`]: std::time::Duration /// [`Instant::now()`]: std::time::Instant::now; - #[clippy::version = "1.65.0"] + #[clippy::version = "1.67.0"] pub UNCHECKED_DURATION_SUBTRACTION, pedantic, "finds unchecked subtraction of a 'Duration' from an 'Instant'" diff --git a/clippy_lints/src/let_underscore.rs b/clippy_lints/src/let_underscore.rs index 61f87b91400d7..f8e3595098088 100644 --- a/clippy_lints/src/let_underscore.rs +++ b/clippy_lints/src/let_underscore.rs @@ -84,7 +84,7 @@ declare_clippy_lint! { /// let _ = foo().await; /// # } /// ``` - #[clippy::version = "1.66"] + #[clippy::version = "1.67.0"] pub LET_UNDERSCORE_FUTURE, suspicious, "non-binding `let` on a future" diff --git a/clippy_lints/src/manual_is_ascii_check.rs b/clippy_lints/src/manual_is_ascii_check.rs index d9ef7dffa020d..2fd32c009eaa7 100644 --- a/clippy_lints/src/manual_is_ascii_check.rs +++ b/clippy_lints/src/manual_is_ascii_check.rs @@ -43,7 +43,7 @@ declare_clippy_lint! { /// 'A'.is_ascii_uppercase(); /// } /// ``` - #[clippy::version = "1.66.0"] + #[clippy::version = "1.67.0"] pub MANUAL_IS_ASCII_CHECK, style, "use dedicated method to check ascii range" diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 77be61b479340..42377a3d138c2 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -3102,7 +3102,7 @@ declare_clippy_lint! { /// Ok(()) /// } /// ``` - #[clippy::version = "1.66.0"] + #[clippy::version = "1.67.0"] pub SEEK_FROM_CURRENT, complexity, "use dedicated method for seek from current position" @@ -3133,7 +3133,7 @@ declare_clippy_lint! { /// t.rewind(); /// } /// ``` - #[clippy::version = "1.66.0"] + #[clippy::version = "1.67.0"] pub SEEK_TO_START_INSTEAD_OF_REWIND, complexity, "jumping to the start of stream using `seek` method" diff --git a/clippy_lints/src/suspicious_xor_used_as_pow.rs b/clippy_lints/src/suspicious_xor_used_as_pow.rs index 301aa5798bf55..c181919b16470 100644 --- a/clippy_lints/src/suspicious_xor_used_as_pow.rs +++ b/clippy_lints/src/suspicious_xor_used_as_pow.rs @@ -18,7 +18,7 @@ declare_clippy_lint! { /// ```rust /// let x = 3_i32.pow(4); /// ``` - #[clippy::version = "1.66.0"] + #[clippy::version = "1.67.0"] pub SUSPICIOUS_XOR_USED_AS_POW, restriction, "XOR (`^`) operator possibly used as exponentiation operator" From d3cfe97a8a975511a631083d64aa6ae3ddf7470a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Mi=C4=85sko?= Date: Thu, 19 Jan 2023 00:00:00 +0000 Subject: [PATCH 233/500] Custom MIR: Support binary and unary operations --- .../src/build/custom/parse/instruction.rs | 6 ++++ .../custom/operators.f.built.after.mir | 26 +++++++++++++++++ tests/mir-opt/building/custom/operators.rs | 28 +++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 tests/mir-opt/building/custom/operators.f.built.after.mir create mode 100644 tests/mir-opt/building/custom/operators.rs diff --git a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs index dca4906c07de5..2560eaee43372 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs +++ b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs @@ -141,6 +141,12 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { ExprKind::AddressOf { mutability, arg } => Ok( Rvalue::AddressOf(*mutability, self.parse_place(*arg)?) ), + ExprKind::Binary { op, lhs, rhs } => Ok( + Rvalue::BinaryOp(*op, Box::new((self.parse_operand(*lhs)?, self.parse_operand(*rhs)?))) + ), + ExprKind::Unary { op, arg } => Ok( + Rvalue::UnaryOp(*op, self.parse_operand(*arg)?) + ), _ => self.parse_operand(expr_id).map(Rvalue::Use), ) } diff --git a/tests/mir-opt/building/custom/operators.f.built.after.mir b/tests/mir-opt/building/custom/operators.f.built.after.mir new file mode 100644 index 0000000000000..a0c5f1b40dbb7 --- /dev/null +++ b/tests/mir-opt/building/custom/operators.f.built.after.mir @@ -0,0 +1,26 @@ +// MIR for `f` after built + +fn f(_1: i32, _2: bool) -> i32 { + let mut _0: i32; // return place in scope 0 at $DIR/operators.rs:+0:30: +0:33 + + bb0: { + _1 = Neg(_1); // scope 0 at $DIR/operators.rs:+2:9: +2:15 + _2 = Not(_2); // scope 0 at $DIR/operators.rs:+3:9: +3:15 + _1 = Add(_1, _1); // scope 0 at $DIR/operators.rs:+4:9: +4:18 + _1 = Sub(_1, _1); // scope 0 at $DIR/operators.rs:+5:9: +5:18 + _1 = Mul(_1, _1); // scope 0 at $DIR/operators.rs:+6:9: +6:18 + _1 = Div(_1, _1); // scope 0 at $DIR/operators.rs:+7:9: +7:18 + _1 = Rem(_1, _1); // scope 0 at $DIR/operators.rs:+8:9: +8:18 + _1 = BitXor(_1, _1); // scope 0 at $DIR/operators.rs:+9:9: +9:18 + _1 = BitAnd(_1, _1); // scope 0 at $DIR/operators.rs:+10:9: +10:18 + _1 = Shl(_1, _1); // scope 0 at $DIR/operators.rs:+11:9: +11:19 + _1 = Shr(_1, _1); // scope 0 at $DIR/operators.rs:+12:9: +12:19 + _2 = Eq(_1, _1); // scope 0 at $DIR/operators.rs:+13:9: +13:19 + _2 = Lt(_1, _1); // scope 0 at $DIR/operators.rs:+14:9: +14:18 + _2 = Le(_1, _1); // scope 0 at $DIR/operators.rs:+15:9: +15:19 + _2 = Ge(_1, _1); // scope 0 at $DIR/operators.rs:+16:9: +16:19 + _2 = Gt(_1, _1); // scope 0 at $DIR/operators.rs:+17:9: +17:18 + _0 = _1; // scope 0 at $DIR/operators.rs:+18:9: +18:16 + return; // scope 0 at $DIR/operators.rs:+19:9: +19:17 + } +} diff --git a/tests/mir-opt/building/custom/operators.rs b/tests/mir-opt/building/custom/operators.rs new file mode 100644 index 0000000000000..51f80c66392a1 --- /dev/null +++ b/tests/mir-opt/building/custom/operators.rs @@ -0,0 +1,28 @@ +// compile-flags: --crate-type=lib +#![feature(custom_mir, core_intrinsics, inline_const)] +use std::intrinsics::mir::*; + +// EMIT_MIR operators.f.built.after.mir +#[custom_mir(dialect = "built")] +pub fn f(a: i32, b: bool) -> i32 { + mir!({ + a = -a; + b = !b; + a = a + a; + a = a - a; + a = a * a; + a = a / a; + a = a % a; + a = a ^ a; + a = a & a; + a = a << a; + a = a >> a; + b = a == a; + b = a < a; + b = a <= a; + b = a >= a; + b = a > a; + RET = a; + Return() + }) +} From f64efd4d318f92cb6b7d0836826fcfe66d920727 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Thu, 19 Jan 2023 21:52:57 +0100 Subject: [PATCH 234/500] Changelog for Rust 1.67 :lady_beetle: --- CHANGELOG.md | 198 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 196 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 84f4654f34e47..073691ad61ce1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,11 +6,204 @@ document. ## Unreleased / Beta / In Rust Nightly -[4f142aa1...master](https://github.com/rust-lang/rust-clippy/compare/4f142aa1...master) +[d822110d...master](https://github.com/rust-lang/rust-clippy/compare/d822110d...master) + +## Rust 1.67 + +Current stable, released 2023-01-26 + +[4f142aa1...d822110d](https://github.com/rust-lang/rust-clippy/compare/4f142aa1...d822110d) + +### New Lints + +* [`seek_from_current`] + [#9681](https://github.com/rust-lang/rust-clippy/pull/9681) +* [`from_raw_with_void_ptr`] + [#9690](https://github.com/rust-lang/rust-clippy/pull/9690) +* [`misnamed_getters`] + [#9770](https://github.com/rust-lang/rust-clippy/pull/9770) +* [`seek_to_start_instead_of_rewind`] + [#9667](https://github.com/rust-lang/rust-clippy/pull/9667) +* [`suspicious_xor_used_as_pow`] + [#9506](https://github.com/rust-lang/rust-clippy/pull/9506) +* [`unnecessary_safety_doc`] + [#9822](https://github.com/rust-lang/rust-clippy/pull/9822) +* [`unchecked_duration_subtraction`] + [#9570](https://github.com/rust-lang/rust-clippy/pull/9570) +* [`manual_is_ascii_check`] + [#9765](https://github.com/rust-lang/rust-clippy/pull/9765) +* [`unnecessary_safety_comment`] + [#9851](https://github.com/rust-lang/rust-clippy/pull/9851) +* [`let_underscore_future`] + [#9760](https://github.com/rust-lang/rust-clippy/pull/9760) +* [`manual_let_else`] + [#8437](https://github.com/rust-lang/rust-clippy/pull/8437) + +### Moves and Deprecations + +* Moved [`uninlined_format_args`] to `style` (Now warn-by-default) + [#9865](https://github.com/rust-lang/rust-clippy/pull/9865) +* Moved [`needless_collect`] to `nursery` (Now allow-by-default) + [#9705](https://github.com/rust-lang/rust-clippy/pull/9705) +* Moved [`or_fun_call`] to `nursery` (Now allow-by-default) + [#9829](https://github.com/rust-lang/rust-clippy/pull/9829) +* Uplifted [`let_underscore_lock`] into rustc + [#9697](https://github.com/rust-lang/rust-clippy/pull/9697) +* Uplifted [`let_underscore_drop`] into rustc + [#9697](https://github.com/rust-lang/rust-clippy/pull/9697) +* Moved [`bool_to_int_with_if`] to `pedantic` (Now allow-by-default) + [#9830](https://github.com/rust-lang/rust-clippy/pull/9830) +* [`manual_swap`]: No longer lints in const context + [#9871](https://github.com/rust-lang/rust-clippy/pull/9871) +* Move `index_refutable_slice` to `pedantic` (Now warn-by-default) + [#9975](https://github.com/rust-lang/rust-clippy/pull/9975) +* Moved [`manual_clamp`] to `nursery` (Now allow-by-default) + [#10101](https://github.com/rust-lang/rust-clippy/pull/10101) + +### Enhancements + +* The scope of `#![clippy::msrv]` is now tracked correctly + [#9924](https://github.com/rust-lang/rust-clippy/pull/9924) +* `#[clippy::msrv]` can now be used as an outer attribute + [#9860](https://github.com/rust-lang/rust-clippy/pull/9860) +* Clippy will now avoid Cargo's cache, if `Cargo.toml` or `clippy.toml` have changed + [#9707](https://github.com/rust-lang/rust-clippy/pull/9707) +* [`uninlined_format_args`]: Added a new config `allow-mixed-uninlined-format-args` to allow the + lint, if only some arguments can be inlined + [#9865](https://github.com/rust-lang/rust-clippy/pull/9865) +* [`needless_lifetimes`]: Now provides suggests for individual lifetimes + [#9743](https://github.com/rust-lang/rust-clippy/pull/9743) +* [`needless_collect`]: Now detects needless `is_empty` and `contains` calls + [#8744](https://github.com/rust-lang/rust-clippy/pull/8744) +* [`blanket_clippy_restriction_lints`]: Now lints, if `clippy::restriction` is enabled via the + command line arguments + [#9755](https://github.com/rust-lang/rust-clippy/pull/9755) +* [`mutable_key_type`]: Now has the `ignore-interior-mutability` configuration, to add types which + should be ignored by the lint + [#9692](https://github.com/rust-lang/rust-clippy/pull/9692) +* [`uninlined_format_args`]: Now works for multiline `format!` expressions + [#9945](https://github.com/rust-lang/rust-clippy/pull/9945) +* [`cognitive_complexity`]: Now works for async functions + [#9828](https://github.com/rust-lang/rust-clippy/pull/9828) + [#9836](https://github.com/rust-lang/rust-clippy/pull/9836) +* [`vec_box`]: Now avoids an off-by-one error when using the `vec-box-size-threshold` configuration + [#9848](https://github.com/rust-lang/rust-clippy/pull/9848) +* [`never_loop`]: Now correctly handles breaks in nested labeled blocks + [#9858](https://github.com/rust-lang/rust-clippy/pull/9858) + [#9837](https://github.com/rust-lang/rust-clippy/pull/9837) +* [`disallowed_methods`], [`disallowed_types`], [`disallowed_macros`]: Now correctly resolve + paths, if a crate is used multiple times with different versions + [#9800](https://github.com/rust-lang/rust-clippy/pull/9800) +* [`disallowed_methods`]: Can now be used for local methods + [#9800](https://github.com/rust-lang/rust-clippy/pull/9800) +* [`print_stdout`], [`print_stderr`]: Can now be enabled in test with the `allow-print-in-tests` + config value + [#9797](https://github.com/rust-lang/rust-clippy/pull/9797) +* [`from_raw_with_void_ptr`]: Now works for `Rc`, `Arc`, `alloc::rc::Weak` and + `alloc::sync::Weak` types. + [#9700](https://github.com/rust-lang/rust-clippy/pull/9700) +* [`needless_borrowed_reference`]: Now works for struct and tuple patterns with wildcards + [#9855](https://github.com/rust-lang/rust-clippy/pull/9855) +* [`or_fun_call`]: Now supports `map_or` methods + [#9689](https://github.com/rust-lang/rust-clippy/pull/9689) +* [`unwrap_used`], [`expect_used`]: No longer lints in test code + [#9686](https://github.com/rust-lang/rust-clippy/pull/9686) +* [`fn_params_excessive_bools`]: Is now emitted with the lint level at the linted function + [#9698](https://github.com/rust-lang/rust-clippy/pull/9698) + +### False Positive Fixes + +* [`new_ret_no_self`]: No longer lints when `impl Trait` is returned + [#9733](https://github.com/rust-lang/rust-clippy/pull/9733) +* [`unnecessary_lazy_evaluations`]: No longer lints, if the type has a significant drop + [#9750](https://github.com/rust-lang/rust-clippy/pull/9750) +* [`option_if_let_else`]: No longer lints, if any arm has guard + [#9747](https://github.com/rust-lang/rust-clippy/pull/9747) +* [`explicit_auto_deref`]: No longer lints, if the target type is a projection with generic + arguments + [#9813](https://github.com/rust-lang/rust-clippy/pull/9813) +* [`unnecessary_to_owned`]: No longer lints, if the suggestion effects types + [#9796](https://github.com/rust-lang/rust-clippy/pull/9796) +* [`needless_borrow`]: No longer lints, if the suggestion is affected by `Deref` + [#9674](https://github.com/rust-lang/rust-clippy/pull/9674) +* [`unused_unit`]: No longer lints, if lifetimes are bound to the return type + [#9849](https://github.com/rust-lang/rust-clippy/pull/9849) +* [`mut_mut`]: No longer lints cases with unsized mutable references + [#9835](https://github.com/rust-lang/rust-clippy/pull/9835) +* [`bool_to_int_with_if`]: No longer lints in const context + [#9738](https://github.com/rust-lang/rust-clippy/pull/9738) +* [`use_self`]: No longer lints in macros + [#9704](https://github.com/rust-lang/rust-clippy/pull/9704) +* [`unnecessary_operation`]: No longer lints, if multiple macros are involved + [#9981](https://github.com/rust-lang/rust-clippy/pull/9981) +* [`allow_attributes_without_reason`]: No longer lints inside external macros + [#9630](https://github.com/rust-lang/rust-clippy/pull/9630) +* [`question_mark`]: No longer lints for `if let Err()` with an `else` branch + [#9722](https://github.com/rust-lang/rust-clippy/pull/9722) +* [`unnecessary_cast`]: No longer lints if the identifier and cast originate from different macros + [#9980](https://github.com/rust-lang/rust-clippy/pull/9980) +* [`arithmetic_side_effects`]: Now detects operations with associated constants + [#9592](https://github.com/rust-lang/rust-clippy/pull/9592) +* [`explicit_auto_deref`]: No longer lints, if the initial value is not a reference or reference + receiver + [#9997](https://github.com/rust-lang/rust-clippy/pull/9997) +* [`module_name_repetitions`], [`single_component_path_imports`]: Now handle `#[allow]` + attributes correctly + [#9879](https://github.com/rust-lang/rust-clippy/pull/9879) +* [`bool_to_int_with_if`]: No longer lints `if let` statements + [#9714](https://github.com/rust-lang/rust-clippy/pull/9714) +* [`needless_borrow`]: No longer lints, `if`-`else`-statements that require the borrow + [#9791](https://github.com/rust-lang/rust-clippy/pull/9791) +* [`needless_borrow`]: No longer lints borrows, if moves were illegal + [#9711](https://github.com/rust-lang/rust-clippy/pull/9711) + +### Suggestion Fixes/Improvements + +* [`missing_safety_doc`], [`missing_errors_doc`], [`missing_panics_doc`]: No longer show the + entire item in the lint emission. + [#9772](https://github.com/rust-lang/rust-clippy/pull/9772) +* [`needless_lifetimes`]: Only suggests `'_` when it's applicable + [#9743](https://github.com/rust-lang/rust-clippy/pull/9743) +* [`use_self`]: Now suggests full paths correctly + [#9726](https://github.com/rust-lang/rust-clippy/pull/9726) +* [`redundant_closure_call`]: Now correctly deals with macros during suggestion creation + [#9987](https://github.com/rust-lang/rust-clippy/pull/9987) +* [`unnecessary_cast`]: Suggestions now correctly deal with references + [#9996](https://github.com/rust-lang/rust-clippy/pull/9996) +* [`unnecessary_join`]: Suggestions now correctly use [turbofish] operators + [#9779](https://github.com/rust-lang/rust-clippy/pull/9779) +* [`equatable_if_let`]: Can now suggest `matches!` replacements + [#9368](https://github.com/rust-lang/rust-clippy/pull/9368) +* [`string_extend_chars`]: Suggestions now correctly work for `str` slices + [#9741](https://github.com/rust-lang/rust-clippy/pull/9741) +* [`redundant_closure_for_method_calls`]: Suggestions now include angle brackets and generic + arguments if needed + [#9745](https://github.com/rust-lang/rust-clippy/pull/9745) +* [`manual_let_else`]: Suggestions no longer expand macro calls + [#9943](https://github.com/rust-lang/rust-clippy/pull/9943) +* [`infallible_destructuring_match`]: Suggestions now preserve references + [#9850](https://github.com/rust-lang/rust-clippy/pull/9850) +* [`result_large_err`]: The error now shows the largest enum variant + [#9662](https://github.com/rust-lang/rust-clippy/pull/9662) +* [`needless_return`]: Suggestions are now formatted better + [#9967](https://github.com/rust-lang/rust-clippy/pull/9967) +* [`unused_rounding`]: The suggestion now preserves the original float literal notation + [#9870](https://github.com/rust-lang/rust-clippy/pull/9870) + +[turbofish]: https://turbo.fish/::%3CClippy%3E + +### ICE Fixes + +* [`result_large_err`]: Fixed ICE for empty enums + [#10007](https://github.com/rust-lang/rust-clippy/pull/10007) +* [`redundant_allocation`]: Fixed ICE for types with bounded variables + [#9773](https://github.com/rust-lang/rust-clippy/pull/9773) +* [`unused_rounding`]: Fixed ICE, if `_` was used as a separator + [#10001](https://github.com/rust-lang/rust-clippy/pull/10001) ## Rust 1.66 -Current stable, released 2022-12-15 +Released 2022-12-15 [b52fb523...4f142aa1](https://github.com/rust-lang/rust-clippy/compare/b52fb523...4f142aa1) @@ -166,6 +359,7 @@ Current stable, released 2022-12-15 * [`unnecessary_to_owned`]: Avoid ICEs in favor of false negatives if information is missing [#9505](https://github.com/rust-lang/rust-clippy/pull/9505) + [#10027](https://github.com/rust-lang/rust-clippy/pull/10027) * [`manual_range_contains`]: No longer ICEs on values behind references [#9627](https://github.com/rust-lang/rust-clippy/pull/9627) * [`needless_pass_by_value`]: No longer ICEs on unsized `dyn Fn` arguments From 096f4547740ba0c945602ad6006f65bdd20f3418 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 20 Jan 2023 03:20:17 +0000 Subject: [PATCH 235/500] Filter predicates first for fast-path type flags --- .../src/traits/select/candidate_assembly.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 2733d9643fd77..87d574ff107b2 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -174,8 +174,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .param_env .caller_bounds() .iter() - .filter_map(|p| p.to_opt_poly_trait_pred()) - .filter(|p| !p.references_error()); + .filter(|p| !p.references_error()) + .filter_map(|p| p.to_opt_poly_trait_pred()); // Micro-optimization: filter out predicates relating to different traits. let matching_bounds = From 412798831792b4a67bea30bf53edd8a01f0c6bbe Mon Sep 17 00:00:00 2001 From: est31 Date: Fri, 20 Jan 2023 08:07:45 +0100 Subject: [PATCH 236/500] ThinBox: Add intra-doc-links for Metadata --- library/alloc/src/boxed/thin.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/library/alloc/src/boxed/thin.rs b/library/alloc/src/boxed/thin.rs index c1a82e452f6c3..ad48315fd70cc 100644 --- a/library/alloc/src/boxed/thin.rs +++ b/library/alloc/src/boxed/thin.rs @@ -48,7 +48,7 @@ unsafe impl Sync for ThinBox {} #[unstable(feature = "thin_box", issue = "92791")] impl ThinBox { - /// Moves a type to the heap with its `Metadata` stored in the heap allocation instead of on + /// Moves a type to the heap with its [`Metadata`] stored in the heap allocation instead of on /// the stack. /// /// # Examples @@ -59,6 +59,8 @@ impl ThinBox { /// /// let five = ThinBox::new(5); /// ``` + /// + /// [`Metadata`]: core::ptr::Pointee::Metadata #[cfg(not(no_global_oom_handling))] pub fn new(value: T) -> Self { let meta = ptr::metadata(&value); @@ -69,7 +71,7 @@ impl ThinBox { #[unstable(feature = "thin_box", issue = "92791")] impl ThinBox { - /// Moves a type to the heap with its `Metadata` stored in the heap allocation instead of on + /// Moves a type to the heap with its [`Metadata`] stored in the heap allocation instead of on /// the stack. /// /// # Examples @@ -80,6 +82,8 @@ impl ThinBox { /// /// let thin_slice = ThinBox::<[i32]>::new_unsize([1, 2, 3, 4]); /// ``` + /// + /// [`Metadata`]: core::ptr::Pointee::Metadata #[cfg(not(no_global_oom_handling))] pub fn new_unsize(value: T) -> Self where From a7ae84bc84fbe35d3f07c4fb5c325e130b0b9d19 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Fri, 20 Jan 2023 09:21:41 +0100 Subject: [PATCH 237/500] Address PR feedback and change text for early merge --- CHANGELOG.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 073691ad61ce1..d3cb880df57b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,13 +4,13 @@ All notable changes to this project will be documented in this file. See [Changelog Update](book/src/development/infrastructure/changelog_update.md) if you want to update this document. -## Unreleased / Beta / In Rust Nightly +## Unreleased / In Rust Nightly [d822110d...master](https://github.com/rust-lang/rust-clippy/compare/d822110d...master) ## Rust 1.67 -Current stable, released 2023-01-26 +Current beta, released 2023-01-26 [4f142aa1...d822110d](https://github.com/rust-lang/rust-clippy/compare/4f142aa1...d822110d) @@ -53,8 +53,6 @@ Current stable, released 2023-01-26 [#9697](https://github.com/rust-lang/rust-clippy/pull/9697) * Moved [`bool_to_int_with_if`] to `pedantic` (Now allow-by-default) [#9830](https://github.com/rust-lang/rust-clippy/pull/9830) -* [`manual_swap`]: No longer lints in const context - [#9871](https://github.com/rust-lang/rust-clippy/pull/9871) * Move `index_refutable_slice` to `pedantic` (Now warn-by-default) [#9975](https://github.com/rust-lang/rust-clippy/pull/9975) * Moved [`manual_clamp`] to `nursery` (Now allow-by-default) @@ -156,6 +154,8 @@ Current stable, released 2023-01-26 [#9791](https://github.com/rust-lang/rust-clippy/pull/9791) * [`needless_borrow`]: No longer lints borrows, if moves were illegal [#9711](https://github.com/rust-lang/rust-clippy/pull/9711) +* [`manual_swap`]: No longer lints in const context + [#9871](https://github.com/rust-lang/rust-clippy/pull/9871) ### Suggestion Fixes/Improvements @@ -203,7 +203,7 @@ Current stable, released 2023-01-26 ## Rust 1.66 -Released 2022-12-15 +Current stable, released 2022-12-15 [b52fb523...4f142aa1](https://github.com/rust-lang/rust-clippy/compare/b52fb523...4f142aa1) From 081c6178fe9e8b1a0dd311c6648263dedff35b83 Mon Sep 17 00:00:00 2001 From: chansuke Date: Fri, 20 Jan 2023 20:25:31 +0900 Subject: [PATCH 238/500] Fix spelling inconsistence of `mdBook` --- book/src/development/infrastructure/book.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/book/src/development/infrastructure/book.md b/book/src/development/infrastructure/book.md index a48742191850b..dbd624ecd7382 100644 --- a/book/src/development/infrastructure/book.md +++ b/book/src/development/infrastructure/book.md @@ -3,15 +3,15 @@ This document explains how to make additions and changes to the Clippy book, the guide to Clippy that you're reading right now. The Clippy book is formatted with [Markdown](https://www.markdownguide.org) and generated by -[mdbook](https://github.com/rust-lang/mdBook). +[mdBook](https://github.com/rust-lang/mdBook). -- [Get mdbook](#get-mdbook) +- [Get mdBook](#get-mdbook) - [Make changes](#make-changes) -## Get mdbook +## Get mdBook While not strictly necessary since the book source is simply Markdown text -files, having mdbook locally will allow you to build, test and serve the book +files, having mdBook locally will allow you to build, test and serve the book locally to view changes before you commit them to the repository. You likely already have `cargo` installed, so the easiest option is to simply: @@ -19,7 +19,7 @@ already have `cargo` installed, so the easiest option is to simply: cargo install mdbook ``` -See the mdbook [installation](https://github.com/rust-lang/mdBook#installation) +See the mdBook [installation](https://github.com/rust-lang/mdBook#installation) instructions for other options. ## Make changes @@ -27,7 +27,7 @@ instructions for other options. The book's [src](https://github.com/rust-lang/rust-clippy/tree/master/book/src) directory contains all of the markdown files used to generate the book. If you -want to see your changes in real time, you can use the mdbook `serve` command to +want to see your changes in real time, you can use the mdBook `serve` command to run a web server locally that will automatically update changes as they are made. From the top level of your `rust-clippy` directory: @@ -38,5 +38,5 @@ mdbook serve book --open Then navigate to `http://localhost:3000` to see the generated book. While the server is running, changes you make will automatically be updated. -For more information, see the mdbook +For more information, see the mdBook [guide](https://rust-lang.github.io/mdBook/). From 7d14e606bef1732c1f42f8598b0ca9d435cfdcaf Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 20 Jan 2023 12:40:54 +0100 Subject: [PATCH 239/500] Rustup to rustc 1.68.0-nightly (4c83bd03a 2023-01-19) --- build_sysroot/Cargo.lock | 12 ++++++------ .../0022-sysroot-Disable-not-compiling-tests.patch | 5 +++-- rust-toolchain | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/build_sysroot/Cargo.lock b/build_sysroot/Cargo.lock index bba3210536ef7..24f15fc8521fe 100644 --- a/build_sysroot/Cargo.lock +++ b/build_sysroot/Cargo.lock @@ -34,9 +34,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.77" +version = "1.0.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4" +checksum = "a20104e2335ce8a659d6dd92a51a767a0c062599c73b343fd152cb401e828c3d" [[package]] name = "cfg-if" @@ -50,9 +50,9 @@ dependencies = [ [[package]] name = "compiler_builtins" -version = "0.1.85" +version = "0.1.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13e81c6cd7ab79f51a0c927d22858d61ad12bd0b3865f0b13ece02a4486aeabb" +checksum = "5dae98c88e576098d7ab13ebcb40cc43e5114b2beafe61a87cda9200649ff205" dependencies = [ "rustc-std-workspace-core", ] @@ -129,9 +129,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.138" +version = "0.2.139" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8" +checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79" dependencies = [ "rustc-std-workspace-core", ] diff --git a/patches/0022-sysroot-Disable-not-compiling-tests.patch b/patches/0022-sysroot-Disable-not-compiling-tests.patch index 8d9ee3f25c49d..865aa833a5eef 100644 --- a/patches/0022-sysroot-Disable-not-compiling-tests.patch +++ b/patches/0022-sysroot-Disable-not-compiling-tests.patch @@ -18,7 +18,7 @@ new file mode 100644 index 0000000..46fd999 --- /dev/null +++ b/library/core/tests/Cargo.toml -@@ -0,0 +1,11 @@ +@@ -0,0 +1,12 @@ +[package] +name = "core" +version = "0.0.0" @@ -29,6 +29,7 @@ index 0000000..46fd999 +path = "lib.rs" + +[dependencies] -+rand = "0.7" ++rand = { version = "0.8.5", default-features = false } ++rand_xorshift = { version = "0.3.0", default-features = false } -- 2.21.0 (Apple Git-122) diff --git a/rust-toolchain b/rust-toolchain index d8f28dbcc15c8..77345b9a17c6e 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-12-13" +channel = "nightly-2023-01-20" components = ["rust-src", "rustc-dev", "llvm-tools-preview"] From 92b4c76652bb79dd767a1f117ecbd88b85dcd807 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 20 Jan 2023 12:41:27 +0100 Subject: [PATCH 240/500] Update rustup.sh for the moved dir of the sysroot source --- scripts/rustup.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/rustup.sh b/scripts/rustup.sh index 6111c20544463..34e3981b5381f 100755 --- a/scripts/rustup.sh +++ b/scripts/rustup.sh @@ -18,9 +18,9 @@ case $1 in ./clean_all.sh - (cd build_sysroot && cargo update) - ./y.rs prepare + + (cd download/sysroot && cargo update && cargo fetch && cp Cargo.lock ../../build_sysroot/) ;; "commit") git add rust-toolchain build_sysroot/Cargo.lock From fb6d048c4d3f266d7e6b0664dd1365acb34e36e3 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 20 Jan 2023 12:49:27 +0100 Subject: [PATCH 241/500] Update patch --- scripts/setup_rust_fork.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/setup_rust_fork.sh b/scripts/setup_rust_fork.sh index ce0d7e9fe07da..a08e80dd19abc 100644 --- a/scripts/setup_rust_fork.sh +++ b/scripts/setup_rust_fork.sh @@ -25,8 +25,8 @@ index d95b5b7f17f..00b6f0e3635 100644 +compiler_builtins = { version = "0.1.66", features = ['rustc-dep-of-std', 'no-asm'] } [dev-dependencies] - rand = "0.7" - rand_xorshift = "0.2" + rand = { version = "0.8.5", default-features = false, features = ["alloc"] } + rand_xorshift = "0.3.0" EOF cat > config.toml < Date: Fri, 20 Jan 2023 13:08:45 +0100 Subject: [PATCH 242/500] Fix rustc test suite --- scripts/test_rustc_tests.sh | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/scripts/test_rustc_tests.sh b/scripts/test_rustc_tests.sh index 81e287f1ddebf..07c9ae6ee9ff2 100755 --- a/scripts/test_rustc_tests.sh +++ b/scripts/test_rustc_tests.sh @@ -78,6 +78,20 @@ rm tests/ui/mir/mir_raw_fat_ptr.rs # same rm tests/ui/consts/issue-33537.rs # same rm tests/ui/layout/valid_range_oob.rs # different ICE message +rm tests/ui/consts/issue-miri-1910.rs # different error message +rm tests/ui/consts/offset_ub.rs # same +rm tests/ui/intrinsics/panic-uninitialized-zeroed.rs # same +rm tests/ui/lint/lint-const-item-mutation.rs # same +rm tests/ui/pattern/usefulness/doc-hidden-non-exhaustive.rs # same +rm tests/ui/suggestions/derive-trait-for-method-call.rs # same +rm tests/ui/typeck/issue-46112.rs # same + +rm tests/ui/proc-macro/crt-static.rs # extra warning about -Cpanic=abort for proc macros +rm tests/ui/proc-macro/proc-macro-deprecated-attr.rs # same +rm tests/ui/proc-macro/quote-debug.rs # same +rm tests/ui/proc-macro/no-missing-docs.rs # same +rm tests/ui/rust-2018/proc-macro-crate-in-paths.rs # same + # doesn't work due to the way the rustc test suite is invoked. # should work when using ./x.py test the way it is intended # ============================================================ @@ -98,12 +112,14 @@ rm tests/ui/simd/intrinsic/generic-reduction-pass.rs # simd_reduce_add_unordered rm tests/ui/simd/intrinsic/generic-as.rs # crash when accessing vector type filed (#1318) rm tests/ui/simd/simd-bitmask.rs # crash +rm tests/ui/dyn-star/dyn-star-to-dyn.rs +rm tests/ui/dyn-star/dispatch-on-pin-mut.rs + # bugs in the test suite # ====================== rm tests/ui/backtrace.rs # TODO warning rm tests/ui/simple_global_asm.rs # TODO add needs-asm-support rm tests/ui/process/nofile-limit.rs # TODO some AArch64 linking issue -rm tests/ui/dyn-star/dispatch-on-pin-mut.rs # TODO failed assertion in vtable::get_ptr_and_method_ref rm tests/ui/stdio-is-blocking.rs # really slow with unoptimized libstd From c6ad186298f6e556607df32c7e02e91435fb84e7 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 20 Jan 2023 17:27:39 +0000 Subject: [PATCH 243/500] Use panic_nounwind and panic_cannot_unwind where necessary These were either regular unwinding panics or aborts in the past but got changed somewhat recently. --- src/base.rs | 34 +++++++++++++++++++++++++++------- src/intrinsics/mod.rs | 6 +++--- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/src/base.rs b/src/base.rs index 0df3ffc4bd890..53fbab9fe2931 100644 --- a/src/base.rs +++ b/src/base.rs @@ -466,7 +466,10 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) { *destination, ); } - TerminatorKind::Resume | TerminatorKind::Abort => { + TerminatorKind::Abort => { + codegen_panic_cannot_unwind(fx, source_info); + } + TerminatorKind::Resume => { // FIXME implement unwinding fx.bcx.ins().trap(TrapCode::UnreachableCodeReached); } @@ -931,7 +934,28 @@ pub(crate) fn codegen_panic<'tcx>( codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, source_info.span); } -pub(crate) fn codegen_panic_inner<'tcx>( +pub(crate) fn codegen_panic_nounwind<'tcx>( + fx: &mut FunctionCx<'_, '_, 'tcx>, + msg_str: &str, + source_info: mir::SourceInfo, +) { + let msg_ptr = fx.anonymous_str(msg_str); + let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap()); + let args = [msg_ptr, msg_len]; + + codegen_panic_inner(fx, rustc_hir::LangItem::PanicNounwind, &args, source_info.span); +} + +pub(crate) fn codegen_panic_cannot_unwind<'tcx>( + fx: &mut FunctionCx<'_, '_, 'tcx>, + source_info: mir::SourceInfo, +) { + let args = []; + + codegen_panic_inner(fx, rustc_hir::LangItem::PanicCannotUnwind, &args, source_info.span); +} + +fn codegen_panic_inner<'tcx>( fx: &mut FunctionCx<'_, '_, 'tcx>, lang_item: rustc_hir::LangItem, args: &[Value], @@ -948,11 +972,7 @@ pub(crate) fn codegen_panic_inner<'tcx>( fx.lib_call( &*symbol_name, - vec![ - AbiParam::new(fx.pointer_type), - AbiParam::new(fx.pointer_type), - AbiParam::new(fx.pointer_type), - ], + args.iter().map(|&arg| AbiParam::new(fx.bcx.func.dfg.value_type(arg))).collect(), vec![], args, ); diff --git a/src/intrinsics/mod.rs b/src/intrinsics/mod.rs index 9cce8e9b9cdc0..52720daac6ffc 100644 --- a/src/intrinsics/mod.rs +++ b/src/intrinsics/mod.rs @@ -649,7 +649,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let layout = fx.layout_of(substs.type_at(0)); if layout.abi.is_uninhabited() { with_no_trimmed_paths!({ - crate::base::codegen_panic( + crate::base::codegen_panic_nounwind( fx, &format!("attempted to instantiate uninhabited type `{}`", layout.ty), source_info, @@ -660,7 +660,7 @@ fn codegen_regular_intrinsic_call<'tcx>( if intrinsic == sym::assert_zero_valid && !fx.tcx.permits_zero_init(layout) { with_no_trimmed_paths!({ - crate::base::codegen_panic( + crate::base::codegen_panic_nounwind( fx, &format!( "attempted to zero-initialize type `{}`, which is invalid", @@ -676,7 +676,7 @@ fn codegen_regular_intrinsic_call<'tcx>( && !fx.tcx.permits_uninit_init(layout) { with_no_trimmed_paths!({ - crate::base::codegen_panic( + crate::base::codegen_panic_nounwind( fx, &format!( "attempted to leave type `{}` uninitialized, which is invalid", From 70f9d520793318617949e660458bd717548ec8d6 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Fri, 20 Jan 2023 15:59:56 +0000 Subject: [PATCH 244/500] Add and use expect methods to hir. --- compiler/rustc_hir/src/hir.rs | 343 +++++++++++++++++- .../rustc_hir_analysis/src/astconv/mod.rs | 3 +- .../src/check/compare_impl_item.rs | 16 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 8 +- .../src/coherence/builtin.rs | 2 +- .../src/coherence/unsafety.rs | 4 +- compiler/rustc_hir_analysis/src/collect.rs | 3 +- 7 files changed, 356 insertions(+), 23 deletions(-) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index d6566860f8170..4640317ac7328 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2263,7 +2263,7 @@ pub struct TraitItem<'hir> { pub defaultness: Defaultness, } -impl TraitItem<'_> { +impl<'hir> TraitItem<'hir> { #[inline] pub fn hir_id(&self) -> HirId { // Items are always HIR owners. @@ -2273,6 +2273,27 @@ impl TraitItem<'_> { pub fn trait_item_id(&self) -> TraitItemId { TraitItemId { owner_id: self.owner_id } } + + /// Expect an [`TraitItemKind::Const`] or panic. + #[track_caller] + pub fn expect_const(&self) -> (&'hir Ty<'hir>, Option) { + let TraitItemKind::Const(ty, body) = self.kind else { unreachable!() }; + (ty, body) + } + + /// Expect an [`TraitItemKind::Fn`] or panic. + #[track_caller] + pub fn expect_fn(&self) -> (&FnSig<'hir>, &TraitFn<'hir>) { + let TraitItemKind::Fn(ty, trfn) = &self.kind else { unreachable!() }; + (ty, trfn) + } + + /// Expect an [`TraitItemKind::ExternCrate`] or panic. + #[track_caller] + pub fn expect_type(&self) -> (GenericBounds<'hir>, Option<&'hir Ty<'hir>>) { + let TraitItemKind::Type(bounds, ty) = self.kind else { unreachable!() }; + (bounds, ty) + } } /// Represents a trait method's body (or just argument names). @@ -2325,7 +2346,7 @@ pub struct ImplItem<'hir> { pub vis_span: Span, } -impl ImplItem<'_> { +impl<'hir> ImplItem<'hir> { #[inline] pub fn hir_id(&self) -> HirId { // Items are always HIR owners. @@ -2335,6 +2356,27 @@ impl ImplItem<'_> { pub fn impl_item_id(&self) -> ImplItemId { ImplItemId { owner_id: self.owner_id } } + + /// Expect an [`ImplItemKind::Const`] or panic. + #[track_caller] + pub fn expect_const(&self) -> (&'hir Ty<'hir>, BodyId) { + let ImplItemKind::Const(ty, body) = self.kind else { unreachable!() }; + (ty, body) + } + + /// Expect an [`ImplItemKind::Fn`] or panic. + #[track_caller] + pub fn expect_fn(&self) -> (&FnSig<'hir>, BodyId) { + let ImplItemKind::Fn(ty, body) = &self.kind else { unreachable!() }; + (ty, *body) + } + + /// Expect an [`ImplItemKind::ExternCrate`] or panic. + #[track_caller] + pub fn expect_type(&self) -> &'hir Ty<'hir> { + let ImplItemKind::Type(ty) = self.kind else { unreachable!() }; + ty + } } /// Represents various kinds of content within an `impl`. @@ -2995,7 +3037,7 @@ pub struct Item<'hir> { pub vis_span: Span, } -impl Item<'_> { +impl<'hir> Item<'hir> { #[inline] pub fn hir_id(&self) -> HirId { // Items are always HIR owners. @@ -3005,6 +3047,127 @@ impl Item<'_> { pub fn item_id(&self) -> ItemId { ItemId { owner_id: self.owner_id } } + + /// Expect an [`ItemKind::ExternCrate`] or panic. + #[track_caller] + pub fn expect_extern_crate(&self) -> Option { + let ItemKind::ExternCrate(s) = self.kind else { unreachable!() }; + s + } + + /// Expect an [`ItemKind::Use`] or panic. + #[track_caller] + pub fn expect_use(&self) -> (&'hir UsePath<'hir>, UseKind) { + let ItemKind::Use(p, uk) = self.kind else { unreachable!() }; + (p, uk) + } + + /// Expect an [`ItemKind::Static`] or panic. + #[track_caller] + pub fn expect_static(&self) -> (&'hir Ty<'hir>, Mutability, BodyId) { + let ItemKind::Static(ty, mutbl, body) = self.kind else { unreachable!() }; + (ty, mutbl, body) + } + /// Expect an [`ItemKind::Const`] or panic. + #[track_caller] + pub fn expect_const(&self) -> (&'hir Ty<'hir>, BodyId) { + let ItemKind::Const(ty, body) = self.kind else { unreachable!() }; + (ty, body) + } + /// Expect an [`ItemKind::Fn`] or panic. + #[track_caller] + pub fn expect_fn(&self) -> (&FnSig<'hir>, &'hir Generics<'hir>, BodyId) { + let ItemKind::Fn(sig, gen, body) = &self.kind else { unreachable!() }; + (sig, gen, *body) + } + + /// Expect an [`ItemKind::Macro`] or panic. + #[track_caller] + pub fn expect_macro(&self) -> (&ast::MacroDef, MacroKind) { + let ItemKind::Macro(def, mk) = &self.kind else { unreachable!() }; + (def, *mk) + } + + /// Expect an [`ItemKind::Mod`] or panic. + #[track_caller] + pub fn expect_mod(&self) -> &'hir Mod<'hir> { + let ItemKind::Mod(m) = self.kind else { unreachable!() }; + m + } + + /// Expect an [`ItemKind::ForeignMod`] or panic. + #[track_caller] + pub fn expect_foreign_mod(&self) -> (Abi, &'hir [ForeignItemRef]) { + let ItemKind::ForeignMod { abi, items } = self.kind else { unreachable!() }; + (abi, items) + } + + /// Expect an [`ItemKind::GlobalAsm`] or panic. + #[track_caller] + pub fn expect_global_asm(&self) -> &'hir InlineAsm<'hir> { + let ItemKind::GlobalAsm(asm) = self.kind else { unreachable!() }; + asm + } + + /// Expect an [`ItemKind::TyAlias`] or panic. + #[track_caller] + pub fn expect_ty_alias(&self) -> (&'hir Ty<'hir>, &'hir Generics<'hir>) { + let ItemKind::TyAlias(ty, gen) = self.kind else { unreachable!() }; + (ty, gen) + } + + /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`. + /// Expect an [`ItemKind::OpaqueTy`] or panic. + #[track_caller] + pub fn expect_opaque_ty(&self) -> &OpaqueTy<'hir> { + let ItemKind::OpaqueTy(ty) = &self.kind else { unreachable!() }; + ty + } + + /// Expect an [`ItemKind::Enum`] or panic. + #[track_caller] + pub fn expect_enum(&self) -> (&EnumDef<'hir>, &'hir Generics<'hir>) { + let ItemKind::Enum(def, gen) = &self.kind else { unreachable!() }; + (def, gen) + } + + /// Expect an [`ItemKind::Struct`] or panic. + #[track_caller] + pub fn expect_struct(&self) -> (&VariantData<'hir>, &'hir Generics<'hir>) { + let ItemKind::Struct(data, gen) = &self.kind else { unreachable!() }; + (data, gen) + } + + /// A union definition, e.g., `union Foo {x: A, y: B}`. + /// Expect an [`ItemKind::Union`] or panic. + #[track_caller] + pub fn expect_union(&self) -> (&VariantData<'hir>, &'hir Generics<'hir>) { + let ItemKind::Union(data, gen) = &self.kind else { unreachable!() }; + (data, gen) + } + + /// Expect an [`ItemKind::Trait`] or panic. + #[track_caller] + pub fn expect_trait( + self, + ) -> (IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]) { + let ItemKind::Trait(is_auto, unsafety, gen, bounds, items) = self.kind else { unreachable!() }; + (is_auto, unsafety, gen, bounds, items) + } + + /// Expect an [`ItemKind::TraitAlias`] or panic. + #[track_caller] + pub fn expect_trait_alias(&self) -> (&'hir Generics<'hir>, GenericBounds<'hir>) { + let ItemKind::TraitAlias(gen, bounds) = self.kind else { unreachable!() }; + (gen, bounds) + } + + /// Expect an [`ItemKind::Impl`] or panic. + #[track_caller] + pub fn expect_impl(&self) -> &'hir Impl<'hir> { + let ItemKind::Impl(imp) = self.kind else { unreachable!() }; + imp + } } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] @@ -3590,6 +3753,180 @@ impl<'hir> Node<'hir> { pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> { if let Node::Ctor(&VariantData::Tuple(fields, _, _)) = self { Some(fields) } else { None } } + + /// Expect a [`Node::Param`] or panic. + #[track_caller] + pub fn expect_param(self) -> &'hir Param<'hir> { + let Node::Param(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Item`] or panic. + #[track_caller] + pub fn expect_item(self) -> &'hir Item<'hir> { + let Node::Item(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::ForeignItem`] or panic. + #[track_caller] + pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> { + let Node::ForeignItem(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::TraitItem`] or panic. + #[track_caller] + pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> { + let Node::TraitItem(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::ImplItem`] or panic. + #[track_caller] + pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> { + let Node::ImplItem(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Variant`] or panic. + #[track_caller] + pub fn expect_variant(self) -> &'hir Variant<'hir> { + let Node::Variant(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Field`] or panic. + #[track_caller] + pub fn expect_field(self) -> &'hir FieldDef<'hir> { + let Node::Field(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::AnonConst`] or panic. + #[track_caller] + pub fn expect_anon_const(self) -> &'hir AnonConst { + let Node::AnonConst(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Expr`] or panic. + #[track_caller] + pub fn expect_expr(self) -> &'hir Expr<'hir> { + let Node::Expr(this) = self else { unreachable!() }; + this + } + /// Expect a [`Node::ExprField`] or panic. + #[track_caller] + pub fn expect_expr_field(self) -> &'hir ExprField<'hir> { + let Node::ExprField(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Stmt`] or panic. + #[track_caller] + pub fn expect_stmt(self) -> &'hir Stmt<'hir> { + let Node::Stmt(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::PathSegment`] or panic. + #[track_caller] + pub fn expect_path_segment(self) -> &'hir PathSegment<'hir> { + let Node::PathSegment(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Ty`] or panic. + #[track_caller] + pub fn expect_ty(self) -> &'hir Ty<'hir> { + let Node::Ty(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::TypeBinding`] or panic. + #[track_caller] + pub fn expect_type_binding(self) -> &'hir TypeBinding<'hir> { + let Node::TypeBinding(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::TraitRef`] or panic. + #[track_caller] + pub fn expect_trait_ref(self) -> &'hir TraitRef<'hir> { + let Node::TraitRef(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Pat`] or panic. + #[track_caller] + pub fn expect_pat(self) -> &'hir Pat<'hir> { + let Node::Pat(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::PatField`] or panic. + #[track_caller] + pub fn expect_pat_field(self) -> &'hir PatField<'hir> { + let Node::PatField(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Arm`] or panic. + #[track_caller] + pub fn expect_arm(self) -> &'hir Arm<'hir> { + let Node::Arm(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Block`] or panic. + #[track_caller] + pub fn expect_block(self) -> &'hir Block<'hir> { + let Node::Block(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Local`] or panic. + #[track_caller] + pub fn expect_local(self) -> &'hir Local<'hir> { + let Node::Local(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Ctor`] or panic. + #[track_caller] + pub fn expect_ctor(self) -> &'hir VariantData<'hir> { + let Node::Ctor(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Lifetime`] or panic. + #[track_caller] + pub fn expect_lifetime(self) -> &'hir Lifetime { + let Node::Lifetime(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::GenericParam`] or panic. + #[track_caller] + pub fn expect_generic_param(self) -> &'hir GenericParam<'hir> { + let Node::GenericParam(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Crate`] or panic. + #[track_caller] + pub fn expect_crate(self) -> &'hir Mod<'hir> { + let Node::Crate(this) = self else { unreachable!() }; + this + } + + /// Expect a [`Node::Infer`] or panic. + #[track_caller] + pub fn expect_infer(self) -> &'hir InferArg { + let Node::Infer(this) = self else { unreachable!() }; + this + } } // Some nodes are used a lot. Make sure they don't unintentionally get bigger. diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index 6435b05cef8a8..1b7509d6d421d 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -3124,8 +3124,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) = hir.get(fn_hir_id) else { return None }; - let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(i), .. }) = - hir.get_parent(fn_hir_id) else { bug!("ImplItem should have Impl parent") }; + let i = hir.get_parent(fn_hir_id).expect_item().expect_impl(); let trait_ref = self.instantiate_mono_trait_ref( i.of_trait.as_ref()?, diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index cfebcceef3cdb..53f5cb2cc9a7c 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -8,7 +8,7 @@ use rustc_errors::{ use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit; -use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind}; +use rustc_hir::{GenericParamKind, ImplItemKind}; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt}; @@ -916,7 +916,7 @@ fn report_trait_method_mismatch<'tcx>( // When the `impl` receiver is an arbitrary self type, like `self: Box`, the // span points only at the type `Box, but we want to cover the whole // argument pattern and type. - let ImplItemKind::Fn(ref sig, body) = tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind else { bug!("{impl_m:?} is not a method") }; + let (sig, body) = tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn(); let span = tcx .hir() .body_param_names(body) @@ -1078,12 +1078,12 @@ fn extract_spans_for_error_reporting<'tcx>( ) -> (Span, Option) { let tcx = infcx.tcx; let mut impl_args = { - let ImplItemKind::Fn(sig, _) = &tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind else { bug!("{:?} is not a method", impl_m) }; + let (sig, _) = tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn(); sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span())) }; let trait_args = trait_m.def_id.as_local().map(|def_id| { - let TraitItemKind::Fn(sig, _) = &tcx.hir().expect_trait_item(def_id).kind else { bug!("{:?} is not a TraitItemKind::Fn", trait_m) }; + let (sig, _) = tcx.hir().expect_trait_item(def_id).expect_fn(); sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span())) }); @@ -1356,7 +1356,7 @@ fn compare_number_of_method_arguments<'tcx>( .def_id .as_local() .and_then(|def_id| { - let TraitItemKind::Fn(trait_m_sig, _) = &tcx.hir().expect_trait_item(def_id).kind else { bug!("{:?} is not a method", impl_m) }; + let (trait_m_sig, _) = &tcx.hir().expect_trait_item(def_id).expect_fn(); let pos = trait_number_args.saturating_sub(1); trait_m_sig.decl.inputs.get(pos).map(|arg| { if pos == 0 { @@ -1368,7 +1368,7 @@ fn compare_number_of_method_arguments<'tcx>( }) .or(trait_item_span); - let ImplItemKind::Fn(impl_m_sig, _) = &tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind else { bug!("{:?} is not a method", impl_m) }; + let (impl_m_sig, _) = &tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn(); let pos = impl_number_args.saturating_sub(1); let impl_span = impl_m_sig .decl @@ -1704,7 +1704,7 @@ pub(super) fn compare_impl_const_raw( ); // Locate the Span containing just the type of the offending impl - let ImplItemKind::Const(ty, _) = tcx.hir().expect_impl_item(impl_const_item_def).kind else { bug!("{impl_const_item:?} is not a impl const") }; + let (ty, _) = tcx.hir().expect_impl_item(impl_const_item_def).expect_const(); cause.span = ty.span; let mut diag = struct_span_err!( @@ -1717,7 +1717,7 @@ pub(super) fn compare_impl_const_raw( let trait_c_span = trait_const_item_def.as_local().map(|trait_c_def_id| { // Add a label to the Span containing just the type of the const - let TraitItemKind::Const(ty, _) = tcx.hir().expect_trait_item(trait_c_def_id).kind else { bug!("{trait_const_item:?} is not a trait const") }; + let (ty, _) = tcx.hir().expect_trait_item(trait_c_def_id).expect_const(); ty.span }); diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 11237afe8a0e3..dd8ecd670cb0f 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -1053,8 +1053,8 @@ fn check_type_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, all_sized: b // All field types must be well-formed. for field in &variant.fields { let field_id = field.did.expect_local(); - let hir::Node::Field(hir::FieldDef { ty: hir_ty, .. }) = tcx.hir().get_by_def_id(field_id) - else { bug!() }; + let hir::FieldDef { ty: hir_ty, .. } = + tcx.hir().get_by_def_id(field_id).expect_field(); let ty = wfcx.normalize(hir_ty.span, None, tcx.type_of(field.did)); wfcx.register_wf_obligation( hir_ty.span, @@ -1087,8 +1087,8 @@ fn check_type_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, all_sized: b { let last = idx == variant.fields.len() - 1; let field_id = field.did.expect_local(); - let hir::Node::Field(hir::FieldDef { ty: hir_ty, .. }) = tcx.hir().get_by_def_id(field_id) - else { bug!() }; + let hir::FieldDef { ty: hir_ty, .. } = + tcx.hir().get_by_def_id(field_id).expect_field(); let ty = wfcx.normalize(hir_ty.span, None, tcx.type_of(field.did)); wfcx.register_bound( traits::ObligationCause::new( diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 55de68f83f284..cd63235857b22 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -54,7 +54,7 @@ fn visit_implementation_of_drop(tcx: TyCtxt<'_>, impl_did: LocalDefId) { _ => {} } - let ItemKind::Impl(impl_) = tcx.hir().expect_item(impl_did).kind else { bug!("expected Drop impl item") }; + let impl_ = tcx.hir().expect_item(impl_did).expect_impl(); tcx.sess.emit_err(DropImplOnWrongItem { span: impl_.self_ty.span }); } diff --git a/compiler/rustc_hir_analysis/src/coherence/unsafety.rs b/compiler/rustc_hir_analysis/src/coherence/unsafety.rs index fe6119dce8735..c6b16171311fb 100644 --- a/compiler/rustc_hir_analysis/src/coherence/unsafety.rs +++ b/compiler/rustc_hir_analysis/src/coherence/unsafety.rs @@ -3,15 +3,13 @@ use rustc_errors::struct_span_err; use rustc_hir as hir; -use rustc_hir::def::DefKind; use rustc_hir::Unsafety; use rustc_middle::ty::TyCtxt; use rustc_span::def_id::LocalDefId; pub(super) fn check_item(tcx: TyCtxt<'_>, def_id: LocalDefId) { - debug_assert!(matches!(tcx.def_kind(def_id), DefKind::Impl)); let item = tcx.hir().expect_item(def_id); - let hir::ItemKind::Impl(impl_) = item.kind else { bug!() }; + let impl_ = item.expect_impl(); if let Some(trait_ref) = tcx.impl_trait_ref(item.owner_id) { let trait_ref = trait_ref.subst_identity(); diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index c17778ce8bc09..1cbface07429a 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -1342,8 +1342,7 @@ fn suggest_impl_trait<'tcx>( fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option>> { let icx = ItemCtxt::new(tcx, def_id); - let item = tcx.hir().expect_item(def_id.expect_local()); - let hir::ItemKind::Impl(impl_) = item.kind else { bug!() }; + let impl_ = tcx.hir().expect_item(def_id.expect_local()).expect_impl(); impl_ .of_trait .as_ref() From 219cdbaac02480b661e4632115c97496d1d4a3ba Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 20 Jan 2023 17:40:53 +0000 Subject: [PATCH 245/500] Fix clif ir writing for simd_gather --- src/base.rs | 3 +++ src/intrinsics/simd.rs | 2 ++ 2 files changed, 5 insertions(+) diff --git a/src/base.rs b/src/base.rs index 53fbab9fe2931..d3a8c10657e8d 100644 --- a/src/base.rs +++ b/src/base.rs @@ -305,6 +305,9 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) { let source_info = bb_data.terminator().source_info; fx.set_debug_loc(source_info); + let _print_guard = + crate::PrintOnPanic(|| format!("terminator {:?}", bb_data.terminator().kind)); + match &bb_data.terminator().kind { TerminatorKind::Goto { target } => { if let TerminatorKind::Return = fx.mir[*target].terminator().kind { diff --git a/src/intrinsics/simd.rs b/src/intrinsics/simd.rs index 791ff5cfcf3c6..b33eb29754ab7 100644 --- a/src/intrinsics/simd.rs +++ b/src/intrinsics/simd.rs @@ -840,6 +840,8 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( fx.bcx.seal_block(next); fx.bcx.switch_to_block(next); + fx.bcx.ins().nop(); + ret.place_lane(fx, lane_idx) .write_cvalue(fx, CValue::by_val(res_lane, ret_lane_layout)); } From 6eef214e46454dd508821759092253c86d269204 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 20 Jan 2023 17:49:59 +0000 Subject: [PATCH 246/500] Separate out abi-cafe runs into separate CI jobs This increases build parallelism --- .github/workflows/main.yml | 67 ++++++++++++++++++++++++++++++++------ 1 file changed, 57 insertions(+), 10 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 90004b408c014..c0daf69e98e91 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -50,11 +50,9 @@ jobs: - os: ubuntu-latest env: TARGET_TRIPLE: s390x-unknown-linux-gnu - # Native Windows build with MSVC - os: windows-latest env: TARGET_TRIPLE: x86_64-pc-windows-msvc - # cross-compile from Windows to Windows MinGW - os: windows-latest env: TARGET_TRIPLE: x86_64-pc-windows-gnu @@ -114,14 +112,6 @@ jobs: TARGET_TRIPLE: ${{ matrix.env.TARGET_TRIPLE }} run: ./y.rs test - - name: Test abi-cafe - env: - TARGET_TRIPLE: ${{ matrix.env.TARGET_TRIPLE }} - run: | - if [[ "$(rustc -vV | grep host | cut -d' ' -f2)" == "$TARGET_TRIPLE" ]]; then - ./y.rs abi-cafe - fi - - name: Package prebuilt cg_clif run: tar cvfJ cg_clif.tar.xz dist @@ -138,3 +128,60 @@ jobs: with: name: cg_clif-${{ runner.os }}-cross-x86_64-mingw path: cg_clif.tar.xz + + + abi_cafe: + runs-on: ${{ matrix.os }} + timeout-minutes: 60 + + defaults: + run: + shell: bash + + strategy: + fail-fast: true + matrix: + include: + - os: ubuntu-latest + env: + TARGET_TRIPLE: x86_64-unknown-linux-gnu + - os: macos-latest + env: + TARGET_TRIPLE: x86_64-apple-darwin + - os: windows-latest + env: + TARGET_TRIPLE: x86_64-pc-windows-msvc + - os: windows-latest + env: + TARGET_TRIPLE: x86_64-pc-windows-gnu + + steps: + - uses: actions/checkout@v3 + + - name: Cache cargo target dir + uses: actions/cache@v3 + with: + path: build/cg_clif + key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }} + + - name: Set MinGW as the default toolchain + if: matrix.env.TARGET_TRIPLE == 'x86_64-pc-windows-gnu' + run: rustup set default-host x86_64-pc-windows-gnu + + - name: Use sparse cargo registry + run: | + cat >> ~/.cargo/config.toml < Date: Sat, 7 Jan 2023 17:06:13 +0000 Subject: [PATCH 247/500] Update to Cranelift 0.92 --- Cargo.lock | 64 ++++++++++++++++------------------------ Cargo.toml | 12 ++++---- src/optimize/peephole.rs | 4 +-- 3 files changed, 33 insertions(+), 47 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3bc2bf31d666d..48800725d2c13 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -57,28 +57,28 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cranelift-bforest" -version = "0.91.0" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc952b310b24444fc14ab8b9cbe3fafd7e7329e3eec84c3a9b11d2b5cf6f3be1" +checksum = "2f3d54eab028f5805ae3b26fd60eca3f3a9cfb76b989d9bab173be3f61356cc3" dependencies = [ "cranelift-entity", ] [[package]] name = "cranelift-codegen" -version = "0.91.0" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e73470419b33011e50dbf0f6439cbccbaabe9381de172da4e1b6efcda4bb8fa7" +checksum = "2be1d5f2c3cca1efb691844bc1988b89c77291f13f778499a3f3c0cf49c0ed61" dependencies = [ "arrayvec", "bumpalo", "cranelift-bforest", "cranelift-codegen-meta", "cranelift-codegen-shared", - "cranelift-egraph", "cranelift-entity", "cranelift-isle", "gimli", + "hashbrown", "log", "regalloc2", "smallvec", @@ -87,44 +87,30 @@ dependencies = [ [[package]] name = "cranelift-codegen-meta" -version = "0.91.0" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "911a1872464108a11ac9965c2b079e61bbdf1bc2e0b9001264264add2e12a38f" +checksum = "3f9b1b1089750ce4005893af7ee00bb08a2cf1c9779999c0f7164cbc8ad2e0d2" dependencies = [ "cranelift-codegen-shared", ] [[package]] name = "cranelift-codegen-shared" -version = "0.91.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e036f3f07adb24a86fb46e977e8fe03b18bb16b1eada949cf2c48283e5f8a862" - -[[package]] -name = "cranelift-egraph" -version = "0.91.0" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d6c623f4b5d2a6bad32c403f03765d4484a827eb93ee78f8cb6219ef118fd59" -dependencies = [ - "cranelift-entity", - "fxhash", - "hashbrown", - "indexmap", - "log", - "smallvec", -] +checksum = "cc5fbaec51de47297fd7304986fd53c8c0030abbe69728a60d72e1c63559318d" [[package]] name = "cranelift-entity" -version = "0.91.0" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74385eb5e405b3562f0caa7bcc4ab9a93c7958dd5bcd0e910bffb7765eacd6fc" +checksum = "dab984c94593f876090fae92e984bdcc74d9b1acf740ab5f79036001c65cba13" [[package]] name = "cranelift-frontend" -version = "0.91.0" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a4ac920422ee36bff2c66257fec861765e3d95a125cdf58d8c0f3bba7e40e61" +checksum = "6e0cb3102d21a2fe5f3210af608748ddd0cd09825ac12d42dc56ed5ed8725fe0" dependencies = [ "cranelift-codegen", "log", @@ -134,15 +120,15 @@ dependencies = [ [[package]] name = "cranelift-isle" -version = "0.91.0" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c541263fb37ad2baa53ec8c37218ee5d02fa0984670d9419dedd8002ea68ff08" +checksum = "72101dd1f441d629735143c41e00b3428f9267738176983ef588ff43382af0a0" [[package]] name = "cranelift-jit" -version = "0.91.0" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48a844e3500d313b69f3eec4b4e15bf9cdbd529756add06a468e0e281c0f6bee" +checksum = "6557f8ce44d498777f2495aa58d9692a4a37d6f84aa445750d666cef770b6a5c" dependencies = [ "anyhow", "cranelift-codegen", @@ -159,9 +145,9 @@ dependencies = [ [[package]] name = "cranelift-module" -version = "0.91.0" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0699ea5fc6ca943456ba80ad49f80212bd6e2b846b992ec59f0f2b912a1d25fa" +checksum = "88807e1c0c47ec02fe433333ccbe56b480425418b1470e333205e11650697d72" dependencies = [ "anyhow", "cranelift-codegen", @@ -169,9 +155,9 @@ dependencies = [ [[package]] name = "cranelift-native" -version = "0.91.0" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1de5d7a063e8563d670aaca38de16591a9b70dc66cbad4d49a7b4ae8395fd1ce" +checksum = "c22b0d9fcbe3fc5a1af9e7021b44ce42b930bcefac446ce22e02e8f9a0d67120" dependencies = [ "cranelift-codegen", "libc", @@ -180,9 +166,9 @@ dependencies = [ [[package]] name = "cranelift-object" -version = "0.91.0" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "307735148f6a556388aabf1ea31f46ccd378ed0739f3e9bdda2029639d701ab7" +checksum = "341375758d7c3fedc0b5315f552e6f0feac46baf87c450a15e9455ef47c2b261" dependencies = [ "anyhow", "cranelift-codegen", @@ -396,9 +382,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasmtime-jit-icache-coherence" -version = "3.0.0" +version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22d9c2e92b0fc124d2cad6cb497a4c840580a7dd2414a37109e8c7cfe699c0ea" +checksum = "08fcba5ebd96da2a9f0747ab6337fe9788adfb3f63fa2c180520d665562d257e" dependencies = [ "cfg-if", "libc", diff --git a/Cargo.toml b/Cargo.toml index f03cc34a81081..eadb4438bc992 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,12 +15,12 @@ crate-type = ["dylib"] [dependencies] # These have to be in sync with each other -cranelift-codegen = { version = "0.91", features = ["unwind", "all-arch"] } -cranelift-frontend = "0.91" -cranelift-module = "0.91" -cranelift-native = "0.91" -cranelift-jit = { version = "0.91", optional = true } -cranelift-object = "0.91" +cranelift-codegen = { version = "0.92", features = ["unwind", "all-arch"] } +cranelift-frontend = { version = "0.92" } +cranelift-module = { version = "0.92" } +cranelift-native = { version = "0.92" } +cranelift-jit = { version = "0.92", optional = true } +cranelift-object = { version = "0.92" } target-lexicon = "0.12.0" gimli = { version = "0.26.0", default-features = false, features = ["write"]} object = { version = "0.29.0", default-features = false, features = ["std", "read_core", "write", "archive", "coff", "elf", "macho", "pe"] } diff --git a/src/optimize/peephole.rs b/src/optimize/peephole.rs index 7f45bbd8f2813..26327dca299b9 100644 --- a/src/optimize/peephole.rs +++ b/src/optimize/peephole.rs @@ -7,7 +7,7 @@ use cranelift_frontend::FunctionBuilder; /// otherwise return the given value and false. pub(crate) fn maybe_unwrap_bool_not(bcx: &mut FunctionBuilder<'_>, arg: Value) -> (Value, bool) { if let ValueDef::Result(arg_inst, 0) = bcx.func.dfg.value_def(arg) { - match bcx.func.dfg[arg_inst] { + match bcx.func.dfg.insts[arg_inst] { // This is the lowering of `Rvalue::Not` InstructionData::IntCompareImm { opcode: Opcode::IcmpImm, @@ -34,7 +34,7 @@ pub(crate) fn maybe_known_branch_taken( return None; }; - match bcx.func.dfg[arg_inst] { + match bcx.func.dfg.insts[arg_inst] { InstructionData::UnaryImm { opcode: Opcode::Iconst, imm } => { if test_zero { Some(imm.bits() == 0) From b9e8286c85aa83fd7ff36603d394082024887dc9 Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Sun, 15 Jan 2023 14:29:20 +0100 Subject: [PATCH 248/500] add debug assertion for suggestions with overlapping parts --- compiler/rustc_errors/src/diagnostic.rs | 71 +++++++++++++++---------- compiler/rustc_errors/src/lib.rs | 1 + 2 files changed, 45 insertions(+), 27 deletions(-) diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index 51b2ff6a00381..4ad24c1400d69 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -629,19 +629,27 @@ impl Diagnostic { applicability: Applicability, style: SuggestionStyle, ) -> &mut Self { - assert!(!suggestion.is_empty()); - debug_assert!( - !(suggestion.iter().any(|(sp, text)| sp.is_empty() && text.is_empty())), - "Span must not be empty and have no suggestion" + let mut parts = suggestion + .into_iter() + .map(|(span, snippet)| SubstitutionPart { snippet, span }) + .collect::>(); + + parts.sort_unstable_by_key(|part| part.span); + + assert!(!parts.is_empty()); + debug_assert_eq!( + parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()), + None, + "Span must not be empty and have no suggestion", + ); + debug_assert_eq!( + parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)), + None, + "suggestion must not have overlapping parts", ); self.push_suggestion(CodeSuggestion { - substitutions: vec![Substitution { - parts: suggestion - .into_iter() - .map(|(span, snippet)| SubstitutionPart { snippet, span }) - .collect(), - }], + substitutions: vec![Substitution { parts }], msg: self.subdiagnostic_message_to_diagnostic_message(msg), style, applicability, @@ -802,25 +810,34 @@ impl Diagnostic { suggestions: impl IntoIterator>, applicability: Applicability, ) -> &mut Self { - let suggestions: Vec<_> = suggestions.into_iter().collect(); - debug_assert!( - !(suggestions - .iter() - .flatten() - .any(|(sp, suggestion)| sp.is_empty() && suggestion.is_empty())), - "Span must not be empty and have no suggestion" - ); + let substitutions = suggestions + .into_iter() + .map(|sugg| { + let mut parts = sugg + .into_iter() + .map(|(span, snippet)| SubstitutionPart { snippet, span }) + .collect::>(); + + parts.sort_unstable_by_key(|part| part.span); + + assert!(!parts.is_empty()); + debug_assert_eq!( + parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()), + None, + "Span must not be empty and have no suggestion", + ); + debug_assert_eq!( + parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)), + None, + "suggestion must not have overlapping parts", + ); + + Substitution { parts } + }) + .collect(); self.push_suggestion(CodeSuggestion { - substitutions: suggestions - .into_iter() - .map(|sugg| Substitution { - parts: sugg - .into_iter() - .map(|(span, snippet)| SubstitutionPart { snippet, span }) - .collect(), - }) - .collect(), + substitutions, msg: self.subdiagnostic_message_to_diagnostic_message(msg), style: SuggestionStyle::ShowCode, applicability, diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 535812fb0e228..d076fc08b0e2f 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -3,6 +3,7 @@ //! This module contains the code for creating and emitting diagnostics. #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] +#![feature(array_windows)] #![feature(drain_filter)] #![feature(if_let_guard)] #![feature(is_terminal)] From 31443c63b520cc97a551fb7168d77abbe160b2ef Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Sun, 15 Jan 2023 17:49:34 +0100 Subject: [PATCH 249/500] preserve delim spans during `macro_rules!` expansion if able --- compiler/rustc_expand/src/mbe/macro_rules.rs | 24 ++++++++++++++----- .../min_const_generics/macro-fail.stderr | 23 +++++++----------- tests/ui/imports/import-prefix-macro-1.stderr | 2 +- tests/ui/parser/issues/issue-44406.stderr | 4 ++-- 4 files changed, 30 insertions(+), 23 deletions(-) diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 4ebd75f018560..cd431f5701958 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -10,7 +10,7 @@ use crate::mbe::transcribe::transcribe; use rustc_ast as ast; use rustc_ast::token::{self, Delimiter, NonterminalKind, Token, TokenKind, TokenKind::*}; -use rustc_ast::tokenstream::{DelimSpan, TokenStream}; +use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree}; use rustc_ast::{NodeId, DUMMY_NODE_ID}; use rustc_ast_pretty::pprust; use rustc_attr::{self as attr, TransparencyError}; @@ -212,7 +212,6 @@ fn expand_macro<'cx>( }; let arm_span = rhses[i].span(); - let rhs_spans = rhs.tts.iter().map(|t| t.span()).collect::>(); // rhs has holes ( `$id` and `$(...)` that need filled) let mut tts = match transcribe(cx, &named_matches, &rhs, rhs_span, transparency) { Ok(tts) => tts, @@ -224,12 +223,25 @@ fn expand_macro<'cx>( // Replace all the tokens for the corresponding positions in the macro, to maintain // proper positions in error reporting, while maintaining the macro_backtrace. - if rhs_spans.len() == tts.len() { + if tts.len() == rhs.tts.len() { tts = tts.map_enumerated(|i, tt| { let mut tt = tt.clone(); - let mut sp = rhs_spans[i]; - sp = sp.with_ctxt(tt.span().ctxt()); - tt.set_span(sp); + let rhs_tt = &rhs.tts[i]; + let ctxt = tt.span().ctxt(); + match (&mut tt, rhs_tt) { + // preserve the delim spans if able + ( + TokenTree::Delimited(target_sp, ..), + mbe::TokenTree::Delimited(source_sp, ..), + ) => { + target_sp.open = source_sp.open.with_ctxt(ctxt); + target_sp.close = source_sp.close.with_ctxt(ctxt); + } + _ => { + let sp = rhs_tt.span().with_ctxt(ctxt); + tt.set_span(sp); + } + } tt }); } diff --git a/tests/ui/const-generics/min_const_generics/macro-fail.stderr b/tests/ui/const-generics/min_const_generics/macro-fail.stderr index 9f73b91aabebf..cc629fd920fab 100644 --- a/tests/ui/const-generics/min_const_generics/macro-fail.stderr +++ b/tests/ui/const-generics/min_const_generics/macro-fail.stderr @@ -8,7 +8,7 @@ LL | fn make_marker() -> impl Marker { | in this macro invocation ... LL | ($rusty: ident) => {{ let $rusty = 3; *&$rusty }} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected type + | ^ expected type | = note: this error originates in the macro `gimme_a_const` (in Nightly builds, run with -Z macro-backtrace for more info) @@ -22,26 +22,21 @@ LL | Example:: | in this macro invocation ... LL | ($rusty: ident) => {{ let $rusty = 3; *&$rusty }} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected type + | ^ expected type | = note: this error originates in the macro `gimme_a_const` (in Nightly builds, run with -Z macro-backtrace for more info) error: expected type, found `{` --> $DIR/macro-fail.rs:4:10 | -LL | () => {{ - | __________^ -LL | | -LL | | const X: usize = 1337; -LL | | X -LL | | }} - | |___^ expected type +LL | () => {{ + | ^ expected type ... -LL | let _fail = Example::; - | ----------------- - | | - | this macro call doesn't expand to a type - | in this macro invocation +LL | let _fail = Example::; + | ----------------- + | | + | this macro call doesn't expand to a type + | in this macro invocation | = note: this error originates in the macro `external_macro` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/imports/import-prefix-macro-1.stderr b/tests/ui/imports/import-prefix-macro-1.stderr index 8868ee3aeaadd..a6a5b1393daec 100644 --- a/tests/ui/imports/import-prefix-macro-1.stderr +++ b/tests/ui/imports/import-prefix-macro-1.stderr @@ -2,7 +2,7 @@ error: expected one of `::`, `;`, or `as`, found `{` --> $DIR/import-prefix-macro-1.rs:11:27 | LL | ($p: path) => (use $p {S, Z}); - | ^^^^^^ expected one of `::`, `;`, or `as` + | ^ expected one of `::`, `;`, or `as` ... LL | import! { a::b::c } | ------------------- in this macro invocation diff --git a/tests/ui/parser/issues/issue-44406.stderr b/tests/ui/parser/issues/issue-44406.stderr index 1f0c1ea4c2f13..de02ea85b27b7 100644 --- a/tests/ui/parser/issues/issue-44406.stderr +++ b/tests/ui/parser/issues/issue-44406.stderr @@ -21,8 +21,8 @@ LL | foo!(true); = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) help: if `bar` is a struct, use braces as delimiters | -LL | bar { } - | ~ +LL | bar { baz: $rest } + | ~ ~ help: if `bar` is a function, use the arguments directly | LL - bar(baz: $rest) From e415e2f1a289f97d3b8ac4f4d2b7eb2b050b86cc Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Sun, 15 Jan 2023 21:01:00 +0100 Subject: [PATCH 250/500] fix overlapping spans for `explicit_outlives_requirements` in macros also delete trailing comma if necessary --- compiler/rustc_lint/src/builtin.rs | 37 +++++++++--- .../edition-lint-infer-outlives-multispan.rs | 20 +++++++ ...ition-lint-infer-outlives-multispan.stderr | 58 ++++++++++++++++++- .../edition-lint-infer-outlives.fixed | 9 +++ .../rust-2018/edition-lint-infer-outlives.rs | 9 +++ .../edition-lint-infer-outlives.stderr | 14 +++-- 6 files changed, 135 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 6f445426df70e..18657c94c586c 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2173,13 +2173,31 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements { dropped_predicate_count += 1; } - if drop_predicate && !in_where_clause { - lint_spans.push(predicate_span); - } else if drop_predicate && i + 1 < num_predicates { - // If all the bounds on a predicate were inferable and there are - // further predicates, we want to eat the trailing comma. - let next_predicate_span = hir_generics.predicates[i + 1].span(); - where_lint_spans.push(predicate_span.to(next_predicate_span.shrink_to_lo())); + if drop_predicate { + if !in_where_clause { + lint_spans.push(predicate_span); + } else if predicate_span.from_expansion() { + // Don't try to extend the span if it comes from a macro expansion. + where_lint_spans.push(predicate_span); + } else if i + 1 < num_predicates { + // If all the bounds on a predicate were inferable and there are + // further predicates, we want to eat the trailing comma. + let next_predicate_span = hir_generics.predicates[i + 1].span(); + if next_predicate_span.from_expansion() { + where_lint_spans.push(predicate_span); + } else { + where_lint_spans + .push(predicate_span.to(next_predicate_span.shrink_to_lo())); + } + } else { + // Eat the optional trailing comma after the last predicate. + let where_span = hir_generics.where_clause_span; + if where_span.from_expansion() { + where_lint_spans.push(predicate_span); + } else { + where_lint_spans.push(predicate_span.to(where_span.shrink_to_hi())); + } + } } else { where_lint_spans.extend(self.consolidate_outlives_bound_spans( predicate_span.shrink_to_lo(), @@ -2223,6 +2241,11 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements { Applicability::MaybeIncorrect }; + // Due to macros, there might be several predicates with the same span + // and we only want to suggest removing them once. + lint_spans.sort_unstable(); + lint_spans.dedup(); + cx.emit_spanned_lint( EXPLICIT_OUTLIVES_REQUIREMENTS, lint_spans.clone(), diff --git a/tests/ui/rust-2018/edition-lint-infer-outlives-multispan.rs b/tests/ui/rust-2018/edition-lint-infer-outlives-multispan.rs index 0b3de0df2b884..d2254acb33f6b 100644 --- a/tests/ui/rust-2018/edition-lint-infer-outlives-multispan.rs +++ b/tests/ui/rust-2018/edition-lint-infer-outlives-multispan.rs @@ -365,4 +365,24 @@ mod unions { } } +// https://github.com/rust-lang/rust/issues/106870 +mod multiple_predicates_with_same_span { + macro_rules! m { + ($($name:ident)+) => { + struct Inline<'a, $($name: 'a,)+>(&'a ($($name,)+)); + //~^ ERROR: outlives requirements can be inferred + struct FullWhere<'a, $($name,)+>(&'a ($($name,)+)) where $($name: 'a,)+; + //~^ ERROR: outlives requirements can be inferred + struct PartialWhere<'a, $($name,)+>(&'a ($($name,)+)) where (): Sized, $($name: 'a,)+; + //~^ ERROR: outlives requirements can be inferred + struct Interleaved<'a, $($name,)+>(&'a ($($name,)+)) + where + (): Sized, + $($name: 'a, $name: 'a, )+ //~ ERROR: outlives requirements can be inferred + $($name: 'a, $name: 'a, )+; + } + } + m!(T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15); +} + fn main() {} diff --git a/tests/ui/rust-2018/edition-lint-infer-outlives-multispan.stderr b/tests/ui/rust-2018/edition-lint-infer-outlives-multispan.stderr index 251d74094caa9..f5ec287d29132 100644 --- a/tests/ui/rust-2018/edition-lint-infer-outlives-multispan.stderr +++ b/tests/ui/rust-2018/edition-lint-infer-outlives-multispan.stderr @@ -819,5 +819,61 @@ LL - union BeeWhereAyTeeYooWhereOutlivesAyIsDebugBee<'a, 'b, T, U> where U: LL + union BeeWhereAyTeeYooWhereOutlivesAyIsDebugBee<'a, 'b, T, U> where U: Debug, { | -error: aborting due to 68 previous errors +error: outlives requirements can be inferred + --> $DIR/edition-lint-infer-outlives-multispan.rs:372:38 + | +LL | struct Inline<'a, $($name: 'a,)+>(&'a ($($name,)+)); + | ^^^^ help: remove these bounds +... +LL | m!(T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15); + | --------------------------------------------------------- in this macro invocation + | + = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: outlives requirements can be inferred + --> $DIR/edition-lint-infer-outlives-multispan.rs:374:64 + | +LL | struct FullWhere<'a, $($name,)+>(&'a ($($name,)+)) where $($name: 'a,)+; + | ^^^^^^^^^^^^^^^^^^ help: remove these bounds +... +LL | m!(T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15); + | --------------------------------------------------------- in this macro invocation + | + = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: outlives requirements can be inferred + --> $DIR/edition-lint-infer-outlives-multispan.rs:376:86 + | +LL | struct PartialWhere<'a, $($name,)+>(&'a ($($name,)+)) where (): Sized, $($name: 'a,)+; + | ^^^^^^^^^ help: remove these bounds +... +LL | m!(T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15); + | --------------------------------------------------------- in this macro invocation + | + = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: outlives requirements can be inferred + --> $DIR/edition-lint-infer-outlives-multispan.rs:381:19 + | +LL | $($name: 'a, $name: 'a, )+ + | ^^^^^^^^^ ^^^^^^^^^ +LL | $($name: 'a, $name: 'a, )+; + | ^^^^^^^^^ ^^^^^^^^^ +... +LL | m!(T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15); + | --------------------------------------------------------- + | | + | in this macro invocation + | in this macro invocation + | in this macro invocation + | in this macro invocation + | + = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) +help: remove these bounds + | +LL ~ $(, , )+ +LL ~ $(, , )+; + | + +error: aborting due to 72 previous errors diff --git a/tests/ui/rust-2018/edition-lint-infer-outlives.fixed b/tests/ui/rust-2018/edition-lint-infer-outlives.fixed index 13645244da069..868bdf2e068d8 100644 --- a/tests/ui/rust-2018/edition-lint-infer-outlives.fixed +++ b/tests/ui/rust-2018/edition-lint-infer-outlives.fixed @@ -791,5 +791,14 @@ struct StaticRef { field: &'static T } +struct TrailingCommaInWhereClause<'a, T, U> +where + T: 'a, + + //~^ ERROR outlives requirements can be inferred +{ + tee: T, + yoo: &'a U +} fn main() {} diff --git a/tests/ui/rust-2018/edition-lint-infer-outlives.rs b/tests/ui/rust-2018/edition-lint-infer-outlives.rs index d9486ba66f8aa..75783764ad6c9 100644 --- a/tests/ui/rust-2018/edition-lint-infer-outlives.rs +++ b/tests/ui/rust-2018/edition-lint-infer-outlives.rs @@ -791,5 +791,14 @@ struct StaticRef { field: &'static T } +struct TrailingCommaInWhereClause<'a, T, U> +where + T: 'a, + U: 'a, + //~^ ERROR outlives requirements can be inferred +{ + tee: T, + yoo: &'a U +} fn main() {} diff --git a/tests/ui/rust-2018/edition-lint-infer-outlives.stderr b/tests/ui/rust-2018/edition-lint-infer-outlives.stderr index faa9f21e38ba2..e655fb4842c71 100644 --- a/tests/ui/rust-2018/edition-lint-infer-outlives.stderr +++ b/tests/ui/rust-2018/edition-lint-infer-outlives.stderr @@ -1,8 +1,8 @@ error: outlives requirements can be inferred - --> $DIR/edition-lint-infer-outlives.rs:26:31 + --> $DIR/edition-lint-infer-outlives.rs:797:5 | -LL | struct TeeOutlivesAy<'a, T: 'a> { - | ^^^^ help: remove this bound +LL | U: 'a, + | ^^^^^^ help: remove this bound | note: the lint level is defined here --> $DIR/edition-lint-infer-outlives.rs:4:9 @@ -10,6 +10,12 @@ note: the lint level is defined here LL | #![deny(explicit_outlives_requirements)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +error: outlives requirements can be inferred + --> $DIR/edition-lint-infer-outlives.rs:26:31 + | +LL | struct TeeOutlivesAy<'a, T: 'a> { + | ^^^^ help: remove this bound + error: outlives requirements can be inferred --> $DIR/edition-lint-infer-outlives.rs:31:40 | @@ -916,5 +922,5 @@ error: outlives requirements can be inferred LL | union BeeWhereOutlivesAyTeeWhereDebug<'a, 'b, T> where 'b: 'a, T: Debug { | ^^^^^^^^ help: remove this bound -error: aborting due to 152 previous errors +error: aborting due to 153 previous errors From 228ddf04fca01e8224ad4fb8a8e9db8483642249 Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Thu, 19 Jan 2023 21:45:38 +0100 Subject: [PATCH 251/500] fix overlapping spans for `clippy::uninlined_format_args` --- src/tools/clippy/clippy_lints/src/format_args.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/tools/clippy/clippy_lints/src/format_args.rs b/src/tools/clippy/clippy_lints/src/format_args.rs index 043112bbc9596..bb7fa3087b748 100644 --- a/src/tools/clippy/clippy_lints/src/format_args.rs +++ b/src/tools/clippy/clippy_lints/src/format_args.rs @@ -311,6 +311,10 @@ fn check_uninlined_args( // in those cases, make the code suggestion hidden let multiline_fix = fixes.iter().any(|(span, _)| cx.sess().source_map().is_multiline(*span)); + // Suggest removing each argument only once, for example in `format!("{0} {0}", arg)`. + fixes.sort_unstable_by_key(|(span, _)| *span); + fixes.dedup_by_key(|(span, _)| *span); + span_lint_and_then( cx, UNINLINED_FORMAT_ARGS, From edd647e141d76152e00c133766b4cf239533856e Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 20 Jan 2023 18:29:35 -0800 Subject: [PATCH 252/500] Release notes for 1.67.0 --- RELEASES.md | 98 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/RELEASES.md b/RELEASES.md index 2901bfcc3e3e9..79c49e9d7909e 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,3 +1,101 @@ +Version 1.67 (2023-01-26) +========================== + + + +Language +-------- + +- [Make `Sized` predicates coinductive, allowing cycles.](https://github.com/rust-lang/rust/pull/100386/) +- [`#[must_use]` annotations on `async fn` also affect the `Future::Output`.](https://github.com/rust-lang/rust/pull/100633/) +- [Elaborate supertrait obligations when deducing closure signatures.](https://github.com/rust-lang/rust/pull/101834/) +- [Invalid literals are no longer an error under `cfg(FALSE)`.](https://github.com/rust-lang/rust/pull/102944/) +- [Unreserve braced enum variants in value namespace.](https://github.com/rust-lang/rust/pull/103578/) + + + +Compiler +-------- + +- [Enable varargs support for calling conventions other than `C` or `cdecl`.](https://github.com/rust-lang/rust/pull/97971/) +- [Add new MIR constant propagation based on dataflow analysis.](https://github.com/rust-lang/rust/pull/101168/) +- [Optimize field ordering by grouping m\*2^n-sized fields with equivalently aligned ones.](https://github.com/rust-lang/rust/pull/102750/) +- [Stabilize native library modifier `verbatim`.](https://github.com/rust-lang/rust/pull/104360/) + +Added and removed targets: + +- [Add a tier 3 target for PowerPC on AIX](https://github.com/rust-lang/rust/pull/102293/), `powerpc64-ibm-aix`. +- [Add a tier 3 target for the Sony PlayStation 1](https://github.com/rust-lang/rust/pull/102689/), `mipsel-sony-psx`. +- [Add tier 3 `no_std` targets for the QNX Neutrino RTOS](https://github.com/rust-lang/rust/pull/102701/), + `aarch64-unknown-nto-qnx710` and `x86_64-pc-nto-qnx710`. +- [Remove tier 3 `linuxkernel` targets](https://github.com/rust-lang/rust/pull/104015/) (not used by the actual kernel). + +Refer to Rust's [platform support page][platform-support-doc] +for more information on Rust's tiered platform support. + + + +Libraries +--------- + +- [Merge `crossbeam-channel` into `std::sync::mpsc`.](https://github.com/rust-lang/rust/pull/93563/) +- [Fix inconsistent rounding of 0.5 when formatted to 0 decimal places.](https://github.com/rust-lang/rust/pull/102935/) +- [Derive `Eq` and `Hash` for `ControlFlow`.](https://github.com/rust-lang/rust/pull/103084/) +- [Don't build `compiler_builtins` with `-C panic=abort`.](https://github.com/rust-lang/rust/pull/103786/) + + + +Stabilized APIs +--------------- + +- [`{integer}::checked_ilog`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.checked_ilog) +- [`{integer}::checked_ilog2`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.checked_ilog2) +- [`{integer}::checked_ilog10`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.checked_ilog10) +- [`{integer}::ilog`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.ilog) +- [`{integer}::ilog2`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.ilog2) +- [`{integer}::ilog10`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.ilog10) +- [`NonZeroU*::ilog2`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html#method.ilog2) +- [`NonZeroU*::ilog10`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html#method.ilog10) +- [`NonZero*::BITS`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html#associatedconstant.BITS) + +These APIs are now stable in const contexts: + +- [`char::from_u32`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.from_u32) +- [`char::from_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.from_digit) +- [`char::to_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.to_digit) +- [`core::char::from_u32`](https://doc.rust-lang.org/stable/core/char/fn.from_u32.html) +- [`core::char::from_digit`](https://doc.rust-lang.org/stable/core/char/fn.from_digit.html) + + + +Compatibility Notes +------------------- + +- [Chains of `&&` and `||` will now drop temporaries from their sub-expressions in + evaluation order, left-to-right.](https://github.com/rust-lang/rust/pull/103293/) + Previously, it was "twisted" such that the _first_ expression dropped its + temporaries _last_, after all of the other expressions dropped in order. +- [Proc-macro derives using inaccessible names from parent modules is now a hard error.](https://github.com/rust-lang/rust/pull/84022/) + This has been a warning since 1.29.0, and denied by default since 1.58.0. + (**TODO**: revert proposed in ) +- [Underscore suffixes on string literals are now a hard error.](https://github.com/rust-lang/rust/pull/103914/) + This has been a future-compatibility warning since 1.20.0. +- [Stop passing `-export-dynamic` to `wasm-ld`.](https://github.com/rust-lang/rust/pull/105405/) +- [`main` is now mangled as `__main_void` on `wasm32-wasi`.](https://github.com/rust-lang/rust/pull/105468/) +- [Cargo now emits an error if there are multiple registries in the configuration + with the same index URL.](https://github.com/rust-lang/cargo/pull/10592) + + + +Internal Changes +---------------- + +These changes do not affect any public interfaces of Rust, but they represent +significant improvements to the performance or internals of rustc and related +tools. + +- [Rewrite LLVM's archive writer in Rust.](https://github.com/rust-lang/rust/pull/97485/) + Version 1.66.1 (2023-01-10) =========================== From 568d6c1ac78df9fb4a8cc988198f6af9371a53d0 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 20 Jan 2023 18:38:09 -0800 Subject: [PATCH 253/500] Expand 1.67 to 1.67.0 --- RELEASES.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index 79c49e9d7909e..6acc8f3dfb4e6 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,7 +1,7 @@ -Version 1.67 (2023-01-26) +Version 1.67.0 (2023-01-26) ========================== - + Language -------- @@ -12,7 +12,7 @@ Language - [Invalid literals are no longer an error under `cfg(FALSE)`.](https://github.com/rust-lang/rust/pull/102944/) - [Unreserve braced enum variants in value namespace.](https://github.com/rust-lang/rust/pull/103578/) - + Compiler -------- @@ -33,7 +33,7 @@ Added and removed targets: Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. - + Libraries --------- @@ -43,7 +43,7 @@ Libraries - [Derive `Eq` and `Hash` for `ControlFlow`.](https://github.com/rust-lang/rust/pull/103084/) - [Don't build `compiler_builtins` with `-C panic=abort`.](https://github.com/rust-lang/rust/pull/103786/) - + Stabilized APIs --------------- @@ -66,7 +66,7 @@ These APIs are now stable in const contexts: - [`core::char::from_u32`](https://doc.rust-lang.org/stable/core/char/fn.from_u32.html) - [`core::char::from_digit`](https://doc.rust-lang.org/stable/core/char/fn.from_digit.html) - + Compatibility Notes ------------------- @@ -85,7 +85,7 @@ Compatibility Notes - [Cargo now emits an error if there are multiple registries in the configuration with the same index URL.](https://github.com/rust-lang/cargo/pull/10592) - + Internal Changes ---------------- From afd530793454a42951dcc0fe50b1cd66f397c438 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sat, 31 Dec 2022 11:00:41 +0100 Subject: [PATCH 254/500] Move `ty::tls` to seperate file --- compiler/rustc_middle/src/ty/context.rs | 174 +------------------- compiler/rustc_middle/src/ty/context/tls.rs | 169 +++++++++++++++++++ 2 files changed, 171 insertions(+), 172 deletions(-) create mode 100644 compiler/rustc_middle/src/ty/context/tls.rs diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index ce04d8d21f4cd..ed23297dba78c 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -2,6 +2,8 @@ #![allow(rustc::usage_of_ty_tykind)] +pub mod tls; + use crate::arena::Arena; use crate::dep_graph::{DepGraph, DepKindStruct}; use crate::infer::canonical::{CanonicalVarInfo, CanonicalVarInfos}; @@ -1188,178 +1190,6 @@ CloneLiftImpls! { for<'tcx> { Constness, traits::WellFormedLoc, ImplPolarity, crate::mir::ReturnConstraint, } } -pub mod tls { - use super::{ptr_eq, GlobalCtxt, TyCtxt}; - - use crate::dep_graph::TaskDepsRef; - use crate::ty::query; - use rustc_data_structures::sync::{self, Lock}; - use rustc_errors::Diagnostic; - use std::mem; - use thin_vec::ThinVec; - - #[cfg(not(parallel_compiler))] - use std::cell::Cell; - - #[cfg(parallel_compiler)] - use rustc_rayon_core as rayon_core; - - /// This is the implicit state of rustc. It contains the current - /// `TyCtxt` and query. It is updated when creating a local interner or - /// executing a new query. Whenever there's a `TyCtxt` value available - /// you should also have access to an `ImplicitCtxt` through the functions - /// in this module. - #[derive(Clone)] - pub struct ImplicitCtxt<'a, 'tcx> { - /// The current `TyCtxt`. - pub tcx: TyCtxt<'tcx>, - - /// The current query job, if any. This is updated by `JobOwner::start` in - /// `ty::query::plumbing` when executing a query. - pub query: Option, - - /// Where to store diagnostics for the current query job, if any. - /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query. - pub diagnostics: Option<&'a Lock>>, - - /// Used to prevent queries from calling too deeply. - pub query_depth: usize, - - /// The current dep graph task. This is used to add dependencies to queries - /// when executing them. - pub task_deps: TaskDepsRef<'a>, - } - - impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> { - pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self { - let tcx = TyCtxt { gcx }; - ImplicitCtxt { - tcx, - query: None, - diagnostics: None, - query_depth: 0, - task_deps: TaskDepsRef::Ignore, - } - } - } - - /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs - /// to `value` during the call to `f`. It is restored to its previous value after. - /// This is used to set the pointer to the new `ImplicitCtxt`. - #[cfg(parallel_compiler)] - #[inline] - fn set_tlv R, R>(value: usize, f: F) -> R { - rayon_core::tlv::with(value, f) - } - - /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs. - /// This is used to get the pointer to the current `ImplicitCtxt`. - #[cfg(parallel_compiler)] - #[inline] - pub fn get_tlv() -> usize { - rayon_core::tlv::get() - } - - #[cfg(not(parallel_compiler))] - thread_local! { - /// A thread local variable that stores a pointer to the current `ImplicitCtxt`. - static TLV: Cell = const { Cell::new(0) }; - } - - /// Sets TLV to `value` during the call to `f`. - /// It is restored to its previous value after. - /// This is used to set the pointer to the new `ImplicitCtxt`. - #[cfg(not(parallel_compiler))] - #[inline] - fn set_tlv R, R>(value: usize, f: F) -> R { - let old = get_tlv(); - let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); - TLV.with(|tlv| tlv.set(value)); - f() - } - - /// Gets the pointer to the current `ImplicitCtxt`. - #[cfg(not(parallel_compiler))] - #[inline] - fn get_tlv() -> usize { - TLV.with(|tlv| tlv.get()) - } - - /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`. - #[inline] - pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R - where - F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, - { - set_tlv(context as *const _ as usize, || f(&context)) - } - - /// Allows access to the current `ImplicitCtxt` in a closure if one is available. - #[inline] - pub fn with_context_opt(f: F) -> R - where - F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R, - { - let context = get_tlv(); - if context == 0 { - f(None) - } else { - // We could get an `ImplicitCtxt` pointer from another thread. - // Ensure that `ImplicitCtxt` is `Sync`. - sync::assert_sync::>(); - - unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) } - } - } - - /// Allows access to the current `ImplicitCtxt`. - /// Panics if there is no `ImplicitCtxt` available. - #[inline] - pub fn with_context(f: F) -> R - where - F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, - { - with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls"))) - } - - /// Allows access to the current `ImplicitCtxt` whose tcx field is the same as the tcx argument - /// passed in. This means the closure is given an `ImplicitCtxt` with the same `'tcx` lifetime - /// as the `TyCtxt` passed in. - /// This will panic if you pass it a `TyCtxt` which is different from the current - /// `ImplicitCtxt`'s `tcx` field. - #[inline] - pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R - where - F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R, - { - with_context(|context| unsafe { - assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); - let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); - f(context) - }) - } - - /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`. - /// Panics if there is no `ImplicitCtxt` available. - #[inline] - pub fn with(f: F) -> R - where - F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R, - { - with_context(|context| f(context.tcx)) - } - - /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`. - /// The closure is passed None if there is no `ImplicitCtxt` available. - #[inline] - pub fn with_opt(f: F) -> R - where - F: for<'tcx> FnOnce(Option>) -> R, - { - with_context_opt(|opt_context| f(opt_context.map(|context| context.tcx))) - } -} - macro_rules! sty_debug_print { ($fmt: expr, $ctxt: expr, $($variant: ident),*) => {{ // Curious inner module to allow variant names to be used as diff --git a/compiler/rustc_middle/src/ty/context/tls.rs b/compiler/rustc_middle/src/ty/context/tls.rs new file mode 100644 index 0000000000000..0737131f1794e --- /dev/null +++ b/compiler/rustc_middle/src/ty/context/tls.rs @@ -0,0 +1,169 @@ +use super::{ptr_eq, GlobalCtxt, TyCtxt}; + +use crate::dep_graph::TaskDepsRef; +use crate::ty::query; +use rustc_data_structures::sync::{self, Lock}; +use rustc_errors::Diagnostic; +use std::mem; +use thin_vec::ThinVec; + +#[cfg(not(parallel_compiler))] +use std::cell::Cell; + +#[cfg(parallel_compiler)] +use rustc_rayon_core as rayon_core; + +/// This is the implicit state of rustc. It contains the current +/// `TyCtxt` and query. It is updated when creating a local interner or +/// executing a new query. Whenever there's a `TyCtxt` value available +/// you should also have access to an `ImplicitCtxt` through the functions +/// in this module. +#[derive(Clone)] +pub struct ImplicitCtxt<'a, 'tcx> { + /// The current `TyCtxt`. + pub tcx: TyCtxt<'tcx>, + + /// The current query job, if any. This is updated by `JobOwner::start` in + /// `ty::query::plumbing` when executing a query. + pub query: Option, + + /// Where to store diagnostics for the current query job, if any. + /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query. + pub diagnostics: Option<&'a Lock>>, + + /// Used to prevent queries from calling too deeply. + pub query_depth: usize, + + /// The current dep graph task. This is used to add dependencies to queries + /// when executing them. + pub task_deps: TaskDepsRef<'a>, +} + +impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> { + pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self { + let tcx = TyCtxt { gcx }; + ImplicitCtxt { + tcx, + query: None, + diagnostics: None, + query_depth: 0, + task_deps: TaskDepsRef::Ignore, + } + } +} + +/// Sets Rayon's thread-local variable, which is preserved for Rayon jobs +/// to `value` during the call to `f`. It is restored to its previous value after. +/// This is used to set the pointer to the new `ImplicitCtxt`. +#[cfg(parallel_compiler)] +#[inline] +fn set_tlv R, R>(value: usize, f: F) -> R { + rayon_core::tlv::with(value, f) +} + +/// Gets Rayon's thread-local variable, which is preserved for Rayon jobs. +/// This is used to get the pointer to the current `ImplicitCtxt`. +#[cfg(parallel_compiler)] +#[inline] +pub fn get_tlv() -> usize { + rayon_core::tlv::get() +} + +#[cfg(not(parallel_compiler))] +thread_local! { + /// A thread local variable that stores a pointer to the current `ImplicitCtxt`. + static TLV: Cell = const { Cell::new(0) }; +} + +/// Sets TLV to `value` during the call to `f`. +/// It is restored to its previous value after. +/// This is used to set the pointer to the new `ImplicitCtxt`. +#[cfg(not(parallel_compiler))] +#[inline] +fn set_tlv R, R>(value: usize, f: F) -> R { + let old = get_tlv(); + let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); + TLV.with(|tlv| tlv.set(value)); + f() +} + +/// Gets the pointer to the current `ImplicitCtxt`. +#[cfg(not(parallel_compiler))] +#[inline] +fn get_tlv() -> usize { + TLV.with(|tlv| tlv.get()) +} + +/// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`. +#[inline] +pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R +where + F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, +{ + set_tlv(context as *const _ as usize, || f(&context)) +} + +/// Allows access to the current `ImplicitCtxt` in a closure if one is available. +#[inline] +pub fn with_context_opt(f: F) -> R +where + F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R, +{ + let context = get_tlv(); + if context == 0 { + f(None) + } else { + // We could get an `ImplicitCtxt` pointer from another thread. + // Ensure that `ImplicitCtxt` is `Sync`. + sync::assert_sync::>(); + + unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) } + } +} + +/// Allows access to the current `ImplicitCtxt`. +/// Panics if there is no `ImplicitCtxt` available. +#[inline] +pub fn with_context(f: F) -> R +where + F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, +{ + with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls"))) +} + +/// Allows access to the current `ImplicitCtxt` whose tcx field is the same as the tcx argument +/// passed in. This means the closure is given an `ImplicitCtxt` with the same `'tcx` lifetime +/// as the `TyCtxt` passed in. +/// This will panic if you pass it a `TyCtxt` which is different from the current +/// `ImplicitCtxt`'s `tcx` field. +#[inline] +pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R +where + F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R, +{ + with_context(|context| unsafe { + assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); + let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); + f(context) + }) +} + +/// Allows access to the `TyCtxt` in the current `ImplicitCtxt`. +/// Panics if there is no `ImplicitCtxt` available. +#[inline] +pub fn with(f: F) -> R +where + F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R, +{ + with_context(|context| f(context.tcx)) +} + +/// Allows access to the `TyCtxt` in the current `ImplicitCtxt`. +/// The closure is passed None if there is no `ImplicitCtxt` available. +#[inline] +pub fn with_opt(f: F) -> R +where + F: for<'tcx> FnOnce(Option>) -> R, +{ + with_context_opt(|opt_context| f(opt_context.map(|context| context.tcx))) +} From 0d11b77005c9304e45db7b1321d8d4b324366e2f Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sat, 31 Dec 2022 11:14:29 +0100 Subject: [PATCH 255/500] Some ty::tls cleanups Putting the cfged functions into a seperate module and giving them better names. --- compiler/rustc_middle/src/ty/context.rs | 6 -- compiler/rustc_middle/src/ty/context/tls.rs | 98 +++++++++++---------- 2 files changed, 53 insertions(+), 51 deletions(-) diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index ed23297dba78c..bae2c863a813d 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -2222,12 +2222,6 @@ pub struct DeducedParamAttrs { pub read_only: bool, } -// We are comparing types with different invariant lifetimes, so `ptr::eq` -// won't work for us. -fn ptr_eq(t: *const T, u: *const U) -> bool { - t as *const () == u as *const () -} - pub fn provide(providers: &mut ty::query::Providers) { providers.module_reexports = |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]); diff --git a/compiler/rustc_middle/src/ty/context/tls.rs b/compiler/rustc_middle/src/ty/context/tls.rs index 0737131f1794e..f1fe47f6ba6ed 100644 --- a/compiler/rustc_middle/src/ty/context/tls.rs +++ b/compiler/rustc_middle/src/ty/context/tls.rs @@ -1,18 +1,13 @@ -use super::{ptr_eq, GlobalCtxt, TyCtxt}; +use super::{GlobalCtxt, TyCtxt}; use crate::dep_graph::TaskDepsRef; use crate::ty::query; use rustc_data_structures::sync::{self, Lock}; use rustc_errors::Diagnostic; use std::mem; +use std::ptr; use thin_vec::ThinVec; -#[cfg(not(parallel_compiler))] -use std::cell::Cell; - -#[cfg(parallel_compiler)] -use rustc_rayon_core as rayon_core; - /// This is the implicit state of rustc. It contains the current /// `TyCtxt` and query. It is updated when creating a local interner or /// executing a new query. Whenever there's a `TyCtxt` value available @@ -52,46 +47,53 @@ impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> { } } -/// Sets Rayon's thread-local variable, which is preserved for Rayon jobs -/// to `value` during the call to `f`. It is restored to its previous value after. -/// This is used to set the pointer to the new `ImplicitCtxt`. #[cfg(parallel_compiler)] -#[inline] -fn set_tlv R, R>(value: usize, f: F) -> R { - rayon_core::tlv::with(value, f) -} +mod tlv { + use rustc_rayon_core as rayon_core; + use std::ptr; + + /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs. + /// This is used to get the pointer to the current `ImplicitCtxt`. + #[inline] + pub(super) fn get_tlv() -> usize { + rayon_core::tlv::get() + } -/// Gets Rayon's thread-local variable, which is preserved for Rayon jobs. -/// This is used to get the pointer to the current `ImplicitCtxt`. -#[cfg(parallel_compiler)] -#[inline] -pub fn get_tlv() -> usize { - rayon_core::tlv::get() + /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs + /// to `value` during the call to `f`. It is restored to its previous value after. + /// This is used to set the pointer to the new `ImplicitCtxt`. + #[inline] + pub(super) fn with_tlv R, R>(value: usize, f: F) -> R { + rayon_core::tlv::with(value, f) + } } #[cfg(not(parallel_compiler))] -thread_local! { - /// A thread local variable that stores a pointer to the current `ImplicitCtxt`. - static TLV: Cell = const { Cell::new(0) }; -} +mod tlv { + use std::cell::Cell; + use std::ptr; -/// Sets TLV to `value` during the call to `f`. -/// It is restored to its previous value after. -/// This is used to set the pointer to the new `ImplicitCtxt`. -#[cfg(not(parallel_compiler))] -#[inline] -fn set_tlv R, R>(value: usize, f: F) -> R { - let old = get_tlv(); - let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); - TLV.with(|tlv| tlv.set(value)); - f() -} + thread_local! { + /// A thread local variable that stores a pointer to the current `ImplicitCtxt`. + static TLV: Cell = const { Cell::new(0) }; + } -/// Gets the pointer to the current `ImplicitCtxt`. -#[cfg(not(parallel_compiler))] -#[inline] -fn get_tlv() -> usize { - TLV.with(|tlv| tlv.get()) + /// Gets the pointer to the current `ImplicitCtxt`. + #[inline] + pub(super) fn get_tlv() -> usize { + TLV.with(|tlv| tlv.get()) + } + + /// Sets TLV to `value` during the call to `f`. + /// It is restored to its previous value after. + /// This is used to set the pointer to the new `ImplicitCtxt`. + #[inline] + pub(super) fn with_tlv R, R>(value: usize, f: F) -> R { + let old = get_tlv(); + let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); + TLV.with(|tlv| tlv.set(value)); + f() + } } /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`. @@ -100,7 +102,7 @@ pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> where F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, { - set_tlv(context as *const _ as usize, || f(&context)) + tlv::with_tlv(context as *const _ as usize, || f(&context)) } /// Allows access to the current `ImplicitCtxt` in a closure if one is available. @@ -109,7 +111,7 @@ pub fn with_context_opt(f: F) -> R where F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R, { - let context = get_tlv(); + let context = tlv::get_tlv(); if context == 0 { f(None) } else { @@ -141,9 +143,15 @@ pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R where F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R, { - with_context(|context| unsafe { - assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); - let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); + with_context(|context| { + // The two gcx have different invariant lifetimes, so we need to erase them for the comparison. + assert!(ptr::eq( + context.tcx.gcx as *const _ as *const (), + tcx.gcx as *const _ as *const () + )); + + let context: &ImplicitCtxt<'_, '_> = unsafe { mem::transmute(context) }; + f(context) }) } From db305d0ca8b03492877a467d061f0c65eb194b2a Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sat, 31 Dec 2022 11:43:40 +0100 Subject: [PATCH 256/500] Use strict provenance APIs in ty::tls --- compiler/rustc_middle/src/lib.rs | 1 + compiler/rustc_middle/src/ty/context/tls.rs | 30 ++++++++++++++------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index 7e4063c2ffd78..95148de251824 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -43,6 +43,7 @@ #![feature(min_specialization)] #![feature(trusted_len)] #![feature(type_alias_impl_trait)] +#![feature(strict_provenance)] #![feature(associated_type_bounds)] #![feature(rustc_attrs)] #![feature(control_flow_enum)] diff --git a/compiler/rustc_middle/src/ty/context/tls.rs b/compiler/rustc_middle/src/ty/context/tls.rs index f1fe47f6ba6ed..71b025dc1be4b 100644 --- a/compiler/rustc_middle/src/ty/context/tls.rs +++ b/compiler/rustc_middle/src/ty/context/tls.rs @@ -55,16 +55,16 @@ mod tlv { /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs. /// This is used to get the pointer to the current `ImplicitCtxt`. #[inline] - pub(super) fn get_tlv() -> usize { - rayon_core::tlv::get() + pub(super) fn get_tlv() -> *const () { + ptr::from_exposed_addr(rayon_core::tlv::get()) } /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs /// to `value` during the call to `f`. It is restored to its previous value after. /// This is used to set the pointer to the new `ImplicitCtxt`. #[inline] - pub(super) fn with_tlv R, R>(value: usize, f: F) -> R { - rayon_core::tlv::with(value, f) + pub(super) fn with_tlv R, R>(value: *const (), f: F) -> R { + rayon_core::tlv::with(value.expose_addr(), f) } } @@ -75,12 +75,12 @@ mod tlv { thread_local! { /// A thread local variable that stores a pointer to the current `ImplicitCtxt`. - static TLV: Cell = const { Cell::new(0) }; + static TLV: Cell<*const ()> = const { Cell::new(ptr::null()) }; } /// Gets the pointer to the current `ImplicitCtxt`. #[inline] - pub(super) fn get_tlv() -> usize { + pub(super) fn get_tlv() -> *const () { TLV.with(|tlv| tlv.get()) } @@ -88,7 +88,7 @@ mod tlv { /// It is restored to its previous value after. /// This is used to set the pointer to the new `ImplicitCtxt`. #[inline] - pub(super) fn with_tlv R, R>(value: usize, f: F) -> R { + pub(super) fn with_tlv R, R>(value: *const (), f: F) -> R { let old = get_tlv(); let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); TLV.with(|tlv| tlv.set(value)); @@ -96,13 +96,23 @@ mod tlv { } } +#[inline] +fn erase(context: &ImplicitCtxt<'_, '_>) -> *const () { + context as *const _ as *const () +} + +#[inline] +unsafe fn downcast<'a, 'tcx>(context: *const ()) -> &'a ImplicitCtxt<'a, 'tcx> { + &*(context as *const ImplicitCtxt<'a, 'tcx>) +} + /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`. #[inline] pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R where F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, { - tlv::with_tlv(context as *const _ as usize, || f(&context)) + tlv::with_tlv(erase(context), || f(&context)) } /// Allows access to the current `ImplicitCtxt` in a closure if one is available. @@ -112,14 +122,14 @@ where F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R, { let context = tlv::get_tlv(); - if context == 0 { + if context.is_null() { f(None) } else { // We could get an `ImplicitCtxt` pointer from another thread. // Ensure that `ImplicitCtxt` is `Sync`. sync::assert_sync::>(); - unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) } + unsafe { f(Some(downcast(context))) } } } From ae39ee23fe45edb9031be8620b50b878b0cdffb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Mi=C4=85sko?= Date: Fri, 20 Jan 2023 00:00:00 +0000 Subject: [PATCH 257/500] Instantiate dominators algorithm only once Remove inline from BasicBlocks::dominators to instantiate the dominator algorithm only once - in the rustc_middle crate. --- compiler/rustc_middle/src/mir/basic_blocks.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/compiler/rustc_middle/src/mir/basic_blocks.rs b/compiler/rustc_middle/src/mir/basic_blocks.rs index 752cbdeae6b25..74e20beebad3f 100644 --- a/compiler/rustc_middle/src/mir/basic_blocks.rs +++ b/compiler/rustc_middle/src/mir/basic_blocks.rs @@ -35,7 +35,6 @@ impl<'tcx> BasicBlocks<'tcx> { self.is_cyclic.is_cyclic(self) } - #[inline] pub fn dominators(&self) -> Dominators { dominators(&self) } From 955e7fbb16e5015a493427dd2ab54aef97f2e23d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Mi=C4=85sko?= Date: Fri, 20 Jan 2023 00:00:00 +0000 Subject: [PATCH 258/500] Consistently use dominates instead of is_dominated_by There is a number of APIs that answer dominance queries. Previously they were named either "dominates" or "is_dominated_by". Consistently use the "dominates" form. No functional changes. --- .../src/graph/dominators/mod.rs | 2 +- compiler/rustc_middle/src/mir/mod.rs | 2 +- .../rustc_mir_transform/src/coverage/counters.rs | 6 +++--- compiler/rustc_mir_transform/src/coverage/graph.rs | 14 +++++++------- compiler/rustc_mir_transform/src/coverage/spans.rs | 12 ++++++------ 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/compiler/rustc_data_structures/src/graph/dominators/mod.rs b/compiler/rustc_data_structures/src/graph/dominators/mod.rs index fb2a22e94a527..6398e8360c0a2 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/mod.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/mod.rs @@ -289,7 +289,7 @@ impl Dominators { Iter { dominators: self, node: Some(node) } } - pub fn is_dominated_by(&self, node: Node, dom: Node) -> bool { + pub fn dominates(&self, dom: Node, node: Node) -> bool { // FIXME -- could be optimized by using post-order-rank self.dominators(node).any(|n| n == dom) } diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index e52b243ecf635..3f43e2311abc1 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -3049,7 +3049,7 @@ impl Location { if self.block == other.block { self.statement_index <= other.statement_index } else { - dominators.is_dominated_by(other.block, self.block) + dominators.dominates(self.block, other.block) } } } diff --git a/compiler/rustc_mir_transform/src/coverage/counters.rs b/compiler/rustc_mir_transform/src/coverage/counters.rs index 45de0c280352f..658e01d931031 100644 --- a/compiler/rustc_mir_transform/src/coverage/counters.rs +++ b/compiler/rustc_mir_transform/src/coverage/counters.rs @@ -520,7 +520,7 @@ impl<'a> BcbCounters<'a> { let mut found_loop_exit = false; for &branch in branches.iter() { if backedge_from_bcbs.iter().any(|&backedge_from_bcb| { - self.bcb_is_dominated_by(backedge_from_bcb, branch.target_bcb) + self.bcb_dominates(branch.target_bcb, backedge_from_bcb) }) { if let Some(reloop_branch) = some_reloop_branch { if reloop_branch.counter(&self.basic_coverage_blocks).is_none() { @@ -603,8 +603,8 @@ impl<'a> BcbCounters<'a> { } #[inline] - fn bcb_is_dominated_by(&self, node: BasicCoverageBlock, dom: BasicCoverageBlock) -> bool { - self.basic_coverage_blocks.is_dominated_by(node, dom) + fn bcb_dominates(&self, dom: BasicCoverageBlock, node: BasicCoverageBlock) -> bool { + self.basic_coverage_blocks.dominates(dom, node) } #[inline] diff --git a/compiler/rustc_mir_transform/src/coverage/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs index 78d28f1ebab7c..a2671eef2e940 100644 --- a/compiler/rustc_mir_transform/src/coverage/graph.rs +++ b/compiler/rustc_mir_transform/src/coverage/graph.rs @@ -209,8 +209,8 @@ impl CoverageGraph { } #[inline(always)] - pub fn is_dominated_by(&self, node: BasicCoverageBlock, dom: BasicCoverageBlock) -> bool { - self.dominators.as_ref().unwrap().is_dominated_by(node, dom) + pub fn dominates(&self, dom: BasicCoverageBlock, node: BasicCoverageBlock) -> bool { + self.dominators.as_ref().unwrap().dominates(dom, node) } #[inline(always)] @@ -312,7 +312,7 @@ rustc_index::newtype_index! { /// to the BCB's primary counter or expression). /// /// The BCB CFG is critical to simplifying the coverage analysis by ensuring graph path-based -/// queries (`is_dominated_by()`, `predecessors`, `successors`, etc.) have branch (control flow) +/// queries (`dominates()`, `predecessors`, `successors`, etc.) have branch (control flow) /// significance. #[derive(Debug, Clone)] pub(super) struct BasicCoverageBlockData { @@ -594,7 +594,7 @@ impl TraverseCoverageGraphWithLoops { // branching block would have given an `Expression` (or vice versa). let (some_successor_to_add, some_loop_header) = if let Some((_, loop_header)) = context.loop_backedges { - if basic_coverage_blocks.is_dominated_by(successor, loop_header) { + if basic_coverage_blocks.dominates(loop_header, successor) { (Some(successor), Some(loop_header)) } else { (None, None) @@ -666,15 +666,15 @@ pub(super) fn find_loop_backedges( // // The overall complexity appears to be comparable to many other MIR transform algorithms, and I // don't expect that this function is creating a performance hot spot, but if this becomes an - // issue, there may be ways to optimize the `is_dominated_by` algorithm (as indicated by an + // issue, there may be ways to optimize the `dominates` algorithm (as indicated by an // existing `FIXME` comment in that code), or possibly ways to optimize it's usage here, perhaps // by keeping track of results for visited `BasicCoverageBlock`s if they can be used to short - // circuit downstream `is_dominated_by` checks. + // circuit downstream `dominates` checks. // // For now, that kind of optimization seems unnecessarily complicated. for (bcb, _) in basic_coverage_blocks.iter_enumerated() { for &successor in &basic_coverage_blocks.successors[bcb] { - if basic_coverage_blocks.is_dominated_by(bcb, successor) { + if basic_coverage_blocks.dominates(successor, bcb) { let loop_header = successor; let backedge_from_bcb = bcb; debug!( diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index c54348404536a..31d5541a31b6b 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -63,7 +63,7 @@ impl CoverageStatement { /// Note: A `CoverageStatement` merged into another CoverageSpan may come from a `BasicBlock` that /// is not part of the `CoverageSpan` bcb if the statement was included because it's `Span` matches /// or is subsumed by the `Span` associated with this `CoverageSpan`, and it's `BasicBlock` -/// `is_dominated_by()` the `BasicBlock`s in this `CoverageSpan`. +/// `dominates()` the `BasicBlock`s in this `CoverageSpan`. #[derive(Debug, Clone)] pub(super) struct CoverageSpan { pub span: Span, @@ -705,12 +705,12 @@ impl<'a, 'tcx> CoverageSpans<'a, 'tcx> { fn hold_pending_dups_unless_dominated(&mut self) { // Equal coverage spans are ordered by dominators before dominated (if any), so it should be // impossible for `curr` to dominate any previous `CoverageSpan`. - debug_assert!(!self.span_bcb_is_dominated_by(self.prev(), self.curr())); + debug_assert!(!self.span_bcb_dominates(self.curr(), self.prev())); let initial_pending_count = self.pending_dups.len(); if initial_pending_count > 0 { let mut pending_dups = self.pending_dups.split_off(0); - pending_dups.retain(|dup| !self.span_bcb_is_dominated_by(self.curr(), dup)); + pending_dups.retain(|dup| !self.span_bcb_dominates(dup, self.curr())); self.pending_dups.append(&mut pending_dups); if self.pending_dups.len() < initial_pending_count { debug!( @@ -721,7 +721,7 @@ impl<'a, 'tcx> CoverageSpans<'a, 'tcx> { } } - if self.span_bcb_is_dominated_by(self.curr(), self.prev()) { + if self.span_bcb_dominates(self.prev(), self.curr()) { debug!( " different bcbs but SAME spans, and prev dominates curr. Discard prev={:?}", self.prev() @@ -787,8 +787,8 @@ impl<'a, 'tcx> CoverageSpans<'a, 'tcx> { } } - fn span_bcb_is_dominated_by(&self, covspan: &CoverageSpan, dom_covspan: &CoverageSpan) -> bool { - self.basic_coverage_blocks.is_dominated_by(covspan.bcb, dom_covspan.bcb) + fn span_bcb_dominates(&self, dom_covspan: &CoverageSpan, covspan: &CoverageSpan) -> bool { + self.basic_coverage_blocks.dominates(dom_covspan.bcb, covspan.bcb) } } From 8f70b5ccb7beda26ce7b012261110cd10890cb1f Mon Sep 17 00:00:00 2001 From: John Paul Adrian Glaubitz Date: Sat, 21 Jan 2023 12:00:14 +0000 Subject: [PATCH 259/500] library/std/sys_common: Define MIN_ALIGN for m68k-unknown-linux-gnu --- library/std/src/sys/common/alloc.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/library/std/src/sys/common/alloc.rs b/library/std/src/sys/common/alloc.rs index 3edbe7280774d..403a5e627f1e7 100644 --- a/library/std/src/sys/common/alloc.rs +++ b/library/std/src/sys/common/alloc.rs @@ -7,6 +7,7 @@ use crate::ptr; #[cfg(any( target_arch = "x86", target_arch = "arm", + target_arch = "m68k", target_arch = "mips", target_arch = "powerpc", target_arch = "powerpc64", From 5f49808bdefc42deb06f5096854ec2f910848cb0 Mon Sep 17 00:00:00 2001 From: Alex Macleod Date: Sat, 21 Jan 2023 17:20:46 +0000 Subject: [PATCH 260/500] Add machine applicable suggestion for `bool_assert_comparison` --- clippy_lints/src/bool_assert_comparison.rs | 53 +++-- tests/ui/bool_assert_comparison.fixed | 161 +++++++++++++ tests/ui/bool_assert_comparison.rs | 43 +++- tests/ui/bool_assert_comparison.stderr | 257 +++++++++++++++++---- 4 files changed, 453 insertions(+), 61 deletions(-) create mode 100644 tests/ui/bool_assert_comparison.fixed diff --git a/clippy_lints/src/bool_assert_comparison.rs b/clippy_lints/src/bool_assert_comparison.rs index 82d368bb8bc2c..556fa579000c6 100644 --- a/clippy_lints/src/bool_assert_comparison.rs +++ b/clippy_lints/src/bool_assert_comparison.rs @@ -1,10 +1,11 @@ +use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::{find_assert_eq_args, root_macro_call_first_node}; -use clippy_utils::{diagnostics::span_lint_and_sugg, ty::implements_trait}; +use clippy_utils::ty::{implements_trait, is_copy}; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, Lit}; -use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty; +use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::Ident; @@ -43,9 +44,7 @@ fn is_bool_lit(e: &Expr<'_>) -> bool { ) && !e.span.from_expansion() } -fn is_impl_not_trait_with_bool_out(cx: &LateContext<'_>, e: &Expr<'_>) -> bool { - let ty = cx.typeck_results().expr_ty(e); - +fn is_impl_not_trait_with_bool_out<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { cx.tcx .lang_items() .not_trait() @@ -77,31 +76,57 @@ impl<'tcx> LateLintPass<'tcx> for BoolAssertComparison { return; } let Some ((a, b, _)) = find_assert_eq_args(cx, expr, macro_call.expn) else { return }; - if !(is_bool_lit(a) ^ is_bool_lit(b)) { + + let a_span = a.span.source_callsite(); + let b_span = b.span.source_callsite(); + + let (lit_span, non_lit_expr) = match (is_bool_lit(a), is_bool_lit(b)) { + // assert_eq!(true, b) + // ^^^^^^ + (true, false) => (a_span.until(b_span), b), + // assert_eq!(a, true) + // ^^^^^^ + (false, true) => (b_span.with_lo(a_span.hi()), a), // If there are two boolean arguments, we definitely don't understand // what's going on, so better leave things as is... // // Or there is simply no boolean and then we can leave things as is! - return; - } + _ => return, + }; - if !is_impl_not_trait_with_bool_out(cx, a) || !is_impl_not_trait_with_bool_out(cx, b) { + let non_lit_ty = cx.typeck_results().expr_ty(non_lit_expr); + + if !is_impl_not_trait_with_bool_out(cx, non_lit_ty) { // At this point the expression which is not a boolean // literal does not implement Not trait with a bool output, // so we cannot suggest to rewrite our code return; } + if !is_copy(cx, non_lit_ty) { + // Only lint with types that are `Copy` because `assert!(x)` takes + // ownership of `x` whereas `assert_eq(x, true)` does not + return; + } + let macro_name = macro_name.as_str(); let non_eq_mac = ¯o_name[..macro_name.len() - 3]; - span_lint_and_sugg( + span_lint_and_then( cx, BOOL_ASSERT_COMPARISON, macro_call.span, &format!("used `{macro_name}!` with a literal bool"), - "replace it with", - format!("{non_eq_mac}!(..)"), - Applicability::MaybeIncorrect, + |diag| { + // assert_eq!(...) + // ^^^^^^^^^ + let name_span = cx.sess().source_map().span_until_char(macro_call.span, '!'); + + diag.multipart_suggestion( + format!("replace it with `{non_eq_mac}!(..)`"), + vec![(name_span, non_eq_mac.to_string()), (lit_span, String::new())], + Applicability::MachineApplicable, + ); + }, ); } } diff --git a/tests/ui/bool_assert_comparison.fixed b/tests/ui/bool_assert_comparison.fixed new file mode 100644 index 0000000000000..95f35a61bb289 --- /dev/null +++ b/tests/ui/bool_assert_comparison.fixed @@ -0,0 +1,161 @@ +// run-rustfix + +#![allow(unused, clippy::assertions_on_constants)] +#![warn(clippy::bool_assert_comparison)] + +use std::ops::Not; + +macro_rules! a { + () => { + true + }; +} +macro_rules! b { + () => { + true + }; +} + +// Implements the Not trait but with an output type +// that's not bool. Should not suggest a rewrite +#[derive(Debug, Clone, Copy)] +enum ImplNotTraitWithoutBool { + VariantX(bool), + VariantY(u32), +} + +impl PartialEq for ImplNotTraitWithoutBool { + fn eq(&self, other: &bool) -> bool { + match *self { + ImplNotTraitWithoutBool::VariantX(b) => b == *other, + _ => false, + } + } +} + +impl Not for ImplNotTraitWithoutBool { + type Output = Self; + + fn not(self) -> Self::Output { + match self { + ImplNotTraitWithoutBool::VariantX(b) => ImplNotTraitWithoutBool::VariantX(!b), + ImplNotTraitWithoutBool::VariantY(0) => ImplNotTraitWithoutBool::VariantY(1), + ImplNotTraitWithoutBool::VariantY(_) => ImplNotTraitWithoutBool::VariantY(0), + } + } +} + +// This type implements the Not trait with an Output of +// type bool. Using assert!(..) must be suggested +#[derive(Debug, Clone, Copy)] +struct ImplNotTraitWithBool; + +impl PartialEq for ImplNotTraitWithBool { + fn eq(&self, other: &bool) -> bool { + false + } +} + +impl Not for ImplNotTraitWithBool { + type Output = bool; + + fn not(self) -> Self::Output { + true + } +} + +#[derive(Debug)] +struct NonCopy; + +impl PartialEq for NonCopy { + fn eq(&self, other: &bool) -> bool { + false + } +} + +impl Not for NonCopy { + type Output = bool; + + fn not(self) -> Self::Output { + true + } +} + +fn main() { + let a = ImplNotTraitWithoutBool::VariantX(true); + let b = ImplNotTraitWithBool; + + assert_eq!("a".len(), 1); + assert!("a".is_empty()); + assert!("".is_empty()); + assert!("".is_empty()); + assert_eq!(a!(), b!()); + assert_eq!(a!(), "".is_empty()); + assert_eq!("".is_empty(), b!()); + assert_eq!(a, true); + assert!(b); + + assert_ne!("a".len(), 1); + assert!("a".is_empty()); + assert!("".is_empty()); + assert!("".is_empty()); + assert_ne!(a!(), b!()); + assert_ne!(a!(), "".is_empty()); + assert_ne!("".is_empty(), b!()); + assert_ne!(a, true); + assert!(b); + + debug_assert_eq!("a".len(), 1); + debug_assert!("a".is_empty()); + debug_assert!("".is_empty()); + debug_assert!("".is_empty()); + debug_assert_eq!(a!(), b!()); + debug_assert_eq!(a!(), "".is_empty()); + debug_assert_eq!("".is_empty(), b!()); + debug_assert_eq!(a, true); + debug_assert!(b); + + debug_assert_ne!("a".len(), 1); + debug_assert!("a".is_empty()); + debug_assert!("".is_empty()); + debug_assert!("".is_empty()); + debug_assert_ne!(a!(), b!()); + debug_assert_ne!(a!(), "".is_empty()); + debug_assert_ne!("".is_empty(), b!()); + debug_assert_ne!(a, true); + debug_assert!(b); + + // assert with error messages + assert_eq!("a".len(), 1, "tadam {}", 1); + assert_eq!("a".len(), 1, "tadam {}", true); + assert!("a".is_empty(), "tadam {}", 1); + assert!("a".is_empty(), "tadam {}", true); + assert!("a".is_empty(), "tadam {}", true); + assert_eq!(a, true, "tadam {}", false); + + debug_assert_eq!("a".len(), 1, "tadam {}", 1); + debug_assert_eq!("a".len(), 1, "tadam {}", true); + debug_assert!("a".is_empty(), "tadam {}", 1); + debug_assert!("a".is_empty(), "tadam {}", true); + debug_assert!("a".is_empty(), "tadam {}", true); + debug_assert_eq!(a, true, "tadam {}", false); + + assert!(a!()); + assert!(b!()); + + use debug_assert_eq as renamed; + renamed!(a, true); + debug_assert!(b); + + let non_copy = NonCopy; + assert_eq!(non_copy, true); + // changing the above to `assert!(non_copy)` would cause a `borrow of moved value` + println!("{non_copy:?}"); + + macro_rules! in_macro { + ($v:expr) => {{ + assert_eq!($v, true); + }}; + } + in_macro!(a); +} diff --git a/tests/ui/bool_assert_comparison.rs b/tests/ui/bool_assert_comparison.rs index ec4d6f3ff8401..88e7560b4f984 100644 --- a/tests/ui/bool_assert_comparison.rs +++ b/tests/ui/bool_assert_comparison.rs @@ -1,3 +1,6 @@ +// run-rustfix + +#![allow(unused, clippy::assertions_on_constants)] #![warn(clippy::bool_assert_comparison)] use std::ops::Not; @@ -15,7 +18,7 @@ macro_rules! b { // Implements the Not trait but with an output type // that's not bool. Should not suggest a rewrite -#[derive(Debug)] +#[derive(Debug, Clone, Copy)] enum ImplNotTraitWithoutBool { VariantX(bool), VariantY(u32), @@ -44,7 +47,7 @@ impl Not for ImplNotTraitWithoutBool { // This type implements the Not trait with an Output of // type bool. Using assert!(..) must be suggested -#[derive(Debug)] +#[derive(Debug, Clone, Copy)] struct ImplNotTraitWithBool; impl PartialEq for ImplNotTraitWithBool { @@ -61,6 +64,23 @@ impl Not for ImplNotTraitWithBool { } } +#[derive(Debug)] +struct NonCopy; + +impl PartialEq for NonCopy { + fn eq(&self, other: &bool) -> bool { + false + } +} + +impl Not for NonCopy { + type Output = bool; + + fn not(self) -> Self::Output { + true + } +} + fn main() { let a = ImplNotTraitWithoutBool::VariantX(true); let b = ImplNotTraitWithBool; @@ -119,4 +139,23 @@ fn main() { debug_assert_eq!("a".is_empty(), false, "tadam {}", true); debug_assert_eq!(false, "a".is_empty(), "tadam {}", true); debug_assert_eq!(a, true, "tadam {}", false); + + assert_eq!(a!(), true); + assert_eq!(true, b!()); + + use debug_assert_eq as renamed; + renamed!(a, true); + renamed!(b, true); + + let non_copy = NonCopy; + assert_eq!(non_copy, true); + // changing the above to `assert!(non_copy)` would cause a `borrow of moved value` + println!("{non_copy:?}"); + + macro_rules! in_macro { + ($v:expr) => {{ + assert_eq!($v, true); + }}; + } + in_macro!(a); } diff --git a/tests/ui/bool_assert_comparison.stderr b/tests/ui/bool_assert_comparison.stderr index 377d51be4cde7..3d9f8573e617c 100644 --- a/tests/ui/bool_assert_comparison.stderr +++ b/tests/ui/bool_assert_comparison.stderr @@ -1,136 +1,303 @@ error: used `assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:69:5 + --> $DIR/bool_assert_comparison.rs:89:5 | LL | assert_eq!("a".is_empty(), false); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `-D clippy::bool-assert-comparison` implied by `-D warnings` +help: replace it with `assert!(..)` + | +LL - assert_eq!("a".is_empty(), false); +LL + assert!("a".is_empty()); + | error: used `assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:70:5 + --> $DIR/bool_assert_comparison.rs:90:5 | LL | assert_eq!("".is_empty(), true); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_eq!("".is_empty(), true); +LL + assert!("".is_empty()); + | error: used `assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:71:5 + --> $DIR/bool_assert_comparison.rs:91:5 | LL | assert_eq!(true, "".is_empty()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_eq!(true, "".is_empty()); +LL + assert!("".is_empty()); + | error: used `assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:76:5 + --> $DIR/bool_assert_comparison.rs:96:5 | LL | assert_eq!(b, true); - | ^^^^^^^^^^^^^^^^^^^ help: replace it with: `assert!(..)` + | ^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_eq!(b, true); +LL + assert!(b); + | error: used `assert_ne!` with a literal bool - --> $DIR/bool_assert_comparison.rs:79:5 + --> $DIR/bool_assert_comparison.rs:99:5 | LL | assert_ne!("a".is_empty(), false); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_ne!("a".is_empty(), false); +LL + assert!("a".is_empty()); + | error: used `assert_ne!` with a literal bool - --> $DIR/bool_assert_comparison.rs:80:5 + --> $DIR/bool_assert_comparison.rs:100:5 | LL | assert_ne!("".is_empty(), true); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_ne!("".is_empty(), true); +LL + assert!("".is_empty()); + | error: used `assert_ne!` with a literal bool - --> $DIR/bool_assert_comparison.rs:81:5 + --> $DIR/bool_assert_comparison.rs:101:5 | LL | assert_ne!(true, "".is_empty()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_ne!(true, "".is_empty()); +LL + assert!("".is_empty()); + | error: used `assert_ne!` with a literal bool - --> $DIR/bool_assert_comparison.rs:86:5 + --> $DIR/bool_assert_comparison.rs:106:5 | LL | assert_ne!(b, true); - | ^^^^^^^^^^^^^^^^^^^ help: replace it with: `assert!(..)` + | ^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_ne!(b, true); +LL + assert!(b); + | error: used `debug_assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:89:5 + --> $DIR/bool_assert_comparison.rs:109:5 | LL | debug_assert_eq!("a".is_empty(), false); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `debug_assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - debug_assert_eq!("a".is_empty(), false); +LL + debug_assert!("a".is_empty()); + | error: used `debug_assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:90:5 + --> $DIR/bool_assert_comparison.rs:110:5 | LL | debug_assert_eq!("".is_empty(), true); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `debug_assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - debug_assert_eq!("".is_empty(), true); +LL + debug_assert!("".is_empty()); + | error: used `debug_assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:91:5 + --> $DIR/bool_assert_comparison.rs:111:5 | LL | debug_assert_eq!(true, "".is_empty()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `debug_assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - debug_assert_eq!(true, "".is_empty()); +LL + debug_assert!("".is_empty()); + | error: used `debug_assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:96:5 + --> $DIR/bool_assert_comparison.rs:116:5 | LL | debug_assert_eq!(b, true); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `debug_assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - debug_assert_eq!(b, true); +LL + debug_assert!(b); + | error: used `debug_assert_ne!` with a literal bool - --> $DIR/bool_assert_comparison.rs:99:5 + --> $DIR/bool_assert_comparison.rs:119:5 | LL | debug_assert_ne!("a".is_empty(), false); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `debug_assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - debug_assert_ne!("a".is_empty(), false); +LL + debug_assert!("a".is_empty()); + | error: used `debug_assert_ne!` with a literal bool - --> $DIR/bool_assert_comparison.rs:100:5 + --> $DIR/bool_assert_comparison.rs:120:5 | LL | debug_assert_ne!("".is_empty(), true); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `debug_assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - debug_assert_ne!("".is_empty(), true); +LL + debug_assert!("".is_empty()); + | error: used `debug_assert_ne!` with a literal bool - --> $DIR/bool_assert_comparison.rs:101:5 + --> $DIR/bool_assert_comparison.rs:121:5 | LL | debug_assert_ne!(true, "".is_empty()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `debug_assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - debug_assert_ne!(true, "".is_empty()); +LL + debug_assert!("".is_empty()); + | error: used `debug_assert_ne!` with a literal bool - --> $DIR/bool_assert_comparison.rs:106:5 + --> $DIR/bool_assert_comparison.rs:126:5 | LL | debug_assert_ne!(b, true); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `debug_assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - debug_assert_ne!(b, true); +LL + debug_assert!(b); + | error: used `assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:111:5 + --> $DIR/bool_assert_comparison.rs:131:5 | LL | assert_eq!("a".is_empty(), false, "tadam {}", 1); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_eq!("a".is_empty(), false, "tadam {}", 1); +LL + assert!("a".is_empty(), "tadam {}", 1); + | error: used `assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:112:5 + --> $DIR/bool_assert_comparison.rs:132:5 | LL | assert_eq!("a".is_empty(), false, "tadam {}", true); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_eq!("a".is_empty(), false, "tadam {}", true); +LL + assert!("a".is_empty(), "tadam {}", true); + | error: used `assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:113:5 + --> $DIR/bool_assert_comparison.rs:133:5 | LL | assert_eq!(false, "a".is_empty(), "tadam {}", true); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_eq!(false, "a".is_empty(), "tadam {}", true); +LL + assert!("a".is_empty(), "tadam {}", true); + | error: used `debug_assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:118:5 + --> $DIR/bool_assert_comparison.rs:138:5 | LL | debug_assert_eq!("a".is_empty(), false, "tadam {}", 1); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `debug_assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - debug_assert_eq!("a".is_empty(), false, "tadam {}", 1); +LL + debug_assert!("a".is_empty(), "tadam {}", 1); + | error: used `debug_assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:119:5 + --> $DIR/bool_assert_comparison.rs:139:5 | LL | debug_assert_eq!("a".is_empty(), false, "tadam {}", true); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `debug_assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - debug_assert_eq!("a".is_empty(), false, "tadam {}", true); +LL + debug_assert!("a".is_empty(), "tadam {}", true); + | error: used `debug_assert_eq!` with a literal bool - --> $DIR/bool_assert_comparison.rs:120:5 + --> $DIR/bool_assert_comparison.rs:140:5 | LL | debug_assert_eq!(false, "a".is_empty(), "tadam {}", true); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `debug_assert!(..)` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - debug_assert_eq!(false, "a".is_empty(), "tadam {}", true); +LL + debug_assert!("a".is_empty(), "tadam {}", true); + | + +error: used `assert_eq!` with a literal bool + --> $DIR/bool_assert_comparison.rs:143:5 + | +LL | assert_eq!(a!(), true); + | ^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_eq!(a!(), true); +LL + assert!(a!()); + | + +error: used `assert_eq!` with a literal bool + --> $DIR/bool_assert_comparison.rs:144:5 + | +LL | assert_eq!(true, b!()); + | ^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace it with `assert!(..)` + | +LL - assert_eq!(true, b!()); +LL + assert!(b!()); + | + +error: used `debug_assert_eq!` with a literal bool + --> $DIR/bool_assert_comparison.rs:148:5 + | +LL | renamed!(b, true); + | ^^^^^^^^^^^^^^^^^ + | +help: replace it with `debug_assert!(..)` + | +LL - renamed!(b, true); +LL + debug_assert!(b); + | -error: aborting due to 22 previous errors +error: aborting due to 25 previous errors From f74ca88384cbce7e318a7a0142a9ac3eda6b8641 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sat, 21 Jan 2023 20:12:40 +0100 Subject: [PATCH 261/500] Use a type-alias-impl-trait in `ObligationForest` --- compiler/rustc_data_structures/src/obligation_forest/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/compiler/rustc_data_structures/src/obligation_forest/mod.rs b/compiler/rustc_data_structures/src/obligation_forest/mod.rs index 10e673cd9297b..dda422c6dd07e 100644 --- a/compiler/rustc_data_structures/src/obligation_forest/mod.rs +++ b/compiler/rustc_data_structures/src/obligation_forest/mod.rs @@ -139,8 +139,7 @@ pub enum ProcessResult { #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] struct ObligationTreeId(usize); -type ObligationTreeIdGenerator = - std::iter::Map, fn(usize) -> ObligationTreeId>; +type ObligationTreeIdGenerator = impl Iterator; pub struct ObligationForest { /// The list of obligations. In between calls to [Self::process_obligations], From 78db9ee21a558d43948cde67c22487993c1b23ac Mon Sep 17 00:00:00 2001 From: Albert Larsan <74931857+albertlarsan68@users.noreply.github.com> Date: Sat, 21 Jan 2023 20:21:04 +0000 Subject: [PATCH 262/500] Pass `--locked` to the x test tidy call This allows to fail the push when the `Cargo.lock` file needs to be updated. --- src/etc/pre-push.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/etc/pre-push.sh b/src/etc/pre-push.sh index 7a846d44ad6a8..ff17931115cd0 100755 --- a/src/etc/pre-push.sh +++ b/src/etc/pre-push.sh @@ -14,4 +14,4 @@ ROOT_DIR="$(git rev-parse --show-toplevel)" echo "Running pre-push script $ROOT_DIR/x test tidy" cd "$ROOT_DIR" -./x test tidy +CARGOFLAGS="--locked" ./x test tidy From ee9e8cd0ec8c204d6c51acbc3663c40d089a3e24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roy=20Wellington=20=E2=85=A3?= Date: Sat, 21 Jan 2023 17:33:03 -0500 Subject: [PATCH 263/500] This function appears to be unused The comment says that it is called from main.js, but there don't seem to be any references to it in main.js. A quick ripgrep says there are no references in all of librustdoc. --- src/librustdoc/html/static/js/storage.js | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/src/librustdoc/html/static/js/storage.js b/src/librustdoc/html/static/js/storage.js index db2db83ca6310..61856303483e7 100644 --- a/src/librustdoc/html/static/js/storage.js +++ b/src/librustdoc/html/static/js/storage.js @@ -153,22 +153,6 @@ function switchTheme(styleElem, mainStyleElem, newThemeName, saveTheme) { } } -// This function is called from "main.js". -// eslint-disable-next-line no-unused-vars -function useSystemTheme(value) { - if (value === undefined) { - value = true; - } - - updateLocalStorage("use-system-theme", value); - - // update the toggle if we're on the settings page - const toggle = document.getElementById("use-system-theme"); - if (toggle && toggle instanceof HTMLInputElement) { - toggle.checked = value; - } -} - const updateSystemTheme = (function() { if (!window.matchMedia) { // fallback to the CSS computed value From fa214c3b11f6444c268b4ca7d93219df3dc020a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roy=20Wellington=20=E2=85=A3?= Date: Sat, 21 Jan 2023 17:34:30 -0500 Subject: [PATCH 264/500] Fix typo in comment --- src/librustdoc/config.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 56b40d8c66baf..2c514a0c8267b 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -509,7 +509,7 @@ impl Options { // these values up both in `dataset` and in the storage API, so it needs to be able // to convert the names back and forth. Despite doing this kebab-case to // StudlyCaps transformation automatically, the JS DOM API does not provide a - // mechanism for doing the just transformation on a string. So we want to avoid + // mechanism for doing just the transformation on a string. So we want to avoid // the StudlyCaps representation in the `dataset` property. // // We solve this by replacing all the `-`s with `_`s. We do that here, when we From 43c18e92ea974ad11b10f8da46d9261f56170803 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Sat, 21 Jan 2023 14:48:18 -0800 Subject: [PATCH 265/500] Remove relnote for #84022 due to revert #107133 --- RELEASES.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index 6acc8f3dfb4e6..6be38ecca2bc7 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -75,9 +75,6 @@ Compatibility Notes evaluation order, left-to-right.](https://github.com/rust-lang/rust/pull/103293/) Previously, it was "twisted" such that the _first_ expression dropped its temporaries _last_, after all of the other expressions dropped in order. -- [Proc-macro derives using inaccessible names from parent modules is now a hard error.](https://github.com/rust-lang/rust/pull/84022/) - This has been a warning since 1.29.0, and denied by default since 1.58.0. - (**TODO**: revert proposed in ) - [Underscore suffixes on string literals are now a hard error.](https://github.com/rust-lang/rust/pull/103914/) This has been a future-compatibility warning since 1.20.0. - [Stop passing `-export-dynamic` to `wasm-ld`.](https://github.com/rust-lang/rust/pull/105405/) From ddcb02d10a575f88a0599893525ded7337ed648e Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Sat, 21 Jan 2023 14:56:57 -0800 Subject: [PATCH 266/500] Move 0.5 rounding to a compat note --- RELEASES.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/RELEASES.md b/RELEASES.md index 6be38ecca2bc7..ea5a1a8729fcc 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -71,6 +71,9 @@ These APIs are now stable in const contexts: Compatibility Notes ------------------- +- [0.5 now rounds to 0 when formatted to 0 decimal places.](https://github.com/rust-lang/rust/pull/102935/) + This makes it consistent with the rest of floating point formatting that + rounds ties toward even digits. - [Chains of `&&` and `||` will now drop temporaries from their sub-expressions in evaluation order, left-to-right.](https://github.com/rust-lang/rust/pull/103293/) Previously, it was "twisted" such that the _first_ expression dropped its From b9be9e5fd1d2b7aace3875a77d1715bd9daa7e54 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Sat, 21 Jan 2023 15:08:48 -0800 Subject: [PATCH 267/500] Move the layout change to 1.67 compat notes --- RELEASES.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/RELEASES.md b/RELEASES.md index ea5a1a8729fcc..a63d4e8a043c6 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -71,6 +71,11 @@ These APIs are now stable in const contexts: Compatibility Notes ------------------- +- [The layout of `repr(Rust)` types now groups m\*2^n-sized fields with + equivalently aligned ones.](https://github.com/rust-lang/rust/pull/102750/) + This is intended to be an optimization, but it is also known to increase type + sizes in a few cases for the placement of enum tags. As a reminder, the layout + of `repr(Rust)` types is an implementation detail, subject to change. - [0.5 now rounds to 0 when formatted to 0 decimal places.](https://github.com/rust-lang/rust/pull/102935/) This makes it consistent with the rest of floating point formatting that rounds ties toward even digits. From 2fe58b9a6a8fca04b1c2493389b186778e05e68a Mon Sep 17 00:00:00 2001 From: Abdur-Rahmaan Janhangeer Date: Fri, 6 May 2022 11:25:51 +0400 Subject: [PATCH 268/500] fix maintainer validation message fix remove token check for maintainers fix: rm validate_maintainers function --- .../mingw-check/validate-toolstate.sh | 6 -- src/tools/publish_toolstate.py | 61 ------------------- 2 files changed, 67 deletions(-) diff --git a/src/ci/docker/host-x86_64/mingw-check/validate-toolstate.sh b/src/ci/docker/host-x86_64/mingw-check/validate-toolstate.sh index c6d728eb80dd0..0b06f5e3623e3 100755 --- a/src/ci/docker/host-x86_64/mingw-check/validate-toolstate.sh +++ b/src/ci/docker/host-x86_64/mingw-check/validate-toolstate.sh @@ -9,11 +9,5 @@ git clone --depth=1 https://github.com/rust-lang-nursery/rust-toolstate.git cd rust-toolstate python3 "../../src/tools/publish_toolstate.py" "$(git rev-parse HEAD)" \ "$(git log --format=%s -n1 HEAD)" "" "" -# Only check maintainers if this build is supposed to publish toolstate. -# Builds that are not supposed to publish don't have the access token. -if [ -n "${TOOLSTATE_PUBLISH+is_set}" ]; then - TOOLSTATE_VALIDATE_MAINTAINERS_REPO=rust-lang/rust python3 \ - "../../src/tools/publish_toolstate.py" -fi cd .. rm -rf rust-toolstate diff --git a/src/tools/publish_toolstate.py b/src/tools/publish_toolstate.py index 04a1d257bc094..db01b9cf25878 100755 --- a/src/tools/publish_toolstate.py +++ b/src/tools/publish_toolstate.py @@ -77,52 +77,6 @@ def load_json_from_response(resp): print("Refusing to decode " + str(type(content)) + " to str") return json.loads(content_str) -def validate_maintainers(repo, github_token): - # type: (str, str) -> None - '''Ensure all maintainers are assignable on a GitHub repo''' - next_link_re = re.compile(r'<([^>]+)>; rel="next"') - - # Load the list of assignable people in the GitHub repo - assignable = [] # type: typing.List[str] - url = 'https://api.github.com/repos/' \ - + '%s/collaborators?per_page=100' % repo # type: typing.Optional[str] - while url is not None: - response = urllib2.urlopen(urllib2.Request(url, headers={ - 'Authorization': 'token ' + github_token, - # Properly load nested teams. - 'Accept': 'application/vnd.github.hellcat-preview+json', - })) - assignable.extend(user['login'] for user in load_json_from_response(response)) - # Load the next page if available - url = None - link_header = response.headers.get('Link') - if link_header: - matches = next_link_re.match(link_header) - if matches is not None: - url = matches.group(1) - - errors = False - for tool, maintainers in MAINTAINERS.items(): - for maintainer in maintainers: - if maintainer not in assignable: - errors = True - print( - "error: %s maintainer @%s is not assignable in the %s repo" - % (tool, maintainer, repo), - ) - - if errors: - print() - print(" To be assignable, a person needs to be explicitly listed as a") - print(" collaborator in the repository settings. The simple way to") - print(" fix this is to ask someone with 'admin' privileges on the repo") - print(" to add the person or whole team as a collaborator with 'read'") - print(" privileges. Those privileges don't grant any extra permissions") - print(" so it's safe to apply them.") - print() - print("The build will fail due to this.") - exit(1) - def read_current_status(current_commit, path): # type: (str, str) -> typing.Mapping[str, typing.Any] @@ -295,21 +249,6 @@ def update_latest( try: if __name__ != '__main__': exit(0) - repo = os.environ.get('TOOLSTATE_VALIDATE_MAINTAINERS_REPO') - if repo: - github_token = os.environ.get('TOOLSTATE_REPO_ACCESS_TOKEN') - if github_token: - # FIXME: This is currently broken. Starting on 2021-09-15, GitHub - # seems to have changed it so that to list the collaborators - # requires admin permissions. I think this will probably just need - # to be removed since we are probably not going to use an admin - # token, and I don't see another way to do this. - print('maintainer validation disabled') - # validate_maintainers(repo, github_token) - else: - print('skipping toolstate maintainers validation since no GitHub token is present') - # When validating maintainers don't run the full script. - exit(0) cur_commit = sys.argv[1] cur_datetime = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') From d7f6564fdd05c9bb0168be0554626de2886f1314 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 3 Jul 2022 22:08:01 +0200 Subject: [PATCH 269/500] Encode AdtDef in the def-id loop. --- compiler/rustc_metadata/src/rmeta/encoder.rs | 141 ++++++------------- 1 file changed, 41 insertions(+), 100 deletions(-) diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index ab2ad79b876d4..772c99a07bc35 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -38,7 +38,6 @@ use rustc_span::symbol::{sym, Symbol}; use rustc_span::{ self, DebuggerVisualizerFile, ExternalSource, FileName, SourceFile, Span, SyntaxContext, }; -use rustc_target::abi::VariantIdx; use std::borrow::Borrow; use std::collections::hash_map::Entry; use std::hash::Hash; @@ -1178,8 +1177,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { record!(self.tables.super_predicates_of[def_id] <- self.tcx.super_predicates_of(def_id)); } if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind { - let params_in_repr = self.tcx.params_in_repr(def_id); - record!(self.tables.params_in_repr[def_id] <- params_in_repr); + self.encode_info_for_adt(def_id); } if should_encode_trait_impl_trait_tys(tcx, def_id) && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id) @@ -1199,9 +1197,38 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } } - fn encode_enum_variant_info(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) { + #[instrument(level = "trace", skip(self))] + fn encode_info_for_adt(&mut self, def_id: DefId) { + let tcx = self.tcx; + let adt_def = tcx.adt_def(def_id); + record!(self.tables.repr_options[def_id] <- adt_def.repr()); + + let params_in_repr = self.tcx.params_in_repr(def_id); + record!(self.tables.params_in_repr[def_id] <- params_in_repr); + + if adt_def.is_enum() { + record_array!(self.tables.children[def_id] <- iter::from_generator(|| + for variant in tcx.adt_def(def_id).variants() { + yield variant.def_id.index; + // Encode constructors which take a separate slot in value namespace. + if let Some(ctor_def_id) = variant.ctor_def_id() { + yield ctor_def_id.index; + } + } + )); + } + + // In some cases, along with the item itself, we also + // encode some sub-items. Usually we want some info from the item + // so it's easier to do that here then to wait until we would encounter + // normally in the visitor walk. + for variant in adt_def.variants().iter() { + self.encode_enum_variant_info(variant); + } + } + + fn encode_enum_variant_info(&mut self, variant: &ty::VariantDef) { let tcx = self.tcx; - let variant = &def.variant(index); let def_id = variant.def_id; debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); @@ -1218,27 +1245,14 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { f.did.index })); if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor { - // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`. - record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id)); - } - } - - fn encode_enum_variant_ctor(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) { - let variant = &def.variant(index); - let Some((ctor_kind, def_id)) = variant.ctor else { return }; - debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id); + debug!("EncodeContext::encode_enum_variant_ctor({:?})", ctor_def_id); - // FIXME(eddyb) encode only the `CtorKind` for constructors. - let data = VariantData { - discr: variant.discr, - ctor: Some((ctor_kind, def_id.index)), - is_non_exhaustive: variant.is_field_list_non_exhaustive(), - }; + self.tables.constness.set(ctor_def_id.index, hir::Constness::Const); - record!(self.tables.variant_data[def_id] <- data); - self.tables.constness.set(def_id.index, hir::Constness::Const); - if ctor_kind == CtorKind::Fn { - record!(self.tables.fn_sig[def_id] <- self.tcx.fn_sig(def_id)); + let fn_sig = tcx.fn_sig(ctor_def_id); + record!(self.tables.fn_sig[ctor_def_id] <- fn_sig); + // FIXME(eddyb) encode signature only for `ctor_def_id`. + record!(self.tables.fn_sig[def_id] <- fn_sig); } } @@ -1291,25 +1305,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } } - fn encode_struct_ctor(&mut self, adt_def: ty::AdtDef<'tcx>) { - let variant = adt_def.non_enum_variant(); - let Some((ctor_kind, def_id)) = variant.ctor else { return }; - debug!("EncodeContext::encode_struct_ctor({:?})", def_id); - - let data = VariantData { - discr: variant.discr, - ctor: Some((ctor_kind, def_id.index)), - is_non_exhaustive: variant.is_field_list_non_exhaustive(), - }; - - record!(self.tables.repr_options[def_id] <- adt_def.repr()); - record!(self.tables.variant_data[def_id] <- data); - self.tables.constness.set(def_id.index, hir::Constness::Const); - if ctor_kind == CtorKind::Fn { - record!(self.tables.fn_sig[def_id] <- self.tcx.fn_sig(def_id)); - } - } - fn encode_explicit_item_bounds(&mut self, def_id: DefId) { debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id); let bounds = self.tcx.explicit_item_bounds(def_id); @@ -1518,33 +1513,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { self.tables.is_type_alias_impl_trait.set(def_id.index, ()); } } - hir::ItemKind::Enum(..) => { - let adt_def = self.tcx.adt_def(def_id); - record!(self.tables.repr_options[def_id] <- adt_def.repr()); - } - hir::ItemKind::Struct(..) => { - let adt_def = self.tcx.adt_def(def_id); - record!(self.tables.repr_options[def_id] <- adt_def.repr()); - self.tables.constness.set(def_id.index, hir::Constness::Const); - - let variant = adt_def.non_enum_variant(); - record!(self.tables.variant_data[def_id] <- VariantData { - discr: variant.discr, - ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)), - is_non_exhaustive: variant.is_field_list_non_exhaustive(), - }); - } - hir::ItemKind::Union(..) => { - let adt_def = self.tcx.adt_def(def_id); - record!(self.tables.repr_options[def_id] <- adt_def.repr()); - - let variant = adt_def.non_enum_variant(); - record!(self.tables.variant_data[def_id] <- VariantData { - discr: variant.discr, - ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)), - is_non_exhaustive: variant.is_field_list_non_exhaustive(), - }); - } hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => { self.tables.impl_defaultness.set(def_id.index, *defaultness); self.tables.constness.set(def_id.index, *constness); @@ -1583,31 +1551,15 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } hir::ItemKind::Static(..) | hir::ItemKind::Const(..) + | hir::ItemKind::Enum(..) + | hir::ItemKind::Struct(..) + | hir::ItemKind::Union(..) | hir::ItemKind::ForeignMod { .. } | hir::ItemKind::GlobalAsm(..) | hir::ItemKind::TyAlias(..) => {} }; // FIXME(eddyb) there should be a nicer way to do this. match item.kind { - hir::ItemKind::Enum(..) => { - record_array!(self.tables.children[def_id] <- iter::from_generator(|| - for variant in tcx.adt_def(def_id).variants() { - yield variant.def_id.index; - // Encode constructors which take a separate slot in value namespace. - if let Some(ctor_def_id) = variant.ctor_def_id() { - yield ctor_def_id.index; - } - } - )) - } - hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { - record_array!(self.tables.children[def_id] <- - self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| { - assert!(f.did.is_local()); - f.did.index - }) - ) - } hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => { let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id); record_array!(self.tables.children[def_id] <- @@ -1635,17 +1587,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { // so it's easier to do that here then to wait until we would encounter // normally in the visitor walk. match item.kind { - hir::ItemKind::Enum(..) => { - let def = self.tcx.adt_def(item.owner_id.to_def_id()); - for (i, _) in def.variants().iter_enumerated() { - self.encode_enum_variant_info(def, i); - self.encode_enum_variant_ctor(def, i); - } - } - hir::ItemKind::Struct(..) => { - let def = self.tcx.adt_def(item.owner_id.to_def_id()); - self.encode_struct_ctor(def); - } hir::ItemKind::Impl { .. } => { for &trait_item_def_id in self.tcx.associated_item_def_ids(item.owner_id.to_def_id()).iter() From 6ecf30d67d7e82722ac7aff232378739e92f33e6 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 3 Jul 2022 22:53:57 +0200 Subject: [PATCH 270/500] Inline encode_enum_variant_info. --- compiler/rustc_metadata/src/rmeta/encoder.rs | 46 ++++++++------------ 1 file changed, 18 insertions(+), 28 deletions(-) diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 772c99a07bc35..6227d01bcfae9 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1223,36 +1223,26 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { // so it's easier to do that here then to wait until we would encounter // normally in the visitor walk. for variant in adt_def.variants().iter() { - self.encode_enum_variant_info(variant); - } - } - - fn encode_enum_variant_info(&mut self, variant: &ty::VariantDef) { - let tcx = self.tcx; - let def_id = variant.def_id; - debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); + let data = VariantData { + discr: variant.discr, + ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)), + is_non_exhaustive: variant.is_field_list_non_exhaustive(), + }; + record!(self.tables.variant_data[variant.def_id] <- data); - let data = VariantData { - discr: variant.discr, - ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)), - is_non_exhaustive: variant.is_field_list_non_exhaustive(), - }; + self.tables.constness.set(variant.def_id.index, hir::Constness::Const); + record_array!(self.tables.children[variant.def_id] <- variant.fields.iter().map(|f| { + assert!(f.did.is_local()); + f.did.index + })); - record!(self.tables.variant_data[def_id] <- data); - self.tables.constness.set(def_id.index, hir::Constness::Const); - record_array!(self.tables.children[def_id] <- variant.fields.iter().map(|f| { - assert!(f.did.is_local()); - f.did.index - })); - if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor { - debug!("EncodeContext::encode_enum_variant_ctor({:?})", ctor_def_id); - - self.tables.constness.set(ctor_def_id.index, hir::Constness::Const); - - let fn_sig = tcx.fn_sig(ctor_def_id); - record!(self.tables.fn_sig[ctor_def_id] <- fn_sig); - // FIXME(eddyb) encode signature only for `ctor_def_id`. - record!(self.tables.fn_sig[def_id] <- fn_sig); + if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor { + self.tables.constness.set(ctor_def_id.index, hir::Constness::Const); + let fn_sig = tcx.fn_sig(ctor_def_id); + record!(self.tables.fn_sig[ctor_def_id] <- fn_sig); + // FIXME only encode signature for ctor_def_id + record!(self.tables.fn_sig[variant.def_id] <- fn_sig); + } } } From 4d11206ee78cd53bfd104c6073f3c8169da8828d Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 22 Jan 2023 11:08:33 +0000 Subject: [PATCH 271/500] Tweak comments. --- compiler/rustc_metadata/src/rmeta/encoder.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 6227d01bcfae9..0dba9a32f9cee 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1216,12 +1216,13 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } } )); + } else { + // For non-enum, there is only one variant, and its def_id is the adt's. + debug_assert_eq!(adt_def.variants().len(), 1); + debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id); + // Therefore, the loop over variants will encode its fields as the adt's children. } - // In some cases, along with the item itself, we also - // encode some sub-items. Usually we want some info from the item - // so it's easier to do that here then to wait until we would encounter - // normally in the visitor walk. for variant in adt_def.variants().iter() { let data = VariantData { discr: variant.discr, From 8874edd238761206cf732740b5b90558ad7f73e5 Mon Sep 17 00:00:00 2001 From: Samuel Moelius <35515885+smoelius@users.noreply.github.com> Date: Sun, 22 Jan 2023 06:41:59 -0500 Subject: [PATCH 272/500] Update main.rs --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 7a78b32620d0b..82147eba33f07 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,7 +28,7 @@ with: -D --deny OPT Set lint denied -F --forbid OPT Set lint forbidden -You can use tool lints to allow or deny lints from your code, eg.: +You can use tool lints to allow or deny lints from your code, e.g.: #[allow(clippy::needless_lifetimes)] "#; From f72e17f8fbcc96b103bb5c9b7b63e2f0e21e5f75 Mon Sep 17 00:00:00 2001 From: Konrad Borowski Date: Sun, 22 Jan 2023 13:05:47 +0100 Subject: [PATCH 273/500] Remove dependency on slice_internals feature in rustc_ast --- Cargo.lock | 1 + compiler/rustc_ast/Cargo.toml | 1 + compiler/rustc_ast/src/lib.rs | 1 - compiler/rustc_ast/src/util/unicode.rs | 2 +- 4 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index da47b08c7df55..6251a4ca5162a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3633,6 +3633,7 @@ name = "rustc_ast" version = "0.0.0" dependencies = [ "bitflags", + "memchr", "rustc_data_structures", "rustc_index", "rustc_lexer", diff --git a/compiler/rustc_ast/Cargo.toml b/compiler/rustc_ast/Cargo.toml index 9253b7e6891a2..10d7fa1db605a 100644 --- a/compiler/rustc_ast/Cargo.toml +++ b/compiler/rustc_ast/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" [dependencies] bitflags = "1.2.1" +memchr = "2.5.0" rustc_data_structures = { path = "../rustc_data_structures" } rustc_index = { path = "../rustc_index" } rustc_lexer = { path = "../rustc_lexer" } diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs index 9c1dfeb1a6142..90c18de966008 100644 --- a/compiler/rustc_ast/src/lib.rs +++ b/compiler/rustc_ast/src/lib.rs @@ -16,7 +16,6 @@ #![feature(let_chains)] #![feature(min_specialization)] #![feature(negative_impls)] -#![feature(slice_internals)] #![feature(stmt_expr_attributes)] #![recursion_limit = "256"] #![deny(rustc::untranslatable_diagnostic)] diff --git a/compiler/rustc_ast/src/util/unicode.rs b/compiler/rustc_ast/src/util/unicode.rs index 0eae791b25e1c..6f57d66b2273a 100644 --- a/compiler/rustc_ast/src/util/unicode.rs +++ b/compiler/rustc_ast/src/util/unicode.rs @@ -17,7 +17,7 @@ pub fn contains_text_flow_control_chars(s: &str) -> bool { // U+2069 - E2 81 A9 let mut bytes = s.as_bytes(); loop { - match core::slice::memchr::memchr(0xE2, bytes) { + match memchr::memchr(0xE2, bytes) { Some(idx) => { // bytes are valid UTF-8 -> E2 must be followed by two bytes let ch = &bytes[idx..idx + 3]; From 77133370ce04666af364c218ba2b2c7ccfb60065 Mon Sep 17 00:00:00 2001 From: Lenko Donchev Date: Thu, 12 Jan 2023 05:56:56 -0600 Subject: [PATCH 274/500] Print why a test was ignored if it's the only test specified. --- library/test/src/console.rs | 7 ++++++- library/test/src/formatters/terse.rs | 9 +++++++++ library/test/src/tests.rs | 1 + 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/library/test/src/console.rs b/library/test/src/console.rs index 24cbe035f2fa7..1ee68c8540bcc 100644 --- a/library/test/src/console.rs +++ b/library/test/src/console.rs @@ -53,6 +53,7 @@ pub struct ConsoleTestState { pub metrics: MetricMap, pub failures: Vec<(TestDesc, Vec)>, pub not_failures: Vec<(TestDesc, Vec)>, + pub ignores: Vec<(TestDesc, Vec)>, pub time_failures: Vec<(TestDesc, Vec)>, pub options: Options, } @@ -76,6 +77,7 @@ impl ConsoleTestState { metrics: MetricMap::new(), failures: Vec::new(), not_failures: Vec::new(), + ignores: Vec::new(), time_failures: Vec::new(), options: opts.options, }) @@ -194,7 +196,10 @@ fn handle_test_result(st: &mut ConsoleTestState, completed_test: CompletedTest) st.passed += 1; st.not_failures.push((test, stdout)); } - TestResult::TrIgnored => st.ignored += 1, + TestResult::TrIgnored => { + st.ignored += 1; + st.ignores.push((test, stdout)); + } TestResult::TrBench(bs) => { st.metrics.insert_metric( test.name.as_slice(), diff --git a/library/test/src/formatters/terse.rs b/library/test/src/formatters/terse.rs index 0837ab1690513..a431acfbc2753 100644 --- a/library/test/src/formatters/terse.rs +++ b/library/test/src/formatters/terse.rs @@ -254,6 +254,15 @@ impl OutputFormatter for TerseFormatter { self.write_plain("\n\n")?; + // Custom handling of cases where there is only 1 test to execute and that test was ignored. + // We want to show more detailed information(why was the test ignored) for investigation purposes. + if self.total_test_count == 1 && state.ignores.len() == 1 { + let test_desc = &state.ignores[0].0; + if let Some(im) = test_desc.ignore_message { + self.write_plain(format!("test: {}, ignore_message: {}\n\n", test_desc.name, im))?; + } + } + Ok(success) } } diff --git a/library/test/src/tests.rs b/library/test/src/tests.rs index 3a0260f86cf5d..44776fb0a316d 100644 --- a/library/test/src/tests.rs +++ b/library/test/src/tests.rs @@ -790,6 +790,7 @@ fn should_sort_failures_before_printing_them() { failures: vec![(test_b, Vec::new()), (test_a, Vec::new())], options: Options::new(), not_failures: Vec::new(), + ignores: Vec::new(), time_failures: Vec::new(), }; From 96f8f995891ad1f7d514a615d9494cf7f56ea0a3 Mon Sep 17 00:00:00 2001 From: Erik Desjardins Date: Sun, 22 Jan 2023 21:02:07 -0500 Subject: [PATCH 275/500] rustc_abi: remove Primitive::{is_float,is_int} there were fixmes for this already i am about to remove is_ptr (since callers need to properly distinguish between pointers in different address spaces), so might as well do this at the same time --- compiler/rustc_abi/src/lib.rs | 12 ------------ compiler/rustc_target/src/abi/call/sparc64.rs | 4 ++-- compiler/rustc_target/src/abi/mod.rs | 2 +- 3 files changed, 3 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index f4cb459f32fdd..b9ec7d2ee74bc 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -887,18 +887,6 @@ impl Primitive { } } - // FIXME(eddyb) remove, it's trivial thanks to `matches!`. - #[inline] - pub fn is_float(self) -> bool { - matches!(self, F32 | F64) - } - - // FIXME(eddyb) remove, it's completely unused. - #[inline] - pub fn is_int(self) -> bool { - matches!(self, Int(..)) - } - #[inline] pub fn is_ptr(self) -> bool { matches!(self, Pointer) diff --git a/compiler/rustc_target/src/abi/call/sparc64.rs b/compiler/rustc_target/src/abi/call/sparc64.rs index c8b6ac5ae25b2..0c7a4f324612e 100644 --- a/compiler/rustc_target/src/abi/call/sparc64.rs +++ b/compiler/rustc_target/src/abi/call/sparc64.rs @@ -20,7 +20,7 @@ where { let dl = cx.data_layout(); - if !scalar.primitive().is_float() { + if !matches!(scalar.primitive(), abi::F32 | abi::F64) { return data; } @@ -87,7 +87,7 @@ where _ => {} } - if (offset.bytes() % 4) != 0 && scalar2.primitive().is_float() { + if (offset.bytes() % 4) != 0 && matches!(scalar2.primitive(), abi::F32 | abi::F64) { offset += Size::from_bytes(4 - (offset.bytes() % 4)); } data = arg_scalar(cx, scalar2, offset, data); diff --git a/compiler/rustc_target/src/abi/mod.rs b/compiler/rustc_target/src/abi/mod.rs index 88a0a1f8ecfde..39761baf1bc29 100644 --- a/compiler/rustc_target/src/abi/mod.rs +++ b/compiler/rustc_target/src/abi/mod.rs @@ -129,7 +129,7 @@ impl<'a, Ty> TyAndLayout<'a, Ty> { C: HasDataLayout, { match self.abi { - Abi::Scalar(scalar) => scalar.primitive().is_float(), + Abi::Scalar(scalar) => matches!(scalar.primitive(), F32 | F64), Abi::Aggregate { .. } => { if self.fields.count() == 1 && self.fields.offset(0).bytes() == 0 { self.field(cx, 0).is_single_fp_element(cx) From 009192b01bd88a7bb6c1948d1f47dd598af0bfd9 Mon Sep 17 00:00:00 2001 From: Erik Desjardins Date: Sun, 22 Jan 2023 23:03:58 -0500 Subject: [PATCH 276/500] abi: add `AddressSpace` field to `Primitive::Pointer` ...and remove it from `PointeeInfo`, which isn't meant for this. There are still various places (marked with FIXMEs) that assume all pointers have the same size and alignment. Fixing this requires parsing non-default address spaces in the data layout string, which will be done in a followup. --- compiler/rustc_abi/src/lib.rs | 24 +- .../rustc_codegen_cranelift/src/common.rs | 3 +- compiler/rustc_codegen_gcc/src/builder.rs | 2 +- compiler/rustc_codegen_gcc/src/common.rs | 2 +- compiler/rustc_codegen_gcc/src/consts.rs | 16 +- compiler/rustc_codegen_gcc/src/type_of.rs | 4 +- compiler/rustc_codegen_llvm/src/asm.rs | 13 +- compiler/rustc_codegen_llvm/src/builder.rs | 2 +- compiler/rustc_codegen_llvm/src/common.rs | 4 +- compiler/rustc_codegen_llvm/src/consts.rs | 2 +- .../src/debuginfo/metadata/enums/mod.rs | 3 +- compiler/rustc_codegen_llvm/src/intrinsic.rs | 2 +- compiler/rustc_codegen_llvm/src/type_of.rs | 15 +- compiler/rustc_codegen_ssa/src/mir/block.rs | 4 +- compiler/rustc_codegen_ssa/src/mir/place.rs | 17 +- .../rustc_const_eval/src/interpret/operand.rs | 6 +- compiler/rustc_hir_typeck/src/intrinsicck.rs | 3 +- compiler/rustc_middle/src/ty/layout.rs | 222 +++++++++--------- .../rustc_target/src/abi/call/loongarch.rs | 2 +- compiler/rustc_target/src/abi/call/mod.rs | 2 +- compiler/rustc_target/src/abi/call/riscv.rs | 2 +- compiler/rustc_target/src/abi/call/sparc64.rs | 2 +- compiler/rustc_target/src/abi/call/x86_64.rs | 2 +- compiler/rustc_ty_utils/src/abi.rs | 4 +- compiler/rustc_ty_utils/src/layout.rs | 8 +- tests/codegen/avr/avr-func-addrspace.rs | 25 ++ 26 files changed, 218 insertions(+), 173 deletions(-) diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index b9ec7d2ee74bc..fe65ad9c6cb0e 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -267,6 +267,9 @@ impl TargetDataLayout { ["a", ref a @ ..] => dl.aggregate_align = align(a, "a")?, ["f32", ref a @ ..] => dl.f32_align = align(a, "f32")?, ["f64", ref a @ ..] => dl.f64_align = align(a, "f64")?, + // FIXME(erikdesjardins): we should be parsing nonzero address spaces + // this will require replacing TargetDataLayout::{pointer_size,pointer_align} + // with e.g. `fn pointer_size_in(AddressSpace)` [p @ "p", s, ref a @ ..] | [p @ "p0", s, ref a @ ..] => { dl.pointer_size = size(s, p)?; dl.pointer_align = align(a, p)?; @@ -861,7 +864,7 @@ pub enum Primitive { Int(Integer, bool), F32, F64, - Pointer, + Pointer(AddressSpace), } impl Primitive { @@ -872,7 +875,10 @@ impl Primitive { Int(i, _) => i.size(), F32 => Size::from_bits(32), F64 => Size::from_bits(64), - Pointer => dl.pointer_size, + // FIXME(erikdesjardins): ignoring address space is technically wrong, pointers in + // different address spaces can have different sizes + // (but TargetDataLayout doesn't currently parse that part of the DL string) + Pointer(_) => dl.pointer_size, } } @@ -883,14 +889,12 @@ impl Primitive { Int(i, _) => i.align(dl), F32 => dl.f32_align, F64 => dl.f64_align, - Pointer => dl.pointer_align, + // FIXME(erikdesjardins): ignoring address space is technically wrong, pointers in + // different address spaces can have different alignments + // (but TargetDataLayout doesn't currently parse that part of the DL string) + Pointer(_) => dl.pointer_align, } } - - #[inline] - pub fn is_ptr(self) -> bool { - matches!(self, Pointer) - } } /// Inclusive wrap-around range of valid values, that is, if @@ -1176,7 +1180,8 @@ impl FieldsShape { /// An identifier that specifies the address space that some operation /// should operate on. Special address spaces have an effect on code generation, /// depending on the target and the address spaces it implements. -#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "nightly", derive(HashStable_Generic))] pub struct AddressSpace(pub u32); impl AddressSpace { @@ -1456,7 +1461,6 @@ pub struct PointeeInfo { pub size: Size, pub align: Align, pub safe: Option, - pub address_space: AddressSpace, } /// Used in `might_permit_raw_init` to indicate the kind of initialisation diff --git a/compiler/rustc_codegen_cranelift/src/common.rs b/compiler/rustc_codegen_cranelift/src/common.rs index 2dcd42fbd8f43..63ed10cdfcc59 100644 --- a/compiler/rustc_codegen_cranelift/src/common.rs +++ b/compiler/rustc_codegen_cranelift/src/common.rs @@ -35,7 +35,8 @@ pub(crate) fn scalar_to_clif_type(tcx: TyCtxt<'_>, scalar: Scalar) -> Type { }, Primitive::F32 => types::F32, Primitive::F64 => types::F64, - Primitive::Pointer => pointer_ty(tcx), + // FIXME(erikdesjardins): handle non-default addrspace ptr sizes + Primitive::Pointer(_) => pointer_ty(tcx), } } diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index a92242b2615c1..e88c12716ecd3 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -709,7 +709,7 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { bx.range_metadata(load, vr); } } - abi::Pointer if vr.start < vr.end && !vr.contains(0) => { + abi::Pointer(_) if vr.start < vr.end && !vr.contains(0) => { bx.nonnull_metadata(load); } _ => {} diff --git a/compiler/rustc_codegen_gcc/src/common.rs b/compiler/rustc_codegen_gcc/src/common.rs index 0afc56b4494d3..c939da9cec3c2 100644 --- a/compiler/rustc_codegen_gcc/src/common.rs +++ b/compiler/rustc_codegen_gcc/src/common.rs @@ -211,7 +211,7 @@ impl<'gcc, 'tcx> ConstMethods<'tcx> for CodegenCx<'gcc, 'tcx> { let base_addr = self.const_bitcast(base_addr, self.usize_type); let offset = self.context.new_rvalue_from_long(self.usize_type, offset.bytes() as i64); let ptr = self.const_bitcast(base_addr + offset, ptr_type); - if layout.primitive() != Pointer { + if !matches!(layout.primitive(), Pointer(_)) { self.const_bitcast(ptr.dereference(None).to_rvalue(), ty) } else { diff --git a/compiler/rustc_codegen_gcc/src/consts.rs b/compiler/rustc_codegen_gcc/src/consts.rs index ea8ab76114604..ba64b1f638942 100644 --- a/compiler/rustc_codegen_gcc/src/consts.rs +++ b/compiler/rustc_codegen_gcc/src/consts.rs @@ -7,9 +7,9 @@ use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs} use rustc_middle::mir::mono::MonoItem; use rustc_middle::ty::{self, Instance, Ty}; use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::mir::interpret::{self, ConstAllocation, ErrorHandled, Scalar as InterpScalar, read_target_uint}; +use rustc_middle::mir::interpret::{self, ConstAllocation, ErrorHandled, GlobalAlloc, Scalar as InterpScalar, read_target_uint}; use rustc_span::def_id::DefId; -use rustc_target::abi::{self, Align, HasDataLayout, Primitive, Size, WrappingRange}; +use rustc_target::abi::{self, AddressSpace, Align, HasDataLayout, Primitive, Size, WrappingRange}; use crate::base; use crate::context::CodegenCx; @@ -322,13 +322,21 @@ pub fn const_alloc_to_gcc<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, alloc: ConstAl ) .expect("const_alloc_to_llvm: could not read relocation pointer") as u64; + + let address_space = match cx.tcx.global_alloc(alloc_id) { + GlobalAlloc::Function(..) => cx.data_layout().instruction_address_space, + GlobalAlloc::Static(..) | GlobalAlloc::Memory(..) | GlobalAlloc::VTable(..) => { + AddressSpace::DATA + } + }; + llvals.push(cx.scalar_to_backend( InterpScalar::from_pointer( interpret::Pointer::new(alloc_id, Size::from_bytes(ptr_offset)), &cx.tcx, ), - abi::Scalar::Initialized { value: Primitive::Pointer, valid_range: WrappingRange::full(dl.pointer_size) }, - cx.type_i8p(), + abi::Scalar::Initialized { value: Primitive::Pointer(address_space), valid_range: WrappingRange::full(dl.pointer_size) }, + cx.type_i8p_ext(address_space), )); next_offset = offset + pointer_size; } diff --git a/compiler/rustc_codegen_gcc/src/type_of.rs b/compiler/rustc_codegen_gcc/src/type_of.rs index 524d10fb5e24d..1326af670cde4 100644 --- a/compiler/rustc_codegen_gcc/src/type_of.rs +++ b/compiler/rustc_codegen_gcc/src/type_of.rs @@ -253,7 +253,7 @@ impl<'tcx> LayoutGccExt<'tcx> for TyAndLayout<'tcx> { Int(i, false) => cx.type_from_unsigned_integer(i), F32 => cx.type_f32(), F64 => cx.type_f64(), - Pointer => { + Pointer(address_space) => { // If we know the alignment, pick something better than i8. let pointee = if let Some(pointee) = self.pointee_info_at(cx, offset) { @@ -262,7 +262,7 @@ impl<'tcx> LayoutGccExt<'tcx> for TyAndLayout<'tcx> { else { cx.type_i8() }; - cx.type_ptr_to(pointee) + cx.type_ptr_to_ext(pointee, address_space) } } } diff --git a/compiler/rustc_codegen_llvm/src/asm.rs b/compiler/rustc_codegen_llvm/src/asm.rs index 52c8b51796c0b..d9f8170a3cffa 100644 --- a/compiler/rustc_codegen_llvm/src/asm.rs +++ b/compiler/rustc_codegen_llvm/src/asm.rs @@ -849,6 +849,7 @@ fn dummy_output_type<'ll>(cx: &CodegenCx<'ll, '_>, reg: InlineAsmRegClass) -> &' /// Helper function to get the LLVM type for a Scalar. Pointers are returned as /// the equivalent integer type. fn llvm_asm_scalar_type<'ll>(cx: &CodegenCx<'ll, '_>, scalar: Scalar) -> &'ll Type { + let dl = &cx.tcx.data_layout; match scalar.primitive() { Primitive::Int(Integer::I8, _) => cx.type_i8(), Primitive::Int(Integer::I16, _) => cx.type_i16(), @@ -856,7 +857,8 @@ fn llvm_asm_scalar_type<'ll>(cx: &CodegenCx<'ll, '_>, scalar: Scalar) -> &'ll Ty Primitive::Int(Integer::I64, _) => cx.type_i64(), Primitive::F32 => cx.type_f32(), Primitive::F64 => cx.type_f64(), - Primitive::Pointer => cx.type_isize(), + // FIXME(erikdesjardins): handle non-default addrspace ptr sizes + Primitive::Pointer(_) => cx.type_from_integer(dl.ptr_sized_integer()), _ => unreachable!(), } } @@ -868,6 +870,7 @@ fn llvm_fixup_input<'ll, 'tcx>( reg: InlineAsmRegClass, layout: &TyAndLayout<'tcx>, ) -> &'ll Value { + let dl = &bx.tcx.data_layout; match (reg, layout.abi) { (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => { if let Primitive::Int(Integer::I8, _) = s.primitive() { @@ -881,8 +884,10 @@ fn llvm_fixup_input<'ll, 'tcx>( let elem_ty = llvm_asm_scalar_type(bx.cx, s); let count = 16 / layout.size.bytes(); let vec_ty = bx.cx.type_vector(elem_ty, count); - if let Primitive::Pointer = s.primitive() { - value = bx.ptrtoint(value, bx.cx.type_isize()); + // FIXME(erikdesjardins): handle non-default addrspace ptr sizes + if let Primitive::Pointer(_) = s.primitive() { + let t = bx.type_from_integer(dl.ptr_sized_integer()); + value = bx.ptrtoint(value, t); } bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0)) } @@ -958,7 +963,7 @@ fn llvm_fixup_output<'ll, 'tcx>( } (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => { value = bx.extract_element(value, bx.const_i32(0)); - if let Primitive::Pointer = s.primitive() { + if let Primitive::Pointer(_) = s.primitive() { value = bx.inttoptr(value, layout.llvm_type(bx.cx)); } value diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 5e98deae48aa2..0f33b98548984 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -511,7 +511,7 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { bx.range_metadata(load, scalar.valid_range(bx)); } } - abi::Pointer => { + abi::Pointer(_) => { if !scalar.valid_range(bx).contains(0) { bx.nonnull_metadata(load); } diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index acee9134fb96e..edb1c160626ea 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -236,7 +236,7 @@ impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> { Scalar::Int(int) => { let data = int.assert_bits(layout.size(self)); let llval = self.const_uint_big(self.type_ix(bitsize), data); - if layout.primitive() == Pointer { + if matches!(layout.primitive(), Pointer(_)) { unsafe { llvm::LLVMConstIntToPtr(llval, llty) } } else { self.const_bitcast(llval, llty) @@ -284,7 +284,7 @@ impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> { 1, ) }; - if layout.primitive() != Pointer { + if !matches!(layout.primitive(), Pointer(_)) { unsafe { llvm::LLVMConstPtrToInt(llval, llty) } } else { self.const_bitcast(llval, llty) diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 16467b614feaf..2f630b32ffe06 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -111,7 +111,7 @@ pub fn const_alloc_to_llvm<'ll>(cx: &CodegenCx<'ll, '_>, alloc: ConstAllocation< &cx.tcx, ), Scalar::Initialized { - value: Primitive::Pointer, + value: Primitive::Pointer(address_space), valid_range: WrappingRange::full(dl.pointer_size), }, cx.type_i8p_ext(address_space), diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs index 564ab351bd41f..54e850f25996b 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs @@ -122,7 +122,8 @@ fn tag_base_type<'ll, 'tcx>( Primitive::Int(t, _) => t, Primitive::F32 => Integer::I32, Primitive::F64 => Integer::I64, - Primitive::Pointer => { + // FIXME(erikdesjardins): handle non-default addrspace ptr sizes + Primitive::Pointer(_) => { // If the niche is the NULL value of a reference, then `discr_enum_ty` will be // a RawPtr. CodeView doesn't know what to do with enums whose base type is a // pointer so we fix this up to just be `usize`. diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index a6a75eff9a36d..dd89c4c59c14d 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -149,7 +149,7 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> { emit_va_arg(self, args[0], ret_ty) } } - Primitive::F64 | Primitive::Pointer => { + Primitive::F64 | Primitive::Pointer(_) => { emit_va_arg(self, args[0], ret_ty) } // `va_arg` should never be used with the return type f32. diff --git a/compiler/rustc_codegen_llvm/src/type_of.rs b/compiler/rustc_codegen_llvm/src/type_of.rs index 75cd5df972316..c73d233b767a4 100644 --- a/compiler/rustc_codegen_llvm/src/type_of.rs +++ b/compiler/rustc_codegen_llvm/src/type_of.rs @@ -7,7 +7,7 @@ use rustc_middle::bug; use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout}; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; use rustc_middle::ty::{self, Ty, TypeVisitable}; -use rustc_target::abi::{Abi, AddressSpace, Align, FieldsShape}; +use rustc_target::abi::{Abi, Align, FieldsShape}; use rustc_target::abi::{Int, Pointer, F32, F64}; use rustc_target::abi::{PointeeInfo, Scalar, Size, TyAbiInterface, Variants}; use smallvec::{smallvec, SmallVec}; @@ -312,14 +312,13 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> { Int(i, _) => cx.type_from_integer(i), F32 => cx.type_f32(), F64 => cx.type_f64(), - Pointer => { + Pointer(address_space) => { // If we know the alignment, pick something better than i8. - let (pointee, address_space) = - if let Some(pointee) = self.pointee_info_at(cx, offset) { - (cx.type_pointee_for_align(pointee.align), pointee.address_space) - } else { - (cx.type_i8(), AddressSpace::DATA) - }; + let pointee = if let Some(pointee) = self.pointee_info_at(cx, offset) { + cx.type_pointee_for_align(pointee.align) + } else { + cx.type_i8() + }; cx.type_ptr_to_ext(pointee, address_space) } } diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 978aff511bfa7..e2106f8b5c570 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -1801,8 +1801,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { match (src.layout.abi, dst.layout.abi) { (abi::Abi::Scalar(src_scalar), abi::Abi::Scalar(dst_scalar)) => { // HACK(eddyb) LLVM doesn't like `bitcast`s between pointers and non-pointers. - let src_is_ptr = src_scalar.primitive() == abi::Pointer; - let dst_is_ptr = dst_scalar.primitive() == abi::Pointer; + let src_is_ptr = matches!(src_scalar.primitive(), abi::Pointer(_)); + let dst_is_ptr = matches!(dst_scalar.primitive(), abi::Pointer(_)); if src_is_ptr == dst_is_ptr { assert_eq!(src.layout.size, dst.layout.size); diff --git a/compiler/rustc_codegen_ssa/src/mir/place.rs b/compiler/rustc_codegen_ssa/src/mir/place.rs index fbe30154a7c8d..cf02f59f67b97 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -9,7 +9,7 @@ use rustc_middle::mir; use rustc_middle::mir::tcx::PlaceTy; use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout}; use rustc_middle::ty::{self, Ty}; -use rustc_target::abi::{Abi, Align, FieldsShape, Int, TagEncoding}; +use rustc_target::abi::{Abi, Align, FieldsShape, Int, Pointer, TagEncoding}; use rustc_target::abi::{VariantIdx, Variants}; #[derive(Copy, Clone, Debug)] @@ -209,6 +209,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { bx: &mut Bx, cast_to: Ty<'tcx>, ) -> V { + let dl = &bx.tcx().data_layout; let cast_to_layout = bx.cx().layout_of(cast_to); let cast_to_size = cast_to_layout.layout.size(); let cast_to = bx.cx().immediate_backend_type(cast_to_layout); @@ -250,12 +251,14 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => { // Cast to an integer so we don't have to treat a pointer as a // special case. - let (tag, tag_llty) = if tag_scalar.primitive().is_ptr() { - let t = bx.type_isize(); - let tag = bx.ptrtoint(tag_imm, t); - (tag, t) - } else { - (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)) + let (tag, tag_llty) = match tag_scalar.primitive() { + // FIXME(erikdesjardins): handle non-default addrspace ptr sizes + Pointer(_) => { + let t = bx.type_from_integer(dl.ptr_sized_integer()); + let tag = bx.ptrtoint(tag_imm, t); + (tag, t) + } + _ => (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)), }; let tag_size = tag_scalar.size(bx.cx()); diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index befc0928f3deb..a1b3985dce4e6 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -319,7 +319,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { assert_eq!(size, mplace.layout.size, "abi::Scalar size does not match layout size"); let scalar = alloc.read_scalar( alloc_range(Size::ZERO, size), - /*read_provenance*/ s.is_ptr(), + /*read_provenance*/ matches!(s, abi::Pointer(_)), )?; Some(ImmTy { imm: scalar.into(), layout: mplace.layout }) } @@ -335,11 +335,11 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { assert!(b_offset.bytes() > 0); // in `operand_field` we use the offset to tell apart the fields let a_val = alloc.read_scalar( alloc_range(Size::ZERO, a_size), - /*read_provenance*/ a.is_ptr(), + /*read_provenance*/ matches!(a, abi::Pointer(_)), )?; let b_val = alloc.read_scalar( alloc_range(b_offset, b_size), - /*read_provenance*/ b.is_ptr(), + /*read_provenance*/ matches!(b, abi::Pointer(_)), )?; Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout }) } diff --git a/compiler/rustc_hir_typeck/src/intrinsicck.rs b/compiler/rustc_hir_typeck/src/intrinsicck.rs index 3c873024c924f..2c76582f2ec8f 100644 --- a/compiler/rustc_hir_typeck/src/intrinsicck.rs +++ b/compiler/rustc_hir_typeck/src/intrinsicck.rs @@ -38,6 +38,7 @@ fn unpack_option_like<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn check_transmute(&self, from: Ty<'tcx>, to: Ty<'tcx>, hir_id: HirId) { let tcx = self.tcx; + let dl = &tcx.data_layout; let span = tcx.hir().span(hir_id); let normalize = |ty| { let ty = self.resolve_vars_if_possible(ty); @@ -69,7 +70,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Special-case transmuting from `typeof(function)` and // `Option` to present a clearer error. let from = unpack_option_like(tcx, from); - if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (from.kind(), sk_to) && size_to == Pointer.size(&tcx) { + if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (from.kind(), sk_to) && size_to == Pointer(dl.instruction_address_space).size(&tcx) { struct_span_err!(tcx.sess, span, E0591, "can't transmute zero-sized type") .note(&format!("source type: {from}")) .note(&format!("target type: {to}")) diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index dfd016569c27a..66b9d96e69577 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -128,7 +128,8 @@ impl PrimitiveExt for Primitive { Int(i, signed) => i.to_ty(tcx, signed), F32 => tcx.types.f32, F64 => tcx.types.f64, - Pointer => tcx.mk_mut_ptr(tcx.mk_unit()), + // FIXME(erikdesjardins): handle non-default addrspace ptr sizes + Pointer(_) => tcx.mk_mut_ptr(tcx.mk_unit()), } } @@ -138,7 +139,11 @@ impl PrimitiveExt for Primitive { fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { match *self { Int(i, signed) => i.to_ty(tcx, signed), - Pointer => tcx.types.usize, + // FIXME(erikdesjardins): handle non-default addrspace ptr sizes + Pointer(_) => { + let signed = false; + tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed) + } F32 | F64 => bug!("floats do not have an int type"), } } @@ -812,132 +817,125 @@ where let tcx = cx.tcx(); let param_env = cx.param_env(); - let addr_space_of_ty = |ty: Ty<'tcx>| { - if ty.is_fn() { cx.data_layout().instruction_address_space } else { AddressSpace::DATA } - }; - - let pointee_info = match *this.ty.kind() { - ty::RawPtr(mt) if offset.bytes() == 0 => { - tcx.layout_of(param_env.and(mt.ty)).ok().map(|layout| PointeeInfo { - size: layout.size, - align: layout.align.abi, - safe: None, - address_space: addr_space_of_ty(mt.ty), - }) - } - ty::FnPtr(fn_sig) if offset.bytes() == 0 => { - tcx.layout_of(param_env.and(tcx.mk_fn_ptr(fn_sig))).ok().map(|layout| PointeeInfo { - size: layout.size, - align: layout.align.abi, - safe: None, - address_space: cx.data_layout().instruction_address_space, - }) - } - ty::Ref(_, ty, mt) if offset.bytes() == 0 => { - let address_space = addr_space_of_ty(ty); - let kind = if tcx.sess.opts.optimize == OptLevel::No { - // Use conservative pointer kind if not optimizing. This saves us the - // Freeze/Unpin queries, and can save time in the codegen backend (noalias - // attributes in LLVM have compile-time cost even in unoptimized builds). - PointerKind::SharedMutable - } else { - match mt { - hir::Mutability::Not => { - if ty.is_freeze(tcx, cx.param_env()) { - PointerKind::Frozen - } else { - PointerKind::SharedMutable + let pointee_info = + match *this.ty.kind() { + ty::RawPtr(mt) if offset.bytes() == 0 => { + tcx.layout_of(param_env.and(mt.ty)).ok().map(|layout| PointeeInfo { + size: layout.size, + align: layout.align.abi, + safe: None, + }) + } + ty::FnPtr(fn_sig) if offset.bytes() == 0 => { + tcx.layout_of(param_env.and(tcx.mk_fn_ptr(fn_sig))).ok().map(|layout| { + PointeeInfo { size: layout.size, align: layout.align.abi, safe: None } + }) + } + ty::Ref(_, ty, mt) if offset.bytes() == 0 => { + let kind = if tcx.sess.opts.optimize == OptLevel::No { + // Use conservative pointer kind if not optimizing. This saves us the + // Freeze/Unpin queries, and can save time in the codegen backend (noalias + // attributes in LLVM have compile-time cost even in unoptimized builds). + PointerKind::SharedMutable + } else { + match mt { + hir::Mutability::Not => { + if ty.is_freeze(tcx, cx.param_env()) { + PointerKind::Frozen + } else { + PointerKind::SharedMutable + } } - } - hir::Mutability::Mut => { - // References to self-referential structures should not be considered - // noalias, as another pointer to the structure can be obtained, that - // is not based-on the original reference. We consider all !Unpin - // types to be potentially self-referential here. - if ty.is_unpin(tcx, cx.param_env()) { - PointerKind::UniqueBorrowed - } else { - PointerKind::UniqueBorrowedPinned + hir::Mutability::Mut => { + // References to self-referential structures should not be considered + // noalias, as another pointer to the structure can be obtained, that + // is not based-on the original reference. We consider all !Unpin + // types to be potentially self-referential here. + if ty.is_unpin(tcx, cx.param_env()) { + PointerKind::UniqueBorrowed + } else { + PointerKind::UniqueBorrowedPinned + } } } - } - }; + }; - tcx.layout_of(param_env.and(ty)).ok().map(|layout| PointeeInfo { - size: layout.size, - align: layout.align.abi, - safe: Some(kind), - address_space, - }) - } + tcx.layout_of(param_env.and(ty)).ok().map(|layout| PointeeInfo { + size: layout.size, + align: layout.align.abi, + safe: Some(kind), + }) + } - _ => { - let mut data_variant = match this.variants { - // Within the discriminant field, only the niche itself is - // always initialized, so we only check for a pointer at its - // offset. - // - // If the niche is a pointer, it's either valid (according - // to its type), or null (which the niche field's scalar - // validity range encodes). This allows using - // `dereferenceable_or_null` for e.g., `Option<&T>`, and - // this will continue to work as long as we don't start - // using more niches than just null (e.g., the first page of - // the address space, or unaligned pointers). - Variants::Multiple { - tag_encoding: TagEncoding::Niche { untagged_variant, .. }, - tag_field, - .. - } if this.fields.offset(tag_field) == offset => { - Some(this.for_variant(cx, untagged_variant)) - } - _ => Some(this), - }; + _ => { + let mut data_variant = match this.variants { + // Within the discriminant field, only the niche itself is + // always initialized, so we only check for a pointer at its + // offset. + // + // If the niche is a pointer, it's either valid (according + // to its type), or null (which the niche field's scalar + // validity range encodes). This allows using + // `dereferenceable_or_null` for e.g., `Option<&T>`, and + // this will continue to work as long as we don't start + // using more niches than just null (e.g., the first page of + // the address space, or unaligned pointers). + Variants::Multiple { + tag_encoding: TagEncoding::Niche { untagged_variant, .. }, + tag_field, + .. + } if this.fields.offset(tag_field) == offset => { + Some(this.for_variant(cx, untagged_variant)) + } + _ => Some(this), + }; - if let Some(variant) = data_variant { - // We're not interested in any unions. - if let FieldsShape::Union(_) = variant.fields { - data_variant = None; + if let Some(variant) = data_variant { + // We're not interested in any unions. + if let FieldsShape::Union(_) = variant.fields { + data_variant = None; + } } - } - let mut result = None; - - if let Some(variant) = data_variant { - let ptr_end = offset + Pointer.size(cx); - for i in 0..variant.fields.count() { - let field_start = variant.fields.offset(i); - if field_start <= offset { - let field = variant.field(cx, i); - result = field.to_result().ok().and_then(|field| { - if ptr_end <= field_start + field.size { - // We found the right field, look inside it. - let field_info = - field.pointee_info_at(cx, offset - field_start); - field_info - } else { - None + let mut result = None; + + if let Some(variant) = data_variant { + // FIXME(erikdesjardins): handle non-default addrspace ptr sizes + // (requires passing in the expected address space from the caller) + let ptr_end = offset + Pointer(AddressSpace::DATA).size(cx); + for i in 0..variant.fields.count() { + let field_start = variant.fields.offset(i); + if field_start <= offset { + let field = variant.field(cx, i); + result = field.to_result().ok().and_then(|field| { + if ptr_end <= field_start + field.size { + // We found the right field, look inside it. + let field_info = + field.pointee_info_at(cx, offset - field_start); + field_info + } else { + None + } + }); + if result.is_some() { + break; } - }); - if result.is_some() { - break; } } } - } - // FIXME(eddyb) This should be for `ptr::Unique`, not `Box`. - if let Some(ref mut pointee) = result { - if let ty::Adt(def, _) = this.ty.kind() { - if def.is_box() && offset.bytes() == 0 { - pointee.safe = Some(PointerKind::UniqueOwned); + // FIXME(eddyb) This should be for `ptr::Unique`, not `Box`. + if let Some(ref mut pointee) = result { + if let ty::Adt(def, _) = this.ty.kind() { + if def.is_box() && offset.bytes() == 0 { + pointee.safe = Some(PointerKind::UniqueOwned); + } } } - } - result - } - }; + result + } + }; debug!( "pointee_info_at (offset={:?}, type kind: {:?}) => {:?}", diff --git a/compiler/rustc_target/src/abi/call/loongarch.rs b/compiler/rustc_target/src/abi/call/loongarch.rs index 4a2d39cc70023..247256f076ba9 100644 --- a/compiler/rustc_target/src/abi/call/loongarch.rs +++ b/compiler/rustc_target/src/abi/call/loongarch.rs @@ -39,7 +39,7 @@ where { match arg_layout.abi { Abi::Scalar(scalar) => match scalar.primitive() { - abi::Int(..) | abi::Pointer => { + abi::Int(..) | abi::Pointer(_) => { if arg_layout.size.bits() > xlen { return Err(CannotUseFpConv); } diff --git a/compiler/rustc_target/src/abi/call/mod.rs b/compiler/rustc_target/src/abi/call/mod.rs index 3b8c867d35ba3..a0730fbb650dc 100644 --- a/compiler/rustc_target/src/abi/call/mod.rs +++ b/compiler/rustc_target/src/abi/call/mod.rs @@ -346,7 +346,7 @@ impl<'a, Ty> TyAndLayout<'a, Ty> { // The primitive for this algorithm. Abi::Scalar(scalar) => { let kind = match scalar.primitive() { - abi::Int(..) | abi::Pointer => RegKind::Integer, + abi::Int(..) | abi::Pointer(_) => RegKind::Integer, abi::F32 | abi::F64 => RegKind::Float, }; Ok(HomogeneousAggregate::Homogeneous(Reg { kind, size: self.size })) diff --git a/compiler/rustc_target/src/abi/call/riscv.rs b/compiler/rustc_target/src/abi/call/riscv.rs index 34280d38e3406..d90dce2a08785 100644 --- a/compiler/rustc_target/src/abi/call/riscv.rs +++ b/compiler/rustc_target/src/abi/call/riscv.rs @@ -45,7 +45,7 @@ where { match arg_layout.abi { Abi::Scalar(scalar) => match scalar.primitive() { - abi::Int(..) | abi::Pointer => { + abi::Int(..) | abi::Pointer(_) => { if arg_layout.size.bits() > xlen { return Err(CannotUseFpConv); } diff --git a/compiler/rustc_target/src/abi/call/sparc64.rs b/compiler/rustc_target/src/abi/call/sparc64.rs index 0c7a4f324612e..cbed5b4afc134 100644 --- a/compiler/rustc_target/src/abi/call/sparc64.rs +++ b/compiler/rustc_target/src/abi/call/sparc64.rs @@ -83,7 +83,7 @@ where (abi::F32, _) => offset += Reg::f32().size, (_, abi::F64) => offset += Reg::f64().size, (abi::Int(i, _signed), _) => offset += i.size(), - (abi::Pointer, _) => offset += Reg::i64().size, + (abi::Pointer(_), _) => offset += Reg::i64().size, _ => {} } diff --git a/compiler/rustc_target/src/abi/call/x86_64.rs b/compiler/rustc_target/src/abi/call/x86_64.rs index c0c071a614f50..9427f27d1b7bb 100644 --- a/compiler/rustc_target/src/abi/call/x86_64.rs +++ b/compiler/rustc_target/src/abi/call/x86_64.rs @@ -50,7 +50,7 @@ where Abi::Uninhabited => return Ok(()), Abi::Scalar(scalar) => match scalar.primitive() { - abi::Int(..) | abi::Pointer => Class::Int, + abi::Int(..) | abi::Pointer(_) => Class::Int, abi::F32 | abi::F64 => Class::Sse, }, diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index 91a505a72fae7..e47e68e0670b9 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -244,7 +244,7 @@ fn adjust_for_rust_scalar<'tcx>( } // Only pointer types handled below. - let Scalar::Initialized { value: Pointer, valid_range} = scalar else { return }; + let Scalar::Initialized { value: Pointer(_), valid_range} = scalar else { return }; if !valid_range.contains(0) { attrs.set(ArgAttribute::NonNull); @@ -479,7 +479,7 @@ fn fn_abi_adjust_for_abi<'tcx>( } let size = arg.layout.size; - if arg.layout.is_unsized() || size > Pointer.size(cx) { + if arg.layout.is_unsized() || size > Pointer(AddressSpace::DATA).size(cx) { arg.make_indirect(); } else { // We want to pass small aggregates as immediates, but using diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 6aa016133ca59..0f25579c7bfa1 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -134,7 +134,7 @@ fn layout_of_uncached<'tcx>( ty::FloatTy::F64 => F64, }), ty::FnPtr(_) => { - let mut ptr = scalar_unit(Pointer); + let mut ptr = scalar_unit(Pointer(dl.instruction_address_space)); ptr.valid_range_mut().start = 1; tcx.intern_layout(LayoutS::scalar(cx, ptr)) } @@ -144,7 +144,7 @@ fn layout_of_uncached<'tcx>( // Potentially-wide pointers. ty::Ref(_, pointee, _) | ty::RawPtr(ty::TypeAndMut { ty: pointee, .. }) => { - let mut data_ptr = scalar_unit(Pointer); + let mut data_ptr = scalar_unit(Pointer(AddressSpace::DATA)); if !ty.is_unsafe_ptr() { data_ptr.valid_range_mut().start = 1; } @@ -178,7 +178,7 @@ fn layout_of_uncached<'tcx>( } ty::Slice(_) | ty::Str => scalar_unit(Int(dl.ptr_sized_integer(), false)), ty::Dynamic(..) => { - let mut vtable = scalar_unit(Pointer); + let mut vtable = scalar_unit(Pointer(AddressSpace::DATA)); vtable.valid_range_mut().start = 1; vtable } @@ -195,7 +195,7 @@ fn layout_of_uncached<'tcx>( ty::Dynamic(_, _, ty::DynStar) => { let mut data = scalar_unit(Int(dl.ptr_sized_integer(), false)); data.valid_range_mut().start = 0; - let mut vtable = scalar_unit(Pointer); + let mut vtable = scalar_unit(Pointer(AddressSpace::DATA)); vtable.valid_range_mut().start = 1; tcx.intern_layout(cx.scalar_pair(data, vtable)) } diff --git a/tests/codegen/avr/avr-func-addrspace.rs b/tests/codegen/avr/avr-func-addrspace.rs index e9740e30da483..bc11e1081244a 100644 --- a/tests/codegen/avr/avr-func-addrspace.rs +++ b/tests/codegen/avr/avr-func-addrspace.rs @@ -109,3 +109,28 @@ pub unsafe fn transmute_fn_ptr_to_data(x: fn()) -> *const () { // as long as it doesn't cause a verifier error by using `bitcast`. transmute(x) } + +pub enum Either { A(T), B(U) } + +// Previously, we would codegen this as passing/returning a scalar pair of `{ i8, ptr }`, +// with the `ptr` field representing both `&i32` and `fn()` depending on the variant. +// This is incorrect, because `fn()` should be `ptr addrspace(1)`, not `ptr`. + +// CHECK: define{{.+}}void @should_not_combine_addrspace({{.+\*|ptr}}{{.+}}sret{{.+}}%0, {{.+\*|ptr}}{{.+}}%x) +#[no_mangle] +#[inline(never)] +pub fn should_not_combine_addrspace(x: Either<&i32, fn()>) -> Either<&i32, fn()> { + x +} + +// The incorrectness described above would result in us producing (after optimizations) +// a `ptrtoint`/`inttoptr` roundtrip to convert from `ptr` to `ptr addrspace(1)`. + +// CHECK-LABEL: @call_with_fn_ptr +#[no_mangle] +pub fn call_with_fn_ptr<'a>(f: fn()) -> Either<&'a i32, fn()> { + // CHECK-NOT: ptrtoint + // CHECK-NOT: inttoptr + // CHECK: call addrspace(1) void @should_not_combine_addrspace + should_not_combine_addrspace(Either::B(f)) +} From 00ff718da84b1dbe5f7851fa39987c5b801ca5ca Mon Sep 17 00:00:00 2001 From: Ezra Shaw Date: Sat, 21 Jan 2023 21:32:05 +1300 Subject: [PATCH 277/500] add UI test + docs for `E0789` --- compiler/rustc_error_codes/src/error_codes.rs | 2 +- .../src/error_codes/E0789.md | 30 +++++++++++++++++++ src/tools/tidy/src/error_codes.rs | 2 +- tests/ui/error-codes/E0789.rs | 12 ++++++++ tests/ui/error-codes/E0789.stderr | 15 ++++++++++ 5 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 compiler/rustc_error_codes/src/error_codes/E0789.md create mode 100644 tests/ui/error-codes/E0789.rs create mode 100644 tests/ui/error-codes/E0789.stderr diff --git a/compiler/rustc_error_codes/src/error_codes.rs b/compiler/rustc_error_codes/src/error_codes.rs index 9d5f4ad752051..4ae372bb90432 100644 --- a/compiler/rustc_error_codes/src/error_codes.rs +++ b/compiler/rustc_error_codes/src/error_codes.rs @@ -506,6 +506,7 @@ E0785: include_str!("./error_codes/E0785.md"), E0786: include_str!("./error_codes/E0786.md"), E0787: include_str!("./error_codes/E0787.md"), E0788: include_str!("./error_codes/E0788.md"), +E0789: include_str!("./error_codes/E0789.md"), E0790: include_str!("./error_codes/E0790.md"), E0791: include_str!("./error_codes/E0791.md"), E0792: include_str!("./error_codes/E0792.md"), @@ -645,5 +646,4 @@ E0792: include_str!("./error_codes/E0792.md"), // E0721, // `await` keyword // E0723, // unstable feature in `const` context // E0738, // Removed; errored on `#[track_caller] fn`s in `extern "Rust" { ... }`. - E0789, // rustc_allowed_through_unstable_modules without stability attribute } diff --git a/compiler/rustc_error_codes/src/error_codes/E0789.md b/compiler/rustc_error_codes/src/error_codes/E0789.md new file mode 100644 index 0000000000000..89b7cd422fe96 --- /dev/null +++ b/compiler/rustc_error_codes/src/error_codes/E0789.md @@ -0,0 +1,30 @@ +#### This error code is internal to the compiler and will not be emitted with normal Rust code. + +The internal `rustc_allowed_through_unstable_modules` attribute must be used +on an item with a `stable` attribute. + +Erroneous code example: + +```compile_fail,E0789 +// NOTE: both of these attributes are perma-unstable and should *never* be +// used outside of the compiler and standard library. +#![feature(rustc_attrs)] +#![feature(staged_api)] + +#![unstable(feature = "foo_module", reason = "...", issue = "123")] + +#[rustc_allowed_through_unstable_modules] +// #[stable(feature = "foo", since = "1.0")] +struct Foo; +// ^^^ error: `rustc_allowed_through_unstable_modules` attribute must be +// paired with a `stable` attribute +``` + +Typically when an item is marked with a `stable` attribute, the modules that +enclose the item must also be marked with `stable` attributes, otherwise the +item becomes *de facto* unstable. `#[rustc_allowed_through_unstable_modules]` +is a workaround which allows an item to "escape" its unstable parent modules. +This error occurs when an item is marked with +`#[rustc_allowed_through_unstable_modules]` but no supplementary `stable` +attribute exists. See [#99288](https://github.com/rust-lang/rust/pull/99288) +for an example of `#[rustc_allowed_through_unstable_modules]` in use. diff --git a/src/tools/tidy/src/error_codes.rs b/src/tools/tidy/src/error_codes.rs index 5b84b51a035d4..6bb4d32f87d0a 100644 --- a/src/tools/tidy/src/error_codes.rs +++ b/src/tools/tidy/src/error_codes.rs @@ -31,7 +31,7 @@ const IGNORE_DOCTEST_CHECK: &[&str] = &["E0464", "E0570", "E0601", "E0602", "E06 // Error codes that don't yet have a UI test. This list will eventually be removed. const IGNORE_UI_TEST_CHECK: &[&str] = - &["E0461", "E0465", "E0476", "E0514", "E0523", "E0554", "E0640", "E0717", "E0729", "E0789"]; + &["E0461", "E0465", "E0476", "E0514", "E0523", "E0554", "E0640", "E0717", "E0729"]; macro_rules! verbose_print { ($verbose:expr, $($fmt:tt)*) => { diff --git a/tests/ui/error-codes/E0789.rs b/tests/ui/error-codes/E0789.rs new file mode 100644 index 0000000000000..c0cbbcc9d2dc2 --- /dev/null +++ b/tests/ui/error-codes/E0789.rs @@ -0,0 +1,12 @@ +// compile-flags: --crate-type lib + +#![feature(rustc_attrs)] +#![feature(staged_api)] +#![unstable(feature = "foo_module", reason = "...", issue = "123")] + +#[rustc_allowed_through_unstable_modules] +// #[stable(feature = "foo", since = "1.0")] +struct Foo; +//~^ ERROR `rustc_allowed_through_unstable_modules` attribute must be paired with a `stable` attribute +//~^^ ERROR `rustc_allowed_through_unstable_modules` attribute must be paired with a `stable` attribute +// FIXME: we shouldn't have two errors here, only occurs when using `-Zdeduplicate-diagnostics=no` diff --git a/tests/ui/error-codes/E0789.stderr b/tests/ui/error-codes/E0789.stderr new file mode 100644 index 0000000000000..faab92bae035d --- /dev/null +++ b/tests/ui/error-codes/E0789.stderr @@ -0,0 +1,15 @@ +error[E0789]: `rustc_allowed_through_unstable_modules` attribute must be paired with a `stable` attribute + --> $DIR/E0789.rs:9:1 + | +LL | struct Foo; + | ^^^^^^^^^^^ + +error[E0789]: `rustc_allowed_through_unstable_modules` attribute must be paired with a `stable` attribute + --> $DIR/E0789.rs:9:1 + | +LL | struct Foo; + | ^^^^^^^^^^^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0789`. From abee6137f70c8293078c03919fda68f0a5b9ca1d Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Wed, 7 Dec 2022 09:33:25 +0000 Subject: [PATCH 278/500] Remove another unneeded use of the resolver --- compiler/rustc_interface/src/passes.rs | 33 ++++++++++++------------- compiler/rustc_interface/src/queries.rs | 9 +++++-- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 379a76528f3bb..4b3034c4781b9 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -30,7 +30,7 @@ use rustc_plugin_impl as plugin; use rustc_query_impl::{OnDiskCache, Queries as TcxQueries}; use rustc_resolve::{Resolver, ResolverArenas}; use rustc_session::config::{CrateType, Input, OutputFilenames, OutputType}; -use rustc_session::cstore::{MetadataLoader, MetadataLoaderDyn, Untracked}; +use rustc_session::cstore::{CrateStoreDyn, MetadataLoader, MetadataLoaderDyn, Untracked}; use rustc_session::output::filename_for_input; use rustc_session::search_paths::PathKind; use rustc_session::{Limit, Session}; @@ -548,7 +548,7 @@ fn escape_dep_env(symbol: Symbol) -> String { fn write_out_deps( sess: &Session, - boxed_resolver: &RefCell, + cstore: &CrateStoreDyn, outputs: &OutputFilenames, out_filenames: &[PathBuf], ) { @@ -600,20 +600,19 @@ fn write_out_deps( } } - boxed_resolver.borrow_mut().access(|resolver| { - for cnum in resolver.cstore().crates_untracked() { - let source = resolver.cstore().crate_source_untracked(cnum); - if let Some((path, _)) = &source.dylib { - files.push(escape_dep_filename(&path.display().to_string())); - } - if let Some((path, _)) = &source.rlib { - files.push(escape_dep_filename(&path.display().to_string())); - } - if let Some((path, _)) = &source.rmeta { - files.push(escape_dep_filename(&path.display().to_string())); - } + let cstore = cstore.as_any().downcast_ref::().unwrap(); + for cnum in cstore.crates_untracked() { + let source = cstore.crate_source_untracked(cnum); + if let Some((path, _)) = &source.dylib { + files.push(escape_dep_filename(&path.display().to_string())); } - }); + if let Some((path, _)) = &source.rlib { + files.push(escape_dep_filename(&path.display().to_string())); + } + if let Some((path, _)) = &source.rmeta { + files.push(escape_dep_filename(&path.display().to_string())); + } + } } let mut file = BufWriter::new(fs::File::create(&deps_filename)?); @@ -664,7 +663,7 @@ fn write_out_deps( pub fn prepare_outputs( sess: &Session, krate: &ast::Crate, - boxed_resolver: &RefCell, + cstore: &CrateStoreDyn, crate_name: Symbol, ) -> Result { let _timer = sess.timer("prepare_outputs"); @@ -697,7 +696,7 @@ pub fn prepare_outputs( } } - write_out_deps(sess, boxed_resolver, &outputs, &output_paths); + write_out_deps(sess, cstore, &outputs, &output_paths); let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo) && sess.opts.output_types.len() == 1; diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index d5a49dd75be6a..fe24d41a4de87 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -212,8 +212,6 @@ impl<'tcx> Queries<'tcx> { let crate_name = *self.crate_name()?.borrow(); let (krate, resolver, lint_store) = self.expansion()?.steal(); - let outputs = passes::prepare_outputs(self.session(), &krate, &resolver, crate_name)?; - let ty::ResolverOutputs { untracked, global_ctxt: untracked_resolutions, @@ -237,6 +235,13 @@ impl<'tcx> Queries<'tcx> { tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, krate))), ); feed.resolutions(tcx.arena.alloc(untracked_resolutions)); + + let outputs = passes::prepare_outputs( + self.session(), + &krate, + &*untracked.cstore, + crate_name, + )?; feed.output_filenames(tcx.arena.alloc(std::sync::Arc::new(outputs))); feed.features_query(tcx.sess.features_untracked()); let feed = tcx.feed_local_crate(); From bcc8b05d5cf792d44b854a0097e9654021ad3177 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 23 Jan 2023 10:25:51 +0000 Subject: [PATCH 279/500] Make `output_filenames` a real query --- compiler/rustc_driver/src/lib.rs | 2 + compiler/rustc_interface/src/passes.rs | 32 +++++++-------- compiler/rustc_interface/src/queries.rs | 8 ---- compiler/rustc_middle/src/query/mod.rs | 3 +- tests/run-make/overwrite-input/Makefile | 13 +++++++ tests/run-make/overwrite-input/file.stderr | 6 +++ tests/run-make/overwrite-input/folder.stderr | 6 +++ tests/run-make/overwrite-input/main.rs | 1 + tests/run-make/overwrite-input/main.stderr | 6 +++ tests/ui/io-checks/inaccessbile-temp-dir.rs | 39 +++++++++++++++++++ .../ui/io-checks/inaccessbile-temp-dir.stderr | 4 ++ .../non-ice-error-on-worker-io-fail.rs | 0 .../non-ice-error-on-worker-io-fail.stderr | 0 13 files changed, 92 insertions(+), 28 deletions(-) create mode 100644 tests/run-make/overwrite-input/Makefile create mode 100644 tests/run-make/overwrite-input/file.stderr create mode 100644 tests/run-make/overwrite-input/folder.stderr create mode 100644 tests/run-make/overwrite-input/main.rs create mode 100644 tests/run-make/overwrite-input/main.stderr create mode 100644 tests/ui/io-checks/inaccessbile-temp-dir.rs create mode 100644 tests/ui/io-checks/inaccessbile-temp-dir.stderr rename tests/ui/{ => io-checks}/non-ice-error-on-worker-io-fail.rs (100%) rename tests/ui/{ => io-checks}/non-ice-error-on-worker-io-fail.stderr (100%) diff --git a/compiler/rustc_driver/src/lib.rs b/compiler/rustc_driver/src/lib.rs index f50ad0137b88a..d00a68471bb77 100644 --- a/compiler/rustc_driver/src/lib.rs +++ b/compiler/rustc_driver/src/lib.rs @@ -333,6 +333,8 @@ fn run_compiler( return early_exit(); } + queries.global_ctxt()?.enter(|tcx| tcx.output_filenames(())); + if sess.opts.output_types.contains_key(&OutputType::DepInfo) && sess.opts.output_types.len() == 1 { diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 4b3034c4781b9..37b381c534ea0 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -16,7 +16,7 @@ use rustc_data_structures::parallel; use rustc_data_structures::sync::{Lrc, OnceCell, WorkerLocal}; use rustc_errors::{ErrorGuaranteed, PResult}; use rustc_expand::base::{ExtCtxt, LintStoreExpand, ResolverExpand}; -use rustc_hir::def_id::StableCrateId; +use rustc_hir::def_id::{StableCrateId, LOCAL_CRATE}; use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore}; use rustc_metadata::creader::CStore; use rustc_middle::arena::Arena; @@ -47,7 +47,7 @@ use std::marker::PhantomPinned; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::rc::Rc; -use std::sync::LazyLock; +use std::sync::{Arc, LazyLock}; use std::{env, fs, iter}; pub fn parse<'a>(sess: &'a Session) -> PResult<'a, ast::Crate> { @@ -660,13 +660,11 @@ fn write_out_deps( } } -pub fn prepare_outputs( - sess: &Session, - krate: &ast::Crate, - cstore: &CrateStoreDyn, - crate_name: Symbol, -) -> Result { +fn output_filenames(tcx: TyCtxt<'_>, (): ()) -> Arc { + let sess = tcx.sess; let _timer = sess.timer("prepare_outputs"); + let (_, krate) = &*tcx.resolver_for_lowering(()).borrow(); + let crate_name = tcx.crate_name(LOCAL_CRATE); // FIXME: rustdoc passes &[] instead of &krate.attrs here let outputs = util::build_output_filenames(&krate.attrs, sess); @@ -678,25 +676,21 @@ pub fn prepare_outputs( if let Some(ref input_path) = sess.io.input.opt_path() { if sess.opts.will_create_output_file() { if output_contains_path(&output_paths, input_path) { - let reported = sess.emit_err(InputFileWouldBeOverWritten { path: input_path }); - return Err(reported); + sess.emit_fatal(InputFileWouldBeOverWritten { path: input_path }); } if let Some(ref dir_path) = output_conflicts_with_dir(&output_paths) { - let reported = - sess.emit_err(GeneratedFileConflictsWithDirectory { input_path, dir_path }); - return Err(reported); + sess.emit_fatal(GeneratedFileConflictsWithDirectory { input_path, dir_path }); } } } if let Some(ref dir) = sess.io.temps_dir { if fs::create_dir_all(dir).is_err() { - let reported = sess.emit_err(TempsDirError); - return Err(reported); + sess.emit_fatal(TempsDirError); } } - write_out_deps(sess, cstore, &outputs, &output_paths); + write_out_deps(sess, tcx.cstore_untracked(), &outputs, &output_paths); let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo) && sess.opts.output_types.len() == 1; @@ -704,19 +698,19 @@ pub fn prepare_outputs( if !only_dep_info { if let Some(ref dir) = sess.io.output_dir { if fs::create_dir_all(dir).is_err() { - let reported = sess.emit_err(OutDirError); - return Err(reported); + sess.emit_fatal(OutDirError); } } } - Ok(outputs) + outputs.into() } pub static DEFAULT_QUERY_PROVIDERS: LazyLock = LazyLock::new(|| { let providers = &mut Providers::default(); providers.analysis = analysis; providers.hir_crate = rustc_ast_lowering::lower_to_hir; + providers.output_filenames = output_filenames; proc_macro_decls::provide(providers); rustc_const_eval::provide(providers); rustc_middle::hir::provide(providers); diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index fe24d41a4de87..96cd3b06321ea 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -235,14 +235,6 @@ impl<'tcx> Queries<'tcx> { tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, krate))), ); feed.resolutions(tcx.arena.alloc(untracked_resolutions)); - - let outputs = passes::prepare_outputs( - self.session(), - &krate, - &*untracked.cstore, - crate_name, - )?; - feed.output_filenames(tcx.arena.alloc(std::sync::Arc::new(outputs))); feed.features_query(tcx.sess.features_untracked()); let feed = tcx.feed_local_crate(); feed.crate_name(crate_name); diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 6bbf7fa3914e6..b1da8d634ea00 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -1862,9 +1862,10 @@ rustc_queries! { /// /// This query returns an `&Arc` because codegen backends need the value even after the `TyCtxt` /// has been destroyed. - query output_filenames(_: ()) -> &'tcx Arc { + query output_filenames(_: ()) -> Arc { feedable desc { "getting output filenames" } + arena_cache } /// Do not call this query directly: invoke `normalize` instead. diff --git a/tests/run-make/overwrite-input/Makefile b/tests/run-make/overwrite-input/Makefile new file mode 100644 index 0000000000000..03b03eb147def --- /dev/null +++ b/tests/run-make/overwrite-input/Makefile @@ -0,0 +1,13 @@ +include ../../run-make-fulldeps/tools.mk + +all: + $(RUSTC) main.rs -o main.rs 2> $(TMPDIR)/file.stderr || echo "failed successfully" + $(RUSTC) main.rs -o . 2> $(TMPDIR)/folder.stderr || echo "failed successfully" + +ifdef RUSTC_BLESS_TEST + cp "$(TMPDIR)"/file.stderr file.stderr + cp "$(TMPDIR)"/folder.stderr folder.stderr +else + $(DIFF) file.stderr "$(TMPDIR)"/file.stderr + $(DIFF) folder.stderr "$(TMPDIR)"/folder.stderr +endif diff --git a/tests/run-make/overwrite-input/file.stderr b/tests/run-make/overwrite-input/file.stderr new file mode 100644 index 0000000000000..9936962b4ee37 --- /dev/null +++ b/tests/run-make/overwrite-input/file.stderr @@ -0,0 +1,6 @@ +warning: ignoring --out-dir flag due to -o flag + +error: the input file "main.rs" would be overwritten by the generated executable + +error: aborting due to previous error; 1 warning emitted + diff --git a/tests/run-make/overwrite-input/folder.stderr b/tests/run-make/overwrite-input/folder.stderr new file mode 100644 index 0000000000000..81b1e7367c75a --- /dev/null +++ b/tests/run-make/overwrite-input/folder.stderr @@ -0,0 +1,6 @@ +warning: ignoring --out-dir flag due to -o flag + +error: the generated executable for the input file "main.rs" conflicts with the existing directory "." + +error: aborting due to previous error; 1 warning emitted + diff --git a/tests/run-make/overwrite-input/main.rs b/tests/run-make/overwrite-input/main.rs new file mode 100644 index 0000000000000..f328e4d9d04c3 --- /dev/null +++ b/tests/run-make/overwrite-input/main.rs @@ -0,0 +1 @@ +fn main() {} diff --git a/tests/run-make/overwrite-input/main.stderr b/tests/run-make/overwrite-input/main.stderr new file mode 100644 index 0000000000000..9936962b4ee37 --- /dev/null +++ b/tests/run-make/overwrite-input/main.stderr @@ -0,0 +1,6 @@ +warning: ignoring --out-dir flag due to -o flag + +error: the input file "main.rs" would be overwritten by the generated executable + +error: aborting due to previous error; 1 warning emitted + diff --git a/tests/ui/io-checks/inaccessbile-temp-dir.rs b/tests/ui/io-checks/inaccessbile-temp-dir.rs new file mode 100644 index 0000000000000..9c0aa01357217 --- /dev/null +++ b/tests/ui/io-checks/inaccessbile-temp-dir.rs @@ -0,0 +1,39 @@ +// Issue #66530: We would ICE if someone compiled with `-o /dev/null`, +// because we would try to generate auxiliary files in `/dev/` (which +// at least the OS X file system rejects). +// +// An attempt to `-o` into a directory we cannot write into should indeed +// be an error; but not an ICE. +// +// However, some folks run tests as root, which can write `/dev/` and end +// up clobbering `/dev/null`. Instead we'll use a non-existent path, which +// also used to ICE, but even root can't magically write there. + +// compile-flags: -Z temps-dir=/does-not-exist/output + +// The error-pattern check occurs *before* normalization, and the error patterns +// are wildly different between build environments. So this is a cop-out (and we +// rely on the checking of the normalized stderr output as our actual +// "verification" of the diagnostic). + +// error-pattern: error + +// On Mac OS X, we get an error like the below +// normalize-stderr-test "failed to write bytecode to /does-not-exist/output.non_ice_error_on_worker_io_fail.*" -> "io error modifying /does-not-exist/" + +// On Linux, we get an error like the below +// normalize-stderr-test "couldn't create a temp dir.*" -> "io error modifying /does-not-exist/" + +// ignore-windows - this is a unix-specific test +// ignore-emscripten - the file-system issues do not replicate here +// ignore-wasm - the file-system issues do not replicate here +// ignore-arm - the file-system issues do not replicate here, at least on armhf-gnu + +#![crate_type = "lib"] +#![cfg_attr(not(feature = "std"), no_std)] +pub mod task { + pub mod __internal { + use crate::task::Waker; + } + pub use core::task::Waker; +} diff --git a/tests/ui/io-checks/inaccessbile-temp-dir.stderr b/tests/ui/io-checks/inaccessbile-temp-dir.stderr new file mode 100644 index 0000000000000..2fc5f93ef791a --- /dev/null +++ b/tests/ui/io-checks/inaccessbile-temp-dir.stderr @@ -0,0 +1,4 @@ +error: failed to find or create the directory specified by `--temps-dir` + +error: aborting due to previous error + diff --git a/tests/ui/non-ice-error-on-worker-io-fail.rs b/tests/ui/io-checks/non-ice-error-on-worker-io-fail.rs similarity index 100% rename from tests/ui/non-ice-error-on-worker-io-fail.rs rename to tests/ui/io-checks/non-ice-error-on-worker-io-fail.rs diff --git a/tests/ui/non-ice-error-on-worker-io-fail.stderr b/tests/ui/io-checks/non-ice-error-on-worker-io-fail.stderr similarity index 100% rename from tests/ui/non-ice-error-on-worker-io-fail.stderr rename to tests/ui/io-checks/non-ice-error-on-worker-io-fail.stderr From 3ddb54f1554c9f1eccc8d0e9315a78d2178ad5aa Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Wed, 7 Dec 2022 11:55:29 +0000 Subject: [PATCH 280/500] Prefer queries over Compiler methods --- compiler/rustc_driver/src/lib.rs | 3 +-- compiler/rustc_driver/src/pretty.rs | 6 +++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_driver/src/lib.rs b/compiler/rustc_driver/src/lib.rs index d00a68471bb77..862931da00998 100644 --- a/compiler/rustc_driver/src/lib.rs +++ b/compiler/rustc_driver/src/lib.rs @@ -296,9 +296,8 @@ fn run_compiler( if let Some(ppm) = &sess.opts.pretty { if ppm.needs_ast_map() { - let expanded_crate = queries.expansion()?.borrow().0.clone(); queries.global_ctxt()?.enter(|tcx| { - pretty::print_after_hir_lowering(tcx, &*expanded_crate, *ppm); + pretty::print_after_hir_lowering(tcx, *ppm); Ok(()) })?; } else { diff --git a/compiler/rustc_driver/src/pretty.rs b/compiler/rustc_driver/src/pretty.rs index ae3ac8625b186..022051e008e32 100644 --- a/compiler/rustc_driver/src/pretty.rs +++ b/compiler/rustc_driver/src/pretty.rs @@ -403,7 +403,7 @@ pub fn print_after_parsing(sess: &Session, krate: &ast::Crate, ppm: PpMode) { write_or_print(&out, sess); } -pub fn print_after_hir_lowering<'tcx>(tcx: TyCtxt<'tcx>, krate: &ast::Crate, ppm: PpMode) { +pub fn print_after_hir_lowering<'tcx>(tcx: TyCtxt<'tcx>, ppm: PpMode) { if ppm.needs_analysis() { abort_on_err(print_with_analysis(tcx, ppm), tcx.sess); return; @@ -420,7 +420,7 @@ pub fn print_after_hir_lowering<'tcx>(tcx: TyCtxt<'tcx>, krate: &ast::Crate, ppm let parse = &sess.parse_sess; pprust::print_crate( sess.source_map(), - krate, + &tcx.resolver_for_lowering(()).borrow().1, src_name, src, annotation.pp_ann(), @@ -433,7 +433,7 @@ pub fn print_after_hir_lowering<'tcx>(tcx: TyCtxt<'tcx>, krate: &ast::Crate, ppm AstTree(PpAstTreeMode::Expanded) => { debug!("pretty-printing expanded AST"); - format!("{krate:#?}") + format!("{:#?}", tcx.resolver_for_lowering(()).borrow().1) } Hir(s) => call_with_pp_support_hir(&s, tcx, move |annotation, hir_map| { From 261bbd7dbaaeb3a4f3d25610b6f93aac874bd910 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Thu, 19 Jan 2023 14:12:29 +0000 Subject: [PATCH 281/500] Store the gctxt instead of fetching it twice. --- compiler/rustc_driver/src/lib.rs | 10 +++++++--- compiler/rustc_interface/src/queries.rs | 2 +- src/librustdoc/lib.rs | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_driver/src/lib.rs b/compiler/rustc_driver/src/lib.rs index 862931da00998..ccefd6adaf14b 100644 --- a/compiler/rustc_driver/src/lib.rs +++ b/compiler/rustc_driver/src/lib.rs @@ -327,12 +327,14 @@ fn run_compiler( } } - queries.global_ctxt()?; + let mut gctxt = queries.global_ctxt()?; if callbacks.after_expansion(compiler, queries) == Compilation::Stop { return early_exit(); } - queries.global_ctxt()?.enter(|tcx| tcx.output_filenames(())); + // Make sure the `output_filenames` query is run for its side + // effects of writing the dep-info and reporting errors. + gctxt.enter(|tcx| tcx.output_filenames(())); if sess.opts.output_types.contains_key(&OutputType::DepInfo) && sess.opts.output_types.len() == 1 @@ -344,7 +346,7 @@ fn run_compiler( return early_exit(); } - queries.global_ctxt()?.enter(|tcx| { + gctxt.enter(|tcx| { let result = tcx.analysis(()); if sess.opts.unstable_opts.save_analysis { let crate_name = tcx.crate_name(LOCAL_CRATE); @@ -361,6 +363,8 @@ fn run_compiler( result })?; + drop(gctxt); + if callbacks.after_analysis(compiler, queries) == Compilation::Stop { return early_exit(); } diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index 96cd3b06321ea..4b0180741c19d 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -65,7 +65,7 @@ impl<'a, T> std::ops::DerefMut for QueryResult<'a, T> { } impl<'a, 'tcx> QueryResult<'a, QueryContext<'tcx>> { - pub fn enter(mut self, f: impl FnOnce(TyCtxt<'tcx>) -> T) -> T { + pub fn enter(&mut self, f: impl FnOnce(TyCtxt<'tcx>) -> T) -> T { (*self.0).get_mut().enter(f) } } diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 86454e1f2eb73..a689b502f0fcc 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -815,7 +815,7 @@ fn main_args(at_args: &[String]) -> MainResult { sess.fatal("Compilation failed, aborting rustdoc"); } - let global_ctxt = abort_on_err(queries.global_ctxt(), sess); + let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess); global_ctxt.enter(|tcx| { let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || { From 7d2c1103d7e6773db6fcef8f142d29f2004a4e3b Mon Sep 17 00:00:00 2001 From: Vincenzo Palazzo Date: Sun, 15 Jan 2023 12:58:46 +0100 Subject: [PATCH 282/500] fix: use LocalDefId instead of HirId in trait res use LocalDefId instead of HirId in trait resolution to simplify the obligation clause resolution Signed-off-by: Vincenzo Palazzo --- .../src/diagnostics/conflict_errors.rs | 2 +- .../rustc_borrowck/src/region_infer/mod.rs | 3 +- .../src/region_infer/opaque_types.rs | 7 +- .../src/transform/check_consts/check.rs | 5 +- compiler/rustc_hir_analysis/src/autoderef.rs | 8 +- .../rustc_hir_analysis/src/check/check.rs | 3 +- .../src/check/compare_impl_item.rs | 66 +++++++------- .../rustc_hir_analysis/src/check/intrinsic.rs | 3 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 86 +++++++++++-------- .../src/coherence/builtin.rs | 11 +-- compiler/rustc_hir_analysis/src/collect.rs | 5 +- .../rustc_hir_analysis/src/hir_wf_check.rs | 9 +- .../src/impl_wf_check/min_specialization.rs | 15 +--- compiler/rustc_hir_analysis/src/lib.rs | 23 ++--- compiler/rustc_hir_typeck/src/_match.rs | 8 +- compiler/rustc_hir_typeck/src/check.rs | 2 +- compiler/rustc_hir_typeck/src/closure.rs | 16 ++-- compiler/rustc_hir_typeck/src/expr.rs | 20 +++-- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 4 +- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 8 +- .../src/fn_ctxt/suggestions.rs | 5 +- compiler/rustc_hir_typeck/src/lib.rs | 2 +- compiler/rustc_hir_typeck/src/method/probe.rs | 14 +-- .../rustc_hir_typeck/src/method/suggest.rs | 16 ++-- .../src/infer/error_reporting/mod.rs | 10 +-- .../src/infer/error_reporting/suggest.rs | 3 +- .../rustc_infer/src/infer/opaque_types.rs | 4 +- compiler/rustc_infer/src/traits/mod.rs | 3 +- compiler/rustc_lint/src/builtin.rs | 2 +- .../src/for_loops_over_fallibles.rs | 3 +- compiler/rustc_middle/src/traits/mod.rs | 11 +-- compiler/rustc_middle/src/ty/mod.rs | 1 + .../src/thir/pattern/const_to_pat.rs | 4 +- .../src/traits/coherence.rs | 9 +- .../src/traits/engine.rs | 3 +- .../src/traits/error_reporting/ambiguity.rs | 2 +- .../src/traits/error_reporting/mod.rs | 19 ++-- .../error_reporting/on_unimplemented.rs | 7 +- .../src/traits/error_reporting/suggestions.rs | 61 ++++++------- .../rustc_trait_selection/src/traits/mod.rs | 9 +- .../src/traits/outlives_bounds.rs | 13 ++- .../rustc_trait_selection/src/traits/wf.rs | 10 +-- .../src/implied_outlives_bounds.rs | 7 +- compiler/rustc_traits/src/type_op.rs | 5 +- compiler/rustc_ty_utils/src/ty.rs | 11 +-- .../clippy_lints/src/future_not_send.rs | 3 +- .../src/methods/unnecessary_to_owned.rs | 2 +- .../clippy_lints/src/transmute/utils.rs | 2 +- 48 files changed, 265 insertions(+), 280 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index e5a36259fa495..720bfe2c77aba 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -766,7 +766,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let copy_did = infcx.tcx.require_lang_item(LangItem::Copy, Some(span)); let cause = ObligationCause::new( span, - self.mir_hir_id(), + self.mir_def_id(), rustc_infer::traits::ObligationCauseCode::MiscObligation, ); let errors = rustc_trait_selection::traits::fully_solve_bound( diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index 238172ea3992f..2ae13990a4589 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -7,7 +7,6 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::graph::scc::Sccs; use rustc_errors::Diagnostic; use rustc_hir::def_id::CRATE_DEF_ID; -use rustc_hir::CRATE_HIR_ID; use rustc_index::vec::IndexVec; use rustc_infer::infer::outlives::test_type_match; use rustc_infer::infer::region_constraints::{GenericKind, VarInfos, VerifyBound, VerifyIfEq}; @@ -2022,7 +2021,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { .map(|constraint| BlameConstraint { category: constraint.category, from_closure: constraint.from_closure, - cause: ObligationCause::new(constraint.span, CRATE_HIR_ID, cause_code.clone()), + cause: ObligationCause::new(constraint.span, CRATE_DEF_ID, cause_code.clone()), variance_info: constraint.variance_info, outlives_constraint: *constraint, }) diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs index db5a67a8b442d..ef6de8b109136 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs @@ -273,7 +273,6 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { // This logic duplicates most of `check_opaque_meets_bounds`. // FIXME(oli-obk): Also do region checks here and then consider removing `check_opaque_meets_bounds` entirely. let param_env = self.tcx.param_env(def_id); - let body_id = self.tcx.local_def_id_to_hir_id(def_id); // HACK This bubble is required for this tests to pass: // type-alias-impl-trait/issue-67844-nested-opaque.rs let infcx = @@ -290,7 +289,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { // the bounds that the function supplies. let opaque_ty = self.tcx.mk_opaque(def_id.to_def_id(), id_substs); if let Err(err) = ocx.eq( - &ObligationCause::misc(instantiated_ty.span, body_id), + &ObligationCause::misc(instantiated_ty.span, def_id), param_env, opaque_ty, definition_ty, @@ -298,7 +297,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { infcx .err_ctxt() .report_mismatched_types( - &ObligationCause::misc(instantiated_ty.span, body_id), + &ObligationCause::misc(instantiated_ty.span, def_id), opaque_ty, definition_ty, err, @@ -309,7 +308,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { ocx.register_obligation(Obligation::misc( infcx.tcx, instantiated_ty.span, - body_id, + def_id, param_env, predicate, )); diff --git a/compiler/rustc_const_eval/src/transform/check_consts/check.rs b/compiler/rustc_const_eval/src/transform/check_consts/check.rs index 79f1737e32b21..cc40c2566d2e6 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/check.rs @@ -754,12 +754,9 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { let ocx = ObligationCtxt::new(&infcx); let predicates = tcx.predicates_of(callee).instantiate(tcx, substs); - let hir_id = tcx - .hir() - .local_def_id_to_hir_id(self.body.source.def_id().expect_local()); let cause = ObligationCause::new( terminator.source_info.span, - hir_id, + self.body.source.def_id().expect_local(), ObligationCauseCode::ItemObligation(callee), ); let normalized_predicates = ocx.normalize(&cause, param_env, predicates); diff --git a/compiler/rustc_hir_analysis/src/autoderef.rs b/compiler/rustc_hir_analysis/src/autoderef.rs index 730560cc68686..a5c96a8b01613 100644 --- a/compiler/rustc_hir_analysis/src/autoderef.rs +++ b/compiler/rustc_hir_analysis/src/autoderef.rs @@ -2,11 +2,11 @@ use crate::errors::AutoDerefReachedRecursionLimit; use crate::traits::query::evaluate_obligation::InferCtxtExt; use crate::traits::NormalizeExt; use crate::traits::{self, TraitEngine, TraitEngineExt}; -use rustc_hir as hir; use rustc_infer::infer::InferCtxt; use rustc_middle::ty::TypeVisitable; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_session::Limit; +use rustc_span::def_id::LocalDefId; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::Span; @@ -28,7 +28,7 @@ pub struct Autoderef<'a, 'tcx> { // Meta infos: infcx: &'a InferCtxt<'tcx>, span: Span, - body_id: hir::HirId, + body_id: LocalDefId, param_env: ty::ParamEnv<'tcx>, // Current state: @@ -96,14 +96,14 @@ impl<'a, 'tcx> Autoderef<'a, 'tcx> { pub fn new( infcx: &'a InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, - body_id: hir::HirId, + body_def_id: LocalDefId, span: Span, base_ty: Ty<'tcx>, ) -> Autoderef<'a, 'tcx> { Autoderef { infcx, span, - body_id, + body_id: body_def_id, param_env, state: AutoderefSnapshot { steps: vec![], diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index abc1c2d7b8d17..6c7482b40c3d2 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -412,7 +412,6 @@ fn check_opaque_meets_bounds<'tcx>( span: Span, origin: &hir::OpaqueTyOrigin, ) { - let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); let defining_use_anchor = match *origin { hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did, hir::OpaqueTyOrigin::TyAlias => def_id, @@ -438,7 +437,7 @@ fn check_opaque_meets_bounds<'tcx>( _ => re, }); - let misc_cause = traits::ObligationCause::misc(span, hir_id); + let misc_cause = traits::ObligationCause::misc(span, def_id); match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) { Ok(()) => {} diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index cfebcceef3cdb..c09294090d310 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -147,12 +147,12 @@ fn compare_method_predicate_entailment<'tcx>( // // FIXME(@lcnr): remove that after removing `cause.body_id` from // obligations. - let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local()); + let impl_m_def_id = impl_m.def_id.expect_local(); let cause = ObligationCause::new( impl_m_span, - impl_m_hir_id, + impl_m_def_id, ObligationCauseCode::CompareImplItemObligation { - impl_item_def_id: impl_m.def_id.expect_local(), + impl_item_def_id: impl_m_def_id, trait_item_def_id: trait_m.def_id, kind: impl_m.kind, }, @@ -198,7 +198,7 @@ fn compare_method_predicate_entailment<'tcx>( // Construct trait parameter environment and then shift it into the placeholder viewpoint. // The key step here is to update the caller_bounds's predicates to be // the new hybrid bounds we computed. - let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id); + let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id); let param_env = ty::ParamEnv::new( tcx.intern_predicates(&hybrid_preds.predicates), Reveal::UserFacing, @@ -213,14 +213,14 @@ fn compare_method_predicate_entailment<'tcx>( let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs); for (predicate, span) in impl_m_own_bounds { - let normalize_cause = traits::ObligationCause::misc(span, impl_m_hir_id); + let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id); let predicate = ocx.normalize(&normalize_cause, param_env, predicate); let cause = ObligationCause::new( span, - impl_m_hir_id, + impl_m_def_id, ObligationCauseCode::CompareImplItemObligation { - impl_item_def_id: impl_m.def_id.expect_local(), + impl_item_def_id: impl_m_def_id, trait_item_def_id: trait_m.def_id, kind: impl_m.kind, }, @@ -253,7 +253,7 @@ fn compare_method_predicate_entailment<'tcx>( ); let unnormalized_impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(unnormalized_impl_sig)); - let norm_cause = ObligationCause::misc(impl_m_span, impl_m_hir_id); + let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id); let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig); debug!("compare_impl_method: impl_fty={:?}", impl_sig); @@ -311,6 +311,7 @@ fn compare_method_predicate_entailment<'tcx>( if !errors.is_empty() { match check_implied_wf { CheckImpliedWfMode::Check => { + let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m_def_id); return compare_method_predicate_entailment( tcx, impl_m, @@ -336,7 +337,7 @@ fn compare_method_predicate_entailment<'tcx>( let outlives_env = OutlivesEnvironment::with_bounds( param_env, Some(infcx), - infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys.clone()), + infcx.implied_bounds_tys(param_env, impl_m_def_id, wf_tys.clone()), ); infcx.process_registered_region_obligations( outlives_env.region_bound_pairs(), @@ -346,6 +347,7 @@ fn compare_method_predicate_entailment<'tcx>( if !errors.is_empty() { // FIXME(compiler-errors): This can be simplified when IMPLIED_BOUNDS_ENTAILMENT // becomes a hard error (i.e. ideally we'd just call `resolve_regions_and_report_errors` + let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m_def_id); match check_implied_wf { CheckImpliedWfMode::Check => { return compare_method_predicate_entailment( @@ -371,7 +373,7 @@ fn compare_method_predicate_entailment<'tcx>( } CheckImpliedWfMode::Skip => { if infcx.tainted_by_errors().is_none() { - infcx.err_ctxt().report_region_errors(impl_m.def_id.expect_local(), &errors); + infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors); } return Err(tcx .sess @@ -610,13 +612,14 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( let trait_to_impl_substs = impl_trait_ref.substs; - let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local()); + let impl_m_def_id = impl_m.def_id.expect_local(); + let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m_def_id); let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span(); let cause = ObligationCause::new( return_span, - impl_m_hir_id, + impl_m_def_id, ObligationCauseCode::CompareImplItemObligation { - impl_item_def_id: impl_m.def_id.expect_local(), + impl_item_def_id: impl_m_def_id, trait_item_def_id: trait_m.def_id, kind: impl_m.kind, }, @@ -633,7 +636,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( let ocx = ObligationCtxt::new(infcx); // Normalize the impl signature with fresh variables for lifetime inference. - let norm_cause = ObligationCause::misc(return_span, impl_m_hir_id); + let norm_cause = ObligationCause::misc(return_span, impl_m_def_id); let impl_sig = ocx.normalize( &norm_cause, param_env, @@ -650,7 +653,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces // them with inference variables. // We will use these inference variables to collect the hidden types of RPITITs. - let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_hir_id); + let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id); let unnormalized_trait_sig = tcx .liberate_late_bound_regions( impl_m.def_id, @@ -732,12 +735,11 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( let outlives_environment = OutlivesEnvironment::with_bounds( param_env, Some(infcx), - infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys), + infcx.implied_bounds_tys(param_env, impl_m_def_id, wf_tys), ); - infcx.err_ctxt().check_region_obligations_and_report_errors( - impl_m.def_id.expect_local(), - &outlives_environment, - )?; + infcx + .err_ctxt() + .check_region_obligations_and_report_errors(impl_m_def_id, &outlives_environment)?; let mut collected_tys = FxHashMap::default(); for (def_id, (ty, substs)) in collector.types { @@ -819,7 +821,7 @@ struct ImplTraitInTraitCollector<'a, 'tcx> { types: FxHashMap, ty::SubstsRef<'tcx>)>, span: Span, param_env: ty::ParamEnv<'tcx>, - body_id: hir::HirId, + body_id: LocalDefId, } impl<'a, 'tcx> ImplTraitInTraitCollector<'a, 'tcx> { @@ -827,7 +829,7 @@ impl<'a, 'tcx> ImplTraitInTraitCollector<'a, 'tcx> { ocx: &'a ObligationCtxt<'a, 'tcx>, span: Span, param_env: ty::ParamEnv<'tcx>, - body_id: hir::HirId, + body_id: LocalDefId, ) -> Self { ImplTraitInTraitCollector { ocx, types: FxHashMap::default(), span, param_env, body_id } } @@ -1671,14 +1673,12 @@ pub(super) fn compare_impl_const_raw( // Create a parameter environment that represents the implementation's // method. - let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_const_item_def); - // Compute placeholder form of impl and trait const tys. let impl_ty = tcx.type_of(impl_const_item_def.to_def_id()); let trait_ty = tcx.bound_type_of(trait_const_item_def).subst(tcx, trait_to_impl_substs); let mut cause = ObligationCause::new( impl_c_span, - impl_c_hir_id, + impl_const_item_def, ObligationCauseCode::CompareImplItemObligation { impl_item_def_id: impl_const_item_def, trait_item_def_id: trait_const_item_def, @@ -1799,7 +1799,7 @@ fn compare_type_predicate_entailment<'tcx>( // This `HirId` should be used for the `body_id` field on each // `ObligationCause` (and the `FnCtxt`). This is what // `regionck_item` expects. - let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local()); + let impl_ty_def_id = impl_ty.def_id.expect_local(); debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs); // The predicates declared by the impl definition, the trait and the @@ -1814,7 +1814,7 @@ fn compare_type_predicate_entailment<'tcx>( debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds); - let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id); + let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_def_id); let param_env = ty::ParamEnv::new( tcx.intern_predicates(&hybrid_preds.predicates), Reveal::UserFacing, @@ -1827,12 +1827,12 @@ fn compare_type_predicate_entailment<'tcx>( debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds()); for (predicate, span) in impl_ty_own_bounds { - let cause = ObligationCause::misc(span, impl_ty_hir_id); + let cause = ObligationCause::misc(span, impl_ty_def_id); let predicate = ocx.normalize(&cause, param_env, predicate); let cause = ObligationCause::new( span, - impl_ty_hir_id, + impl_ty_def_id, ObligationCauseCode::CompareImplItemObligation { impl_item_def_id: impl_ty.def_id.expect_local(), trait_item_def_id: trait_ty.def_id, @@ -2008,7 +2008,7 @@ pub(super) fn check_type_bounds<'tcx>( }; debug!(?normalize_param_env); - let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local()); + let impl_ty_def_id = impl_ty.def_id.expect_local(); let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id); let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs); @@ -2020,7 +2020,7 @@ pub(super) fn check_type_bounds<'tcx>( let normalize_cause = ObligationCause::new( impl_ty_span, - impl_ty_hir_id, + impl_ty_def_id, ObligationCauseCode::CheckAssociatedTypeBounds { impl_item_def_id: impl_ty.def_id.expect_local(), trait_item_def_id: trait_ty.def_id, @@ -2032,7 +2032,7 @@ pub(super) fn check_type_bounds<'tcx>( } else { traits::BindingObligation(trait_ty.def_id, span) }; - ObligationCause::new(impl_ty_span, impl_ty_hir_id, code) + ObligationCause::new(impl_ty_span, impl_ty_def_id, code) }; let obligations = tcx @@ -2063,7 +2063,7 @@ pub(super) fn check_type_bounds<'tcx>( // Finally, resolve all regions. This catches wily misuses of // lifetime parameters. - let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_hir_id, assumed_wf_types); + let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_def_id, assumed_wf_types); let outlives_environment = OutlivesEnvironment::with_bounds(param_env, Some(&infcx), implied_bounds); diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 598dc2dca5c62..c93ac5ad963d2 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -56,7 +56,8 @@ fn equate_intrinsic_type<'tcx>( && gen_count_ok(own_counts.consts, 0, "const") { let fty = tcx.mk_fn_ptr(sig); - let cause = ObligationCause::new(it.span, it.hir_id(), ObligationCauseCode::IntrinsicType); + let it_def_id = it.owner_id.def_id; + let cause = ObligationCause::new(it.span, it_def_id, ObligationCauseCode::IntrinsicType); require_same_types(tcx, &cause, tcx.mk_fn_ptr(tcx.fn_sig(it.owner_id)), fty); } } diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 11237afe8a0e3..cf14da35375cc 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -37,7 +37,7 @@ use std::ops::{ControlFlow, Deref}; pub(super) struct WfCheckingCtxt<'a, 'tcx> { pub(super) ocx: ObligationCtxt<'a, 'tcx>, span: Span, - body_id: hir::HirId, + body_def_id: LocalDefId, param_env: ty::ParamEnv<'tcx>, } impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> { @@ -59,7 +59,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { T: TypeFoldable<'tcx>, { self.ocx.normalize( - &ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc)), + &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)), self.param_env, value, ) @@ -71,8 +71,11 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { loc: Option, arg: ty::GenericArg<'tcx>, ) { - let cause = - traits::ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc)); + let cause = traits::ObligationCause::new( + span, + self.body_def_id, + ObligationCauseCode::WellFormed(loc), + ); // for a type to be WF, we do not need to check if const trait predicates satisfy. let param_env = self.param_env.without_const(); self.ocx.register_obligation(traits::Obligation::new( @@ -93,11 +96,10 @@ pub(super) fn enter_wf_checking_ctxt<'tcx, F>( F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>), { let param_env = tcx.param_env(body_def_id); - let body_id = tcx.hir().local_def_id_to_hir_id(body_def_id); let infcx = &tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new(infcx); - let mut wfcx = WfCheckingCtxt { ocx, span, body_id, param_env }; + let mut wfcx = WfCheckingCtxt { ocx, span, body_def_id, param_env }; if !tcx.features().trivial_bounds { wfcx.check_false_global_bounds() @@ -105,7 +107,7 @@ pub(super) fn enter_wf_checking_ctxt<'tcx, F>( f(&mut wfcx); let assumed_wf_types = wfcx.ocx.assumed_wf_types(param_env, span, body_def_id); - let implied_bounds = infcx.implied_bounds_tys(param_env, body_id, assumed_wf_types); + let implied_bounds = infcx.implied_bounds_tys(param_env, body_def_id, assumed_wf_types); let errors = wfcx.select_all_or_error(); if !errors.is_empty() { @@ -374,7 +376,6 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe continue; } - let item_hir_id = item.id.hir_id(); let param_env = tcx.param_env(item_def_id); let item_required_bounds = match item.kind { @@ -390,7 +391,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe gather_gat_bounds( tcx, param_env, - item_hir_id, + item_def_id.def_id, sig.inputs_and_output, // We also assume that all of the function signature's parameter types // are well formed. @@ -412,7 +413,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe gather_gat_bounds( tcx, param_env, - item_hir_id, + item_def_id.def_id, tcx.explicit_item_bounds(item_def_id).to_vec(), &FxIndexSet::default(), gat_def_id.def_id, @@ -458,7 +459,6 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe let gat_item_hir = tcx.hir().expect_trait_item(gat_def_id.def_id); debug!(?required_bounds); let param_env = tcx.param_env(gat_def_id); - let gat_hir = gat_item_hir.hir_id(); let mut unsatisfied_bounds: Vec<_> = required_bounds .into_iter() @@ -466,13 +466,25 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe ty::PredicateKind::Clause(ty::Clause::RegionOutlives(ty::OutlivesPredicate( a, b, - ))) => { - !region_known_to_outlive(tcx, gat_hir, param_env, &FxIndexSet::default(), a, b) - } + ))) => !region_known_to_outlive( + tcx, + gat_def_id.def_id, + param_env, + &FxIndexSet::default(), + a, + b, + ), ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate( a, b, - ))) => !ty_known_to_outlive(tcx, gat_hir, param_env, &FxIndexSet::default(), a, b), + ))) => !ty_known_to_outlive( + tcx, + gat_def_id.def_id, + param_env, + &FxIndexSet::default(), + a, + b, + ), _ => bug!("Unexpected PredicateKind"), }) .map(|clause| clause.to_string()) @@ -551,7 +563,7 @@ fn augment_param_env<'tcx>( fn gather_gat_bounds<'tcx, T: TypeFoldable<'tcx>>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, - item_hir: hir::HirId, + item_def_id: LocalDefId, to_check: T, wf_tys: &FxIndexSet>, gat_def_id: LocalDefId, @@ -584,7 +596,7 @@ fn gather_gat_bounds<'tcx, T: TypeFoldable<'tcx>>( // reflected in a where clause on the GAT itself. for (ty, ty_idx) in &types { // In our example, requires that `Self: 'a` - if ty_known_to_outlive(tcx, item_hir, param_env, &wf_tys, *ty, *region_a) { + if ty_known_to_outlive(tcx, item_def_id, param_env, &wf_tys, *ty, *region_a) { debug!(?ty_idx, ?region_a_idx); debug!("required clause: {ty} must outlive {region_a}"); // Translate into the generic parameters of the GAT. In @@ -622,7 +634,7 @@ fn gather_gat_bounds<'tcx, T: TypeFoldable<'tcx>>( if ty::ReStatic == **region_b || region_a == region_b { continue; } - if region_known_to_outlive(tcx, item_hir, param_env, &wf_tys, *region_a, *region_b) { + if region_known_to_outlive(tcx, item_def_id, param_env, &wf_tys, *region_a, *region_b) { debug!(?region_a_idx, ?region_b_idx); debug!("required clause: {region_a} must outlive {region_b}"); // Translate into the generic parameters of the GAT. @@ -658,7 +670,7 @@ fn gather_gat_bounds<'tcx, T: TypeFoldable<'tcx>>( /// `ty` outlives `region`. fn ty_known_to_outlive<'tcx>( tcx: TyCtxt<'tcx>, - id: hir::HirId, + id: LocalDefId, param_env: ty::ParamEnv<'tcx>, wf_tys: &FxIndexSet>, ty: Ty<'tcx>, @@ -675,7 +687,7 @@ fn ty_known_to_outlive<'tcx>( /// `region_a` outlives `region_b` fn region_known_to_outlive<'tcx>( tcx: TyCtxt<'tcx>, - id: hir::HirId, + id: LocalDefId, param_env: ty::ParamEnv<'tcx>, wf_tys: &FxIndexSet>, region_a: ty::Region<'tcx>, @@ -699,7 +711,7 @@ fn region_known_to_outlive<'tcx>( /// to be tested), then resolve region and return errors fn resolve_regions_with_wf_tys<'tcx>( tcx: TyCtxt<'tcx>, - id: hir::HirId, + id: LocalDefId, param_env: ty::ParamEnv<'tcx>, wf_tys: &FxIndexSet>, add_constraints: impl for<'a> FnOnce(&'a InferCtxt<'tcx>, &'a RegionBoundPairs<'tcx>), @@ -1093,7 +1105,7 @@ fn check_type_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, all_sized: b wfcx.register_bound( traits::ObligationCause::new( hir_ty.span, - wfcx.body_id, + wfcx.body_def_id, traits::FieldSized { adt_kind: match item_adt_kind(&item.kind) { Some(i) => i, @@ -1113,7 +1125,7 @@ fn check_type_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, all_sized: b if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr { let cause = traits::ObligationCause::new( tcx.def_span(discr_def_id), - wfcx.body_id, + wfcx.body_def_id, traits::MiscObligation, ); wfcx.register_obligation(traits::Obligation::new( @@ -1174,7 +1186,7 @@ fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: &ty::AssocI traits::wf::predicate_obligations( wfcx.infcx, wfcx.param_env, - wfcx.body_id, + wfcx.body_def_id, normalized_bound, bound_span, ) @@ -1214,7 +1226,7 @@ fn check_item_type(tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, allow_fo wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into()); if forbid_unsized { wfcx.register_bound( - traits::ObligationCause::new(ty_span, wfcx.body_id, traits::WellFormed(None)), + traits::ObligationCause::new(ty_span, wfcx.body_def_id, traits::WellFormed(None)), wfcx.param_env, item_ty, tcx.require_lang_item(LangItem::Sized, None), @@ -1229,7 +1241,7 @@ fn check_item_type(tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, allow_fo if should_check_for_sync { wfcx.register_bound( - traits::ObligationCause::new(ty_span, wfcx.body_id, traits::SharedStatic), + traits::ObligationCause::new(ty_span, wfcx.body_def_id, traits::SharedStatic), wfcx.param_env, item_ty, tcx.require_lang_item(LangItem::Sync, Some(ty_span)), @@ -1269,7 +1281,7 @@ fn check_impl<'tcx>( let mut obligations = traits::wf::trait_obligations( wfcx.infcx, wfcx.param_env, - wfcx.body_id, + wfcx.body_def_id, &trait_pred, ast_trait_ref.path.span, item, @@ -1466,7 +1478,7 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id let pred = wfcx.normalize(sp, None, pred); let cause = traits::ObligationCause::new( sp, - wfcx.body_id, + wfcx.body_def_id, traits::ItemObligation(def_id.to_def_id()), ); traits::Obligation::new(tcx, cause, wfcx.param_env, pred) @@ -1482,12 +1494,11 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id traits::wf::predicate_obligations( infcx, wfcx.param_env.without_const(), - wfcx.body_id, + wfcx.body_def_id, p, sp, ) }); - let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect(); wfcx.register_obligations(obligations); } @@ -1549,7 +1560,7 @@ fn check_fn_or_method<'tcx>( // Check that the argument is a tuple if let Some(ty) = inputs.next() { wfcx.register_bound( - ObligationCause::new(span, wfcx.body_id, ObligationCauseCode::RustCall), + ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall), wfcx.param_env, *ty, tcx.require_lang_item(hir::LangItem::Tuple, Some(span)), @@ -1597,7 +1608,7 @@ fn check_return_position_impl_trait_in_trait_bounds<'tcx>( traits::wf::predicate_obligations( wfcx.infcx, wfcx.param_env, - wfcx.body_id, + wfcx.body_def_id, normalized_bound, bound_span, ) @@ -1697,7 +1708,7 @@ fn receiver_is_valid<'tcx>( let infcx = wfcx.infcx; let tcx = wfcx.tcx(); let cause = - ObligationCause::new(span, wfcx.body_id, traits::ObligationCauseCode::MethodReceiver); + ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver); let can_eq_self = |ty| infcx.can_eq(wfcx.param_env, self_ty, ty).is_ok(); @@ -1709,7 +1720,7 @@ fn receiver_is_valid<'tcx>( return true; } - let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_id, span, receiver_ty); + let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty); // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`. if arbitrary_self_types_enabled { @@ -1894,8 +1905,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { let mut span = self.span; let empty_env = ty::ParamEnv::empty(); - let def_id = tcx.hir().local_def_id(self.body_id); - let predicates_with_span = tcx.predicates_of(def_id).predicates.iter().copied(); + let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied(); // Check elaborated bounds. let implied_obligations = traits::elaborate_predicates_with_span(tcx, predicates_with_span); @@ -1910,7 +1920,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { // Match the existing behavior. if pred.is_global() && !pred.has_late_bound_vars() { let pred = self.normalize(span, None, pred); - let hir_node = tcx.hir().find(self.body_id); + let hir_node = tcx.hir().find_by_def_id(self.body_def_id); // only use the span of the predicate clause (#90869) @@ -1929,7 +1939,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { let obligation = traits::Obligation::new( tcx, - traits::ObligationCause::new(span, self.body_id, traits::TrivialBound), + traits::ObligationCause::new(span, self.body_def_id, traits::TrivialBound), empty_env, pred, ); diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 28c04087868a7..76668f7e9ac4b 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -64,8 +64,6 @@ fn visit_implementation_of_drop(tcx: TyCtxt<'_>, impl_did: LocalDefId) { fn visit_implementation_of_copy(tcx: TyCtxt<'_>, impl_did: LocalDefId) { debug!("visit_implementation_of_copy: impl_did={:?}", impl_did); - let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_did); - let self_type = tcx.type_of(impl_did); debug!("visit_implementation_of_copy: self_type={:?} (bound)", self_type); @@ -80,7 +78,7 @@ fn visit_implementation_of_copy(tcx: TyCtxt<'_>, impl_did: LocalDefId) { _ => bug!("expected Copy impl item"), }; - let cause = traits::ObligationCause::misc(span, impl_hir_id); + let cause = traits::ObligationCause::misc(span, impl_did); match type_allowed_to_implement_copy(tcx, param_env, self_type, cause) { Ok(()) => {} Err(CopyImplementationError::InfrigingFields(fields)) => { @@ -224,7 +222,7 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: LocalDef let create_err = |msg: &str| struct_span_err!(tcx.sess, span, E0378, "{}", msg); let infcx = tcx.infer_ctxt().build(); - let cause = ObligationCause::misc(span, impl_hir_id); + let cause = ObligationCause::misc(span, impl_did); use rustc_type_ir::sty::TyKind::*; match (source.kind(), target.kind()) { @@ -386,8 +384,7 @@ pub fn coerce_unsized_info<'tcx>(tcx: TyCtxt<'tcx>, impl_did: DefId) -> CoerceUn debug!("visit_implementation_of_coerce_unsized: {:?} -> {:?} (free)", source, target); let infcx = tcx.infer_ctxt().build(); - let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_did); - let cause = ObligationCause::misc(span, impl_hir_id); + let cause = ObligationCause::misc(span, impl_did); let check_mutbl = |mt_a: ty::TypeAndMut<'tcx>, mt_b: ty::TypeAndMut<'tcx>, mk_ptr: &dyn Fn(Ty<'tcx>) -> Ty<'tcx>| { @@ -575,7 +572,7 @@ pub fn coerce_unsized_info<'tcx>(tcx: TyCtxt<'tcx>, impl_did: DefId) -> CoerceUn }; // Register an obligation for `A: Trait`. - let cause = traits::ObligationCause::misc(span, impl_hir_id); + let cause = traits::ObligationCause::misc(span, impl_did); let predicate = predicate_for_trait_def(tcx, param_env, cause, trait_def_id, 0, [source, target]); let errors = traits::fully_solve_obligation(&infcx, predicate); diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index c17778ce8bc09..e253459ef64ab 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -1248,11 +1248,12 @@ fn infer_return_ty_for_fn_sig<'tcx>( } } +// FIXME(vincenzopalazzo): remove the hir item when the refactoring is stable fn suggest_impl_trait<'tcx>( tcx: TyCtxt<'tcx>, ret_ty: Ty<'tcx>, span: Span, - hir_id: hir::HirId, + _hir_id: hir::HirId, def_id: LocalDefId, ) -> Option { let format_as_assoc: fn(_, _, _, _, _) -> _ = @@ -1324,7 +1325,7 @@ fn suggest_impl_trait<'tcx>( } let ocx = ObligationCtxt::new_in_snapshot(&infcx); let item_ty = ocx.normalize( - &ObligationCause::misc(span, hir_id), + &ObligationCause::misc(span, def_id), param_env, tcx.mk_projection(assoc_item_def_id, substs), ); diff --git a/compiler/rustc_hir_analysis/src/hir_wf_check.rs b/compiler/rustc_hir_analysis/src/hir_wf_check.rs index 17dbb126bd1b0..9cf82b39ec947 100644 --- a/compiler/rustc_hir_analysis/src/hir_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/hir_wf_check.rs @@ -1,11 +1,12 @@ use crate::collect::ItemCtxt; use rustc_hir as hir; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{ForeignItem, ForeignItemKind, HirId}; +use rustc_hir::{ForeignItem, ForeignItemKind}; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::{ObligationCause, WellFormedLoc}; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, Region, TyCtxt, TypeFoldable, TypeFolder}; +use rustc_span::def_id::LocalDefId; use rustc_trait_selection::traits; pub fn provide(providers: &mut Providers) { @@ -57,7 +58,7 @@ fn diagnostic_hir_wf_check<'tcx>( cause: Option>, cause_depth: usize, icx: ItemCtxt<'tcx>, - hir_id: HirId, + def_id: LocalDefId, param_env: ty::ParamEnv<'tcx>, depth: usize, } @@ -68,7 +69,7 @@ fn diagnostic_hir_wf_check<'tcx>( let tcx_ty = self.icx.to_ty(ty).fold_with(&mut EraseAllBoundRegions { tcx: self.tcx }); let cause = traits::ObligationCause::new( ty.span, - self.hir_id, + self.def_id, traits::ObligationCauseCode::WellFormed(None), ); let errors = traits::fully_solve_obligation( @@ -106,7 +107,7 @@ fn diagnostic_hir_wf_check<'tcx>( cause: None, cause_depth: 0, icx, - hir_id, + def_id, param_env: tcx.param_env(def_id.to_def_id()), depth: 0, }; diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs index bcda26c4cc854..a5dcfab9be8e8 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs @@ -164,7 +164,6 @@ fn get_impl_substs( let infcx = &tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new(infcx); let param_env = tcx.param_env(impl1_def_id); - let impl1_hir_id = tcx.hir().local_def_id_to_hir_id(impl1_def_id); let assumed_wf_types = ocx.assumed_wf_types(param_env, tcx.def_span(impl1_def_id), impl1_def_id); @@ -179,7 +178,7 @@ fn get_impl_substs( return None; } - let implied_bounds = infcx.implied_bounds_tys(param_env, impl1_hir_id, assumed_wf_types); + let implied_bounds = infcx.implied_bounds_tys(param_env, impl1_def_id, assumed_wf_types); let outlives_env = OutlivesEnvironment::with_bounds(param_env, Some(infcx), implied_bounds); let _ = infcx.err_ctxt().check_region_obligations_and_report_errors(impl1_def_id, &outlives_env); @@ -372,15 +371,9 @@ fn check_predicates<'tcx>( // Include the well-formed predicates of the type parameters of the impl. for arg in tcx.impl_trait_ref(impl1_def_id).unwrap().subst_identity().substs { let infcx = &tcx.infer_ctxt().build(); - let obligations = wf::obligations( - infcx, - tcx.param_env(impl1_def_id), - tcx.hir().local_def_id_to_hir_id(impl1_def_id), - 0, - arg, - span, - ) - .unwrap(); + let obligations = + wf::obligations(infcx, tcx.param_env(impl1_def_id), impl1_def_id, 0, arg, span) + .unwrap(); assert!(!obligations.needs_infer()); impl2_predicates.extend( diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index 02548ae893f28..da35210023891 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -100,14 +100,14 @@ mod variance; use rustc_errors::{struct_span_err, ErrorGuaranteed}; use rustc_hir as hir; -use rustc_hir::def_id::DefId; -use rustc_hir::{Node, CRATE_HIR_ID}; +use rustc_hir::Node; use rustc_infer::infer::{InferOk, TyCtxtInferExt}; use rustc_middle::middle; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::util; use rustc_session::{config::EntryFnType, parse::feature_err}; +use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_span::{symbol::sym, Span, DUMMY_SP}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _; @@ -185,16 +185,15 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { let main_fnsig = tcx.fn_sig(main_def_id); let main_span = tcx.def_span(main_def_id); - fn main_fn_diagnostics_hir_id(tcx: TyCtxt<'_>, def_id: DefId, sp: Span) -> hir::HirId { + fn main_fn_diagnostics_def_id(tcx: TyCtxt<'_>, def_id: DefId, sp: Span) -> LocalDefId { if let Some(local_def_id) = def_id.as_local() { - let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id); let hir_type = tcx.type_of(local_def_id); if !matches!(hir_type.kind(), ty::FnDef(..)) { span_bug!(sp, "main has a non-function type: found `{}`", hir_type); } - hir_id + local_def_id } else { - CRATE_HIR_ID + CRATE_DEF_ID } } @@ -251,7 +250,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { } let mut error = false; - let main_diagnostics_hir_id = main_fn_diagnostics_hir_id(tcx, main_def_id, main_span); + let main_diagnostics_def_id = main_fn_diagnostics_def_id(tcx, main_def_id, main_span); let main_fn_generics = tcx.generics_of(main_def_id); let main_fn_predicates = tcx.predicates_of(main_def_id); if main_fn_generics.count() != 0 || !main_fnsig.bound_vars().is_empty() { @@ -326,7 +325,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { let param_env = ty::ParamEnv::empty(); let cause = traits::ObligationCause::new( return_ty_span, - main_diagnostics_hir_id, + main_diagnostics_def_id, ObligationCauseCode::MainFunctionType, ); let ocx = traits::ObligationCtxt::new(&infcx); @@ -356,7 +355,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { tcx, &ObligationCause::new( main_span, - main_diagnostics_hir_id, + main_diagnostics_def_id, ObligationCauseCode::MainFunctionType, ), se_ty, @@ -444,7 +443,11 @@ fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: DefId) { require_same_types( tcx, - &ObligationCause::new(start_span, start_id, ObligationCauseCode::StartFunctionType), + &ObligationCause::new( + start_span, + start_def_id, + ObligationCauseCode::StartFunctionType, + ), se_ty, tcx.mk_fn_ptr(tcx.fn_sig(start_def_id)), ); diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index b6f19d3cc684a..73aba2780d680 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -186,10 +186,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { prior_arm: Option<(Option, Ty<'tcx>, Span)>, ) { let hir = self.tcx.hir(); - // First, check that we're actually in the tail of a function. - let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Block(block, _), .. }) = - hir.get(self.body_id) else { return; }; + let Some(body_id) = hir.maybe_body_owned_by(self.body_id) else { return; }; + let body = hir.body(body_id); + let hir::ExprKind::Block(block, _) = body.value.kind else { return; }; let Some(hir::Stmt { kind: hir::StmtKind::Semi(last_expr), .. }) = block.innermost_block().stmts.last() else { return; }; if last_expr.hir_id != expr.hir_id { @@ -198,7 +198,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Next, make sure that we have no type expectation. let Some(ret) = hir - .find_by_def_id(self.body_id.owner.def_id) + .find_by_def_id(self.body_id) .and_then(|owner| owner.fn_decl()) .map(|decl| decl.output.span()) else { return; }; let Expectation::IsLast(stmt) = expectation else { diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index 57feefbcab6c8..8bbbf04c0cd47 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -43,7 +43,7 @@ pub(super) fn check_fn<'a, 'tcx>( let ret_ty = fcx.register_infer_ok_obligations(fcx.infcx.replace_opaque_types_with_inference_vars( declared_ret_ty, - body.value.hir_id, + fn_def_id, decl.output.span(), fcx.param_env, )); diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 12a2abfa76a92..329b69eff54a3 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -4,7 +4,6 @@ use super::{check_fn, Expectation, FnCtxt, GeneratorTypes}; use hir::def::DefKind; use rustc_hir as hir; -use rustc_hir::def_id::LocalDefId; use rustc_hir::lang_items::LangItem; use rustc_hir_analysis::astconv::AstConv; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; @@ -14,6 +13,7 @@ use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_middle::ty::subst::InternalSubsts; use rustc_middle::ty::visit::TypeVisitable; use rustc_middle::ty::{self, Ty, TypeSuperVisitable, TypeVisitor}; +use rustc_span::def_id::LocalDefId; use rustc_span::source_map::Span; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits; @@ -80,7 +80,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!(?bound_sig, ?liberated_sig); - let mut fcx = FnCtxt::new(self, self.param_env.without_const(), body.value.hir_id); + let mut fcx = FnCtxt::new(self, self.param_env.without_const(), closure.def_id); let generator_types = check_fn( &mut fcx, liberated_sig, @@ -620,8 +620,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // function. Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => { debug!("closure is async fn body"); - self.deduce_future_output_from_obligations(expr_def_id, body.id().hir_id) - .unwrap_or_else(|| { + let def_id = self.tcx.hir().body_owner_def_id(body.id()); + self.deduce_future_output_from_obligations(expr_def_id, def_id).unwrap_or_else( + || { // AFAIK, deducing the future output // always succeeds *except* in error cases // like #65159. I'd like to return Error @@ -630,7 +631,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // *have* reported an // error. --nikomatsakis astconv.ty_infer(None, decl.output.span()) - }) + }, + ) } _ => astconv.ty_infer(None, decl.output.span()), @@ -665,7 +667,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn deduce_future_output_from_obligations( &self, expr_def_id: LocalDefId, - body_id: hir::HirId, + body_def_id: LocalDefId, ) -> Option> { let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| { span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn") @@ -725,7 +727,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let InferOk { value: output_ty, obligations } = self .replace_opaque_types_with_inference_vars( output_ty, - body_id, + body_def_id, self.tcx.def_span(expr_def_id), self.param_env, ); diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index bc7474cdfcf3d..058984731040a 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -852,7 +852,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Point any obligations that were registered due to opaque type // inference at the return expression. self.select_obligations_where_possible(|errors| { - self.point_at_return_for_opaque_ty_error(errors, span, return_expr_ty); + self.point_at_return_for_opaque_ty_error(errors, span, return_expr_ty, return_expr.span); }); } } @@ -862,9 +862,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { errors: &mut Vec>, span: Span, return_expr_ty: Ty<'tcx>, + return_span: Span, ) { // Don't point at the whole block if it's empty - if span == self.tcx.hir().span(self.body_id) { + if span == return_span { return; } for err in errors { @@ -1374,7 +1375,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let body = self.tcx.hir().body(anon_const.body); // Create a new function context. - let fcx = FnCtxt::new(self, self.param_env.with_const(), body.value.hir_id); + let def_id = anon_const.def_id; + let fcx = FnCtxt::new(self, self.param_env.with_const(), def_id); crate::GatherLocalsVisitor::new(&fcx).visit_body(body); let ty = fcx.check_expr_with_expectation(&body.value, expected); @@ -2151,13 +2153,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { variant: &'tcx ty::VariantDef, access_span: Span, ) -> Vec { + let body_owner_hir_id = self.tcx.hir().local_def_id_to_hir_id(self.body_id); variant .fields .iter() .filter(|field| { let def_scope = self .tcx - .adjust_ident_and_get_scope(field.ident(self.tcx), variant.def_id, self.body_id) + .adjust_ident_and_get_scope( + field.ident(self.tcx), + variant.def_id, + body_owner_hir_id, + ) .1; field.vis.is_accessible_from(def_scope, self.tcx) && !matches!( @@ -2199,8 +2206,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match deref_base_ty.kind() { ty::Adt(base_def, substs) if !base_def.is_enum() => { debug!("struct named {:?}", deref_base_ty); + let body_hir_id = self.tcx.hir().local_def_id_to_hir_id(self.body_id); let (ident, def_scope) = - self.tcx.adjust_ident_and_get_scope(field, base_def.did(), self.body_id); + self.tcx.adjust_ident_and_get_scope(field, base_def.did(), body_hir_id); let fields = &base_def.non_enum_variant().fields; if let Some(index) = fields .iter() @@ -2538,7 +2546,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } fn point_at_param_definition(&self, err: &mut Diagnostic, param: ty::ParamTy) { - let generics = self.tcx.generics_of(self.body_id.owner.to_def_id()); + let generics = self.tcx.generics_of(self.body_id); let generic_param = generics.type_param(¶m, self.tcx); if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind { return; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index c9609e6943981..a6d96881c8f29 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -2126,7 +2126,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match *callee_ty.kind() { ty::Param(param) => { let param = - self.tcx.generics_of(self.body_id.owner).type_param(¶m, self.tcx); + self.tcx.generics_of(self.body_id).type_param(¶m, self.tcx); if param.kind.is_synthetic() { // if it's `impl Fn() -> ..` then just fall down to the def-id based logic def_id = param.def_id; @@ -2135,7 +2135,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // and point at that. let instantiated = self .tcx - .explicit_predicates_of(self.body_id.owner) + .explicit_predicates_of(self.body_id) .instantiate_identity(self.tcx); // FIXME(compiler-errors): This could be problematic if something has two // fn-like predicates with different args, but callable types really never diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index 428fde642bc09..8724e69cc5134 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -10,7 +10,7 @@ pub use suggestions::*; use crate::coercion::DynamicCoerceMany; use crate::{Diverges, EnclosingBreakables, Inherited}; use rustc_hir as hir; -use rustc_hir::def_id::DefId; +use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir_analysis::astconv::AstConv; use rustc_infer::infer; use rustc_infer::infer::error_reporting::TypeErrCtxt; @@ -38,7 +38,7 @@ use std::ops::Deref; /// [`ItemCtxt`]: rustc_hir_analysis::collect::ItemCtxt /// [`InferCtxt`]: infer::InferCtxt pub struct FnCtxt<'a, 'tcx> { - pub(super) body_id: hir::HirId, + pub(super) body_id: LocalDefId, /// The parameter environment used for proving trait obligations /// in this function. This can change when we descend into @@ -117,7 +117,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn new( inh: &'a Inherited<'tcx>, param_env: ty::ParamEnv<'tcx>, - body_id: hir::HirId, + body_id: LocalDefId, ) -> FnCtxt<'a, 'tcx> { FnCtxt { body_id, @@ -204,7 +204,7 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { } fn item_def_id(&self) -> DefId { - self.body_id.owner.to_def_id() + self.body_id.to_def_id() } fn get_type_parameter_bounds( diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 4d673ac91472f..6046e55c65c18 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -31,7 +31,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.typeck_results .borrow() .liberated_fn_sigs() - .get(self.tcx.hir().parent_id(self.body_id)) + .get(self.tcx.hir().local_def_id_to_hir_id(self.body_id)) .copied() } @@ -164,7 +164,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, ty: Ty<'tcx>, ) -> Option<(DefIdOrName, Ty<'tcx>, Vec>)> { - self.err_ctxt().extract_callable_info(self.body_id, self.param_env, ty) + let body_hir_id = self.tcx.hir().local_def_id_to_hir_id(self.body_id); + self.err_ctxt().extract_callable_info(body_hir_id, self.param_env, ty) } pub fn suggest_two_fn_call( diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 7ddf9eaa4d899..bb487facc23fd 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -201,7 +201,7 @@ fn typeck_with_fallback<'tcx>( let typeck_results = Inherited::build(tcx, def_id).enter(|inh| { let param_env = tcx.param_env(def_id); - let mut fcx = FnCtxt::new(&inh, param_env, body.value.hir_id); + let mut fcx = FnCtxt::new(&inh, param_env, def_id); if let Some(hir::FnSig { header, decl, .. }) = fn_sig { let fn_sig = if rustc_hir_analysis::collect::get_infer_ret_ty(&decl.output).is_some() { diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 9c06a22315bcb..939f9c93a02ca 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -508,9 +508,10 @@ fn method_autoderef_steps<'tcx>( let (ref infcx, goal, inference_vars) = tcx.infer_ctxt().build_with_canonical(DUMMY_SP, &goal); let ParamEnvAnd { param_env, value: self_ty } = goal; - let mut autoderef = Autoderef::new(infcx, param_env, hir::CRATE_HIR_ID, DUMMY_SP, self_ty) - .include_raw_pointers() - .silence_errors(); + let mut autoderef = + Autoderef::new(infcx, param_env, hir::def_id::CRATE_DEF_ID, DUMMY_SP, self_ty) + .include_raw_pointers() + .silence_errors(); let mut reached_raw_pointer = false; let mut steps: Vec<_> = autoderef .by_ref() @@ -610,10 +611,9 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { fn push_candidate(&mut self, candidate: Candidate<'tcx>, is_inherent: bool) { let is_accessible = if let Some(name) = self.method_name { let item = candidate.item; - let def_scope = self - .tcx - .adjust_ident_and_get_scope(name, item.container_id(self.tcx), self.body_id) - .1; + let hir_id = self.tcx.hir().local_def_id_to_hir_id(self.body_id); + let def_scope = + self.tcx.adjust_ident_and_get_scope(name, item.container_id(self.tcx), hir_id).1; item.visibility(self.tcx).is_accessible_from(def_scope, self.tcx) } else { true diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 8c54e9bdb5fb3..7a2791b11bfdd 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -352,7 +352,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty_span = match rcvr_ty.kind() { ty::Param(param_type) => { - Some(param_type.span_from_generics(self.tcx, self.body_id.owner.to_def_id())) + Some(param_type.span_from_generics(self.tcx, self.body_id.to_def_id())) } ty::Adt(def, _) if def.did().is_local() => Some(tcx.def_span(def.did())), _ => None, @@ -403,7 +403,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { args, sugg_span, ); - self.note_candidates_on_method_error( rcvr_ty, item_name, @@ -496,9 +495,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::Param(_) => { // Account for `fn` items like in `issue-35677.rs` to // suggest restricting its type params. - let parent_body = - hir.body_owner(hir::BodyId { hir_id: self.body_id }); - Some(hir.get(parent_body)) + Some(hir.get_by_def_id(self.body_id)) } ty::Adt(def, _) => { def.did().as_local().map(|def_id| hir.get_by_def_id(def_id)) @@ -1343,7 +1340,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => None, }); if let Some((field, field_ty)) = field_receiver { - let scope = tcx.parent_module(self.body_id); + let scope = tcx.parent_module_from_def_id(self.body_id); let is_accessible = field.vis.is_accessible_from(scope, tcx); if is_accessible { @@ -1593,7 +1590,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { else { return }; let map = self.infcx.tcx.hir(); - let body = map.body(rustc_hir::BodyId { hir_id: self.body_id }); + let body_id = self.tcx.hir().body_owned_by(self.body_id); + let body = map.body(body_id); struct LetVisitor<'a> { result: Option<&'a hir::Expr<'a>>, ident_name: Symbol, @@ -2195,7 +2193,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { true }); - let module_did = self.tcx.parent_module(self.body_id); + let module_did = self.tcx.parent_module_from_def_id(self.body_id); let (module, _, _) = self.tcx.hir().get_module(module_did); let span = module.spans.inject_use_span; @@ -2517,7 +2515,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Obtain the span for `param` and use it for a structured suggestion. if let Some(param) = param_type { - let generics = self.tcx.generics_of(self.body_id.owner.to_def_id()); + let generics = self.tcx.generics_of(self.body_id.to_def_id()); let type_param = generics.type_param(param, self.tcx); let hir = self.tcx.hir(); if let Some(def_id) = type_param.def_id.as_local() { diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 28fd03b878b2b..a98ce36df096f 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -1844,16 +1844,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } } - // In some (most?) cases cause.body_id points to actual body, but in some cases - // it's an actual definition. According to the comments (e.g. in - // rustc_hir_analysis/check/compare_impl_item.rs:compare_predicate_entailment) the latter - // is relied upon by some other code. This might (or might not) need cleanup. - let body_owner_def_id = - self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| { - self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id }) - }); self.check_and_note_conflicting_crates(diag, terr); - self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id()); + self.tcx.note_and_explain_type_err(diag, terr, cause, span, cause.body_id.to_def_id()); if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind() diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index 5b02956a106c6..976a8a90ef088 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -411,8 +411,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { span: Span, ) { let hir = self.tcx.hir(); - let fn_hir_id = hir.parent_id(cause.body_id); - if let Some(node) = self.tcx.hir().find(fn_hir_id) && + if let Some(node) = self.tcx.hir().find_by_def_id(cause.body_id) && let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_sig, _, body_id), .. }) = node { diff --git a/compiler/rustc_infer/src/infer/opaque_types.rs b/compiler/rustc_infer/src/infer/opaque_types.rs index c54c66eab2799..b68b0baaa4062 100644 --- a/compiler/rustc_infer/src/infer/opaque_types.rs +++ b/compiler/rustc_infer/src/infer/opaque_types.rs @@ -3,7 +3,7 @@ use crate::infer::{DefiningAnchor, InferCtxt, InferOk}; use crate::traits; use hir::def::DefKind; use hir::def_id::{DefId, LocalDefId}; -use hir::{HirId, OpaqueTyOrigin}; +use hir::OpaqueTyOrigin; use rustc_data_structures::sync::Lrc; use rustc_data_structures::vec_map::VecMap; use rustc_hir as hir; @@ -48,7 +48,7 @@ impl<'tcx> InferCtxt<'tcx> { pub fn replace_opaque_types_with_inference_vars>( &self, value: T, - body_id: HirId, + body_id: LocalDefId, span: Span, param_env: ty::ParamEnv<'tcx>, ) -> InferOk<'tcx, T> { diff --git a/compiler/rustc_infer/src/traits/mod.rs b/compiler/rustc_infer/src/traits/mod.rs index 026713b6a28b8..3a82899660b19 100644 --- a/compiler/rustc_infer/src/traits/mod.rs +++ b/compiler/rustc_infer/src/traits/mod.rs @@ -8,6 +8,7 @@ mod project; mod structural_impls; pub mod util; +use hir::def_id::LocalDefId; use rustc_hir as hir; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{self, Const, ToPredicate, Ty, TyCtxt}; @@ -146,7 +147,7 @@ impl<'tcx, O> Obligation<'tcx, O> { pub fn misc( tcx: TyCtxt<'tcx>, span: Span, - body_id: hir::HirId, + body_id: LocalDefId, param_env: ty::ParamEnv<'tcx>, trait_ref: impl ToPredicate<'tcx, O>, ) -> Obligation<'tcx, O> { diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index fe188162cf85b..f27fd90c55c2a 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -732,7 +732,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations { cx.tcx, param_env, ty, - traits::ObligationCause::misc(item.span, item.hir_id()), + traits::ObligationCause::misc(item.span, item.owner_id.def_id), ) .is_ok() { diff --git a/compiler/rustc_lint/src/for_loops_over_fallibles.rs b/compiler/rustc_lint/src/for_loops_over_fallibles.rs index 5219992ee94f0..1add352e0c42d 100644 --- a/compiler/rustc_lint/src/for_loops_over_fallibles.rs +++ b/compiler/rustc_lint/src/for_loops_over_fallibles.rs @@ -139,9 +139,10 @@ fn suggest_question_mark<'tcx>( let ty = substs.type_at(0); let infcx = cx.tcx.infer_ctxt().build(); + let body_def_id = cx.tcx.hir().body_owner_def_id(body_id); let cause = ObligationCause::new( span, - body_id.hir_id, + body_def_id, rustc_infer::traits::ObligationCauseCode::MiscObligation, ); let errors = rustc_trait_selection::traits::fully_solve_bound( diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index d00b26a5a3d0b..f6fae8ab55274 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -18,7 +18,8 @@ use crate::ty::{self, AdtKind, Ty, TyCtxt}; use rustc_data_structures::sync::Lrc; use rustc_errors::{Applicability, Diagnostic}; use rustc_hir as hir; -use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::def_id::DefId; +use rustc_span::def_id::{LocalDefId, CRATE_DEF_ID}; use rustc_span::symbol::Symbol; use rustc_span::{Span, DUMMY_SP}; use smallvec::SmallVec; @@ -99,7 +100,7 @@ pub struct ObligationCause<'tcx> { /// (in particular, closures can add new assumptions). See the /// field `region_obligations` of the `FulfillmentContext` for more /// information. - pub body_id: hir::HirId, + pub body_id: LocalDefId, code: InternedObligationCauseCode<'tcx>, } @@ -120,13 +121,13 @@ impl<'tcx> ObligationCause<'tcx> { #[inline] pub fn new( span: Span, - body_id: hir::HirId, + body_id: LocalDefId, code: ObligationCauseCode<'tcx>, ) -> ObligationCause<'tcx> { ObligationCause { span, body_id, code: code.into() } } - pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> { + pub fn misc(span: Span, body_id: LocalDefId) -> ObligationCause<'tcx> { ObligationCause::new(span, body_id, MiscObligation) } @@ -137,7 +138,7 @@ impl<'tcx> ObligationCause<'tcx> { #[inline(always)] pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> { - ObligationCause { span, body_id: hir::CRATE_HIR_ID, code: Default::default() } + ObligationCause { span, body_id: CRATE_DEF_ID, code: Default::default() } } pub fn span(&self) -> Span { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index f83bceca3b53b..4af29fcbfb586 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -2437,6 +2437,7 @@ impl<'tcx> TyCtxt<'tcx> { ident } + // FIXME(vincenzoapalzzo): move the HirId to a LocalDefId pub fn adjust_ident_and_get_scope( self, mut ident: Ident, diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index 7f3519945c3fe..b0d24af958dd7 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -5,6 +5,7 @@ use rustc_middle::mir::{self, Field}; use rustc_middle::thir::{FieldPat, Pat, PatKind}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_session::lint; +use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::Span; use rustc_trait_selection::traits::predicate_for_trait_def; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; @@ -189,10 +190,11 @@ impl<'tcx> ConstToPat<'tcx> { // using `PartialEq::eq` in this scenario in the past.) let partial_eq_trait_id = self.tcx().require_lang_item(hir::LangItem::PartialEq, Some(self.span)); + let def_id = self.tcx().hir().opt_local_def_id(self.id).unwrap_or(CRATE_DEF_ID); let obligation: PredicateObligation<'_> = predicate_for_trait_def( self.tcx(), self.param_env, - ObligationCause::misc(self.span, self.id), + ObligationCause::misc(self.span, def_id), partial_eq_trait_id, 0, [ty, ty], diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 225c1050c7c95..ecee0bf7a6d1b 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -17,7 +17,6 @@ use crate::traits::{ use rustc_data_structures::fx::FxIndexSet; use rustc_errors::Diagnostic; use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE}; -use rustc_hir::CRATE_HIR_ID; use rustc_infer::infer::{DefiningAnchor, InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::util; use rustc_middle::traits::specialization_graph::OverlapMode; @@ -382,18 +381,14 @@ fn resolve_negative_obligation<'tcx>( return false; } - let (body_id, body_def_id) = if let Some(body_def_id) = body_def_id.as_local() { - (tcx.hir().local_def_id_to_hir_id(body_def_id), body_def_id) - } else { - (CRATE_HIR_ID, CRATE_DEF_ID) - }; + let body_def_id = body_def_id.as_local().unwrap_or(CRATE_DEF_ID); let ocx = ObligationCtxt::new(&infcx); let wf_tys = ocx.assumed_wf_types(param_env, DUMMY_SP, body_def_id); let outlives_env = OutlivesEnvironment::with_bounds( param_env, Some(&infcx), - infcx.implied_bounds_tys(param_env, body_id, wf_tys), + infcx.implied_bounds_tys(param_env, body_def_id, wf_tys), ); infcx.process_registered_region_obligations(outlives_env.region_bound_pairs(), param_env); diff --git a/compiler/rustc_trait_selection/src/traits/engine.rs b/compiler/rustc_trait_selection/src/traits/engine.rs index 369f80139a806..a2ddd91546c18 100644 --- a/compiler/rustc_trait_selection/src/traits/engine.rs +++ b/compiler/rustc_trait_selection/src/traits/engine.rs @@ -190,8 +190,7 @@ impl<'a, 'tcx> ObligationCtxt<'a, 'tcx> { let tcx = self.infcx.tcx; let assumed_wf_types = tcx.assumed_wf_types(def_id); let mut implied_bounds = FxIndexSet::default(); - let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); - let cause = ObligationCause::misc(span, hir_id); + let cause = ObligationCause::misc(span, def_id); for ty in assumed_wf_types { // FIXME(@lcnr): rustc currently does not check wf for types // pre-normalization, meaning that implied bounds are sometimes diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/ambiguity.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/ambiguity.rs index 0419bb3f724f9..6bf453c3ff084 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/ambiguity.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/ambiguity.rs @@ -81,7 +81,7 @@ pub fn recompute_applicable_impls<'tcx>( ); let predicates = - tcx.predicates_of(obligation.cause.body_id.owner.to_def_id()).instantiate_identity(tcx); + tcx.predicates_of(obligation.cause.body_id.to_def_id()).instantiate_identity(tcx); for obligation in elaborate_predicates_with_span(tcx, predicates.into_iter()) { let kind = obligation.predicate.kind(); if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = kind.skip_binder() diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index 52971486c553e..aaeb3def06ac3 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -839,14 +839,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.note(s.as_str()); } if let Some(ref s) = parent_label { - let body = tcx - .hir() - .opt_local_def_id(obligation.cause.body_id) - .unwrap_or_else(|| { - tcx.hir().body_owner_def_id(hir::BodyId { - hir_id: obligation.cause.body_id, - }) - }); + let body = obligation.cause.body_id; err.span_label(tcx.def_span(body), s); } @@ -934,6 +927,8 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ); } + let body_hir_id = + self.tcx.hir().local_def_id_to_hir_id(obligation.cause.body_id); // Try to report a help message if is_fn_trait && let Ok((implemented_kind, params)) = self.type_implements_fn_trait( @@ -1014,7 +1009,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if !self.report_similar_impl_candidates( impl_candidates, trait_ref, - obligation.cause.body_id, + body_hir_id, &mut err, true, ) { @@ -1050,7 +1045,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { self.report_similar_impl_candidates( impl_candidates, trait_ref, - obligation.cause.body_id, + body_hir_id, &mut err, true, ); @@ -2305,10 +2300,12 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { predicate.to_opt_poly_trait_pred().unwrap(), ); if impl_candidates.len() < 10 { + let hir = + self.tcx.hir().local_def_id_to_hir_id(obligation.cause.body_id); self.report_similar_impl_candidates( impl_candidates, trait_ref, - body_id.map(|id| id.hir_id).unwrap_or(obligation.cause.body_id), + body_id.map(|id| id.hir_id).unwrap_or(hir), &mut err, false, ); diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs index 18d308f7123ae..a3209d35e58be 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs @@ -149,10 +149,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { .unwrap_or_else(|| (trait_ref.def_id(), trait_ref.skip_binder().substs)); let trait_ref = trait_ref.skip_binder(); - let mut flags = vec![( - sym::ItemContext, - self.describe_enclosure(obligation.cause.body_id).map(|s| s.to_owned()), - )]; + let body_hir = self.tcx.hir().local_def_id_to_hir_id(obligation.cause.body_id); + let mut flags = + vec![(sym::ItemContext, self.describe_enclosure(body_hir).map(|s| s.to_owned()))]; match obligation.cause.code() { ObligationCauseCode::BuiltinDerivedObligation(..) diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 39e50b2accf17..bf5e77e6ce12f 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -9,7 +9,6 @@ use crate::infer::InferCtxt; use crate::traits::{NormalizeExt, ObligationCtxt}; use hir::def::CtorOf; -use hir::{Expr, HirId}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::{ @@ -22,6 +21,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node}; +use rustc_hir::{Expr, HirId}; use rustc_infer::infer::error_reporting::TypeErrCtxt; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{InferOk, LateBoundRegionConversionTime}; @@ -34,6 +34,7 @@ use rustc_middle::ty::{ IsSuggestable, ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable, TypeckResults, }; +use rustc_span::def_id::LocalDefId; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::{BytePos, DesugaringKind, ExpnKind, MacroKind, Span, DUMMY_SP}; use rustc_target::spec::abi; @@ -179,7 +180,7 @@ pub trait TypeErrCtxtExt<'tcx> { err: &mut Diagnostic, trait_pred: ty::PolyTraitPredicate<'tcx>, associated_item: Option<(&'static str, Ty<'tcx>)>, - body_id: hir::HirId, + body_id: LocalDefId, ); fn suggest_dereferences( @@ -522,7 +523,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { mut err: &mut Diagnostic, trait_pred: ty::PolyTraitPredicate<'tcx>, associated_ty: Option<(&'static str, Ty<'tcx>)>, - body_id: hir::HirId, + body_id: LocalDefId, ) { let trait_pred = self.resolve_numeric_literals_with_default(trait_pred); @@ -535,8 +536,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we // don't suggest `T: Sized + ?Sized`. - let mut hir_id = body_id; - while let Some(node) = self.tcx.hir().find(hir_id) { + let mut body_id = body_id; + while let Some(node) = self.tcx.hir().find_by_def_id(body_id) { + let hir_id = self.tcx.hir().local_def_id_to_hir_id(body_id); match node { hir::Node::Item(hir::Item { ident, @@ -713,8 +715,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { _ => {} } - - hir_id = self.tcx.hir().get_parent_item(hir_id).into(); + body_id = self.tcx.local_parent(body_id); } } @@ -905,8 +906,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { trait_pred.self_ty(), ); + let body_hir_id = self.tcx.hir().local_def_id_to_hir_id(obligation.cause.body_id); let Some((def_id_or_name, output, inputs)) = self.extract_callable_info( - obligation.cause.body_id, + body_hir_id, obligation.param_env, self_ty, ) else { return false; }; @@ -1004,8 +1006,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { span.remove_mark(); } let mut expr_finder = FindExprBySpan::new(span); - let Some(hir::Node::Expr(body)) = self.tcx.hir().find(obligation.cause.body_id) else { return; }; - expr_finder.visit_expr(&body); + let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else { return; }; + let body = self.tcx.hir().body(body_id); + expr_finder.visit_expr(body.value); let Some(expr) = expr_finder.result else { return; }; let Some(typeck) = &self.typeck_results else { return; }; let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else { return; }; @@ -1060,8 +1063,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ) -> bool { let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty()); let ty = self.tcx.erase_late_bound_regions(self_ty); - let owner = self.tcx.hir().get_parent_item(obligation.cause.body_id); - let Some(generics) = self.tcx.hir().get_generics(owner.def_id) else { return false }; + let Some(generics) = self.tcx.hir().get_generics(obligation.cause.body_id) else { return false }; let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false }; let ty::Param(param) = inner_ty.kind() else { return false }; let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() else { return false }; @@ -1104,6 +1106,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { /// Extracts information about a callable type for diagnostics. This is a /// heuristic -- it doesn't necessarily mean that a type is always callable, /// because the callable type must also be well-formed to be called. + // FIXME(vincenzopalazzo): move the HirId to a LocalDefId fn extract_callable_info( &self, hir_id: HirId, @@ -1429,10 +1432,11 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { span.remove_mark(); } let mut expr_finder = super::FindExprBySpan::new(span); - let Some(hir::Node::Expr(body)) = self.tcx.hir().find(obligation.cause.body_id) else { + let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else { return false; }; - expr_finder.visit_expr(&body); + let body = self.tcx.hir().body(body_id); + expr_finder.visit_expr(body.value); let mut maybe_suggest = |suggested_ty, count, suggestions| { // Remapping bound vars here let trait_pred_and_suggested_ty = @@ -1670,8 +1674,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> bool { let hir = self.tcx.hir(); - let parent_node = hir.parent_id(obligation.cause.body_id); - let node = hir.find(parent_node); + let node = hir.find_by_def_id(obligation.cause.body_id); if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind && sig.decl.output.span().overlaps(span) @@ -1707,8 +1710,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option { let hir = self.tcx.hir(); - let parent_node = hir.parent_id(obligation.cause.body_id); - let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else { + let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find_by_def_id(obligation.cause.body_id) else { return None; }; @@ -1732,8 +1734,8 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } let hir = self.tcx.hir(); - let fn_hir_id = hir.parent_id(obligation.cause.body_id); - let node = hir.find(fn_hir_id); + let fn_hir_id = hir.local_def_id_to_hir_id(obligation.cause.body_id); + let node = hir.find_by_def_id(obligation.cause.body_id); let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. @@ -1806,7 +1808,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { match liberated_sig.output().kind() { ty::Dynamic(predicates, _, ty::Dyn) => { - let cause = ObligationCause::misc(ret_ty.span, fn_hir_id); + let cause = ObligationCause::misc(ret_ty.span, obligation.cause.body_id); let param_env = ty::ParamEnv::empty(); if !only_never_return { @@ -1944,8 +1946,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } let hir = self.tcx.hir(); - let parent_node = hir.parent_id(obligation.cause.body_id); - let node = hir.find(parent_node); + let node = hir.find_by_def_id(obligation.cause.body_id); if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) = node { @@ -3283,12 +3284,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { trait_pred: ty::PolyTraitPredicate<'tcx>, span: Span, ) { - let body_hir_id = obligation.cause.body_id; - let item_id = self.tcx.hir().parent_id(body_hir_id); - - if let Some(body_id) = - self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id)) - { + if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) { let body = self.tcx.hir().body(body_id); if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind { let future_trait = self.tcx.require_lang_item(LangItem::Future, None); @@ -3727,9 +3723,14 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { term: ty_var.into(), }, ))); + let body_def_id = self.tcx.hir().enclosing_body_owner(body_id); // Add `::Item = _` obligation. ocx.register_obligation(Obligation::misc( - self.tcx, span, body_id, param_env, projection, + self.tcx, + span, + body_def_id, + param_env, + projection, )); if ocx.select_where_possible().is_empty() { // `ty_var` now holds the type that `Item` is for `ExprTy`. diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 3c640cdc503ce..83458017e00f0 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -26,12 +26,11 @@ use crate::infer::{InferCtxt, TyCtxtInferExt}; use crate::traits::error_reporting::TypeErrCtxtExt as _; use crate::traits::query::evaluate_obligation::InferCtxtExt as _; use rustc_errors::ErrorGuaranteed; -use rustc_hir as hir; -use rustc_hir::def_id::DefId; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::visit::TypeVisitable; use rustc_middle::ty::{self, DefIdTree, ToPredicate, Ty, TyCtxt, TypeSuperVisitable}; use rustc_middle::ty::{InternalSubsts, SubstsRef}; +use rustc_span::def_id::{DefId, CRATE_DEF_ID}; use rustc_span::Span; use std::fmt::Debug; @@ -151,7 +150,7 @@ fn pred_known_to_hold_modulo_regions<'tcx>( // We can use a dummy node-id here because we won't pay any mind // to region obligations that arise (there shouldn't really be any // anyhow). - cause: ObligationCause::misc(span, hir::CRATE_HIR_ID), + cause: ObligationCause::misc(span, CRATE_DEF_ID), recursion_depth: 0, predicate: pred.to_predicate(infcx.tcx), }; @@ -166,14 +165,12 @@ fn pred_known_to_hold_modulo_regions<'tcx>( // that guess. While imperfect, I believe this is sound. // FIXME(@lcnr): this function doesn't seem right. + // // The handling of regions in this area of the code is terrible, // see issue #29149. We should be able to improve on this with // NLL. let errors = fully_solve_obligation(infcx, obligation); - // Note: we only assume something is `Copy` if we can - // *definitively* show that it implements `Copy`. Otherwise, - // assume it is move; linear is always ok. match &errors[..] { [] => true, errors => { diff --git a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs index f2c5f730b31b9..6cb64ad574f5b 100644 --- a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs @@ -3,9 +3,8 @@ use crate::traits::query::type_op::{self, TypeOp, TypeOpOutput}; use crate::traits::query::NoSolution; use crate::traits::ObligationCause; use rustc_data_structures::fx::FxIndexSet; -use rustc_hir as hir; -use rustc_hir::HirId; use rustc_middle::ty::{self, ParamEnv, Ty}; +use rustc_span::def_id::LocalDefId; pub use rustc_middle::traits::query::OutlivesBound; @@ -14,14 +13,14 @@ pub trait InferCtxtExt<'a, 'tcx> { fn implied_outlives_bounds( &self, param_env: ty::ParamEnv<'tcx>, - body_id: hir::HirId, + body_id: LocalDefId, ty: Ty<'tcx>, ) -> Vec>; fn implied_bounds_tys( &'a self, param_env: ty::ParamEnv<'tcx>, - body_id: hir::HirId, + body_id: LocalDefId, tys: FxIndexSet>, ) -> Bounds<'a, 'tcx>; } @@ -50,10 +49,10 @@ impl<'a, 'tcx: 'a> InferCtxtExt<'a, 'tcx> for InferCtxt<'tcx> { fn implied_outlives_bounds( &self, param_env: ty::ParamEnv<'tcx>, - body_id: hir::HirId, + body_id: LocalDefId, ty: Ty<'tcx>, ) -> Vec> { - let span = self.tcx.hir().span(body_id); + let span = self.tcx.def_span(body_id); let result = param_env .and(type_op::implied_outlives_bounds::ImpliedOutlivesBounds { ty }) .fully_perform(self); @@ -102,7 +101,7 @@ impl<'a, 'tcx: 'a> InferCtxtExt<'a, 'tcx> for InferCtxt<'tcx> { fn implied_bounds_tys( &'a self, param_env: ParamEnv<'tcx>, - body_id: HirId, + body_id: LocalDefId, tys: FxIndexSet>, ) -> Bounds<'a, 'tcx> { tys.into_iter() diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 12d4cb4fc6920..d9556848099f1 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -1,10 +1,10 @@ use crate::infer::InferCtxt; use crate::traits; use rustc_hir as hir; -use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable}; +use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::Span; use std::iter; @@ -17,7 +17,7 @@ use std::iter; pub fn obligations<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, - body_id: hir::HirId, + body_id: LocalDefId, recursion_depth: usize, arg: GenericArg<'tcx>, span: Span, @@ -82,7 +82,7 @@ pub fn obligations<'tcx>( pub fn trait_obligations<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, - body_id: hir::HirId, + body_id: LocalDefId, trait_pred: &ty::TraitPredicate<'tcx>, span: Span, item: &'tcx hir::Item<'tcx>, @@ -105,7 +105,7 @@ pub fn trait_obligations<'tcx>( pub fn predicate_obligations<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, - body_id: hir::HirId, + body_id: LocalDefId, predicate: ty::Predicate<'tcx>, span: Span, ) -> Vec> { @@ -167,7 +167,7 @@ pub fn predicate_obligations<'tcx>( struct WfPredicates<'tcx> { tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, - body_id: hir::HirId, + body_id: LocalDefId, span: Span, out: Vec>, recursion_depth: usize, diff --git a/compiler/rustc_traits/src/implied_outlives_bounds.rs b/compiler/rustc_traits/src/implied_outlives_bounds.rs index 7d2d8433c932d..fe633d687d91b 100644 --- a/compiler/rustc_traits/src/implied_outlives_bounds.rs +++ b/compiler/rustc_traits/src/implied_outlives_bounds.rs @@ -2,13 +2,13 @@ //! Do not call this query directory. See //! [`rustc_trait_selection::traits::query::type_op::implied_outlives_bounds`]. -use rustc_hir as hir; use rustc_infer::infer::canonical::{self, Canonical}; use rustc_infer::infer::outlives::components::{push_outlives_components, Component}; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::query::OutlivesBound; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable}; +use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::source_map::DUMMY_SP; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::traits::query::{CanonicalTyGoal, Fallible, NoSolution}; @@ -67,9 +67,8 @@ fn compute_implied_outlives_bounds<'tcx>( // FIXME(@lcnr): It's not really "always fine", having fewer implied // bounds can be backward incompatible, e.g. #101951 was caused by // us not dealing with inference vars in `TypeOutlives` predicates. - let obligations = - wf::obligations(ocx.infcx, param_env, hir::CRATE_HIR_ID, 0, arg, DUMMY_SP) - .unwrap_or_default(); + let obligations = wf::obligations(ocx.infcx, param_env, CRATE_DEF_ID, 0, arg, DUMMY_SP) + .unwrap_or_default(); // While these predicates should all be implied by other parts of // the program, they are still relevant as they may constrain diff --git a/compiler/rustc_traits/src/type_op.rs b/compiler/rustc_traits/src/type_op.rs index f35c5e44882df..27dc16259926b 100644 --- a/compiler/rustc_traits/src/type_op.rs +++ b/compiler/rustc_traits/src/type_op.rs @@ -6,6 +6,7 @@ use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, FnSig, Lift, PolyFnSig, Ty, TyCtxt, TypeFoldable}; use rustc_middle::ty::{ParamEnvAnd, Predicate}; use rustc_middle::ty::{UserSelfTy, UserSubsts, UserType}; +use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::{Span, DUMMY_SP}; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt; @@ -76,7 +77,6 @@ fn relate_mir_and_user_ty<'tcx>( // FIXME(#104764): We should check well-formedness before normalization. let predicate = ty::Binder::dummy(ty::PredicateKind::WellFormed(user_ty.into())); ocx.register_obligation(Obligation::new(ocx.infcx.tcx, cause, param_env, predicate)); - Ok(()) } @@ -111,7 +111,7 @@ fn relate_mir_and_user_substs<'tcx>( let span = if span == DUMMY_SP { predicate_span } else { span }; let cause = ObligationCause::new( span, - hir::CRATE_HIR_ID, + CRATE_DEF_ID, ObligationCauseCode::AscribeUserTypeProvePredicate(predicate_span), ); let instantiated_predicate = @@ -126,7 +126,6 @@ fn relate_mir_and_user_substs<'tcx>( let impl_self_ty = ocx.normalize(&cause, param_env, impl_self_ty); ocx.eq(&cause, param_env, self_ty, impl_self_ty)?; - let predicate = ty::Binder::dummy(ty::PredicateKind::WellFormed(impl_self_ty.into())); ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, predicate)); } diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index eb5454bf2634b..13a7664869016 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -1,8 +1,8 @@ use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; -use rustc_hir::def_id::DefId; use rustc_middle::ty::{self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt}; use rustc_session::config::TraitSolver; +use rustc_span::def_id::{DefId, CRATE_DEF_ID}; use rustc_trait_selection::traits; fn sized_constraint_for_ty<'tcx>( @@ -208,14 +208,7 @@ fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> { constness, ); - let body_id = - local_did.and_then(|id| tcx.hir().maybe_body_owned_by(id).map(|body| body.hir_id)); - let body_id = match body_id { - Some(id) => id, - None if hir_id.is_some() => hir_id.unwrap(), - _ => hir::CRATE_HIR_ID, - }; - + let body_id = local_did.unwrap_or(CRATE_DEF_ID); let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id); traits::normalize_param_env_or_error(tcx, unnormalized_env, cause) } diff --git a/src/tools/clippy/clippy_lints/src/future_not_send.rs b/src/tools/clippy/clippy_lints/src/future_not_send.rs index 989f83cf80d59..2a79b18b82994 100644 --- a/src/tools/clippy/clippy_lints/src/future_not_send.rs +++ b/src/tools/clippy/clippy_lints/src/future_not_send.rs @@ -78,7 +78,8 @@ impl<'tcx> LateLintPass<'tcx> for FutureNotSend { let send_trait = cx.tcx.get_diagnostic_item(sym::Send).unwrap(); let span = decl.output.span(); let infcx = cx.tcx.infer_ctxt().build(); - let cause = traits::ObligationCause::misc(span, hir_id); + let def_id = cx.tcx.hir().local_def_id(hir_id); + let cause = traits::ObligationCause::misc(span, def_id); let send_errors = traits::fully_solve_bound(&infcx, cause, cx.param_env, ret_ty, send_trait); if !send_errors.is_empty() { span_lint_and_then( diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index 9263f0519724b..b812e81cb107b 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -371,7 +371,7 @@ fn can_change_type<'a>(cx: &LateContext<'a>, mut expr: &'a Expr<'a>, mut ty: Ty< && let output_ty = return_ty(cx, item.hir_id()) && let local_def_id = cx.tcx.hir().local_def_id(item.hir_id()) && Inherited::build(cx.tcx, local_def_id).enter(|inherited| { - let fn_ctxt = FnCtxt::new(inherited, cx.param_env, item.hir_id()); + let fn_ctxt = FnCtxt::new(inherited, cx.param_env, local_def_id); fn_ctxt.can_coerce(ty, output_ty) }) { if has_lifetime(output_ty) && has_lifetime(ty) { diff --git a/src/tools/clippy/clippy_lints/src/transmute/utils.rs b/src/tools/clippy/clippy_lints/src/transmute/utils.rs index 49d863ec03f1d..b59d52dfc4d31 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/utils.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/utils.rs @@ -46,7 +46,7 @@ fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx> let local_def_id = hir_id.owner.def_id; Inherited::build(cx.tcx, local_def_id).enter(|inherited| { - let fn_ctxt = FnCtxt::new(inherited, cx.param_env, hir_id); + let fn_ctxt = FnCtxt::new(inherited, cx.param_env, local_def_id); // If we already have errors, we can't be sure we can pointer cast. assert!( From 2d8ede23353266c38f0b7c91be934495e941f2cc Mon Sep 17 00:00:00 2001 From: Vincenzo Palazzo Date: Sun, 15 Jan 2023 12:58:46 +0100 Subject: [PATCH 283/500] fix: use LocalDefId instead of HirId in trait res use LocalDefId instead of HirId in trait resolution to simplify the obligation clause resolution Signed-off-by: Vincenzo Palazzo --- clippy_lints/src/future_not_send.rs | 3 ++- clippy_lints/src/methods/unnecessary_to_owned.rs | 2 +- clippy_lints/src/transmute/utils.rs | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/clippy_lints/src/future_not_send.rs b/clippy_lints/src/future_not_send.rs index 989f83cf80d59..2a79b18b82994 100644 --- a/clippy_lints/src/future_not_send.rs +++ b/clippy_lints/src/future_not_send.rs @@ -78,7 +78,8 @@ impl<'tcx> LateLintPass<'tcx> for FutureNotSend { let send_trait = cx.tcx.get_diagnostic_item(sym::Send).unwrap(); let span = decl.output.span(); let infcx = cx.tcx.infer_ctxt().build(); - let cause = traits::ObligationCause::misc(span, hir_id); + let def_id = cx.tcx.hir().local_def_id(hir_id); + let cause = traits::ObligationCause::misc(span, def_id); let send_errors = traits::fully_solve_bound(&infcx, cause, cx.param_env, ret_ty, send_trait); if !send_errors.is_empty() { span_lint_and_then( diff --git a/clippy_lints/src/methods/unnecessary_to_owned.rs b/clippy_lints/src/methods/unnecessary_to_owned.rs index 9263f0519724b..b812e81cb107b 100644 --- a/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -371,7 +371,7 @@ fn can_change_type<'a>(cx: &LateContext<'a>, mut expr: &'a Expr<'a>, mut ty: Ty< && let output_ty = return_ty(cx, item.hir_id()) && let local_def_id = cx.tcx.hir().local_def_id(item.hir_id()) && Inherited::build(cx.tcx, local_def_id).enter(|inherited| { - let fn_ctxt = FnCtxt::new(inherited, cx.param_env, item.hir_id()); + let fn_ctxt = FnCtxt::new(inherited, cx.param_env, local_def_id); fn_ctxt.can_coerce(ty, output_ty) }) { if has_lifetime(output_ty) && has_lifetime(ty) { diff --git a/clippy_lints/src/transmute/utils.rs b/clippy_lints/src/transmute/utils.rs index 49d863ec03f1d..b59d52dfc4d31 100644 --- a/clippy_lints/src/transmute/utils.rs +++ b/clippy_lints/src/transmute/utils.rs @@ -46,7 +46,7 @@ fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx> let local_def_id = hir_id.owner.def_id; Inherited::build(cx.tcx, local_def_id).enter(|inherited| { - let fn_ctxt = FnCtxt::new(inherited, cx.param_env, hir_id); + let fn_ctxt = FnCtxt::new(inherited, cx.param_env, local_def_id); // If we already have errors, we can't be sure we can pointer cast. assert!( From 236f8231a64241d3fb3b9d81a8cd3175367e691d Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Mon, 23 Jan 2023 14:42:32 +0200 Subject: [PATCH 284/500] `sub_ptr()` is equivalent to `usize::try_from().unwrap_unchecked()`, not `usize::from().unwrap_unchecked()`. `usize::from()` gives a `usize`, not `Result`, and `usize: From` is not implemented. --- library/core/src/ptr/const_ptr.rs | 2 +- library/core/src/ptr/mut_ptr.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 7b1cb5488bcac..16eb726f6f614 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -731,7 +731,7 @@ impl *const T { /// This computes the same value that [`offset_from`](#method.offset_from) /// would compute, but with the added precondition that the offset is /// guaranteed to be non-negative. This method is equivalent to - /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`, + /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`, /// but it provides slightly more information to the optimizer, which can /// sometimes allow it to optimize slightly better with some backends. /// diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index ed1e3bd481227..0a2f63e3ec6a5 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -904,7 +904,7 @@ impl *mut T { /// This computes the same value that [`offset_from`](#method.offset_from) /// would compute, but with the added precondition that the offset is /// guaranteed to be non-negative. This method is equivalent to - /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`, + /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`, /// but it provides slightly more information to the optimizer, which can /// sometimes allow it to optimize slightly better with some backends. /// From d924a8ca59bb12b16923dbda594cb7048230f0ff Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 23 Jan 2023 12:00:03 +0000 Subject: [PATCH 285/500] Evaluate `output_filenames` before one of its dependencies gets stolen --- compiler/rustc_ast_lowering/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index bc6d2cf12c78a..0172762506482 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -416,6 +416,7 @@ fn compute_hir_hash( pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> hir::Crate<'_> { let sess = tcx.sess; + tcx.ensure().output_filenames(()); let (mut resolver, krate) = tcx.resolver_for_lowering(()).steal(); let ast_index = index_crate(&resolver.node_id_to_def_id, &krate); From e477cf9475540bf7f5f71940b29fc065cb988982 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 8 Jan 2023 02:54:59 +0000 Subject: [PATCH 286/500] Suggest coercion of `Result` using `?` Fix #47560. --- compiler/rustc_hir_typeck/src/coercion.rs | 49 ++++++++++++++++++- .../coerce-result-return-value.fixed | 16 ++++++ .../type-check/coerce-result-return-value.rs | 16 ++++++ .../coerce-result-return-value.stderr | 33 +++++++++++++ 4 files changed, 113 insertions(+), 1 deletion(-) create mode 100644 tests/ui/type/type-check/coerce-result-return-value.fixed create mode 100644 tests/ui/type/type-check/coerce-result-return-value.rs create mode 100644 tests/ui/type/type-check/coerce-result-return-value.stderr diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index bbf7b81a2cc66..752e3f79d4abf 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -45,7 +45,7 @@ use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::Expr; use rustc_hir_analysis::astconv::AstConv; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; -use rustc_infer::infer::{Coercion, InferOk, InferResult}; +use rustc_infer::infer::{Coercion, InferOk, InferResult, TyCtxtInferExt}; use rustc_infer::traits::Obligation; use rustc_middle::lint::in_external_macro; use rustc_middle::ty::adjustment::{ @@ -1565,6 +1565,9 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { && let hir::ExprKind::Loop(loop_blk, ..) = expression.kind { intravisit::walk_block(& mut visitor, loop_blk); } + if let Some(expr) = expression { + self.note_result_coercion(fcx, &mut err, expr, expected, found); + } } ObligationCauseCode::ReturnValue(id) => { err = self.report_return_mismatched_types( @@ -1581,6 +1584,9 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { let id = fcx.tcx.hir().parent_id(id); unsized_return = self.is_return_ty_unsized(fcx, id); } + if let Some(expr) = expression { + self.note_result_coercion(fcx, &mut err, expr, expected, found); + } } _ => { err = fcx.err_ctxt().report_mismatched_types( @@ -1619,6 +1625,47 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { } } } + + fn note_result_coercion( + &self, + fcx: &FnCtxt<'_, 'tcx>, + err: &mut Diagnostic, + expr: &hir::Expr<'tcx>, + expected: Ty<'tcx>, + found: Ty<'tcx>, + ) { + let ty::Adt(e, substs_e) = expected.kind() else { return; }; + let ty::Adt(f, substs_f) = found.kind() else { return; }; + if e.did() != f.did() { + return; + } + if Some(e.did()) != fcx.tcx.get_diagnostic_item(sym::Result) { + return; + } + let e = substs_e.type_at(1); + let f = substs_f.type_at(1); + if fcx + .tcx + .infer_ctxt() + .build() + .type_implements_trait( + fcx.tcx.get_diagnostic_item(sym::Into).unwrap(), + [fcx.tcx.erase_regions(f), fcx.tcx.erase_regions(e)], + fcx.param_env, + ) + .must_apply_modulo_regions() + { + err.multipart_suggestion( + "you can rely on the implicit conversion that `?` does to transform the error type", + vec![ + (expr.span.shrink_to_lo(), "Ok(".to_string()), + (expr.span.shrink_to_hi(), "?)".to_string()), + ], + Applicability::MaybeIncorrect, + ); + } + } + fn note_unreachable_loop_return( &self, err: &mut Diagnostic, diff --git a/tests/ui/type/type-check/coerce-result-return-value.fixed b/tests/ui/type/type-check/coerce-result-return-value.fixed new file mode 100644 index 0000000000000..91066262303ec --- /dev/null +++ b/tests/ui/type/type-check/coerce-result-return-value.fixed @@ -0,0 +1,16 @@ +// run-rustfix +struct A; +struct B; +impl From for B { + fn from(_: A) -> Self { B } +} +fn foo1(x: Result<(), A>) -> Result<(), B> { + Ok(x?) //~ ERROR mismatched types +} +fn foo2(x: Result<(), A>) -> Result<(), B> { + return Ok(x?); //~ ERROR mismatched types +} +fn main() { + let _ = foo1(Ok(())); + let _ = foo2(Ok(())); +} diff --git a/tests/ui/type/type-check/coerce-result-return-value.rs b/tests/ui/type/type-check/coerce-result-return-value.rs new file mode 100644 index 0000000000000..9a71376f462dc --- /dev/null +++ b/tests/ui/type/type-check/coerce-result-return-value.rs @@ -0,0 +1,16 @@ +// run-rustfix +struct A; +struct B; +impl From for B { + fn from(_: A) -> Self { B } +} +fn foo1(x: Result<(), A>) -> Result<(), B> { + x //~ ERROR mismatched types +} +fn foo2(x: Result<(), A>) -> Result<(), B> { + return x; //~ ERROR mismatched types +} +fn main() { + let _ = foo1(Ok(())); + let _ = foo2(Ok(())); +} diff --git a/tests/ui/type/type-check/coerce-result-return-value.stderr b/tests/ui/type/type-check/coerce-result-return-value.stderr new file mode 100644 index 0000000000000..7aebc9dcc7ad8 --- /dev/null +++ b/tests/ui/type/type-check/coerce-result-return-value.stderr @@ -0,0 +1,33 @@ +error[E0308]: mismatched types + --> $DIR/coerce-result-return-value.rs:8:5 + | +LL | fn foo1(x: Result<(), A>) -> Result<(), B> { + | ------------- expected `Result<(), B>` because of return type +LL | x + | ^ expected struct `B`, found struct `A` + | + = note: expected enum `Result<_, B>` + found enum `Result<_, A>` +help: you can rely on the implicit conversion that `?` does to transform the error type + | +LL | Ok(x?) + | +++ ++ + +error[E0308]: mismatched types + --> $DIR/coerce-result-return-value.rs:11:12 + | +LL | fn foo2(x: Result<(), A>) -> Result<(), B> { + | ------------- expected `Result<(), B>` because of return type +LL | return x; + | ^ expected struct `B`, found struct `A` + | + = note: expected enum `Result<_, B>` + found enum `Result<_, A>` +help: you can rely on the implicit conversion that `?` does to transform the error type + | +LL | return Ok(x?); + | +++ ++ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0308`. From d5a1609ec450d624fd8bf3f88647e966cf83eee8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 8 Jan 2023 07:05:23 +0000 Subject: [PATCH 287/500] review comment: use `fcx.infcx` --- compiler/rustc_hir_typeck/src/coercion.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 752e3f79d4abf..893d1e88bf8a2 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -1645,9 +1645,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { let e = substs_e.type_at(1); let f = substs_f.type_at(1); if fcx - .tcx - .infer_ctxt() - .build() + .infcx .type_implements_trait( fcx.tcx.get_diagnostic_item(sym::Into).unwrap(), [fcx.tcx.erase_regions(f), fcx.tcx.erase_regions(e)], From ddd9a9fb4666401d4f1a92edd8a7d8b33bf0824f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 8 Jan 2023 07:14:17 +0000 Subject: [PATCH 288/500] Add call in `emit_type_mismatch_suggestions` --- compiler/rustc_hir_typeck/src/coercion.rs | 46 +---------------------- compiler/rustc_hir_typeck/src/demand.rs | 42 ++++++++++++++++++++- 2 files changed, 42 insertions(+), 46 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 893d1e88bf8a2..d5f37abb8b455 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -45,7 +45,7 @@ use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::Expr; use rustc_hir_analysis::astconv::AstConv; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; -use rustc_infer::infer::{Coercion, InferOk, InferResult, TyCtxtInferExt}; +use rustc_infer::infer::{Coercion, InferOk, InferResult}; use rustc_infer::traits::Obligation; use rustc_middle::lint::in_external_macro; use rustc_middle::ty::adjustment::{ @@ -1565,9 +1565,6 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { && let hir::ExprKind::Loop(loop_blk, ..) = expression.kind { intravisit::walk_block(& mut visitor, loop_blk); } - if let Some(expr) = expression { - self.note_result_coercion(fcx, &mut err, expr, expected, found); - } } ObligationCauseCode::ReturnValue(id) => { err = self.report_return_mismatched_types( @@ -1584,9 +1581,6 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { let id = fcx.tcx.hir().parent_id(id); unsized_return = self.is_return_ty_unsized(fcx, id); } - if let Some(expr) = expression { - self.note_result_coercion(fcx, &mut err, expr, expected, found); - } } _ => { err = fcx.err_ctxt().report_mismatched_types( @@ -1626,44 +1620,6 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { } } - fn note_result_coercion( - &self, - fcx: &FnCtxt<'_, 'tcx>, - err: &mut Diagnostic, - expr: &hir::Expr<'tcx>, - expected: Ty<'tcx>, - found: Ty<'tcx>, - ) { - let ty::Adt(e, substs_e) = expected.kind() else { return; }; - let ty::Adt(f, substs_f) = found.kind() else { return; }; - if e.did() != f.did() { - return; - } - if Some(e.did()) != fcx.tcx.get_diagnostic_item(sym::Result) { - return; - } - let e = substs_e.type_at(1); - let f = substs_f.type_at(1); - if fcx - .infcx - .type_implements_trait( - fcx.tcx.get_diagnostic_item(sym::Into).unwrap(), - [fcx.tcx.erase_regions(f), fcx.tcx.erase_regions(e)], - fcx.param_env, - ) - .must_apply_modulo_regions() - { - err.multipart_suggestion( - "you can rely on the implicit conversion that `?` does to transform the error type", - vec![ - (expr.span.shrink_to_lo(), "Ok(".to_string()), - (expr.span.shrink_to_hi(), "?)".to_string()), - ], - Applicability::MaybeIncorrect, - ); - } - } - fn note_unreachable_loop_return( &self, err: &mut Diagnostic, diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 665dc8b6a2f2a..b10bb593ead4b 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -59,7 +59,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { || self.suggest_copied_or_cloned(err, expr, expr_ty, expected) || self.suggest_clone_for_ref(err, expr, expr_ty, expected) || self.suggest_into(err, expr, expr_ty, expected) - || self.suggest_floating_point_literal(err, expr, expected); + || self.suggest_floating_point_literal(err, expr, expected) + || self.note_result_coercion(err, expr, expected, expr_ty); if !suggested { self.point_at_expr_source_of_inferred_type(err, expr, expr_ty, expected); } @@ -697,6 +698,45 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } + pub(crate) fn note_result_coercion( + &self, + err: &mut Diagnostic, + expr: &hir::Expr<'tcx>, + expected: Ty<'tcx>, + found: Ty<'tcx>, + ) -> bool { + let ty::Adt(e, substs_e) = expected.kind() else { return false; }; + let ty::Adt(f, substs_f) = found.kind() else { return false; }; + if e.did() != f.did() { + return false; + } + if Some(e.did()) != self.tcx.get_diagnostic_item(sym::Result) { + return false; + } + let e = substs_e.type_at(1); + let f = substs_f.type_at(1); + if self + .infcx + .type_implements_trait( + self.tcx.get_diagnostic_item(sym::Into).unwrap(), + [self.tcx.erase_regions(f), self.tcx.erase_regions(e)], + self.param_env, + ) + .must_apply_modulo_regions() + { + err.multipart_suggestion( + "you can rely on the implicit conversion that `?` does to transform the error type", + vec![ + (expr.span.shrink_to_lo(), "Ok(".to_string()), + (expr.span.shrink_to_hi(), "?)".to_string()), + ], + Applicability::MaybeIncorrect, + ); + return true; + } + false + } + /// If the expected type is an enum (Issue #55250) with any variants whose /// sole field is of the found type, suggest such variants. (Issue #42764) fn suggest_compatible_variants( From fcf0ed90187ae60739c76ef3e72e8232bf14746b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 8 Jan 2023 07:43:24 +0000 Subject: [PATCH 289/500] Do not erase regions --- compiler/rustc_hir_typeck/src/demand.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index b10bb593ead4b..d55ea52d16b02 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -719,7 +719,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .infcx .type_implements_trait( self.tcx.get_diagnostic_item(sym::Into).unwrap(), - [self.tcx.erase_regions(f), self.tcx.erase_regions(e)], + [f, e], self.param_env, ) .must_apply_modulo_regions() From df81147b51f95441c8db74eda92b5c5fadecb20e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 8 Jan 2023 19:12:15 +0000 Subject: [PATCH 290/500] Ensure suggestion correctness --- compiler/rustc_hir_typeck/src/demand.rs | 10 ++++ .../coerce-result-return-value-2.rs | 24 ++++++++++ .../coerce-result-return-value-2.stderr | 47 +++++++++++++++++++ .../coerce-result-return-value.fixed | 8 ++++ .../type-check/coerce-result-return-value.rs | 8 ++++ .../coerce-result-return-value.stderr | 34 +++++++++++++- 6 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 tests/ui/type/type-check/coerce-result-return-value-2.rs create mode 100644 tests/ui/type/type-check/coerce-result-return-value-2.stderr diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index d55ea52d16b02..97490194e2558 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -713,6 +713,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if Some(e.did()) != self.tcx.get_diagnostic_item(sym::Result) { return false; } + let map = self.tcx.hir(); + if let Some(hir::Node::Expr(expr)) = map.find_parent(expr.hir_id) + && let hir::ExprKind::Ret(_) = expr.kind + { + // `return foo;` + } else if map.get_return_block(expr.hir_id).is_some() { + // Function's tail expression. + } else { + return false; + } let e = substs_e.type_at(1); let f = substs_f.type_at(1); if self diff --git a/tests/ui/type/type-check/coerce-result-return-value-2.rs b/tests/ui/type/type-check/coerce-result-return-value-2.rs new file mode 100644 index 0000000000000..23bafa6c5c94c --- /dev/null +++ b/tests/ui/type/type-check/coerce-result-return-value-2.rs @@ -0,0 +1,24 @@ +struct A; +struct B; +impl From for B { + fn from(_: A) -> Self { B } +} +fn foo4(x: Result<(), A>) -> Result<(), B> { + match true { + true => x, //~ ERROR mismatched types + false => x, + } +} +fn foo5(x: Result<(), A>) -> Result<(), B> { + match true { + true => return x, //~ ERROR mismatched types + false => return x, + } +} +fn main() { + let _ = foo4(Ok(())); + let _ = foo5(Ok(())); + let _: Result<(), B> = { //~ ERROR mismatched types + Err(A); + }; +} diff --git a/tests/ui/type/type-check/coerce-result-return-value-2.stderr b/tests/ui/type/type-check/coerce-result-return-value-2.stderr new file mode 100644 index 0000000000000..64a8c779fce76 --- /dev/null +++ b/tests/ui/type/type-check/coerce-result-return-value-2.stderr @@ -0,0 +1,47 @@ +error[E0308]: mismatched types + --> $DIR/coerce-result-return-value-2.rs:8:17 + | +LL | fn foo4(x: Result<(), A>) -> Result<(), B> { + | ------------- expected `Result<(), B>` because of return type +LL | match true { +LL | true => x, + | ^ expected struct `B`, found struct `A` + | + = note: expected enum `Result<_, B>` + found enum `Result<_, A>` +help: you can rely on the implicit conversion that `?` does to transform the error type + | +LL | true => Ok(x?), + | +++ ++ + +error[E0308]: mismatched types + --> $DIR/coerce-result-return-value-2.rs:14:24 + | +LL | fn foo5(x: Result<(), A>) -> Result<(), B> { + | ------------- expected `Result<(), B>` because of return type +LL | match true { +LL | true => return x, + | ^ expected struct `B`, found struct `A` + | + = note: expected enum `Result<_, B>` + found enum `Result<_, A>` +help: you can rely on the implicit conversion that `?` does to transform the error type + | +LL | true => return Ok(x?), + | +++ ++ + +error[E0308]: mismatched types + --> $DIR/coerce-result-return-value-2.rs:21:28 + | +LL | let _: Result<(), B> = { + | ____________________________^ +LL | | Err(A); +LL | | }; + | |_____^ expected enum `Result`, found `()` + | + = note: expected enum `Result<(), B>` + found unit type `()` + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/type/type-check/coerce-result-return-value.fixed b/tests/ui/type/type-check/coerce-result-return-value.fixed index 91066262303ec..8a05407070dad 100644 --- a/tests/ui/type/type-check/coerce-result-return-value.fixed +++ b/tests/ui/type/type-check/coerce-result-return-value.fixed @@ -10,7 +10,15 @@ fn foo1(x: Result<(), A>) -> Result<(), B> { fn foo2(x: Result<(), A>) -> Result<(), B> { return Ok(x?); //~ ERROR mismatched types } +fn foo3(x: Result<(), A>) -> Result<(), B> { + if true { + Ok(x?) //~ ERROR mismatched types + } else { + Ok(x?) //~ ERROR mismatched types + } +} fn main() { let _ = foo1(Ok(())); let _ = foo2(Ok(())); + let _ = foo3(Ok(())); } diff --git a/tests/ui/type/type-check/coerce-result-return-value.rs b/tests/ui/type/type-check/coerce-result-return-value.rs index 9a71376f462dc..442203addb787 100644 --- a/tests/ui/type/type-check/coerce-result-return-value.rs +++ b/tests/ui/type/type-check/coerce-result-return-value.rs @@ -10,7 +10,15 @@ fn foo1(x: Result<(), A>) -> Result<(), B> { fn foo2(x: Result<(), A>) -> Result<(), B> { return x; //~ ERROR mismatched types } +fn foo3(x: Result<(), A>) -> Result<(), B> { + if true { + x //~ ERROR mismatched types + } else { + x //~ ERROR mismatched types + } +} fn main() { let _ = foo1(Ok(())); let _ = foo2(Ok(())); + let _ = foo3(Ok(())); } diff --git a/tests/ui/type/type-check/coerce-result-return-value.stderr b/tests/ui/type/type-check/coerce-result-return-value.stderr index 7aebc9dcc7ad8..18993b3cef1b9 100644 --- a/tests/ui/type/type-check/coerce-result-return-value.stderr +++ b/tests/ui/type/type-check/coerce-result-return-value.stderr @@ -28,6 +28,38 @@ help: you can rely on the implicit conversion that `?` does to transform the err LL | return Ok(x?); | +++ ++ -error: aborting due to 2 previous errors +error[E0308]: mismatched types + --> $DIR/coerce-result-return-value.rs:15:9 + | +LL | fn foo3(x: Result<(), A>) -> Result<(), B> { + | ------------- expected `Result<(), B>` because of return type +LL | if true { +LL | x + | ^ expected struct `B`, found struct `A` + | + = note: expected enum `Result<_, B>` + found enum `Result<_, A>` +help: you can rely on the implicit conversion that `?` does to transform the error type + | +LL | Ok(x?) + | +++ ++ + +error[E0308]: mismatched types + --> $DIR/coerce-result-return-value.rs:17:9 + | +LL | fn foo3(x: Result<(), A>) -> Result<(), B> { + | ------------- expected `Result<(), B>` because of return type +... +LL | x + | ^ expected struct `B`, found struct `A` + | + = note: expected enum `Result<_, B>` + found enum `Result<_, A>` +help: you can rely on the implicit conversion that `?` does to transform the error type + | +LL | Ok(x?) + | +++ ++ + +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0308`. From 62aff3bbc75468bedf751b01a746e52886be760c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Mon, 23 Jan 2023 14:46:30 +0000 Subject: [PATCH 291/500] tweak wording --- compiler/rustc_hir_typeck/src/demand.rs | 3 ++- .../type/type-check/coerce-result-return-value-2.stderr | 4 ++-- .../ui/type/type-check/coerce-result-return-value.stderr | 8 ++++---- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 97490194e2558..3f185dfae0241 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -735,7 +735,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .must_apply_modulo_regions() { err.multipart_suggestion( - "you can rely on the implicit conversion that `?` does to transform the error type", + "use `?` to coerce and return an appropriate `Err`, and wrap the resulting value \ + in `Ok` so the expression remains of type `Result`", vec![ (expr.span.shrink_to_lo(), "Ok(".to_string()), (expr.span.shrink_to_hi(), "?)".to_string()), diff --git a/tests/ui/type/type-check/coerce-result-return-value-2.stderr b/tests/ui/type/type-check/coerce-result-return-value-2.stderr index 64a8c779fce76..5992162341e6e 100644 --- a/tests/ui/type/type-check/coerce-result-return-value-2.stderr +++ b/tests/ui/type/type-check/coerce-result-return-value-2.stderr @@ -9,7 +9,7 @@ LL | true => x, | = note: expected enum `Result<_, B>` found enum `Result<_, A>` -help: you can rely on the implicit conversion that `?` does to transform the error type +help: use `?` to coerce and return an appropriate `Err`, and wrap the resulting value in `Ok` so the expression remains of type `Result` | LL | true => Ok(x?), | +++ ++ @@ -25,7 +25,7 @@ LL | true => return x, | = note: expected enum `Result<_, B>` found enum `Result<_, A>` -help: you can rely on the implicit conversion that `?` does to transform the error type +help: use `?` to coerce and return an appropriate `Err`, and wrap the resulting value in `Ok` so the expression remains of type `Result` | LL | true => return Ok(x?), | +++ ++ diff --git a/tests/ui/type/type-check/coerce-result-return-value.stderr b/tests/ui/type/type-check/coerce-result-return-value.stderr index 18993b3cef1b9..550153520782c 100644 --- a/tests/ui/type/type-check/coerce-result-return-value.stderr +++ b/tests/ui/type/type-check/coerce-result-return-value.stderr @@ -8,7 +8,7 @@ LL | x | = note: expected enum `Result<_, B>` found enum `Result<_, A>` -help: you can rely on the implicit conversion that `?` does to transform the error type +help: use `?` to coerce and return an appropriate `Err`, and wrap the resulting value in `Ok` so the expression remains of type `Result` | LL | Ok(x?) | +++ ++ @@ -23,7 +23,7 @@ LL | return x; | = note: expected enum `Result<_, B>` found enum `Result<_, A>` -help: you can rely on the implicit conversion that `?` does to transform the error type +help: use `?` to coerce and return an appropriate `Err`, and wrap the resulting value in `Ok` so the expression remains of type `Result` | LL | return Ok(x?); | +++ ++ @@ -39,7 +39,7 @@ LL | x | = note: expected enum `Result<_, B>` found enum `Result<_, A>` -help: you can rely on the implicit conversion that `?` does to transform the error type +help: use `?` to coerce and return an appropriate `Err`, and wrap the resulting value in `Ok` so the expression remains of type `Result` | LL | Ok(x?) | +++ ++ @@ -55,7 +55,7 @@ LL | x | = note: expected enum `Result<_, B>` found enum `Result<_, A>` -help: you can rely on the implicit conversion that `?` does to transform the error type +help: use `?` to coerce and return an appropriate `Err`, and wrap the resulting value in `Ok` so the expression remains of type `Result` | LL | Ok(x?) | +++ ++ From 033047a72cd3129831d4c0ae59024d77f17106ec Mon Sep 17 00:00:00 2001 From: lcnr Date: Mon, 23 Jan 2023 15:34:11 +0100 Subject: [PATCH 292/500] `new_outside_solver` -> `evaluate_root_goal` --- .../src/solve/fulfill.rs | 7 +--- .../rustc_trait_selection/src/solve/mod.rs | 42 +++++++++++++------ 2 files changed, 32 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index 40b9bedc84fd3..d59fa71406c31 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -1,5 +1,6 @@ use std::mem; +use super::{Certainty, InferCtxtEvalExt}; use rustc_infer::{ infer::InferCtxt, traits::{ @@ -8,8 +9,6 @@ use rustc_infer::{ }, }; -use super::{search_graph, Certainty, EvalCtxt}; - /// A trait engine using the new trait solver. /// /// This is mostly identical to how `evaluate_all` works inside of the @@ -66,9 +65,7 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> { let mut has_changed = false; for obligation in mem::take(&mut self.obligations) { let goal = obligation.clone().into(); - let search_graph = &mut search_graph::SearchGraph::new(infcx.tcx); - let mut ecx = EvalCtxt::new_outside_solver(infcx, search_graph); - let (changed, certainty) = match ecx.evaluate_goal(goal) { + let (changed, certainty) = match infcx.evaluate_root_goal(goal) { Ok(result) => result, Err(NoSolution) => { errors.push(FulfillmentError { diff --git a/compiler/rustc_trait_selection/src/solve/mod.rs b/compiler/rustc_trait_selection/src/solve/mod.rs index da2a1a19957e1..70f094014453e 100644 --- a/compiler/rustc_trait_selection/src/solve/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/mod.rs @@ -152,6 +152,36 @@ impl<'tcx> TyCtxtExt<'tcx> for TyCtxt<'tcx> { } } +pub trait InferCtxtEvalExt<'tcx> { + /// Evaluates a goal from **outside** of the trait solver. + /// + /// Using this while inside of the solver is wrong as it uses a new + /// search graph which would break cycle detection. + fn evaluate_root_goal( + &self, + goal: Goal<'tcx, ty::Predicate<'tcx>>, + ) -> Result<(bool, Certainty), NoSolution>; +} + +impl<'tcx> InferCtxtEvalExt<'tcx> for InferCtxt<'tcx> { + fn evaluate_root_goal( + &self, + goal: Goal<'tcx, ty::Predicate<'tcx>>, + ) -> Result<(bool, Certainty), NoSolution> { + let mut search_graph = search_graph::SearchGraph::new(self.tcx); + + let result = EvalCtxt { + search_graph: &mut search_graph, + infcx: self, + var_values: CanonicalVarValues::dummy(), + } + .evaluate_goal(goal); + + assert!(search_graph.is_empty()); + result + } +} + struct EvalCtxt<'a, 'tcx> { infcx: &'a InferCtxt<'tcx>, var_values: CanonicalVarValues<'tcx>, @@ -164,18 +194,6 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { self.infcx.tcx } - /// Creates a new evaluation context outside of the trait solver. - /// - /// With this solver making a canonical response doesn't make much sense. - /// The `search_graph` for this solver has to be completely empty. - fn new_outside_solver( - infcx: &'a InferCtxt<'tcx>, - search_graph: &'a mut search_graph::SearchGraph<'tcx>, - ) -> EvalCtxt<'a, 'tcx> { - assert!(search_graph.is_empty()); - EvalCtxt { infcx, var_values: CanonicalVarValues::dummy(), search_graph } - } - #[instrument(level = "debug", skip(tcx, search_graph), ret)] fn evaluate_canonical_goal( tcx: TyCtxt<'tcx>, From 91fdbd73437aa53d1cc74faa41ae62951839f13a Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sat, 21 Jan 2023 18:38:14 +0400 Subject: [PATCH 293/500] rustc_metadata: Support non-`Option` nullable values in metadata tables This is a convenience feature for cases in which "no value in the table" and "default value in the table" are equivalent. Tables using `Table` are migrated in this PR, some other cases can be migrated later. This helps `DocFlags` in https://github.com/rust-lang/rust/pull/107136 in particular. --- compiler/rustc_metadata/src/rmeta/decoder.rs | 8 +-- .../src/rmeta/decoder/cstore_impl.rs | 7 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 14 ++-- compiler/rustc_metadata/src/rmeta/mod.rs | 39 +++++----- compiler/rustc_metadata/src/rmeta/table.rs | 72 ++++++++----------- 5 files changed, 64 insertions(+), 76 deletions(-) diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index 44da3fbe300ca..bb2dd290c6d5d 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -985,7 +985,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { let vis = self.get_visibility(id); let span = self.get_span(id, sess); let macro_rules = match kind { - DefKind::Macro(..) => self.root.tables.macro_rules.get(self, id).is_some(), + DefKind::Macro(..) => self.root.tables.is_macro_rules.get(self, id), _ => false, }; @@ -1283,7 +1283,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { fn get_macro(self, id: DefIndex, sess: &Session) -> ast::MacroDef { match self.def_kind(id) { DefKind::Macro(_) => { - let macro_rules = self.root.tables.macro_rules.get(self, id).is_some(); + let macro_rules = self.root.tables.is_macro_rules.get(self, id); let body = self.root.tables.macro_definition.get(self, id).unwrap().decode((self, sess)); ast::MacroDef { macro_rules, body: ast::ptr::P(body) } @@ -1595,11 +1595,11 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { } fn get_attr_flags(self, index: DefIndex) -> AttrFlags { - self.root.tables.attr_flags.get(self, index).unwrap_or(AttrFlags::empty()) + self.root.tables.attr_flags.get(self, index) } fn get_is_intrinsic(self, index: DefIndex) -> bool { - self.root.tables.is_intrinsic.get(self, index).is_some() + self.root.tables.is_intrinsic.get(self, index) } } diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 2fa645cd9e33d..eebc2f21dfe4e 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -226,12 +226,7 @@ provide! { tcx, def_id, other, cdata, deduced_param_attrs => { table } is_type_alias_impl_trait => { debug_assert_eq!(tcx.def_kind(def_id), DefKind::OpaqueTy); - cdata - .root - .tables - .is_type_alias_impl_trait - .get(cdata, def_id.index) - .is_some() + cdata.root.tables.is_type_alias_impl_trait.get(cdata, def_id.index) } collect_return_position_impl_trait_in_trait_tys => { Ok(cdata diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 2ecaa33d4d315..97f0457ba7116 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -483,7 +483,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map())) } - fn encode_source_map(&mut self) -> LazyTable> { + fn encode_source_map(&mut self) -> LazyTable>> { let source_map = self.tcx.sess.source_map(); let all_source_files = source_map.files(); @@ -1130,7 +1130,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { attr_flags |= AttrFlags::IS_DOC_HIDDEN; } if !attr_flags.is_empty() { - self.tables.attr_flags.set(def_id.local_def_index, attr_flags); + self.tables.attr_flags.set_nullable(def_id.local_def_index, attr_flags); } } @@ -1387,7 +1387,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { if impl_item.kind == ty::AssocKind::Fn { record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); if tcx.is_intrinsic(def_id) { - self.tables.is_intrinsic.set(def_id.index, ()); + self.tables.is_intrinsic.set_nullable(def_id.index, true); } } } @@ -1519,7 +1519,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } hir::ItemKind::Macro(ref macro_def, _) => { if macro_def.macro_rules { - self.tables.macro_rules.set(def_id.index, ()); + self.tables.is_macro_rules.set_nullable(def_id.index, true); } record!(self.tables.macro_definition[def_id] <- &*macro_def.body); } @@ -1529,7 +1529,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { hir::ItemKind::OpaqueTy(ref opaque) => { self.encode_explicit_item_bounds(def_id); if matches!(opaque.origin, hir::OpaqueTyOrigin::TyAlias) { - self.tables.is_type_alias_impl_trait.set(def_id.index, ()); + self.tables.is_type_alias_impl_trait.set_nullable(def_id.index, true); } } hir::ItemKind::Enum(..) => { @@ -1636,7 +1636,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { if let hir::ItemKind::Fn(..) = item.kind { record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); if tcx.is_intrinsic(def_id) { - self.tables.is_intrinsic.set(def_id.index, ()); + self.tables.is_intrinsic.set_nullable(def_id.index, true); } } if let hir::ItemKind::Impl { .. } = item.kind { @@ -2038,7 +2038,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } if let hir::ForeignItemKind::Fn(..) = nitem.kind { if tcx.is_intrinsic(def_id) { - self.tables.is_intrinsic.set(def_id.index, ()); + self.tables.is_intrinsic.set_nullable(def_id.index, true); } } } diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 69690264ae4ea..698b2ebc4732a 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -185,9 +185,9 @@ enum LazyState { Previous(NonZeroUsize), } -type SyntaxContextTable = LazyTable>; -type ExpnDataTable = LazyTable>; -type ExpnHashTable = LazyTable>; +type SyntaxContextTable = LazyTable>>; +type ExpnDataTable = LazyTable>>; +type ExpnHashTable = LazyTable>>; #[derive(MetadataEncodable, MetadataDecodable)] pub(crate) struct ProcMacroData { @@ -253,7 +253,7 @@ pub(crate) struct CrateRoot { def_path_hash_map: LazyValue>, - source_map: LazyTable>, + source_map: LazyTable>>, compiler_builtins: bool, needs_allocator: bool, @@ -315,21 +315,27 @@ pub(crate) struct IncoherentImpls { /// Define `LazyTables` and `TableBuilders` at the same time. macro_rules! define_tables { - ($($name:ident: Table<$IDX:ty, $T:ty>),+ $(,)?) => { + ( + - nullable: $($name1:ident: Table<$IDX1:ty, $T1:ty>,)+ + - optional: $($name2:ident: Table<$IDX2:ty, $T2:ty>,)+ + ) => { #[derive(MetadataEncodable, MetadataDecodable)] pub(crate) struct LazyTables { - $($name: LazyTable<$IDX, $T>),+ + $($name1: LazyTable<$IDX1, $T1>,)+ + $($name2: LazyTable<$IDX2, Option<$T2>>,)+ } #[derive(Default)] struct TableBuilders { - $($name: TableBuilder<$IDX, $T>),+ + $($name1: TableBuilder<$IDX1, $T1>,)+ + $($name2: TableBuilder<$IDX2, Option<$T2>>,)+ } impl TableBuilders { fn encode(&self, buf: &mut FileEncoder) -> LazyTables { LazyTables { - $($name: self.$name.encode(buf)),+ + $($name1: self.$name1.encode(buf),)+ + $($name2: self.$name2.encode(buf),)+ } } } @@ -337,9 +343,15 @@ macro_rules! define_tables { } define_tables! { +- nullable: + is_intrinsic: Table, + is_macro_rules: Table, + is_type_alias_impl_trait: Table, + attr_flags: Table, + +- optional: attributes: Table>, children: Table>, - opt_def_kind: Table, visibility: Table>>, def_span: Table>, @@ -370,7 +382,6 @@ define_tables! { impl_parent: Table, impl_polarity: Table, constness: Table, - is_intrinsic: Table, impl_defaultness: Table, // FIXME(eddyb) perhaps compute this on the fly if cheap enough? coerce_unsized_info: Table>, @@ -380,7 +391,6 @@ define_tables! { fn_arg_names: Table>, generator_kind: Table>, trait_def: Table>, - trait_item_def_id: Table, inherent_impls: Table>, expn_that_defined: Table>, @@ -395,18 +405,12 @@ define_tables! { def_path_hashes: Table, proc_macro_quoted_spans: Table>, generator_diagnostic_data: Table>>, - attr_flags: Table, variant_data: Table>, assoc_container: Table, - // Slot is full when macro is macro_rules. - macro_rules: Table, macro_definition: Table>, proc_macro: Table, module_reexports: Table>, deduced_param_attrs: Table>, - // Slot is full when opaque is TAIT. - is_type_alias_impl_trait: Table, - trait_impl_trait_tys: Table>>>, } @@ -419,6 +423,7 @@ struct VariantData { } bitflags::bitflags! { + #[derive(Default)] pub struct AttrFlags: u8 { const MAY_HAVE_DOC_LINKS = 1 << 0; const IS_DOC_HIDDEN = 1 << 1; diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs index dc003227d40bd..70dbf6476e2fa 100644 --- a/compiler/rustc_metadata/src/rmeta/table.rs +++ b/compiler/rustc_metadata/src/rmeta/table.rs @@ -16,6 +16,7 @@ use std::num::NonZeroUsize; /// but this has no impact on safety. pub(super) trait FixedSizeEncoding: Default { /// This should be `[u8; BYTE_LEN]`; + /// Cannot use an associated `const BYTE_LEN: usize` instead due to const eval limitations. type ByteArray; fn from_bytes(b: &Self::ByteArray) -> Self; @@ -199,31 +200,31 @@ impl FixedSizeEncoding for Option { } } -impl FixedSizeEncoding for Option { +impl FixedSizeEncoding for AttrFlags { type ByteArray = [u8; 1]; #[inline] fn from_bytes(b: &[u8; 1]) -> Self { - (b[0] != 0).then(|| AttrFlags::from_bits_truncate(b[0])) + AttrFlags::from_bits_truncate(b[0]) } #[inline] fn write_to_bytes(self, b: &mut [u8; 1]) { - b[0] = self.map_or(0, |flags| flags.bits()) + b[0] = self.bits(); } } -impl FixedSizeEncoding for Option<()> { +impl FixedSizeEncoding for bool { type ByteArray = [u8; 1]; #[inline] fn from_bytes(b: &[u8; 1]) -> Self { - (b[0] != 0).then(|| ()) + b[0] != 0 } #[inline] fn write_to_bytes(self, b: &mut [u8; 1]) { - b[0] = self.is_some() as u8 + b[0] = self as u8 } } @@ -273,44 +274,38 @@ impl FixedSizeEncoding for Option> { } /// Helper for constructing a table's serialization (also see `Table`). -pub(super) struct TableBuilder -where - Option: FixedSizeEncoding, -{ - blocks: IndexVec as FixedSizeEncoding>::ByteArray>, +pub(super) struct TableBuilder { + blocks: IndexVec, _marker: PhantomData, } -impl Default for TableBuilder -where - Option: FixedSizeEncoding, -{ +impl Default for TableBuilder { fn default() -> Self { TableBuilder { blocks: Default::default(), _marker: PhantomData } } } -impl TableBuilder +impl TableBuilder> where - Option: FixedSizeEncoding, + Option: FixedSizeEncoding, { - pub(crate) fn set(&mut self, i: I, value: T) - where - Option: FixedSizeEncoding, - { + pub(crate) fn set(&mut self, i: I, value: T) { + self.set_nullable(i, Some(value)) + } +} + +impl> TableBuilder { + pub(crate) fn set_nullable(&mut self, i: I, value: T) { // FIXME(eddyb) investigate more compact encodings for sparse tables. // On the PR @michaelwoerister mentioned: // > Space requirements could perhaps be optimized by using the HAMT `popcnt` // > trick (i.e. divide things into buckets of 32 or 64 items and then // > store bit-masks of which item in each bucket is actually serialized). self.blocks.ensure_contains_elem(i, || [0; N]); - Some(value).write_to_bytes(&mut self.blocks[i]); + value.write_to_bytes(&mut self.blocks[i]); } - pub(crate) fn encode(&self, buf: &mut FileEncoder) -> LazyTable - where - Option: FixedSizeEncoding, - { + pub(crate) fn encode(&self, buf: &mut FileEncoder) -> LazyTable { let pos = buf.position(); for block in &self.blocks { buf.emit_raw_bytes(block); @@ -323,34 +318,27 @@ where } } -impl LazyTable +impl + ParameterizedOverTcx> + LazyTable where - Option: FixedSizeEncoding, + for<'tcx> T::Value<'tcx>: FixedSizeEncoding, { /// Given the metadata, extract out the value at a particular index (if any). #[inline(never)] - pub(super) fn get<'a, 'tcx, M: Metadata<'a, 'tcx>, const N: usize>( - &self, - metadata: M, - i: I, - ) -> Option> - where - Option>: FixedSizeEncoding, - { + pub(super) fn get<'a, 'tcx, M: Metadata<'a, 'tcx>>(&self, metadata: M, i: I) -> T::Value<'tcx> { debug!("LazyTable::lookup: index={:?} len={:?}", i, self.encoded_size); let start = self.position.get(); let bytes = &metadata.blob()[start..start + self.encoded_size]; let (bytes, []) = bytes.as_chunks::() else { panic!() }; - let bytes = bytes.get(i.index())?; - FixedSizeEncoding::from_bytes(bytes) + match bytes.get(i.index()) { + Some(bytes) => FixedSizeEncoding::from_bytes(bytes), + None => FixedSizeEncoding::from_bytes(&[0; N]), + } } /// Size of the table in entries, including possible gaps. - pub(super) fn size(&self) -> usize - where - for<'tcx> Option>: FixedSizeEncoding, - { + pub(super) fn size(&self) -> usize { self.encoded_size / N } } From da3ecb09d8dda5293569ebf4e13ade3f7e2825f0 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 22 Jan 2023 05:11:24 +0000 Subject: [PATCH 294/500] Use proper InferCtxt when probing for associated types in astconv --- .../rustc_hir_analysis/src/astconv/mod.rs | 106 ++++++++++-------- compiler/rustc_hir_analysis/src/collect.rs | 6 +- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 4 + tests/ui/typeck/issue-107087.rs | 18 +++ tests/ui/typeck/issue-107087.stderr | 9 ++ 5 files changed, 97 insertions(+), 46 deletions(-) create mode 100644 tests/ui/typeck/issue-107087.rs create mode 100644 tests/ui/typeck/issue-107087.stderr diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index 6435b05cef8a8..d23368e9bae5a 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -27,7 +27,7 @@ use rustc_hir::def::{CtorOf, DefKind, Namespace, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{walk_generics, Visitor as _}; use rustc_hir::{GenericArg, GenericArgs, OpaqueTyOrigin}; -use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_middle::middle::stability::AllowUnstable; use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, SubstsRef}; use rustc_middle::ty::GenericParamDefKind; @@ -37,7 +37,7 @@ use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, BARE_TRAIT_OBJECT use rustc_span::edition::Edition; use rustc_span::lev_distance::find_best_match_for_name; use rustc_span::symbol::{kw, Ident, Symbol}; -use rustc_span::{sym, Span}; +use rustc_span::{sym, Span, DUMMY_SP}; use rustc_target::spec::abi; use rustc_trait_selection::traits; use rustc_trait_selection::traits::astconv_object_safety_violations; @@ -54,7 +54,7 @@ use std::slice; pub struct PathSeg(pub DefId, pub usize); pub trait AstConv<'tcx> { - fn tcx<'a>(&'a self) -> TyCtxt<'tcx>; + fn tcx(&self) -> TyCtxt<'tcx>; fn item_def_id(&self) -> DefId; @@ -131,6 +131,8 @@ pub trait AstConv<'tcx> { { self } + + fn infcx(&self) -> Option<&InferCtxt<'tcx>>; } #[derive(Debug)] @@ -2132,48 +2134,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ) .emit() // Already reported in an earlier stage. } else { - // Find all the `impl`s that `qself_ty` has for any trait that has the - // associated type, so that we suggest the right one. - let infcx = tcx.infer_ctxt().build(); - // We create a fresh `ty::ParamEnv` instead of the one for `self.item_def_id()` - // to avoid a cycle error in `src/test/ui/resolve/issue-102946.rs`. - let param_env = ty::ParamEnv::empty(); - let traits: Vec<_> = self - .tcx() - .all_traits() - .filter(|trait_def_id| { - // Consider only traits with the associated type - tcx.associated_items(*trait_def_id) - .in_definition_order() - .any(|i| { - i.kind.namespace() == Namespace::TypeNS - && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident - && matches!(i.kind, ty::AssocKind::Type) - }) - // Consider only accessible traits - && tcx.visibility(*trait_def_id) - .is_accessible_from(self.item_def_id(), tcx) - && tcx.all_impls(*trait_def_id) - .any(|impl_def_id| { - let trait_ref = tcx.impl_trait_ref(impl_def_id); - trait_ref.map_or(false, |trait_ref| { - let impl_ = trait_ref.subst( - tcx, - infcx.fresh_substs_for_item(span, impl_def_id), - ); - infcx - .can_eq( - param_env, - tcx.erase_regions(impl_.self_ty()), - tcx.erase_regions(qself_ty), - ) - .is_ok() - }) - && tcx.impl_polarity(impl_def_id) != ty::ImplPolarity::Negative - }) - }) - .map(|trait_def_id| tcx.def_path_str(trait_def_id)) - .collect(); + let traits: Vec<_> = + self.probe_traits_that_match_assoc_ty(qself_ty, assoc_ident); // Don't print `TyErr` to the user. self.report_ambiguous_associated_type( @@ -2232,6 +2194,60 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { Ok((ty, DefKind::AssocTy, assoc_ty_did)) } + fn probe_traits_that_match_assoc_ty( + &self, + qself_ty: Ty<'tcx>, + assoc_ident: Ident, + ) -> Vec { + let tcx = self.tcx(); + + // In contexts that have no inference context, just make a new one. + // We do need a local variable to store it, though. + let infcx_; + let infcx = if let Some(infcx) = self.infcx() { + infcx + } else { + assert!(!qself_ty.needs_infer()); + infcx_ = tcx.infer_ctxt().build(); + &infcx_ + }; + + tcx.all_traits() + .filter(|trait_def_id| { + // Consider only traits with the associated type + tcx.associated_items(*trait_def_id) + .in_definition_order() + .any(|i| { + i.kind.namespace() == Namespace::TypeNS + && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident + && matches!(i.kind, ty::AssocKind::Type) + }) + // Consider only accessible traits + && tcx.visibility(*trait_def_id) + .is_accessible_from(self.item_def_id(), tcx) + && tcx.all_impls(*trait_def_id) + .any(|impl_def_id| { + let trait_ref = tcx.impl_trait_ref(impl_def_id); + trait_ref.map_or(false, |trait_ref| { + let impl_ = trait_ref.subst( + tcx, + infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id), + ); + infcx + .can_eq( + ty::ParamEnv::empty(), + tcx.erase_regions(impl_.self_ty()), + tcx.erase_regions(qself_ty), + ) + .is_ok() + }) + && tcx.impl_polarity(impl_def_id) != ty::ImplPolarity::Negative + }) + }) + .map(|trait_def_id| tcx.def_path_str(trait_def_id)) + .collect() + } + fn lookup_assoc_ty( &self, ident: Ident, diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index c17778ce8bc09..c3ea867785b14 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -25,7 +25,7 @@ use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{GenericParamKind, Node}; -use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::ObligationCause; use rustc_middle::hir::nested_filter; use rustc_middle::ty::query::Providers; @@ -517,6 +517,10 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) { // There's no place to record types from signatures? } + + fn infcx(&self) -> Option<&InferCtxt<'tcx>> { + None + } } /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present. diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index 428fde642bc09..2747dabc2368f 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -324,6 +324,10 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { let ty = if !ty.has_escaping_bound_vars() { self.normalize(span, ty) } else { ty }; self.write_ty(hir_id, ty) } + + fn infcx(&self) -> Option<&infer::InferCtxt<'tcx>> { + Some(&self.infcx) + } } /// Represents a user-provided type in the raw form (never normalized). diff --git a/tests/ui/typeck/issue-107087.rs b/tests/ui/typeck/issue-107087.rs new file mode 100644 index 0000000000000..135cdf19e3e3e --- /dev/null +++ b/tests/ui/typeck/issue-107087.rs @@ -0,0 +1,18 @@ +struct A(T); + +trait Foo { + type B; +} + +impl Foo for A { + type B = i32; +} + +impl Foo for A { + type B = i32; +} + +fn main() { + A::B::<>::C + //~^ ERROR ambiguous associated type +} diff --git a/tests/ui/typeck/issue-107087.stderr b/tests/ui/typeck/issue-107087.stderr new file mode 100644 index 0000000000000..70f19320802b9 --- /dev/null +++ b/tests/ui/typeck/issue-107087.stderr @@ -0,0 +1,9 @@ +error[E0223]: ambiguous associated type + --> $DIR/issue-107087.rs:16:5 + | +LL | A::B::<>::C + | ^^^^^^^^ help: use the fully-qualified path: ` as Foo>::B` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0223`. From bed3bb53d207c1bf92c26833e8d3d4280550f83e Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 21 Jan 2023 21:54:49 +0000 Subject: [PATCH 295/500] Don't resolve type var roots in point_at_expr_source_of_inferred_type --- compiler/rustc_hir_typeck/src/demand.rs | 4 +++- tests/ui/typeck/bad-type-in-vec-push.rs | 14 ++++++++++++++ tests/ui/typeck/bad-type-in-vec-push.stderr | 20 ++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 tests/ui/typeck/bad-type-in-vec-push.rs create mode 100644 tests/ui/typeck/bad-type-in-vec-push.stderr diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index bd1626dff7951..d8cca55a8f892 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -270,7 +270,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { lt_op: |_| self.tcx.lifetimes.re_erased, ct_op: |c| c, ty_op: |t| match *t.kind() { - ty::Infer(ty::TyVar(vid)) => self.tcx.mk_ty_infer(ty::TyVar(self.root_var(vid))), + ty::Infer(ty::TyVar(_)) => self.tcx.mk_ty_var(ty::TyVid::from_u32(0)), ty::Infer(ty::IntVar(_)) => { self.tcx.mk_ty_infer(ty::IntVar(ty::IntVid { index: 0 })) } @@ -333,6 +333,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // inferred in this method call. let arg = &args[i]; let arg_ty = self.node_ty(arg.hir_id); + if !arg.span.overlaps(mismatch_span) { err.span_label( arg.span, &format!( @@ -340,6 +341,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { inferred as `{ty}`", ), ); + } param_args.insert(param_ty, (arg, arg_ty)); } } diff --git a/tests/ui/typeck/bad-type-in-vec-push.rs b/tests/ui/typeck/bad-type-in-vec-push.rs new file mode 100644 index 0000000000000..397e07dc17b42 --- /dev/null +++ b/tests/ui/typeck/bad-type-in-vec-push.rs @@ -0,0 +1,14 @@ +// The error message here still is pretty confusing. + +fn main() { + let mut result = vec![1]; + // The type of `result` is constrained to be `Vec<{integer}>` here. + // But the logic we use to find what expression constrains a type + // is not sophisticated enough to know this. + + let mut vector = Vec::new(); + vector.sort(); + result.push(vector); + //~^ ERROR mismatched types + // So it thinks that the type of `result` is constrained here. +} diff --git a/tests/ui/typeck/bad-type-in-vec-push.stderr b/tests/ui/typeck/bad-type-in-vec-push.stderr new file mode 100644 index 0000000000000..a24c49f0e9a3c --- /dev/null +++ b/tests/ui/typeck/bad-type-in-vec-push.stderr @@ -0,0 +1,20 @@ +error[E0308]: mismatched types + --> $DIR/bad-type-in-vec-push.rs:11:17 + | +LL | vector.sort(); + | ------ here the type of `vector` is inferred to be `Vec<_>` +LL | result.push(vector); + | ---- ^^^^^^ + | | | + | | expected integer, found struct `Vec` + | | this is of type `Vec<_>`, which causes `result` to be inferred as `Vec<{integer}>` + | arguments to this method are incorrect + | + = note: expected type `{integer}` + found struct `Vec<_>` +note: associated function defined here + --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. From 9f933b5642c08e4241cbfed0f15270df552ce8e6 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 21 Jan 2023 22:18:51 +0000 Subject: [PATCH 296/500] Hack to suppress bad labels in type mismatch inference deduction code --- compiler/rustc_hir_typeck/src/demand.rs | 36 ++++++++++--------- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 8 ++++- tests/ui/typeck/bad-type-in-vec-push.rs | 6 ++++ tests/ui/typeck/bad-type-in-vec-push.stderr | 19 +++++++--- 4 files changed, 47 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index d8cca55a8f892..8e23ded3c09b4 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -61,7 +61,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { || self.suggest_into(err, expr, expr_ty, expected) || self.suggest_floating_point_literal(err, expr, expected); if !suggested { - self.point_at_expr_source_of_inferred_type(err, expr, expr_ty, expected); + self.point_at_expr_source_of_inferred_type(err, expr, expr_ty, expected, expr.span); } } @@ -222,6 +222,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr: &hir::Expr<'_>, found: Ty<'tcx>, expected: Ty<'tcx>, + mismatch_span: Span, ) -> bool { let map = self.tcx.hir(); @@ -281,7 +282,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }, }; let mut prev = eraser.fold_ty(ty); - let mut prev_span = None; + let mut prev_span: Option = None; for binding in expr_finder.uses { // In every expression where the binding is referenced, we will look at that @@ -334,13 +335,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let arg = &args[i]; let arg_ty = self.node_ty(arg.hir_id); if !arg.span.overlaps(mismatch_span) { - err.span_label( - arg.span, - &format!( - "this is of type `{arg_ty}`, which causes `{ident}` to be \ - inferred as `{ty}`", - ), - ); + err.span_label( + arg.span, + &format!( + "this is of type `{arg_ty}`, which causes `{ident}` to be \ + inferred as `{ty}`", + ), + ); } param_args.insert(param_ty, (arg, arg_ty)); } @@ -384,12 +385,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && self.can_eq(self.param_env, ty, found).is_ok() { // We only point at the first place where the found type was inferred. + if !segment.ident.span.overlaps(mismatch_span) { err.span_label( segment.ident.span, with_forced_trimmed_paths!(format!( "here the type of `{ident}` is inferred to be `{ty}`", )), - ); + );} break; } else if !param_args.is_empty() { break; @@ -408,12 +410,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We use the *previous* span because if the type is known *here* it means // it was *evaluated earlier*. We don't do this for method calls because we // evaluate the method's self type eagerly, but not in any other case. - err.span_label( - span, - with_forced_trimmed_paths!(format!( - "here the type of `{ident}` is inferred to be `{ty}`", - )), - ); + if !span.overlaps(mismatch_span) { + err.span_label( + span, + with_forced_trimmed_paths!(format!( + "here the type of `{ident}` is inferred to be `{ty}`", + )), + ); + } break; } prev = ty; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index c9609e6943981..677c80297b912 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -808,7 +808,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { kind: TypeVariableOriginKind::MiscVariable, span: full_call_span, }); - self.point_at_expr_source_of_inferred_type(&mut err, rcvr, expected, callee_ty); + self.point_at_expr_source_of_inferred_type( + &mut err, + rcvr, + expected, + callee_ty, + provided_arg_span, + ); } // Call out where the function is defined self.label_fn_like( diff --git a/tests/ui/typeck/bad-type-in-vec-push.rs b/tests/ui/typeck/bad-type-in-vec-push.rs index 397e07dc17b42..a807f030cfce4 100644 --- a/tests/ui/typeck/bad-type-in-vec-push.rs +++ b/tests/ui/typeck/bad-type-in-vec-push.rs @@ -12,3 +12,9 @@ fn main() { //~^ ERROR mismatched types // So it thinks that the type of `result` is constrained here. } + +fn example2() { + let mut x = vec![1]; + x.push(""); + //~^ ERROR mismatched types +} diff --git a/tests/ui/typeck/bad-type-in-vec-push.stderr b/tests/ui/typeck/bad-type-in-vec-push.stderr index a24c49f0e9a3c..e4c99ec8e701f 100644 --- a/tests/ui/typeck/bad-type-in-vec-push.stderr +++ b/tests/ui/typeck/bad-type-in-vec-push.stderr @@ -4,10 +4,8 @@ error[E0308]: mismatched types LL | vector.sort(); | ------ here the type of `vector` is inferred to be `Vec<_>` LL | result.push(vector); - | ---- ^^^^^^ - | | | - | | expected integer, found struct `Vec` - | | this is of type `Vec<_>`, which causes `result` to be inferred as `Vec<{integer}>` + | ---- ^^^^^^ expected integer, found struct `Vec` + | | | arguments to this method are incorrect | = note: expected type `{integer}` @@ -15,6 +13,17 @@ LL | result.push(vector); note: associated function defined here --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL -error: aborting due to previous error +error[E0308]: mismatched types + --> $DIR/bad-type-in-vec-push.rs:18:12 + | +LL | x.push(""); + | ---- ^^ expected integer, found `&str` + | | + | arguments to this method are incorrect + | +note: associated function defined here + --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL + +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. From 62a1e76d2beaa87d7f02a55e2d7faa03cdd5fd7f Mon Sep 17 00:00:00 2001 From: yanchen4791 Date: Mon, 5 Dec 2022 16:51:49 -0800 Subject: [PATCH 297/500] Add hint for missing lifetime bound on trait object when type alias is used --- .../src/diagnostics/region_errors.rs | 59 +++++++++++++------ compiler/rustc_hir/src/hir.rs | 7 +++ compiler/rustc_middle/src/ty/context.rs | 24 ++++++++ ...und-on-trait-object-using-type-alias.fixed | 45 ++++++++++++++ ...-bound-on-trait-object-using-type-alias.rs | 45 ++++++++++++++ ...nd-on-trait-object-using-type-alias.stderr | 15 +++++ 6 files changed, 176 insertions(+), 19 deletions(-) create mode 100644 tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.fixed create mode 100644 tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.rs create mode 100644 tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.stderr diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 187861ba127bd..87db08ef5b510 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -813,17 +813,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { if *outlived_f != ty::ReStatic { return; } + let suitable_region = self.infcx.tcx.is_suitable_region(f); + let Some(suitable_region) = suitable_region else { return; }; - let fn_returns = self - .infcx - .tcx - .is_suitable_region(f) - .map(|r| self.infcx.tcx.return_type_impl_or_dyn_traits(r.def_id)) - .unwrap_or_default(); - - if fn_returns.is_empty() { - return; - } + let fn_returns = self.infcx.tcx.return_type_impl_or_dyn_traits(suitable_region.def_id); let param = if let Some(param) = find_param_with_region(self.infcx.tcx, f, outlived_f) { param @@ -839,15 +832,43 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { }; let captures = format!("captures data from {arg}"); - return nice_region_error::suggest_new_region_bound( - self.infcx.tcx, - diag, - fn_returns, - lifetime.to_string(), - Some(arg), - captures, - Some((param.param_ty_span, param.param_ty.to_string())), - self.infcx.tcx.is_suitable_region(f).map(|r| r.def_id), + if !fn_returns.is_empty() { + nice_region_error::suggest_new_region_bound( + self.infcx.tcx, + diag, + fn_returns, + lifetime.to_string(), + Some(arg), + captures, + Some((param.param_ty_span, param.param_ty.to_string())), + Some(suitable_region.def_id), + ); + return; + } + + let Some((alias_tys, alias_span)) = self + .infcx + .tcx + .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.def_id) else { return; }; + + // in case the return type of the method is a type alias + let mut spans_suggs: Vec<_> = Vec::new(); + for alias_ty in alias_tys { + if alias_ty.span.desugaring_kind().is_some() { + // Skip `async` desugaring `impl Future`. + () + } + if let TyKind::TraitObject(_, lt, _) = alias_ty.kind { + spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string())); + } + } + spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string())); + diag.multipart_suggestion_verbose( + &format!( + "to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias" + ), + spans_suggs, + Applicability::MaybeIncorrect, ); } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index d6566860f8170..b456bd08048db 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -3524,6 +3524,13 @@ impl<'hir> Node<'hir> { } } + pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> { + match self { + Node::Item(Item { kind: ItemKind::TyAlias(ty, ..), .. }) => Some(ty), + _ => None, + } + } + pub fn body_id(&self) -> Option { match self { Node::TraitItem(TraitItem { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index ce04d8d21f4cd..0b16270ea9874 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -997,6 +997,30 @@ impl<'tcx> TyCtxt<'tcx> { v.0 } + /// Given a `DefId` for an `fn`, return all the `dyn` and `impl` traits in its return type and associated alias span when type alias is used + pub fn return_type_impl_or_dyn_traits_with_type_alias( + self, + scope_def_id: LocalDefId, + ) -> Option<(Vec<&'tcx hir::Ty<'tcx>>, Span)> { + let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id); + let mut v = TraitObjectVisitor(vec![], self.hir()); + // when the return type is a type alias + if let Some(hir::FnDecl { output: hir::FnRetTy::Return(hir_output), .. }) = self.hir().fn_decl_by_hir_id(hir_id) + && let hir::TyKind::Path(hir::QPath::Resolved( + None, + hir::Path { res: hir::def::Res::Def(DefKind::TyAlias, def_id), .. }, )) = hir_output.kind + && let Some(local_id) = def_id.as_local() + && let Some(alias_ty) = self.hir().get_by_def_id(local_id).alias_ty() // it is type alias + && let Some(alias_generics) = self.hir().get_by_def_id(local_id).generics() + { + v.visit_ty(alias_ty); + if !v.0.is_empty() { + return Some((v.0, alias_generics.span)); + } + } + return None; + } + pub fn return_type_impl_trait(self, scope_def_id: LocalDefId) -> Option<(Ty<'tcx>, Span)> { // `type_of()` will fail on these (#55796, #86483), so only allow `fn`s or closures. match self.hir().get_by_def_id(scope_def_id) { diff --git a/tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.fixed b/tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.fixed new file mode 100644 index 0000000000000..aa3bce2945b68 --- /dev/null +++ b/tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.fixed @@ -0,0 +1,45 @@ +// run-rustfix + +trait Greeter0 { + fn greet(&self); +} + +trait Greeter1 { + fn greet(&self); +} + +type BoxedGreeter<'a> = (Box, Box); +//~^ HELP to declare that the trait object captures data from argument `self`, you can add a lifetime parameter `'a` in the type alias + +struct FixedGreeter<'a>(pub &'a str); + +impl Greeter0 for FixedGreeter<'_> { + fn greet(&self) { + println!("0 {}", self.0) + } +} + +impl Greeter1 for FixedGreeter<'_> { + fn greet(&self) { + println!("1 {}", self.0) + } +} + +struct Greetings(pub Vec); + +impl Greetings { + pub fn get(&self, i: usize) -> BoxedGreeter { + (Box::new(FixedGreeter(&self.0[i])), Box::new(FixedGreeter(&self.0[i]))) + //~^ ERROR lifetime may not live long enough + } +} + +fn main() { + let mut g = Greetings {0 : vec!()}; + g.0.push("a".to_string()); + g.0.push("b".to_string()); + g.get(0).0.greet(); + g.get(0).1.greet(); + g.get(1).0.greet(); + g.get(1).1.greet(); +} diff --git a/tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.rs b/tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.rs new file mode 100644 index 0000000000000..20c88ec69813a --- /dev/null +++ b/tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.rs @@ -0,0 +1,45 @@ +// run-rustfix + +trait Greeter0 { + fn greet(&self); +} + +trait Greeter1 { + fn greet(&self); +} + +type BoxedGreeter = (Box, Box); +//~^ HELP to declare that the trait object captures data from argument `self`, you can add a lifetime parameter `'a` in the type alias + +struct FixedGreeter<'a>(pub &'a str); + +impl Greeter0 for FixedGreeter<'_> { + fn greet(&self) { + println!("0 {}", self.0) + } +} + +impl Greeter1 for FixedGreeter<'_> { + fn greet(&self) { + println!("1 {}", self.0) + } +} + +struct Greetings(pub Vec); + +impl Greetings { + pub fn get(&self, i: usize) -> BoxedGreeter { + (Box::new(FixedGreeter(&self.0[i])), Box::new(FixedGreeter(&self.0[i]))) + //~^ ERROR lifetime may not live long enough + } +} + +fn main() { + let mut g = Greetings {0 : vec!()}; + g.0.push("a".to_string()); + g.0.push("b".to_string()); + g.get(0).0.greet(); + g.get(0).1.greet(); + g.get(1).0.greet(); + g.get(1).1.greet(); +} diff --git a/tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.stderr b/tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.stderr new file mode 100644 index 0000000000000..808d8bb905885 --- /dev/null +++ b/tests/ui/lifetimes/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.stderr @@ -0,0 +1,15 @@ +error: lifetime may not live long enough + --> $DIR/issue-103582-hint-for-missing-lifetime-bound-on-trait-object-using-type-alias.rs:32:9 + | +LL | pub fn get(&self, i: usize) -> BoxedGreeter { + | - let's call the lifetime of this reference `'1` +LL | (Box::new(FixedGreeter(&self.0[i])), Box::new(FixedGreeter(&self.0[i]))) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static` + | +help: to declare that the trait object captures data from argument `self`, you can add a lifetime parameter `'a` in the type alias + | +LL | type BoxedGreeter<'a> = (Box, Box); + | ++++ ++++ ++++ + +error: aborting due to previous error + From aae222c974a982e878f279b95bd1a9d0166ff229 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Mon, 23 Jan 2023 10:54:05 -0600 Subject: [PATCH 298/500] fix: correct span for structs with const generics --- src/items.rs | 2 +- tests/target/issue_5668.rs | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 tests/target/issue_5668.rs diff --git a/src/items.rs b/src/items.rs index 755a41f6bf0cd..063a6428a08f7 100644 --- a/src/items.rs +++ b/src/items.rs @@ -1245,7 +1245,7 @@ fn format_unit_struct( ) -> Option { let header_str = format_header(context, p.prefix, p.ident, p.vis, offset); let generics_str = if let Some(generics) = p.generics { - let hi = context.snippet_provider.span_before(p.span, ";"); + let hi = context.snippet_provider.span_before_last(p.span, ";"); format_generics( context, generics, diff --git a/tests/target/issue_5668.rs b/tests/target/issue_5668.rs new file mode 100644 index 0000000000000..bbd9a530b81c0 --- /dev/null +++ b/tests/target/issue_5668.rs @@ -0,0 +1,8 @@ +type Foo = impl Send; +struct Struct< + const C: usize = { + let _: Foo = (); + //~^ ERROR: mismatched types + 0 + }, +>; From 020cca8d36cb678e3ddc2ead41364be314d19e93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Mon, 23 Jan 2023 14:29:53 +0000 Subject: [PATCH 299/500] review comment: Remove AST AnonTy --- compiler/rustc_ast/src/ast.rs | 3 --- compiler/rustc_ast/src/mut_visit.rs | 2 +- compiler/rustc_ast/src/visit.rs | 2 +- compiler/rustc_ast_lowering/src/lib.rs | 1 - compiler/rustc_ast_pretty/src/pprust/state.rs | 3 --- compiler/rustc_parse/src/parser/ty.rs | 2 +- compiler/rustc_passes/src/hir_stats.rs | 1 - src/tools/rustfmt/src/types.rs | 4 +--- 8 files changed, 4 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 3aad51325dcd6..7de594719ddc4 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -2096,9 +2096,6 @@ pub enum TyKind { Err, /// Placeholder for a `va_list`. CVarArgs, - /// Placeholder for "anonymous enums", which don't exist, but keeping their - /// information around lets us produce better diagnostics. - AnonEnum(Vec>), } impl TyKind { diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index 894885cf0fea7..77f342d1eb322 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -470,7 +470,7 @@ pub fn noop_visit_ty(ty: &mut P, vis: &mut T) { vis.visit_fn_decl(decl); vis.visit_span(decl_span); } - TyKind::AnonEnum(tys) | TyKind::Tup(tys) => visit_vec(tys, |ty| vis.visit_ty(ty)), + TyKind::Tup(tys) => visit_vec(tys, |ty| vis.visit_ty(ty)), TyKind::Paren(ty) => vis.visit_ty(ty), TyKind::Path(qself, path) => { vis.visit_qself(qself); diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index 1ab70f0309c01..feb5187536ffa 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -400,7 +400,7 @@ pub fn walk_ty<'a, V: Visitor<'a>>(visitor: &mut V, typ: &'a Ty) { walk_list!(visitor, visit_lifetime, opt_lifetime, LifetimeCtxt::Ref); visitor.visit_ty(&mutable_type.ty) } - TyKind::AnonEnum(tys) | TyKind::Tup(tys) => { + TyKind::Tup(tys) => { walk_list!(visitor, visit_ty, tys); } TyKind::BareFn(function_declaration) => { diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index a60d02002da33..41d4a5679f1a0 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1235,7 +1235,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let kind = match &t.kind { TyKind::Infer => hir::TyKind::Infer, TyKind::Err => hir::TyKind::Err, - TyKind::AnonEnum(_) => hir::TyKind::Err, TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)), TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)), TyKind::Ref(region, mt) => { diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 3f9b96a6158a1..6a8064b0e874e 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -1041,9 +1041,6 @@ impl<'a> State<'a> { } self.pclose(); } - ast::TyKind::AnonEnum(elts) => { - self.strsep("|", false, Inconsistent, elts, |s, ty| s.print_type(ty)); - } ast::TyKind::Paren(typ) => { self.popen(); self.print_type(typ); diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index 72994df6f9f46..43e6eac438ba5 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -390,7 +390,7 @@ impl<'a> Parser<'a> { .join("\n"), )); err.emit(); - return Ok(self.mk_ty(lo.to(self.prev_token.span), TyKind::AnonEnum(types))); + return Ok(self.mk_ty(lo.to(self.prev_token.span), TyKind::Err)); } if allow_qpath_recovery { self.maybe_recover_from_bad_qpath(ty) } else { Ok(ty) } } diff --git a/compiler/rustc_passes/src/hir_stats.rs b/compiler/rustc_passes/src/hir_stats.rs index 312bd8839e0d0..b86d2316820ce 100644 --- a/compiler/rustc_passes/src/hir_stats.rs +++ b/compiler/rustc_passes/src/hir_stats.rs @@ -579,7 +579,6 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { [ Slice, Array, - AnonEnum, Ptr, Ref, BareFn, diff --git a/src/tools/rustfmt/src/types.rs b/src/tools/rustfmt/src/types.rs index f065ec680d724..c1991e8d2c808 100644 --- a/src/tools/rustfmt/src/types.rs +++ b/src/tools/rustfmt/src/types.rs @@ -839,9 +839,7 @@ impl Rewrite for ast::Ty { }) } ast::TyKind::CVarArgs => Some("...".to_owned()), - ast::TyKind::AnonEnum(_) | ast::TyKind::Err => { - Some(context.snippet(self.span).to_owned()) - } + ast::TyKind::Err => Some(context.snippet(self.span).to_owned()), ast::TyKind::Typeof(ref anon_const) => rewrite_call( context, "typeof", From 7f5ce942809e15f65d91089e8baacc6affdf6c9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Mi=C4=85sko?= Date: Mon, 23 Jan 2023 00:00:00 +0000 Subject: [PATCH 300/500] Bring tests back into rustc source tarball They were missing after recent move from src/test to tests. --- src/bootstrap/dist.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 2d86ff1d2baea..02e35d2436e2f 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -962,7 +962,7 @@ impl Step for PlainSourceTarball { "Cargo.toml", "Cargo.lock", ]; - let src_dirs = ["src", "compiler", "library"]; + let src_dirs = ["src", "compiler", "library", "tests"]; copy_src_dirs(builder, &builder.src, &src_dirs, &[], &plain_dst_src); From 57ca36861d35dd1f75d8b51dd975c884bb2c6872 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 23 Jan 2023 14:31:35 -0700 Subject: [PATCH 301/500] rustdoc: make item links consistently use `title="{shortty} {path}"` The ordering in item tables was flipped in 3030cbea957adbd560bf2eaa34c1b8a56daee16a, making it inconsistent with the ordering in method signatures. Compare these: https://github.com/rust-lang/rust/blob/c8e6a9e8b6251bbc8276cb78cabe1998deecbed7/src/librustdoc/html/render/print_item.rs#L455-L459 https://github.com/rust-lang/rust/blob/c8e6a9e8b6251bbc8276cb78cabe1998deecbed7/src/librustdoc/html/format.rs#L903-L908 --- src/librustdoc/html/render/print_item.rs | 2 +- tests/rustdoc-gui/unsafe-fn.goml | 4 ++-- ...ue-83375-multiple-mods-w-same-name-doc-inline-last-item.rs | 2 +- .../issue-83375-multiple-mods-w-same-name-doc-inline.rs | 2 +- tests/rustdoc/issue-99221-multiple-structs-w-same-name.rs | 2 +- tests/rustdoc/issue-99734-multiple-foreigns-w-same-name.rs | 2 +- tests/rustdoc/issue-99734-multiple-mods-w-same-name.rs | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index f824c9e3ad2bd..a09f309502a28 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -452,7 +452,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: stab = stab.unwrap_or_default(), unsafety_flag = unsafety_flag, href = item_path(myitem.type_(), myitem.name.unwrap().as_str()), - title = [full_path(cx, myitem), myitem.type_().to_string()] + title = [myitem.type_().to_string(), full_path(cx, myitem)] .iter() .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None }) .collect::>() diff --git a/tests/rustdoc-gui/unsafe-fn.goml b/tests/rustdoc-gui/unsafe-fn.goml index d3a672ddde6e4..3ecb25c82a44e 100644 --- a/tests/rustdoc-gui/unsafe-fn.goml +++ b/tests/rustdoc-gui/unsafe-fn.goml @@ -4,8 +4,8 @@ goto: "file://" + |DOC_PATH| + "/test_docs/index.html" show-text: true compare-elements-property: ( - "//a[@title='test_docs::safe_fn fn']/..", - "//a[@title='test_docs::unsafe_fn fn']/..", + "//a[@title='fn test_docs::safe_fn']/..", + "//a[@title='fn test_docs::unsafe_fn']/..", ["clientHeight"] ) diff --git a/tests/rustdoc/issue-83375-multiple-mods-w-same-name-doc-inline-last-item.rs b/tests/rustdoc/issue-83375-multiple-mods-w-same-name-doc-inline-last-item.rs index d3a7a870b580a..9bce25846d858 100644 --- a/tests/rustdoc/issue-83375-multiple-mods-w-same-name-doc-inline-last-item.rs +++ b/tests/rustdoc/issue-83375-multiple-mods-w-same-name-doc-inline-last-item.rs @@ -11,6 +11,6 @@ pub mod sub { #[doc(inline)] pub use sub::*; -// @count foo/index.html '//a[@class="mod"][@title="foo::prelude mod"]' 1 +// @count foo/index.html '//a[@class="mod"][@title="mod foo::prelude"]' 1 // @count foo/prelude/index.html '//div[@class="item-row"]' 0 pub mod prelude {} diff --git a/tests/rustdoc/issue-83375-multiple-mods-w-same-name-doc-inline.rs b/tests/rustdoc/issue-83375-multiple-mods-w-same-name-doc-inline.rs index b836925099364..d0960dfef4362 100644 --- a/tests/rustdoc/issue-83375-multiple-mods-w-same-name-doc-inline.rs +++ b/tests/rustdoc/issue-83375-multiple-mods-w-same-name-doc-inline.rs @@ -8,7 +8,7 @@ pub mod sub { } } -// @count foo/index.html '//a[@class="mod"][@title="foo::prelude mod"]' 1 +// @count foo/index.html '//a[@class="mod"][@title="mod foo::prelude"]' 1 // @count foo/prelude/index.html '//div[@class="item-row"]' 0 pub mod prelude {} diff --git a/tests/rustdoc/issue-99221-multiple-structs-w-same-name.rs b/tests/rustdoc/issue-99221-multiple-structs-w-same-name.rs index 41e64726a3246..ba29a77ebdff8 100644 --- a/tests/rustdoc/issue-99221-multiple-structs-w-same-name.rs +++ b/tests/rustdoc/issue-99221-multiple-structs-w-same-name.rs @@ -9,6 +9,6 @@ extern crate issue_99221_aux; pub use issue_99221_aux::*; -// @count foo/index.html '//a[@class="struct"][@title="foo::Print struct"]' 1 +// @count foo/index.html '//a[@class="struct"][@title="struct foo::Print"]' 1 pub struct Print; diff --git a/tests/rustdoc/issue-99734-multiple-foreigns-w-same-name.rs b/tests/rustdoc/issue-99734-multiple-foreigns-w-same-name.rs index 3208fea05b376..b56ec6e11eafc 100644 --- a/tests/rustdoc/issue-99734-multiple-foreigns-w-same-name.rs +++ b/tests/rustdoc/issue-99734-multiple-foreigns-w-same-name.rs @@ -9,7 +9,7 @@ extern crate issue_99734_aux; pub use issue_99734_aux::*; -// @count foo/index.html '//a[@class="fn"][@title="foo::main fn"]' 1 +// @count foo/index.html '//a[@class="fn"][@title="fn foo::main"]' 1 extern "C" { pub fn main() -> std::ffi::c_int; diff --git a/tests/rustdoc/issue-99734-multiple-mods-w-same-name.rs b/tests/rustdoc/issue-99734-multiple-mods-w-same-name.rs index b2f9b8b46578b..8f5d6fa3d56d3 100644 --- a/tests/rustdoc/issue-99734-multiple-mods-w-same-name.rs +++ b/tests/rustdoc/issue-99734-multiple-mods-w-same-name.rs @@ -9,6 +9,6 @@ extern crate issue_99734_aux; pub use issue_99734_aux::*; -// @count foo/index.html '//a[@class="mod"][@title="foo::task mod"]' 1 +// @count foo/index.html '//a[@class="mod"][@title="mod foo::task"]' 1 pub mod task {} From 5dd87c58aa8f9628eb8da9ad71f9c6488d409853 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 23 Jan 2023 10:44:01 -0700 Subject: [PATCH 302/500] rustdoc: simplify settings popover DOM * Changes the class names so that they all start with `setting-`. That should make it harder to accidentally use a setting class outside the settings popover, where loading the CSS might accidentally change the styles of something unrelated. * Get rid of an unnecessary wrapper DIV around the radio button line. * Simplify CSS selectors by making the DOM easier and more intuitive to target. --- src/librustdoc/html/static/css/settings.css | 28 ++++++-------- src/librustdoc/html/static/js/settings.js | 40 ++++++++++---------- tests/rustdoc-gui/mobile.goml | 4 +- tests/rustdoc-gui/settings.goml | 42 ++++++++++----------- tests/rustdoc-gui/theme-change.goml | 8 ++-- 5 files changed, 60 insertions(+), 62 deletions(-) diff --git a/src/librustdoc/html/static/css/settings.css b/src/librustdoc/html/static/css/settings.css index 4e9803fe2366d..c28cefebc8bf5 100644 --- a/src/librustdoc/html/static/css/settings.css +++ b/src/librustdoc/html/static/css/settings.css @@ -3,8 +3,7 @@ position: relative; } -.setting-line .radio-line input, -.setting-line .settings-toggle input { +.setting-radio input, .setting-check input { margin-right: 0.3em; height: 1.2rem; width: 1.2rem; @@ -14,21 +13,20 @@ -webkit-appearance: none; cursor: pointer; } -.setting-line .radio-line input { +.setting-radio input { border-radius: 50%; } -.setting-line .settings-toggle input:checked { +.setting-check input:checked { content: url('data:image/svg+xml,\ \ '); } -.setting-line .radio-line input + span, -.setting-line .settings-toggle span { +.setting-radio span, .setting-check span { padding-bottom: 1px; } -.radio-line .choice { +.setting-radio { margin-top: 0.1em; margin-bottom: 0.1em; min-width: 3.8em; @@ -37,11 +35,11 @@ align-items: center; cursor: pointer; } -.radio-line .choice + .choice { +.setting-radio + .setting-radio { margin-left: 0.5em; } -.settings-toggle { +.setting-check { position: relative; width: 100%; margin-right: 20px; @@ -50,23 +48,21 @@ cursor: pointer; } -.setting-line .radio-line input:checked { +.setting-radio input:checked { box-shadow: inset 0 0 0 3px var(--main-background-color); background-color: var(--settings-input-color); } -.setting-line .settings-toggle input:checked { +.setting-check input:checked { background-color: var(--settings-input-color); } -.setting-line .radio-line input:focus, -.setting-line .settings-toggle input:focus { +.setting-radio input:focus, .setting-check input:focus { box-shadow: 0 0 1px 1px var(--settings-input-color); } /* In here we combine both `:focus` and `:checked` properties. */ -.setting-line .radio-line input:checked:focus { +.setting-radio input:checked:focus { box-shadow: inset 0 0 0 3px var(--main-background-color), 0 0 2px 2px var(--settings-input-color); } -.setting-line .radio-line input:hover, -.setting-line .settings-toggle input:hover { +.setting-radio input:hover, .setting-check input:hover { border-color: var(--settings-input-color) !important; } diff --git a/src/librustdoc/html/static/js/settings.js b/src/librustdoc/html/static/js/settings.js index 84df1b7d3911a..fef856d5e2c2a 100644 --- a/src/librustdoc/html/static/js/settings.js +++ b/src/librustdoc/html/static/js/settings.js @@ -48,13 +48,13 @@ } function showLightAndDark() { - removeClass(document.getElementById("preferred-light-theme").parentElement, "hidden"); - removeClass(document.getElementById("preferred-dark-theme").parentElement, "hidden"); + removeClass(document.getElementById("preferred-light-theme"), "hidden"); + removeClass(document.getElementById("preferred-dark-theme"), "hidden"); } function hideLightAndDark() { - addClass(document.getElementById("preferred-light-theme").parentElement, "hidden"); - addClass(document.getElementById("preferred-dark-theme").parentElement, "hidden"); + addClass(document.getElementById("preferred-light-theme"), "hidden"); + addClass(document.getElementById("preferred-dark-theme"), "hidden"); } function updateLightAndDark() { @@ -127,38 +127,40 @@ let output = ""; for (const setting of settings) { - output += "
"; const js_data_name = setting["js_name"]; const setting_name = setting["name"]; if (setting["options"] !== undefined) { // This is a select setting. output += `\ -
-
${setting_name}
-
`; +
+
${setting_name}
+
`; onEach(setting["options"], option => { const checked = option === setting["default"] ? " checked" : ""; const full = `${js_data_name}-${option.replace(/ /g,"-")}`; output += `\ -`; + `; }); - output += "
"; + output += `\ +
+
`; } else { // This is a checkbox toggle. const checked = setting["default"] === true ? " checked" : ""; output += `\ -`; +
\ + \ +
`; } - output += "
"; } return output; } diff --git a/tests/rustdoc-gui/mobile.goml b/tests/rustdoc-gui/mobile.goml index 895864d89445f..3e444cbd6dc99 100644 --- a/tests/rustdoc-gui/mobile.goml +++ b/tests/rustdoc-gui/mobile.goml @@ -28,7 +28,7 @@ goto: "file://" + |DOC_PATH| + "/settings.html" size: (400, 600) // Ignored for now https://github.com/rust-lang/rust/issues/93784. // compare-elements-position-near-false: ( -// "#preferred-light-theme .setting-name", -// "#preferred-light-theme .choice", +// "#preferred-light-theme .setting-radio-name", +// "#preferred-light-theme .setting-radio", // {"y": 16}, // ) diff --git a/tests/rustdoc-gui/settings.goml b/tests/rustdoc-gui/settings.goml index 419cc5ebac35d..a841728857808 100644 --- a/tests/rustdoc-gui/settings.goml +++ b/tests/rustdoc-gui/settings.goml @@ -43,12 +43,12 @@ wait-for: "#settings" // We check that the "Use system theme" is disabled. assert-property: ("#theme-system-preference", {"checked": "false"}) // Meaning that only the "theme" menu is showing up. -assert: ".setting-line:not(.hidden) #theme" -assert: ".setting-line.hidden #preferred-dark-theme" -assert: ".setting-line.hidden #preferred-light-theme" +assert: "#theme.setting-line:not(.hidden)" +assert: "#preferred-dark-theme.setting-line.hidden" +assert: "#preferred-light-theme.setting-line.hidden" // We check that the correct theme is selected. -assert-property: ("#theme .choices #theme-dark", {"checked": "true"}) +assert-property: ("#theme .setting-radio-choices #theme-dark", {"checked": "true"}) // Some style checks... move-cursor-to: "#settings-menu > a" @@ -109,31 +109,31 @@ assert-css: ( "box-shadow": "rgb(33, 150, 243) 0px 0px 1px 1px", }, ) -// Now we check the setting-name for radio buttons is on a different line than the label. +// Now we check the setting-radio-name is on a different line than the label. compare-elements-position-near: ( - "#theme .setting-name", - "#theme .choices", + "#theme .setting-radio-name", + "#theme .setting-radio-choices", {"x": 1} ) compare-elements-position-near-false: ( - "#theme .setting-name", - "#theme .choices", + "#theme .setting-radio-name", + "#theme .setting-radio-choices", {"y": 1} ) // Now we check that the label positions are all on the same line. compare-elements-position-near: ( - "#theme .choices #theme-light", - "#theme .choices #theme-dark", + "#theme .setting-radio-choices #theme-light", + "#theme .setting-radio-choices #theme-dark", {"y": 1} ) compare-elements-position-near: ( - "#theme .choices #theme-dark", - "#theme .choices #theme-ayu", + "#theme .setting-radio-choices #theme-dark", + "#theme .setting-radio-choices #theme-ayu", {"y": 1} ) compare-elements-position-near: ( - "#theme .choices #theme-ayu", - "#theme .choices #theme-system-preference", + "#theme .setting-radio-choices #theme-ayu", + "#theme .setting-radio-choices #theme-system-preference", {"y": 1} ) @@ -180,17 +180,17 @@ assert-css: ( // We now switch the display. click: "#theme-system-preference" // Wait for the hidden element to show up. -wait-for: ".setting-line:not(.hidden) #preferred-dark-theme" -assert: ".setting-line:not(.hidden) #preferred-light-theme" +wait-for: "#preferred-dark-theme.setting-line:not(.hidden)" +assert: "#preferred-light-theme.setting-line:not(.hidden)" // We check their text as well. -assert-text: ("#preferred-dark-theme .setting-name", "Preferred dark theme") -assert-text: ("#preferred-light-theme .setting-name", "Preferred light theme") +assert-text: ("#preferred-dark-theme .setting-radio-name", "Preferred dark theme") +assert-text: ("#preferred-light-theme .setting-radio-name", "Preferred light theme") // We now check that clicking on the toggles' text is like clicking on the checkbox. // To test it, we use the "Disable keyboard shortcuts". local-storage: {"rustdoc-disable-shortcuts": "false"} -click: ".setting-line:last-child .settings-toggle .label" +click: ".setting-line:last-child .setting-check span" assert-local-storage: {"rustdoc-disable-shortcuts": "true"} // Make sure that "Disable keyboard shortcuts" actually took effect. @@ -200,7 +200,7 @@ assert-false: "#help-button .popover" wait-for-css: ("#settings-menu .popover", {"display": "block"}) // Now turn keyboard shortcuts back on, and see if they work. -click: ".setting-line:last-child .settings-toggle .label" +click: ".setting-line:last-child .setting-check span" assert-local-storage: {"rustdoc-disable-shortcuts": "false"} press-key: "Escape" press-key: "?" diff --git a/tests/rustdoc-gui/theme-change.goml b/tests/rustdoc-gui/theme-change.goml index cc47f1f450c5a..31c9d99aa8324 100644 --- a/tests/rustdoc-gui/theme-change.goml +++ b/tests/rustdoc-gui/theme-change.goml @@ -43,7 +43,7 @@ assert-local-storage: { "rustdoc-theme": "ayu" } assert-local-storage-false: { "rustdoc-use-system-theme": "true" } click: "#theme-system-preference" -wait-for: ".setting-line:not(.hidden) #preferred-light-theme" +wait-for: "#preferred-light-theme.setting-line:not(.hidden)" assert-local-storage: { "rustdoc-use-system-theme": "true" } // We click on both preferred light and dark themes to be sure that there is a change. click: "#preferred-light-theme-dark" @@ -52,16 +52,16 @@ wait-for-css: ("body", { "background-color": |background_dark| }) reload: // Ensure that the "preferred themes" are still displayed. -wait-for: ".setting-line:not(.hidden) #preferred-light-theme" +wait-for: "#preferred-light-theme.setting-line:not(.hidden)" click: "#theme-light" wait-for-css: ("body", { "background-color": |background_light| }) assert-local-storage: { "rustdoc-theme": "light" } // Ensure it's now hidden again -wait-for: ".setting-line.hidden #preferred-light-theme" +wait-for: "#preferred-light-theme.setting-line.hidden" // And ensure the theme was rightly set. wait-for-css: ("body", { "background-color": |background_light| }) assert-local-storage: { "rustdoc-theme": "light" } reload: wait-for: "#settings" -assert: ".setting-line.hidden #preferred-light-theme" +assert: "#preferred-light-theme.setting-line.hidden" From 1c41b4d5aced0f7d9f692efde53e896a234c7f48 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 23 Jan 2023 10:46:40 -0700 Subject: [PATCH 303/500] rustdoc: remove dead settings JS for obsolete select-wrapper --- src/librustdoc/html/static/js/settings.js | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/librustdoc/html/static/js/settings.js b/src/librustdoc/html/static/js/settings.js index fef856d5e2c2a..a841b4b63bae8 100644 --- a/src/librustdoc/html/static/js/settings.js +++ b/src/librustdoc/html/static/js/settings.js @@ -80,17 +80,6 @@ toggle.onkeyup = handleKey; toggle.onkeyrelease = handleKey; }); - onEachLazy(settingsElement.getElementsByClassName("select-wrapper"), elem => { - const select = elem.getElementsByTagName("select")[0]; - const settingId = select.id; - const settingValue = getSettingValue(settingId); - if (settingValue !== null) { - select.value = settingValue; - } - select.onchange = function() { - changeSetting(this.id, this.value); - }; - }); onEachLazy(settingsElement.querySelectorAll("input[type=\"radio\"]"), elem => { const settingId = elem.name; let settingValue = getSettingValue(settingId); From 72117ab2c7c32805e963bbf5f0d1bdc7cd72274c Mon Sep 17 00:00:00 2001 From: clubby789 Date: Thu, 19 Jan 2023 21:11:17 +0000 Subject: [PATCH 304/500] Print PID holding bootstrap build lock on Linux --- src/bootstrap/bin/main.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/src/bootstrap/bin/main.rs b/src/bootstrap/bin/main.rs index be69f819c6428..3856bb64fb310 100644 --- a/src/bootstrap/bin/main.rs +++ b/src/bootstrap/bin/main.rs @@ -16,12 +16,17 @@ fn main() { let mut build_lock; let _build_lock_guard; if cfg!(any(unix, windows)) { - build_lock = fd_lock::RwLock::new(t!(std::fs::File::create(config.out.join("lock")))); + let path = config.out.join("lock"); + build_lock = fd_lock::RwLock::new(t!(std::fs::File::create(&path))); _build_lock_guard = match build_lock.try_write() { Ok(lock) => lock, err => { - println!("warning: build directory locked, waiting for lock"); drop(err); + if let Some(pid) = get_lock_owner(&path) { + println!("warning: build directory locked by process {pid}, waiting for lock"); + } else { + println!("warning: build directory locked, waiting for lock"); + } t!(build_lock.write()) } }; @@ -98,3 +103,30 @@ fn check_version(config: &Config) -> Option { Some(msg) } + +/// Get the PID of the process which took the write lock by +/// parsing `/proc/locks`. +#[cfg(target_os = "linux")] +fn get_lock_owner(f: &std::path::Path) -> Option { + use std::fs::File; + use std::io::{BufRead, BufReader}; + use std::os::unix::fs::MetadataExt; + + let lock_inode = std::fs::metadata(f).ok()?.ino(); + let lockfile = File::open("/proc/locks").ok()?; + BufReader::new(lockfile).lines().find_map(|line| { + // pid--vvvvvv vvvvvvv--- inode + // 21: FLOCK ADVISORY WRITE 359238 08:02:3719774 0 EOF + let line = line.ok()?; + let parts = line.split_whitespace().collect::>(); + let (pid, inode) = (parts[4].parse::().ok()?, &parts[5]); + let inode = inode.rsplit_once(':')?.1.parse::().ok()?; + if inode == lock_inode { Some(pid) } else { None } + }) +} + +#[cfg(not(target_os = "linux"))] +fn get_lock_owner(_: &std::path::Path) -> Option { + // FIXME: Implement on other OS's + None +} From 360db516ccf358bd4b35c483ae44634a74c66c0b Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Tue, 20 Dec 2022 00:51:17 +0000 Subject: [PATCH 305/500] Create stable metric to measure long computation in Const Eval This patch adds a `MirPass` that tracks the number of back-edges and function calls in the CFG, adds a new MIR instruction to increment a counter every time they are encountered during Const Eval, and emit a warning if a configured limit is breached. --- compiler/rustc_borrowck/src/dataflow.rs | 1 + compiler/rustc_borrowck/src/invalidation.rs | 3 +- compiler/rustc_borrowck/src/lib.rs | 3 +- compiler/rustc_borrowck/src/type_check/mod.rs | 1 + .../rustc_codegen_ssa/src/mir/statement.rs | 1 + .../src/const_eval/eval_queries.rs | 3 + .../src/const_eval/machine.rs | 1 + .../src/interpret/eval_context.rs | 5 + .../rustc_const_eval/src/interpret/place.rs | 11 +++ .../rustc_const_eval/src/interpret/step.rs | 5 + .../src/transform/check_consts/check.rs | 1 + .../src/transform/validate.rs | 1 + compiler/rustc_middle/src/mir/mod.rs | 1 + compiler/rustc_middle/src/mir/query.rs | 8 +- compiler/rustc_middle/src/mir/spanview.rs | 1 + compiler/rustc_middle/src/mir/syntax.rs | 7 +- compiler/rustc_middle/src/mir/visit.rs | 1 + .../rustc_mir_dataflow/src/impls/liveness.rs | 1 + .../src/impls/storage_liveness.rs | 1 + .../src/move_paths/builder.rs | 1 + .../rustc_mir_dataflow/src/value_analysis.rs | 3 +- .../rustc_mir_transform/src/check_unsafety.rs | 1 + .../rustc_mir_transform/src/coverage/spans.rs | 2 + .../rustc_mir_transform/src/ctfe_limit.rs | 92 +++++++++++++++++++ .../src/dead_store_elimination.rs | 1 + compiler/rustc_mir_transform/src/dest_prop.rs | 1 + compiler/rustc_mir_transform/src/generator.rs | 1 + compiler/rustc_mir_transform/src/lib.rs | 11 ++- .../src/remove_noop_landing_pads.rs | 1 + .../src/separate_const_switch.rs | 2 + compiler/rustc_mir_transform/src/simplify.rs | 2 +- .../stable-metric/ctfe-labelled-loop.rs | 25 +++++ .../stable-metric/ctfe-labelled-loop.stderr | 4 + .../stable-metric/ctfe-recursion.rs | 15 +++ .../stable-metric/ctfe-recursion.stderr | 4 + .../stable-metric/ctfe-simple-loop.rs | 16 ++++ .../stable-metric/ctfe-simple-loop.stderr | 4 + 37 files changed, 233 insertions(+), 9 deletions(-) create mode 100644 compiler/rustc_mir_transform/src/ctfe_limit.rs create mode 100644 src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs create mode 100644 src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr create mode 100644 src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.rs create mode 100644 src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr create mode 100644 src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs create mode 100644 src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr diff --git a/compiler/rustc_borrowck/src/dataflow.rs b/compiler/rustc_borrowck/src/dataflow.rs index 8c4885770ad37..2821677c5371f 100644 --- a/compiler/rustc_borrowck/src/dataflow.rs +++ b/compiler/rustc_borrowck/src/dataflow.rs @@ -393,6 +393,7 @@ impl<'tcx> rustc_mir_dataflow::GenKillAnalysis<'tcx> for Borrows<'_, 'tcx> { | mir::StatementKind::AscribeUserType(..) | mir::StatementKind::Coverage(..) | mir::StatementKind::Intrinsic(..) + | mir::StatementKind::ConstEvalCounter | mir::StatementKind::Nop => {} } } diff --git a/compiler/rustc_borrowck/src/invalidation.rs b/compiler/rustc_borrowck/src/invalidation.rs index 6fd9290058c36..6217676d5c150 100644 --- a/compiler/rustc_borrowck/src/invalidation.rs +++ b/compiler/rustc_borrowck/src/invalidation.rs @@ -91,7 +91,8 @@ impl<'cx, 'tcx> Visitor<'tcx> for InvalidationGenerator<'cx, 'tcx> { LocalMutationIsAllowed::Yes, ); } - StatementKind::Nop + StatementKind::ConstEvalCounter + | StatementKind::Nop | StatementKind::Retag { .. } | StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => { diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 73ea7314b75cc..8f8fae2c630b5 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -620,7 +620,8 @@ impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtx flow_state, ); } - StatementKind::Nop + StatementKind::ConstEvalCounter + | StatementKind::Nop | StatementKind::Retag { .. } | StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => { diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 81bd4c2a783e9..06087b0c579d8 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -1258,6 +1258,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { | StatementKind::StorageDead(..) | StatementKind::Retag { .. } | StatementKind::Coverage(..) + | StatementKind::ConstEvalCounter | StatementKind::Nop => {} StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => { bug!("Statement not allowed in this MIR phase") diff --git a/compiler/rustc_codegen_ssa/src/mir/statement.rs b/compiler/rustc_codegen_ssa/src/mir/statement.rs index 19452c8cdc805..60fbceb344d88 100644 --- a/compiler/rustc_codegen_ssa/src/mir/statement.rs +++ b/compiler/rustc_codegen_ssa/src/mir/statement.rs @@ -91,6 +91,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { mir::StatementKind::FakeRead(..) | mir::StatementKind::Retag { .. } | mir::StatementKind::AscribeUserType(..) + | mir::StatementKind::ConstEvalCounter | mir::StatementKind::Nop => {} } } diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index 18e01567ca35e..041e9d413575e 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -22,6 +22,8 @@ use crate::interpret::{ RefTracking, StackPopCleanup, }; +use tracing::info; + const NOTE_ON_UNDEFINED_BEHAVIOR_ERROR: &str = "The rules on what exactly is undefined behavior aren't clear, \ so this check might be overzealous. Please open an issue on the rustc \ repository if you believe it should not be considered undefined behavior."; @@ -33,6 +35,7 @@ fn eval_body_using_ecx<'mir, 'tcx>( body: &'mir mir::Body<'tcx>, ) -> InterpResult<'tcx, MPlaceTy<'tcx>> { debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env); + info!("HERE body is {:#?}", body); let tcx = *ecx.tcx; assert!( cid.promoted.is_some() diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 4709514c82e85..befc71ce6a0dd 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -369,6 +369,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, } } + #[instrument(skip(ecx), ret)] fn load_mir( ecx: &InterpCx<'mir, 'tcx, Self>, instance: ty::InstanceDef<'tcx>, diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index d13fed7a9c263..cc97564e8fc28 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -46,6 +46,9 @@ pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> { /// The recursion limit (cached from `tcx.recursion_limit(())`) pub recursion_limit: Limit, + + pub const_eval_limit: u32, + pub const_eval_counter: u32, } // The Phantomdata exists to prevent this type from being `Send`. If it were sent across a thread @@ -408,6 +411,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { param_env, memory: Memory::new(), recursion_limit: tcx.recursion_limit(), + const_eval_limit: 20, + const_eval_counter: 0, } } diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index 274af61ee7c1d..271a3a74fe319 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -293,6 +293,17 @@ where Prov: Provenance + 'static, M: Machine<'mir, 'tcx, Provenance = Prov>, { + pub fn increment_const_eval_counter(&mut self) { + self.const_eval_counter = self.const_eval_counter + 1; + if self.const_eval_counter == self.const_eval_limit { + let mut warn = self.tcx.sess.struct_warn(format!( + "Const eval counter limit ({}) has been crossed", + self.const_eval_limit + )); + warn.emit(); + } + } + /// Take a value, which represents a (thin or wide) reference, and make it a place. /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`. /// diff --git a/compiler/rustc_const_eval/src/interpret/step.rs b/compiler/rustc_const_eval/src/interpret/step.rs index fad4cb06cd6fe..0f0eb5aadd71d 100644 --- a/compiler/rustc_const_eval/src/interpret/step.rs +++ b/compiler/rustc_const_eval/src/interpret/step.rs @@ -129,6 +129,11 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // FIXME(#73156): Handle source code coverage in const eval Coverage(..) => {} + // FIXME(bryangarza): Update this to do some logic!!! + ConstEvalCounter => { + self.increment_const_eval_counter(); + } + // Defined to do nothing. These are added by optimization passes, to avoid changing the // size of MIR constantly. Nop => {} diff --git a/compiler/rustc_const_eval/src/transform/check_consts/check.rs b/compiler/rustc_const_eval/src/transform/check_consts/check.rs index 79f1737e32b21..16b504dd9d491 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/check.rs @@ -693,6 +693,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { | StatementKind::AscribeUserType(..) | StatementKind::Coverage(..) | StatementKind::Intrinsic(..) + | StatementKind::ConstEvalCounter | StatementKind::Nop => {} } } diff --git a/compiler/rustc_const_eval/src/transform/validate.rs b/compiler/rustc_const_eval/src/transform/validate.rs index dd168a9ac3cd3..4ad699c0395e3 100644 --- a/compiler/rustc_const_eval/src/transform/validate.rs +++ b/compiler/rustc_const_eval/src/transform/validate.rs @@ -766,6 +766,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { StatementKind::StorageLive(..) | StatementKind::StorageDead(..) | StatementKind::Coverage(_) + | StatementKind::ConstEvalCounter | StatementKind::Nop => {} } diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 4da893e4c0716..dae7e84e415f0 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -1461,6 +1461,7 @@ impl Debug for Statement<'_> { } Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind), Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"), + ConstEvalCounter => write!(fmt, "ConstEvalCounter"), Nop => write!(fmt, "nop"), } } diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index a8a4532223c2d..c281fe00591ae 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -441,10 +441,14 @@ impl<'tcx> TyCtxt<'tcx> { #[inline] pub fn mir_for_ctfe_opt_const_arg(self, def: ty::WithOptConstParam) -> &'tcx Body<'tcx> { - if let Some((did, param_did)) = def.as_const_arg() { + let res = if let Some((did, param_did)) = def.as_const_arg() { + info!("calling mir_for_ctfe_of_const_arg for DedId {did:?}"); self.mir_for_ctfe_of_const_arg((did, param_did)) } else { + info!("calling mir_for_ctfe for DefId {:?}", def.did); self.mir_for_ctfe(def.did) - } + }; + //info!("RES OF CALLING MIR_FOR_CTFE_OPT_CONST_ARG: {:#?}", res); + res } } diff --git a/compiler/rustc_middle/src/mir/spanview.rs b/compiler/rustc_middle/src/mir/spanview.rs index 887ee57157540..7efe1fde09343 100644 --- a/compiler/rustc_middle/src/mir/spanview.rs +++ b/compiler/rustc_middle/src/mir/spanview.rs @@ -250,6 +250,7 @@ pub fn statement_kind_name(statement: &Statement<'_>) -> &'static str { AscribeUserType(..) => "AscribeUserType", Coverage(..) => "Coverage", Intrinsic(..) => "Intrinsic", + ConstEvalCounter => "ConstEvalCounter", Nop => "Nop", } } diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 52c2b10cbbea9..faf903a594901 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -286,7 +286,10 @@ pub enum StatementKind<'tcx> { /// This is permitted for both generators and ADTs. This does not necessarily write to the /// entire place; instead, it writes to the minimum set of bytes as required by the layout for /// the type. - SetDiscriminant { place: Box>, variant_index: VariantIdx }, + SetDiscriminant { + place: Box>, + variant_index: VariantIdx, + }, /// Deinitializes the place. /// @@ -355,6 +358,8 @@ pub enum StatementKind<'tcx> { /// This avoids adding a new block and a terminator for simple intrinsics. Intrinsic(Box>), + ConstEvalCounter, + /// No-op. Useful for deleting instructions without affecting statement indices. Nop, } diff --git a/compiler/rustc_middle/src/mir/visit.rs b/compiler/rustc_middle/src/mir/visit.rs index 1a264d2d5af9a..3ddac5e11fbc5 100644 --- a/compiler/rustc_middle/src/mir/visit.rs +++ b/compiler/rustc_middle/src/mir/visit.rs @@ -427,6 +427,7 @@ macro_rules! make_mir_visitor { } } } + StatementKind::ConstEvalCounter => {} StatementKind::Nop => {} } } diff --git a/compiler/rustc_mir_dataflow/src/impls/liveness.rs b/compiler/rustc_mir_dataflow/src/impls/liveness.rs index 923dc16c11b07..2890fa32cc915 100644 --- a/compiler/rustc_mir_dataflow/src/impls/liveness.rs +++ b/compiler/rustc_mir_dataflow/src/impls/liveness.rs @@ -271,6 +271,7 @@ impl<'a, 'tcx> Analysis<'tcx> for MaybeTransitiveLiveLocals<'a> { | StatementKind::AscribeUserType(..) | StatementKind::Coverage(..) | StatementKind::Intrinsic(..) + | StatementKind::ConstEvalCounter | StatementKind::Nop => None, }; if let Some(destination) = destination { diff --git a/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs b/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs index 8d379b90a86db..fcf0ce9d82118 100644 --- a/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs +++ b/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs @@ -141,6 +141,7 @@ impl<'mir, 'tcx> crate::GenKillAnalysis<'tcx> for MaybeRequiresStorage<'mir, 'tc StatementKind::AscribeUserType(..) | StatementKind::Coverage(..) | StatementKind::FakeRead(..) + | StatementKind::ConstEvalCounter | StatementKind::Nop | StatementKind::Retag(..) | StatementKind::Intrinsic(..) diff --git a/compiler/rustc_mir_dataflow/src/move_paths/builder.rs b/compiler/rustc_mir_dataflow/src/move_paths/builder.rs index f46fd118bde5d..0195693a7cb0e 100644 --- a/compiler/rustc_mir_dataflow/src/move_paths/builder.rs +++ b/compiler/rustc_mir_dataflow/src/move_paths/builder.rs @@ -331,6 +331,7 @@ impl<'b, 'a, 'tcx> Gatherer<'b, 'a, 'tcx> { | StatementKind::AscribeUserType(..) | StatementKind::Coverage(..) | StatementKind::Intrinsic(..) + | StatementKind::ConstEvalCounter | StatementKind::Nop => {} } } diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index 0522c657939f5..6bdbda909d7bd 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -84,7 +84,8 @@ pub trait ValueAnalysis<'tcx> { StatementKind::Retag(..) => { // We don't track references. } - StatementKind::Nop + StatementKind::ConstEvalCounter + | StatementKind::Nop | StatementKind::FakeRead(..) | StatementKind::Coverage(..) | StatementKind::AscribeUserType(..) => (), diff --git a/compiler/rustc_mir_transform/src/check_unsafety.rs b/compiler/rustc_mir_transform/src/check_unsafety.rs index adf6ae4c7270f..837233953e7ad 100644 --- a/compiler/rustc_mir_transform/src/check_unsafety.rs +++ b/compiler/rustc_mir_transform/src/check_unsafety.rs @@ -104,6 +104,7 @@ impl<'tcx> Visitor<'tcx> for UnsafetyChecker<'_, 'tcx> { | StatementKind::AscribeUserType(..) | StatementKind::Coverage(..) | StatementKind::Intrinsic(..) + | StatementKind::ConstEvalCounter | StatementKind::Nop => { // safe (at least as emitted during MIR construction) } diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index 31d5541a31b6b..f973c1ed28f4a 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -802,6 +802,8 @@ pub(super) fn filtered_statement_span(statement: &Statement<'_>) -> Option | StatementKind::StorageDead(_) // Coverage should not be encountered, but don't inject coverage coverage | StatementKind::Coverage(_) + // Ignore `ConstEvalCounter`s + | StatementKind::ConstEvalCounter // Ignore `Nop`s | StatementKind::Nop => None, diff --git a/compiler/rustc_mir_transform/src/ctfe_limit.rs b/compiler/rustc_mir_transform/src/ctfe_limit.rs new file mode 100644 index 0000000000000..dc54b983c0e2c --- /dev/null +++ b/compiler/rustc_mir_transform/src/ctfe_limit.rs @@ -0,0 +1,92 @@ +use crate::MirPass; + +use rustc_middle::mir::{BasicBlock, Body, Statement, StatementKind, TerminatorKind}; +use rustc_middle::ty::TyCtxt; + +use tracing::{info, instrument}; + +pub struct CtfeLimit; + +impl<'tcx> MirPass<'tcx> for CtfeLimit { + #[instrument(skip(self, _tcx, body))] + fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { + let doms = body.basic_blocks.dominators(); + //info!("Got body with {} basic blocks: {:#?}", body.basic_blocks.len(), body.basic_blocks); + //info!("With doms: {doms:?}"); + + /* + for (index, basic_block) in body.basic_blocks.iter().enumerate() { + info!("bb{index}: {basic_block:#?}") + }*/ + for (index, basic_block) in body.basic_blocks.iter().enumerate() { + info!( + "bb{index} -> successors = {:?}", + basic_block.terminator().successors().collect::>() + ); + } + for (index, basic_block) in body.basic_blocks.iter().enumerate() { + info!("bb{index} -> unwind = {:?}", basic_block.terminator().unwind()) + } + + let mut dominators = Vec::new(); + for idom in 0..body.basic_blocks.len() { + let mut nodes = Vec::new(); + for inode in 0..body.basic_blocks.len() { + let dom = BasicBlock::from_usize(idom); + let node = BasicBlock::from_usize(inode); + if doms.is_reachable(dom) + && doms.is_reachable(node) + && doms.is_dominated_by(node, dom) + { + //info!("{idom} dominates {inode}"); + nodes.push(true); + } else { + nodes.push(false); + } + } + dominators.push(nodes); + } + /* + for idom in 0..body.basic_blocks.len() { + print!("{idom} | dom | "); + for inode in 0..body.basic_blocks.len() { + if dominators[idom][inode] { + print!("{inode} | "); + } else { + print!(" | "); + } + } + print!("\n"); + } + */ + + for (index, basic_block) in body.basic_blocks_mut().iter_mut().enumerate() { + // info!("bb{index}: {basic_block:#?}"); + //info!("bb{index} -> successors = {:?}", basic_block.terminator().successors().collect::>()); + let is_back_edge_or_fn_call = 'label: { + match basic_block.terminator().kind { + TerminatorKind::Call { .. } => { + break 'label true; + } + _ => (), + } + for successor in basic_block.terminator().successors() { + let s_index = successor.as_usize(); + if dominators[s_index][index] { + info!("{s_index} to {index} is a loop"); + break 'label true; + } + } + false + }; + if is_back_edge_or_fn_call { + basic_block.statements.push(Statement { + source_info: basic_block.terminator().source_info, + kind: StatementKind::ConstEvalCounter, + }); + info!("New basic block statements vector: {:?}", basic_block.statements); + } + } + info!("With doms: {doms:?}"); + } +} diff --git a/compiler/rustc_mir_transform/src/dead_store_elimination.rs b/compiler/rustc_mir_transform/src/dead_store_elimination.rs index 09546330cec92..9dbfb089dc665 100644 --- a/compiler/rustc_mir_transform/src/dead_store_elimination.rs +++ b/compiler/rustc_mir_transform/src/dead_store_elimination.rs @@ -53,6 +53,7 @@ pub fn eliminate<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, borrowed: &BitS | StatementKind::StorageDead(_) | StatementKind::Coverage(_) | StatementKind::Intrinsic(_) + | StatementKind::ConstEvalCounter | StatementKind::Nop => (), StatementKind::FakeRead(_) | StatementKind::AscribeUserType(_, _) => { diff --git a/compiler/rustc_mir_transform/src/dest_prop.rs b/compiler/rustc_mir_transform/src/dest_prop.rs index 08e296a837127..20ffb0ab33404 100644 --- a/compiler/rustc_mir_transform/src/dest_prop.rs +++ b/compiler/rustc_mir_transform/src/dest_prop.rs @@ -577,6 +577,7 @@ impl WriteInfo { self.add_place(**place); } StatementKind::Intrinsic(_) + | StatementKind::ConstEvalCounter | StatementKind::Nop | StatementKind::Coverage(_) | StatementKind::StorageLive(_) diff --git a/compiler/rustc_mir_transform/src/generator.rs b/compiler/rustc_mir_transform/src/generator.rs index 39c61a34afcbd..0df732aa22bad 100644 --- a/compiler/rustc_mir_transform/src/generator.rs +++ b/compiler/rustc_mir_transform/src/generator.rs @@ -1583,6 +1583,7 @@ impl<'tcx> Visitor<'tcx> for EnsureGeneratorFieldAssignmentsNeverAlias<'_> { | StatementKind::AscribeUserType(..) | StatementKind::Coverage(..) | StatementKind::Intrinsic(..) + | StatementKind::ConstEvalCounter | StatementKind::Nop => {} } } diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 20b7fdcfe6d4d..e5c8127bea140 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -55,6 +55,7 @@ mod const_goto; mod const_prop; mod const_prop_lint; mod coverage; +mod ctfe_limit; mod dataflow_const_prop; mod dead_store_elimination; mod deaggregator; @@ -349,11 +350,14 @@ fn mir_promoted( /// Compute the MIR that is used during CTFE (and thus has no optimizations run on it) fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: DefId) -> &Body<'_> { let did = def_id.expect_local(); - if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) { + let body = if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) { tcx.mir_for_ctfe_of_const_arg(def) } else { tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did))) - } + }; + //info!("MIR_FOR_CTFE (DefId = {def_id:?}) body res: {:#?}", body); + info!("MIR_FOR_CTFE (DefId = {def_id:?})"); + body } /// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter. @@ -447,6 +451,7 @@ fn mir_drops_elaborated_and_const_checked( run_analysis_to_runtime_passes(tcx, &mut body); + //info!("MIR after runtime passes: {:#?}", body); tcx.alloc_steal_mir(body) } @@ -517,6 +522,7 @@ fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // CTFE support for aggregates. &deaggregator::Deaggregator, &Lint(const_prop_lint::ConstProp), + &ctfe_limit::CtfeLimit, ]; pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial))); } @@ -617,6 +623,7 @@ fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> { let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst); debug!("body: {:#?}", body); run_optimization_passes(tcx, &mut body); + //info!("body after OPTIMIZATION: {:#?}", body); debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR"); diff --git a/compiler/rustc_mir_transform/src/remove_noop_landing_pads.rs b/compiler/rustc_mir_transform/src/remove_noop_landing_pads.rs index f1bbf2ea7e8ea..e3a03aa08af4b 100644 --- a/compiler/rustc_mir_transform/src/remove_noop_landing_pads.rs +++ b/compiler/rustc_mir_transform/src/remove_noop_landing_pads.rs @@ -35,6 +35,7 @@ impl RemoveNoopLandingPads { | StatementKind::StorageDead(_) | StatementKind::AscribeUserType(..) | StatementKind::Coverage(..) + | StatementKind::ConstEvalCounter | StatementKind::Nop => { // These are all noops in a landing pad } diff --git a/compiler/rustc_mir_transform/src/separate_const_switch.rs b/compiler/rustc_mir_transform/src/separate_const_switch.rs index 2f116aaa95849..a24d2d34d791b 100644 --- a/compiler/rustc_mir_transform/src/separate_const_switch.rs +++ b/compiler/rustc_mir_transform/src/separate_const_switch.rs @@ -250,6 +250,7 @@ fn is_likely_const<'tcx>(mut tracked_place: Place<'tcx>, block: &BasicBlockData< | StatementKind::Coverage(_) | StatementKind::StorageDead(_) | StatementKind::Intrinsic(_) + | StatementKind::ConstEvalCounter | StatementKind::Nop => {} } } @@ -318,6 +319,7 @@ fn find_determining_place<'tcx>( | StatementKind::AscribeUserType(_, _) | StatementKind::Coverage(_) | StatementKind::Intrinsic(_) + | StatementKind::ConstEvalCounter | StatementKind::Nop => {} // If the discriminant is set, it is always set diff --git a/compiler/rustc_mir_transform/src/simplify.rs b/compiler/rustc_mir_transform/src/simplify.rs index 8f6abe7a912fe..7b6fa2baf2f95 100644 --- a/compiler/rustc_mir_transform/src/simplify.rs +++ b/compiler/rustc_mir_transform/src/simplify.rs @@ -517,7 +517,7 @@ impl<'tcx> Visitor<'tcx> for UsedLocals { self.super_statement(statement, location); } - StatementKind::Nop => {} + StatementKind::ConstEvalCounter | StatementKind::Nop => {} StatementKind::StorageLive(_local) | StatementKind::StorageDead(_local) => {} diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs b/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs new file mode 100644 index 0000000000000..71f29ce8731f0 --- /dev/null +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs @@ -0,0 +1,25 @@ +// check-pass +#![feature(const_for)] + +const fn labelled_loop() -> u32 { + let mut n = 0; + 'outer: loop { + 'inner: loop { + n = n + 1; + if n > 5 && n <= 10 { + n = n + 1; + continue 'inner + } + if n > 30 { + break 'outer + } + } + } + n +} + +const X: u32 = labelled_loop(); + +fn main() { + println!("{X}"); +} diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr b/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr new file mode 100644 index 0000000000000..183bed3b75b25 --- /dev/null +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr @@ -0,0 +1,4 @@ +warning: Const eval counter limit (20) has been crossed + +warning: 1 warning emitted + diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.rs b/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.rs new file mode 100644 index 0000000000000..00b4fc258593a --- /dev/null +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.rs @@ -0,0 +1,15 @@ +// check-pass + +const fn recurse(n: u32) -> u32 { + if n == 0 { + n + } else { + recurse(n - 1) + } +} + +const X: u32 = recurse(30); + +fn main() { + println!("{X}"); +} diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr b/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr new file mode 100644 index 0000000000000..183bed3b75b25 --- /dev/null +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr @@ -0,0 +1,4 @@ +warning: Const eval counter limit (20) has been crossed + +warning: 1 warning emitted + diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs b/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs new file mode 100644 index 0000000000000..74dc74734b45e --- /dev/null +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs @@ -0,0 +1,16 @@ +// check-pass +const fn simple_loop(n: u32) -> u32 { + let mut index = 0; + let mut res = 0; + while index < n { + res = res + index; + index = index + 1; + } + res +} + +const X: u32 = simple_loop(30); + +fn main() { + println!("{X}"); +} diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr b/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr new file mode 100644 index 0000000000000..183bed3b75b25 --- /dev/null +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr @@ -0,0 +1,4 @@ +warning: Const eval counter limit (20) has been crossed + +warning: 1 warning emitted + From 026a67377f2b28968d293a92cad3f92e22f76b6d Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Thu, 29 Dec 2022 03:38:34 +0000 Subject: [PATCH 306/500] Clean up CtfeLimit MirPass --- .../rustc_mir_transform/src/ctfe_limit.rs | 105 ++++++------------ .../const-eval/stable-metric/ctfe-fn-call.rs | 33 ++++++ .../stable-metric/ctfe-fn-call.stderr | 4 + 3 files changed, 68 insertions(+), 74 deletions(-) create mode 100644 src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs create mode 100644 src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr diff --git a/compiler/rustc_mir_transform/src/ctfe_limit.rs b/compiler/rustc_mir_transform/src/ctfe_limit.rs index dc54b983c0e2c..f2c99b1943307 100644 --- a/compiler/rustc_mir_transform/src/ctfe_limit.rs +++ b/compiler/rustc_mir_transform/src/ctfe_limit.rs @@ -1,92 +1,49 @@ use crate::MirPass; -use rustc_middle::mir::{BasicBlock, Body, Statement, StatementKind, TerminatorKind}; +use rustc_middle::mir::{BasicBlockData, Body, Statement, StatementKind, TerminatorKind}; use rustc_middle::ty::TyCtxt; -use tracing::{info, instrument}; - pub struct CtfeLimit; impl<'tcx> MirPass<'tcx> for CtfeLimit { #[instrument(skip(self, _tcx, body))] fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let doms = body.basic_blocks.dominators(); - //info!("Got body with {} basic blocks: {:#?}", body.basic_blocks.len(), body.basic_blocks); - //info!("With doms: {doms:?}"); - - /* - for (index, basic_block) in body.basic_blocks.iter().enumerate() { - info!("bb{index}: {basic_block:#?}") - }*/ - for (index, basic_block) in body.basic_blocks.iter().enumerate() { - info!( - "bb{index} -> successors = {:?}", - basic_block.terminator().successors().collect::>() - ); - } - for (index, basic_block) in body.basic_blocks.iter().enumerate() { - info!("bb{index} -> unwind = {:?}", basic_block.terminator().unwind()) - } - - let mut dominators = Vec::new(); - for idom in 0..body.basic_blocks.len() { - let mut nodes = Vec::new(); - for inode in 0..body.basic_blocks.len() { - let dom = BasicBlock::from_usize(idom); - let node = BasicBlock::from_usize(inode); - if doms.is_reachable(dom) + let mut indices = Vec::new(); + for (node, node_data) in body.basic_blocks.iter_enumerated() { + if let TerminatorKind::Call { .. } = node_data.terminator().kind { + indices.push(node); + continue; + } + // Back edges in a CFG indicate loops + for (potential_dom, _) in body.basic_blocks.iter_enumerated() { + if doms.is_reachable(potential_dom) && doms.is_reachable(node) - && doms.is_dominated_by(node, dom) + && doms.is_dominated_by(node, potential_dom) + && node_data + .terminator() + .successors() + .into_iter() + .any(|succ| succ == potential_dom) { - //info!("{idom} dominates {inode}"); - nodes.push(true); - } else { - nodes.push(false); + indices.push(node); + continue; } } - dominators.push(nodes); } - /* - for idom in 0..body.basic_blocks.len() { - print!("{idom} | dom | "); - for inode in 0..body.basic_blocks.len() { - if dominators[idom][inode] { - print!("{inode} | "); - } else { - print!(" | "); - } - } - print!("\n"); - } - */ - - for (index, basic_block) in body.basic_blocks_mut().iter_mut().enumerate() { - // info!("bb{index}: {basic_block:#?}"); - //info!("bb{index} -> successors = {:?}", basic_block.terminator().successors().collect::>()); - let is_back_edge_or_fn_call = 'label: { - match basic_block.terminator().kind { - TerminatorKind::Call { .. } => { - break 'label true; - } - _ => (), - } - for successor in basic_block.terminator().successors() { - let s_index = successor.as_usize(); - if dominators[s_index][index] { - info!("{s_index} to {index} is a loop"); - break 'label true; - } - } - false - }; - if is_back_edge_or_fn_call { - basic_block.statements.push(Statement { - source_info: basic_block.terminator().source_info, - kind: StatementKind::ConstEvalCounter, - }); - info!("New basic block statements vector: {:?}", basic_block.statements); - } + for index in indices { + insert_counter( + body.basic_blocks_mut() + .get_mut(index) + .expect("basic_blocks index {index} should exist"), + ); } - info!("With doms: {doms:?}"); } } + +fn insert_counter(basic_block_data: &mut BasicBlockData<'_>) { + basic_block_data.statements.push(Statement { + source_info: basic_block_data.terminator().source_info, + kind: StatementKind::ConstEvalCounter, + }); +} diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs b/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs new file mode 100644 index 0000000000000..33488bd1d1c55 --- /dev/null +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs @@ -0,0 +1,33 @@ +// check-pass + +const fn foo() {} + +const fn call_foo() -> u32 { + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + foo(); + 0 +} + +const X: u32 = call_foo(); + +fn main() { + println!("{X}"); +} diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr b/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr new file mode 100644 index 0000000000000..183bed3b75b25 --- /dev/null +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr @@ -0,0 +1,4 @@ +warning: Const eval counter limit (20) has been crossed + +warning: 1 warning emitted + From b763f9094fadc06fd65b906d5e8db0a9fd8ec6ba Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Thu, 29 Dec 2022 03:49:48 +0000 Subject: [PATCH 307/500] Remove debugging-related code --- compiler/rustc_const_eval/src/const_eval/eval_queries.rs | 3 --- compiler/rustc_const_eval/src/const_eval/machine.rs | 1 - compiler/rustc_const_eval/src/interpret/step.rs | 1 - compiler/rustc_middle/src/mir/query.rs | 8 ++------ compiler/rustc_mir_transform/src/lib.rs | 9 ++------- 5 files changed, 4 insertions(+), 18 deletions(-) diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index 041e9d413575e..18e01567ca35e 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -22,8 +22,6 @@ use crate::interpret::{ RefTracking, StackPopCleanup, }; -use tracing::info; - const NOTE_ON_UNDEFINED_BEHAVIOR_ERROR: &str = "The rules on what exactly is undefined behavior aren't clear, \ so this check might be overzealous. Please open an issue on the rustc \ repository if you believe it should not be considered undefined behavior."; @@ -35,7 +33,6 @@ fn eval_body_using_ecx<'mir, 'tcx>( body: &'mir mir::Body<'tcx>, ) -> InterpResult<'tcx, MPlaceTy<'tcx>> { debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env); - info!("HERE body is {:#?}", body); let tcx = *ecx.tcx; assert!( cid.promoted.is_some() diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index befc71ce6a0dd..4709514c82e85 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -369,7 +369,6 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, } } - #[instrument(skip(ecx), ret)] fn load_mir( ecx: &InterpCx<'mir, 'tcx, Self>, instance: ty::InstanceDef<'tcx>, diff --git a/compiler/rustc_const_eval/src/interpret/step.rs b/compiler/rustc_const_eval/src/interpret/step.rs index 0f0eb5aadd71d..6c5594bc1b086 100644 --- a/compiler/rustc_const_eval/src/interpret/step.rs +++ b/compiler/rustc_const_eval/src/interpret/step.rs @@ -129,7 +129,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // FIXME(#73156): Handle source code coverage in const eval Coverage(..) => {} - // FIXME(bryangarza): Update this to do some logic!!! ConstEvalCounter => { self.increment_const_eval_counter(); } diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index c281fe00591ae..a8a4532223c2d 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -441,14 +441,10 @@ impl<'tcx> TyCtxt<'tcx> { #[inline] pub fn mir_for_ctfe_opt_const_arg(self, def: ty::WithOptConstParam) -> &'tcx Body<'tcx> { - let res = if let Some((did, param_did)) = def.as_const_arg() { - info!("calling mir_for_ctfe_of_const_arg for DedId {did:?}"); + if let Some((did, param_did)) = def.as_const_arg() { self.mir_for_ctfe_of_const_arg((did, param_did)) } else { - info!("calling mir_for_ctfe for DefId {:?}", def.did); self.mir_for_ctfe(def.did) - }; - //info!("RES OF CALLING MIR_FOR_CTFE_OPT_CONST_ARG: {:#?}", res); - res + } } } diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index e5c8127bea140..9a786d0c8d62a 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -350,14 +350,11 @@ fn mir_promoted( /// Compute the MIR that is used during CTFE (and thus has no optimizations run on it) fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: DefId) -> &Body<'_> { let did = def_id.expect_local(); - let body = if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) { + if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) { tcx.mir_for_ctfe_of_const_arg(def) } else { tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did))) - }; - //info!("MIR_FOR_CTFE (DefId = {def_id:?}) body res: {:#?}", body); - info!("MIR_FOR_CTFE (DefId = {def_id:?})"); - body + } } /// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter. @@ -451,7 +448,6 @@ fn mir_drops_elaborated_and_const_checked( run_analysis_to_runtime_passes(tcx, &mut body); - //info!("MIR after runtime passes: {:#?}", body); tcx.alloc_steal_mir(body) } @@ -623,7 +619,6 @@ fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> { let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst); debug!("body: {:#?}", body); run_optimization_passes(tcx, &mut body); - //info!("body after OPTIMIZATION: {:#?}", body); debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR"); From 009beb00bcbaf5367937e50196d7d40d5d112068 Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Thu, 29 Dec 2022 04:43:13 +0000 Subject: [PATCH 308/500] Change code to use map insead of for-loop --- .../rustc_mir_transform/src/ctfe_limit.rs | 48 ++++++++++--------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/compiler/rustc_mir_transform/src/ctfe_limit.rs b/compiler/rustc_mir_transform/src/ctfe_limit.rs index f2c99b1943307..462be8afaafeb 100644 --- a/compiler/rustc_mir_transform/src/ctfe_limit.rs +++ b/compiler/rustc_mir_transform/src/ctfe_limit.rs @@ -1,6 +1,8 @@ use crate::MirPass; -use rustc_middle::mir::{BasicBlockData, Body, Statement, StatementKind, TerminatorKind}; +use rustc_middle::mir::{ + BasicBlock, BasicBlockData, Body, Statement, StatementKind, TerminatorKind, +}; use rustc_middle::ty::TyCtxt; pub struct CtfeLimit; @@ -9,28 +11,28 @@ impl<'tcx> MirPass<'tcx> for CtfeLimit { #[instrument(skip(self, _tcx, body))] fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let doms = body.basic_blocks.dominators(); - let mut indices = Vec::new(); - for (node, node_data) in body.basic_blocks.iter_enumerated() { - if let TerminatorKind::Call { .. } = node_data.terminator().kind { - indices.push(node); - continue; - } - // Back edges in a CFG indicate loops - for (potential_dom, _) in body.basic_blocks.iter_enumerated() { - if doms.is_reachable(potential_dom) - && doms.is_reachable(node) - && doms.is_dominated_by(node, potential_dom) - && node_data - .terminator() - .successors() - .into_iter() - .any(|succ| succ == potential_dom) - { - indices.push(node); - continue; - } - } - } + let indices: Vec = + body.basic_blocks + .iter_enumerated() + .filter_map(|(node, node_data)| { + if matches!(node_data.terminator().kind, TerminatorKind::Call { .. }) || + // Back edges in a CFG indicate loops + body.basic_blocks.iter_enumerated().any(|(potential_dom, _)| { + doms.is_reachable(potential_dom) + && doms.is_reachable(node) + && doms.is_dominated_by(node, potential_dom) + && node_data + .terminator() + .successors() + .into_iter() + .any(|succ| succ == potential_dom) + }) { + Some(node) + } else { + None + } + }) + .collect(); for index in indices { insert_counter( body.basic_blocks_mut() From 8d99b0fc8d732bcef84127bf431517922878461f Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Thu, 29 Dec 2022 19:37:33 +0000 Subject: [PATCH 309/500] Abstract out has_back_edge fn --- .../rustc_mir_transform/src/ctfe_limit.rs | 51 ++++++++++--------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/compiler/rustc_mir_transform/src/ctfe_limit.rs b/compiler/rustc_mir_transform/src/ctfe_limit.rs index 462be8afaafeb..1ff8b792dca36 100644 --- a/compiler/rustc_mir_transform/src/ctfe_limit.rs +++ b/compiler/rustc_mir_transform/src/ctfe_limit.rs @@ -1,7 +1,7 @@ use crate::MirPass; use rustc_middle::mir::{ - BasicBlock, BasicBlockData, Body, Statement, StatementKind, TerminatorKind, + BasicBlock, BasicBlockData, BasicBlocks, Body, Statement, StatementKind, TerminatorKind, }; use rustc_middle::ty::TyCtxt; @@ -10,29 +10,20 @@ pub struct CtfeLimit; impl<'tcx> MirPass<'tcx> for CtfeLimit { #[instrument(skip(self, _tcx, body))] fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { - let doms = body.basic_blocks.dominators(); - let indices: Vec = - body.basic_blocks - .iter_enumerated() - .filter_map(|(node, node_data)| { - if matches!(node_data.terminator().kind, TerminatorKind::Call { .. }) || + let indices: Vec = body + .basic_blocks + .iter_enumerated() + .filter_map(|(node, node_data)| { + if matches!(node_data.terminator().kind, TerminatorKind::Call { .. }) // Back edges in a CFG indicate loops - body.basic_blocks.iter_enumerated().any(|(potential_dom, _)| { - doms.is_reachable(potential_dom) - && doms.is_reachable(node) - && doms.is_dominated_by(node, potential_dom) - && node_data - .terminator() - .successors() - .into_iter() - .any(|succ| succ == potential_dom) - }) { - Some(node) - } else { - None - } - }) - .collect(); + || has_back_edge(&body.basic_blocks, node, &node_data) + { + Some(node) + } else { + None + } + }) + .collect(); for index in indices { insert_counter( body.basic_blocks_mut() @@ -43,6 +34,20 @@ impl<'tcx> MirPass<'tcx> for CtfeLimit { } } +fn has_back_edge( + basic_blocks: &BasicBlocks<'_>, + node: BasicBlock, + node_data: &BasicBlockData<'_>, +) -> bool { + let doms = basic_blocks.dominators(); + basic_blocks.indices().any(|potential_dom| { + doms.is_reachable(potential_dom) + && doms.is_reachable(node) + && doms.is_dominated_by(node, potential_dom) + && node_data.terminator().successors().into_iter().any(|succ| succ == potential_dom) + }) +} + fn insert_counter(basic_block_data: &mut BasicBlockData<'_>) { basic_block_data.statements.push(Statement { source_info: basic_block_data.terminator().source_info, From eea42733ac070b62492037107ee38028abb71f1a Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Thu, 29 Dec 2022 23:14:29 +0000 Subject: [PATCH 310/500] Replace terminator-based const eval limit - Remove logic that limits const eval based on terminators, and use the stable metric instead (back edges + fn calls) - Add unstable flag `tiny-const-eval-limit` to add UI tests that do not have to go up to the regular 2M step limit --- .../src/const_eval/machine.rs | 4 +-- .../src/interpret/eval_context.rs | 5 ---- .../rustc_const_eval/src/interpret/machine.rs | 6 ++-- .../rustc_const_eval/src/interpret/place.rs | 11 ------- .../rustc_const_eval/src/interpret/step.rs | 4 +-- compiler/rustc_interface/src/tests.rs | 1 + compiler/rustc_middle/src/ty/context.rs | 8 ++++- compiler/rustc_session/src/options.rs | 2 ++ .../compiler-flags/tiny-const-eval-limit.md | 6 ++++ .../const-eval/stable-metric/ctfe-fn-call.rs | 9 ++++-- .../stable-metric/ctfe-fn-call.stderr | 20 +++++++++++-- .../stable-metric/ctfe-labelled-loop.rs | 26 +++++++--------- .../stable-metric/ctfe-labelled-loop.stderr | 30 +++++++++++++++++-- .../stable-metric/ctfe-recursion.rs | 7 +++-- .../stable-metric/ctfe-recursion.stderr | 25 ++++++++++++++-- .../stable-metric/ctfe-simple-loop.rs | 11 ++++--- .../stable-metric/ctfe-simple-loop.stderr | 24 +++++++++++++-- 17 files changed, 138 insertions(+), 61 deletions(-) create mode 100644 src/doc/unstable-book/src/compiler-flags/tiny-const-eval-limit.md diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 4709514c82e85..a5bc121485d8c 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -561,8 +561,8 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time"); } - fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { - // The step limit has already been hit in a previous call to `before_terminator`. + fn increment_const_eval_counter(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { + // The step limit has already been hit in a previous call to `increment_const_eval_counter`. if ecx.machine.steps_remaining == 0 { return Ok(()); } diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index cc97564e8fc28..d13fed7a9c263 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -46,9 +46,6 @@ pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> { /// The recursion limit (cached from `tcx.recursion_limit(())`) pub recursion_limit: Limit, - - pub const_eval_limit: u32, - pub const_eval_counter: u32, } // The Phantomdata exists to prevent this type from being `Send`. If it were sent across a thread @@ -411,8 +408,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { param_env, memory: Memory::new(), recursion_limit: tcx.recursion_limit(), - const_eval_limit: 20, - const_eval_counter: 0, } } diff --git a/compiler/rustc_const_eval/src/interpret/machine.rs b/compiler/rustc_const_eval/src/interpret/machine.rs index 248953de86728..1f63a4ac53784 100644 --- a/compiler/rustc_const_eval/src/interpret/machine.rs +++ b/compiler/rustc_const_eval/src/interpret/machine.rs @@ -243,10 +243,10 @@ pub trait Machine<'mir, 'tcx>: Sized { ecx.stack_mut()[frame].locals[local].access_mut() } - /// Called before a basic block terminator is executed. - /// You can use this to detect endlessly running programs. + /// Called when the interpreter encounters a `StatementKind::ConstEvalCounter` instruction. + /// You can use this to detect long or endlessly running programs. #[inline] - fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { + fn increment_const_eval_counter(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { Ok(()) } diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index 271a3a74fe319..274af61ee7c1d 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -293,17 +293,6 @@ where Prov: Provenance + 'static, M: Machine<'mir, 'tcx, Provenance = Prov>, { - pub fn increment_const_eval_counter(&mut self) { - self.const_eval_counter = self.const_eval_counter + 1; - if self.const_eval_counter == self.const_eval_limit { - let mut warn = self.tcx.sess.struct_warn(format!( - "Const eval counter limit ({}) has been crossed", - self.const_eval_limit - )); - warn.emit(); - } - } - /// Take a value, which represents a (thin or wide) reference, and make it a place. /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`. /// diff --git a/compiler/rustc_const_eval/src/interpret/step.rs b/compiler/rustc_const_eval/src/interpret/step.rs index 6c5594bc1b086..7668e890c7bc3 100644 --- a/compiler/rustc_const_eval/src/interpret/step.rs +++ b/compiler/rustc_const_eval/src/interpret/step.rs @@ -62,8 +62,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { return Ok(true); } - M::before_terminator(self)?; - let terminator = basic_block.terminator(); self.terminator(terminator)?; Ok(true) @@ -130,7 +128,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { Coverage(..) => {} ConstEvalCounter => { - self.increment_const_eval_counter(); + M::increment_const_eval_counter(self)?; } // Defined to do nothing. These are added by optimization passes, to avoid changing the diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index f94bc4d4c66ac..52a4e0e74181f 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -802,6 +802,7 @@ fn test_unstable_options_tracking_hash() { tracked!(teach, true); tracked!(thinlto, Some(true)); tracked!(thir_unsafeck, true); + tracked!(tiny_const_eval_limit, true); tracked!(tls_model, Some(TlsModel::GeneralDynamic)); tracked!(trait_solver, TraitSolver::Chalk); tracked!(translate_remapped_path_to_local_path, false); diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index ce04d8d21f4cd..8a61fd2e029bc 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -75,6 +75,8 @@ use std::iter; use std::mem; use std::ops::{Bound, Deref}; +const TINY_CONST_EVAL_LIMIT: Limit = Limit(20); + pub trait OnDiskCache<'tcx>: rustc_data_structures::sync::Sync { /// Creates a new `OnDiskCache` instance from the serialized data in `data`. fn new(sess: &'tcx Session, data: Mmap, start_pos: usize) -> Self @@ -1078,7 +1080,11 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn const_eval_limit(self) -> Limit { - self.limits(()).const_eval_limit + if self.sess.opts.unstable_opts.tiny_const_eval_limit { + TINY_CONST_EVAL_LIMIT + } else { + self.limits(()).const_eval_limit + } } pub fn all_traits(self) -> impl Iterator + 'tcx { diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 7b5fd6cc2a81d..789af0c7bf966 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1616,6 +1616,8 @@ options! { "measure time of each LLVM pass (default: no)"), time_passes: bool = (false, parse_bool, [UNTRACKED], "measure time of each rustc pass (default: no)"), + tiny_const_eval_limit: bool = (false, parse_bool, [TRACKED], + "sets a tiny, non-configurable limit for const eval; useful for compiler tests"), #[rustc_lint_opt_deny_field_access("use `Session::tls_model` instead of this field")] tls_model: Option = (None, parse_tls_model, [TRACKED], "choose the TLS model to use (`rustc --print tls-models` for details)"), diff --git a/src/doc/unstable-book/src/compiler-flags/tiny-const-eval-limit.md b/src/doc/unstable-book/src/compiler-flags/tiny-const-eval-limit.md new file mode 100644 index 0000000000000..51c5fd69c6377 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/tiny-const-eval-limit.md @@ -0,0 +1,6 @@ +# `tiny-const-eval-limit` + +-------------------- + +The `-Ztiny-const-eval-limit` compiler flag sets a tiny, non-configurable limit for const eval. +This flag should only be used by const eval tests in the rustc test suite. diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs b/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs index 33488bd1d1c55..c59596238e140 100644 --- a/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs @@ -1,4 +1,5 @@ -// check-pass +// check-fail +// compile-flags: -Z tiny-const-eval-limit const fn foo() {} @@ -8,21 +9,23 @@ const fn call_foo() -> u32 { foo(); foo(); foo(); + foo(); foo(); foo(); foo(); foo(); + foo(); foo(); foo(); foo(); foo(); + foo(); foo(); foo(); - foo(); - foo(); + foo(); //~ ERROR evaluation of constant value failed [E0080] 0 } diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr b/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr index 183bed3b75b25..ed70975af341d 100644 --- a/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr @@ -1,4 +1,20 @@ -warning: Const eval counter limit (20) has been crossed +error[E0080]: evaluation of constant value failed + --> $DIR/ctfe-fn-call.rs:28:5 + | +LL | foo(); + | ^^^^^ exceeded interpreter step limit (see `#[const_eval_limit]`) + | +note: inside `call_foo` + --> $DIR/ctfe-fn-call.rs:28:5 + | +LL | foo(); + | ^^^^^ +note: inside `X` + --> $DIR/ctfe-fn-call.rs:32:16 + | +LL | const X: u32 = call_foo(); + | ^^^^^^^^^^ -warning: 1 warning emitted +error: aborting due to previous error +For more information about this error, try `rustc --explain E0080`. diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs b/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs index 71f29ce8731f0..c10b8d8379119 100644 --- a/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs @@ -1,24 +1,18 @@ -// check-pass -#![feature(const_for)] +// check-fail +// compile-flags: -Z tiny-const-eval-limit -const fn labelled_loop() -> u32 { - let mut n = 0; - 'outer: loop { - 'inner: loop { - n = n + 1; - if n > 5 && n <= 10 { - n = n + 1; - continue 'inner - } - if n > 30 { - break 'outer - } +const fn labelled_loop(n: u32) -> u32 { + let mut i = 0; + 'mylabel: loop { //~ ERROR evaluation of constant value failed [E0080] + if i > n { + break 'mylabel } + i += 1; } - n + 0 } -const X: u32 = labelled_loop(); +const X: u32 = labelled_loop(19); fn main() { println!("{X}"); diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr b/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr index 183bed3b75b25..d9404edd5b108 100644 --- a/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr @@ -1,4 +1,30 @@ -warning: Const eval counter limit (20) has been crossed +error[E0080]: evaluation of constant value failed + --> $DIR/ctfe-labelled-loop.rs:6:5 + | +LL | / 'mylabel: loop { +LL | | if i > n { +LL | | break 'mylabel +LL | | } +LL | | i += 1; +LL | | } + | |_____^ exceeded interpreter step limit (see `#[const_eval_limit]`) + | +note: inside `labelled_loop` + --> $DIR/ctfe-labelled-loop.rs:6:5 + | +LL | / 'mylabel: loop { +LL | | if i > n { +LL | | break 'mylabel +LL | | } +LL | | i += 1; +LL | | } + | |_____^ +note: inside `X` + --> $DIR/ctfe-labelled-loop.rs:15:16 + | +LL | const X: u32 = labelled_loop(19); + | ^^^^^^^^^^^^^^^^^ -warning: 1 warning emitted +error: aborting due to previous error +For more information about this error, try `rustc --explain E0080`. diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.rs b/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.rs index 00b4fc258593a..80ff835f3e8dd 100644 --- a/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.rs +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.rs @@ -1,14 +1,15 @@ -// check-pass +// check-fail +// compile-flags: -Z tiny-const-eval-limit const fn recurse(n: u32) -> u32 { if n == 0 { n } else { - recurse(n - 1) + recurse(n - 1) //~ ERROR evaluation of constant value failed [E0080] } } -const X: u32 = recurse(30); +const X: u32 = recurse(19); fn main() { println!("{X}"); diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr b/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr index 183bed3b75b25..ed9a31119427a 100644 --- a/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr @@ -1,4 +1,25 @@ -warning: Const eval counter limit (20) has been crossed +error[E0080]: evaluation of constant value failed + --> $DIR/ctfe-recursion.rs:8:9 + | +LL | recurse(n - 1) + | ^^^^^^^^^^^^^^ exceeded interpreter step limit (see `#[const_eval_limit]`) + | +note: inside `recurse` + --> $DIR/ctfe-recursion.rs:8:9 + | +LL | recurse(n - 1) + | ^^^^^^^^^^^^^^ +note: [... 18 additional calls inside `recurse` ...] + --> $DIR/ctfe-recursion.rs:8:9 + | +LL | recurse(n - 1) + | ^^^^^^^^^^^^^^ +note: inside `X` + --> $DIR/ctfe-recursion.rs:12:16 + | +LL | const X: u32 = recurse(19); + | ^^^^^^^^^^^ -warning: 1 warning emitted +error: aborting due to previous error +For more information about this error, try `rustc --explain E0080`. diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs b/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs index 74dc74734b45e..ca0eec93c5dac 100644 --- a/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs @@ -1,15 +1,14 @@ -// check-pass +// check-fail +// compile-flags: -Z tiny-const-eval-limit const fn simple_loop(n: u32) -> u32 { let mut index = 0; - let mut res = 0; - while index < n { - res = res + index; + while index < n { //~ ERROR evaluation of constant value failed [E0080] index = index + 1; } - res + 0 } -const X: u32 = simple_loop(30); +const X: u32 = simple_loop(19); fn main() { println!("{X}"); diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr b/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr index 183bed3b75b25..83ff275de7049 100644 --- a/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr +++ b/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr @@ -1,4 +1,24 @@ -warning: Const eval counter limit (20) has been crossed +error[E0080]: evaluation of constant value failed + --> $DIR/ctfe-simple-loop.rs:5:5 + | +LL | / while index < n { +LL | | index = index + 1; +LL | | } + | |_____^ exceeded interpreter step limit (see `#[const_eval_limit]`) + | +note: inside `simple_loop` + --> $DIR/ctfe-simple-loop.rs:5:5 + | +LL | / while index < n { +LL | | index = index + 1; +LL | | } + | |_____^ +note: inside `X` + --> $DIR/ctfe-simple-loop.rs:11:16 + | +LL | const X: u32 = simple_loop(19); + | ^^^^^^^^^^^^^^^ -warning: 1 warning emitted +error: aborting due to previous error +For more information about this error, try `rustc --explain E0080`. From 164ff640131cf90f5a6e8639a5cdc7ece297ba83 Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Thu, 29 Dec 2022 23:44:16 +0000 Subject: [PATCH 311/500] Update codegen cranelift for ConstEvalCounter --- compiler/rustc_codegen_cranelift/src/base.rs | 1 + compiler/rustc_codegen_cranelift/src/constant.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/compiler/rustc_codegen_cranelift/src/base.rs b/compiler/rustc_codegen_cranelift/src/base.rs index 89d955e8bf2e1..6e584c308c109 100644 --- a/compiler/rustc_codegen_cranelift/src/base.rs +++ b/compiler/rustc_codegen_cranelift/src/base.rs @@ -789,6 +789,7 @@ fn codegen_stmt<'tcx>( StatementKind::StorageLive(_) | StatementKind::StorageDead(_) | StatementKind::Deinit(_) + | StatementKind::ConstEvalCounter | StatementKind::Nop | StatementKind::FakeRead(..) | StatementKind::Retag { .. } diff --git a/compiler/rustc_codegen_cranelift/src/constant.rs b/compiler/rustc_codegen_cranelift/src/constant.rs index 51450897bfc11..49c4f1aaaefc6 100644 --- a/compiler/rustc_codegen_cranelift/src/constant.rs +++ b/compiler/rustc_codegen_cranelift/src/constant.rs @@ -530,6 +530,7 @@ pub(crate) fn mir_operand_get_const_val<'tcx>( | StatementKind::Retag(_, _) | StatementKind::AscribeUserType(_, _) | StatementKind::Coverage(_) + | StatementKind::ConstEvalCounter | StatementKind::Nop => {} } } From 80a3d2ad0ceaabd353d4800339045a45559385c7 Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Thu, 29 Dec 2022 23:50:53 +0000 Subject: [PATCH 312/500] Update Clippy for ConstEvalCounter --- src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index e5d7da682813c..d127b896deacf 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -240,6 +240,7 @@ fn check_statement<'tcx>( | StatementKind::Retag { .. } | StatementKind::AscribeUserType(..) | StatementKind::Coverage(..) + | StatementKind::ConstEvalCounter | StatementKind::Nop => Ok(()), } } From 08de246cd71a67915d4931aa37bc4f1c6374be0e Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Fri, 30 Dec 2022 00:24:41 +0000 Subject: [PATCH 313/500] Move CtfeLimit to mir_const's set of passes --- compiler/rustc_borrowck/src/lib.rs | 4 ++-- compiler/rustc_mir_transform/src/lib.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 8f8fae2c630b5..e21f6e6a67cd9 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -610,6 +610,7 @@ impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtx // Doesn't have any language semantics | StatementKind::Coverage(..) // Does not actually affect borrowck + | StatementKind::ConstEvalCounter | StatementKind::StorageLive(..) => {} StatementKind::StorageDead(local) => { self.access_place( @@ -620,8 +621,7 @@ impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtx flow_state, ); } - StatementKind::ConstEvalCounter - | StatementKind::Nop + StatementKind::Nop | StatementKind::Retag { .. } | StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => { diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 9a786d0c8d62a..e1388e678f1f7 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -299,6 +299,7 @@ fn mir_const(tcx: TyCtxt<'_>, def: ty::WithOptConstParam) -> &Steal< // What we need to do constant evaluation. &simplify::SimplifyCfg::new("initial"), &rustc_peek::SanityCheck, // Just a lint + &ctfe_limit::CtfeLimit, ], None, ); @@ -518,7 +519,6 @@ fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // CTFE support for aggregates. &deaggregator::Deaggregator, &Lint(const_prop_lint::ConstProp), - &ctfe_limit::CtfeLimit, ]; pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial))); } From 172662dede507cc678747cc3d090f2ae744733cf Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Fri, 30 Dec 2022 00:34:17 +0000 Subject: [PATCH 314/500] Add back Machine::before_terminator(...) method Added it back because it's used by Miri, but in the compiler itself, it will not do anything (just return `Ok(())`. --- compiler/rustc_const_eval/src/const_eval/machine.rs | 5 +++++ compiler/rustc_const_eval/src/interpret/machine.rs | 6 ++++++ compiler/rustc_const_eval/src/interpret/step.rs | 2 ++ 3 files changed, 13 insertions(+) diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index a5bc121485d8c..e51f52783d4c1 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -561,6 +561,11 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time"); } + // Not used here, but used by Miri (see `src/tools/miri/src/machine.rs`). + fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { + Ok(()) + } + fn increment_const_eval_counter(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { // The step limit has already been hit in a previous call to `increment_const_eval_counter`. if ecx.machine.steps_remaining == 0 { diff --git a/compiler/rustc_const_eval/src/interpret/machine.rs b/compiler/rustc_const_eval/src/interpret/machine.rs index 1f63a4ac53784..76ed7b80f8d81 100644 --- a/compiler/rustc_const_eval/src/interpret/machine.rs +++ b/compiler/rustc_const_eval/src/interpret/machine.rs @@ -243,6 +243,12 @@ pub trait Machine<'mir, 'tcx>: Sized { ecx.stack_mut()[frame].locals[local].access_mut() } + /// Called before a basic block terminator is executed. + #[inline] + fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { + Ok(()) + } + /// Called when the interpreter encounters a `StatementKind::ConstEvalCounter` instruction. /// You can use this to detect long or endlessly running programs. #[inline] diff --git a/compiler/rustc_const_eval/src/interpret/step.rs b/compiler/rustc_const_eval/src/interpret/step.rs index 7668e890c7bc3..d101937fd7406 100644 --- a/compiler/rustc_const_eval/src/interpret/step.rs +++ b/compiler/rustc_const_eval/src/interpret/step.rs @@ -62,6 +62,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { return Ok(true); } + M::before_terminator(self)?; + let terminator = basic_block.terminator(); self.terminator(terminator)?; Ok(true) From d3c13a010295002211fae61f2cac2fbe374bc0fc Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Fri, 30 Dec 2022 01:55:16 +0000 Subject: [PATCH 315/500] Revert "Move CtfeLimit to mir_const's set of passes" This reverts commit 332542a92223b2800ed372d2d461921147f29477. --- compiler/rustc_borrowck/src/lib.rs | 4 ++-- compiler/rustc_mir_transform/src/lib.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index e21f6e6a67cd9..8f8fae2c630b5 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -610,7 +610,6 @@ impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtx // Doesn't have any language semantics | StatementKind::Coverage(..) // Does not actually affect borrowck - | StatementKind::ConstEvalCounter | StatementKind::StorageLive(..) => {} StatementKind::StorageDead(local) => { self.access_place( @@ -621,7 +620,8 @@ impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtx flow_state, ); } - StatementKind::Nop + StatementKind::ConstEvalCounter + | StatementKind::Nop | StatementKind::Retag { .. } | StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => { diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index e1388e678f1f7..9a786d0c8d62a 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -299,7 +299,6 @@ fn mir_const(tcx: TyCtxt<'_>, def: ty::WithOptConstParam) -> &Steal< // What we need to do constant evaluation. &simplify::SimplifyCfg::new("initial"), &rustc_peek::SanityCheck, // Just a lint - &ctfe_limit::CtfeLimit, ], None, ); @@ -519,6 +518,7 @@ fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // CTFE support for aggregates. &deaggregator::Deaggregator, &Lint(const_prop_lint::ConstProp), + &ctfe_limit::CtfeLimit, ]; pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial))); } From 999d19d8aa39422e16c55598aef25c2fa56e0540 Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Wed, 4 Jan 2023 04:20:14 +0000 Subject: [PATCH 316/500] Move CtfeLimit MirPass to inner_mir_for_ctfe --- compiler/rustc_mir_transform/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 9a786d0c8d62a..f12e04cccd404 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -411,6 +411,8 @@ fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam) - } } + pm::run_passes(tcx, &mut body, &[&ctfe_limit::CtfeLimit], None); + debug_assert!(!body.has_free_regions(), "Free regions in MIR for CTFE"); body @@ -518,7 +520,6 @@ fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // CTFE support for aggregates. &deaggregator::Deaggregator, &Lint(const_prop_lint::ConstProp), - &ctfe_limit::CtfeLimit, ]; pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial))); } From aae331d610f318cd2d472c39f1e09b02d4f83d81 Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Wed, 4 Jan 2023 04:29:27 +0000 Subject: [PATCH 317/500] During MirBorrowck, ignore ConstEvalCounter --- compiler/rustc_borrowck/src/lib.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 8f8fae2c630b5..bc81abe4005c9 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -609,7 +609,8 @@ impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtx StatementKind::AscribeUserType(..) // Doesn't have any language semantics | StatementKind::Coverage(..) - // Does not actually affect borrowck + // These do not actually affect borrowck + | StatementKind::ConstEvalCounter | StatementKind::StorageLive(..) => {} StatementKind::StorageDead(local) => { self.access_place( @@ -620,8 +621,7 @@ impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtx flow_state, ); } - StatementKind::ConstEvalCounter - | StatementKind::Nop + StatementKind::Nop | StatementKind::Retag { .. } | StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => { From 75b7c6c8ecc6865823e64ff6b2ab5b018c8ca15b Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Wed, 4 Jan 2023 05:04:03 +0000 Subject: [PATCH 318/500] Bless and update consts tests --- tests/ui/consts/const-eval/infinite_loop.stderr | 9 ++++++--- tests/ui/consts/const-eval/issue-52475.rs | 4 ++-- tests/ui/consts/const-eval/issue-52475.stderr | 9 ++++++--- .../consts/const_limit/const_eval_limit_reached.stderr | 9 ++++++--- 4 files changed, 20 insertions(+), 11 deletions(-) diff --git a/tests/ui/consts/const-eval/infinite_loop.stderr b/tests/ui/consts/const-eval/infinite_loop.stderr index 8b58cb279f376..f30bfaf3f958c 100644 --- a/tests/ui/consts/const-eval/infinite_loop.stderr +++ b/tests/ui/consts/const-eval/infinite_loop.stderr @@ -1,8 +1,11 @@ error[E0080]: evaluation of constant value failed - --> $DIR/infinite_loop.rs:6:15 + --> $DIR/infinite_loop.rs:6:9 | -LL | while n != 0 { - | ^^^^^^ exceeded interpreter step limit (see `#[const_eval_limit]`) +LL | / while n != 0 { +LL | | +LL | | n = if n % 2 == 0 { n/2 } else { 3*n + 1 }; +LL | | } + | |_________^ exceeded interpreter step limit (see `#[const_eval_limit]`) error: aborting due to previous error diff --git a/tests/ui/consts/const-eval/issue-52475.rs b/tests/ui/consts/const-eval/issue-52475.rs index ce65407bbab0b..307c1a6683410 100644 --- a/tests/ui/consts/const-eval/issue-52475.rs +++ b/tests/ui/consts/const-eval/issue-52475.rs @@ -2,8 +2,8 @@ fn main() { let _ = [(); { let mut x = &0; let mut n = 0; - while n < 5 { - n = (n + 1) % 5; //~ ERROR evaluation of constant value failed + while n < 5 { //~ ERROR evaluation of constant value failed [E0080] + n = (n + 1) % 5; x = &0; // Materialize a new AllocId } 0 diff --git a/tests/ui/consts/const-eval/issue-52475.stderr b/tests/ui/consts/const-eval/issue-52475.stderr index 8536ff02c6dae..3aa6bd277ddcb 100644 --- a/tests/ui/consts/const-eval/issue-52475.stderr +++ b/tests/ui/consts/const-eval/issue-52475.stderr @@ -1,8 +1,11 @@ error[E0080]: evaluation of constant value failed - --> $DIR/issue-52475.rs:6:17 + --> $DIR/issue-52475.rs:5:9 | -LL | n = (n + 1) % 5; - | ^^^^^^^^^^^ exceeded interpreter step limit (see `#[const_eval_limit]`) +LL | / while n < 5 { +LL | | n = (n + 1) % 5; +LL | | x = &0; // Materialize a new AllocId +LL | | } + | |_________^ exceeded interpreter step limit (see `#[const_eval_limit]`) error: aborting due to previous error diff --git a/tests/ui/consts/const_limit/const_eval_limit_reached.stderr b/tests/ui/consts/const_limit/const_eval_limit_reached.stderr index 850aebdfb2a6d..a8e8ae9bb088a 100644 --- a/tests/ui/consts/const_limit/const_eval_limit_reached.stderr +++ b/tests/ui/consts/const_limit/const_eval_limit_reached.stderr @@ -1,8 +1,11 @@ error[E0080]: evaluation of constant value failed - --> $DIR/const_eval_limit_reached.rs:6:11 + --> $DIR/const_eval_limit_reached.rs:6:5 | -LL | while x != 1000 { - | ^^^^^^^^^ exceeded interpreter step limit (see `#[const_eval_limit]`) +LL | / while x != 1000 { +LL | | +LL | | x += 1; +LL | | } + | |_____^ exceeded interpreter step limit (see `#[const_eval_limit]`) error: aborting due to previous error From a8c9528e0692d723736eb090bb10ab6145d4bf8c Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Wed, 4 Jan 2023 05:59:37 +0000 Subject: [PATCH 319/500] Bless z-help test for new flag --- tests/rustdoc-ui/z-help.stdout | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/rustdoc-ui/z-help.stdout b/tests/rustdoc-ui/z-help.stdout index 4bdecdc1b7944..3d7919826b574 100644 --- a/tests/rustdoc-ui/z-help.stdout +++ b/tests/rustdoc-ui/z-help.stdout @@ -172,6 +172,7 @@ -Z threads=val -- use a thread pool with N threads -Z time-llvm-passes=val -- measure time of each LLVM pass (default: no) -Z time-passes=val -- measure time of each rustc pass (default: no) + -Z tiny-const-eval-limit=val -- sets a tiny, non-configurable limit for const eval; useful for compiler tests -Z tls-model=val -- choose the TLS model to use (`rustc --print tls-models` for details) -Z trace-macros=val -- for every macro invocation, print its name and arguments (default: no) -Z track-diagnostics=val -- tracks where in rustc a diagnostic was emitted From f9982ea24a55a1912198bc49578f7af090e487e9 Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Fri, 6 Jan 2023 16:26:56 +0000 Subject: [PATCH 320/500] Add comment on cause of panic in dominators algorithm --- .../src/graph/dominators/mod.rs | 42 ++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_data_structures/src/graph/dominators/mod.rs b/compiler/rustc_data_structures/src/graph/dominators/mod.rs index 6398a501983cf..38a687af7e696 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/mod.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/mod.rs @@ -135,7 +135,47 @@ pub fn dominators(graph: G) -> Dominators { // This loop computes the semi[w] for w. semi[w] = w; for v in graph.predecessors(pre_order_to_real[w]) { - // Reachable vertices may have unreachable predecessors, so ignore any of them + // TL;DR: Reachable vertices may have unreachable predecessors, so ignore any of them. + // + // Ignore blocks which are not connected to the entry block. + // + // The algorithm that was used to traverse the graph and build the + // `pre_order_to_real` and `real_to_pre_order` vectors does so by + // starting from the entry block and following the successors. + // Therefore, any blocks not reachable from the entry block will be + // set to `None` in the `pre_order_to_real` vector. + // + // For example, in this graph, A and B should be skipped: + // + // ┌─────┐ + // │ │ + // └──┬──┘ + // │ + // ┌──▼──┐ ┌─────┐ + // │ │ │ A │ + // └──┬──┘ └──┬──┘ + // │ │ + // ┌───────┴───────┐ │ + // │ │ │ + // ┌──▼──┐ ┌──▼──┐ ┌──▼──┐ + // │ │ │ │ │ B │ + // └──┬──┘ └──┬──┘ └──┬──┘ + // │ └──────┬─────┘ + // ┌──▼──┐ │ + // │ │ │ + // └──┬──┘ ┌──▼──┐ + // │ │ │ + // │ └─────┘ + // ┌──▼──┐ + // │ │ + // └──┬──┘ + // │ + // ┌──▼──┐ + // │ │ + // └─────┘ + // + // ...this may be the case if a MirPass modifies the CFG to remove + // or rearrange certain blocks/edges. let Some(v) = real_to_pre_order[v] else { continue }; From 7618163a1caf0d6dfa5618c8369742720c90ef6b Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Fri, 6 Jan 2023 16:39:24 +0000 Subject: [PATCH 321/500] Add comments and remove unnecessary code --- compiler/rustc_const_eval/src/const_eval/machine.rs | 5 ----- compiler/rustc_middle/src/mir/syntax.rs | 9 +++++---- compiler/rustc_mir_transform/src/ctfe_limit.rs | 2 ++ 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index e51f52783d4c1..a5bc121485d8c 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -561,11 +561,6 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time"); } - // Not used here, but used by Miri (see `src/tools/miri/src/machine.rs`). - fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { - Ok(()) - } - fn increment_const_eval_counter(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { // The step limit has already been hit in a previous call to `increment_const_eval_counter`. if ecx.machine.steps_remaining == 0 { diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index faf903a594901..549bc65d6d79c 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -286,10 +286,7 @@ pub enum StatementKind<'tcx> { /// This is permitted for both generators and ADTs. This does not necessarily write to the /// entire place; instead, it writes to the minimum set of bytes as required by the layout for /// the type. - SetDiscriminant { - place: Box>, - variant_index: VariantIdx, - }, + SetDiscriminant { place: Box>, variant_index: VariantIdx }, /// Deinitializes the place. /// @@ -358,6 +355,10 @@ pub enum StatementKind<'tcx> { /// This avoids adding a new block and a terminator for simple intrinsics. Intrinsic(Box>), + /// Instructs the const eval interpreter to increment a counter; this counter is used to track + /// how many steps the interpreter has taken. It is used to prevent the user from writing const + /// code that runs for too long or infinitely. Other than in the const eval interpreter, this + /// is a no-op. ConstEvalCounter, /// No-op. Useful for deleting instructions without affecting statement indices. diff --git a/compiler/rustc_mir_transform/src/ctfe_limit.rs b/compiler/rustc_mir_transform/src/ctfe_limit.rs index 1ff8b792dca36..76db4a09d9153 100644 --- a/compiler/rustc_mir_transform/src/ctfe_limit.rs +++ b/compiler/rustc_mir_transform/src/ctfe_limit.rs @@ -1,3 +1,5 @@ +//! A pass that inserts the `ConstEvalCounter` instruction into any blocks that have a back edge +//! (thus indicating there is a loop in the CFG), or whose terminator is a function call. use crate::MirPass; use rustc_middle::mir::{ From 1bbd655888ec50220e6cd34e846c816c1cad8f17 Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Fri, 6 Jan 2023 22:04:25 +0000 Subject: [PATCH 322/500] Improve efficiency of has_back_edge(...) --- .../src/graph/dominators/mod.rs | 7 +++++++ .../rustc_mir_transform/src/ctfe_limit.rs | 21 ++++++++++--------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_data_structures/src/graph/dominators/mod.rs b/compiler/rustc_data_structures/src/graph/dominators/mod.rs index 38a687af7e696..0a21a4249c829 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/mod.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/mod.rs @@ -304,13 +304,18 @@ fn compress( } } +/// Tracks the list of dominators for each node. #[derive(Clone, Debug)] pub struct Dominators { post_order_rank: IndexVec, + // Even though we track only the immediate dominator of each node, it's + // possible to get its full list of dominators by looking up the dominator + // of each dominator. (See the `impl Iterator for Iter` definition). immediate_dominators: IndexVec>, } impl Dominators { + /// Whether the given Node has an immediate dominator. pub fn is_reachable(&self, node: Node) -> bool { self.immediate_dominators[node].is_some() } @@ -320,6 +325,8 @@ impl Dominators { self.immediate_dominators[node].unwrap() } + /// Provides an iterator over each dominator up the CFG, for the given Node. + /// See the `impl Iterator for Iter` definition to understand how this works. pub fn dominators(&self, node: Node) -> Iter<'_, Node> { assert!(self.is_reachable(node), "node {node:?} is not reachable"); Iter { dominators: self, node: Some(node) } diff --git a/compiler/rustc_mir_transform/src/ctfe_limit.rs b/compiler/rustc_mir_transform/src/ctfe_limit.rs index 76db4a09d9153..7d127032179b4 100644 --- a/compiler/rustc_mir_transform/src/ctfe_limit.rs +++ b/compiler/rustc_mir_transform/src/ctfe_limit.rs @@ -2,8 +2,9 @@ //! (thus indicating there is a loop in the CFG), or whose terminator is a function call. use crate::MirPass; +use rustc_data_structures::graph::dominators::Dominators; use rustc_middle::mir::{ - BasicBlock, BasicBlockData, BasicBlocks, Body, Statement, StatementKind, TerminatorKind, + BasicBlock, BasicBlockData, Body, Statement, StatementKind, TerminatorKind, }; use rustc_middle::ty::TyCtxt; @@ -12,13 +13,14 @@ pub struct CtfeLimit; impl<'tcx> MirPass<'tcx> for CtfeLimit { #[instrument(skip(self, _tcx, body))] fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { + let doms = body.basic_blocks.dominators(); let indices: Vec = body .basic_blocks .iter_enumerated() .filter_map(|(node, node_data)| { if matches!(node_data.terminator().kind, TerminatorKind::Call { .. }) // Back edges in a CFG indicate loops - || has_back_edge(&body.basic_blocks, node, &node_data) + || has_back_edge(&doms, node, &node_data) { Some(node) } else { @@ -37,17 +39,16 @@ impl<'tcx> MirPass<'tcx> for CtfeLimit { } fn has_back_edge( - basic_blocks: &BasicBlocks<'_>, + doms: &Dominators, node: BasicBlock, node_data: &BasicBlockData<'_>, ) -> bool { - let doms = basic_blocks.dominators(); - basic_blocks.indices().any(|potential_dom| { - doms.is_reachable(potential_dom) - && doms.is_reachable(node) - && doms.is_dominated_by(node, potential_dom) - && node_data.terminator().successors().into_iter().any(|succ| succ == potential_dom) - }) + if !doms.is_reachable(node) { + return false; + } + // Check if any of the dominators of the node are also the node's successor. + doms.dominators(node) + .any(|dom| node_data.terminator().successors().into_iter().any(|succ| succ == dom)) } fn insert_counter(basic_block_data: &mut BasicBlockData<'_>) { From bdb815a22ab00450dcc010a99309c24c475432a6 Mon Sep 17 00:00:00 2001 From: Bryan Garza <1396101+bryangarza@users.noreply.github.com> Date: Tue, 17 Jan 2023 22:35:05 +0000 Subject: [PATCH 323/500] Move const-eval/stable-metric ui tests --- .../const-eval/stable-metric/ctfe-fn-call.rs | 0 .../stable-metric/ctfe-fn-call.stderr | 0 .../stable-metric/ctfe-labelled-loop.rs | 0 .../stable-metric/ctfe-labelled-loop.stderr | 0 .../stable-metric/ctfe-recursion.rs | 0 .../stable-metric/ctfe-recursion.stderr | 0 .../stable-metric/ctfe-simple-loop.rs | 0 .../stable-metric/ctfe-simple-loop.stderr | 0 .../stable-metric/dominators-edge-case.rs | 19 +++++++++++++++++++ 9 files changed, 19 insertions(+) rename {src/test => tests}/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs (100%) rename {src/test => tests}/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr (100%) rename {src/test => tests}/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs (100%) rename {src/test => tests}/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr (100%) rename {src/test => tests}/ui/consts/const-eval/stable-metric/ctfe-recursion.rs (100%) rename {src/test => tests}/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr (100%) rename {src/test => tests}/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs (100%) rename {src/test => tests}/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr (100%) create mode 100644 tests/ui/consts/const-eval/stable-metric/dominators-edge-case.rs diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs b/tests/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs similarity index 100% rename from src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs rename to tests/ui/consts/const-eval/stable-metric/ctfe-fn-call.rs diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr b/tests/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr similarity index 100% rename from src/test/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr rename to tests/ui/consts/const-eval/stable-metric/ctfe-fn-call.stderr diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs b/tests/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs similarity index 100% rename from src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs rename to tests/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.rs diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr b/tests/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr similarity index 100% rename from src/test/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr rename to tests/ui/consts/const-eval/stable-metric/ctfe-labelled-loop.stderr diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.rs b/tests/ui/consts/const-eval/stable-metric/ctfe-recursion.rs similarity index 100% rename from src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.rs rename to tests/ui/consts/const-eval/stable-metric/ctfe-recursion.rs diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr b/tests/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr similarity index 100% rename from src/test/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr rename to tests/ui/consts/const-eval/stable-metric/ctfe-recursion.stderr diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs b/tests/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs similarity index 100% rename from src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs rename to tests/ui/consts/const-eval/stable-metric/ctfe-simple-loop.rs diff --git a/src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr b/tests/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr similarity index 100% rename from src/test/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr rename to tests/ui/consts/const-eval/stable-metric/ctfe-simple-loop.stderr diff --git a/tests/ui/consts/const-eval/stable-metric/dominators-edge-case.rs b/tests/ui/consts/const-eval/stable-metric/dominators-edge-case.rs new file mode 100644 index 0000000000000..0b0f361809f20 --- /dev/null +++ b/tests/ui/consts/const-eval/stable-metric/dominators-edge-case.rs @@ -0,0 +1,19 @@ +// check-pass +// +// Exercising an edge case which was found during Stage 2 compilation. +// Compilation would fail for this code when running the `CtfeLimit` +// MirPass (specifically when looking up the dominators). +#![crate_type="lib"] + +const DUMMY: Expr = Expr::Path(ExprPath { + attrs: Vec::new(), + path: Vec::new(), +}); + +pub enum Expr { + Path(ExprPath), +} +pub struct ExprPath { + pub attrs: Vec<()>, + pub path: Vec<()>, +} From 5bfad5cc858d3b59d30da6d411449883581ff510 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Sun, 22 Jan 2023 17:06:28 -0500 Subject: [PATCH 324/500] Thread a ParamEnv down to might_permit_raw_init --- .../src/intrinsics/mod.rs | 7 ++++-- compiler/rustc_codegen_ssa/src/mir/block.rs | 4 ++-- .../src/interpret/intrinsics.rs | 4 ++-- compiler/rustc_const_eval/src/lib.rs | 11 ++++++--- .../src/util/might_permit_raw_init.rs | 3 ++- compiler/rustc_middle/src/query/mod.rs | 8 +++---- .../rustc_middle/src/ty/structural_impls.rs | 7 ++++++ .../rustc_mir_transform/src/instcombine.rs | 23 ++++++++++++------- 8 files changed, 45 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index e4ac89a7bec6b..b1adaa193b333 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -21,6 +21,7 @@ mod simd; pub(crate) use cpuid::codegen_cpuid_call; pub(crate) use llvm::codegen_llvm_intrinsic_call; +use rustc_middle::ty::layout::HasParamEnv; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::subst::SubstsRef; use rustc_span::symbol::{kw, sym, Symbol}; @@ -659,7 +660,9 @@ fn codegen_regular_intrinsic_call<'tcx>( return; } - if intrinsic == sym::assert_zero_valid && !fx.tcx.permits_zero_init(layout) { + if intrinsic == sym::assert_zero_valid + && !fx.tcx.permits_zero_init(fx.param_env().and(layout)) + { with_no_trimmed_paths!({ crate::base::codegen_panic( fx, @@ -674,7 +677,7 @@ fn codegen_regular_intrinsic_call<'tcx>( } if intrinsic == sym::assert_mem_uninitialized_valid - && !fx.tcx.permits_uninit_init(layout) + && !fx.tcx.permits_uninit_init(fx.param_env().and(layout)) { with_no_trimmed_paths!({ crate::base::codegen_panic( diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 978aff511bfa7..c73f415ad8f20 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -678,8 +678,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let layout = bx.layout_of(ty); let do_panic = match intrinsic { Inhabited => layout.abi.is_uninhabited(), - ZeroValid => !bx.tcx().permits_zero_init(layout), - MemUninitializedValid => !bx.tcx().permits_uninit_init(layout), + ZeroValid => !bx.tcx().permits_zero_init(bx.param_env().and(layout)), + MemUninitializedValid => !bx.tcx().permits_uninit_init(bx.param_env().and(layout)), }; Some(if do_panic { let msg_str = with_no_visible_paths!({ diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 666fcbd6f8048..236a4a813ab10 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -449,7 +449,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } if intrinsic_name == sym::assert_zero_valid { - let should_panic = !self.tcx.permits_zero_init(layout); + let should_panic = !self.tcx.permits_zero_init(self.param_env.and(layout)); if should_panic { M::abort( @@ -463,7 +463,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } if intrinsic_name == sym::assert_mem_uninitialized_valid { - let should_panic = !self.tcx.permits_uninit_init(layout); + let should_panic = !self.tcx.permits_uninit_init(self.param_env.and(layout)); if should_panic { M::abort( diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs index 46e7b09a55e10..9d890f0194d39 100644 --- a/compiler/rustc_const_eval/src/lib.rs +++ b/compiler/rustc_const_eval/src/lib.rs @@ -59,7 +59,12 @@ pub fn provide(providers: &mut Providers) { let (param_env, value) = param_env_and_value.into_parts(); const_eval::deref_mir_constant(tcx, param_env, value) }; - providers.permits_uninit_init = - |tcx, ty| util::might_permit_raw_init(tcx, ty, InitKind::UninitMitigated0x01Fill); - providers.permits_zero_init = |tcx, ty| util::might_permit_raw_init(tcx, ty, InitKind::Zero); + providers.permits_uninit_init = |tcx, param_env_and_ty| { + let (param_env, ty) = param_env_and_ty.into_parts(); + util::might_permit_raw_init(tcx, param_env, ty, InitKind::UninitMitigated0x01Fill) + }; + providers.permits_zero_init = |tcx, param_env_and_ty| { + let (param_env, ty) = param_env_and_ty.into_parts(); + util::might_permit_raw_init(tcx, param_env, ty, InitKind::Zero) + }; } diff --git a/compiler/rustc_const_eval/src/util/might_permit_raw_init.rs b/compiler/rustc_const_eval/src/util/might_permit_raw_init.rs index 4ce107ea68d4f..48961b7aac645 100644 --- a/compiler/rustc_const_eval/src/util/might_permit_raw_init.rs +++ b/compiler/rustc_const_eval/src/util/might_permit_raw_init.rs @@ -20,13 +20,14 @@ use crate::interpret::{InterpCx, MemoryKind, OpTy}; /// to the full uninit check). pub fn might_permit_raw_init<'tcx>( tcx: TyCtxt<'tcx>, + param_env: ParamEnv<'tcx>, ty: TyAndLayout<'tcx>, kind: InitKind, ) -> bool { if tcx.sess.opts.unstable_opts.strict_init_checks { might_permit_raw_init_strict(ty, tcx, kind) } else { - let layout_cx = LayoutCx { tcx, param_env: ParamEnv::reveal_all() }; + let layout_cx = LayoutCx { tcx, param_env }; might_permit_raw_init_lax(ty, &layout_cx, kind) } } diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index b3acf815e0c10..7f1bb721b8108 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -2109,12 +2109,12 @@ rustc_queries! { separate_provide_extern } - query permits_uninit_init(key: TyAndLayout<'tcx>) -> bool { - desc { "checking to see if `{}` permits being left uninit", key.ty } + query permits_uninit_init(key: ty::ParamEnvAnd<'tcx, TyAndLayout<'tcx>>) -> bool { + desc { "checking to see if `{}` permits being left uninit", key.value.ty } } - query permits_zero_init(key: TyAndLayout<'tcx>) -> bool { - desc { "checking to see if `{}` permits being left zeroed", key.ty } + query permits_zero_init(key: ty::ParamEnvAnd<'tcx, TyAndLayout<'tcx>>) -> bool { + desc { "checking to see if `{}` permits being left zeroed", key.value.ty } } query compare_impl_const( diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 30073b541ecbd..164e92046155c 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -11,6 +11,7 @@ use crate::ty::{self, InferConst, Lift, Term, TermKind, Ty, TyCtxt}; use rustc_data_structures::functor::IdFunctor; use rustc_hir::def::Namespace; use rustc_index::vec::{Idx, IndexVec}; +use rustc_target::abi::TyAndLayout; use std::fmt; use std::mem::ManuallyDrop; @@ -843,3 +844,9 @@ impl<'tcx> TypeSuperVisitable<'tcx> for ty::UnevaluatedConst<'tcx> { self.substs.visit_with(visitor) } } + +impl<'tcx> TypeVisitable<'tcx> for TyAndLayout<'tcx, Ty<'tcx>> { + fn visit_with>(&self, visitor: &mut V) -> ControlFlow { + visitor.visit_ty(self.ty) + } +} diff --git a/compiler/rustc_mir_transform/src/instcombine.rs b/compiler/rustc_mir_transform/src/instcombine.rs index 1b795479a928e..e1faa7a08d939 100644 --- a/compiler/rustc_mir_transform/src/instcombine.rs +++ b/compiler/rustc_mir_transform/src/instcombine.rs @@ -6,7 +6,7 @@ use rustc_middle::mir::{ BinOp, Body, Constant, ConstantKind, LocalDecls, Operand, Place, ProjectionElem, Rvalue, SourceInfo, Statement, StatementKind, Terminator, TerminatorKind, UnOp, }; -use rustc_middle::ty::{self, layout::TyAndLayout, ParamEnv, SubstsRef, Ty, TyCtxt}; +use rustc_middle::ty::{self, layout::TyAndLayout, ParamEnv, ParamEnvAnd, SubstsRef, Ty, TyCtxt}; use rustc_span::symbol::{sym, Symbol}; pub struct InstCombine; @@ -231,7 +231,7 @@ impl<'tcx> InstCombineContext<'tcx, '_> { // Check this is a foldable intrinsic before we query the layout of our generic parameter let Some(assert_panics) = intrinsic_assert_panics(intrinsic_name) else { return; }; let Ok(layout) = self.tcx.layout_of(self.param_env.and(ty)) else { return; }; - if assert_panics(self.tcx, layout) { + if assert_panics(self.tcx, self.param_env.and(layout)) { // If we know the assert panics, indicate to later opts that the call diverges *target = None; } else { @@ -243,18 +243,25 @@ impl<'tcx> InstCombineContext<'tcx, '_> { fn intrinsic_assert_panics<'tcx>( intrinsic_name: Symbol, -) -> Option, TyAndLayout<'tcx>) -> bool> { - fn inhabited_predicate<'tcx>(_tcx: TyCtxt<'tcx>, layout: TyAndLayout<'tcx>) -> bool { +) -> Option, ParamEnvAnd<'tcx, TyAndLayout<'tcx>>) -> bool> { + fn inhabited_predicate<'tcx>( + _tcx: TyCtxt<'tcx>, + param_env_and_layout: ParamEnvAnd<'tcx, TyAndLayout<'tcx>>, + ) -> bool { + let (_param_env, layout) = param_env_and_layout.into_parts(); layout.abi.is_uninhabited() } - fn zero_valid_predicate<'tcx>(tcx: TyCtxt<'tcx>, layout: TyAndLayout<'tcx>) -> bool { - !tcx.permits_zero_init(layout) + fn zero_valid_predicate<'tcx>( + tcx: TyCtxt<'tcx>, + param_env_and_layout: ParamEnvAnd<'tcx, TyAndLayout<'tcx>>, + ) -> bool { + !tcx.permits_zero_init(param_env_and_layout) } fn mem_uninitialized_valid_predicate<'tcx>( tcx: TyCtxt<'tcx>, - layout: TyAndLayout<'tcx>, + param_env_and_layout: ParamEnvAnd<'tcx, TyAndLayout<'tcx>>, ) -> bool { - !tcx.permits_uninit_init(layout) + !tcx.permits_uninit_init(param_env_and_layout) } match intrinsic_name { From e65b36110f943118b7e50c4e39e26ad1f07d8552 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 23 Jan 2023 17:10:54 -0700 Subject: [PATCH 325/500] rustdoc: rearrange HTML in primitive reference links This patch avoids hard-to-click single character links by making the generic part of the link: Before:
&T After: &T --- src/librustdoc/html/format.rs | 10 ++-------- tests/rustdoc/whitespace-after-where-clause.enum.html | 2 +- tests/rustdoc/whitespace-after-where-clause.enum2.html | 2 +- .../rustdoc/whitespace-after-where-clause.struct.html | 2 +- .../rustdoc/whitespace-after-where-clause.struct2.html | 2 +- 5 files changed, 6 insertions(+), 12 deletions(-) diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index d3dc4065dfc72..33404a7683597 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -1064,14 +1064,8 @@ fn fmt_type<'cx>( fmt_type(ty, f, use_absolute, cx)?; write!(f, ")") } - clean::Generic(..) => { - primitive_link( - f, - PrimitiveType::Reference, - &format!("{}{}{}", amp, lt, m), - cx, - )?; - fmt_type(ty, f, use_absolute, cx) + clean::Generic(name) => { + primitive_link(f, PrimitiveType::Reference, &format!("{amp}{lt}{m}{name}"), cx) } _ => { write!(f, "{}{}{}", amp, lt, m)?; diff --git a/tests/rustdoc/whitespace-after-where-clause.enum.html b/tests/rustdoc/whitespace-after-where-clause.enum.html index 20bde549a0378..eeb22878f3c63 100644 --- a/tests/rustdoc/whitespace-after-where-clause.enum.html +++ b/tests/rustdoc/whitespace-after-where-clause.enum.html @@ -1,4 +1,4 @@
pub enum Cow<'a, B>where
    B: ToOwned<dyn Clone> + ?Sized + 'a,
{ - Borrowed(&'a B), + Borrowed(&'a B), Whatever(u32), }
\ No newline at end of file diff --git a/tests/rustdoc/whitespace-after-where-clause.enum2.html b/tests/rustdoc/whitespace-after-where-clause.enum2.html index d9fc0c22309db..c8037c2a8df5a 100644 --- a/tests/rustdoc/whitespace-after-where-clause.enum2.html +++ b/tests/rustdoc/whitespace-after-where-clause.enum2.html @@ -1,4 +1,4 @@
pub enum Cow2<'a, B: ?Sized + ToOwned<dyn Clone> + 'a> {
-    Borrowed(&'a B),
+    Borrowed(&'a B),
     Whatever(u32),
 }
\ No newline at end of file diff --git a/tests/rustdoc/whitespace-after-where-clause.struct.html b/tests/rustdoc/whitespace-after-where-clause.struct.html index f375265d7c183..5892270b2f930 100644 --- a/tests/rustdoc/whitespace-after-where-clause.struct.html +++ b/tests/rustdoc/whitespace-after-where-clause.struct.html @@ -1,4 +1,4 @@
pub struct Struct<'a, B>where
    B: ToOwned<dyn Clone> + ?Sized + 'a,
{ - pub a: &'a B, + pub a: &'a B, pub b: u32, }
\ No newline at end of file diff --git a/tests/rustdoc/whitespace-after-where-clause.struct2.html b/tests/rustdoc/whitespace-after-where-clause.struct2.html index 1c59962eb1c58..d3952b0c56699 100644 --- a/tests/rustdoc/whitespace-after-where-clause.struct2.html +++ b/tests/rustdoc/whitespace-after-where-clause.struct2.html @@ -1,4 +1,4 @@
pub struct Struct2<'a, B: ?Sized + ToOwned<dyn Clone> + 'a> {
-    pub a: &'a B,
+    pub a: &'a B,
     pub b: u32,
 }
\ No newline at end of file From 18dd0757dbef84611fc0f1f522b15913248b8541 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Mon, 23 Jan 2023 21:44:03 -0600 Subject: [PATCH 326/500] chore: bump toolchain --- rust-toolchain | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust-toolchain b/rust-toolchain index f8ed76d2e6f9e..22283b3d62002 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-08-06" -components = ["rustc-dev"] +channel = "nightly-2023-01-24" +components = ["llvm-tools", "rustc-dev"] From a8b77cfe5464e29b25389593ced9d080bf0dd6c8 Mon Sep 17 00:00:00 2001 From: Edward Shen Date: Mon, 23 Jan 2023 20:31:45 -0800 Subject: [PATCH 327/500] Add suggestion to remove if in let...else block Adds an additional hint to failures where we encounter an else keyword while we're parsing an if-let block. This is likely that the user has accidentally mixed if-let and let...else together. --- .../locales/en-US/parse.ftl | 1 + compiler/rustc_parse/src/errors.rs | 11 ++++++- compiler/rustc_parse/src/parser/expr.rs | 33 +++++++++++-------- tests/ui/let-else/accidental-if.rs | 6 ++++ tests/ui/let-else/accidental-if.stderr | 19 +++++++++++ ...e-does-not-interact-with-let-chains.stderr | 5 +++ 6 files changed, 61 insertions(+), 14 deletions(-) create mode 100644 tests/ui/let-else/accidental-if.rs create mode 100644 tests/ui/let-else/accidental-if.stderr diff --git a/compiler/rustc_error_messages/locales/en-US/parse.ftl b/compiler/rustc_error_messages/locales/en-US/parse.ftl index 8f063f5082c95..a3e2002da781c 100644 --- a/compiler/rustc_error_messages/locales/en-US/parse.ftl +++ b/compiler/rustc_error_messages/locales/en-US/parse.ftl @@ -238,6 +238,7 @@ parse_const_let_mutually_exclusive = `const` and `let` are mutually exclusive parse_invalid_expression_in_let_else = a `{$operator}` expression cannot be directly assigned in `let...else` parse_invalid_curly_in_let_else = right curly brace `{"}"}` before `else` in a `let...else` statement not allowed +parse_extra_if_in_let_else = remove the `if` if you meant to write a `let...else` statement parse_compound_assignment_expression_in_let = can't reassign to an uninitialized variable .suggestion = initialize the variable diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index 06b970ad97977..40763da0bb547 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -337,7 +337,9 @@ pub(crate) struct IfExpressionMissingThenBlock { #[primary_span] pub if_span: Span, #[subdiagnostic] - pub sub: IfExpressionMissingThenBlockSub, + pub missing_then_block_sub: IfExpressionMissingThenBlockSub, + #[subdiagnostic] + pub let_else_sub: Option, } #[derive(Subdiagnostic)] @@ -348,6 +350,13 @@ pub(crate) enum IfExpressionMissingThenBlockSub { AddThenBlock(#[primary_span] Span), } +#[derive(Subdiagnostic)] +#[help(parse_extra_if_in_let_else)] +pub(crate) struct IfExpressionLetSomeSub { + #[primary_span] + pub if_span: Span, +} + #[derive(Diagnostic)] #[diag(parse_if_expression_missing_condition)] pub(crate) struct IfExpressionMissingCondition { diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index bf93a89f06555..3225a309a319b 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -11,15 +11,15 @@ use crate::errors::{ ComparisonOrShiftInterpretedAsGenericSugg, DoCatchSyntaxRemoved, DotDotDot, EqFieldInit, ExpectedElseBlock, ExpectedEqForLetExpr, ExpectedExpressionFoundLet, FieldExpressionWithGeneric, FloatLiteralRequiresIntegerPart, FoundExprWouldBeStmt, - IfExpressionMissingCondition, IfExpressionMissingThenBlock, IfExpressionMissingThenBlockSub, - InvalidBlockMacroSegment, InvalidComparisonOperator, InvalidComparisonOperatorSub, - InvalidInterpolatedExpression, InvalidLiteralSuffixOnTupleIndex, InvalidLogicalOperator, - InvalidLogicalOperatorSub, LabeledLoopInBreak, LeadingPlusNotSupported, LeftArrowOperator, - LifetimeInBorrowExpression, MacroInvocationWithQualifiedPath, MalformedLoopLabel, - MatchArmBodyWithoutBraces, MatchArmBodyWithoutBracesSugg, MissingCommaAfterMatchArm, - MissingDotDot, MissingInInForLoop, MissingInInForLoopSub, MissingSemicolonBeforeArray, - NoFieldsForFnCall, NotAsNegationOperator, NotAsNegationOperatorSub, - OuterAttributeNotAllowedOnIfElse, ParenthesesWithStructFields, + IfExpressionLetSomeSub, IfExpressionMissingCondition, IfExpressionMissingThenBlock, + IfExpressionMissingThenBlockSub, InvalidBlockMacroSegment, InvalidComparisonOperator, + InvalidComparisonOperatorSub, InvalidInterpolatedExpression, InvalidLiteralSuffixOnTupleIndex, + InvalidLogicalOperator, InvalidLogicalOperatorSub, LabeledLoopInBreak, LeadingPlusNotSupported, + LeftArrowOperator, LifetimeInBorrowExpression, MacroInvocationWithQualifiedPath, + MalformedLoopLabel, MatchArmBodyWithoutBraces, MatchArmBodyWithoutBracesSugg, + MissingCommaAfterMatchArm, MissingDotDot, MissingInInForLoop, MissingInInForLoopSub, + MissingSemicolonBeforeArray, NoFieldsForFnCall, NotAsNegationOperator, + NotAsNegationOperatorSub, OuterAttributeNotAllowedOnIfElse, ParenthesesWithStructFields, RequireColonAfterLabeledExpression, ShiftInterpretedAsGeneric, StructLiteralNotAllowedHere, StructLiteralNotAllowedHereSugg, TildeAsUnaryOperator, UnexpectedIfWithIf, UnexpectedTokenAfterLabel, UnexpectedTokenAfterLabelSugg, WrapExpressionInParentheses, @@ -2251,9 +2251,10 @@ impl<'a> Parser<'a> { if let ExprKind::Block(_, None) = right.kind => { self.sess.emit_err(IfExpressionMissingThenBlock { if_span: lo, - sub: IfExpressionMissingThenBlockSub::UnfinishedCondition( - cond_span.shrink_to_lo().to(*binop_span) - ), + missing_then_block_sub: + IfExpressionMissingThenBlockSub::UnfinishedCondition(cond_span.shrink_to_lo().to(*binop_span)), + let_else_sub: None, + }); std::mem::replace(right, this.mk_expr_err(binop_span.shrink_to_hi())) }, @@ -2279,9 +2280,15 @@ impl<'a> Parser<'a> { if let Some(block) = recover_block_from_condition(self) { block } else { + let let_else_sub = matches!(cond.kind, ExprKind::Let(..)) + .then(|| IfExpressionLetSomeSub { if_span: lo }); + self.sess.emit_err(IfExpressionMissingThenBlock { if_span: lo, - sub: IfExpressionMissingThenBlockSub::AddThenBlock(cond_span.shrink_to_hi()), + missing_then_block_sub: IfExpressionMissingThenBlockSub::AddThenBlock( + cond_span.shrink_to_hi(), + ), + let_else_sub, }); self.mk_block_err(cond_span.shrink_to_hi()) } diff --git a/tests/ui/let-else/accidental-if.rs b/tests/ui/let-else/accidental-if.rs new file mode 100644 index 0000000000000..3fba630435c71 --- /dev/null +++ b/tests/ui/let-else/accidental-if.rs @@ -0,0 +1,6 @@ +fn main() { + let x = Some(123); + if let Some(y) = x else { //~ ERROR this `if` expression is missing a block + return; + }; +} diff --git a/tests/ui/let-else/accidental-if.stderr b/tests/ui/let-else/accidental-if.stderr new file mode 100644 index 0000000000000..5474a67aac45a --- /dev/null +++ b/tests/ui/let-else/accidental-if.stderr @@ -0,0 +1,19 @@ +error: this `if` expression is missing a block after the condition + --> $DIR/accidental-if.rs:3:5 + | +LL | if let Some(y) = x else { + | ^^ + | +help: add a block here + --> $DIR/accidental-if.rs:3:23 + | +LL | if let Some(y) = x else { + | ^ +help: remove the `if` if you meant to write a `let...else` statement + --> $DIR/accidental-if.rs:3:5 + | +LL | if let Some(y) = x else { + | ^^ + +error: aborting due to previous error + diff --git a/tests/ui/rfc-2497-if-let-chains/ensure-that-let-else-does-not-interact-with-let-chains.stderr b/tests/ui/rfc-2497-if-let-chains/ensure-that-let-else-does-not-interact-with-let-chains.stderr index 498a112fa9bb3..f34ccecdd45e6 100644 --- a/tests/ui/rfc-2497-if-let-chains/ensure-that-let-else-does-not-interact-with-let-chains.stderr +++ b/tests/ui/rfc-2497-if-let-chains/ensure-that-let-else-does-not-interact-with-let-chains.stderr @@ -37,6 +37,11 @@ help: add a block here | LL | if let Some(n) = opt else { | ^ +help: remove the `if` if you meant to write a `let...else` statement + --> $DIR/ensure-that-let-else-does-not-interact-with-let-chains.rs:24:5 + | +LL | if let Some(n) = opt else { + | ^^ error: this `if` expression is missing a block after the condition --> $DIR/ensure-that-let-else-does-not-interact-with-let-chains.rs:28:5 From a2d1cb2c22016ae003ab51d9654746cc4fc5200a Mon Sep 17 00:00:00 2001 From: dimi Date: Tue, 24 May 2022 23:56:19 +0200 Subject: [PATCH 328/500] impl DispatchFromDyn for Cell and UnsafeCell --- library/core/src/cell.rs | 33 ++++++++++++++++++- ...itrary_self_types_pointers_and_wrappers.rs | 22 +++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index 129213fde7491..7f109491350f0 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -196,7 +196,7 @@ use crate::cmp::Ordering; use crate::fmt::{self, Debug, Display}; use crate::marker::{PhantomData, Unsize}; use crate::mem; -use crate::ops::{CoerceUnsized, Deref, DerefMut}; +use crate::ops::{CoerceUnsized, Deref, DerefMut, DispatchFromDyn}; use crate::ptr::{self, NonNull}; mod lazy; @@ -571,6 +571,16 @@ impl Cell { #[unstable(feature = "coerce_unsized", issue = "18598")] impl, U> CoerceUnsized> for Cell {} +// Allow types that wrap `Cell` to also implement `DispatchFromDyn` +// and become object safe method receivers. +// Note that currently `Cell` itself cannot be a method receiver +// because it does not implement Deref. +// In other words: +// `self: Cell<&Self>` won't work +// `self: CellWrapper` becomes possible +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +impl, U> DispatchFromDyn> for Cell {} + impl Cell<[T]> { /// Returns a `&[Cell]` from a `&Cell<[T]>` /// @@ -2078,6 +2088,16 @@ impl const From for UnsafeCell { #[unstable(feature = "coerce_unsized", issue = "18598")] impl, U> CoerceUnsized> for UnsafeCell {} +// Allow types that wrap `UnsafeCell` to also implement `DispatchFromDyn` +// and become object safe method receivers. +// Note that currently `UnsafeCell` itself cannot be a method receiver +// because it does not implement Deref. +// In other words: +// `self: UnsafeCell<&Self>` won't work +// `self: UnsafeCellWrapper` becomes possible +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +impl, U> DispatchFromDyn> for UnsafeCell {} + /// [`UnsafeCell`], but [`Sync`]. /// /// This is just an `UnsafeCell`, except it implements `Sync` @@ -2169,6 +2189,17 @@ impl const From for SyncUnsafeCell { //#[unstable(feature = "sync_unsafe_cell", issue = "95439")] impl, U> CoerceUnsized> for SyncUnsafeCell {} +// Allow types that wrap `SyncUnsafeCell` to also implement `DispatchFromDyn` +// and become object safe method receivers. +// Note that currently `SyncUnsafeCell` itself cannot be a method receiver +// because it does not implement Deref. +// In other words: +// `self: SyncUnsafeCell<&Self>` won't work +// `self: SyncUnsafeCellWrapper` becomes possible +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +//#[unstable(feature = "sync_unsafe_cell", issue = "95439")] +impl, U> DispatchFromDyn> for SyncUnsafeCell {} + #[allow(unused)] fn assert_coerce_unsized( a: UnsafeCell<&i32>, diff --git a/tests/ui/self/arbitrary_self_types_pointers_and_wrappers.rs b/tests/ui/self/arbitrary_self_types_pointers_and_wrappers.rs index 65fec3becacee..91aacedfc5778 100644 --- a/tests/ui/self/arbitrary_self_types_pointers_and_wrappers.rs +++ b/tests/ui/self/arbitrary_self_types_pointers_and_wrappers.rs @@ -3,6 +3,7 @@ #![feature(rustc_attrs)] use std::{ + cell::Cell, ops::{Deref, CoerceUnsized, DispatchFromDyn}, marker::Unsize, }; @@ -20,6 +21,20 @@ impl Deref for Ptr { impl + ?Sized, U: ?Sized> CoerceUnsized> for Ptr {} impl + ?Sized, U: ?Sized> DispatchFromDyn> for Ptr {} + +struct CellPtr<'a, T: ?Sized>(Cell<&'a T>); + +impl<'a, T: ?Sized> Deref for CellPtr<'a, T> { + type Target = T; + + fn deref(&self) -> &T { + self.0.get() + } +} + +impl<'a, T: Unsize + ?Sized, U: ?Sized> CoerceUnsized> for CellPtr<'a, T> {} +impl<'a, T: Unsize + ?Sized, U: ?Sized> DispatchFromDyn> for CellPtr<'a, T> {} + struct Wrapper(T); impl Deref for Wrapper { @@ -42,6 +57,7 @@ trait Trait { fn ptr_wrapper(self: Ptr>) -> i32; fn wrapper_ptr(self: Wrapper>) -> i32; fn wrapper_ptr_wrapper(self: Wrapper>>) -> i32; + fn cell(self: CellPtr) -> i32; } impl Trait for i32 { @@ -54,6 +70,9 @@ impl Trait for i32 { fn wrapper_ptr_wrapper(self: Wrapper>>) -> i32 { ***self } + fn cell(self: CellPtr) -> i32 { + *self + } } fn main() { @@ -65,4 +84,7 @@ fn main() { let wpw = Wrapper(Ptr(Box::new(Wrapper(7)))) as Wrapper>>; assert_eq!(wpw.wrapper_ptr_wrapper(), 7); + + let c = CellPtr(Cell::new(&8)) as CellPtr; + assert_eq!(c.cell(), 8); } From e6e93e021e7be6c9ae400145a2aa235f16f9eb45 Mon Sep 17 00:00:00 2001 From: lcnr Date: Tue, 24 Jan 2023 12:41:18 +0100 Subject: [PATCH 329/500] add test where we ignore hr implied bounds --- tests/ui/regions/higher-ranked-implied.rs | 14 +++++++++++++ tests/ui/regions/higher-ranked-implied.stderr | 21 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 tests/ui/regions/higher-ranked-implied.rs create mode 100644 tests/ui/regions/higher-ranked-implied.stderr diff --git a/tests/ui/regions/higher-ranked-implied.rs b/tests/ui/regions/higher-ranked-implied.rs new file mode 100644 index 0000000000000..103884c50313f --- /dev/null +++ b/tests/ui/regions/higher-ranked-implied.rs @@ -0,0 +1,14 @@ +// FIXME: This test should pass as the first two fields add implied bounds that +// `'a` is equal to `'b` while the last one should simply use that fact. With +// the current implementation this errors. We have to be careful as implied bounds +// are only sound if they're also correctly checked. + +struct Inv(*mut T); // `T` is invariant. +type A = for<'a, 'b> fn(Inv<&'a &'b ()>, Inv<&'b &'a ()>, Inv<&'a ()>); +type B = for<'a, 'b> fn(Inv<&'a &'b ()>, Inv<&'b &'a ()>, Inv<&'b ()>); + +fn main() { + let x: A = |_, _, _| (); + let y: B = x; //~ ERROR mismatched types + let _: A = y; //~ ERROR mismatched types +} diff --git a/tests/ui/regions/higher-ranked-implied.stderr b/tests/ui/regions/higher-ranked-implied.stderr new file mode 100644 index 0000000000000..9d80eacd7c320 --- /dev/null +++ b/tests/ui/regions/higher-ranked-implied.stderr @@ -0,0 +1,21 @@ +error[E0308]: mismatched types + --> $DIR/higher-ranked-implied.rs:12:16 + | +LL | let y: B = x; + | ^ one type is more general than the other + | + = note: expected fn pointer `for<'a, 'b> fn(Inv<&'a &'b ()>, Inv<&'b &'a ()>, Inv<&'b ()>)` + found fn pointer `for<'a, 'b> fn(Inv<&'a &'b ()>, Inv<&'b &'a ()>, Inv<&'a ()>)` + +error[E0308]: mismatched types + --> $DIR/higher-ranked-implied.rs:13:16 + | +LL | let _: A = y; + | ^ one type is more general than the other + | + = note: expected fn pointer `for<'a, 'b> fn(Inv<&'a &'b ()>, Inv<&'b &'a ()>, Inv<&'a ()>)` + found fn pointer `for<'a, 'b> fn(Inv<&'a &'b ()>, Inv<&'b &'a ()>, Inv<&'b ()>)` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0308`. From ad7393668f7f54372b974baa37854601756bacc3 Mon Sep 17 00:00:00 2001 From: Jakob Degen Date: Tue, 24 Jan 2023 04:13:52 -0800 Subject: [PATCH 330/500] Delete `SimplifyArmIdentity` and `SimplifyBranchSame` mir opts --- compiler/rustc_mir_transform/src/lib.rs | 3 - .../rustc_mir_transform/src/simplify_try.rs | 822 ------------------ ..._regression.encode.SimplifyBranchSame.diff | 29 - tests/mir-opt/76803_regression.rs | 19 - .../issue_73223.main.SimplifyArmIdentity.diff | 156 ---- tests/mir-opt/issue_73223.rs | 12 - 6 files changed, 1041 deletions(-) delete mode 100644 compiler/rustc_mir_transform/src/simplify_try.rs delete mode 100644 tests/mir-opt/76803_regression.encode.SimplifyBranchSame.diff delete mode 100644 tests/mir-opt/76803_regression.rs delete mode 100644 tests/mir-opt/issue_73223.main.SimplifyArmIdentity.diff delete mode 100644 tests/mir-opt/issue_73223.rs diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 20b7fdcfe6d4d..4a598862d10f8 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -90,7 +90,6 @@ mod shim; pub mod simplify; mod simplify_branches; mod simplify_comparison_integral; -mod simplify_try; mod sroa; mod uninhabited_enum_branching; mod unreachable_prop; @@ -567,8 +566,6 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { &o1(simplify_branches::SimplifyConstCondition::new("after-const-prop")), &early_otherwise_branch::EarlyOtherwiseBranch, &simplify_comparison_integral::SimplifyComparisonIntegral, - &simplify_try::SimplifyArmIdentity, - &simplify_try::SimplifyBranchSame, &dead_store_elimination::DeadStoreElimination, &dest_prop::DestinationPropagation, &o1(simplify_branches::SimplifyConstCondition::new("final")), diff --git a/compiler/rustc_mir_transform/src/simplify_try.rs b/compiler/rustc_mir_transform/src/simplify_try.rs deleted file mode 100644 index e4f3ace9a93da..0000000000000 --- a/compiler/rustc_mir_transform/src/simplify_try.rs +++ /dev/null @@ -1,822 +0,0 @@ -//! The general point of the optimizations provided here is to simplify something like: -//! -//! ```rust -//! # fn foo(x: Result) -> Result { -//! match x { -//! Ok(x) => Ok(x), -//! Err(x) => Err(x) -//! } -//! # } -//! ``` -//! -//! into just `x`. - -use crate::{simplify, MirPass}; -use itertools::Itertools as _; -use rustc_index::{bit_set::BitSet, vec::IndexVec}; -use rustc_middle::mir::visit::{NonUseContext, PlaceContext, Visitor}; -use rustc_middle::mir::*; -use rustc_middle::ty::{self, List, Ty, TyCtxt}; -use rustc_target::abi::VariantIdx; -use std::iter::{once, Enumerate, Peekable}; -use std::slice::Iter; - -/// Simplifies arms of form `Variant(x) => Variant(x)` to just a move. -/// -/// This is done by transforming basic blocks where the statements match: -/// -/// ```ignore (MIR) -/// _LOCAL_TMP = ((_LOCAL_1 as Variant ).FIELD: TY ); -/// _TMP_2 = _LOCAL_TMP; -/// ((_LOCAL_0 as Variant).FIELD: TY) = move _TMP_2; -/// discriminant(_LOCAL_0) = VAR_IDX; -/// ``` -/// -/// into: -/// -/// ```ignore (MIR) -/// _LOCAL_0 = move _LOCAL_1 -/// ``` -pub struct SimplifyArmIdentity; - -#[derive(Debug)] -struct ArmIdentityInfo<'tcx> { - /// Storage location for the variant's field - local_temp_0: Local, - /// Storage location holding the variant being read from - local_1: Local, - /// The variant field being read from - vf_s0: VarField<'tcx>, - /// Index of the statement which loads the variant being read - get_variant_field_stmt: usize, - - /// Tracks each assignment to a temporary of the variant's field - field_tmp_assignments: Vec<(Local, Local)>, - - /// Storage location holding the variant's field that was read from - local_tmp_s1: Local, - /// Storage location holding the enum that we are writing to - local_0: Local, - /// The variant field being written to - vf_s1: VarField<'tcx>, - - /// Storage location that the discriminant is being written to - set_discr_local: Local, - /// The variant being written - set_discr_var_idx: VariantIdx, - - /// Index of the statement that should be overwritten as a move - stmt_to_overwrite: usize, - /// SourceInfo for the new move - source_info: SourceInfo, - - /// Indices of matching Storage{Live,Dead} statements encountered. - /// (StorageLive index,, StorageDead index, Local) - storage_stmts: Vec<(usize, usize, Local)>, - - /// The statements that should be removed (turned into nops) - stmts_to_remove: Vec, - - /// Indices of debug variables that need to be adjusted to point to - // `{local_0}.{dbg_projection}`. - dbg_info_to_adjust: Vec, - - /// The projection used to rewrite debug info. - dbg_projection: &'tcx List>, -} - -fn get_arm_identity_info<'a, 'tcx>( - stmts: &'a [Statement<'tcx>], - locals_count: usize, - debug_info: &'a [VarDebugInfo<'tcx>], -) -> Option> { - // This can't possibly match unless there are at least 3 statements in the block - // so fail fast on tiny blocks. - if stmts.len() < 3 { - return None; - } - - let mut tmp_assigns = Vec::new(); - let mut nop_stmts = Vec::new(); - let mut storage_stmts = Vec::new(); - let mut storage_live_stmts = Vec::new(); - let mut storage_dead_stmts = Vec::new(); - - type StmtIter<'a, 'tcx> = Peekable>>>; - - fn is_storage_stmt(stmt: &Statement<'_>) -> bool { - matches!(stmt.kind, StatementKind::StorageLive(_) | StatementKind::StorageDead(_)) - } - - /// Eats consecutive Statements which match `test`, performing the specified `action` for each. - /// The iterator `stmt_iter` is not advanced if none were matched. - fn try_eat<'a, 'tcx>( - stmt_iter: &mut StmtIter<'a, 'tcx>, - test: impl Fn(&'a Statement<'tcx>) -> bool, - mut action: impl FnMut(usize, &'a Statement<'tcx>), - ) { - while stmt_iter.peek().map_or(false, |(_, stmt)| test(stmt)) { - let (idx, stmt) = stmt_iter.next().unwrap(); - - action(idx, stmt); - } - } - - /// Eats consecutive `StorageLive` and `StorageDead` Statements. - /// The iterator `stmt_iter` is not advanced if none were found. - fn try_eat_storage_stmts( - stmt_iter: &mut StmtIter<'_, '_>, - storage_live_stmts: &mut Vec<(usize, Local)>, - storage_dead_stmts: &mut Vec<(usize, Local)>, - ) { - try_eat(stmt_iter, is_storage_stmt, |idx, stmt| { - if let StatementKind::StorageLive(l) = stmt.kind { - storage_live_stmts.push((idx, l)); - } else if let StatementKind::StorageDead(l) = stmt.kind { - storage_dead_stmts.push((idx, l)); - } - }) - } - - fn is_tmp_storage_stmt(stmt: &Statement<'_>) -> bool { - use rustc_middle::mir::StatementKind::Assign; - if let Assign(box (place, Rvalue::Use(Operand::Copy(p) | Operand::Move(p)))) = &stmt.kind { - place.as_local().is_some() && p.as_local().is_some() - } else { - false - } - } - - /// Eats consecutive `Assign` Statements. - // The iterator `stmt_iter` is not advanced if none were found. - fn try_eat_assign_tmp_stmts( - stmt_iter: &mut StmtIter<'_, '_>, - tmp_assigns: &mut Vec<(Local, Local)>, - nop_stmts: &mut Vec, - ) { - try_eat(stmt_iter, is_tmp_storage_stmt, |idx, stmt| { - use rustc_middle::mir::StatementKind::Assign; - if let Assign(box (place, Rvalue::Use(Operand::Copy(p) | Operand::Move(p)))) = - &stmt.kind - { - tmp_assigns.push((place.as_local().unwrap(), p.as_local().unwrap())); - nop_stmts.push(idx); - } - }) - } - - fn find_storage_live_dead_stmts_for_local( - local: Local, - stmts: &[Statement<'_>], - ) -> Option<(usize, usize)> { - trace!("looking for {:?}", local); - let mut storage_live_stmt = None; - let mut storage_dead_stmt = None; - for (idx, stmt) in stmts.iter().enumerate() { - if stmt.kind == StatementKind::StorageLive(local) { - storage_live_stmt = Some(idx); - } else if stmt.kind == StatementKind::StorageDead(local) { - storage_dead_stmt = Some(idx); - } - } - - Some((storage_live_stmt?, storage_dead_stmt.unwrap_or(usize::MAX))) - } - - // Try to match the expected MIR structure with the basic block we're processing. - // We want to see something that looks like: - // ``` - // (StorageLive(_) | StorageDead(_));* - // _LOCAL_INTO = ((_LOCAL_FROM as Variant).FIELD: TY); - // (StorageLive(_) | StorageDead(_));* - // (tmp_n+1 = tmp_n);* - // (StorageLive(_) | StorageDead(_));* - // (tmp_n+1 = tmp_n);* - // ((LOCAL_FROM as Variant).FIELD: TY) = move tmp; - // discriminant(LOCAL_FROM) = VariantIdx; - // (StorageLive(_) | StorageDead(_));* - // ``` - let mut stmt_iter = stmts.iter().enumerate().peekable(); - - try_eat_storage_stmts(&mut stmt_iter, &mut storage_live_stmts, &mut storage_dead_stmts); - - let (get_variant_field_stmt, stmt) = stmt_iter.next()?; - let (local_tmp_s0, local_1, vf_s0, dbg_projection) = match_get_variant_field(stmt)?; - - try_eat_storage_stmts(&mut stmt_iter, &mut storage_live_stmts, &mut storage_dead_stmts); - - try_eat_assign_tmp_stmts(&mut stmt_iter, &mut tmp_assigns, &mut nop_stmts); - - try_eat_storage_stmts(&mut stmt_iter, &mut storage_live_stmts, &mut storage_dead_stmts); - - try_eat_assign_tmp_stmts(&mut stmt_iter, &mut tmp_assigns, &mut nop_stmts); - - let (idx, stmt) = stmt_iter.next()?; - let (local_tmp_s1, local_0, vf_s1) = match_set_variant_field(stmt)?; - nop_stmts.push(idx); - - let (idx, stmt) = stmt_iter.next()?; - let (set_discr_local, set_discr_var_idx) = match_set_discr(stmt)?; - let discr_stmt_source_info = stmt.source_info; - nop_stmts.push(idx); - - try_eat_storage_stmts(&mut stmt_iter, &mut storage_live_stmts, &mut storage_dead_stmts); - - for (live_idx, live_local) in storage_live_stmts { - if let Some(i) = storage_dead_stmts.iter().rposition(|(_, l)| *l == live_local) { - let (dead_idx, _) = storage_dead_stmts.swap_remove(i); - storage_stmts.push((live_idx, dead_idx, live_local)); - - if live_local == local_tmp_s0 { - nop_stmts.push(get_variant_field_stmt); - } - } - } - // We sort primitive usize here so we can use unstable sort - nop_stmts.sort_unstable(); - - // Use one of the statements we're going to discard between the point - // where the storage location for the variant field becomes live and - // is killed. - let (live_idx, dead_idx) = find_storage_live_dead_stmts_for_local(local_tmp_s0, stmts)?; - let stmt_to_overwrite = - nop_stmts.iter().find(|stmt_idx| live_idx < **stmt_idx && **stmt_idx < dead_idx); - - let mut tmp_assigned_vars = BitSet::new_empty(locals_count); - for (l, r) in &tmp_assigns { - tmp_assigned_vars.insert(*l); - tmp_assigned_vars.insert(*r); - } - - let dbg_info_to_adjust: Vec<_> = debug_info - .iter() - .enumerate() - .filter_map(|(i, var_info)| { - if let VarDebugInfoContents::Place(p) = var_info.value { - if tmp_assigned_vars.contains(p.local) { - return Some(i); - } - } - - None - }) - .collect(); - - Some(ArmIdentityInfo { - local_temp_0: local_tmp_s0, - local_1, - vf_s0, - get_variant_field_stmt, - field_tmp_assignments: tmp_assigns, - local_tmp_s1, - local_0, - vf_s1, - set_discr_local, - set_discr_var_idx, - stmt_to_overwrite: *stmt_to_overwrite?, - source_info: discr_stmt_source_info, - storage_stmts, - stmts_to_remove: nop_stmts, - dbg_info_to_adjust, - dbg_projection, - }) -} - -fn optimization_applies<'tcx>( - opt_info: &ArmIdentityInfo<'tcx>, - local_decls: &IndexVec>, - local_uses: &IndexVec, - var_debug_info: &[VarDebugInfo<'tcx>], -) -> bool { - trace!("testing if optimization applies..."); - - // FIXME(wesleywiser): possibly relax this restriction? - if opt_info.local_0 == opt_info.local_1 { - trace!("NO: moving into ourselves"); - return false; - } else if opt_info.vf_s0 != opt_info.vf_s1 { - trace!("NO: the field-and-variant information do not match"); - return false; - } else if local_decls[opt_info.local_0].ty != local_decls[opt_info.local_1].ty { - // FIXME(Centril,oli-obk): possibly relax to same layout? - trace!("NO: source and target locals have different types"); - return false; - } else if (opt_info.local_0, opt_info.vf_s0.var_idx) - != (opt_info.set_discr_local, opt_info.set_discr_var_idx) - { - trace!("NO: the discriminants do not match"); - return false; - } - - // Verify the assignment chain consists of the form b = a; c = b; d = c; etc... - if opt_info.field_tmp_assignments.is_empty() { - trace!("NO: no assignments found"); - return false; - } - let mut last_assigned_to = opt_info.field_tmp_assignments[0].1; - let source_local = last_assigned_to; - for (l, r) in &opt_info.field_tmp_assignments { - if *r != last_assigned_to { - trace!("NO: found unexpected assignment {:?} = {:?}", l, r); - return false; - } - - last_assigned_to = *l; - } - - // Check that the first and last used locals are only used twice - // since they are of the form: - // - // ``` - // _first = ((_x as Variant).n: ty); - // _n = _first; - // ... - // ((_y as Variant).n: ty) = _n; - // discriminant(_y) = z; - // ``` - for (l, r) in &opt_info.field_tmp_assignments { - if local_uses[*l] != 2 { - warn!("NO: FAILED assignment chain local {:?} was used more than twice", l); - return false; - } else if local_uses[*r] != 2 { - warn!("NO: FAILED assignment chain local {:?} was used more than twice", r); - return false; - } - } - - // Check that debug info only points to full Locals and not projections. - for dbg_idx in &opt_info.dbg_info_to_adjust { - let dbg_info = &var_debug_info[*dbg_idx]; - if let VarDebugInfoContents::Place(p) = dbg_info.value { - if !p.projection.is_empty() { - trace!("NO: debug info for {:?} had a projection {:?}", dbg_info.name, p); - return false; - } - } - } - - if source_local != opt_info.local_temp_0 { - trace!( - "NO: start of assignment chain does not match enum variant temp: {:?} != {:?}", - source_local, - opt_info.local_temp_0 - ); - return false; - } else if last_assigned_to != opt_info.local_tmp_s1 { - trace!( - "NO: end of assignment chain does not match written enum temp: {:?} != {:?}", - last_assigned_to, - opt_info.local_tmp_s1 - ); - return false; - } - - trace!("SUCCESS: optimization applies!"); - true -} - -impl<'tcx> MirPass<'tcx> for SimplifyArmIdentity { - fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { - // FIXME(77359): This optimization can result in unsoundness. - if !tcx.sess.opts.unstable_opts.unsound_mir_opts { - return; - } - - let source = body.source; - trace!("running SimplifyArmIdentity on {:?}", source); - - let local_uses = LocalUseCounter::get_local_uses(body); - for bb in body.basic_blocks.as_mut() { - if let Some(opt_info) = - get_arm_identity_info(&bb.statements, body.local_decls.len(), &body.var_debug_info) - { - trace!("got opt_info = {:#?}", opt_info); - if !optimization_applies( - &opt_info, - &body.local_decls, - &local_uses, - &body.var_debug_info, - ) { - debug!("optimization skipped for {:?}", source); - continue; - } - - // Also remove unused Storage{Live,Dead} statements which correspond - // to temps used previously. - for (live_idx, dead_idx, local) in &opt_info.storage_stmts { - // The temporary that we've read the variant field into is scoped to this block, - // so we can remove the assignment. - if *local == opt_info.local_temp_0 { - bb.statements[opt_info.get_variant_field_stmt].make_nop(); - } - - for (left, right) in &opt_info.field_tmp_assignments { - if local == left || local == right { - bb.statements[*live_idx].make_nop(); - bb.statements[*dead_idx].make_nop(); - } - } - } - - // Right shape; transform - for stmt_idx in opt_info.stmts_to_remove { - bb.statements[stmt_idx].make_nop(); - } - - let stmt = &mut bb.statements[opt_info.stmt_to_overwrite]; - stmt.source_info = opt_info.source_info; - stmt.kind = StatementKind::Assign(Box::new(( - opt_info.local_0.into(), - Rvalue::Use(Operand::Move(opt_info.local_1.into())), - ))); - - bb.statements.retain(|stmt| stmt.kind != StatementKind::Nop); - - // Fix the debug info to point to the right local - for dbg_index in opt_info.dbg_info_to_adjust { - let dbg_info = &mut body.var_debug_info[dbg_index]; - assert!( - matches!(dbg_info.value, VarDebugInfoContents::Place(_)), - "value was not a Place" - ); - if let VarDebugInfoContents::Place(p) = &mut dbg_info.value { - assert!(p.projection.is_empty()); - p.local = opt_info.local_0; - p.projection = opt_info.dbg_projection; - } - } - - trace!("block is now {:?}", bb.statements); - } - } - } -} - -struct LocalUseCounter { - local_uses: IndexVec, -} - -impl LocalUseCounter { - fn get_local_uses(body: &Body<'_>) -> IndexVec { - let mut counter = LocalUseCounter { local_uses: IndexVec::from_elem(0, &body.local_decls) }; - counter.visit_body(body); - counter.local_uses - } -} - -impl Visitor<'_> for LocalUseCounter { - fn visit_local(&mut self, local: Local, context: PlaceContext, _location: Location) { - if context.is_storage_marker() - || context == PlaceContext::NonUse(NonUseContext::VarDebugInfo) - { - return; - } - - self.local_uses[local] += 1; - } -} - -/// Match on: -/// ```ignore (MIR) -/// _LOCAL_INTO = ((_LOCAL_FROM as Variant).FIELD: TY); -/// ``` -fn match_get_variant_field<'tcx>( - stmt: &Statement<'tcx>, -) -> Option<(Local, Local, VarField<'tcx>, &'tcx List>)> { - match &stmt.kind { - StatementKind::Assign(box ( - place_into, - Rvalue::Use(Operand::Copy(pf) | Operand::Move(pf)), - )) => { - let local_into = place_into.as_local()?; - let (local_from, vf) = match_variant_field_place(*pf)?; - Some((local_into, local_from, vf, pf.projection)) - } - _ => None, - } -} - -/// Match on: -/// ```ignore (MIR) -/// ((_LOCAL_FROM as Variant).FIELD: TY) = move _LOCAL_INTO; -/// ``` -fn match_set_variant_field<'tcx>(stmt: &Statement<'tcx>) -> Option<(Local, Local, VarField<'tcx>)> { - match &stmt.kind { - StatementKind::Assign(box (place_from, Rvalue::Use(Operand::Move(place_into)))) => { - let local_into = place_into.as_local()?; - let (local_from, vf) = match_variant_field_place(*place_from)?; - Some((local_into, local_from, vf)) - } - _ => None, - } -} - -/// Match on: -/// ```ignore (MIR) -/// discriminant(_LOCAL_TO_SET) = VAR_IDX; -/// ``` -fn match_set_discr(stmt: &Statement<'_>) -> Option<(Local, VariantIdx)> { - match &stmt.kind { - StatementKind::SetDiscriminant { place, variant_index } => { - Some((place.as_local()?, *variant_index)) - } - _ => None, - } -} - -#[derive(PartialEq, Debug)] -struct VarField<'tcx> { - field: Field, - field_ty: Ty<'tcx>, - var_idx: VariantIdx, -} - -/// Match on `((_LOCAL as Variant).FIELD: TY)`. -fn match_variant_field_place(place: Place<'_>) -> Option<(Local, VarField<'_>)> { - match place.as_ref() { - PlaceRef { - local, - projection: &[ProjectionElem::Downcast(_, var_idx), ProjectionElem::Field(field, ty)], - } => Some((local, VarField { field, field_ty: ty, var_idx })), - _ => None, - } -} - -/// Simplifies `SwitchInt(_) -> [targets]`, -/// where all the `targets` have the same form, -/// into `goto -> target_first`. -pub struct SimplifyBranchSame; - -impl<'tcx> MirPass<'tcx> for SimplifyBranchSame { - fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { - // This optimization is disabled by default for now due to - // soundness concerns; see issue #89485 and PR #89489. - if !tcx.sess.opts.unstable_opts.unsound_mir_opts { - return; - } - - trace!("Running SimplifyBranchSame on {:?}", body.source); - let finder = SimplifyBranchSameOptimizationFinder { body, tcx }; - let opts = finder.find(); - - let did_remove_blocks = opts.len() > 0; - for opt in opts.iter() { - trace!("SUCCESS: Applying optimization {:?}", opt); - // Replace `SwitchInt(..) -> [bb_first, ..];` with a `goto -> bb_first;`. - body.basic_blocks_mut()[opt.bb_to_opt_terminator].terminator_mut().kind = - TerminatorKind::Goto { target: opt.bb_to_goto }; - } - - if did_remove_blocks { - // We have dead blocks now, so remove those. - simplify::remove_dead_blocks(tcx, body); - } - } -} - -#[derive(Debug)] -struct SimplifyBranchSameOptimization { - /// All basic blocks are equal so go to this one - bb_to_goto: BasicBlock, - /// Basic block where the terminator can be simplified to a goto - bb_to_opt_terminator: BasicBlock, -} - -struct SwitchTargetAndValue { - target: BasicBlock, - // None in case of the `otherwise` case - value: Option, -} - -struct SimplifyBranchSameOptimizationFinder<'a, 'tcx> { - body: &'a Body<'tcx>, - tcx: TyCtxt<'tcx>, -} - -impl<'tcx> SimplifyBranchSameOptimizationFinder<'_, 'tcx> { - fn find(&self) -> Vec { - self.body - .basic_blocks - .iter_enumerated() - .filter_map(|(bb_idx, bb)| { - let (discr_switched_on, targets_and_values) = match &bb.terminator().kind { - TerminatorKind::SwitchInt { targets, discr, .. } => { - let targets_and_values: Vec<_> = targets.iter() - .map(|(val, target)| SwitchTargetAndValue { target, value: Some(val) }) - .chain(once(SwitchTargetAndValue { target: targets.otherwise(), value: None })) - .collect(); - (discr, targets_and_values) - }, - _ => return None, - }; - - // find the adt that has its discriminant read - // assuming this must be the last statement of the block - let adt_matched_on = match &bb.statements.last()?.kind { - StatementKind::Assign(box (place, rhs)) - if Some(*place) == discr_switched_on.place() => - { - match rhs { - Rvalue::Discriminant(adt_place) if adt_place.ty(self.body, self.tcx).ty.is_enum() => adt_place, - _ => { - trace!("NO: expected a discriminant read of an enum instead of: {:?}", rhs); - return None; - } - } - } - other => { - trace!("NO: expected an assignment of a discriminant read to a place. Found: {:?}", other); - return None - }, - }; - - let mut iter_bbs_reachable = targets_and_values - .iter() - .map(|target_and_value| (target_and_value, &self.body.basic_blocks[target_and_value.target])) - .filter(|(_, bb)| { - // Reaching `unreachable` is UB so assume it doesn't happen. - bb.terminator().kind != TerminatorKind::Unreachable - }) - .peekable(); - - let bb_first = iter_bbs_reachable.peek().map_or(&targets_and_values[0], |(idx, _)| *idx); - let mut all_successors_equivalent = StatementEquality::TrivialEqual; - - // All successor basic blocks must be equal or contain statements that are pairwise considered equal. - for ((target_and_value_l,bb_l), (target_and_value_r,bb_r)) in iter_bbs_reachable.tuple_windows() { - let trivial_checks = bb_l.is_cleanup == bb_r.is_cleanup - && bb_l.terminator().kind == bb_r.terminator().kind - && bb_l.statements.len() == bb_r.statements.len(); - let statement_check = || { - bb_l.statements.iter().zip(&bb_r.statements).try_fold(StatementEquality::TrivialEqual, |acc,(l,r)| { - let stmt_equality = self.statement_equality(*adt_matched_on, &l, target_and_value_l, &r, target_and_value_r); - if matches!(stmt_equality, StatementEquality::NotEqual) { - // short circuit - None - } else { - Some(acc.combine(&stmt_equality)) - } - }) - .unwrap_or(StatementEquality::NotEqual) - }; - if !trivial_checks { - all_successors_equivalent = StatementEquality::NotEqual; - break; - } - all_successors_equivalent = all_successors_equivalent.combine(&statement_check()); - }; - - match all_successors_equivalent{ - StatementEquality::TrivialEqual => { - // statements are trivially equal, so just take first - trace!("Statements are trivially equal"); - Some(SimplifyBranchSameOptimization { - bb_to_goto: bb_first.target, - bb_to_opt_terminator: bb_idx, - }) - } - StatementEquality::ConsideredEqual(bb_to_choose) => { - trace!("Statements are considered equal"); - Some(SimplifyBranchSameOptimization { - bb_to_goto: bb_to_choose, - bb_to_opt_terminator: bb_idx, - }) - } - StatementEquality::NotEqual => { - trace!("NO: not all successors of basic block {:?} were equivalent", bb_idx); - None - } - } - }) - .collect() - } - - /// Tests if two statements can be considered equal - /// - /// Statements can be trivially equal if the kinds match. - /// But they can also be considered equal in the following case A: - /// ```ignore (MIR) - /// discriminant(_0) = 0; // bb1 - /// _0 = move _1; // bb2 - /// ``` - /// In this case the two statements are equal iff - /// - `_0` is an enum where the variant index 0 is fieldless, and - /// - bb1 was targeted by a switch where the discriminant of `_1` was switched on - fn statement_equality( - &self, - adt_matched_on: Place<'tcx>, - x: &Statement<'tcx>, - x_target_and_value: &SwitchTargetAndValue, - y: &Statement<'tcx>, - y_target_and_value: &SwitchTargetAndValue, - ) -> StatementEquality { - let helper = |rhs: &Rvalue<'tcx>, - place: &Place<'tcx>, - variant_index: VariantIdx, - switch_value: u128, - side_to_choose| { - let place_type = place.ty(self.body, self.tcx).ty; - let adt = match *place_type.kind() { - ty::Adt(adt, _) if adt.is_enum() => adt, - _ => return StatementEquality::NotEqual, - }; - // We need to make sure that the switch value that targets the bb with - // SetDiscriminant is the same as the variant discriminant. - let variant_discr = adt.discriminant_for_variant(self.tcx, variant_index).val; - if variant_discr != switch_value { - trace!( - "NO: variant discriminant {} does not equal switch value {}", - variant_discr, - switch_value - ); - return StatementEquality::NotEqual; - } - let variant_is_fieldless = adt.variant(variant_index).fields.is_empty(); - if !variant_is_fieldless { - trace!("NO: variant {:?} was not fieldless", variant_index); - return StatementEquality::NotEqual; - } - - match rhs { - Rvalue::Use(operand) if operand.place() == Some(adt_matched_on) => { - StatementEquality::ConsideredEqual(side_to_choose) - } - _ => { - trace!( - "NO: RHS of assignment was {:?}, but expected it to match the adt being matched on in the switch, which is {:?}", - rhs, - adt_matched_on - ); - StatementEquality::NotEqual - } - } - }; - match (&x.kind, &y.kind) { - // trivial case - (x, y) if x == y => StatementEquality::TrivialEqual, - - // check for case A - ( - StatementKind::Assign(box (_, rhs)), - &StatementKind::SetDiscriminant { ref place, variant_index }, - ) if y_target_and_value.value.is_some() => { - // choose basic block of x, as that has the assign - helper( - rhs, - place, - variant_index, - y_target_and_value.value.unwrap(), - x_target_and_value.target, - ) - } - ( - &StatementKind::SetDiscriminant { ref place, variant_index }, - &StatementKind::Assign(box (_, ref rhs)), - ) if x_target_and_value.value.is_some() => { - // choose basic block of y, as that has the assign - helper( - rhs, - place, - variant_index, - x_target_and_value.value.unwrap(), - y_target_and_value.target, - ) - } - _ => { - trace!("NO: statements `{:?}` and `{:?}` not considered equal", x, y); - StatementEquality::NotEqual - } - } - } -} - -#[derive(Copy, Clone, Eq, PartialEq)] -enum StatementEquality { - /// The two statements are trivially equal; same kind - TrivialEqual, - /// The two statements are considered equal, but may be of different kinds. The BasicBlock field is the basic block to jump to when performing the branch-same optimization. - /// For example, `_0 = _1` and `discriminant(_0) = discriminant(0)` are considered equal if 0 is a fieldless variant of an enum. But we don't want to jump to the basic block with the SetDiscriminant, as that is not legal if _1 is not the 0 variant index - ConsideredEqual(BasicBlock), - /// The two statements are not equal - NotEqual, -} - -impl StatementEquality { - fn combine(&self, other: &StatementEquality) -> StatementEquality { - use StatementEquality::*; - match (self, other) { - (TrivialEqual, TrivialEqual) => TrivialEqual, - (TrivialEqual, ConsideredEqual(b)) | (ConsideredEqual(b), TrivialEqual) => { - ConsideredEqual(*b) - } - (ConsideredEqual(b1), ConsideredEqual(b2)) => { - if b1 == b2 { - ConsideredEqual(*b1) - } else { - NotEqual - } - } - (_, NotEqual) | (NotEqual, _) => NotEqual, - } - } -} diff --git a/tests/mir-opt/76803_regression.encode.SimplifyBranchSame.diff b/tests/mir-opt/76803_regression.encode.SimplifyBranchSame.diff deleted file mode 100644 index 9780332d8bf18..0000000000000 --- a/tests/mir-opt/76803_regression.encode.SimplifyBranchSame.diff +++ /dev/null @@ -1,29 +0,0 @@ -- // MIR for `encode` before SimplifyBranchSame -+ // MIR for `encode` after SimplifyBranchSame - - fn encode(_1: Type) -> Type { - debug v => _1; // in scope 0 at $DIR/76803_regression.rs:+0:15: +0:16 - let mut _0: Type; // return place in scope 0 at $DIR/76803_regression.rs:+0:27: +0:31 - let mut _2: isize; // in scope 0 at $DIR/76803_regression.rs:+2:9: +2:16 - - bb0: { - _2 = discriminant(_1); // scope 0 at $DIR/76803_regression.rs:+1:11: +1:12 - switchInt(move _2) -> [0: bb2, otherwise: bb1]; // scope 0 at $DIR/76803_regression.rs:+1:5: +1:12 - } - - bb1: { - _0 = move _1; // scope 0 at $DIR/76803_regression.rs:+3:14: +3:15 - goto -> bb3; // scope 0 at $DIR/76803_regression.rs:+3:14: +3:15 - } - - bb2: { - Deinit(_0); // scope 0 at $DIR/76803_regression.rs:+2:20: +2:27 - discriminant(_0) = 1; // scope 0 at $DIR/76803_regression.rs:+2:20: +2:27 - goto -> bb3; // scope 0 at $DIR/76803_regression.rs:+2:20: +2:27 - } - - bb3: { - return; // scope 0 at $DIR/76803_regression.rs:+5:2: +5:2 - } - } - diff --git a/tests/mir-opt/76803_regression.rs b/tests/mir-opt/76803_regression.rs deleted file mode 100644 index 05dc3c9784109..0000000000000 --- a/tests/mir-opt/76803_regression.rs +++ /dev/null @@ -1,19 +0,0 @@ -// compile-flags: -Z mir-opt-level=1 -// EMIT_MIR 76803_regression.encode.SimplifyBranchSame.diff - -#[derive(Debug, Eq, PartialEq)] -pub enum Type { - A, - B, -} - -pub fn encode(v: Type) -> Type { - match v { - Type::A => Type::B, - _ => v, - } -} - -fn main() { - assert_eq!(Type::B, encode(Type::A)); -} diff --git a/tests/mir-opt/issue_73223.main.SimplifyArmIdentity.diff b/tests/mir-opt/issue_73223.main.SimplifyArmIdentity.diff deleted file mode 100644 index bf3bcfdb59442..0000000000000 --- a/tests/mir-opt/issue_73223.main.SimplifyArmIdentity.diff +++ /dev/null @@ -1,156 +0,0 @@ -- // MIR for `main` before SimplifyArmIdentity -+ // MIR for `main` after SimplifyArmIdentity - - fn main() -> () { - let mut _0: (); // return place in scope 0 at $DIR/issue_73223.rs:+0:11: +0:11 - let _1: i32; // in scope 0 at $DIR/issue_73223.rs:+1:9: +1:14 - let mut _2: std::option::Option; // in scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 - let mut _3: isize; // in scope 0 at $DIR/issue_73223.rs:+2:9: +2:16 - let _4: i32; // in scope 0 at $DIR/issue_73223.rs:+2:14: +2:15 - let mut _6: i32; // in scope 0 at $DIR/issue_73223.rs:+6:22: +6:27 - let mut _7: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _8: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _11: bool; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _12: bool; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _13: i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _14: i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let _16: !; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _17: core::panicking::AssertKind; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _18: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let _19: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _20: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let _21: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _22: std::option::Option>; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _24: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _25: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - scope 1 { - debug split => _1; // in scope 1 at $DIR/issue_73223.rs:+1:9: +1:14 - let _5: std::option::Option; // in scope 1 at $DIR/issue_73223.rs:+6:9: +6:14 - scope 3 { - debug _prev => _5; // in scope 3 at $DIR/issue_73223.rs:+6:9: +6:14 - let _9: &i32; // in scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let _10: &i32; // in scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let mut _23: &i32; // in scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - scope 4 { - debug left_val => _9; // in scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - debug right_val => _10; // in scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - let _15: core::panicking::AssertKind; // in scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - scope 5 { - debug kind => _15; // in scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - } - } - } - } - scope 2 { - debug v => _4; // in scope 2 at $DIR/issue_73223.rs:+2:14: +2:15 - } - - bb0: { - StorageLive(_1); // scope 0 at $DIR/issue_73223.rs:+1:9: +1:14 - StorageLive(_2); // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 - Deinit(_2); // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 - ((_2 as Some).0: i32) = const 1_i32; // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 - discriminant(_2) = 1; // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 - _3 = const 1_isize; // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 - goto -> bb3; // scope 0 at $DIR/issue_73223.rs:+1:17: +1:30 - } - - bb1: { - StorageDead(_2); // scope 0 at $DIR/issue_73223.rs:+4:6: +4:7 - StorageDead(_1); // scope 0 at $DIR/issue_73223.rs:+8:1: +8:2 - return; // scope 0 at $DIR/issue_73223.rs:+8:2: +8:2 - } - - bb2: { - unreachable; // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 - } - - bb3: { - StorageLive(_4); // scope 0 at $DIR/issue_73223.rs:+2:14: +2:15 - _4 = ((_2 as Some).0: i32); // scope 0 at $DIR/issue_73223.rs:+2:14: +2:15 - _1 = _4; // scope 2 at $DIR/issue_73223.rs:+2:20: +2:21 - StorageDead(_4); // scope 0 at $DIR/issue_73223.rs:+2:20: +2:21 - StorageDead(_2); // scope 0 at $DIR/issue_73223.rs:+4:6: +4:7 - StorageLive(_5); // scope 1 at $DIR/issue_73223.rs:+6:9: +6:14 - StorageLive(_6); // scope 1 at $DIR/issue_73223.rs:+6:22: +6:27 - _6 = _1; // scope 1 at $DIR/issue_73223.rs:+6:22: +6:27 - Deinit(_5); // scope 1 at $DIR/issue_73223.rs:+6:17: +6:28 - ((_5 as Some).0: i32) = move _6; // scope 1 at $DIR/issue_73223.rs:+6:17: +6:28 - discriminant(_5) = 1; // scope 1 at $DIR/issue_73223.rs:+6:17: +6:28 - StorageDead(_6); // scope 1 at $DIR/issue_73223.rs:+6:27: +6:28 - StorageLive(_24); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_25); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_7); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _7 = &_1; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _23 = const _; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - // mir::Constant - // + span: $SRC_DIR/core/src/macros/mod.rs:LL:COL - // + literal: Const { ty: &i32, val: Unevaluated(main, [], Some(promoted[0])) } - _8 = _23; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - Deinit(_24); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - Deinit(_25); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _24 = move _7; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _25 = move _8; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_7); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_9); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _9 = _24; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_10); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _10 = _25; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_11); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_12); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_13); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _13 = (*_9); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_14); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _14 = const 1_i32; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _12 = Eq(move _13, const 1_i32); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_14); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_13); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _11 = Not(move _12); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_12); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - switchInt(move _11) -> [0: bb5, otherwise: bb4]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - } - - bb4: { - StorageLive(_15); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - Deinit(_15); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - discriminant(_15) = 0; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_16); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_17); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _17 = const core::panicking::AssertKind::Eq; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - // mir::Constant - // + span: $SRC_DIR/core/src/macros/mod.rs:LL:COL - // + literal: Const { ty: core::panicking::AssertKind, val: Value(Scalar(0x00)) } - StorageLive(_18); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_19); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _19 = _9; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _18 = _19; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_20); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_21); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _21 = _10; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _20 = _21; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageLive(_22); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - Deinit(_22); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - discriminant(_22) = 0; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _16 = core::panicking::assert_failed::(const core::panicking::AssertKind::Eq, move _18, move _20, move _22); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - // mir::Constant - // + span: $SRC_DIR/core/src/macros/mod.rs:LL:COL - // + literal: Const { ty: for<'a, 'b, 'c> fn(core::panicking::AssertKind, &'a i32, &'b i32, Option>) -> ! {core::panicking::assert_failed::}, val: Value() } - // mir::Constant - // + span: $SRC_DIR/core/src/macros/mod.rs:LL:COL - // + literal: Const { ty: core::panicking::AssertKind, val: Value(Scalar(0x00)) } - } - - bb5: { - StorageDead(_11); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_10); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_9); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_24); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_25); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_5); // scope 1 at $DIR/issue_73223.rs:+8:1: +8:2 - StorageDead(_1); // scope 0 at $DIR/issue_73223.rs:+8:1: +8:2 - return; // scope 0 at $DIR/issue_73223.rs:+8:2: +8:2 - } - } - diff --git a/tests/mir-opt/issue_73223.rs b/tests/mir-opt/issue_73223.rs deleted file mode 100644 index be114cab719c0..0000000000000 --- a/tests/mir-opt/issue_73223.rs +++ /dev/null @@ -1,12 +0,0 @@ -fn main() { - let split = match Some(1) { - Some(v) => v, - None => return, - }; - - let _prev = Some(split); - assert_eq!(split, 1); -} - - -// EMIT_MIR issue_73223.main.SimplifyArmIdentity.diff From af58854168f2ae6b0af89d7945584cb78e276193 Mon Sep 17 00:00:00 2001 From: dimi Date: Wed, 26 Oct 2022 14:40:03 +0200 Subject: [PATCH 331/500] add feature gate tests for DispatchFromDyn --- .../feature-gate-dispatch-from-dyn-cell.rs | 9 ++++ ...feature-gate-dispatch-from-dyn-cell.stderr | 12 +++++ ...ure-gate-dispatch-from-dyn-missing-impl.rs | 35 +++++++++++++++ ...gate-dispatch-from-dyn-missing-impl.stderr | 45 +++++++++++++++++++ 4 files changed, 101 insertions(+) create mode 100644 tests/ui/feature-gates/feature-gate-dispatch-from-dyn-cell.rs create mode 100644 tests/ui/feature-gates/feature-gate-dispatch-from-dyn-cell.stderr create mode 100644 tests/ui/feature-gates/feature-gate-dispatch-from-dyn-missing-impl.rs create mode 100644 tests/ui/feature-gates/feature-gate-dispatch-from-dyn-missing-impl.stderr diff --git a/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-cell.rs b/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-cell.rs new file mode 100644 index 0000000000000..83366ea02b09a --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-cell.rs @@ -0,0 +1,9 @@ +// Check that even though Cell: DispatchFromDyn it remains an invalid self parameter type + +use std::cell::Cell; + +trait Trait{ + fn cell(self: Cell<&Self>); //~ ERROR invalid `self` parameter type: Cell<&Self> +} + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-cell.stderr b/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-cell.stderr new file mode 100644 index 0000000000000..ce06ce916a758 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-cell.stderr @@ -0,0 +1,12 @@ +error[E0307]: invalid `self` parameter type: Cell<&Self> + --> $DIR/feature-gate-dispatch-from-dyn-cell.rs:6:19 + | +LL | fn cell(self: Cell<&Self>); + | ^^^^^^^^^^^ + | + = note: type of `self` must be `Self` or a type that dereferences to it + = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0307`. diff --git a/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-missing-impl.rs b/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-missing-impl.rs new file mode 100644 index 0000000000000..23857cbaca85e --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-missing-impl.rs @@ -0,0 +1,35 @@ +// Check that a self parameter type requires a DispatchFromDyn impl to be object safe + +#![feature(arbitrary_self_types, unsize, coerce_unsized)] + +use std::{ + marker::Unsize, + ops::{CoerceUnsized, Deref}, +}; + +struct Ptr(Box); + +impl Deref for Ptr { + type Target = T; + + fn deref(&self) -> &T { + &*self.0 + } +} + +impl + ?Sized, U: ?Sized> CoerceUnsized> for Ptr {} +// Because this impl is missing the coercion below fails. +// impl + ?Sized, U: ?Sized> DispatchFromDyn> for Ptr {} + +trait Trait { + fn ptr(self: Ptr); +} +impl Trait for i32 { + fn ptr(self: Ptr) {} +} + +fn main() { + Ptr(Box::new(4)) as Ptr; + //~^ ERROR the trait `Trait` cannot be made into an object + //~^^ ERROR the trait `Trait` cannot be made into an object +} diff --git a/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-missing-impl.stderr b/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-missing-impl.stderr new file mode 100644 index 0000000000000..d81eade8e9bfb --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-dispatch-from-dyn-missing-impl.stderr @@ -0,0 +1,45 @@ +error[E0038]: the trait `Trait` cannot be made into an object + --> $DIR/feature-gate-dispatch-from-dyn-missing-impl.rs:32:25 + | +LL | fn ptr(self: Ptr); + | --------- help: consider changing method `ptr`'s `self` parameter to be `&self`: `&Self` +... +LL | Ptr(Box::new(4)) as Ptr; + | ^^^^^^^^^^^^^^ `Trait` cannot be made into an object + | +note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit + --> $DIR/feature-gate-dispatch-from-dyn-missing-impl.rs:25:18 + | +LL | trait Trait { + | ----- this trait cannot be made into an object... +LL | fn ptr(self: Ptr); + | ^^^^^^^^^ ...because method `ptr`'s `self` parameter cannot be dispatched on + +error[E0038]: the trait `Trait` cannot be made into an object + --> $DIR/feature-gate-dispatch-from-dyn-missing-impl.rs:32:5 + | +LL | fn ptr(self: Ptr); + | --------- help: consider changing method `ptr`'s `self` parameter to be `&self`: `&Self` +... +LL | Ptr(Box::new(4)) as Ptr; + | ^^^^^^^^^^^^^^^^ `Trait` cannot be made into an object + | +note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit + --> $DIR/feature-gate-dispatch-from-dyn-missing-impl.rs:25:18 + | +LL | trait Trait { + | ----- this trait cannot be made into an object... +LL | fn ptr(self: Ptr); + | ^^^^^^^^^ ...because method `ptr`'s `self` parameter cannot be dispatched on +note: required for `Ptr<{integer}>` to implement `CoerceUnsized>` + --> $DIR/feature-gate-dispatch-from-dyn-missing-impl.rs:20:40 + | +LL | impl + ?Sized, U: ?Sized> CoerceUnsized> for Ptr {} + | --------- ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ + | | + | unsatisfied trait bound introduced here + = note: required by cast to type `Ptr` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0038`. From db731e42b3c139587cd7a87acaa92cd82ab8a11c Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Tue, 24 Jan 2023 16:44:00 +0100 Subject: [PATCH 332/500] Work around issue 106930. --- compiler/rustc_ast/src/format.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/compiler/rustc_ast/src/format.rs b/compiler/rustc_ast/src/format.rs index ce99c2b58b570..da05b09b37dcc 100644 --- a/compiler/rustc_ast/src/format.rs +++ b/compiler/rustc_ast/src/format.rs @@ -67,6 +67,12 @@ pub struct FormatArguments { names: FxHashMap, } +// FIXME: Rustdoc has trouble proving Send/Sync for this. See #106930. +#[cfg(parallel_compiler)] +unsafe impl Sync for FormatArguments {} +#[cfg(parallel_compiler)] +unsafe impl Send for FormatArguments {} + impl FormatArguments { pub fn new() -> Self { Self { From 11a94f242d48739a557b6e09cbd8d3cde2fcdedf Mon Sep 17 00:00:00 2001 From: KaDiWa Date: Tue, 24 Jan 2023 16:46:45 +0100 Subject: [PATCH 333/500] rustdoc: prevent scroll bar on source viewer --- src/librustdoc/html/static/css/rustdoc.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css index 424bbb0ec42be..bf83ff2044e69 100644 --- a/src/librustdoc/html/static/css/rustdoc.css +++ b/src/librustdoc/html/static/css/rustdoc.css @@ -533,7 +533,7 @@ ul.block, .block li { .rustdoc .example-wrap > pre { margin: 0; flex-grow: 1; - overflow-x: auto; + overflow: auto hidden; } .rustdoc .example-wrap > pre.example-line-numbers, From bba274fabbaf6e2387db5e09d1ad3a9c2ca48560 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Tue, 24 Jan 2023 17:00:45 +0100 Subject: [PATCH 334/500] add option to include private items in library docs --- config.toml.example | 3 +++ src/bootstrap/config.rs | 3 +++ src/bootstrap/doc.rs | 3 +++ 3 files changed, 9 insertions(+) diff --git a/config.toml.example b/config.toml.example index 299bfd779e57a..85f058f3664e3 100644 --- a/config.toml.example +++ b/config.toml.example @@ -233,6 +233,9 @@ changelog-seen = 2 # and generated in already-minified form from the beginning. #docs-minification = true +# Flag to specify whether private items should be included in the library docs. +#library-docs-private-items = false + # Indicate whether the compiler should be documented in addition to the standard # library and facade crates. #compiler-docs = false diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index b41d60d51a8b5..0bcc919aee802 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -65,6 +65,7 @@ pub struct Config { pub verbose: usize, pub submodules: Option, pub compiler_docs: bool, + pub library_docs_private_items: bool, pub docs_minification: bool, pub docs: bool, pub locked_deps: bool, @@ -606,6 +607,7 @@ define_config! { rustfmt: Option = "rustfmt", docs: Option = "docs", compiler_docs: Option = "compiler-docs", + library_docs_private_items: Option = "library-docs-private-items", docs_minification: Option = "docs-minification", submodules: Option = "submodules", gdb: Option = "gdb", @@ -1015,6 +1017,7 @@ impl Config { config.submodules = build.submodules; set(&mut config.low_priority, build.low_priority); set(&mut config.compiler_docs, build.compiler_docs); + set(&mut config.library_docs_private_items, build.library_docs_private_items); set(&mut config.docs_minification, build.docs_minification); set(&mut config.docs, build.docs); set(&mut config.locked_deps, build.locked_deps); diff --git a/src/bootstrap/doc.rs b/src/bootstrap/doc.rs index 9bad9046ecc2c..5d5a808200d91 100644 --- a/src/bootstrap/doc.rs +++ b/src/bootstrap/doc.rs @@ -597,6 +597,9 @@ fn doc_std( .arg("--resource-suffix") .arg(&builder.version) .args(extra_args); + if builder.config.library_docs_private_items { + cargo.arg("--document-private-items"); + } builder.run(&mut cargo.into()); }; From 5139b14620832d08a436ad85c1bef4037c36395b Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Tue, 24 Jan 2023 11:13:54 -0600 Subject: [PATCH 335/500] fix: version gate changes for multiline single generic bound --- src/types.rs | 23 ++++++++++++----------- tests/target/issue-4689/one.rs | 16 ++++++++-------- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/src/types.rs b/src/types.rs index 2cae549810751..01e2fb6e61e15 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1057,21 +1057,22 @@ fn join_bounds_inner( }, )?; - // Whether retry the function with forced newline is needed: + // Whether to retry with a forced newline: // Only if result is not already multiline and did not exceed line width, // and either there is more than one item; // or the single item is of type `Trait`, // and any of the internal arrays contains more than one item; - let retry_with_force_newline = - if force_newline || (!result.0.contains('\n') && result.0.len() <= shape.width) { - false - } else { - if items.len() > 1 { - true - } else { - is_item_with_multi_items_array(&items[0]) - } - }; + let retry_with_force_newline = match context.config.version() { + Version::One => { + !force_newline + && items.len() > 1 + && (result.0.contains('\n') || result.0.len() > shape.width) + } + Version::Two if force_newline => false, + Version::Two if (!result.0.contains('\n') && result.0.len() <= shape.width) => false, + Version::Two if items.len() > 1 => true, + Version::Two => is_item_with_multi_items_array(&items[0]), + }; if retry_with_force_newline { join_bounds_inner(context, shape, items, need_indent, true) diff --git a/tests/target/issue-4689/one.rs b/tests/target/issue-4689/one.rs index df1a507bc1da9..7735e34f3b5ed 100644 --- a/tests/target/issue-4689/one.rs +++ b/tests/target/issue-4689/one.rs @@ -3,14 +3,14 @@ // Based on the issue description pub trait PrettyPrinter<'tcx>: Printer< - 'tcx, - Error = fmt::Error, - Path = Self, - Region = Self, - Type = Self, - DynExistential = Self, - Const = Self, - > + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, +> { // } From ae3aa718a4d70f560b4fe5fb6297f8a8461a1e9e Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Tue, 24 Jan 2023 19:03:13 +0100 Subject: [PATCH 336/500] Update tidy for cranelift-egraph removal and new windows-sys targets --- src/tools/tidy/src/deps.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index bc2edf634de2b..8ce19c8b5145b 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -59,7 +59,6 @@ const EXCEPTIONS_CRANELIFT: &[(&str, &str)] = &[ ("cranelift-codegen", "Apache-2.0 WITH LLVM-exception"), ("cranelift-codegen-meta", "Apache-2.0 WITH LLVM-exception"), ("cranelift-codegen-shared", "Apache-2.0 WITH LLVM-exception"), - ("cranelift-egraph", "Apache-2.0 WITH LLVM-exception"), ("cranelift-entity", "Apache-2.0 WITH LLVM-exception"), ("cranelift-frontend", "Apache-2.0 WITH LLVM-exception"), ("cranelift-isle", "Apache-2.0 WITH LLVM-exception"), @@ -286,7 +285,6 @@ const PERMITTED_CRANELIFT_DEPENDENCIES: &[&str] = &[ "cranelift-codegen", "cranelift-codegen-meta", "cranelift-codegen-shared", - "cranelift-egraph", "cranelift-entity", "cranelift-frontend", "cranelift-isle", @@ -321,10 +319,12 @@ const PERMITTED_CRANELIFT_DEPENDENCIES: &[&str] = &[ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", "windows-sys", + "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_msvc", "windows_x86_64_gnu", + "windows_x86_64_gnullvm", "windows_x86_64_msvc", ]; From 1e22280f231e02b9ec8624e16b473b4082d7dfad Mon Sep 17 00:00:00 2001 From: Matthew J Perez Date: Sun, 11 Dec 2022 02:49:07 -0500 Subject: [PATCH 337/500] Add suggestions for function pointers - On compiler-error's suggestion of moving this lower down the stack, along the path of `report_mismatched_types()`, which is used by `rustc_hir_analysis` and `rustc_hir_typeck`. - update ui tests, add test - add suggestions for references to fn pointers - modify `TypeErrCtxt::same_type_modulo_infer` to take `T: relate::Relate` instead of `Ty` --- compiler/rustc_hir_typeck/src/coercion.rs | 2 + compiler/rustc_hir_typeck/src/demand.rs | 1 - .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 37 --------- .../src/infer/error_reporting/mod.rs | 3 +- .../src/infer/error_reporting/suggest.rs | 78 +++++++++++++++++- tests/ui/fn/fn-compare-mismatch.stderr | 1 + tests/ui/fn/fn-item-type.rs | 37 +++++---- tests/ui/fn/fn-item-type.stderr | 49 +++++------ tests/ui/fn/fn-pointer-mismatch.rs | 56 +++++++++++++ tests/ui/fn/fn-pointer-mismatch.stderr | 81 +++++++++++++++++++ tests/ui/reify-intrinsic.stderr | 4 +- .../fn-ptr.mir.stderr | 7 +- .../fn-ptr.thir.stderr | 7 +- .../ui/static/static-reference-to-fn-1.stderr | 6 +- 14 files changed, 273 insertions(+), 96 deletions(-) create mode 100644 tests/ui/fn/fn-pointer-mismatch.rs create mode 100644 tests/ui/fn/fn-pointer-mismatch.stderr diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index bbf7b81a2cc66..1a0715a91cb0c 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -1613,12 +1613,14 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { if visitor.ret_exprs.len() > 0 && let Some(expr) = expression { self.note_unreachable_loop_return(&mut err, &expr, &visitor.ret_exprs); } + let reported = err.emit_unless(unsized_return); self.final_ty = Some(fcx.tcx.ty_error_with_guaranteed(reported)); } } } + fn note_unreachable_loop_return( &self, err: &mut Diagnostic, diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index bd1626dff7951..d02d77afa0a9f 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -81,7 +81,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.annotate_expected_due_to_let_ty(err, expr, error); self.emit_type_mismatch_suggestions(err, expr, expr_ty, expected, expected_ty_expr, error); self.note_type_is_not_clone(err, expected, expr_ty, expr); - self.note_need_for_fn_pointer(err, expected, expr_ty); self.note_internal_mutation_in_method(err, expr, expected, expr_ty); self.check_for_range_as_method_call(err, expr, expr_ty, expected); self.check_for_binding_assigned_block_without_tail_expression(err, expr, expr_ty, expected); diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 6ed8adb47425a..e9858aef6d0bf 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -926,43 +926,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub(in super::super) fn note_need_for_fn_pointer( - &self, - err: &mut Diagnostic, - expected: Ty<'tcx>, - found: Ty<'tcx>, - ) { - let (sig, did, substs) = match (&expected.kind(), &found.kind()) { - (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => { - let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1); - let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2); - if sig1 != sig2 { - return; - } - err.note( - "different `fn` items always have unique types, even if their signatures are \ - the same", - ); - (sig1, *did1, substs1) - } - (ty::FnDef(did, substs), ty::FnPtr(sig2)) => { - let sig1 = self.tcx.bound_fn_sig(*did).subst(self.tcx, substs); - if sig1 != *sig2 { - return; - } - (sig1, *did, substs) - } - _ => return, - }; - err.help(&format!("change the expected type to be function pointer `{}`", sig)); - err.help(&format!( - "if the expected type is due to type inference, cast the expected `fn` to a function \ - pointer: `{} as {}`", - self.tcx.def_path_str_with_substs(did, substs), - sig - )); - } - // Instantiates the given path, which must refer to an item with the given // number of type parameters and type. #[instrument(skip(self, span), level = "debug")] diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 28fd03b878b2b..212683a5429ed 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -1841,6 +1841,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { self.suggest_as_ref_where_appropriate(span, &exp_found, diag); self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag); self.suggest_await_on_expect_found(cause, span, &exp_found, diag); + self.suggest_function_pointers(cause, span, &exp_found, diag); } } @@ -2585,7 +2586,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or /// FloatVar inference type are compatible with themselves or their concrete types (Int and /// Float types, respectively). When comparing two ADTs, these rules apply recursively. - pub fn same_type_modulo_infer(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool { + pub fn same_type_modulo_infer>(&self, a: T, b: T) -> bool { let (a, b) = self.resolve_vars_if_possible((a, b)); SameTypeModuloInfer(self).relate(a, b).is_ok() } diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index 5b02956a106c6..b2ab39630bdaf 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -8,7 +8,7 @@ use rustc_middle::traits::{ StatementAsExpression, }; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::{self as ty, Ty, TypeVisitable}; +use rustc_middle::ty::{self as ty, IsSuggestable, Ty, TypeVisitable}; use rustc_span::{sym, BytePos, Span}; use crate::errors::SuggAddLetForLetChains; @@ -351,6 +351,82 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } } + pub(super) fn suggest_function_pointers( + &self, + cause: &ObligationCause<'tcx>, + span: Span, + exp_found: &ty::error::ExpectedFound>, + diag: &mut Diagnostic, + ) { + debug!("suggest_function_pointers(cause={:?}, exp_found={:?})", cause, exp_found); + let ty::error::ExpectedFound { expected, found } = exp_found; + let expected_inner = expected.peel_refs(); + let found_inner = found.peel_refs(); + if !expected_inner.is_fn() || !found_inner.is_fn() { + return; + } + match (&expected_inner.kind(), &found_inner.kind()) { + (ty::FnPtr(sig), ty::FnDef(did, substs)) => { + let expected_sig = &(self.normalize_fn_sig)(*sig); + let found_sig = + &(self.normalize_fn_sig)(self.tcx.bound_fn_sig(*did).subst(self.tcx, substs)); + + let fn_name = self.tcx.def_path_str_with_substs(*did, substs); + + if !self.same_type_modulo_infer(*found_sig, *expected_sig) + || !sig.is_suggestable(self.tcx, true) + || ty::util::is_intrinsic(self.tcx, *did) + { + return; + } + + let (msg, sugg) = match (expected.is_ref(), found.is_ref()) { + (true, false) => { + let msg = "consider using a reference"; + let sug = format!("&{fn_name}"); + (msg, sug) + } + (false, true) => { + let msg = "consider removing the reference"; + let sug = format!("{fn_name}"); + (msg, sug) + } + (true, true) => { + diag.note("fn items are distinct from fn pointers"); + let msg = "consider casting to a fn pointer"; + let sug = format!("&({fn_name} as {sig})"); + (msg, sug) + } + (false, false) => { + diag.note("fn items are distinct from fn pointers"); + let msg = "consider casting to a fn pointer"; + let sug = format!("{fn_name} as {sig}"); + (msg, sug) + } + }; + diag.span_suggestion(span, msg, &sugg, Applicability::MaybeIncorrect); + } + (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => { + let expected_sig = + &(self.normalize_fn_sig)(self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1)); + let found_sig = + &(self.normalize_fn_sig)(self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2)); + + if self.same_type_modulo_infer(*found_sig, *expected_sig) { + diag.note( + "different fn items have unique types, even if their signatures are the same", + ); + } + } + (ty::FnDef(_, _), ty::FnPtr(_)) => { + diag.note("fn items are distinct from fn pointers"); + } + _ => { + return; + } + }; + } + pub fn should_suggest_as_ref(&self, expected: Ty<'tcx>, found: Ty<'tcx>) -> Option<&str> { if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) = (expected.kind(), found.kind()) diff --git a/tests/ui/fn/fn-compare-mismatch.stderr b/tests/ui/fn/fn-compare-mismatch.stderr index df838cb118105..f247ff6cf3f55 100644 --- a/tests/ui/fn/fn-compare-mismatch.stderr +++ b/tests/ui/fn/fn-compare-mismatch.stderr @@ -19,6 +19,7 @@ LL | let x = f == g; | = note: expected fn item `fn() {f}` found fn item `fn() {g}` + = note: different fn items have unique types, even if their signatures are the same error: aborting due to 2 previous errors diff --git a/tests/ui/fn/fn-item-type.rs b/tests/ui/fn/fn-item-type.rs index 1831e6cbf1050..b6ebc867d284b 100644 --- a/tests/ui/fn/fn-item-type.rs +++ b/tests/ui/fn/fn-item-type.rs @@ -1,13 +1,22 @@ // Test that the types of distinct fn items are not compatible by // default. See also `run-pass/fn-item-type-*.rs`. -fn foo(x: isize) -> isize { x * 2 } -fn bar(x: isize) -> isize { x * 4 } +fn foo(x: isize) -> isize { + x * 2 +} +fn bar(x: isize) -> isize { + x * 4 +} -fn eq(x: T, y: T) { } +fn eq(x: T, y: T) {} -trait Foo { fn foo() { /* this is a default fn */ } } -impl Foo for T { /* `foo` is still default here */ } +trait Foo { + fn foo() { /* this is a default fn */ + } +} +impl Foo for T { + /* `foo` is still default here */ +} fn main() { eq(foo::, bar::); @@ -15,39 +24,29 @@ fn main() { //~| expected fn item `fn(_) -> _ {foo::}` //~| found fn item `fn(_) -> _ {bar::}` //~| expected fn item, found a different fn item - //~| different `fn` items always have unique types, even if their signatures are the same - //~| change the expected type to be function pointer - //~| if the expected type is due to type inference, cast the expected `fn` to a function pointer + //~| different fn items have unique types, even if their signatures are the same eq(foo::, foo::); //~^ ERROR mismatched types //~| expected `u8`, found `i8` - //~| different `fn` items always have unique types, even if their signatures are the same - //~| change the expected type to be function pointer - //~| if the expected type is due to type inference, cast the expected `fn` to a function pointer + //~| different fn items have unique types, even if their signatures are the same eq(bar::, bar::>); //~^ ERROR mismatched types //~| found fn item `fn(_) -> _ {bar::>}` //~| expected struct `String`, found struct `Vec` - //~| different `fn` items always have unique types, even if their signatures are the same - //~| change the expected type to be function pointer - //~| if the expected type is due to type inference, cast the expected `fn` to a function pointer + //~| different fn items have unique types, even if their signatures are the same // Make sure we distinguish between trait methods correctly. eq(::foo, ::foo); //~^ ERROR mismatched types //~| expected `u8`, found `u16` - //~| different `fn` items always have unique types, even if their signatures are the same - //~| change the expected type to be function pointer - //~| if the expected type is due to type inference, cast the expected `fn` to a function pointer + //~| different fn items have unique types, even if their signatures are the same eq(foo::, bar:: as fn(isize) -> isize); //~^ ERROR mismatched types //~| found fn pointer `fn(_) -> _` //~| expected fn item, found fn pointer - //~| change the expected type to be function pointer - //~| if the expected type is due to type inference, cast the expected `fn` to a function pointer eq(foo:: as fn(isize) -> isize, bar::); // ok! } diff --git a/tests/ui/fn/fn-item-type.stderr b/tests/ui/fn/fn-item-type.stderr index f03a47d5c2c75..cb1b88c7ab8f3 100644 --- a/tests/ui/fn/fn-item-type.stderr +++ b/tests/ui/fn/fn-item-type.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/fn-item-type.rs:13:19 + --> $DIR/fn-item-type.rs:22:19 | LL | eq(foo::, bar::); | -- ^^^^^^^^^ expected fn item, found a different fn item @@ -8,17 +8,15 @@ LL | eq(foo::, bar::); | = note: expected fn item `fn(_) -> _ {foo::}` found fn item `fn(_) -> _ {bar::}` - = note: different `fn` items always have unique types, even if their signatures are the same - = help: change the expected type to be function pointer `fn(isize) -> isize` - = help: if the expected type is due to type inference, cast the expected `fn` to a function pointer: `foo:: as fn(isize) -> isize` + = note: different fn items have unique types, even if their signatures are the same note: function defined here - --> $DIR/fn-item-type.rs:7:4 + --> $DIR/fn-item-type.rs:11:4 | -LL | fn eq(x: T, y: T) { } +LL | fn eq(x: T, y: T) {} | ^^ ---- error[E0308]: mismatched types - --> $DIR/fn-item-type.rs:22:19 + --> $DIR/fn-item-type.rs:29:19 | LL | eq(foo::, foo::); | -- ^^^^^^^^^ expected `u8`, found `i8` @@ -27,17 +25,15 @@ LL | eq(foo::, foo::); | = note: expected fn item `fn(_) -> _ {foo::}` found fn item `fn(_) -> _ {foo::}` - = note: different `fn` items always have unique types, even if their signatures are the same - = help: change the expected type to be function pointer `fn(isize) -> isize` - = help: if the expected type is due to type inference, cast the expected `fn` to a function pointer: `foo:: as fn(isize) -> isize` + = note: different fn items have unique types, even if their signatures are the same note: function defined here - --> $DIR/fn-item-type.rs:7:4 + --> $DIR/fn-item-type.rs:11:4 | -LL | fn eq(x: T, y: T) { } +LL | fn eq(x: T, y: T) {} | ^^ ---- error[E0308]: mismatched types - --> $DIR/fn-item-type.rs:29:23 + --> $DIR/fn-item-type.rs:34:23 | LL | eq(bar::, bar::>); | -- ^^^^^^^^^^^^^^ expected struct `String`, found struct `Vec` @@ -46,17 +42,15 @@ LL | eq(bar::, bar::>); | = note: expected fn item `fn(_) -> _ {bar::}` found fn item `fn(_) -> _ {bar::>}` - = note: different `fn` items always have unique types, even if their signatures are the same - = help: change the expected type to be function pointer `fn(isize) -> isize` - = help: if the expected type is due to type inference, cast the expected `fn` to a function pointer: `bar:: as fn(isize) -> isize` + = note: different fn items have unique types, even if their signatures are the same note: function defined here - --> $DIR/fn-item-type.rs:7:4 + --> $DIR/fn-item-type.rs:11:4 | -LL | fn eq(x: T, y: T) { } +LL | fn eq(x: T, y: T) {} | ^^ ---- error[E0308]: mismatched types - --> $DIR/fn-item-type.rs:38:26 + --> $DIR/fn-item-type.rs:41:26 | LL | eq(::foo, ::foo); | -- ^^^^^^^^^^^^^^^^^ expected `u8`, found `u16` @@ -65,17 +59,15 @@ LL | eq(::foo, ::foo); | = note: expected fn item `fn() {::foo}` found fn item `fn() {::foo}` - = note: different `fn` items always have unique types, even if their signatures are the same - = help: change the expected type to be function pointer `fn()` - = help: if the expected type is due to type inference, cast the expected `fn` to a function pointer: `::foo as fn()` + = note: different fn items have unique types, even if their signatures are the same note: function defined here - --> $DIR/fn-item-type.rs:7:4 + --> $DIR/fn-item-type.rs:11:4 | -LL | fn eq(x: T, y: T) { } +LL | fn eq(x: T, y: T) {} | ^^ ---- error[E0308]: mismatched types - --> $DIR/fn-item-type.rs:45:19 + --> $DIR/fn-item-type.rs:46:19 | LL | eq(foo::, bar:: as fn(isize) -> isize); | -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected fn item, found fn pointer @@ -84,12 +76,11 @@ LL | eq(foo::, bar:: as fn(isize) -> isize); | = note: expected fn item `fn(_) -> _ {foo::}` found fn pointer `fn(_) -> _` - = help: change the expected type to be function pointer `fn(isize) -> isize` - = help: if the expected type is due to type inference, cast the expected `fn` to a function pointer: `foo:: as fn(isize) -> isize` + = note: fn items are distinct from fn pointers note: function defined here - --> $DIR/fn-item-type.rs:7:4 + --> $DIR/fn-item-type.rs:11:4 | -LL | fn eq(x: T, y: T) { } +LL | fn eq(x: T, y: T) {} | ^^ ---- error: aborting due to 5 previous errors diff --git a/tests/ui/fn/fn-pointer-mismatch.rs b/tests/ui/fn/fn-pointer-mismatch.rs new file mode 100644 index 0000000000000..0597478cb4292 --- /dev/null +++ b/tests/ui/fn/fn-pointer-mismatch.rs @@ -0,0 +1,56 @@ +fn foo(x: u32) -> u32 { + x * 2 +} + +fn bar(x: u32) -> u32 { + x * 3 +} + +// original example from Issue #102608 +fn foobar(n: u32) -> u32 { + let g = if n % 2 == 0 { &foo } else { &bar }; + //~^ ERROR `if` and `else` have incompatible types + //~| different fn items have unique types, even if their signatures are the same + g(n) +} + +fn main() { + assert_eq!(foobar(7), 21); + assert_eq!(foobar(8), 16); + + // general mismatch of fn item types + let mut a = foo; + a = bar; + //~^ ERROR mismatched types + //~| expected fn item `fn(_) -> _ {foo}` + //~| found fn item `fn(_) -> _ {bar}` + //~| different fn items have unique types, even if their signatures are the same + + // display note even when boxed + let mut b = Box::new(foo); + b = Box::new(bar); + //~^ ERROR mismatched types + //~| different fn items have unique types, even if their signatures are the same + + // suggest removing reference + let c: fn(u32) -> u32 = &foo; + //~^ ERROR mismatched types + //~| expected fn pointer `fn(u32) -> u32` + //~| found reference `&fn(u32) -> u32 {foo}` + + // suggest using reference + let d: &fn(u32) -> u32 = foo; + //~^ ERROR mismatched types + //~| expected reference `&fn(u32) -> u32` + //~| found fn item `fn(u32) -> u32 {foo}` + + // suggest casting with reference + let e: &fn(u32) -> u32 = &foo; + //~^ ERROR mismatched types + //~| expected reference `&fn(u32) -> u32` + //~| found reference `&fn(u32) -> u32 {foo}` + + // OK + let mut z: fn(u32) -> u32 = foo as fn(u32) -> u32; + z = bar; +} diff --git a/tests/ui/fn/fn-pointer-mismatch.stderr b/tests/ui/fn/fn-pointer-mismatch.stderr new file mode 100644 index 0000000000000..2dc0710e27e46 --- /dev/null +++ b/tests/ui/fn/fn-pointer-mismatch.stderr @@ -0,0 +1,81 @@ +error[E0308]: `if` and `else` have incompatible types + --> $DIR/fn-pointer-mismatch.rs:11:43 + | +LL | let g = if n % 2 == 0 { &foo } else { &bar }; + | ---- ^^^^ expected fn item, found a different fn item + | | + | expected because of this + | + = note: expected reference `&fn(u32) -> u32 {foo}` + found reference `&fn(u32) -> u32 {bar}` + = note: different fn items have unique types, even if their signatures are the same + +error[E0308]: mismatched types + --> $DIR/fn-pointer-mismatch.rs:23:9 + | +LL | let mut a = foo; + | --- expected due to this value +LL | a = bar; + | ^^^ expected fn item, found a different fn item + | + = note: expected fn item `fn(_) -> _ {foo}` + found fn item `fn(_) -> _ {bar}` + = note: different fn items have unique types, even if their signatures are the same + +error[E0308]: mismatched types + --> $DIR/fn-pointer-mismatch.rs:31:18 + | +LL | b = Box::new(bar); + | -------- ^^^ expected fn item, found a different fn item + | | + | arguments to this function are incorrect + | + = note: expected fn item `fn(_) -> _ {foo}` + found fn item `fn(_) -> _ {bar}` + = note: different fn items have unique types, even if their signatures are the same +note: associated function defined here + --> $SRC_DIR/alloc/src/boxed.rs:LL:COL + +error[E0308]: mismatched types + --> $DIR/fn-pointer-mismatch.rs:36:29 + | +LL | let c: fn(u32) -> u32 = &foo; + | -------------- ^^^^ + | | | + | | expected fn pointer, found reference + | | help: consider removing the reference: `foo` + | expected due to this + | + = note: expected fn pointer `fn(u32) -> u32` + found reference `&fn(u32) -> u32 {foo}` + +error[E0308]: mismatched types + --> $DIR/fn-pointer-mismatch.rs:42:30 + | +LL | let d: &fn(u32) -> u32 = foo; + | --------------- ^^^ + | | | + | | expected `&fn(u32) -> u32`, found fn item + | | help: consider using a reference: `&foo` + | expected due to this + | + = note: expected reference `&fn(u32) -> u32` + found fn item `fn(u32) -> u32 {foo}` + +error[E0308]: mismatched types + --> $DIR/fn-pointer-mismatch.rs:48:30 + | +LL | let e: &fn(u32) -> u32 = &foo; + | --------------- ^^^^ + | | | + | | expected fn pointer, found fn item + | | help: consider casting to a fn pointer: `&(foo as fn(u32) -> u32)` + | expected due to this + | + = note: expected reference `&fn(u32) -> u32` + found reference `&fn(u32) -> u32 {foo}` + = note: fn items are distinct from fn pointers + +error: aborting due to 6 previous errors + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/reify-intrinsic.stderr b/tests/ui/reify-intrinsic.stderr index f78f1d822bf60..310b6c224e0e7 100644 --- a/tests/ui/reify-intrinsic.stderr +++ b/tests/ui/reify-intrinsic.stderr @@ -23,9 +23,7 @@ LL | std::intrinsics::unlikely, | = note: expected fn item `extern "rust-intrinsic" fn(_) -> _ {likely}` found fn item `extern "rust-intrinsic" fn(_) -> _ {unlikely}` - = note: different `fn` items always have unique types, even if their signatures are the same - = help: change the expected type to be function pointer `extern "rust-intrinsic" fn(bool) -> bool` - = help: if the expected type is due to type inference, cast the expected `fn` to a function pointer: `likely as extern "rust-intrinsic" fn(bool) -> bool` + = note: different fn items have unique types, even if their signatures are the same error: aborting due to 3 previous errors diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.mir.stderr b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.mir.stderr index cf5815df56e1c..07f6dc906c6bb 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.mir.stderr +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.mir.stderr @@ -5,12 +5,15 @@ LL | #[target_feature(enable = "sse2")] | ---------------------------------- `#[target_feature]` added here ... LL | let foo: fn() = foo; - | ---- ^^^ cannot coerce functions with `#[target_feature]` to safe function pointers - | | + | ---- ^^^ + | | | + | | cannot coerce functions with `#[target_feature]` to safe function pointers + | | help: consider casting to a fn pointer: `foo as fn()` | expected due to this | = note: expected fn pointer `fn()` found fn item `fn() {foo}` + = note: fn items are distinct from fn pointers = note: functions with `#[target_feature]` can only be coerced to `unsafe` function pointers error: aborting due to previous error diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.thir.stderr b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.thir.stderr index cf5815df56e1c..07f6dc906c6bb 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.thir.stderr +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.thir.stderr @@ -5,12 +5,15 @@ LL | #[target_feature(enable = "sse2")] | ---------------------------------- `#[target_feature]` added here ... LL | let foo: fn() = foo; - | ---- ^^^ cannot coerce functions with `#[target_feature]` to safe function pointers - | | + | ---- ^^^ + | | | + | | cannot coerce functions with `#[target_feature]` to safe function pointers + | | help: consider casting to a fn pointer: `foo as fn()` | expected due to this | = note: expected fn pointer `fn()` found fn item `fn() {foo}` + = note: fn items are distinct from fn pointers = note: functions with `#[target_feature]` can only be coerced to `unsafe` function pointers error: aborting due to previous error diff --git a/tests/ui/static/static-reference-to-fn-1.stderr b/tests/ui/static/static-reference-to-fn-1.stderr index 67b478bdb75c3..f68939d0ec8c9 100644 --- a/tests/ui/static/static-reference-to-fn-1.stderr +++ b/tests/ui/static/static-reference-to-fn-1.stderr @@ -2,10 +2,14 @@ error[E0308]: mismatched types --> $DIR/static-reference-to-fn-1.rs:17:15 | LL | func: &foo, - | ^^^^ expected fn pointer, found fn item + | ^^^^ + | | + | expected fn pointer, found fn item + | help: consider casting to a fn pointer: `&(foo as fn() -> Option)` | = note: expected reference `&fn() -> Option` found reference `&fn() -> Option {foo}` + = note: fn items are distinct from fn pointers error: aborting due to previous error From 1d8491b120223272b13451fc81265aa64f7f4d5b Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Tue, 24 Jan 2023 13:08:52 -0600 Subject: [PATCH 338/500] chore: prep v1.5.2 release --- CHANGELOG.md | 26 ++++++++++++++++++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e9ce930dabc68..60f961fa12ac8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,32 @@ ## [Unreleased] +## [1.5.2] 2023-01-24 + +### Fixed + +- Resolve issue when comments are found within const generic defaults in unit structs [#5668](https://github.com/rust-lang/rustfmt/issues/5668) +- Resolve issue when block comments are found within trait generics [#5358](https://github.com/rust-lang/rustfmt/issues/5358) +- Correctly handle alignment of comments containing unicode characters [#5504](https://github.com/rust-lang/rustfmt/issues/5504) +- Properly indent a single generic bound that requires being written across multiple lines [#4689](https://github.com/rust-lang/rustfmt/issues/4689) (n.b. this change is version gated and will only appear when the `version` configuration option is set to `Two`) + +### Changed + +- Renamed `fn_args_layout` configuration option to `fn_params_layout` [#4149](https://github.com/rust-lang/rustfmt/issues/4149). Note that `fn_args_layout` has only been soft deprecated: `fn_args_layout` will continue to work without issue, but rustfmt will display a warning to encourage users to switch to the new name + +### Added + +- New configuration option (`skip_macro_invocations`)[https://rust-lang.github.io/rustfmt/?version=master&search=#skip_macro_invocations] [#5347](https://github.com/rust-lang/rustfmt/pull/5347) that can be used to globally define a single enumerated list of macro calls that rustfmt should skip formatting. rustfmt [currently also supports this via a custom tool attribute](https://github.com/rust-lang/rustfmt#tips), however, these cannot be used in all contexts because [custom inner attributes are unstable](https://github.com/rust-lang/rust/issues/54726) + +### Misc + +- rustfmt now internally supports the ability to have both stable and unstable variants of a configuration option [#5378](https://github.com/rust-lang/rustfmt/issues/5378). This ability will allow the rustfmt team to make certain configuration options available on stable toolchains more quickly because we no longer have to wait for _every_ variant to be stable-ready before stabilizing _any_ variant. + +### Install/Download Options +- **rustup (nightly)** - nightly-2023-01-24 +- **GitHub Release Binaries** - [Release v1.5.2](https://github.com/rust-lang/rustfmt/releases/tag/v1.5.2) +- **Build from source** - [Tag v1.5.2](https://github.com/rust-lang/rustfmt/tree/v1.5.2), see instructions for how to [install rustfmt from source][install-from-source] + ## [1.5.1] 2022-06-24 **N.B** A bug was introduced in v1.5.0/nightly-2022-06-15 which modified formatting. If you happened to run rustfmt over your code with one of those ~10 nightlies it's possible you may have seen formatting changes, and you may see additional changes after this fix since that bug has now been reverted. diff --git a/Cargo.lock b/Cargo.lock index e51755289706c..24166d51c51fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -485,7 +485,7 @@ dependencies = [ [[package]] name = "rustfmt-nightly" -version = "1.5.1" +version = "1.5.2" dependencies = [ "annotate-snippets", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 7438335eaa78f..87ce59d0217e8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustfmt-nightly" -version = "1.5.1" +version = "1.5.2" description = "Tool to find and fix Rust formatting issues" repository = "https://github.com/rust-lang/rustfmt" readme = "README.md" From 6bf1a87fcd45dbde0d8c69099a3ab74197bd2fc8 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Tue, 24 Jan 2023 14:21:14 -0600 Subject: [PATCH 339/500] update rustfmt subtree version in lockfile --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8e1a3c57f0314..65571b1472f00 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4926,7 +4926,7 @@ dependencies = [ [[package]] name = "rustfmt-config_proc_macro" -version = "0.2.0" +version = "0.3.0" dependencies = [ "proc-macro2", "quote", @@ -4936,7 +4936,7 @@ dependencies = [ [[package]] name = "rustfmt-nightly" -version = "1.5.1" +version = "1.5.2" dependencies = [ "annotate-snippets", "anyhow", From e9eb979081a134c6a06a937ba8732899d6aa0cc3 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Tue, 24 Jan 2023 20:34:33 +0000 Subject: [PATCH 340/500] Update cargo 11 commits in 985d561f0bb9b76ec043a2b12511790ec7a2b954..3c5af6bed9a1a243a693e8e22ee2486bd5b82a6c 2023-01-20 14:39:28 +0000 to 2023-01-24 15:48:15 +0000 - Add a note about verifying your email address on crates.io (rust-lang/cargo#11620) - Improve CI caching by skipping mtime checks for paths in $CARGO_HOME (rust-lang/cargo#11613) - test: Update for clap 4.1.3 (rust-lang/cargo#11619) - Fix unused attribute on Windows. (rust-lang/cargo#11614) - [Doc]: Added links to the `Target` section of the glossary for occurences of `target triple` (rust-lang/cargo#11603) - feat: stabilize auto fix note (rust-lang/cargo#11558) - Clarify the difference between CARGO_CRATE_NAME and CARGO_PKG_NAME (rust-lang/cargo#11576) - Temporarily pin libgit2-sys. (rust-lang/cargo#11609) - Disable network SSH tests on windows. (rust-lang/cargo#11610) - fix(toml): Add `default-features` to `TomlWorkspaceDependency` (rust-lang/cargo#11409) - doc(contrib): remove rls in release process (rust-lang/cargo#11601) --- Cargo.lock | 22 +++++++++++----------- src/tools/cargo | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8e1a3c57f0314..d31bc533d330c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -351,7 +351,7 @@ dependencies = [ "cargo-test-macro", "cargo-test-support", "cargo-util", - "clap 4.1.1", + "clap 4.1.3", "crates-io", "curl", "curl-sys", @@ -655,9 +655,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.1.1" +version = "4.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ec7a4128863c188deefe750ac1d1dfe66c236909f845af04beed823638dc1b2" +checksum = "d8d93d855ce6a0aa87b8473ef9169482f40abaa2e9e0993024c35c902cbd5920" dependencies = [ "bitflags", "clap_derive 4.1.0", @@ -675,7 +675,7 @@ version = "4.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10861370d2ba66b0f5989f83ebf35db6421713fd92351790e7fdd6c36774c56b" dependencies = [ - "clap 4.1.1", + "clap 4.1.3", ] [[package]] @@ -1799,9 +1799,9 @@ dependencies = [ [[package]] name = "git2" -version = "0.16.1" +version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf7f68c2995f392c49fffb4f95ae2c873297830eb25c6bc4c114ce8f4562acc" +checksum = "be36bc9e0546df253c0cc41fd0af34f5e92845ad8509462ec76672fac6997f5b" dependencies = [ "bitflags", "libc", @@ -2294,7 +2294,7 @@ name = "jsondoclint" version = "0.1.0" dependencies = [ "anyhow", - "clap 4.1.1", + "clap 4.1.3", "fs-err", "rustdoc-json-types", "serde", @@ -2365,9 +2365,9 @@ dependencies = [ [[package]] name = "libgit2-sys" -version = "0.14.2+1.5.1" +version = "0.14.1+1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f3d95f6b51075fe9810a7ae22c7095f12b98005ab364d8544797a825ce946a4" +checksum = "4a07fb2692bc3593bda59de45a502bb3071659f2c515e28c71e728306b038e17" dependencies = [ "cc", "libc", @@ -2557,7 +2557,7 @@ dependencies = [ "ammonia", "anyhow", "chrono", - "clap 4.1.1", + "clap 4.1.3", "clap_complete", "elasticlunr-rs", "env_logger 0.10.0", @@ -3528,7 +3528,7 @@ dependencies = [ name = "rustbook" version = "0.1.0" dependencies = [ - "clap 4.1.1", + "clap 4.1.3", "env_logger 0.7.1", "mdbook", ] diff --git a/src/tools/cargo b/src/tools/cargo index 985d561f0bb9b..3c5af6bed9a1a 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit 985d561f0bb9b76ec043a2b12511790ec7a2b954 +Subproject commit 3c5af6bed9a1a243a693e8e22ee2486bd5b82a6c From 5b77cb459fd358947ecf2173b5c46a0a5a86a2ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 24 Jan 2023 21:40:43 +0100 Subject: [PATCH 341/500] Port pgo.sh to Python --- .github/workflows/ci.yml | 2 +- .../host-x86_64/dist-x86_64-linux/Dockerfile | 2 +- src/ci/github-actions/ci.yml | 2 +- src/ci/stage-build.py | 663 ++++++++++++++++++ 4 files changed, 666 insertions(+), 3 deletions(-) create mode 100644 src/ci/stage-build.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 82048f800d0e8..04a50f1f10785 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -439,7 +439,7 @@ jobs: - name: dist-x86_64-msvc env: RUST_CONFIGURE_ARGS: "--build=x86_64-pc-windows-msvc --host=x86_64-pc-windows-msvc --target=x86_64-pc-windows-msvc --enable-full-tools --enable-profiler --set rust.lto=thin" - SCRIPT: PGO_HOST=x86_64-pc-windows-msvc src/ci/pgo.sh python x.py dist bootstrap --include-default-paths + SCRIPT: PGO_HOST=x86_64-pc-windows-msvc python src/ci/stage-build.py python x.py dist bootstrap --include-default-paths DIST_REQUIRE_ALL_TOOLS: 1 os: windows-latest-xl - name: dist-i686-msvc diff --git a/src/ci/docker/host-x86_64/dist-x86_64-linux/Dockerfile b/src/ci/docker/host-x86_64/dist-x86_64-linux/Dockerfile index 6bdc88e18f530..5feba4e0605ec 100644 --- a/src/ci/docker/host-x86_64/dist-x86_64-linux/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-x86_64-linux/Dockerfile @@ -81,7 +81,7 @@ ENV RUST_CONFIGURE_ARGS \ --set rust.jemalloc \ --set rust.use-lld=true \ --set rust.lto=thin -ENV SCRIPT ../src/ci/pgo.sh python3 ../x.py dist \ +ENV SCRIPT python3 ../src/ci/stage-build.py python3 ../x.py dist \ --host $HOSTS --target $HOSTS \ --include-default-paths \ build-manifest bootstrap diff --git a/src/ci/github-actions/ci.yml b/src/ci/github-actions/ci.yml index d2a9264c84a12..8d86590777be3 100644 --- a/src/ci/github-actions/ci.yml +++ b/src/ci/github-actions/ci.yml @@ -676,7 +676,7 @@ jobs: --enable-full-tools --enable-profiler --set rust.lto=thin - SCRIPT: PGO_HOST=x86_64-pc-windows-msvc src/ci/pgo.sh python x.py dist bootstrap --include-default-paths + SCRIPT: PGO_HOST=x86_64-pc-windows-msvc python src/ci/stage-build.py python x.py dist bootstrap --include-default-paths DIST_REQUIRE_ALL_TOOLS: 1 <<: *job-windows-xl diff --git a/src/ci/stage-build.py b/src/ci/stage-build.py new file mode 100644 index 0000000000000..c373edfcf46a2 --- /dev/null +++ b/src/ci/stage-build.py @@ -0,0 +1,663 @@ +#!/usr/bin/env python3 +# ignore-tidy-linelength + +# Compatible with Python 3.6+ + +import contextlib +import getpass +import glob +import logging +import os +import pprint +import shutil +import subprocess +import sys +import time +import traceback +import urllib.request +from collections import OrderedDict +from io import StringIO +from pathlib import Path +from typing import Callable, Dict, Iterable, List, Optional, Union + +PGO_HOST = os.environ["PGO_HOST"] + +LOGGER = logging.getLogger("stage-build") + +LLVM_PGO_CRATES = [ + "syn-1.0.89", + "cargo-0.60.0", + "serde-1.0.136", + "ripgrep-13.0.0", + "regex-1.5.5", + "clap-3.1.6", + "hyper-0.14.18" +] + +RUSTC_PGO_CRATES = [ + "externs", + "ctfe-stress-5", + "cargo-0.60.0", + "token-stream-stress", + "match-stress", + "tuple-stress", + "diesel-1.4.8", + "bitmaps-3.1.0" +] + +LLVM_BOLT_CRATES = LLVM_PGO_CRATES + + +class Pipeline: + # Paths + def checkout_path(self) -> Path: + """ + The root checkout, where the source is located. + """ + raise NotImplementedError + + def downloaded_llvm_dir(self) -> Path: + """ + Directory where the host LLVM is located. + """ + raise NotImplementedError + + def build_root(self) -> Path: + """ + The main directory where the build occurs. + """ + raise NotImplementedError + + def build_artifacts(self) -> Path: + return self.build_root() / "build" / PGO_HOST + + def rustc_stage_0(self) -> Path: + return self.build_artifacts() / "stage0" / "bin" / "rustc" + + def cargo_stage_0(self) -> Path: + return self.build_artifacts() / "stage0" / "bin" / "cargo" + + def rustc_stage_2(self) -> Path: + return self.build_artifacts() / "stage2" / "bin" / "rustc" + + def opt_artifacts(self) -> Path: + raise NotImplementedError + + def llvm_profile_dir_root(self) -> Path: + return self.opt_artifacts() / "llvm-pgo" + + def llvm_profile_merged_file(self) -> Path: + return self.opt_artifacts() / "llvm-pgo.profdata" + + def rustc_perf_dir(self) -> Path: + return self.opt_artifacts() / "rustc-perf" + + def build_rustc_perf(self): + raise NotImplementedError() + + def rustc_profile_dir_root(self) -> Path: + return self.opt_artifacts() / "rustc-pgo" + + def rustc_profile_merged_file(self) -> Path: + return self.opt_artifacts() / "rustc-pgo.profdata" + + def rustc_profile_template_path(self) -> Path: + """ + The profile data is written into a single filepath that is being repeatedly merged when each + rustc invocation ends. Empirically, this can result in some profiling data being lost. That's + why we override the profile path to include the PID. This will produce many more profiling + files, but the resulting profile will produce a slightly faster rustc binary. + """ + return self.rustc_profile_dir_root() / "default_%m_%p.profraw" + + def supports_bolt(self) -> bool: + raise NotImplementedError + + def llvm_bolt_profile_merged_file(self) -> Path: + return self.opt_artifacts() / "bolt.profdata" + + +class LinuxPipeline(Pipeline): + def checkout_path(self) -> Path: + return Path("/checkout") + + def downloaded_llvm_dir(self) -> Path: + return Path("/rustroot") + + def build_root(self) -> Path: + return self.checkout_path() / "obj" + + def opt_artifacts(self) -> Path: + return Path("/tmp/tmp-multistage/opt-artifacts") + + def build_rustc_perf(self): + # /tmp/rustc-perf comes from the Dockerfile + shutil.copytree("/tmp/rustc-perf", self.rustc_perf_dir()) + cmd(["chown", "-R", f"{getpass.getuser()}:", self.rustc_perf_dir()]) + + with change_cwd(self.rustc_perf_dir()): + cmd([self.cargo_stage_0(), "build", "-p", "collector"], env=dict( + RUSTC=str(self.rustc_stage_0()), + RUSTC_BOOTSTRAP="1" + )) + + def supports_bolt(self) -> bool: + return True + + +class WindowsPipeline(Pipeline): + def __init__(self): + self.checkout_dir = Path(os.getcwd()) + + def checkout_path(self) -> Path: + return self.checkout_dir + + def downloaded_llvm_dir(self) -> Path: + return self.checkout_path() / "citools" / "clang-rust" + + def build_root(self) -> Path: + return self.checkout_path() + + def opt_artifacts(self) -> Path: + return self.checkout_path() / "opt-artifacts" + + def rustc_stage_0(self) -> Path: + return super().rustc_stage_0().with_suffix(".exe") + + def cargo_stage_0(self) -> Path: + return super().cargo_stage_0().with_suffix(".exe") + + def rustc_stage_2(self) -> Path: + return super().rustc_stage_2().with_suffix(".exe") + + def build_rustc_perf(self): + # rustc-perf version from 2022-07-22 + perf_commit = "3c253134664fdcba862c539d37f0de18557a9a4c" + rustc_perf_zip_path = self.opt_artifacts() / "perf.zip" + + def download_rustc_perf(): + download_file( + f"https://github.com/rust-lang/rustc-perf/archive/{perf_commit}.zip", + rustc_perf_zip_path + ) + with change_cwd(self.opt_artifacts()): + unpack_archive(rustc_perf_zip_path) + move_path(Path(f"rustc-perf-{perf_commit}"), self.rustc_perf_dir()) + delete_file(rustc_perf_zip_path) + + retry_action(download_rustc_perf, "Download rustc-perf") + + with change_cwd(self.rustc_perf_dir()): + cmd([self.cargo_stage_0(), "build", "-p", "collector"], env=dict( + RUSTC=str(self.rustc_stage_0()), + RUSTC_BOOTSTRAP="1" + )) + + def rustc_profile_template_path(self) -> Path: + """ + On Windows, we don't have enough space to use separate files for each rustc invocation. + Therefore, we use a single file for the generated profiles. + """ + return self.rustc_profile_dir_root() / "default_%m.profraw" + + def supports_bolt(self) -> bool: + return False + + +class Timer: + def __init__(self): + # We want this dictionary to be ordered by insertion. + # We use `OrderedDict` for compatibility with older Python versions. + self.stages = OrderedDict() + + @contextlib.contextmanager + def stage(self, name: str): + assert name not in self.stages + + start = time.time() + exc = None + try: + LOGGER.info(f"Stage `{name}` starts") + yield + except BaseException as exception: + exc = exception + raise + finally: + end = time.time() + duration = end - start + self.stages[name] = duration + if exc is None: + LOGGER.info(f"Stage `{name}` ended: OK ({duration:.2f}s)") + else: + LOGGER.info(f"Stage `{name}` ended: FAIL ({duration:.2f}s)") + + def print_stats(self): + total_duration = sum(self.stages.values()) + + # 57 is the width of the whole table + divider = "-" * 57 + + with StringIO() as output: + print(divider, file=output) + for (name, duration) in self.stages.items(): + pct = (duration / total_duration) * 100 + name_str = f"{name}:" + print(f"{name_str:<34} {duration:>12.2f}s ({pct:>5.2f}%)", file=output) + + total_duration_label = "Total duration:" + print(f"{total_duration_label:<34} {total_duration:>12.2f}s", file=output) + print(divider, file=output, end="") + LOGGER.info(f"Timer results\n{output.getvalue()}") + + +@contextlib.contextmanager +def change_cwd(dir: Path): + """ + Temporarily change working directory to `dir`. + """ + cwd = os.getcwd() + LOGGER.debug(f"Changing working dir from `{cwd}` to `{dir}`") + os.chdir(dir) + try: + yield + finally: + LOGGER.debug(f"Reverting working dir to `{cwd}`") + os.chdir(cwd) + + +def move_path(src: Path, dst: Path): + LOGGER.info(f"Moving `{src}` to `{dst}`") + shutil.move(src, dst) + + +def delete_file(path: Path): + LOGGER.info(f"Deleting file `{path}`") + os.unlink(path) + + +def delete_directory(path: Path): + LOGGER.info(f"Deleting directory `{path}`") + shutil.rmtree(path) + + +def unpack_archive(archive: Path): + LOGGER.info(f"Unpacking archive `{archive}`") + shutil.unpack_archive(archive) + + +def download_file(src: str, target: Path): + LOGGER.info(f"Downloading `{src}` into `{target}`") + urllib.request.urlretrieve(src, str(target)) + + +def retry_action(action, name: str, max_fails: int = 5): + LOGGER.info(f"Attempting to perform action `{name}` with retry") + for iteration in range(max_fails): + LOGGER.info(f"Attempt {iteration + 1}/{max_fails}") + try: + action() + return + except: + LOGGER.error(f"Action `{name}` has failed\n{traceback.format_exc()}") + + raise Exception(f"Action `{name}` has failed after {max_fails} attempts") + + +def cmd( + args: List[Union[str, Path]], + env: Optional[Dict[str, str]] = None, + output_path: Optional[Path] = None +): + args = [str(arg) for arg in args] + + environment = os.environ.copy() + + cmd_str = "" + if env is not None: + environment.update(env) + cmd_str += " ".join(f"{k}={v}" for (k, v) in (env or {}).items()) + cmd_str += " " + cmd_str += " ".join(args) + if output_path is not None: + cmd_str += f" > {output_path}" + LOGGER.info(f"Executing `{cmd_str}`") + + if output_path is not None: + with open(output_path, "w") as f: + return subprocess.run( + args, + env=environment, + check=True, + stdout=f + ) + return subprocess.run(args, env=environment, check=True) + + +def run_compiler_benchmarks( + pipeline: Pipeline, + profiles: List[str], + scenarios: List[str], + crates: List[str], + env: Optional[Dict[str, str]] = None +): + env = env if env is not None else {} + + # Compile libcore, both in opt-level=0 and opt-level=3 + with change_cwd(pipeline.build_root()): + cmd([ + pipeline.rustc_stage_2(), + "--edition", "2021", + "--crate-type", "lib", + str(pipeline.checkout_path() / "library/core/src/lib.rs"), + "--out-dir", pipeline.opt_artifacts() + ], env=dict(RUSTC_BOOTSTRAP="1", **env)) + + cmd([ + pipeline.rustc_stage_2(), + "--edition", "2021", + "--crate-type", "lib", + "-Copt-level=3", + str(pipeline.checkout_path() / "library/core/src/lib.rs"), + "--out-dir", pipeline.opt_artifacts() + ], env=dict(RUSTC_BOOTSTRAP="1", **env)) + + # Run rustc-perf benchmarks + # Benchmark using profile_local with eprintln, which essentially just means + # don't actually benchmark -- just make sure we run rustc a bunch of times. + with change_cwd(pipeline.rustc_perf_dir()): + cmd([ + pipeline.cargo_stage_0(), + "run", + "-p", "collector", "--bin", "collector", "--", + "profile_local", "eprintln", + pipeline.rustc_stage_2(), + "--id", "Test", + "--cargo", pipeline.cargo_stage_0(), + "--profiles", ",".join(profiles), + "--scenarios", ",".join(scenarios), + "--include", ",".join(crates) + ], env=dict( + RUST_LOG="collector=debug", + RUSTC=str(pipeline.rustc_stage_0()), + RUSTC_BOOTSTRAP="1", + **env + )) + + +# https://stackoverflow.com/a/31631711/1107768 +def format_bytes(size: int) -> str: + """Return the given bytes as a human friendly KiB, MiB or GiB string.""" + KB = 1024 + MB = KB ** 2 # 1,048,576 + GB = KB ** 3 # 1,073,741,824 + TB = KB ** 4 # 1,099,511,627,776 + + if size < KB: + return f"{size} B" + elif KB <= size < MB: + return f"{size / KB:.2f} KiB" + elif MB <= size < GB: + return f"{size / MB:.2f} MiB" + elif GB <= size < TB: + return f"{size / GB:.2f} GiB" + else: + return str(size) + + +# https://stackoverflow.com/a/63307131/1107768 +def count_files(path: Path) -> int: + return sum(1 for p in path.rglob("*") if p.is_file()) + + +def count_files_with_prefix(path: Path) -> int: + return sum(1 for p in glob.glob(f"{path}*") if Path(p).is_file()) + + +# https://stackoverflow.com/a/55659577/1107768 +def get_path_size(path: Path) -> int: + if path.is_dir(): + return sum(p.stat().st_size for p in path.rglob("*")) + return path.stat().st_size + + +def get_path_prefix_size(path: Path) -> int: + """ + Get size of all files beginning with the prefix `path`. + Alternative to shell `du -sh *`. + """ + return sum(Path(p).stat().st_size for p in glob.glob(f"{path}*")) + + +def get_files(directory: Path, filter: Optional[Callable[[Path], bool]] = None) -> Iterable[Path]: + for file in os.listdir(directory): + path = directory / file + if filter is None or filter(path): + yield path + + +def build_rustc( + pipeline: Pipeline, + args: List[str], + env: Optional[Dict[str, str]] = None +): + arguments = [ + sys.executable, + pipeline.checkout_path() / "x.py", + "build", + "--target", PGO_HOST, + "--host", PGO_HOST, + "--stage", "2", + "library/std" + ] + args + cmd(arguments, env=env) + + +def create_pipeline() -> Pipeline: + if sys.platform == "linux": + return LinuxPipeline() + elif sys.platform in ("cygwin", "win32"): + return WindowsPipeline() + else: + raise Exception(f"Optimized build is not supported for platform {sys.platform}") + + +def gather_llvm_profiles(pipeline: Pipeline): + LOGGER.info("Running benchmarks with PGO instrumented LLVM") + run_compiler_benchmarks( + pipeline, + profiles=["Debug", "Opt"], + scenarios=["Full"], + crates=LLVM_PGO_CRATES + ) + + profile_path = pipeline.llvm_profile_merged_file() + LOGGER.info(f"Merging LLVM PGO profiles to {profile_path}") + cmd([ + pipeline.downloaded_llvm_dir() / "bin" / "llvm-profdata", + "merge", + "-o", profile_path, + pipeline.llvm_profile_dir_root() + ]) + + LOGGER.info("LLVM PGO statistics") + LOGGER.info(f"{profile_path}: {format_bytes(get_path_size(profile_path))}") + LOGGER.info( + f"{pipeline.llvm_profile_dir_root()}: {format_bytes(get_path_size(pipeline.llvm_profile_dir_root()))}") + LOGGER.info(f"Profile file count: {count_files(pipeline.llvm_profile_dir_root())}") + + # We don't need the individual .profraw files now that they have been merged + # into a final .profdata + delete_directory(pipeline.llvm_profile_dir_root()) + + +def gather_rustc_profiles(pipeline: Pipeline): + LOGGER.info("Running benchmarks with PGO instrumented rustc") + + # Here we're profiling the `rustc` frontend, so we also include `Check`. + # The benchmark set includes various stress tests that put the frontend under pressure. + run_compiler_benchmarks( + pipeline, + profiles=["Check", "Debug", "Opt"], + scenarios=["All"], + crates=RUSTC_PGO_CRATES, + env=dict( + LLVM_PROFILE_FILE=str(pipeline.rustc_profile_template_path()) + ) + ) + + profile_path = pipeline.rustc_profile_merged_file() + LOGGER.info(f"Merging Rustc PGO profiles to {profile_path}") + cmd([ + pipeline.build_artifacts() / "llvm" / "bin" / "llvm-profdata", + "merge", + "-o", profile_path, + pipeline.rustc_profile_dir_root() + ]) + + LOGGER.info("Rustc PGO statistics") + LOGGER.info(f"{profile_path}: {format_bytes(get_path_size(profile_path))}") + LOGGER.info( + f"{pipeline.rustc_profile_dir_root()}: {format_bytes(get_path_size(pipeline.rustc_profile_dir_root()))}") + LOGGER.info(f"Profile file count: {count_files(pipeline.rustc_profile_dir_root())}") + + # We don't need the individual .profraw files now that they have been merged + # into a final .profdata + delete_directory(pipeline.rustc_profile_dir_root()) + + +def gather_llvm_bolt_profiles(pipeline: Pipeline): + LOGGER.info("Running benchmarks with BOLT instrumented LLVM") + run_compiler_benchmarks( + pipeline, + profiles=["Check", "Debug", "Opt"], + scenarios=["Full"], + crates=LLVM_BOLT_CRATES + ) + + merged_profile_path = pipeline.llvm_bolt_profile_merged_file() + profile_files_path = Path("/tmp/prof.fdata") + LOGGER.info(f"Merging LLVM BOLT profiles to {merged_profile_path}") + + profile_files = sorted(glob.glob(f"{profile_files_path}*")) + cmd([ + "merge-fdata", + *profile_files, + ], output_path=merged_profile_path) + + LOGGER.info("LLVM BOLT statistics") + LOGGER.info(f"{merged_profile_path}: {format_bytes(get_path_size(merged_profile_path))}") + LOGGER.info( + f"{profile_files_path}: {format_bytes(get_path_prefix_size(profile_files_path))}") + LOGGER.info(f"Profile file count: {count_files_with_prefix(profile_files_path)}") + + +def clear_llvm_files(pipeline: Pipeline): + """ + Rustbuild currently doesn't support rebuilding LLVM when PGO options + change (or any other llvm-related options); so just clear out the relevant + directories ourselves. + """ + LOGGER.info("Clearing LLVM build files") + delete_directory(pipeline.build_artifacts() / "llvm") + delete_directory(pipeline.build_artifacts() / "lld") + + +def print_binary_sizes(pipeline: Pipeline): + bin_dir = pipeline.build_artifacts() / "stage2" / "bin" + binaries = get_files(bin_dir) + + lib_dir = pipeline.build_artifacts() / "stage2" / "lib" + libraries = get_files(lib_dir, lambda p: p.suffix == ".so") + + paths = sorted(binaries) + sorted(libraries) + with StringIO() as output: + for path in paths: + path_str = f"{path.name}:" + print(f"{path_str:<30}{format_bytes(path.stat().st_size):>14}", file=output) + LOGGER.info(f"Rustc binary size\n{output.getvalue()}") + + +def execute_build_pipeline(timer: Timer, pipeline: Pipeline, final_build_args: List[str]): + # Clear and prepare tmp directory + shutil.rmtree(pipeline.opt_artifacts(), ignore_errors=True) + os.makedirs(pipeline.opt_artifacts(), exist_ok=True) + + pipeline.build_rustc_perf() + + # Stage 1: Build rustc + PGO instrumented LLVM + with timer.stage("Build rustc (LLVM PGO)"): + build_rustc(pipeline, args=[ + "--llvm-profile-generate" + ], env=dict( + LLVM_PROFILE_DIR=str(pipeline.llvm_profile_dir_root() / "prof-%p") + )) + + with timer.stage("Gather profiles (LLVM PGO)"): + gather_llvm_profiles(pipeline) + + clear_llvm_files(pipeline) + final_build_args += [ + "--llvm-profile-use", + pipeline.llvm_profile_merged_file() + ] + + # Stage 2: Build PGO instrumented rustc + LLVM + with timer.stage("Build rustc (rustc PGO)"): + build_rustc(pipeline, args=[ + "--rust-profile-generate", + pipeline.rustc_profile_dir_root() + ]) + + with timer.stage("Gather profiles (rustc PGO)"): + gather_rustc_profiles(pipeline) + + clear_llvm_files(pipeline) + final_build_args += [ + "--rust-profile-use", + pipeline.rustc_profile_merged_file() + ] + + # Stage 3: Build rustc + BOLT instrumented LLVM + if pipeline.supports_bolt(): + with timer.stage("Build rustc (LLVM BOLT)"): + build_rustc(pipeline, args=[ + "--llvm-profile-use", + pipeline.llvm_profile_merged_file(), + "--llvm-bolt-profile-generate", + ]) + with timer.stage("Gather profiles (LLVM BOLT)"): + gather_llvm_bolt_profiles(pipeline) + + clear_llvm_files(pipeline) + final_build_args += [ + "--llvm-bolt-profile-use", + pipeline.llvm_bolt_profile_merged_file() + ] + + # Stage 4: Build PGO optimized rustc + PGO/BOLT optimized LLVM + with timer.stage("Final build"): + cmd(final_build_args) + + +if __name__ == "__main__": + logging.basicConfig( + level=logging.DEBUG, + format="%(name)s %(levelname)-4s: %(message)s", + ) + + LOGGER.info(f"Running multi-stage build using Python {sys.version}") + LOGGER.info(f"Environment values\n{pprint.pformat(dict(os.environ), indent=2)}") + + build_args = sys.argv[1:] + + timer = Timer() + pipeline = create_pipeline() + try: + execute_build_pipeline(timer, pipeline, build_args) + except BaseException as e: + LOGGER.error("The multi-stage build has failed") + raise e + finally: + timer.print_stats() + + print_binary_sizes(pipeline) From 430dab0b424abdf68d9071232a654874771570bc Mon Sep 17 00:00:00 2001 From: Boxy Date: Tue, 24 Jan 2023 23:24:25 +0000 Subject: [PATCH 342/500] implement builtin candidate --- .../src/solve/assembly.rs | 7 ++ .../src/solve/project_goals.rs | 92 +++++++++++++++++++ .../src/solve/trait_goals.rs | 7 ++ tests/ui/traits/new-solver/pointee.rs | 23 +++++ 4 files changed, 129 insertions(+) create mode 100644 tests/ui/traits/new-solver/pointee.rs diff --git a/compiler/rustc_trait_selection/src/solve/assembly.rs b/compiler/rustc_trait_selection/src/solve/assembly.rs index cdb72d49834f0..0b642fcba2812 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly.rs @@ -133,6 +133,11 @@ pub(super) trait GoalKind<'tcx>: TypeFoldable<'tcx> + Copy + Eq { ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; + + fn consider_builtin_pointee_candidate( + ecx: &mut EvalCtxt<'_, 'tcx>, + goal: Goal<'tcx, Self>, + ) -> QueryResult<'tcx>; } impl<'tcx> EvalCtxt<'_, 'tcx> { @@ -259,6 +264,8 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { G::consider_builtin_fn_trait_candidates(self, goal, kind) } else if lang_items.tuple_trait() == Some(trait_def_id) { G::consider_builtin_tuple_candidate(self, goal) + } else if lang_items.pointee_trait() == Some(trait_def_id) { + G::consider_builtin_pointee_candidate(self, goal) } else { Err(NoSolution) }; diff --git a/compiler/rustc_trait_selection/src/solve/project_goals.rs b/compiler/rustc_trait_selection/src/solve/project_goals.rs index 32e15f03998b3..914a1d6a66a67 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals.rs @@ -7,6 +7,7 @@ use super::{Certainty, EvalCtxt, Goal, QueryResult}; use rustc_errors::ErrorGuaranteed; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; +use rustc_hir::LangItem; use rustc_infer::infer::InferCtxt; use rustc_infer::traits::query::NoSolution; use rustc_infer::traits::specialization_graph::LeafDef; @@ -391,6 +392,97 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { ) -> QueryResult<'tcx> { bug!("`Tuple` does not have an associated type: {:?}", goal); } + + fn consider_builtin_pointee_candidate( + ecx: &mut EvalCtxt<'_, 'tcx>, + goal: Goal<'tcx, Self>, + ) -> QueryResult<'tcx> { + let tcx = ecx.tcx(); + ecx.infcx.probe(|_| { + let metadata_ty = match goal.predicate.self_ty().kind() { + ty::Bool + | ty::Char + | ty::Int(..) + | ty::Uint(..) + | ty::Float(..) + | ty::Array(..) + | ty::RawPtr(..) + | ty::Ref(..) + | ty::FnDef(..) + | ty::FnPtr(..) + | ty::Closure(..) + | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) + | ty::Generator(..) + | ty::GeneratorWitness(..) + | ty::Never + | ty::Foreign(..) => tcx.types.unit, + + ty::Error(e) => tcx.ty_error_with_guaranteed(*e), + + ty::Str | ty::Slice(_) => tcx.types.usize, + + ty::Dynamic(_, _, _) => { + let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, None); + tcx.bound_type_of(dyn_metadata) + .subst(tcx, &[ty::GenericArg::from(goal.predicate.self_ty())]) + } + + ty::Infer(ty::TyVar(..)) | ty::Alias(_, _) | ty::Param(_) | ty::Placeholder(..) => { + // FIXME(erica_solver, ptr_metadata): It would also be possible to return a `Ok(Ambig)` with no constraints. + let sized_predicate = ty::Binder::dummy(tcx.at(DUMMY_SP).mk_trait_ref( + LangItem::Sized, + [ty::GenericArg::from(goal.predicate.self_ty())], + )) + .without_const(); + + let mut nested_goals = ecx.infcx.eq( + goal.param_env, + goal.predicate.term.ty().unwrap(), + tcx.types.unit, + )?; + nested_goals.push(goal.with(tcx, sized_predicate)); + + return ecx.evaluate_all_and_make_canonical_response(nested_goals); + } + + ty::Adt(def, substs) if def.is_struct() => { + match def.non_enum_variant().fields.last() { + None => tcx.types.unit, + Some(field_def) => { + let self_ty = field_def.ty(tcx, substs); + let new_goal = goal.with( + tcx, + ty::Binder::dummy(goal.predicate.with_self_ty(tcx, self_ty)), + ); + return ecx.evaluate_all_and_make_canonical_response(vec![new_goal]); + } + } + } + ty::Adt(_, _) => tcx.types.unit, + + ty::Tuple(elements) => match elements.last() { + None => tcx.types.unit, + Some(&self_ty) => { + let new_goal = goal.with( + tcx, + ty::Binder::dummy(goal.predicate.with_self_ty(tcx, self_ty)), + ); + return ecx.evaluate_all_and_make_canonical_response(vec![new_goal]); + } + }, + + ty::Infer(ty::FreshTy(..) | ty::FreshIntTy(..) | ty::FreshFloatTy(..)) + | ty::Bound(..) => bug!( + "unexpected self ty `{:?}` when normalizing `::Metadata`", + goal.predicate.self_ty() + ), + }; + + let nested_goals = + ecx.infcx.eq(goal.param_env, goal.predicate.term.ty().unwrap(), metadata_ty)?; + ecx.evaluate_all_and_make_canonical_response(nested_goals) + }) + } } /// This behavior is also implemented in `rustc_ty_utils` and in the old `project` code. diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals.rs b/compiler/rustc_trait_selection/src/solve/trait_goals.rs index 4b6d673c999c9..67bd249566546 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals.rs @@ -185,6 +185,13 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { Err(NoSolution) } } + + fn consider_builtin_pointee_candidate( + ecx: &mut EvalCtxt<'_, 'tcx>, + _goal: Goal<'tcx, Self>, + ) -> QueryResult<'tcx> { + ecx.make_canonical_response(Certainty::Yes) + } } impl<'tcx> EvalCtxt<'_, 'tcx> { diff --git a/tests/ui/traits/new-solver/pointee.rs b/tests/ui/traits/new-solver/pointee.rs new file mode 100644 index 0000000000000..fa6ee2e2daf64 --- /dev/null +++ b/tests/ui/traits/new-solver/pointee.rs @@ -0,0 +1,23 @@ +// compile-flags: -Ztrait-solver=next +// check-pass +#![feature(ptr_metadata)] + +use std::ptr::{DynMetadata, Pointee}; + +trait Trait {} +struct MyDst(T); + +fn works() { + let _: ::Metadata = (); + let _: <[T] as Pointee>::Metadata = 1_usize; + let _: ::Metadata = 1_usize; + let _: as Pointee>::Metadata = give::>>(); + let _: as Pointee>::Metadata = (); + let _: <((((([u8],),),),),) as Pointee>::Metadata = 1_usize; +} + +fn give() -> U { + loop {} +} + +fn main() {} From 2f924b0e3cdebc341c88056af8fa0bacaed5acde Mon Sep 17 00:00:00 2001 From: Boxy Date: Tue, 24 Jan 2023 23:29:02 +0000 Subject: [PATCH 343/500] sorry erica --- compiler/rustc_trait_selection/src/solve/project_goals.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_trait_selection/src/solve/project_goals.rs b/compiler/rustc_trait_selection/src/solve/project_goals.rs index 914a1d6a66a67..d33dfba6247d8 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals.rs @@ -428,7 +428,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { } ty::Infer(ty::TyVar(..)) | ty::Alias(_, _) | ty::Param(_) | ty::Placeholder(..) => { - // FIXME(erica_solver, ptr_metadata): It would also be possible to return a `Ok(Ambig)` with no constraints. + // FIXME(ptr_metadata): It would also be possible to return a `Ok(Ambig)` with no constraints. let sized_predicate = ty::Binder::dummy(tcx.at(DUMMY_SP).mk_trait_ref( LangItem::Sized, [ty::GenericArg::from(goal.predicate.self_ty())], From a418e39b75a8b3628cfea0b233de2f8985331f6d Mon Sep 17 00:00:00 2001 From: Boxy Date: Tue, 24 Jan 2023 23:32:47 +0000 Subject: [PATCH 344/500] no without_constness --- compiler/rustc_trait_selection/src/solve/project_goals.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/compiler/rustc_trait_selection/src/solve/project_goals.rs b/compiler/rustc_trait_selection/src/solve/project_goals.rs index d33dfba6247d8..e5072d8e2d152 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals.rs @@ -432,8 +432,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { let sized_predicate = ty::Binder::dummy(tcx.at(DUMMY_SP).mk_trait_ref( LangItem::Sized, [ty::GenericArg::from(goal.predicate.self_ty())], - )) - .without_const(); + )); let mut nested_goals = ecx.infcx.eq( goal.param_env, From 1cd7dbfbf85599d764c403cb5fee555da16c003a Mon Sep 17 00:00:00 2001 From: Michal Rostecki Date: Mon, 16 Jan 2023 19:13:52 +0800 Subject: [PATCH 345/500] Add `target_has_atomic*` symbols if any atomic width is supported Atomic operations for different widths (8-bit, 16-bit, 32-bit etc.) are guarded by `target_has_atomic = "value"` symbol (i.e. `target_has_atomic = "8"`) (and the other derivatives), but before this change, there was no width-agnostic symbol indicating a general availability of atomic operations. This change introduces: * `target_has_atomic_load_store` symbol when atomics for any integer width are supported by the target. * `target_has_atomic` symbol when also CAS is supported. Fixes #106845 Signed-off-by: Michal Rostecki --- compiler/rustc_session/src/config.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 586454f76574c..09bd474688bf2 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -957,6 +957,7 @@ fn default_configuration(sess: &Session) -> CrateConfig { if sess.target.has_thread_local { ret.insert((sym::target_thread_local, None)); } + let mut has_atomic = false; for (i, align) in [ (8, layout.i8_align.abi), (16, layout.i16_align.abi), @@ -965,6 +966,7 @@ fn default_configuration(sess: &Session) -> CrateConfig { (128, layout.i128_align.abi), ] { if i >= min_atomic_width && i <= max_atomic_width { + has_atomic = true; let mut insert_atomic = |s, align: Align| { ret.insert((sym::target_has_atomic_load_store, Some(Symbol::intern(s)))); if atomic_cas { @@ -981,6 +983,12 @@ fn default_configuration(sess: &Session) -> CrateConfig { } } } + if sess.is_nightly_build() && has_atomic { + ret.insert((sym::target_has_atomic_load_store, None)); + if atomic_cas { + ret.insert((sym::target_has_atomic, None)); + } + } let panic_strategy = sess.panic_strategy(); ret.insert((sym::panic, Some(panic_strategy.desc_symbol()))); From 474ea87943c3077feb7d7f2a6f295bd06654ef82 Mon Sep 17 00:00:00 2001 From: Michal Rostecki Date: Mon, 16 Jan 2023 19:40:38 +0800 Subject: [PATCH 346/500] core: Support variety of atomic widths in width-agnostic functions Before this change, the following functions and macros were annotated with `#[cfg(target_has_atomic = "8")]` or `#[cfg(target_has_atomic_load_store = "8")]`: * `atomic_int` * `strongest_failure_ordering` * `atomic_swap` * `atomic_add` * `atomic_sub` * `atomic_compare_exchange` * `atomic_compare_exchange_weak` * `atomic_and` * `atomic_nand` * `atomic_or` * `atomic_xor` * `atomic_max` * `atomic_min` * `atomic_umax` * `atomic_umin` However, none of those functions and macros actually depend on 8-bit width and they are needed for all atomic widths (16-bit, 32-bit, 64-bit etc.). Some targets might not support 8-bit atomics (i.e. BPF, if we would enable atomic CAS for it). This change fixes that by removing the `"8"` argument from annotations, which results in accepting the whole variety of widths. Fixes #106845 Fixes #106795 Signed-off-by: Michal Rostecki --- library/core/src/sync/atomic.rs | 45 ++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 14367eb09bc75..818721062d7f7 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -1861,7 +1861,8 @@ macro_rules! if_not_8_bit { ($_:ident, $($tt:tt)*) => { $($tt)* }; } -#[cfg(target_has_atomic_load_store = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic_load_store))] +#[cfg_attr(bootstrap, cfg(target_has_atomic_load_store = "8"))] macro_rules! atomic_int { ($cfg_cas:meta, $cfg_align:meta, @@ -2988,7 +2989,8 @@ atomic_int_ptr_sized! { } #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] fn strongest_failure_ordering(order: Ordering) -> Ordering { match order { Release => Relaxed, @@ -3030,7 +3032,8 @@ unsafe fn atomic_load(dst: *const T, order: Ordering) -> T { } #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_swap`. @@ -3047,7 +3050,8 @@ unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T { /// Returns the previous value (like __sync_fetch_and_add). #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_add(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_add`. @@ -3064,7 +3068,8 @@ unsafe fn atomic_add(dst: *mut T, val: T, order: Ordering) -> T { /// Returns the previous value (like __sync_fetch_and_sub). #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_sub(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_sub`. @@ -3080,7 +3085,8 @@ unsafe fn atomic_sub(dst: *mut T, val: T, order: Ordering) -> T { } #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_compare_exchange( dst: *mut T, @@ -3115,7 +3121,8 @@ unsafe fn atomic_compare_exchange( } #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_compare_exchange_weak( dst: *mut T, @@ -3150,7 +3157,8 @@ unsafe fn atomic_compare_exchange_weak( } #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_and(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_and` @@ -3166,7 +3174,8 @@ unsafe fn atomic_and(dst: *mut T, val: T, order: Ordering) -> T { } #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_nand(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_nand` @@ -3182,7 +3191,8 @@ unsafe fn atomic_nand(dst: *mut T, val: T, order: Ordering) -> T { } #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_or(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_or` @@ -3198,7 +3208,8 @@ unsafe fn atomic_or(dst: *mut T, val: T, order: Ordering) -> T { } #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_xor(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_xor` @@ -3215,7 +3226,8 @@ unsafe fn atomic_xor(dst: *mut T, val: T, order: Ordering) -> T { /// returns the max value (signed comparison) #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_max(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_max` @@ -3232,7 +3244,8 @@ unsafe fn atomic_max(dst: *mut T, val: T, order: Ordering) -> T { /// returns the min value (signed comparison) #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_min(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_min` @@ -3249,7 +3262,8 @@ unsafe fn atomic_min(dst: *mut T, val: T, order: Ordering) -> T { /// returns the max value (unsigned comparison) #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_umax(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_umax` @@ -3266,7 +3280,8 @@ unsafe fn atomic_umax(dst: *mut T, val: T, order: Ordering) -> T { /// returns the min value (unsigned comparison) #[inline] -#[cfg(target_has_atomic = "8")] +#[cfg_attr(not(bootstrap), cfg(target_has_atomic))] +#[cfg_attr(bootstrap, cfg(target_has_atomic = "8"))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces unsafe fn atomic_umin(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_umin` From 20cc72e8a8269107f3405a24861ea7f9d2d748dc Mon Sep 17 00:00:00 2001 From: Martin Fischer Date: Wed, 25 Jan 2023 07:07:10 +0100 Subject: [PATCH 347/500] Improve span for module_name_repetitions --- clippy_lints/src/enum_variants.rs | 4 ++-- tests/ui/module_name_repetitions.stderr | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/clippy_lints/src/enum_variants.rs b/clippy_lints/src/enum_variants.rs index b77b5621b4c68..4c69dacf381ad 100644 --- a/clippy_lints/src/enum_variants.rs +++ b/clippy_lints/src/enum_variants.rs @@ -277,7 +277,7 @@ impl LateLintPass<'_> for EnumVariantNames { Some(c) if is_word_beginning(c) => span_lint( cx, MODULE_NAME_REPETITIONS, - item.span, + item.ident.span, "item name starts with its containing module's name", ), _ => (), @@ -287,7 +287,7 @@ impl LateLintPass<'_> for EnumVariantNames { span_lint( cx, MODULE_NAME_REPETITIONS, - item.span, + item.ident.span, "item name ends with its containing module's name", ); } diff --git a/tests/ui/module_name_repetitions.stderr b/tests/ui/module_name_repetitions.stderr index 3f343a3e43018..277801194a1d5 100644 --- a/tests/ui/module_name_repetitions.stderr +++ b/tests/ui/module_name_repetitions.stderr @@ -1,34 +1,34 @@ error: item name starts with its containing module's name - --> $DIR/module_name_repetitions.rs:8:5 + --> $DIR/module_name_repetitions.rs:8:12 | LL | pub fn foo_bar() {} - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ | = note: `-D clippy::module-name-repetitions` implied by `-D warnings` error: item name ends with its containing module's name - --> $DIR/module_name_repetitions.rs:9:5 + --> $DIR/module_name_repetitions.rs:9:12 | LL | pub fn bar_foo() {} - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: item name starts with its containing module's name - --> $DIR/module_name_repetitions.rs:10:5 + --> $DIR/module_name_repetitions.rs:10:16 | LL | pub struct FooCake; - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: item name ends with its containing module's name - --> $DIR/module_name_repetitions.rs:11:5 + --> $DIR/module_name_repetitions.rs:11:14 | LL | pub enum CakeFoo {} - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: item name starts with its containing module's name - --> $DIR/module_name_repetitions.rs:12:5 + --> $DIR/module_name_repetitions.rs:12:16 | LL | pub struct Foo7Bar; - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: aborting due to 5 previous errors From c70b7aafae283b69762ee809d6b2b5adaf0f3c43 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sat, 21 Jan 2023 23:49:23 +0400 Subject: [PATCH 348/500] rustc_metadata: Fix `encode_attrs` This function didn't do what the authors intended it to do. - Due to `move` in the closure `is_public` wasn't captured by mutalbe reference and wasn't used as a cache. - Due to iterator cloning all the `should_encode_attr` logic run for the second time to calculate `may_have_doc_links` This PR fixes these issues, and calculates all the needed attribute flags in one go. --- compiler/rustc_metadata/src/rmeta/encoder.rs | 77 ++++++++++++-------- 1 file changed, 48 insertions(+), 29 deletions(-) diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 2ecaa33d4d315..e6430d327879f 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -3,6 +3,7 @@ use crate::rmeta::def_path_hash_map::DefPathHashMapRef; use crate::rmeta::table::TableBuilder; use crate::rmeta::*; +use rustc_ast::util::comments; use rustc_ast::Attribute; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; @@ -760,36 +761,54 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } } +struct AnalyzeAttrState { + is_exported: bool, + may_have_doc_links: bool, + is_doc_hidden: bool, +} + /// Returns whether an attribute needs to be recorded in metadata, that is, if it's usable and /// useful in downstream crates. Local-only attributes are an obvious example, but some /// rustdoc-specific attributes can equally be of use while documenting the current crate only. /// /// Removing these superfluous attributes speeds up compilation by making the metadata smaller. /// -/// Note: the `is_def_id_public` parameter is used to cache whether the given `DefId` has a public +/// Note: the `is_exported` parameter is used to cache whether the given `DefId` has a public /// visibility: this is a piece of data that can be computed once per defid, and not once per /// attribute. Some attributes would only be usable downstream if they are public. #[inline] -fn should_encode_attr( - tcx: TyCtxt<'_>, - attr: &Attribute, - def_id: LocalDefId, - is_def_id_public: &mut Option, -) -> bool { +fn analyze_attr(attr: &Attribute, state: &mut AnalyzeAttrState) -> bool { + let mut should_encode = false; if rustc_feature::is_builtin_only_local(attr.name_or_empty()) { // Attributes marked local-only don't need to be encoded for downstream crates. - false - } else if attr.doc_str().is_some() { - // We keep all public doc comments because they might be "imported" into downstream crates - // if they use `#[doc(inline)]` to copy an item's documentation into their own. - *is_def_id_public.get_or_insert_with(|| tcx.effective_visibilities(()).is_exported(def_id)) + } else if let Some(s) = attr.doc_str() { + // We keep all doc comments reachable to rustdoc because they might be "imported" into + // downstream crates if they use `#[doc(inline)]` to copy an item's documentation into + // their own. + if state.is_exported { + should_encode = true; + if comments::may_have_doc_links(s.as_str()) { + state.may_have_doc_links = true; + } + } } else if attr.has_name(sym::doc) { - // If this is a `doc` attribute, and it's marked `inline` (as in `#[doc(inline)]`), we can - // remove it. It won't be inlinable in downstream crates. - attr.meta_item_list().map(|l| l.iter().any(|l| !l.has_name(sym::inline))).unwrap_or(false) + // If this is a `doc` attribute that doesn't have anything except maybe `inline` (as in + // `#[doc(inline)]`), then we can remove it. It won't be inlinable in downstream crates. + if let Some(item_list) = attr.meta_item_list() { + for item in item_list { + if !item.has_name(sym::inline) { + should_encode = true; + if item.has_name(sym::hidden) { + state.is_doc_hidden = true; + break; + } + } + } + } } else { - true + should_encode = true; } + should_encode } fn should_encode_visibility(def_kind: DefKind) -> bool { @@ -1109,24 +1128,24 @@ fn should_encode_trait_impl_trait_tys(tcx: TyCtxt<'_>, def_id: DefId) -> bool { impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_attrs(&mut self, def_id: LocalDefId) { let tcx = self.tcx; - let mut is_public: Option = None; - - let hir_attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(def_id)); - let mut attrs = hir_attrs + let mut state = AnalyzeAttrState { + is_exported: tcx.effective_visibilities(()).is_exported(def_id), + may_have_doc_links: false, + is_doc_hidden: false, + }; + let attr_iter = tcx + .hir() + .attrs(tcx.hir().local_def_id_to_hir_id(def_id)) .iter() - .filter(move |attr| should_encode_attr(tcx, attr, def_id, &mut is_public)); + .filter(|attr| analyze_attr(attr, &mut state)); + + record_array!(self.tables.attributes[def_id.to_def_id()] <- attr_iter); - record_array!(self.tables.attributes[def_id.to_def_id()] <- attrs.clone()); let mut attr_flags = AttrFlags::empty(); - if attrs.any(|attr| attr.may_have_doc_links()) { + if state.may_have_doc_links { attr_flags |= AttrFlags::MAY_HAVE_DOC_LINKS; } - if hir_attrs - .iter() - .filter(|attr| attr.has_name(sym::doc)) - .filter_map(|attr| attr.meta_item_list()) - .any(|items| items.iter().any(|item| item.has_name(sym::hidden))) - { + if state.is_doc_hidden { attr_flags |= AttrFlags::IS_DOC_HIDDEN; } if !attr_flags.is_empty() { From adc18904483fbd9df409291da4c4e299c8b6cb3e Mon Sep 17 00:00:00 2001 From: Erik Desjardins Date: Wed, 25 Jan 2023 01:46:19 -0500 Subject: [PATCH 349/500] create and use GlobalAlloc::address_space --- compiler/rustc_codegen_gcc/src/consts.rs | 11 +++-------- compiler/rustc_codegen_llvm/src/consts.rs | 13 +++---------- compiler/rustc_middle/src/mir/interpret/mod.rs | 13 ++++++++++++- 3 files changed, 18 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_codegen_gcc/src/consts.rs b/compiler/rustc_codegen_gcc/src/consts.rs index ba64b1f638942..dc41cb761b59c 100644 --- a/compiler/rustc_codegen_gcc/src/consts.rs +++ b/compiler/rustc_codegen_gcc/src/consts.rs @@ -7,9 +7,9 @@ use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs} use rustc_middle::mir::mono::MonoItem; use rustc_middle::ty::{self, Instance, Ty}; use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::mir::interpret::{self, ConstAllocation, ErrorHandled, GlobalAlloc, Scalar as InterpScalar, read_target_uint}; +use rustc_middle::mir::interpret::{self, ConstAllocation, ErrorHandled, Scalar as InterpScalar, read_target_uint}; use rustc_span::def_id::DefId; -use rustc_target::abi::{self, AddressSpace, Align, HasDataLayout, Primitive, Size, WrappingRange}; +use rustc_target::abi::{self, Align, HasDataLayout, Primitive, Size, WrappingRange}; use crate::base; use crate::context::CodegenCx; @@ -323,12 +323,7 @@ pub fn const_alloc_to_gcc<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, alloc: ConstAl .expect("const_alloc_to_llvm: could not read relocation pointer") as u64; - let address_space = match cx.tcx.global_alloc(alloc_id) { - GlobalAlloc::Function(..) => cx.data_layout().instruction_address_space, - GlobalAlloc::Static(..) | GlobalAlloc::Memory(..) | GlobalAlloc::VTable(..) => { - AddressSpace::DATA - } - }; + let address_space = cx.tcx.global_alloc(alloc_id).address_space(cx); llvals.push(cx.scalar_to_backend( InterpScalar::from_pointer( diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 2f630b32ffe06..cad3c5d87b73c 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -13,7 +13,7 @@ use rustc_codegen_ssa::traits::*; use rustc_hir::def_id::DefId; use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs}; use rustc_middle::mir::interpret::{ - read_target_uint, Allocation, ConstAllocation, ErrorHandled, GlobalAlloc, InitChunk, Pointer, + read_target_uint, Allocation, ConstAllocation, ErrorHandled, InitChunk, Pointer, Scalar as InterpScalar, }; use rustc_middle::mir::mono::MonoItem; @@ -21,9 +21,7 @@ use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, Instance, Ty}; use rustc_middle::{bug, span_bug}; use rustc_session::config::Lto; -use rustc_target::abi::{ - AddressSpace, Align, HasDataLayout, Primitive, Scalar, Size, WrappingRange, -}; +use rustc_target::abi::{Align, HasDataLayout, Primitive, Scalar, Size, WrappingRange}; use std::ops::Range; pub fn const_alloc_to_llvm<'ll>(cx: &CodegenCx<'ll, '_>, alloc: ConstAllocation<'_>) -> &'ll Value { @@ -98,12 +96,7 @@ pub fn const_alloc_to_llvm<'ll>(cx: &CodegenCx<'ll, '_>, alloc: ConstAllocation< .expect("const_alloc_to_llvm: could not read relocation pointer") as u64; - let address_space = match cx.tcx.global_alloc(alloc_id) { - GlobalAlloc::Function(..) => cx.data_layout().instruction_address_space, - GlobalAlloc::Static(..) | GlobalAlloc::Memory(..) | GlobalAlloc::VTable(..) => { - AddressSpace::DATA - } - }; + let address_space = cx.tcx.global_alloc(alloc_id).address_space(cx); llvals.push(cx.scalar_to_backend( InterpScalar::from_pointer( diff --git a/compiler/rustc_middle/src/mir/interpret/mod.rs b/compiler/rustc_middle/src/mir/interpret/mod.rs index 5f425a287687e..b0975616b6151 100644 --- a/compiler/rustc_middle/src/mir/interpret/mod.rs +++ b/compiler/rustc_middle/src/mir/interpret/mod.rs @@ -110,7 +110,7 @@ use rustc_hir::def_id::DefId; use rustc_macros::HashStable; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_serialize::{Decodable, Encodable}; -use rustc_target::abi::Endian; +use rustc_target::abi::{AddressSpace, Endian, HasDataLayout}; use crate::mir; use crate::ty::codec::{TyDecoder, TyEncoder}; @@ -438,6 +438,17 @@ impl<'tcx> GlobalAlloc<'tcx> { _ => bug!("expected vtable, got {:?}", self), } } + + /// The address space that this `GlobalAlloc` should be placed in. + #[inline] + pub fn address_space(&self, cx: &impl HasDataLayout) -> AddressSpace { + match self { + GlobalAlloc::Function(..) => cx.data_layout().instruction_address_space, + GlobalAlloc::Static(..) | GlobalAlloc::Memory(..) | GlobalAlloc::VTable(..) => { + AddressSpace::DATA + } + } + } } pub(crate) struct AllocMap<'tcx> { From 8b12d5f42f98f50e5e47156eea343ea6d32b10db Mon Sep 17 00:00:00 2001 From: Andy Russell Date: Sun, 22 Jan 2023 12:06:23 -0500 Subject: [PATCH 350/500] suggest qualifying bare associated constants --- compiler/rustc_resolve/src/late/diagnostics.rs | 17 ++++++++++++----- .../ui/suggestions/assoc-const-without-self.rs | 11 +++++++++++ .../suggestions/assoc-const-without-self.stderr | 14 ++++++++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) create mode 100644 tests/ui/suggestions/assoc-const-without-self.rs create mode 100644 tests/ui/suggestions/assoc-const-without-self.stderr diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 6d448433ee6db..37beff37c1fb9 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -227,20 +227,27 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> { && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt() && let Some(items) = self.diagnostic_metadata.current_impl_items && let Some(item) = items.iter().find(|i| { - if let AssocItemKind::Fn(_) = &i.kind && i.ident.name == item_str.name + if let AssocItemKind::Fn(..) | AssocItemKind::Const(..) = &i.kind + && i.ident.name == item_str.name { debug!(?item_str.name); return true } false }) - && let AssocItemKind::Fn(fn_) = &item.kind { - debug!(?fn_); - let self_sugg = if fn_.sig.decl.has_self() { "self." } else { "Self::" }; + let self_sugg = match &item.kind { + AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => "self.", + _ => "Self::", + }; + Some(( item_span.shrink_to_lo(), - "consider using the associated function", + match &item.kind { + AssocItemKind::Fn(..) => "consider using the associated function", + AssocItemKind::Const(..) => "consider using the associated constant", + _ => unreachable!("item kind was filtered above"), + }, self_sugg.to_string() )) } else { diff --git a/tests/ui/suggestions/assoc-const-without-self.rs b/tests/ui/suggestions/assoc-const-without-self.rs new file mode 100644 index 0000000000000..95070ec601cd4 --- /dev/null +++ b/tests/ui/suggestions/assoc-const-without-self.rs @@ -0,0 +1,11 @@ +struct Foo; + +impl Foo { + const A_CONST: usize = 1; + + fn foo() -> usize { + A_CONST //~ ERROR cannot find value `A_CONST` in this scope + } +} + +fn main() {} diff --git a/tests/ui/suggestions/assoc-const-without-self.stderr b/tests/ui/suggestions/assoc-const-without-self.stderr new file mode 100644 index 0000000000000..88d72da70cb9b --- /dev/null +++ b/tests/ui/suggestions/assoc-const-without-self.stderr @@ -0,0 +1,14 @@ +error[E0425]: cannot find value `A_CONST` in this scope + --> $DIR/assoc-const-without-self.rs:7:9 + | +LL | A_CONST + | ^^^^^^^ not found in this scope + | +help: consider using the associated constant + | +LL | Self::A_CONST + | ++++++ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0425`. From dde74fe09239e1f185810908bbe57b135f7076e9 Mon Sep 17 00:00:00 2001 From: Urgau Date: Thu, 19 Jan 2023 17:46:54 +0100 Subject: [PATCH 351/500] Remove outdated cfg on `le32` See https://github.com/rust-lang/rust/pull/45041 for the removal of the target (le32-unknown-nacl). --- library/std/src/os/fuchsia/raw.rs | 7 +------ library/std/src/os/l4re/raw.rs | 1 - library/std/src/os/linux/raw.rs | 1 - 3 files changed, 1 insertion(+), 8 deletions(-) diff --git a/library/std/src/os/fuchsia/raw.rs b/library/std/src/os/fuchsia/raw.rs index 060d6e86b6c2b..ea6b94f2f13c4 100644 --- a/library/std/src/os/fuchsia/raw.rs +++ b/library/std/src/os/fuchsia/raw.rs @@ -24,12 +24,7 @@ pub type pthread_t = c_ulong; #[stable(feature = "raw_ext", since = "1.1.0")] pub use self::arch::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t}; -#[cfg(any( - target_arch = "x86", - target_arch = "le32", - target_arch = "powerpc", - target_arch = "arm" -))] +#[cfg(any(target_arch = "x86", target_arch = "powerpc", target_arch = "arm"))] mod arch { use crate::os::raw::{c_long, c_short, c_uint}; diff --git a/library/std/src/os/l4re/raw.rs b/library/std/src/os/l4re/raw.rs index 699e8be33c8a8..b3f7439f8cdc0 100644 --- a/library/std/src/os/l4re/raw.rs +++ b/library/std/src/os/l4re/raw.rs @@ -26,7 +26,6 @@ pub use self::arch::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t}; #[cfg(any( target_arch = "x86", - target_arch = "le32", target_arch = "m68k", target_arch = "powerpc", target_arch = "sparc", diff --git a/library/std/src/os/linux/raw.rs b/library/std/src/os/linux/raw.rs index c73791d14529c..f46028c3a96c9 100644 --- a/library/std/src/os/linux/raw.rs +++ b/library/std/src/os/linux/raw.rs @@ -26,7 +26,6 @@ pub use self::arch::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t}; #[cfg(any( target_arch = "x86", - target_arch = "le32", target_arch = "m68k", target_arch = "powerpc", target_arch = "sparc", From 1578b1c73fa2c2ae1b78b5d66f36734f41b968b8 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Wed, 25 Jan 2023 15:19:40 +0100 Subject: [PATCH 352/500] Vendor newer version of cranelift-native It fixes a bug that caused compilation on 32bit x86 to fail --- compiler/rustc_codegen_cranelift/Cargo.lock | 1 - compiler/rustc_codegen_cranelift/Cargo.toml | 4 +- .../src/cranelift_native.rs | 268 ++++++++++++++++++ compiler/rustc_codegen_cranelift/src/lib.rs | 2 + 4 files changed, 273 insertions(+), 2 deletions(-) create mode 100644 compiler/rustc_codegen_cranelift/src/cranelift_native.rs diff --git a/compiler/rustc_codegen_cranelift/Cargo.lock b/compiler/rustc_codegen_cranelift/Cargo.lock index 48800725d2c13..50249ea1bdb49 100644 --- a/compiler/rustc_codegen_cranelift/Cargo.lock +++ b/compiler/rustc_codegen_cranelift/Cargo.lock @@ -333,7 +333,6 @@ dependencies = [ "cranelift-frontend", "cranelift-jit", "cranelift-module", - "cranelift-native", "cranelift-object", "gimli", "indexmap", diff --git a/compiler/rustc_codegen_cranelift/Cargo.toml b/compiler/rustc_codegen_cranelift/Cargo.toml index eadb4438bc992..34117c2886feb 100644 --- a/compiler/rustc_codegen_cranelift/Cargo.toml +++ b/compiler/rustc_codegen_cranelift/Cargo.toml @@ -18,7 +18,9 @@ crate-type = ["dylib"] cranelift-codegen = { version = "0.92", features = ["unwind", "all-arch"] } cranelift-frontend = { version = "0.92" } cranelift-module = { version = "0.92" } -cranelift-native = { version = "0.92" } +# NOTE vendored as src/cranelift_native.rs +# FIXME revert back to the external crate with Cranelift 0.93 +#cranelift-native = { version = "0.92" } cranelift-jit = { version = "0.92", optional = true } cranelift-object = { version = "0.92" } target-lexicon = "0.12.0" diff --git a/compiler/rustc_codegen_cranelift/src/cranelift_native.rs b/compiler/rustc_codegen_cranelift/src/cranelift_native.rs new file mode 100644 index 0000000000000..7c0ca1adc2d48 --- /dev/null +++ b/compiler/rustc_codegen_cranelift/src/cranelift_native.rs @@ -0,0 +1,268 @@ +// Vendored from https://github.com/bytecodealliance/wasmtime/blob/b58a197d33f044193c3d608010f5e6ec394ac07e/cranelift/native/src/lib.rs +// which is licensed as +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// unlike rustc_codegen_cranelift itself. +// FIXME revert back to the external crate with Cranelift 0.93 +#![allow(warnings)] + +//! Performs autodetection of the host for the purposes of running +//! Cranelift to generate code to run on the same machine. + +#![deny( + missing_docs, + trivial_numeric_casts, + unused_extern_crates, + unstable_features +)] +#![warn(unused_import_braces)] +#![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))] +#![cfg_attr(feature = "cargo-clippy", allow(clippy::new_without_default))] +#![cfg_attr( + feature = "cargo-clippy", + warn( + clippy::float_arithmetic, + clippy::mut_mut, + clippy::nonminimal_bool, + clippy::map_unwrap_or, + clippy::clippy::print_stdout, + clippy::unicode_not_nfc, + clippy::use_self + ) +)] + +use cranelift_codegen::isa; +use target_lexicon::Triple; + +/// Return an `isa` builder configured for the current host +/// machine, or `Err(())` if the host machine is not supported +/// in the current configuration. +pub fn builder() -> Result { + builder_with_options(true) +} + +/// Return an `isa` builder configured for the current host +/// machine, or `Err(())` if the host machine is not supported +/// in the current configuration. +/// +/// Selects the given backend variant specifically; this is +/// useful when more than oen backend exists for a given target +/// (e.g., on x86-64). +pub fn builder_with_options(infer_native_flags: bool) -> Result { + let mut isa_builder = isa::lookup(Triple::host()).map_err(|err| match err { + isa::LookupError::SupportDisabled => "support for architecture disabled at compile time", + isa::LookupError::Unsupported => "unsupported architecture", + })?; + + #[cfg(target_arch = "x86_64")] + { + use cranelift_codegen::settings::Configurable; + + if !std::is_x86_feature_detected!("sse2") { + return Err("x86 support requires SSE2"); + } + + if !infer_native_flags { + return Ok(isa_builder); + } + + // These are temporarily enabled by default (see #3810 for + // more) so that a default-constructed `Flags` can work with + // default Wasmtime features. Otherwise, the user must + // explicitly use native flags or turn these on when on x86-64 + // platforms to avoid a configuration panic. In order for the + // "enable if detected" logic below to work, we must turn them + // *off* (differing from the default) and then re-enable below + // if present. + isa_builder.set("has_sse3", "false").unwrap(); + isa_builder.set("has_ssse3", "false").unwrap(); + isa_builder.set("has_sse41", "false").unwrap(); + isa_builder.set("has_sse42", "false").unwrap(); + + if std::is_x86_feature_detected!("sse3") { + isa_builder.enable("has_sse3").unwrap(); + } + if std::is_x86_feature_detected!("ssse3") { + isa_builder.enable("has_ssse3").unwrap(); + } + if std::is_x86_feature_detected!("sse4.1") { + isa_builder.enable("has_sse41").unwrap(); + } + if std::is_x86_feature_detected!("sse4.2") { + isa_builder.enable("has_sse42").unwrap(); + } + if std::is_x86_feature_detected!("popcnt") { + isa_builder.enable("has_popcnt").unwrap(); + } + if std::is_x86_feature_detected!("avx") { + isa_builder.enable("has_avx").unwrap(); + } + if std::is_x86_feature_detected!("avx2") { + isa_builder.enable("has_avx2").unwrap(); + } + if std::is_x86_feature_detected!("fma") { + isa_builder.enable("has_fma").unwrap(); + } + if std::is_x86_feature_detected!("bmi1") { + isa_builder.enable("has_bmi1").unwrap(); + } + if std::is_x86_feature_detected!("bmi2") { + isa_builder.enable("has_bmi2").unwrap(); + } + if std::is_x86_feature_detected!("avx512bitalg") { + isa_builder.enable("has_avx512bitalg").unwrap(); + } + if std::is_x86_feature_detected!("avx512dq") { + isa_builder.enable("has_avx512dq").unwrap(); + } + if std::is_x86_feature_detected!("avx512f") { + isa_builder.enable("has_avx512f").unwrap(); + } + if std::is_x86_feature_detected!("avx512vl") { + isa_builder.enable("has_avx512vl").unwrap(); + } + if std::is_x86_feature_detected!("avx512vbmi") { + isa_builder.enable("has_avx512vbmi").unwrap(); + } + if std::is_x86_feature_detected!("lzcnt") { + isa_builder.enable("has_lzcnt").unwrap(); + } + } + + #[cfg(target_arch = "aarch64")] + { + use cranelift_codegen::settings::Configurable; + + if !infer_native_flags { + return Ok(isa_builder); + } + + if std::arch::is_aarch64_feature_detected!("lse") { + isa_builder.enable("has_lse").unwrap(); + } + + if std::arch::is_aarch64_feature_detected!("paca") { + isa_builder.enable("has_pauth").unwrap(); + } + + if cfg!(target_os = "macos") { + // Pointer authentication is always available on Apple Silicon. + isa_builder.enable("sign_return_address").unwrap(); + // macOS enforces the use of the B key for return addresses. + isa_builder.enable("sign_return_address_with_bkey").unwrap(); + } + } + + // There is no is_s390x_feature_detected macro yet, so for now + // we use getauxval from the libc crate directly. + #[cfg(all(target_arch = "s390x", target_os = "linux"))] + { + use cranelift_codegen::settings::Configurable; + + if !infer_native_flags { + return Ok(isa_builder); + } + + let v = unsafe { libc::getauxval(libc::AT_HWCAP) }; + const HWCAP_S390X_VXRS_EXT2: libc::c_ulong = 32768; + if (v & HWCAP_S390X_VXRS_EXT2) != 0 { + isa_builder.enable("has_vxrs_ext2").unwrap(); + // There is no separate HWCAP bit for mie2, so assume + // that any machine with vxrs_ext2 also has mie2. + isa_builder.enable("has_mie2").unwrap(); + } + } + + // `is_riscv_feature_detected` is nightly only for now, use + // getauxval from the libc crate directly as a temporary measure. + #[cfg(all(target_arch = "riscv64", target_os = "linux"))] + { + use cranelift_codegen::settings::Configurable; + + if !infer_native_flags { + return Ok(isa_builder); + } + + let v = unsafe { libc::getauxval(libc::AT_HWCAP) }; + + const HWCAP_RISCV_EXT_A: libc::c_ulong = 1 << (b'a' - b'a'); + const HWCAP_RISCV_EXT_C: libc::c_ulong = 1 << (b'c' - b'a'); + const HWCAP_RISCV_EXT_D: libc::c_ulong = 1 << (b'd' - b'a'); + const HWCAP_RISCV_EXT_F: libc::c_ulong = 1 << (b'f' - b'a'); + const HWCAP_RISCV_EXT_M: libc::c_ulong = 1 << (b'm' - b'a'); + const HWCAP_RISCV_EXT_V: libc::c_ulong = 1 << (b'v' - b'a'); + + if (v & HWCAP_RISCV_EXT_A) != 0 { + isa_builder.enable("has_a").unwrap(); + } + + if (v & HWCAP_RISCV_EXT_C) != 0 { + isa_builder.enable("has_c").unwrap(); + } + + if (v & HWCAP_RISCV_EXT_D) != 0 { + isa_builder.enable("has_d").unwrap(); + } + + if (v & HWCAP_RISCV_EXT_F) != 0 { + isa_builder.enable("has_f").unwrap(); + + // TODO: There doesn't seem to be a bit associated with this extension + // rust enables it with the `f` extension: + // https://github.com/rust-lang/stdarch/blob/790411f93c4b5eada3c23abb4c9a063fb0b24d99/crates/std_detect/src/detect/os/linux/riscv.rs#L43 + isa_builder.enable("has_zicsr").unwrap(); + } + + if (v & HWCAP_RISCV_EXT_M) != 0 { + isa_builder.enable("has_m").unwrap(); + } + + if (v & HWCAP_RISCV_EXT_V) != 0 { + isa_builder.enable("has_v").unwrap(); + } + + // TODO: ZiFencei does not have a bit associated with it + // TODO: Zbkb does not have a bit associated with it + } + + // squelch warnings about unused mut/variables on some platforms. + drop(&mut isa_builder); + drop(infer_native_flags); + + Ok(isa_builder) +} + +#[cfg(test)] +mod tests { + use super::builder; + use cranelift_codegen::isa::CallConv; + use cranelift_codegen::settings; + + #[test] + fn test() { + if let Ok(isa_builder) = builder() { + let flag_builder = settings::builder(); + let isa = isa_builder + .finish(settings::Flags::new(flag_builder)) + .unwrap(); + + if cfg!(all(target_os = "macos", target_arch = "aarch64")) { + assert_eq!(isa.default_call_conv(), CallConv::AppleAarch64); + } else if cfg!(any(unix, target_os = "nebulet")) { + assert_eq!(isa.default_call_conv(), CallConv::SystemV); + } else if cfg!(windows) { + assert_eq!(isa.default_call_conv(), CallConv::WindowsFastcall); + } + + if cfg!(target_pointer_width = "64") { + assert_eq!(isa.pointer_bits(), 64); + } else if cfg!(target_pointer_width = "32") { + assert_eq!(isa.pointer_bits(), 32); + } else if cfg!(target_pointer_width = "16") { + assert_eq!(isa.pointer_bits(), 16); + } + } + } +} + +/// Version number of this crate. +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/compiler/rustc_codegen_cranelift/src/lib.rs b/compiler/rustc_codegen_cranelift/src/lib.rs index 70d0cc339a80c..d3868730557b7 100644 --- a/compiler/rustc_codegen_cranelift/src/lib.rs +++ b/compiler/rustc_codegen_cranelift/src/lib.rs @@ -57,6 +57,8 @@ mod compiler_builtins; mod concurrency_limiter; mod config; mod constant; +// FIXME revert back to the external crate with Cranelift 0.93 +mod cranelift_native; mod debuginfo; mod discriminant; mod driver; From a01a54021434f19b7dfd000579dc23551935a855 Mon Sep 17 00:00:00 2001 From: Urgau Date: Thu, 19 Jan 2023 18:01:25 +0100 Subject: [PATCH 353/500] Cleanup extra check configs in bootstrap - `target_os=watchos`: no longer relevant because there are now proper targets `*-apple-watchos` - `target_arch=nvptx64`: `nvptx64-nvidia-cuda` - `target_arch=le32`: target was removed (https://github.com/rust-lang/rust/pull/45041) - `release`: was removed from rustfmt (https://github.com/rust-lang/rustfmt/pull/5375 and https://github.com/rust-lang/rustfmt/pull/5449) - `dont_compile_me`: was removed from stdarch (https://github.com/rust-lang/stdarch/pull/1308) Also made some external cfg exception mode clear and only activated for rustc and rustc tools (as to not have the Standard Library unintentionally depend on them). --- src/bootstrap/lib.rs | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index d44b96cfb991e..376149a95678c 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -203,7 +203,6 @@ const EXTRA_CHECK_CFGS: &[(Option, &'static str, Option<&[&'static str]>)] (None, "bootstrap", None), (Some(Mode::Rustc), "parallel_compiler", None), (Some(Mode::ToolRustc), "parallel_compiler", None), - (Some(Mode::ToolRustc), "emulate_second_only_system", None), (Some(Mode::Codegen), "parallel_compiler", None), (Some(Mode::Std), "stdarch_intel_sde", None), (Some(Mode::Std), "no_fp_fmt_parse", None), @@ -214,18 +213,9 @@ const EXTRA_CHECK_CFGS: &[(Option, &'static str, Option<&[&'static str]>)] (Some(Mode::Std), "backtrace_in_libstd", None), /* Extra values not defined in the built-in targets yet, but used in std */ (Some(Mode::Std), "target_env", Some(&["libnx"])), - (Some(Mode::Std), "target_os", Some(&["watchos"])), - ( - Some(Mode::Std), - "target_arch", - Some(&["asmjs", "spirv", "nvptx", "nvptx64", "le32", "xtensa"]), - ), + // (Some(Mode::Std), "target_os", Some(&[])), + (Some(Mode::Std), "target_arch", Some(&["asmjs", "spirv", "nvptx", "xtensa"])), /* Extra names used by dependencies */ - // FIXME: Used by rustfmt is their test but is invalid (neither cargo nor bootstrap ever set - // this config) should probably by removed or use a allow attribute. - (Some(Mode::ToolRustc), "release", None), - // FIXME: Used by stdarch in their test, should use a allow attribute instead. - (Some(Mode::Std), "dont_compile_me", None), // FIXME: Used by serde_json, but we should not be triggering on external dependencies. (Some(Mode::Rustc), "no_btreemap_remove_entry", None), (Some(Mode::ToolRustc), "no_btreemap_remove_entry", None), @@ -235,8 +225,12 @@ const EXTRA_CHECK_CFGS: &[(Option, &'static str, Option<&[&'static str]>)] // FIXME: Used by proc-macro2, but we should not be triggering on external dependencies. (Some(Mode::Rustc), "span_locations", None), (Some(Mode::ToolRustc), "span_locations", None), - // Can be passed in RUSTFLAGS to prevent direct syscalls in rustix. - (None, "rustix_use_libc", None), + // FIXME: Used by rustix, but we should not be triggering on external dependencies. + (Some(Mode::Rustc), "rustix_use_libc", None), + (Some(Mode::ToolRustc), "rustix_use_libc", None), + // FIXME: Used by filetime, but we should not be triggering on external dependencies. + (Some(Mode::Rustc), "emulate_second_only_system", None), + (Some(Mode::ToolRustc), "emulate_second_only_system", None), ]; /// A structure representing a Rust compiler. From 3808bc4639468018b1e5c30e1cd2e6905485ce67 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Wed, 25 Jan 2023 15:56:22 +0100 Subject: [PATCH 354/500] Fix CI --- .../src/cranelift_native.rs | 28 +++---------------- 1 file changed, 4 insertions(+), 24 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/src/cranelift_native.rs b/compiler/rustc_codegen_cranelift/src/cranelift_native.rs index 7c0ca1adc2d48..6c4efca442448 100644 --- a/compiler/rustc_codegen_cranelift/src/cranelift_native.rs +++ b/compiler/rustc_codegen_cranelift/src/cranelift_native.rs @@ -1,34 +1,16 @@ // Vendored from https://github.com/bytecodealliance/wasmtime/blob/b58a197d33f044193c3d608010f5e6ec394ac07e/cranelift/native/src/lib.rs // which is licensed as // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// unlike rustc_codegen_cranelift itself. +// unlike rustc_codegen_cranelift itself. Also applies a small change to remove #![cfg_attr] that +// rust's CI complains about and to fix formatting to match rustc. // FIXME revert back to the external crate with Cranelift 0.93 #![allow(warnings)] //! Performs autodetection of the host for the purposes of running //! Cranelift to generate code to run on the same machine. -#![deny( - missing_docs, - trivial_numeric_casts, - unused_extern_crates, - unstable_features -)] +#![deny(missing_docs, trivial_numeric_casts, unused_extern_crates, unstable_features)] #![warn(unused_import_braces)] -#![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))] -#![cfg_attr(feature = "cargo-clippy", allow(clippy::new_without_default))] -#![cfg_attr( - feature = "cargo-clippy", - warn( - clippy::float_arithmetic, - clippy::mut_mut, - clippy::nonminimal_bool, - clippy::map_unwrap_or, - clippy::clippy::print_stdout, - clippy::unicode_not_nfc, - clippy::use_self - ) -)] use cranelift_codegen::isa; use target_lexicon::Triple; @@ -241,9 +223,7 @@ mod tests { fn test() { if let Ok(isa_builder) = builder() { let flag_builder = settings::builder(); - let isa = isa_builder - .finish(settings::Flags::new(flag_builder)) - .unwrap(); + let isa = isa_builder.finish(settings::Flags::new(flag_builder)).unwrap(); if cfg!(all(target_os = "macos", target_arch = "aarch64")) { assert_eq!(isa.default_call_conv(), CallConv::AppleAarch64); From 957bc606dd638e28dea6c39f6678d5f9977c8cf2 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Tue, 17 Jan 2023 01:09:23 +0400 Subject: [PATCH 355/500] rustdoc: Collect rustdoc-reachable items during early doc link resolution --- .../src/rmeta/decoder/cstore_impl.rs | 6 +++ src/librustdoc/clean/utils.rs | 5 -- src/librustdoc/core.rs | 5 ++ .../passes/collect_intra_doc_links/early.rs | 22 ++++++++ src/librustdoc/visit_lib.rs | 51 ++++++++++++++++++- 5 files changed, 83 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index eebc2f21dfe4e..e5d0bb87edf66 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -632,6 +632,12 @@ impl CStore { .get_attr_flags(def_id.index) .contains(AttrFlags::MAY_HAVE_DOC_LINKS) } + + pub fn is_doc_hidden_untracked(&self, def_id: DefId) -> bool { + self.get_crate_data(def_id.krate) + .get_attr_flags(def_id.index) + .contains(AttrFlags::IS_DOC_HIDDEN) + } } impl CrateStore for CStore { diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index a12f764fa8e3b..ca3a70c7236fe 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -29,11 +29,6 @@ mod tests; pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate { let module = crate::visit_ast::RustdocVisitor::new(cx).visit(); - for &cnum in cx.tcx.crates(()) { - // Analyze doc-reachability for extern items - crate::visit_lib::lib_embargo_visit_item(cx, cnum.as_def_id()); - } - // Clean the crate, translating the entire librustc_ast AST to one that is // understood by rustdoc. let mut module = clean_doc_module(&module, cx); diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 10b606f425ea4..0ce43f7db8e8b 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -41,6 +41,7 @@ pub(crate) struct ResolverCaches { pub(crate) traits_in_scope: DefIdMap>, pub(crate) all_trait_impls: Option>, pub(crate) all_macro_rules: FxHashMap>, + pub(crate) extern_doc_reachable: DefIdSet, } pub(crate) struct DocContext<'tcx> { @@ -363,6 +364,10 @@ pub(crate) fn run_global_ctxt( show_coverage, }; + ctxt.cache + .effective_visibilities + .init(mem::take(&mut ctxt.resolver_caches.extern_doc_reachable)); + // Small hack to force the Sized trait to be present. // // Note that in case of `#![no_core]`, the trait is not available. diff --git a/src/librustdoc/passes/collect_intra_doc_links/early.rs b/src/librustdoc/passes/collect_intra_doc_links/early.rs index 42677bd849748..150e53f63b9a5 100644 --- a/src/librustdoc/passes/collect_intra_doc_links/early.rs +++ b/src/librustdoc/passes/collect_intra_doc_links/early.rs @@ -2,6 +2,7 @@ use crate::clean::Attributes; use crate::core::ResolverCaches; use crate::passes::collect_intra_doc_links::preprocessed_markdown_links; use crate::passes::collect_intra_doc_links::{Disambiguator, PreprocessedMarkdownLink}; +use crate::visit_lib::early_lib_embargo_visit_item; use rustc_ast::visit::{self, AssocCtxt, Visitor}; use rustc_ast::{self as ast, ItemKind}; @@ -34,6 +35,8 @@ pub(crate) fn early_resolve_intra_doc_links( traits_in_scope: Default::default(), all_trait_impls: Default::default(), all_macro_rules: Default::default(), + extern_doc_reachable: Default::default(), + local_doc_reachable: Default::default(), document_private_items, }; @@ -61,6 +64,7 @@ pub(crate) fn early_resolve_intra_doc_links( traits_in_scope: link_resolver.traits_in_scope, all_trait_impls: Some(link_resolver.all_trait_impls), all_macro_rules: link_resolver.all_macro_rules, + extern_doc_reachable: link_resolver.extern_doc_reachable, } } @@ -77,6 +81,15 @@ struct EarlyDocLinkResolver<'r, 'ra> { traits_in_scope: DefIdMap>, all_trait_impls: Vec, all_macro_rules: FxHashMap>, + /// This set is used as a seed for `effective_visibilities`, which are then extended by some + /// more items using `lib_embargo_visit_item` during doc inlining. + extern_doc_reachable: DefIdSet, + /// This is an easily identifiable superset of items added to `effective_visibilities` + /// using `lib_embargo_visit_item` during doc inlining. + /// The union of `(extern,local)_doc_reachable` is therefore a superset of + /// `effective_visibilities` and can be used for pruning extern impls here + /// in early doc link resolution. + local_doc_reachable: DefIdSet, document_private_items: bool, } @@ -114,6 +127,14 @@ impl<'ra> EarlyDocLinkResolver<'_, 'ra> { let mut start_cnum = 0; loop { let crates = Vec::from_iter(self.resolver.cstore().crates_untracked()); + for cnum in &crates[start_cnum..] { + early_lib_embargo_visit_item( + self.resolver, + &mut self.extern_doc_reachable, + cnum.as_def_id(), + true, + ); + } for &cnum in &crates[start_cnum..] { let all_trait_impls = Vec::from_iter(self.resolver.cstore().trait_impls_in_crate_untracked(cnum)); @@ -298,6 +319,7 @@ impl<'ra> EarlyDocLinkResolver<'_, 'ra> { && module_id.is_local() { if let Some(def_id) = child.res.opt_def_id() && !def_id.is_local() { + self.local_doc_reachable.insert(def_id); let scope_id = match child.res { Res::Def( DefKind::Variant diff --git a/src/librustdoc/visit_lib.rs b/src/librustdoc/visit_lib.rs index fd4f9254107ca..07d8b78d767db 100644 --- a/src/librustdoc/visit_lib.rs +++ b/src/librustdoc/visit_lib.rs @@ -1,7 +1,8 @@ use crate::core::DocContext; -use rustc_hir::def::DefKind; +use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, DefIdSet}; use rustc_middle::ty::TyCtxt; +use rustc_resolve::Resolver; // FIXME: this may not be exhaustive, but is sufficient for rustdocs current uses @@ -25,6 +26,10 @@ impl RustdocEffectiveVisibilities { define_method!(is_directly_public); define_method!(is_exported); define_method!(is_reachable); + + pub(crate) fn init(&mut self, extern_public: DefIdSet) { + self.extern_public = extern_public; + } } pub(crate) fn lib_embargo_visit_item(cx: &mut DocContext<'_>, def_id: DefId) { @@ -37,6 +42,17 @@ pub(crate) fn lib_embargo_visit_item(cx: &mut DocContext<'_>, def_id: DefId) { .visit_item(def_id) } +pub(crate) fn early_lib_embargo_visit_item( + resolver: &Resolver<'_>, + extern_public: &mut DefIdSet, + def_id: DefId, + is_mod: bool, +) { + assert!(!def_id.is_local()); + EarlyLibEmbargoVisitor { resolver, extern_public, visited_mods: Default::default() } + .visit_item(def_id, is_mod) +} + /// Similar to `librustc_privacy::EmbargoVisitor`, but also takes /// specific rustdoc annotations into account (i.e., `doc(hidden)`) struct LibEmbargoVisitor<'a, 'tcx> { @@ -47,6 +63,14 @@ struct LibEmbargoVisitor<'a, 'tcx> { visited_mods: DefIdSet, } +struct EarlyLibEmbargoVisitor<'r, 'ra> { + resolver: &'r Resolver<'ra>, + // Effective visibilities for reachable nodes + extern_public: &'r mut DefIdSet, + // Keeps track of already visited modules, in case a module re-exports its parent + visited_mods: DefIdSet, +} + impl LibEmbargoVisitor<'_, '_> { fn visit_mod(&mut self, def_id: DefId) { if !self.visited_mods.insert(def_id) { @@ -71,3 +95,28 @@ impl LibEmbargoVisitor<'_, '_> { } } } + +impl EarlyLibEmbargoVisitor<'_, '_> { + fn visit_mod(&mut self, def_id: DefId) { + if !self.visited_mods.insert(def_id) { + return; + } + + for item in self.resolver.cstore().module_children_untracked(def_id, self.resolver.sess()) { + if let Some(def_id) = item.res.opt_def_id() { + if item.vis.is_public() { + self.visit_item(def_id, matches!(item.res, Res::Def(DefKind::Mod, _))); + } + } + } + } + + fn visit_item(&mut self, def_id: DefId, is_mod: bool) { + if !self.resolver.cstore().is_doc_hidden_untracked(def_id) { + self.extern_public.insert(def_id); + if is_mod { + self.visit_mod(def_id); + } + } + } +} From ca93310eb7b18eb34ca743fad530ae4a0e34c5c7 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Wed, 25 Jan 2023 23:22:00 +0400 Subject: [PATCH 356/500] rustdoc: Use rustdoc-reachable set to prune extern impls --- .../passes/collect_intra_doc_links/early.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/librustdoc/passes/collect_intra_doc_links/early.rs b/src/librustdoc/passes/collect_intra_doc_links/early.rs index 150e53f63b9a5..920028dd63c8f 100644 --- a/src/librustdoc/passes/collect_intra_doc_links/early.rs +++ b/src/librustdoc/passes/collect_intra_doc_links/early.rs @@ -118,6 +118,10 @@ impl<'ra> EarlyDocLinkResolver<'_, 'ra> { } } + fn is_doc_reachable(&self, def_id: DefId) -> bool { + self.extern_doc_reachable.contains(&def_id) || self.local_doc_reachable.contains(&def_id) + } + /// Add traits in scope for links in impls collected by the `collect-intra-doc-links` pass. /// That pass filters impls using type-based information, but we don't yet have such /// information here, so we just conservatively calculate traits in scope for *all* modules @@ -148,10 +152,10 @@ impl<'ra> EarlyDocLinkResolver<'_, 'ra> { // privacy, private traits and impls from other crates are never documented in // the current crate, and links in their doc comments are not resolved. for &(trait_def_id, impl_def_id, simplified_self_ty) in &all_trait_impls { - if self.resolver.cstore().visibility_untracked(trait_def_id).is_public() - && simplified_self_ty.and_then(|ty| ty.def()).map_or(true, |ty_def_id| { - self.resolver.cstore().visibility_untracked(ty_def_id).is_public() - }) + if self.is_doc_reachable(trait_def_id) + && simplified_self_ty + .and_then(|ty| ty.def()) + .map_or(true, |ty_def_id| self.is_doc_reachable(ty_def_id)) { if self.visited_mods.insert(trait_def_id) { self.resolve_doc_links_extern_impl(trait_def_id, false); @@ -160,7 +164,7 @@ impl<'ra> EarlyDocLinkResolver<'_, 'ra> { } } for (ty_def_id, impl_def_id) in all_inherent_impls { - if self.resolver.cstore().visibility_untracked(ty_def_id).is_public() { + if self.is_doc_reachable(ty_def_id) { self.resolve_doc_links_extern_impl(impl_def_id, true); } } From 800f1f351399a4923636c77b7a34a66ee0b09d8b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 25 Jan 2023 19:18:01 +0000 Subject: [PATCH 357/500] Liberate late-bound regions correctly --- .../src/traits/error_reporting/suggestions.rs | 4 +-- .../late-bound-in-borrow-closure-sugg.rs | 28 +++++++++++++++++++ .../late-bound-in-borrow-closure-sugg.stderr | 26 +++++++++++++++++ 3 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 tests/ui/suggestions/late-bound-in-borrow-closure-sugg.rs create mode 100644 tests/ui/suggestions/late-bound-in-borrow-closure-sugg.stderr diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 39e50b2accf17..3028242781cb0 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -3758,13 +3758,13 @@ fn hint_missing_borrow<'tcx>( err: &mut Diagnostic, ) { let found_args = match found.kind() { - ty::FnPtr(f) => f.inputs().skip_binder().iter(), + ty::FnPtr(f) => infcx.replace_bound_vars_with_placeholders(*f).inputs().iter(), kind => { span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind) } }; let expected_args = match expected.kind() { - ty::FnPtr(f) => f.inputs().skip_binder().iter(), + ty::FnPtr(f) => infcx.replace_bound_vars_with_placeholders(*f).inputs().iter(), kind => { span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind) } diff --git a/tests/ui/suggestions/late-bound-in-borrow-closure-sugg.rs b/tests/ui/suggestions/late-bound-in-borrow-closure-sugg.rs new file mode 100644 index 0000000000000..3bf6b7bb9b19e --- /dev/null +++ b/tests/ui/suggestions/late-bound-in-borrow-closure-sugg.rs @@ -0,0 +1,28 @@ +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +pub struct Trader<'a> { + closure: Box, +} + +impl<'a> Trader<'a> { + pub fn new() -> Self { + Trader { + closure: Box::new(|_| {}), + } + } + pub fn set_closure(&mut self, function: impl Fn(&mut Trader) + 'a) { + //foo + } +} + +fn main() { + let closure = |trader : Trader| { + println!("Woooosh!"); + }; + + let mut trader = Trader::new(); + trader.set_closure(closure); + //~^ ERROR type mismatch in closure arguments +} diff --git a/tests/ui/suggestions/late-bound-in-borrow-closure-sugg.stderr b/tests/ui/suggestions/late-bound-in-borrow-closure-sugg.stderr new file mode 100644 index 0000000000000..4fb5c65235cbb --- /dev/null +++ b/tests/ui/suggestions/late-bound-in-borrow-closure-sugg.stderr @@ -0,0 +1,26 @@ +error[E0631]: type mismatch in closure arguments + --> $DIR/late-bound-in-borrow-closure-sugg.rs:26:24 + | +LL | let closure = |trader : Trader| { + | ----------------- found signature defined here +... +LL | trader.set_closure(closure); + | ----------- ^^^^^^^ expected due to this + | | + | required by a bound introduced by this call + | + = note: expected closure signature `for<'a, 'b> fn(&'a mut Trader<'b>) -> _` + found closure signature `for<'a> fn(Trader<'a>) -> _` +note: required by a bound in `Trader::<'a>::set_closure` + --> $DIR/late-bound-in-borrow-closure-sugg.rs:15:50 + | +LL | pub fn set_closure(&mut self, function: impl Fn(&mut Trader) + 'a) { + | ^^^^^^^^^^^^^^^ required by this bound in `Trader::<'a>::set_closure` +help: consider borrowing the argument + | +LL | let closure = |trader : &Trader| { + | + + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0631`. From b83ab0ce965356308921acabe8a40fe88bcdd8c7 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 25 Jan 2023 19:17:46 +0000 Subject: [PATCH 358/500] Suggest mutable borrows correctly --- .../src/traits/error_reporting/suggestions.rs | 26 +++++++++++++------ .../late-bound-in-borrow-closure-sugg.stderr | 4 +-- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 3028242781cb0..64f19aa009700 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -3775,12 +3775,12 @@ fn hint_missing_borrow<'tcx>( let args = fn_decl.inputs.iter().map(|ty| ty); - fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, usize) { - let mut refs = 0; + fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec) { + let mut refs = vec![]; - while let ty::Ref(_, new_ty, _) = ty.kind() { + while let ty::Ref(_, new_ty, mutbl) = ty.kind() { ty = *new_ty; - refs += 1; + refs.push(*mutbl); } (ty, refs) @@ -3794,11 +3794,21 @@ fn hint_missing_borrow<'tcx>( let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg); if infcx.can_eq(param_env, found_ty, expected_ty).is_ok() { - if found_refs < expected_refs { - to_borrow.push((arg.span.shrink_to_lo(), "&".repeat(expected_refs - found_refs))); - } else if found_refs > expected_refs { + // FIXME: This could handle more exotic cases like mutability mismatches too! + if found_refs.len() < expected_refs.len() + && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..] + { + to_borrow.push(( + arg.span.shrink_to_lo(), + expected_refs[..expected_refs.len() - found_refs.len()] + .iter() + .map(|mutbl| format!("&{}", mutbl.prefix_str())) + .collect::>() + .join(""), + )); + } else if found_refs.len() > expected_refs.len() { let mut span = arg.span.shrink_to_lo(); - let mut left = found_refs - expected_refs; + let mut left = found_refs.len() - expected_refs.len(); let mut ty = arg; while let hir::TyKind::Ref(_, mut_ty) = &ty.kind && left > 0 { span = span.with_hi(mut_ty.ty.span.lo()); diff --git a/tests/ui/suggestions/late-bound-in-borrow-closure-sugg.stderr b/tests/ui/suggestions/late-bound-in-borrow-closure-sugg.stderr index 4fb5c65235cbb..6820af1fd45c3 100644 --- a/tests/ui/suggestions/late-bound-in-borrow-closure-sugg.stderr +++ b/tests/ui/suggestions/late-bound-in-borrow-closure-sugg.stderr @@ -18,8 +18,8 @@ LL | pub fn set_closure(&mut self, function: impl Fn(&mut Trader) + 'a) { | ^^^^^^^^^^^^^^^ required by this bound in `Trader::<'a>::set_closure` help: consider borrowing the argument | -LL | let closure = |trader : &Trader| { - | + +LL | let closure = |trader : &mut Trader| { + | ++++ error: aborting due to previous error From 398225842cbff0cdd45021bfe91712d407a900b8 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Wed, 25 Jan 2023 23:29:19 +0400 Subject: [PATCH 359/500] rustdoc: Don't put non rustdoc-reachable impls into `all_trait_impls` --- src/librustdoc/passes/collect_intra_doc_links/early.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/librustdoc/passes/collect_intra_doc_links/early.rs b/src/librustdoc/passes/collect_intra_doc_links/early.rs index 920028dd63c8f..f690c49005d9c 100644 --- a/src/librustdoc/passes/collect_intra_doc_links/early.rs +++ b/src/librustdoc/passes/collect_intra_doc_links/early.rs @@ -162,6 +162,7 @@ impl<'ra> EarlyDocLinkResolver<'_, 'ra> { } self.resolve_doc_links_extern_impl(impl_def_id, false); } + self.all_trait_impls.push(impl_def_id); } for (ty_def_id, impl_def_id) in all_inherent_impls { if self.is_doc_reachable(ty_def_id) { @@ -171,9 +172,6 @@ impl<'ra> EarlyDocLinkResolver<'_, 'ra> { for impl_def_id in all_incoherent_impls { self.resolve_doc_links_extern_impl(impl_def_id, true); } - - self.all_trait_impls - .extend(all_trait_impls.into_iter().map(|(_, def_id, _)| def_id)); } if crates.len() > start_cnum { From b222f2e2660f8d81dc30061c918d774147fcf1a6 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Wed, 25 Jan 2023 19:53:03 +0100 Subject: [PATCH 360/500] Move `note_and_explain_type_err` from `rustc_middle` to `rustc_infer` This way we can properly deal with the types. --- .../src/infer/error_reporting/mod.rs | 5 +- .../infer/error_reporting/note_and_explain.rs | 647 ++++++++++++++++++ compiler/rustc_middle/src/ty/assoc.rs | 2 +- compiler/rustc_middle/src/ty/error.rs | 637 +---------------- 4 files changed, 657 insertions(+), 634 deletions(-) create mode 100644 compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 79704b6adf78e..faba723acda8d 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -79,6 +79,7 @@ use std::path::PathBuf; use std::{cmp, fmt, iter}; mod note; +mod note_and_explain; mod suggest; pub(crate) mod need_type_info; @@ -1846,7 +1847,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } self.check_and_note_conflicting_crates(diag, terr); - self.tcx.note_and_explain_type_err(diag, terr, cause, span, cause.body_id.to_def_id()); + + self.note_and_explain_type_err(diag, terr, cause, span, cause.body_id.to_def_id()); + if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind() diff --git a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs new file mode 100644 index 0000000000000..6e781a041e013 --- /dev/null +++ b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs @@ -0,0 +1,647 @@ +use super::TypeErrCtxt; +use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect}; +use rustc_errors::{pluralize, Diagnostic, MultiSpan}; +use rustc_hir::{self as hir, def::DefKind}; +use rustc_middle::traits::ObligationCauseCode; +use rustc_middle::ty::error::ExpectedFound; +use rustc_middle::ty::print::Printer; +use rustc_middle::{ + traits::ObligationCause, + ty::{self, error::TypeError, print::FmtPrinter, suggest_constraining_type_param, Ty}, +}; +use rustc_span::{def_id::DefId, sym, BytePos, Span, Symbol}; + +impl<'tcx> TypeErrCtxt<'_, 'tcx> { + pub fn note_and_explain_type_err( + &self, + diag: &mut Diagnostic, + err: TypeError<'tcx>, + cause: &ObligationCause<'tcx>, + sp: Span, + body_owner_def_id: DefId, + ) { + use ty::error::TypeError::*; + debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause); + + let tcx = self.tcx; + + match err { + ArgumentSorts(values, _) | Sorts(values) => { + match (values.expected.kind(), values.found.kind()) { + (ty::Closure(..), ty::Closure(..)) => { + diag.note("no two closures, even if identical, have the same type"); + diag.help("consider boxing your closure and/or using it as a trait object"); + } + (ty::Alias(ty::Opaque, ..), ty::Alias(ty::Opaque, ..)) => { + // Issue #63167 + diag.note("distinct uses of `impl Trait` result in different opaque types"); + } + (ty::Float(_), ty::Infer(ty::IntVar(_))) + if let Ok( + // Issue #53280 + snippet, + ) = tcx.sess.source_map().span_to_snippet(sp) => + { + if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') { + diag.span_suggestion( + sp, + "use a float literal", + format!("{}.0", snippet), + MachineApplicable, + ); + } + } + (ty::Param(expected), ty::Param(found)) => { + let generics = tcx.generics_of(body_owner_def_id); + let e_span = tcx.def_span(generics.type_param(expected, tcx).def_id); + if !sp.contains(e_span) { + diag.span_label(e_span, "expected type parameter"); + } + let f_span = tcx.def_span(generics.type_param(found, tcx).def_id); + if !sp.contains(f_span) { + diag.span_label(f_span, "found type parameter"); + } + diag.note( + "a type parameter was expected, but a different one was found; \ + you might be missing a type parameter or trait bound", + ); + diag.note( + "for more information, visit \ + https://doc.rust-lang.org/book/ch10-02-traits.html\ + #traits-as-parameters", + ); + } + (ty::Alias(ty::Projection, _), ty::Alias(ty::Projection, _)) => { + diag.note("an associated type was expected, but a different one was found"); + } + (ty::Param(p), ty::Alias(ty::Projection, proj)) | (ty::Alias(ty::Projection, proj), ty::Param(p)) + if tcx.def_kind(proj.def_id) != DefKind::ImplTraitPlaceholder => + { + let generics = tcx.generics_of(body_owner_def_id); + let p_span = tcx.def_span(generics.type_param(p, tcx).def_id); + if !sp.contains(p_span) { + diag.span_label(p_span, "this type parameter"); + } + let hir = tcx.hir(); + let mut note = true; + if let Some(generics) = generics + .type_param(p, tcx) + .def_id + .as_local() + .map(|id| hir.local_def_id_to_hir_id(id)) + .and_then(|id| tcx.hir().find_parent(id)) + .as_ref() + .and_then(|node| node.generics()) + { + // Synthesize the associated type restriction `Add`. + // FIXME: extract this logic for use in other diagnostics. + let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(tcx); + let path = + tcx.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs); + let item_name = tcx.item_name(proj.def_id); + let item_args = self.format_generic_args(assoc_substs); + + let path = if path.ends_with('>') { + format!( + "{}, {}{} = {}>", + &path[..path.len() - 1], + item_name, + item_args, + p + ) + } else { + format!("{}<{}{} = {}>", path, item_name, item_args, p) + }; + note = !suggest_constraining_type_param( + tcx, + generics, + diag, + &format!("{}", proj.self_ty()), + &path, + None, + ); + } + if note { + diag.note("you might be missing a type parameter or trait bound"); + } + } + (ty::Param(p), ty::Dynamic(..) | ty::Alias(ty::Opaque, ..)) + | (ty::Dynamic(..) | ty::Alias(ty::Opaque, ..), ty::Param(p)) => { + let generics = tcx.generics_of(body_owner_def_id); + let p_span = tcx.def_span(generics.type_param(p, tcx).def_id); + if !sp.contains(p_span) { + diag.span_label(p_span, "this type parameter"); + } + diag.help("type parameters must be constrained to match other types"); + if tcx.sess.teach(&diag.get_code().unwrap()) { + diag.help( + "given a type parameter `T` and a method `foo`: +``` +trait Trait { fn foo(&tcx) -> T; } +``` +the only ways to implement method `foo` are: +- constrain `T` with an explicit type: +``` +impl Trait for X { + fn foo(&tcx) -> String { String::new() } +} +``` +- add a trait bound to `T` and call a method on that trait that returns `Self`: +``` +impl Trait for X { + fn foo(&tcx) -> T { ::default() } +} +``` +- change `foo` to return an argument of type `T`: +``` +impl Trait for X { + fn foo(&tcx, x: T) -> T { x } +} +```", + ); + } + diag.note( + "for more information, visit \ + https://doc.rust-lang.org/book/ch10-02-traits.html\ + #traits-as-parameters", + ); + } + (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => { + let generics = tcx.generics_of(body_owner_def_id); + let p_span = tcx.def_span(generics.type_param(p, tcx).def_id); + if !sp.contains(p_span) { + diag.span_label(p_span, "this type parameter"); + } + diag.help(&format!( + "every closure has a distinct type and so could not always match the \ + caller-chosen type of parameter `{}`", + p + )); + } + (ty::Param(p), _) | (_, ty::Param(p)) => { + let generics = tcx.generics_of(body_owner_def_id); + let p_span = tcx.def_span(generics.type_param(p, tcx).def_id); + if !sp.contains(p_span) { + diag.span_label(p_span, "this type parameter"); + } + } + (ty::Alias(ty::Projection, proj_ty), _) if tcx.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => { + self.expected_projection( + diag, + proj_ty, + values, + body_owner_def_id, + cause.code(), + ); + } + (_, ty::Alias(ty::Projection, proj_ty)) if tcx.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => { + let msg = format!( + "consider constraining the associated type `{}` to `{}`", + values.found, values.expected, + ); + if !(self.suggest_constraining_opaque_associated_type( + diag, + &msg, + proj_ty, + values.expected, + ) || self.suggest_constraint( + diag, + &msg, + body_owner_def_id, + proj_ty, + values.expected, + )) { + diag.help(&msg); + diag.note( + "for more information, visit \ + https://doc.rust-lang.org/book/ch19-03-advanced-traits.html", + ); + } + } + _ => {} + } + debug!( + "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})", + values.expected, + values.expected.kind(), + values.found, + values.found.kind(), + ); + } + CyclicTy(ty) => { + // Watch out for various cases of cyclic types and try to explain. + if ty.is_closure() || ty.is_generator() { + diag.note( + "closures cannot capture themselves or take themselves as argument;\n\ + this error may be the result of a recent compiler bug-fix,\n\ + see issue #46062 \n\ + for more information", + ); + } + } + TargetFeatureCast(def_id) => { + let target_spans = tcx.get_attrs(def_id, sym::target_feature).map(|attr| attr.span); + diag.note( + "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers" + ); + diag.span_labels(target_spans, "`#[target_feature]` added here"); + } + _ => {} + } + } + + fn suggest_constraint( + &self, + diag: &mut Diagnostic, + msg: &str, + body_owner_def_id: DefId, + proj_ty: &ty::AliasTy<'tcx>, + ty: Ty<'tcx>, + ) -> bool { + let tcx = self.tcx; + let assoc = tcx.associated_item(proj_ty.def_id); + let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx); + if let Some(item) = tcx.hir().get_if_local(body_owner_def_id) { + if let Some(hir_generics) = item.generics() { + // Get the `DefId` for the type parameter corresponding to `A` in `::Foo`. + // This will also work for `impl Trait`. + let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() { + let generics = tcx.generics_of(body_owner_def_id); + generics.type_param(param_ty, tcx).def_id + } else { + return false; + }; + let Some(def_id) = def_id.as_local() else { + return false; + }; + + // First look in the `where` clause, as this might be + // `fn foo(x: T) where T: Trait`. + for pred in hir_generics.bounds_for_param(def_id) { + if self.constrain_generic_bound_associated_type_structured_suggestion( + diag, + &trait_ref, + pred.bounds, + &assoc, + assoc_substs, + ty, + msg, + false, + ) { + return true; + } + } + } + } + false + } + + /// An associated type was expected and a different type was found. + /// + /// We perform a few different checks to see what we can suggest: + /// + /// - In the current item, look for associated functions that return the expected type and + /// suggest calling them. (Not a structured suggestion.) + /// - If any of the item's generic bounds can be constrained, we suggest constraining the + /// associated type to the found type. + /// - If the associated type has a default type and was expected inside of a `trait`, we + /// mention that this is disallowed. + /// - If all other things fail, and the error is not because of a mismatch between the `trait` + /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc + /// fn that returns the type. + fn expected_projection( + &self, + diag: &mut Diagnostic, + proj_ty: &ty::AliasTy<'tcx>, + values: ExpectedFound>, + body_owner_def_id: DefId, + cause_code: &ObligationCauseCode<'_>, + ) { + let tcx = self.tcx; + + let msg = format!( + "consider constraining the associated type `{}` to `{}`", + values.expected, values.found + ); + let body_owner = tcx.hir().get_if_local(body_owner_def_id); + let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name); + + // We don't want to suggest calling an assoc fn in a scope where that isn't feasible. + let callable_scope = matches!( + body_owner, + Some( + hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. }) + | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. }) + | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }), + ) + ); + let impl_comparison = + matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. }); + let assoc = tcx.associated_item(proj_ty.def_id); + if !callable_scope || impl_comparison { + // We do not want to suggest calling functions when the reason of the + // type error is a comparison of an `impl` with its `trait` or when the + // scope is outside of a `Body`. + } else { + // If we find a suitable associated function that returns the expected type, we don't + // want the more general suggestion later in this method about "consider constraining + // the associated type or calling a method that returns the associated type". + let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type( + diag, + assoc.container_id(tcx), + current_method_ident, + proj_ty.def_id, + values.expected, + ); + // Possibly suggest constraining the associated type to conform to the + // found type. + if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found) + || point_at_assoc_fn + { + return; + } + } + + self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found); + + if self.point_at_associated_type(diag, body_owner_def_id, values.found) { + return; + } + + if !impl_comparison { + // Generic suggestion when we can't be more specific. + if callable_scope { + diag.help(&format!( + "{} or calling a method that returns `{}`", + msg, values.expected + )); + } else { + diag.help(&msg); + } + diag.note( + "for more information, visit \ + https://doc.rust-lang.org/book/ch19-03-advanced-traits.html", + ); + } + if tcx.sess.teach(&diag.get_code().unwrap()) { + diag.help( + "given an associated type `T` and a method `foo`: +``` +trait Trait { +type T; +fn foo(&tcx) -> Self::T; +} +``` +the only way of implementing method `foo` is to constrain `T` with an explicit associated type: +``` +impl Trait for X { +type T = String; +fn foo(&tcx) -> Self::T { String::new() } +} +```", + ); + } + } + + /// When the expected `impl Trait` is not defined in the current item, it will come from + /// a return type. This can occur when dealing with `TryStream` (#71035). + fn suggest_constraining_opaque_associated_type( + &self, + diag: &mut Diagnostic, + msg: &str, + proj_ty: &ty::AliasTy<'tcx>, + ty: Ty<'tcx>, + ) -> bool { + let tcx = self.tcx; + + let assoc = tcx.associated_item(proj_ty.def_id); + if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() { + let opaque_local_def_id = def_id.as_local(); + let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id { + match &tcx.hir().expect_item(opaque_local_def_id).kind { + hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty, + _ => bug!("The HirId comes from a `ty::Opaque`"), + } + } else { + return false; + }; + + let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx); + + self.constrain_generic_bound_associated_type_structured_suggestion( + diag, + &trait_ref, + opaque_hir_ty.bounds, + assoc, + assoc_substs, + ty, + msg, + true, + ) + } else { + false + } + } + + fn point_at_methods_that_satisfy_associated_type( + &self, + diag: &mut Diagnostic, + assoc_container_id: DefId, + current_method_ident: Option, + proj_ty_item_def_id: DefId, + expected: Ty<'tcx>, + ) -> bool { + let tcx = self.tcx; + + let items = tcx.associated_items(assoc_container_id); + // Find all the methods in the trait that could be called to construct the + // expected associated type. + // FIXME: consider suggesting the use of associated `const`s. + let methods: Vec<(Span, String)> = items + .in_definition_order() + .filter(|item| { + ty::AssocKind::Fn == item.kind && Some(item.name) != current_method_ident + }) + .filter_map(|item| { + let method = tcx.fn_sig(item.def_id); + match *method.output().skip_binder().kind() { + ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. }) + if item_def_id == proj_ty_item_def_id => + { + Some(( + tcx.def_span(item.def_id), + format!("consider calling `{}`", tcx.def_path_str(item.def_id)), + )) + } + _ => None, + } + }) + .collect(); + if !methods.is_empty() { + // Use a single `help:` to show all the methods in the trait that can + // be used to construct the expected associated type. + let mut span: MultiSpan = + methods.iter().map(|(sp, _)| *sp).collect::>().into(); + let msg = format!( + "{some} method{s} {are} available that return{r} `{ty}`", + some = if methods.len() == 1 { "a" } else { "some" }, + s = pluralize!(methods.len()), + are = pluralize!("is", methods.len()), + r = if methods.len() == 1 { "s" } else { "" }, + ty = expected + ); + for (sp, label) in methods.into_iter() { + span.push_span_label(sp, label); + } + diag.span_help(span, &msg); + return true; + } + false + } + + fn point_at_associated_type( + &self, + diag: &mut Diagnostic, + body_owner_def_id: DefId, + found: Ty<'tcx>, + ) -> bool { + let tcx = self.tcx; + + let Some(hir_id) = body_owner_def_id.as_local() else { + return false; + }; + let hir_id = tcx.hir().local_def_id_to_hir_id(hir_id); + // When `body_owner` is an `impl` or `trait` item, look in its associated types for + // `expected` and point at it. + let parent_id = tcx.hir().get_parent_item(hir_id); + let item = tcx.hir().find_by_def_id(parent_id.def_id); + debug!("expected_projection parent item {:?}", item); + match item { + Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => { + // FIXME: account for `#![feature(specialization)]` + for item in &items[..] { + match item.kind { + hir::AssocItemKind::Type => { + // FIXME: account for returning some type in a trait fn impl that has + // an assoc type as a return type (#72076). + if let hir::Defaultness::Default { has_value: true } = + tcx.impl_defaultness(item.id.owner_id) + { + if tcx.type_of(item.id.owner_id) == found { + diag.span_label( + item.span, + "associated type defaults can't be assumed inside the \ + trait defining them", + ); + return true; + } + } + } + _ => {} + } + } + } + Some(hir::Node::Item(hir::Item { + kind: hir::ItemKind::Impl(hir::Impl { items, .. }), + .. + })) => { + for item in &items[..] { + if let hir::AssocItemKind::Type = item.kind { + if tcx.type_of(item.id.owner_id) == found { + diag.span_label(item.span, "expected this associated type"); + return true; + } + } + } + } + _ => {} + } + false + } + + /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref` + /// requirement, provide a structured suggestion to constrain it to a given type `ty`. + /// + /// `is_bound_surely_present` indicates whether we know the bound we're looking for is + /// inside `bounds`. If that's the case then we can consider `bounds` containing only one + /// trait bound as the one we're looking for. This can help in cases where the associated + /// type is defined on a supertrait of the one present in the bounds. + fn constrain_generic_bound_associated_type_structured_suggestion( + &self, + diag: &mut Diagnostic, + trait_ref: &ty::TraitRef<'tcx>, + bounds: hir::GenericBounds<'_>, + assoc: &ty::AssocItem, + assoc_substs: &[ty::GenericArg<'tcx>], + ty: Ty<'tcx>, + msg: &str, + is_bound_surely_present: bool, + ) -> bool { + // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting. + + let trait_bounds = bounds.iter().filter_map(|bound| match bound { + hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr), + _ => None, + }); + + let matching_trait_bounds = trait_bounds + .clone() + .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id)) + .collect::>(); + + let span = match &matching_trait_bounds[..] { + &[ptr] => ptr.span, + &[] if is_bound_surely_present => match &trait_bounds.collect::>()[..] { + &[ptr] => ptr.span, + _ => return false, + }, + _ => return false, + }; + + self.constrain_associated_type_structured_suggestion( + diag, + span, + assoc, + assoc_substs, + ty, + msg, + ) + } + + /// Given a span corresponding to a bound, provide a structured suggestion to set an + /// associated type to a given type `ty`. + fn constrain_associated_type_structured_suggestion( + &self, + diag: &mut Diagnostic, + span: Span, + assoc: &ty::AssocItem, + assoc_substs: &[ty::GenericArg<'tcx>], + ty: Ty<'tcx>, + msg: &str, + ) -> bool { + let tcx = self.tcx; + + if let Ok(has_params) = + tcx.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>')) + { + let (span, sugg) = if has_params { + let pos = span.hi() - BytePos(1); + let span = Span::new(pos, pos, span.ctxt(), span.parent()); + (span, format!(", {} = {}", assoc.ident(tcx), ty)) + } else { + let item_args = self.format_generic_args(assoc_substs); + (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(tcx), item_args, ty)) + }; + diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect); + return true; + } + false + } + + pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String { + FmtPrinter::new(self.tcx, hir::def::Namespace::TypeNS) + .path_generic_args(Ok, args) + .expect("could not write to `String`.") + .into_buffer() + } +} diff --git a/compiler/rustc_middle/src/ty/assoc.rs b/compiler/rustc_middle/src/ty/assoc.rs index bb7fba3ee7119..47091ca1d69a7 100644 --- a/compiler/rustc_middle/src/ty/assoc.rs +++ b/compiler/rustc_middle/src/ty/assoc.rs @@ -130,7 +130,7 @@ impl std::fmt::Display for AssocKind { /// done only on items with the same name. #[derive(Debug, Clone, PartialEq, HashStable)] pub struct AssocItems<'tcx> { - pub(super) items: SortedIndexMultiMap, + items: SortedIndexMultiMap, } impl<'tcx> AssocItems<'tcx> { diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index 5d394f71f0d76..c8a700c4e280d 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -1,24 +1,18 @@ -use crate::traits::{ObligationCause, ObligationCauseCode}; -use crate::ty::diagnostics::suggest_constraining_type_param; -use crate::ty::print::{with_forced_trimmed_paths, FmtPrinter, Printer}; +use crate::ty::print::{with_forced_trimmed_paths, FmtPrinter, PrettyPrinter}; use crate::ty::{self, BoundRegionKind, Region, Ty, TyCtxt}; -use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect}; -use rustc_errors::{pluralize, Diagnostic, MultiSpan}; +use rustc_errors::pluralize; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind}; use rustc_hir::def_id::DefId; -use rustc_span::symbol::{sym, Symbol}; -use rustc_span::{BytePos, Span}; +use rustc_span::symbol::Symbol; use rustc_target::spec::abi; - use std::borrow::Cow; use std::collections::hash_map::DefaultHasher; use std::fmt; -use std::hash::{Hash, Hasher}; +use std::hash::Hash; +use std::hash::Hasher; use std::path::PathBuf; -use super::print::PrettyPrinter; - #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable, Lift)] pub struct ExpectedFound { pub expected: T, @@ -391,620 +385,6 @@ impl<'tcx> Ty<'tcx> { } impl<'tcx> TyCtxt<'tcx> { - pub fn note_and_explain_type_err( - self, - diag: &mut Diagnostic, - err: TypeError<'tcx>, - cause: &ObligationCause<'tcx>, - sp: Span, - body_owner_def_id: DefId, - ) { - use self::TypeError::*; - debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause); - match err { - ArgumentSorts(values, _) | Sorts(values) => { - match (values.expected.kind(), values.found.kind()) { - (ty::Closure(..), ty::Closure(..)) => { - diag.note("no two closures, even if identical, have the same type"); - diag.help("consider boxing your closure and/or using it as a trait object"); - } - (ty::Alias(ty::Opaque, ..), ty::Alias(ty::Opaque, ..)) => { - // Issue #63167 - diag.note("distinct uses of `impl Trait` result in different opaque types"); - } - (ty::Float(_), ty::Infer(ty::IntVar(_))) - if let Ok( - // Issue #53280 - snippet, - ) = self.sess.source_map().span_to_snippet(sp) => - { - if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') { - diag.span_suggestion( - sp, - "use a float literal", - format!("{}.0", snippet), - MachineApplicable, - ); - } - } - (ty::Param(expected), ty::Param(found)) => { - let generics = self.generics_of(body_owner_def_id); - let e_span = self.def_span(generics.type_param(expected, self).def_id); - if !sp.contains(e_span) { - diag.span_label(e_span, "expected type parameter"); - } - let f_span = self.def_span(generics.type_param(found, self).def_id); - if !sp.contains(f_span) { - diag.span_label(f_span, "found type parameter"); - } - diag.note( - "a type parameter was expected, but a different one was found; \ - you might be missing a type parameter or trait bound", - ); - diag.note( - "for more information, visit \ - https://doc.rust-lang.org/book/ch10-02-traits.html\ - #traits-as-parameters", - ); - } - (ty::Alias(ty::Projection, _), ty::Alias(ty::Projection, _)) => { - diag.note("an associated type was expected, but a different one was found"); - } - (ty::Param(p), ty::Alias(ty::Projection, proj)) | (ty::Alias(ty::Projection, proj), ty::Param(p)) - if self.def_kind(proj.def_id) != DefKind::ImplTraitPlaceholder => - { - let generics = self.generics_of(body_owner_def_id); - let p_span = self.def_span(generics.type_param(p, self).def_id); - if !sp.contains(p_span) { - diag.span_label(p_span, "this type parameter"); - } - let hir = self.hir(); - let mut note = true; - if let Some(generics) = generics - .type_param(p, self) - .def_id - .as_local() - .map(|id| hir.local_def_id_to_hir_id(id)) - .and_then(|id| self.hir().find_parent(id)) - .as_ref() - .and_then(|node| node.generics()) - { - // Synthesize the associated type restriction `Add`. - // FIXME: extract this logic for use in other diagnostics. - let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(self); - let path = - self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs); - let item_name = self.item_name(proj.def_id); - let item_args = self.format_generic_args(assoc_substs); - - let path = if path.ends_with('>') { - format!( - "{}, {}{} = {}>", - &path[..path.len() - 1], - item_name, - item_args, - p - ) - } else { - format!("{}<{}{} = {}>", path, item_name, item_args, p) - }; - note = !suggest_constraining_type_param( - self, - generics, - diag, - &format!("{}", proj.self_ty()), - &path, - None, - ); - } - if note { - diag.note("you might be missing a type parameter or trait bound"); - } - } - (ty::Param(p), ty::Dynamic(..) | ty::Alias(ty::Opaque, ..)) - | (ty::Dynamic(..) | ty::Alias(ty::Opaque, ..), ty::Param(p)) => { - let generics = self.generics_of(body_owner_def_id); - let p_span = self.def_span(generics.type_param(p, self).def_id); - if !sp.contains(p_span) { - diag.span_label(p_span, "this type parameter"); - } - diag.help("type parameters must be constrained to match other types"); - if self.sess.teach(&diag.get_code().unwrap()) { - diag.help( - "given a type parameter `T` and a method `foo`: -``` -trait Trait { fn foo(&self) -> T; } -``` -the only ways to implement method `foo` are: -- constrain `T` with an explicit type: -``` -impl Trait for X { - fn foo(&self) -> String { String::new() } -} -``` -- add a trait bound to `T` and call a method on that trait that returns `Self`: -``` -impl Trait for X { - fn foo(&self) -> T { ::default() } -} -``` -- change `foo` to return an argument of type `T`: -``` -impl Trait for X { - fn foo(&self, x: T) -> T { x } -} -```", - ); - } - diag.note( - "for more information, visit \ - https://doc.rust-lang.org/book/ch10-02-traits.html\ - #traits-as-parameters", - ); - } - (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => { - let generics = self.generics_of(body_owner_def_id); - let p_span = self.def_span(generics.type_param(p, self).def_id); - if !sp.contains(p_span) { - diag.span_label(p_span, "this type parameter"); - } - diag.help(&format!( - "every closure has a distinct type and so could not always match the \ - caller-chosen type of parameter `{}`", - p - )); - } - (ty::Param(p), _) | (_, ty::Param(p)) => { - let generics = self.generics_of(body_owner_def_id); - let p_span = self.def_span(generics.type_param(p, self).def_id); - if !sp.contains(p_span) { - diag.span_label(p_span, "this type parameter"); - } - } - (ty::Alias(ty::Projection, proj_ty), _) if self.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => { - self.expected_projection( - diag, - proj_ty, - values, - body_owner_def_id, - cause.code(), - ); - } - (_, ty::Alias(ty::Projection, proj_ty)) if self.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => { - let msg = format!( - "consider constraining the associated type `{}` to `{}`", - values.found, values.expected, - ); - if !(self.suggest_constraining_opaque_associated_type( - diag, - &msg, - proj_ty, - values.expected, - ) || self.suggest_constraint( - diag, - &msg, - body_owner_def_id, - proj_ty, - values.expected, - )) { - diag.help(&msg); - diag.note( - "for more information, visit \ - https://doc.rust-lang.org/book/ch19-03-advanced-traits.html", - ); - } - } - _ => {} - } - debug!( - "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})", - values.expected, - values.expected.kind(), - values.found, - values.found.kind(), - ); - } - CyclicTy(ty) => { - // Watch out for various cases of cyclic types and try to explain. - if ty.is_closure() || ty.is_generator() { - diag.note( - "closures cannot capture themselves or take themselves as argument;\n\ - this error may be the result of a recent compiler bug-fix,\n\ - see issue #46062 \n\ - for more information", - ); - } - } - TargetFeatureCast(def_id) => { - let target_spans = - self.get_attrs(def_id, sym::target_feature).map(|attr| attr.span); - diag.note( - "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers" - ); - diag.span_labels(target_spans, "`#[target_feature]` added here"); - } - _ => {} - } - } - - fn suggest_constraint( - self, - diag: &mut Diagnostic, - msg: &str, - body_owner_def_id: DefId, - proj_ty: &ty::AliasTy<'tcx>, - ty: Ty<'tcx>, - ) -> bool { - let assoc = self.associated_item(proj_ty.def_id); - let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self); - if let Some(item) = self.hir().get_if_local(body_owner_def_id) { - if let Some(hir_generics) = item.generics() { - // Get the `DefId` for the type parameter corresponding to `A` in `::Foo`. - // This will also work for `impl Trait`. - let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() { - let generics = self.generics_of(body_owner_def_id); - generics.type_param(param_ty, self).def_id - } else { - return false; - }; - let Some(def_id) = def_id.as_local() else { - return false; - }; - - // First look in the `where` clause, as this might be - // `fn foo(x: T) where T: Trait`. - for pred in hir_generics.bounds_for_param(def_id) { - if self.constrain_generic_bound_associated_type_structured_suggestion( - diag, - &trait_ref, - pred.bounds, - &assoc, - assoc_substs, - ty, - msg, - false, - ) { - return true; - } - } - } - } - false - } - - /// An associated type was expected and a different type was found. - /// - /// We perform a few different checks to see what we can suggest: - /// - /// - In the current item, look for associated functions that return the expected type and - /// suggest calling them. (Not a structured suggestion.) - /// - If any of the item's generic bounds can be constrained, we suggest constraining the - /// associated type to the found type. - /// - If the associated type has a default type and was expected inside of a `trait`, we - /// mention that this is disallowed. - /// - If all other things fail, and the error is not because of a mismatch between the `trait` - /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc - /// fn that returns the type. - fn expected_projection( - self, - diag: &mut Diagnostic, - proj_ty: &ty::AliasTy<'tcx>, - values: ExpectedFound>, - body_owner_def_id: DefId, - cause_code: &ObligationCauseCode<'_>, - ) { - let msg = format!( - "consider constraining the associated type `{}` to `{}`", - values.expected, values.found - ); - let body_owner = self.hir().get_if_local(body_owner_def_id); - let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name); - - // We don't want to suggest calling an assoc fn in a scope where that isn't feasible. - let callable_scope = matches!( - body_owner, - Some( - hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. }) - | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. }) - | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }), - ) - ); - let impl_comparison = - matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. }); - let assoc = self.associated_item(proj_ty.def_id); - if !callable_scope || impl_comparison { - // We do not want to suggest calling functions when the reason of the - // type error is a comparison of an `impl` with its `trait` or when the - // scope is outside of a `Body`. - } else { - // If we find a suitable associated function that returns the expected type, we don't - // want the more general suggestion later in this method about "consider constraining - // the associated type or calling a method that returns the associated type". - let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type( - diag, - assoc.container_id(self), - current_method_ident, - proj_ty.def_id, - values.expected, - ); - // Possibly suggest constraining the associated type to conform to the - // found type. - if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found) - || point_at_assoc_fn - { - return; - } - } - - self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found); - - if self.point_at_associated_type(diag, body_owner_def_id, values.found) { - return; - } - - if !impl_comparison { - // Generic suggestion when we can't be more specific. - if callable_scope { - diag.help(&format!( - "{} or calling a method that returns `{}`", - msg, values.expected - )); - } else { - diag.help(&msg); - } - diag.note( - "for more information, visit \ - https://doc.rust-lang.org/book/ch19-03-advanced-traits.html", - ); - } - if self.sess.teach(&diag.get_code().unwrap()) { - diag.help( - "given an associated type `T` and a method `foo`: -``` -trait Trait { -type T; -fn foo(&self) -> Self::T; -} -``` -the only way of implementing method `foo` is to constrain `T` with an explicit associated type: -``` -impl Trait for X { -type T = String; -fn foo(&self) -> Self::T { String::new() } -} -```", - ); - } - } - - /// When the expected `impl Trait` is not defined in the current item, it will come from - /// a return type. This can occur when dealing with `TryStream` (#71035). - fn suggest_constraining_opaque_associated_type( - self, - diag: &mut Diagnostic, - msg: &str, - proj_ty: &ty::AliasTy<'tcx>, - ty: Ty<'tcx>, - ) -> bool { - let assoc = self.associated_item(proj_ty.def_id); - if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() { - let opaque_local_def_id = def_id.as_local(); - let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id { - match &self.hir().expect_item(opaque_local_def_id).kind { - hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty, - _ => bug!("The HirId comes from a `ty::Opaque`"), - } - } else { - return false; - }; - - let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self); - - self.constrain_generic_bound_associated_type_structured_suggestion( - diag, - &trait_ref, - opaque_hir_ty.bounds, - assoc, - assoc_substs, - ty, - msg, - true, - ) - } else { - false - } - } - - fn point_at_methods_that_satisfy_associated_type( - self, - diag: &mut Diagnostic, - assoc_container_id: DefId, - current_method_ident: Option, - proj_ty_item_def_id: DefId, - expected: Ty<'tcx>, - ) -> bool { - let items = self.associated_items(assoc_container_id); - // Find all the methods in the trait that could be called to construct the - // expected associated type. - // FIXME: consider suggesting the use of associated `const`s. - let methods: Vec<(Span, String)> = items - .items - .iter() - .filter(|(name, item)| { - ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident - }) - .filter_map(|(_, item)| { - let method = self.fn_sig(item.def_id); - match *method.output().skip_binder().kind() { - ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. }) - if item_def_id == proj_ty_item_def_id => - { - Some(( - self.def_span(item.def_id), - format!("consider calling `{}`", self.def_path_str(item.def_id)), - )) - } - _ => None, - } - }) - .collect(); - if !methods.is_empty() { - // Use a single `help:` to show all the methods in the trait that can - // be used to construct the expected associated type. - let mut span: MultiSpan = - methods.iter().map(|(sp, _)| *sp).collect::>().into(); - let msg = format!( - "{some} method{s} {are} available that return{r} `{ty}`", - some = if methods.len() == 1 { "a" } else { "some" }, - s = pluralize!(methods.len()), - are = pluralize!("is", methods.len()), - r = if methods.len() == 1 { "s" } else { "" }, - ty = expected - ); - for (sp, label) in methods.into_iter() { - span.push_span_label(sp, label); - } - diag.span_help(span, &msg); - return true; - } - false - } - - fn point_at_associated_type( - self, - diag: &mut Diagnostic, - body_owner_def_id: DefId, - found: Ty<'tcx>, - ) -> bool { - let Some(hir_id) = body_owner_def_id.as_local() else { - return false; - }; - let hir_id = self.hir().local_def_id_to_hir_id(hir_id); - // When `body_owner` is an `impl` or `trait` item, look in its associated types for - // `expected` and point at it. - let parent_id = self.hir().get_parent_item(hir_id); - let item = self.hir().find_by_def_id(parent_id.def_id); - debug!("expected_projection parent item {:?}", item); - match item { - Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => { - // FIXME: account for `#![feature(specialization)]` - for item in &items[..] { - match item.kind { - hir::AssocItemKind::Type => { - // FIXME: account for returning some type in a trait fn impl that has - // an assoc type as a return type (#72076). - if let hir::Defaultness::Default { has_value: true } = - self.impl_defaultness(item.id.owner_id) - { - if self.type_of(item.id.owner_id) == found { - diag.span_label( - item.span, - "associated type defaults can't be assumed inside the \ - trait defining them", - ); - return true; - } - } - } - _ => {} - } - } - } - Some(hir::Node::Item(hir::Item { - kind: hir::ItemKind::Impl(hir::Impl { items, .. }), - .. - })) => { - for item in &items[..] { - if let hir::AssocItemKind::Type = item.kind { - if self.type_of(item.id.owner_id) == found { - diag.span_label(item.span, "expected this associated type"); - return true; - } - } - } - } - _ => {} - } - false - } - - /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref` - /// requirement, provide a structured suggestion to constrain it to a given type `ty`. - /// - /// `is_bound_surely_present` indicates whether we know the bound we're looking for is - /// inside `bounds`. If that's the case then we can consider `bounds` containing only one - /// trait bound as the one we're looking for. This can help in cases where the associated - /// type is defined on a supertrait of the one present in the bounds. - fn constrain_generic_bound_associated_type_structured_suggestion( - self, - diag: &mut Diagnostic, - trait_ref: &ty::TraitRef<'tcx>, - bounds: hir::GenericBounds<'_>, - assoc: &ty::AssocItem, - assoc_substs: &[ty::GenericArg<'tcx>], - ty: Ty<'tcx>, - msg: &str, - is_bound_surely_present: bool, - ) -> bool { - // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting. - - let trait_bounds = bounds.iter().filter_map(|bound| match bound { - hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr), - _ => None, - }); - - let matching_trait_bounds = trait_bounds - .clone() - .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id)) - .collect::>(); - - let span = match &matching_trait_bounds[..] { - &[ptr] => ptr.span, - &[] if is_bound_surely_present => match &trait_bounds.collect::>()[..] { - &[ptr] => ptr.span, - _ => return false, - }, - _ => return false, - }; - - self.constrain_associated_type_structured_suggestion( - diag, - span, - assoc, - assoc_substs, - ty, - msg, - ) - } - - /// Given a span corresponding to a bound, provide a structured suggestion to set an - /// associated type to a given type `ty`. - fn constrain_associated_type_structured_suggestion( - self, - diag: &mut Diagnostic, - span: Span, - assoc: &ty::AssocItem, - assoc_substs: &[ty::GenericArg<'tcx>], - ty: Ty<'tcx>, - msg: &str, - ) -> bool { - if let Ok(has_params) = - self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>')) - { - let (span, sugg) = if has_params { - let pos = span.hi() - BytePos(1); - let span = Span::new(pos, pos, span.ctxt(), span.parent()); - (span, format!(", {} = {}", assoc.ident(self), ty)) - } else { - let item_args = self.format_generic_args(assoc_substs); - (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(self), item_args, ty)) - }; - diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect); - return true; - } - false - } - pub fn short_ty_string(self, ty: Ty<'tcx>) -> (String, Option) { let width = self.sess.diagnostic_width(); let length_limit = width.saturating_sub(30); @@ -1047,11 +427,4 @@ fn foo(&self) -> Self::T { String::new() } Err(_) => (regular, None), } } - - fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String { - FmtPrinter::new(self, hir::def::Namespace::TypeNS) - .path_generic_args(Ok, args) - .expect("could not write to `String`.") - .into_buffer() - } } From 943000fdcf9eac6c77b44923f551409aa06a46b5 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Wed, 25 Jan 2023 20:11:05 +0100 Subject: [PATCH 361/500] Use `can_eq` to compare types for default assoc type error This works correctly with inference variables. --- .../src/infer/error_reporting/mod.rs | 1 - .../infer/error_reporting/note_and_explain.rs | 11 +++++++++-- compiler/rustc_middle/src/ty/query.rs | 8 ++++++++ compiler/rustc_middle/src/ty/util.rs | 11 ----------- .../defaults-in-other-trait-items.rs | 14 ++++++++++++++ .../defaults-in-other-trait-items.stderr | 17 ++++++++++++++++- tests/ui/associated-types/issue-26681.stderr | 4 ++-- 7 files changed, 49 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index faba723acda8d..d19a0007f0880 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -1850,7 +1850,6 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { self.note_and_explain_type_err(diag, terr, cause, span, cause.body_id.to_def_id()); - if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind() && let Some(def_id) = def_id.as_local() diff --git a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs index 6e781a041e013..425cde3302db8 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs @@ -515,7 +515,11 @@ fn foo(&tcx) -> Self::T { String::new() } // `expected` and point at it. let parent_id = tcx.hir().get_parent_item(hir_id); let item = tcx.hir().find_by_def_id(parent_id.def_id); + debug!("expected_projection parent item {:?}", item); + + let param_env = tcx.param_env(body_owner_def_id); + match item { Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => { // FIXME: account for `#![feature(specialization)]` @@ -527,7 +531,8 @@ fn foo(&tcx) -> Self::T { String::new() } if let hir::Defaultness::Default { has_value: true } = tcx.impl_defaultness(item.id.owner_id) { - if tcx.type_of(item.id.owner_id) == found { + let assoc_ty = tcx.bound_type_of(item.id.owner_id).subst_identity(); + if self.infcx.can_eq(param_env, assoc_ty, found).is_ok() { diag.span_label( item.span, "associated type defaults can't be assumed inside the \ @@ -547,7 +552,9 @@ fn foo(&tcx) -> Self::T { String::new() } })) => { for item in &items[..] { if let hir::AssocItemKind::Type = item.kind { - if tcx.type_of(item.id.owner_id) == found { + let assoc_ty = tcx.bound_type_of(item.id.owner_id).subst_identity(); + + if self.infcx.can_eq(param_env, assoc_ty, found).is_ok() { diag.span_label(item.span, "expected this associated type"); return true; } diff --git a/compiler/rustc_middle/src/ty/query.rs b/compiler/rustc_middle/src/ty/query.rs index 9d4ee22a7273b..28b9bdf566018 100644 --- a/compiler/rustc_middle/src/ty/query.rs +++ b/compiler/rustc_middle/src/ty/query.rs @@ -441,6 +441,10 @@ impl<'tcx> TyCtxt<'tcx> { self.opt_def_kind(def_id) .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", def_id)) } + + pub fn bound_type_of(self, def_id: impl IntoQueryParam) -> ty::EarlyBinder> { + ty::EarlyBinder(self.type_of(def_id)) + } } impl<'tcx> TyCtxtAt<'tcx> { @@ -449,4 +453,8 @@ impl<'tcx> TyCtxtAt<'tcx> { self.opt_def_kind(def_id) .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", def_id)) } + + pub fn bound_type_of(self, def_id: impl IntoQueryParam) -> ty::EarlyBinder> { + ty::EarlyBinder(self.type_of(def_id)) + } } diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 60076c8cb5f99..95abbb5038017 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -3,7 +3,6 @@ use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; use crate::mir; use crate::ty::layout::IntegerExt; -use crate::ty::query::TyCtxtAt; use crate::ty::{ self, DefIdTree, FallibleTypeFolder, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable, @@ -637,10 +636,6 @@ impl<'tcx> TyCtxt<'tcx> { if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) } } - pub fn bound_type_of(self, def_id: DefId) -> ty::EarlyBinder> { - ty::EarlyBinder(self.type_of(def_id)) - } - pub fn bound_return_position_impl_trait_in_trait_tys( self, def_id: DefId, @@ -738,12 +733,6 @@ impl<'tcx> TyCtxt<'tcx> { } } -impl<'tcx> TyCtxtAt<'tcx> { - pub fn bound_type_of(self, def_id: DefId) -> ty::EarlyBinder> { - ty::EarlyBinder(self.type_of(def_id)) - } -} - struct OpaqueTypeExpander<'tcx> { // Contains the DefIds of the opaque types that are currently being // expanded. When we expand an opaque type we insert the DefId of diff --git a/tests/ui/associated-types/defaults-in-other-trait-items.rs b/tests/ui/associated-types/defaults-in-other-trait-items.rs index 505751969b623..f263809552fdf 100644 --- a/tests/ui/associated-types/defaults-in-other-trait-items.rs +++ b/tests/ui/associated-types/defaults-in-other-trait-items.rs @@ -44,4 +44,18 @@ impl AssocConst for () { const C: Self::Ty = 0u8; } +pub trait Trait { + type Res = isize; //~ NOTE associated type defaults can't be assumed inside the trait defining them + + fn infer_me_correctly() -> Self::Res { + //~^ NOTE expected `::Res` because of return type + + // {integer} == isize + 2 + //~^ ERROR mismatched types + //~| NOTE expected associated type, found integer + //~| NOTE expected associated type `::Res` + } +} + fn main() {} diff --git a/tests/ui/associated-types/defaults-in-other-trait-items.stderr b/tests/ui/associated-types/defaults-in-other-trait-items.stderr index 71d421926e702..bdcfadd3955d2 100644 --- a/tests/ui/associated-types/defaults-in-other-trait-items.stderr +++ b/tests/ui/associated-types/defaults-in-other-trait-items.stderr @@ -24,6 +24,21 @@ LL | const C: Self::Ty = 0u8; = note: expected associated type `::Ty` found type `u8` -error: aborting due to 2 previous errors +error[E0308]: mismatched types + --> $DIR/defaults-in-other-trait-items.rs:54:9 + | +LL | type Res = isize; + | ----------------- associated type defaults can't be assumed inside the trait defining them +LL | +LL | fn infer_me_correctly() -> Self::Res { + | --------- expected `::Res` because of return type +... +LL | 2 + | ^ expected associated type, found integer + | + = note: expected associated type `::Res` + found type `{integer}` + +error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/associated-types/issue-26681.stderr b/tests/ui/associated-types/issue-26681.stderr index 74411008c9dda..977620d9052f2 100644 --- a/tests/ui/associated-types/issue-26681.stderr +++ b/tests/ui/associated-types/issue-26681.stderr @@ -1,13 +1,13 @@ error[E0308]: mismatched types --> $DIR/issue-26681.rs:17:39 | +LL | type Fv: Foo = u8; + | ------------------ associated type defaults can't be assumed inside the trait defining them LL | const C: ::Bar = 6665; | ^^^^ expected associated type, found integer | = note: expected associated type `<::Fv as Foo>::Bar` found type `{integer}` - = help: consider constraining the associated type `<::Fv as Foo>::Bar` to `{integer}` - = note: for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html error: aborting due to previous error From 50f29d48bd5fb17b7b1669b842aba89bbe9bef6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Thu, 10 Nov 2022 19:19:39 +0100 Subject: [PATCH 362/500] Stabilize the const_socketaddr feature --- library/std/src/lib.rs | 1 - library/std/src/net/socket_addr.rs | 26 +++++++++++++------------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 99cc018631048..762f7a7c9a1a0 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -358,7 +358,6 @@ #![feature(const_ip)] #![feature(const_ipv4)] #![feature(const_ipv6)] -#![feature(const_socketaddr)] #![feature(thread_local_internals)] // #![default_lib_allocator] diff --git a/library/std/src/net/socket_addr.rs b/library/std/src/net/socket_addr.rs index 33b0dfa03e0ed..1264bae809b26 100644 --- a/library/std/src/net/socket_addr.rs +++ b/library/std/src/net/socket_addr.rs @@ -133,7 +133,7 @@ impl SocketAddr { /// ``` #[stable(feature = "ip_addr", since = "1.7.0")] #[must_use] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn new(ip: IpAddr, port: u16) -> SocketAddr { match ip { IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)), @@ -153,7 +153,7 @@ impl SocketAddr { /// ``` #[must_use] #[stable(feature = "ip_addr", since = "1.7.0")] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn ip(&self) -> IpAddr { match *self { SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()), @@ -194,7 +194,7 @@ impl SocketAddr { /// ``` #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn port(&self) -> u16 { match *self { SocketAddr::V4(ref a) => a.port(), @@ -238,7 +238,7 @@ impl SocketAddr { /// ``` #[must_use] #[stable(feature = "sockaddr_checker", since = "1.16.0")] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn is_ipv4(&self) -> bool { matches!(*self, SocketAddr::V4(_)) } @@ -260,7 +260,7 @@ impl SocketAddr { /// ``` #[must_use] #[stable(feature = "sockaddr_checker", since = "1.16.0")] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn is_ipv6(&self) -> bool { matches!(*self, SocketAddr::V6(_)) } @@ -280,7 +280,7 @@ impl SocketAddrV4 { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 { SocketAddrV4 { ip, port } } @@ -297,7 +297,7 @@ impl SocketAddrV4 { /// ``` #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn ip(&self) -> &Ipv4Addr { &self.ip } @@ -330,7 +330,7 @@ impl SocketAddrV4 { /// ``` #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn port(&self) -> u16 { self.port } @@ -371,7 +371,7 @@ impl SocketAddrV6 { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 { SocketAddrV6 { ip, port, flowinfo, scope_id } } @@ -388,7 +388,7 @@ impl SocketAddrV6 { /// ``` #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn ip(&self) -> &Ipv6Addr { &self.ip } @@ -421,7 +421,7 @@ impl SocketAddrV6 { /// ``` #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn port(&self) -> u16 { self.port } @@ -464,7 +464,7 @@ impl SocketAddrV6 { /// ``` #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn flowinfo(&self) -> u32 { self.flowinfo } @@ -504,7 +504,7 @@ impl SocketAddrV6 { /// ``` #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] + #[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")] pub const fn scope_id(&self) -> u32 { self.scope_id } From b3f0085376fbd0d1d798eefac1fa2bfdc0f3cdbe Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 24 Jan 2023 18:48:15 +0000 Subject: [PATCH 363/500] Implement ObjectSafe and WF in the new solver --- .../rustc_trait_selection/src/solve/mod.rs | 41 +++++++++++++++++-- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_trait_selection/src/solve/mod.rs b/compiler/rustc_trait_selection/src/solve/mod.rs index 70f094014453e..a920f04621db5 100644 --- a/compiler/rustc_trait_selection/src/solve/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/mod.rs @@ -20,6 +20,7 @@ use std::mem; use rustc_hir::def_id::DefId; +use rustc_hir::CRATE_HIR_ID; use rustc_infer::infer::canonical::{Canonical, CanonicalVarKind, CanonicalVarValues}; use rustc_infer::infer::canonical::{OriginalQueryValues, QueryRegionConstraints, QueryResponse}; use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt}; @@ -277,12 +278,15 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { param_env, predicate: (def_id, substs, kind), }), + ty::PredicateKind::ObjectSafe(trait_def_id) => { + self.compute_object_safe_goal(trait_def_id) + } + ty::PredicateKind::WellFormed(arg) => { + self.compute_well_formed_goal(Goal { param_env, predicate: arg }) + } ty::PredicateKind::Ambiguous => self.make_canonical_response(Certainty::AMBIGUOUS), // FIXME: implement these predicates :) - ty::PredicateKind::WellFormed(_) - | ty::PredicateKind::ObjectSafe(_) - | ty::PredicateKind::ConstEvaluatable(_) - | ty::PredicateKind::ConstEquate(_, _) => { + ty::PredicateKind::ConstEvaluatable(_) | ty::PredicateKind::ConstEquate(_, _) => { self.make_canonical_response(Certainty::Yes) } ty::PredicateKind::TypeWellFormedFromEnv(..) => { @@ -362,6 +366,35 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { Err(NoSolution) } } + + fn compute_object_safe_goal(&mut self, trait_def_id: DefId) -> QueryResult<'tcx> { + if self.tcx().is_object_safe(trait_def_id) { + self.make_canonical_response(Certainty::Yes) + } else { + Err(NoSolution) + } + } + + fn compute_well_formed_goal( + &mut self, + goal: Goal<'tcx, ty::GenericArg<'tcx>>, + ) -> QueryResult<'tcx> { + self.infcx.probe(|_| { + match crate::traits::wf::obligations( + self.infcx, + goal.param_env, + CRATE_HIR_ID, // FIXME body id + 0, + goal.predicate, + DUMMY_SP, + ) { + Some(obligations) => self.evaluate_all_and_make_canonical_response( + obligations.into_iter().map(|o| o.into()).collect(), + ), + None => self.make_canonical_response(Certainty::AMBIGUOUS), + } + }) + } } impl<'tcx> EvalCtxt<'_, 'tcx> { From 02b80d2f9c2034b6dcaa1f83bf8c6e1eca4d8388 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 24 Jan 2023 19:10:56 +0000 Subject: [PATCH 364/500] Don't normalize obligations in WF goal for the new solver --- Cargo.lock | 14 ++++---- .../rustc_trait_selection/src/solve/mod.rs | 6 +--- .../rustc_trait_selection/src/traits/wf.rs | 32 +++++++++++++++++-- 3 files changed, 38 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3175e98e81e53..6298d1e366bc6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -351,7 +351,7 @@ dependencies = [ "cargo-test-macro", "cargo-test-support", "cargo-util", - "clap 4.1.3", + "clap 4.1.4", "crates-io", "curl", "curl-sys", @@ -655,9 +655,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.1.3" +version = "4.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8d93d855ce6a0aa87b8473ef9169482f40abaa2e9e0993024c35c902cbd5920" +checksum = "f13b9c79b5d1dd500d20ef541215a6423c75829ef43117e1b4d17fd8af0b5d76" dependencies = [ "bitflags", "clap_derive 4.1.0", @@ -675,7 +675,7 @@ version = "4.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10861370d2ba66b0f5989f83ebf35db6421713fd92351790e7fdd6c36774c56b" dependencies = [ - "clap 4.1.3", + "clap 4.1.4", ] [[package]] @@ -2294,7 +2294,7 @@ name = "jsondoclint" version = "0.1.0" dependencies = [ "anyhow", - "clap 4.1.3", + "clap 4.1.4", "fs-err", "rustdoc-json-types", "serde", @@ -2557,7 +2557,7 @@ dependencies = [ "ammonia", "anyhow", "chrono", - "clap 4.1.3", + "clap 4.1.4", "clap_complete", "elasticlunr-rs", "env_logger 0.10.0", @@ -3528,7 +3528,7 @@ dependencies = [ name = "rustbook" version = "0.1.0" dependencies = [ - "clap 4.1.3", + "clap 4.1.4", "env_logger 0.7.1", "mdbook", ] diff --git a/compiler/rustc_trait_selection/src/solve/mod.rs b/compiler/rustc_trait_selection/src/solve/mod.rs index a920f04621db5..f44648c95d742 100644 --- a/compiler/rustc_trait_selection/src/solve/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/mod.rs @@ -20,7 +20,6 @@ use std::mem; use rustc_hir::def_id::DefId; -use rustc_hir::CRATE_HIR_ID; use rustc_infer::infer::canonical::{Canonical, CanonicalVarKind, CanonicalVarValues}; use rustc_infer::infer::canonical::{OriginalQueryValues, QueryRegionConstraints, QueryResponse}; use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt}; @@ -380,13 +379,10 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { goal: Goal<'tcx, ty::GenericArg<'tcx>>, ) -> QueryResult<'tcx> { self.infcx.probe(|_| { - match crate::traits::wf::obligations( + match crate::traits::wf::unnormalized_obligations( self.infcx, goal.param_env, - CRATE_HIR_ID, // FIXME body id - 0, goal.predicate, - DUMMY_SP, ) { Some(obligations) => self.evaluate_all_and_make_canonical_response( obligations.into_iter().map(|o| o.into()).collect(), diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index d9556848099f1..767e31ddf781a 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -4,8 +4,8 @@ use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable}; -use rustc_span::def_id::{DefId, LocalDefId}; -use rustc_span::Span; +use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; +use rustc_span::{Span, DUMMY_SP}; use std::iter; /// Returns the set of obligations needed to make `arg` well-formed. @@ -75,6 +75,34 @@ pub fn obligations<'tcx>( Some(result) } +/// Compute the predicates that are required for a type to be well-formed. +/// +/// This is only intended to be used in the new solver, since it does not +/// take into account recursion depth or proper error-reporting spans. +pub fn unnormalized_obligations<'tcx>( + infcx: &InferCtxt<'tcx>, + param_env: ty::ParamEnv<'tcx>, + arg: GenericArg<'tcx>, +) -> Option>> { + if let ty::GenericArgKind::Lifetime(..) = arg.unpack() { + return Some(vec![]); + } + + debug_assert_eq!(arg, infcx.resolve_vars_if_possible(arg)); + + let mut wf = WfPredicates { + tcx: infcx.tcx, + param_env, + body_id: CRATE_DEF_ID, + span: DUMMY_SP, + out: vec![], + recursion_depth: 0, + item: None, + }; + wf.compute(arg); + Some(wf.out) +} + /// Returns the obligations that make this trait reference /// well-formed. For example, if there is a trait `Set` defined like /// `trait Set`, then the trait reference `Foo: Set` is WF From da538c1fa8f568260c8dc29ffae063be85e3aff1 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Wed, 25 Jan 2023 19:58:22 -0600 Subject: [PATCH 365/500] add style team triagebot config --- triagebot.toml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/triagebot.toml b/triagebot.toml index 16a3132151374..79958729fc521 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -456,6 +456,9 @@ These commits modify **compiler targets**. (See the [Target Tier Policy](https://doc.rust-lang.org/nightly/rustc/target-tier-policy.html).) """ +[mentions."src/doc/style-guide"] +cc = ["@rust-lang/style"] + [assign] warn_non_default_branch = true contributing_url = "https://rustc-dev-guide.rust-lang.org/contributing.html" @@ -560,6 +563,12 @@ ast_lowering = [ fallback = [ "@Mark-Simulacrum" ] +style-team = [ + "@calebcartwright", + "@compiler-errors", + "@joshtriplett", + "@yaahc", +] [assign.owners] "/.github/workflows" = ["infra-ci"] @@ -604,6 +613,7 @@ fallback = [ "/src/doc/rust-by-example" = ["@ehuss"] "/src/doc/rustc-dev-guide" = ["@ehuss"] "/src/doc/rustdoc" = ["rustdoc"] +"/src/doc/style-guide" = ["style-team"] "/src/etc" = ["@Mark-Simulacrum"] "/src/librustdoc" = ["rustdoc"] "/src/llvm-project" = ["@cuviper"] From c4d00d710c86aa062f2e08fc90a14345f55a8b4b Mon Sep 17 00:00:00 2001 From: yukang Date: Thu, 26 Jan 2023 10:52:57 +0800 Subject: [PATCH 366/500] add testcase for #104012 --- tests/ui/parser/deli-ident-issue-1.rs | 25 +++++++++++++ tests/ui/parser/deli-ident-issue-1.stderr | 37 +++++++++++++++++++ tests/ui/parser/deli-ident-issue-2.rs | 7 ++++ tests/ui/parser/deli-ident-issue-2.stderr | 21 +++++++++++ .../ui/parser/issue-68987-unmatch-issue-1.rs | 12 ++++++ .../parser/issue-68987-unmatch-issue-1.stderr | 11 ++++++ .../ui/parser/issue-68987-unmatch-issue-2.rs | 14 +++++++ .../parser/issue-68987-unmatch-issue-2.stderr | 21 +++++++++++ .../ui/parser/issue-68987-unmatch-issue-3.rs | 8 ++++ .../parser/issue-68987-unmatch-issue-3.stderr | 21 +++++++++++ tests/ui/parser/issue-68987-unmatch-issue.rs | 12 ++++++ .../parser/issue-68987-unmatch-issue.stderr | 11 ++++++ tests/ui/parser/issues/issue-69259.rs | 3 ++ tests/ui/parser/issues/issue-69259.stderr | 13 +++++++ 14 files changed, 216 insertions(+) create mode 100644 tests/ui/parser/deli-ident-issue-1.rs create mode 100644 tests/ui/parser/deli-ident-issue-1.stderr create mode 100644 tests/ui/parser/deli-ident-issue-2.rs create mode 100644 tests/ui/parser/deli-ident-issue-2.stderr create mode 100644 tests/ui/parser/issue-68987-unmatch-issue-1.rs create mode 100644 tests/ui/parser/issue-68987-unmatch-issue-1.stderr create mode 100644 tests/ui/parser/issue-68987-unmatch-issue-2.rs create mode 100644 tests/ui/parser/issue-68987-unmatch-issue-2.stderr create mode 100644 tests/ui/parser/issue-68987-unmatch-issue-3.rs create mode 100644 tests/ui/parser/issue-68987-unmatch-issue-3.stderr create mode 100644 tests/ui/parser/issue-68987-unmatch-issue.rs create mode 100644 tests/ui/parser/issue-68987-unmatch-issue.stderr create mode 100644 tests/ui/parser/issues/issue-69259.rs create mode 100644 tests/ui/parser/issues/issue-69259.stderr diff --git a/tests/ui/parser/deli-ident-issue-1.rs b/tests/ui/parser/deli-ident-issue-1.rs new file mode 100644 index 0000000000000..a8cbf8640f7a3 --- /dev/null +++ b/tests/ui/parser/deli-ident-issue-1.rs @@ -0,0 +1,25 @@ +// error-pattern: this file contains an unclosed delimiter +#![feature(let_chains)] +trait Demo {} + +impl dyn Demo { + pub fn report(&self) -> u32 { + let sum = |a: u32, + b: u32, + c: u32| { + a + b + c + }; + sum(1, 2, 3) + } + + fn check(&self, val: Option, num: Option) { + if let Some(b) = val + && let Some(c) = num { + && b == c { + //~^ ERROR expected struct + //~| ERROR mismatched types + } + } +} + +fn main() { } //~ ERROR this file contains an unclosed delimiter diff --git a/tests/ui/parser/deli-ident-issue-1.stderr b/tests/ui/parser/deli-ident-issue-1.stderr new file mode 100644 index 0000000000000..784f598f9d05c --- /dev/null +++ b/tests/ui/parser/deli-ident-issue-1.stderr @@ -0,0 +1,37 @@ +error: this file contains an unclosed delimiter + --> $DIR/deli-ident-issue-1.rs:25:66 + | +LL | impl dyn Demo { + | - unclosed delimiter +... +LL | c: u32| { + | - this delimiter might not be properly closed... +LL | a + b + c +LL | }; + | - ...as it matches this but it has different indentation +... +LL | fn main() { } + | ^ + +error[E0574]: expected struct, variant or union type, found local variable `c` + --> $DIR/deli-ident-issue-1.rs:18:17 + | +LL | && b == c { + | ^ not a struct, variant or union type + +error[E0308]: mismatched types + --> $DIR/deli-ident-issue-1.rs:18:9 + | +LL | fn check(&self, val: Option, num: Option) { + | - expected `()` because of default return type +... +LL | / && b == c { +LL | | +LL | | +LL | | } + | |_________^ expected `()`, found `bool` + +error: aborting due to 3 previous errors + +Some errors have detailed explanations: E0308, E0574. +For more information about an error, try `rustc --explain E0308`. diff --git a/tests/ui/parser/deli-ident-issue-2.rs b/tests/ui/parser/deli-ident-issue-2.rs new file mode 100644 index 0000000000000..5394760df7026 --- /dev/null +++ b/tests/ui/parser/deli-ident-issue-2.rs @@ -0,0 +1,7 @@ +fn main() { + if 1 < 2 { + let _a = vec!]; //~ ERROR mismatched closing delimiter + } +} //~ ERROR unexpected closing delimiter + +fn main() {} diff --git a/tests/ui/parser/deli-ident-issue-2.stderr b/tests/ui/parser/deli-ident-issue-2.stderr new file mode 100644 index 0000000000000..782dac8f32d35 --- /dev/null +++ b/tests/ui/parser/deli-ident-issue-2.stderr @@ -0,0 +1,21 @@ +error: unexpected closing delimiter: `}` + --> $DIR/deli-ident-issue-2.rs:5:1 + | +LL | fn main() { + | - this opening brace... +... +LL | } + | - ...matches this closing brace +LL | } + | ^ unexpected closing delimiter + +error: mismatched closing delimiter: `]` + --> $DIR/deli-ident-issue-2.rs:2:14 + | +LL | if 1 < 2 { + | ^ unclosed delimiter +LL | let _a = vec!]; + | ^ mismatched closing delimiter + +error: aborting due to 2 previous errors + diff --git a/tests/ui/parser/issue-68987-unmatch-issue-1.rs b/tests/ui/parser/issue-68987-unmatch-issue-1.rs new file mode 100644 index 0000000000000..30e7ef467368a --- /dev/null +++ b/tests/ui/parser/issue-68987-unmatch-issue-1.rs @@ -0,0 +1,12 @@ +// This file has unexpected closing delimiter, + +fn func(o: Option) { + match o { + Some(_x) => {} // Extra '}' + let _ = if true {}; + } + None => {} + } +} //~ ERROR unexpected closing delimiter + +fn main() {} diff --git a/tests/ui/parser/issue-68987-unmatch-issue-1.stderr b/tests/ui/parser/issue-68987-unmatch-issue-1.stderr new file mode 100644 index 0000000000000..b5c1887f76f08 --- /dev/null +++ b/tests/ui/parser/issue-68987-unmatch-issue-1.stderr @@ -0,0 +1,11 @@ +error: unexpected closing delimiter: `}` + --> $DIR/issue-68987-unmatch-issue-1.rs:10:1 + | +LL | None => {} + | -- block is empty, you might have not meant to close it +LL | } +LL | } + | ^ unexpected closing delimiter + +error: aborting due to previous error + diff --git a/tests/ui/parser/issue-68987-unmatch-issue-2.rs b/tests/ui/parser/issue-68987-unmatch-issue-2.rs new file mode 100644 index 0000000000000..89aaa68ba4095 --- /dev/null +++ b/tests/ui/parser/issue-68987-unmatch-issue-2.rs @@ -0,0 +1,14 @@ +// FIXME: this case need more work to fix +// currently the TokenTree matching ')' with '{', which is not user friendly for diagnostics +async fn obstest() -> Result<> { + let obs_connect = || -> Result<(), MyError) { //~ ERROR mismatched closing delimiter + async { + } + } + + if let Ok(version, scene_list) = obs_connect() { + + } else { + + } +} //~ ERROR unexpected closing delimiter diff --git a/tests/ui/parser/issue-68987-unmatch-issue-2.stderr b/tests/ui/parser/issue-68987-unmatch-issue-2.stderr new file mode 100644 index 0000000000000..253f12d44b83f --- /dev/null +++ b/tests/ui/parser/issue-68987-unmatch-issue-2.stderr @@ -0,0 +1,21 @@ +error: unexpected closing delimiter: `}` + --> $DIR/issue-68987-unmatch-issue-2.rs:14:1 + | +LL | } else { + | - this opening brace... +LL | +LL | } + | - ...matches this closing brace +LL | } + | ^ unexpected closing delimiter + +error: mismatched closing delimiter: `)` + --> $DIR/issue-68987-unmatch-issue-2.rs:3:32 + | +LL | async fn obstest() -> Result<> { + | ^ unclosed delimiter +LL | let obs_connect = || -> Result<(), MyError) { + | ^ mismatched closing delimiter + +error: aborting due to 2 previous errors + diff --git a/tests/ui/parser/issue-68987-unmatch-issue-3.rs b/tests/ui/parser/issue-68987-unmatch-issue-3.rs new file mode 100644 index 0000000000000..e98df8d7c3c4e --- /dev/null +++ b/tests/ui/parser/issue-68987-unmatch-issue-3.rs @@ -0,0 +1,8 @@ +// the `{` is closed with `)`, there is a missing `(` +fn f(i: u32, j: u32) { + let res = String::new(); + let mut cnt = i; + while cnt < j { + write!&mut res, " "); //~ ERROR mismatched closing delimiter + } +} //~ ERROR unexpected closing delimiter diff --git a/tests/ui/parser/issue-68987-unmatch-issue-3.stderr b/tests/ui/parser/issue-68987-unmatch-issue-3.stderr new file mode 100644 index 0000000000000..258a692c8557b --- /dev/null +++ b/tests/ui/parser/issue-68987-unmatch-issue-3.stderr @@ -0,0 +1,21 @@ +error: unexpected closing delimiter: `}` + --> $DIR/issue-68987-unmatch-issue-3.rs:8:1 + | +LL | fn f(i: u32, j: u32) { + | - this opening brace... +... +LL | } + | - ...matches this closing brace +LL | } + | ^ unexpected closing delimiter + +error: mismatched closing delimiter: `)` + --> $DIR/issue-68987-unmatch-issue-3.rs:5:19 + | +LL | while cnt < j { + | ^ unclosed delimiter +LL | write!&mut res, " "); + | ^ mismatched closing delimiter + +error: aborting due to 2 previous errors + diff --git a/tests/ui/parser/issue-68987-unmatch-issue.rs b/tests/ui/parser/issue-68987-unmatch-issue.rs new file mode 100644 index 0000000000000..5a3620bf24bd4 --- /dev/null +++ b/tests/ui/parser/issue-68987-unmatch-issue.rs @@ -0,0 +1,12 @@ +// This file has unexpected closing delimiter, + +fn func(o: Option) { + match o { + Some(_x) => // Missing '{' + let _ = if true {}; + } + None => {} + } +} //~ ERROR unexpected closing delimiter + +fn main() {} diff --git a/tests/ui/parser/issue-68987-unmatch-issue.stderr b/tests/ui/parser/issue-68987-unmatch-issue.stderr new file mode 100644 index 0000000000000..00e9c9a5ccee0 --- /dev/null +++ b/tests/ui/parser/issue-68987-unmatch-issue.stderr @@ -0,0 +1,11 @@ +error: unexpected closing delimiter: `}` + --> $DIR/issue-68987-unmatch-issue.rs:10:1 + | +LL | None => {} + | -- block is empty, you might have not meant to close it +LL | } +LL | } + | ^ unexpected closing delimiter + +error: aborting due to previous error + diff --git a/tests/ui/parser/issues/issue-69259.rs b/tests/ui/parser/issues/issue-69259.rs new file mode 100644 index 0000000000000..01fc2c0854647 --- /dev/null +++ b/tests/ui/parser/issues/issue-69259.rs @@ -0,0 +1,3 @@ +fn main() {} + +fn f) {} //~ ERROR unexpected closing delimiter diff --git a/tests/ui/parser/issues/issue-69259.stderr b/tests/ui/parser/issues/issue-69259.stderr new file mode 100644 index 0000000000000..f4cb391cb1ff2 --- /dev/null +++ b/tests/ui/parser/issues/issue-69259.stderr @@ -0,0 +1,13 @@ +error: unexpected closing delimiter: `)` + --> $DIR/issue-69259.rs:3:5 + | +LL | fn main() {} + | -- ...matches this closing brace + | | + | this opening brace... +LL | +LL | fn f) {} + | ^ unexpected closing delimiter + +error: aborting due to previous error + From 8434b43a7f9886a0b0e5f36b115d6c26dde4953d Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 24 Jan 2023 23:57:26 +0000 Subject: [PATCH 367/500] Report the right fulfillment errors --- .../src/solve/fulfill.rs | 67 ++++++++++++++++--- 1 file changed, 57 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index d59fa71406c31..278024b22760a 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -1,13 +1,14 @@ use std::mem; -use super::{Certainty, InferCtxtEvalExt}; -use rustc_infer::{ - infer::InferCtxt, - traits::{ - query::NoSolution, FulfillmentError, FulfillmentErrorCode, PredicateObligation, - SelectionError, TraitEngine, - }, +use rustc_infer::infer::InferCtxt; +use rustc_infer::traits::{ + query::NoSolution, FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes, + PredicateObligation, SelectionError, TraitEngine, }; +use rustc_middle::ty; +use rustc_middle::ty::error::{ExpectedFound, TypeError}; + +use super::{Certainty, InferCtxtEvalExt}; /// A trait engine using the new trait solver. /// @@ -70,9 +71,55 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> { Err(NoSolution) => { errors.push(FulfillmentError { obligation: obligation.clone(), - code: FulfillmentErrorCode::CodeSelectionError( - SelectionError::Unimplemented, - ), + code: match goal.predicate.kind().skip_binder() { + ty::PredicateKind::Clause(ty::Clause::Projection(_)) => { + FulfillmentErrorCode::CodeProjectionError( + // FIXME: This could be a `Sorts` if the term is a type + MismatchedProjectionTypes { err: TypeError::Mismatch }, + ) + } + ty::PredicateKind::Subtype(pred) => { + let (a, b) = infcx.replace_bound_vars_with_placeholders( + goal.predicate.kind().rebind((pred.a, pred.b)), + ); + let expected_found = ExpectedFound::new(true, a, b); + FulfillmentErrorCode::CodeSubtypeError( + expected_found, + TypeError::Sorts(expected_found), + ) + } + ty::PredicateKind::Coerce(pred) => { + let (a, b) = infcx.replace_bound_vars_with_placeholders( + goal.predicate.kind().rebind((pred.a, pred.b)), + ); + let expected_found = ExpectedFound::new(false, a, b); + FulfillmentErrorCode::CodeSubtypeError( + expected_found, + TypeError::Sorts(expected_found), + ) + } + ty::PredicateKind::ConstEquate(a, b) => { + let (a, b) = infcx.replace_bound_vars_with_placeholders( + goal.predicate.kind().rebind((a, b)), + ); + let expected_found = ExpectedFound::new(true, a, b); + FulfillmentErrorCode::CodeConstEquateError( + expected_found, + TypeError::ConstMismatch(expected_found), + ) + } + ty::PredicateKind::Clause(_) + | ty::PredicateKind::WellFormed(_) + | ty::PredicateKind::ObjectSafe(_) + | ty::PredicateKind::ClosureKind(_, _, _) + | ty::PredicateKind::ConstEvaluatable(_) + | ty::PredicateKind::TypeWellFormedFromEnv(_) + | ty::PredicateKind::Ambiguous => { + FulfillmentErrorCode::CodeSelectionError( + SelectionError::Unimplemented, + ) + } + }, root_obligation: obligation, }); continue; From d600b94ebb5a418ba011797b85045975f18f90dd Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 24 Jan 2023 23:38:20 +0000 Subject: [PATCH 368/500] Implement Generator and Future --- .../src/solve/assembly.rs | 14 ++++ .../src/solve/project_goals.rs | 69 ++++++++++++++++++- .../src/solve/trait_goals.rs | 44 ++++++++++++ .../solve/trait_goals/structural_traits.rs | 1 + tests/ui/traits/new-solver/async.fail.stderr | 17 +++++ tests/ui/traits/new-solver/async.rs | 19 +++++ .../traits/new-solver/generator.fail.stderr | 64 +++++++++++++++++ tests/ui/traits/new-solver/generator.rs | 32 +++++++++ 8 files changed, 259 insertions(+), 1 deletion(-) create mode 100644 tests/ui/traits/new-solver/async.fail.stderr create mode 100644 tests/ui/traits/new-solver/async.rs create mode 100644 tests/ui/traits/new-solver/generator.fail.stderr create mode 100644 tests/ui/traits/new-solver/generator.rs diff --git a/compiler/rustc_trait_selection/src/solve/assembly.rs b/compiler/rustc_trait_selection/src/solve/assembly.rs index 0b642fcba2812..baff0f8630ee5 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly.rs @@ -138,6 +138,16 @@ pub(super) trait GoalKind<'tcx>: TypeFoldable<'tcx> + Copy + Eq { ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; + + fn consider_builtin_future_candidate( + ecx: &mut EvalCtxt<'_, 'tcx>, + goal: Goal<'tcx, Self>, + ) -> QueryResult<'tcx>; + + fn consider_builtin_generator_candidate( + ecx: &mut EvalCtxt<'_, 'tcx>, + goal: Goal<'tcx, Self>, + ) -> QueryResult<'tcx>; } impl<'tcx> EvalCtxt<'_, 'tcx> { @@ -266,6 +276,10 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { G::consider_builtin_tuple_candidate(self, goal) } else if lang_items.pointee_trait() == Some(trait_def_id) { G::consider_builtin_pointee_candidate(self, goal) + } else if lang_items.future_trait() == Some(trait_def_id) { + G::consider_builtin_future_candidate(self, goal) + } else if lang_items.gen_trait() == Some(trait_def_id) { + G::consider_builtin_generator_candidate(self, goal) } else { Err(NoSolution) }; diff --git a/compiler/rustc_trait_selection/src/solve/project_goals.rs b/compiler/rustc_trait_selection/src/solve/project_goals.rs index e5072d8e2d152..4a9b95af4a27c 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals.rs @@ -16,7 +16,7 @@ use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{ProjectionPredicate, TypeSuperVisitable, TypeVisitor}; use rustc_middle::ty::{ToPredicate, TypeVisitable}; -use rustc_span::DUMMY_SP; +use rustc_span::{sym, DUMMY_SP}; use std::iter; use std::ops::ControlFlow; @@ -482,6 +482,73 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { ecx.evaluate_all_and_make_canonical_response(nested_goals) }) } + + fn consider_builtin_future_candidate( + ecx: &mut EvalCtxt<'_, 'tcx>, + goal: Goal<'tcx, Self>, + ) -> QueryResult<'tcx> { + let self_ty = goal.predicate.self_ty(); + let ty::Generator(def_id, substs, _) = *self_ty.kind() else { + return Err(NoSolution); + }; + + // Generators are not futures unless they come from `async` desugaring + let tcx = ecx.tcx(); + if !tcx.generator_is_async(def_id) { + return Err(NoSolution); + } + + let term = substs.as_generator().return_ty().into(); + + Self::consider_assumption( + ecx, + goal, + ty::Binder::dummy(ty::ProjectionPredicate { + projection_ty: ecx.tcx().mk_alias_ty(goal.predicate.def_id(), [self_ty]), + term, + }) + .to_predicate(tcx), + ) + } + + fn consider_builtin_generator_candidate( + ecx: &mut EvalCtxt<'_, 'tcx>, + goal: Goal<'tcx, Self>, + ) -> QueryResult<'tcx> { + let self_ty = goal.predicate.self_ty(); + let ty::Generator(def_id, substs, _) = *self_ty.kind() else { + return Err(NoSolution); + }; + + // `async`-desugared generators do not implement the generator trait + let tcx = ecx.tcx(); + if tcx.generator_is_async(def_id) { + return Err(NoSolution); + } + + let generator = substs.as_generator(); + + let name = tcx.associated_item(goal.predicate.def_id()).name; + let term = if name == sym::Return { + generator.return_ty().into() + } else if name == sym::Yield { + generator.yield_ty().into() + } else { + bug!("unexpected associated item `<{self_ty} as Generator>::{name}`") + }; + + Self::consider_assumption( + ecx, + goal, + ty::Binder::dummy(ty::ProjectionPredicate { + projection_ty: ecx + .tcx() + .mk_alias_ty(goal.predicate.def_id(), [self_ty, generator.resume_ty()]), + term, + }) + .to_predicate(tcx), + ) + } } /// This behavior is also implemented in `rustc_ty_utils` and in the old `project` code. diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals.rs b/compiler/rustc_trait_selection/src/solve/trait_goals.rs index 67bd249566546..d74857dc4b480 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals.rs @@ -192,6 +192,50 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { ) -> QueryResult<'tcx> { ecx.make_canonical_response(Certainty::Yes) } + + fn consider_builtin_future_candidate( + ecx: &mut EvalCtxt<'_, 'tcx>, + goal: Goal<'tcx, Self>, + ) -> QueryResult<'tcx> { + let ty::Generator(def_id, _, _) = *goal.predicate.self_ty().kind() else { + return Err(NoSolution); + }; + + // Generators are not futures unless they come from `async` desugaring + let tcx = ecx.tcx(); + if !tcx.generator_is_async(def_id) { + return Err(NoSolution); + } + + // Async generator unconditionally implement `Future` + ecx.make_canonical_response(Certainty::Yes) + } + + fn consider_builtin_generator_candidate( + ecx: &mut EvalCtxt<'_, 'tcx>, + goal: Goal<'tcx, Self>, + ) -> QueryResult<'tcx> { + let self_ty = goal.predicate.self_ty(); + let ty::Generator(def_id, substs, _) = *self_ty.kind() else { + return Err(NoSolution); + }; + + // `async`-desugared generators do not implement the generator trait + let tcx = ecx.tcx(); + if tcx.generator_is_async(def_id) { + return Err(NoSolution); + } + + let generator = substs.as_generator(); + Self::consider_assumption( + ecx, + goal, + ty::Binder::dummy( + tcx.mk_trait_ref(goal.predicate.def_id(), [self_ty, generator.resume_ty()]), + ) + .to_predicate(tcx), + ) + } } impl<'tcx> EvalCtxt<'_, 'tcx> { diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs b/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs index a11cd13cb0856..162953180c75c 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs @@ -173,6 +173,7 @@ pub(super) fn instantiate_constituent_tys_for_copy_clone_trait<'tcx>( } } +// Returns a binder of the tupled inputs types and output type from a builtin callable type. pub(crate) fn extract_tupled_inputs_and_output_from_callable<'tcx>( tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>, diff --git a/tests/ui/traits/new-solver/async.fail.stderr b/tests/ui/traits/new-solver/async.fail.stderr new file mode 100644 index 0000000000000..b395c23ae0057 --- /dev/null +++ b/tests/ui/traits/new-solver/async.fail.stderr @@ -0,0 +1,17 @@ +error[E0271]: expected `[async block@$DIR/async.rs:12:17: 12:25]` to be a future that resolves to `i32`, but it resolves to `()` + --> $DIR/async.rs:12:17 + | +LL | needs_async(async {}); + | ----------- ^^^^^^^^ expected `i32`, found `()` + | | + | required by a bound introduced by this call + | +note: required by a bound in `needs_async` + --> $DIR/async.rs:8:31 + | +LL | fn needs_async(_: impl Future) {} + | ^^^^^^^^^^^^ required by this bound in `needs_async` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0271`. diff --git a/tests/ui/traits/new-solver/async.rs b/tests/ui/traits/new-solver/async.rs new file mode 100644 index 0000000000000..195cc35cad2ad --- /dev/null +++ b/tests/ui/traits/new-solver/async.rs @@ -0,0 +1,19 @@ +// compile-flags: -Ztrait-solver=next +// edition: 2021 +// revisions: pass fail +//[pass] check-pass + +use std::future::Future; + +fn needs_async(_: impl Future) {} + +#[cfg(fail)] +fn main() { + needs_async(async {}); + //[fail]~^ ERROR to be a future that resolves to `i32`, but it resolves to `()` +} + +#[cfg(pass)] +fn main() { + needs_async(async { 1i32 }); +} diff --git a/tests/ui/traits/new-solver/generator.fail.stderr b/tests/ui/traits/new-solver/generator.fail.stderr new file mode 100644 index 0000000000000..d94d41e3587b6 --- /dev/null +++ b/tests/ui/traits/new-solver/generator.fail.stderr @@ -0,0 +1,64 @@ +error[E0277]: the trait bound `[generator@$DIR/generator.rs:18:21: 18:23]: Generator` is not satisfied + --> $DIR/generator.rs:18:21 + | +LL | needs_generator(|| { + | _____---------------_^ + | | | + | | required by a bound introduced by this call +LL | | +LL | | +LL | | +LL | | yield (); +LL | | }); + | |_____^ the trait `Generator` is not implemented for `[generator@$DIR/generator.rs:18:21: 18:23]` + | +note: required by a bound in `needs_generator` + --> $DIR/generator.rs:14:28 + | +LL | fn needs_generator(_: impl Generator) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `needs_generator` + +error[E0271]: type mismatch resolving `<[generator@$DIR/generator.rs:18:21: 18:23] as Generator>::Yield == B` + --> $DIR/generator.rs:18:21 + | +LL | needs_generator(|| { + | _____---------------_^ + | | | + | | required by a bound introduced by this call +LL | | +LL | | +LL | | +LL | | yield (); +LL | | }); + | |_____^ types differ + | +note: required by a bound in `needs_generator` + --> $DIR/generator.rs:14:41 + | +LL | fn needs_generator(_: impl Generator) {} + | ^^^^^^^^^ required by this bound in `needs_generator` + +error[E0271]: type mismatch resolving `<[generator@$DIR/generator.rs:18:21: 18:23] as Generator>::Return == C` + --> $DIR/generator.rs:18:21 + | +LL | needs_generator(|| { + | _____---------------_^ + | | | + | | required by a bound introduced by this call +LL | | +LL | | +LL | | +LL | | yield (); +LL | | }); + | |_____^ types differ + | +note: required by a bound in `needs_generator` + --> $DIR/generator.rs:14:52 + | +LL | fn needs_generator(_: impl Generator) {} + | ^^^^^^^^^^ required by this bound in `needs_generator` + +error: aborting due to 3 previous errors + +Some errors have detailed explanations: E0271, E0277. +For more information about an error, try `rustc --explain E0271`. diff --git a/tests/ui/traits/new-solver/generator.rs b/tests/ui/traits/new-solver/generator.rs new file mode 100644 index 0000000000000..364373ca8be71 --- /dev/null +++ b/tests/ui/traits/new-solver/generator.rs @@ -0,0 +1,32 @@ +// compile-flags: -Ztrait-solver=next +// edition: 2021 +// revisions: pass fail +//[pass] check-pass + +#![feature(generator_trait, generators)] + +use std::ops::Generator; + +struct A; +struct B; +struct C; + +fn needs_generator(_: impl Generator) {} + +#[cfg(fail)] +fn main() { + needs_generator(|| { + //[fail]~^ ERROR Generator` is not satisfied + //[fail]~| ERROR as Generator>::Yield == B` + //[fail]~| ERROR as Generator>::Return == C` + yield (); + }); +} + +#[cfg(pass)] +fn main() { + needs_generator(|_: A| { + let _: A = yield B; + C + }) +} From 0f24e11ef5cd0a8363ae1791cee3f96de3d0845c Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 25 Jan 2023 00:38:34 +0000 Subject: [PATCH 369/500] ICE in new solver if we see an inference variable --- .../src/solve/assembly.rs | 10 +++-- .../src/solve/project_goals.rs | 6 ++- .../solve/trait_goals/structural_traits.rs | 39 +++++++++++-------- 3 files changed, 33 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_trait_selection/src/solve/assembly.rs b/compiler/rustc_trait_selection/src/solve/assembly.rs index 0b642fcba2812..7e4fc7191351f 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly.rs @@ -321,9 +321,10 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { | ty::Tuple(_) | ty::Param(_) | ty::Placeholder(..) - | ty::Infer(_) + | ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Error(_) => return, - ty::Bound(..) => bug!("unexpected bound type: {goal:?}"), + ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) + | ty::Bound(..) => bug!("unexpected self type for `{goal:?}`"), ty::Alias(_, alias_ty) => alias_ty, }; @@ -371,9 +372,10 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { | ty::Tuple(_) | ty::Param(_) | ty::Placeholder(..) - | ty::Infer(_) + | ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Error(_) => return, - ty::Bound(..) => bug!("unexpected bound type: {goal:?}"), + ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) + | ty::Bound(..) => bug!("unexpected self type for `{goal:?}`"), ty::Dynamic(bounds, ..) => bounds, }; diff --git a/compiler/rustc_trait_selection/src/solve/project_goals.rs b/compiler/rustc_trait_selection/src/solve/project_goals.rs index e5072d8e2d152..b321adcb646bc 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals.rs @@ -427,7 +427,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { .subst(tcx, &[ty::GenericArg::from(goal.predicate.self_ty())]) } - ty::Infer(ty::TyVar(..)) | ty::Alias(_, _) | ty::Param(_) | ty::Placeholder(..) => { + ty::Alias(_, _) | ty::Param(_) | ty::Placeholder(..) => { // FIXME(ptr_metadata): It would also be possible to return a `Ok(Ambig)` with no constraints. let sized_predicate = ty::Binder::dummy(tcx.at(DUMMY_SP).mk_trait_ref( LangItem::Sized, @@ -470,7 +470,9 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { } }, - ty::Infer(ty::FreshTy(..) | ty::FreshIntTy(..) | ty::FreshFloatTy(..)) + ty::Infer( + ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_), + ) | ty::Bound(..) => bug!( "unexpected self ty `{:?}` when normalizing `::Metadata`", goal.predicate.self_ty() diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs b/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs index a11cd13cb0856..676c0eb52647d 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs @@ -24,15 +24,16 @@ pub(super) fn instantiate_constituent_tys_for_auto_trait<'tcx>( | ty::Never | ty::Char => Ok(vec![]), - ty::Placeholder(..) - | ty::Dynamic(..) + ty::Dynamic(..) | ty::Param(..) | ty::Foreign(..) | ty::Alias(ty::Projection, ..) - | ty::Bound(..) - | ty::Infer(ty::TyVar(_)) => Err(NoSolution), + | ty::Placeholder(..) => Err(NoSolution), - ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => bug!(), + ty::Bound(..) + | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { + bug!("unexpected type `{ty}`") + } ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => { Ok(vec![element_ty]) @@ -99,11 +100,12 @@ pub(super) fn instantiate_constituent_tys_for_sized_trait<'tcx>( | ty::Foreign(..) | ty::Alias(..) | ty::Param(_) - | ty::Infer(ty::TyVar(_)) => Err(NoSolution), + | ty::Placeholder(..) => Err(NoSolution), - ty::Placeholder(..) - | ty::Bound(..) - | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => bug!(), + ty::Bound(..) + | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { + bug!("unexpected type `{ty}`") + } ty::Tuple(tys) => Ok(tys.to_vec()), @@ -148,11 +150,12 @@ pub(super) fn instantiate_constituent_tys_for_copy_clone_trait<'tcx>( | ty::Adt(_, _) | ty::Alias(_, _) | ty::Param(_) - | ty::Infer(ty::TyVar(_)) => Err(NoSolution), + | ty::Placeholder(..) => Err(NoSolution), - ty::Placeholder(..) - | ty::Bound(..) - | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => bug!(), + ty::Bound(..) + | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { + bug!("unexpected type `{ty}`") + } ty::Tuple(tys) => Ok(tys.to_vec()), @@ -215,9 +218,13 @@ pub(crate) fn extract_tupled_inputs_and_output_from_callable<'tcx>( | ty::Tuple(_) | ty::Alias(_, _) | ty::Param(_) - | ty::Placeholder(_) - | ty::Bound(_, _) - | ty::Infer(_) + | ty::Placeholder(..) + | ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Error(_) => Err(NoSolution), + + ty::Bound(..) + | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { + bug!("unexpected type `{self_ty}`") + } } } From 3016f55579bfb3a6a130eb75ddfcc699a64f0477 Mon Sep 17 00:00:00 2001 From: Matthew J Perez Date: Wed, 25 Jan 2023 17:10:26 +0000 Subject: [PATCH 370/500] improve fn pointer notes - add note and suggestion for casting both expected and found fn items to fn pointers - add note for casting expected fn item to fn pointer --- .../src/infer/error_reporting/suggest.rs | 52 ++++++++++++++++--- tests/ui/fn/fn-compare-mismatch.stderr | 1 + tests/ui/fn/fn-item-type.stderr | 6 ++- tests/ui/fn/fn-pointer-mismatch.stderr | 3 ++ 4 files changed, 53 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index eb7bd7256c674..768cef89f3c43 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -380,7 +380,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { return; } - let (msg, sugg) = match (expected.is_ref(), found.is_ref()) { + let (msg, sug) = match (expected.is_ref(), found.is_ref()) { (true, false) => { let msg = "consider using a reference"; let sug = format!("&{fn_name}"); @@ -404,7 +404,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { (msg, sug) } }; - diag.span_suggestion(span, msg, &sugg, Applicability::MaybeIncorrect); + diag.span_suggestion(span, msg, sug, Applicability::MaybeIncorrect); } (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => { let expected_sig = @@ -412,14 +412,50 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let found_sig = &(self.normalize_fn_sig)(self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2)); - if self.same_type_modulo_infer(*found_sig, *expected_sig) { - diag.note( - "different fn items have unique types, even if their signatures are the same", - ); + if self.same_type_modulo_infer(*expected_sig, *found_sig) { + diag.note("different fn items have unique types, even if their signatures are the same"); + } + + if !self.same_type_modulo_infer(*found_sig, *expected_sig) + || !found_sig.is_suggestable(self.tcx, true) + || !expected_sig.is_suggestable(self.tcx, true) + || ty::util::is_intrinsic(self.tcx, *did1) + || ty::util::is_intrinsic(self.tcx, *did2) + { + return; } + + let fn_name = self.tcx.def_path_str_with_substs(*did2, substs2); + let sug = if found.is_ref() { + format!("&({fn_name} as {found_sig})") + } else { + format!("{fn_name} as {found_sig}") + }; + + let msg = format!( + "consider casting both fn items to fn pointers using `as {expected_sig}`" + ); + + diag.span_suggestion_hidden(span, msg, sug, Applicability::MaybeIncorrect); } - (ty::FnDef(_, _), ty::FnPtr(_)) => { - diag.note("fn items are distinct from fn pointers"); + (ty::FnDef(did, substs), ty::FnPtr(sig)) => { + let expected_sig = + &(self.normalize_fn_sig)(self.tcx.bound_fn_sig(*did).subst(self.tcx, substs)); + let found_sig = &(self.normalize_fn_sig)(*sig); + + if !self.same_type_modulo_infer(*found_sig, *expected_sig) { + return; + } + + let fn_name = self.tcx.def_path_str_with_substs(*did, substs); + + let casting = if expected.is_ref() { + format!("&({fn_name} as {found_sig})") + } else { + format!("{fn_name} as {found_sig}") + }; + + diag.help(&format!("consider casting the fn item to a fn pointer: `{}`", casting)); } _ => { return; diff --git a/tests/ui/fn/fn-compare-mismatch.stderr b/tests/ui/fn/fn-compare-mismatch.stderr index f247ff6cf3f55..b4e71e75fdb9a 100644 --- a/tests/ui/fn/fn-compare-mismatch.stderr +++ b/tests/ui/fn/fn-compare-mismatch.stderr @@ -20,6 +20,7 @@ LL | let x = f == g; = note: expected fn item `fn() {f}` found fn item `fn() {g}` = note: different fn items have unique types, even if their signatures are the same + = help: consider casting both fn items to fn pointers using `as fn()` error: aborting due to 2 previous errors diff --git a/tests/ui/fn/fn-item-type.stderr b/tests/ui/fn/fn-item-type.stderr index cb1b88c7ab8f3..9d41243ef1191 100644 --- a/tests/ui/fn/fn-item-type.stderr +++ b/tests/ui/fn/fn-item-type.stderr @@ -14,6 +14,7 @@ note: function defined here | LL | fn eq(x: T, y: T) {} | ^^ ---- + = help: consider casting both fn items to fn pointers using `as fn(isize) -> isize` error[E0308]: mismatched types --> $DIR/fn-item-type.rs:29:19 @@ -31,6 +32,7 @@ note: function defined here | LL | fn eq(x: T, y: T) {} | ^^ ---- + = help: consider casting both fn items to fn pointers using `as fn(isize) -> isize` error[E0308]: mismatched types --> $DIR/fn-item-type.rs:34:23 @@ -48,6 +50,7 @@ note: function defined here | LL | fn eq(x: T, y: T) {} | ^^ ---- + = help: consider casting both fn items to fn pointers using `as fn(isize) -> isize` error[E0308]: mismatched types --> $DIR/fn-item-type.rs:41:26 @@ -65,6 +68,7 @@ note: function defined here | LL | fn eq(x: T, y: T) {} | ^^ ---- + = help: consider casting both fn items to fn pointers using `as fn()` error[E0308]: mismatched types --> $DIR/fn-item-type.rs:46:19 @@ -76,7 +80,7 @@ LL | eq(foo::, bar:: as fn(isize) -> isize); | = note: expected fn item `fn(_) -> _ {foo::}` found fn pointer `fn(_) -> _` - = note: fn items are distinct from fn pointers + = help: consider casting the fn item to a fn pointer: `foo:: as fn(isize) -> isize` note: function defined here --> $DIR/fn-item-type.rs:11:4 | diff --git a/tests/ui/fn/fn-pointer-mismatch.stderr b/tests/ui/fn/fn-pointer-mismatch.stderr index 2dc0710e27e46..e0bd60fbc0b5e 100644 --- a/tests/ui/fn/fn-pointer-mismatch.stderr +++ b/tests/ui/fn/fn-pointer-mismatch.stderr @@ -9,6 +9,7 @@ LL | let g = if n % 2 == 0 { &foo } else { &bar }; = note: expected reference `&fn(u32) -> u32 {foo}` found reference `&fn(u32) -> u32 {bar}` = note: different fn items have unique types, even if their signatures are the same + = help: consider casting both fn items to fn pointers using `as fn(u32) -> u32` error[E0308]: mismatched types --> $DIR/fn-pointer-mismatch.rs:23:9 @@ -21,6 +22,7 @@ LL | a = bar; = note: expected fn item `fn(_) -> _ {foo}` found fn item `fn(_) -> _ {bar}` = note: different fn items have unique types, even if their signatures are the same + = help: consider casting both fn items to fn pointers using `as fn(u32) -> u32` error[E0308]: mismatched types --> $DIR/fn-pointer-mismatch.rs:31:18 @@ -35,6 +37,7 @@ LL | b = Box::new(bar); = note: different fn items have unique types, even if their signatures are the same note: associated function defined here --> $SRC_DIR/alloc/src/boxed.rs:LL:COL + = help: consider casting both fn items to fn pointers using `as fn(u32) -> u32` error[E0308]: mismatched types --> $DIR/fn-pointer-mismatch.rs:36:29 From 77d7c63872c2a09ffc082bfd947b98ab216f2a76 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Thu, 26 Jan 2023 05:49:37 +0000 Subject: [PATCH 371/500] Update snap from `1.0.1` to `1.1.0` As spotted by @mejrs, snap 1.0.1 emits a future compatibility warning. This was fixed in https://github.com/BurntSushi/rust-snappy/pull/39 --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3175e98e81e53..c81bf9fddf607 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5214,9 +5214,9 @@ checksum = "cc88c725d61fc6c3132893370cac4a0200e3fedf5da8331c570664b1987f5ca2" [[package]] name = "snap" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da73c8f77aebc0e40c300b93f0a5f1bece7a248a36eee287d4e095f35c7b7d6e" +checksum = "5e9f0ab6ef7eb7353d9119c170a436d1bf248eea575ac42d19d12f4e34130831" [[package]] name = "snapbox" From a499862948371bbbcc534ca8d7a20cb107ce9952 Mon Sep 17 00:00:00 2001 From: Yann Simon Date: Thu, 26 Jan 2023 11:01:36 +0100 Subject: [PATCH 372/500] remove avx512 prefix for gfni, vaes and vpclmulqdq --- library/std/tests/run-time-detect.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/std/tests/run-time-detect.rs b/library/std/tests/run-time-detect.rs index 7fbfe3daaa826..c25c3f84d2b6c 100644 --- a/library/std/tests/run-time-detect.rs +++ b/library/std/tests/run-time-detect.rs @@ -120,16 +120,16 @@ fn x86_all() { println!("avx512dq: {:?}", is_x86_feature_detected!("avx512dq")); println!("avx512er: {:?}", is_x86_feature_detected!("avx512er")); println!("avx512f: {:?}", is_x86_feature_detected!("avx512f")); - println!("avx512gfni: {:?}", is_x86_feature_detected!("avx512gfni")); + println!("gfni: {:?}", is_x86_feature_detected!("gfni")); println!("avx512ifma: {:?}", is_x86_feature_detected!("avx512ifma")); println!("avx512pf: {:?}", is_x86_feature_detected!("avx512pf")); - println!("avx512vaes: {:?}", is_x86_feature_detected!("avx512vaes")); + println!("vaes: {:?}", is_x86_feature_detected!("vaes")); println!("avx512vbmi2: {:?}", is_x86_feature_detected!("avx512vbmi2")); println!("avx512vbmi: {:?}", is_x86_feature_detected!("avx512vbmi")); println!("avx512vl: {:?}", is_x86_feature_detected!("avx512vl")); println!("avx512vnni: {:?}", is_x86_feature_detected!("avx512vnni")); println!("avx512vp2intersect: {:?}", is_x86_feature_detected!("avx512vp2intersect")); - println!("avx512vpclmulqdq: {:?}", is_x86_feature_detected!("avx512vpclmulqdq")); + println!("vpclmulqdq: {:?}", is_x86_feature_detected!("vpclmulqdq")); println!("avx512vpopcntdq: {:?}", is_x86_feature_detected!("avx512vpopcntdq")); println!("avx: {:?}", is_x86_feature_detected!("avx")); println!("bmi1: {:?}", is_x86_feature_detected!("bmi1")); From 727b987e0668fb87a328b7312cafdd40b75e8ed9 Mon Sep 17 00:00:00 2001 From: lcnr Date: Thu, 26 Jan 2023 10:57:11 +0100 Subject: [PATCH 373/500] solver comments + remove `TyCtxt::evaluate_goal` --- .../rustc_trait_selection/src/solve/mod.rs | 20 +++++++++---------- .../src/solve/project_goals.rs | 4 ++-- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_trait_selection/src/solve/mod.rs b/compiler/rustc_trait_selection/src/solve/mod.rs index f44648c95d742..7880cbad5fe03 100644 --- a/compiler/rustc_trait_selection/src/solve/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/mod.rs @@ -141,17 +141,6 @@ type CanonicalResponse<'tcx> = Canonical<'tcx, Response<'tcx>>; /// solver, merge the two responses again. pub type QueryResult<'tcx> = Result, NoSolution>; -pub trait TyCtxtExt<'tcx> { - fn evaluate_goal(self, goal: CanonicalGoal<'tcx>) -> QueryResult<'tcx>; -} - -impl<'tcx> TyCtxtExt<'tcx> for TyCtxt<'tcx> { - fn evaluate_goal(self, goal: CanonicalGoal<'tcx>) -> QueryResult<'tcx> { - let mut search_graph = search_graph::SearchGraph::new(self); - EvalCtxt::evaluate_canonical_goal(self, &mut search_graph, goal) - } -} - pub trait InferCtxtEvalExt<'tcx> { /// Evaluates a goal from **outside** of the trait solver. /// @@ -194,6 +183,15 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { self.infcx.tcx } + /// The entry point of the solver. + /// + /// This function deals with (coinductive) cycles, overflow, and caching + /// and then calls [`EvalCtxt::compute_goal`] which contains the actual + /// logic of the solver. + /// + /// Instead of calling this function directly, use either [EvalCtxt::evaluate_goal] + /// if you're inside of the solver or [InferCtxtEvalExt::evaluate_root_goal] if you're + /// outside of it. #[instrument(level = "debug", skip(tcx, search_graph), ret)] fn evaluate_canonical_goal( tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_trait_selection/src/solve/project_goals.rs b/compiler/rustc_trait_selection/src/solve/project_goals.rs index b583705ac4369..30902c2bc4506 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals.rs @@ -28,8 +28,8 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { // To only compute normalization once for each projection we only // normalize if the expected term is an unconstrained inference variable. // - // E.g. for `::Assoc = u32` we recursively compute the goal - // `exists ::Assoc = U` and then take the resulting type for + // E.g. for `::Assoc == u32` we recursively compute the goal + // `exists ::Assoc == U` and then take the resulting type for // `U` and equate it with `u32`. This means that we don't need a separate // projection cache in the solver. if self.term_is_fully_unconstrained(goal) { From 2e8162a0b00c3b1cc06b244c3b6ddbbb31caa26d Mon Sep 17 00:00:00 2001 From: Yann Simon Date: Thu, 26 Jan 2023 11:09:32 +0100 Subject: [PATCH 374/500] fix alphabetical sort --- library/std/tests/run-time-detect.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/std/tests/run-time-detect.rs b/library/std/tests/run-time-detect.rs index c25c3f84d2b6c..ffcca9897c135 100644 --- a/library/std/tests/run-time-detect.rs +++ b/library/std/tests/run-time-detect.rs @@ -120,16 +120,13 @@ fn x86_all() { println!("avx512dq: {:?}", is_x86_feature_detected!("avx512dq")); println!("avx512er: {:?}", is_x86_feature_detected!("avx512er")); println!("avx512f: {:?}", is_x86_feature_detected!("avx512f")); - println!("gfni: {:?}", is_x86_feature_detected!("gfni")); println!("avx512ifma: {:?}", is_x86_feature_detected!("avx512ifma")); println!("avx512pf: {:?}", is_x86_feature_detected!("avx512pf")); - println!("vaes: {:?}", is_x86_feature_detected!("vaes")); println!("avx512vbmi2: {:?}", is_x86_feature_detected!("avx512vbmi2")); println!("avx512vbmi: {:?}", is_x86_feature_detected!("avx512vbmi")); println!("avx512vl: {:?}", is_x86_feature_detected!("avx512vl")); println!("avx512vnni: {:?}", is_x86_feature_detected!("avx512vnni")); println!("avx512vp2intersect: {:?}", is_x86_feature_detected!("avx512vp2intersect")); - println!("vpclmulqdq: {:?}", is_x86_feature_detected!("vpclmulqdq")); println!("avx512vpopcntdq: {:?}", is_x86_feature_detected!("avx512vpopcntdq")); println!("avx: {:?}", is_x86_feature_detected!("avx")); println!("bmi1: {:?}", is_x86_feature_detected!("bmi1")); @@ -138,6 +135,7 @@ fn x86_all() { println!("f16c: {:?}", is_x86_feature_detected!("f16c")); println!("fma: {:?}", is_x86_feature_detected!("fma")); println!("fxsr: {:?}", is_x86_feature_detected!("fxsr")); + println!("gfni: {:?}", is_x86_feature_detected!("gfni")); println!("lzcnt: {:?}", is_x86_feature_detected!("lzcnt")); //println!("movbe: {:?}", is_x86_feature_detected!("movbe")); // movbe is unsupported as a target feature println!("pclmulqdq: {:?}", is_x86_feature_detected!("pclmulqdq")); @@ -154,6 +152,8 @@ fn x86_all() { println!("sse: {:?}", is_x86_feature_detected!("sse")); println!("ssse3: {:?}", is_x86_feature_detected!("ssse3")); println!("tbm: {:?}", is_x86_feature_detected!("tbm")); + println!("vaes: {:?}", is_x86_feature_detected!("vaes")); + println!("vpclmulqdq: {:?}", is_x86_feature_detected!("vpclmulqdq")); println!("xsave: {:?}", is_x86_feature_detected!("xsave")); println!("xsavec: {:?}", is_x86_feature_detected!("xsavec")); println!("xsaveopt: {:?}", is_x86_feature_detected!("xsaveopt")); From 90e4c134090fddd91b4981dd1a97b12e5dd3d9a7 Mon Sep 17 00:00:00 2001 From: b-naber Date: Tue, 17 Jan 2023 21:13:33 +0100 Subject: [PATCH 375/500] output tree representation for thir-tree --- compiler/rustc_middle/src/thir.rs | 1 + compiler/rustc_middle/src/thir/print.rs | 881 ++++++++++++++++++++ compiler/rustc_middle/src/ty/adt.rs | 6 +- compiler/rustc_mir_build/src/build/mod.rs | 4 + compiler/rustc_mir_build/src/thir/cx/mod.rs | 5 +- 5 files changed, 893 insertions(+), 4 deletions(-) create mode 100644 compiler/rustc_middle/src/thir/print.rs diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index 5f320708c8416..6f2dac467532c 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -29,6 +29,7 @@ use rustc_target::asm::InlineAsmRegOrRegClass; use std::fmt; use std::ops::Index; +pub mod print; pub mod visit; macro_rules! thir_with_elements { diff --git a/compiler/rustc_middle/src/thir/print.rs b/compiler/rustc_middle/src/thir/print.rs new file mode 100644 index 0000000000000..28ef768ade6f7 --- /dev/null +++ b/compiler/rustc_middle/src/thir/print.rs @@ -0,0 +1,881 @@ +use crate::thir::*; +use crate::ty::{self, TyCtxt}; + +use std::fmt::{self, Write}; + +impl<'tcx> TyCtxt<'tcx> { + pub fn thir_tree_representation<'a>(self, thir: &'a Thir<'tcx>) -> String { + let mut printer = ThirPrinter::new(thir); + printer.print(); + printer.into_buffer() + } +} + +struct ThirPrinter<'a, 'tcx> { + thir: &'a Thir<'tcx>, + fmt: String, +} + +const INDENT: &str = " "; + +macro_rules! print_indented { + ($writer:ident, $s:expr, $indent_lvl:expr) => { + let indent = (0..$indent_lvl).map(|_| INDENT).collect::>().concat(); + writeln!($writer, "{}{}", indent, $s).expect("unable to write to ThirPrinter"); + }; +} + +impl<'a, 'tcx> Write for ThirPrinter<'a, 'tcx> { + fn write_str(&mut self, s: &str) -> fmt::Result { + self.fmt.push_str(s); + Ok(()) + } +} + +impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { + fn new(thir: &'a Thir<'tcx>) -> Self { + Self { thir, fmt: String::new() } + } + + fn print(&mut self) { + print_indented!(self, "params: [", 0); + for param in self.thir.params.iter() { + self.print_param(param, 1); + } + print_indented!(self, "]", 0); + + print_indented!(self, "body:", 0); + let expr = ExprId::from_usize(self.thir.exprs.len() - 1); + self.print_expr(expr, 1); + } + + fn into_buffer(self) -> String { + self.fmt + } + + fn print_param(&mut self, param: &Param<'tcx>, depth_lvl: usize) { + let Param { pat, ty, ty_span, self_kind, hir_id } = param; + + print_indented!(self, "Param {", depth_lvl); + print_indented!(self, format!("ty: {:?}", ty), depth_lvl + 1); + print_indented!(self, format!("ty_span: {:?}", ty_span), depth_lvl + 1); + print_indented!(self, format!("self_kind: {:?}", self_kind), depth_lvl + 1); + print_indented!(self, format!("hir_id: {:?}", hir_id), depth_lvl + 1); + + if let Some(pat) = pat { + print_indented!(self, "param: Some( ", depth_lvl + 1); + self.print_pat(pat, depth_lvl + 2); + print_indented!(self, ")", depth_lvl + 1); + } else { + print_indented!(self, "param: None", depth_lvl + 1); + } + + print_indented!(self, "}", depth_lvl); + } + + fn print_block(&mut self, block_id: BlockId, depth_lvl: usize) { + let Block { + targeted_by_break, + opt_destruction_scope, + span, + region_scope, + stmts, + expr, + safety_mode, + } = &self.thir.blocks[block_id]; + + print_indented!(self, "Block {", depth_lvl); + print_indented!(self, format!("targeted_by_break: {}", targeted_by_break), depth_lvl + 1); + print_indented!( + self, + format!("opt_destruction_scope: {:?}", opt_destruction_scope), + depth_lvl + 1 + ); + print_indented!(self, format!("span: {:?}", span), depth_lvl + 1); + print_indented!(self, format!("region_scope: {:?}", region_scope), depth_lvl + 1); + print_indented!(self, format!("safety_mode: {:?}", safety_mode), depth_lvl + 1); + + if stmts.len() > 0 { + print_indented!(self, "stmts: [", depth_lvl + 1); + for stmt in stmts.iter() { + self.print_stmt(*stmt, depth_lvl + 2); + } + print_indented!(self, "]", depth_lvl + 1); + } else { + print_indented!(self, "stmts: []", depth_lvl + 1); + } + + if let Some(expr_id) = expr { + print_indented!(self, "expr:", depth_lvl + 1); + self.print_expr(*expr_id, depth_lvl + 2); + } else { + print_indented!(self, "expr: []", depth_lvl + 1); + } + + print_indented!(self, "}", depth_lvl); + } + + fn print_stmt(&mut self, stmt_id: StmtId, depth_lvl: usize) { + let Stmt { kind, opt_destruction_scope } = &self.thir.stmts[stmt_id]; + + print_indented!(self, "Stmt {", depth_lvl); + print_indented!( + self, + format!("opt_destruction_scope: {:?}", opt_destruction_scope), + depth_lvl + 1 + ); + + match kind { + StmtKind::Expr { scope, expr } => { + print_indented!(self, "kind: Expr {", depth_lvl + 1); + print_indented!(self, format!("scope: {:?}", scope), depth_lvl + 2); + print_indented!(self, "expr:", depth_lvl + 2); + self.print_expr(*expr, depth_lvl + 3); + print_indented!(self, "}", depth_lvl + 1); + } + StmtKind::Let { + remainder_scope, + init_scope, + pattern, + initializer, + else_block, + lint_level, + } => { + print_indented!(self, "kind: Let {", depth_lvl + 1); + print_indented!( + self, + format!("remainder_scope: {:?}", remainder_scope), + depth_lvl + 2 + ); + print_indented!(self, format!("init_scope: {:?}", init_scope), depth_lvl + 2); + + print_indented!(self, "pattern: ", depth_lvl + 2); + self.print_pat(pattern, depth_lvl + 3); + print_indented!(self, ",", depth_lvl + 2); + + if let Some(init) = initializer { + print_indented!(self, "initializer: Some(", depth_lvl + 2); + self.print_expr(*init, depth_lvl + 3); + print_indented!(self, ")", depth_lvl + 2); + } else { + print_indented!(self, "initializer: None", depth_lvl + 2); + } + + if let Some(else_block) = else_block { + print_indented!(self, "else_block: Some(", depth_lvl + 2); + self.print_block(*else_block, depth_lvl + 3); + print_indented!(self, ")", depth_lvl + 2); + } else { + print_indented!(self, "else_block: None", depth_lvl + 2); + } + + print_indented!(self, format!("lint_level: {:?}", lint_level), depth_lvl + 2); + print_indented!(self, "}", depth_lvl + 1); + } + } + + print_indented!(self, "}", depth_lvl); + } + + fn print_expr(&mut self, expr: ExprId, depth_lvl: usize) { + let Expr { ty, temp_lifetime, span, kind } = &self.thir[expr]; + print_indented!(self, "Expr {", depth_lvl); + print_indented!(self, format!("ty: {:?}", ty), depth_lvl + 1); + print_indented!(self, format!("temp_lifetime: {:?}", temp_lifetime), depth_lvl + 1); + print_indented!(self, format!("span: {:?}", span), depth_lvl + 1); + print_indented!(self, "kind: ", depth_lvl + 1); + self.print_expr_kind(kind, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + + fn print_expr_kind(&mut self, expr_kind: &ExprKind<'tcx>, depth_lvl: usize) { + use rustc_middle::thir::ExprKind::*; + + match expr_kind { + Scope { region_scope, value, lint_level } => { + print_indented!(self, "Scope {", depth_lvl); + print_indented!(self, format!("region_scope: {:?}", region_scope), depth_lvl + 1); + print_indented!(self, format!("lint_level: {:?}", lint_level), depth_lvl + 1); + print_indented!(self, "value:", depth_lvl + 1); + self.print_expr(*value, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Box { value } => { + print_indented!(self, "Box {", depth_lvl); + self.print_expr(*value, depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + If { if_then_scope, cond, then, else_opt } => { + print_indented!(self, "If {", depth_lvl); + print_indented!(self, format!("if_then_scope: {:?}", if_then_scope), depth_lvl + 1); + print_indented!(self, "cond:", depth_lvl + 1); + self.print_expr(*cond, depth_lvl + 2); + print_indented!(self, "then:", depth_lvl + 1); + self.print_expr(*then, depth_lvl + 2); + + if let Some(else_expr) = else_opt { + print_indented!(self, "else:", depth_lvl + 1); + self.print_expr(*else_expr, depth_lvl + 2); + } + + print_indented!(self, "}", depth_lvl); + } + Call { fun, args, ty, from_hir_call, fn_span } => { + print_indented!(self, "Call {", depth_lvl); + print_indented!(self, format!("ty: {:?}", ty), depth_lvl + 1); + print_indented!(self, format!("from_hir_call: {}", from_hir_call), depth_lvl + 1); + print_indented!(self, format!("fn_span: {:?}", fn_span), depth_lvl + 1); + print_indented!(self, "fun:", depth_lvl + 1); + self.print_expr(*fun, depth_lvl + 2); + + if args.len() > 0 { + print_indented!(self, "args: [", depth_lvl + 1); + for arg in args.iter() { + self.print_expr(*arg, depth_lvl + 2); + } + print_indented!(self, "]", depth_lvl + 1); + } else { + print_indented!(self, "args: []", depth_lvl + 1); + } + + print_indented!(self, "}", depth_lvl); + } + Deref { arg } => { + print_indented!(self, "Deref {", depth_lvl); + self.print_expr(*arg, depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + Binary { op, lhs, rhs } => { + print_indented!(self, "Binary {", depth_lvl); + print_indented!(self, format!("op: {:?}", op), depth_lvl + 1); + print_indented!(self, "lhs:", depth_lvl + 1); + self.print_expr(*lhs, depth_lvl + 2); + print_indented!(self, "rhs:", depth_lvl + 1); + self.print_expr(*rhs, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + LogicalOp { op, lhs, rhs } => { + print_indented!(self, "LogicalOp {", depth_lvl); + print_indented!(self, format!("op: {:?}", op), depth_lvl + 1); + print_indented!(self, "lhs:", depth_lvl + 1); + self.print_expr(*lhs, depth_lvl + 2); + print_indented!(self, "rhs:", depth_lvl + 1); + self.print_expr(*rhs, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Unary { op, arg } => { + print_indented!(self, "Unary {", depth_lvl); + print_indented!(self, format!("op: {:?}", op), depth_lvl + 1); + print_indented!(self, "arg:", depth_lvl + 1); + self.print_expr(*arg, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Cast { source } => { + print_indented!(self, "Cast {", depth_lvl); + print_indented!(self, "source:", depth_lvl + 1); + self.print_expr(*source, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Use { source } => { + print_indented!(self, "Use {", depth_lvl); + print_indented!(self, "source:", depth_lvl + 1); + self.print_expr(*source, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + NeverToAny { source } => { + print_indented!(self, "NeverToAny {", depth_lvl); + print_indented!(self, "source:", depth_lvl + 1); + self.print_expr(*source, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Pointer { cast, source } => { + print_indented!(self, "Pointer {", depth_lvl); + print_indented!(self, format!("cast: {:?}", cast), depth_lvl + 1); + print_indented!(self, "source:", depth_lvl + 1); + self.print_expr(*source, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Loop { body } => { + print_indented!(self, "Loop (", depth_lvl); + print_indented!(self, "body:", depth_lvl + 1); + self.print_expr(*body, depth_lvl + 2); + print_indented!(self, ")", depth_lvl); + } + Let { expr, pat } => { + print_indented!(self, "Let {", depth_lvl); + print_indented!(self, "expr:", depth_lvl + 1); + self.print_expr(*expr, depth_lvl + 2); + print_indented!(self, format!("pat: {:?}", pat), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + Match { scrutinee, arms } => { + print_indented!(self, "Match {", depth_lvl); + print_indented!(self, "scrutinee:", depth_lvl + 1); + self.print_expr(*scrutinee, depth_lvl + 2); + + print_indented!(self, "arms: [", depth_lvl + 1); + for arm_id in arms.iter() { + self.print_arm(*arm_id, depth_lvl + 2); + } + print_indented!(self, "]", depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + Block { block } => self.print_block(*block, depth_lvl), + Assign { lhs, rhs } => { + print_indented!(self, "Assign {", depth_lvl); + print_indented!(self, "lhs:", depth_lvl + 1); + self.print_expr(*lhs, depth_lvl + 2); + print_indented!(self, "rhs:", depth_lvl + 1); + self.print_expr(*rhs, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + AssignOp { op, lhs, rhs } => { + print_indented!(self, "AssignOp {", depth_lvl); + print_indented!(self, format!("op: {:?}", op), depth_lvl + 1); + print_indented!(self, "lhs:", depth_lvl + 1); + self.print_expr(*lhs, depth_lvl + 2); + print_indented!(self, "rhs:", depth_lvl + 1); + self.print_expr(*rhs, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Field { lhs, variant_index, name } => { + print_indented!(self, "Field {", depth_lvl); + print_indented!(self, format!("variant_index: {:?}", variant_index), depth_lvl + 1); + print_indented!(self, format!("name: {:?}", name), depth_lvl + 1); + print_indented!(self, "lhs:", depth_lvl + 1); + self.print_expr(*lhs, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Index { lhs, index } => { + print_indented!(self, "Index {", depth_lvl); + print_indented!(self, format!("index: {:?}", index), depth_lvl + 1); + print_indented!(self, "lhs:", depth_lvl + 1); + self.print_expr(*lhs, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + VarRef { id } => { + print_indented!(self, "VarRef {", depth_lvl); + print_indented!(self, format!("id: {:?}", id), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + UpvarRef { closure_def_id, var_hir_id } => { + print_indented!(self, "UpvarRef {", depth_lvl); + print_indented!( + self, + format!("closure_def_id: {:?}", closure_def_id), + depth_lvl + 1 + ); + print_indented!(self, format!("var_hir_id: {:?}", var_hir_id), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + Borrow { borrow_kind, arg } => { + print_indented!(self, "Borrow (", depth_lvl); + print_indented!(self, format!("borrow_kind: {:?}", borrow_kind), depth_lvl + 1); + print_indented!(self, "arg:", depth_lvl + 1); + self.print_expr(*arg, depth_lvl + 2); + print_indented!(self, ")", depth_lvl); + } + AddressOf { mutability, arg } => { + print_indented!(self, "AddressOf {", depth_lvl); + print_indented!(self, format!("mutability: {:?}", mutability), depth_lvl + 1); + print_indented!(self, "arg:", depth_lvl + 1); + self.print_expr(*arg, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Break { label, value } => { + print_indented!(self, "Break (", depth_lvl); + print_indented!(self, format!("label: {:?}", label), depth_lvl + 1); + + if let Some(value) = value { + print_indented!(self, "value:", depth_lvl + 1); + self.print_expr(*value, depth_lvl + 2); + } + + print_indented!(self, ")", depth_lvl); + } + Continue { label } => { + print_indented!(self, "Continue {", depth_lvl); + print_indented!(self, format!("label: {:?}", label), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + Return { value } => { + print_indented!(self, "Return {", depth_lvl); + print_indented!(self, "value:", depth_lvl + 1); + + if let Some(value) = value { + self.print_expr(*value, depth_lvl + 2); + } + + print_indented!(self, "}", depth_lvl); + } + ConstBlock { did, substs } => { + print_indented!(self, "ConstBlock {", depth_lvl); + print_indented!(self, format!("did: {:?}", did), depth_lvl + 1); + print_indented!(self, format!("substs: {:?}", substs), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + Repeat { value, count } => { + print_indented!(self, "Repeat {", depth_lvl); + print_indented!(self, format!("count: {:?}", count), depth_lvl + 1); + print_indented!(self, "value:", depth_lvl + 1); + self.print_expr(*value, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Array { fields } => { + print_indented!(self, "Array {", depth_lvl); + print_indented!(self, "fields: [", depth_lvl + 1); + for field_id in fields.iter() { + self.print_expr(*field_id, depth_lvl + 2); + } + print_indented!(self, "]", depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + Tuple { fields } => { + print_indented!(self, "Tuple {", depth_lvl); + print_indented!(self, "fields: [", depth_lvl + 1); + for field_id in fields.iter() { + self.print_expr(*field_id, depth_lvl + 2); + } + print_indented!(self, "]", depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + Adt(adt_expr) => { + print_indented!(self, "Adt {", depth_lvl); + self.print_adt_expr(&**adt_expr, depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + PlaceTypeAscription { source, user_ty } => { + print_indented!(self, "PlaceTypeAscription {", depth_lvl); + print_indented!(self, format!("user_ty: {:?}", user_ty), depth_lvl + 1); + print_indented!(self, "source:", depth_lvl + 1); + self.print_expr(*source, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + ValueTypeAscription { source, user_ty } => { + print_indented!(self, "ValueTypeAscription {", depth_lvl); + print_indented!(self, format!("user_ty: {:?}", user_ty), depth_lvl + 1); + print_indented!(self, "source:", depth_lvl + 1); + self.print_expr(*source, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Closure(closure_expr) => { + print_indented!(self, "Closure {", depth_lvl); + print_indented!(self, "closure_expr:", depth_lvl + 1); + self.print_closure_expr(&**closure_expr, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + Literal { lit, neg } => { + print_indented!( + self, + format!("Literal( lit: {:?}, neg: {:?})\n", lit, neg), + depth_lvl + ); + } + NonHirLiteral { lit, user_ty } => { + print_indented!(self, "NonHirLiteral {", depth_lvl); + print_indented!(self, format!("lit: {:?}", lit), depth_lvl + 1); + print_indented!(self, format!("user_ty: {:?}", user_ty), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + ZstLiteral { user_ty } => { + print_indented!(self, format!("ZstLiteral(user_ty: {:?})", user_ty), depth_lvl); + } + NamedConst { def_id, substs, user_ty } => { + print_indented!(self, "NamedConst {", depth_lvl); + print_indented!(self, format!("def_id: {:?}", def_id), depth_lvl + 1); + print_indented!(self, format!("user_ty: {:?}", user_ty), depth_lvl + 1); + print_indented!(self, format!("substs: {:?}", substs), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + ConstParam { param, def_id } => { + print_indented!(self, "ConstParam {", depth_lvl); + print_indented!(self, format!("def_id: {:?}", def_id), depth_lvl + 1); + print_indented!(self, format!("param: {:?}", param), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + StaticRef { alloc_id, ty, def_id } => { + print_indented!(self, "StaticRef {", depth_lvl); + print_indented!(self, format!("def_id: {:?}", def_id), depth_lvl + 1); + print_indented!(self, format!("ty: {:?}", ty), depth_lvl + 1); + print_indented!(self, format!("alloc_id: {:?}", alloc_id), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + InlineAsm(expr) => { + print_indented!(self, "InlineAsm {", depth_lvl); + print_indented!(self, "expr:", depth_lvl + 1); + self.print_inline_asm_expr(&**expr, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + ThreadLocalRef(def_id) => { + print_indented!(self, "ThreadLocalRef {", depth_lvl); + print_indented!(self, format!("def_id: {:?}", def_id), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + Yield { value } => { + print_indented!(self, "Yield {", depth_lvl); + print_indented!(self, "value:", depth_lvl + 1); + self.print_expr(*value, depth_lvl + 2); + print_indented!(self, "}", depth_lvl); + } + } + } + + fn print_adt_expr(&mut self, adt_expr: &AdtExpr<'tcx>, depth_lvl: usize) { + print_indented!(self, "adt_def:", depth_lvl); + self.print_adt_def(&*adt_expr.adt_def.0, depth_lvl + 1); + print_indented!( + self, + format!("variant_index: {:?}", adt_expr.variant_index), + depth_lvl + 1 + ); + print_indented!(self, format!("substs: {:?}", adt_expr.substs), depth_lvl + 1); + print_indented!(self, format!("user_ty: {:?}", adt_expr.user_ty), depth_lvl + 1); + + for (i, field_expr) in adt_expr.fields.iter().enumerate() { + print_indented!(self, format!("field {}:", i), depth_lvl + 1); + self.print_expr(field_expr.expr, depth_lvl + 2); + } + + if let Some(ref base) = adt_expr.base { + print_indented!(self, "base:", depth_lvl + 1); + self.print_fru_info(base, depth_lvl + 2); + } else { + print_indented!(self, "base: None", depth_lvl + 1); + } + } + + fn print_adt_def(&mut self, adt_def: &ty::AdtDefData, depth_lvl: usize) { + print_indented!(self, "AdtDef {", depth_lvl); + print_indented!(self, format!("did: {:?}", adt_def.did), depth_lvl + 1); + print_indented!(self, format!("variants: {:?}", adt_def.variants), depth_lvl + 1); + print_indented!(self, format!("flags: {:?}", adt_def.flags), depth_lvl + 1); + print_indented!(self, format!("repr: {:?}", adt_def.repr), depth_lvl + 1); + } + + fn print_fru_info(&mut self, fru_info: &FruInfo<'tcx>, depth_lvl: usize) { + print_indented!(self, "FruInfo {", depth_lvl); + print_indented!(self, "base: ", depth_lvl + 1); + self.print_expr(fru_info.base, depth_lvl + 2); + print_indented!(self, "field_types: [", depth_lvl + 1); + for ty in fru_info.field_types.iter() { + print_indented!(self, format!("ty: {:?}", ty), depth_lvl + 2); + } + print_indented!(self, "}", depth_lvl); + } + + fn print_arm(&mut self, arm_id: ArmId, depth_lvl: usize) { + print_indented!(self, "Arm {", depth_lvl); + + let arm = &self.thir.arms[arm_id]; + let Arm { pattern, guard, body, lint_level, scope, span } = arm; + + print_indented!(self, "pattern: ", depth_lvl + 1); + self.print_pat(pattern, depth_lvl + 2); + + if let Some(guard) = guard { + print_indented!(self, "guard: ", depth_lvl + 1); + self.print_guard(guard, depth_lvl + 2); + } else { + print_indented!(self, "guard: None", depth_lvl + 1); + } + + print_indented!(self, "body: ", depth_lvl + 1); + self.print_expr(*body, depth_lvl + 2); + print_indented!(self, format!("lint_level: {:?}", lint_level), depth_lvl + 1); + print_indented!(self, format!("scope: {:?}", scope), depth_lvl + 1); + print_indented!(self, format!("span: {:?}", span), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + + fn print_pat(&mut self, pat: &Box>, depth_lvl: usize) { + let Pat { ty, span, kind } = &**pat; + + print_indented!(self, "Pat: {", depth_lvl); + print_indented!(self, format!("ty: {:?}", ty), depth_lvl + 1); + print_indented!(self, format!("span: {:?}", span), depth_lvl + 1); + self.print_pat_kind(kind, depth_lvl + 1); + print_indented!(self, "}", depth_lvl); + } + + fn print_pat_kind(&mut self, pat_kind: &PatKind<'tcx>, depth_lvl: usize) { + print_indented!(self, "kind: PatKind {", depth_lvl); + + match pat_kind { + PatKind::Wild => { + print_indented!(self, "Wild", depth_lvl + 1); + } + PatKind::AscribeUserType { ascription, subpattern } => { + print_indented!(self, "AscribeUserType: {", depth_lvl + 1); + print_indented!(self, format!("ascription: {:?}", ascription), depth_lvl + 2); + print_indented!(self, "subpattern: ", depth_lvl + 2); + self.print_pat(subpattern, depth_lvl + 3); + print_indented!(self, "}", depth_lvl + 1); + } + PatKind::Binding { mutability, name, mode, var, ty, subpattern, is_primary } => { + print_indented!(self, "Binding {", depth_lvl + 1); + print_indented!(self, format!("mutability: {:?}", mutability), depth_lvl + 2); + print_indented!(self, format!("name: {:?}", name), depth_lvl + 2); + print_indented!(self, format!("mode: {:?}", mode), depth_lvl + 2); + print_indented!(self, format!("var: {:?}", var), depth_lvl + 2); + print_indented!(self, format!("ty: {:?}", ty), depth_lvl + 2); + print_indented!(self, format!("is_primary: {:?}", is_primary), depth_lvl + 2); + + if let Some(subpattern) = subpattern { + print_indented!(self, "subpattern: Some( ", depth_lvl + 2); + self.print_pat(subpattern, depth_lvl + 3); + print_indented!(self, ")", depth_lvl + 2); + } else { + print_indented!(self, "subpattern: None", depth_lvl + 2); + } + + print_indented!(self, "}", depth_lvl + 1); + } + PatKind::Variant { adt_def, substs, variant_index, subpatterns } => { + print_indented!(self, "Variant {", depth_lvl + 1); + print_indented!(self, "adt_def: ", depth_lvl + 2); + self.print_adt_def(&*adt_def.0, depth_lvl + 3); + print_indented!(self, format!("substs: {:?}", substs), depth_lvl + 2); + print_indented!(self, format!("variant_index: {:?}", variant_index), depth_lvl + 2); + + if subpatterns.len() > 0 { + print_indented!(self, "subpatterns: [", depth_lvl + 2); + for field_pat in subpatterns.iter() { + self.print_pat(&field_pat.pattern, depth_lvl + 3); + } + print_indented!(self, "]", depth_lvl + 2); + } else { + print_indented!(self, "subpatterns: []", depth_lvl + 2); + } + + print_indented!(self, "}", depth_lvl + 1); + } + PatKind::Leaf { subpatterns } => { + print_indented!(self, "Leaf { ", depth_lvl + 1); + print_indented!(self, "subpatterns: [", depth_lvl + 2); + for field_pat in subpatterns.iter() { + self.print_pat(&field_pat.pattern, depth_lvl + 3); + } + print_indented!(self, "]", depth_lvl + 2); + print_indented!(self, "}", depth_lvl + 1); + } + PatKind::Deref { subpattern } => { + print_indented!(self, "Deref { ", depth_lvl + 1); + print_indented!(self, "subpattern: ", depth_lvl + 2); + self.print_pat(subpattern, depth_lvl + 2); + print_indented!(self, "}", depth_lvl + 1); + } + PatKind::Constant { value } => { + print_indented!(self, "Constant {", depth_lvl + 1); + print_indented!(self, format!("value: {:?}", value), depth_lvl + 2); + print_indented!(self, "}", depth_lvl + 1); + } + PatKind::Range(pat_range) => { + print_indented!(self, format!("Range ( {:?} )", pat_range), depth_lvl + 1); + } + PatKind::Slice { prefix, slice, suffix } => { + print_indented!(self, "Slice {", depth_lvl + 1); + + print_indented!(self, "prefix: [", depth_lvl + 2); + for prefix_pat in prefix.iter() { + self.print_pat(prefix_pat, depth_lvl + 3); + } + print_indented!(self, "]", depth_lvl + 2); + + if let Some(slice) = slice { + print_indented!(self, "slice: ", depth_lvl + 2); + self.print_pat(slice, depth_lvl + 3); + } + + print_indented!(self, "suffix: [", depth_lvl + 2); + for suffix_pat in suffix.iter() { + self.print_pat(suffix_pat, depth_lvl + 3); + } + print_indented!(self, "]", depth_lvl + 2); + + print_indented!(self, "}", depth_lvl + 1); + } + PatKind::Array { prefix, slice, suffix } => { + print_indented!(self, "Array {", depth_lvl + 1); + + print_indented!(self, "prefix: [", depth_lvl + 2); + for prefix_pat in prefix.iter() { + self.print_pat(prefix_pat, depth_lvl + 3); + } + print_indented!(self, "]", depth_lvl + 2); + + if let Some(slice) = slice { + print_indented!(self, "slice: ", depth_lvl + 2); + self.print_pat(slice, depth_lvl + 3); + } + + print_indented!(self, "suffix: [", depth_lvl + 2); + for suffix_pat in suffix.iter() { + self.print_pat(suffix_pat, depth_lvl + 3); + } + print_indented!(self, "]", depth_lvl + 2); + + print_indented!(self, "}", depth_lvl + 1); + } + PatKind::Or { pats } => { + print_indented!(self, "Or {", depth_lvl + 1); + print_indented!(self, "pats: [", depth_lvl + 2); + for pat in pats.iter() { + self.print_pat(pat, depth_lvl + 3); + } + print_indented!(self, "]", depth_lvl + 2); + print_indented!(self, "}", depth_lvl + 1); + } + } + + print_indented!(self, "}", depth_lvl); + } + + fn print_guard(&mut self, guard: &Guard<'tcx>, depth_lvl: usize) { + print_indented!(self, "Guard {", depth_lvl); + + match guard { + Guard::If(expr_id) => { + print_indented!(self, "If (", depth_lvl + 1); + self.print_expr(*expr_id, depth_lvl + 2); + print_indented!(self, ")", depth_lvl + 1); + } + Guard::IfLet(pat, expr_id) => { + print_indented!(self, "IfLet (", depth_lvl + 1); + self.print_pat(pat, depth_lvl + 2); + print_indented!(self, ",", depth_lvl + 1); + self.print_expr(*expr_id, depth_lvl + 2); + print_indented!(self, ")", depth_lvl + 1); + } + } + + print_indented!(self, "}", depth_lvl); + } + + fn print_closure_expr(&mut self, expr: &ClosureExpr<'tcx>, depth_lvl: usize) { + let ClosureExpr { closure_id, substs, upvars, movability, fake_reads } = expr; + + print_indented!(self, "ClosureExpr {", depth_lvl); + print_indented!(self, format!("closure_id: {:?}", closure_id), depth_lvl + 1); + print_indented!(self, format!("substs: {:?}", substs), depth_lvl + 1); + + if upvars.len() > 0 { + print_indented!(self, "upvars: [", depth_lvl + 1); + for upvar in upvars.iter() { + self.print_expr(*upvar, depth_lvl + 2); + print_indented!(self, ",", depth_lvl + 1); + } + print_indented!(self, "]", depth_lvl + 1); + } else { + print_indented!(self, "upvars: []", depth_lvl + 1); + } + + print_indented!(self, format!("movability: {:?}", movability), depth_lvl + 1); + + if fake_reads.len() > 0 { + print_indented!(self, "fake_reads: [", depth_lvl + 1); + for (fake_read_expr, cause, hir_id) in fake_reads.iter() { + print_indented!(self, "(", depth_lvl + 2); + self.print_expr(*fake_read_expr, depth_lvl + 3); + print_indented!(self, ",", depth_lvl + 2); + print_indented!(self, format!("cause: {:?}", cause), depth_lvl + 3); + print_indented!(self, ",", depth_lvl + 2); + print_indented!(self, format!("hir_id: {:?}", hir_id), depth_lvl + 3); + print_indented!(self, "),", depth_lvl + 2); + } + print_indented!(self, "]", depth_lvl + 1); + } else { + print_indented!(self, "fake_reads: []", depth_lvl + 1); + } + + print_indented!(self, "}", depth_lvl); + } + + fn print_inline_asm_expr(&mut self, expr: &InlineAsmExpr<'tcx>, depth_lvl: usize) { + let InlineAsmExpr { template, operands, options, line_spans } = expr; + + print_indented!(self, "InlineAsmExpr {", depth_lvl); + + print_indented!(self, "template: [", depth_lvl + 1); + for template_piece in template.iter() { + print_indented!(self, format!("{:?}", template_piece), depth_lvl + 2); + } + print_indented!(self, "]", depth_lvl + 1); + + print_indented!(self, "operands: [", depth_lvl + 1); + for operand in operands.iter() { + self.print_inline_operand(operand, depth_lvl + 2); + } + print_indented!(self, "]", depth_lvl + 1); + + print_indented!(self, format!("options: {:?}", options), depth_lvl + 1); + print_indented!(self, format!("line_spans: {:?}", line_spans), depth_lvl + 1); + } + + fn print_inline_operand(&mut self, operand: &InlineAsmOperand<'tcx>, depth_lvl: usize) { + match operand { + InlineAsmOperand::In { reg, expr } => { + print_indented!(self, "InlineAsmOperand::In {", depth_lvl); + print_indented!(self, format!("reg: {:?}", reg), depth_lvl + 1); + print_indented!(self, "expr: ", depth_lvl + 1); + self.print_expr(*expr, depth_lvl + 2); + print_indented!(self, "}", depth_lvl + 1); + } + InlineAsmOperand::Out { reg, late, expr } => { + print_indented!(self, "InlineAsmOperand::Out {", depth_lvl); + print_indented!(self, format!("reg: {:?}", reg), depth_lvl + 1); + print_indented!(self, format!("late: {:?}", late), depth_lvl + 1); + + if let Some(out) = expr { + print_indented!(self, "place: Some( ", depth_lvl + 1); + self.print_expr(*out, depth_lvl + 2); + print_indented!(self, ")", depth_lvl + 1); + } else { + print_indented!(self, "place: None", depth_lvl + 1); + } + print_indented!(self, "}", depth_lvl + 1); + } + InlineAsmOperand::InOut { reg, late, expr } => { + print_indented!(self, "InlineAsmOperand::InOut {", depth_lvl); + print_indented!(self, format!("reg: {:?}", reg), depth_lvl + 1); + print_indented!(self, format!("late: {:?}", late), depth_lvl + 1); + print_indented!(self, "expr: ", depth_lvl + 1); + self.print_expr(*expr, depth_lvl + 2); + print_indented!(self, "}", depth_lvl + 1); + } + InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => { + print_indented!(self, "InlineAsmOperand::SplitInOut {", depth_lvl); + print_indented!(self, format!("reg: {:?}", reg), depth_lvl + 1); + print_indented!(self, format!("late: {:?}", late), depth_lvl + 1); + print_indented!(self, "in_expr: ", depth_lvl + 1); + self.print_expr(*in_expr, depth_lvl + 2); + + if let Some(out_expr) = out_expr { + print_indented!(self, "out_expr: Some( ", depth_lvl + 1); + self.print_expr(*out_expr, depth_lvl + 2); + print_indented!(self, ")", depth_lvl + 1); + } else { + print_indented!(self, "out_expr: None", depth_lvl + 1); + } + + print_indented!(self, "}", depth_lvl + 1); + } + InlineAsmOperand::Const { value, span } => { + print_indented!(self, "InlineAsmOperand::Const {", depth_lvl); + print_indented!(self, format!("value: {:?}", value), depth_lvl + 1); + print_indented!(self, format!("span: {:?}", span), depth_lvl + 1); + print_indented!(self, "}", depth_lvl + 1); + } + InlineAsmOperand::SymFn { value, span } => { + print_indented!(self, "InlineAsmOperand::SymFn {", depth_lvl); + print_indented!(self, format!("value: {:?}", *value), depth_lvl + 1); + print_indented!(self, format!("span: {:?}", span), depth_lvl + 1); + print_indented!(self, "}", depth_lvl + 1); + } + InlineAsmOperand::SymStatic { def_id } => { + print_indented!(self, "InlineAsmOperand::SymStatic {", depth_lvl); + print_indented!(self, format!("def_id: {:?}", def_id), depth_lvl + 1); + print_indented!(self, "}", depth_lvl + 1); + } + } + } +} diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index d3d667f68407f..3d6da7fe792e7 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -90,11 +90,11 @@ pub struct AdtDefData { /// The `DefId` of the struct, enum or union item. pub did: DefId, /// Variants of the ADT. If this is a struct or union, then there will be a single variant. - variants: IndexVec, + pub(crate) variants: IndexVec, /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?). - flags: AdtFlags, + pub(crate) flags: AdtFlags, /// Repr options provided by the user. - repr: ReprOptions, + pub(crate) repr: ReprOptions, } impl PartialOrd for AdtDefData { diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index 9daf68a15f4b1..76d537946044c 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -439,6 +439,10 @@ fn construct_fn<'tcx>( let fn_id = tcx.hir().local_def_id_to_hir_id(fn_def.did); let generator_kind = tcx.generator_kind(fn_def.did); + // The representation of thir for `-Zunpretty=thir-tree` relies on + // the entry expression being the last element of `thir.exprs`. + assert_eq!(expr.as_usize(), thir.exprs.len() - 1); + // Figure out what primary body this item has. let body_id = tcx.hir().body_owned_by(fn_def.did); let span_with_body = tcx.hir().span_with_body(fn_id); diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index a355e1bdab5f5..52ecc67524b73 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -54,7 +54,10 @@ pub(crate) fn thir_body( pub(crate) fn thir_tree(tcx: TyCtxt<'_>, owner_def: ty::WithOptConstParam) -> String { match thir_body(tcx, owner_def) { - Ok((thir, _)) => format!("{:#?}", thir.steal()), + Ok((thir, _)) => { + let thir = thir.steal(); + tcx.thir_tree_representation(&thir) + } Err(_) => "error".into(), } } From d7f59e91e09037c3a0b6721f4f50081ee15e405a Mon Sep 17 00:00:00 2001 From: Jakob Degen Date: Thu, 26 Jan 2023 03:29:28 -0800 Subject: [PATCH 376/500] Custom mir: Add support for some remaining, easy to support constructs --- .../src/build/custom/parse/instruction.rs | 14 ++++++++++++++ library/core/src/intrinsics/mir.rs | 10 ++++++++-- .../custom/arrays.arrays.built.after.mir | 14 ++++++++++++++ tests/mir-opt/building/custom/arrays.rs | 19 +++++++++++++++++++ tests/mir-opt/building/custom/enums.rs | 1 + .../custom/enums.set_discr.built.after.mir | 5 +++-- .../custom/operators.f.built.after.mir | 8 ++++++-- tests/mir-opt/building/custom/operators.rs | 3 +++ 8 files changed, 68 insertions(+), 6 deletions(-) create mode 100644 tests/mir-opt/building/custom/arrays.arrays.built.after.mir create mode 100644 tests/mir-opt/building/custom/arrays.rs diff --git a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs index 9840b95feefde..dbba529aef7a5 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs +++ b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs @@ -18,6 +18,9 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { @call("mir_storage_dead", args) => { Ok(StatementKind::StorageDead(self.parse_local(args[0])?)) }, + @call("mir_deinit", args) => { + Ok(StatementKind::Deinit(Box::new(self.parse_place(args[0])?))) + }, @call("mir_retag", args) => { Ok(StatementKind::Retag(RetagKind::Default, Box::new(self.parse_place(args[0])?))) }, @@ -141,6 +144,14 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { fn parse_rvalue(&self, expr_id: ExprId) -> PResult> { parse_by_kind!(self, expr_id, _, "rvalue", @call("mir_discriminant", args) => self.parse_place(args[0]).map(Rvalue::Discriminant), + @call("mir_checked", args) => { + parse_by_kind!(self, args[0], _, "binary op", + ExprKind::Binary { op, lhs, rhs } => Ok(Rvalue::CheckedBinaryOp( + *op, Box::new((self.parse_operand(*lhs)?, self.parse_operand(*rhs)?)) + )), + ) + }, + @call("mir_len", args) => Ok(Rvalue::Len(self.parse_place(args[0])?)), ExprKind::Borrow { borrow_kind, arg } => Ok( Rvalue::Ref(self.tcx.lifetimes.re_erased, *borrow_kind, self.parse_place(*arg)?) ), @@ -153,6 +164,9 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { ExprKind::Unary { op, arg } => Ok( Rvalue::UnaryOp(*op, self.parse_operand(*arg)?) ), + ExprKind::Repeat { value, count } => Ok( + Rvalue::Repeat(self.parse_operand(*value)?, *count) + ), _ => self.parse_operand(expr_id).map(Rvalue::Use), ) } diff --git a/library/core/src/intrinsics/mir.rs b/library/core/src/intrinsics/mir.rs index e3157b66902eb..3d7ccffa1735c 100644 --- a/library/core/src/intrinsics/mir.rs +++ b/library/core/src/intrinsics/mir.rs @@ -211,13 +211,16 @@ //! //! #### Statements //! - Assign statements work via normal Rust assignment. -//! - [`Retag`] statements have an associated function. +//! - [`Retag`], [`StorageLive`], [`StorageDead`], [`Deinit`] statements have an associated function. //! //! #### Rvalues //! //! - Operands implicitly convert to `Use` rvalues. //! - `&`, `&mut`, `addr_of!`, and `addr_of_mut!` all work to create their associated rvalue. -//! - [`Discriminant`] has an associated function. +//! - [`Discriminant`] and [`Len`] have associated functions. +//! - Unary and binary operations use their normal Rust syntax - `a * b`, `!c`, etc. +//! - Checked binary operations are represented by wrapping the associated binop in [`Checked`]. +//! - Array repetition syntax (`[foo; 10]`) creates the associated rvalue. //! //! #### Terminators //! @@ -261,6 +264,9 @@ define!("mir_drop_and_replace", fn DropAndReplace(place: T, value: T, goto: B define!("mir_call", fn Call(place: T, goto: BasicBlock, call: T)); define!("mir_storage_live", fn StorageLive(local: T)); define!("mir_storage_dead", fn StorageDead(local: T)); +define!("mir_deinit", fn Deinit(place: T)); +define!("mir_checked", fn Checked(binop: T) -> (T, bool)); +define!("mir_len", fn Len(place: T) -> usize); define!("mir_retag", fn Retag(place: T)); define!("mir_move", fn Move(place: T) -> T); define!("mir_static", fn Static(s: T) -> &'static T); diff --git a/tests/mir-opt/building/custom/arrays.arrays.built.after.mir b/tests/mir-opt/building/custom/arrays.arrays.built.after.mir new file mode 100644 index 0000000000000..4c92127288596 --- /dev/null +++ b/tests/mir-opt/building/custom/arrays.arrays.built.after.mir @@ -0,0 +1,14 @@ +// MIR for `arrays` after built + +fn arrays() -> usize { + let mut _0: usize; // return place in scope 0 at $DIR/arrays.rs:+0:32: +0:37 + let mut _1: [i32; C]; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + let mut _2: usize; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + + bb0: { + _1 = [const 5_i32; C]; // scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + _2 = Len(_1); // scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + _0 = _2; // scope 0 at $DIR/arrays.rs:+4:9: +4:16 + return; // scope 0 at $DIR/arrays.rs:+5:9: +5:17 + } +} diff --git a/tests/mir-opt/building/custom/arrays.rs b/tests/mir-opt/building/custom/arrays.rs new file mode 100644 index 0000000000000..8e0a1fd7a4390 --- /dev/null +++ b/tests/mir-opt/building/custom/arrays.rs @@ -0,0 +1,19 @@ +#![feature(custom_mir, core_intrinsics, inline_const)] + +extern crate core; +use core::intrinsics::mir::*; + +// EMIT_MIR arrays.arrays.built.after.mir +#[custom_mir(dialect = "built")] +fn arrays() -> usize { + mir!({ + let x = [5_i32; C]; + let c = Len(x); + RET = c; + Return() + }) +} + +fn main() { + assert_eq!(arrays::<20>(), 20); +} diff --git a/tests/mir-opt/building/custom/enums.rs b/tests/mir-opt/building/custom/enums.rs index e5cd456377844..eca5b792ec0a2 100644 --- a/tests/mir-opt/building/custom/enums.rs +++ b/tests/mir-opt/building/custom/enums.rs @@ -86,6 +86,7 @@ fn switch_option_repr(option: Bool) -> bool { #[custom_mir(dialect = "runtime", phase = "initial")] fn set_discr(option: &mut Option<()>) { mir!({ + Deinit(*option); SetDiscriminant(*option, 0); Return() }) diff --git a/tests/mir-opt/building/custom/enums.set_discr.built.after.mir b/tests/mir-opt/building/custom/enums.set_discr.built.after.mir index 7de9ed0983fe8..6d07473658ace 100644 --- a/tests/mir-opt/building/custom/enums.set_discr.built.after.mir +++ b/tests/mir-opt/building/custom/enums.set_discr.built.after.mir @@ -4,7 +4,8 @@ fn set_discr(_1: &mut Option<()>) -> () { let mut _0: (); // return place in scope 0 at $DIR/enums.rs:+0:39: +0:39 bb0: { - discriminant((*_1)) = 0; // scope 0 at $DIR/enums.rs:+2:9: +2:36 - return; // scope 0 at $DIR/enums.rs:+3:9: +3:17 + Deinit((*_1)); // scope 0 at $DIR/enums.rs:+2:9: +2:24 + discriminant((*_1)) = 0; // scope 0 at $DIR/enums.rs:+3:9: +3:36 + return; // scope 0 at $DIR/enums.rs:+4:9: +4:17 } } diff --git a/tests/mir-opt/building/custom/operators.f.built.after.mir b/tests/mir-opt/building/custom/operators.f.built.after.mir index a0c5f1b40dbb7..cb43d5e6ed7c7 100644 --- a/tests/mir-opt/building/custom/operators.f.built.after.mir +++ b/tests/mir-opt/building/custom/operators.f.built.after.mir @@ -2,6 +2,7 @@ fn f(_1: i32, _2: bool) -> i32 { let mut _0: i32; // return place in scope 0 at $DIR/operators.rs:+0:30: +0:33 + let mut _3: (i32, bool); // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL bb0: { _1 = Neg(_1); // scope 0 at $DIR/operators.rs:+2:9: +2:15 @@ -20,7 +21,10 @@ fn f(_1: i32, _2: bool) -> i32 { _2 = Le(_1, _1); // scope 0 at $DIR/operators.rs:+15:9: +15:19 _2 = Ge(_1, _1); // scope 0 at $DIR/operators.rs:+16:9: +16:19 _2 = Gt(_1, _1); // scope 0 at $DIR/operators.rs:+17:9: +17:18 - _0 = _1; // scope 0 at $DIR/operators.rs:+18:9: +18:16 - return; // scope 0 at $DIR/operators.rs:+19:9: +19:17 + _3 = CheckedAdd(_1, _1); // scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + _2 = (_3.1: bool); // scope 0 at $DIR/operators.rs:+19:9: +19:18 + _1 = (_3.0: i32); // scope 0 at $DIR/operators.rs:+20:9: +20:18 + _0 = _1; // scope 0 at $DIR/operators.rs:+21:9: +21:16 + return; // scope 0 at $DIR/operators.rs:+22:9: +22:17 } } diff --git a/tests/mir-opt/building/custom/operators.rs b/tests/mir-opt/building/custom/operators.rs index 51f80c66392a1..db7a48317d928 100644 --- a/tests/mir-opt/building/custom/operators.rs +++ b/tests/mir-opt/building/custom/operators.rs @@ -22,6 +22,9 @@ pub fn f(a: i32, b: bool) -> i32 { b = a <= a; b = a >= a; b = a > a; + let res = Checked(a + a); + b = res.1; + a = res.0; RET = a; Return() }) From f8aaf9aadb12c599eb20679cc141ce7c7c253c3a Mon Sep 17 00:00:00 2001 From: Jakob Degen Date: Thu, 26 Jan 2023 03:50:37 -0800 Subject: [PATCH 377/500] Disable ConstGoto opt in cleanup blocks --- compiler/rustc_mir_transform/src/const_goto.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/compiler/rustc_mir_transform/src/const_goto.rs b/compiler/rustc_mir_transform/src/const_goto.rs index 40eefda4f0763..da101ca7ad279 100644 --- a/compiler/rustc_mir_transform/src/const_goto.rs +++ b/compiler/rustc_mir_transform/src/const_goto.rs @@ -57,6 +57,15 @@ impl<'tcx> MirPass<'tcx> for ConstGoto { } impl<'tcx> Visitor<'tcx> for ConstGotoOptimizationFinder<'_, 'tcx> { + fn visit_basic_block_data(&mut self, block: BasicBlock, data: &BasicBlockData<'tcx>) { + if data.is_cleanup { + // Because of the restrictions around control flow in cleanup blocks, we don't perform + // this optimization at all in such blocks. + return; + } + self.super_basic_block_data(block, data); + } + fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) { let _: Option<_> = try { let target = terminator.kind.as_goto()?; From 347fa7a26f3eb6085418a26cef18f133635f7a9f Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 26 Jan 2023 14:30:28 +0400 Subject: [PATCH 378/500] rustdoc: Stop using `HirId`s Use `LocalDefId`s instead --- src/librustdoc/clean/mod.rs | 36 ++++---- src/librustdoc/clean/types.rs | 16 +--- src/librustdoc/doctest.rs | 26 +++--- src/librustdoc/html/markdown.rs | 44 +++------- .../passes/calculate_doc_coverage.rs | 8 +- .../passes/check_doc_test_visibility.rs | 19 +++-- .../passes/collect_intra_doc_links.rs | 11 +-- .../passes/lint/check_code_block_syntax.rs | 5 +- src/librustdoc/passes/propagate_doc_cfg.rs | 17 ++-- src/librustdoc/visit_ast.rs | 82 ++++++++++--------- 10 files changed, 113 insertions(+), 151 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 34a7068e5da53..3cb6ad10e72b8 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -15,7 +15,7 @@ use rustc_attr as attr; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, IndexEntry}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; -use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LOCAL_CRATE}; +use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId, LOCAL_CRATE}; use rustc_hir::PredicateOrigin; use rustc_hir_analysis::hir_ty_to_ty; use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData}; @@ -116,7 +116,8 @@ pub(crate) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext< } }); - Item::from_hir_id_and_parts(doc.id, Some(doc.name), ModuleItem(Module { items, span }), cx) + let kind = ModuleItem(Module { items, span }); + Item::from_def_id_and_parts(doc.def_id.to_def_id(), Some(doc.name), kind, cx) } fn clean_generic_bound<'tcx>( @@ -2067,12 +2068,12 @@ struct OneLevelVisitor<'hir> { map: rustc_middle::hir::map::Map<'hir>, item: Option<&'hir hir::Item<'hir>>, looking_for: Ident, - target_hir_id: hir::HirId, + target_def_id: LocalDefId, } impl<'hir> OneLevelVisitor<'hir> { - fn new(map: rustc_middle::hir::map::Map<'hir>, target_hir_id: hir::HirId) -> Self { - Self { map, item: None, looking_for: Ident::empty(), target_hir_id } + fn new(map: rustc_middle::hir::map::Map<'hir>, target_def_id: LocalDefId) -> Self { + Self { map, item: None, looking_for: Ident::empty(), target_def_id } } fn reset(&mut self, looking_for: Ident) { @@ -2092,7 +2093,7 @@ impl<'hir> hir::intravisit::Visitor<'hir> for OneLevelVisitor<'hir> { if self.item.is_none() && item.ident == self.looking_for && matches!(item.kind, hir::ItemKind::Use(_, _)) - || item.hir_id() == self.target_hir_id + || item.owner_id.def_id == self.target_def_id { self.item = Some(item); } @@ -2106,11 +2107,11 @@ impl<'hir> hir::intravisit::Visitor<'hir> for OneLevelVisitor<'hir> { fn get_all_import_attributes<'hir>( mut item: &hir::Item<'hir>, tcx: TyCtxt<'hir>, - target_hir_id: hir::HirId, + target_def_id: LocalDefId, attributes: &mut Vec, ) { let hir_map = tcx.hir(); - let mut visitor = OneLevelVisitor::new(hir_map, target_hir_id); + let mut visitor = OneLevelVisitor::new(hir_map, target_def_id); // If the item is an import and has at least a path with two parts, we go into it. while let hir::ItemKind::Use(path, _) = item.kind && path.segments.len() > 1 && @@ -2138,7 +2139,7 @@ fn clean_maybe_renamed_item<'tcx>( cx: &mut DocContext<'tcx>, item: &hir::Item<'tcx>, renamed: Option, - import_id: Option, + import_id: Option, ) -> Vec { use hir::ItemKind; @@ -2183,7 +2184,7 @@ fn clean_maybe_renamed_item<'tcx>( generics: clean_generics(generics, cx), fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(), }), - ItemKind::Impl(impl_) => return clean_impl(impl_, item.hir_id(), cx), + ItemKind::Impl(impl_) => return clean_impl(impl_, item.owner_id.def_id, cx), // proc macros can have a name set by attributes ItemKind::Fn(ref sig, generics, body_id) => { clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx) @@ -2218,10 +2219,10 @@ fn clean_maybe_renamed_item<'tcx>( let mut extra_attrs = Vec::new(); if let Some(hir::Node::Item(use_node)) = - import_id.and_then(|hir_id| cx.tcx.hir().find(hir_id)) + import_id.and_then(|def_id| cx.tcx.hir().find_by_def_id(def_id)) { // We get all the various imports' attributes. - get_all_import_attributes(use_node, cx.tcx, item.hir_id(), &mut extra_attrs); + get_all_import_attributes(use_node, cx.tcx, item.owner_id.def_id, &mut extra_attrs); } if !extra_attrs.is_empty() { @@ -2244,12 +2245,12 @@ fn clean_maybe_renamed_item<'tcx>( fn clean_variant<'tcx>(variant: &hir::Variant<'tcx>, cx: &mut DocContext<'tcx>) -> Item { let kind = VariantItem(clean_variant_data(&variant.data, &variant.disr_expr, cx)); - Item::from_hir_id_and_parts(variant.hir_id, Some(variant.ident.name), kind, cx) + Item::from_def_id_and_parts(variant.def_id.to_def_id(), Some(variant.ident.name), kind, cx) } fn clean_impl<'tcx>( impl_: &hir::Impl<'tcx>, - hir_id: hir::HirId, + def_id: LocalDefId, cx: &mut DocContext<'tcx>, ) -> Vec { let tcx = cx.tcx; @@ -2260,7 +2261,6 @@ fn clean_impl<'tcx>( .iter() .map(|ii| clean_impl_item(tcx.hir().impl_item(ii.id), cx)) .collect::>(); - let def_id = tcx.hir().local_def_id(hir_id); // If this impl block is an implementation of the Deref trait, then we // need to try inlining the target's inherent impl blocks as well. @@ -2289,7 +2289,7 @@ fn clean_impl<'tcx>( ImplKind::Normal }, })); - Item::from_hir_id_and_parts(hir_id, None, kind, cx) + Item::from_def_id_and_parts(def_id.to_def_id(), None, kind, cx) }; if let Some(type_alias) = type_alias { ret.push(make_item(trait_.clone(), type_alias, items.clone())); @@ -2510,8 +2510,8 @@ fn clean_maybe_renamed_foreign_item<'tcx>( hir::ForeignItemKind::Type => ForeignTypeItem, }; - Item::from_hir_id_and_parts( - item.hir_id(), + Item::from_def_id_and_parts( + item.owner_id.def_id.to_def_id(), Some(renamed.unwrap_or(item.ident.name)), kind, cx, diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index a020ccd53b842..3b258c4d919f8 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -439,17 +439,6 @@ impl Item { self.attrs.doc_value() } - /// Convenience wrapper around [`Self::from_def_id_and_parts`] which converts - /// `hir_id` to a [`DefId`] - pub(crate) fn from_hir_id_and_parts( - hir_id: hir::HirId, - name: Option, - kind: ItemKind, - cx: &mut DocContext<'_>, - ) -> Item { - Item::from_def_id_and_parts(cx.tcx.hir().local_def_id(hir_id).to_def_id(), name, kind, cx) - } - pub(crate) fn from_def_id_and_parts( def_id: DefId, name: Option, @@ -2416,10 +2405,7 @@ impl ConstantKind { pub(crate) fn is_literal(&self, tcx: TyCtxt<'_>) -> bool { match *self { - ConstantKind::TyConst { .. } => false, - ConstantKind::Extern { def_id } => def_id.as_local().map_or(false, |def_id| { - is_literal_expr(tcx, tcx.hir().local_def_id_to_hir_id(def_id)) - }), + ConstantKind::TyConst { .. } | ConstantKind::Extern { .. } => false, ConstantKind::Local { body, .. } | ConstantKind::Anonymous { body } => { is_literal_expr(tcx, body.hir_id) } diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index c1a652c75f4a1..37a1005cba1fc 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -2,10 +2,8 @@ use rustc_ast as ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::sync::Lrc; use rustc_errors::{ColorConfig, ErrorGuaranteed, FatalError}; -use rustc_hir as hir; -use rustc_hir::def_id::LOCAL_CRATE; -use rustc_hir::intravisit; -use rustc_hir::{HirId, CRATE_HIR_ID}; +use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::{self as hir, intravisit, CRATE_HIR_ID}; use rustc_interface::interface; use rustc_middle::hir::map::Map; use rustc_middle::hir::nested_filter; @@ -140,7 +138,7 @@ pub(crate) fn run(options: RustdocOptions) -> Result<(), ErrorGuaranteed> { }; hir_collector.visit_testable( "".to_string(), - CRATE_HIR_ID, + CRATE_DEF_ID, tcx.hir().span(CRATE_HIR_ID), |this| tcx.hir().walk_toplevel_module(this), ); @@ -1214,11 +1212,11 @@ impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> { fn visit_testable( &mut self, name: String, - hir_id: HirId, + def_id: LocalDefId, sp: Span, nested: F, ) { - let ast_attrs = self.tcx.hir().attrs(hir_id); + let ast_attrs = self.tcx.hir().attrs(self.tcx.hir().local_def_id_to_hir_id(def_id)); if let Some(ref cfg) = ast_attrs.cfg(self.tcx, &FxHashSet::default()) { if !cfg.matches(&self.sess.parse_sess, Some(self.tcx.features())) { return; @@ -1247,7 +1245,7 @@ impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> { self.collector.enable_per_target_ignores, Some(&crate::html::markdown::ExtraInfo::new( self.tcx, - hir_id, + def_id.to_def_id(), span_of_attrs(&attrs).unwrap_or(sp), )), ); @@ -1276,37 +1274,37 @@ impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> _ => item.ident.to_string(), }; - self.visit_testable(name, item.hir_id(), item.span, |this| { + self.visit_testable(name, item.owner_id.def_id, item.span, |this| { intravisit::walk_item(this, item); }); } fn visit_trait_item(&mut self, item: &'hir hir::TraitItem<'_>) { - self.visit_testable(item.ident.to_string(), item.hir_id(), item.span, |this| { + self.visit_testable(item.ident.to_string(), item.owner_id.def_id, item.span, |this| { intravisit::walk_trait_item(this, item); }); } fn visit_impl_item(&mut self, item: &'hir hir::ImplItem<'_>) { - self.visit_testable(item.ident.to_string(), item.hir_id(), item.span, |this| { + self.visit_testable(item.ident.to_string(), item.owner_id.def_id, item.span, |this| { intravisit::walk_impl_item(this, item); }); } fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem<'_>) { - self.visit_testable(item.ident.to_string(), item.hir_id(), item.span, |this| { + self.visit_testable(item.ident.to_string(), item.owner_id.def_id, item.span, |this| { intravisit::walk_foreign_item(this, item); }); } fn visit_variant(&mut self, v: &'hir hir::Variant<'_>) { - self.visit_testable(v.ident.to_string(), v.hir_id, v.span, |this| { + self.visit_testable(v.ident.to_string(), v.def_id, v.span, |this| { intravisit::walk_variant(this, v); }); } fn visit_field_def(&mut self, f: &'hir hir::FieldDef<'_>) { - self.visit_testable(f.ident.to_string(), f.hir_id, f.span, |this| { + self.visit_testable(f.ident.to_string(), f.def_id, f.span, |this| { intravisit::walk_field_def(this, f); }); } diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 4ff67fe1551dd..33bff01b64fed 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -27,7 +27,6 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::DefId; -use rustc_hir::HirId; use rustc_middle::ty::TyCtxt; use rustc_span::edition::Edition; use rustc_span::{Span, Symbol}; @@ -784,45 +783,26 @@ pub(crate) fn find_testable_code( } pub(crate) struct ExtraInfo<'tcx> { - id: ExtraInfoId, + def_id: DefId, sp: Span, tcx: TyCtxt<'tcx>, } -enum ExtraInfoId { - Hir(HirId), - Def(DefId), -} - impl<'tcx> ExtraInfo<'tcx> { - pub(crate) fn new(tcx: TyCtxt<'tcx>, hir_id: HirId, sp: Span) -> ExtraInfo<'tcx> { - ExtraInfo { id: ExtraInfoId::Hir(hir_id), sp, tcx } - } - - pub(crate) fn new_did(tcx: TyCtxt<'tcx>, did: DefId, sp: Span) -> ExtraInfo<'tcx> { - ExtraInfo { id: ExtraInfoId::Def(did), sp, tcx } + pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: DefId, sp: Span) -> ExtraInfo<'tcx> { + ExtraInfo { def_id, sp, tcx } } fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) { - let hir_id = match self.id { - ExtraInfoId::Hir(hir_id) => hir_id, - ExtraInfoId::Def(item_did) => { - match item_did.as_local() { - Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did), - None => { - // If non-local, no need to check anything. - return; - } - } - } - }; - self.tcx.struct_span_lint_hir( - crate::lint::INVALID_CODEBLOCK_ATTRIBUTES, - hir_id, - self.sp, - msg, - |lint| lint.help(help), - ); + if let Some(def_id) = self.def_id.as_local() { + self.tcx.struct_span_lint_hir( + crate::lint::INVALID_CODEBLOCK_ATTRIBUTES, + self.tcx.hir().local_def_id_to_hir_id(def_id), + self.sp, + msg, + |lint| lint.help(help), + ); + } } } diff --git a/src/librustdoc/passes/calculate_doc_coverage.rs b/src/librustdoc/passes/calculate_doc_coverage.rs index 02b2278960869..0b22f943dab99 100644 --- a/src/librustdoc/passes/calculate_doc_coverage.rs +++ b/src/librustdoc/passes/calculate_doc_coverage.rs @@ -216,13 +216,7 @@ impl<'a, 'b> DocVisitor for CoverageCalculator<'a, 'b> { ); let has_doc_example = tests.found_tests != 0; - // The `expect_def_id()` should be okay because `local_def_id_to_hir_id` - // would presumably panic if a fake `DefIndex` were passed. - let hir_id = self - .ctx - .tcx - .hir() - .local_def_id_to_hir_id(i.item_id.expect_def_id().expect_local()); + let hir_id = DocContext::as_local_hir_id(self.ctx.tcx, i.item_id).unwrap(); let (level, source) = self.ctx.tcx.lint_level_at_node(MISSING_DOCS, hir_id); // In case we have: diff --git a/src/librustdoc/passes/check_doc_test_visibility.rs b/src/librustdoc/passes/check_doc_test_visibility.rs index 6aa2dda980cf3..f3961d5017ef4 100644 --- a/src/librustdoc/passes/check_doc_test_visibility.rs +++ b/src/librustdoc/passes/check_doc_test_visibility.rs @@ -14,8 +14,8 @@ use crate::visit::DocVisitor; use crate::visit_ast::inherits_doc_hidden; use rustc_hir as hir; use rustc_middle::lint::LintLevelSource; +use rustc_middle::ty::DefIdTree; use rustc_session::lint; -use rustc_span::symbol::sym; pub(crate) const CHECK_DOC_TEST_VISIBILITY: Pass = Pass { name: "check_doc_test_visibility", @@ -79,11 +79,11 @@ pub(crate) fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) - // The `expect_def_id()` should be okay because `local_def_id_to_hir_id` // would presumably panic if a fake `DefIndex` were passed. - let hir_id = cx.tcx.hir().local_def_id_to_hir_id(item.item_id.expect_def_id().expect_local()); + let def_id = item.item_id.expect_def_id().expect_local(); // check if parent is trait impl - if let Some(parent_hir_id) = cx.tcx.hir().opt_parent_id(hir_id) { - if let Some(parent_node) = cx.tcx.hir().find(parent_hir_id) { + if let Some(parent_def_id) = cx.tcx.opt_local_parent(def_id) { + if let Some(parent_node) = cx.tcx.hir().find_by_def_id(parent_def_id) { if matches!( parent_node, hir::Node::Item(hir::Item { @@ -96,13 +96,16 @@ pub(crate) fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) - } } - if cx.tcx.hir().attrs(hir_id).lists(sym::doc).has_word(sym::hidden) - || inherits_doc_hidden(cx.tcx, hir_id) - || cx.tcx.hir().span(hir_id).in_derive_expansion() + if cx.tcx.is_doc_hidden(def_id.to_def_id()) + || inherits_doc_hidden(cx.tcx, def_id) + || cx.tcx.def_span(def_id.to_def_id()).in_derive_expansion() { return false; } - let (level, source) = cx.tcx.lint_level_at_node(crate::lint::MISSING_DOC_CODE_EXAMPLES, hir_id); + let (level, source) = cx.tcx.lint_level_at_node( + crate::lint::MISSING_DOC_CODE_EXAMPLES, + cx.tcx.hir().local_def_id_to_hir_id(def_id), + ); level != lint::Level::Allow || matches!(source, LintLevelSource::Default) } diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 075951312a639..e42921c080945 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -1194,14 +1194,9 @@ impl LinkCollector<'_, '_> { } // item can be non-local e.g. when using #[doc(primitive = "pointer")] - if let Some((src_id, dst_id)) = id - .as_local() - // The `expect_def_id()` should be okay because `local_def_id_to_hir_id` - // would presumably panic if a fake `DefIndex` were passed. - .and_then(|dst_id| { - item.item_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id)) - }) - { + if let Some((src_id, dst_id)) = id.as_local().and_then(|dst_id| { + item.item_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id)) + }) { if self.cx.tcx.effective_visibilities(()).is_exported(src_id) && !self.cx.tcx.effective_visibilities(()).is_exported(dst_id) { diff --git a/src/librustdoc/passes/lint/check_code_block_syntax.rs b/src/librustdoc/passes/lint/check_code_block_syntax.rs index 7158355ffdacc..03be5e7997167 100644 --- a/src/librustdoc/passes/lint/check_code_block_syntax.rs +++ b/src/librustdoc/passes/lint/check_code_block_syntax.rs @@ -19,8 +19,7 @@ use crate::passes::source_span_for_markdown_range; pub(crate) fn visit_item(cx: &DocContext<'_>, item: &clean::Item) { if let Some(dox) = &item.attrs.collapsed_doc_value() { let sp = item.attr_span(cx.tcx); - let extra = - crate::html::markdown::ExtraInfo::new_did(cx.tcx, item.item_id.expect_def_id(), sp); + let extra = crate::html::markdown::ExtraInfo::new(cx.tcx, item.item_id.expect_def_id(), sp); for code_block in markdown::rust_code_blocks(dox, &extra) { check_rust_syntax(cx, item, dox, code_block); } @@ -73,7 +72,6 @@ fn check_rust_syntax( return; }; - let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_id); let empty_block = code_block.lang_string == Default::default() && code_block.is_fenced; let is_ignore = code_block.lang_string.ignore != markdown::Ignore::None; @@ -93,6 +91,7 @@ fn check_rust_syntax( // Finally build and emit the completed diagnostic. // All points of divergence have been handled earlier so this can be // done the same way whether the span is precise or not. + let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_id); cx.tcx.struct_span_lint_hir(crate::lint::INVALID_RUST_CODEBLOCKS, hir_id, sp, msg, |lint| { let explanation = if is_ignore { "`ignore` code blocks require valid Rust code for syntax highlighting; \ diff --git a/src/librustdoc/passes/propagate_doc_cfg.rs b/src/librustdoc/passes/propagate_doc_cfg.rs index de3a4b3390595..a4bc486900b3e 100644 --- a/src/librustdoc/passes/propagate_doc_cfg.rs +++ b/src/librustdoc/passes/propagate_doc_cfg.rs @@ -9,6 +9,7 @@ use crate::fold::DocFolder; use crate::passes::Pass; use rustc_hir::def_id::LocalDefId; +use rustc_middle::ty::DefIdTree; pub(crate) const PROPAGATE_DOC_CFG: Pass = Pass { name: "propagate-doc-cfg", @@ -41,24 +42,22 @@ impl<'a, 'tcx> CfgPropagator<'a, 'tcx> { let Some(def_id) = item.item_id.as_def_id().and_then(|def_id| def_id.as_local()) else { return }; - let hir = self.cx.tcx.hir(); - let hir_id = hir.local_def_id_to_hir_id(def_id); - if check_parent { - let expected_parent = hir.get_parent_item(hir_id); + let expected_parent = self.cx.tcx.opt_local_parent(def_id); // If parents are different, it means that `item` is a reexport and we need // to compute the actual `cfg` by iterating through its "real" parents. - if self.parent == Some(expected_parent.def_id) { + if self.parent.is_some() && self.parent == expected_parent { return; } } let mut attrs = Vec::new(); - for (parent_hir_id, _) in hir.parent_iter(hir_id) { - if let Some(def_id) = hir.opt_local_def_id(parent_hir_id) { - attrs.extend_from_slice(load_attrs(self.cx, def_id.to_def_id())); - } + let mut next_def_id = def_id; + while let Some(parent_def_id) = self.cx.tcx.opt_local_parent(next_def_id) { + attrs.extend_from_slice(load_attrs(self.cx, parent_def_id.to_def_id())); + next_def_id = parent_def_id; } + let (_, cfg) = merge_attrs(self.cx, None, item.attrs.other_attrs.as_slice(), Some(&attrs)); item.cfg = cfg; } diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 00ea6ca4152c8..a89d6fa83983d 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -4,9 +4,9 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{DefId, DefIdMap}; -use rustc_hir::{HirIdSet, Node, CRATE_HIR_ID}; -use rustc_middle::ty::TyCtxt; +use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, LocalDefIdSet}; +use rustc_hir::{Node, CRATE_HIR_ID}; +use rustc_middle::ty::{DefIdTree, TyCtxt}; use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE}; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; @@ -23,19 +23,26 @@ pub(crate) struct Module<'hir> { pub(crate) name: Symbol, pub(crate) where_inner: Span, pub(crate) mods: Vec>, - pub(crate) id: hir::HirId, + pub(crate) def_id: LocalDefId, // (item, renamed, import_id) - pub(crate) items: Vec<(&'hir hir::Item<'hir>, Option, Option)>, + pub(crate) items: Vec<(&'hir hir::Item<'hir>, Option, Option)>, pub(crate) foreigns: Vec<(&'hir hir::ForeignItem<'hir>, Option)>, } impl Module<'_> { - pub(crate) fn new(name: Symbol, id: hir::HirId, where_inner: Span) -> Self { - Module { name, id, where_inner, mods: Vec::new(), items: Vec::new(), foreigns: Vec::new() } + pub(crate) fn new(name: Symbol, def_id: LocalDefId, where_inner: Span) -> Self { + Module { + name, + def_id, + where_inner, + mods: Vec::new(), + items: Vec::new(), + foreigns: Vec::new(), + } } pub(crate) fn where_outer(&self, tcx: TyCtxt<'_>) -> Span { - tcx.hir().span(self.id) + tcx.def_span(self.def_id) } } @@ -46,10 +53,10 @@ fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec { std::iter::once(crate_name).chain(relative).collect() } -pub(crate) fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: hir::HirId) -> bool { - while let Some(id) = tcx.hir().get_enclosing_scope(node) { +pub(crate) fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: LocalDefId) -> bool { + while let Some(id) = tcx.opt_local_parent(node) { node = id; - if tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) { + if tcx.is_doc_hidden(node.to_def_id()) { return true; } } @@ -61,7 +68,7 @@ pub(crate) fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: hir::HirId) -> bool pub(crate) struct RustdocVisitor<'a, 'tcx> { cx: &'a mut core::DocContext<'tcx>, - view_item_stack: HirIdSet, + view_item_stack: LocalDefIdSet, inlining: bool, /// Are the current module and all of its parents public? inside_public_path: bool, @@ -71,8 +78,8 @@ pub(crate) struct RustdocVisitor<'a, 'tcx> { impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { pub(crate) fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> { // If the root is re-exported, terminate all recursion. - let mut stack = HirIdSet::default(); - stack.insert(hir::CRATE_HIR_ID); + let mut stack = LocalDefIdSet::default(); + stack.insert(CRATE_DEF_ID); RustdocVisitor { cx, view_item_stack: stack, @@ -89,7 +96,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { pub(crate) fn visit(mut self) -> Module<'tcx> { let mut top_level_module = self.visit_mod_contents( - hir::CRATE_HIR_ID, + CRATE_DEF_ID, self.cx.tcx.hir().root_module(), self.cx.tcx.crate_name(LOCAL_CRATE), None, @@ -152,16 +159,15 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { fn visit_mod_contents( &mut self, - id: hir::HirId, + def_id: LocalDefId, m: &'tcx hir::Mod<'tcx>, name: Symbol, - parent_id: Option, + parent_id: Option, ) -> Module<'tcx> { - let mut om = Module::new(name, id, m.spans.inner_span); - let def_id = self.cx.tcx.hir().local_def_id(id).to_def_id(); + let mut om = Module::new(name, def_id, m.spans.inner_span); // Keep track of if there were any private modules in the path. let orig_inside_public_path = self.inside_public_path; - self.inside_public_path &= self.cx.tcx.visibility(def_id).is_public(); + self.inside_public_path &= self.cx.tcx.local_visibility(def_id).is_public(); for &i in m.item_ids { let item = self.cx.tcx.hir().item(i); if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) { @@ -193,7 +199,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { /// Returns `true` if the target has been inlined. fn maybe_inline_local( &mut self, - id: hir::HirId, + def_id: LocalDefId, res: Res, renamed: Option, glob: bool, @@ -211,10 +217,10 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { return false; }; - let use_attrs = tcx.hir().attrs(id); + let use_attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(def_id)); // Don't inline `doc(hidden)` imports so they can be stripped at a later stage. let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline) - || use_attrs.lists(sym::doc).has_word(sym::hidden); + || tcx.is_doc_hidden(def_id.to_def_id()); // For cross-crate impl inlining we need to know whether items are // reachable in documentation -- a previously unreachable item can be @@ -225,37 +231,39 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { return false; } - let res_hir_id = match res_did.as_local() { - Some(n) => tcx.hir().local_def_id_to_hir_id(n), - None => return false, + let Some(res_did) = res_did.as_local() else { + return false; }; - let is_private = - !self.cx.cache.effective_visibilities.is_directly_public(self.cx.tcx, res_did); - let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id); + let is_private = !self + .cx + .cache + .effective_visibilities + .is_directly_public(self.cx.tcx, res_did.to_def_id()); + let is_hidden = inherits_doc_hidden(self.cx.tcx, res_did); // Only inline if requested or if the item would otherwise be stripped. if (!please_inline && !is_private && !is_hidden) || is_no_inline { return false; } - if !self.view_item_stack.insert(res_hir_id) { + if !self.view_item_stack.insert(res_did) { return false; } - let ret = match tcx.hir().get(res_hir_id) { + let ret = match tcx.hir().get_by_def_id(res_did) { Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => { let prev = mem::replace(&mut self.inlining, true); for &i in m.item_ids { let i = self.cx.tcx.hir().item(i); - self.visit_item(i, None, om, Some(id)); + self.visit_item(i, None, om, Some(def_id)); } self.inlining = prev; true } Node::Item(it) if !glob => { let prev = mem::replace(&mut self.inlining, true); - self.visit_item(it, renamed, om, Some(id)); + self.visit_item(it, renamed, om, Some(def_id)); self.inlining = prev; true } @@ -267,7 +275,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { } _ => false, }; - self.view_item_stack.remove(&res_hir_id); + self.view_item_stack.remove(&res_did); ret } @@ -276,7 +284,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { item: &'tcx hir::Item<'_>, renamed: Option, om: &mut Module<'tcx>, - parent_id: Option, + parent_id: Option, ) { debug!("visiting item {:?}", item); let name = renamed.unwrap_or(item.ident.name); @@ -321,7 +329,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { let is_glob = kind == hir::UseKind::Glob; let ident = if is_glob { None } else { Some(name) }; if self.maybe_inline_local( - item.hir_id(), + item.owner_id.def_id, res, ident, is_glob, @@ -356,7 +364,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { } } hir::ItemKind::Mod(ref m) => { - om.mods.push(self.visit_mod_contents(item.hir_id(), m, name, parent_id)); + om.mods.push(self.visit_mod_contents(item.owner_id.def_id, m, name, parent_id)); } hir::ItemKind::Fn(..) | hir::ItemKind::ExternCrate(..) From 8f84408697dfa95fd3b6367094105b959969702e Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Thu, 26 Jan 2023 14:13:35 +0100 Subject: [PATCH 379/500] also document hidden items --- src/bootstrap/doc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/doc.rs b/src/bootstrap/doc.rs index 5d5a808200d91..7f8aa2573ddb3 100644 --- a/src/bootstrap/doc.rs +++ b/src/bootstrap/doc.rs @@ -598,7 +598,7 @@ fn doc_std( .arg(&builder.version) .args(extra_args); if builder.config.library_docs_private_items { - cargo.arg("--document-private-items"); + cargo.arg("--document-private-items").arg("--document-hidden-items"); } builder.run(&mut cargo.into()); }; From 4441753127733dae478d6d25dc95798eef1f1a71 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Fri, 20 Jan 2023 09:54:07 +0100 Subject: [PATCH 380/500] Mark Rust 1.67 as released in the changelog --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3cb880df57b0..e2cde09776f4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,13 +4,13 @@ All notable changes to this project will be documented in this file. See [Changelog Update](book/src/development/infrastructure/changelog_update.md) if you want to update this document. -## Unreleased / In Rust Nightly +## Unreleased / Beta / In Rust Nightly [d822110d...master](https://github.com/rust-lang/rust-clippy/compare/d822110d...master) ## Rust 1.67 -Current beta, released 2023-01-26 +Current stable, released 2023-01-26 [4f142aa1...d822110d](https://github.com/rust-lang/rust-clippy/compare/4f142aa1...d822110d) @@ -203,7 +203,7 @@ Current beta, released 2023-01-26 ## Rust 1.66 -Current stable, released 2022-12-15 +Released 2022-12-15 [b52fb523...4f142aa1](https://github.com/rust-lang/rust-clippy/compare/b52fb523...4f142aa1) From ac3ec77f0726daef011cfd6e44a4a52b1ef89803 Mon Sep 17 00:00:00 2001 From: chansuke Date: Fri, 27 Jan 2023 01:21:21 +0900 Subject: [PATCH 381/500] Fix woriding from `rustbuild` to `bootstrap` --- src/bootstrap/bootstrap.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index 9cf43fc7a2193..abdd12127d366 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -712,7 +712,7 @@ def bootstrap_binary(self): def build_bootstrap(self, color): """Build bootstrap""" - print("Building rustbuild") + print("Building bootstrap") build_dir = os.path.join(self.build_dir, "bootstrap") if self.clean and os.path.exists(build_dir): shutil.rmtree(build_dir) From 3bce66f786685b74fbeb7eae53ccf6283fded994 Mon Sep 17 00:00:00 2001 From: b-naber Date: Tue, 17 Jan 2023 22:11:18 +0100 Subject: [PATCH 382/500] add test --- tests/ui/thir-tree-match.rs | 23 +++ tests/ui/thir-tree-match.stdout | 342 ++++++++++++++++++++++++++++++++ tests/ui/thir-tree.stdout | 95 ++++----- 3 files changed, 406 insertions(+), 54 deletions(-) create mode 100644 tests/ui/thir-tree-match.rs create mode 100644 tests/ui/thir-tree-match.stdout diff --git a/tests/ui/thir-tree-match.rs b/tests/ui/thir-tree-match.rs new file mode 100644 index 0000000000000..a5511ec95437f --- /dev/null +++ b/tests/ui/thir-tree-match.rs @@ -0,0 +1,23 @@ +// check-pass +// compile-flags: -Zunpretty=thir-tree + +enum Bar { + First, + Second, + Third, +} + +enum Foo { + FooOne(Bar), + FooTwo, +} + +fn has_match(foo: Foo) -> bool { + match foo { + Foo::FooOne(Bar::First) => true, + Foo::FooOne(_) => false, + Foo::FooTwo => true, + } +} + +fn main() {} diff --git a/tests/ui/thir-tree-match.stdout b/tests/ui/thir-tree-match.stdout new file mode 100644 index 0000000000000..d6174ec262a44 --- /dev/null +++ b/tests/ui/thir-tree-match.stdout @@ -0,0 +1,342 @@ +DefId(0:16 ~ thir_tree_match[3c9a]::has_match): +params: [ + Param { + ty: Foo + ty_span: Some($DIR/thir-tree-match.rs:15:19: 15:22 (#0)) + self_kind: None + hir_id: Some(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).1)) + param: Some( + Pat: { + ty: Foo + span: $DIR/thir-tree-match.rs:15:14: 15:17 (#0) + kind: PatKind { + Binding { + mutability: Not + name: "foo" + mode: ByValue + var: LocalVarId(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).2)) + ty: Foo + is_primary: true + subpattern: None + } + } + } + ) + } +] +body: + Expr { + ty: bool + temp_lifetime: Some(Node(26)) + span: $DIR/thir-tree-match.rs:15:32: 21:2 (#0) + kind: + Scope { + region_scope: Destruction(26) + lint_level: Inherited + value: + Expr { + ty: bool + temp_lifetime: Some(Node(26)) + span: $DIR/thir-tree-match.rs:15:32: 21:2 (#0) + kind: + Scope { + region_scope: Node(26) + lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).26)) + value: + Expr { + ty: bool + temp_lifetime: Some(Node(26)) + span: $DIR/thir-tree-match.rs:15:32: 21:2 (#0) + kind: + Block { + targeted_by_break: false + opt_destruction_scope: None + span: $DIR/thir-tree-match.rs:15:32: 21:2 (#0) + region_scope: Node(25) + safety_mode: Safe + stmts: [] + expr: + Expr { + ty: bool + temp_lifetime: Some(Node(26)) + span: $DIR/thir-tree-match.rs:16:5: 20:6 (#0) + kind: + Scope { + region_scope: Node(3) + lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).3)) + value: + Expr { + ty: bool + temp_lifetime: Some(Node(26)) + span: $DIR/thir-tree-match.rs:16:5: 20:6 (#0) + kind: + Match { + scrutinee: + Expr { + ty: Foo + temp_lifetime: Some(Node(26)) + span: $DIR/thir-tree-match.rs:16:11: 16:14 (#0) + kind: + Scope { + region_scope: Node(4) + lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).4)) + value: + Expr { + ty: Foo + temp_lifetime: Some(Node(26)) + span: $DIR/thir-tree-match.rs:16:11: 16:14 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).2)) + } + } + } + } + arms: [ + Arm { + pattern: + Pat: { + ty: Foo + span: $DIR/thir-tree-match.rs:17:9: 17:32 (#0) + kind: PatKind { + Variant { + adt_def: + AdtDef { + did: DefId(0:10 ~ thir_tree_match[3c9a]::Foo) + variants: [VariantDef { def_id: DefId(0:11 ~ thir_tree_match[3c9a]::Foo::FooOne), ctor: Some((Fn, DefId(0:12 ~ thir_tree_match[3c9a]::Foo::FooOne::{constructor#0}))), name: "FooOne", discr: Relative(0), fields: [FieldDef { did: DefId(0:13 ~ thir_tree_match[3c9a]::Foo::FooOne::0), name: "0", vis: Restricted(DefId(0:0 ~ thir_tree_match[3c9a])) }], flags: NO_VARIANT_FLAGS }, VariantDef { def_id: DefId(0:14 ~ thir_tree_match[3c9a]::Foo::FooTwo), ctor: Some((Const, DefId(0:15 ~ thir_tree_match[3c9a]::Foo::FooTwo::{constructor#0}))), name: "FooTwo", discr: Relative(1), fields: [], flags: NO_VARIANT_FLAGS }] + flags: IS_ENUM + repr: ReprOptions { int: None, align: None, pack: None, flags: (empty), field_shuffle_seed: 11573694388057581 } + substs: [] + variant_index: 0 + subpatterns: [ + Pat: { + ty: Bar + span: $DIR/thir-tree-match.rs:17:21: 17:31 (#0) + kind: PatKind { + Variant { + adt_def: + AdtDef { + did: DefId(0:3 ~ thir_tree_match[3c9a]::Bar) + variants: [VariantDef { def_id: DefId(0:4 ~ thir_tree_match[3c9a]::Bar::First), ctor: Some((Const, DefId(0:5 ~ thir_tree_match[3c9a]::Bar::First::{constructor#0}))), name: "First", discr: Relative(0), fields: [], flags: NO_VARIANT_FLAGS }, VariantDef { def_id: DefId(0:6 ~ thir_tree_match[3c9a]::Bar::Second), ctor: Some((Const, DefId(0:7 ~ thir_tree_match[3c9a]::Bar::Second::{constructor#0}))), name: "Second", discr: Relative(1), fields: [], flags: NO_VARIANT_FLAGS }, VariantDef { def_id: DefId(0:8 ~ thir_tree_match[3c9a]::Bar::Third), ctor: Some((Const, DefId(0:9 ~ thir_tree_match[3c9a]::Bar::Third::{constructor#0}))), name: "Third", discr: Relative(2), fields: [], flags: NO_VARIANT_FLAGS }] + flags: IS_ENUM + repr: ReprOptions { int: None, align: None, pack: None, flags: (empty), field_shuffle_seed: 3125160937860410723 } + substs: [] + variant_index: 0 + subpatterns: [] + } + } + } + ] + } + } + } + guard: None + body: + Expr { + ty: bool + temp_lifetime: Some(Node(13)) + span: $DIR/thir-tree-match.rs:17:36: 17:40 (#0) + kind: + Scope { + region_scope: Destruction(13) + lint_level: Inherited + value: + Expr { + ty: bool + temp_lifetime: Some(Node(13)) + span: $DIR/thir-tree-match.rs:17:36: 17:40 (#0) + kind: + Scope { + region_scope: Node(13) + lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).13)) + value: + Expr { + ty: bool + temp_lifetime: Some(Node(13)) + span: $DIR/thir-tree-match.rs:17:36: 17:40 (#0) + kind: + Literal( lit: Spanned { node: Bool(true), span: $DIR/thir-tree-match.rs:17:36: 17:40 (#0) }, neg: false) + + } + } + } + } + } + lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).12)) + scope: Node(12) + span: $DIR/thir-tree-match.rs:17:9: 17:40 (#0) + } + Arm { + pattern: + Pat: { + ty: Foo + span: $DIR/thir-tree-match.rs:18:9: 18:23 (#0) + kind: PatKind { + Variant { + adt_def: + AdtDef { + did: DefId(0:10 ~ thir_tree_match[3c9a]::Foo) + variants: [VariantDef { def_id: DefId(0:11 ~ thir_tree_match[3c9a]::Foo::FooOne), ctor: Some((Fn, DefId(0:12 ~ thir_tree_match[3c9a]::Foo::FooOne::{constructor#0}))), name: "FooOne", discr: Relative(0), fields: [FieldDef { did: DefId(0:13 ~ thir_tree_match[3c9a]::Foo::FooOne::0), name: "0", vis: Restricted(DefId(0:0 ~ thir_tree_match[3c9a])) }], flags: NO_VARIANT_FLAGS }, VariantDef { def_id: DefId(0:14 ~ thir_tree_match[3c9a]::Foo::FooTwo), ctor: Some((Const, DefId(0:15 ~ thir_tree_match[3c9a]::Foo::FooTwo::{constructor#0}))), name: "FooTwo", discr: Relative(1), fields: [], flags: NO_VARIANT_FLAGS }] + flags: IS_ENUM + repr: ReprOptions { int: None, align: None, pack: None, flags: (empty), field_shuffle_seed: 11573694388057581 } + substs: [] + variant_index: 0 + subpatterns: [ + Pat: { + ty: Bar + span: $DIR/thir-tree-match.rs:18:21: 18:22 (#0) + kind: PatKind { + Wild + } + } + ] + } + } + } + guard: None + body: + Expr { + ty: bool + temp_lifetime: Some(Node(19)) + span: $DIR/thir-tree-match.rs:18:27: 18:32 (#0) + kind: + Scope { + region_scope: Destruction(19) + lint_level: Inherited + value: + Expr { + ty: bool + temp_lifetime: Some(Node(19)) + span: $DIR/thir-tree-match.rs:18:27: 18:32 (#0) + kind: + Scope { + region_scope: Node(19) + lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).19)) + value: + Expr { + ty: bool + temp_lifetime: Some(Node(19)) + span: $DIR/thir-tree-match.rs:18:27: 18:32 (#0) + kind: + Literal( lit: Spanned { node: Bool(false), span: $DIR/thir-tree-match.rs:18:27: 18:32 (#0) }, neg: false) + + } + } + } + } + } + lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).18)) + scope: Node(18) + span: $DIR/thir-tree-match.rs:18:9: 18:32 (#0) + } + Arm { + pattern: + Pat: { + ty: Foo + span: $DIR/thir-tree-match.rs:19:9: 19:20 (#0) + kind: PatKind { + Variant { + adt_def: + AdtDef { + did: DefId(0:10 ~ thir_tree_match[3c9a]::Foo) + variants: [VariantDef { def_id: DefId(0:11 ~ thir_tree_match[3c9a]::Foo::FooOne), ctor: Some((Fn, DefId(0:12 ~ thir_tree_match[3c9a]::Foo::FooOne::{constructor#0}))), name: "FooOne", discr: Relative(0), fields: [FieldDef { did: DefId(0:13 ~ thir_tree_match[3c9a]::Foo::FooOne::0), name: "0", vis: Restricted(DefId(0:0 ~ thir_tree_match[3c9a])) }], flags: NO_VARIANT_FLAGS }, VariantDef { def_id: DefId(0:14 ~ thir_tree_match[3c9a]::Foo::FooTwo), ctor: Some((Const, DefId(0:15 ~ thir_tree_match[3c9a]::Foo::FooTwo::{constructor#0}))), name: "FooTwo", discr: Relative(1), fields: [], flags: NO_VARIANT_FLAGS }] + flags: IS_ENUM + repr: ReprOptions { int: None, align: None, pack: None, flags: (empty), field_shuffle_seed: 11573694388057581 } + substs: [] + variant_index: 1 + subpatterns: [] + } + } + } + guard: None + body: + Expr { + ty: bool + temp_lifetime: Some(Node(24)) + span: $DIR/thir-tree-match.rs:19:24: 19:28 (#0) + kind: + Scope { + region_scope: Destruction(24) + lint_level: Inherited + value: + Expr { + ty: bool + temp_lifetime: Some(Node(24)) + span: $DIR/thir-tree-match.rs:19:24: 19:28 (#0) + kind: + Scope { + region_scope: Node(24) + lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).24)) + value: + Expr { + ty: bool + temp_lifetime: Some(Node(24)) + span: $DIR/thir-tree-match.rs:19:24: 19:28 (#0) + kind: + Literal( lit: Spanned { node: Bool(true), span: $DIR/thir-tree-match.rs:19:24: 19:28 (#0) }, neg: false) + + } + } + } + } + } + lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[3c9a]::has_match).23)) + scope: Node(23) + span: $DIR/thir-tree-match.rs:19:9: 19:28 (#0) + } + ] + } + } + } + } + } + } + } + } + } + } + + +DefId(0:17 ~ thir_tree_match[3c9a]::main): +params: [ +] +body: + Expr { + ty: () + temp_lifetime: Some(Node(2)) + span: $DIR/thir-tree-match.rs:23:11: 23:13 (#0) + kind: + Scope { + region_scope: Destruction(2) + lint_level: Inherited + value: + Expr { + ty: () + temp_lifetime: Some(Node(2)) + span: $DIR/thir-tree-match.rs:23:11: 23:13 (#0) + kind: + Scope { + region_scope: Node(2) + lint_level: Explicit(HirId(DefId(0:17 ~ thir_tree_match[3c9a]::main).2)) + value: + Expr { + ty: () + temp_lifetime: Some(Node(2)) + span: $DIR/thir-tree-match.rs:23:11: 23:13 (#0) + kind: + Block { + targeted_by_break: false + opt_destruction_scope: None + span: $DIR/thir-tree-match.rs:23:11: 23:13 (#0) + region_scope: Node(1) + safety_mode: Safe + stmts: [] + expr: [] + } + } + } + } + } + } + + diff --git a/tests/ui/thir-tree.stdout b/tests/ui/thir-tree.stdout index 4b6915f771526..0a35d9fb78ca2 100644 --- a/tests/ui/thir-tree.stdout +++ b/tests/ui/thir-tree.stdout @@ -1,56 +1,43 @@ DefId(0:3 ~ thir_tree[8f1d]::main): -Thir { - arms: [], - blocks: [ - Block { - targeted_by_break: false, - region_scope: Node(1), - opt_destruction_scope: None, - span: $DIR/thir-tree.rs:4:15: 4:17 (#0), - stmts: [], - expr: None, - safety_mode: Safe, - }, - ], - exprs: [ - Expr { - ty: (), - temp_lifetime: Some( - Node(2), - ), - span: $DIR/thir-tree.rs:4:15: 4:17 (#0), - kind: Block { - block: b0, - }, - }, - Expr { - ty: (), - temp_lifetime: Some( - Node(2), - ), - span: $DIR/thir-tree.rs:4:15: 4:17 (#0), - kind: Scope { - region_scope: Node(2), - lint_level: Explicit( - HirId(DefId(0:3 ~ thir_tree[8f1d]::main).2), - ), - value: e0, - }, - }, - Expr { - ty: (), - temp_lifetime: Some( - Node(2), - ), - span: $DIR/thir-tree.rs:4:15: 4:17 (#0), - kind: Scope { - region_scope: Destruction(2), - lint_level: Inherited, - value: e1, - }, - }, - ], - stmts: [], - params: [], -} +params: [ +] +body: + Expr { + ty: () + temp_lifetime: Some(Node(2)) + span: $DIR/thir-tree.rs:4:15: 4:17 (#0) + kind: + Scope { + region_scope: Destruction(2) + lint_level: Inherited + value: + Expr { + ty: () + temp_lifetime: Some(Node(2)) + span: $DIR/thir-tree.rs:4:15: 4:17 (#0) + kind: + Scope { + region_scope: Node(2) + lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree[8f1d]::main).2)) + value: + Expr { + ty: () + temp_lifetime: Some(Node(2)) + span: $DIR/thir-tree.rs:4:15: 4:17 (#0) + kind: + Block { + targeted_by_break: false + opt_destruction_scope: None + span: $DIR/thir-tree.rs:4:15: 4:17 (#0) + region_scope: Node(1) + safety_mode: Safe + stmts: [] + expr: [] + } + } + } + } + } + } + From 51df99f3c2bac3ee7158b115ff6d54b687d018e1 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Tue, 24 Jan 2023 15:39:59 -0700 Subject: [PATCH 383/500] rustdoc: use smarter encoding for playground URL The old way would compress okay with DEFLATE, but this version makes uncompressed docs smaller, which matters for memory usage and stuff like `cargo doc`. Try it out: In local testing, this change shrinks sample pages by anywhere between 4.0% and 0.031% $ du -b after.dir/std/vec/struct.Vec.html before.dir/std/vec/struct.Vec.html 759235 after.dir/std/vec/struct.Vec.html 781842 before.dir/std/vec/struct.Vec.html 100*((759235-781842)/781842)=-2.8 $ du -b after.dir/std/num/struct.Wrapping.html before.dir/std/num/struct.Wrapping.html 3194173 after.dir/std/num/struct.Wrapping.html 3204351 before.dir/std/num/struct.Wrapping.html 100*((3194173-3204351)/3204351)=-0.031 $ du -b after.dir/std/keyword.match.html before.dir/std/keyword.match.html 8151 after.dir/std/keyword.match.html 8495 before.dir/std/keyword.match.html 100*((8151-8495)/8495)=-4.0 Gzipped tarball sizes seem shrunk, but not by much. du -s before.tar.gz after.tar.gz 69600 before.tar.gz 69480 after.tar.gz 100*((69480-69600)/69600)=-0.17 --- src/librustdoc/html/markdown.rs | 19 ++++++++++++++++++- tests/rustdoc/playground-arg.rs | 2 +- tests/rustdoc/playground.rs | 6 +++--- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 4ff67fe1551dd..b1efbf4bdcaf7 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -296,7 +296,9 @@ impl<'a, I: Iterator>> Iterator for CodeBlocks<'_, 'a, I> { let channel = if test.contains("#![feature(") { "&version=nightly" } else { "" }; // These characters don't need to be escaped in a URI. - // FIXME: use a library function for percent encoding. + // See https://url.spec.whatwg.org/#query-percent-encode-set + // and https://url.spec.whatwg.org/#urlencoded-parsing + // and https://url.spec.whatwg.org/#url-code-points fn dont_escape(c: u8) -> bool { (b'a' <= c && c <= b'z') || (b'A' <= c && c <= b'Z') @@ -304,17 +306,32 @@ impl<'a, I: Iterator>> Iterator for CodeBlocks<'_, 'a, I> { || c == b'-' || c == b'_' || c == b'.' + || c == b',' || c == b'~' || c == b'!' || c == b'\'' || c == b'(' || c == b')' || c == b'*' + || c == b'/' + || c == b';' + || c == b':' + || c == b'?' + // As described in urlencoded-parsing, the + // first `=` is the one that separates key from + // value. Following `=`s are part of the value. + || c == b'=' } let mut test_escaped = String::new(); for b in test.bytes() { if dont_escape(b) { test_escaped.push(char::from(b)); + } else if b == b' ' { + // URL queries are decoded with + replaced with SP + test_escaped.push('+'); + } else if b == b'%' { + test_escaped.push('%'); + test_escaped.push('%'); } else { write!(test_escaped, "%{:02X}", b).unwrap(); } diff --git a/tests/rustdoc/playground-arg.rs b/tests/rustdoc/playground-arg.rs index 69c8962653931..f3811fe0b0ad1 100644 --- a/tests/rustdoc/playground-arg.rs +++ b/tests/rustdoc/playground-arg.rs @@ -10,4 +10,4 @@ pub fn dummy() {} // ensure that `extern crate foo;` was inserted into code snips automatically: -// @matches foo/index.html '//a[@class="test-arrow"][@href="https://example.com/?code=%23!%5Ballow(unused)%5D%0Aextern%20crate%20r%23foo%3B%0Afn%20main()%20%7B%0Ause%20foo%3A%3Adummy%3B%0Adummy()%3B%0A%7D&edition=2015"]' "Run" +// @matches foo/index.html '//a[@class="test-arrow"][@href="https://example.com/?code=%23!%5Ballow(unused)%5D%0Aextern+crate+r%23foo;%0Afn+main()+%7B%0Ause+foo::dummy;%0Adummy();%0A%7D&edition=2015"]' "Run" diff --git a/tests/rustdoc/playground.rs b/tests/rustdoc/playground.rs index 877ea1cfba15a..5c7fa33efc5e5 100644 --- a/tests/rustdoc/playground.rs +++ b/tests/rustdoc/playground.rs @@ -22,6 +22,6 @@ //! } //! ``` -// @matches foo/index.html '//a[@class="test-arrow"][@href="https://www.example.com/?code=%23!%5Ballow(unused)%5D%0Afn%20main()%20%7B%0A%20%20%20%20println!(%22Hello%2C%20world!%22)%3B%0A%7D&edition=2015"]' "Run" -// @matches foo/index.html '//a[@class="test-arrow"][@href="https://www.example.com/?code=%23!%5Ballow(unused)%5D%0Afn%20main()%20%7B%0Aprintln!(%22Hello%2C%20world!%22)%3B%0A%7D&edition=2015"]' "Run" -// @matches foo/index.html '//a[@class="test-arrow"][@href="https://www.example.com/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(something)%5D%0A%0Afn%20main()%20%7B%0A%20%20%20%20println!(%22Hello%2C%20world!%22)%3B%0A%7D&version=nightly&edition=2015"]' "Run" +// @matches foo/index.html '//a[@class="test-arrow"][@href="https://www.example.com/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0Aprintln!(%22Hello,+world!%22);%0A%7D&edition=2015"]' "Run" +// @matches foo/index.html '//a[@class="test-arrow"][@href="https://www.example.com/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++println!(%22Hello,+world!%22);%0A%7D&edition=2015"]' "Run" +// @matches foo/index.html '//a[@class="test-arrow"][@href="https://www.example.com/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(something)%5D%0A%0Afn+main()+%7B%0A++++println!(%22Hello,+world!%22);%0A%7D&version=nightly&edition=2015"]' "Run" From 97f8189614a5a6c52382e735dda55400c97cd8af Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Thu, 26 Jan 2023 12:50:14 -0700 Subject: [PATCH 384/500] rustdoc: remove mostly-unused CSS classes import/module-item --- src/librustdoc/html/render/print_item.rs | 4 ++-- src/librustdoc/html/static/css/rustdoc.css | 3 +-- tests/rustdoc-gui/label-next-to-symbol.goml | 8 ++++---- tests/rustdoc-gui/module-items-font.goml | 2 +- tests/rustdoc/cfg_doc_reexport.rs | 4 ++-- tests/rustdoc/deprecated.rs | 2 +- tests/rustdoc/doc-cfg.rs | 6 +++--- tests/rustdoc/duplicate-cfg.rs | 4 ++-- tests/rustdoc/glob-shadowing.rs | 2 +- tests/rustdoc/inline_cross/macros.rs | 4 ++-- tests/rustdoc/issue-32374.rs | 4 ++-- tests/rustdoc/issue-55364.rs | 4 ++-- tests/rustdoc/issue-95873.rs | 2 +- tests/rustdoc/reexport-check.rs | 4 ++-- 14 files changed, 26 insertions(+), 27 deletions(-) diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index f824c9e3ad2bd..61fba4ecddddf 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -391,7 +391,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: }; write!( w, - "

\ + "
\ {vis}{imp}\
\ {stab_tags_before}{stab_tags}{stab_tags_after}", @@ -437,7 +437,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: }; write!( w, - "
\ + "
\ {name}\ {visibility_emoji}\ {unsafety_flag}\ diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css index bf83ff2044e69..8699508e43916 100644 --- a/src/librustdoc/html/static/css/rustdoc.css +++ b/src/librustdoc/html/static/css/rustdoc.css @@ -977,8 +977,7 @@ so that we can apply CSS-filters to change the arrow color in themes */ 0 -1px 0 black; } -.module-item.unstable, -.import-item.unstable { +.item-left.unstable { opacity: 0.65; } diff --git a/tests/rustdoc-gui/label-next-to-symbol.goml b/tests/rustdoc-gui/label-next-to-symbol.goml index 05f8ddc716e87..3f4f65890b422 100644 --- a/tests/rustdoc-gui/label-next-to-symbol.goml +++ b/tests/rustdoc-gui/label-next-to-symbol.goml @@ -20,7 +20,7 @@ assert-css: ( // table like view assert-css: (".item-right.docblock-short", { "padding-left": "0px" }) compare-elements-position-near: ( - "//*[@class='item-left module-item']//a[text()='replaced_function']", + "//*[@class='item-left']//a[text()='replaced_function']", ".item-left .stab.deprecated", {"y": 2}, ) @@ -32,7 +32,7 @@ compare-elements-position: ( // Ensure no wrap compare-elements-position: ( - "//*[@class='item-left module-item']//a[text()='replaced_function']/..", + "//*[@class='item-left']//a[text()='replaced_function']/..", "//*[@class='item-right docblock-short'][text()='a thing with a label']", ("y"), ) @@ -43,7 +43,7 @@ size: (600, 600) // staggered layout with 2em spacing assert-css: (".item-right.docblock-short", { "padding-left": "32px" }) compare-elements-position-near: ( - "//*[@class='item-left module-item']//a[text()='replaced_function']", + "//*[@class='item-left']//a[text()='replaced_function']", ".item-left .stab.deprecated", {"y": 2}, ) @@ -55,7 +55,7 @@ compare-elements-position: ( // Ensure wrap compare-elements-position-false: ( - "//*[@class='item-left module-item']//a[text()='replaced_function']/..", + "//*[@class='item-left']//a[text()='replaced_function']/..", "//*[@class='item-right docblock-short'][text()='a thing with a label']", ("y"), ) diff --git a/tests/rustdoc-gui/module-items-font.goml b/tests/rustdoc-gui/module-items-font.goml index cd3676a987138..5940962a8ddba 100644 --- a/tests/rustdoc-gui/module-items-font.goml +++ b/tests/rustdoc-gui/module-items-font.goml @@ -1,7 +1,7 @@ // This test checks that the correct font is used on module items (in index.html pages). goto: "file://" + |DOC_PATH| + "/test_docs/index.html" assert-css: ( - ".item-table .module-item a", + ".item-table .item-left > a", {"font-family": '"Fira Sans", Arial, NanumBarunGothic, sans-serif'}, ALL, ) diff --git a/tests/rustdoc/cfg_doc_reexport.rs b/tests/rustdoc/cfg_doc_reexport.rs index addb6709db1da..89c7f0a6f342c 100644 --- a/tests/rustdoc/cfg_doc_reexport.rs +++ b/tests/rustdoc/cfg_doc_reexport.rs @@ -5,8 +5,8 @@ #![no_core] // @has 'foo/index.html' -// @has - '//*[@class="item-left module-item"]/*[@class="stab portability"]' 'foobar' -// @has - '//*[@class="item-left module-item"]/*[@class="stab portability"]' 'bar' +// @has - '//*[@class="item-left"]/*[@class="stab portability"]' 'foobar' +// @has - '//*[@class="item-left"]/*[@class="stab portability"]' 'bar' #[doc(cfg(feature = "foobar"))] mod imp_priv { diff --git a/tests/rustdoc/deprecated.rs b/tests/rustdoc/deprecated.rs index b3178da98eeb2..5cbe4d59108a4 100644 --- a/tests/rustdoc/deprecated.rs +++ b/tests/rustdoc/deprecated.rs @@ -1,4 +1,4 @@ -// @has deprecated/index.html '//*[@class="item-left module-item"]/span[@class="stab deprecated"]' \ +// @has deprecated/index.html '//*[@class="item-left"]/span[@class="stab deprecated"]' \ // 'Deprecated' // @has - '//*[@class="item-right docblock-short"]' 'Deprecated docs' diff --git a/tests/rustdoc/doc-cfg.rs b/tests/rustdoc/doc-cfg.rs index 4cddb0b76d410..1cfbfec6fcd30 100644 --- a/tests/rustdoc/doc-cfg.rs +++ b/tests/rustdoc/doc-cfg.rs @@ -12,7 +12,7 @@ pub struct Portable; // @has doc_cfg/unix_only/index.html \ // '//*[@id="main-content"]/*[@class="item-info"]/*[@class="stab portability"]' \ // 'Available on Unix only.' -// @matches - '//*[@class="item-left module-item"]//*[@class="stab portability"]' '\AARM\Z' +// @matches - '//*[@class="item-left"]//*[@class="stab portability"]' '\AARM\Z' // @count - '//*[@class="stab portability"]' 2 #[doc(cfg(unix))] pub mod unix_only { @@ -42,7 +42,7 @@ pub mod unix_only { // @has doc_cfg/wasi_only/index.html \ // '//*[@id="main-content"]/*[@class="item-info"]/*[@class="stab portability"]' \ // 'Available on WASI only.' -// @matches - '//*[@class="item-left module-item"]//*[@class="stab portability"]' '\AWebAssembly\Z' +// @matches - '//*[@class="item-left"]//*[@class="stab portability"]' '\AWebAssembly\Z' // @count - '//*[@class="stab portability"]' 2 #[doc(cfg(target_os = "wasi"))] pub mod wasi_only { @@ -74,7 +74,7 @@ pub mod wasi_only { // the portability header is different on the module view versus the full view // @has doc_cfg/index.html -// @matches - '//*[@class="item-left module-item"]//*[@class="stab portability"]' '\Aavx\Z' +// @matches - '//*[@class="item-left"]//*[@class="stab portability"]' '\Aavx\Z' // @has doc_cfg/fn.uses_target_feature.html // @has - '//*[@id="main-content"]/*[@class="item-info"]/*[@class="stab portability"]' \ diff --git a/tests/rustdoc/duplicate-cfg.rs b/tests/rustdoc/duplicate-cfg.rs index 18f3900b263b0..1ac2e52324964 100644 --- a/tests/rustdoc/duplicate-cfg.rs +++ b/tests/rustdoc/duplicate-cfg.rs @@ -2,8 +2,8 @@ #![feature(doc_cfg)] // @has 'foo/index.html' -// @matches '-' '//*[@class="item-left module-item"]//*[@class="stab portability"]' '^sync$' -// @has '-' '//*[@class="item-left module-item"]//*[@class="stab portability"]/@title' 'Available on crate feature `sync` only' +// @matches '-' '//*[@class="item-left"]//*[@class="stab portability"]' '^sync$' +// @has '-' '//*[@class="item-left"]//*[@class="stab portability"]/@title' 'Available on crate feature `sync` only' // @has 'foo/struct.Foo.html' // @has '-' '//*[@class="stab portability"]' 'sync' diff --git a/tests/rustdoc/glob-shadowing.rs b/tests/rustdoc/glob-shadowing.rs index 66a31c42bcfc7..2668b33349790 100644 --- a/tests/rustdoc/glob-shadowing.rs +++ b/tests/rustdoc/glob-shadowing.rs @@ -1,5 +1,5 @@ // @has 'glob_shadowing/index.html' -// @count - '//div[@class="item-left module-item"]' 6 +// @count - '//div[@class="item-left"]' 6 // @!has - '//div[@class="item-right docblock-short"]' 'sub1::describe' // @has - '//div[@class="item-right docblock-short"]' 'sub2::describe' diff --git a/tests/rustdoc/inline_cross/macros.rs b/tests/rustdoc/inline_cross/macros.rs index 5daa0d4baad63..d5b0de5725bce 100644 --- a/tests/rustdoc/inline_cross/macros.rs +++ b/tests/rustdoc/inline_cross/macros.rs @@ -6,9 +6,9 @@ extern crate macros; -// @has foo/index.html '//*[@class="item-left unstable deprecated module-item"]/span[@class="stab deprecated"]' \ +// @has foo/index.html '//*[@class="item-left unstable deprecated"]/span[@class="stab deprecated"]' \ // Deprecated -// @has - '//*[@class="item-left unstable deprecated module-item"]/span[@class="stab unstable"]' \ +// @has - '//*[@class="item-left unstable deprecated"]/span[@class="stab unstable"]' \ // Experimental // @has foo/macro.my_macro.html diff --git a/tests/rustdoc/issue-32374.rs b/tests/rustdoc/issue-32374.rs index 8d2c27cf3d77d..8296d7a81f2b1 100644 --- a/tests/rustdoc/issue-32374.rs +++ b/tests/rustdoc/issue-32374.rs @@ -2,9 +2,9 @@ #![doc(issue_tracker_base_url = "https://issue_url/")] #![unstable(feature = "test", issue = "32374")] -// @matches issue_32374/index.html '//*[@class="item-left unstable deprecated module-item"]/span[@class="stab deprecated"]' \ +// @matches issue_32374/index.html '//*[@class="item-left unstable deprecated"]/span[@class="stab deprecated"]' \ // 'Deprecated' -// @matches issue_32374/index.html '//*[@class="item-left unstable deprecated module-item"]/span[@class="stab unstable"]' \ +// @matches issue_32374/index.html '//*[@class="item-left unstable deprecated"]/span[@class="stab unstable"]' \ // 'Experimental' // @matches issue_32374/index.html '//*[@class="item-right docblock-short"]/text()' 'Docs' diff --git a/tests/rustdoc/issue-55364.rs b/tests/rustdoc/issue-55364.rs index 14a6f5041f208..b987da30ed290 100644 --- a/tests/rustdoc/issue-55364.rs +++ b/tests/rustdoc/issue-55364.rs @@ -29,8 +29,8 @@ pub mod subone { // @has - '//section[@id="main-content"]/details/div[@class="docblock"]//a[@href="../fn.foo.html"]' 'foo' // @has - '//section[@id="main-content"]/details/div[@class="docblock"]//a[@href="../fn.bar.html"]' 'bar' // Though there should be such links later -// @has - '//section[@id="main-content"]/div[@class="item-table"]//div[@class="item-left module-item"]/a[@class="fn"][@href="fn.foo.html"]' 'foo' -// @has - '//section[@id="main-content"]/div[@class="item-table"]//div[@class="item-left module-item"]/a[@class="fn"][@href="fn.bar.html"]' 'bar' +// @has - '//section[@id="main-content"]/div[@class="item-table"]//div[@class="item-left"]/a[@class="fn"][@href="fn.foo.html"]' 'foo' +// @has - '//section[@id="main-content"]/div[@class="item-table"]//div[@class="item-left"]/a[@class="fn"][@href="fn.bar.html"]' 'bar' /// See either [foo] or [bar]. pub mod subtwo { diff --git a/tests/rustdoc/issue-95873.rs b/tests/rustdoc/issue-95873.rs index ff33fb63a0bab..3df93eb7cf16f 100644 --- a/tests/rustdoc/issue-95873.rs +++ b/tests/rustdoc/issue-95873.rs @@ -1,2 +1,2 @@ -// @has issue_95873/index.html "//*[@class='item-left import-item']" "pub use ::std as x;" +// @has issue_95873/index.html "//*[@class='item-left']" "pub use ::std as x;" pub use ::std as x; diff --git a/tests/rustdoc/reexport-check.rs b/tests/rustdoc/reexport-check.rs index db1f90c699978..acac0c9919716 100644 --- a/tests/rustdoc/reexport-check.rs +++ b/tests/rustdoc/reexport-check.rs @@ -4,12 +4,12 @@ extern crate reexport_check; // @!has 'foo/index.html' '//code' 'pub use self::i32;' -// @has 'foo/index.html' '//div[@class="item-left deprecated module-item"]' 'i32' +// @has 'foo/index.html' '//div[@class="item-left deprecated"]' 'i32' // @has 'foo/i32/index.html' #[allow(deprecated, deprecated_in_future)] pub use std::i32; // @!has 'foo/index.html' '//code' 'pub use self::string::String;' -// @has 'foo/index.html' '//div[@class="item-left module-item"]' 'String' +// @has 'foo/index.html' '//div[@class="item-left"]' 'String' pub use std::string::String; // @has 'foo/index.html' '//div[@class="item-right docblock-short"]' 'Docs in original' From 9b5a2a4a4861500d64b9f1ebbe6c1140eda0a493 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 24 Jan 2023 21:43:21 +0000 Subject: [PATCH 385/500] Use new solver during selection --- .../src/traits/select/mod.rs | 57 ++++++++++++++----- 1 file changed, 43 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index f90da95d51668..1d23634b6aacf 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -38,6 +38,8 @@ use rustc_errors::Diagnostic; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_infer::infer::LateBoundRegionConversionTime; +use rustc_infer::traits::TraitEngine; +use rustc_infer::traits::TraitEngineExt; use rustc_middle::dep_graph::{DepKind, DepNodeIndex}; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::abstract_const::NotConstEvaluatable; @@ -47,6 +49,7 @@ use rustc_middle::ty::relate::TypeRelation; use rustc_middle::ty::SubstsRef; use rustc_middle::ty::{self, EarlyBinder, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate}; use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable, TypeVisitable}; +use rustc_session::config::TraitSolver; use rustc_span::symbol::sym; use std::cell::{Cell, RefCell}; @@ -544,10 +547,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligation: &PredicateObligation<'tcx>, ) -> Result { self.evaluation_probe(|this| { - this.evaluate_predicate_recursively( - TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()), - obligation.clone(), - ) + if this.tcx().sess.opts.unstable_opts.trait_solver != TraitSolver::Next { + this.evaluate_predicate_recursively( + TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()), + obligation.clone(), + ) + } else { + this.evaluate_predicates_recursively_in_new_solver([obligation.clone()]) + } }) } @@ -586,18 +593,40 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { where I: IntoIterator> + std::fmt::Debug, { - let mut result = EvaluatedToOk; - for obligation in predicates { - let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?; - if let EvaluatedToErr = eval { - // fast-path - EvaluatedToErr is the top of the lattice, - // so we don't need to look on the other predicates. - return Ok(EvaluatedToErr); - } else { - result = cmp::max(result, eval); + if self.tcx().sess.opts.unstable_opts.trait_solver != TraitSolver::Next { + let mut result = EvaluatedToOk; + for obligation in predicates { + let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?; + if let EvaluatedToErr = eval { + // fast-path - EvaluatedToErr is the top of the lattice, + // so we don't need to look on the other predicates. + return Ok(EvaluatedToErr); + } else { + result = cmp::max(result, eval); + } } + Ok(result) + } else { + self.evaluate_predicates_recursively_in_new_solver(predicates) } - Ok(result) + } + + /// Evaluates the predicates using the new solver when `-Ztrait-solver=next` is enabled + fn evaluate_predicates_recursively_in_new_solver( + &mut self, + predicates: impl IntoIterator>, + ) -> Result { + let mut fulfill_cx = crate::solve::FulfillmentCtxt::new(); + fulfill_cx.register_predicate_obligations(self.infcx, predicates); + // True errors + if !fulfill_cx.select_where_possible(self.infcx).is_empty() { + return Ok(EvaluatedToErr); + } + if !fulfill_cx.select_all_or_error(self.infcx).is_empty() { + return Ok(EvaluatedToAmbig); + } + // Regions and opaques are handled in the `evaluation_probe` by looking at the snapshot + Ok(EvaluatedToOk) } #[instrument( From 4ff674f94237a1a21c7a1c1f6801bf751de41cdf Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 25 Jan 2023 18:04:57 +0000 Subject: [PATCH 386/500] Intern CanonicalVarValues --- .../rustc_infer/src/infer/canonical/mod.rs | 15 ++--- .../src/infer/canonical/query_response.rs | 11 ++-- .../src/infer/canonical/substitute.rs | 7 +-- compiler/rustc_middle/src/infer/canonical.rs | 62 +++++++++---------- .../rustc_trait_selection/src/solve/mod.rs | 40 ++++++------ .../src/solve/search_graph/cache.rs | 1 + compiler/rustc_traits/src/chalk/mod.rs | 18 +++--- 7 files changed, 73 insertions(+), 81 deletions(-) diff --git a/compiler/rustc_infer/src/infer/canonical/mod.rs b/compiler/rustc_infer/src/infer/canonical/mod.rs index e59715b706b29..f7e3e4a1cc09e 100644 --- a/compiler/rustc_infer/src/infer/canonical/mod.rs +++ b/compiler/rustc_infer/src/infer/canonical/mod.rs @@ -26,7 +26,7 @@ use crate::infer::{InferCtxt, RegionVariableOrigin, TypeVariableOrigin, TypeVari use rustc_index::vec::IndexVec; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::subst::GenericArg; -use rustc_middle::ty::{self, BoundVar, List}; +use rustc_middle::ty::{self, List}; use rustc_span::source_map::Span; pub use rustc_middle::infer::canonical::*; @@ -87,12 +87,13 @@ impl<'tcx> InferCtxt<'tcx> { variables: &List>, universe_map: impl Fn(ty::UniverseIndex) -> ty::UniverseIndex, ) -> CanonicalVarValues<'tcx> { - let var_values: IndexVec> = variables - .iter() - .map(|info| self.instantiate_canonical_var(span, info, &universe_map)) - .collect(); - - CanonicalVarValues { var_values } + CanonicalVarValues { + var_values: self.tcx.mk_substs( + variables + .iter() + .map(|info| self.instantiate_canonical_var(span, info, &universe_map)), + ), + } } /// Given the "info" about a canonical variable, creates a fresh diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index 3d49182f0b817..98272708c1666 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -482,11 +482,8 @@ impl<'tcx> InferCtxt<'tcx> { // given variable in the loop above, use that. Otherwise, use // a fresh inference variable. let result_subst = CanonicalVarValues { - var_values: query_response - .variables - .iter() - .enumerate() - .map(|(index, info)| { + var_values: self.tcx.mk_substs(query_response.variables.iter().enumerate().map( + |(index, info)| { if info.is_existential() { match opt_values[BoundVar::new(index)] { Some(k) => k, @@ -499,8 +496,8 @@ impl<'tcx> InferCtxt<'tcx> { universe_map[u.as_usize()] }) } - }) - .collect(), + }, + )), }; let mut obligations = vec![]; diff --git a/compiler/rustc_infer/src/infer/canonical/substitute.rs b/compiler/rustc_infer/src/infer/canonical/substitute.rs index 389afe22eb767..e77f2d37b7dae 100644 --- a/compiler/rustc_infer/src/infer/canonical/substitute.rs +++ b/compiler/rustc_infer/src/infer/canonical/substitute.rs @@ -72,16 +72,15 @@ where value } else { let delegate = FnMutDelegate { - regions: &mut |br: ty::BoundRegion| match var_values.var_values[br.var].unpack() { + regions: &mut |br: ty::BoundRegion| match var_values[br.var].unpack() { GenericArgKind::Lifetime(l) => l, r => bug!("{:?} is a region but value is {:?}", br, r), }, - types: &mut |bound_ty: ty::BoundTy| match var_values.var_values[bound_ty.var].unpack() { + types: &mut |bound_ty: ty::BoundTy| match var_values[bound_ty.var].unpack() { GenericArgKind::Type(ty) => ty, r => bug!("{:?} is a type but value is {:?}", bound_ty, r), }, - consts: &mut |bound_ct: ty::BoundVar, _| match var_values.var_values[bound_ct].unpack() - { + consts: &mut |bound_ct: ty::BoundVar, _| match var_values[bound_ct].unpack() { GenericArgKind::Const(ct) => ct, c => bug!("{:?} is a const but value is {:?}", bound_ct, c), }, diff --git a/compiler/rustc_middle/src/infer/canonical.rs b/compiler/rustc_middle/src/infer/canonical.rs index 43583b5723e69..2247090c38c4a 100644 --- a/compiler/rustc_middle/src/infer/canonical.rs +++ b/compiler/rustc_middle/src/infer/canonical.rs @@ -25,10 +25,8 @@ use crate::infer::MemberConstraint; use crate::mir::ConstraintCategory; use crate::ty::subst::GenericArg; use crate::ty::{self, BoundVar, List, Region, Ty, TyCtxt}; -use rustc_index::vec::IndexVec; use rustc_macros::HashStable; use smallvec::SmallVec; -use std::iter; use std::ops::Index; /// A "canonicalized" type `V` is one where all free inference @@ -62,23 +60,23 @@ impl<'tcx> ty::TypeFoldable<'tcx> for CanonicalVarInfos<'tcx> { /// vectors with the original values that were replaced by canonical /// variables. You will need to supply it later to instantiate the /// canonicalized query response. -#[derive(Clone, Debug, PartialEq, Eq, Hash, TyDecodable, TyEncodable)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyDecodable, TyEncodable)] #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)] pub struct CanonicalVarValues<'tcx> { - pub var_values: IndexVec>, + pub var_values: ty::SubstsRef<'tcx>, } impl CanonicalVarValues<'_> { pub fn is_identity(&self) -> bool { - self.var_values.iter_enumerated().all(|(bv, arg)| match arg.unpack() { + self.var_values.iter().enumerate().all(|(bv, arg)| match arg.unpack() { ty::GenericArgKind::Lifetime(r) => { - matches!(*r, ty::ReLateBound(ty::INNERMOST, br) if br.var == bv) + matches!(*r, ty::ReLateBound(ty::INNERMOST, br) if br.var.as_usize() == bv) } ty::GenericArgKind::Type(ty) => { - matches!(*ty.kind(), ty::Bound(ty::INNERMOST, bt) if bt.var == bv) + matches!(*ty.kind(), ty::Bound(ty::INNERMOST, bt) if bt.var.as_usize() == bv) } ty::GenericArgKind::Const(ct) => { - matches!(ct.kind(), ty::ConstKind::Bound(ty::INNERMOST, bc) if bc == bv) + matches!(ct.kind(), ty::ConstKind::Bound(ty::INNERMOST, bc) if bc.as_usize() == bv) } }) } @@ -342,7 +340,7 @@ impl<'tcx> CanonicalVarValues<'tcx> { /// Creates dummy var values which should not be used in a /// canonical response. pub fn dummy() -> CanonicalVarValues<'tcx> { - CanonicalVarValues { var_values: Default::default() } + CanonicalVarValues { var_values: ty::List::empty() } } #[inline] @@ -360,36 +358,38 @@ impl<'tcx> CanonicalVarValues<'tcx> { use crate::ty::subst::GenericArgKind; CanonicalVarValues { - var_values: iter::zip(&self.var_values, 0..) - .map(|(kind, i)| match kind.unpack() { - GenericArgKind::Type(..) => { - tcx.mk_ty(ty::Bound(ty::INNERMOST, ty::BoundVar::from_u32(i).into())).into() - } - GenericArgKind::Lifetime(..) => { - let br = ty::BoundRegion { - var: ty::BoundVar::from_u32(i), - kind: ty::BrAnon(i, None), - }; - tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)).into() + var_values: tcx.mk_substs(self.var_values.iter().enumerate().map( + |(i, kind)| -> ty::GenericArg<'tcx> { + match kind.unpack() { + GenericArgKind::Type(..) => tcx + .mk_ty(ty::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i).into())) + .into(), + GenericArgKind::Lifetime(..) => { + let br = ty::BoundRegion { + var: ty::BoundVar::from_usize(i), + kind: ty::BrAnon(i as u32, None), + }; + tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)).into() + } + GenericArgKind::Const(ct) => tcx + .mk_const( + ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i)), + ct.ty(), + ) + .into(), } - GenericArgKind::Const(ct) => tcx - .mk_const( - ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_u32(i)), - ct.ty(), - ) - .into(), - }) - .collect(), + }, + )), } } } impl<'a, 'tcx> IntoIterator for &'a CanonicalVarValues<'tcx> { type Item = GenericArg<'tcx>; - type IntoIter = ::std::iter::Cloned<::std::slice::Iter<'a, GenericArg<'tcx>>>; + type IntoIter = ::std::iter::Copied<::std::slice::Iter<'a, GenericArg<'tcx>>>; fn into_iter(self) -> Self::IntoIter { - self.var_values.iter().cloned() + self.var_values.iter() } } @@ -397,6 +397,6 @@ impl<'tcx> Index for CanonicalVarValues<'tcx> { type Output = GenericArg<'tcx>; fn index(&self, value: BoundVar) -> &GenericArg<'tcx> { - &self.var_values[value] + &self.var_values[value.as_usize()] } } diff --git a/compiler/rustc_trait_selection/src/solve/mod.rs b/compiler/rustc_trait_selection/src/solve/mod.rs index f44648c95d742..1bd2f0fbda9ef 100644 --- a/compiler/rustc_trait_selection/src/solve/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/mod.rs @@ -13,8 +13,6 @@ // preserves universes and creates a unique var (in the highest universe) for each // appearance of a region. -// FIXME: `CanonicalVarValues` should be interned and `Copy`. - // FIXME: uses of `infcx.at` need to enable deferred projection equality once that's implemented. use std::mem; @@ -227,7 +225,7 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { let external_constraints = take_external_constraints(self.infcx)?; Ok(self.infcx.canonicalize_response(Response { - var_values: self.var_values.clone(), + var_values: self.var_values, external_constraints, certainty, })) @@ -483,26 +481,24 @@ pub(super) fn response_no_constraints<'tcx>( goal: Canonical<'tcx, impl Sized>, certainty: Certainty, ) -> QueryResult<'tcx> { - let var_values = goal - .variables - .iter() - .enumerate() - .map(|(i, info)| match info.kind { - CanonicalVarKind::Ty(_) | CanonicalVarKind::PlaceholderTy(_) => { - tcx.mk_ty(ty::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i).into())).into() - } - CanonicalVarKind::Region(_) | CanonicalVarKind::PlaceholderRegion(_) => { - let br = ty::BoundRegion { - var: ty::BoundVar::from_usize(i), - kind: ty::BrAnon(i as u32, None), - }; - tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)).into() + let var_values = + tcx.mk_substs(goal.variables.iter().enumerate().map(|(i, info)| -> ty::GenericArg<'tcx> { + match info.kind { + CanonicalVarKind::Ty(_) | CanonicalVarKind::PlaceholderTy(_) => { + tcx.mk_ty(ty::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i).into())).into() + } + CanonicalVarKind::Region(_) | CanonicalVarKind::PlaceholderRegion(_) => { + let br = ty::BoundRegion { + var: ty::BoundVar::from_usize(i), + kind: ty::BrAnon(i as u32, None), + }; + tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)).into() + } + CanonicalVarKind::Const(_, ty) | CanonicalVarKind::PlaceholderConst(_, ty) => tcx + .mk_const(ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i)), ty) + .into(), } - CanonicalVarKind::Const(_, ty) | CanonicalVarKind::PlaceholderConst(_, ty) => tcx - .mk_const(ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i)), ty) - .into(), - }) - .collect(); + })); Ok(Canonical { max_universe: goal.max_universe, diff --git a/compiler/rustc_trait_selection/src/solve/search_graph/cache.rs b/compiler/rustc_trait_selection/src/solve/search_graph/cache.rs index 730a8e6125887..80a388b8498b9 100644 --- a/compiler/rustc_trait_selection/src/solve/search_graph/cache.rs +++ b/compiler/rustc_trait_selection/src/solve/search_graph/cache.rs @@ -95,6 +95,7 @@ impl<'tcx> ProvisionalCache<'tcx> { } pub(super) fn provisional_result(&self, entry_index: EntryIndex) -> QueryResult<'tcx> { + // FIXME: Responses should probably be `Copy` as well self.entries[entry_index].response.clone() } } diff --git a/compiler/rustc_traits/src/chalk/mod.rs b/compiler/rustc_traits/src/chalk/mod.rs index f76386fa720df..13d83b9268941 100644 --- a/compiler/rustc_traits/src/chalk/mod.rs +++ b/compiler/rustc_traits/src/chalk/mod.rs @@ -8,13 +8,10 @@ pub(crate) mod lowering; use rustc_data_structures::fx::FxHashMap; -use rustc_index::vec::IndexVec; - use rustc_middle::infer::canonical::{CanonicalTyVarKind, CanonicalVarKind}; use rustc_middle::traits::ChalkRustInterner; use rustc_middle::ty::query::Providers; -use rustc_middle::ty::subst::GenericArg; -use rustc_middle::ty::{self, BoundVar, ParamTy, TyCtxt, TypeFoldable, TypeVisitable}; +use rustc_middle::ty::{self, ParamTy, TyCtxt, TypeFoldable, TypeVisitable}; use rustc_infer::infer::canonical::{ Canonical, CanonicalVarValues, Certainty, QueryRegionConstraints, QueryResponse, @@ -100,11 +97,13 @@ pub(crate) fn evaluate_goal<'tcx>( binders: chalk_ir::CanonicalVarKinds<_>| { use rustc_middle::infer::canonical::CanonicalVarInfo; - let mut var_values: IndexVec> = IndexVec::new(); let mut reverse_param_substitutor = ReverseParamsSubstitutor::new(tcx, params); - subst.as_slice(interner).iter().for_each(|p| { - var_values.push(p.lower_into(interner).fold_with(&mut reverse_param_substitutor)); - }); + let var_values = tcx.mk_substs( + subst + .as_slice(interner) + .iter() + .map(|p| p.lower_into(interner).fold_with(&mut reverse_param_substitutor)), + ); let variables: Vec<_> = binders .iter(interner) .map(|var| { @@ -159,8 +158,7 @@ pub(crate) fn evaluate_goal<'tcx>( max_universe: ty::UniverseIndex::from_usize(0), variables: obligation.variables, value: QueryResponse { - var_values: CanonicalVarValues { var_values: IndexVec::new() } - .make_identity(tcx), + var_values: CanonicalVarValues::dummy(), region_constraints: QueryRegionConstraints::default(), certainty: Certainty::Ambiguous, opaque_types: vec![], From 2d5591df00755c2c2dd310b134acaa6a60a4484a Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 26 Jan 2023 20:33:34 +0000 Subject: [PATCH 387/500] Make make_identity take CanonicalVarInfos --- compiler/rustc_middle/src/infer/canonical.rs | 52 +++++++++---------- .../rustc_trait_selection/src/solve/mod.rs | 23 +------- 2 files changed, 27 insertions(+), 48 deletions(-) diff --git a/compiler/rustc_middle/src/infer/canonical.rs b/compiler/rustc_middle/src/infer/canonical.rs index 2247090c38c4a..6e130bbf7d828 100644 --- a/compiler/rustc_middle/src/infer/canonical.rs +++ b/compiler/rustc_middle/src/infer/canonical.rs @@ -337,44 +337,31 @@ TrivialTypeTraversalAndLiftImpls! { } impl<'tcx> CanonicalVarValues<'tcx> { - /// Creates dummy var values which should not be used in a - /// canonical response. - pub fn dummy() -> CanonicalVarValues<'tcx> { - CanonicalVarValues { var_values: ty::List::empty() } - } - - #[inline] - pub fn len(&self) -> usize { - self.var_values.len() - } - - /// Makes an identity substitution from this one: each bound var - /// is matched to the same bound var, preserving the original kinds. - /// For example, if we have: - /// `self.var_values == [Type(u32), Lifetime('a), Type(u64)]` - /// we'll return a substitution `subst` with: - /// `subst.var_values == [Type(^0), Lifetime(^1), Type(^2)]`. - pub fn make_identity(&self, tcx: TyCtxt<'tcx>) -> Self { - use crate::ty::subst::GenericArgKind; - + // Given a list of canonical variables, construct a set of values which are + // the identity response. + pub fn make_identity( + tcx: TyCtxt<'tcx>, + infos: CanonicalVarInfos<'tcx>, + ) -> CanonicalVarValues<'tcx> { CanonicalVarValues { - var_values: tcx.mk_substs(self.var_values.iter().enumerate().map( - |(i, kind)| -> ty::GenericArg<'tcx> { - match kind.unpack() { - GenericArgKind::Type(..) => tcx + var_values: tcx.mk_substs(infos.iter().enumerate().map( + |(i, info)| -> ty::GenericArg<'tcx> { + match info.kind { + CanonicalVarKind::Ty(_) | CanonicalVarKind::PlaceholderTy(_) => tcx .mk_ty(ty::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i).into())) .into(), - GenericArgKind::Lifetime(..) => { + CanonicalVarKind::Region(_) | CanonicalVarKind::PlaceholderRegion(_) => { let br = ty::BoundRegion { var: ty::BoundVar::from_usize(i), kind: ty::BrAnon(i as u32, None), }; tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)).into() } - GenericArgKind::Const(ct) => tcx + CanonicalVarKind::Const(_, ty) + | CanonicalVarKind::PlaceholderConst(_, ty) => tcx .mk_const( ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i)), - ct.ty(), + ty, ) .into(), } @@ -382,6 +369,17 @@ impl<'tcx> CanonicalVarValues<'tcx> { )), } } + + /// Creates dummy var values which should not be used in a + /// canonical response. + pub fn dummy() -> CanonicalVarValues<'tcx> { + CanonicalVarValues { var_values: ty::List::empty() } + } + + #[inline] + pub fn len(&self) -> usize { + self.var_values.len() + } } impl<'a, 'tcx> IntoIterator for &'a CanonicalVarValues<'tcx> { diff --git a/compiler/rustc_trait_selection/src/solve/mod.rs b/compiler/rustc_trait_selection/src/solve/mod.rs index 1bd2f0fbda9ef..cfb0dccd7b009 100644 --- a/compiler/rustc_trait_selection/src/solve/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/mod.rs @@ -18,7 +18,7 @@ use std::mem; use rustc_hir::def_id::DefId; -use rustc_infer::infer::canonical::{Canonical, CanonicalVarKind, CanonicalVarValues}; +use rustc_infer::infer::canonical::{Canonical, CanonicalVarValues}; use rustc_infer::infer::canonical::{OriginalQueryValues, QueryRegionConstraints, QueryResponse}; use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt}; use rustc_infer::traits::query::NoSolution; @@ -481,30 +481,11 @@ pub(super) fn response_no_constraints<'tcx>( goal: Canonical<'tcx, impl Sized>, certainty: Certainty, ) -> QueryResult<'tcx> { - let var_values = - tcx.mk_substs(goal.variables.iter().enumerate().map(|(i, info)| -> ty::GenericArg<'tcx> { - match info.kind { - CanonicalVarKind::Ty(_) | CanonicalVarKind::PlaceholderTy(_) => { - tcx.mk_ty(ty::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i).into())).into() - } - CanonicalVarKind::Region(_) | CanonicalVarKind::PlaceholderRegion(_) => { - let br = ty::BoundRegion { - var: ty::BoundVar::from_usize(i), - kind: ty::BrAnon(i as u32, None), - }; - tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)).into() - } - CanonicalVarKind::Const(_, ty) | CanonicalVarKind::PlaceholderConst(_, ty) => tcx - .mk_const(ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i)), ty) - .into(), - } - })); - Ok(Canonical { max_universe: goal.max_universe, variables: goal.variables, value: Response { - var_values: CanonicalVarValues { var_values }, + var_values: CanonicalVarValues::make_identity(tcx, goal.variables), external_constraints: Default::default(), certainty, }, From 9438126fd12a57fe065cbfe35a952024a7d8e4c0 Mon Sep 17 00:00:00 2001 From: b-naber Date: Thu, 26 Jan 2023 23:35:24 +0100 Subject: [PATCH 388/500] previous thir unpretty output through thir-flat --- compiler/rustc_driver/src/pretty.rs | 15 +++++++++++++++ compiler/rustc_middle/src/query/mod.rs | 7 +++++++ compiler/rustc_mir_build/src/lib.rs | 1 + compiler/rustc_mir_build/src/thir/cx/mod.rs | 7 +++++++ compiler/rustc_session/src/config.rs | 11 ++++++++--- 5 files changed, 38 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_driver/src/pretty.rs b/compiler/rustc_driver/src/pretty.rs index ae3ac8625b186..a7c040397a154 100644 --- a/compiler/rustc_driver/src/pretty.rs +++ b/compiler/rustc_driver/src/pretty.rs @@ -498,6 +498,21 @@ fn print_with_analysis(tcx: TyCtxt<'_>, ppm: PpMode) -> Result<(), ErrorGuarante out } + ThirFlat => { + let mut out = String::new(); + abort_on_err(rustc_hir_analysis::check_crate(tcx), tcx.sess); + debug!("pretty printing THIR flat"); + for did in tcx.hir().body_owners() { + let _ = writeln!( + out, + "{:?}:\n{}\n", + did, + tcx.thir_flat(ty::WithOptConstParam::unknown(did)) + ); + } + out + } + _ => unreachable!(), }; diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index b1e0d380d04bc..2543614318f6d 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -361,6 +361,13 @@ rustc_queries! { desc { |tcx| "constructing THIR tree for `{}`", tcx.def_path_str(key.did.to_def_id()) } } + /// Create a list-like THIR representation for debugging. + query thir_flat(key: ty::WithOptConstParam) -> String { + no_hash + arena_cache + desc { |tcx| "constructing flat THIR representation for `{}`", tcx.def_path_str(key.did.to_def_id()) } + } + /// Set of all the `DefId`s in this crate that have MIR associated with /// them. This includes all the body owners, but also things like struct /// constructors. diff --git a/compiler/rustc_mir_build/src/lib.rs b/compiler/rustc_mir_build/src/lib.rs index a428180a4fa82..94dae36154c26 100644 --- a/compiler/rustc_mir_build/src/lib.rs +++ b/compiler/rustc_mir_build/src/lib.rs @@ -34,4 +34,5 @@ pub fn provide(providers: &mut Providers) { providers.thir_check_unsafety_for_const_arg = check_unsafety::thir_check_unsafety_for_const_arg; providers.thir_body = thir::cx::thir_body; providers.thir_tree = thir::cx::thir_tree; + providers.thir_flat = thir::cx::thir_flat; } diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index 52ecc67524b73..10df4b229520f 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -62,6 +62,13 @@ pub(crate) fn thir_tree(tcx: TyCtxt<'_>, owner_def: ty::WithOptConstParam, owner_def: ty::WithOptConstParam) -> String { + match thir_body(tcx, owner_def) { + Ok((thir, _)) => format!("{:#?}", thir.steal()), + Err(_) => "error".into(), + } +} + struct Cx<'tcx> { tcx: TyCtxt<'tcx>, thir: Thir<'tcx>, diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 586454f76574c..1abe5d242497b 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -2577,6 +2577,7 @@ fn parse_pretty(unstable_opts: &UnstableOptions, efmt: ErrorOutputType) -> Optio "hir,typed" => Hir(PpHirMode::Typed), "hir-tree" => HirTree, "thir-tree" => ThirTree, + "thir-flat" => ThirFlat, "mir" => Mir, "mir-cfg" => MirCFG, name => early_error( @@ -2585,7 +2586,8 @@ fn parse_pretty(unstable_opts: &UnstableOptions, efmt: ErrorOutputType) -> Optio "argument to `unpretty` must be one of `normal`, `identified`, \ `expanded`, `expanded,identified`, `expanded,hygiene`, \ `ast-tree`, `ast-tree,expanded`, `hir`, `hir,identified`, \ - `hir,typed`, `hir-tree`, `thir-tree`, `mir` or `mir-cfg`; got {name}" + `hir,typed`, `hir-tree`, `thir-tree`, `thir-flat`, `mir` or \ + `mir-cfg`; got {name}" ), ), }; @@ -2740,6 +2742,8 @@ pub enum PpMode { HirTree, /// `-Zunpretty=thir-tree` ThirTree, + /// `-Zunpretty=`thir-flat` + ThirFlat, /// `-Zunpretty=mir` Mir, /// `-Zunpretty=mir-cfg` @@ -2758,6 +2762,7 @@ impl PpMode { | Hir(_) | HirTree | ThirTree + | ThirFlat | Mir | MirCFG => true, } @@ -2767,13 +2772,13 @@ impl PpMode { match *self { Source(_) | AstTree(_) => false, - Hir(_) | HirTree | ThirTree | Mir | MirCFG => true, + Hir(_) | HirTree | ThirTree | ThirFlat | Mir | MirCFG => true, } } pub fn needs_analysis(&self) -> bool { use PpMode::*; - matches!(*self, Mir | MirCFG | ThirTree) + matches!(*self, Mir | MirCFG | ThirTree | ThirFlat) } } From e489971902c814e5adb7041d1bda230a1acb4fd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Mi=C4=85sko?= Date: Sun, 22 Jan 2023 00:00:00 +0000 Subject: [PATCH 389/500] Fix def-use dominance check A definition does not dominate a use in the same statement. For example in MIR generated for compound assignment x += a (when overflow checks are disabled). --- compiler/rustc_codegen_ssa/src/mir/analyze.rs | 33 ++++++++++++------- tests/ui/mir/mir_codegen_ssa.rs | 19 +++++++++++ 2 files changed, 41 insertions(+), 11 deletions(-) create mode 100644 tests/ui/mir/mir_codegen_ssa.rs diff --git a/compiler/rustc_codegen_ssa/src/mir/analyze.rs b/compiler/rustc_codegen_ssa/src/mir/analyze.rs index dd1ac2c74aed4..95aad10fdb0f9 100644 --- a/compiler/rustc_codegen_ssa/src/mir/analyze.rs +++ b/compiler/rustc_codegen_ssa/src/mir/analyze.rs @@ -36,7 +36,7 @@ pub fn non_ssa_locals<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( // Arguments get assigned to by means of the function being called for arg in mir.args_iter() { - analyzer.assign(arg, mir::START_BLOCK.start_location()); + analyzer.assign(arg, DefLocation::Argument); } // If there exists a local definition that dominates all uses of that local, @@ -64,7 +64,22 @@ enum LocalKind { /// A scalar or a scalar pair local that is neither defined nor used. Unused, /// A scalar or a scalar pair local with a single definition that dominates all uses. - SSA(mir::Location), + SSA(DefLocation), +} + +#[derive(Copy, Clone, PartialEq, Eq)] +enum DefLocation { + Argument, + Body(Location), +} + +impl DefLocation { + fn dominates(self, location: Location, dominators: &Dominators) -> bool { + match self { + DefLocation::Argument => true, + DefLocation::Body(def) => def.successor_within_block().dominates(location, dominators), + } + } } struct LocalAnalyzer<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> { @@ -74,17 +89,13 @@ struct LocalAnalyzer<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> { } impl<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> LocalAnalyzer<'mir, 'a, 'tcx, Bx> { - fn assign(&mut self, local: mir::Local, location: Location) { + fn assign(&mut self, local: mir::Local, location: DefLocation) { let kind = &mut self.locals[local]; match *kind { LocalKind::ZST => {} LocalKind::Memory => {} - LocalKind::Unused => { - *kind = LocalKind::SSA(location); - } - LocalKind::SSA(_) => { - *kind = LocalKind::Memory; - } + LocalKind::Unused => *kind = LocalKind::SSA(location), + LocalKind::SSA(_) => *kind = LocalKind::Memory, } } @@ -166,7 +177,7 @@ impl<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> Visitor<'tcx> debug!("visit_assign(place={:?}, rvalue={:?})", place, rvalue); if let Some(local) = place.as_local() { - self.assign(local, location); + self.assign(local, DefLocation::Body(location)); if self.locals[local] != LocalKind::Memory { let decl_span = self.fx.mir.local_decls[local].source_info.span; if !self.fx.rvalue_creates_operand(rvalue, decl_span) { @@ -189,7 +200,7 @@ impl<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> Visitor<'tcx> match context { PlaceContext::MutatingUse(MutatingUseContext::Call) | PlaceContext::MutatingUse(MutatingUseContext::Yield) => { - self.assign(local, location); + self.assign(local, DefLocation::Body(location)); } PlaceContext::NonUse(_) | PlaceContext::MutatingUse(MutatingUseContext::Retag) => {} diff --git a/tests/ui/mir/mir_codegen_ssa.rs b/tests/ui/mir/mir_codegen_ssa.rs new file mode 100644 index 0000000000000..5e2f10cefe92b --- /dev/null +++ b/tests/ui/mir/mir_codegen_ssa.rs @@ -0,0 +1,19 @@ +// build-pass +// compile-flags: --crate-type=lib +#![feature(custom_mir, core_intrinsics)] +use std::intrinsics::mir::*; + +#[custom_mir(dialect = "runtime", phase = "optimized")] +pub fn f(a: u32) -> u32 { + mir!( + let x: u32; + { + // Previously code generation failed with ICE "use of .. before def ..." because the + // definition of x was incorrectly identified as dominating the use of x located in the + // same statement: + x = x + a; + RET = x; + Return() + } + ) +} From a1a01c19f15d597215911e966667e0d35905e967 Mon Sep 17 00:00:00 2001 From: Collin Styles Date: Thu, 26 Jan 2023 16:44:44 -0800 Subject: [PATCH 390/500] Fix docs for `suspicious_xor_used_as_pow` lint There was a tab after the three leading slashes which caused the contents of the "Why is this bad?" section to be rendered as a code block. --- clippy_lints/src/suspicious_xor_used_as_pow.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/suspicious_xor_used_as_pow.rs b/clippy_lints/src/suspicious_xor_used_as_pow.rs index c181919b16470..9c0dc8096d0dc 100644 --- a/clippy_lints/src/suspicious_xor_used_as_pow.rs +++ b/clippy_lints/src/suspicious_xor_used_as_pow.rs @@ -9,7 +9,7 @@ declare_clippy_lint! { /// ### What it does /// Warns for a Bitwise XOR (`^`) operator being probably confused as a powering. It will not trigger if any of the numbers are not in decimal. /// ### Why is this bad? - /// It's most probably a typo and may lead to unexpected behaviours. + /// It's most probably a typo and may lead to unexpected behaviours. /// ### Example /// ```rust /// let x = 3_i32 ^ 4_i32; From 381187dc7650cb89a55e51aef2d0ded2a9339212 Mon Sep 17 00:00:00 2001 From: Ali MJ Al-Nasrawy Date: Fri, 27 Jan 2023 02:23:08 +0300 Subject: [PATCH 391/500] internally change regions to be covariant --- .../rustc_hir_analysis/src/variance/constraints.rs | 8 +++----- compiler/rustc_infer/src/infer/glb.rs | 3 ++- compiler/rustc_infer/src/infer/lub.rs | 3 ++- compiler/rustc_infer/src/infer/nll_relate/mod.rs | 8 ++++---- compiler/rustc_infer/src/infer/sub.rs | 3 ++- compiler/rustc_middle/src/ty/relate.rs | 14 ++------------ tests/ui/error-codes/E0208.rs | 2 +- tests/ui/error-codes/E0208.stderr | 2 +- tests/ui/variance/variance-associated-types.rs | 2 +- tests/ui/variance/variance-associated-types.stderr | 2 +- tests/ui/variance/variance-regions-direct.rs | 12 ++++++------ tests/ui/variance/variance-regions-direct.stderr | 12 ++++++------ tests/ui/variance/variance-regions-indirect.rs | 8 ++++---- tests/ui/variance/variance-regions-indirect.stderr | 8 ++++---- tests/ui/variance/variance-trait-object-bound.rs | 2 +- .../ui/variance/variance-trait-object-bound.stderr | 2 +- tests/ui/variance/variance-types.rs | 2 +- tests/ui/variance/variance-types.stderr | 2 +- 18 files changed, 43 insertions(+), 52 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index 5e4d82b6fd569..ca65020728761 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -221,8 +221,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { } ty::Ref(region, ty, mutbl) => { - let contra = self.contravariant(variance); - self.add_constraints_from_region(current, region, contra); + self.add_constraints_from_region(current, region, variance); self.add_constraints_from_mt(current, &ty::TypeAndMut { ty, mutbl }, variance); } @@ -254,9 +253,8 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { } ty::Dynamic(data, r, _) => { - // The type `Foo` is contravariant w/r/t `'a`: - let contra = self.contravariant(variance); - self.add_constraints_from_region(current, r, contra); + // The type `Foo` is covariant w/r/t `'a`: + self.add_constraints_from_region(current, r, variance); if let Some(poly_trait_ref) = data.principal() { self.add_constraints_from_invariant_substs( diff --git a/compiler/rustc_infer/src/infer/glb.rs b/compiler/rustc_infer/src/infer/glb.rs index 21b68ce998997..b92b162a9786a 100644 --- a/compiler/rustc_infer/src/infer/glb.rs +++ b/compiler/rustc_infer/src/infer/glb.rs @@ -79,7 +79,8 @@ impl<'tcx> TypeRelation<'tcx> for Glb<'_, '_, 'tcx> { debug!("{}.regions({:?}, {:?})", self.tag(), a, b); let origin = Subtype(Box::new(self.fields.trace.clone())); - Ok(self.fields.infcx.inner.borrow_mut().unwrap_region_constraints().glb_regions( + // GLB(&'static u8, &'a u8) == &RegionLUB('static, 'a) u8 == &'static u8 + Ok(self.fields.infcx.inner.borrow_mut().unwrap_region_constraints().lub_regions( self.tcx(), origin, a, diff --git a/compiler/rustc_infer/src/infer/lub.rs b/compiler/rustc_infer/src/infer/lub.rs index c07ac1d3ace92..f6e0554fd1f95 100644 --- a/compiler/rustc_infer/src/infer/lub.rs +++ b/compiler/rustc_infer/src/infer/lub.rs @@ -79,7 +79,8 @@ impl<'tcx> TypeRelation<'tcx> for Lub<'_, '_, 'tcx> { debug!("{}.regions({:?}, {:?})", self.tag(), a, b); let origin = Subtype(Box::new(self.fields.trace.clone())); - Ok(self.fields.infcx.inner.borrow_mut().unwrap_region_constraints().lub_regions( + // LUB(&'static u8, &'a u8) == &RegionGLB('static, 'a) u8 == &'a u8 + Ok(self.fields.infcx.inner.borrow_mut().unwrap_region_constraints().glb_regions( self.tcx(), origin, a, diff --git a/compiler/rustc_infer/src/infer/nll_relate/mod.rs b/compiler/rustc_infer/src/infer/nll_relate/mod.rs index f235cb5ab4503..f83219b8ee2a0 100644 --- a/compiler/rustc_infer/src/infer/nll_relate/mod.rs +++ b/compiler/rustc_infer/src/infer/nll_relate/mod.rs @@ -663,13 +663,13 @@ where debug!(?v_b); if self.ambient_covariance() { - // Covariance: a <= b. Hence, `b: a`. - self.push_outlives(v_b, v_a, self.ambient_variance_info); + // Covariant: &'a u8 <: &'b u8. Hence, `'a: 'b`. + self.push_outlives(v_a, v_b, self.ambient_variance_info); } if self.ambient_contravariance() { - // Contravariant: b <= a. Hence, `a: b`. - self.push_outlives(v_a, v_b, self.ambient_variance_info); + // Contravariant: &'b u8 <: &'a u8. Hence, `'b: 'a`. + self.push_outlives(v_b, v_a, self.ambient_variance_info); } Ok(a) diff --git a/compiler/rustc_infer/src/infer/sub.rs b/compiler/rustc_infer/src/infer/sub.rs index bd38b52ba34a7..51c34f0d55f6f 100644 --- a/compiler/rustc_infer/src/infer/sub.rs +++ b/compiler/rustc_infer/src/infer/sub.rs @@ -191,12 +191,13 @@ impl<'tcx> TypeRelation<'tcx> for Sub<'_, '_, 'tcx> { // from the "cause" field, we could perhaps give more tailored // error messages. let origin = SubregionOrigin::Subtype(Box::new(self.fields.trace.clone())); + // Subtype(&'a u8, &'b u8) => Outlives('a: 'b) => SubRegion('b, 'a) self.fields .infcx .inner .borrow_mut() .unwrap_region_constraints() - .make_subregion(origin, a, b); + .make_subregion(origin, b, a); Ok(a) } diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index 65fd8d9753de1..114a91de5d3b7 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -443,12 +443,7 @@ pub fn super_relate_tys<'tcx, R: TypeRelation<'tcx>>( if a_repr == b_repr => { let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| { - relation.relate_with_variance( - ty::Contravariant, - ty::VarianceDiagInfo::default(), - a_region, - b_region, - ) + relation.relate(a_region, b_region) })?; Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound, a_repr)) } @@ -487,12 +482,7 @@ pub fn super_relate_tys<'tcx, R: TypeRelation<'tcx>>( } (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => { - let r = relation.relate_with_variance( - ty::Contravariant, - ty::VarianceDiagInfo::default(), - a_r, - b_r, - )?; + let r = relation.relate(a_r, b_r)?; let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl }; let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl }; let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?; diff --git a/tests/ui/error-codes/E0208.rs b/tests/ui/error-codes/E0208.rs index c67d42889d69b..74c138af483c1 100644 --- a/tests/ui/error-codes/E0208.rs +++ b/tests/ui/error-codes/E0208.rs @@ -1,7 +1,7 @@ #![feature(rustc_attrs)] #[rustc_variance] -struct Foo<'a, T> { //~ ERROR [-, o] +struct Foo<'a, T> { //~ ERROR [+, o] t: &'a mut T, } diff --git a/tests/ui/error-codes/E0208.stderr b/tests/ui/error-codes/E0208.stderr index dbbb41e79500c..2c7072a7e7626 100644 --- a/tests/ui/error-codes/E0208.stderr +++ b/tests/ui/error-codes/E0208.stderr @@ -1,4 +1,4 @@ -error: [-, o] +error: [+, o] --> $DIR/E0208.rs:4:1 | LL | struct Foo<'a, T> { diff --git a/tests/ui/variance/variance-associated-types.rs b/tests/ui/variance/variance-associated-types.rs index 1165fb53c7342..ecb0821827dc0 100644 --- a/tests/ui/variance/variance-associated-types.rs +++ b/tests/ui/variance/variance-associated-types.rs @@ -10,7 +10,7 @@ trait Trait<'a> { } #[rustc_variance] -struct Foo<'a, T : Trait<'a>> { //~ ERROR [-, +] +struct Foo<'a, T : Trait<'a>> { //~ ERROR [+, +] field: (T, &'a ()) } diff --git a/tests/ui/variance/variance-associated-types.stderr b/tests/ui/variance/variance-associated-types.stderr index 51f17c7c22887..70cb246f6e906 100644 --- a/tests/ui/variance/variance-associated-types.stderr +++ b/tests/ui/variance/variance-associated-types.stderr @@ -1,4 +1,4 @@ -error: [-, +] +error: [+, +] --> $DIR/variance-associated-types.rs:13:1 | LL | struct Foo<'a, T : Trait<'a>> { diff --git a/tests/ui/variance/variance-regions-direct.rs b/tests/ui/variance/variance-regions-direct.rs index 3f34e7655f3a5..39ea77a8aa21a 100644 --- a/tests/ui/variance/variance-regions-direct.rs +++ b/tests/ui/variance/variance-regions-direct.rs @@ -6,7 +6,7 @@ // Regions that just appear in normal spots are contravariant: #[rustc_variance] -struct Test2<'a, 'b, 'c> { //~ ERROR [-, -, -] +struct Test2<'a, 'b, 'c> { //~ ERROR [+, +, +] x: &'a isize, y: &'b [isize], c: &'c str @@ -15,7 +15,7 @@ struct Test2<'a, 'b, 'c> { //~ ERROR [-, -, -] // Those same annotations in function arguments become covariant: #[rustc_variance] -struct Test3<'a, 'b, 'c> { //~ ERROR [+, +, +] +struct Test3<'a, 'b, 'c> { //~ ERROR [-, -, -] x: extern "Rust" fn(&'a isize), y: extern "Rust" fn(&'b [isize]), c: extern "Rust" fn(&'c str), @@ -24,7 +24,7 @@ struct Test3<'a, 'b, 'c> { //~ ERROR [+, +, +] // Mutability induces invariance: #[rustc_variance] -struct Test4<'a, 'b:'a> { //~ ERROR [-, o] +struct Test4<'a, 'b:'a> { //~ ERROR [+, o] x: &'a mut &'b isize, } @@ -32,7 +32,7 @@ struct Test4<'a, 'b:'a> { //~ ERROR [-, o] // contravariant context: #[rustc_variance] -struct Test5<'a, 'b:'a> { //~ ERROR [+, o] +struct Test5<'a, 'b:'a> { //~ ERROR [-, o] x: extern "Rust" fn(&'a mut &'b isize), } @@ -42,7 +42,7 @@ struct Test5<'a, 'b:'a> { //~ ERROR [+, o] // argument list occurs in an invariant context. #[rustc_variance] -struct Test6<'a, 'b:'a> { //~ ERROR [-, o] +struct Test6<'a, 'b:'a> { //~ ERROR [+, o] x: &'a mut extern "Rust" fn(&'b isize), } @@ -56,7 +56,7 @@ struct Test7<'a> { //~ ERROR [*] // Try enums too. #[rustc_variance] -enum Test8<'a, 'b, 'c:'b> { //~ ERROR [+, -, o] +enum Test8<'a, 'b, 'c:'b> { //~ ERROR [-, +, o] Test8A(extern "Rust" fn(&'a isize)), Test8B(&'b [isize]), Test8C(&'b mut &'c str), diff --git a/tests/ui/variance/variance-regions-direct.stderr b/tests/ui/variance/variance-regions-direct.stderr index eda02e9b03bb8..c55730296f1c5 100644 --- a/tests/ui/variance/variance-regions-direct.stderr +++ b/tests/ui/variance/variance-regions-direct.stderr @@ -1,28 +1,28 @@ -error: [-, -, -] +error: [+, +, +] --> $DIR/variance-regions-direct.rs:9:1 | LL | struct Test2<'a, 'b, 'c> { | ^^^^^^^^^^^^^^^^^^^^^^^^ -error: [+, +, +] +error: [-, -, -] --> $DIR/variance-regions-direct.rs:18:1 | LL | struct Test3<'a, 'b, 'c> { | ^^^^^^^^^^^^^^^^^^^^^^^^ -error: [-, o] +error: [+, o] --> $DIR/variance-regions-direct.rs:27:1 | LL | struct Test4<'a, 'b:'a> { | ^^^^^^^^^^^^^^^^^^^^^^^ -error: [+, o] +error: [-, o] --> $DIR/variance-regions-direct.rs:35:1 | LL | struct Test5<'a, 'b:'a> { | ^^^^^^^^^^^^^^^^^^^^^^^ -error: [-, o] +error: [+, o] --> $DIR/variance-regions-direct.rs:45:1 | LL | struct Test6<'a, 'b:'a> { @@ -34,7 +34,7 @@ error: [*] LL | struct Test7<'a> { | ^^^^^^^^^^^^^^^^ -error: [+, -, o] +error: [-, +, o] --> $DIR/variance-regions-direct.rs:59:1 | LL | enum Test8<'a, 'b, 'c:'b> { diff --git a/tests/ui/variance/variance-regions-indirect.rs b/tests/ui/variance/variance-regions-indirect.rs index f84f25ada14de..0d00535fef11b 100644 --- a/tests/ui/variance/variance-regions-indirect.rs +++ b/tests/ui/variance/variance-regions-indirect.rs @@ -5,14 +5,14 @@ #![feature(rustc_attrs)] #[rustc_variance] -enum Base<'a, 'b, 'c:'b, 'd> { //~ ERROR [+, -, o, *] +enum Base<'a, 'b, 'c:'b, 'd> { //~ ERROR [-, +, o, *] Test8A(extern "Rust" fn(&'a isize)), Test8B(&'b [isize]), Test8C(&'b mut &'c str), } #[rustc_variance] -struct Derived1<'w, 'x:'y, 'y, 'z> { //~ ERROR [*, o, -, +] +struct Derived1<'w, 'x:'y, 'y, 'z> { //~ ERROR [*, o, +, -] f: Base<'z, 'y, 'x, 'w> } @@ -22,12 +22,12 @@ struct Derived2<'a, 'b:'a, 'c> { //~ ERROR [o, o, *] } #[rustc_variance] // Combine + and o to yield o (just pay attention to 'a here) -struct Derived3<'a:'b, 'b, 'c> { //~ ERROR [o, -, *] +struct Derived3<'a:'b, 'b, 'c> { //~ ERROR [o, +, *] f: Base<'a, 'b, 'a, 'c> } #[rustc_variance] // Combine + and * to yield + (just pay attention to 'a here) -struct Derived4<'a, 'b, 'c:'b> { //~ ERROR [+, -, o] +struct Derived4<'a, 'b, 'c:'b> { //~ ERROR [-, +, o] f: Base<'a, 'b, 'c, 'a> } diff --git a/tests/ui/variance/variance-regions-indirect.stderr b/tests/ui/variance/variance-regions-indirect.stderr index fa2f4d507f3d5..edf2626d5984f 100644 --- a/tests/ui/variance/variance-regions-indirect.stderr +++ b/tests/ui/variance/variance-regions-indirect.stderr @@ -1,10 +1,10 @@ -error: [+, -, o, *] +error: [-, +, o, *] --> $DIR/variance-regions-indirect.rs:8:1 | LL | enum Base<'a, 'b, 'c:'b, 'd> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: [*, o, -, +] +error: [*, o, +, -] --> $DIR/variance-regions-indirect.rs:15:1 | LL | struct Derived1<'w, 'x:'y, 'y, 'z> { @@ -16,13 +16,13 @@ error: [o, o, *] LL | struct Derived2<'a, 'b:'a, 'c> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: [o, -, *] +error: [o, +, *] --> $DIR/variance-regions-indirect.rs:25:1 | LL | struct Derived3<'a:'b, 'b, 'c> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: [+, -, o] +error: [-, +, o] --> $DIR/variance-regions-indirect.rs:30:1 | LL | struct Derived4<'a, 'b, 'c:'b> { diff --git a/tests/ui/variance/variance-trait-object-bound.rs b/tests/ui/variance/variance-trait-object-bound.rs index ec3c973bc7639..11303c4652005 100644 --- a/tests/ui/variance/variance-trait-object-bound.rs +++ b/tests/ui/variance/variance-trait-object-bound.rs @@ -11,7 +11,7 @@ use std::mem; trait T { fn foo(&self); } #[rustc_variance] -struct TOption<'a> { //~ ERROR [-] +struct TOption<'a> { //~ ERROR [+] v: Option>, } diff --git a/tests/ui/variance/variance-trait-object-bound.stderr b/tests/ui/variance/variance-trait-object-bound.stderr index 7c46b553f4394..bfcc8d4a1d11b 100644 --- a/tests/ui/variance/variance-trait-object-bound.stderr +++ b/tests/ui/variance/variance-trait-object-bound.stderr @@ -1,4 +1,4 @@ -error: [-] +error: [+] --> $DIR/variance-trait-object-bound.rs:14:1 | LL | struct TOption<'a> { diff --git a/tests/ui/variance/variance-types.rs b/tests/ui/variance/variance-types.rs index b9b6d9c9bb5e4..cfc03b754734d 100644 --- a/tests/ui/variance/variance-types.rs +++ b/tests/ui/variance/variance-types.rs @@ -7,7 +7,7 @@ use std::cell::Cell; // not considered bivariant. #[rustc_variance] -struct InvariantMut<'a,A:'a,B:'a> { //~ ERROR [-, o, o] +struct InvariantMut<'a,A:'a,B:'a> { //~ ERROR [+, o, o] t: &'a mut (A,B) } diff --git a/tests/ui/variance/variance-types.stderr b/tests/ui/variance/variance-types.stderr index 9f7f1d9b0e332..0fda4b8036e72 100644 --- a/tests/ui/variance/variance-types.stderr +++ b/tests/ui/variance/variance-types.stderr @@ -1,4 +1,4 @@ -error: [-, o, o] +error: [+, o, o] --> $DIR/variance-types.rs:10:1 | LL | struct InvariantMut<'a,A:'a,B:'a> { From e982971ff22fa190369b5f536403c37c52b10a26 Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Wed, 18 Jan 2023 15:43:20 -0700 Subject: [PATCH 392/500] replace usages of fn_sig query with bound_fn_sig --- .../src/diagnostics/conflict_errors.rs | 2 +- .../rustc_borrowck/src/diagnostics/mod.rs | 2 +- .../rustc_borrowck/src/universal_regions.rs | 4 ++-- .../rustc_codegen_cranelift/src/main_shim.rs | 2 +- compiler/rustc_codegen_llvm/src/attributes.rs | 2 +- .../rustc_codegen_ssa/src/codegen_attrs.rs | 6 +++--- .../src/const_eval/fn_queries.rs | 4 ++-- .../src/transform/check_consts/mod.rs | 2 +- .../src/check/compare_impl_item.rs | 20 +++++++++---------- .../rustc_hir_analysis/src/check/intrinsic.rs | 2 +- compiler/rustc_hir_analysis/src/check/mod.rs | 2 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 8 ++++---- .../rustc_hir_analysis/src/collect/type_of.rs | 4 +++- compiler/rustc_hir_analysis/src/lib.rs | 4 ++-- .../src/variance/constraints.rs | 6 +++++- compiler/rustc_hir_typeck/src/demand.rs | 20 ++++++++++++++++--- compiler/rustc_hir_typeck/src/expr.rs | 4 +++- compiler/rustc_hir_typeck/src/lib.rs | 2 +- compiler/rustc_hir_typeck/src/method/mod.rs | 4 ++-- .../rustc_hir_typeck/src/method/suggest.rs | 13 ++++++------ .../error_reporting/nice_region_error/util.rs | 2 +- compiler/rustc_lint/src/types.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 2 +- compiler/rustc_middle/src/ty/assoc.rs | 2 +- compiler/rustc_middle/src/ty/instance.rs | 2 +- compiler/rustc_middle/src/ty/util.rs | 5 ++++- compiler/rustc_mir_build/src/build/mod.rs | 4 +++- .../src/function_item_references.rs | 5 +++-- compiler/rustc_mir_transform/src/shim.rs | 6 +++++- compiler/rustc_monomorphize/src/collector.rs | 2 +- compiler/rustc_privacy/src/lib.rs | 2 +- .../src/traits/object_safety.rs | 2 +- compiler/rustc_ty_utils/src/implied_bounds.rs | 4 ++-- compiler/rustc_ty_utils/src/ty.rs | 2 +- src/librustdoc/clean/inline.rs | 2 +- src/librustdoc/clean/mod.rs | 2 +- src/librustdoc/clean/types.rs | 4 ++-- .../clippy_lints/src/casts/as_ptr_cast_mut.rs | 2 +- .../src/default_numeric_fallback.rs | 4 ++-- .../clippy/clippy_lints/src/dereference.rs | 14 ++++++------- .../src/functions/not_unsafe_ptr_arg_deref.rs | 2 +- .../clippy_lints/src/functions/result.rs | 2 +- .../clippy_lints/src/inherent_to_string.rs | 2 +- .../src/iter_not_returning_iterator.rs | 2 +- src/tools/clippy/clippy_lints/src/len_zero.rs | 10 +++++----- .../src/loops/needless_range_loop.rs | 2 +- .../clippy/clippy_lints/src/map_unit_fn.rs | 2 +- .../src/methods/expect_fun_call.rs | 4 ++-- .../clippy/clippy_lints/src/methods/mod.rs | 2 +- .../src/methods/needless_collect.rs | 4 ++-- .../src/methods/unnecessary_to_owned.rs | 4 ++-- src/tools/clippy/clippy_lints/src/mut_key.rs | 2 +- .../src/needless_pass_by_value.rs | 2 +- .../clippy_lints/src/pass_by_ref_or_value.rs | 2 +- src/tools/clippy/clippy_lints/src/ptr.rs | 6 +++--- src/tools/clippy/clippy_lints/src/returns.rs | 3 ++- .../src/unit_return_expecting_ord.rs | 2 +- .../src/unit_types/let_unit_value.rs | 2 +- src/tools/clippy/clippy_lints/src/use_self.rs | 2 +- .../clippy/clippy_utils/src/eager_or_lazy.rs | 2 +- src/tools/clippy/clippy_utils/src/lib.rs | 6 +++--- .../clippy_utils/src/qualify_min_const_fn.rs | 2 +- src/tools/clippy/clippy_utils/src/sugg.rs | 2 +- src/tools/clippy/clippy_utils/src/ty.rs | 2 +- src/tools/clippy/clippy_utils/src/visitors.rs | 4 ++-- src/tools/miri/src/eval.rs | 2 +- 66 files changed, 147 insertions(+), 113 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index a1eb2960d7b7c..8e910dea9f3e4 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -2599,7 +2599,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { match ty.kind() { ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig( self.mir_def_id(), - self.infcx.tcx.fn_sig(self.mir_def_id()), + self.infcx.tcx.bound_fn_sig(self.mir_def_id().into()).subst_identity(), ), _ => None, } diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 1b40b7143cbb6..409b18a579d6d 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -1136,7 +1136,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { && let self_ty = infcx.replace_bound_vars_with_fresh_vars( fn_call_span, LateBoundRegionConversionTime::FnCall, - tcx.fn_sig(method_did).input(0), + tcx.bound_fn_sig(method_did).subst_identity().input(0), ) && infcx.can_eq(self.param_env, ty, self_ty).is_ok() { diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index 8bff66f8d5cca..4b62e5cce47bf 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -472,7 +472,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { // C-variadic fns also have a `VaList` input that's not listed in the signature // (as it's created inside the body itself, not passed in from outside). if let DefiningTy::FnDef(def_id, _) = defining_ty { - if self.infcx.tcx.fn_sig(def_id).c_variadic() { + if self.infcx.tcx.bound_fn_sig(def_id).skip_binder().c_variadic() { let va_list_did = self.infcx.tcx.require_lang_item( LangItem::VaList, Some(self.infcx.tcx.def_span(self.mir_def.did)), @@ -665,7 +665,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { } DefiningTy::FnDef(def_id, _) => { - let sig = tcx.fn_sig(def_id); + let sig = tcx.bound_fn_sig(def_id).subst_identity(); let sig = indices.fold_to_region_vids(tcx, sig); sig.inputs_and_output() } diff --git a/compiler/rustc_codegen_cranelift/src/main_shim.rs b/compiler/rustc_codegen_cranelift/src/main_shim.rs index c10054e7f0d2c..f46e6b6528c88 100644 --- a/compiler/rustc_codegen_cranelift/src/main_shim.rs +++ b/compiler/rustc_codegen_cranelift/src/main_shim.rs @@ -46,7 +46,7 @@ pub(crate) fn maybe_create_entry_wrapper( is_main_fn: bool, sigpipe: u8, ) { - let main_ret_ty = tcx.fn_sig(rust_main_def_id).output(); + let main_ret_ty = tcx.bound_fn_sig(rust_main_def_id).subst_identity().output(); // Given that `main()` has no arguments, // then its return type cannot have // late-bound regions, since late-bound diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index 95baa95b02183..4d802206f2365 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -441,7 +441,7 @@ pub fn from_fn_attrs<'ll, 'tcx>( // the WebAssembly specification, which has this feature. This won't be // needed when LLVM enables this `multivalue` feature by default. if !cx.tcx.is_closure(instance.def_id()) { - let abi = cx.tcx.fn_sig(instance.def_id()).abi(); + let abi = cx.tcx.bound_fn_sig(instance.def_id()).skip_binder().abi(); if abi == Abi::Wasm { function_features.push("+multivalue".to_string()); } diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 8808ad2dcd135..61cea048a5e26 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -214,7 +214,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs { } } else if attr.has_name(sym::cmse_nonsecure_entry) { if validate_fn_only_attr(attr.span) - && !matches!(tcx.fn_sig(did).abi(), abi::Abi::C { .. }) + && !matches!(tcx.bound_fn_sig(did.into()).skip_binder().abi(), abi::Abi::C { .. }) { struct_span_err!( tcx.sess, @@ -234,7 +234,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs { } else if attr.has_name(sym::track_caller) { if !tcx.is_closure(did.to_def_id()) && validate_fn_only_attr(attr.span) - && tcx.fn_sig(did).abi() != abi::Abi::Rust + && tcx.bound_fn_sig(did.into()).skip_binder().abi() != abi::Abi::Rust { struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI") .emit(); @@ -266,7 +266,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs { } } else if attr.has_name(sym::target_feature) { if !tcx.is_closure(did.to_def_id()) - && tcx.fn_sig(did).unsafety() == hir::Unsafety::Normal + && tcx.bound_fn_sig(did.into()).skip_binder().unsafety() == hir::Unsafety::Normal { if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc { // The `#[target_feature]` attribute is allowed on diff --git a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs index 351c701305adc..f91912104e5ab 100644 --- a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs @@ -64,9 +64,9 @@ fn is_promotable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> bool { && match tcx.lookup_const_stability(def_id) { Some(stab) => { if cfg!(debug_assertions) && stab.promotable { - let sig = tcx.fn_sig(def_id); + let sig = tcx.bound_fn_sig(def_id); assert_eq!( - sig.unsafety(), + sig.skip_binder().unsafety(), hir::Unsafety::Normal, "don't mark const unsafe fns as promotable", // https://github.com/rust-lang/rust/pull/53851#issuecomment-418760682 diff --git a/compiler/rustc_const_eval/src/transform/check_consts/mod.rs b/compiler/rustc_const_eval/src/transform/check_consts/mod.rs index 54868e418c4b3..64155b2594b00 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/mod.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/mod.rs @@ -72,7 +72,7 @@ impl<'mir, 'tcx> ConstCx<'mir, 'tcx> { let ty::Closure(_, substs) = ty.kind() else { bug!("type_of closure not ty::Closure") }; substs.as_closure().sig() } else { - self.tcx.fn_sig(did) + self.tcx.bound_fn_sig(did).subst_identity() } } } diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index c09294090d310..475be4fde7aa1 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -249,7 +249,7 @@ fn compare_method_predicate_entailment<'tcx>( let unnormalized_impl_sig = infcx.replace_bound_vars_with_fresh_vars( impl_m_span, infer::HigherRankedType, - tcx.fn_sig(impl_m.def_id), + tcx.bound_fn_sig(impl_m.def_id).subst_identity(), ); let unnormalized_impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(unnormalized_impl_sig)); @@ -422,8 +422,8 @@ fn extract_bad_args_for_implies_lint<'tcx>( // Map late-bound regions from trait to impl, so the names are right. let mapping = std::iter::zip( - tcx.fn_sig(trait_m.def_id).bound_vars(), - tcx.fn_sig(impl_m.def_id).bound_vars(), + tcx.bound_fn_sig(trait_m.def_id).subst_identity().bound_vars(), + tcx.bound_fn_sig(impl_m.def_id).subst_identity().bound_vars(), ) .filter_map(|(impl_bv, trait_bv)| { if let ty::BoundVariableKind::Region(impl_bv) = impl_bv @@ -540,7 +540,7 @@ fn compare_asyncness<'tcx>( trait_item_span: Option, ) -> Result<(), ErrorGuaranteed> { if tcx.asyncness(trait_m.def_id) == hir::IsAsync::Async { - match tcx.fn_sig(impl_m.def_id).skip_binder().output().kind() { + match tcx.bound_fn_sig(impl_m.def_id).subst_identity().skip_binder().output().kind() { ty::Alias(ty::Opaque, ..) => { // allow both `async fn foo()` and `fn foo() -> impl Future` } @@ -643,7 +643,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( infcx.replace_bound_vars_with_fresh_vars( return_span, infer::HigherRankedType, - tcx.fn_sig(impl_m.def_id), + tcx.bound_fn_sig(impl_m.def_id).subst_identity(), ), ); impl_sig.error_reported()?; @@ -1117,7 +1117,7 @@ fn compare_self_type<'tcx>( ty::ImplContainer => impl_trait_ref.self_ty(), ty::TraitContainer => tcx.types.self_param, }; - let self_arg_ty = tcx.fn_sig(method.def_id).input(0); + let self_arg_ty = tcx.bound_fn_sig(method.def_id).subst_identity().input(0); let param_env = ty::ParamEnv::reveal_all(); let infcx = tcx.infer_ctxt().build(); @@ -1348,10 +1348,10 @@ fn compare_number_of_method_arguments<'tcx>( trait_m: &ty::AssocItem, trait_item_span: Option, ) -> Result<(), ErrorGuaranteed> { - let impl_m_fty = tcx.fn_sig(impl_m.def_id); - let trait_m_fty = tcx.fn_sig(trait_m.def_id); - let trait_number_args = trait_m_fty.inputs().skip_binder().len(); - let impl_number_args = impl_m_fty.inputs().skip_binder().len(); + let impl_m_fty = tcx.bound_fn_sig(impl_m.def_id); + let trait_m_fty = tcx.bound_fn_sig(trait_m.def_id); + let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len(); + let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len(); if trait_number_args != impl_number_args { let trait_span = trait_m diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index c93ac5ad963d2..fe2720fa1afc9 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -58,7 +58,7 @@ fn equate_intrinsic_type<'tcx>( let fty = tcx.mk_fn_ptr(sig); let it_def_id = it.owner_id.def_id; let cause = ObligationCause::new(it.span, it_def_id, ObligationCauseCode::IntrinsicType); - require_same_types(tcx, &cause, tcx.mk_fn_ptr(tcx.fn_sig(it.owner_id)), fty); + require_same_types(tcx, &cause, tcx.mk_fn_ptr(tcx.bound_fn_sig(it.owner_id.to_def_id()).subst_identity()), fty); } } diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index 14bca34b77bea..3b0ddad25fc82 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -445,7 +445,7 @@ fn suggestion_signature(assoc: &ty::AssocItem, tcx: TyCtxt<'_>) -> String { // regions just fine, showing `fn(&MyType)`. fn_sig_suggestion( tcx, - tcx.fn_sig(assoc.def_id).skip_binder(), + tcx.bound_fn_sig(assoc.def_id).subst_identity().skip_binder(), assoc.ident(tcx), tcx.predicates_of(assoc.def_id), assoc, diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index cf14da35375cc..a0a0c72ded96b 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -386,7 +386,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from. let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions( item_def_id.to_def_id(), - tcx.fn_sig(item_def_id), + tcx.bound_fn_sig(item_def_id.to_def_id()).subst_identity(), ); gather_gat_bounds( tcx, @@ -1018,7 +1018,7 @@ fn check_associated_item( wfcx.register_wf_obligation(span, loc, ty.into()); } ty::AssocKind::Fn => { - let sig = tcx.fn_sig(item.def_id); + let sig = tcx.bound_fn_sig(item.def_id).subst_identity(); let hir_sig = sig_if_method.expect("bad signature for method"); check_fn_or_method( wfcx, @@ -1203,7 +1203,7 @@ fn check_item_fn( decl: &hir::FnDecl<'_>, ) { enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| { - let sig = tcx.fn_sig(def_id); + let sig = tcx.bound_fn_sig(def_id.into()).subst_identity(); check_fn_or_method(wfcx, ident.span, sig, decl, def_id); }) } @@ -1638,7 +1638,7 @@ fn check_method_receiver<'tcx>( let span = fn_sig.decl.inputs[0].span; - let sig = tcx.fn_sig(method.def_id); + let sig = tcx.bound_fn_sig(method.def_id).subst_identity(); let sig = tcx.liberate_late_bound_regions(method.def_id, sig); let sig = wfcx.normalize(span, None, sig); diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 5e388a2f2babb..82c4aaba0891a 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -867,7 +867,9 @@ fn infer_placeholder_type<'a>( } match ty.kind() { - ty::FnDef(def_id, _) => self.tcx.mk_fn_ptr(self.tcx.fn_sig(*def_id)), + ty::FnDef(def_id, _) => { + self.tcx.mk_fn_ptr(self.tcx.bound_fn_sig(*def_id).subst_identity()) + } // FIXME: non-capturing closures should also suggest a function pointer ty::Closure(..) | ty::Generator(..) => { self.success = false; diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index da35210023891..7a359ab22feac 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -182,7 +182,7 @@ fn require_same_types<'tcx>( } fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { - let main_fnsig = tcx.fn_sig(main_def_id); + let main_fnsig = tcx.bound_fn_sig(main_def_id).subst_identity(); let main_span = tcx.def_span(main_def_id); fn main_fn_diagnostics_def_id(tcx: TyCtxt<'_>, def_id: DefId, sp: Span) -> LocalDefId { @@ -449,7 +449,7 @@ fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: DefId) { ObligationCauseCode::StartFunctionType, ), se_ty, - tcx.mk_fn_ptr(tcx.fn_sig(start_def_id)), + tcx.mk_fn_ptr(tcx.bound_fn_sig(start_def_id.into()).subst_identity()), ); } _ => { diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index 5e4d82b6fd569..b662dfca71a30 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -119,7 +119,11 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { } ty::FnDef(..) => { - self.add_constraints_from_sig(current_item, tcx.fn_sig(def_id), self.covariant); + self.add_constraints_from_sig( + current_item, + tcx.bound_fn_sig(def_id.into()).subst_identity(), + self.covariant, + ); } ty::Error(_) => {} diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index a7b6a5c0331fc..c01def290353b 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -299,7 +299,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { // We special case methods, because they can influence inference through the // call's arguments and we can provide a more explicit span. - let sig = self.tcx.fn_sig(def_id); + let sig = self.tcx.bound_fn_sig(def_id).subst_identity(); let def_self_ty = sig.input(0).skip_binder(); let rcvr_ty = self.node_ty(rcvr.hir_id); // Get the evaluated type *after* calling the method call, so that the influence @@ -611,7 +611,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { with_no_trimmed_paths!( self.tcx.def_path_str_with_substs(m.def_id, substs,) ), - match self.tcx.fn_sig(m.def_id).input(0).skip_binder().kind() { + match self + .tcx + .bound_fn_sig(m.def_id) + .subst_identity() + .input(0) + .skip_binder() + .kind() + { ty::Ref(_, _, hir::Mutability::Mut) => "&mut ", ty::Ref(_, _, _) => "&", _ => "", @@ -1036,7 +1043,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match method.kind { ty::AssocKind::Fn => { method.fn_has_self_parameter - && self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1 + && self + .tcx + .bound_fn_sig(method.def_id) + .skip_binder() + .inputs() + .skip_binder() + .len() + == 1 } _ => false, } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 058984731040a..1313230efac0b 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -542,7 +542,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let ty::FnDef(did, ..) = *ty.kind() { let fn_sig = ty.fn_sig(tcx); - if tcx.fn_sig(did).abi() == RustIntrinsic && tcx.item_name(did) == sym::transmute { + if tcx.bound_fn_sig(did).skip_binder().abi() == RustIntrinsic + && tcx.item_name(did) == sym::transmute + { let from = fn_sig.inputs().skip_binder()[0]; let to = fn_sig.output().skip_binder(); // We defer the transmute to the end of typeck, once all inference vars have diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index bb487facc23fd..3fa1469811a2f 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -207,7 +207,7 @@ fn typeck_with_fallback<'tcx>( let fn_sig = if rustc_hir_analysis::collect::get_infer_ret_ty(&decl.output).is_some() { fcx.astconv().ty_of_fn(id, header.unsafety, header.abi, decl, None, None) } else { - tcx.fn_sig(def_id) + tcx.bound_fn_sig(def_id.into()).subst_identity() }; check_abi(tcx, id, span, fn_sig.abi()); diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index 47396204b14e7..b56abfad761f8 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -144,8 +144,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None, ) .map(|pick| { - let sig = self.tcx.fn_sig(pick.item.def_id); - sig.inputs().skip_binder().len().saturating_sub(1) + let sig = self.tcx.bound_fn_sig(pick.item.def_id); + sig.skip_binder().inputs().skip_binder().len().saturating_sub(1) }) .unwrap_or(0); diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 7a2791b11bfdd..37e712db3a098 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -1127,7 +1127,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::AssocKind::Const | ty::AssocKind::Type => rcvr_ty, ty::AssocKind::Fn => self .tcx - .fn_sig(item.def_id) + .bound_fn_sig(item.def_id) + .subst_identity() .inputs() .skip_binder() .get(0) @@ -1264,7 +1265,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && let Some(assoc) = self.associated_value(*impl_did, item_name) && assoc.kind == ty::AssocKind::Fn { - let sig = self.tcx.fn_sig(assoc.def_id); + let sig = self.tcx.bound_fn_sig(assoc.def_id).subst_identity(); sig.inputs().skip_binder().get(0).and_then(|first| if first.peel_refs() == rcvr_ty.peel_refs() { None } else { @@ -2098,7 +2099,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // just changing the path. && pick.item.fn_has_self_parameter && let Some(self_ty) = - self.tcx.fn_sig(pick.item.def_id).inputs().skip_binder().get(0) + self.tcx.bound_fn_sig(pick.item.def_id).subst_identity().inputs().skip_binder().get(0) && self_ty.is_ref() { let suggested_path = match deref_ty.kind() { @@ -2351,7 +2352,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // implement the `AsRef` trait. let skip = skippable.contains(&did) || (("Pin::new" == *pre) && (sym::as_ref == item_name.name)) - || inputs_len.map_or(false, |inputs_len| pick.item.kind == ty::AssocKind::Fn && self.tcx.fn_sig(pick.item.def_id).skip_binder().inputs().len() != inputs_len); + || inputs_len.map_or(false, |inputs_len| pick.item.kind == ty::AssocKind::Fn && self.tcx.bound_fn_sig(pick.item.def_id).skip_binder().skip_binder().inputs().len() != inputs_len); // Make sure the method is defined for the *actual* receiver: we don't // want to treat `Box` as a receiver if it only works because of // an autoderef to `&self` @@ -2730,8 +2731,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // check the method arguments number if let Ok(pick) = probe && - let fn_sig = self.tcx.fn_sig(pick.item.def_id) && - let fn_args = fn_sig.skip_binder().inputs() && + let fn_sig = self.tcx.bound_fn_sig(pick.item.def_id) && + let fn_args = fn_sig.skip_binder().skip_binder().inputs() && fn_args.len() == args.len() + 1 { err.span_suggestion_verbose( method_name.span.shrink_to_hi(), diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs index fd26d7d29c5ee..e607791d3049b 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs @@ -65,7 +65,7 @@ pub fn find_param_with_region<'tcx>( let owner_id = hir.body_owner(body_id); let fn_decl = hir.fn_decl_by_hir_id(owner_id).unwrap(); - let poly_fn_sig = tcx.fn_sig(id); + let poly_fn_sig = tcx.bound_fn_sig(id).subst_identity(); let fn_sig = tcx.liberate_late_bound_regions(id, poly_fn_sig); let body = hir.body(body_id); diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index be47a3e238c1c..b4fd6682df6dd 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1225,7 +1225,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { fn check_foreign_fn(&mut self, id: hir::HirId, decl: &hir::FnDecl<'_>) { let def_id = self.cx.tcx.hir().local_def_id(id); - let sig = self.cx.tcx.fn_sig(def_id); + let sig = self.cx.tcx.bound_fn_sig(def_id.into()).subst_identity(); let sig = self.cx.tcx.erase_late_bound_regions(sig); for (input_ty, input_hir) in iter::zip(sig.inputs(), decl.inputs) { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 29eba278750b1..cba4b10e4c8a6 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1093,7 +1093,7 @@ fn should_encode_trait_impl_trait_tys(tcx: TyCtxt<'_>, def_id: DefId) -> bool { // of the trait fn to look for any RPITITs, but that's kinda doing a lot // of work. We can probably remove this when we refactor RPITITs to be // associated types. - tcx.fn_sig(trait_item_def_id).skip_binder().output().walk().any(|arg| { + tcx.bound_fn_sig(trait_item_def_id).subst_identity().skip_binder().output().walk().any(|arg| { if let ty::GenericArgKind::Type(ty) = arg.unpack() && let ty::Alias(ty::Projection, data) = ty.kind() && tcx.def_kind(data.def_id) == DefKind::ImplTraitPlaceholder diff --git a/compiler/rustc_middle/src/ty/assoc.rs b/compiler/rustc_middle/src/ty/assoc.rs index 47091ca1d69a7..bab084f619224 100644 --- a/compiler/rustc_middle/src/ty/assoc.rs +++ b/compiler/rustc_middle/src/ty/assoc.rs @@ -79,7 +79,7 @@ impl AssocItem { // late-bound regions, and we don't want method signatures to show up // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound // regions just fine, showing `fn(&MyType)`. - tcx.fn_sig(self.def_id).skip_binder().to_string() + tcx.bound_fn_sig(self.def_id).subst_identity().skip_binder().to_string() } ty::AssocKind::Type => format!("type {};", self.name), ty::AssocKind::Const => { diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 6ac00d16c53de..073791fef7a50 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -459,7 +459,7 @@ impl<'tcx> Instance<'tcx> { substs: SubstsRef<'tcx>, ) -> Option> { debug!("resolve_for_vtable(def_id={:?}, substs={:?})", def_id, substs); - let fn_sig = tcx.fn_sig(def_id); + let fn_sig = tcx.bound_fn_sig(def_id).subst_identity(); let is_vtable_shim = !fn_sig.inputs().skip_binder().is_empty() && fn_sig.input(0).skip_binder().is_param(0) && tcx.generics_of(def_id).has_self; diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 95abbb5038017..488903867653f 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -1315,7 +1315,10 @@ pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool { /// Determines whether an item is an intrinsic by Abi. pub fn is_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool { - matches!(tcx.fn_sig(def_id).abi(), Abi::RustIntrinsic | Abi::PlatformIntrinsic) + matches!( + tcx.bound_fn_sig(def_id).skip_binder().abi(), + Abi::RustIntrinsic | Abi::PlatformIntrinsic + ) } pub fn provide(providers: &mut ty::query::Providers) { diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index 9daf68a15f4b1..769f7769530e3 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -637,7 +637,9 @@ fn construct_error( let ty = tcx.ty_error(); let num_params = match body_owner_kind { - hir::BodyOwnerKind::Fn => tcx.fn_sig(def).inputs().skip_binder().len(), + hir::BodyOwnerKind::Fn => { + tcx.bound_fn_sig(def.into()).skip_binder().inputs().skip_binder().len() + } hir::BodyOwnerKind::Closure => { let ty = tcx.type_of(def); match ty.kind() { diff --git a/compiler/rustc_mir_transform/src/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs index b708d780b7005..178cc66144865 100644 --- a/compiler/rustc_mir_transform/src/function_item_references.rs +++ b/compiler/rustc_mir_transform/src/function_item_references.rs @@ -79,7 +79,8 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { for bound in bounds { if let Some(bound_ty) = self.is_pointer_trait(&bound.kind().skip_binder()) { // Get the argument types as they appear in the function signature. - let arg_defs = self.tcx.fn_sig(def_id).skip_binder().inputs(); + let arg_defs = + self.tcx.bound_fn_sig(def_id).subst_identity().skip_binder().inputs(); for (arg_num, arg_def) in arg_defs.iter().enumerate() { // For all types reachable from the argument type in the fn sig for generic_inner_ty in arg_def.walk() { @@ -161,7 +162,7 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { .as_ref() .assert_crate_local() .lint_root; - let fn_sig = self.tcx.fn_sig(fn_id); + let fn_sig = self.tcx.bound_fn_sig(fn_id).skip_binder(); let unsafety = fn_sig.unsafety().prefix_str(); let abi = match fn_sig.abi() { Abi::Rust => String::from(""), diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index dace540fa29d2..5deeb109dd14d 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -798,7 +798,11 @@ pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { let param_env = tcx.param_env(ctor_id); // Normalize the sig. - let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature"); + let sig = tcx + .bound_fn_sig(ctor_id) + .subst_identity() + .no_bound_vars() + .expect("LBR in ADT constructor signature"); let sig = tcx.normalize_erasing_regions(param_env, sig); let ty::Adt(adt_def, substs) = sig.output().kind() else { diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index ec1de3056872b..9311d96bc7e00 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -1296,7 +1296,7 @@ impl<'v> RootCollector<'_, 'v> { }; let start_def_id = self.tcx.require_lang_item(LangItem::Start, None); - let main_ret_ty = self.tcx.fn_sig(main_def_id).output(); + let main_ret_ty = self.tcx.bound_fn_sig(main_def_id).subst_identity().output(); // Given that `main()` has no arguments, // then its return type cannot have diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 9a5d3cceb914e..682985c6c07f7 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -198,7 +198,7 @@ where // Something like `fn() -> Priv {my_func}` is considered a private type even if // `my_func` is public, so we need to visit signatures. if let ty::FnDef(..) = ty.kind() { - tcx.fn_sig(def_id).visit_with(self)?; + tcx.bound_fn_sig(def_id).subst_identity().visit_with(self)?; } // Inherent static methods don't have self type in substs. // Something like `fn() {my_method}` type of the method diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index c9121212cd8f1..f0a6bbf76d454 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -395,7 +395,7 @@ fn virtual_call_violation_for_method<'tcx>( trait_def_id: DefId, method: &ty::AssocItem, ) -> Option { - let sig = tcx.fn_sig(method.def_id); + let sig = tcx.bound_fn_sig(method.def_id).subst_identity(); // The method's first parameter must be named `self` if !method.fn_has_self_parameter { diff --git a/compiler/rustc_ty_utils/src/implied_bounds.rs b/compiler/rustc_ty_utils/src/implied_bounds.rs index 7a24645803c96..81297464eab36 100644 --- a/compiler/rustc_ty_utils/src/implied_bounds.rs +++ b/compiler/rustc_ty_utils/src/implied_bounds.rs @@ -9,12 +9,12 @@ pub fn provide(providers: &mut ty::query::Providers) { fn assumed_wf_types(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::List> { match tcx.def_kind(def_id) { DefKind::Fn => { - let sig = tcx.fn_sig(def_id); + let sig = tcx.bound_fn_sig(def_id).skip_binder(); let liberated_sig = tcx.liberate_late_bound_regions(def_id, sig); liberated_sig.inputs_and_output } DefKind::AssocFn => { - let sig = tcx.fn_sig(def_id); + let sig = tcx.bound_fn_sig(def_id).skip_binder(); let liberated_sig = tcx.liberate_late_bound_regions(def_id, sig); let mut assumed_wf_types: Vec<_> = tcx.assumed_wf_types(tcx.parent(def_id)).as_slice().into(); diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index 13a7664869016..f1a927520b492 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -299,7 +299,7 @@ fn well_formed_types_in_env(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::List { - let fn_sig = tcx.fn_sig(def_id); + let fn_sig = tcx.bound_fn_sig(def_id).subst_identity(); let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig); inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk())); diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index da300b89a4e9b..a41ff4d66594a 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -251,7 +251,7 @@ pub(crate) fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean } fn build_external_function<'tcx>(cx: &mut DocContext<'tcx>, did: DefId) -> Box { - let sig = cx.tcx.fn_sig(did); + let sig = cx.tcx.bound_fn_sig(did).subst_identity(); let late_bound_regions = sig.bound_vars().into_iter().filter_map(|var| match var { ty::BoundVariableKind::Region(ty::BrNamed(_, name)) if name != kw::UnderscoreLifetime => { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 34a7068e5da53..0b37d5ecbd4c8 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1230,7 +1230,7 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( } } ty::AssocKind::Fn => { - let sig = tcx.fn_sig(assoc_item.def_id); + let sig = tcx.bound_fn_sig(assoc_item.def_id).subst_identity(); let late_bound_regions = sig.bound_vars().into_iter().filter_map(|var| match var { ty::BoundVariableKind::Region(ty::BrNamed(_, name)) diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index a020ccd53b842..4f3f738f7b81e 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -665,7 +665,7 @@ impl Item { tcx: TyCtxt<'_>, asyncness: hir::IsAsync, ) -> hir::FnHeader { - let sig = tcx.fn_sig(def_id); + let sig = tcx.bound_fn_sig(def_id).skip_binder(); let constness = if tcx.is_const_fn(def_id) && is_unstable_const_fn(tcx, def_id).is_none() { hir::Constness::Const @@ -677,7 +677,7 @@ impl Item { let header = match *self.kind { ItemKind::ForeignFunctionItem(_) => { let def_id = self.item_id.as_def_id().unwrap(); - let abi = tcx.fn_sig(def_id).abi(); + let abi = tcx.bound_fn_sig(def_id).skip_binder().abi(); hir::FnHeader { unsafety: if abi == Abi::RustIntrinsic { intrinsic_operation_unsafety(tcx, self.item_id.as_def_id().unwrap()) diff --git a/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs b/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs index 9409f4844f54b..2a0e0857c5610 100644 --- a/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs +++ b/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs @@ -17,7 +17,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, && let ExprKind::MethodCall(method_name, receiver, [], _) = cast_expr.peel_blocks().kind && method_name.ident.name == rustc_span::sym::as_ptr && let Some(as_ptr_did) = cx.typeck_results().type_dependent_def_id(cast_expr.peel_blocks().hir_id) - && let as_ptr_sig = cx.tcx.fn_sig(as_ptr_did) + && let as_ptr_sig = cx.tcx.bound_fn_sig(as_ptr_did).subst_identity() && let Some(first_param_ty) = as_ptr_sig.skip_binder().inputs().iter().next() && let ty::Ref(_, _, Mutability::Not) = first_param_ty.kind() && let Some(recv) = snippet_opt(cx, receiver.span) diff --git a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs index 03460689e19ad..9c5a9f583743f 100644 --- a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs +++ b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs @@ -141,7 +141,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { ExprKind::MethodCall(_, receiver, args, _) => { if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) { - let fn_sig = self.cx.tcx.fn_sig(def_id).skip_binder(); + let fn_sig = self.cx.tcx.bound_fn_sig(def_id).subst_identity().skip_binder(); for (expr, bound) in iter::zip(std::iter::once(*receiver).chain(args.iter()), fn_sig.inputs()) { self.ty_bounds.push((*bound).into()); self.visit_expr(expr); @@ -215,7 +215,7 @@ fn fn_sig_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option Some(cx.tcx.fn_sig(*def_id)), + ty::FnDef(def_id, _) => Some(cx.tcx.bound_fn_sig(*def_id).subst_identity()), ty::FnPtr(fn_sig) => Some(*fn_sig), _ => None, } diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 05f2b92c03709..25620f45b8a98 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -759,7 +759,7 @@ fn walk_parents<'tcx>( }) if span.ctxt() == ctxt => { let output = cx .tcx - .erase_late_bound_regions(cx.tcx.fn_sig(owner_id.to_def_id()).output()); + .erase_late_bound_regions(cx.tcx.bound_fn_sig(owner_id.to_def_id()).subst_identity().output()); Some(ty_auto_deref_stability(cx, output, precedence).position_for_result(cx)) }, @@ -791,7 +791,7 @@ fn walk_parents<'tcx>( } else { let output = cx .tcx - .erase_late_bound_regions(cx.tcx.fn_sig(cx.tcx.hir().local_def_id(owner_id)).output()); + .erase_late_bound_regions(cx.tcx.bound_fn_sig(cx.tcx.hir().local_def_id(owner_id).into()).subst_identity().output()); ty_auto_deref_stability(cx, output, precedence).position_for_result(cx) }, ) @@ -858,7 +858,7 @@ fn walk_parents<'tcx>( && let subs = cx .typeck_results() .node_substs_opt(parent.hir_id).map(|subs| &subs[1..]).unwrap_or_default() - && let impl_ty = if cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref() { + && let impl_ty = if cx.tcx.bound_fn_sig(id).subst_identity().skip_binder().inputs()[0].is_ref() { // Trait methods taking `&self` sub_ty } else { @@ -879,7 +879,7 @@ fn walk_parents<'tcx>( return Some(Position::MethodReceiver); } args.iter().position(|arg| arg.hir_id == child_id).map(|i| { - let ty = cx.tcx.fn_sig(id).skip_binder().inputs()[i + 1]; + let ty = cx.tcx.bound_fn_sig(id).subst_identity().skip_binder().inputs()[i + 1]; // `e.hir_id == child_id` for https://github.com/rust-lang/rust-clippy/issues/9739 // `method.args.is_none()` for https://github.com/rust-lang/rust-clippy/issues/9782 if e.hir_id == child_id && method.args.is_none() && let ty::Param(param_ty) = ty.kind() { @@ -896,7 +896,7 @@ fn walk_parents<'tcx>( } else { ty_auto_deref_stability( cx, - cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).input(i + 1)), + cx.tcx.erase_late_bound_regions(cx.tcx.bound_fn_sig(id).subst_identity().input(i + 1)), precedence, ) .position_for_arg() @@ -1093,7 +1093,7 @@ fn needless_borrow_impl_arg_position<'tcx>( let sized_trait_def_id = cx.tcx.lang_items().sized_trait(); let Some(callee_def_id) = fn_def_id(cx, parent) else { return Position::Other(precedence) }; - let fn_sig = cx.tcx.fn_sig(callee_def_id).skip_binder(); + let fn_sig = cx.tcx.bound_fn_sig(callee_def_id).subst_identity().skip_binder(); let substs_with_expr_ty = cx .typeck_results() .node_substs(if let ExprKind::Call(callee, _) = parent.kind { @@ -1221,7 +1221,7 @@ fn has_ref_mut_self_method(cx: &LateContext<'_>, trait_def_id: DefId) -> bool { .in_definition_order() .any(|assoc_item| { if assoc_item.fn_has_self_parameter { - let self_ty = cx.tcx.fn_sig(assoc_item.def_id).skip_binder().inputs()[0]; + let self_ty = cx.tcx.bound_fn_sig(assoc_item.def_id).subst_identity().skip_binder().inputs()[0]; matches!(self_ty.kind(), ty::Ref(_, _, Mutability::Mut)) } else { false diff --git a/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs b/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs index 2c0bf551fd7e2..4f0371c027c25 100644 --- a/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs +++ b/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs @@ -58,7 +58,7 @@ fn check_raw_ptr<'tcx>( }, hir::ExprKind::MethodCall(_, recv, args, _) => { let def_id = typeck.type_dependent_def_id(e.hir_id).unwrap(); - if cx.tcx.fn_sig(def_id).skip_binder().unsafety == hir::Unsafety::Unsafe { + if cx.tcx.bound_fn_sig(def_id).skip_binder().skip_binder().unsafety == hir::Unsafety::Unsafe { check_arg(cx, &raw_ptrs, recv); for arg in args { check_arg(cx, &raw_ptrs, arg); diff --git a/src/tools/clippy/clippy_lints/src/functions/result.rs b/src/tools/clippy/clippy_lints/src/functions/result.rs index 23da145d03825..21de62581f1c3 100644 --- a/src/tools/clippy/clippy_lints/src/functions/result.rs +++ b/src/tools/clippy/clippy_lints/src/functions/result.rs @@ -21,7 +21,7 @@ fn result_err_ty<'tcx>( ) -> Option<(&'tcx hir::Ty<'tcx>, Ty<'tcx>)> { if !in_external_macro(cx.sess(), item_span) && let hir::FnRetTy::Return(hir_ty) = decl.output - && let ty = cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).output()) + && let ty = cx.tcx.erase_late_bound_regions(cx.tcx.bound_fn_sig(id.into()).subst_identity().output()) && is_type_diagnostic_item(cx, ty, sym::Result) && let ty::Adt(_, substs) = ty.kind() { diff --git a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs index aaecc4fa8f256..d971684a3aa9c 100644 --- a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs +++ b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs @@ -124,7 +124,7 @@ fn show_lint(cx: &LateContext<'_>, item: &ImplItem<'_>) { .expect("Failed to get trait ID of `Display`!"); // Get the real type of 'self' - let self_type = cx.tcx.fn_sig(item.owner_id).input(0); + let self_type = cx.tcx.bound_fn_sig(item.owner_id.to_def_id()).skip_binder().input(0); let self_type = self_type.skip_binder().peel_refs(); // Emit either a warning or an error diff --git a/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs b/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs index e76de77f195d7..131af2fd9c381 100644 --- a/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs @@ -66,7 +66,7 @@ impl<'tcx> LateLintPass<'tcx> for IterNotReturningIterator { fn check_sig(cx: &LateContext<'_>, name: &str, sig: &FnSig<'_>, fn_id: LocalDefId) { if sig.decl.implicit_self.has_implicit_self() { - let ret_ty = cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(fn_id).output()); + let ret_ty = cx.tcx.erase_late_bound_regions(cx.tcx.bound_fn_sig(fn_id.into()).subst_identity().output()); let ret_ty = cx .tcx .try_normalize_erasing_regions(cx.param_env, ret_ty) diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index 3c70c9cf19a51..121d6b9f0fe7e 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -144,7 +144,7 @@ impl<'tcx> LateLintPass<'tcx> for LenZero { if let Some(local_id) = ty_id.as_local(); let ty_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_id); if !is_lint_allowed(cx, LEN_WITHOUT_IS_EMPTY, ty_hir_id); - if let Some(output) = parse_len_output(cx, cx.tcx.fn_sig(item.owner_id).skip_binder()); + if let Some(output) = parse_len_output(cx, cx.tcx.bound_fn_sig(item.owner_id.to_def_id()).subst_identity().skip_binder()); then { let (name, kind) = match cx.tcx.hir().find(ty_hir_id) { Some(Node::ForeignItem(x)) => (x.ident.name, "extern type"), @@ -196,7 +196,7 @@ fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: Symbol) -> bool { item.ident.name == name && if let AssocItemKind::Fn { has_self } = item.kind { - has_self && { cx.tcx.fn_sig(item.id.owner_id).inputs().skip_binder().len() == 1 } + has_self && { cx.tcx.bound_fn_sig(item.id.owner_id.to_def_id()).skip_binder().inputs().skip_binder().len() == 1 } } else { false } @@ -224,7 +224,7 @@ fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items .any(|i| { i.kind == ty::AssocKind::Fn && i.fn_has_self_parameter - && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1 + && cx.tcx.bound_fn_sig(i.def_id).skip_binder().inputs().skip_binder().len() == 1 }); if !is_empty_method_found { @@ -342,7 +342,7 @@ fn check_for_is_empty<'tcx>( ), Some(is_empty) if !(is_empty.fn_has_self_parameter - && check_is_empty_sig(cx.tcx.fn_sig(is_empty.def_id).skip_binder(), self_kind, output)) => + && check_is_empty_sig(cx.tcx.bound_fn_sig(is_empty.def_id).subst_identity().skip_binder(), self_kind, output)) => { ( format!( @@ -473,7 +473,7 @@ fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { /// Gets an `AssocItem` and return true if it matches `is_empty(self)`. fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool { if item.kind == ty::AssocKind::Fn { - let sig = cx.tcx.fn_sig(item.def_id); + let sig = cx.tcx.bound_fn_sig(item.def_id).skip_binder(); let ty = sig.skip_binder(); ty.inputs().len() == 1 } else { diff --git a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs index 3bca93d80aa7f..3e025bc0e7160 100644 --- a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs @@ -370,7 +370,7 @@ impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> { ExprKind::MethodCall(_, receiver, args, _) => { let def_id = self.cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap(); for (ty, expr) in iter::zip( - self.cx.tcx.fn_sig(def_id).inputs().skip_binder(), + self.cx.tcx.bound_fn_sig(def_id).subst_identity().inputs().skip_binder(), std::iter::once(receiver).chain(args.iter()), ) { self.prefer_mutable = false; diff --git a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs index 59195d1ae4e0a..a179dd091e421 100644 --- a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs +++ b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs @@ -104,7 +104,7 @@ fn is_unit_function(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { let ty = cx.typeck_results().expr_ty(expr); if let ty::FnDef(id, _) = *ty.kind() { - if let Some(fn_type) = cx.tcx.fn_sig(id).no_bound_vars() { + if let Some(fn_type) = cx.tcx.bound_fn_sig(id).subst_identity().no_bound_vars() { return is_unit_type(fn_type.output()); } } diff --git a/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs b/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs index a9189b31c5710..3f670ebc9178b 100644 --- a/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs +++ b/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs @@ -70,7 +70,7 @@ pub(super) fn check<'tcx>( if let hir::ExprKind::Path(ref p) = fun.kind { match cx.qpath_res(p, fun.hir_id) { hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!( - cx.tcx.fn_sig(def_id).output().skip_binder().kind(), + cx.tcx.bound_fn_sig(def_id).subst_identity().output().skip_binder().kind(), ty::Ref(re, ..) if re.is_static(), ), _ => false, @@ -84,7 +84,7 @@ pub(super) fn check<'tcx>( .type_dependent_def_id(arg.hir_id) .map_or(false, |method_id| { matches!( - cx.tcx.fn_sig(method_id).output().skip_binder().kind(), + cx.tcx.bound_fn_sig(method_id).subst_identity().output().skip_binder().kind(), ty::Ref(re, ..) if re.is_static() ) }) diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index 77be61b479340..6002ef1340bea 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -3352,7 +3352,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. })); if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind { - let method_sig = cx.tcx.fn_sig(impl_item.owner_id); + let method_sig = cx.tcx.bound_fn_sig(impl_item.owner_id.to_def_id()).subst_identity(); let method_sig = cx.tcx.erase_late_bound_regions(method_sig); let first_arg_ty_opt = method_sig.inputs().iter().next().copied(); // if this impl block implements a trait, lint in trait definition instead diff --git a/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs b/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs index f4d3ef3b74250..1a1715d03a7cb 100644 --- a/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs @@ -137,7 +137,7 @@ pub(super) fn check<'tcx>( /// Checks if the given method call matches the expected signature of `([&[mut]] self) -> bool` fn is_is_empty_sig(cx: &LateContext<'_>, call_id: HirId) -> bool { cx.typeck_results().type_dependent_def_id(call_id).map_or(false, |id| { - let sig = cx.tcx.fn_sig(id).skip_binder(); + let sig = cx.tcx.bound_fn_sig(id).subst_identity().skip_binder(); sig.inputs().len() == 1 && sig.output().is_bool() }) } @@ -165,7 +165,7 @@ fn iterates_same_ty<'tcx>(cx: &LateContext<'tcx>, iter_ty: Ty<'tcx>, collect_ty: fn is_contains_sig(cx: &LateContext<'_>, call_id: HirId, iter_expr: &Expr<'_>) -> bool { let typeck = cx.typeck_results(); if let Some(id) = typeck.type_dependent_def_id(call_id) - && let sig = cx.tcx.fn_sig(id) + && let sig = cx.tcx.bound_fn_sig(id).subst_identity() && sig.skip_binder().output().is_bool() && let [_, search_ty] = *sig.skip_binder().inputs() && let ty::Ref(_, search_ty, Mutability::Not) = *cx.tcx.erase_late_bound_regions(sig.rebind(search_ty)).kind() diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index b812e81cb107b..8036e787aaecc 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -246,7 +246,7 @@ fn check_other_call_arg<'tcx>( if_chain! { if let Some((maybe_call, maybe_arg)) = skip_addr_of_ancestors(cx, expr); if let Some((callee_def_id, _, recv, call_args)) = get_callee_substs_and_args(cx, maybe_call); - let fn_sig = cx.tcx.fn_sig(callee_def_id).skip_binder(); + let fn_sig = cx.tcx.bound_fn_sig(callee_def_id).subst_identity().skip_binder(); if let Some(i) = recv.into_iter().chain(call_args).position(|arg| arg.hir_id == maybe_arg.hir_id); if let Some(input) = fn_sig.inputs().get(i); let (input, n_refs) = peel_mid_ty_refs(*input); @@ -386,7 +386,7 @@ fn can_change_type<'a>(cx: &LateContext<'a>, mut expr: &'a Expr<'a>, mut ty: Ty< Node::Expr(parent_expr) => { if let Some((callee_def_id, call_substs, recv, call_args)) = get_callee_substs_and_args(cx, parent_expr) { - let fn_sig = cx.tcx.fn_sig(callee_def_id).skip_binder(); + let fn_sig = cx.tcx.bound_fn_sig(callee_def_id).subst_identity().skip_binder(); if let Some(arg_index) = recv.into_iter().chain(call_args).position(|arg| arg.hir_id == expr.hir_id) && let Some(param_ty) = fn_sig.inputs().get(arg_index) && let ty::Param(ParamTy { index: param_index , ..}) = param_ty.kind() diff --git a/src/tools/clippy/clippy_lints/src/mut_key.rs b/src/tools/clippy/clippy_lints/src/mut_key.rs index a651020ca6566..a2868883673f5 100644 --- a/src/tools/clippy/clippy_lints/src/mut_key.rs +++ b/src/tools/clippy/clippy_lints/src/mut_key.rs @@ -138,7 +138,7 @@ impl MutableKeyType { fn check_sig(&self, cx: &LateContext<'_>, item_hir_id: hir::HirId, decl: &hir::FnDecl<'_>) { let fn_def_id = cx.tcx.hir().local_def_id(item_hir_id); - let fn_sig = cx.tcx.fn_sig(fn_def_id); + let fn_sig = cx.tcx.bound_fn_sig(fn_def_id.into()).subst_identity(); for (hir_ty, ty) in iter::zip(decl.inputs, fn_sig.inputs().skip_binder()) { self.check_ty_(cx, hir_ty.span, *ty); } diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs index 8c9d4c5cfe66f..e3d25603a7157 100644 --- a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs +++ b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs @@ -147,7 +147,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { ctx }; - let fn_sig = cx.tcx.fn_sig(fn_def_id); + let fn_sig = cx.tcx.bound_fn_sig(fn_def_id.into()).subst_identity(); let fn_sig = cx.tcx.erase_late_bound_regions(fn_sig); for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(body.params).enumerate() { diff --git a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs index 2d21aaa4f7fdb..5512109c6cbb1 100644 --- a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs +++ b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs @@ -143,7 +143,7 @@ impl<'tcx> PassByRefOrValue { return; } - let fn_sig = cx.tcx.fn_sig(def_id); + let fn_sig = cx.tcx.bound_fn_sig(def_id.into()).subst_identity(); let fn_body = cx.enclosing_body.map(|id| cx.tcx.hir().body(id)); // Gather all the lifetimes found in the output type which may affect whether diff --git a/src/tools/clippy/clippy_lints/src/ptr.rs b/src/tools/clippy/clippy_lints/src/ptr.rs index 262953042581a..0a2d35015f573 100644 --- a/src/tools/clippy/clippy_lints/src/ptr.rs +++ b/src/tools/clippy/clippy_lints/src/ptr.rs @@ -164,7 +164,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { check_mut_from_ref(cx, sig, None); for arg in check_fn_args( cx, - cx.tcx.fn_sig(item.owner_id).skip_binder().inputs(), + cx.tcx.bound_fn_sig(item.owner_id.to_def_id()).subst_identity().skip_binder().inputs(), sig.decl.inputs, &[], ) @@ -217,7 +217,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { check_mut_from_ref(cx, sig, Some(body)); let decl = sig.decl; - let sig = cx.tcx.fn_sig(item_id).skip_binder(); + let sig = cx.tcx.bound_fn_sig(item_id.to_def_id()).subst_identity().skip_binder(); let lint_args: Vec<_> = check_fn_args(cx, sig.inputs(), decl.inputs, body.params) .filter(|arg| !is_trait_item || arg.mutability() == Mutability::Not) .collect(); @@ -624,7 +624,7 @@ fn check_ptr_arg_usage<'tcx>(cx: &LateContext<'tcx>, body: &'tcx Body<'_>, args: return; }; - match *self.cx.tcx.fn_sig(id).skip_binder().inputs()[i].peel_refs().kind() { + match *self.cx.tcx.bound_fn_sig(id).subst_identity().skip_binder().inputs()[i].peel_refs().kind() { ty::Dynamic(preds, _, _) if !matches_preds(self.cx, args.deref_ty.ty(self.cx), preds) => { set_skip_flag(); }, diff --git a/src/tools/clippy/clippy_lints/src/returns.rs b/src/tools/clippy/clippy_lints/src/returns.rs index bbbd9e4989e97..f3c5033060433 100644 --- a/src/tools/clippy/clippy_lints/src/returns.rs +++ b/src/tools/clippy/clippy_lints/src/returns.rs @@ -287,7 +287,8 @@ fn last_statement_borrows<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) if let Some(def_id) = fn_def_id(cx, e) && cx .tcx - .fn_sig(def_id) + .bound_fn_sig(def_id) + .subst_identity() .skip_binder() .output() .walk() diff --git a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs index a138a4baa9b31..5df26d8b0a38c 100644 --- a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs +++ b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs @@ -76,7 +76,7 @@ fn get_projection_pred<'tcx>( fn get_args_to_check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Vec<(usize, String)> { let mut args_to_check = Vec::new(); if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) { - let fn_sig = cx.tcx.fn_sig(def_id); + let fn_sig = cx.tcx.bound_fn_sig(def_id).subst_identity(); let generics = cx.tcx.predicates_of(def_id); let fn_mut_preds = get_trait_predicates_for_trait_id(cx, generics, cx.tcx.lang_items().fn_mut_trait()); let ord_preds = get_trait_predicates_for_trait_id(cx, generics, cx.tcx.get_diagnostic_item(sym::Ord)); diff --git a/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs b/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs index ce9ebad8c89a8..681e59a1575d4 100644 --- a/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs +++ b/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs @@ -156,7 +156,7 @@ fn needs_inferred_result_ty( }, _ => return false, }; - let sig = cx.tcx.fn_sig(id).skip_binder(); + let sig = cx.tcx.bound_fn_sig(id).subst_identity().skip_binder(); if let ty::Param(output_ty) = *sig.output().kind() { let args: Vec<&Expr<'_>> = if let Some(receiver) = receiver { std::iter::once(receiver).chain(args.iter()).collect() diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index 6ae9d9d635380..09324fd92943c 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -146,7 +146,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { .associated_item(impl_item.owner_id) .trait_item_def_id .expect("impl method matches a trait method"); - let trait_method_sig = cx.tcx.fn_sig(trait_method); + let trait_method_sig = cx.tcx.bound_fn_sig(trait_method).subst_identity(); let trait_method_sig = cx.tcx.erase_late_bound_regions(trait_method_sig); // `impl_inputs_outputs` is an iterator over the types (`hir::Ty`) declared in the diff --git a/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs b/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs index 96711936968b5..38588e32dbfe9 100644 --- a/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs +++ b/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs @@ -79,7 +79,7 @@ fn fn_eagerness(cx: &LateContext<'_>, fn_id: DefId, name: Symbol, have_one_arg: && subs.types().all(|x| matches!(x.peel_refs().kind(), ty::Param(_))) { // Limit the function to either `(self) -> bool` or `(&self) -> bool` - match &**cx.tcx.fn_sig(fn_id).skip_binder().inputs_and_output { + match &**cx.tcx.bound_fn_sig(fn_id).subst_identity().skip_binder().inputs_and_output { [arg, res] if !arg.is_mutable_ptr() && arg.peel_refs() == ty && res.is_bool() => NoChange, _ => Lazy, } diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 7a4a9036dd363..ccc5f3503d2f5 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -1379,7 +1379,7 @@ pub fn get_enclosing_loop_or_multi_call_closure<'tcx>( .chain(args.iter()) .position(|arg| arg.hir_id == id)?; let id = cx.typeck_results().type_dependent_def_id(e.hir_id)?; - let ty = cx.tcx.fn_sig(id).skip_binder().inputs()[i]; + let ty = cx.tcx.bound_fn_sig(id).subst_identity().skip_binder().inputs()[i]; ty_is_fn_once_param(cx.tcx, ty, cx.tcx.param_env(id).caller_bounds()).then_some(()) }, _ => None, @@ -1580,14 +1580,14 @@ pub fn is_direct_expn_of(span: Span, name: &str) -> Option { /// Convenience function to get the return type of a function. pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId) -> Ty<'tcx> { let fn_def_id = cx.tcx.hir().local_def_id(fn_item); - let ret_ty = cx.tcx.fn_sig(fn_def_id).output(); + let ret_ty = cx.tcx.bound_fn_sig(fn_def_id.into()).subst_identity().output(); cx.tcx.erase_late_bound_regions(ret_ty) } /// Convenience function to get the nth argument type of a function. pub fn nth_arg<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId, nth: usize) -> Ty<'tcx> { let fn_def_id = cx.tcx.hir().local_def_id(fn_item); - let arg = cx.tcx.fn_sig(fn_def_id).input(nth); + let arg = cx.tcx.bound_fn_sig(fn_def_id.into()).subst_identity().input(nth); cx.tcx.erase_late_bound_regions(arg) } diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index e5d7da682813c..1552e343582ee 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -55,7 +55,7 @@ pub fn is_min_const_fn<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, msrv: &Msrv) // impl trait is gone in MIR, so check the return type manually check_ty( tcx, - tcx.fn_sig(def_id).output().skip_binder(), + tcx.bound_fn_sig(def_id).subst_identity().output().skip_binder(), body.local_decls.iter().next().unwrap().source_info.span, )?; diff --git a/src/tools/clippy/clippy_utils/src/sugg.rs b/src/tools/clippy/clippy_utils/src/sugg.rs index 2d1044af17e8c..d6a698bbeaa8a 100644 --- a/src/tools/clippy/clippy_utils/src/sugg.rs +++ b/src/tools/clippy/clippy_utils/src/sugg.rs @@ -885,7 +885,7 @@ impl<'tcx> DerefDelegate<'_, 'tcx> { .cx .typeck_results() .type_dependent_def_id(parent_expr.hir_id) - .map(|did| self.cx.tcx.fn_sig(did).skip_binder()) + .map(|did| self.cx.tcx.bound_fn_sig(did).subst_identity().skip_binder()) { std::iter::once(receiver) .chain(call_args.iter()) diff --git a/src/tools/clippy/clippy_utils/src/ty.rs b/src/tools/clippy/clippy_utils/src/ty.rs index 99fba4fe741a1..14fc2c1001704 100644 --- a/src/tools/clippy/clippy_utils/src/ty.rs +++ b/src/tools/clippy/clippy_utils/src/ty.rs @@ -628,7 +628,7 @@ impl<'tcx> ExprFnSig<'tcx> { /// If the expression is function like, get the signature for it. pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option> { if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = path_res(cx, expr) { - Some(ExprFnSig::Sig(cx.tcx.fn_sig(id), Some(id))) + Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst_identity(), Some(id))) } else { ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs()) } diff --git a/src/tools/clippy/clippy_utils/src/visitors.rs b/src/tools/clippy/clippy_utils/src/visitors.rs index 14c01a60b4c32..1680a40206a3a 100644 --- a/src/tools/clippy/clippy_utils/src/visitors.rs +++ b/src/tools/clippy/clippy_utils/src/visitors.rs @@ -392,12 +392,12 @@ pub fn is_expr_unsafe<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool { .cx .typeck_results() .type_dependent_def_id(e.hir_id) - .map_or(false, |id| self.cx.tcx.fn_sig(id).unsafety() == Unsafety::Unsafe) => + .map_or(false, |id| self.cx.tcx.bound_fn_sig(id).skip_binder().unsafety() == Unsafety::Unsafe) => { self.is_unsafe = true; }, ExprKind::Call(func, _) => match *self.cx.typeck_results().expr_ty(func).peel_refs().kind() { - ty::FnDef(id, _) if self.cx.tcx.fn_sig(id).unsafety() == Unsafety::Unsafe => self.is_unsafe = true, + ty::FnDef(id, _) if self.cx.tcx.bound_fn_sig(id).skip_binder().unsafety() == Unsafety::Unsafe => self.is_unsafe = true, ty::FnPtr(sig) if sig.unsafety() == Unsafety::Unsafe => self.is_unsafe = true, _ => walk_expr(self, e), }, diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index 6c87dad1f1f4a..e333a66a0b3ae 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -357,7 +357,7 @@ pub fn create_ecx<'mir, 'tcx: 'mir>( match entry_type { EntryFnType::Main { .. } => { let start_id = tcx.lang_items().start_fn().unwrap(); - let main_ret_ty = tcx.fn_sig(entry_id).output(); + let main_ret_ty = tcx.bound_fn_sig(entry_id).subst_identity().output(); let main_ret_ty = main_ret_ty.no_bound_vars().unwrap(); let start_instance = ty::Instance::resolve( tcx, From c2414dfaa4a01a60ec65c44879e103c3fc3152bb Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Wed, 18 Jan 2023 16:52:47 -0700 Subject: [PATCH 393/500] change fn_sig query to use EarlyBinder; remove bound_fn_sig query; add EarlyBinder to fn_sig in metadata --- .../src/diagnostics/conflict_errors.rs | 2 +- .../rustc_borrowck/src/diagnostics/mod.rs | 2 +- .../rustc_borrowck/src/universal_regions.rs | 4 ++-- .../rustc_codegen_cranelift/src/main_shim.rs | 2 +- compiler/rustc_codegen_llvm/src/attributes.rs | 2 +- compiler/rustc_codegen_ssa/src/base.rs | 2 +- .../rustc_codegen_ssa/src/codegen_attrs.rs | 6 +++--- .../src/const_eval/fn_queries.rs | 2 +- .../src/transform/check_consts/mod.rs | 2 +- .../rustc_hir_analysis/src/astconv/mod.rs | 2 +- .../src/check/compare_impl_item.rs | 20 +++++++++---------- .../rustc_hir_analysis/src/check/intrinsic.rs | 7 ++++++- compiler/rustc_hir_analysis/src/check/mod.rs | 2 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 8 ++++---- compiler/rustc_hir_analysis/src/collect.rs | 7 ++++--- .../rustc_hir_analysis/src/collect/type_of.rs | 2 +- compiler/rustc_hir_analysis/src/lib.rs | 4 ++-- .../src/variance/constraints.rs | 2 +- compiler/rustc_hir_typeck/src/callee.rs | 2 +- compiler/rustc_hir_typeck/src/demand.rs | 12 +++-------- compiler/rustc_hir_typeck/src/expr.rs | 2 +- compiler/rustc_hir_typeck/src/lib.rs | 2 +- .../rustc_hir_typeck/src/method/confirm.rs | 2 +- compiler/rustc_hir_typeck/src/method/mod.rs | 4 ++-- compiler/rustc_hir_typeck/src/method/probe.rs | 4 ++-- .../rustc_hir_typeck/src/method/suggest.rs | 10 +++++----- .../src/infer/error_reporting/mod.rs | 8 ++++---- .../error_reporting/nice_region_error/util.rs | 2 +- compiler/rustc_lint/src/types.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 4 ++-- compiler/rustc_metadata/src/rmeta/mod.rs | 2 +- compiler/rustc_middle/src/query/mod.rs | 2 +- compiler/rustc_middle/src/ty/assoc.rs | 2 +- compiler/rustc_middle/src/ty/instance.rs | 2 +- compiler/rustc_middle/src/ty/print/pretty.rs | 2 +- compiler/rustc_middle/src/ty/sty.rs | 2 +- compiler/rustc_middle/src/ty/util.rs | 9 +-------- compiler/rustc_mir_build/src/build/mod.rs | 4 +--- .../src/function_item_references.rs | 5 ++--- compiler/rustc_mir_transform/src/inline.rs | 2 +- compiler/rustc_mir_transform/src/shim.rs | 8 ++++---- compiler/rustc_monomorphize/src/collector.rs | 2 +- compiler/rustc_privacy/src/lib.rs | 2 +- .../src/traits/object_safety.rs | 2 +- compiler/rustc_traits/src/chalk/db.rs | 2 +- compiler/rustc_ty_utils/src/abi.rs | 2 +- compiler/rustc_ty_utils/src/implied_bounds.rs | 4 ++-- compiler/rustc_ty_utils/src/ty.rs | 2 +- src/librustdoc/clean/inline.rs | 2 +- src/librustdoc/clean/mod.rs | 2 +- src/librustdoc/clean/types.rs | 4 ++-- .../clippy_lints/src/casts/as_ptr_cast_mut.rs | 2 +- .../src/default_numeric_fallback.rs | 4 ++-- .../clippy/clippy_lints/src/dereference.rs | 14 ++++++------- .../src/functions/not_unsafe_ptr_arg_deref.rs | 2 +- .../clippy_lints/src/functions/result.rs | 2 +- .../clippy_lints/src/inherent_to_string.rs | 2 +- .../src/iter_not_returning_iterator.rs | 2 +- src/tools/clippy/clippy_lints/src/len_zero.rs | 10 +++++----- .../src/loops/needless_range_loop.rs | 2 +- .../clippy/clippy_lints/src/map_unit_fn.rs | 2 +- .../src/methods/expect_fun_call.rs | 4 ++-- .../clippy/clippy_lints/src/methods/mod.rs | 2 +- .../src/methods/needless_collect.rs | 4 ++-- .../src/methods/unnecessary_to_owned.rs | 4 ++-- src/tools/clippy/clippy_lints/src/mut_key.rs | 2 +- .../src/needless_pass_by_value.rs | 2 +- .../clippy_lints/src/pass_by_ref_or_value.rs | 2 +- src/tools/clippy/clippy_lints/src/ptr.rs | 6 +++--- src/tools/clippy/clippy_lints/src/returns.rs | 2 +- .../src/unit_return_expecting_ord.rs | 2 +- .../src/unit_types/let_unit_value.rs | 2 +- src/tools/clippy/clippy_lints/src/use_self.rs | 2 +- .../clippy/clippy_utils/src/eager_or_lazy.rs | 2 +- src/tools/clippy/clippy_utils/src/lib.rs | 6 +++--- .../clippy_utils/src/qualify_min_const_fn.rs | 2 +- src/tools/clippy/clippy_utils/src/sugg.rs | 2 +- src/tools/clippy/clippy_utils/src/ty.rs | 4 ++-- src/tools/clippy/clippy_utils/src/visitors.rs | 4 ++-- src/tools/miri/src/eval.rs | 2 +- 80 files changed, 142 insertions(+), 152 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 8e910dea9f3e4..50c0faf4597f1 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -2599,7 +2599,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { match ty.kind() { ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig( self.mir_def_id(), - self.infcx.tcx.bound_fn_sig(self.mir_def_id().into()).subst_identity(), + self.infcx.tcx.fn_sig(self.mir_def_id()).subst_identity(), ), _ => None, } diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 409b18a579d6d..13a24767debc3 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -1136,7 +1136,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { && let self_ty = infcx.replace_bound_vars_with_fresh_vars( fn_call_span, LateBoundRegionConversionTime::FnCall, - tcx.bound_fn_sig(method_did).subst_identity().input(0), + tcx.fn_sig(method_did).subst_identity().input(0), ) && infcx.can_eq(self.param_env, ty, self_ty).is_ok() { diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index 4b62e5cce47bf..5380913f5c86a 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -472,7 +472,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { // C-variadic fns also have a `VaList` input that's not listed in the signature // (as it's created inside the body itself, not passed in from outside). if let DefiningTy::FnDef(def_id, _) = defining_ty { - if self.infcx.tcx.bound_fn_sig(def_id).skip_binder().c_variadic() { + if self.infcx.tcx.fn_sig(def_id).skip_binder().c_variadic() { let va_list_did = self.infcx.tcx.require_lang_item( LangItem::VaList, Some(self.infcx.tcx.def_span(self.mir_def.did)), @@ -665,7 +665,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { } DefiningTy::FnDef(def_id, _) => { - let sig = tcx.bound_fn_sig(def_id).subst_identity(); + let sig = tcx.fn_sig(def_id).subst_identity(); let sig = indices.fold_to_region_vids(tcx, sig); sig.inputs_and_output() } diff --git a/compiler/rustc_codegen_cranelift/src/main_shim.rs b/compiler/rustc_codegen_cranelift/src/main_shim.rs index f46e6b6528c88..bc1b1ec7cd597 100644 --- a/compiler/rustc_codegen_cranelift/src/main_shim.rs +++ b/compiler/rustc_codegen_cranelift/src/main_shim.rs @@ -46,7 +46,7 @@ pub(crate) fn maybe_create_entry_wrapper( is_main_fn: bool, sigpipe: u8, ) { - let main_ret_ty = tcx.bound_fn_sig(rust_main_def_id).subst_identity().output(); + let main_ret_ty = tcx.fn_sig(rust_main_def_id).subst_identity().output(); // Given that `main()` has no arguments, // then its return type cannot have // late-bound regions, since late-bound diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index 4d802206f2365..54ac7a46cf2f3 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -441,7 +441,7 @@ pub fn from_fn_attrs<'ll, 'tcx>( // the WebAssembly specification, which has this feature. This won't be // needed when LLVM enables this `multivalue` feature by default. if !cx.tcx.is_closure(instance.def_id()) { - let abi = cx.tcx.bound_fn_sig(instance.def_id()).skip_binder().abi(); + let abi = cx.tcx.fn_sig(instance.def_id()).skip_binder().abi(); if abi == Abi::Wasm { function_features.push("+multivalue".to_string()); } diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 32d3cfe6fc650..2013a2dcbc22b 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -436,7 +436,7 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( cx.type_func(&[], cx.type_int()) }; - let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).output(); + let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).subst_identity().output(); // Given that `main()` has no arguments, // then its return type cannot have // late-bound regions, since late-bound diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 61cea048a5e26..87b819ebc9849 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -214,7 +214,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs { } } else if attr.has_name(sym::cmse_nonsecure_entry) { if validate_fn_only_attr(attr.span) - && !matches!(tcx.bound_fn_sig(did.into()).skip_binder().abi(), abi::Abi::C { .. }) + && !matches!(tcx.fn_sig(did).skip_binder().abi(), abi::Abi::C { .. }) { struct_span_err!( tcx.sess, @@ -234,7 +234,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs { } else if attr.has_name(sym::track_caller) { if !tcx.is_closure(did.to_def_id()) && validate_fn_only_attr(attr.span) - && tcx.bound_fn_sig(did.into()).skip_binder().abi() != abi::Abi::Rust + && tcx.fn_sig(did).skip_binder().abi() != abi::Abi::Rust { struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI") .emit(); @@ -266,7 +266,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs { } } else if attr.has_name(sym::target_feature) { if !tcx.is_closure(did.to_def_id()) - && tcx.bound_fn_sig(did.into()).skip_binder().unsafety() == hir::Unsafety::Normal + && tcx.fn_sig(did).skip_binder().unsafety() == hir::Unsafety::Normal { if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc { // The `#[target_feature]` attribute is allowed on diff --git a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs index f91912104e5ab..f92277b111374 100644 --- a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs @@ -64,7 +64,7 @@ fn is_promotable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> bool { && match tcx.lookup_const_stability(def_id) { Some(stab) => { if cfg!(debug_assertions) && stab.promotable { - let sig = tcx.bound_fn_sig(def_id); + let sig = tcx.fn_sig(def_id); assert_eq!( sig.skip_binder().unsafety(), hir::Unsafety::Normal, diff --git a/compiler/rustc_const_eval/src/transform/check_consts/mod.rs b/compiler/rustc_const_eval/src/transform/check_consts/mod.rs index 64155b2594b00..e841500bf3e05 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/mod.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/mod.rs @@ -72,7 +72,7 @@ impl<'mir, 'tcx> ConstCx<'mir, 'tcx> { let ty::Closure(_, substs) = ty.kind() else { bug!("type_of closure not ty::Closure") }; substs.as_closure().sig() } else { - self.tcx.bound_fn_sig(did).subst_identity() + self.tcx.fn_sig(did).subst_identity() } } } diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index 6435b05cef8a8..27284f8b983b6 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -3140,7 +3140,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { trait_ref.def_id, )?; - let fn_sig = tcx.bound_fn_sig(assoc.def_id).subst( + let fn_sig = tcx.fn_sig(assoc.def_id).subst( tcx, trait_ref.substs.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)), ); diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 475be4fde7aa1..d93d2314ed65d 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -249,7 +249,7 @@ fn compare_method_predicate_entailment<'tcx>( let unnormalized_impl_sig = infcx.replace_bound_vars_with_fresh_vars( impl_m_span, infer::HigherRankedType, - tcx.bound_fn_sig(impl_m.def_id).subst_identity(), + tcx.fn_sig(impl_m.def_id).subst_identity(), ); let unnormalized_impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(unnormalized_impl_sig)); @@ -257,7 +257,7 @@ fn compare_method_predicate_entailment<'tcx>( let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig); debug!("compare_impl_method: impl_fty={:?}", impl_sig); - let trait_sig = tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs); + let trait_sig = tcx.fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs); let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig); // Next, add all inputs and output as well-formed tys. Importantly, @@ -422,8 +422,8 @@ fn extract_bad_args_for_implies_lint<'tcx>( // Map late-bound regions from trait to impl, so the names are right. let mapping = std::iter::zip( - tcx.bound_fn_sig(trait_m.def_id).subst_identity().bound_vars(), - tcx.bound_fn_sig(impl_m.def_id).subst_identity().bound_vars(), + tcx.fn_sig(trait_m.def_id).subst_identity().bound_vars(), + tcx.fn_sig(impl_m.def_id).subst_identity().bound_vars(), ) .filter_map(|(impl_bv, trait_bv)| { if let ty::BoundVariableKind::Region(impl_bv) = impl_bv @@ -540,7 +540,7 @@ fn compare_asyncness<'tcx>( trait_item_span: Option, ) -> Result<(), ErrorGuaranteed> { if tcx.asyncness(trait_m.def_id) == hir::IsAsync::Async { - match tcx.bound_fn_sig(impl_m.def_id).subst_identity().skip_binder().output().kind() { + match tcx.fn_sig(impl_m.def_id).subst_identity().skip_binder().output().kind() { ty::Alias(ty::Opaque, ..) => { // allow both `async fn foo()` and `fn foo() -> impl Future` } @@ -643,7 +643,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( infcx.replace_bound_vars_with_fresh_vars( return_span, infer::HigherRankedType, - tcx.bound_fn_sig(impl_m.def_id).subst_identity(), + tcx.fn_sig(impl_m.def_id).subst_identity(), ), ); impl_sig.error_reported()?; @@ -657,7 +657,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( let unnormalized_trait_sig = tcx .liberate_late_bound_regions( impl_m.def_id, - tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs), + tcx.fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs), ) .fold_with(&mut collector); let trait_sig = ocx.normalize(&norm_cause, param_env, unnormalized_trait_sig); @@ -1117,7 +1117,7 @@ fn compare_self_type<'tcx>( ty::ImplContainer => impl_trait_ref.self_ty(), ty::TraitContainer => tcx.types.self_param, }; - let self_arg_ty = tcx.bound_fn_sig(method.def_id).subst_identity().input(0); + let self_arg_ty = tcx.fn_sig(method.def_id).subst_identity().input(0); let param_env = ty::ParamEnv::reveal_all(); let infcx = tcx.infer_ctxt().build(); @@ -1348,8 +1348,8 @@ fn compare_number_of_method_arguments<'tcx>( trait_m: &ty::AssocItem, trait_item_span: Option, ) -> Result<(), ErrorGuaranteed> { - let impl_m_fty = tcx.bound_fn_sig(impl_m.def_id); - let trait_m_fty = tcx.bound_fn_sig(trait_m.def_id); + let impl_m_fty = tcx.fn_sig(impl_m.def_id); + let trait_m_fty = tcx.fn_sig(trait_m.def_id); let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len(); let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len(); diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index fe2720fa1afc9..955cacf03b1c6 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -58,7 +58,12 @@ fn equate_intrinsic_type<'tcx>( let fty = tcx.mk_fn_ptr(sig); let it_def_id = it.owner_id.def_id; let cause = ObligationCause::new(it.span, it_def_id, ObligationCauseCode::IntrinsicType); - require_same_types(tcx, &cause, tcx.mk_fn_ptr(tcx.bound_fn_sig(it.owner_id.to_def_id()).subst_identity()), fty); + require_same_types( + tcx, + &cause, + tcx.mk_fn_ptr(tcx.fn_sig(it.owner_id).subst_identity()), + fty, + ); } } diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index 3b0ddad25fc82..2f2ee702837bc 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -445,7 +445,7 @@ fn suggestion_signature(assoc: &ty::AssocItem, tcx: TyCtxt<'_>) -> String { // regions just fine, showing `fn(&MyType)`. fn_sig_suggestion( tcx, - tcx.bound_fn_sig(assoc.def_id).subst_identity().skip_binder(), + tcx.fn_sig(assoc.def_id).subst_identity().skip_binder(), assoc.ident(tcx), tcx.predicates_of(assoc.def_id), assoc, diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index a0a0c72ded96b..870c57d5e0595 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -386,7 +386,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from. let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions( item_def_id.to_def_id(), - tcx.bound_fn_sig(item_def_id.to_def_id()).subst_identity(), + tcx.fn_sig(item_def_id).subst_identity(), ); gather_gat_bounds( tcx, @@ -1018,7 +1018,7 @@ fn check_associated_item( wfcx.register_wf_obligation(span, loc, ty.into()); } ty::AssocKind::Fn => { - let sig = tcx.bound_fn_sig(item.def_id).subst_identity(); + let sig = tcx.fn_sig(item.def_id).subst_identity(); let hir_sig = sig_if_method.expect("bad signature for method"); check_fn_or_method( wfcx, @@ -1203,7 +1203,7 @@ fn check_item_fn( decl: &hir::FnDecl<'_>, ) { enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| { - let sig = tcx.bound_fn_sig(def_id.into()).subst_identity(); + let sig = tcx.fn_sig(def_id).subst_identity(); check_fn_or_method(wfcx, ident.span, sig, decl, def_id); }) } @@ -1638,7 +1638,7 @@ fn check_method_receiver<'tcx>( let span = fn_sig.decl.inputs[0].span; - let sig = tcx.bound_fn_sig(method.def_id).subst_identity(); + let sig = tcx.fn_sig(method.def_id).subst_identity(); let sig = tcx.liberate_late_bound_regions(method.def_id, sig); let sig = wfcx.normalize(span, None, sig); diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index e253459ef64ab..b73a05ff39846 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -1087,7 +1087,7 @@ pub fn get_infer_ret_ty<'hir>(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir } #[instrument(level = "debug", skip(tcx))] -fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> { +fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::EarlyBinder> { use rustc_hir::Node::*; use rustc_hir::*; @@ -1096,7 +1096,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> { let icx = ItemCtxt::new(tcx, def_id.to_def_id()); - match tcx.hir().get(hir_id) { + let output = match tcx.hir().get(hir_id) { TraitItem(hir::TraitItem { kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)), generics, @@ -1169,7 +1169,8 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> { x => { bug!("unexpected sort of node in fn_sig(): {:?}", x); } - } + }; + ty::EarlyBinder(output) } fn infer_return_ty_for_fn_sig<'tcx>( diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 82c4aaba0891a..b28458fb7cfc4 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -868,7 +868,7 @@ fn infer_placeholder_type<'a>( match ty.kind() { ty::FnDef(def_id, _) => { - self.tcx.mk_fn_ptr(self.tcx.bound_fn_sig(*def_id).subst_identity()) + self.tcx.mk_fn_ptr(self.tcx.fn_sig(*def_id).subst_identity()) } // FIXME: non-capturing closures should also suggest a function pointer ty::Closure(..) | ty::Generator(..) => { diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index 7a359ab22feac..c2fa46e563e60 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -182,7 +182,7 @@ fn require_same_types<'tcx>( } fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { - let main_fnsig = tcx.bound_fn_sig(main_def_id).subst_identity(); + let main_fnsig = tcx.fn_sig(main_def_id).subst_identity(); let main_span = tcx.def_span(main_def_id); fn main_fn_diagnostics_def_id(tcx: TyCtxt<'_>, def_id: DefId, sp: Span) -> LocalDefId { @@ -449,7 +449,7 @@ fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: DefId) { ObligationCauseCode::StartFunctionType, ), se_ty, - tcx.mk_fn_ptr(tcx.bound_fn_sig(start_def_id.into()).subst_identity()), + tcx.mk_fn_ptr(tcx.fn_sig(start_def_id).subst_identity()), ); } _ => { diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index b662dfca71a30..2cd2b6a5f7631 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -121,7 +121,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { ty::FnDef(..) => { self.add_constraints_from_sig( current_item, - tcx.bound_fn_sig(def_id.into()).subst_identity(), + tcx.fn_sig(def_id).subst_identity(), self.covariant, ); } diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index b617821fbd652..c220956a2012e 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -367,7 +367,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Ty<'tcx> { let (fn_sig, def_id) = match *callee_ty.kind() { ty::FnDef(def_id, subst) => { - let fn_sig = self.tcx.bound_fn_sig(def_id).subst(self.tcx, subst); + let fn_sig = self.tcx.fn_sig(def_id).subst(self.tcx, subst); // Unit testing: function items annotated with // `#[rustc_evaluate_where_clauses]` trigger special output diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index c01def290353b..45bd2026e414a 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -299,7 +299,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { // We special case methods, because they can influence inference through the // call's arguments and we can provide a more explicit span. - let sig = self.tcx.bound_fn_sig(def_id).subst_identity(); + let sig = self.tcx.fn_sig(def_id).subst_identity(); let def_self_ty = sig.input(0).skip_binder(); let rcvr_ty = self.node_ty(rcvr.hir_id); // Get the evaluated type *after* calling the method call, so that the influence @@ -613,7 +613,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ), match self .tcx - .bound_fn_sig(m.def_id) + .fn_sig(m.def_id) .subst_identity() .input(0) .skip_binder() @@ -1043,13 +1043,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match method.kind { ty::AssocKind::Fn => { method.fn_has_self_parameter - && self - .tcx - .bound_fn_sig(method.def_id) - .skip_binder() - .inputs() - .skip_binder() - .len() + && self.tcx.fn_sig(method.def_id).skip_binder().inputs().skip_binder().len() == 1 } _ => false, diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 1313230efac0b..74913bac72411 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -542,7 +542,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let ty::FnDef(did, ..) = *ty.kind() { let fn_sig = ty.fn_sig(tcx); - if tcx.bound_fn_sig(did).skip_binder().abi() == RustIntrinsic + if tcx.fn_sig(did).skip_binder().abi() == RustIntrinsic && tcx.item_name(did) == sym::transmute { let from = fn_sig.inputs().skip_binder()[0]; diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 3fa1469811a2f..04ac9c085ea21 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -207,7 +207,7 @@ fn typeck_with_fallback<'tcx>( let fn_sig = if rustc_hir_analysis::collect::get_infer_ret_ty(&decl.output).is_some() { fcx.astconv().ty_of_fn(id, header.unsafety, header.abi, decl, None, None) } else { - tcx.bound_fn_sig(def_id.into()).subst_identity() + tcx.fn_sig(def_id).subst_identity() }; check_abi(tcx, id, span, fn_sig.abi()); diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 372ea30ebd08e..ff3596f595b45 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -503,7 +503,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { debug!("method_predicates after subst = {:?}", method_predicates); - let sig = self.tcx.bound_fn_sig(def_id); + let sig = self.tcx.fn_sig(def_id); let sig = sig.subst(self.tcx, all_substs); debug!("type scheme substituted, sig={:?}", sig); diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index b56abfad761f8..c0b6ed2e614dd 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -144,7 +144,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None, ) .map(|pick| { - let sig = self.tcx.bound_fn_sig(pick.item.def_id); + let sig = self.tcx.fn_sig(pick.item.def_id); sig.skip_binder().inputs().skip_binder().len().saturating_sub(1) }) .unwrap_or(0); @@ -399,7 +399,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // N.B., instantiate late-bound regions before normalizing the // function signature so that normalization does not need to deal // with bound regions. - let fn_sig = tcx.bound_fn_sig(def_id); + let fn_sig = tcx.fn_sig(def_id); let fn_sig = fn_sig.subst(self.tcx, substs); let fn_sig = self.replace_bound_vars_with_fresh_vars(obligation.cause.span, infer::FnCall, fn_sig); diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 939f9c93a02ca..f67beab3c31a6 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -922,7 +922,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { ) -> bool { match method.kind { ty::AssocKind::Fn => { - let fty = self.tcx.bound_fn_sig(method.def_id); + let fty = self.tcx.fn_sig(method.def_id); self.probe(|_| { let substs = self.fresh_substs_for_item(self.span, method.def_id); let fty = fty.subst(self.tcx, substs); @@ -1887,7 +1887,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { #[instrument(level = "debug", skip(self))] fn xform_method_sig(&self, method: DefId, substs: SubstsRef<'tcx>) -> ty::FnSig<'tcx> { - let fn_sig = self.tcx.bound_fn_sig(method); + let fn_sig = self.tcx.fn_sig(method); debug!(?fn_sig); assert!(!substs.has_escaping_bound_vars()); diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 37e712db3a098..31d55a41d8a31 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -1127,7 +1127,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::AssocKind::Const | ty::AssocKind::Type => rcvr_ty, ty::AssocKind::Fn => self .tcx - .bound_fn_sig(item.def_id) + .fn_sig(item.def_id) .subst_identity() .inputs() .skip_binder() @@ -1265,7 +1265,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && let Some(assoc) = self.associated_value(*impl_did, item_name) && assoc.kind == ty::AssocKind::Fn { - let sig = self.tcx.bound_fn_sig(assoc.def_id).subst_identity(); + let sig = self.tcx.fn_sig(assoc.def_id).subst_identity(); sig.inputs().skip_binder().get(0).and_then(|first| if first.peel_refs() == rcvr_ty.peel_refs() { None } else { @@ -2099,7 +2099,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // just changing the path. && pick.item.fn_has_self_parameter && let Some(self_ty) = - self.tcx.bound_fn_sig(pick.item.def_id).subst_identity().inputs().skip_binder().get(0) + self.tcx.fn_sig(pick.item.def_id).subst_identity().inputs().skip_binder().get(0) && self_ty.is_ref() { let suggested_path = match deref_ty.kind() { @@ -2352,7 +2352,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // implement the `AsRef` trait. let skip = skippable.contains(&did) || (("Pin::new" == *pre) && (sym::as_ref == item_name.name)) - || inputs_len.map_or(false, |inputs_len| pick.item.kind == ty::AssocKind::Fn && self.tcx.bound_fn_sig(pick.item.def_id).skip_binder().skip_binder().inputs().len() != inputs_len); + || inputs_len.map_or(false, |inputs_len| pick.item.kind == ty::AssocKind::Fn && self.tcx.fn_sig(pick.item.def_id).skip_binder().skip_binder().inputs().len() != inputs_len); // Make sure the method is defined for the *actual* receiver: we don't // want to treat `Box` as a receiver if it only works because of // an autoderef to `&self` @@ -2731,7 +2731,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // check the method arguments number if let Ok(pick) = probe && - let fn_sig = self.tcx.bound_fn_sig(pick.item.def_id) && + let fn_sig = self.tcx.fn_sig(pick.item.def_id) && let fn_args = fn_sig.skip_binder().skip_binder().inputs() && fn_args.len() == args.len() + 1 { err.span_suggestion_verbose( diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index d19a0007f0880..b11db8396c920 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -1345,8 +1345,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => { - let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1); - let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2); + let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1); + let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2); let mut values = self.cmp_fn_sig(&sig1, &sig2); let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1)); let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2)); @@ -1357,7 +1357,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => { - let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1); + let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1); let mut values = self.cmp_fn_sig(&sig1, sig2); values.0.push_highlighted(format!( " {{{}}}", @@ -1367,7 +1367,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => { - let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2); + let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2); let mut values = self.cmp_fn_sig(sig1, &sig2); values.1.push_normal(format!( " {{{}}}", diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs index e607791d3049b..4c0f457b46a7c 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs @@ -65,7 +65,7 @@ pub fn find_param_with_region<'tcx>( let owner_id = hir.body_owner(body_id); let fn_decl = hir.fn_decl_by_hir_id(owner_id).unwrap(); - let poly_fn_sig = tcx.bound_fn_sig(id).subst_identity(); + let poly_fn_sig = tcx.fn_sig(id).subst_identity(); let fn_sig = tcx.liberate_late_bound_regions(id, poly_fn_sig); let body = hir.body(body_id); diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index b4fd6682df6dd..9be4b577aeb10 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1225,7 +1225,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { fn check_foreign_fn(&mut self, id: hir::HirId, decl: &hir::FnDecl<'_>) { let def_id = self.cx.tcx.hir().local_def_id(id); - let sig = self.cx.tcx.bound_fn_sig(def_id.into()).subst_identity(); + let sig = self.cx.tcx.fn_sig(def_id).subst_identity(); let sig = self.cx.tcx.erase_late_bound_regions(sig); for (input_ty, input_hir) in iter::zip(sig.inputs(), decl.inputs) { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index cba4b10e4c8a6..6dd138a6ca330 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1093,7 +1093,7 @@ fn should_encode_trait_impl_trait_tys(tcx: TyCtxt<'_>, def_id: DefId) -> bool { // of the trait fn to look for any RPITITs, but that's kinda doing a lot // of work. We can probably remove this when we refactor RPITITs to be // associated types. - tcx.bound_fn_sig(trait_item_def_id).subst_identity().skip_binder().output().walk().any(|arg| { + tcx.fn_sig(trait_item_def_id).subst_identity().skip_binder().output().walk().any(|arg| { if let ty::GenericArgKind::Type(ty) = arg.unpack() && let ty::Alias(ty::Projection, data) = ty.kind() && tcx.def_kind(data.def_id) == DefKind::ImplTraitPlaceholder @@ -1628,7 +1628,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { ty::Closure(_, substs) => { let constness = self.tcx.constness(def_id.to_def_id()); self.tables.constness.set(def_id.to_def_id().index, constness); - record!(self.tables.fn_sig[def_id.to_def_id()] <- substs.as_closure().sig()); + record!(self.tables.fn_sig[def_id.to_def_id()] <- ty::EarlyBinder(substs.as_closure().sig())); } _ => bug!("closure that is neither generator nor closure"), diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 698b2ebc4732a..cf735e5bd17b4 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -369,7 +369,7 @@ define_tables! { super_predicates_of: Table>>, type_of: Table>>, variances_of: Table>, - fn_sig: Table>>, + fn_sig: Table>>>, codegen_fn_attrs: Table>, impl_trait_ref: Table>>>, const_param_default: Table>>>, diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 2e5261331e8be..dc626c2433c4e 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -814,7 +814,7 @@ rustc_queries! { } /// Computes the signature of the function. - query fn_sig(key: DefId) -> ty::PolyFnSig<'tcx> { + query fn_sig(key: DefId) -> ty::EarlyBinder> { desc { |tcx| "computing function signature of `{}`", tcx.def_path_str(key) } cache_on_disk_if { key.is_local() } separate_provide_extern diff --git a/compiler/rustc_middle/src/ty/assoc.rs b/compiler/rustc_middle/src/ty/assoc.rs index bab084f619224..71cecfb558fb2 100644 --- a/compiler/rustc_middle/src/ty/assoc.rs +++ b/compiler/rustc_middle/src/ty/assoc.rs @@ -79,7 +79,7 @@ impl AssocItem { // late-bound regions, and we don't want method signatures to show up // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound // regions just fine, showing `fn(&MyType)`. - tcx.bound_fn_sig(self.def_id).subst_identity().skip_binder().to_string() + tcx.fn_sig(self.def_id).subst_identity().skip_binder().to_string() } ty::AssocKind::Type => format!("type {};", self.name), ty::AssocKind::Const => { diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 073791fef7a50..8b4fccc58bd44 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -459,7 +459,7 @@ impl<'tcx> Instance<'tcx> { substs: SubstsRef<'tcx>, ) -> Option> { debug!("resolve_for_vtable(def_id={:?}, substs={:?})", def_id, substs); - let fn_sig = tcx.bound_fn_sig(def_id).subst_identity(); + let fn_sig = tcx.fn_sig(def_id).subst_identity(); let is_vtable_shim = !fn_sig.inputs().skip_binder().is_empty() && fn_sig.input(0).skip_binder().is_param(0) && tcx.generics_of(def_id).has_self; diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index ae7c20fff0c34..2f30dbebbc22c 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -675,7 +675,7 @@ pub trait PrettyPrinter<'tcx>: p!(")") } ty::FnDef(def_id, substs) => { - let sig = self.tcx().bound_fn_sig(def_id).subst(self.tcx(), substs); + let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs); p!(print(sig), " {{", print_value_path(def_id, substs), "}}"); } ty::FnPtr(ref bare_fn) => p!(print(bare_fn)), diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 6a7b23e40a779..0656c77d0b51c 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -2059,7 +2059,7 @@ impl<'tcx> Ty<'tcx> { pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> { match self.kind() { - FnDef(def_id, substs) => tcx.bound_fn_sig(*def_id).subst(tcx, substs), + FnDef(def_id, substs) => tcx.fn_sig(*def_id).subst(tcx, substs), FnPtr(f) => *f, Error(_) => { // ignore errors (#54954) diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 488903867653f..54ea63bb4cff7 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -643,10 +643,6 @@ impl<'tcx> TyCtxt<'tcx> { ty::EarlyBinder(self.collect_return_position_impl_trait_in_trait_tys(def_id)) } - pub fn bound_fn_sig(self, def_id: DefId) -> ty::EarlyBinder> { - ty::EarlyBinder(self.fn_sig(def_id)) - } - pub fn bound_explicit_item_bounds( self, def_id: DefId, @@ -1315,10 +1311,7 @@ pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool { /// Determines whether an item is an intrinsic by Abi. pub fn is_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool { - matches!( - tcx.bound_fn_sig(def_id).skip_binder().abi(), - Abi::RustIntrinsic | Abi::PlatformIntrinsic - ) + matches!(tcx.fn_sig(def_id).skip_binder().abi(), Abi::RustIntrinsic | Abi::PlatformIntrinsic) } pub fn provide(providers: &mut ty::query::Providers) { diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index 769f7769530e3..f85831b4fc6b5 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -637,9 +637,7 @@ fn construct_error( let ty = tcx.ty_error(); let num_params = match body_owner_kind { - hir::BodyOwnerKind::Fn => { - tcx.bound_fn_sig(def.into()).skip_binder().inputs().skip_binder().len() - } + hir::BodyOwnerKind::Fn => tcx.fn_sig(def).skip_binder().inputs().skip_binder().len(), hir::BodyOwnerKind::Closure => { let ty = tcx.type_of(def); match ty.kind() { diff --git a/compiler/rustc_mir_transform/src/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs index 178cc66144865..19a74d8fc6649 100644 --- a/compiler/rustc_mir_transform/src/function_item_references.rs +++ b/compiler/rustc_mir_transform/src/function_item_references.rs @@ -79,8 +79,7 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { for bound in bounds { if let Some(bound_ty) = self.is_pointer_trait(&bound.kind().skip_binder()) { // Get the argument types as they appear in the function signature. - let arg_defs = - self.tcx.bound_fn_sig(def_id).subst_identity().skip_binder().inputs(); + let arg_defs = self.tcx.fn_sig(def_id).subst_identity().skip_binder().inputs(); for (arg_num, arg_def) in arg_defs.iter().enumerate() { // For all types reachable from the argument type in the fn sig for generic_inner_ty in arg_def.walk() { @@ -162,7 +161,7 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { .as_ref() .assert_crate_local() .lint_root; - let fn_sig = self.tcx.bound_fn_sig(fn_id).skip_binder(); + let fn_sig = self.tcx.fn_sig(fn_id).skip_binder(); let unsafety = fn_sig.unsafety().prefix_str(); let abi = match fn_sig.abi() { Abi::Rust => String::from(""), diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 28c9080d38d7d..69627fc5cb24a 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -331,7 +331,7 @@ impl<'tcx> Inliner<'tcx> { return None; } - let fn_sig = self.tcx.bound_fn_sig(def_id).subst(self.tcx, substs); + let fn_sig = self.tcx.fn_sig(def_id).subst(self.tcx, substs); let source_info = SourceInfo { span: fn_span, ..terminator.source_info }; return Some(CallSite { callee, fn_sig, block: bb, target, source_info }); diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 5deeb109dd14d..8d4fe74e7d392 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -152,7 +152,7 @@ fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option>) } else { InternalSubsts::identity_for_item(tcx, def_id) }; - let sig = tcx.bound_fn_sig(def_id).subst(tcx, substs); + let sig = tcx.fn_sig(def_id).subst(tcx, substs); let sig = tcx.erase_late_bound_regions(sig); let span = tcx.def_span(def_id); @@ -363,7 +363,7 @@ impl<'tcx> CloneShimBuilder<'tcx> { // we must subst the self_ty because it's // otherwise going to be TySelf and we can't index // or access fields of a Place of type TySelf. - let sig = tcx.bound_fn_sig(def_id).subst(tcx, &[self_ty.into()]); + let sig = tcx.fn_sig(def_id).subst(tcx, &[self_ty.into()]); let sig = tcx.erase_late_bound_regions(sig); let span = tcx.def_span(def_id); @@ -606,7 +606,7 @@ fn build_call_shim<'tcx>( }; let def_id = instance.def_id(); - let sig = tcx.bound_fn_sig(def_id); + let sig = tcx.fn_sig(def_id); let sig = sig.map_bound(|sig| tcx.erase_late_bound_regions(sig)); assert_eq!(sig_substs.is_some(), !instance.has_polymorphic_mir_body()); @@ -799,7 +799,7 @@ pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { // Normalize the sig. let sig = tcx - .bound_fn_sig(ctor_id) + .fn_sig(ctor_id) .subst_identity() .no_bound_vars() .expect("LBR in ADT constructor signature"); diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 9311d96bc7e00..28e806fdd4741 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -1296,7 +1296,7 @@ impl<'v> RootCollector<'_, 'v> { }; let start_def_id = self.tcx.require_lang_item(LangItem::Start, None); - let main_ret_ty = self.tcx.bound_fn_sig(main_def_id).subst_identity().output(); + let main_ret_ty = self.tcx.fn_sig(main_def_id).subst_identity().output(); // Given that `main()` has no arguments, // then its return type cannot have diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 682985c6c07f7..5c701bef30486 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -198,7 +198,7 @@ where // Something like `fn() -> Priv {my_func}` is considered a private type even if // `my_func` is public, so we need to visit signatures. if let ty::FnDef(..) = ty.kind() { - tcx.bound_fn_sig(def_id).subst_identity().visit_with(self)?; + tcx.fn_sig(def_id).subst_identity().visit_with(self)?; } // Inherent static methods don't have self type in substs. // Something like `fn() {my_method}` type of the method diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index f0a6bbf76d454..55c2f7e2e358d 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -395,7 +395,7 @@ fn virtual_call_violation_for_method<'tcx>( trait_def_id: DefId, method: &ty::AssocItem, ) -> Option { - let sig = tcx.bound_fn_sig(method.def_id).subst_identity(); + let sig = tcx.fn_sig(method.def_id).subst_identity(); // The method's first parameter must be named `self` if !method.fn_has_self_parameter { diff --git a/compiler/rustc_traits/src/chalk/db.rs b/compiler/rustc_traits/src/chalk/db.rs index f146de3966ba1..2e9107e153c2a 100644 --- a/compiler/rustc_traits/src/chalk/db.rs +++ b/compiler/rustc_traits/src/chalk/db.rs @@ -269,7 +269,7 @@ impl<'tcx> chalk_solve::RustIrDatabase> for RustIrDatabase<'t let where_clauses = self.where_clauses_for(def_id, bound_vars); - let sig = self.interner.tcx.bound_fn_sig(def_id); + let sig = self.interner.tcx.fn_sig(def_id); let (inputs_and_output, iobinders, _) = crate::chalk::lowering::collect_bound_vars( self.interner, self.interner.tcx, diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index e47e68e0670b9..1c74aeca5ab1f 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -41,7 +41,7 @@ fn fn_sig_for_fn_abi<'tcx>( // We normalize the `fn_sig` again after substituting at a later point. let mut sig = match *ty.kind() { ty::FnDef(def_id, substs) => tcx - .bound_fn_sig(def_id) + .fn_sig(def_id) .map_bound(|fn_sig| { tcx.normalize_erasing_regions(tcx.param_env(def_id), fn_sig) }) diff --git a/compiler/rustc_ty_utils/src/implied_bounds.rs b/compiler/rustc_ty_utils/src/implied_bounds.rs index 81297464eab36..d308543304cce 100644 --- a/compiler/rustc_ty_utils/src/implied_bounds.rs +++ b/compiler/rustc_ty_utils/src/implied_bounds.rs @@ -9,12 +9,12 @@ pub fn provide(providers: &mut ty::query::Providers) { fn assumed_wf_types(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::List> { match tcx.def_kind(def_id) { DefKind::Fn => { - let sig = tcx.bound_fn_sig(def_id).skip_binder(); + let sig = tcx.fn_sig(def_id).skip_binder(); let liberated_sig = tcx.liberate_late_bound_regions(def_id, sig); liberated_sig.inputs_and_output } DefKind::AssocFn => { - let sig = tcx.bound_fn_sig(def_id).skip_binder(); + let sig = tcx.fn_sig(def_id).skip_binder(); let liberated_sig = tcx.liberate_late_bound_regions(def_id, sig); let mut assumed_wf_types: Vec<_> = tcx.assumed_wf_types(tcx.parent(def_id)).as_slice().into(); diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index f1a927520b492..77986ad48613d 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -299,7 +299,7 @@ fn well_formed_types_in_env(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::List { - let fn_sig = tcx.bound_fn_sig(def_id).subst_identity(); + let fn_sig = tcx.fn_sig(def_id).subst_identity(); let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig); inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk())); diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index a41ff4d66594a..6592692d8b214 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -251,7 +251,7 @@ pub(crate) fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean } fn build_external_function<'tcx>(cx: &mut DocContext<'tcx>, did: DefId) -> Box { - let sig = cx.tcx.bound_fn_sig(did).subst_identity(); + let sig = cx.tcx.fn_sig(did).subst_identity(); let late_bound_regions = sig.bound_vars().into_iter().filter_map(|var| match var { ty::BoundVariableKind::Region(ty::BrNamed(_, name)) if name != kw::UnderscoreLifetime => { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 0b37d5ecbd4c8..8230518288581 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1230,7 +1230,7 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( } } ty::AssocKind::Fn => { - let sig = tcx.bound_fn_sig(assoc_item.def_id).subst_identity(); + let sig = tcx.fn_sig(assoc_item.def_id).subst_identity(); let late_bound_regions = sig.bound_vars().into_iter().filter_map(|var| match var { ty::BoundVariableKind::Region(ty::BrNamed(_, name)) diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 4f3f738f7b81e..e43f389b8854c 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -665,7 +665,7 @@ impl Item { tcx: TyCtxt<'_>, asyncness: hir::IsAsync, ) -> hir::FnHeader { - let sig = tcx.bound_fn_sig(def_id).skip_binder(); + let sig = tcx.fn_sig(def_id).skip_binder(); let constness = if tcx.is_const_fn(def_id) && is_unstable_const_fn(tcx, def_id).is_none() { hir::Constness::Const @@ -677,7 +677,7 @@ impl Item { let header = match *self.kind { ItemKind::ForeignFunctionItem(_) => { let def_id = self.item_id.as_def_id().unwrap(); - let abi = tcx.bound_fn_sig(def_id).skip_binder().abi(); + let abi = tcx.fn_sig(def_id).skip_binder().abi(); hir::FnHeader { unsafety: if abi == Abi::RustIntrinsic { intrinsic_operation_unsafety(tcx, self.item_id.as_def_id().unwrap()) diff --git a/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs b/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs index 2a0e0857c5610..1633ffd589c38 100644 --- a/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs +++ b/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs @@ -17,7 +17,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, && let ExprKind::MethodCall(method_name, receiver, [], _) = cast_expr.peel_blocks().kind && method_name.ident.name == rustc_span::sym::as_ptr && let Some(as_ptr_did) = cx.typeck_results().type_dependent_def_id(cast_expr.peel_blocks().hir_id) - && let as_ptr_sig = cx.tcx.bound_fn_sig(as_ptr_did).subst_identity() + && let as_ptr_sig = cx.tcx.fn_sig(as_ptr_did).subst_identity() && let Some(first_param_ty) = as_ptr_sig.skip_binder().inputs().iter().next() && let ty::Ref(_, _, Mutability::Not) = first_param_ty.kind() && let Some(recv) = snippet_opt(cx, receiver.span) diff --git a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs index 9c5a9f583743f..f806ba238c7c6 100644 --- a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs +++ b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs @@ -141,7 +141,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { ExprKind::MethodCall(_, receiver, args, _) => { if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) { - let fn_sig = self.cx.tcx.bound_fn_sig(def_id).subst_identity().skip_binder(); + let fn_sig = self.cx.tcx.fn_sig(def_id).subst_identity().skip_binder(); for (expr, bound) in iter::zip(std::iter::once(*receiver).chain(args.iter()), fn_sig.inputs()) { self.ty_bounds.push((*bound).into()); self.visit_expr(expr); @@ -215,7 +215,7 @@ fn fn_sig_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option Some(cx.tcx.bound_fn_sig(*def_id).subst_identity()), + ty::FnDef(def_id, _) => Some(cx.tcx.fn_sig(*def_id).subst_identity()), ty::FnPtr(fn_sig) => Some(*fn_sig), _ => None, } diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 25620f45b8a98..fa3e5aa6b7213 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -759,7 +759,7 @@ fn walk_parents<'tcx>( }) if span.ctxt() == ctxt => { let output = cx .tcx - .erase_late_bound_regions(cx.tcx.bound_fn_sig(owner_id.to_def_id()).subst_identity().output()); + .erase_late_bound_regions(cx.tcx.fn_sig(owner_id).subst_identity().output()); Some(ty_auto_deref_stability(cx, output, precedence).position_for_result(cx)) }, @@ -791,7 +791,7 @@ fn walk_parents<'tcx>( } else { let output = cx .tcx - .erase_late_bound_regions(cx.tcx.bound_fn_sig(cx.tcx.hir().local_def_id(owner_id).into()).subst_identity().output()); + .erase_late_bound_regions(cx.tcx.fn_sig(cx.tcx.hir().local_def_id(owner_id)).subst_identity().output()); ty_auto_deref_stability(cx, output, precedence).position_for_result(cx) }, ) @@ -858,7 +858,7 @@ fn walk_parents<'tcx>( && let subs = cx .typeck_results() .node_substs_opt(parent.hir_id).map(|subs| &subs[1..]).unwrap_or_default() - && let impl_ty = if cx.tcx.bound_fn_sig(id).subst_identity().skip_binder().inputs()[0].is_ref() { + && let impl_ty = if cx.tcx.fn_sig(id).subst_identity().skip_binder().inputs()[0].is_ref() { // Trait methods taking `&self` sub_ty } else { @@ -879,7 +879,7 @@ fn walk_parents<'tcx>( return Some(Position::MethodReceiver); } args.iter().position(|arg| arg.hir_id == child_id).map(|i| { - let ty = cx.tcx.bound_fn_sig(id).subst_identity().skip_binder().inputs()[i + 1]; + let ty = cx.tcx.fn_sig(id).subst_identity().skip_binder().inputs()[i + 1]; // `e.hir_id == child_id` for https://github.com/rust-lang/rust-clippy/issues/9739 // `method.args.is_none()` for https://github.com/rust-lang/rust-clippy/issues/9782 if e.hir_id == child_id && method.args.is_none() && let ty::Param(param_ty) = ty.kind() { @@ -896,7 +896,7 @@ fn walk_parents<'tcx>( } else { ty_auto_deref_stability( cx, - cx.tcx.erase_late_bound_regions(cx.tcx.bound_fn_sig(id).subst_identity().input(i + 1)), + cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).subst_identity().input(i + 1)), precedence, ) .position_for_arg() @@ -1093,7 +1093,7 @@ fn needless_borrow_impl_arg_position<'tcx>( let sized_trait_def_id = cx.tcx.lang_items().sized_trait(); let Some(callee_def_id) = fn_def_id(cx, parent) else { return Position::Other(precedence) }; - let fn_sig = cx.tcx.bound_fn_sig(callee_def_id).subst_identity().skip_binder(); + let fn_sig = cx.tcx.fn_sig(callee_def_id).subst_identity().skip_binder(); let substs_with_expr_ty = cx .typeck_results() .node_substs(if let ExprKind::Call(callee, _) = parent.kind { @@ -1221,7 +1221,7 @@ fn has_ref_mut_self_method(cx: &LateContext<'_>, trait_def_id: DefId) -> bool { .in_definition_order() .any(|assoc_item| { if assoc_item.fn_has_self_parameter { - let self_ty = cx.tcx.bound_fn_sig(assoc_item.def_id).subst_identity().skip_binder().inputs()[0]; + let self_ty = cx.tcx.fn_sig(assoc_item.def_id).subst_identity().skip_binder().inputs()[0]; matches!(self_ty.kind(), ty::Ref(_, _, Mutability::Mut)) } else { false diff --git a/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs b/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs index 4f0371c027c25..cdb5e22e75982 100644 --- a/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs +++ b/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs @@ -58,7 +58,7 @@ fn check_raw_ptr<'tcx>( }, hir::ExprKind::MethodCall(_, recv, args, _) => { let def_id = typeck.type_dependent_def_id(e.hir_id).unwrap(); - if cx.tcx.bound_fn_sig(def_id).skip_binder().skip_binder().unsafety == hir::Unsafety::Unsafe { + if cx.tcx.fn_sig(def_id).skip_binder().skip_binder().unsafety == hir::Unsafety::Unsafe { check_arg(cx, &raw_ptrs, recv); for arg in args { check_arg(cx, &raw_ptrs, arg); diff --git a/src/tools/clippy/clippy_lints/src/functions/result.rs b/src/tools/clippy/clippy_lints/src/functions/result.rs index 21de62581f1c3..fa2a9b30c058d 100644 --- a/src/tools/clippy/clippy_lints/src/functions/result.rs +++ b/src/tools/clippy/clippy_lints/src/functions/result.rs @@ -21,7 +21,7 @@ fn result_err_ty<'tcx>( ) -> Option<(&'tcx hir::Ty<'tcx>, Ty<'tcx>)> { if !in_external_macro(cx.sess(), item_span) && let hir::FnRetTy::Return(hir_ty) = decl.output - && let ty = cx.tcx.erase_late_bound_regions(cx.tcx.bound_fn_sig(id.into()).subst_identity().output()) + && let ty = cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).subst_identity().output()) && is_type_diagnostic_item(cx, ty, sym::Result) && let ty::Adt(_, substs) = ty.kind() { diff --git a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs index d971684a3aa9c..612c3ea8fdfd8 100644 --- a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs +++ b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs @@ -124,7 +124,7 @@ fn show_lint(cx: &LateContext<'_>, item: &ImplItem<'_>) { .expect("Failed to get trait ID of `Display`!"); // Get the real type of 'self' - let self_type = cx.tcx.bound_fn_sig(item.owner_id.to_def_id()).skip_binder().input(0); + let self_type = cx.tcx.fn_sig(item.owner_id).skip_binder().input(0); let self_type = self_type.skip_binder().peel_refs(); // Emit either a warning or an error diff --git a/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs b/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs index 131af2fd9c381..7557a9ce13f11 100644 --- a/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs @@ -66,7 +66,7 @@ impl<'tcx> LateLintPass<'tcx> for IterNotReturningIterator { fn check_sig(cx: &LateContext<'_>, name: &str, sig: &FnSig<'_>, fn_id: LocalDefId) { if sig.decl.implicit_self.has_implicit_self() { - let ret_ty = cx.tcx.erase_late_bound_regions(cx.tcx.bound_fn_sig(fn_id.into()).subst_identity().output()); + let ret_ty = cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(fn_id).subst_identity().output()); let ret_ty = cx .tcx .try_normalize_erasing_regions(cx.param_env, ret_ty) diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index 121d6b9f0fe7e..80ed2862a419a 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -144,7 +144,7 @@ impl<'tcx> LateLintPass<'tcx> for LenZero { if let Some(local_id) = ty_id.as_local(); let ty_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_id); if !is_lint_allowed(cx, LEN_WITHOUT_IS_EMPTY, ty_hir_id); - if let Some(output) = parse_len_output(cx, cx.tcx.bound_fn_sig(item.owner_id.to_def_id()).subst_identity().skip_binder()); + if let Some(output) = parse_len_output(cx, cx.tcx.fn_sig(item.owner_id).subst_identity().skip_binder()); then { let (name, kind) = match cx.tcx.hir().find(ty_hir_id) { Some(Node::ForeignItem(x)) => (x.ident.name, "extern type"), @@ -196,7 +196,7 @@ fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: Symbol) -> bool { item.ident.name == name && if let AssocItemKind::Fn { has_self } = item.kind { - has_self && { cx.tcx.bound_fn_sig(item.id.owner_id.to_def_id()).skip_binder().inputs().skip_binder().len() == 1 } + has_self && { cx.tcx.fn_sig(item.id.owner_id).skip_binder().inputs().skip_binder().len() == 1 } } else { false } @@ -224,7 +224,7 @@ fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items .any(|i| { i.kind == ty::AssocKind::Fn && i.fn_has_self_parameter - && cx.tcx.bound_fn_sig(i.def_id).skip_binder().inputs().skip_binder().len() == 1 + && cx.tcx.fn_sig(i.def_id).skip_binder().inputs().skip_binder().len() == 1 }); if !is_empty_method_found { @@ -342,7 +342,7 @@ fn check_for_is_empty<'tcx>( ), Some(is_empty) if !(is_empty.fn_has_self_parameter - && check_is_empty_sig(cx.tcx.bound_fn_sig(is_empty.def_id).subst_identity().skip_binder(), self_kind, output)) => + && check_is_empty_sig(cx.tcx.fn_sig(is_empty.def_id).subst_identity().skip_binder(), self_kind, output)) => { ( format!( @@ -473,7 +473,7 @@ fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { /// Gets an `AssocItem` and return true if it matches `is_empty(self)`. fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool { if item.kind == ty::AssocKind::Fn { - let sig = cx.tcx.bound_fn_sig(item.def_id).skip_binder(); + let sig = cx.tcx.fn_sig(item.def_id).skip_binder(); let ty = sig.skip_binder(); ty.inputs().len() == 1 } else { diff --git a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs index 3e025bc0e7160..e6ed4ea7a5db5 100644 --- a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs @@ -370,7 +370,7 @@ impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> { ExprKind::MethodCall(_, receiver, args, _) => { let def_id = self.cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap(); for (ty, expr) in iter::zip( - self.cx.tcx.bound_fn_sig(def_id).subst_identity().inputs().skip_binder(), + self.cx.tcx.fn_sig(def_id).subst_identity().inputs().skip_binder(), std::iter::once(receiver).chain(args.iter()), ) { self.prefer_mutable = false; diff --git a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs index a179dd091e421..edcab6968cbe0 100644 --- a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs +++ b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs @@ -104,7 +104,7 @@ fn is_unit_function(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { let ty = cx.typeck_results().expr_ty(expr); if let ty::FnDef(id, _) = *ty.kind() { - if let Some(fn_type) = cx.tcx.bound_fn_sig(id).subst_identity().no_bound_vars() { + if let Some(fn_type) = cx.tcx.fn_sig(id).subst_identity().no_bound_vars() { return is_unit_type(fn_type.output()); } } diff --git a/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs b/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs index 3f670ebc9178b..aed0ad5d9b5a7 100644 --- a/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs +++ b/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs @@ -70,7 +70,7 @@ pub(super) fn check<'tcx>( if let hir::ExprKind::Path(ref p) = fun.kind { match cx.qpath_res(p, fun.hir_id) { hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!( - cx.tcx.bound_fn_sig(def_id).subst_identity().output().skip_binder().kind(), + cx.tcx.fn_sig(def_id).subst_identity().output().skip_binder().kind(), ty::Ref(re, ..) if re.is_static(), ), _ => false, @@ -84,7 +84,7 @@ pub(super) fn check<'tcx>( .type_dependent_def_id(arg.hir_id) .map_or(false, |method_id| { matches!( - cx.tcx.bound_fn_sig(method_id).subst_identity().output().skip_binder().kind(), + cx.tcx.fn_sig(method_id).subst_identity().output().skip_binder().kind(), ty::Ref(re, ..) if re.is_static() ) }) diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index 6002ef1340bea..a7e45d5126ab0 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -3352,7 +3352,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. })); if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind { - let method_sig = cx.tcx.bound_fn_sig(impl_item.owner_id.to_def_id()).subst_identity(); + let method_sig = cx.tcx.fn_sig(impl_item.owner_id).subst_identity(); let method_sig = cx.tcx.erase_late_bound_regions(method_sig); let first_arg_ty_opt = method_sig.inputs().iter().next().copied(); // if this impl block implements a trait, lint in trait definition instead diff --git a/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs b/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs index 1a1715d03a7cb..82d3b830d4f39 100644 --- a/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs @@ -137,7 +137,7 @@ pub(super) fn check<'tcx>( /// Checks if the given method call matches the expected signature of `([&[mut]] self) -> bool` fn is_is_empty_sig(cx: &LateContext<'_>, call_id: HirId) -> bool { cx.typeck_results().type_dependent_def_id(call_id).map_or(false, |id| { - let sig = cx.tcx.bound_fn_sig(id).subst_identity().skip_binder(); + let sig = cx.tcx.fn_sig(id).subst_identity().skip_binder(); sig.inputs().len() == 1 && sig.output().is_bool() }) } @@ -165,7 +165,7 @@ fn iterates_same_ty<'tcx>(cx: &LateContext<'tcx>, iter_ty: Ty<'tcx>, collect_ty: fn is_contains_sig(cx: &LateContext<'_>, call_id: HirId, iter_expr: &Expr<'_>) -> bool { let typeck = cx.typeck_results(); if let Some(id) = typeck.type_dependent_def_id(call_id) - && let sig = cx.tcx.bound_fn_sig(id).subst_identity() + && let sig = cx.tcx.fn_sig(id).subst_identity() && sig.skip_binder().output().is_bool() && let [_, search_ty] = *sig.skip_binder().inputs() && let ty::Ref(_, search_ty, Mutability::Not) = *cx.tcx.erase_late_bound_regions(sig.rebind(search_ty)).kind() diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index 8036e787aaecc..12e053cb2134d 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -246,7 +246,7 @@ fn check_other_call_arg<'tcx>( if_chain! { if let Some((maybe_call, maybe_arg)) = skip_addr_of_ancestors(cx, expr); if let Some((callee_def_id, _, recv, call_args)) = get_callee_substs_and_args(cx, maybe_call); - let fn_sig = cx.tcx.bound_fn_sig(callee_def_id).subst_identity().skip_binder(); + let fn_sig = cx.tcx.fn_sig(callee_def_id).subst_identity().skip_binder(); if let Some(i) = recv.into_iter().chain(call_args).position(|arg| arg.hir_id == maybe_arg.hir_id); if let Some(input) = fn_sig.inputs().get(i); let (input, n_refs) = peel_mid_ty_refs(*input); @@ -386,7 +386,7 @@ fn can_change_type<'a>(cx: &LateContext<'a>, mut expr: &'a Expr<'a>, mut ty: Ty< Node::Expr(parent_expr) => { if let Some((callee_def_id, call_substs, recv, call_args)) = get_callee_substs_and_args(cx, parent_expr) { - let fn_sig = cx.tcx.bound_fn_sig(callee_def_id).subst_identity().skip_binder(); + let fn_sig = cx.tcx.fn_sig(callee_def_id).subst_identity().skip_binder(); if let Some(arg_index) = recv.into_iter().chain(call_args).position(|arg| arg.hir_id == expr.hir_id) && let Some(param_ty) = fn_sig.inputs().get(arg_index) && let ty::Param(ParamTy { index: param_index , ..}) = param_ty.kind() diff --git a/src/tools/clippy/clippy_lints/src/mut_key.rs b/src/tools/clippy/clippy_lints/src/mut_key.rs index a2868883673f5..16947cd5e3548 100644 --- a/src/tools/clippy/clippy_lints/src/mut_key.rs +++ b/src/tools/clippy/clippy_lints/src/mut_key.rs @@ -138,7 +138,7 @@ impl MutableKeyType { fn check_sig(&self, cx: &LateContext<'_>, item_hir_id: hir::HirId, decl: &hir::FnDecl<'_>) { let fn_def_id = cx.tcx.hir().local_def_id(item_hir_id); - let fn_sig = cx.tcx.bound_fn_sig(fn_def_id.into()).subst_identity(); + let fn_sig = cx.tcx.fn_sig(fn_def_id).subst_identity(); for (hir_ty, ty) in iter::zip(decl.inputs, fn_sig.inputs().skip_binder()) { self.check_ty_(cx, hir_ty.span, *ty); } diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs index e3d25603a7157..25ec9082c7076 100644 --- a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs +++ b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs @@ -147,7 +147,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { ctx }; - let fn_sig = cx.tcx.bound_fn_sig(fn_def_id.into()).subst_identity(); + let fn_sig = cx.tcx.fn_sig(fn_def_id).subst_identity(); let fn_sig = cx.tcx.erase_late_bound_regions(fn_sig); for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(body.params).enumerate() { diff --git a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs index 5512109c6cbb1..954eeba751ffa 100644 --- a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs +++ b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs @@ -143,7 +143,7 @@ impl<'tcx> PassByRefOrValue { return; } - let fn_sig = cx.tcx.bound_fn_sig(def_id.into()).subst_identity(); + let fn_sig = cx.tcx.fn_sig(def_id).subst_identity(); let fn_body = cx.enclosing_body.map(|id| cx.tcx.hir().body(id)); // Gather all the lifetimes found in the output type which may affect whether diff --git a/src/tools/clippy/clippy_lints/src/ptr.rs b/src/tools/clippy/clippy_lints/src/ptr.rs index 0a2d35015f573..8afe286fbd5dc 100644 --- a/src/tools/clippy/clippy_lints/src/ptr.rs +++ b/src/tools/clippy/clippy_lints/src/ptr.rs @@ -164,7 +164,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { check_mut_from_ref(cx, sig, None); for arg in check_fn_args( cx, - cx.tcx.bound_fn_sig(item.owner_id.to_def_id()).subst_identity().skip_binder().inputs(), + cx.tcx.fn_sig(item.owner_id).subst_identity().skip_binder().inputs(), sig.decl.inputs, &[], ) @@ -217,7 +217,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { check_mut_from_ref(cx, sig, Some(body)); let decl = sig.decl; - let sig = cx.tcx.bound_fn_sig(item_id.to_def_id()).subst_identity().skip_binder(); + let sig = cx.tcx.fn_sig(item_id).subst_identity().skip_binder(); let lint_args: Vec<_> = check_fn_args(cx, sig.inputs(), decl.inputs, body.params) .filter(|arg| !is_trait_item || arg.mutability() == Mutability::Not) .collect(); @@ -624,7 +624,7 @@ fn check_ptr_arg_usage<'tcx>(cx: &LateContext<'tcx>, body: &'tcx Body<'_>, args: return; }; - match *self.cx.tcx.bound_fn_sig(id).subst_identity().skip_binder().inputs()[i].peel_refs().kind() { + match *self.cx.tcx.fn_sig(id).subst_identity().skip_binder().inputs()[i].peel_refs().kind() { ty::Dynamic(preds, _, _) if !matches_preds(self.cx, args.deref_ty.ty(self.cx), preds) => { set_skip_flag(); }, diff --git a/src/tools/clippy/clippy_lints/src/returns.rs b/src/tools/clippy/clippy_lints/src/returns.rs index f3c5033060433..dc1275a3686d0 100644 --- a/src/tools/clippy/clippy_lints/src/returns.rs +++ b/src/tools/clippy/clippy_lints/src/returns.rs @@ -287,7 +287,7 @@ fn last_statement_borrows<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) if let Some(def_id) = fn_def_id(cx, e) && cx .tcx - .bound_fn_sig(def_id) + .fn_sig(def_id) .subst_identity() .skip_binder() .output() diff --git a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs index 5df26d8b0a38c..289ca4e9bed3c 100644 --- a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs +++ b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs @@ -76,7 +76,7 @@ fn get_projection_pred<'tcx>( fn get_args_to_check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Vec<(usize, String)> { let mut args_to_check = Vec::new(); if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) { - let fn_sig = cx.tcx.bound_fn_sig(def_id).subst_identity(); + let fn_sig = cx.tcx.fn_sig(def_id).subst_identity(); let generics = cx.tcx.predicates_of(def_id); let fn_mut_preds = get_trait_predicates_for_trait_id(cx, generics, cx.tcx.lang_items().fn_mut_trait()); let ord_preds = get_trait_predicates_for_trait_id(cx, generics, cx.tcx.get_diagnostic_item(sym::Ord)); diff --git a/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs b/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs index 681e59a1575d4..d6167a62169d4 100644 --- a/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs +++ b/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs @@ -156,7 +156,7 @@ fn needs_inferred_result_ty( }, _ => return false, }; - let sig = cx.tcx.bound_fn_sig(id).subst_identity().skip_binder(); + let sig = cx.tcx.fn_sig(id).subst_identity().skip_binder(); if let ty::Param(output_ty) = *sig.output().kind() { let args: Vec<&Expr<'_>> = if let Some(receiver) = receiver { std::iter::once(receiver).chain(args.iter()).collect() diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index 09324fd92943c..3cd35838961f6 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -146,7 +146,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { .associated_item(impl_item.owner_id) .trait_item_def_id .expect("impl method matches a trait method"); - let trait_method_sig = cx.tcx.bound_fn_sig(trait_method).subst_identity(); + let trait_method_sig = cx.tcx.fn_sig(trait_method).subst_identity(); let trait_method_sig = cx.tcx.erase_late_bound_regions(trait_method_sig); // `impl_inputs_outputs` is an iterator over the types (`hir::Ty`) declared in the diff --git a/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs b/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs index 38588e32dbfe9..5c89dd3e49f41 100644 --- a/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs +++ b/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs @@ -79,7 +79,7 @@ fn fn_eagerness(cx: &LateContext<'_>, fn_id: DefId, name: Symbol, have_one_arg: && subs.types().all(|x| matches!(x.peel_refs().kind(), ty::Param(_))) { // Limit the function to either `(self) -> bool` or `(&self) -> bool` - match &**cx.tcx.bound_fn_sig(fn_id).subst_identity().skip_binder().inputs_and_output { + match &**cx.tcx.fn_sig(fn_id).subst_identity().skip_binder().inputs_and_output { [arg, res] if !arg.is_mutable_ptr() && arg.peel_refs() == ty && res.is_bool() => NoChange, _ => Lazy, } diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index ccc5f3503d2f5..23791ebe92254 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -1379,7 +1379,7 @@ pub fn get_enclosing_loop_or_multi_call_closure<'tcx>( .chain(args.iter()) .position(|arg| arg.hir_id == id)?; let id = cx.typeck_results().type_dependent_def_id(e.hir_id)?; - let ty = cx.tcx.bound_fn_sig(id).subst_identity().skip_binder().inputs()[i]; + let ty = cx.tcx.fn_sig(id).subst_identity().skip_binder().inputs()[i]; ty_is_fn_once_param(cx.tcx, ty, cx.tcx.param_env(id).caller_bounds()).then_some(()) }, _ => None, @@ -1580,14 +1580,14 @@ pub fn is_direct_expn_of(span: Span, name: &str) -> Option { /// Convenience function to get the return type of a function. pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId) -> Ty<'tcx> { let fn_def_id = cx.tcx.hir().local_def_id(fn_item); - let ret_ty = cx.tcx.bound_fn_sig(fn_def_id.into()).subst_identity().output(); + let ret_ty = cx.tcx.fn_sig(fn_def_id).subst_identity().output(); cx.tcx.erase_late_bound_regions(ret_ty) } /// Convenience function to get the nth argument type of a function. pub fn nth_arg<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId, nth: usize) -> Ty<'tcx> { let fn_def_id = cx.tcx.hir().local_def_id(fn_item); - let arg = cx.tcx.bound_fn_sig(fn_def_id.into()).subst_identity().input(nth); + let arg = cx.tcx.fn_sig(fn_def_id).subst_identity().input(nth); cx.tcx.erase_late_bound_regions(arg) } diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index 1552e343582ee..13de780b71095 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -55,7 +55,7 @@ pub fn is_min_const_fn<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, msrv: &Msrv) // impl trait is gone in MIR, so check the return type manually check_ty( tcx, - tcx.bound_fn_sig(def_id).subst_identity().output().skip_binder(), + tcx.fn_sig(def_id).subst_identity().output().skip_binder(), body.local_decls.iter().next().unwrap().source_info.span, )?; diff --git a/src/tools/clippy/clippy_utils/src/sugg.rs b/src/tools/clippy/clippy_utils/src/sugg.rs index d6a698bbeaa8a..8d767f9d44d3a 100644 --- a/src/tools/clippy/clippy_utils/src/sugg.rs +++ b/src/tools/clippy/clippy_utils/src/sugg.rs @@ -885,7 +885,7 @@ impl<'tcx> DerefDelegate<'_, 'tcx> { .cx .typeck_results() .type_dependent_def_id(parent_expr.hir_id) - .map(|did| self.cx.tcx.bound_fn_sig(did).subst_identity().skip_binder()) + .map(|did| self.cx.tcx.fn_sig(did).subst_identity().skip_binder()) { std::iter::once(receiver) .chain(call_args.iter()) diff --git a/src/tools/clippy/clippy_utils/src/ty.rs b/src/tools/clippy/clippy_utils/src/ty.rs index 14fc2c1001704..1d5d55d5b54cf 100644 --- a/src/tools/clippy/clippy_utils/src/ty.rs +++ b/src/tools/clippy/clippy_utils/src/ty.rs @@ -628,7 +628,7 @@ impl<'tcx> ExprFnSig<'tcx> { /// If the expression is function like, get the signature for it. pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option> { if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = path_res(cx, expr) { - Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst_identity(), Some(id))) + Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).subst_identity(), Some(id))) } else { ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs()) } @@ -646,7 +646,7 @@ pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs), Some(id))), + ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).subst(cx.tcx, subs), Some(id))), ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { sig_from_bounds(cx, ty, cx.tcx.item_bounds(def_id).subst(cx.tcx, substs), cx.tcx.opt_parent(def_id)) }, diff --git a/src/tools/clippy/clippy_utils/src/visitors.rs b/src/tools/clippy/clippy_utils/src/visitors.rs index 1680a40206a3a..d18b62d1bf16a 100644 --- a/src/tools/clippy/clippy_utils/src/visitors.rs +++ b/src/tools/clippy/clippy_utils/src/visitors.rs @@ -392,12 +392,12 @@ pub fn is_expr_unsafe<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool { .cx .typeck_results() .type_dependent_def_id(e.hir_id) - .map_or(false, |id| self.cx.tcx.bound_fn_sig(id).skip_binder().unsafety() == Unsafety::Unsafe) => + .map_or(false, |id| self.cx.tcx.fn_sig(id).skip_binder().unsafety() == Unsafety::Unsafe) => { self.is_unsafe = true; }, ExprKind::Call(func, _) => match *self.cx.typeck_results().expr_ty(func).peel_refs().kind() { - ty::FnDef(id, _) if self.cx.tcx.bound_fn_sig(id).skip_binder().unsafety() == Unsafety::Unsafe => self.is_unsafe = true, + ty::FnDef(id, _) if self.cx.tcx.fn_sig(id).skip_binder().unsafety() == Unsafety::Unsafe => self.is_unsafe = true, ty::FnPtr(sig) if sig.unsafety() == Unsafety::Unsafe => self.is_unsafe = true, _ => walk_expr(self, e), }, diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index e333a66a0b3ae..4031e304d868f 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -357,7 +357,7 @@ pub fn create_ecx<'mir, 'tcx: 'mir>( match entry_type { EntryFnType::Main { .. } => { let start_id = tcx.lang_items().start_fn().unwrap(); - let main_ret_ty = tcx.bound_fn_sig(entry_id).subst_identity().output(); + let main_ret_ty = tcx.fn_sig(entry_id).subst_identity().output(); let main_ret_ty = main_ret_ty.no_bound_vars().unwrap(); let start_instance = ty::Instance::resolve( tcx, From ab40ba2fb1c034554f12a0f8ada3f5f3e42ad592 Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Thu, 19 Jan 2023 12:09:01 -0700 Subject: [PATCH 394/500] add EarlyBinder::no_bound_vars --- compiler/rustc_codegen_cranelift/src/main_shim.rs | 2 +- compiler/rustc_codegen_ssa/src/base.rs | 2 +- compiler/rustc_middle/src/ty/subst.rs | 5 +++++ compiler/rustc_monomorphize/src/collector.rs | 2 +- src/tools/miri/src/eval.rs | 2 +- 5 files changed, 9 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/src/main_shim.rs b/compiler/rustc_codegen_cranelift/src/main_shim.rs index bc1b1ec7cd597..70cf28267d70c 100644 --- a/compiler/rustc_codegen_cranelift/src/main_shim.rs +++ b/compiler/rustc_codegen_cranelift/src/main_shim.rs @@ -46,7 +46,7 @@ pub(crate) fn maybe_create_entry_wrapper( is_main_fn: bool, sigpipe: u8, ) { - let main_ret_ty = tcx.fn_sig(rust_main_def_id).subst_identity().output(); + let main_ret_ty = tcx.fn_sig(rust_main_def_id).no_bound_vars().unwrap().output(); // Given that `main()` has no arguments, // then its return type cannot have // late-bound regions, since late-bound diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 2013a2dcbc22b..02b502d948c2c 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -436,7 +436,7 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( cx.type_func(&[], cx.type_int()) }; - let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).subst_identity().output(); + let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output(); // Given that `main()` has no arguments, // then its return type cannot have // late-bound regions, since late-bound diff --git a/compiler/rustc_middle/src/ty/subst.rs b/compiler/rustc_middle/src/ty/subst.rs index a07582fc8ff1e..cf1bb5f8ac8db 100644 --- a/compiler/rustc_middle/src/ty/subst.rs +++ b/compiler/rustc_middle/src/ty/subst.rs @@ -758,6 +758,11 @@ impl<'tcx, T: TypeFoldable<'tcx>> ty::EarlyBinder { pub fn subst_identity(self) -> T { self.0 } + + /// Returns the inner value, but only if it contains no bound vars. + pub fn no_bound_vars(self) -> Option { + if !self.0.needs_subst() { Some(self.0) } else { None } + } } /////////////////////////////////////////////////////////////////////////// diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 28e806fdd4741..305f0427e501b 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -1296,7 +1296,7 @@ impl<'v> RootCollector<'_, 'v> { }; let start_def_id = self.tcx.require_lang_item(LangItem::Start, None); - let main_ret_ty = self.tcx.fn_sig(main_def_id).subst_identity().output(); + let main_ret_ty = self.tcx.fn_sig(main_def_id).no_bound_vars().unwrap().output(); // Given that `main()` has no arguments, // then its return type cannot have diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index 4031e304d868f..96ab8b0d98e63 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -357,7 +357,7 @@ pub fn create_ecx<'mir, 'tcx: 'mir>( match entry_type { EntryFnType::Main { .. } => { let start_id = tcx.lang_items().start_fn().unwrap(); - let main_ret_ty = tcx.fn_sig(entry_id).subst_identity().output(); + let main_ret_ty = tcx.fn_sig(entry_id).no_bound_vars().unwrap().output(); let main_ret_ty = main_ret_ty.no_bound_vars().unwrap(); let start_instance = ty::Instance::resolve( tcx, From a969c194d87f0fe1c30e5eeec981414e8b11dc47 Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Thu, 19 Jan 2023 12:52:52 -0700 Subject: [PATCH 395/500] fix up subst_identity vs skip_binder; add some FIXMEs as identified in review --- .../rustc_borrowck/src/diagnostics/mod.rs | 4 ++- .../src/check/compare_impl_item.rs | 6 ++-- .../rustc_hir_analysis/src/collect/type_of.rs | 4 +-- compiler/rustc_hir_typeck/src/demand.rs | 19 ++++------- .../rustc_hir_typeck/src/method/confirm.rs | 4 +-- compiler/rustc_hir_typeck/src/method/mod.rs | 3 +- compiler/rustc_hir_typeck/src/method/probe.rs | 34 ++++++++----------- .../src/function_item_references.rs | 3 +- compiler/rustc_privacy/src/lib.rs | 1 + compiler/rustc_ty_utils/src/implied_bounds.rs | 4 +-- 10 files changed, 37 insertions(+), 45 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 13a24767debc3..18d2caa149bfb 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -1136,7 +1136,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { && let self_ty = infcx.replace_bound_vars_with_fresh_vars( fn_call_span, LateBoundRegionConversionTime::FnCall, - tcx.fn_sig(method_did).subst_identity().input(0), + // FIXME: should use `subst` with the method substs. + // Probably need to add `method_substs` to `CallKind` + tcx.fn_sig(method_did).skip_binder().input(0), ) && infcx.can_eq(self.param_env, ty, self_ty).is_ok() { diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index d93d2314ed65d..780d5271619e7 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -422,8 +422,8 @@ fn extract_bad_args_for_implies_lint<'tcx>( // Map late-bound regions from trait to impl, so the names are right. let mapping = std::iter::zip( - tcx.fn_sig(trait_m.def_id).subst_identity().bound_vars(), - tcx.fn_sig(impl_m.def_id).subst_identity().bound_vars(), + tcx.fn_sig(trait_m.def_id).skip_binder().bound_vars(), + tcx.fn_sig(impl_m.def_id).skip_binder().bound_vars(), ) .filter_map(|(impl_bv, trait_bv)| { if let ty::BoundVariableKind::Region(impl_bv) = impl_bv @@ -540,7 +540,7 @@ fn compare_asyncness<'tcx>( trait_item_span: Option, ) -> Result<(), ErrorGuaranteed> { if tcx.asyncness(trait_m.def_id) == hir::IsAsync::Async { - match tcx.fn_sig(impl_m.def_id).subst_identity().skip_binder().output().kind() { + match tcx.fn_sig(impl_m.def_id).skip_binder().skip_binder().output().kind() { ty::Alias(ty::Opaque, ..) => { // allow both `async fn foo()` and `fn foo() -> impl Future` } diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index b28458fb7cfc4..d0d819d9687bb 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -867,8 +867,8 @@ fn infer_placeholder_type<'a>( } match ty.kind() { - ty::FnDef(def_id, _) => { - self.tcx.mk_fn_ptr(self.tcx.fn_sig(*def_id).subst_identity()) + ty::FnDef(def_id, substs) => { + self.tcx.mk_fn_ptr(self.tcx.fn_sig(*def_id).subst(self.tcx, substs)) } // FIXME: non-capturing closures should also suggest a function pointer ty::Closure(..) | ty::Generator(..) => { diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 45bd2026e414a..19b8fb96cde37 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -603,6 +603,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let substs = ty::InternalSubsts::for_item(self.tcx, m.def_id, |param, _| { self.var_for_def(deref.span, param) }); + let mutability = + match self.tcx.fn_sig(m.def_id).skip_binder().input(0).skip_binder().kind() { + ty::Ref(_, _, hir::Mutability::Mut) => "&mut ", + ty::Ref(_, _, _) => "&", + _ => "", + }; vec![ ( deref.span.until(base.span), @@ -611,18 +617,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { with_no_trimmed_paths!( self.tcx.def_path_str_with_substs(m.def_id, substs,) ), - match self - .tcx - .fn_sig(m.def_id) - .subst_identity() - .input(0) - .skip_binder() - .kind() - { - ty::Ref(_, _, hir::Mutability::Mut) => "&mut ", - ty::Ref(_, _, _) => "&", - _ => "", - }, + mutability, ), ), match &args[..] { diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index ff3596f595b45..65ca47bfe538b 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -503,9 +503,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { debug!("method_predicates after subst = {:?}", method_predicates); - let sig = self.tcx.fn_sig(def_id); - - let sig = sig.subst(self.tcx, all_substs); + let sig = self.tcx.fn_sig(def_id).subst(self.tcx, all_substs); debug!("type scheme substituted, sig={:?}", sig); let sig = self.replace_bound_vars_with_fresh_vars(sig); diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index c0b6ed2e614dd..60d4dc326eea1 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -399,8 +399,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // N.B., instantiate late-bound regions before normalizing the // function signature so that normalization does not need to deal // with bound regions. - let fn_sig = tcx.fn_sig(def_id); - let fn_sig = fn_sig.subst(self.tcx, substs); + let fn_sig = tcx.fn_sig(def_id).subst(self.tcx, substs); let fn_sig = self.replace_bound_vars_with_fresh_vars(obligation.cause.span, infer::FnCall, fn_sig); diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index f67beab3c31a6..9fc4c16fb071d 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -921,26 +921,22 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { expected: Ty<'tcx>, ) -> bool { match method.kind { - ty::AssocKind::Fn => { - let fty = self.tcx.fn_sig(method.def_id); - self.probe(|_| { - let substs = self.fresh_substs_for_item(self.span, method.def_id); - let fty = fty.subst(self.tcx, substs); - let fty = - self.replace_bound_vars_with_fresh_vars(self.span, infer::FnCall, fty); - - if let Some(self_ty) = self_ty { - if self - .at(&ObligationCause::dummy(), self.param_env) - .sup(fty.inputs()[0], self_ty) - .is_err() - { - return false; - } + ty::AssocKind::Fn => self.probe(|_| { + let substs = self.fresh_substs_for_item(self.span, method.def_id); + let fty = self.tcx.fn_sig(method.def_id).subst(self.tcx, substs); + let fty = self.replace_bound_vars_with_fresh_vars(self.span, infer::FnCall, fty); + + if let Some(self_ty) = self_ty { + if self + .at(&ObligationCause::dummy(), self.param_env) + .sup(fty.inputs()[0], self_ty) + .is_err() + { + return false; } - self.can_sub(self.param_env, fty.output(), expected).is_ok() - }) - } + } + self.can_sub(self.param_env, fty.output(), expected).is_ok() + }), _ => false, } } diff --git a/compiler/rustc_mir_transform/src/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs index 19a74d8fc6649..aa19b1fdb5efa 100644 --- a/compiler/rustc_mir_transform/src/function_item_references.rs +++ b/compiler/rustc_mir_transform/src/function_item_references.rs @@ -161,7 +161,8 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { .as_ref() .assert_crate_local() .lint_root; - let fn_sig = self.tcx.fn_sig(fn_id).skip_binder(); + // FIXME: use existing printing routines to print the function signature + let fn_sig = self.tcx.fn_sig(fn_id).subst(self.tcx, fn_substs); let unsafety = fn_sig.unsafety().prefix_str(); let abi = match fn_sig.abi() { Abi::Rust => String::from(""), diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 5c701bef30486..e969bb6db9ec4 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -198,6 +198,7 @@ where // Something like `fn() -> Priv {my_func}` is considered a private type even if // `my_func` is public, so we need to visit signatures. if let ty::FnDef(..) = ty.kind() { + // FIXME: this should probably use `substs` from `FnDef` tcx.fn_sig(def_id).subst_identity().visit_with(self)?; } // Inherent static methods don't have self type in substs. diff --git a/compiler/rustc_ty_utils/src/implied_bounds.rs b/compiler/rustc_ty_utils/src/implied_bounds.rs index d308543304cce..961c04974e508 100644 --- a/compiler/rustc_ty_utils/src/implied_bounds.rs +++ b/compiler/rustc_ty_utils/src/implied_bounds.rs @@ -9,12 +9,12 @@ pub fn provide(providers: &mut ty::query::Providers) { fn assumed_wf_types(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::List> { match tcx.def_kind(def_id) { DefKind::Fn => { - let sig = tcx.fn_sig(def_id).skip_binder(); + let sig = tcx.fn_sig(def_id).subst_identity(); let liberated_sig = tcx.liberate_late_bound_regions(def_id, sig); liberated_sig.inputs_and_output } DefKind::AssocFn => { - let sig = tcx.fn_sig(def_id).skip_binder(); + let sig = tcx.fn_sig(def_id).subst_identity(); let liberated_sig = tcx.liberate_late_bound_regions(def_id, sig); let mut assumed_wf_types: Vec<_> = tcx.assumed_wf_types(tcx.parent(def_id)).as_slice().into(); From 4a7d0e9754aa75eb0fd37bfeb4f00562806d112f Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Fri, 20 Jan 2023 15:17:01 -0700 Subject: [PATCH 396/500] add method_substs to CallKind --- compiler/rustc_borrowck/src/diagnostics/mod.rs | 6 ++---- compiler/rustc_const_eval/src/util/call_kind.rs | 3 ++- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 18d2caa149bfb..1011794d7b3b2 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -1064,7 +1064,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ); } } - CallKind::Normal { self_arg, desugaring, method_did } => { + CallKind::Normal { self_arg, desugaring, method_did, method_substs } => { let self_arg = self_arg.unwrap(); let tcx = self.infcx.tcx; if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring { @@ -1136,9 +1136,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { && let self_ty = infcx.replace_bound_vars_with_fresh_vars( fn_call_span, LateBoundRegionConversionTime::FnCall, - // FIXME: should use `subst` with the method substs. - // Probably need to add `method_substs` to `CallKind` - tcx.fn_sig(method_did).skip_binder().input(0), + tcx.fn_sig(method_did).subst(tcx, method_substs).input(0), ) && infcx.can_eq(self.param_env, ty, self_ty).is_ok() { diff --git a/compiler/rustc_const_eval/src/util/call_kind.rs b/compiler/rustc_const_eval/src/util/call_kind.rs index 38d9b044981cd..995363c0edd92 100644 --- a/compiler/rustc_const_eval/src/util/call_kind.rs +++ b/compiler/rustc_const_eval/src/util/call_kind.rs @@ -40,6 +40,7 @@ pub enum CallKind<'tcx> { self_arg: Option, desugaring: Option<(CallDesugaringKind, Ty<'tcx>)>, method_did: DefId, + method_substs: SubstsRef<'tcx>, }, /// A call to `Fn(..)::call(..)`, desugared from `my_closure(a, b, c)` FnCall { fn_trait_id: DefId, self_ty: Ty<'tcx> }, @@ -131,6 +132,6 @@ pub fn call_kind<'tcx>( } else { None }; - CallKind::Normal { self_arg, desugaring, method_did } + CallKind::Normal { self_arg, desugaring, method_did, method_substs } }) } From dc1216bc0660c2d76535a68a53ff37462c5b1cb0 Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Thu, 26 Jan 2023 20:33:27 -0700 Subject: [PATCH 397/500] fixup new usages of fn_sig, bound_fn_sig after rebasing --- .../src/infer/error_reporting/note_and_explain.rs | 2 +- compiler/rustc_infer/src/infer/error_reporting/suggest.rs | 8 ++++---- compiler/rustc_passes/src/check_attr.rs | 3 ++- .../src/solve/trait_goals/structural_traits.rs | 2 +- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs index 425cde3302db8..34e8edd6140b2 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs @@ -463,7 +463,7 @@ fn foo(&tcx) -> Self::T { String::new() } ty::AssocKind::Fn == item.kind && Some(item.name) != current_method_ident }) .filter_map(|item| { - let method = tcx.fn_sig(item.def_id); + let method = tcx.fn_sig(item.def_id).subst_identity(); match *method.output().skip_binder().kind() { ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. }) if item_def_id == proj_ty_item_def_id => diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index 768cef89f3c43..23063e80b05ff 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -369,7 +369,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { (ty::FnPtr(sig), ty::FnDef(did, substs)) => { let expected_sig = &(self.normalize_fn_sig)(*sig); let found_sig = - &(self.normalize_fn_sig)(self.tcx.bound_fn_sig(*did).subst(self.tcx, substs)); + &(self.normalize_fn_sig)(self.tcx.fn_sig(*did).subst(self.tcx, substs)); let fn_name = self.tcx.def_path_str_with_substs(*did, substs); @@ -408,9 +408,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => { let expected_sig = - &(self.normalize_fn_sig)(self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1)); + &(self.normalize_fn_sig)(self.tcx.fn_sig(*did1).subst(self.tcx, substs1)); let found_sig = - &(self.normalize_fn_sig)(self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2)); + &(self.normalize_fn_sig)(self.tcx.fn_sig(*did2).subst(self.tcx, substs2)); if self.same_type_modulo_infer(*expected_sig, *found_sig) { diag.note("different fn items have unique types, even if their signatures are the same"); @@ -440,7 +440,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } (ty::FnDef(did, substs), ty::FnPtr(sig)) => { let expected_sig = - &(self.normalize_fn_sig)(self.tcx.bound_fn_sig(*did).subst(self.tcx, substs)); + &(self.normalize_fn_sig)(self.tcx.fn_sig(*did).subst(self.tcx, substs)); let found_sig = &(self.normalize_fn_sig)(*sig); if !self.same_type_modulo_infer(*found_sig, *expected_sig) { diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 4232985325945..f4673c332b887 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -2120,7 +2120,8 @@ impl CheckAttrVisitor<'_> { let id = hir_id.expect_owner(); let hir_sig = tcx.hir().fn_sig_by_hir_id(hir_id).unwrap(); - let sig = tcx.liberate_late_bound_regions(id.to_def_id(), tcx.fn_sig(id)); + let sig = + tcx.liberate_late_bound_regions(id.to_def_id(), tcx.fn_sig(id).subst_identity()); let sig = tcx.normalize_erasing_regions(ParamEnv::empty(), sig); // We don't currently require that the function signature is equal to diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs b/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs index c2a19372f18c4..6cab0bc6a4b25 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs @@ -184,7 +184,7 @@ pub(crate) fn extract_tupled_inputs_and_output_from_callable<'tcx>( ) -> Result, Ty<'tcx>)>>, NoSolution> { match *self_ty.kind() { ty::FnDef(def_id, substs) => Ok(Some( - tcx.bound_fn_sig(def_id) + tcx.fn_sig(def_id) .subst(tcx, substs) .map_bound(|sig| (tcx.mk_tup(sig.inputs().iter()), sig.output())), )), From cce452d8c89ce69002bdafb3cbca83d86203d55c Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Fri, 27 Jan 2023 07:52:44 +0200 Subject: [PATCH 398/500] reduce rightward-drift --- compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index d9a73c7a5c904..240a9d2f37184 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -295,9 +295,8 @@ fn add_unused_functions(cx: &CodegenCx<'_, '_>) { DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator ) { return None; - } else if ignore_unused_generics - && tcx.generics_of(def_id).requires_monomorphization(tcx) - { + } + if ignore_unused_generics && tcx.generics_of(def_id).requires_monomorphization(tcx) { return None; } Some(local_def_id.to_def_id()) From 9ef84076109ca9b6dd87fca7040781d778eb7605 Mon Sep 17 00:00:00 2001 From: Sergey Prytkov Date: Mon, 23 Jan 2023 21:03:06 +0300 Subject: [PATCH 399/500] Revisit fix_is_ci_llvm_available logic; read build triple from toml --- src/bootstrap/config.rs | 3 ++ src/bootstrap/config/tests.rs | 7 ++++ src/bootstrap/native.rs | 65 +++++++++++++++++------------------ 3 files changed, 41 insertions(+), 34 deletions(-) diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index b41d60d51a8b5..fdd659c60ca7f 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -965,6 +965,9 @@ impl Config { config.changelog_seen = toml.changelog_seen; let build = toml.build.unwrap_or_default(); + if let Some(file_build) = build.build { + config.build = TargetSelection::from_user(&file_build); + }; set(&mut config.out, flags.build_dir.or_else(|| build.build_dir.map(PathBuf::from))); // NOTE: Bootstrap spawns various commands with different working directories. diff --git a/src/bootstrap/config/tests.rs b/src/bootstrap/config/tests.rs index c30c9131745c8..681ecbfeb5b8f 100644 --- a/src/bootstrap/config/tests.rs +++ b/src/bootstrap/config/tests.rs @@ -19,6 +19,13 @@ fn download_ci_llvm() { assert_eq!(parse_llvm(""), if_available); assert_eq!(parse_llvm("rust.channel = \"dev\""), if_available); assert!(!parse_llvm("rust.channel = \"stable\"")); + assert!(parse_llvm("build.build = \"x86_64-unknown-linux-gnu\"")); + assert!(parse_llvm( + "llvm.assertions = true \r\n build.build = \"x86_64-unknown-linux-gnu\" \r\n llvm.download-ci-llvm = \"if-available\"" + )); + assert!(!parse_llvm( + "llvm.assertions = true \r\n build.build = \"aarch64-apple-darwin\" \r\n llvm.download-ci-llvm = \"if-available\"" + )); } // FIXME: add test for detecting `src` and `out` diff --git a/src/bootstrap/native.rs b/src/bootstrap/native.rs index cb5706ca0a651..3acc2d4b5c4b1 100644 --- a/src/bootstrap/native.rs +++ b/src/bootstrap/native.rs @@ -180,43 +180,40 @@ pub(crate) fn is_ci_llvm_available(config: &Config, asserts: bool) -> bool { // https://doc.rust-lang.org/rustc/platform-support.html#tier-1 let supported_platforms = [ // tier 1 - "aarch64-unknown-linux-gnu", - "i686-pc-windows-gnu", - "i686-pc-windows-msvc", - "i686-unknown-linux-gnu", - "x86_64-unknown-linux-gnu", - "x86_64-apple-darwin", - "x86_64-pc-windows-gnu", - "x86_64-pc-windows-msvc", + ("aarch64-unknown-linux-gnu", false), + ("i686-pc-windows-gnu", false), + ("i686-pc-windows-msvc", false), + ("i686-unknown-linux-gnu", false), + ("x86_64-unknown-linux-gnu", true), + ("x86_64-apple-darwin", true), + ("x86_64-pc-windows-gnu", true), + ("x86_64-pc-windows-msvc", true), // tier 2 with host tools - "aarch64-apple-darwin", - "aarch64-pc-windows-msvc", - "aarch64-unknown-linux-musl", - "arm-unknown-linux-gnueabi", - "arm-unknown-linux-gnueabihf", - "armv7-unknown-linux-gnueabihf", - "mips-unknown-linux-gnu", - "mips64-unknown-linux-gnuabi64", - "mips64el-unknown-linux-gnuabi64", - "mipsel-unknown-linux-gnu", - "powerpc-unknown-linux-gnu", - "powerpc64-unknown-linux-gnu", - "powerpc64le-unknown-linux-gnu", - "riscv64gc-unknown-linux-gnu", - "s390x-unknown-linux-gnu", - "x86_64-unknown-freebsd", - "x86_64-unknown-illumos", - "x86_64-unknown-linux-musl", - "x86_64-unknown-netbsd", + ("aarch64-apple-darwin", false), + ("aarch64-pc-windows-msvc", false), + ("aarch64-unknown-linux-musl", false), + ("arm-unknown-linux-gnueabi", false), + ("arm-unknown-linux-gnueabihf", false), + ("armv7-unknown-linux-gnueabihf", false), + ("mips-unknown-linux-gnu", false), + ("mips64-unknown-linux-gnuabi64", false), + ("mips64el-unknown-linux-gnuabi64", false), + ("mipsel-unknown-linux-gnu", false), + ("powerpc-unknown-linux-gnu", false), + ("powerpc64-unknown-linux-gnu", false), + ("powerpc64le-unknown-linux-gnu", false), + ("riscv64gc-unknown-linux-gnu", false), + ("s390x-unknown-linux-gnu", false), + ("x86_64-unknown-freebsd", false), + ("x86_64-unknown-illumos", false), + ("x86_64-unknown-linux-musl", false), + ("x86_64-unknown-netbsd", false), ]; - if !supported_platforms.contains(&&*config.build.triple) { - return false; - } - let triple = &*config.build.triple; - if (triple == "aarch64-unknown-linux-gnu" || triple.contains("i686")) && asserts { - // No alt builder for aarch64-unknown-linux-gnu today. - return false; + if !supported_platforms.contains(&(&*config.build.triple, asserts)) { + if asserts == true || !supported_platforms.contains(&(&*config.build.triple, true)) { + return false; + } } if CiEnv::is_ci() { From 0abf8a0617877a160f1ac6c46129ca428685cbca Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Fri, 13 Jan 2023 13:32:49 +0100 Subject: [PATCH 400/500] Replace format flags u32 by enums and bools. --- compiler/rustc_ast/src/format.rs | 26 ++++++- compiler/rustc_ast_lowering/src/format.rs | 9 ++- .../rustc_ast_pretty/src/pprust/state/expr.rs | 28 +++---- compiler/rustc_builtin_macros/src/format.rs | 13 +++- compiler/rustc_parse_format/src/lib.rs | 65 +++++++++------- compiler/rustc_parse_format/src/tests.rs | 75 +++++++++++++++---- 6 files changed, 154 insertions(+), 62 deletions(-) diff --git a/compiler/rustc_ast/src/format.rs b/compiler/rustc_ast/src/format.rs index da05b09b37dcc..d021bea5ecacb 100644 --- a/compiler/rustc_ast/src/format.rs +++ b/compiler/rustc_ast/src/format.rs @@ -227,8 +227,30 @@ pub struct FormatOptions { pub alignment: Option, /// The fill character. E.g. the `.` in `{:.>10}`. pub fill: Option, - /// The `+`, `-`, `0`, `#`, `x?` and `X?` flags. - pub flags: u32, + /// The `+` or `-` flag. + pub sign: Option, + /// The `#` flag. + pub alternate: bool, + /// The `0` flag. E.g. the `0` in `{:02x}`. + pub zero_pad: bool, + /// The `x` or `X` flag (for `Debug` only). E.g. the `x` in `{:x?}`. + pub debug_hex: Option, +} + +#[derive(Copy, Clone, Encodable, Decodable, Debug, PartialEq, Eq)] +pub enum FormatSign { + /// The `+` flag. + Plus, + /// The `-` flag. + Minus, +} + +#[derive(Copy, Clone, Encodable, Decodable, Debug, PartialEq, Eq)] +pub enum FormatDebugHex { + /// The `x` flag in `{:x?}`. + Lower, + /// The `X` flag in `{:X?}`. + Upper, } #[derive(Copy, Clone, Encodable, Decodable, Debug, PartialEq, Eq)] diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index 776b532b0de86..5d1770c734d5d 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -148,7 +148,14 @@ fn make_format_spec<'hir>( None => sym::Unknown, }, ); - let flags = ctx.expr_u32(sp, placeholder.format_options.flags); + // This needs to match `FlagV1` in library/core/src/fmt/mod.rs. + let flags: u32 = ((placeholder.format_options.sign == Some(FormatSign::Plus)) as u32) + | ((placeholder.format_options.sign == Some(FormatSign::Minus)) as u32) << 1 + | (placeholder.format_options.alternate as u32) << 2 + | (placeholder.format_options.zero_pad as u32) << 3 + | ((placeholder.format_options.debug_hex == Some(FormatDebugHex::Lower)) as u32) << 4 + | ((placeholder.format_options.debug_hex == Some(FormatDebugHex::Upper)) as u32) << 5; + let flags = ctx.expr_u32(sp, flags); let prec = make_count(ctx, sp, &placeholder.format_options.precision, argmap); let width = make_count(ctx, sp, &placeholder.format_options.width, argmap); let format_placeholder_new = ctx.arena.alloc(ctx.expr_lang_item_type_relative( diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs index 99ffa19016f27..cacfe9eb2f107 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -6,7 +6,10 @@ use rustc_ast::token; use rustc_ast::util::literal::escape_byte_str_symbol; use rustc_ast::util::parser::{self, AssocOp, Fixity}; use rustc_ast::{self as ast, BlockCheckMode}; -use rustc_ast::{FormatAlignment, FormatArgPosition, FormatArgsPiece, FormatCount, FormatTrait}; +use rustc_ast::{ + FormatAlignment, FormatArgPosition, FormatArgsPiece, FormatCount, FormatDebugHex, FormatSign, + FormatTrait, +}; use std::fmt::Write; impl<'a> State<'a> { @@ -675,17 +678,15 @@ pub fn reconstruct_format_args_template_string(pieces: &[FormatArgsPiece]) -> St Some(FormatAlignment::Center) => template.push_str("^"), None => {} } - let flags = p.format_options.flags; - if flags >> (rustc_parse_format::FlagSignPlus as usize) & 1 != 0 { - template.push('+'); - } - if flags >> (rustc_parse_format::FlagSignMinus as usize) & 1 != 0 { - template.push('-'); + match p.format_options.sign { + Some(FormatSign::Plus) => template.push('+'), + Some(FormatSign::Minus) => template.push('-'), + None => {} } - if flags >> (rustc_parse_format::FlagAlternate as usize) & 1 != 0 { + if p.format_options.alternate { template.push('#'); } - if flags >> (rustc_parse_format::FlagSignAwareZeroPad as usize) & 1 != 0 { + if p.format_options.zero_pad { template.push('0'); } if let Some(width) = &p.format_options.width { @@ -709,11 +710,10 @@ pub fn reconstruct_format_args_template_string(pieces: &[FormatArgsPiece]) -> St } } } - if flags >> (rustc_parse_format::FlagDebugLowerHex as usize) & 1 != 0 { - template.push('x'); - } - if flags >> (rustc_parse_format::FlagDebugUpperHex as usize) & 1 != 0 { - template.push('X'); + match p.format_options.debug_hex { + Some(FormatDebugHex::Lower) => template.push('x'), + Some(FormatDebugHex::Upper) => template.push('X'), + None => {} } template.push_str(match p.format_trait { FormatTrait::Display => "", diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index 469f0dc130383..e93a23394c03f 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -4,7 +4,7 @@ use rustc_ast::tokenstream::TokenStream; use rustc_ast::{ Expr, ExprKind, FormatAlignment, FormatArgPosition, FormatArgPositionKind, FormatArgs, FormatArgsPiece, FormatArgument, FormatArgumentKind, FormatArguments, FormatCount, - FormatOptions, FormatPlaceholder, FormatTrait, + FormatDebugHex, FormatOptions, FormatPlaceholder, FormatSign, FormatTrait, }; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{pluralize, Applicability, MultiSpan, PResult}; @@ -435,7 +435,16 @@ pub fn make_format_args( format_options: FormatOptions { fill: format.fill, alignment, - flags: format.flags, + sign: format.sign.map(|s| match s { + parse::Sign::Plus => FormatSign::Plus, + parse::Sign::Minus => FormatSign::Minus, + }), + alternate: format.alternate, + zero_pad: format.zero_pad, + debug_hex: format.debug_hex.map(|s| match s { + parse::DebugHex::Lower => FormatDebugHex::Lower, + parse::DebugHex::Upper => FormatDebugHex::Upper, + }), precision, width, }, diff --git a/compiler/rustc_parse_format/src/lib.rs b/compiler/rustc_parse_format/src/lib.rs index 7b016cadac320..a6dfcd2976247 100644 --- a/compiler/rustc_parse_format/src/lib.rs +++ b/compiler/rustc_parse_format/src/lib.rs @@ -16,7 +16,6 @@ pub use Alignment::*; pub use Count::*; -pub use Flag::*; pub use Piece::*; pub use Position::*; @@ -111,8 +110,14 @@ pub struct FormatSpec<'a> { pub fill: Option, /// Optionally specified alignment. pub align: Alignment, - /// Packed version of various flags provided. - pub flags: u32, + /// The `+` or `-` flag. + pub sign: Option, + /// The `#` flag. + pub alternate: bool, + /// The `0` flag. + pub zero_pad: bool, + /// The `x` or `X` flag. (Only for `Debug`.) + pub debug_hex: Option, /// The integer precision to use. pub precision: Count<'a>, /// The span of the precision formatting flag (for diagnostics). @@ -162,24 +167,22 @@ pub enum Alignment { AlignUnknown, } -/// Various flags which can be applied to format strings. The meaning of these -/// flags is defined by the formatters themselves. +/// Enum for the sign flags. #[derive(Copy, Clone, Debug, PartialEq)] -pub enum Flag { - /// A `+` will be used to denote positive numbers. - FlagSignPlus, - /// A `-` will be used to denote negative numbers. This is the default. - FlagSignMinus, - /// An alternate form will be used for the value. In the case of numbers, - /// this means that the number will be prefixed with the supplied string. - FlagAlternate, - /// For numbers, this means that the number will be padded with zeroes, - /// and the sign (`+` or `-`) will precede them. - FlagSignAwareZeroPad, - /// For Debug / `?`, format integers in lower-case hexadecimal. - FlagDebugLowerHex, - /// For Debug / `?`, format integers in upper-case hexadecimal. - FlagDebugUpperHex, +pub enum Sign { + /// The `+` flag. + Plus, + /// The `-` flag. + Minus, +} + +/// Enum for the debug hex flags. +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum DebugHex { + /// The `x` flag in `{:x?}`. + Lower, + /// The `X` flag in `{:X?}`. + Upper, } /// A count is used for the precision and width parameters of an integer, and @@ -597,7 +600,10 @@ impl<'a> Parser<'a> { let mut spec = FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountImplied, precision_span: None, width: CountImplied, @@ -626,13 +632,13 @@ impl<'a> Parser<'a> { } // Sign flags if self.consume('+') { - spec.flags |= 1 << (FlagSignPlus as u32); + spec.sign = Some(Sign::Plus); } else if self.consume('-') { - spec.flags |= 1 << (FlagSignMinus as u32); + spec.sign = Some(Sign::Minus); } // Alternate marker if self.consume('#') { - spec.flags |= 1 << (FlagAlternate as u32); + spec.alternate = true; } // Width and precision let mut havewidth = false; @@ -647,7 +653,7 @@ impl<'a> Parser<'a> { spec.width_span = Some(self.span(end - 1, end + 1)); havewidth = true; } else { - spec.flags |= 1 << (FlagSignAwareZeroPad as u32); + spec.zero_pad = true; } } @@ -678,14 +684,14 @@ impl<'a> Parser<'a> { // Optional radix followed by the actual format specifier if self.consume('x') { if self.consume('?') { - spec.flags |= 1 << (FlagDebugLowerHex as u32); + spec.debug_hex = Some(DebugHex::Lower); spec.ty = "?"; } else { spec.ty = "x"; } } else if self.consume('X') { if self.consume('?') { - spec.flags |= 1 << (FlagDebugUpperHex as u32); + spec.debug_hex = Some(DebugHex::Upper); spec.ty = "?"; } else { spec.ty = "X"; @@ -708,7 +714,10 @@ impl<'a> Parser<'a> { let mut spec = FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountImplied, precision_span: None, width: CountImplied, diff --git a/compiler/rustc_parse_format/src/tests.rs b/compiler/rustc_parse_format/src/tests.rs index 2992ba845ab16..45314e2fb5500 100644 --- a/compiler/rustc_parse_format/src/tests.rs +++ b/compiler/rustc_parse_format/src/tests.rs @@ -10,7 +10,10 @@ fn fmtdflt() -> FormatSpec<'static> { return FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountImplied, width: CountImplied, precision_span: None, @@ -126,7 +129,10 @@ fn format_type() { format: FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountImplied, width: CountImplied, precision_span: None, @@ -147,7 +153,10 @@ fn format_align_fill() { format: FormatSpec { fill: None, align: AlignRight, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountImplied, width: CountImplied, precision_span: None, @@ -165,7 +174,10 @@ fn format_align_fill() { format: FormatSpec { fill: Some('0'), align: AlignLeft, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountImplied, width: CountImplied, precision_span: None, @@ -183,7 +195,10 @@ fn format_align_fill() { format: FormatSpec { fill: Some('*'), align: AlignLeft, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountImplied, width: CountImplied, precision_span: None, @@ -204,7 +219,10 @@ fn format_counts() { format: FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountImplied, precision_span: None, width: CountIs(10), @@ -222,7 +240,10 @@ fn format_counts() { format: FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountIs(10), precision_span: Some(InnerSpan { start: 6, end: 9 }), width: CountIsParam(10), @@ -240,7 +261,10 @@ fn format_counts() { format: FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountIs(10), precision_span: Some(InnerSpan { start: 6, end: 9 }), width: CountIsParam(0), @@ -258,7 +282,10 @@ fn format_counts() { format: FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountIsStar(0), precision_span: Some(InnerSpan { start: 3, end: 5 }), width: CountImplied, @@ -276,7 +303,10 @@ fn format_counts() { format: FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountIsParam(10), width: CountImplied, precision_span: Some(InnerSpan::new(3, 7)), @@ -294,7 +324,10 @@ fn format_counts() { format: FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountIsName("b", InnerSpan { start: 6, end: 7 }), precision_span: Some(InnerSpan { start: 5, end: 8 }), width: CountIsName("a", InnerSpan { start: 3, end: 4 }), @@ -312,7 +345,10 @@ fn format_counts() { format: FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountIs(4), precision_span: Some(InnerSpan { start: 3, end: 5 }), width: CountImplied, @@ -333,7 +369,10 @@ fn format_flags() { format: FormatSpec { fill: None, align: AlignUnknown, - flags: (1 << FlagSignMinus as u32), + sign: Some(Sign::Minus), + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountImplied, width: CountImplied, precision_span: None, @@ -351,7 +390,10 @@ fn format_flags() { format: FormatSpec { fill: None, align: AlignUnknown, - flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32), + sign: Some(Sign::Plus), + alternate: true, + zero_pad: false, + debug_hex: None, precision: CountImplied, width: CountImplied, precision_span: None, @@ -374,7 +416,10 @@ fn format_mixture() { format: FormatSpec { fill: None, align: AlignUnknown, - flags: 0, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, precision: CountImplied, width: CountImplied, precision_span: None, From be69002dd704a918885de493355705a545fa908a Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Fri, 13 Jan 2023 13:56:51 +0100 Subject: [PATCH 401/500] Update clippy for restructured format flags fields. --- src/tools/clippy/clippy_utils/src/macros.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/tools/clippy/clippy_utils/src/macros.rs b/src/tools/clippy/clippy_utils/src/macros.rs index a8f8da67b5171..659063b97e74a 100644 --- a/src/tools/clippy/clippy_utils/src/macros.rs +++ b/src/tools/clippy/clippy_utils/src/macros.rs @@ -711,8 +711,8 @@ pub struct FormatSpec<'tcx> { pub fill: Option, /// Optionally specified alignment. pub align: Alignment, - /// Packed version of various flags provided, see [`rustc_parse_format::Flag`]. - pub flags: u32, + /// Whether all flag options are set to default (no flags specified). + pub no_flags: bool, /// Represents either the maximum width or the integer precision. pub precision: Count<'tcx>, /// The minimum width, will be padded according to `width`/`align` @@ -728,7 +728,7 @@ impl<'tcx> FormatSpec<'tcx> { Some(Self { fill: spec.fill, align: spec.align, - flags: spec.flags, + no_flags: spec.sign.is_none() && !spec.alternate && !spec.zero_pad && spec.debug_hex.is_none(), precision: Count::new( FormatParamUsage::Precision, spec.precision, @@ -773,7 +773,7 @@ impl<'tcx> FormatSpec<'tcx> { self.width.is_implied() && self.precision.is_implied() && self.align == Alignment::AlignUnknown - && self.flags == 0 + && self.no_flags } } From 43cb610464393640a56fd7aa528c1c8f5b33ad0d Mon Sep 17 00:00:00 2001 From: Ali MJ Al-Nasrawy Date: Fri, 27 Jan 2023 12:43:29 +0300 Subject: [PATCH 402/500] update comment on trait objects --- compiler/rustc_hir_analysis/src/variance/constraints.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index ca65020728761..8366f9f0ad613 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -253,7 +253,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { } ty::Dynamic(data, r, _) => { - // The type `Foo` is covariant w/r/t `'a`: + // The type `dyn Trait +'a` is covariant w/r/t `'a`: self.add_constraints_from_region(current, r, variance); if let Some(poly_trait_ref) = data.principal() { From cd233231aa215b7a5642e6a80869959b375e0725 Mon Sep 17 00:00:00 2001 From: yukang Date: Thu, 26 Jan 2023 11:02:19 +0800 Subject: [PATCH 403/500] Improve unexpected close and mismatch delimiter hint in TokenTreesReader --- compiler/rustc_parse/src/lexer/diagnostics.rs | 119 ++++++++++++++++ compiler/rustc_parse/src/lexer/mod.rs | 1 + compiler/rustc_parse/src/lexer/tokentrees.rs | 129 ++++++------------ tests/ui/parser/deli-ident-issue-1.rs | 1 - tests/ui/parser/deli-ident-issue-1.stderr | 16 +-- tests/ui/parser/deli-ident-issue-2.stderr | 6 +- .../parser/issue-68987-unmatch-issue-1.stderr | 11 +- .../parser/issue-68987-unmatch-issue-2.stderr | 8 +- .../parser/issue-68987-unmatch-issue-3.stderr | 6 +- .../parser/issue-68987-unmatch-issue.stderr | 11 +- tests/ui/parser/issue-81827.stderr | 10 +- tests/ui/parser/issues/issue-62973.stderr | 12 +- tests/ui/parser/issues/issue-63116.stderr | 5 +- tests/ui/parser/issues/issue-69259.stderr | 5 - .../issue-70583-block-is-empty-1.stderr | 4 +- .../issue-70583-block-is-empty-2.stderr | 6 +- .../macro-mismatched-delim-paren-brace.stderr | 4 +- tests/ui/typeck/issue-91334.stderr | 10 +- 18 files changed, 225 insertions(+), 139 deletions(-) create mode 100644 compiler/rustc_parse/src/lexer/diagnostics.rs diff --git a/compiler/rustc_parse/src/lexer/diagnostics.rs b/compiler/rustc_parse/src/lexer/diagnostics.rs new file mode 100644 index 0000000000000..386bf026bb4af --- /dev/null +++ b/compiler/rustc_parse/src/lexer/diagnostics.rs @@ -0,0 +1,119 @@ +use super::UnmatchedBrace; +use rustc_ast::token::Delimiter; +use rustc_errors::Diagnostic; +use rustc_span::source_map::SourceMap; +use rustc_span::Span; + +#[derive(Default)] +pub struct TokenTreeDiagInfo { + /// Stack of open delimiters and their spans. Used for error message. + pub open_braces: Vec<(Delimiter, Span)>, + pub unmatched_braces: Vec, + + /// Used only for error recovery when arriving to EOF with mismatched braces. + pub last_unclosed_found_span: Option, + + /// Collect empty block spans that might have been auto-inserted by editors. + pub empty_block_spans: Vec, + + /// Collect the spans of braces (Open, Close). Used only + /// for detecting if blocks are empty and only braces. + pub matching_block_spans: Vec<(Span, Span)>, +} + +pub fn same_identation_level(sm: &SourceMap, open_sp: Span, close_sp: Span) -> bool { + match (sm.span_to_margin(open_sp), sm.span_to_margin(close_sp)) { + (Some(open_padding), Some(close_padding)) => open_padding == close_padding, + _ => false, + } +} + +// When we get a `)` or `]` for `{`, we should emit help message here +// it's more friendly compared to report `unmatched error` in later phase +pub fn report_missing_open_delim( + err: &mut Diagnostic, + unmatched_braces: &[UnmatchedBrace], +) -> bool { + let mut reported_missing_open = false; + for unmatch_brace in unmatched_braces.iter() { + if let Some(delim) = unmatch_brace.found_delim + && matches!(delim, Delimiter::Parenthesis | Delimiter::Bracket) + { + let missed_open = match delim { + Delimiter::Parenthesis => "(", + Delimiter::Bracket => "[", + _ => unreachable!(), + }; + err.span_label( + unmatch_brace.found_span.shrink_to_lo(), + format!("missing open `{}` for this delimiter", missed_open), + ); + reported_missing_open = true; + } + } + reported_missing_open +} + +pub fn report_suspicious_mismatch_block( + err: &mut Diagnostic, + diag_info: &TokenTreeDiagInfo, + sm: &SourceMap, + delim: Delimiter, +) { + if report_missing_open_delim(err, &diag_info.unmatched_braces) { + return; + } + + let mut matched_spans: Vec<(Span, bool)> = diag_info + .matching_block_spans + .iter() + .map(|&(open, close)| (open.with_hi(close.lo()), same_identation_level(sm, open, close))) + .collect(); + + // sort by `lo`, so the large block spans in the front + matched_spans.sort_by(|a, b| a.0.lo().cmp(&b.0.lo())); + + // We use larger block whose identation is well to cover those inner mismatched blocks + // O(N^2) here, but we are on error reporting path, so it is fine + for i in 0..matched_spans.len() { + let (block_span, same_ident) = matched_spans[i]; + if same_ident { + for j in i + 1..matched_spans.len() { + let (inner_block, inner_same_ident) = matched_spans[j]; + if block_span.contains(inner_block) && !inner_same_ident { + matched_spans[j] = (inner_block, true); + } + } + } + } + + // Find the inner-most span candidate for final report + let candidate_span = + matched_spans.into_iter().rev().find(|&(_, same_ident)| !same_ident).map(|(span, _)| span); + + if let Some(block_span) = candidate_span { + err.span_label(block_span.shrink_to_lo(), "this delimiter might not be properly closed..."); + err.span_label( + block_span.shrink_to_hi(), + "...as it matches this but it has different indentation", + ); + + // If there is a empty block in the mismatched span, note it + if delim == Delimiter::Brace { + for span in diag_info.empty_block_spans.iter() { + if block_span.contains(*span) { + err.span_label(*span, "block is empty, you might have not meant to close it"); + break; + } + } + } + } else { + // If there is no suspicious span, give the last properly closed block may help + if let Some(parent) = diag_info.matching_block_spans.last() + && diag_info.open_braces.last().is_none() + && diag_info.empty_block_spans.iter().all(|&sp| sp != parent.0.to(parent.1)) { + err.span_label(parent.0, "this opening brace..."); + err.span_label(parent.1, "...matches this closing brace"); + } + } +} diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs index 9fe8d9836ba60..e957224a03377 100644 --- a/compiler/rustc_parse/src/lexer/mod.rs +++ b/compiler/rustc_parse/src/lexer/mod.rs @@ -17,6 +17,7 @@ use rustc_session::parse::ParseSess; use rustc_span::symbol::{sym, Symbol}; use rustc_span::{edition::Edition, BytePos, Pos, Span}; +mod diagnostics; mod tokentrees; mod unescape_error_reporting; mod unicode_chars; diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs index b2701817d489b..0de8f79112c65 100644 --- a/compiler/rustc_parse/src/lexer/tokentrees.rs +++ b/compiler/rustc_parse/src/lexer/tokentrees.rs @@ -1,29 +1,18 @@ +use super::diagnostics::report_suspicious_mismatch_block; +use super::diagnostics::same_identation_level; +use super::diagnostics::TokenTreeDiagInfo; use super::{StringReader, UnmatchedBrace}; use rustc_ast::token::{self, Delimiter, Token}; use rustc_ast::tokenstream::{DelimSpan, Spacing, TokenStream, TokenTree}; use rustc_ast_pretty::pprust::token_to_string; -use rustc_data_structures::fx::FxHashMap; use rustc_errors::{PErr, PResult}; -use rustc_span::Span; pub(super) struct TokenTreesReader<'a> { string_reader: StringReader<'a>, /// The "next" token, which has been obtained from the `StringReader` but /// not yet handled by the `TokenTreesReader`. token: Token, - /// Stack of open delimiters and their spans. Used for error message. - open_braces: Vec<(Delimiter, Span)>, - unmatched_braces: Vec, - /// The type and spans for all braces - /// - /// Used only for error recovery when arriving to EOF with mismatched braces. - matching_delim_spans: Vec<(Delimiter, Span, Span)>, - last_unclosed_found_span: Option, - /// Collect empty block spans that might have been auto-inserted by editors. - last_delim_empty_block_spans: FxHashMap, - /// Collect the spans of braces (Open, Close). Used only - /// for detecting if blocks are empty and only braces. - matching_block_spans: Vec<(Span, Span)>, + diag_info: TokenTreeDiagInfo, } impl<'a> TokenTreesReader<'a> { @@ -33,15 +22,10 @@ impl<'a> TokenTreesReader<'a> { let mut tt_reader = TokenTreesReader { string_reader, token: Token::dummy(), - open_braces: Vec::new(), - unmatched_braces: Vec::new(), - matching_delim_spans: Vec::new(), - last_unclosed_found_span: None, - last_delim_empty_block_spans: FxHashMap::default(), - matching_block_spans: Vec::new(), + diag_info: TokenTreeDiagInfo::default(), }; let res = tt_reader.parse_token_trees(/* is_delimited */ false); - (res, tt_reader.unmatched_braces) + (res, tt_reader.diag_info.unmatched_braces) } // Parse a stream of tokens into a list of `TokenTree`s. @@ -92,9 +76,9 @@ impl<'a> TokenTreesReader<'a> { fn eof_err(&mut self) -> PErr<'a> { let msg = "this file contains an unclosed delimiter"; let mut err = self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, msg); - for &(_, sp) in &self.open_braces { + for &(_, sp) in &self.diag_info.open_braces { err.span_label(sp, "unclosed delimiter"); - self.unmatched_braces.push(UnmatchedBrace { + self.diag_info.unmatched_braces.push(UnmatchedBrace { expected_delim: Delimiter::Brace, found_delim: None, found_span: self.token.span, @@ -103,23 +87,13 @@ impl<'a> TokenTreesReader<'a> { }); } - if let Some((delim, _)) = self.open_braces.last() { - if let Some((_, open_sp, close_sp)) = - self.matching_delim_spans.iter().find(|(d, open_sp, close_sp)| { - let sm = self.string_reader.sess.source_map(); - if let Some(close_padding) = sm.span_to_margin(*close_sp) { - if let Some(open_padding) = sm.span_to_margin(*open_sp) { - return delim == d && close_padding != open_padding; - } - } - false - }) - // these are in reverse order as they get inserted on close, but - { - // we want the last open/first close - err.span_label(*open_sp, "this delimiter might not be properly closed..."); - err.span_label(*close_sp, "...as it matches this but it has different indentation"); - } + if let Some((delim, _)) = self.diag_info.open_braces.last() { + report_suspicious_mismatch_block( + &mut err, + &self.diag_info, + &self.string_reader.sess.source_map(), + *delim, + ) } err } @@ -128,7 +102,7 @@ impl<'a> TokenTreesReader<'a> { // The span for beginning of the delimited section let pre_span = self.token.span; - self.open_braces.push((open_delim, self.token.span)); + self.diag_info.open_braces.push((open_delim, self.token.span)); // Parse the token trees within the delimiters. // We stop at any delimiter so we can try to recover if the user @@ -137,35 +111,29 @@ impl<'a> TokenTreesReader<'a> { // Expand to cover the entire delimited token tree let delim_span = DelimSpan::from_pair(pre_span, self.token.span); + let sm = self.string_reader.sess.source_map(); match self.token.kind { // Correct delimiter. token::CloseDelim(close_delim) if close_delim == open_delim => { - let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); + let (open_brace, open_brace_span) = self.diag_info.open_braces.pop().unwrap(); let close_brace_span = self.token.span; - if tts.is_empty() { + if tts.is_empty() && close_delim == Delimiter::Brace { let empty_block_span = open_brace_span.to(close_brace_span); - let sm = self.string_reader.sess.source_map(); if !sm.is_multiline(empty_block_span) { // Only track if the block is in the form of `{}`, otherwise it is // likely that it was written on purpose. - self.last_delim_empty_block_spans.insert(open_delim, empty_block_span); + self.diag_info.empty_block_spans.push(empty_block_span); } } - //only add braces + // only add braces if let (Delimiter::Brace, Delimiter::Brace) = (open_brace, open_delim) { - self.matching_block_spans.push((open_brace_span, close_brace_span)); + // Add all the matching spans, we will sort by span later + self.diag_info.matching_block_spans.push((open_brace_span, close_brace_span)); } - if self.open_braces.is_empty() { - // Clear up these spans to avoid suggesting them as we've found - // properly matched delimiters so far for an entire block. - self.matching_delim_spans.clear(); - } else { - self.matching_delim_spans.push((open_brace, open_brace_span, close_brace_span)); - } // Move past the closing delimiter. self.token = self.string_reader.next_token().0; } @@ -174,28 +142,25 @@ impl<'a> TokenTreesReader<'a> { let mut unclosed_delimiter = None; let mut candidate = None; - if self.last_unclosed_found_span != Some(self.token.span) { + if self.diag_info.last_unclosed_found_span != Some(self.token.span) { // do not complain about the same unclosed delimiter multiple times - self.last_unclosed_found_span = Some(self.token.span); + self.diag_info.last_unclosed_found_span = Some(self.token.span); // This is a conservative error: only report the last unclosed // delimiter. The previous unclosed delimiters could actually be // closed! The parser just hasn't gotten to them yet. - if let Some(&(_, sp)) = self.open_braces.last() { + if let Some(&(_, sp)) = self.diag_info.open_braces.last() { unclosed_delimiter = Some(sp); }; - let sm = self.string_reader.sess.source_map(); - if let Some(current_padding) = sm.span_to_margin(self.token.span) { - for (brace, brace_span) in &self.open_braces { - if let Some(padding) = sm.span_to_margin(*brace_span) { - // high likelihood of these two corresponding - if current_padding == padding && brace == &close_delim { - candidate = Some(*brace_span); - } - } + for (brace, brace_span) in &self.diag_info.open_braces { + if same_identation_level(&sm, self.token.span, *brace_span) + && brace == &close_delim + { + // high likelihood of these two corresponding + candidate = Some(*brace_span); } } - let (tok, _) = self.open_braces.pop().unwrap(); - self.unmatched_braces.push(UnmatchedBrace { + let (tok, _) = self.diag_info.open_braces.pop().unwrap(); + self.diag_info.unmatched_braces.push(UnmatchedBrace { expected_delim: tok, found_delim: Some(close_delim), found_span: self.token.span, @@ -203,7 +168,7 @@ impl<'a> TokenTreesReader<'a> { candidate_span: candidate, }); } else { - self.open_braces.pop(); + self.diag_info.open_braces.pop(); } // If the incorrect delimiter matches an earlier opening @@ -213,7 +178,7 @@ impl<'a> TokenTreesReader<'a> { // fn foo() { // bar(baz( // } // Incorrect delimiter but matches the earlier `{` - if !self.open_braces.iter().any(|&(b, _)| b == close_delim) { + if !self.diag_info.open_braces.iter().any(|&(b, _)| b == close_delim) { self.token = self.string_reader.next_token().0; } } @@ -236,22 +201,12 @@ impl<'a> TokenTreesReader<'a> { let mut err = self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, &msg); - // Braces are added at the end, so the last element is the biggest block - if let Some(parent) = self.matching_block_spans.last() { - if let Some(span) = self.last_delim_empty_block_spans.remove(&delim) { - // Check if the (empty block) is in the last properly closed block - if (parent.0.to(parent.1)).contains(span) { - err.span_label(span, "block is empty, you might have not meant to close it"); - } else { - err.span_label(parent.0, "this opening brace..."); - err.span_label(parent.1, "...matches this closing brace"); - } - } else { - err.span_label(parent.0, "this opening brace..."); - err.span_label(parent.1, "...matches this closing brace"); - } - } - + report_suspicious_mismatch_block( + &mut err, + &self.diag_info, + &self.string_reader.sess.source_map(), + delim, + ); err.span_label(self.token.span, "unexpected closing delimiter"); err } diff --git a/tests/ui/parser/deli-ident-issue-1.rs b/tests/ui/parser/deli-ident-issue-1.rs index a8cbf8640f7a3..54485262a0cc8 100644 --- a/tests/ui/parser/deli-ident-issue-1.rs +++ b/tests/ui/parser/deli-ident-issue-1.rs @@ -1,4 +1,3 @@ -// error-pattern: this file contains an unclosed delimiter #![feature(let_chains)] trait Demo {} diff --git a/tests/ui/parser/deli-ident-issue-1.stderr b/tests/ui/parser/deli-ident-issue-1.stderr index 784f598f9d05c..1119edb199f05 100644 --- a/tests/ui/parser/deli-ident-issue-1.stderr +++ b/tests/ui/parser/deli-ident-issue-1.stderr @@ -1,26 +1,26 @@ error: this file contains an unclosed delimiter - --> $DIR/deli-ident-issue-1.rs:25:66 + --> $DIR/deli-ident-issue-1.rs:24:66 | LL | impl dyn Demo { | - unclosed delimiter ... -LL | c: u32| { - | - this delimiter might not be properly closed... -LL | a + b + c -LL | }; - | - ...as it matches this but it has different indentation +LL | && let Some(c) = num { + | - this delimiter might not be properly closed... +... +LL | } + | - ...as it matches this but it has different indentation ... LL | fn main() { } | ^ error[E0574]: expected struct, variant or union type, found local variable `c` - --> $DIR/deli-ident-issue-1.rs:18:17 + --> $DIR/deli-ident-issue-1.rs:17:17 | LL | && b == c { | ^ not a struct, variant or union type error[E0308]: mismatched types - --> $DIR/deli-ident-issue-1.rs:18:9 + --> $DIR/deli-ident-issue-1.rs:17:9 | LL | fn check(&self, val: Option, num: Option) { | - expected `()` because of default return type diff --git a/tests/ui/parser/deli-ident-issue-2.stderr b/tests/ui/parser/deli-ident-issue-2.stderr index 782dac8f32d35..c8f59c9d32b5f 100644 --- a/tests/ui/parser/deli-ident-issue-2.stderr +++ b/tests/ui/parser/deli-ident-issue-2.stderr @@ -1,11 +1,9 @@ error: unexpected closing delimiter: `}` --> $DIR/deli-ident-issue-2.rs:5:1 | -LL | fn main() { - | - this opening brace... -... +LL | let _a = vec!]; + | - missing open `[` for this delimiter LL | } - | - ...matches this closing brace LL | } | ^ unexpected closing delimiter diff --git a/tests/ui/parser/issue-68987-unmatch-issue-1.stderr b/tests/ui/parser/issue-68987-unmatch-issue-1.stderr index b5c1887f76f08..2d873b46193ce 100644 --- a/tests/ui/parser/issue-68987-unmatch-issue-1.stderr +++ b/tests/ui/parser/issue-68987-unmatch-issue-1.stderr @@ -1,9 +1,14 @@ error: unexpected closing delimiter: `}` --> $DIR/issue-68987-unmatch-issue-1.rs:10:1 | -LL | None => {} - | -- block is empty, you might have not meant to close it -LL | } +LL | match o { + | - this delimiter might not be properly closed... +LL | Some(_x) => {} // Extra '}' + | -- block is empty, you might have not meant to close it +LL | let _ = if true {}; +LL | } + | - ...as it matches this but it has different indentation +... LL | } | ^ unexpected closing delimiter diff --git a/tests/ui/parser/issue-68987-unmatch-issue-2.stderr b/tests/ui/parser/issue-68987-unmatch-issue-2.stderr index 253f12d44b83f..2c08d41a15f1b 100644 --- a/tests/ui/parser/issue-68987-unmatch-issue-2.stderr +++ b/tests/ui/parser/issue-68987-unmatch-issue-2.stderr @@ -1,11 +1,9 @@ error: unexpected closing delimiter: `}` --> $DIR/issue-68987-unmatch-issue-2.rs:14:1 | -LL | } else { - | - this opening brace... -LL | -LL | } - | - ...matches this closing brace +LL | let obs_connect = || -> Result<(), MyError) { + | - missing open `(` for this delimiter +... LL | } | ^ unexpected closing delimiter diff --git a/tests/ui/parser/issue-68987-unmatch-issue-3.stderr b/tests/ui/parser/issue-68987-unmatch-issue-3.stderr index 258a692c8557b..a3fc46a1e883c 100644 --- a/tests/ui/parser/issue-68987-unmatch-issue-3.stderr +++ b/tests/ui/parser/issue-68987-unmatch-issue-3.stderr @@ -1,11 +1,9 @@ error: unexpected closing delimiter: `}` --> $DIR/issue-68987-unmatch-issue-3.rs:8:1 | -LL | fn f(i: u32, j: u32) { - | - this opening brace... -... +LL | write!&mut res, " "); + | - missing open `(` for this delimiter LL | } - | - ...matches this closing brace LL | } | ^ unexpected closing delimiter diff --git a/tests/ui/parser/issue-68987-unmatch-issue.stderr b/tests/ui/parser/issue-68987-unmatch-issue.stderr index 00e9c9a5ccee0..cabd133242f60 100644 --- a/tests/ui/parser/issue-68987-unmatch-issue.stderr +++ b/tests/ui/parser/issue-68987-unmatch-issue.stderr @@ -1,9 +1,14 @@ error: unexpected closing delimiter: `}` --> $DIR/issue-68987-unmatch-issue.rs:10:1 | -LL | None => {} - | -- block is empty, you might have not meant to close it -LL | } +LL | match o { + | - this delimiter might not be properly closed... +LL | Some(_x) => // Missing '{' +LL | let _ = if true {}; + | -- block is empty, you might have not meant to close it +LL | } + | - ...as it matches this but it has different indentation +... LL | } | ^ unexpected closing delimiter diff --git a/tests/ui/parser/issue-81827.stderr b/tests/ui/parser/issue-81827.stderr index 069de33919494..867244b72e849 100644 --- a/tests/ui/parser/issue-81827.stderr +++ b/tests/ui/parser/issue-81827.stderr @@ -2,8 +2,9 @@ error: this file contains an unclosed delimiter --> $DIR/issue-81827.rs:11:27 | LL | fn r()->i{0|{#[cfg(r(0{]0 - | - - ^ - | | | + | - - - ^ + | | | | + | | | missing open `[` for this delimiter | | unclosed delimiter | unclosed delimiter @@ -11,8 +12,9 @@ error: this file contains an unclosed delimiter --> $DIR/issue-81827.rs:11:27 | LL | fn r()->i{0|{#[cfg(r(0{]0 - | - - ^ - | | | + | - - - ^ + | | | | + | | | missing open `[` for this delimiter | | unclosed delimiter | unclosed delimiter diff --git a/tests/ui/parser/issues/issue-62973.stderr b/tests/ui/parser/issues/issue-62973.stderr index 4737bc71860c2..3cb6d75a6754b 100644 --- a/tests/ui/parser/issues/issue-62973.stderr +++ b/tests/ui/parser/issues/issue-62973.stderr @@ -2,8 +2,10 @@ error: this file contains an unclosed delimiter --> $DIR/issue-62973.rs:8:2 | LL | fn p() { match s { v, E { [) {) } - | - - unclosed delimiter - | | + | - - - - missing open `(` for this delimiter + | | | | + | | | missing open `(` for this delimiter + | | unclosed delimiter | unclosed delimiter LL | LL | @@ -13,8 +15,10 @@ error: this file contains an unclosed delimiter --> $DIR/issue-62973.rs:8:2 | LL | fn p() { match s { v, E { [) {) } - | - - unclosed delimiter - | | + | - - - - missing open `(` for this delimiter + | | | | + | | | missing open `(` for this delimiter + | | unclosed delimiter | unclosed delimiter LL | LL | diff --git a/tests/ui/parser/issues/issue-63116.stderr b/tests/ui/parser/issues/issue-63116.stderr index cfdd99d1434ae..a1f8a77ffa7c6 100644 --- a/tests/ui/parser/issues/issue-63116.stderr +++ b/tests/ui/parser/issues/issue-63116.stderr @@ -2,8 +2,9 @@ error: this file contains an unclosed delimiter --> $DIR/issue-63116.rs:3:18 | LL | impl W $DIR/issue-69259.rs:3:5 | -LL | fn main() {} - | -- ...matches this closing brace - | | - | this opening brace... -LL | LL | fn f) {} | ^ unexpected closing delimiter diff --git a/tests/ui/parser/issues/issue-70583-block-is-empty-1.stderr b/tests/ui/parser/issues/issue-70583-block-is-empty-1.stderr index 39bf113ef83de..46cbb056d1d88 100644 --- a/tests/ui/parser/issues/issue-70583-block-is-empty-1.stderr +++ b/tests/ui/parser/issues/issue-70583-block-is-empty-1.stderr @@ -2,10 +2,10 @@ error: unexpected closing delimiter: `}` --> $DIR/issue-70583-block-is-empty-1.rs:20:1 | LL | fn struct_generic(x: Vec) { - | - this opening brace... + | - this delimiter might not be properly closed... ... LL | } - | - ...matches this closing brace + | - ...as it matches this but it has different indentation LL | } | ^ unexpected closing delimiter diff --git a/tests/ui/parser/issues/issue-70583-block-is-empty-2.stderr b/tests/ui/parser/issues/issue-70583-block-is-empty-2.stderr index 5d37b216427f6..9ae94c701869b 100644 --- a/tests/ui/parser/issues/issue-70583-block-is-empty-2.stderr +++ b/tests/ui/parser/issues/issue-70583-block-is-empty-2.stderr @@ -1,8 +1,12 @@ error: unexpected closing delimiter: `}` --> $DIR/issue-70583-block-is-empty-2.rs:14:1 | +LL | match self { + | - this delimiter might not be properly closed... LL | ErrorHandled::Reported => {}} - | -- block is empty, you might have not meant to close it + | --- ...as it matches this but it has different indentation + | | + | block is empty, you might have not meant to close it ... LL | } | ^ unexpected closing delimiter diff --git a/tests/ui/parser/macro-mismatched-delim-paren-brace.stderr b/tests/ui/parser/macro-mismatched-delim-paren-brace.stderr index 967a3e6fdc11b..689ce1eb6b704 100644 --- a/tests/ui/parser/macro-mismatched-delim-paren-brace.stderr +++ b/tests/ui/parser/macro-mismatched-delim-paren-brace.stderr @@ -2,10 +2,10 @@ error: unexpected closing delimiter: `}` --> $DIR/macro-mismatched-delim-paren-brace.rs:5:1 | LL | fn main() { - | - this opening brace... + | - this delimiter might not be properly closed... ... LL | } - | - ...matches this closing brace + | - ...as it matches this but it has different indentation LL | } | ^ unexpected closing delimiter diff --git a/tests/ui/typeck/issue-91334.stderr b/tests/ui/typeck/issue-91334.stderr index 8508f7a38e239..78f392c9a8acc 100644 --- a/tests/ui/typeck/issue-91334.stderr +++ b/tests/ui/typeck/issue-91334.stderr @@ -2,8 +2,9 @@ error: this file contains an unclosed delimiter --> $DIR/issue-91334.rs:10:23 | LL | fn f(){||yield(((){), - | - - ^ - | | | + | - - - ^ + | | | | + | | | missing open `(` for this delimiter | | unclosed delimiter | unclosed delimiter @@ -11,8 +12,9 @@ error: this file contains an unclosed delimiter --> $DIR/issue-91334.rs:10:23 | LL | fn f(){||yield(((){), - | - - ^ - | | | + | - - - ^ + | | | | + | | | missing open `(` for this delimiter | | unclosed delimiter | unclosed delimiter From 706132d409d4a0156e88eeedeca255a19554841f Mon Sep 17 00:00:00 2001 From: Samuel Ortiz Date: Fri, 27 Jan 2023 10:58:58 +0100 Subject: [PATCH 404/500] compiler: Fix E0587 explanation We meant to use 8 as the packed argument. Signed-off-by: Samuel Ortiz --- compiler/rustc_error_codes/src/error_codes/E0587.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_error_codes/src/error_codes/E0587.md b/compiler/rustc_error_codes/src/error_codes/E0587.md index ee9031dc3796c..d7998af85b94f 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0587.md +++ b/compiler/rustc_error_codes/src/error_codes/E0587.md @@ -11,6 +11,6 @@ You cannot use `packed` and `align` hints on a same type. If you want to pack a type to a given size, you should provide a size to packed: ``` -#[repr(packed)] // ok! +#[repr(packed(8))] // ok! struct Umbrella(i32); ``` From 21cf9dbc8540656cb137ef31f9db8fd9f1398fd9 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Fri, 27 Jan 2023 11:43:38 +0100 Subject: [PATCH 405/500] Destructure format_options in make_format_spec. --- compiler/rustc_ast_lowering/src/format.rs | 32 +++++++++++++++-------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index 5d1770c734d5d..e7dd0b18a03b9 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -137,11 +137,21 @@ fn make_format_spec<'hir>( } Err(_) => ctx.expr(sp, hir::ExprKind::Err), }; - let fill = ctx.expr_char(sp, placeholder.format_options.fill.unwrap_or(' ')); + let &FormatOptions { + ref width, + ref precision, + alignment, + fill, + sign, + alternate, + zero_pad, + debug_hex, + } = &placeholder.format_options; + let fill = ctx.expr_char(sp, fill.unwrap_or(' ')); let align = ctx.expr_lang_item_type_relative( sp, hir::LangItem::FormatAlignment, - match placeholder.format_options.alignment { + match alignment { Some(FormatAlignment::Left) => sym::Left, Some(FormatAlignment::Right) => sym::Right, Some(FormatAlignment::Center) => sym::Center, @@ -149,21 +159,21 @@ fn make_format_spec<'hir>( }, ); // This needs to match `FlagV1` in library/core/src/fmt/mod.rs. - let flags: u32 = ((placeholder.format_options.sign == Some(FormatSign::Plus)) as u32) - | ((placeholder.format_options.sign == Some(FormatSign::Minus)) as u32) << 1 - | (placeholder.format_options.alternate as u32) << 2 - | (placeholder.format_options.zero_pad as u32) << 3 - | ((placeholder.format_options.debug_hex == Some(FormatDebugHex::Lower)) as u32) << 4 - | ((placeholder.format_options.debug_hex == Some(FormatDebugHex::Upper)) as u32) << 5; + let flags: u32 = ((sign == Some(FormatSign::Plus)) as u32) + | ((sign == Some(FormatSign::Minus)) as u32) << 1 + | (alternate as u32) << 2 + | (zero_pad as u32) << 3 + | ((debug_hex == Some(FormatDebugHex::Lower)) as u32) << 4 + | ((debug_hex == Some(FormatDebugHex::Upper)) as u32) << 5; let flags = ctx.expr_u32(sp, flags); - let prec = make_count(ctx, sp, &placeholder.format_options.precision, argmap); - let width = make_count(ctx, sp, &placeholder.format_options.width, argmap); + let precision = make_count(ctx, sp, &precision, argmap); + let width = make_count(ctx, sp, &width, argmap); let format_placeholder_new = ctx.arena.alloc(ctx.expr_lang_item_type_relative( sp, hir::LangItem::FormatPlaceholder, sym::new, )); - let args = ctx.arena.alloc_from_iter([position, fill, align, flags, prec, width]); + let args = ctx.arena.alloc_from_iter([position, fill, align, flags, precision, width]); ctx.expr_call_mut(sp, format_placeholder_new, args) } From dbe911ff36316c08f1e3316e593c96512d6860d7 Mon Sep 17 00:00:00 2001 From: Yuki Okushi Date: Fri, 27 Jan 2023 19:46:56 +0900 Subject: [PATCH 406/500] Add regression test for #60755 Signed-off-by: Yuki Okushi --- tests/ui/traits/alias/issue-60755.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 tests/ui/traits/alias/issue-60755.rs diff --git a/tests/ui/traits/alias/issue-60755.rs b/tests/ui/traits/alias/issue-60755.rs new file mode 100644 index 0000000000000..6b955a752479f --- /dev/null +++ b/tests/ui/traits/alias/issue-60755.rs @@ -0,0 +1,12 @@ +// check-pass + +#![feature(trait_alias)] + +struct MyStruct {} +trait MyFn = Fn(&MyStruct); + +fn foo(_: impl MyFn) {} + +fn main() { + foo(|_| {}); +} From b8c44fa414ebd27c21035b5e9247902723fa2590 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 27 Jan 2023 12:09:50 +0100 Subject: [PATCH 407/500] Fix infinite loop in rustdoc get_all_import_attributes function --- src/librustdoc/clean/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 3cb6ad10e72b8..4b1cd78c4adf9 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2112,10 +2112,12 @@ fn get_all_import_attributes<'hir>( ) { let hir_map = tcx.hir(); let mut visitor = OneLevelVisitor::new(hir_map, target_def_id); + let mut visited = FxHashSet::default(); // If the item is an import and has at least a path with two parts, we go into it. while let hir::ItemKind::Use(path, _) = item.kind && path.segments.len() > 1 && - let hir::def::Res::Def(_, def_id) = path.segments[path.segments.len() - 2].res + let hir::def::Res::Def(_, def_id) = path.segments[path.segments.len() - 2].res && + visited.insert(def_id) { if let Some(hir::Node::Item(parent_item)) = hir_map.get_if_local(def_id) { // We add the attributes from this import into the list. From 1b64e16643eb3322b61f916c8cfec436e30e7bf3 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 27 Jan 2023 12:10:05 +0100 Subject: [PATCH 408/500] Add regression test for #107350 --- tests/rustdoc/issue-107350.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 tests/rustdoc/issue-107350.rs diff --git a/tests/rustdoc/issue-107350.rs b/tests/rustdoc/issue-107350.rs new file mode 100644 index 0000000000000..75f378ed24980 --- /dev/null +++ b/tests/rustdoc/issue-107350.rs @@ -0,0 +1,18 @@ +// This is a regression test for . +// It shouldn't loop indefinitely. + +#![crate_name = "foo"] + +// @has 'foo/oops/enum.OhNo.html' + +pub mod oops { + pub use crate::oops::OhNo; + + mod inner { + pub enum OhNo { + Item = 1, + } + } + + pub use self::inner::*; +} From ed707a106cac7393db3b59d85b8b065d09840c61 Mon Sep 17 00:00:00 2001 From: clubby789 Date: Thu, 19 Jan 2023 23:48:08 +0000 Subject: [PATCH 409/500] Detect references to non-existant messages in Fluent resources --- .../rustc_macros/src/diagnostics/fluent.rs | 34 +++++++++++++++++-- .../fluent-messages/missing-message-ref.ftl | 1 + tests/ui-fulldeps/fluent-messages/test.rs | 9 +++++ tests/ui-fulldeps/fluent-messages/test.stderr | 10 +++++- 4 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 tests/ui-fulldeps/fluent-messages/missing-message-ref.ftl diff --git a/compiler/rustc_macros/src/diagnostics/fluent.rs b/compiler/rustc_macros/src/diagnostics/fluent.rs index 32338f9dfc5e3..08098c9bb2a85 100644 --- a/compiler/rustc_macros/src/diagnostics/fluent.rs +++ b/compiler/rustc_macros/src/diagnostics/fluent.rs @@ -4,7 +4,10 @@ use annotate_snippets::{ }; use fluent_bundle::{FluentBundle, FluentError, FluentResource}; use fluent_syntax::{ - ast::{Attribute, Entry, Identifier, Message}, + ast::{ + Attribute, Entry, Expression, Identifier, InlineExpression, Message, Pattern, + PatternElement, + }, parser::ParserError, }; use proc_macro::{Diagnostic, Level, Span}; @@ -185,9 +188,12 @@ pub(crate) fn fluent_messages(input: proc_macro::TokenStream) -> proc_macro::Tok }; let mut constants = TokenStream::new(); + let mut messagerefs = Vec::new(); for entry in resource.entries() { let span = res.krate.span(); - if let Entry::Message(Message { id: Identifier { name }, attributes, .. }) = entry { + if let Entry::Message(Message { id: Identifier { name }, attributes, value, .. }) = + entry + { let _ = previous_defns.entry(name.to_string()).or_insert(path_span); if name.contains('-') { @@ -200,6 +206,18 @@ pub(crate) fn fluent_messages(input: proc_macro::TokenStream) -> proc_macro::Tok .emit(); } + if let Some(Pattern { elements }) = value { + for elt in elements { + if let PatternElement::Placeable { + expression: + Expression::Inline(InlineExpression::MessageReference { id, .. }), + } = elt + { + messagerefs.push((id.name, *name)); + } + } + } + // Require that the message name starts with the crate name // `hir_typeck_foo_bar` (in `hir_typeck.ftl`) // `const_eval_baz` (in `const_eval.ftl`) @@ -258,6 +276,18 @@ pub(crate) fn fluent_messages(input: proc_macro::TokenStream) -> proc_macro::Tok } } + for (mref, name) in messagerefs.into_iter() { + if !previous_defns.contains_key(mref) { + Diagnostic::spanned( + path_span, + Level::Error, + format!("referenced message `{mref}` does not exist (in message `{name}`)"), + ) + .help(&format!("you may have meant to use a variable reference (`{{${mref}}}`)")) + .emit(); + } + } + if let Err(errs) = bundle.add_resource(resource) { for e in errs { match e { diff --git a/tests/ui-fulldeps/fluent-messages/missing-message-ref.ftl b/tests/ui-fulldeps/fluent-messages/missing-message-ref.ftl new file mode 100644 index 0000000000000..0cd8229b23010 --- /dev/null +++ b/tests/ui-fulldeps/fluent-messages/missing-message-ref.ftl @@ -0,0 +1 @@ +missing_message_ref = {message} diff --git a/tests/ui-fulldeps/fluent-messages/test.rs b/tests/ui-fulldeps/fluent-messages/test.rs index 4e8147e2b76dc..74303e97dba94 100644 --- a/tests/ui-fulldeps/fluent-messages/test.rs +++ b/tests/ui-fulldeps/fluent-messages/test.rs @@ -96,3 +96,12 @@ mod missing_crate_name { use self::fluent_generated::{DEFAULT_LOCALE_RESOURCES, test_crate_foo, with_hyphens}; } + +mod missing_message_ref { + use super::fluent_messages; + + fluent_messages! { + missing => "./missing-message-ref.ftl" +//~^ ERROR referenced message `message` does not exist + } +} diff --git a/tests/ui-fulldeps/fluent-messages/test.stderr b/tests/ui-fulldeps/fluent-messages/test.stderr index d1cd4fe26da27..2631b0a623275 100644 --- a/tests/ui-fulldeps/fluent-messages/test.stderr +++ b/tests/ui-fulldeps/fluent-messages/test.stderr @@ -93,6 +93,14 @@ LL | test_crate => "./missing-crate-name.ftl", | = help: replace any '-'s with '_'s -error: aborting due to 10 previous errors +error: referenced message `message` does not exist (in message `missing_message_ref`) + --> $DIR/test.rs:104:20 + | +LL | missing => "./missing-message-ref.ftl" + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: you may have meant to use a variable reference (`{$message}`) + +error: aborting due to 11 previous errors For more information about this error, try `rustc --explain E0428`. From 0ae0d87c5dd7b0b0b17124dadb2d5a3ce7e2bfef Mon Sep 17 00:00:00 2001 From: clubby789 Date: Thu, 19 Jan 2023 23:53:26 +0000 Subject: [PATCH 410/500] Fix some Fluent typos --- compiler/rustc_error_messages/locales/en-US/codegen_gcc.ftl | 2 +- compiler/rustc_error_messages/locales/en-US/codegen_ssa.ftl | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_error_messages/locales/en-US/codegen_gcc.ftl b/compiler/rustc_error_messages/locales/en-US/codegen_gcc.ftl index 08ce5172574ac..6101b28ab0cdd 100644 --- a/compiler/rustc_error_messages/locales/en-US/codegen_gcc.ftl +++ b/compiler/rustc_error_messages/locales/en-US/codegen_gcc.ftl @@ -23,7 +23,7 @@ codegen_gcc_invalid_monomorphization_unsupported_element = invalid monomorphization of `{$name}` intrinsic: unsupported {$name} from `{$in_ty}` with element `{$elem_ty}` to `{$ret_ty}` codegen_gcc_invalid_monomorphization_invalid_bitmask = - invalid monomorphization of `{$name}` intrinsic: invalid bitmask `{ty}`, expected `u{$expected_int_bits}` or `[u8; {$expected_bytes}]` + invalid monomorphization of `{$name}` intrinsic: invalid bitmask `{$ty}`, expected `u{$expected_int_bits}` or `[u8; {$expected_bytes}]` codegen_gcc_invalid_monomorphization_simd_shuffle = invalid monomorphization of `{$name}` intrinsic: simd_shuffle index must be an array of `u32`, got `{$ty}` diff --git a/compiler/rustc_error_messages/locales/en-US/codegen_ssa.ftl b/compiler/rustc_error_messages/locales/en-US/codegen_ssa.ftl index c8c7afb5f9196..4924105128db6 100644 --- a/compiler/rustc_error_messages/locales/en-US/codegen_ssa.ftl +++ b/compiler/rustc_error_messages/locales/en-US/codegen_ssa.ftl @@ -179,9 +179,9 @@ codegen_ssa_extract_bundled_libs_write_file = failed to write file '{$rlib}': {$ codegen_ssa_unsupported_arch = unsupported arch `{$arch}` for os `{$os}` -codegen_ssa_apple_sdk_error_sdk_path = failed to get {$sdk_name} SDK path: {error} +codegen_ssa_apple_sdk_error_sdk_path = failed to get {$sdk_name} SDK path: {$error} -codegen_ssa_read_file = failed to read file: {message} +codegen_ssa_read_file = failed to read file: {$message} codegen_ssa_unsupported_link_self_contained = option `-C link-self-contained` is not supported on this target From b2e298853113e9b9d68c956749d92ad540fb286d Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 27 Jan 2023 11:46:20 +0000 Subject: [PATCH 411/500] Revert "Avoid a temporary file when processing macOS fat archives" This reverts commit bd8e476d8bd85b6d60a0de7694d154b4a74f5133. --- .../rustc_codegen_ssa/src/back/archive.rs | 70 ++++++++++--------- 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/back/archive.rs b/compiler/rustc_codegen_ssa/src/back/archive.rs index 6eb120157da02..d3cd085cfb668 100644 --- a/compiler/rustc_codegen_ssa/src/back/archive.rs +++ b/compiler/rustc_codegen_ssa/src/back/archive.rs @@ -14,7 +14,7 @@ use tempfile::Builder as TempFileBuilder; use std::error::Error; use std::fs::File; -use std::io; +use std::io::{self, Write}; use std::path::{Path, PathBuf}; // Re-exporting for rustc_codegen_llvm::back::archive @@ -116,11 +116,12 @@ impl<'a> ArArchiveBuilder<'a> { } } -fn try_filter_fat_archs<'a>( +fn try_filter_fat_archs( archs: object::read::Result<&[impl FatArch]>, target_arch: object::Architecture, - archive_map_data: &'a [u8], -) -> io::Result> { + archive_path: &Path, + archive_map_data: &[u8], +) -> io::Result> { let archs = archs.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; let desired = match archs.iter().find(|a| a.architecture() == target_arch) { @@ -128,30 +129,38 @@ fn try_filter_fat_archs<'a>( None => return Ok(None), }; - Ok(Some(( + let (mut new_f, extracted_path) = tempfile::Builder::new() + .suffix(archive_path.file_name().unwrap()) + .tempfile()? + .keep() + .unwrap(); + + new_f.write_all( desired.data(archive_map_data).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?, - desired.offset().into(), - ))) + )?; + + Ok(Some(extracted_path)) } -pub fn try_extract_macho_fat_archive<'a>( +pub fn try_extract_macho_fat_archive( sess: &Session, - archive_bytes: &'a [u8], -) -> io::Result> { + archive_path: &Path, +) -> io::Result> { + let archive_map = unsafe { Mmap::map(File::open(&archive_path)?)? }; let target_arch = match sess.target.arch.as_ref() { "aarch64" => object::Architecture::Aarch64, "x86_64" => object::Architecture::X86_64, _ => return Ok(None), }; - match object::macho::FatHeader::parse(archive_bytes) { + match object::macho::FatHeader::parse(&*archive_map) { Ok(h) if h.magic.get(object::endian::BigEndian) == object::macho::FAT_MAGIC => { - let archs = object::macho::FatHeader::parse_arch32(archive_bytes); - try_filter_fat_archs(archs, target_arch, archive_bytes) + let archs = object::macho::FatHeader::parse_arch32(&*archive_map); + try_filter_fat_archs(archs, target_arch, archive_path, &*archive_map) } Ok(h) if h.magic.get(object::endian::BigEndian) == object::macho::FAT_MAGIC_64 => { - let archs = object::macho::FatHeader::parse_arch64(archive_bytes); - try_filter_fat_archs(archs, target_arch, archive_bytes) + let archs = object::macho::FatHeader::parse_arch64(&*archive_map); + try_filter_fat_archs(archs, target_arch, archive_path, &*archive_map) } // Not a FatHeader at all, just return None. _ => Ok(None), @@ -164,24 +173,21 @@ impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> { archive_path: &Path, mut skip: Box bool + 'static>, ) -> io::Result<()> { - let archive_map = unsafe { Mmap::map(File::open(&archive_path)?)? }; + let mut archive_path = archive_path.to_path_buf(); + if self.sess.target.llvm_target.contains("-apple-macosx") { + if let Some(new_archive_path) = + try_extract_macho_fat_archive(&self.sess, &archive_path)? + { + archive_path = new_archive_path + } + } + if self.src_archives.iter().any(|archive| archive.0 == archive_path) { return Ok(()); } - let (archive_bytes, offset) = if self.sess.target.llvm_target.contains("-apple-macosx") { - if let Some((sub_archive, archive_offset)) = - try_extract_macho_fat_archive(&self.sess, &*archive_map)? - { - (sub_archive, Some(archive_offset)) - } else { - (&*archive_map, None) - } - } else { - (&*archive_map, None) - }; - - let archive = ArchiveFile::parse(&*archive_bytes) + let archive_map = unsafe { Mmap::map(File::open(&archive_path)?)? }; + let archive = ArchiveFile::parse(&*archive_map) .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; let archive_index = self.src_archives.len(); @@ -190,13 +196,9 @@ impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> { let file_name = String::from_utf8(entry.name().to_vec()) .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; if !skip(&file_name) { - let mut range = entry.file_range(); - if let Some(offset) = offset { - range.0 += offset; - } self.entries.push(( file_name.into_bytes(), - ArchiveEntry::FromArchive { archive_index, file_range: range }, + ArchiveEntry::FromArchive { archive_index, file_range: entry.file_range() }, )); } } From 2cf101c3e7d5fffab8f72b1e04224bc3bc2d9e02 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 27 Jan 2023 11:46:27 +0000 Subject: [PATCH 412/500] Revert "Remove macOS fat archive support from LlvmArchiveBuilder" This reverts commit 047c7cc60c05e2cf182c6f578581cf2a67b1d0ff. --- compiler/rustc_codegen_llvm/src/back/archive.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/back/archive.rs b/compiler/rustc_codegen_llvm/src/back/archive.rs index 426f57c060800..b00676b7c592b 100644 --- a/compiler/rustc_codegen_llvm/src/back/archive.rs +++ b/compiler/rustc_codegen_llvm/src/back/archive.rs @@ -15,8 +15,8 @@ use crate::errors::{ use crate::llvm::archive_ro::{ArchiveRO, Child}; use crate::llvm::{self, ArchiveKind, LLVMMachineType, LLVMRustCOFFShortExport}; use rustc_codegen_ssa::back::archive::{ - get_native_object_symbols, ArArchiveBuilder, ArchiveBuildFailure, ArchiveBuilder, - ArchiveBuilderBuilder, UnknownArchiveKind, + get_native_object_symbols, try_extract_macho_fat_archive, ArArchiveBuilder, + ArchiveBuildFailure, ArchiveBuilder, ArchiveBuilderBuilder, UnknownArchiveKind, }; use rustc_session::cstore::DllImport; @@ -66,7 +66,13 @@ impl<'a> ArchiveBuilder<'a> for LlvmArchiveBuilder<'a> { archive: &Path, skip: Box bool + 'static>, ) -> io::Result<()> { - let archive_ro = match ArchiveRO::open(archive) { + let mut archive = archive.to_path_buf(); + if self.sess.target.llvm_target.contains("-apple-macosx") { + if let Some(new_archive) = try_extract_macho_fat_archive(&self.sess, &archive)? { + archive = new_archive + } + } + let archive_ro = match ArchiveRO::open(&archive) { Ok(ar) => ar, Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)), }; @@ -74,7 +80,7 @@ impl<'a> ArchiveBuilder<'a> for LlvmArchiveBuilder<'a> { return Ok(()); } self.additions.push(Addition::Archive { - path: archive.to_path_buf(), + path: archive, archive: archive_ro, skip: Box::new(skip), }); From de363d54c40a378717881240e719f5f7223ba376 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 27 Jan 2023 11:48:36 +0000 Subject: [PATCH 413/500] Revert back to LlvmArchiveBuilder on all platforms ArArchiveBuilder doesn't support reading thin archives, causing a regression. --- compiler/rustc_codegen_llvm/src/back/archive.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_llvm/src/back/archive.rs b/compiler/rustc_codegen_llvm/src/back/archive.rs index b00676b7c592b..58ca87524deb6 100644 --- a/compiler/rustc_codegen_llvm/src/back/archive.rs +++ b/compiler/rustc_codegen_llvm/src/back/archive.rs @@ -108,7 +108,9 @@ pub struct LlvmArchiveBuilderBuilder; impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder { fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box + 'a> { - if sess.target.arch == "wasm32" || sess.target.arch == "wasm64" { + // FIXME use ArArchiveBuilder on most targets again once reading thin archives is + // implemented + if true || sess.target.arch == "wasm32" || sess.target.arch == "wasm64" { Box::new(LlvmArchiveBuilder { sess, additions: Vec::new() }) } else { Box::new(ArArchiveBuilder::new(sess, get_llvm_object_symbols)) From e5995e61687673dca684914b774d1456160f1891 Mon Sep 17 00:00:00 2001 From: Michael Woerister Date: Fri, 27 Jan 2023 15:29:04 +0000 Subject: [PATCH 414/500] Don't merge vtables when full debuginfo is enabled. --- compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs | 5 +++++ tests/codegen/debug-vtable.rs | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index b6eb5ee183fa3..f73bbf3d22bd7 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -1499,6 +1499,11 @@ pub fn create_vtable_di_node<'ll, 'tcx>( return; } + // When full debuginfo is enabled, we want to try and prevent vtables from being + // merged. Otherwise debuggers will have a hard time mapping from dyn pointer + // to concrete type. + llvm::SetUnnamedAddress(vtable, llvm::UnnamedAddr::No); + let vtable_name = compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::GlobalVariable); let vtable_type_di_node = build_vtable_type_di_node(cx, ty, poly_trait_ref); diff --git a/tests/codegen/debug-vtable.rs b/tests/codegen/debug-vtable.rs index bdd312878ec88..d82b737de0b41 100644 --- a/tests/codegen/debug-vtable.rs +++ b/tests/codegen/debug-vtable.rs @@ -9,6 +9,14 @@ // compile-flags: -Cdebuginfo=2 -Copt-level=0 -Csymbol-mangling-version=v0 // ignore-tidy-linelength +// Make sure that vtables don't have the unnamed_addr attribute when debuginfo is enabled. +// This helps debuggers more reliably map from dyn pointer to concrete type. +// CHECK: @vtable.0 = private constant <{ +// CHECK: @vtable.1 = private constant <{ +// CHECK: @vtable.2 = private constant <{ +// CHECK: @vtable.3 = private constant <{ +// CHECK: @vtable.4 = private constant <{ + // NONMSVC: ![[USIZE:[0-9]+]] = !DIBasicType(name: "usize" // MSVC: ![[USIZE:[0-9]+]] = !DIDerivedType(tag: DW_TAG_typedef, name: "usize" // NONMSVC: ![[PTR:[0-9]+]] = !DIDerivedType(tag: DW_TAG_pointer_type, name: "*const ()" From 5bfd90efd121cace34bccdf6fe47578b2202bdf9 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 27 Jan 2023 17:46:18 +0000 Subject: [PATCH 415/500] Use now solver in evaluate_obligation --- .../src/traits/query/evaluate_obligation.rs | 43 ++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs index 09b58894d3040..f183248f2d08b 100644 --- a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs +++ b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs @@ -1,7 +1,9 @@ use rustc_middle::ty; +use rustc_session::config::TraitSolver; use crate::infer::canonical::OriginalQueryValues; use crate::infer::InferCtxt; +use crate::solve::{Certainty, Goal, InferCtxtEvalExt, MaybeCause}; use crate::traits::{EvaluationResult, OverflowError, PredicateObligation, SelectionContext}; pub trait InferCtxtExt<'tcx> { @@ -77,12 +79,38 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { _ => obligation.param_env.without_const(), }; - let c_pred = self - .canonicalize_query_keep_static(param_env.and(obligation.predicate), &mut _orig_values); - // Run canonical query. If overflow occurs, rerun from scratch but this time - // in standard trait query mode so that overflow is handled appropriately - // within `SelectionContext`. - self.tcx.at(obligation.cause.span()).evaluate_obligation(c_pred) + if self.tcx.sess.opts.unstable_opts.trait_solver != TraitSolver::Next { + let c_pred = self.canonicalize_query_keep_static( + param_env.and(obligation.predicate), + &mut _orig_values, + ); + self.tcx.at(obligation.cause.span()).evaluate_obligation(c_pred) + } else { + self.probe(|snapshot| { + if let Ok((_, certainty)) = + self.evaluate_root_goal(Goal::new(self.tcx, param_env, obligation.predicate)) + { + match certainty { + Certainty::Yes => { + if self.opaque_types_added_in_snapshot(snapshot) { + Ok(EvaluationResult::EvaluatedToOkModuloOpaqueTypes) + } else if self.region_constraints_added_in_snapshot(snapshot).is_some() + { + Ok(EvaluationResult::EvaluatedToOkModuloRegions) + } else { + Ok(EvaluationResult::EvaluatedToOk) + } + } + Certainty::Maybe(MaybeCause::Ambiguity) => { + Ok(EvaluationResult::EvaluatedToAmbig) + } + Certainty::Maybe(MaybeCause::Overflow) => Err(OverflowError::Canonical), + } + } else { + Ok(EvaluationResult::EvaluatedToErr) + } + }) + } } // Helper function that canonicalizes and runs the query. If an @@ -92,6 +120,9 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { &self, obligation: &PredicateObligation<'tcx>, ) -> EvaluationResult { + // Run canonical query. If overflow occurs, rerun from scratch but this time + // in standard trait query mode so that overflow is handled appropriately + // within `SelectionContext`. match self.evaluate_obligation(obligation) { Ok(result) => result, Err(OverflowError::Canonical) => { From 8ba0cd6c9ea44d17f38c5862e3c952a54db2a256 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 7 Jan 2023 21:10:38 +0000 Subject: [PATCH 416/500] Make tests unit. --- .../const_prop/ref_deref.main.ConstProp.diff | 9 +++-- .../ref_deref.main.PromoteTemps.diff | 30 ----------------- tests/mir-opt/const_prop/ref_deref.rs | 3 +- .../ref_deref_project.main.ConstProp.diff | 4 +-- .../ref_deref_project.main.PromoteTemps.diff | 30 ----------------- tests/mir-opt/const_prop/ref_deref_project.rs | 3 +- .../slice_len.main.ConstProp.32bit.diff | 6 ++-- .../slice_len.main.ConstProp.64bit.diff | 6 ++-- tests/mir-opt/const_prop/slice_len.rs | 3 +- .../const_prop_miscompile.bar.ConstProp.diff | 33 +++++++++++-------- .../const_prop_miscompile.foo.ConstProp.diff | 1 + tests/mir-opt/const_prop_miscompile.rs | 1 + 12 files changed, 37 insertions(+), 92 deletions(-) delete mode 100644 tests/mir-opt/const_prop/ref_deref.main.PromoteTemps.diff delete mode 100644 tests/mir-opt/const_prop/ref_deref_project.main.PromoteTemps.diff diff --git a/tests/mir-opt/const_prop/ref_deref.main.ConstProp.diff b/tests/mir-opt/const_prop/ref_deref.main.ConstProp.diff index 8a73f0390e122..924a267f3d8ff 100644 --- a/tests/mir-opt/const_prop/ref_deref.main.ConstProp.diff +++ b/tests/mir-opt/const_prop/ref_deref.main.ConstProp.diff @@ -13,14 +13,13 @@ StorageLive(_2); // scope 0 at $DIR/ref_deref.rs:+1:6: +1:10 _4 = const _; // scope 0 at $DIR/ref_deref.rs:+1:6: +1:10 // mir::Constant - // + span: $DIR/ref_deref.rs:6:6: 6:10 + // + span: $DIR/ref_deref.rs:5:6: 5:10 // + literal: Const { ty: &i32, val: Unevaluated(main, [], Some(promoted[0])) } - _2 = _4; // scope 0 at $DIR/ref_deref.rs:+1:6: +1:10 -- _1 = (*_2); // scope 0 at $DIR/ref_deref.rs:+1:5: +1:10 -+ _1 = const 4_i32; // scope 0 at $DIR/ref_deref.rs:+1:5: +1:10 + _2 = &(*_4); // scope 0 at $DIR/ref_deref.rs:+1:6: +1:10 + _1 = (*_2); // scope 0 at $DIR/ref_deref.rs:+1:5: +1:10 StorageDead(_2); // scope 0 at $DIR/ref_deref.rs:+1:10: +1:11 StorageDead(_1); // scope 0 at $DIR/ref_deref.rs:+1:10: +1:11 - nop; // scope 0 at $DIR/ref_deref.rs:+0:11: +2:2 + _0 = const (); // scope 0 at $DIR/ref_deref.rs:+0:11: +2:2 return; // scope 0 at $DIR/ref_deref.rs:+2:2: +2:2 } } diff --git a/tests/mir-opt/const_prop/ref_deref.main.PromoteTemps.diff b/tests/mir-opt/const_prop/ref_deref.main.PromoteTemps.diff deleted file mode 100644 index 015ec4d078c10..0000000000000 --- a/tests/mir-opt/const_prop/ref_deref.main.PromoteTemps.diff +++ /dev/null @@ -1,30 +0,0 @@ -- // MIR for `main` before PromoteTemps -+ // MIR for `main` after PromoteTemps - - fn main() -> () { - let mut _0: (); // return place in scope 0 at $DIR/ref_deref.rs:+0:11: +0:11 - let _1: i32; // in scope 0 at $DIR/ref_deref.rs:+1:5: +1:10 - let mut _2: &i32; // in scope 0 at $DIR/ref_deref.rs:+1:6: +1:10 - let _3: i32; // in scope 0 at $DIR/ref_deref.rs:+1:8: +1:9 -+ let mut _4: &i32; // in scope 0 at $DIR/ref_deref.rs:+1:6: +1:10 - - bb0: { - StorageLive(_1); // scope 0 at $DIR/ref_deref.rs:+1:5: +1:10 - StorageLive(_2); // scope 0 at $DIR/ref_deref.rs:+1:6: +1:10 -- StorageLive(_3); // scope 0 at $DIR/ref_deref.rs:+1:8: +1:9 -- _3 = const 4_i32; // scope 0 at $DIR/ref_deref.rs:+1:8: +1:9 -- _2 = &_3; // scope 0 at $DIR/ref_deref.rs:+1:6: +1:10 -+ _4 = const _; // scope 0 at $DIR/ref_deref.rs:+1:6: +1:10 -+ // mir::Constant -+ // + span: $DIR/ref_deref.rs:6:6: 6:10 -+ // + literal: Const { ty: &i32, val: Unevaluated(main, [], Some(promoted[0])) } -+ _2 = &(*_4); // scope 0 at $DIR/ref_deref.rs:+1:6: +1:10 - _1 = (*_2); // scope 0 at $DIR/ref_deref.rs:+1:5: +1:10 -- StorageDead(_3); // scope 0 at $DIR/ref_deref.rs:+1:10: +1:11 - StorageDead(_2); // scope 0 at $DIR/ref_deref.rs:+1:10: +1:11 - StorageDead(_1); // scope 0 at $DIR/ref_deref.rs:+1:10: +1:11 - _0 = const (); // scope 0 at $DIR/ref_deref.rs:+0:11: +2:2 - return; // scope 0 at $DIR/ref_deref.rs:+2:2: +2:2 - } - } - diff --git a/tests/mir-opt/const_prop/ref_deref.rs b/tests/mir-opt/const_prop/ref_deref.rs index d2549c8b6aa5a..76e56916af09a 100644 --- a/tests/mir-opt/const_prop/ref_deref.rs +++ b/tests/mir-opt/const_prop/ref_deref.rs @@ -1,5 +1,4 @@ -// compile-flags: -Zmir-enable-passes=-SimplifyLocals-before-const-prop -// EMIT_MIR ref_deref.main.PromoteTemps.diff +// unit-test: ConstProp // EMIT_MIR ref_deref.main.ConstProp.diff fn main() { diff --git a/tests/mir-opt/const_prop/ref_deref_project.main.ConstProp.diff b/tests/mir-opt/const_prop/ref_deref_project.main.ConstProp.diff index ec3d90433159d..59095b4483713 100644 --- a/tests/mir-opt/const_prop/ref_deref_project.main.ConstProp.diff +++ b/tests/mir-opt/const_prop/ref_deref_project.main.ConstProp.diff @@ -13,13 +13,13 @@ StorageLive(_2); // scope 0 at $DIR/ref_deref_project.rs:+1:6: +1:17 _4 = const _; // scope 0 at $DIR/ref_deref_project.rs:+1:6: +1:17 // mir::Constant - // + span: $DIR/ref_deref_project.rs:6:6: 6:17 + // + span: $DIR/ref_deref_project.rs:5:6: 5:17 // + literal: Const { ty: &(i32, i32), val: Unevaluated(main, [], Some(promoted[0])) } _2 = &((*_4).1: i32); // scope 0 at $DIR/ref_deref_project.rs:+1:6: +1:17 _1 = (*_2); // scope 0 at $DIR/ref_deref_project.rs:+1:5: +1:17 StorageDead(_2); // scope 0 at $DIR/ref_deref_project.rs:+1:17: +1:18 StorageDead(_1); // scope 0 at $DIR/ref_deref_project.rs:+1:17: +1:18 - nop; // scope 0 at $DIR/ref_deref_project.rs:+0:11: +2:2 + _0 = const (); // scope 0 at $DIR/ref_deref_project.rs:+0:11: +2:2 return; // scope 0 at $DIR/ref_deref_project.rs:+2:2: +2:2 } } diff --git a/tests/mir-opt/const_prop/ref_deref_project.main.PromoteTemps.diff b/tests/mir-opt/const_prop/ref_deref_project.main.PromoteTemps.diff deleted file mode 100644 index cd0616e65baf8..0000000000000 --- a/tests/mir-opt/const_prop/ref_deref_project.main.PromoteTemps.diff +++ /dev/null @@ -1,30 +0,0 @@ -- // MIR for `main` before PromoteTemps -+ // MIR for `main` after PromoteTemps - - fn main() -> () { - let mut _0: (); // return place in scope 0 at $DIR/ref_deref_project.rs:+0:11: +0:11 - let _1: i32; // in scope 0 at $DIR/ref_deref_project.rs:+1:5: +1:17 - let mut _2: &i32; // in scope 0 at $DIR/ref_deref_project.rs:+1:6: +1:17 - let _3: (i32, i32); // in scope 0 at $DIR/ref_deref_project.rs:+1:8: +1:14 -+ let mut _4: &(i32, i32); // in scope 0 at $DIR/ref_deref_project.rs:+1:6: +1:17 - - bb0: { - StorageLive(_1); // scope 0 at $DIR/ref_deref_project.rs:+1:5: +1:17 - StorageLive(_2); // scope 0 at $DIR/ref_deref_project.rs:+1:6: +1:17 -- StorageLive(_3); // scope 0 at $DIR/ref_deref_project.rs:+1:8: +1:14 -- _3 = (const 4_i32, const 5_i32); // scope 0 at $DIR/ref_deref_project.rs:+1:8: +1:14 -- _2 = &(_3.1: i32); // scope 0 at $DIR/ref_deref_project.rs:+1:6: +1:17 -+ _4 = const _; // scope 0 at $DIR/ref_deref_project.rs:+1:6: +1:17 -+ // mir::Constant -+ // + span: $DIR/ref_deref_project.rs:6:6: 6:17 -+ // + literal: Const { ty: &(i32, i32), val: Unevaluated(main, [], Some(promoted[0])) } -+ _2 = &((*_4).1: i32); // scope 0 at $DIR/ref_deref_project.rs:+1:6: +1:17 - _1 = (*_2); // scope 0 at $DIR/ref_deref_project.rs:+1:5: +1:17 -- StorageDead(_3); // scope 0 at $DIR/ref_deref_project.rs:+1:17: +1:18 - StorageDead(_2); // scope 0 at $DIR/ref_deref_project.rs:+1:17: +1:18 - StorageDead(_1); // scope 0 at $DIR/ref_deref_project.rs:+1:17: +1:18 - _0 = const (); // scope 0 at $DIR/ref_deref_project.rs:+0:11: +2:2 - return; // scope 0 at $DIR/ref_deref_project.rs:+2:2: +2:2 - } - } - diff --git a/tests/mir-opt/const_prop/ref_deref_project.rs b/tests/mir-opt/const_prop/ref_deref_project.rs index 2fdd4e1531901..04fc7f8daa124 100644 --- a/tests/mir-opt/const_prop/ref_deref_project.rs +++ b/tests/mir-opt/const_prop/ref_deref_project.rs @@ -1,5 +1,4 @@ -// compile-flags: -Zmir-enable-passes=-SimplifyLocals-before-const-prop -// EMIT_MIR ref_deref_project.main.PromoteTemps.diff +// unit-test: ConstProp // EMIT_MIR ref_deref_project.main.ConstProp.diff fn main() { diff --git a/tests/mir-opt/const_prop/slice_len.main.ConstProp.32bit.diff b/tests/mir-opt/const_prop/slice_len.main.ConstProp.32bit.diff index 9017fd18e4875..b99b83b0cba85 100644 --- a/tests/mir-opt/const_prop/slice_len.main.ConstProp.32bit.diff +++ b/tests/mir-opt/const_prop/slice_len.main.ConstProp.32bit.diff @@ -20,7 +20,7 @@ StorageLive(_4); // scope 0 at $DIR/slice_len.rs:+1:6: +1:19 _9 = const _; // scope 0 at $DIR/slice_len.rs:+1:6: +1:19 // mir::Constant - // + span: $DIR/slice_len.rs:6:6: 6:19 + // + span: $DIR/slice_len.rs:7:6: 7:19 // + literal: Const { ty: &[u32; 3], val: Unevaluated(main, [], Some(promoted[0])) } _4 = _9; // scope 0 at $DIR/slice_len.rs:+1:6: +1:19 _3 = _4; // scope 0 at $DIR/slice_len.rs:+1:6: +1:19 @@ -33,7 +33,7 @@ - assert(move _8, "index out of bounds: the length is {} but the index is {}", move _7, _6) -> bb1; // scope 0 at $DIR/slice_len.rs:+1:5: +1:33 + _7 = const 3_usize; // scope 0 at $DIR/slice_len.rs:+1:5: +1:33 + _8 = const true; // scope 0 at $DIR/slice_len.rs:+1:5: +1:33 -+ assert(const true, "index out of bounds: the length is {} but the index is {}", const 3_usize, const 1_usize) -> bb1; // scope 0 at $DIR/slice_len.rs:+1:5: +1:33 ++ assert(const true, "index out of bounds: the length is {} but the index is {}", move _7, _6) -> bb1; // scope 0 at $DIR/slice_len.rs:+1:5: +1:33 } bb1: { @@ -43,7 +43,7 @@ StorageDead(_4); // scope 0 at $DIR/slice_len.rs:+1:33: +1:34 StorageDead(_2); // scope 0 at $DIR/slice_len.rs:+1:33: +1:34 StorageDead(_1); // scope 0 at $DIR/slice_len.rs:+1:33: +1:34 - nop; // scope 0 at $DIR/slice_len.rs:+0:11: +2:2 + _0 = const (); // scope 0 at $DIR/slice_len.rs:+0:11: +2:2 return; // scope 0 at $DIR/slice_len.rs:+2:2: +2:2 } } diff --git a/tests/mir-opt/const_prop/slice_len.main.ConstProp.64bit.diff b/tests/mir-opt/const_prop/slice_len.main.ConstProp.64bit.diff index 9017fd18e4875..b99b83b0cba85 100644 --- a/tests/mir-opt/const_prop/slice_len.main.ConstProp.64bit.diff +++ b/tests/mir-opt/const_prop/slice_len.main.ConstProp.64bit.diff @@ -20,7 +20,7 @@ StorageLive(_4); // scope 0 at $DIR/slice_len.rs:+1:6: +1:19 _9 = const _; // scope 0 at $DIR/slice_len.rs:+1:6: +1:19 // mir::Constant - // + span: $DIR/slice_len.rs:6:6: 6:19 + // + span: $DIR/slice_len.rs:7:6: 7:19 // + literal: Const { ty: &[u32; 3], val: Unevaluated(main, [], Some(promoted[0])) } _4 = _9; // scope 0 at $DIR/slice_len.rs:+1:6: +1:19 _3 = _4; // scope 0 at $DIR/slice_len.rs:+1:6: +1:19 @@ -33,7 +33,7 @@ - assert(move _8, "index out of bounds: the length is {} but the index is {}", move _7, _6) -> bb1; // scope 0 at $DIR/slice_len.rs:+1:5: +1:33 + _7 = const 3_usize; // scope 0 at $DIR/slice_len.rs:+1:5: +1:33 + _8 = const true; // scope 0 at $DIR/slice_len.rs:+1:5: +1:33 -+ assert(const true, "index out of bounds: the length is {} but the index is {}", const 3_usize, const 1_usize) -> bb1; // scope 0 at $DIR/slice_len.rs:+1:5: +1:33 ++ assert(const true, "index out of bounds: the length is {} but the index is {}", move _7, _6) -> bb1; // scope 0 at $DIR/slice_len.rs:+1:5: +1:33 } bb1: { @@ -43,7 +43,7 @@ StorageDead(_4); // scope 0 at $DIR/slice_len.rs:+1:33: +1:34 StorageDead(_2); // scope 0 at $DIR/slice_len.rs:+1:33: +1:34 StorageDead(_1); // scope 0 at $DIR/slice_len.rs:+1:33: +1:34 - nop; // scope 0 at $DIR/slice_len.rs:+0:11: +2:2 + _0 = const (); // scope 0 at $DIR/slice_len.rs:+0:11: +2:2 return; // scope 0 at $DIR/slice_len.rs:+2:2: +2:2 } } diff --git a/tests/mir-opt/const_prop/slice_len.rs b/tests/mir-opt/const_prop/slice_len.rs index eaaf34b960eb6..8183def0c63db 100644 --- a/tests/mir-opt/const_prop/slice_len.rs +++ b/tests/mir-opt/const_prop/slice_len.rs @@ -1,4 +1,5 @@ -// compile-flags: -Zmir-enable-passes=-SimplifyLocals-before-const-prop +// unit-test: ConstProp +// compile-flags: -Zmir-enable-passes=+InstCombine // EMIT_MIR_FOR_EACH_BIT_WIDTH // EMIT_MIR slice_len.main.ConstProp.diff diff --git a/tests/mir-opt/const_prop_miscompile.bar.ConstProp.diff b/tests/mir-opt/const_prop_miscompile.bar.ConstProp.diff index ea9fec0aa15d1..b6b542fb79436 100644 --- a/tests/mir-opt/const_prop_miscompile.bar.ConstProp.diff +++ b/tests/mir-opt/const_prop_miscompile.bar.ConstProp.diff @@ -4,15 +4,16 @@ fn bar() -> () { let mut _0: (); // return place in scope 0 at $DIR/const_prop_miscompile.rs:+0:10: +0:10 let mut _1: (i32,); // in scope 0 at $DIR/const_prop_miscompile.rs:+1:9: +1:14 - let mut _2: *mut i32; // in scope 0 at $DIR/const_prop_miscompile.rs:+3:10: +3:22 - let mut _4: i32; // in scope 0 at $DIR/const_prop_miscompile.rs:+5:13: +5:20 + let _2: (); // in scope 0 at $DIR/const_prop_miscompile.rs:+2:5: +4:6 + let mut _3: *mut i32; // in scope 0 at $DIR/const_prop_miscompile.rs:+3:10: +3:22 + let mut _5: i32; // in scope 0 at $DIR/const_prop_miscompile.rs:+5:13: +5:20 scope 1 { debug v => _1; // in scope 1 at $DIR/const_prop_miscompile.rs:+1:9: +1:14 - let _3: bool; // in scope 1 at $DIR/const_prop_miscompile.rs:+5:9: +5:10 + let _4: bool; // in scope 1 at $DIR/const_prop_miscompile.rs:+5:9: +5:10 scope 2 { } scope 3 { - debug y => _3; // in scope 3 at $DIR/const_prop_miscompile.rs:+5:9: +5:10 + debug y => _4; // in scope 3 at $DIR/const_prop_miscompile.rs:+5:9: +5:10 } } @@ -20,16 +21,20 @@ StorageLive(_1); // scope 0 at $DIR/const_prop_miscompile.rs:+1:9: +1:14 Deinit(_1); // scope 0 at $DIR/const_prop_miscompile.rs:+1:17: +1:21 (_1.0: i32) = const 1_i32; // scope 0 at $DIR/const_prop_miscompile.rs:+1:17: +1:21 - StorageLive(_2); // scope 2 at $DIR/const_prop_miscompile.rs:+3:10: +3:22 - _2 = &raw mut (_1.0: i32); // scope 2 at $DIR/const_prop_miscompile.rs:+3:10: +3:22 - (*_2) = const 5_i32; // scope 2 at $DIR/const_prop_miscompile.rs:+3:9: +3:26 - StorageDead(_2); // scope 2 at $DIR/const_prop_miscompile.rs:+3:26: +3:27 - StorageLive(_3); // scope 1 at $DIR/const_prop_miscompile.rs:+5:9: +5:10 - StorageLive(_4); // scope 1 at $DIR/const_prop_miscompile.rs:+5:13: +5:20 - _4 = (_1.0: i32); // scope 1 at $DIR/const_prop_miscompile.rs:+5:15: +5:18 - _3 = Eq(move _4, const 5_i32); // scope 1 at $DIR/const_prop_miscompile.rs:+5:13: +5:25 - StorageDead(_4); // scope 1 at $DIR/const_prop_miscompile.rs:+5:24: +5:25 - StorageDead(_3); // scope 1 at $DIR/const_prop_miscompile.rs:+6:1: +6:2 + StorageLive(_2); // scope 1 at $DIR/const_prop_miscompile.rs:+2:5: +4:6 + StorageLive(_3); // scope 2 at $DIR/const_prop_miscompile.rs:+3:10: +3:22 + _3 = &raw mut (_1.0: i32); // scope 2 at $DIR/const_prop_miscompile.rs:+3:10: +3:22 + (*_3) = const 5_i32; // scope 2 at $DIR/const_prop_miscompile.rs:+3:9: +3:26 + StorageDead(_3); // scope 2 at $DIR/const_prop_miscompile.rs:+3:26: +3:27 + _2 = const (); // scope 2 at $DIR/const_prop_miscompile.rs:+2:5: +4:6 + StorageDead(_2); // scope 1 at $DIR/const_prop_miscompile.rs:+4:5: +4:6 + StorageLive(_4); // scope 1 at $DIR/const_prop_miscompile.rs:+5:9: +5:10 + StorageLive(_5); // scope 1 at $DIR/const_prop_miscompile.rs:+5:13: +5:20 + _5 = (_1.0: i32); // scope 1 at $DIR/const_prop_miscompile.rs:+5:15: +5:18 + _4 = Eq(move _5, const 5_i32); // scope 1 at $DIR/const_prop_miscompile.rs:+5:13: +5:25 + StorageDead(_5); // scope 1 at $DIR/const_prop_miscompile.rs:+5:24: +5:25 + _0 = const (); // scope 0 at $DIR/const_prop_miscompile.rs:+0:10: +6:2 + StorageDead(_4); // scope 1 at $DIR/const_prop_miscompile.rs:+6:1: +6:2 StorageDead(_1); // scope 0 at $DIR/const_prop_miscompile.rs:+6:1: +6:2 return; // scope 0 at $DIR/const_prop_miscompile.rs:+6:2: +6:2 } diff --git a/tests/mir-opt/const_prop_miscompile.foo.ConstProp.diff b/tests/mir-opt/const_prop_miscompile.foo.ConstProp.diff index 043f404741710..e43735fd9e145 100644 --- a/tests/mir-opt/const_prop_miscompile.foo.ConstProp.diff +++ b/tests/mir-opt/const_prop_miscompile.foo.ConstProp.diff @@ -27,6 +27,7 @@ _4 = (_1.0: i32); // scope 1 at $DIR/const_prop_miscompile.rs:+3:15: +3:18 _3 = Eq(move _4, const 5_i32); // scope 1 at $DIR/const_prop_miscompile.rs:+3:13: +3:25 StorageDead(_4); // scope 1 at $DIR/const_prop_miscompile.rs:+3:24: +3:25 + _0 = const (); // scope 0 at $DIR/const_prop_miscompile.rs:+0:10: +4:2 StorageDead(_3); // scope 1 at $DIR/const_prop_miscompile.rs:+4:1: +4:2 StorageDead(_1); // scope 0 at $DIR/const_prop_miscompile.rs:+4:1: +4:2 return; // scope 0 at $DIR/const_prop_miscompile.rs:+4:2: +4:2 diff --git a/tests/mir-opt/const_prop_miscompile.rs b/tests/mir-opt/const_prop_miscompile.rs index bc54556b34947..dbbe5ee08408f 100644 --- a/tests/mir-opt/const_prop_miscompile.rs +++ b/tests/mir-opt/const_prop_miscompile.rs @@ -1,3 +1,4 @@ +// unit-test: ConstProp #![feature(raw_ref_op)] // EMIT_MIR const_prop_miscompile.foo.ConstProp.diff From 8f7e441a547ee2d70d9401502171e944d6e5e797 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 4 Dec 2022 18:21:37 +0000 Subject: [PATCH 417/500] Add mir-opt test. --- tests/mir-opt/slice_filter.rs | 21 ++ ..._a-{closure#0}.DestinationPropagation.diff | 317 ++++++++++++++++++ ..._b-{closure#0}.DestinationPropagation.diff | 181 ++++++++++ 3 files changed, 519 insertions(+) create mode 100644 tests/mir-opt/slice_filter.rs create mode 100644 tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff create mode 100644 tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff diff --git a/tests/mir-opt/slice_filter.rs b/tests/mir-opt/slice_filter.rs new file mode 100644 index 0000000000000..83e6926d5328e --- /dev/null +++ b/tests/mir-opt/slice_filter.rs @@ -0,0 +1,21 @@ +fn main() { + let input = vec![]; + + // 1761ms on my machine + let _variant_a_result = variant_a(&input); + + // 656ms on my machine + let _variant_b_result = variant_b(&input); +} + + +// EMIT_MIR slice_filter.variant_a-{closure#0}.DestinationPropagation.diff +pub fn variant_a(input: &[(usize, usize, usize, usize)]) -> usize { + input.iter().filter(|(a, b, c, d)| a <= c && d <= b || c <= a && b <= d).count() +} + + +// EMIT_MIR slice_filter.variant_b-{closure#0}.DestinationPropagation.diff +pub fn variant_b(input: &[(usize, usize, usize, usize)]) -> usize { + input.iter().filter(|&&(a, b, c, d)| a <= c && d <= b || c <= a && b <= d).count() +} diff --git a/tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff b/tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff new file mode 100644 index 0000000000000..0f848ec07909b --- /dev/null +++ b/tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff @@ -0,0 +1,317 @@ +- // MIR for `variant_a::{closure#0}` before DestinationPropagation ++ // MIR for `variant_a::{closure#0}` after DestinationPropagation + + fn variant_a::{closure#0}(_1: &mut [closure@$DIR/slice_filter.rs:14:25: 14:39], _2: &&(usize, usize, usize, usize)) -> bool { + let mut _0: bool; // return place in scope 0 at $DIR/slice_filter.rs:+0:40: +0:40 + let _3: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + let _4: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + let _5: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + let _6: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + let mut _7: bool; // in scope 0 at $DIR/slice_filter.rs:+0:40: +0:56 + let mut _8: bool; // in scope 0 at $DIR/slice_filter.rs:+0:40: +0:46 + let mut _9: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:40: +0:41 + let mut _10: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:45: +0:46 + let _11: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:45: +0:46 + let mut _12: bool; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:56 + let mut _13: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:51 + let mut _14: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:55: +0:56 + let _15: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:55: +0:56 + let mut _16: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:76 + let mut _17: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:66 + let mut _18: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:61 + let mut _19: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:65: +0:66 + let _20: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:65: +0:66 + let mut _21: bool; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:76 + let mut _22: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:71 + let mut _23: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + let _24: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + let mut _25: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _26: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _27: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _28: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + scope 1 { + debug a => _3; // in scope 1 at $DIR/slice_filter.rs:+0:27: +0:28 + debug b => _4; // in scope 1 at $DIR/slice_filter.rs:+0:30: +0:31 + debug c => _5; // in scope 1 at $DIR/slice_filter.rs:+0:33: +0:34 + debug d => _6; // in scope 1 at $DIR/slice_filter.rs:+0:36: +0:37 + scope 2 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:14:40: 14:46 + debug self => _9; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _10; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _29: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _30: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _31: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _32: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + scope 3 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug self => _29; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug other => _30; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug self => _31; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug other => _32; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _33: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _34: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + } + } + scope 4 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:14:60: 14:66 + debug self => _18; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _19; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _35: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _36: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _37: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _38: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + scope 5 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug self => _35; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug other => _36; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug self => _37; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug other => _38; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _39: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _40: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + } + } + scope 6 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:14:50: 14:56 + debug self => _13; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _14; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _41: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _42: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _43: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _44: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + scope 7 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug self => _41; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug other => _42; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug self => _43; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug other => _44; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _45: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _46: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + } + } + scope 8 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:14:70: 14:76 + debug self => _22; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _23; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _47: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _48: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _49: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _50: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + scope 9 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug self => _47; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug other => _48; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug self => _49; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug other => _50; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _51: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _52: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + } + } + } + + bb0: { + StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + _25 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + _3 = &((*_25).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + _26 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + _4 = &((*_26).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + _27 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + _5 = &((*_27).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + _28 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + _6 = &((*_28).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 +- StorageLive(_7); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + StorageLive(_8); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:46 + StorageLive(_9); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:41 + _9 = &_3; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:41 + StorageLive(_10); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + _11 = _5; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + _10 = &_11; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 +- StorageLive(_29); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + _31 = deref_copy (*_9); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _29 = _31; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageLive(_30); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + _32 = deref_copy (*_10); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _30 = _32; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_33); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _33 = (*_29); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _33 = (*_31); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_34); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _34 = (*_30); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _34 = (*_32); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + _8 = Le(move _33, move _34); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_34); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_33); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_30); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_29); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + StorageDead(_10); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + StorageDead(_9); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + switchInt(move _8) -> [0: bb4, otherwise: bb5]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + } + + bb1: { + _0 = const true; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + goto -> bb3; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + } + + bb2: { +- StorageLive(_16); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + StorageLive(_17); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:66 + StorageLive(_18); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 + _18 = &_5; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 + StorageLive(_19); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + StorageLive(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + _20 = _3; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + _19 = &_20; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 +- StorageLive(_35); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + _37 = deref_copy (*_18); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _35 = _37; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageLive(_36); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + _38 = deref_copy (*_19); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _36 = _38; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_39); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _39 = (*_35); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _39 = (*_37); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_40); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _40 = (*_36); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _40 = (*_38); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + _17 = Le(move _39, move _40); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_40); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_39); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_36); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_35); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + StorageDead(_19); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + StorageDead(_18); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + switchInt(move _17) -> [0: bb6, otherwise: bb7]; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + } + + bb3: { +- StorageDead(_16); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageDead(_7); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_6); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_5); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_4); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_3); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + return; // scope 0 at $DIR/slice_filter.rs:+0:76: +0:76 + } + + bb4: { +- StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + goto -> bb2; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + } + + bb5: { +- StorageLive(_12); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:56 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:50: +0:56 + StorageLive(_13); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 + _13 = &_6; // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 + StorageLive(_14); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageLive(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + _15 = _4; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + _14 = &_15; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 +- StorageLive(_41); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + _43 = deref_copy (*_13); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _41 = _43; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageLive(_42); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + _44 = deref_copy (*_14); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _42 = _44; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_45); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _45 = (*_41); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _45 = (*_43); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_46); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _46 = (*_42); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _46 = (*_44); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + _12 = Le(move _45, move _46); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_46); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_45); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_42); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_41); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageDead(_14); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageDead(_13); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 +- _7 = move _12; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 +- StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 +- switchInt(move _7) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 ++ switchInt(move _12) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + } + + bb6: { +- _16 = const false; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 ++ _0 = const false; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + } + + bb7: { +- StorageLive(_21); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:76 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:70: +0:76 + StorageLive(_22); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 + _22 = &_4; // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 + StorageLive(_23); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageLive(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _24 = _6; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _23 = &_24; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageLive(_47); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + _49 = deref_copy (*_22); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _47 = _49; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageLive(_48); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + _50 = deref_copy (*_23); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _48 = _50; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_51); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _51 = (*_47); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _51 = (*_49); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_52); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _52 = (*_48); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _21 = Le(move _51, move _52); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _52 = (*_50); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _0 = Le(move _51, move _52); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_52); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_51); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_48); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_47); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_23); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_22); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- _16 = move _21; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + } + + bb8: { +- StorageDead(_21); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_17); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- _0 = move _16; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + goto -> bb3; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + } + } + diff --git a/tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff b/tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff new file mode 100644 index 0000000000000..a0c4b4f652c47 --- /dev/null +++ b/tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff @@ -0,0 +1,181 @@ +- // MIR for `variant_b::{closure#0}` before DestinationPropagation ++ // MIR for `variant_b::{closure#0}` after DestinationPropagation + + fn variant_b::{closure#0}(_1: &mut [closure@$DIR/slice_filter.rs:20:25: 20:41], _2: &&(usize, usize, usize, usize)) -> bool { + let mut _0: bool; // return place in scope 0 at $DIR/slice_filter.rs:+0:42: +0:42 + let _3: usize; // in scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 + let _4: usize; // in scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 + let _5: usize; // in scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 + let _6: usize; // in scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 + let mut _7: bool; // in scope 0 at $DIR/slice_filter.rs:+0:42: +0:58 + let mut _8: bool; // in scope 0 at $DIR/slice_filter.rs:+0:42: +0:48 + let mut _9: usize; // in scope 0 at $DIR/slice_filter.rs:+0:42: +0:43 + let mut _10: usize; // in scope 0 at $DIR/slice_filter.rs:+0:47: +0:48 + let mut _11: bool; // in scope 0 at $DIR/slice_filter.rs:+0:52: +0:58 + let mut _12: usize; // in scope 0 at $DIR/slice_filter.rs:+0:52: +0:53 + let mut _13: usize; // in scope 0 at $DIR/slice_filter.rs:+0:57: +0:58 + let mut _14: bool; // in scope 0 at $DIR/slice_filter.rs:+0:62: +0:78 + let mut _15: bool; // in scope 0 at $DIR/slice_filter.rs:+0:62: +0:68 + let mut _16: usize; // in scope 0 at $DIR/slice_filter.rs:+0:62: +0:63 + let mut _17: usize; // in scope 0 at $DIR/slice_filter.rs:+0:67: +0:68 + let mut _18: bool; // in scope 0 at $DIR/slice_filter.rs:+0:72: +0:78 + let mut _19: usize; // in scope 0 at $DIR/slice_filter.rs:+0:72: +0:73 + let mut _20: usize; // in scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 + let mut _21: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + let mut _22: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + let mut _23: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + let mut _24: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + scope 1 { +- debug a => _3; // in scope 1 at $DIR/slice_filter.rs:+0:29: +0:30 +- debug b => _4; // in scope 1 at $DIR/slice_filter.rs:+0:32: +0:33 +- debug c => _5; // in scope 1 at $DIR/slice_filter.rs:+0:35: +0:36 +- debug d => _6; // in scope 1 at $DIR/slice_filter.rs:+0:38: +0:39 ++ debug a => _17; // in scope 1 at $DIR/slice_filter.rs:+0:29: +0:30 ++ debug b => _19; // in scope 1 at $DIR/slice_filter.rs:+0:32: +0:33 ++ debug c => _16; // in scope 1 at $DIR/slice_filter.rs:+0:35: +0:36 ++ debug d => _20; // in scope 1 at $DIR/slice_filter.rs:+0:38: +0:39 + } + + bb0: { +- StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 ++ nop; // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 + _21 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 +- _3 = ((*_21).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 +- StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 ++ _17 = ((*_21).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 ++ nop; // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 + _22 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 +- _4 = ((*_22).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 +- StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 ++ _19 = ((*_22).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 ++ nop; // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 + _23 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 +- _5 = ((*_23).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 +- StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 ++ _16 = ((*_23).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 ++ nop; // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 + _24 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 +- _6 = ((*_24).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 +- StorageLive(_7); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 ++ _20 = ((*_24).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 + StorageLive(_8); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:48 + StorageLive(_9); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:43 +- _9 = _3; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:43 ++ _9 = _17; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:43 + StorageLive(_10); // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 +- _10 = _5; // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 ++ _10 = _16; // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 + _8 = Le(move _9, move _10); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:48 + StorageDead(_10); // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 + StorageDead(_9); // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 + switchInt(move _8) -> [0: bb4, otherwise: bb5]; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 + } + + bb1: { + _0 = const true; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + goto -> bb3; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + } + + bb2: { +- StorageLive(_14); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + StorageLive(_15); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:68 +- StorageLive(_16); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:63 +- _16 = _5; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:63 +- StorageLive(_17); // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 +- _17 = _3; // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:63 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:63 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 + _15 = Le(move _16, move _17); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:68 +- StorageDead(_17); // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 +- StorageDead(_16); // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 + switchInt(move _15) -> [0: bb6, otherwise: bb7]; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + } + + bb3: { +- StorageDead(_14); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_7); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_6); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_5); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_4); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_3); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 ++ nop; // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 ++ nop; // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 ++ nop; // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 ++ nop; // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 + return; // scope 0 at $DIR/slice_filter.rs:+0:78: +0:78 + } + + bb4: { +- StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + goto -> bb2; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 + } + + bb5: { +- StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:58 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:52: +0:58 + StorageLive(_12); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:53 +- _12 = _6; // scope 1 at $DIR/slice_filter.rs:+0:52: +0:53 ++ _12 = _20; // scope 1 at $DIR/slice_filter.rs:+0:52: +0:53 + StorageLive(_13); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 +- _13 = _4; // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 ++ _13 = _19; // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + _11 = Le(move _12, move _13); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:58 + StorageDead(_13); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 +- _7 = move _11; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 +- StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 +- switchInt(move _7) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 ++ switchInt(move _11) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + } + + bb6: { +- _14 = const false; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 ++ _0 = const false; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + } + + bb7: { +- StorageLive(_18); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 +- StorageLive(_19); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:73 +- _19 = _4; // scope 1 at $DIR/slice_filter.rs:+0:72: +0:73 +- StorageLive(_20); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- _20 = _6; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- _18 = Le(move _19, move _20); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 +- StorageDead(_20); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_19); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- _14 = move _18; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:72: +0:73 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:72: +0:73 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 ++ _0 = Le(move _19, move _20); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + } + + bb8: { +- StorageDead(_18); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 + StorageDead(_15); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- _0 = move _14; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 ++ nop; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + goto -> bb3; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + } + } + From 982726cdc4c291b88f1099f49e573a1a6de078ff Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Thu, 29 Dec 2022 19:15:00 +0000 Subject: [PATCH 418/500] Consider `CopyForDeref` for DestProp. --- compiler/rustc_mir_transform/src/dest_prop.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_mir_transform/src/dest_prop.rs b/compiler/rustc_mir_transform/src/dest_prop.rs index 08e296a837127..91428fd08648d 100644 --- a/compiler/rustc_mir_transform/src/dest_prop.rs +++ b/compiler/rustc_mir_transform/src/dest_prop.rs @@ -328,7 +328,8 @@ impl<'a, 'tcx> MutVisitor<'tcx> for Merger<'a, 'tcx> { match &statement.kind { StatementKind::Assign(box (dest, rvalue)) => { match rvalue { - Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) => { + Rvalue::CopyForDeref(place) + | Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) => { // These might've been turned into self-assignments by the replacement // (this includes the original statement we wanted to eliminate). if dest == place { @@ -754,7 +755,7 @@ impl<'tcx> Visitor<'tcx> for FindAssignments<'_, '_, 'tcx> { fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) { if let StatementKind::Assign(box ( lhs, - Rvalue::Use(Operand::Copy(rhs) | Operand::Move(rhs)), + Rvalue::CopyForDeref(rhs) | Rvalue::Use(Operand::Copy(rhs) | Operand::Move(rhs)), )) = &statement.kind { let Some((src, dest)) = places_to_candidate_pair(*lhs, *rhs, self.body) else { From c4fe96c3234a1e21b2d61fc3e6f28e6522ad7ab2 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Wed, 11 Jan 2023 16:30:35 +0000 Subject: [PATCH 419/500] Allow to remove unused definitions without renumbering locals. --- compiler/rustc_mir_transform/src/simplify.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_mir_transform/src/simplify.rs b/compiler/rustc_mir_transform/src/simplify.rs index 8f6abe7a912fe..09b980bab2942 100644 --- a/compiler/rustc_mir_transform/src/simplify.rs +++ b/compiler/rustc_mir_transform/src/simplify.rs @@ -404,6 +404,18 @@ impl<'tcx> MirPass<'tcx> for SimplifyLocals { } } +pub fn remove_unused_definitions<'tcx>(body: &mut Body<'tcx>) { + // First, we're going to get a count of *actual* uses for every `Local`. + let mut used_locals = UsedLocals::new(body); + + // Next, we're going to remove any `Local` with zero actual uses. When we remove those + // `Locals`, we're also going to subtract any uses of other `Locals` from the `used_locals` + // count. For example, if we removed `_2 = discriminant(_1)`, then we'll subtract one from + // `use_counts[_1]`. That in turn might make `_1` unused, so we loop until we hit a + // fixedpoint where there are no more unused locals. + remove_unused_definitions_helper(&mut used_locals, body); +} + pub fn simplify_locals<'tcx>(body: &mut Body<'tcx>, tcx: TyCtxt<'tcx>) { // First, we're going to get a count of *actual* uses for every `Local`. let mut used_locals = UsedLocals::new(body); @@ -413,7 +425,7 @@ pub fn simplify_locals<'tcx>(body: &mut Body<'tcx>, tcx: TyCtxt<'tcx>) { // count. For example, if we removed `_2 = discriminant(_1)`, then we'll subtract one from // `use_counts[_1]`. That in turn might make `_1` unused, so we loop until we hit a // fixedpoint where there are no more unused locals. - remove_unused_definitions(&mut used_locals, body); + remove_unused_definitions_helper(&mut used_locals, body); // Finally, we'll actually do the work of shrinking `body.local_decls` and remapping the `Local`s. let map = make_local_map(&mut body.local_decls, &used_locals); @@ -548,7 +560,7 @@ impl<'tcx> Visitor<'tcx> for UsedLocals { } /// Removes unused definitions. Updates the used locals to reflect the changes made. -fn remove_unused_definitions(used_locals: &mut UsedLocals, body: &mut Body<'_>) { +fn remove_unused_definitions_helper(used_locals: &mut UsedLocals, body: &mut Body<'_>) { // The use counts are updated as we remove the statements. A local might become unused // during the retain operation, leading to a temporary inconsistency (storage statements or // definitions referencing the local might remain). For correctness it is crucial that this From 6ed9f8f62ebe52f388f9098fb4c05791f588729b Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Thu, 12 Jan 2023 18:23:48 +0000 Subject: [PATCH 420/500] Implement SSA CopyProp pass. --- compiler/rustc_mir_transform/src/copy_prop.rs | 267 +++++++++++++ compiler/rustc_mir_transform/src/lib.rs | 2 + .../const_debuginfo.main.ConstDebugInfo.diff | 15 - .../bad_op_mod_by_zero.main.ConstProp.diff | 18 +- ...e_oob_for_slices.main.ConstProp.32bit.diff | 5 +- ...e_oob_for_slices.main.ConstProp.64bit.diff | 5 +- .../boolean_identities.test.ConstProp.diff | 12 +- .../mult_by_zero.test.ConstProp.diff | 5 +- ...ar_literal_propagation.main.ConstProp.diff | 8 +- ...herit_overflow.main.DataflowConstProp.diff | 10 - ...erflow.const_dividend.PreCodegen.after.mir | 2 +- ...verflow.const_divisor.PreCodegen.after.mir | 2 +- ...float_to_exponential_common.ConstProp.diff | 23 +- .../inline/dyn_trait.get_query.Inline.diff | 4 +- .../dyn_trait.try_execute_query.Inline.diff | 2 +- .../inline_any_operand.bar.Inline.after.mir | 2 +- .../inline/inline_generator.main.Inline.diff | 4 +- ...line_trait_method_2.test2.Inline.after.mir | 2 +- .../mir-opt/issue_101973.inner.ConstProp.diff | 24 +- ...76432.test.SimplifyComparisonIntegral.diff | 18 +- ...y_len_e2e.array_bound.PreCodegen.after.mir | 22 +- ...n_e2e.array_bound_mut.PreCodegen.after.mir | 42 +-- ..._option_map_e2e.ezmap.PreCodegen.after.mir | 2 +- .../simplify_match.main.ConstProp.diff | 8 +- tests/mir-opt/slice_filter.rs | 13 +- ...filter.variant_a-{closure#0}.CopyProp.diff | 283 ++++++++++++++ ..._a-{closure#0}.DestinationPropagation.diff | 350 +++++++----------- ...filter.variant_b-{closure#0}.CopyProp.diff | 139 +++++++ ..._b-{closure#0}.DestinationPropagation.diff | 154 ++------ .../try_identity_e2e.new.PreCodegen.after.mir | 6 +- .../try_identity_e2e.old.PreCodegen.after.mir | 2 +- ...le_storage.while_loop.PreCodegen.after.mir | 22 +- 32 files changed, 935 insertions(+), 538 deletions(-) create mode 100644 compiler/rustc_mir_transform/src/copy_prop.rs create mode 100644 tests/mir-opt/slice_filter.variant_a-{closure#0}.CopyProp.diff create mode 100644 tests/mir-opt/slice_filter.variant_b-{closure#0}.CopyProp.diff diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs new file mode 100644 index 0000000000000..e39e661d4a14a --- /dev/null +++ b/compiler/rustc_mir_transform/src/copy_prop.rs @@ -0,0 +1,267 @@ +use either::Either; +use rustc_index::bit_set::BitSet; +use rustc_index::vec::IndexVec; +use rustc_middle::middle::resolve_lifetime::Set1; +use rustc_middle::mir::visit::*; +use rustc_middle::mir::*; +use rustc_middle::ty::{ParamEnv, TyCtxt}; +use rustc_mir_dataflow::impls::borrowed_locals; + +use crate::MirPass; + +/// Unify locals that copy each other. +/// +/// We consider patterns of the form +/// _a = rvalue +/// _b = move? _a +/// _c = move? _a +/// _d = move? _c +/// where each of the locals is only assigned once. +/// +/// We want to replace all those locals by `_a`, either copied or moved. +pub struct CopyProp; + +impl<'tcx> MirPass<'tcx> for CopyProp { + fn is_enabled(&self, sess: &rustc_session::Session) -> bool { + sess.mir_opt_level() >= 4 + } + + #[instrument(level = "trace", skip(self, tcx, body))] + fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { + debug!(def_id = ?body.source.def_id()); + propagate_ssa(tcx, body); + } +} + +fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { + let param_env = tcx.param_env_reveal_all_normalized(body.source.def_id()); + let ssa = SsaLocals::new(tcx, param_env, body); + + let (copy_classes, fully_moved) = compute_copy_classes(&ssa, body); + debug!(?copy_classes); + + let mut storage_to_remove = BitSet::new_empty(fully_moved.domain_size()); + for (local, &head) in copy_classes.iter_enumerated() { + if local != head { + storage_to_remove.insert(head); + storage_to_remove.insert(local); + } + } + + let any_replacement = copy_classes.iter_enumerated().any(|(l, &h)| l != h); + + Replacer { tcx, copy_classes, fully_moved, storage_to_remove }.visit_body_preserves_cfg(body); + + if any_replacement { + crate::simplify::remove_unused_definitions(body); + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum LocationExtended { + Plain(Location), + Arg, +} + +#[derive(Debug)] +struct SsaLocals { + /// Assignments to each local. This defines whether the local is SSA. + assignments: IndexVec>, + /// We visit the body in reverse postorder, to ensure each local is assigned before it is used. + /// We remember the order in which we saw the assignments to compute the SSA values in a single + /// pass. + assignment_order: Vec, +} + +impl SsaLocals { + fn new<'tcx>(tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, body: &Body<'tcx>) -> SsaLocals { + let assignment_order = Vec::new(); + + let assignments = IndexVec::from_elem(Set1::Empty, &body.local_decls); + let mut this = SsaLocals { assignments, assignment_order }; + + let borrowed = borrowed_locals(body); + for (local, decl) in body.local_decls.iter_enumerated() { + if matches!(body.local_kind(local), LocalKind::Arg) { + this.assignments[local] = Set1::One(LocationExtended::Arg); + } + if borrowed.contains(local) && !decl.ty.is_freeze(tcx, param_env) { + this.assignments[local] = Set1::Many; + } + } + + for (bb, data) in traversal::reverse_postorder(body) { + this.visit_basic_block_data(bb, data); + } + + for var_debug_info in &body.var_debug_info { + this.visit_var_debug_info(var_debug_info); + } + + debug!(?this.assignments); + + this.assignment_order.retain(|&local| matches!(this.assignments[local], Set1::One(_))); + debug!(?this.assignment_order); + + this + } +} + +impl<'tcx> Visitor<'tcx> for SsaLocals { + fn visit_local(&mut self, local: Local, ctxt: PlaceContext, loc: Location) { + match ctxt { + PlaceContext::MutatingUse(MutatingUseContext::Store) => { + self.assignments[local].insert(LocationExtended::Plain(loc)); + self.assignment_order.push(local); + } + PlaceContext::MutatingUse(_) => self.assignments[local] = Set1::Many, + // Immutable borrows and AddressOf are taken into account in `SsaLocals::new` by + // removing non-freeze locals. + PlaceContext::NonMutatingUse(_) | PlaceContext::NonUse(_) => {} + } + } +} + +/// Compute the equivalence classes for locals, based on copy statements. +/// +/// The returned vector maps each local to the one it copies. In the following case: +/// _a = &mut _0 +/// _b = move? _a +/// _c = move? _a +/// _d = move? _c +/// We return the mapping +/// _a => _a // not a copy so, represented by itself +/// _b => _a +/// _c => _a +/// _d => _a // transitively through _c +/// +/// This function also returns whether all the `move?` in the pattern are `move` and not copies. +/// A local which is in the bitset can be replaced by `move _a`. Otherwise, it must be +/// replaced by `copy _a`, as we cannot move multiple times from `_a`. +/// +/// If an operand copies `_c`, it must happen before the assignment `_d = _c`, otherwise it is UB. +/// This means that replacing it by a copy of `_a` if ok, since this copy happens before `_c` is +/// moved, and therefore that `_d` is moved. +#[instrument(level = "trace", skip(ssa, body))] +fn compute_copy_classes( + ssa: &SsaLocals, + body: &Body<'_>, +) -> (IndexVec, BitSet) { + let mut copies = IndexVec::from_fn_n(|l| l, body.local_decls.len()); + let mut fully_moved = BitSet::new_filled(copies.len()); + + for &local in &ssa.assignment_order { + debug!(?local); + + if local == RETURN_PLACE { + // `_0` is special, we cannot rename it. + continue; + } + + // This is not SSA: mark that we don't know the value. + debug!(assignments = ?ssa.assignments[local]); + let Set1::One(LocationExtended::Plain(loc)) = ssa.assignments[local] else { continue }; + + // `loc` must point to a direct assignment to `local`. + let Either::Left(stmt) = body.stmt_at(loc) else { bug!() }; + let Some((_target, rvalue)) = stmt.kind.as_assign() else { bug!() }; + assert_eq!(_target.as_local(), Some(local)); + + let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) | Rvalue::CopyForDeref(place)) + = rvalue + else { continue }; + + let Some(rhs) = place.as_local() else { continue }; + let Set1::One(_) = ssa.assignments[rhs] else { continue }; + + // We visit in `assignment_order`, ie. reverse post-order, so `rhs` has been + // visited before `local`, and we just have to copy the representing local. + copies[local] = copies[rhs]; + + if let Rvalue::Use(Operand::Copy(_)) | Rvalue::CopyForDeref(_) = rvalue { + fully_moved.remove(rhs); + } + } + + debug!(?copies); + + // Invariant: `copies` must point to the head of an equivalence class. + #[cfg(debug_assertions)] + for &head in copies.iter() { + assert_eq!(copies[head], head); + } + + meet_copy_equivalence(&copies, &mut fully_moved); + + (copies, fully_moved) +} + +/// Make a property uniform on a copy equivalence class by removing elements. +fn meet_copy_equivalence(copies: &IndexVec, property: &mut BitSet) { + // Consolidate to have a local iff all its copies are. + // + // `copies` defines equivalence classes between locals. The `local`s that recursively + // move/copy the same local all have the same `head`. + for (local, &head) in copies.iter_enumerated() { + // If any copy does not have `property`, then the head is not. + if !property.contains(local) { + property.remove(head); + } + } + for (local, &head) in copies.iter_enumerated() { + // If any copy does not have `property`, then the head doesn't either, + // then no copy has `property`. + if !property.contains(head) { + property.remove(local); + } + } + + // Verify that we correctly computed equivalence classes. + #[cfg(debug_assertions)] + for (local, &head) in copies.iter_enumerated() { + assert_eq!(property.contains(local), property.contains(head)); + } +} + +/// Utility to help performing subtitution of `*pattern` by `target`. +struct Replacer<'tcx> { + tcx: TyCtxt<'tcx>, + fully_moved: BitSet, + storage_to_remove: BitSet, + copy_classes: IndexVec, +} + +impl<'tcx> MutVisitor<'tcx> for Replacer<'tcx> { + fn tcx(&self) -> TyCtxt<'tcx> { + self.tcx + } + + fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) { + *local = self.copy_classes[*local]; + } + + fn visit_operand(&mut self, operand: &mut Operand<'tcx>, loc: Location) { + if let Operand::Move(place) = *operand + && let Some(local) = place.as_local() + && !self.fully_moved.contains(local) + { + *operand = Operand::Copy(place); + } + self.super_operand(operand, loc); + } + + fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) { + if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind + && self.storage_to_remove.contains(l) + { + stmt.make_nop(); + } + if let StatementKind::Assign(box (ref place, _)) = stmt.kind + && let Some(l) = place.as_local() + && self.copy_classes[l] != l + { + stmt.make_nop(); + } + self.super_statement(stmt, loc); + } +} diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 4a598862d10f8..1330f1e26b8ed 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -54,6 +54,7 @@ mod const_debuginfo; mod const_goto; mod const_prop; mod const_prop_lint; +mod copy_prop; mod coverage; mod dataflow_const_prop; mod dead_store_elimination; @@ -556,6 +557,7 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { &instcombine::InstCombine, &separate_const_switch::SeparateConstSwitch, &simplify::SimplifyLocals::new("before-const-prop"), + ©_prop::CopyProp, // // FIXME(#70073): This pass is responsible for both optimization as well as some lints. &const_prop::ConstProp, diff --git a/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff b/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff index dd548adde7e5f..4405b55875ed9 100644 --- a/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff +++ b/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff @@ -56,25 +56,13 @@ } bb0: { - StorageLive(_1); // scope 0 at $DIR/const_debuginfo.rs:+1:9: +1:10 _1 = const 1_u8; // scope 0 at $DIR/const_debuginfo.rs:+1:13: +1:16 - StorageLive(_2); // scope 1 at $DIR/const_debuginfo.rs:+2:9: +2:10 _2 = const 2_u8; // scope 1 at $DIR/const_debuginfo.rs:+2:13: +2:16 - StorageLive(_3); // scope 2 at $DIR/const_debuginfo.rs:+3:9: +3:10 _3 = const 3_u8; // scope 2 at $DIR/const_debuginfo.rs:+3:13: +3:16 StorageLive(_4); // scope 3 at $DIR/const_debuginfo.rs:+4:9: +4:12 StorageLive(_5); // scope 3 at $DIR/const_debuginfo.rs:+4:15: +4:20 - StorageLive(_6); // scope 3 at $DIR/const_debuginfo.rs:+4:15: +4:16 - _6 = const 1_u8; // scope 3 at $DIR/const_debuginfo.rs:+4:15: +4:16 - StorageLive(_7); // scope 3 at $DIR/const_debuginfo.rs:+4:19: +4:20 - _7 = const 2_u8; // scope 3 at $DIR/const_debuginfo.rs:+4:19: +4:20 _5 = const 3_u8; // scope 3 at $DIR/const_debuginfo.rs:+4:15: +4:20 - StorageDead(_7); // scope 3 at $DIR/const_debuginfo.rs:+4:19: +4:20 - StorageDead(_6); // scope 3 at $DIR/const_debuginfo.rs:+4:19: +4:20 - StorageLive(_8); // scope 3 at $DIR/const_debuginfo.rs:+4:23: +4:24 - _8 = const 3_u8; // scope 3 at $DIR/const_debuginfo.rs:+4:23: +4:24 _4 = const 6_u8; // scope 3 at $DIR/const_debuginfo.rs:+4:15: +4:24 - StorageDead(_8); // scope 3 at $DIR/const_debuginfo.rs:+4:23: +4:24 StorageDead(_5); // scope 3 at $DIR/const_debuginfo.rs:+4:23: +4:24 StorageLive(_9); // scope 4 at $DIR/const_debuginfo.rs:+6:9: +6:10 _9 = const "hello, world!"; // scope 4 at $DIR/const_debuginfo.rs:+6:13: +6:28 @@ -117,9 +105,6 @@ StorageDead(_16); // scope 5 at $DIR/const_debuginfo.rs:+14:1: +14:2 StorageDead(_9); // scope 4 at $DIR/const_debuginfo.rs:+14:1: +14:2 StorageDead(_4); // scope 3 at $DIR/const_debuginfo.rs:+14:1: +14:2 - StorageDead(_3); // scope 2 at $DIR/const_debuginfo.rs:+14:1: +14:2 - StorageDead(_2); // scope 1 at $DIR/const_debuginfo.rs:+14:1: +14:2 - StorageDead(_1); // scope 0 at $DIR/const_debuginfo.rs:+14:1: +14:2 return; // scope 0 at $DIR/const_debuginfo.rs:+14:2: +14:2 } } diff --git a/tests/mir-opt/const_prop/bad_op_mod_by_zero.main.ConstProp.diff b/tests/mir-opt/const_prop/bad_op_mod_by_zero.main.ConstProp.diff index 8485703e39f2c..ae9ffd519a148 100644 --- a/tests/mir-opt/const_prop/bad_op_mod_by_zero.main.ConstProp.diff +++ b/tests/mir-opt/const_prop/bad_op_mod_by_zero.main.ConstProp.diff @@ -18,35 +18,27 @@ } bb0: { - StorageLive(_1); // scope 0 at $DIR/bad_op_mod_by_zero.rs:+1:9: +1:10 _1 = const 0_i32; // scope 0 at $DIR/bad_op_mod_by_zero.rs:+1:13: +1:14 StorageLive(_2); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:9: +2:11 - StorageLive(_3); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:18: +2:19 -- _3 = _1; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:18: +2:19 -- _4 = Eq(_3, const 0_i32); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 +- _4 = Eq(_1, const 0_i32); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 - assert(!move _4, "attempt to calculate the remainder of `{}` with a divisor of zero", const 1_i32) -> bb1; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 -+ _3 = const 0_i32; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:18: +2:19 + _4 = const true; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 + assert(!const true, "attempt to calculate the remainder of `{}` with a divisor of zero", const 1_i32) -> bb1; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 } bb1: { -- _5 = Eq(_3, const -1_i32); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 + _5 = Eq(_1, const -1_i32); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 - _6 = Eq(const 1_i32, const i32::MIN); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 - _7 = BitAnd(move _5, move _6); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 -- assert(!move _7, "attempt to compute the remainder of `{} % {}`, which would overflow", const 1_i32, _3) -> bb2; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 -+ _5 = const false; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 +- assert(!move _7, "attempt to compute the remainder of `{} % {}`, which would overflow", const 1_i32, _1) -> bb2; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 + _6 = const false; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 + _7 = const false; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 -+ assert(!const false, "attempt to compute the remainder of `{} % {}`, which would overflow", const 1_i32, const 0_i32) -> bb2; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 ++ assert(!const false, "attempt to compute the remainder of `{} % {}`, which would overflow", const 1_i32, _1) -> bb2; // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 } bb2: { -- _2 = Rem(const 1_i32, move _3); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 -+ _2 = Rem(const 1_i32, const 0_i32); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 - StorageDead(_3); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:18: +2:19 + _2 = Rem(const 1_i32, _1); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 StorageDead(_2); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+3:1: +3:2 - StorageDead(_1); // scope 0 at $DIR/bad_op_mod_by_zero.rs:+3:1: +3:2 return; // scope 0 at $DIR/bad_op_mod_by_zero.rs:+3:2: +3:2 } } diff --git a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.ConstProp.32bit.diff b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.ConstProp.32bit.diff index 27e41d4869d75..4bd0aa0987239 100644 --- a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.ConstProp.32bit.diff +++ b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.ConstProp.32bit.diff @@ -23,16 +23,13 @@ bb0: { StorageLive(_1); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:9: +1:10 StorageLive(_2); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 - StorageLive(_3); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 _8 = const _; // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 // mir::Constant // + span: $DIR/bad_op_unsafe_oob_for_slices.rs:5:25: 5:35 // + literal: Const { ty: &[i32; 3], val: Unevaluated(main, [], Some(promoted[0])) } - _3 = _8; // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 - _2 = &raw const (*_3); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 + _2 = &raw const (*_8); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 _1 = move _2 as *const [i32] (Pointer(Unsize)); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 StorageDead(_2); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:34: +1:35 - StorageDead(_3); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:35: +1:36 StorageLive(_4); // scope 2 at $DIR/bad_op_unsafe_oob_for_slices.rs:+3:13: +3:15 StorageLive(_5); // scope 2 at $DIR/bad_op_unsafe_oob_for_slices.rs:+3:23: +3:24 _5 = const 3_usize; // scope 2 at $DIR/bad_op_unsafe_oob_for_slices.rs:+3:23: +3:24 diff --git a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.ConstProp.64bit.diff b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.ConstProp.64bit.diff index 27e41d4869d75..4bd0aa0987239 100644 --- a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.ConstProp.64bit.diff +++ b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.ConstProp.64bit.diff @@ -23,16 +23,13 @@ bb0: { StorageLive(_1); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:9: +1:10 StorageLive(_2); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 - StorageLive(_3); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 _8 = const _; // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 // mir::Constant // + span: $DIR/bad_op_unsafe_oob_for_slices.rs:5:25: 5:35 // + literal: Const { ty: &[i32; 3], val: Unevaluated(main, [], Some(promoted[0])) } - _3 = _8; // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 - _2 = &raw const (*_3); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 + _2 = &raw const (*_8); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 _1 = move _2 as *const [i32] (Pointer(Unsize)); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:25: +1:35 StorageDead(_2); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:34: +1:35 - StorageDead(_3); // scope 0 at $DIR/bad_op_unsafe_oob_for_slices.rs:+1:35: +1:36 StorageLive(_4); // scope 2 at $DIR/bad_op_unsafe_oob_for_slices.rs:+3:13: +3:15 StorageLive(_5); // scope 2 at $DIR/bad_op_unsafe_oob_for_slices.rs:+3:23: +3:24 _5 = const 3_usize; // scope 2 at $DIR/bad_op_unsafe_oob_for_slices.rs:+3:23: +3:24 diff --git a/tests/mir-opt/const_prop/boolean_identities.test.ConstProp.diff b/tests/mir-opt/const_prop/boolean_identities.test.ConstProp.diff index 0de800917534a..549b4711e874d 100644 --- a/tests/mir-opt/const_prop/boolean_identities.test.ConstProp.diff +++ b/tests/mir-opt/const_prop/boolean_identities.test.ConstProp.diff @@ -12,18 +12,12 @@ bb0: { StorageLive(_3); // scope 0 at $DIR/boolean_identities.rs:+1:5: +1:15 - StorageLive(_4); // scope 0 at $DIR/boolean_identities.rs:+1:6: +1:7 - _4 = _2; // scope 0 at $DIR/boolean_identities.rs:+1:6: +1:7 -- _3 = BitOr(move _4, const true); // scope 0 at $DIR/boolean_identities.rs:+1:5: +1:15 +- _3 = BitOr(_2, const true); // scope 0 at $DIR/boolean_identities.rs:+1:5: +1:15 + _3 = const true; // scope 0 at $DIR/boolean_identities.rs:+1:5: +1:15 - StorageDead(_4); // scope 0 at $DIR/boolean_identities.rs:+1:14: +1:15 StorageLive(_5); // scope 0 at $DIR/boolean_identities.rs:+1:18: +1:29 - StorageLive(_6); // scope 0 at $DIR/boolean_identities.rs:+1:19: +1:20 - _6 = _1; // scope 0 at $DIR/boolean_identities.rs:+1:19: +1:20 -- _5 = BitAnd(move _6, const false); // scope 0 at $DIR/boolean_identities.rs:+1:18: +1:29 -+ _5 = const false; // scope 0 at $DIR/boolean_identities.rs:+1:18: +1:29 - StorageDead(_6); // scope 0 at $DIR/boolean_identities.rs:+1:28: +1:29 +- _5 = BitAnd(_1, const false); // scope 0 at $DIR/boolean_identities.rs:+1:18: +1:29 - _0 = BitAnd(move _3, move _5); // scope 0 at $DIR/boolean_identities.rs:+1:5: +1:29 ++ _5 = const false; // scope 0 at $DIR/boolean_identities.rs:+1:18: +1:29 + _0 = const false; // scope 0 at $DIR/boolean_identities.rs:+1:5: +1:29 StorageDead(_5); // scope 0 at $DIR/boolean_identities.rs:+1:28: +1:29 StorageDead(_3); // scope 0 at $DIR/boolean_identities.rs:+1:28: +1:29 diff --git a/tests/mir-opt/const_prop/mult_by_zero.test.ConstProp.diff b/tests/mir-opt/const_prop/mult_by_zero.test.ConstProp.diff index 629c8e60148fd..1cfe47d0a8612 100644 --- a/tests/mir-opt/const_prop/mult_by_zero.test.ConstProp.diff +++ b/tests/mir-opt/const_prop/mult_by_zero.test.ConstProp.diff @@ -7,11 +7,8 @@ let mut _2: i32; // in scope 0 at $DIR/mult_by_zero.rs:+1:3: +1:4 bb0: { - StorageLive(_2); // scope 0 at $DIR/mult_by_zero.rs:+1:3: +1:4 - _2 = _1; // scope 0 at $DIR/mult_by_zero.rs:+1:3: +1:4 -- _0 = Mul(move _2, const 0_i32); // scope 0 at $DIR/mult_by_zero.rs:+1:3: +1:8 +- _0 = Mul(_1, const 0_i32); // scope 0 at $DIR/mult_by_zero.rs:+1:3: +1:8 + _0 = const 0_i32; // scope 0 at $DIR/mult_by_zero.rs:+1:3: +1:8 - StorageDead(_2); // scope 0 at $DIR/mult_by_zero.rs:+1:7: +1:8 return; // scope 0 at $DIR/mult_by_zero.rs:+2:2: +2:2 } } diff --git a/tests/mir-opt/const_prop/scalar_literal_propagation.main.ConstProp.diff b/tests/mir-opt/const_prop/scalar_literal_propagation.main.ConstProp.diff index d518eff04eba2..22f710387db71 100644 --- a/tests/mir-opt/const_prop/scalar_literal_propagation.main.ConstProp.diff +++ b/tests/mir-opt/const_prop/scalar_literal_propagation.main.ConstProp.diff @@ -11,13 +11,9 @@ } bb0: { - StorageLive(_1); // scope 0 at $DIR/scalar_literal_propagation.rs:+1:9: +1:10 _1 = const 1_u32; // scope 0 at $DIR/scalar_literal_propagation.rs:+1:13: +1:14 StorageLive(_2); // scope 1 at $DIR/scalar_literal_propagation.rs:+2:5: +2:15 - StorageLive(_3); // scope 1 at $DIR/scalar_literal_propagation.rs:+2:13: +2:14 -- _3 = _1; // scope 1 at $DIR/scalar_literal_propagation.rs:+2:13: +2:14 -- _2 = consume(move _3) -> bb1; // scope 1 at $DIR/scalar_literal_propagation.rs:+2:5: +2:15 -+ _3 = const 1_u32; // scope 1 at $DIR/scalar_literal_propagation.rs:+2:13: +2:14 +- _2 = consume(_1) -> bb1; // scope 1 at $DIR/scalar_literal_propagation.rs:+2:5: +2:15 + _2 = consume(const 1_u32) -> bb1; // scope 1 at $DIR/scalar_literal_propagation.rs:+2:5: +2:15 // mir::Constant // + span: $DIR/scalar_literal_propagation.rs:4:5: 4:12 @@ -25,9 +21,7 @@ } bb1: { - StorageDead(_3); // scope 1 at $DIR/scalar_literal_propagation.rs:+2:14: +2:15 StorageDead(_2); // scope 1 at $DIR/scalar_literal_propagation.rs:+2:15: +2:16 - StorageDead(_1); // scope 0 at $DIR/scalar_literal_propagation.rs:+3:1: +3:2 return; // scope 0 at $DIR/scalar_literal_propagation.rs:+3:2: +3:2 } } diff --git a/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.diff b/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.diff index 02aafd7acc4ca..9c3f87f47c12c 100644 --- a/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.diff +++ b/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.diff @@ -16,23 +16,13 @@ } bb0: { - StorageLive(_1); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47 _1 = const u8::MAX; // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47 - StorageLive(_2); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47 _2 = const 1_u8; // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47 - StorageLive(_3); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL - _3 = const u8::MAX; // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL - StorageLive(_4); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL - _4 = const 1_u8; // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL _5 = CheckedAdd(const u8::MAX, const 1_u8); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL assert(!move (_5.1: bool), "attempt to compute `{} + {}`, which would overflow", const u8::MAX, const 1_u8) -> bb1; // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL } bb1: { - StorageDead(_4); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL - StorageDead(_3); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL - StorageDead(_2); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47 - StorageDead(_1); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47 return; // scope 0 at $DIR/inherit_overflow.rs:+4:2: +4:2 } } diff --git a/tests/mir-opt/div_overflow.const_dividend.PreCodegen.after.mir b/tests/mir-opt/div_overflow.const_dividend.PreCodegen.after.mir index d7f66a6bf4d56..1a7fb916e56db 100644 --- a/tests/mir-opt/div_overflow.const_dividend.PreCodegen.after.mir +++ b/tests/mir-opt/div_overflow.const_dividend.PreCodegen.after.mir @@ -11,7 +11,7 @@ fn const_dividend(_1: i32) -> i32 { } bb1: { - _0 = Div(const 256_i32, move _1); // scope 0 at $DIR/div_overflow.rs:+1:5: +1:12 + _0 = Div(const 256_i32, _1); // scope 0 at $DIR/div_overflow.rs:+1:5: +1:12 return; // scope 0 at $DIR/div_overflow.rs:+2:2: +2:2 } } diff --git a/tests/mir-opt/div_overflow.const_divisor.PreCodegen.after.mir b/tests/mir-opt/div_overflow.const_divisor.PreCodegen.after.mir index 7b7ab1978258f..5526a194be563 100644 --- a/tests/mir-opt/div_overflow.const_divisor.PreCodegen.after.mir +++ b/tests/mir-opt/div_overflow.const_divisor.PreCodegen.after.mir @@ -5,7 +5,7 @@ fn const_divisor(_1: i32) -> i32 { let mut _0: i32; // return place in scope 0 at $DIR/div_overflow.rs:+0:33: +0:36 bb0: { - _0 = Div(move _1, const 256_i32); // scope 0 at $DIR/div_overflow.rs:+1:5: +1:12 + _0 = Div(_1, const 256_i32); // scope 0 at $DIR/div_overflow.rs:+1:5: +1:12 return; // scope 0 at $DIR/div_overflow.rs:+2:2: +2:2 } } diff --git a/tests/mir-opt/funky_arms.float_to_exponential_common.ConstProp.diff b/tests/mir-opt/funky_arms.float_to_exponential_common.ConstProp.diff index c1c2cde71ab5b..7c5d28069d59d 100644 --- a/tests/mir-opt/funky_arms.float_to_exponential_common.ConstProp.diff +++ b/tests/mir-opt/funky_arms.float_to_exponential_common.ConstProp.diff @@ -79,59 +79,42 @@ } bb6: { - StorageLive(_10); // scope 3 at $DIR/funky_arms.rs:+13:17: +13:26 _10 = ((_7 as Some).0: usize); // scope 3 at $DIR/funky_arms.rs:+13:17: +13:26 StorageLive(_11); // scope 3 at $DIR/funky_arms.rs:+15:43: +15:46 _11 = &mut (*_1); // scope 3 at $DIR/funky_arms.rs:+15:43: +15:46 - StorageLive(_12); // scope 3 at $DIR/funky_arms.rs:+15:48: +15:51 - _12 = _2; // scope 3 at $DIR/funky_arms.rs:+15:48: +15:51 StorageLive(_13); // scope 3 at $DIR/funky_arms.rs:+15:53: +15:57 _13 = _6; // scope 3 at $DIR/funky_arms.rs:+15:53: +15:57 StorageLive(_14); // scope 3 at $DIR/funky_arms.rs:+15:59: +15:79 StorageLive(_15); // scope 3 at $DIR/funky_arms.rs:+15:59: +15:75 - StorageLive(_16); // scope 3 at $DIR/funky_arms.rs:+15:59: +15:68 - _16 = _10; // scope 3 at $DIR/funky_arms.rs:+15:59: +15:68 - _15 = move _16 as u32 (IntToInt); // scope 3 at $DIR/funky_arms.rs:+15:59: +15:75 - StorageDead(_16); // scope 3 at $DIR/funky_arms.rs:+15:74: +15:75 + _15 = _10 as u32 (IntToInt); // scope 3 at $DIR/funky_arms.rs:+15:59: +15:75 _14 = Add(move _15, const 1_u32); // scope 3 at $DIR/funky_arms.rs:+15:59: +15:79 StorageDead(_15); // scope 3 at $DIR/funky_arms.rs:+15:78: +15:79 - StorageLive(_17); // scope 3 at $DIR/funky_arms.rs:+15:81: +15:86 - _17 = _3; // scope 3 at $DIR/funky_arms.rs:+15:81: +15:86 - _0 = float_to_exponential_common_exact::(move _11, move _12, move _13, move _14, move _17) -> bb7; // scope 3 at $DIR/funky_arms.rs:+15:9: +15:87 + _0 = float_to_exponential_common_exact::(move _11, _2, move _13, move _14, _3) -> bb7; // scope 3 at $DIR/funky_arms.rs:+15:9: +15:87 // mir::Constant // + span: $DIR/funky_arms.rs:26:9: 26:42 // + literal: Const { ty: for<'a, 'b, 'c> fn(&'a mut Formatter<'b>, &'c T, Sign, u32, bool) -> Result<(), std::fmt::Error> {float_to_exponential_common_exact::}, val: Value() } } bb7: { - StorageDead(_17); // scope 3 at $DIR/funky_arms.rs:+15:86: +15:87 StorageDead(_14); // scope 3 at $DIR/funky_arms.rs:+15:86: +15:87 StorageDead(_13); // scope 3 at $DIR/funky_arms.rs:+15:86: +15:87 - StorageDead(_12); // scope 3 at $DIR/funky_arms.rs:+15:86: +15:87 StorageDead(_11); // scope 3 at $DIR/funky_arms.rs:+15:86: +15:87 - StorageDead(_10); // scope 2 at $DIR/funky_arms.rs:+16:5: +16:6 goto -> bb10; // scope 2 at $DIR/funky_arms.rs:+13:5: +18:6 } bb8: { StorageLive(_18); // scope 2 at $DIR/funky_arms.rs:+17:46: +17:49 _18 = &mut (*_1); // scope 2 at $DIR/funky_arms.rs:+17:46: +17:49 - StorageLive(_19); // scope 2 at $DIR/funky_arms.rs:+17:51: +17:54 - _19 = _2; // scope 2 at $DIR/funky_arms.rs:+17:51: +17:54 StorageLive(_20); // scope 2 at $DIR/funky_arms.rs:+17:56: +17:60 _20 = _6; // scope 2 at $DIR/funky_arms.rs:+17:56: +17:60 - StorageLive(_21); // scope 2 at $DIR/funky_arms.rs:+17:62: +17:67 - _21 = _3; // scope 2 at $DIR/funky_arms.rs:+17:62: +17:67 - _0 = float_to_exponential_common_shortest::(move _18, move _19, move _20, move _21) -> bb9; // scope 2 at $DIR/funky_arms.rs:+17:9: +17:68 + _0 = float_to_exponential_common_shortest::(move _18, _2, move _20, _3) -> bb9; // scope 2 at $DIR/funky_arms.rs:+17:9: +17:68 // mir::Constant // + span: $DIR/funky_arms.rs:28:9: 28:45 // + literal: Const { ty: for<'a, 'b, 'c> fn(&'a mut Formatter<'b>, &'c T, Sign, bool) -> Result<(), std::fmt::Error> {float_to_exponential_common_shortest::}, val: Value() } } bb9: { - StorageDead(_21); // scope 2 at $DIR/funky_arms.rs:+17:67: +17:68 StorageDead(_20); // scope 2 at $DIR/funky_arms.rs:+17:67: +17:68 - StorageDead(_19); // scope 2 at $DIR/funky_arms.rs:+17:67: +17:68 StorageDead(_18); // scope 2 at $DIR/funky_arms.rs:+17:67: +17:68 goto -> bb10; // scope 2 at $DIR/funky_arms.rs:+13:5: +18:6 } diff --git a/tests/mir-opt/inline/dyn_trait.get_query.Inline.diff b/tests/mir-opt/inline/dyn_trait.get_query.Inline.diff index 8ea1a0757f2f0..64c3e47ff46ed 100644 --- a/tests/mir-opt/inline/dyn_trait.get_query.Inline.diff +++ b/tests/mir-opt/inline/dyn_trait.get_query.Inline.diff @@ -35,8 +35,8 @@ _4 = &(*_2); // scope 1 at $DIR/dyn_trait.rs:+2:23: +2:24 - _0 = try_execute_query::<::C>(move _4) -> bb2; // scope 1 at $DIR/dyn_trait.rs:+2:5: +2:25 + StorageLive(_5); // scope 2 at $DIR/dyn_trait.rs:27:14: 27:15 -+ _5 = move _4 as &dyn Cache::V> (Pointer(Unsize)); // scope 2 at $DIR/dyn_trait.rs:27:14: 27:15 -+ _0 = ::V> as Cache>::store_nocache(move _5) -> bb2; // scope 3 at $DIR/dyn_trait.rs:21:5: 21:22 ++ _5 = _4 as &dyn Cache::V> (Pointer(Unsize)); // scope 2 at $DIR/dyn_trait.rs:27:14: 27:15 ++ _0 = ::V> as Cache>::store_nocache(_5) -> bb2; // scope 3 at $DIR/dyn_trait.rs:21:5: 21:22 // mir::Constant - // + span: $DIR/dyn_trait.rs:34:5: 34:22 - // + literal: Const { ty: for<'a> fn(&'a ::C) {try_execute_query::<::C>}, val: Value() } diff --git a/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.diff b/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.diff index a71d73b745354..3fa9c3e88f634 100644 --- a/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.diff +++ b/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.diff @@ -17,7 +17,7 @@ _2 = move _3 as &dyn Cache::V> (Pointer(Unsize)); // scope 0 at $DIR/dyn_trait.rs:+1:14: +1:15 StorageDead(_3); // scope 0 at $DIR/dyn_trait.rs:+1:14: +1:15 - _0 = mk_cycle::<::V>(move _2) -> bb1; // scope 0 at $DIR/dyn_trait.rs:+1:5: +1:16 -+ _0 = ::V> as Cache>::store_nocache(move _2) -> bb1; // scope 1 at $DIR/dyn_trait.rs:21:5: 21:22 ++ _0 = ::V> as Cache>::store_nocache(_2) -> bb1; // scope 1 at $DIR/dyn_trait.rs:21:5: 21:22 // mir::Constant - // + span: $DIR/dyn_trait.rs:27:5: 27:13 - // + literal: Const { ty: for<'a> fn(&'a (dyn Cache::V> + 'a)) {mk_cycle::<::V>}, val: Value() } diff --git a/tests/mir-opt/inline/inline_any_operand.bar.Inline.after.mir b/tests/mir-opt/inline/inline_any_operand.bar.Inline.after.mir index 3502c25864bf9..20f737cc29f62 100644 --- a/tests/mir-opt/inline/inline_any_operand.bar.Inline.after.mir +++ b/tests/mir-opt/inline/inline_any_operand.bar.Inline.after.mir @@ -26,7 +26,7 @@ fn bar() -> bool { _3 = const 1_i32; // scope 1 at $DIR/inline_any_operand.rs:+2:5: +2:13 StorageLive(_4); // scope 1 at $DIR/inline_any_operand.rs:+2:5: +2:13 _4 = const -1_i32; // scope 1 at $DIR/inline_any_operand.rs:+2:5: +2:13 - _0 = Eq(move _3, move _4); // scope 2 at $DIR/inline_any_operand.rs:17:5: 17:11 + _0 = Eq(_3, _4); // scope 2 at $DIR/inline_any_operand.rs:17:5: 17:11 StorageDead(_4); // scope 1 at $DIR/inline_any_operand.rs:+2:5: +2:13 StorageDead(_3); // scope 1 at $DIR/inline_any_operand.rs:+2:5: +2:13 StorageDead(_2); // scope 1 at $DIR/inline_any_operand.rs:+2:12: +2:13 diff --git a/tests/mir-opt/inline/inline_generator.main.Inline.diff b/tests/mir-opt/inline/inline_generator.main.Inline.diff index f27b64c305457..57574acf92354 100644 --- a/tests/mir-opt/inline/inline_generator.main.Inline.diff +++ b/tests/mir-opt/inline/inline_generator.main.Inline.diff @@ -92,7 +92,7 @@ + + bb3: { + StorageLive(_8); // scope 6 at $DIR/inline_generator.rs:15:17: 15:39 -+ switchInt(move _7) -> [0: bb5, otherwise: bb4]; // scope 6 at $DIR/inline_generator.rs:15:20: 15:21 ++ switchInt(_7) -> [0: bb5, otherwise: bb4]; // scope 6 at $DIR/inline_generator.rs:15:20: 15:21 + } + + bb4: { @@ -118,7 +118,7 @@ + StorageLive(_8); // scope 6 at $DIR/inline_generator.rs:15:5: 15:41 + StorageDead(_8); // scope 6 at $DIR/inline_generator.rs:15:38: 15:39 + Deinit(_1); // scope 6 at $DIR/inline_generator.rs:15:41: 15:41 -+ ((_1 as Complete).0: bool) = move _7; // scope 6 at $DIR/inline_generator.rs:15:41: 15:41 ++ ((_1 as Complete).0: bool) = _7; // scope 6 at $DIR/inline_generator.rs:15:41: 15:41 + discriminant(_1) = 1; // scope 6 at $DIR/inline_generator.rs:15:41: 15:41 + _12 = deref_copy (_2.0: &mut [generator@$DIR/inline_generator.rs:15:5: 15:8]); // scope 6 at $DIR/inline_generator.rs:15:41: 15:41 + discriminant((*_12)) = 1; // scope 6 at $DIR/inline_generator.rs:15:41: 15:41 diff --git a/tests/mir-opt/inline/inline_trait_method_2.test2.Inline.after.mir b/tests/mir-opt/inline/inline_trait_method_2.test2.Inline.after.mir index 73aea719eed51..b7c5bbecb6883 100644 --- a/tests/mir-opt/inline/inline_trait_method_2.test2.Inline.after.mir +++ b/tests/mir-opt/inline/inline_trait_method_2.test2.Inline.after.mir @@ -15,7 +15,7 @@ fn test2(_1: &dyn X) -> bool { _3 = &(*_1); // scope 0 at $DIR/inline_trait_method_2.rs:+1:10: +1:11 _2 = move _3 as &dyn X (Pointer(Unsize)); // scope 0 at $DIR/inline_trait_method_2.rs:+1:10: +1:11 StorageDead(_3); // scope 0 at $DIR/inline_trait_method_2.rs:+1:10: +1:11 - _0 = ::y(move _2) -> bb1; // scope 1 at $DIR/inline_trait_method_2.rs:10:5: 10:10 + _0 = ::y(_2) -> bb1; // scope 1 at $DIR/inline_trait_method_2.rs:10:5: 10:10 // mir::Constant // + span: $DIR/inline_trait_method_2.rs:10:7: 10:8 // + literal: Const { ty: for<'a> fn(&'a dyn X) -> bool {::y}, val: Value() } diff --git a/tests/mir-opt/issue_101973.inner.ConstProp.diff b/tests/mir-opt/issue_101973.inner.ConstProp.diff index b2706e5a436e2..002392c5cf81a 100644 --- a/tests/mir-opt/issue_101973.inner.ConstProp.diff +++ b/tests/mir-opt/issue_101973.inner.ConstProp.diff @@ -15,7 +15,7 @@ let mut _10: (u32, bool); // in scope 0 at $DIR/issue_101973.rs:+1:32: +1:45 let mut _11: (u32, bool); // in scope 0 at $DIR/issue_101973.rs:+1:31: +1:57 scope 1 (inlined imm8) { // at $DIR/issue_101973.rs:14:5: 14:17 - debug x => _5; // in scope 1 at $DIR/issue_101973.rs:5:13: 5:14 + debug x => _1; // in scope 1 at $DIR/issue_101973.rs:5:13: 5:14 let mut _12: u32; // in scope 1 at $DIR/issue_101973.rs:7:12: 7:27 let mut _13: u32; // in scope 1 at $DIR/issue_101973.rs:7:12: 7:20 let mut _14: (u32, bool); // in scope 1 at $DIR/issue_101973.rs:7:12: 7:20 @@ -33,18 +33,14 @@ bb0: { StorageLive(_2); // scope 0 at $DIR/issue_101973.rs:+1:5: +1:65 StorageLive(_3); // scope 0 at $DIR/issue_101973.rs:+1:5: +1:58 - StorageLive(_4); // scope 0 at $DIR/issue_101973.rs:+1:5: +1:17 - StorageLive(_5); // scope 0 at $DIR/issue_101973.rs:+1:10: +1:16 - _5 = _1; // scope 0 at $DIR/issue_101973.rs:+1:10: +1:16 StorageLive(_12); // scope 2 at $DIR/issue_101973.rs:7:12: 7:27 StorageLive(_13); // scope 2 at $DIR/issue_101973.rs:7:12: 7:20 - _14 = CheckedShr(_5, const 0_i32); // scope 2 at $DIR/issue_101973.rs:7:12: 7:20 + _14 = CheckedShr(_1, const 0_i32); // scope 2 at $DIR/issue_101973.rs:7:12: 7:20 assert(!move (_14.1: bool), "attempt to shift right by `{}`, which would overflow", const 0_i32) -> bb3; // scope 2 at $DIR/issue_101973.rs:7:12: 7:20 } bb1: { _8 = move (_10.0: u32); // scope 0 at $DIR/issue_101973.rs:+1:32: +1:45 - StorageDead(_9); // scope 0 at $DIR/issue_101973.rs:+1:44: +1:45 _7 = BitAnd(move _8, const 15_u32); // scope 0 at $DIR/issue_101973.rs:+1:31: +1:52 StorageDead(_8); // scope 0 at $DIR/issue_101973.rs:+1:51: +1:52 _11 = CheckedShl(_7, const 1_i32); // scope 0 at $DIR/issue_101973.rs:+1:31: +1:57 @@ -54,11 +50,7 @@ bb2: { _6 = move (_11.0: u32); // scope 0 at $DIR/issue_101973.rs:+1:31: +1:57 StorageDead(_7); // scope 0 at $DIR/issue_101973.rs:+1:56: +1:57 - StorageLive(_15); // scope 3 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - _15 = _4; // scope 3 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - StorageLive(_16); // scope 3 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - _16 = _6; // scope 3 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - _3 = rotate_right::(move _15, move _16) -> bb4; // scope 3 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + _3 = rotate_right::(_4, _6) -> bb4; // scope 3 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL // mir::Constant // + span: $SRC_DIR/core/src/num/uint_macros.rs:LL:COL // + literal: Const { ty: extern "rust-intrinsic" fn(u32, u32) -> u32 {rotate_right::}, val: Value() } @@ -70,21 +62,13 @@ StorageDead(_13); // scope 2 at $DIR/issue_101973.rs:7:26: 7:27 _4 = BitOr(const 0_u32, move _12); // scope 2 at $DIR/issue_101973.rs:7:5: 7:27 StorageDead(_12); // scope 2 at $DIR/issue_101973.rs:7:26: 7:27 - StorageDead(_5); // scope 0 at $DIR/issue_101973.rs:+1:16: +1:17 - StorageLive(_6); // scope 0 at $DIR/issue_101973.rs:+1:31: +1:57 StorageLive(_7); // scope 0 at $DIR/issue_101973.rs:+1:31: +1:52 StorageLive(_8); // scope 0 at $DIR/issue_101973.rs:+1:32: +1:45 - StorageLive(_9); // scope 0 at $DIR/issue_101973.rs:+1:33: +1:39 - _9 = _1; // scope 0 at $DIR/issue_101973.rs:+1:33: +1:39 - _10 = CheckedShr(_9, const 8_i32); // scope 0 at $DIR/issue_101973.rs:+1:32: +1:45 + _10 = CheckedShr(_1, const 8_i32); // scope 0 at $DIR/issue_101973.rs:+1:32: +1:45 assert(!move (_10.1: bool), "attempt to shift right by `{}`, which would overflow", const 8_i32) -> bb1; // scope 0 at $DIR/issue_101973.rs:+1:32: +1:45 } bb4: { - StorageDead(_16); // scope 3 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - StorageDead(_15); // scope 3 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - StorageDead(_6); // scope 0 at $DIR/issue_101973.rs:+1:57: +1:58 - StorageDead(_4); // scope 0 at $DIR/issue_101973.rs:+1:57: +1:58 _2 = move _3 as i32 (IntToInt); // scope 0 at $DIR/issue_101973.rs:+1:5: +1:65 StorageDead(_3); // scope 0 at $DIR/issue_101973.rs:+1:64: +1:65 _0 = move _2 as i64 (IntToInt); // scope 0 at $DIR/issue_101973.rs:+1:5: +1:72 diff --git a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.diff b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.diff index c24543daeacb7..cc4f7cc06991f 100644 --- a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.diff +++ b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.diff @@ -29,24 +29,10 @@ bb0: { StorageLive(_2); // scope 0 at $DIR/issue_76432.rs:+1:9: +1:10 - StorageLive(_3); // scope 0 at $DIR/issue_76432.rs:+1:19: +1:29 - StorageLive(_4); // scope 0 at $DIR/issue_76432.rs:+1:19: +1:29 StorageLive(_5); // scope 0 at $DIR/issue_76432.rs:+1:20: +1:29 - StorageLive(_6); // scope 0 at $DIR/issue_76432.rs:+1:21: +1:22 - _6 = _1; // scope 0 at $DIR/issue_76432.rs:+1:21: +1:22 - StorageLive(_7); // scope 0 at $DIR/issue_76432.rs:+1:24: +1:25 - _7 = _1; // scope 0 at $DIR/issue_76432.rs:+1:24: +1:25 - StorageLive(_8); // scope 0 at $DIR/issue_76432.rs:+1:27: +1:28 - _8 = _1; // scope 0 at $DIR/issue_76432.rs:+1:27: +1:28 - _5 = [move _6, move _7, move _8]; // scope 0 at $DIR/issue_76432.rs:+1:20: +1:29 - StorageDead(_8); // scope 0 at $DIR/issue_76432.rs:+1:28: +1:29 - StorageDead(_7); // scope 0 at $DIR/issue_76432.rs:+1:28: +1:29 - StorageDead(_6); // scope 0 at $DIR/issue_76432.rs:+1:28: +1:29 + _5 = [_1, _1, _1]; // scope 0 at $DIR/issue_76432.rs:+1:20: +1:29 _4 = &_5; // scope 0 at $DIR/issue_76432.rs:+1:19: +1:29 - _3 = _4; // scope 0 at $DIR/issue_76432.rs:+1:19: +1:29 - _2 = move _3 as &[T] (Pointer(Unsize)); // scope 0 at $DIR/issue_76432.rs:+1:19: +1:29 - StorageDead(_3); // scope 0 at $DIR/issue_76432.rs:+1:28: +1:29 - StorageDead(_4); // scope 0 at $DIR/issue_76432.rs:+1:29: +1:30 + _2 = _4 as &[T] (Pointer(Unsize)); // scope 0 at $DIR/issue_76432.rs:+1:19: +1:29 _9 = Len((*_2)); // scope 1 at $DIR/issue_76432.rs:+3:9: +3:33 _10 = const 3_usize; // scope 1 at $DIR/issue_76432.rs:+3:9: +3:33 - _11 = Eq(move _9, const 3_usize); // scope 1 at $DIR/issue_76432.rs:+3:9: +3:33 diff --git a/tests/mir-opt/lower_array_len_e2e.array_bound.PreCodegen.after.mir b/tests/mir-opt/lower_array_len_e2e.array_bound.PreCodegen.after.mir index 701c2ad705af2..dee1d538395ef 100644 --- a/tests/mir-opt/lower_array_len_e2e.array_bound.PreCodegen.after.mir +++ b/tests/mir-opt/lower_array_len_e2e.array_bound.PreCodegen.after.mir @@ -5,27 +5,23 @@ fn array_bound(_1: usize, _2: &[u8; N]) -> u8 { debug slice => _2; // in scope 0 at $DIR/lower_array_len_e2e.rs:+0:50: +0:55 let mut _0: u8; // return place in scope 0 at $DIR/lower_array_len_e2e.rs:+0:70: +0:72 let mut _3: bool; // in scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:27 - let mut _4: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:13 - let mut _5: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 - let mut _6: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 - let mut _7: bool; // in scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 + let mut _4: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 + let mut _5: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 + let mut _6: bool; // in scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 bb0: { StorageLive(_3); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:27 - StorageLive(_4); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:13 - _4 = _1; // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:13 - StorageLive(_5); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 - _5 = const N; // scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 - _3 = Lt(move _4, move _5); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:27 - StorageDead(_5); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:26: +1:27 + StorageLive(_4); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 + _4 = const N; // scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 + _3 = Lt(_1, move _4); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:27 StorageDead(_4); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:26: +1:27 switchInt(move _3) -> [0: bb3, otherwise: bb1]; // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:27 } bb1: { - _6 = const N; // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 - _7 = Lt(_1, _6); // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 - assert(move _7, "index out of bounds: the length is {} but the index is {}", move _6, _1) -> bb2; // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 + _5 = const N; // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 + _6 = Lt(_1, _5); // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 + assert(move _6, "index out of bounds: the length is {} but the index is {}", move _5, _1) -> bb2; // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 } bb2: { diff --git a/tests/mir-opt/lower_array_len_e2e.array_bound_mut.PreCodegen.after.mir b/tests/mir-opt/lower_array_len_e2e.array_bound_mut.PreCodegen.after.mir index 0440cfce2893f..e35fe758ab12d 100644 --- a/tests/mir-opt/lower_array_len_e2e.array_bound_mut.PreCodegen.after.mir +++ b/tests/mir-opt/lower_array_len_e2e.array_bound_mut.PreCodegen.after.mir @@ -5,30 +5,26 @@ fn array_bound_mut(_1: usize, _2: &mut [u8; N]) -> u8 { debug slice => _2; // in scope 0 at $DIR/lower_array_len_e2e.rs:+0:54: +0:59 let mut _0: u8; // return place in scope 0 at $DIR/lower_array_len_e2e.rs:+0:78: +0:80 let mut _3: bool; // in scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:27 - let mut _4: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:13 - let mut _5: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 - let mut _6: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 - let mut _7: bool; // in scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 - let _8: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+4:15: +4:16 - let mut _9: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:17 - let mut _10: bool; // in scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:17 + let mut _4: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 + let mut _5: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 + let mut _6: bool; // in scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 + let _7: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+4:15: +4:16 + let mut _8: usize; // in scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:17 + let mut _9: bool; // in scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:17 bb0: { StorageLive(_3); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:27 - StorageLive(_4); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:13 - _4 = _1; // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:13 - StorageLive(_5); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 - _5 = const N; // scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 - _3 = Lt(move _4, move _5); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:27 - StorageDead(_5); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:26: +1:27 + StorageLive(_4); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 + _4 = const N; // scope 0 at $DIR/lower_array_len_e2e.rs:+1:16: +1:27 + _3 = Lt(_1, move _4); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:27 StorageDead(_4); // scope 0 at $DIR/lower_array_len_e2e.rs:+1:26: +1:27 switchInt(move _3) -> [0: bb3, otherwise: bb1]; // scope 0 at $DIR/lower_array_len_e2e.rs:+1:8: +1:27 } bb1: { - _6 = const N; // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 - _7 = Lt(_1, _6); // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 - assert(move _7, "index out of bounds: the length is {} but the index is {}", move _6, _1) -> bb2; // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 + _5 = const N; // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 + _6 = Lt(_1, _5); // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 + assert(move _6, "index out of bounds: the length is {} but the index is {}", move _5, _1) -> bb2; // scope 0 at $DIR/lower_array_len_e2e.rs:+2:9: +2:21 } bb2: { @@ -37,16 +33,16 @@ fn array_bound_mut(_1: usize, _2: &mut [u8; N]) -> u8 { } bb3: { - StorageLive(_8); // scope 0 at $DIR/lower_array_len_e2e.rs:+4:15: +4:16 - _8 = const 0_usize; // scope 0 at $DIR/lower_array_len_e2e.rs:+4:15: +4:16 - _9 = const N; // scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:17 - _10 = Lt(const 0_usize, _9); // scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:17 - assert(move _10, "index out of bounds: the length is {} but the index is {}", move _9, const 0_usize) -> bb4; // scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:17 + StorageLive(_7); // scope 0 at $DIR/lower_array_len_e2e.rs:+4:15: +4:16 + _7 = const 0_usize; // scope 0 at $DIR/lower_array_len_e2e.rs:+4:15: +4:16 + _8 = const N; // scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:17 + _9 = Lt(const 0_usize, _8); // scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:17 + assert(move _9, "index out of bounds: the length is {} but the index is {}", move _8, const 0_usize) -> bb4; // scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:17 } bb4: { - (*_2)[_8] = const 42_u8; // scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:22 - StorageDead(_8); // scope 0 at $DIR/lower_array_len_e2e.rs:+4:22: +4:23 + (*_2)[_7] = const 42_u8; // scope 0 at $DIR/lower_array_len_e2e.rs:+4:9: +4:22 + StorageDead(_7); // scope 0 at $DIR/lower_array_len_e2e.rs:+4:22: +4:23 _0 = const 42_u8; // scope 0 at $DIR/lower_array_len_e2e.rs:+6:9: +6:11 goto -> bb5; // scope 0 at $DIR/lower_array_len_e2e.rs:+1:5: +7:6 } diff --git a/tests/mir-opt/simple_option_map_e2e.ezmap.PreCodegen.after.mir b/tests/mir-opt/simple_option_map_e2e.ezmap.PreCodegen.after.mir index 916f99049c60a..760f48d956d62 100644 --- a/tests/mir-opt/simple_option_map_e2e.ezmap.PreCodegen.after.mir +++ b/tests/mir-opt/simple_option_map_e2e.ezmap.PreCodegen.after.mir @@ -37,7 +37,7 @@ fn ezmap(_1: Option) -> Option { bb3: { _5 = move ((_1 as Some).0: i32); // scope 1 at $DIR/simple_option_map_e2e.rs:7:14: 7:15 StorageLive(_4); // scope 2 at $DIR/simple_option_map_e2e.rs:7:25: 7:29 - _4 = Add(move _5, const 1_i32); // scope 3 at $DIR/simple_option_map_e2e.rs:+1:16: +1:21 + _4 = Add(_5, const 1_i32); // scope 3 at $DIR/simple_option_map_e2e.rs:+1:16: +1:21 Deinit(_0); // scope 2 at $DIR/simple_option_map_e2e.rs:7:20: 7:30 ((_0 as Some).0: i32) = move _4; // scope 2 at $DIR/simple_option_map_e2e.rs:7:20: 7:30 discriminant(_0) = 1; // scope 2 at $DIR/simple_option_map_e2e.rs:7:20: 7:30 diff --git a/tests/mir-opt/simplify_match.main.ConstProp.diff b/tests/mir-opt/simplify_match.main.ConstProp.diff index 70bfbf1b3e366..b700adfb105b0 100644 --- a/tests/mir-opt/simplify_match.main.ConstProp.diff +++ b/tests/mir-opt/simplify_match.main.ConstProp.diff @@ -10,13 +10,8 @@ } bb0: { - StorageLive(_1); // scope 0 at $DIR/simplify_match.rs:+1:11: +1:31 - StorageLive(_2); // scope 0 at $DIR/simplify_match.rs:+1:17: +1:18 _2 = const false; // scope 0 at $DIR/simplify_match.rs:+1:21: +1:26 -- _1 = _2; // scope 1 at $DIR/simplify_match.rs:+1:28: +1:29 -+ _1 = const false; // scope 1 at $DIR/simplify_match.rs:+1:28: +1:29 - StorageDead(_2); // scope 0 at $DIR/simplify_match.rs:+1:30: +1:31 -- switchInt(_1) -> [0: bb1, otherwise: bb2]; // scope 0 at $DIR/simplify_match.rs:+1:5: +1:31 +- switchInt(_2) -> [0: bb1, otherwise: bb2]; // scope 0 at $DIR/simplify_match.rs:+1:5: +1:31 + switchInt(const false) -> [0: bb1, otherwise: bb2]; // scope 0 at $DIR/simplify_match.rs:+1:5: +1:31 } @@ -32,7 +27,6 @@ } bb3: { - StorageDead(_1); // scope 0 at $DIR/simplify_match.rs:+5:1: +5:2 return; // scope 0 at $DIR/simplify_match.rs:+5:2: +5:2 } } diff --git a/tests/mir-opt/slice_filter.rs b/tests/mir-opt/slice_filter.rs index 83e6926d5328e..97c18af31de7f 100644 --- a/tests/mir-opt/slice_filter.rs +++ b/tests/mir-opt/slice_filter.rs @@ -1,21 +1,18 @@ fn main() { let input = vec![]; - - // 1761ms on my machine let _variant_a_result = variant_a(&input); - - // 656ms on my machine let _variant_b_result = variant_b(&input); } - -// EMIT_MIR slice_filter.variant_a-{closure#0}.DestinationPropagation.diff pub fn variant_a(input: &[(usize, usize, usize, usize)]) -> usize { input.iter().filter(|(a, b, c, d)| a <= c && d <= b || c <= a && b <= d).count() } - -// EMIT_MIR slice_filter.variant_b-{closure#0}.DestinationPropagation.diff pub fn variant_b(input: &[(usize, usize, usize, usize)]) -> usize { input.iter().filter(|&&(a, b, c, d)| a <= c && d <= b || c <= a && b <= d).count() } + +// EMIT_MIR slice_filter.variant_a-{closure#0}.CopyProp.diff +// EMIT_MIR slice_filter.variant_a-{closure#0}.DestinationPropagation.diff +// EMIT_MIR slice_filter.variant_b-{closure#0}.CopyProp.diff +// EMIT_MIR slice_filter.variant_b-{closure#0}.DestinationPropagation.diff diff --git a/tests/mir-opt/slice_filter.variant_a-{closure#0}.CopyProp.diff b/tests/mir-opt/slice_filter.variant_a-{closure#0}.CopyProp.diff new file mode 100644 index 0000000000000..ca8c04c386fa5 --- /dev/null +++ b/tests/mir-opt/slice_filter.variant_a-{closure#0}.CopyProp.diff @@ -0,0 +1,283 @@ +- // MIR for `variant_a::{closure#0}` before CopyProp ++ // MIR for `variant_a::{closure#0}` after CopyProp + + fn variant_a::{closure#0}(_1: &mut [closure@$DIR/slice_filter.rs:8:25: 8:39], _2: &&(usize, usize, usize, usize)) -> bool { + let mut _0: bool; // return place in scope 0 at $DIR/slice_filter.rs:+0:40: +0:40 + let _3: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + let _4: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + let _5: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + let _6: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + let mut _7: bool; // in scope 0 at $DIR/slice_filter.rs:+0:40: +0:56 + let mut _8: bool; // in scope 0 at $DIR/slice_filter.rs:+0:40: +0:46 + let mut _9: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:40: +0:41 + let mut _10: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:45: +0:46 + let _11: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:45: +0:46 + let mut _12: bool; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:56 + let mut _13: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:51 + let mut _14: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:55: +0:56 + let _15: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:55: +0:56 + let mut _16: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:76 + let mut _17: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:66 + let mut _18: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:61 + let mut _19: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:65: +0:66 + let _20: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:65: +0:66 + let mut _21: bool; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:76 + let mut _22: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:71 + let mut _23: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + let _24: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + let mut _25: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _26: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _27: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _28: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + scope 1 { + debug a => _3; // in scope 1 at $DIR/slice_filter.rs:+0:27: +0:28 + debug b => _4; // in scope 1 at $DIR/slice_filter.rs:+0:30: +0:31 + debug c => _5; // in scope 1 at $DIR/slice_filter.rs:+0:33: +0:34 + debug d => _6; // in scope 1 at $DIR/slice_filter.rs:+0:36: +0:37 + scope 2 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:40: 8:46 + debug self => _9; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _10; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _29: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _30: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _31: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _32: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + scope 3 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug self => _29; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug other => _30; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug self => _31; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug other => _32; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _33: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _34: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + } + } + scope 4 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:60: 8:66 + debug self => _18; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _19; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _35: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _36: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _37: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _38: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + scope 5 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug self => _35; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug other => _36; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug self => _37; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug other => _38; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _39: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _40: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + } + } + scope 6 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:50: 8:56 + debug self => _13; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _14; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _41: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _42: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _43: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _44: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + scope 7 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug self => _41; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug other => _42; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug self => _43; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug other => _44; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _45: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _46: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + } + } + scope 8 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:70: 8:76 + debug self => _22; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _23; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _47: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _48: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _49: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _50: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + scope 9 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug self => _47; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL +- debug other => _48; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug self => _49; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ debug other => _50; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _51: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _52: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + } + } + } + + bb0: { +- StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + _25 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + _3 = &((*_25).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 +- StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + _26 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + _4 = &((*_26).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 +- StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + _27 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + _5 = &((*_27).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 +- StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + _28 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + _6 = &((*_28).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + StorageLive(_7); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + StorageLive(_8); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:46 + StorageLive(_9); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:41 + _9 = &_3; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:41 + StorageLive(_10); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 +- StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 +- _11 = _5; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 +- _10 = &_11; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 +- StorageLive(_29); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _10 = &_5; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + _31 = deref_copy (*_9); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _29 = _31; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageLive(_30); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + _32 = deref_copy (*_10); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _30 = _32; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_33); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _33 = (*_29); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _33 = (*_31); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_34); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _34 = (*_30); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _34 = (*_32); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + _8 = Le(move _33, move _34); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_34); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_33); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_30); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_29); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + StorageDead(_10); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + StorageDead(_9); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + switchInt(move _8) -> [0: bb4, otherwise: bb5]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + } + + bb1: { + _0 = const true; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + goto -> bb3; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + } + + bb2: { + StorageLive(_16); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + StorageLive(_17); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:66 + StorageLive(_18); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 + _18 = &_5; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 + StorageLive(_19); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 +- StorageLive(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 +- _20 = _3; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 +- _19 = &_20; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 +- StorageLive(_35); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _19 = &_3; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + _37 = deref_copy (*_18); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _35 = _37; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageLive(_36); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + _38 = deref_copy (*_19); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _36 = _38; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_39); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _39 = (*_35); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _39 = (*_37); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_40); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _40 = (*_36); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _40 = (*_38); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + _17 = Le(move _39, move _40); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_40); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_39); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_36); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_35); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + StorageDead(_19); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + StorageDead(_18); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + switchInt(move _17) -> [0: bb6, otherwise: bb7]; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + } + + bb3: { + StorageDead(_16); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_7); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageDead(_6); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageDead(_5); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageDead(_4); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageDead(_3); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + return; // scope 0 at $DIR/slice_filter.rs:+0:76: +0:76 + } + + bb4: { + _7 = const false; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + goto -> bb2; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + } + + bb5: { + StorageLive(_12); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:56 + StorageLive(_13); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 + _13 = &_6; // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 + StorageLive(_14); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 +- StorageLive(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 +- _15 = _4; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 +- _14 = &_15; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 +- StorageLive(_41); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _14 = &_4; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + _43 = deref_copy (*_13); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _41 = _43; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageLive(_42); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + _44 = deref_copy (*_14); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _42 = _44; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_45); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _45 = (*_41); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _45 = (*_43); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_46); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _46 = (*_42); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _46 = (*_44); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + _12 = Le(move _45, move _46); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_46); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_45); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_42); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_41); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageDead(_14); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageDead(_13); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + _7 = move _12; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + switchInt(move _7) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + } + + bb6: { + _16 = const false; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + } + + bb7: { + StorageLive(_21); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:76 + StorageLive(_22); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 + _22 = &_4; // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 + StorageLive(_23); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageLive(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- _24 = _6; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- _23 = &_24; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageLive(_47); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _23 = &_6; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _49 = deref_copy (*_22); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _47 = _49; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageLive(_48); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + _50 = deref_copy (*_23); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _48 = _50; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_51); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _51 = (*_47); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _51 = (*_49); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_52); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _52 = (*_48); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _52 = (*_50); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + _21 = Le(move _51, move _52); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_52); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_51); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_48); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_47); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL +- StorageDead(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_23); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_22); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _16 = move _21; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + } + + bb8: { + StorageDead(_21); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_17); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _0 = move _16; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + goto -> bb3; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + } + } + diff --git a/tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff b/tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff index 0f848ec07909b..30b49158b4ff8 100644 --- a/tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff +++ b/tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff @@ -1,7 +1,7 @@ - // MIR for `variant_a::{closure#0}` before DestinationPropagation + // MIR for `variant_a::{closure#0}` after DestinationPropagation - fn variant_a::{closure#0}(_1: &mut [closure@$DIR/slice_filter.rs:14:25: 14:39], _2: &&(usize, usize, usize, usize)) -> bool { + fn variant_a::{closure#0}(_1: &mut [closure@$DIR/slice_filter.rs:8:25: 8:39], _2: &&(usize, usize, usize, usize)) -> bool { let mut _0: bool; // return place in scope 0 at $DIR/slice_filter.rs:+0:40: +0:40 let _3: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 let _4: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 @@ -11,141 +11,100 @@ let mut _8: bool; // in scope 0 at $DIR/slice_filter.rs:+0:40: +0:46 let mut _9: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:40: +0:41 let mut _10: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:45: +0:46 - let _11: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:45: +0:46 - let mut _12: bool; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:56 - let mut _13: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:51 - let mut _14: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:55: +0:56 - let _15: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:55: +0:56 - let mut _16: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:76 - let mut _17: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:66 - let mut _18: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:61 - let mut _19: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:65: +0:66 - let _20: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:65: +0:66 - let mut _21: bool; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:76 - let mut _22: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:71 - let mut _23: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 - let _24: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 - let mut _25: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 - let mut _26: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 - let mut _27: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 - let mut _28: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _11: bool; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:56 + let mut _12: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:51 + let mut _13: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:55: +0:56 + let mut _14: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:76 + let mut _15: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:66 + let mut _16: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:61 + let mut _17: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:65: +0:66 + let mut _18: bool; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:76 + let mut _19: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:71 + let mut _20: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + let mut _21: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _22: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _23: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _24: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 scope 1 { debug a => _3; // in scope 1 at $DIR/slice_filter.rs:+0:27: +0:28 debug b => _4; // in scope 1 at $DIR/slice_filter.rs:+0:30: +0:31 debug c => _5; // in scope 1 at $DIR/slice_filter.rs:+0:33: +0:34 debug d => _6; // in scope 1 at $DIR/slice_filter.rs:+0:36: +0:37 - scope 2 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:14:40: 14:46 + scope 2 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:40: 8:46 debug self => _9; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL debug other => _10; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _29: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _30: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _31: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _32: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _25: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _26: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL scope 3 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL -- debug self => _29; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL -- debug other => _30; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ debug self => _31; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ debug other => _32; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _33: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _34: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug self => _25; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _26; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _27: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _28: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL } } - scope 4 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:14:60: 14:66 - debug self => _18; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - debug other => _19; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _35: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _36: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _37: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _38: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + scope 4 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:60: 8:66 + debug self => _16; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _17; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _29: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _30: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL scope 5 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL -- debug self => _35; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL -- debug other => _36; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ debug self => _37; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ debug other => _38; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _39: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _40: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug self => _29; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _30; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _31: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _32: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL } } - scope 6 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:14:50: 14:56 - debug self => _13; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - debug other => _14; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _41: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _42: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _43: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _44: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + scope 6 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:50: 8:56 + debug self => _12; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _13; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _33: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _34: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL scope 7 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL -- debug self => _41; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL -- debug other => _42; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ debug self => _43; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ debug other => _44; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _45: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _46: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug self => _33; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _34; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _35: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _36: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL } } - scope 8 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:14:70: 14:76 - debug self => _22; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - debug other => _23; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _47: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _48: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _49: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _50: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + scope 8 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:70: 8:76 + debug self => _19; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _20; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _37: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _38: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL scope 9 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL -- debug self => _47; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -- debug other => _48; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ debug self => _49; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ debug other => _50; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _51: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _52: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug self => _37; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _38; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _39: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _40: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL } } } bb0: { - StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 - _25 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 - _3 = &((*_25).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 - StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 - _26 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 - _4 = &((*_26).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 - StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 - _27 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 - _5 = &((*_27).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 - StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 - _28 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 - _6 = &((*_28).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + _21 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + _3 = &((*_21).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + _22 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + _4 = &((*_22).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + _23 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + _5 = &((*_23).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + _24 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + _6 = &((*_24).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 - StorageLive(_7); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + nop; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 StorageLive(_8); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:46 StorageLive(_9); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:41 _9 = &_3; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:41 StorageLive(_10); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 - StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 - _11 = _5; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 - _10 = &_11; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 -- StorageLive(_29); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - _31 = deref_copy (*_9); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _29 = _31; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageLive(_30); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - _32 = deref_copy (*_10); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _30 = _32; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_33); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _33 = (*_29); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _33 = (*_31); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_34); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _34 = (*_30); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _34 = (*_32); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - _8 = Le(move _33, move _34); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_34); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_33); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_30); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_29); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + _10 = &_5; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + _25 = deref_copy (*_9); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + _26 = deref_copy (*_10); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_27); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + _27 = (*_25); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_28); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + _28 = (*_26); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + _8 = Le(move _27, move _28); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_28); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_27); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL StorageDead(_10); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 StorageDead(_9); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 switchInt(move _8) -> [0: bb4, otherwise: bb5]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 @@ -157,159 +116,104 @@ } bb2: { -- StorageLive(_16); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 +- StorageLive(_14); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 - StorageLive(_17); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:66 - StorageLive(_18); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 - _18 = &_5; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 - StorageLive(_19); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 - StorageLive(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 - _20 = _3; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 - _19 = &_20; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 -- StorageLive(_35); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - _37 = deref_copy (*_18); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _35 = _37; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageLive(_36); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - _38 = deref_copy (*_19); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _36 = _38; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_39); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _39 = (*_35); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _39 = (*_37); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_40); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _40 = (*_36); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _40 = (*_38); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - _17 = Le(move _39, move _40); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_40); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_39); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_36); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_35); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 - StorageDead(_19); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 - StorageDead(_18); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 - switchInt(move _17) -> [0: bb6, otherwise: bb7]; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + StorageLive(_15); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:66 + StorageLive(_16); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 + _16 = &_5; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 + StorageLive(_17); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + _17 = &_3; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + _29 = deref_copy (*_16); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + _30 = deref_copy (*_17); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_31); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + _31 = (*_29); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_32); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + _32 = (*_30); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + _15 = Le(move _31, move _32); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_32); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_31); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_17); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + StorageDead(_16); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + switchInt(move _15) -> [0: bb6, otherwise: bb7]; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 } bb3: { -- StorageDead(_16); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageDead(_14); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageDead(_7); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageDead(_6); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageDead(_5); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageDead(_4); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageDead(_3); // scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 return; // scope 0 at $DIR/slice_filter.rs:+0:76: +0:76 } bb4: { -- StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 +- StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + nop; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 goto -> bb2; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 } bb5: { -- StorageLive(_12); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:56 +- StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:56 + nop; // scope 1 at $DIR/slice_filter.rs:+0:50: +0:56 - StorageLive(_13); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 - _13 = &_6; // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 - StorageLive(_14); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 - StorageLive(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 - _15 = _4; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 - _14 = &_15; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 -- StorageLive(_41); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - _43 = deref_copy (*_13); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _41 = _43; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageLive(_42); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - _44 = deref_copy (*_14); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _42 = _44; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_45); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _45 = (*_41); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _45 = (*_43); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_46); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _46 = (*_42); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _46 = (*_44); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - _12 = Le(move _45, move _46); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_46); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_45); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_42); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_41); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 - StorageDead(_14); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageLive(_12); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 + _12 = &_6; // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 + StorageLive(_13); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + _13 = &_4; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + _33 = deref_copy (*_12); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + _34 = deref_copy (*_13); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_35); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + _35 = (*_33); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_36); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + _36 = (*_34); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + _11 = Le(move _35, move _36); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_36); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_35); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL StorageDead(_13); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 -- _7 = move _12; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 -- StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 +- _7 = move _11; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 +- StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + nop; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + nop; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 - switchInt(move _7) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 -+ switchInt(move _12) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 ++ switchInt(move _11) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 } bb6: { -- _16 = const false; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 +- _14 = const false; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + _0 = const false; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 } bb7: { -- StorageLive(_21); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:76 +- StorageLive(_18); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:70: +0:76 - StorageLive(_22); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 - _22 = &_4; // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 - StorageLive(_23); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageLive(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - _24 = _6; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - _23 = &_24; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 -- StorageLive(_47); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - _49 = deref_copy (*_22); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _47 = _49; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageLive(_48); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - _50 = deref_copy (*_23); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _48 = _50; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_51); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _51 = (*_47); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _51 = (*_49); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_52); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _52 = (*_48); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _21 = Le(move _51, move _52); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _52 = (*_50); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _0 = Le(move _51, move _52); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_52); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_51); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_48); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_47); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ nop; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageDead(_23); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageDead(_22); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 -- _16 = move _21; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + StorageLive(_19); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 + _19 = &_4; // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 + StorageLive(_20); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _20 = &_6; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _37 = deref_copy (*_19); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + _38 = deref_copy (*_20); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_39); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + _39 = (*_37); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_40); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + _40 = (*_38); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _18 = Le(move _39, move _40); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _0 = Le(move _39, move _40); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_40); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_39); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_20); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_19); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- _14 = move _18; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 } bb8: { -- StorageDead(_21); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageDead(_18); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageDead(_17); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 -- _0 = move _16; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + StorageDead(_15); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- _0 = move _14; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 goto -> bb3; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 } diff --git a/tests/mir-opt/slice_filter.variant_b-{closure#0}.CopyProp.diff b/tests/mir-opt/slice_filter.variant_b-{closure#0}.CopyProp.diff new file mode 100644 index 0000000000000..5e4bdbdfa2e2f --- /dev/null +++ b/tests/mir-opt/slice_filter.variant_b-{closure#0}.CopyProp.diff @@ -0,0 +1,139 @@ +- // MIR for `variant_b::{closure#0}` before CopyProp ++ // MIR for `variant_b::{closure#0}` after CopyProp + + fn variant_b::{closure#0}(_1: &mut [closure@$DIR/slice_filter.rs:12:25: 12:41], _2: &&(usize, usize, usize, usize)) -> bool { + let mut _0: bool; // return place in scope 0 at $DIR/slice_filter.rs:+0:42: +0:42 + let _3: usize; // in scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 + let _4: usize; // in scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 + let _5: usize; // in scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 + let _6: usize; // in scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 + let mut _7: bool; // in scope 0 at $DIR/slice_filter.rs:+0:42: +0:58 + let mut _8: bool; // in scope 0 at $DIR/slice_filter.rs:+0:42: +0:48 + let mut _9: usize; // in scope 0 at $DIR/slice_filter.rs:+0:42: +0:43 + let mut _10: usize; // in scope 0 at $DIR/slice_filter.rs:+0:47: +0:48 + let mut _11: bool; // in scope 0 at $DIR/slice_filter.rs:+0:52: +0:58 + let mut _12: usize; // in scope 0 at $DIR/slice_filter.rs:+0:52: +0:53 + let mut _13: usize; // in scope 0 at $DIR/slice_filter.rs:+0:57: +0:58 + let mut _14: bool; // in scope 0 at $DIR/slice_filter.rs:+0:62: +0:78 + let mut _15: bool; // in scope 0 at $DIR/slice_filter.rs:+0:62: +0:68 + let mut _16: usize; // in scope 0 at $DIR/slice_filter.rs:+0:62: +0:63 + let mut _17: usize; // in scope 0 at $DIR/slice_filter.rs:+0:67: +0:68 + let mut _18: bool; // in scope 0 at $DIR/slice_filter.rs:+0:72: +0:78 + let mut _19: usize; // in scope 0 at $DIR/slice_filter.rs:+0:72: +0:73 + let mut _20: usize; // in scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 + let mut _21: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + let mut _22: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + let mut _23: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + let mut _24: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + scope 1 { + debug a => _3; // in scope 1 at $DIR/slice_filter.rs:+0:29: +0:30 + debug b => _4; // in scope 1 at $DIR/slice_filter.rs:+0:32: +0:33 + debug c => _5; // in scope 1 at $DIR/slice_filter.rs:+0:35: +0:36 + debug d => _6; // in scope 1 at $DIR/slice_filter.rs:+0:38: +0:39 + } + + bb0: { +- StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 + _21 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 + _3 = ((*_21).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 +- StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 + _22 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 + _4 = ((*_22).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 +- StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 + _23 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 + _5 = ((*_23).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 +- StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 + _24 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 + _6 = ((*_24).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 + StorageLive(_7); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 + StorageLive(_8); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:48 +- StorageLive(_9); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:43 +- _9 = _3; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:43 +- StorageLive(_10); // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 +- _10 = _5; // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 +- _8 = Le(move _9, move _10); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:48 +- StorageDead(_10); // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 +- StorageDead(_9); // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 ++ _8 = Le(_3, _5); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:48 + switchInt(move _8) -> [0: bb4, otherwise: bb5]; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 + } + + bb1: { + _0 = const true; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + goto -> bb3; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + } + + bb2: { + StorageLive(_14); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + StorageLive(_15); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:68 +- StorageLive(_16); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:63 +- _16 = _5; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:63 +- StorageLive(_17); // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 +- _17 = _3; // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 +- _15 = Le(move _16, move _17); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:68 +- StorageDead(_17); // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 +- StorageDead(_16); // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 ++ _15 = Le(_5, _3); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:68 + switchInt(move _15) -> [0: bb6, otherwise: bb7]; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + } + + bb3: { + StorageDead(_14); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 + StorageDead(_7); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_6); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_5); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_4); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_3); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 + return; // scope 0 at $DIR/slice_filter.rs:+0:78: +0:78 + } + + bb4: { + _7 = const false; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 + StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + goto -> bb2; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 + } + + bb5: { + StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:58 +- StorageLive(_12); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:53 +- _12 = _6; // scope 1 at $DIR/slice_filter.rs:+0:52: +0:53 +- StorageLive(_13); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 +- _13 = _4; // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 +- _11 = Le(move _12, move _13); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:58 +- StorageDead(_13); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 +- StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 ++ _11 = Le(_6, _4); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:58 + _7 = move _11; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 + StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + switchInt(move _7) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + } + + bb6: { + _14 = const false; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + } + + bb7: { + StorageLive(_18); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 +- StorageLive(_19); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:73 +- _19 = _4; // scope 1 at $DIR/slice_filter.rs:+0:72: +0:73 +- StorageLive(_20); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- _20 = _6; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- _18 = Le(move _19, move _20); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 +- StorageDead(_20); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_19); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 ++ _18 = Le(_4, _6); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 + _14 = move _18; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + } + + bb8: { + StorageDead(_18); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 + StorageDead(_15); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 + _0 = move _14; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + goto -> bb3; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + } + } + diff --git a/tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff b/tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff index a0c4b4f652c47..45af6600cd4e8 100644 --- a/tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff +++ b/tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff @@ -1,7 +1,7 @@ - // MIR for `variant_b::{closure#0}` before DestinationPropagation + // MIR for `variant_b::{closure#0}` after DestinationPropagation - fn variant_b::{closure#0}(_1: &mut [closure@$DIR/slice_filter.rs:20:25: 20:41], _2: &&(usize, usize, usize, usize)) -> bool { + fn variant_b::{closure#0}(_1: &mut [closure@$DIR/slice_filter.rs:12:25: 12:41], _2: &&(usize, usize, usize, usize)) -> bool { let mut _0: bool; // return place in scope 0 at $DIR/slice_filter.rs:+0:42: +0:42 let _3: usize; // in scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 let _4: usize; // in scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 @@ -9,66 +9,34 @@ let _6: usize; // in scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 let mut _7: bool; // in scope 0 at $DIR/slice_filter.rs:+0:42: +0:58 let mut _8: bool; // in scope 0 at $DIR/slice_filter.rs:+0:42: +0:48 - let mut _9: usize; // in scope 0 at $DIR/slice_filter.rs:+0:42: +0:43 - let mut _10: usize; // in scope 0 at $DIR/slice_filter.rs:+0:47: +0:48 - let mut _11: bool; // in scope 0 at $DIR/slice_filter.rs:+0:52: +0:58 - let mut _12: usize; // in scope 0 at $DIR/slice_filter.rs:+0:52: +0:53 - let mut _13: usize; // in scope 0 at $DIR/slice_filter.rs:+0:57: +0:58 - let mut _14: bool; // in scope 0 at $DIR/slice_filter.rs:+0:62: +0:78 - let mut _15: bool; // in scope 0 at $DIR/slice_filter.rs:+0:62: +0:68 - let mut _16: usize; // in scope 0 at $DIR/slice_filter.rs:+0:62: +0:63 - let mut _17: usize; // in scope 0 at $DIR/slice_filter.rs:+0:67: +0:68 - let mut _18: bool; // in scope 0 at $DIR/slice_filter.rs:+0:72: +0:78 - let mut _19: usize; // in scope 0 at $DIR/slice_filter.rs:+0:72: +0:73 - let mut _20: usize; // in scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 - let mut _21: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 - let mut _22: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 - let mut _23: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 - let mut _24: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + let mut _9: bool; // in scope 0 at $DIR/slice_filter.rs:+0:52: +0:58 + let mut _10: bool; // in scope 0 at $DIR/slice_filter.rs:+0:62: +0:78 + let mut _11: bool; // in scope 0 at $DIR/slice_filter.rs:+0:62: +0:68 + let mut _12: bool; // in scope 0 at $DIR/slice_filter.rs:+0:72: +0:78 + let mut _13: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + let mut _14: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + let mut _15: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 + let mut _16: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:40 scope 1 { -- debug a => _3; // in scope 1 at $DIR/slice_filter.rs:+0:29: +0:30 -- debug b => _4; // in scope 1 at $DIR/slice_filter.rs:+0:32: +0:33 -- debug c => _5; // in scope 1 at $DIR/slice_filter.rs:+0:35: +0:36 -- debug d => _6; // in scope 1 at $DIR/slice_filter.rs:+0:38: +0:39 -+ debug a => _17; // in scope 1 at $DIR/slice_filter.rs:+0:29: +0:30 -+ debug b => _19; // in scope 1 at $DIR/slice_filter.rs:+0:32: +0:33 -+ debug c => _16; // in scope 1 at $DIR/slice_filter.rs:+0:35: +0:36 -+ debug d => _20; // in scope 1 at $DIR/slice_filter.rs:+0:38: +0:39 + debug a => _3; // in scope 1 at $DIR/slice_filter.rs:+0:29: +0:30 + debug b => _4; // in scope 1 at $DIR/slice_filter.rs:+0:32: +0:33 + debug c => _5; // in scope 1 at $DIR/slice_filter.rs:+0:35: +0:36 + debug d => _6; // in scope 1 at $DIR/slice_filter.rs:+0:38: +0:39 } bb0: { -- StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 -+ nop; // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 - _21 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 -- _3 = ((*_21).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 -- StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 -+ _17 = ((*_21).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 -+ nop; // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 - _22 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 -- _4 = ((*_22).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 -- StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 -+ _19 = ((*_22).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 -+ nop; // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 - _23 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 -- _5 = ((*_23).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 -- StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 -+ _16 = ((*_23).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 -+ nop; // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 - _24 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 -- _6 = ((*_24).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 + _13 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 + _3 = ((*_13).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 + _14 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 + _4 = ((*_14).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 + _15 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 + _5 = ((*_15).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 + _16 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 + _6 = ((*_16).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 - StorageLive(_7); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 -+ _20 = ((*_24).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 + nop; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 StorageLive(_8); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:48 - StorageLive(_9); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:43 -- _9 = _3; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:43 -+ _9 = _17; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:43 - StorageLive(_10); // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 -- _10 = _5; // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 -+ _10 = _16; // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 - _8 = Le(move _9, move _10); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:48 - StorageDead(_10); // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 - StorageDead(_9); // scope 1 at $DIR/slice_filter.rs:+0:47: +0:48 + _8 = Le(_3, _5); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:48 switchInt(move _8) -> [0: bb4, otherwise: bb5]; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 } @@ -78,102 +46,62 @@ } bb2: { -- StorageLive(_14); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 +- StorageLive(_10); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + nop; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 - StorageLive(_15); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:68 -- StorageLive(_16); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:63 -- _16 = _5; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:63 -- StorageLive(_17); // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 -- _17 = _3; // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:63 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:63 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 - _15 = Le(move _16, move _17); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:68 -- StorageDead(_17); // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 -- StorageDead(_16); // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:67: +0:68 - switchInt(move _15) -> [0: bb6, otherwise: bb7]; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:68 + _11 = Le(_5, _3); // scope 1 at $DIR/slice_filter.rs:+0:62: +0:68 + switchInt(move _11) -> [0: bb6, otherwise: bb7]; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 } bb3: { -- StorageDead(_14); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_10); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 - StorageDead(_7); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 -- StorageDead(_6); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 -- StorageDead(_5); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 -- StorageDead(_4); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 -- StorageDead(_3); // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 + nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 + nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 -+ nop; // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 -+ nop; // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 -+ nop; // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 -+ nop; // scope 0 at $DIR/slice_filter.rs:+0:77: +0:78 return; // scope 0 at $DIR/slice_filter.rs:+0:78: +0:78 } bb4: { -- StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 +- StorageDead(_9); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + nop; // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 goto -> bb2; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 } bb5: { -- StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:58 +- StorageLive(_9); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:58 + nop; // scope 1 at $DIR/slice_filter.rs:+0:52: +0:58 - StorageLive(_12); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:53 -- _12 = _6; // scope 1 at $DIR/slice_filter.rs:+0:52: +0:53 -+ _12 = _20; // scope 1 at $DIR/slice_filter.rs:+0:52: +0:53 - StorageLive(_13); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 -- _13 = _4; // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 -+ _13 = _19; // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 - _11 = Le(move _12, move _13); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:58 - StorageDead(_13); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 - StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 -- _7 = move _11; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 -- StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + _9 = Le(_6, _4); // scope 1 at $DIR/slice_filter.rs:+0:52: +0:58 +- _7 = move _9; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 +- StorageDead(_9); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 + nop; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 + nop; // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:57: +0:58 - switchInt(move _7) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 -+ switchInt(move _11) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 ++ switchInt(move _9) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 } bb6: { -- _14 = const false; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 +- _10 = const false; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + _0 = const false; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 } bb7: { -- StorageLive(_18); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 -- StorageLive(_19); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:73 -- _19 = _4; // scope 1 at $DIR/slice_filter.rs:+0:72: +0:73 -- StorageLive(_20); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 -- _20 = _6; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 -- _18 = Le(move _19, move _20); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 -- StorageDead(_20); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 -- StorageDead(_19); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 -- _14 = move _18; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 +- StorageLive(_12); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 +- _12 = Le(_4, _6); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 +- _10 = move _12; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 + nop; // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:72: +0:73 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:72: +0:73 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 -+ _0 = Le(move _19, move _20); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 -+ nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 ++ _0 = Le(_4, _6); // scope 1 at $DIR/slice_filter.rs:+0:72: +0:78 + nop; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:62: +0:78 } bb8: { -- StorageDead(_18); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 + nop; // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 - StorageDead(_15); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 -- _0 = move _14; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:77: +0:78 +- _0 = move _10; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 + nop; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 goto -> bb3; // scope 1 at $DIR/slice_filter.rs:+0:42: +0:78 } diff --git a/tests/mir-opt/try_identity_e2e.new.PreCodegen.after.mir b/tests/mir-opt/try_identity_e2e.new.PreCodegen.after.mir index b254bfeb7c992..a4d2660ca6aeb 100644 --- a/tests/mir-opt/try_identity_e2e.new.PreCodegen.after.mir +++ b/tests/mir-opt/try_identity_e2e.new.PreCodegen.after.mir @@ -5,11 +5,11 @@ fn new(_1: Result) -> Result { let mut _0: std::result::Result; // return place in scope 0 at $DIR/try_identity_e2e.rs:+0:34: +0:46 let mut _2: std::ops::ControlFlow; // in scope 0 at $DIR/try_identity_e2e.rs:+2:15: +7:10 let mut _3: isize; // in scope 0 at $DIR/try_identity_e2e.rs:+4:17: +4:22 - let mut _4: T; // in scope 0 at $DIR/try_identity_e2e.rs:+4:48: +4:49 - let mut _5: E; // in scope 0 at $DIR/try_identity_e2e.rs:+5:46: +5:47 + let _4: T; // in scope 0 at $DIR/try_identity_e2e.rs:+4:20: +4:21 + let _5: E; // in scope 0 at $DIR/try_identity_e2e.rs:+5:21: +5:22 let mut _6: isize; // in scope 0 at $DIR/try_identity_e2e.rs:+8:13: +8:37 let _7: T; // in scope 0 at $DIR/try_identity_e2e.rs:+8:35: +8:36 - let mut _8: E; // in scope 0 at $DIR/try_identity_e2e.rs:+9:49: +9:50 + let _8: E; // in scope 0 at $DIR/try_identity_e2e.rs:+9:32: +9:33 scope 1 { debug v => _4; // in scope 1 at $DIR/try_identity_e2e.rs:+4:20: +4:21 } diff --git a/tests/mir-opt/try_identity_e2e.old.PreCodegen.after.mir b/tests/mir-opt/try_identity_e2e.old.PreCodegen.after.mir index cdbc0681cb8a3..37851c66a6076 100644 --- a/tests/mir-opt/try_identity_e2e.old.PreCodegen.after.mir +++ b/tests/mir-opt/try_identity_e2e.old.PreCodegen.after.mir @@ -5,7 +5,7 @@ fn old(_1: Result) -> Result { let mut _0: std::result::Result; // return place in scope 0 at $DIR/try_identity_e2e.rs:+0:34: +0:46 let mut _2: isize; // in scope 0 at $DIR/try_identity_e2e.rs:+3:13: +3:18 let _3: T; // in scope 0 at $DIR/try_identity_e2e.rs:+3:16: +3:17 - let mut _4: E; // in scope 0 at $DIR/try_identity_e2e.rs:+4:34: +4:35 + let _4: E; // in scope 0 at $DIR/try_identity_e2e.rs:+4:17: +4:18 scope 1 { debug v => _3; // in scope 1 at $DIR/try_identity_e2e.rs:+3:16: +3:17 } diff --git a/tests/mir-opt/while_storage.while_loop.PreCodegen.after.mir b/tests/mir-opt/while_storage.while_loop.PreCodegen.after.mir index b95d91b13dd79..318119bd477c1 100644 --- a/tests/mir-opt/while_storage.while_loop.PreCodegen.after.mir +++ b/tests/mir-opt/while_storage.while_loop.PreCodegen.after.mir @@ -4,9 +4,7 @@ fn while_loop(_1: bool) -> () { debug c => _1; // in scope 0 at $DIR/while_storage.rs:+0:15: +0:16 let mut _0: (); // return place in scope 0 at $DIR/while_storage.rs:+0:24: +0:24 let mut _2: bool; // in scope 0 at $DIR/while_storage.rs:+1:11: +1:22 - let mut _3: bool; // in scope 0 at $DIR/while_storage.rs:+1:20: +1:21 - let mut _4: bool; // in scope 0 at $DIR/while_storage.rs:+2:12: +2:23 - let mut _5: bool; // in scope 0 at $DIR/while_storage.rs:+2:21: +2:22 + let mut _3: bool; // in scope 0 at $DIR/while_storage.rs:+2:12: +2:23 bb0: { goto -> bb1; // scope 0 at $DIR/while_storage.rs:+1:5: +5:6 @@ -14,41 +12,35 @@ fn while_loop(_1: bool) -> () { bb1: { StorageLive(_2); // scope 0 at $DIR/while_storage.rs:+1:11: +1:22 - StorageLive(_3); // scope 0 at $DIR/while_storage.rs:+1:20: +1:21 - _3 = _1; // scope 0 at $DIR/while_storage.rs:+1:20: +1:21 - _2 = get_bool(move _3) -> bb2; // scope 0 at $DIR/while_storage.rs:+1:11: +1:22 + _2 = get_bool(_1) -> bb2; // scope 0 at $DIR/while_storage.rs:+1:11: +1:22 // mir::Constant // + span: $DIR/while_storage.rs:10:11: 10:19 // + literal: Const { ty: fn(bool) -> bool {get_bool}, val: Value() } } bb2: { - StorageDead(_3); // scope 0 at $DIR/while_storage.rs:+1:21: +1:22 switchInt(move _2) -> [0: bb7, otherwise: bb3]; // scope 0 at $DIR/while_storage.rs:+1:11: +1:22 } bb3: { - StorageLive(_4); // scope 0 at $DIR/while_storage.rs:+2:12: +2:23 - StorageLive(_5); // scope 0 at $DIR/while_storage.rs:+2:21: +2:22 - _5 = _1; // scope 0 at $DIR/while_storage.rs:+2:21: +2:22 - _4 = get_bool(move _5) -> bb4; // scope 0 at $DIR/while_storage.rs:+2:12: +2:23 + StorageLive(_3); // scope 0 at $DIR/while_storage.rs:+2:12: +2:23 + _3 = get_bool(_1) -> bb4; // scope 0 at $DIR/while_storage.rs:+2:12: +2:23 // mir::Constant // + span: $DIR/while_storage.rs:11:12: 11:20 // + literal: Const { ty: fn(bool) -> bool {get_bool}, val: Value() } } bb4: { - StorageDead(_5); // scope 0 at $DIR/while_storage.rs:+2:22: +2:23 - switchInt(move _4) -> [0: bb6, otherwise: bb5]; // scope 0 at $DIR/while_storage.rs:+2:12: +2:23 + switchInt(move _3) -> [0: bb6, otherwise: bb5]; // scope 0 at $DIR/while_storage.rs:+2:12: +2:23 } bb5: { - StorageDead(_4); // scope 0 at $DIR/while_storage.rs:+4:9: +4:10 + StorageDead(_3); // scope 0 at $DIR/while_storage.rs:+4:9: +4:10 goto -> bb7; // scope 0 at no-location } bb6: { - StorageDead(_4); // scope 0 at $DIR/while_storage.rs:+4:9: +4:10 + StorageDead(_3); // scope 0 at $DIR/while_storage.rs:+4:9: +4:10 StorageDead(_2); // scope 0 at $DIR/while_storage.rs:+5:5: +5:6 goto -> bb1; // scope 0 at $DIR/while_storage.rs:+1:5: +5:6 } From 38b55dc68459bf68cd5489b8c5d808b6902c83d1 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 15 Jan 2023 15:30:09 +0000 Subject: [PATCH 421/500] Add tests. --- .../copy-prop/branch.foo.CopyProp.diff | 65 +++++++++++++++++++ tests/mir-opt/copy-prop/branch.rs | 27 ++++++++ ...copy_propagation_arg.arg_src.CopyProp.diff | 21 ++++++ .../copy_propagation_arg.bar.CopyProp.diff | 28 ++++++++ .../copy_propagation_arg.baz.CopyProp.diff | 18 +++++ .../copy_propagation_arg.foo.CopyProp.diff | 28 ++++++++ .../mir-opt/copy-prop/copy_propagation_arg.rs | 40 ++++++++++++ .../copy-prop/cycle.main.CopyProp.diff | 60 +++++++++++++++++ tests/mir-opt/copy-prop/cycle.rs | 15 +++++ .../dead_stores_79191.f.CopyProp.after.mir | 29 +++++++++ tests/mir-opt/copy-prop/dead_stores_79191.rs | 17 +++++ .../dead_stores_better.f.CopyProp.after.mir | 29 +++++++++ tests/mir-opt/copy-prop/dead_stores_better.rs | 21 ++++++ .../copy-prop/move_arg.f.CopyProp.diff | 40 ++++++++++++ tests/mir-opt/copy-prop/move_arg.rs | 15 +++++ 15 files changed, 453 insertions(+) create mode 100644 tests/mir-opt/copy-prop/branch.foo.CopyProp.diff create mode 100644 tests/mir-opt/copy-prop/branch.rs create mode 100644 tests/mir-opt/copy-prop/copy_propagation_arg.arg_src.CopyProp.diff create mode 100644 tests/mir-opt/copy-prop/copy_propagation_arg.bar.CopyProp.diff create mode 100644 tests/mir-opt/copy-prop/copy_propagation_arg.baz.CopyProp.diff create mode 100644 tests/mir-opt/copy-prop/copy_propagation_arg.foo.CopyProp.diff create mode 100644 tests/mir-opt/copy-prop/copy_propagation_arg.rs create mode 100644 tests/mir-opt/copy-prop/cycle.main.CopyProp.diff create mode 100644 tests/mir-opt/copy-prop/cycle.rs create mode 100644 tests/mir-opt/copy-prop/dead_stores_79191.f.CopyProp.after.mir create mode 100644 tests/mir-opt/copy-prop/dead_stores_79191.rs create mode 100644 tests/mir-opt/copy-prop/dead_stores_better.f.CopyProp.after.mir create mode 100644 tests/mir-opt/copy-prop/dead_stores_better.rs create mode 100644 tests/mir-opt/copy-prop/move_arg.f.CopyProp.diff create mode 100644 tests/mir-opt/copy-prop/move_arg.rs diff --git a/tests/mir-opt/copy-prop/branch.foo.CopyProp.diff b/tests/mir-opt/copy-prop/branch.foo.CopyProp.diff new file mode 100644 index 0000000000000..8b116532d9f5d --- /dev/null +++ b/tests/mir-opt/copy-prop/branch.foo.CopyProp.diff @@ -0,0 +1,65 @@ +- // MIR for `foo` before CopyProp ++ // MIR for `foo` after CopyProp + + fn foo() -> i32 { + let mut _0: i32; // return place in scope 0 at $DIR/branch.rs:+0:13: +0:16 + let _1: i32; // in scope 0 at $DIR/branch.rs:+1:9: +1:10 + let mut _3: bool; // in scope 0 at $DIR/branch.rs:+3:16: +3:22 + let _4: i32; // in scope 0 at $DIR/branch.rs:+6:9: +6:14 + scope 1 { + debug x => _1; // in scope 1 at $DIR/branch.rs:+1:9: +1:10 + let _2: i32; // in scope 1 at $DIR/branch.rs:+3:9: +3:10 + scope 2 { + debug y => _2; // in scope 2 at $DIR/branch.rs:+3:9: +3:10 + } + } + + bb0: { + StorageLive(_1); // scope 0 at $DIR/branch.rs:+1:9: +1:10 + _1 = val() -> bb1; // scope 0 at $DIR/branch.rs:+1:13: +1:18 + // mir::Constant + // + span: $DIR/branch.rs:13:13: 13:16 + // + literal: Const { ty: fn() -> i32 {val}, val: Value() } + } + + bb1: { + StorageLive(_2); // scope 1 at $DIR/branch.rs:+3:9: +3:10 + StorageLive(_3); // scope 1 at $DIR/branch.rs:+3:16: +3:22 + _3 = cond() -> bb2; // scope 1 at $DIR/branch.rs:+3:16: +3:22 + // mir::Constant + // + span: $DIR/branch.rs:15:16: 15:20 + // + literal: Const { ty: fn() -> bool {cond}, val: Value() } + } + + bb2: { + switchInt(move _3) -> [0: bb4, otherwise: bb3]; // scope 1 at $DIR/branch.rs:+3:16: +3:22 + } + + bb3: { + _2 = _1; // scope 1 at $DIR/branch.rs:+4:9: +4:10 + goto -> bb6; // scope 1 at $DIR/branch.rs:+3:13: +8:6 + } + + bb4: { + StorageLive(_4); // scope 1 at $DIR/branch.rs:+6:9: +6:14 + _4 = val() -> bb5; // scope 1 at $DIR/branch.rs:+6:9: +6:14 + // mir::Constant + // + span: $DIR/branch.rs:18:9: 18:12 + // + literal: Const { ty: fn() -> i32 {val}, val: Value() } + } + + bb5: { + StorageDead(_4); // scope 1 at $DIR/branch.rs:+6:14: +6:15 + _2 = _1; // scope 1 at $DIR/branch.rs:+7:9: +7:10 + goto -> bb6; // scope 1 at $DIR/branch.rs:+3:13: +8:6 + } + + bb6: { + StorageDead(_3); // scope 1 at $DIR/branch.rs:+8:5: +8:6 + _0 = _2; // scope 2 at $DIR/branch.rs:+10:5: +10:6 + StorageDead(_2); // scope 1 at $DIR/branch.rs:+11:1: +11:2 + StorageDead(_1); // scope 0 at $DIR/branch.rs:+11:1: +11:2 + return; // scope 0 at $DIR/branch.rs:+11:2: +11:2 + } + } + diff --git a/tests/mir-opt/copy-prop/branch.rs b/tests/mir-opt/copy-prop/branch.rs new file mode 100644 index 0000000000000..50b1e00fad4f7 --- /dev/null +++ b/tests/mir-opt/copy-prop/branch.rs @@ -0,0 +1,27 @@ +//! Tests that we bail out when there are multiple assignments to the same local. +// unit-test: CopyProp +fn val() -> i32 { + 1 +} + +fn cond() -> bool { + true +} + +// EMIT_MIR branch.foo.CopyProp.diff +fn foo() -> i32 { + let x = val(); + + let y = if cond() { + x + } else { + val(); + x + }; + + y +} + +fn main() { + foo(); +} diff --git a/tests/mir-opt/copy-prop/copy_propagation_arg.arg_src.CopyProp.diff b/tests/mir-opt/copy-prop/copy_propagation_arg.arg_src.CopyProp.diff new file mode 100644 index 0000000000000..69acebf7642e9 --- /dev/null +++ b/tests/mir-opt/copy-prop/copy_propagation_arg.arg_src.CopyProp.diff @@ -0,0 +1,21 @@ +- // MIR for `arg_src` before CopyProp ++ // MIR for `arg_src` after CopyProp + + fn arg_src(_1: i32) -> i32 { + debug x => _1; // in scope 0 at $DIR/copy_propagation_arg.rs:+0:12: +0:17 + let mut _0: i32; // return place in scope 0 at $DIR/copy_propagation_arg.rs:+0:27: +0:30 + let _2: i32; // in scope 0 at $DIR/copy_propagation_arg.rs:+1:9: +1:10 + scope 1 { + debug y => _2; // in scope 1 at $DIR/copy_propagation_arg.rs:+1:9: +1:10 + } + + bb0: { + StorageLive(_2); // scope 0 at $DIR/copy_propagation_arg.rs:+1:9: +1:10 + _2 = _1; // scope 0 at $DIR/copy_propagation_arg.rs:+1:13: +1:14 + _1 = const 123_i32; // scope 1 at $DIR/copy_propagation_arg.rs:+2:5: +2:12 + _0 = _2; // scope 1 at $DIR/copy_propagation_arg.rs:+3:5: +3:6 + StorageDead(_2); // scope 0 at $DIR/copy_propagation_arg.rs:+4:1: +4:2 + return; // scope 0 at $DIR/copy_propagation_arg.rs:+4:2: +4:2 + } + } + diff --git a/tests/mir-opt/copy-prop/copy_propagation_arg.bar.CopyProp.diff b/tests/mir-opt/copy-prop/copy_propagation_arg.bar.CopyProp.diff new file mode 100644 index 0000000000000..ac4e9a2bfa735 --- /dev/null +++ b/tests/mir-opt/copy-prop/copy_propagation_arg.bar.CopyProp.diff @@ -0,0 +1,28 @@ +- // MIR for `bar` before CopyProp ++ // MIR for `bar` after CopyProp + + fn bar(_1: u8) -> () { + debug x => _1; // in scope 0 at $DIR/copy_propagation_arg.rs:+0:8: +0:13 + let mut _0: (); // return place in scope 0 at $DIR/copy_propagation_arg.rs:+0:19: +0:19 + let _2: u8; // in scope 0 at $DIR/copy_propagation_arg.rs:+1:5: +1:13 + let mut _3: u8; // in scope 0 at $DIR/copy_propagation_arg.rs:+1:11: +1:12 + + bb0: { + StorageLive(_2); // scope 0 at $DIR/copy_propagation_arg.rs:+1:5: +1:13 + StorageLive(_3); // scope 0 at $DIR/copy_propagation_arg.rs:+1:11: +1:12 + _3 = _1; // scope 0 at $DIR/copy_propagation_arg.rs:+1:11: +1:12 + _2 = dummy(move _3) -> bb1; // scope 0 at $DIR/copy_propagation_arg.rs:+1:5: +1:13 + // mir::Constant + // + span: $DIR/copy_propagation_arg.rs:16:5: 16:10 + // + literal: Const { ty: fn(u8) -> u8 {dummy}, val: Value() } + } + + bb1: { + StorageDead(_3); // scope 0 at $DIR/copy_propagation_arg.rs:+1:12: +1:13 + StorageDead(_2); // scope 0 at $DIR/copy_propagation_arg.rs:+1:13: +1:14 + _1 = const 5_u8; // scope 0 at $DIR/copy_propagation_arg.rs:+2:5: +2:10 + _0 = const (); // scope 0 at $DIR/copy_propagation_arg.rs:+0:19: +3:2 + return; // scope 0 at $DIR/copy_propagation_arg.rs:+3:2: +3:2 + } + } + diff --git a/tests/mir-opt/copy-prop/copy_propagation_arg.baz.CopyProp.diff b/tests/mir-opt/copy-prop/copy_propagation_arg.baz.CopyProp.diff new file mode 100644 index 0000000000000..7ab6ebb7d53e0 --- /dev/null +++ b/tests/mir-opt/copy-prop/copy_propagation_arg.baz.CopyProp.diff @@ -0,0 +1,18 @@ +- // MIR for `baz` before CopyProp ++ // MIR for `baz` after CopyProp + + fn baz(_1: i32) -> i32 { + debug x => _1; // in scope 0 at $DIR/copy_propagation_arg.rs:+0:8: +0:13 + let mut _0: i32; // return place in scope 0 at $DIR/copy_propagation_arg.rs:+0:23: +0:26 + let mut _2: i32; // in scope 0 at $DIR/copy_propagation_arg.rs:+2:9: +2:10 + + bb0: { + StorageLive(_2); // scope 0 at $DIR/copy_propagation_arg.rs:+2:9: +2:10 + _2 = _1; // scope 0 at $DIR/copy_propagation_arg.rs:+2:9: +2:10 + _1 = move _2; // scope 0 at $DIR/copy_propagation_arg.rs:+2:5: +2:10 + StorageDead(_2); // scope 0 at $DIR/copy_propagation_arg.rs:+2:9: +2:10 + _0 = _1; // scope 0 at $DIR/copy_propagation_arg.rs:+3:5: +3:6 + return; // scope 0 at $DIR/copy_propagation_arg.rs:+4:2: +4:2 + } + } + diff --git a/tests/mir-opt/copy-prop/copy_propagation_arg.foo.CopyProp.diff b/tests/mir-opt/copy-prop/copy_propagation_arg.foo.CopyProp.diff new file mode 100644 index 0000000000000..0a3e985e7c260 --- /dev/null +++ b/tests/mir-opt/copy-prop/copy_propagation_arg.foo.CopyProp.diff @@ -0,0 +1,28 @@ +- // MIR for `foo` before CopyProp ++ // MIR for `foo` after CopyProp + + fn foo(_1: u8) -> () { + debug x => _1; // in scope 0 at $DIR/copy_propagation_arg.rs:+0:8: +0:13 + let mut _0: (); // return place in scope 0 at $DIR/copy_propagation_arg.rs:+0:19: +0:19 + let mut _2: u8; // in scope 0 at $DIR/copy_propagation_arg.rs:+2:9: +2:17 + let mut _3: u8; // in scope 0 at $DIR/copy_propagation_arg.rs:+2:15: +2:16 + + bb0: { + StorageLive(_2); // scope 0 at $DIR/copy_propagation_arg.rs:+2:9: +2:17 + StorageLive(_3); // scope 0 at $DIR/copy_propagation_arg.rs:+2:15: +2:16 + _3 = _1; // scope 0 at $DIR/copy_propagation_arg.rs:+2:15: +2:16 + _2 = dummy(move _3) -> bb1; // scope 0 at $DIR/copy_propagation_arg.rs:+2:9: +2:17 + // mir::Constant + // + span: $DIR/copy_propagation_arg.rs:11:9: 11:14 + // + literal: Const { ty: fn(u8) -> u8 {dummy}, val: Value() } + } + + bb1: { + StorageDead(_3); // scope 0 at $DIR/copy_propagation_arg.rs:+2:16: +2:17 + _1 = move _2; // scope 0 at $DIR/copy_propagation_arg.rs:+2:5: +2:17 + StorageDead(_2); // scope 0 at $DIR/copy_propagation_arg.rs:+2:16: +2:17 + _0 = const (); // scope 0 at $DIR/copy_propagation_arg.rs:+0:19: +3:2 + return; // scope 0 at $DIR/copy_propagation_arg.rs:+3:2: +3:2 + } + } + diff --git a/tests/mir-opt/copy-prop/copy_propagation_arg.rs b/tests/mir-opt/copy-prop/copy_propagation_arg.rs new file mode 100644 index 0000000000000..cc98985f1fda6 --- /dev/null +++ b/tests/mir-opt/copy-prop/copy_propagation_arg.rs @@ -0,0 +1,40 @@ +// Check that CopyProp does not propagate an assignment to a function argument +// (doing so can break usages of the original argument value) +// unit-test: CopyProp +fn dummy(x: u8) -> u8 { + x +} + +// EMIT_MIR copy_propagation_arg.foo.CopyProp.diff +fn foo(mut x: u8) { + // calling `dummy` to make a use of `x` that copyprop cannot eliminate + x = dummy(x); // this will assign a local to `x` +} + +// EMIT_MIR copy_propagation_arg.bar.CopyProp.diff +fn bar(mut x: u8) { + dummy(x); + x = 5; +} + +// EMIT_MIR copy_propagation_arg.baz.CopyProp.diff +fn baz(mut x: i32) -> i32 { + // self-assignment to a function argument should be eliminated + x = x; + x +} + +// EMIT_MIR copy_propagation_arg.arg_src.CopyProp.diff +fn arg_src(mut x: i32) -> i32 { + let y = x; + x = 123; // Don't propagate this assignment to `y` + y +} + +fn main() { + // Make sure the function actually gets instantiated. + foo(0); + bar(0); + baz(0); + arg_src(0); +} diff --git a/tests/mir-opt/copy-prop/cycle.main.CopyProp.diff b/tests/mir-opt/copy-prop/cycle.main.CopyProp.diff new file mode 100644 index 0000000000000..3e61869e82f11 --- /dev/null +++ b/tests/mir-opt/copy-prop/cycle.main.CopyProp.diff @@ -0,0 +1,60 @@ +- // MIR for `main` before CopyProp ++ // MIR for `main` after CopyProp + + fn main() -> () { + let mut _0: (); // return place in scope 0 at $DIR/cycle.rs:+0:11: +0:11 + let mut _1: i32; // in scope 0 at $DIR/cycle.rs:+1:9: +1:14 + let mut _4: i32; // in scope 0 at $DIR/cycle.rs:+4:9: +4:10 + let _5: (); // in scope 0 at $DIR/cycle.rs:+6:5: +6:12 + let mut _6: i32; // in scope 0 at $DIR/cycle.rs:+6:10: +6:11 + scope 1 { + debug x => _1; // in scope 1 at $DIR/cycle.rs:+1:9: +1:14 + let _2: i32; // in scope 1 at $DIR/cycle.rs:+2:9: +2:10 + scope 2 { + debug y => _2; // in scope 2 at $DIR/cycle.rs:+2:9: +2:10 + let _3: i32; // in scope 2 at $DIR/cycle.rs:+3:9: +3:10 + scope 3 { +- debug z => _3; // in scope 3 at $DIR/cycle.rs:+3:9: +3:10 ++ debug z => _2; // in scope 3 at $DIR/cycle.rs:+3:9: +3:10 + } + } + } + + bb0: { + StorageLive(_1); // scope 0 at $DIR/cycle.rs:+1:9: +1:14 + _1 = val() -> bb1; // scope 0 at $DIR/cycle.rs:+1:17: +1:22 + // mir::Constant + // + span: $DIR/cycle.rs:9:17: 9:20 + // + literal: Const { ty: fn() -> i32 {val}, val: Value() } + } + + bb1: { +- StorageLive(_2); // scope 1 at $DIR/cycle.rs:+2:9: +2:10 + _2 = _1; // scope 1 at $DIR/cycle.rs:+2:13: +2:14 +- StorageLive(_3); // scope 2 at $DIR/cycle.rs:+3:9: +3:10 +- _3 = _2; // scope 2 at $DIR/cycle.rs:+3:13: +3:14 +- StorageLive(_4); // scope 3 at $DIR/cycle.rs:+4:9: +4:10 +- _4 = _3; // scope 3 at $DIR/cycle.rs:+4:9: +4:10 +- _1 = move _4; // scope 3 at $DIR/cycle.rs:+4:5: +4:10 +- StorageDead(_4); // scope 3 at $DIR/cycle.rs:+4:9: +4:10 ++ _1 = _2; // scope 3 at $DIR/cycle.rs:+4:5: +4:10 + StorageLive(_5); // scope 3 at $DIR/cycle.rs:+6:5: +6:12 + StorageLive(_6); // scope 3 at $DIR/cycle.rs:+6:10: +6:11 + _6 = _1; // scope 3 at $DIR/cycle.rs:+6:10: +6:11 + _5 = std::mem::drop::(move _6) -> bb2; // scope 3 at $DIR/cycle.rs:+6:5: +6:12 + // mir::Constant + // + span: $DIR/cycle.rs:14:5: 14:9 + // + literal: Const { ty: fn(i32) {std::mem::drop::}, val: Value() } + } + + bb2: { + StorageDead(_6); // scope 3 at $DIR/cycle.rs:+6:11: +6:12 + StorageDead(_5); // scope 3 at $DIR/cycle.rs:+6:12: +6:13 + _0 = const (); // scope 0 at $DIR/cycle.rs:+0:11: +7:2 +- StorageDead(_3); // scope 2 at $DIR/cycle.rs:+7:1: +7:2 +- StorageDead(_2); // scope 1 at $DIR/cycle.rs:+7:1: +7:2 + StorageDead(_1); // scope 0 at $DIR/cycle.rs:+7:1: +7:2 + return; // scope 0 at $DIR/cycle.rs:+7:2: +7:2 + } + } + diff --git a/tests/mir-opt/copy-prop/cycle.rs b/tests/mir-opt/copy-prop/cycle.rs new file mode 100644 index 0000000000000..b74c397269dee --- /dev/null +++ b/tests/mir-opt/copy-prop/cycle.rs @@ -0,0 +1,15 @@ +//! Tests that cyclic assignments don't hang CopyProp, and result in reasonable code. +// unit-test: CopyProp +fn val() -> i32 { + 1 +} + +// EMIT_MIR cycle.main.CopyProp.diff +fn main() { + let mut x = val(); + let y = x; + let z = y; + x = z; + + drop(x); +} diff --git a/tests/mir-opt/copy-prop/dead_stores_79191.f.CopyProp.after.mir b/tests/mir-opt/copy-prop/dead_stores_79191.f.CopyProp.after.mir new file mode 100644 index 0000000000000..d48b04e2de273 --- /dev/null +++ b/tests/mir-opt/copy-prop/dead_stores_79191.f.CopyProp.after.mir @@ -0,0 +1,29 @@ +// MIR for `f` after CopyProp + +fn f(_1: usize) -> usize { + debug a => _1; // in scope 0 at $DIR/dead_stores_79191.rs:+0:6: +0:11 + let mut _0: usize; // return place in scope 0 at $DIR/dead_stores_79191.rs:+0:23: +0:28 + let _2: usize; // in scope 0 at $DIR/dead_stores_79191.rs:+1:9: +1:10 + let mut _3: usize; // in scope 0 at $DIR/dead_stores_79191.rs:+3:9: +3:10 + let mut _4: usize; // in scope 0 at $DIR/dead_stores_79191.rs:+4:8: +4:9 + scope 1 { + debug b => _2; // in scope 1 at $DIR/dead_stores_79191.rs:+1:9: +1:10 + } + + bb0: { + _2 = _1; // scope 0 at $DIR/dead_stores_79191.rs:+1:13: +1:14 + _1 = const 5_usize; // scope 1 at $DIR/dead_stores_79191.rs:+2:5: +2:10 + _1 = _2; // scope 1 at $DIR/dead_stores_79191.rs:+3:5: +3:10 + StorageLive(_4); // scope 1 at $DIR/dead_stores_79191.rs:+4:8: +4:9 + _4 = _1; // scope 1 at $DIR/dead_stores_79191.rs:+4:8: +4:9 + _0 = id::(move _4) -> bb1; // scope 1 at $DIR/dead_stores_79191.rs:+4:5: +4:10 + // mir::Constant + // + span: $DIR/dead_stores_79191.rs:12:5: 12:7 + // + literal: Const { ty: fn(usize) -> usize {id::}, val: Value() } + } + + bb1: { + StorageDead(_4); // scope 1 at $DIR/dead_stores_79191.rs:+4:9: +4:10 + return; // scope 0 at $DIR/dead_stores_79191.rs:+5:2: +5:2 + } +} diff --git a/tests/mir-opt/copy-prop/dead_stores_79191.rs b/tests/mir-opt/copy-prop/dead_stores_79191.rs new file mode 100644 index 0000000000000..e3493b8b7a185 --- /dev/null +++ b/tests/mir-opt/copy-prop/dead_stores_79191.rs @@ -0,0 +1,17 @@ +// unit-test: CopyProp + +fn id(x: T) -> T { + x +} + +// EMIT_MIR dead_stores_79191.f.CopyProp.after.mir +fn f(mut a: usize) -> usize { + let b = a; + a = 5; + a = b; + id(a) +} + +fn main() { + f(0); +} diff --git a/tests/mir-opt/copy-prop/dead_stores_better.f.CopyProp.after.mir b/tests/mir-opt/copy-prop/dead_stores_better.f.CopyProp.after.mir new file mode 100644 index 0000000000000..727791f50a4ef --- /dev/null +++ b/tests/mir-opt/copy-prop/dead_stores_better.f.CopyProp.after.mir @@ -0,0 +1,29 @@ +// MIR for `f` after CopyProp + +fn f(_1: usize) -> usize { + debug a => _1; // in scope 0 at $DIR/dead_stores_better.rs:+0:10: +0:15 + let mut _0: usize; // return place in scope 0 at $DIR/dead_stores_better.rs:+0:27: +0:32 + let _2: usize; // in scope 0 at $DIR/dead_stores_better.rs:+1:9: +1:10 + let mut _3: usize; // in scope 0 at $DIR/dead_stores_better.rs:+3:9: +3:10 + let mut _4: usize; // in scope 0 at $DIR/dead_stores_better.rs:+4:8: +4:9 + scope 1 { + debug b => _2; // in scope 1 at $DIR/dead_stores_better.rs:+1:9: +1:10 + } + + bb0: { + _2 = _1; // scope 0 at $DIR/dead_stores_better.rs:+1:13: +1:14 + _1 = const 5_usize; // scope 1 at $DIR/dead_stores_better.rs:+2:5: +2:10 + _1 = _2; // scope 1 at $DIR/dead_stores_better.rs:+3:5: +3:10 + StorageLive(_4); // scope 1 at $DIR/dead_stores_better.rs:+4:8: +4:9 + _4 = _1; // scope 1 at $DIR/dead_stores_better.rs:+4:8: +4:9 + _0 = id::(move _4) -> bb1; // scope 1 at $DIR/dead_stores_better.rs:+4:5: +4:10 + // mir::Constant + // + span: $DIR/dead_stores_better.rs:16:5: 16:7 + // + literal: Const { ty: fn(usize) -> usize {id::}, val: Value() } + } + + bb1: { + StorageDead(_4); // scope 1 at $DIR/dead_stores_better.rs:+4:9: +4:10 + return; // scope 0 at $DIR/dead_stores_better.rs:+5:2: +5:2 + } +} diff --git a/tests/mir-opt/copy-prop/dead_stores_better.rs b/tests/mir-opt/copy-prop/dead_stores_better.rs new file mode 100644 index 0000000000000..8465b3c98536e --- /dev/null +++ b/tests/mir-opt/copy-prop/dead_stores_better.rs @@ -0,0 +1,21 @@ +// This is a copy of the `dead_stores_79191` test, except that we turn on DSE. This demonstrates +// that that pass enables this one to do more optimizations. + +// unit-test: CopyProp +// compile-flags: -Zmir-enable-passes=+DeadStoreElimination + +fn id(x: T) -> T { + x +} + +// EMIT_MIR dead_stores_better.f.CopyProp.after.mir +pub fn f(mut a: usize) -> usize { + let b = a; + a = 5; + a = b; + id(a) +} + +fn main() { + f(0); +} diff --git a/tests/mir-opt/copy-prop/move_arg.f.CopyProp.diff b/tests/mir-opt/copy-prop/move_arg.f.CopyProp.diff new file mode 100644 index 0000000000000..d76bf1cfe7e0e --- /dev/null +++ b/tests/mir-opt/copy-prop/move_arg.f.CopyProp.diff @@ -0,0 +1,40 @@ +- // MIR for `f` before CopyProp ++ // MIR for `f` after CopyProp + + fn f(_1: T) -> () { + debug a => _1; // in scope 0 at $DIR/move_arg.rs:+0:19: +0:20 + let mut _0: (); // return place in scope 0 at $DIR/move_arg.rs:+0:25: +0:25 + let _2: T; // in scope 0 at $DIR/move_arg.rs:+1:9: +1:10 + let _3: (); // in scope 0 at $DIR/move_arg.rs:+2:5: +2:12 + let mut _4: T; // in scope 0 at $DIR/move_arg.rs:+2:7: +2:8 + let mut _5: T; // in scope 0 at $DIR/move_arg.rs:+2:10: +2:11 + scope 1 { +- debug b => _2; // in scope 1 at $DIR/move_arg.rs:+1:9: +1:10 ++ debug b => _1; // in scope 1 at $DIR/move_arg.rs:+1:9: +1:10 + } + + bb0: { +- StorageLive(_2); // scope 0 at $DIR/move_arg.rs:+1:9: +1:10 +- _2 = _1; // scope 0 at $DIR/move_arg.rs:+1:13: +1:14 + StorageLive(_3); // scope 1 at $DIR/move_arg.rs:+2:5: +2:12 +- StorageLive(_4); // scope 1 at $DIR/move_arg.rs:+2:7: +2:8 +- _4 = _1; // scope 1 at $DIR/move_arg.rs:+2:7: +2:8 +- StorageLive(_5); // scope 1 at $DIR/move_arg.rs:+2:10: +2:11 +- _5 = _2; // scope 1 at $DIR/move_arg.rs:+2:10: +2:11 +- _3 = g::(move _4, move _5) -> bb1; // scope 1 at $DIR/move_arg.rs:+2:5: +2:12 ++ _3 = g::(_1, _1) -> bb1; // scope 1 at $DIR/move_arg.rs:+2:5: +2:12 + // mir::Constant + // + span: $DIR/move_arg.rs:7:5: 7:6 + // + literal: Const { ty: fn(T, T) {g::}, val: Value() } + } + + bb1: { +- StorageDead(_5); // scope 1 at $DIR/move_arg.rs:+2:11: +2:12 +- StorageDead(_4); // scope 1 at $DIR/move_arg.rs:+2:11: +2:12 + StorageDead(_3); // scope 1 at $DIR/move_arg.rs:+2:12: +2:13 + _0 = const (); // scope 0 at $DIR/move_arg.rs:+0:25: +3:2 +- StorageDead(_2); // scope 0 at $DIR/move_arg.rs:+3:1: +3:2 + return; // scope 0 at $DIR/move_arg.rs:+3:2: +3:2 + } + } + diff --git a/tests/mir-opt/copy-prop/move_arg.rs b/tests/mir-opt/copy-prop/move_arg.rs new file mode 100644 index 0000000000000..40ae1d8f46619 --- /dev/null +++ b/tests/mir-opt/copy-prop/move_arg.rs @@ -0,0 +1,15 @@ +// Test that we do not move multiple times from the same local. +// unit-test: CopyProp + +// EMIT_MIR move_arg.f.CopyProp.diff +pub fn f(a: T) { + let b = a; + g(a, b); +} + +#[inline(never)] +pub fn g(_: T, _: T) {} + +fn main() { + f(5) +} From d45815eb4ae2737b5fb8f4eeeb0eb3d784efeca3 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 15 Jan 2023 20:16:28 +0000 Subject: [PATCH 422/500] Only consider a local to be SSA if assignment dominates all uses. --- compiler/rustc_mir_transform/src/copy_prop.rs | 23 +++++++++++++-- .../copy-prop/non_dominate.f.CopyProp.diff | 29 +++++++++++++++++++ tests/mir-opt/copy-prop/non_dominate.rs | 26 +++++++++++++++++ 3 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 tests/mir-opt/copy-prop/non_dominate.f.CopyProp.diff create mode 100644 tests/mir-opt/copy-prop/non_dominate.rs diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs index e39e661d4a14a..13a182695857f 100644 --- a/compiler/rustc_mir_transform/src/copy_prop.rs +++ b/compiler/rustc_mir_transform/src/copy_prop.rs @@ -1,4 +1,5 @@ use either::Either; +use rustc_data_structures::graph::dominators::Dominators; use rustc_index::bit_set::BitSet; use rustc_index::vec::IndexVec; use rustc_middle::middle::resolve_lifetime::Set1; @@ -65,6 +66,7 @@ enum LocationExtended { #[derive(Debug)] struct SsaLocals { + dominators: Dominators, /// Assignments to each local. This defines whether the local is SSA. assignments: IndexVec>, /// We visit the body in reverse postorder, to ensure each local is assigned before it is used. @@ -78,7 +80,8 @@ impl SsaLocals { let assignment_order = Vec::new(); let assignments = IndexVec::from_elem(Set1::Empty, &body.local_decls); - let mut this = SsaLocals { assignments, assignment_order }; + let dominators = body.basic_blocks.dominators(); + let mut this = SsaLocals { assignments, assignment_order, dominators }; let borrowed = borrowed_locals(body); for (local, decl) in body.local_decls.iter_enumerated() { @@ -117,7 +120,23 @@ impl<'tcx> Visitor<'tcx> for SsaLocals { PlaceContext::MutatingUse(_) => self.assignments[local] = Set1::Many, // Immutable borrows and AddressOf are taken into account in `SsaLocals::new` by // removing non-freeze locals. - PlaceContext::NonMutatingUse(_) | PlaceContext::NonUse(_) => {} + PlaceContext::NonMutatingUse(_) => { + let set = &mut self.assignments[local]; + let assign_dominates = match *set { + Set1::Empty | Set1::Many => false, + Set1::One(LocationExtended::Arg) => true, + Set1::One(LocationExtended::Plain(assign)) => { + assign.dominates(loc, &self.dominators) + } + }; + // We are visiting a use that is not dominated by an assignment. + // Either there is a cycle involved, or we are reading for uninitialized local. + // Bail out. + if !assign_dominates { + *set = Set1::Many; + } + } + PlaceContext::NonUse(_) => {} } } } diff --git a/tests/mir-opt/copy-prop/non_dominate.f.CopyProp.diff b/tests/mir-opt/copy-prop/non_dominate.f.CopyProp.diff new file mode 100644 index 0000000000000..9760fd3740fb9 --- /dev/null +++ b/tests/mir-opt/copy-prop/non_dominate.f.CopyProp.diff @@ -0,0 +1,29 @@ +- // MIR for `f` before CopyProp ++ // MIR for `f` after CopyProp + + fn f(_1: bool) -> bool { + let mut _0: bool; // return place in scope 0 at $DIR/non_dominate.rs:+0:18: +0:22 + let mut _2: bool; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + let mut _3: bool; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + + bb0: { + goto -> bb1; // scope 0 at $DIR/non_dominate.rs:+4:11: +4:20 + } + + bb1: { + _3 = _1; // scope 0 at $DIR/non_dominate.rs:+5:17: +5:22 + switchInt(_3) -> [0: bb3, otherwise: bb2]; // scope 0 at $DIR/non_dominate.rs:+5:24: +5:58 + } + + bb2: { + _2 = _3; // scope 0 at $DIR/non_dominate.rs:+8:17: +8:22 + _1 = const false; // scope 0 at $DIR/non_dominate.rs:+8:24: +8:33 + goto -> bb1; // scope 0 at $DIR/non_dominate.rs:+8:35: +8:44 + } + + bb3: { + _0 = _2; // scope 0 at $DIR/non_dominate.rs:+9:17: +9:24 + return; // scope 0 at $DIR/non_dominate.rs:+9:26: +9:34 + } + } + diff --git a/tests/mir-opt/copy-prop/non_dominate.rs b/tests/mir-opt/copy-prop/non_dominate.rs new file mode 100644 index 0000000000000..c0ea838e1c885 --- /dev/null +++ b/tests/mir-opt/copy-prop/non_dominate.rs @@ -0,0 +1,26 @@ +// unit-test: CopyProp + +#![feature(custom_mir, core_intrinsics)] +#![allow(unused_assignments)] +extern crate core; +use core::intrinsics::mir::*; + +#[custom_mir(dialect = "analysis", phase = "post-cleanup")] +fn f(c: bool) -> bool { + mir!( + let a: bool; + let b: bool; + { Goto(bb1) } + bb1 = { b = c; match b { false => bb3, _ => bb2 }} + // This assignment to `a` does not dominate the use in `bb3`. + // It should not be replaced by `b`. + bb2 = { a = b; c = false; Goto(bb1) } + bb3 = { RET = a; Return() } + ) +} + +fn main() { + assert_eq!(true, f(true)); +} + +// EMIT_MIR non_dominate.f.CopyProp.diff From 8f1dbe54ea5e05725273ae8ac6c1dda15153fa7c Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Wed, 18 Jan 2023 22:59:52 +0000 Subject: [PATCH 423/500] Discard raw pointers from SSA locals. --- compiler/rustc_mir_transform/src/copy_prop.rs | 6 +++-- .../mutate_through_pointer.f.CopyProp.diff | 19 ++++++++++++++++ .../copy-prop/mutate_through_pointer.rs | 22 +++++++++++++++++++ 3 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 tests/mir-opt/copy-prop/mutate_through_pointer.f.CopyProp.diff create mode 100644 tests/mir-opt/copy-prop/mutate_through_pointer.rs diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs index 13a182695857f..bce307d368ca5 100644 --- a/compiler/rustc_mir_transform/src/copy_prop.rs +++ b/compiler/rustc_mir_transform/src/copy_prop.rs @@ -117,8 +117,10 @@ impl<'tcx> Visitor<'tcx> for SsaLocals { self.assignments[local].insert(LocationExtended::Plain(loc)); self.assignment_order.push(local); } - PlaceContext::MutatingUse(_) => self.assignments[local] = Set1::Many, - // Immutable borrows and AddressOf are taken into account in `SsaLocals::new` by + // Anything can happen with raw pointers, so remove them. + PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf) + | PlaceContext::MutatingUse(_) => self.assignments[local] = Set1::Many, + // Immutable borrows are taken into account in `SsaLocals::new` by // removing non-freeze locals. PlaceContext::NonMutatingUse(_) => { let set = &mut self.assignments[local]; diff --git a/tests/mir-opt/copy-prop/mutate_through_pointer.f.CopyProp.diff b/tests/mir-opt/copy-prop/mutate_through_pointer.f.CopyProp.diff new file mode 100644 index 0000000000000..61fdd6f8c05bf --- /dev/null +++ b/tests/mir-opt/copy-prop/mutate_through_pointer.f.CopyProp.diff @@ -0,0 +1,19 @@ +- // MIR for `f` before CopyProp ++ // MIR for `f` after CopyProp + + fn f(_1: bool) -> bool { + let mut _0: bool; // return place in scope 0 at $DIR/mutate_through_pointer.rs:+0:18: +0:22 + let mut _2: bool; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + let mut _3: *const bool; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + let mut _4: *mut bool; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + + bb0: { + _2 = _1; // scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + _3 = &raw const _2; // scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + _4 = &raw mut (*_3); // scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + (*_4) = const false; // scope 0 at $DIR/mutate_through_pointer.rs:+5:9: +5:20 + _0 = _1; // scope 0 at $DIR/mutate_through_pointer.rs:+6:9: +6:16 + return; // scope 0 at $DIR/mutate_through_pointer.rs:+7:9: +7:17 + } + } + diff --git a/tests/mir-opt/copy-prop/mutate_through_pointer.rs b/tests/mir-opt/copy-prop/mutate_through_pointer.rs new file mode 100644 index 0000000000000..609e49d6bc998 --- /dev/null +++ b/tests/mir-opt/copy-prop/mutate_through_pointer.rs @@ -0,0 +1,22 @@ +#![feature(custom_mir, core_intrinsics)] +#![allow(unused_assignments)] +extern crate core; +use core::intrinsics::mir::*; + +#[custom_mir(dialect = "analysis", phase = "post-cleanup")] +fn f(c: bool) -> bool { + mir!({ + let a = c; + let p = core::ptr::addr_of!(a); + let p2 = core::ptr::addr_of_mut!(*p); + *p2 = false; + RET = c; + Return() + }) +} + +fn main() { + assert_eq!(true, f(true)); +} + +// EMIT_MIR mutate_through_pointer.f.CopyProp.diff From bec73b09fdc77d74972d25fefd111fbb9d20fba1 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Thu, 19 Jan 2023 16:57:32 +0000 Subject: [PATCH 424/500] Pacify tidy. --- compiler/rustc_mir_transform/src/copy_prop.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs index bce307d368ca5..8b024721718d2 100644 --- a/compiler/rustc_mir_transform/src/copy_prop.rs +++ b/compiler/rustc_mir_transform/src/copy_prop.rs @@ -67,7 +67,7 @@ enum LocationExtended { #[derive(Debug)] struct SsaLocals { dominators: Dominators, - /// Assignments to each local. This defines whether the local is SSA. + /// Assignments to each local. This defines whether the local is SSA. assignments: IndexVec>, /// We visit the body in reverse postorder, to ensure each local is assigned before it is used. /// We remember the order in which we saw the assignments to compute the SSA values in a single @@ -157,7 +157,7 @@ impl<'tcx> Visitor<'tcx> for SsaLocals { /// _d => _a // transitively through _c /// /// This function also returns whether all the `move?` in the pattern are `move` and not copies. -/// A local which is in the bitset can be replaced by `move _a`. Otherwise, it must be +/// A local which is in the bitset can be replaced by `move _a`. Otherwise, it must be /// replaced by `copy _a`, as we cannot move multiple times from `_a`. /// /// If an operand copies `_c`, it must happen before the assignment `_d = _c`, otherwise it is UB. @@ -221,7 +221,7 @@ fn compute_copy_classes( fn meet_copy_equivalence(copies: &IndexVec, property: &mut BitSet) { // Consolidate to have a local iff all its copies are. // - // `copies` defines equivalence classes between locals. The `local`s that recursively + // `copies` defines equivalence classes between locals. The `local`s that recursively // move/copy the same local all have the same `head`. for (local, &head) in copies.iter_enumerated() { // If any copy does not have `property`, then the head is not. From 9096d31dcc292bad1281e0ab37e55d9a3aac5dc4 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Thu, 19 Jan 2023 22:23:41 +0000 Subject: [PATCH 425/500] Extract SsaLocals abstraction. --- compiler/rustc_mir_transform/src/copy_prop.rs | 195 ++-------------- compiler/rustc_mir_transform/src/lib.rs | 1 + compiler/rustc_mir_transform/src/ssa.rs | 219 ++++++++++++++++++ 3 files changed, 240 insertions(+), 175 deletions(-) create mode 100644 compiler/rustc_mir_transform/src/ssa.rs diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs index 8b024721718d2..58211bc795fee 100644 --- a/compiler/rustc_mir_transform/src/copy_prop.rs +++ b/compiler/rustc_mir_transform/src/copy_prop.rs @@ -1,13 +1,10 @@ -use either::Either; -use rustc_data_structures::graph::dominators::Dominators; use rustc_index::bit_set::BitSet; use rustc_index::vec::IndexVec; -use rustc_middle::middle::resolve_lifetime::Set1; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; -use rustc_middle::ty::{ParamEnv, TyCtxt}; -use rustc_mir_dataflow::impls::borrowed_locals; +use rustc_middle::ty::TyCtxt; +use crate::ssa::SsaLocals; use crate::MirPass; /// Unify locals that copy each other. @@ -38,123 +35,28 @@ fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let param_env = tcx.param_env_reveal_all_normalized(body.source.def_id()); let ssa = SsaLocals::new(tcx, param_env, body); - let (copy_classes, fully_moved) = compute_copy_classes(&ssa, body); - debug!(?copy_classes); + let fully_moved = fully_moved_locals(&ssa, body); + debug!(?fully_moved); let mut storage_to_remove = BitSet::new_empty(fully_moved.domain_size()); - for (local, &head) in copy_classes.iter_enumerated() { + for (local, &head) in ssa.copy_classes().iter_enumerated() { if local != head { storage_to_remove.insert(head); storage_to_remove.insert(local); } } - let any_replacement = copy_classes.iter_enumerated().any(|(l, &h)| l != h); + let any_replacement = ssa.copy_classes().iter_enumerated().any(|(l, &h)| l != h); - Replacer { tcx, copy_classes, fully_moved, storage_to_remove }.visit_body_preserves_cfg(body); + Replacer { tcx, copy_classes: &ssa.copy_classes(), fully_moved, storage_to_remove } + .visit_body_preserves_cfg(body); if any_replacement { crate::simplify::remove_unused_definitions(body); } } -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -enum LocationExtended { - Plain(Location), - Arg, -} - -#[derive(Debug)] -struct SsaLocals { - dominators: Dominators, - /// Assignments to each local. This defines whether the local is SSA. - assignments: IndexVec>, - /// We visit the body in reverse postorder, to ensure each local is assigned before it is used. - /// We remember the order in which we saw the assignments to compute the SSA values in a single - /// pass. - assignment_order: Vec, -} - -impl SsaLocals { - fn new<'tcx>(tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, body: &Body<'tcx>) -> SsaLocals { - let assignment_order = Vec::new(); - - let assignments = IndexVec::from_elem(Set1::Empty, &body.local_decls); - let dominators = body.basic_blocks.dominators(); - let mut this = SsaLocals { assignments, assignment_order, dominators }; - - let borrowed = borrowed_locals(body); - for (local, decl) in body.local_decls.iter_enumerated() { - if matches!(body.local_kind(local), LocalKind::Arg) { - this.assignments[local] = Set1::One(LocationExtended::Arg); - } - if borrowed.contains(local) && !decl.ty.is_freeze(tcx, param_env) { - this.assignments[local] = Set1::Many; - } - } - - for (bb, data) in traversal::reverse_postorder(body) { - this.visit_basic_block_data(bb, data); - } - - for var_debug_info in &body.var_debug_info { - this.visit_var_debug_info(var_debug_info); - } - - debug!(?this.assignments); - - this.assignment_order.retain(|&local| matches!(this.assignments[local], Set1::One(_))); - debug!(?this.assignment_order); - - this - } -} - -impl<'tcx> Visitor<'tcx> for SsaLocals { - fn visit_local(&mut self, local: Local, ctxt: PlaceContext, loc: Location) { - match ctxt { - PlaceContext::MutatingUse(MutatingUseContext::Store) => { - self.assignments[local].insert(LocationExtended::Plain(loc)); - self.assignment_order.push(local); - } - // Anything can happen with raw pointers, so remove them. - PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf) - | PlaceContext::MutatingUse(_) => self.assignments[local] = Set1::Many, - // Immutable borrows are taken into account in `SsaLocals::new` by - // removing non-freeze locals. - PlaceContext::NonMutatingUse(_) => { - let set = &mut self.assignments[local]; - let assign_dominates = match *set { - Set1::Empty | Set1::Many => false, - Set1::One(LocationExtended::Arg) => true, - Set1::One(LocationExtended::Plain(assign)) => { - assign.dominates(loc, &self.dominators) - } - }; - // We are visiting a use that is not dominated by an assignment. - // Either there is a cycle involved, or we are reading for uninitialized local. - // Bail out. - if !assign_dominates { - *set = Set1::Many; - } - } - PlaceContext::NonUse(_) => {} - } - } -} - -/// Compute the equivalence classes for locals, based on copy statements. -/// -/// The returned vector maps each local to the one it copies. In the following case: -/// _a = &mut _0 -/// _b = move? _a -/// _c = move? _a -/// _d = move? _c -/// We return the mapping -/// _a => _a // not a copy so, represented by itself -/// _b => _a -/// _c => _a -/// _d => _a // transitively through _c +/// `SsaLocals` computed equivalence classes between locals considering copy/move assignments. /// /// This function also returns whether all the `move?` in the pattern are `move` and not copies. /// A local which is in the bitset can be replaced by `move _a`. Otherwise, it must be @@ -164,95 +66,38 @@ impl<'tcx> Visitor<'tcx> for SsaLocals { /// This means that replacing it by a copy of `_a` if ok, since this copy happens before `_c` is /// moved, and therefore that `_d` is moved. #[instrument(level = "trace", skip(ssa, body))] -fn compute_copy_classes( - ssa: &SsaLocals, - body: &Body<'_>, -) -> (IndexVec, BitSet) { - let mut copies = IndexVec::from_fn_n(|l| l, body.local_decls.len()); - let mut fully_moved = BitSet::new_filled(copies.len()); - - for &local in &ssa.assignment_order { - debug!(?local); - - if local == RETURN_PLACE { - // `_0` is special, we cannot rename it. - continue; - } - - // This is not SSA: mark that we don't know the value. - debug!(assignments = ?ssa.assignments[local]); - let Set1::One(LocationExtended::Plain(loc)) = ssa.assignments[local] else { continue }; - - // `loc` must point to a direct assignment to `local`. - let Either::Left(stmt) = body.stmt_at(loc) else { bug!() }; - let Some((_target, rvalue)) = stmt.kind.as_assign() else { bug!() }; - assert_eq!(_target.as_local(), Some(local)); +fn fully_moved_locals(ssa: &SsaLocals, body: &Body<'_>) -> BitSet { + let mut fully_moved = BitSet::new_filled(body.local_decls.len()); + for (_, rvalue) in ssa.assignments(body) { let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) | Rvalue::CopyForDeref(place)) = rvalue else { continue }; let Some(rhs) = place.as_local() else { continue }; - let Set1::One(_) = ssa.assignments[rhs] else { continue }; - - // We visit in `assignment_order`, ie. reverse post-order, so `rhs` has been - // visited before `local`, and we just have to copy the representing local. - copies[local] = copies[rhs]; + if !ssa.is_ssa(rhs) { + continue; + } if let Rvalue::Use(Operand::Copy(_)) | Rvalue::CopyForDeref(_) = rvalue { fully_moved.remove(rhs); } } - debug!(?copies); + ssa.meet_copy_equivalence(&mut fully_moved); - // Invariant: `copies` must point to the head of an equivalence class. - #[cfg(debug_assertions)] - for &head in copies.iter() { - assert_eq!(copies[head], head); - } - - meet_copy_equivalence(&copies, &mut fully_moved); - - (copies, fully_moved) -} - -/// Make a property uniform on a copy equivalence class by removing elements. -fn meet_copy_equivalence(copies: &IndexVec, property: &mut BitSet) { - // Consolidate to have a local iff all its copies are. - // - // `copies` defines equivalence classes between locals. The `local`s that recursively - // move/copy the same local all have the same `head`. - for (local, &head) in copies.iter_enumerated() { - // If any copy does not have `property`, then the head is not. - if !property.contains(local) { - property.remove(head); - } - } - for (local, &head) in copies.iter_enumerated() { - // If any copy does not have `property`, then the head doesn't either, - // then no copy has `property`. - if !property.contains(head) { - property.remove(local); - } - } - - // Verify that we correctly computed equivalence classes. - #[cfg(debug_assertions)] - for (local, &head) in copies.iter_enumerated() { - assert_eq!(property.contains(local), property.contains(head)); - } + fully_moved } /// Utility to help performing subtitution of `*pattern` by `target`. -struct Replacer<'tcx> { +struct Replacer<'a, 'tcx> { tcx: TyCtxt<'tcx>, fully_moved: BitSet, storage_to_remove: BitSet, - copy_classes: IndexVec, + copy_classes: &'a IndexVec, } -impl<'tcx> MutVisitor<'tcx> for Replacer<'tcx> { +impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> { fn tcx(&self) -> TyCtxt<'tcx> { self.tcx } diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 1330f1e26b8ed..8a7c14472ac2f 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -87,6 +87,7 @@ mod required_consts; mod reveal_all; mod separate_const_switch; mod shim; +mod ssa; // This pass is public to allow external drivers to perform MIR cleanup pub mod simplify; mod simplify_branches; diff --git a/compiler/rustc_mir_transform/src/ssa.rs b/compiler/rustc_mir_transform/src/ssa.rs new file mode 100644 index 0000000000000..a5ae671be81f7 --- /dev/null +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -0,0 +1,219 @@ +use either::Either; +use rustc_data_structures::graph::dominators::Dominators; +use rustc_index::bit_set::BitSet; +use rustc_index::vec::IndexVec; +use rustc_middle::middle::resolve_lifetime::Set1; +use rustc_middle::mir::visit::*; +use rustc_middle::mir::*; +use rustc_middle::ty::{ParamEnv, TyCtxt}; +use rustc_mir_dataflow::impls::borrowed_locals; + +#[derive(Debug)] +pub struct SsaLocals { + /// Assignments to each local. This defines whether the local is SSA. + assignments: IndexVec>, + /// We visit the body in reverse postorder, to ensure each local is assigned before it is used. + /// We remember the order in which we saw the assignments to compute the SSA values in a single + /// pass. + assignment_order: Vec, + /// Copy equivalence classes between locals. See `copy_classes` for documentation. + copy_classes: IndexVec, +} + +impl SsaLocals { + pub fn new<'tcx>(tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, body: &Body<'tcx>) -> SsaLocals { + let assignment_order = Vec::new(); + + let assignments = IndexVec::from_elem(Set1::Empty, &body.local_decls); + let dominators = body.basic_blocks.dominators(); + let mut visitor = SsaVisitor { assignments, assignment_order, dominators }; + + let borrowed = borrowed_locals(body); + for (local, decl) in body.local_decls.iter_enumerated() { + if matches!(body.local_kind(local), LocalKind::Arg) { + visitor.assignments[local] = Set1::One(LocationExtended::Arg); + } + if borrowed.contains(local) && !decl.ty.is_freeze(tcx, param_env) { + visitor.assignments[local] = Set1::Many; + } + } + + for (bb, data) in traversal::reverse_postorder(body) { + visitor.visit_basic_block_data(bb, data); + } + + for var_debug_info in &body.var_debug_info { + visitor.visit_var_debug_info(var_debug_info); + } + + debug!(?visitor.assignments); + + visitor + .assignment_order + .retain(|&local| matches!(visitor.assignments[local], Set1::One(_))); + debug!(?visitor.assignment_order); + + let copy_classes = compute_copy_classes(&visitor, body); + + SsaLocals { + assignments: visitor.assignments, + assignment_order: visitor.assignment_order, + copy_classes, + } + } + + pub fn is_ssa(&self, local: Local) -> bool { + matches!(self.assignments[local], Set1::One(_)) + } + + pub fn assignments<'a, 'tcx>( + &'a self, + body: &'a Body<'tcx>, + ) -> impl Iterator)> + 'a { + self.assignment_order.iter().filter_map(|&local| { + if let Set1::One(LocationExtended::Plain(loc)) = self.assignments[local] { + // `loc` must point to a direct assignment to `local`. + let Either::Left(stmt) = body.stmt_at(loc) else { bug!() }; + let Some((target, rvalue)) = stmt.kind.as_assign() else { bug!() }; + assert_eq!(target.as_local(), Some(local)); + Some((local, rvalue)) + } else { + None + } + }) + } + + /// Compute the equivalence classes for locals, based on copy statements. + /// + /// The returned vector maps each local to the one it copies. In the following case: + /// _a = &mut _0 + /// _b = move? _a + /// _c = move? _a + /// _d = move? _c + /// We return the mapping + /// _a => _a // not a copy so, represented by itself + /// _b => _a + /// _c => _a + /// _d => _a // transitively through _c + /// + /// Exception: we do not see through the return place, as it cannot be substituted. + pub fn copy_classes(&self) -> &IndexVec { + &self.copy_classes + } + + /// Make a property uniform on a copy equivalence class by removing elements. + pub fn meet_copy_equivalence(&self, property: &mut BitSet) { + // Consolidate to have a local iff all its copies are. + // + // `copy_classes` defines equivalence classes between locals. The `local`s that recursively + // move/copy the same local all have the same `head`. + for (local, &head) in self.copy_classes.iter_enumerated() { + // If any copy does not have `property`, then the head is not. + if !property.contains(local) { + property.remove(head); + } + } + for (local, &head) in self.copy_classes.iter_enumerated() { + // If any copy does not have `property`, then the head doesn't either, + // then no copy has `property`. + if !property.contains(head) { + property.remove(local); + } + } + + // Verify that we correctly computed equivalence classes. + #[cfg(debug_assertions)] + for (local, &head) in self.copy_classes.iter_enumerated() { + assert_eq!(property.contains(local), property.contains(head)); + } + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum LocationExtended { + Plain(Location), + Arg, +} + +struct SsaVisitor { + dominators: Dominators, + assignments: IndexVec>, + assignment_order: Vec, +} + +impl<'tcx> Visitor<'tcx> for SsaVisitor { + fn visit_local(&mut self, local: Local, ctxt: PlaceContext, loc: Location) { + match ctxt { + PlaceContext::MutatingUse(MutatingUseContext::Store) => { + self.assignments[local].insert(LocationExtended::Plain(loc)); + self.assignment_order.push(local); + } + // Anything can happen with raw pointers, so remove them. + PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf) + | PlaceContext::MutatingUse(_) => self.assignments[local] = Set1::Many, + // Immutable borrows are taken into account in `SsaLocals::new` by + // removing non-freeze locals. + PlaceContext::NonMutatingUse(_) => { + let set = &mut self.assignments[local]; + let assign_dominates = match *set { + Set1::Empty | Set1::Many => false, + Set1::One(LocationExtended::Arg) => true, + Set1::One(LocationExtended::Plain(assign)) => { + assign.dominates(loc, &self.dominators) + } + }; + // We are visiting a use that is not dominated by an assignment. + // Either there is a cycle involved, or we are reading for uninitialized local. + // Bail out. + if !assign_dominates { + *set = Set1::Many; + } + } + PlaceContext::NonUse(_) => {} + } + } +} + +#[instrument(level = "trace", skip(ssa, body))] +fn compute_copy_classes(ssa: &SsaVisitor, body: &Body<'_>) -> IndexVec { + let mut copies = IndexVec::from_fn_n(|l| l, body.local_decls.len()); + + for &local in &ssa.assignment_order { + debug!(?local); + + if local == RETURN_PLACE { + // `_0` is special, we cannot rename it. + continue; + } + + // This is not SSA: mark that we don't know the value. + debug!(assignments = ?ssa.assignments[local]); + let Set1::One(LocationExtended::Plain(loc)) = ssa.assignments[local] else { continue }; + + // `loc` must point to a direct assignment to `local`. + let Either::Left(stmt) = body.stmt_at(loc) else { bug!() }; + let Some((_target, rvalue)) = stmt.kind.as_assign() else { bug!() }; + assert_eq!(_target.as_local(), Some(local)); + + let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) | Rvalue::CopyForDeref(place)) + = rvalue + else { continue }; + + let Some(rhs) = place.as_local() else { continue }; + let Set1::One(_) = ssa.assignments[rhs] else { continue }; + + // We visit in `assignment_order`, ie. reverse post-order, so `rhs` has been + // visited before `local`, and we just have to copy the representing local. + copies[local] = copies[rhs]; + } + + debug!(?copies); + + // Invariant: `copies` must point to the head of an equivalence class. + #[cfg(debug_assertions)] + for &head in copies.iter() { + assert_eq!(copies[head], head); + } + + copies +} From d29dc057ba53063a9ce7f1b307a89759a096f4ac Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 20 Jan 2023 19:34:46 +0000 Subject: [PATCH 426/500] Do not merge locals that have their address taken. --- compiler/rustc_mir_transform/src/copy_prop.rs | 71 ++++- compiler/rustc_mir_transform/src/ssa.rs | 11 +- .../const_debuginfo.main.ConstDebugInfo.diff | 3 + .../bad_op_mod_by_zero.main.ConstProp.diff | 1 + ...ar_literal_propagation.main.ConstProp.diff | 1 + .../copy-prop/borrowed_local.f.CopyProp.diff | 34 +++ tests/mir-opt/copy-prop/borrowed_local.rs | 39 +++ .../copy-prop/cycle.main.CopyProp.diff | 2 +- .../dead_stores_79191.f.CopyProp.after.mir | 1 + .../dead_stores_better.f.CopyProp.after.mir | 1 + ...herit_overflow.main.DataflowConstProp.diff | 2 + ...float_to_exponential_common.ConstProp.diff | 1 + .../mir-opt/issue_101973.inner.ConstProp.diff | 2 + ...76432.test.SimplifyComparisonIntegral.diff | 1 + .../simplify_match.main.ConstProp.diff | 1 + ...filter.variant_a-{closure#0}.CopyProp.diff | 44 ++- ..._a-{closure#0}.DestinationPropagation.diff | 264 ++++++++++-------- ...filter.variant_b-{closure#0}.CopyProp.diff | 8 +- ..._b-{closure#0}.DestinationPropagation.diff | 4 + .../try_identity_e2e.new.PreCodegen.after.mir | 4 + .../try_identity_e2e.old.PreCodegen.after.mir | 2 + 21 files changed, 329 insertions(+), 168 deletions(-) create mode 100644 tests/mir-opt/copy-prop/borrowed_local.f.CopyProp.diff create mode 100644 tests/mir-opt/copy-prop/borrowed_local.rs diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs index 58211bc795fee..182b3015dd7d7 100644 --- a/compiler/rustc_mir_transform/src/copy_prop.rs +++ b/compiler/rustc_mir_transform/src/copy_prop.rs @@ -3,6 +3,7 @@ use rustc_index::vec::IndexVec; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; +use rustc_mir_dataflow::impls::borrowed_locals; use crate::ssa::SsaLocals; use crate::MirPass; @@ -33,7 +34,8 @@ impl<'tcx> MirPass<'tcx> for CopyProp { fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let param_env = tcx.param_env_reveal_all_normalized(body.source.def_id()); - let ssa = SsaLocals::new(tcx, param_env, body); + let borrowed_locals = borrowed_locals(body); + let ssa = SsaLocals::new(tcx, param_env, body, &borrowed_locals); let fully_moved = fully_moved_locals(&ssa, body); debug!(?fully_moved); @@ -42,14 +44,19 @@ fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { for (local, &head) in ssa.copy_classes().iter_enumerated() { if local != head { storage_to_remove.insert(head); - storage_to_remove.insert(local); } } let any_replacement = ssa.copy_classes().iter_enumerated().any(|(l, &h)| l != h); - Replacer { tcx, copy_classes: &ssa.copy_classes(), fully_moved, storage_to_remove } - .visit_body_preserves_cfg(body); + Replacer { + tcx, + copy_classes: &ssa.copy_classes(), + fully_moved, + borrowed_locals, + storage_to_remove, + } + .visit_body_preserves_cfg(body); if any_replacement { crate::simplify::remove_unused_definitions(body); @@ -94,6 +101,7 @@ struct Replacer<'a, 'tcx> { tcx: TyCtxt<'tcx>, fully_moved: BitSet, storage_to_remove: BitSet, + borrowed_locals: BitSet, copy_classes: &'a IndexVec, } @@ -102,8 +110,45 @@ impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> { self.tcx } - fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) { - *local = self.copy_classes[*local]; + fn visit_local(&mut self, local: &mut Local, ctxt: PlaceContext, _: Location) { + let new_local = self.copy_classes[*local]; + match ctxt { + // Do not modify the local in storage statements. + PlaceContext::NonUse(NonUseContext::StorageLive | NonUseContext::StorageDead) => {} + // The local should have been marked as non-SSA. + PlaceContext::MutatingUse(_) => assert_eq!(*local, new_local), + // We access the value. + _ => *local = new_local, + } + } + + fn visit_place(&mut self, place: &mut Place<'tcx>, ctxt: PlaceContext, loc: Location) { + if let Some(new_projection) = self.process_projection(&place.projection, loc) { + place.projection = self.tcx().intern_place_elems(&new_projection); + } + + let observes_address = match ctxt { + PlaceContext::NonMutatingUse( + NonMutatingUseContext::SharedBorrow + | NonMutatingUseContext::ShallowBorrow + | NonMutatingUseContext::UniqueBorrow + | NonMutatingUseContext::AddressOf, + ) => true, + // For debuginfo, merging locals is ok. + PlaceContext::NonUse(NonUseContext::VarDebugInfo) => { + self.borrowed_locals.contains(place.local) + } + _ => false, + }; + if observes_address && !place.is_indirect() { + // We observe the address of `place.local`. Do not replace it. + } else { + self.visit_local( + &mut place.local, + PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy), + loc, + ) + } } fn visit_operand(&mut self, operand: &mut Operand<'tcx>, loc: Location) { @@ -117,17 +162,17 @@ impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> { } fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) { - if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind + if let StatementKind::StorageDead(l) = stmt.kind && self.storage_to_remove.contains(l) { stmt.make_nop(); - } - if let StatementKind::Assign(box (ref place, _)) = stmt.kind - && let Some(l) = place.as_local() - && self.copy_classes[l] != l + } else if let StatementKind::Assign(box (ref place, ref mut rvalue)) = stmt.kind + && place.as_local().is_some() { - stmt.make_nop(); + // Do not replace assignments. + self.visit_rvalue(rvalue, loc) + } else { + self.super_statement(stmt, loc); } - self.super_statement(stmt, loc); } } diff --git a/compiler/rustc_mir_transform/src/ssa.rs b/compiler/rustc_mir_transform/src/ssa.rs index a5ae671be81f7..b6e0c6e615098 100644 --- a/compiler/rustc_mir_transform/src/ssa.rs +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -6,7 +6,6 @@ use rustc_middle::middle::resolve_lifetime::Set1; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; use rustc_middle::ty::{ParamEnv, TyCtxt}; -use rustc_mir_dataflow::impls::borrowed_locals; #[derive(Debug)] pub struct SsaLocals { @@ -21,19 +20,23 @@ pub struct SsaLocals { } impl SsaLocals { - pub fn new<'tcx>(tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, body: &Body<'tcx>) -> SsaLocals { + pub fn new<'tcx>( + tcx: TyCtxt<'tcx>, + param_env: ParamEnv<'tcx>, + body: &Body<'tcx>, + borrowed_locals: &BitSet, + ) -> SsaLocals { let assignment_order = Vec::new(); let assignments = IndexVec::from_elem(Set1::Empty, &body.local_decls); let dominators = body.basic_blocks.dominators(); let mut visitor = SsaVisitor { assignments, assignment_order, dominators }; - let borrowed = borrowed_locals(body); for (local, decl) in body.local_decls.iter_enumerated() { if matches!(body.local_kind(local), LocalKind::Arg) { visitor.assignments[local] = Set1::One(LocationExtended::Arg); } - if borrowed.contains(local) && !decl.ty.is_freeze(tcx, param_env) { + if borrowed_locals.contains(local) && !decl.ty.is_freeze(tcx, param_env) { visitor.assignments[local] = Set1::Many; } } diff --git a/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff b/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff index 4405b55875ed9..5e587be1f1653 100644 --- a/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff +++ b/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff @@ -56,8 +56,11 @@ } bb0: { + StorageLive(_1); // scope 0 at $DIR/const_debuginfo.rs:+1:9: +1:10 _1 = const 1_u8; // scope 0 at $DIR/const_debuginfo.rs:+1:13: +1:16 + StorageLive(_2); // scope 1 at $DIR/const_debuginfo.rs:+2:9: +2:10 _2 = const 2_u8; // scope 1 at $DIR/const_debuginfo.rs:+2:13: +2:16 + StorageLive(_3); // scope 2 at $DIR/const_debuginfo.rs:+3:9: +3:10 _3 = const 3_u8; // scope 2 at $DIR/const_debuginfo.rs:+3:13: +3:16 StorageLive(_4); // scope 3 at $DIR/const_debuginfo.rs:+4:9: +4:12 StorageLive(_5); // scope 3 at $DIR/const_debuginfo.rs:+4:15: +4:20 diff --git a/tests/mir-opt/const_prop/bad_op_mod_by_zero.main.ConstProp.diff b/tests/mir-opt/const_prop/bad_op_mod_by_zero.main.ConstProp.diff index ae9ffd519a148..e085a88b2da8b 100644 --- a/tests/mir-opt/const_prop/bad_op_mod_by_zero.main.ConstProp.diff +++ b/tests/mir-opt/const_prop/bad_op_mod_by_zero.main.ConstProp.diff @@ -18,6 +18,7 @@ } bb0: { + StorageLive(_1); // scope 0 at $DIR/bad_op_mod_by_zero.rs:+1:9: +1:10 _1 = const 0_i32; // scope 0 at $DIR/bad_op_mod_by_zero.rs:+1:13: +1:14 StorageLive(_2); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:9: +2:11 - _4 = Eq(_1, const 0_i32); // scope 1 at $DIR/bad_op_mod_by_zero.rs:+2:14: +2:19 diff --git a/tests/mir-opt/const_prop/scalar_literal_propagation.main.ConstProp.diff b/tests/mir-opt/const_prop/scalar_literal_propagation.main.ConstProp.diff index 22f710387db71..e3f5b120a3234 100644 --- a/tests/mir-opt/const_prop/scalar_literal_propagation.main.ConstProp.diff +++ b/tests/mir-opt/const_prop/scalar_literal_propagation.main.ConstProp.diff @@ -11,6 +11,7 @@ } bb0: { + StorageLive(_1); // scope 0 at $DIR/scalar_literal_propagation.rs:+1:9: +1:10 _1 = const 1_u32; // scope 0 at $DIR/scalar_literal_propagation.rs:+1:13: +1:14 StorageLive(_2); // scope 1 at $DIR/scalar_literal_propagation.rs:+2:5: +2:15 - _2 = consume(_1) -> bb1; // scope 1 at $DIR/scalar_literal_propagation.rs:+2:5: +2:15 diff --git a/tests/mir-opt/copy-prop/borrowed_local.f.CopyProp.diff b/tests/mir-opt/copy-prop/borrowed_local.f.CopyProp.diff new file mode 100644 index 0000000000000..b183865a9bcf5 --- /dev/null +++ b/tests/mir-opt/copy-prop/borrowed_local.f.CopyProp.diff @@ -0,0 +1,34 @@ +- // MIR for `f` before CopyProp ++ // MIR for `f` after CopyProp + + fn f() -> bool { + let mut _0: bool; // return place in scope 0 at $DIR/borrowed_local.rs:+0:11: +0:15 + let mut _1: u8; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + let mut _2: &u8; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + let mut _3: u8; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + let mut _4: &u8; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + + bb0: { + _1 = const 5_u8; // scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + _2 = &_1; // scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + _3 = _1; // scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + _4 = &_3; // scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL + _0 = cmp_ref(_2, _4) -> bb1; // scope 0 at $DIR/borrowed_local.rs:+8:13: +8:45 + // mir::Constant + // + span: $DIR/borrowed_local.rs:23:29: 23:36 + // + literal: Const { ty: for<'a, 'b> fn(&'a u8, &'b u8) -> bool {cmp_ref}, val: Value() } + } + + bb1: { +- _0 = opaque::(_3) -> bb2; // scope 0 at $DIR/borrowed_local.rs:+12:13: +12:38 ++ _0 = opaque::(_1) -> bb2; // scope 0 at $DIR/borrowed_local.rs:+12:13: +12:38 + // mir::Constant + // + span: $DIR/borrowed_local.rs:27:28: 27:34 + // + literal: Const { ty: fn(u8) -> bool {opaque::}, val: Value() } + } + + bb2: { + return; // scope 0 at $DIR/borrowed_local.rs:+15:13: +15:21 + } + } + diff --git a/tests/mir-opt/copy-prop/borrowed_local.rs b/tests/mir-opt/copy-prop/borrowed_local.rs new file mode 100644 index 0000000000000..c4b980e2b3516 --- /dev/null +++ b/tests/mir-opt/copy-prop/borrowed_local.rs @@ -0,0 +1,39 @@ +// unit-test: CopyProp + +#![feature(custom_mir, core_intrinsics)] +#![allow(unused_assignments)] +extern crate core; +use core::intrinsics::mir::*; + +fn opaque(_: impl Sized) -> bool { true } + +fn cmp_ref(a: &u8, b: &u8) -> bool { + std::ptr::eq(a as *const u8, b as *const u8) +} + +#[custom_mir(dialect = "analysis", phase = "post-cleanup")] +fn f() -> bool { + mir!( + { + let a = 5_u8; + let r1 = &a; + let b = a; + // We cannot propagate the place `a`. + let r2 = &b; + Call(RET, next, cmp_ref(r1, r2)) + } + next = { + // But we can propagate the value `a`. + Call(RET, ret, opaque(b)) + } + ret = { + Return() + } + ) +} + +fn main() { + assert!(!f()); +} + +// EMIT_MIR borrowed_local.f.CopyProp.diff diff --git a/tests/mir-opt/copy-prop/cycle.main.CopyProp.diff b/tests/mir-opt/copy-prop/cycle.main.CopyProp.diff index 3e61869e82f11..bc5083e1ad01a 100644 --- a/tests/mir-opt/copy-prop/cycle.main.CopyProp.diff +++ b/tests/mir-opt/copy-prop/cycle.main.CopyProp.diff @@ -29,7 +29,7 @@ } bb1: { -- StorageLive(_2); // scope 1 at $DIR/cycle.rs:+2:9: +2:10 + StorageLive(_2); // scope 1 at $DIR/cycle.rs:+2:9: +2:10 _2 = _1; // scope 1 at $DIR/cycle.rs:+2:13: +2:14 - StorageLive(_3); // scope 2 at $DIR/cycle.rs:+3:9: +3:10 - _3 = _2; // scope 2 at $DIR/cycle.rs:+3:13: +3:14 diff --git a/tests/mir-opt/copy-prop/dead_stores_79191.f.CopyProp.after.mir b/tests/mir-opt/copy-prop/dead_stores_79191.f.CopyProp.after.mir index d48b04e2de273..918817da56ce4 100644 --- a/tests/mir-opt/copy-prop/dead_stores_79191.f.CopyProp.after.mir +++ b/tests/mir-opt/copy-prop/dead_stores_79191.f.CopyProp.after.mir @@ -11,6 +11,7 @@ fn f(_1: usize) -> usize { } bb0: { + StorageLive(_2); // scope 0 at $DIR/dead_stores_79191.rs:+1:9: +1:10 _2 = _1; // scope 0 at $DIR/dead_stores_79191.rs:+1:13: +1:14 _1 = const 5_usize; // scope 1 at $DIR/dead_stores_79191.rs:+2:5: +2:10 _1 = _2; // scope 1 at $DIR/dead_stores_79191.rs:+3:5: +3:10 diff --git a/tests/mir-opt/copy-prop/dead_stores_better.f.CopyProp.after.mir b/tests/mir-opt/copy-prop/dead_stores_better.f.CopyProp.after.mir index 727791f50a4ef..cf21fadd43790 100644 --- a/tests/mir-opt/copy-prop/dead_stores_better.f.CopyProp.after.mir +++ b/tests/mir-opt/copy-prop/dead_stores_better.f.CopyProp.after.mir @@ -11,6 +11,7 @@ fn f(_1: usize) -> usize { } bb0: { + StorageLive(_2); // scope 0 at $DIR/dead_stores_better.rs:+1:9: +1:10 _2 = _1; // scope 0 at $DIR/dead_stores_better.rs:+1:13: +1:14 _1 = const 5_usize; // scope 1 at $DIR/dead_stores_better.rs:+2:5: +2:10 _1 = _2; // scope 1 at $DIR/dead_stores_better.rs:+3:5: +3:10 diff --git a/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.diff b/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.diff index 9c3f87f47c12c..6870d7d6c45b4 100644 --- a/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.diff +++ b/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.diff @@ -16,7 +16,9 @@ } bb0: { + StorageLive(_1); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47 _1 = const u8::MAX; // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47 + StorageLive(_2); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47 _2 = const 1_u8; // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47 _5 = CheckedAdd(const u8::MAX, const 1_u8); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL assert(!move (_5.1: bool), "attempt to compute `{} + {}`, which would overflow", const u8::MAX, const 1_u8) -> bb1; // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL diff --git a/tests/mir-opt/funky_arms.float_to_exponential_common.ConstProp.diff b/tests/mir-opt/funky_arms.float_to_exponential_common.ConstProp.diff index 7c5d28069d59d..df9f8dcf1a407 100644 --- a/tests/mir-opt/funky_arms.float_to_exponential_common.ConstProp.diff +++ b/tests/mir-opt/funky_arms.float_to_exponential_common.ConstProp.diff @@ -79,6 +79,7 @@ } bb6: { + StorageLive(_10); // scope 3 at $DIR/funky_arms.rs:+13:17: +13:26 _10 = ((_7 as Some).0: usize); // scope 3 at $DIR/funky_arms.rs:+13:17: +13:26 StorageLive(_11); // scope 3 at $DIR/funky_arms.rs:+15:43: +15:46 _11 = &mut (*_1); // scope 3 at $DIR/funky_arms.rs:+15:43: +15:46 diff --git a/tests/mir-opt/issue_101973.inner.ConstProp.diff b/tests/mir-opt/issue_101973.inner.ConstProp.diff index 002392c5cf81a..30bf2c0684e52 100644 --- a/tests/mir-opt/issue_101973.inner.ConstProp.diff +++ b/tests/mir-opt/issue_101973.inner.ConstProp.diff @@ -33,6 +33,7 @@ bb0: { StorageLive(_2); // scope 0 at $DIR/issue_101973.rs:+1:5: +1:65 StorageLive(_3); // scope 0 at $DIR/issue_101973.rs:+1:5: +1:58 + StorageLive(_4); // scope 0 at $DIR/issue_101973.rs:+1:5: +1:17 StorageLive(_12); // scope 2 at $DIR/issue_101973.rs:7:12: 7:27 StorageLive(_13); // scope 2 at $DIR/issue_101973.rs:7:12: 7:20 _14 = CheckedShr(_1, const 0_i32); // scope 2 at $DIR/issue_101973.rs:7:12: 7:20 @@ -62,6 +63,7 @@ StorageDead(_13); // scope 2 at $DIR/issue_101973.rs:7:26: 7:27 _4 = BitOr(const 0_u32, move _12); // scope 2 at $DIR/issue_101973.rs:7:5: 7:27 StorageDead(_12); // scope 2 at $DIR/issue_101973.rs:7:26: 7:27 + StorageLive(_6); // scope 0 at $DIR/issue_101973.rs:+1:31: +1:57 StorageLive(_7); // scope 0 at $DIR/issue_101973.rs:+1:31: +1:52 StorageLive(_8); // scope 0 at $DIR/issue_101973.rs:+1:32: +1:45 _10 = CheckedShr(_1, const 8_i32); // scope 0 at $DIR/issue_101973.rs:+1:32: +1:45 diff --git a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.diff b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.diff index cc4f7cc06991f..c14780052fb09 100644 --- a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.diff +++ b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.diff @@ -29,6 +29,7 @@ bb0: { StorageLive(_2); // scope 0 at $DIR/issue_76432.rs:+1:9: +1:10 + StorageLive(_4); // scope 0 at $DIR/issue_76432.rs:+1:19: +1:29 StorageLive(_5); // scope 0 at $DIR/issue_76432.rs:+1:20: +1:29 _5 = [_1, _1, _1]; // scope 0 at $DIR/issue_76432.rs:+1:20: +1:29 _4 = &_5; // scope 0 at $DIR/issue_76432.rs:+1:19: +1:29 diff --git a/tests/mir-opt/simplify_match.main.ConstProp.diff b/tests/mir-opt/simplify_match.main.ConstProp.diff index b700adfb105b0..35ffc4963cb63 100644 --- a/tests/mir-opt/simplify_match.main.ConstProp.diff +++ b/tests/mir-opt/simplify_match.main.ConstProp.diff @@ -10,6 +10,7 @@ } bb0: { + StorageLive(_2); // scope 0 at $DIR/simplify_match.rs:+1:17: +1:18 _2 = const false; // scope 0 at $DIR/simplify_match.rs:+1:21: +1:26 - switchInt(_2) -> [0: bb1, otherwise: bb2]; // scope 0 at $DIR/simplify_match.rs:+1:5: +1:31 + switchInt(const false) -> [0: bb1, otherwise: bb2]; // scope 0 at $DIR/simplify_match.rs:+1:5: +1:31 diff --git a/tests/mir-opt/slice_filter.variant_a-{closure#0}.CopyProp.diff b/tests/mir-opt/slice_filter.variant_a-{closure#0}.CopyProp.diff index ca8c04c386fa5..d1f6fd97dc7c6 100644 --- a/tests/mir-opt/slice_filter.variant_a-{closure#0}.CopyProp.diff +++ b/tests/mir-opt/slice_filter.variant_a-{closure#0}.CopyProp.diff @@ -101,16 +101,16 @@ } bb0: { -- StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 _25 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 _3 = &((*_25).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 -- StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 _26 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 _4 = &((*_26).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 -- StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 _27 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 _5 = &((*_27).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 -- StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 _28 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 _6 = &((*_28).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 StorageLive(_7); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 @@ -118,11 +118,10 @@ StorageLive(_9); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:41 _9 = &_3; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:41 StorageLive(_10); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 -- StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 -- _11 = _5; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 -- _10 = &_11; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + _11 = _5; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + _10 = &_11; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 - StorageLive(_29); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _10 = &_5; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 _31 = deref_copy (*_9); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - _29 = _31; // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_30); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL @@ -139,7 +138,7 @@ StorageDead(_33); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_30); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_29); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 StorageDead(_10); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 StorageDead(_9); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 switchInt(move _8) -> [0: bb4, otherwise: bb5]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 @@ -156,11 +155,10 @@ StorageLive(_18); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 _18 = &_5; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 StorageLive(_19); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 -- StorageLive(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 -- _20 = _3; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 -- _19 = &_20; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + StorageLive(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + _20 = _3; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + _19 = &_20; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 - StorageLive(_35); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _19 = &_3; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 _37 = deref_copy (*_18); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - _35 = _37; // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_36); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL @@ -177,7 +175,7 @@ StorageDead(_39); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_36); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_35); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + StorageDead(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 StorageDead(_19); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 StorageDead(_18); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 switchInt(move _17) -> [0: bb6, otherwise: bb7]; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 @@ -205,11 +203,10 @@ StorageLive(_13); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 _13 = &_6; // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 StorageLive(_14); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 -- StorageLive(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 -- _15 = _4; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 -- _14 = &_15; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageLive(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + _15 = _4; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + _14 = &_15; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 - StorageLive(_41); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _14 = &_4; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 _43 = deref_copy (*_13); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - _41 = _43; // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_42); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL @@ -226,7 +223,7 @@ StorageDead(_45); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_42); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_41); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageDead(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 StorageDead(_14); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 StorageDead(_13); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 _7 = move _12; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 @@ -245,11 +242,10 @@ StorageLive(_22); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 _22 = &_4; // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 StorageLive(_23); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 -- StorageLive(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 -- _24 = _6; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 -- _23 = &_24; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageLive(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _24 = _6; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _23 = &_24; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageLive(_47); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _23 = &_6; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 _49 = deref_copy (*_22); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - _47 = _49; // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_48); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL @@ -266,7 +262,7 @@ StorageDead(_51); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_48); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_47); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL -- StorageDead(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 StorageDead(_23); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 StorageDead(_22); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 _16 = move _21; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 diff --git a/tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff b/tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff index 30b49158b4ff8..259cd41189608 100644 --- a/tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff +++ b/tests/mir-opt/slice_filter.variant_a-{closure#0}.DestinationPropagation.diff @@ -11,20 +11,24 @@ let mut _8: bool; // in scope 0 at $DIR/slice_filter.rs:+0:40: +0:46 let mut _9: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:40: +0:41 let mut _10: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:45: +0:46 - let mut _11: bool; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:56 - let mut _12: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:51 - let mut _13: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:55: +0:56 - let mut _14: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:76 - let mut _15: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:66 - let mut _16: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:61 - let mut _17: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:65: +0:66 - let mut _18: bool; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:76 - let mut _19: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:71 - let mut _20: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 - let mut _21: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 - let mut _22: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 - let mut _23: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 - let mut _24: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let _11: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:45: +0:46 + let mut _12: bool; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:56 + let mut _13: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:50: +0:51 + let mut _14: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:55: +0:56 + let _15: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:55: +0:56 + let mut _16: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:76 + let mut _17: bool; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:66 + let mut _18: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:60: +0:61 + let mut _19: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:65: +0:66 + let _20: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:65: +0:66 + let mut _21: bool; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:76 + let mut _22: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:70: +0:71 + let mut _23: &&usize; // in scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + let _24: &usize; // in scope 0 at $DIR/slice_filter.rs:+0:75: +0:76 + let mut _25: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _26: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _27: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 + let mut _28: &(usize, usize, usize, usize); // in scope 0 at $DIR/slice_filter.rs:+0:26: +0:38 scope 1 { debug a => _3; // in scope 1 at $DIR/slice_filter.rs:+0:27: +0:28 debug b => _4; // in scope 1 at $DIR/slice_filter.rs:+0:30: +0:31 @@ -33,78 +37,85 @@ scope 2 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:40: 8:46 debug self => _9; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL debug other => _10; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _25: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _26: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _29: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _30: &usize; // in scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL scope 3 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL - debug self => _25; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - debug other => _26; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _27: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _28: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug self => _29; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _30; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _31: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _32: usize; // in scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL } } scope 4 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:60: 8:66 - debug self => _16; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - debug other => _17; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _29: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _30: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug self => _18; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _19; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _33: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _34: &usize; // in scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL scope 5 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL - debug self => _29; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - debug other => _30; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _31: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _32: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug self => _33; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _34; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _35: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _36: usize; // in scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL } } scope 6 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:50: 8:56 - debug self => _12; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - debug other => _13; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _33: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _34: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug self => _13; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _14; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _37: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _38: &usize; // in scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL scope 7 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL - debug self => _33; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - debug other => _34; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _35: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _36: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug self => _37; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _38; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _39: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _40: usize; // in scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL } } scope 8 (inlined cmp::impls::::le) { // at $DIR/slice_filter.rs:8:70: 8:76 - debug self => _19; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - debug other => _20; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _37: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _38: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug self => _22; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _23; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _41: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _42: &usize; // in scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL scope 9 (inlined cmp::impls::::le) { // at $SRC_DIR/core/src/cmp.rs:LL:COL - debug self => _37; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - debug other => _38; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _39: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - let mut _40: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug self => _41; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + debug other => _42; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _43: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + let mut _44: usize; // in scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL } } } bb0: { - _21 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 - _3 = &((*_21).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 - _22 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 - _4 = &((*_22).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 - _23 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 - _5 = &((*_23).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 - _24 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 - _6 = &((*_24).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + _25 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + _3 = &((*_25).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:27: +0:28 + StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + _26 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + _4 = &((*_26).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:30: +0:31 + StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + _27 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + _5 = &((*_27).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:33: +0:34 + StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + _28 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 + _6 = &((*_28).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:36: +0:37 - StorageLive(_7); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + nop; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 StorageLive(_8); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:46 StorageLive(_9); // scope 1 at $DIR/slice_filter.rs:+0:40: +0:41 _9 = &_3; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:41 StorageLive(_10); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 - _10 = &_5; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 - _25 = deref_copy (*_9); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - _26 = deref_copy (*_10); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_27); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - _27 = (*_25); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_28); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - _28 = (*_26); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - _8 = Le(move _27, move _28); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_28); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_27); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + _11 = _5; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + _10 = &_11; // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 + _29 = deref_copy (*_9); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + _30 = deref_copy (*_10); // scope 2 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_31); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + _31 = (*_29); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_32); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + _32 = (*_30); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + _8 = Le(move _31, move _32); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_32); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_31); // scope 3 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 StorageDead(_10); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 StorageDead(_9); // scope 1 at $DIR/slice_filter.rs:+0:45: +0:46 switchInt(move _8) -> [0: bb4, otherwise: bb5]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 @@ -116,29 +127,32 @@ } bb2: { -- StorageLive(_14); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 +- StorageLive(_16); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 - StorageLive(_15); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:66 - StorageLive(_16); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 - _16 = &_5; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 - StorageLive(_17); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 - _17 = &_3; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 - _29 = deref_copy (*_16); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - _30 = deref_copy (*_17); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_31); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - _31 = (*_29); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_32); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - _32 = (*_30); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - _15 = Le(move _31, move _32); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_32); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_31); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_17); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 - StorageDead(_16); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 - switchInt(move _15) -> [0: bb6, otherwise: bb7]; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + StorageLive(_17); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:66 + StorageLive(_18); // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 + _18 = &_5; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:61 + StorageLive(_19); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + StorageLive(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + _20 = _3; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + _19 = &_20; // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + _33 = deref_copy (*_18); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + _34 = deref_copy (*_19); // scope 4 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_35); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + _35 = (*_33); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_36); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + _36 = (*_34); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + _17 = Le(move _35, move _36); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_36); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_35); // scope 5 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_20); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + StorageDead(_19); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + StorageDead(_18); // scope 1 at $DIR/slice_filter.rs:+0:65: +0:66 + switchInt(move _17) -> [0: bb6, otherwise: bb7]; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 } bb3: { -- StorageDead(_14); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageDead(_16); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageDead(_7); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 @@ -146,74 +160,80 @@ } bb4: { -- StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 +- StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + nop; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 goto -> bb2; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 } bb5: { -- StorageLive(_11); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:56 +- StorageLive(_12); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:56 + nop; // scope 1 at $DIR/slice_filter.rs:+0:50: +0:56 - StorageLive(_12); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 - _12 = &_6; // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 - StorageLive(_13); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 - _13 = &_4; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 - _33 = deref_copy (*_12); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - _34 = deref_copy (*_13); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_35); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - _35 = (*_33); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_36); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - _36 = (*_34); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - _11 = Le(move _35, move _36); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_36); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_35); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_13); // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 + _13 = &_6; // scope 1 at $DIR/slice_filter.rs:+0:50: +0:51 + StorageLive(_14); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageLive(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + _15 = _4; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + _14 = &_15; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + _37 = deref_copy (*_13); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + _38 = deref_copy (*_14); // scope 6 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_39); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + _39 = (*_37); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_40); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + _40 = (*_38); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + _12 = Le(move _39, move _40); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_40); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_39); // scope 7 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_15); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + StorageDead(_14); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 StorageDead(_13); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 - StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 -- _7 = move _11; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 -- StorageDead(_11); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 +- _7 = move _12; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 +- StorageDead(_12); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 + nop; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:56 + nop; // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 StorageDead(_8); // scope 1 at $DIR/slice_filter.rs:+0:55: +0:56 - switchInt(move _7) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 -+ switchInt(move _11) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 ++ switchInt(move _12) -> [0: bb2, otherwise: bb1]; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 } bb6: { -- _14 = const false; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 +- _16 = const false; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + _0 = const false; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 } bb7: { -- StorageLive(_18); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:76 +- StorageLive(_21); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:70: +0:76 - StorageLive(_19); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 - _19 = &_4; // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 - StorageLive(_20); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - _20 = &_6; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - _37 = deref_copy (*_19); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - _38 = deref_copy (*_20); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_39); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - _39 = (*_37); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageLive(_40); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - _40 = (*_38); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -- _18 = Le(move _39, move _40); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL -+ _0 = Le(move _39, move _40); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_40); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_39); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL - StorageDead(_20); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageDead(_19); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 -- _14 = move _18; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + StorageLive(_22); // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 + _22 = &_4; // scope 1 at $DIR/slice_filter.rs:+0:70: +0:71 + StorageLive(_23); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageLive(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _24 = _6; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _23 = &_24; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + _41 = deref_copy (*_22); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + _42 = deref_copy (*_23); // scope 8 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_43); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + _43 = (*_41); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageLive(_44); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + _44 = (*_42); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL +- _21 = Le(move _43, move _44); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL ++ _0 = Le(move _43, move _44); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_44); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_43); // scope 9 at $SRC_DIR/core/src/cmp.rs:LL:COL + StorageDead(_24); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_23); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + StorageDead(_22); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- _16 = move _21; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 goto -> bb8; // scope 1 at $DIR/slice_filter.rs:+0:60: +0:76 } bb8: { -- StorageDead(_18); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- StorageDead(_21); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 - StorageDead(_15); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 -- _0 = move _14; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + StorageDead(_17); // scope 1 at $DIR/slice_filter.rs:+0:75: +0:76 +- _0 = move _16; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 + nop; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 goto -> bb3; // scope 1 at $DIR/slice_filter.rs:+0:40: +0:76 } diff --git a/tests/mir-opt/slice_filter.variant_b-{closure#0}.CopyProp.diff b/tests/mir-opt/slice_filter.variant_b-{closure#0}.CopyProp.diff index 5e4bdbdfa2e2f..c3b8e7d2eba25 100644 --- a/tests/mir-opt/slice_filter.variant_b-{closure#0}.CopyProp.diff +++ b/tests/mir-opt/slice_filter.variant_b-{closure#0}.CopyProp.diff @@ -33,16 +33,16 @@ } bb0: { -- StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 + StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 _21 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 _3 = ((*_21).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 -- StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 + StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 _22 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 _4 = ((*_22).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 -- StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 + StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 _23 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 _5 = ((*_23).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 -- StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 + StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 _24 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 _6 = ((*_24).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 StorageLive(_7); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 diff --git a/tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff b/tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff index 45af6600cd4e8..a43e84d29c7ad 100644 --- a/tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff +++ b/tests/mir-opt/slice_filter.variant_b-{closure#0}.DestinationPropagation.diff @@ -25,12 +25,16 @@ } bb0: { + StorageLive(_3); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 _13 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 _3 = ((*_13).0: usize); // scope 0 at $DIR/slice_filter.rs:+0:29: +0:30 + StorageLive(_4); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 _14 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 _4 = ((*_14).1: usize); // scope 0 at $DIR/slice_filter.rs:+0:32: +0:33 + StorageLive(_5); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 _15 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 _5 = ((*_15).2: usize); // scope 0 at $DIR/slice_filter.rs:+0:35: +0:36 + StorageLive(_6); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 _16 = deref_copy (*_2); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 _6 = ((*_16).3: usize); // scope 0 at $DIR/slice_filter.rs:+0:38: +0:39 - StorageLive(_7); // scope 1 at $DIR/slice_filter.rs:+0:42: +0:58 diff --git a/tests/mir-opt/try_identity_e2e.new.PreCodegen.after.mir b/tests/mir-opt/try_identity_e2e.new.PreCodegen.after.mir index a4d2660ca6aeb..7c67d2abcf7c3 100644 --- a/tests/mir-opt/try_identity_e2e.new.PreCodegen.after.mir +++ b/tests/mir-opt/try_identity_e2e.new.PreCodegen.after.mir @@ -30,6 +30,7 @@ fn new(_1: Result) -> Result { } bb1: { + StorageLive(_5); // scope 0 at $DIR/try_identity_e2e.rs:+5:21: +5:22 _5 = move ((_1 as Err).0: E); // scope 0 at $DIR/try_identity_e2e.rs:+5:21: +5:22 Deinit(_2); // scope 2 at $DIR/try_identity_e2e.rs:+5:27: +5:48 ((_2 as Break).0: E) = move _5; // scope 2 at $DIR/try_identity_e2e.rs:+5:27: +5:48 @@ -39,6 +40,7 @@ fn new(_1: Result) -> Result { } bb2: { + StorageLive(_4); // scope 0 at $DIR/try_identity_e2e.rs:+4:20: +4:21 _4 = move ((_1 as Ok).0: T); // scope 0 at $DIR/try_identity_e2e.rs:+4:20: +4:21 Deinit(_2); // scope 1 at $DIR/try_identity_e2e.rs:+4:26: +4:50 ((_2 as Continue).0: T) = move _4; // scope 1 at $DIR/try_identity_e2e.rs:+4:26: +4:50 @@ -48,6 +50,7 @@ fn new(_1: Result) -> Result { } bb3: { + StorageLive(_8); // scope 0 at $DIR/try_identity_e2e.rs:+9:32: +9:33 _8 = move ((_2 as Break).0: E); // scope 0 at $DIR/try_identity_e2e.rs:+9:32: +9:33 Deinit(_0); // scope 4 at $DIR/try_identity_e2e.rs:+9:45: +9:51 ((_0 as Err).0: E) = move _8; // scope 4 at $DIR/try_identity_e2e.rs:+9:45: +9:51 @@ -61,6 +64,7 @@ fn new(_1: Result) -> Result { } bb5: { + StorageLive(_7); // scope 0 at $DIR/try_identity_e2e.rs:+8:35: +8:36 _7 = move ((_2 as Continue).0: T); // scope 0 at $DIR/try_identity_e2e.rs:+8:35: +8:36 Deinit(_0); // scope 0 at $DIR/try_identity_e2e.rs:+1:5: +11:6 ((_0 as Ok).0: T) = move _7; // scope 0 at $DIR/try_identity_e2e.rs:+1:5: +11:6 diff --git a/tests/mir-opt/try_identity_e2e.old.PreCodegen.after.mir b/tests/mir-opt/try_identity_e2e.old.PreCodegen.after.mir index 37851c66a6076..4a838e140262e 100644 --- a/tests/mir-opt/try_identity_e2e.old.PreCodegen.after.mir +++ b/tests/mir-opt/try_identity_e2e.old.PreCodegen.after.mir @@ -19,6 +19,7 @@ fn old(_1: Result) -> Result { } bb1: { + StorageLive(_4); // scope 0 at $DIR/try_identity_e2e.rs:+4:17: +4:18 _4 = move ((_1 as Err).0: E); // scope 0 at $DIR/try_identity_e2e.rs:+4:17: +4:18 Deinit(_0); // scope 2 at $DIR/try_identity_e2e.rs:+4:30: +4:36 ((_0 as Err).0: E) = move _4; // scope 2 at $DIR/try_identity_e2e.rs:+4:30: +4:36 @@ -31,6 +32,7 @@ fn old(_1: Result) -> Result { } bb3: { + StorageLive(_3); // scope 0 at $DIR/try_identity_e2e.rs:+3:16: +3:17 _3 = move ((_1 as Ok).0: T); // scope 0 at $DIR/try_identity_e2e.rs:+3:16: +3:17 Deinit(_0); // scope 0 at $DIR/try_identity_e2e.rs:+1:5: +6:6 ((_0 as Ok).0: T) = move _3; // scope 0 at $DIR/try_identity_e2e.rs:+1:5: +6:6 From 263da251af6b1735487add274a4ed09487c69412 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 22 Jan 2023 20:39:44 +0000 Subject: [PATCH 427/500] Use successor location for dominator check. The assignment is complete only after the statement. This marks self-assignments `x = x + 1` as non-sSA. --- compiler/rustc_mir_transform/src/ssa.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_mir_transform/src/ssa.rs b/compiler/rustc_mir_transform/src/ssa.rs index b6e0c6e615098..bc3fe65cf6c34 100644 --- a/compiler/rustc_mir_transform/src/ssa.rs +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -162,7 +162,7 @@ impl<'tcx> Visitor<'tcx> for SsaVisitor { Set1::Empty | Set1::Many => false, Set1::One(LocationExtended::Arg) => true, Set1::One(LocationExtended::Plain(assign)) => { - assign.dominates(loc, &self.dominators) + assign.successor_within_block().dominates(loc, &self.dominators) } }; // We are visiting a use that is not dominated by an assignment. From 80a1536c7ab73c867d5a60f4441058e7e2231d8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Sun, 22 Jan 2023 12:05:36 +0100 Subject: [PATCH 428/500] recover more unbraced const args --- .../rustc_parse/src/parser/diagnostics.rs | 22 ++++ compiler/rustc_parse/src/parser/path.rs | 48 +++++--- .../const-generics/bad-const-generic-exprs.rs | 34 +++++- .../bad-const-generic-exprs.stderr | 106 +++++++++++++++++- 4 files changed, 188 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 4c918c6702ed9..6596a06afab65 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -2353,6 +2353,28 @@ impl<'a> Parser<'a> { Err(err) } + /// Try to recover from an unbraced const argument whose first token [could begin a type][ty]. + /// + /// [ty]: token::Token::can_begin_type + pub(crate) fn recover_unbraced_const_arg_that_can_begin_ty( + &mut self, + mut snapshot: SnapshotParser<'a>, + ) -> Option> { + match snapshot.parse_expr_res(Restrictions::CONST_EXPR, None) { + // Since we don't know the exact reason why we failed to parse the type or the + // expression, employ a simple heuristic to weed out some pathological cases. + Ok(expr) if let token::Comma | token::Gt = snapshot.token.kind => { + self.restore_snapshot(snapshot); + Some(expr) + } + Ok(_) => None, + Err(err) => { + err.cancel(); + None + } + } + } + /// Creates a dummy const argument, and reports that the expression must be enclosed in braces pub fn dummy_const_arg_needs_braces( &self, diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index 5333d3b8587dd..2e706a00cf7f3 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -675,22 +675,42 @@ impl<'a> Parser<'a> { GenericArg::Const(self.parse_const_arg()?) } else if self.check_type() { // Parse type argument. - let is_const_fn = - self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Parenthesis)); - let mut snapshot = self.create_snapshot_for_diagnostic(); + + // Proactively create a parser snapshot enabling us to rewind and try to reparse the + // input as a const expression in case we fail to parse a type. If we successfully + // do so, we will report an error that it needs to be wrapped in braces. + let mut snapshot = None; + if self.may_recover() && self.token.can_begin_expr() { + snapshot = Some(self.create_snapshot_for_diagnostic()); + } + match self.parse_ty() { - Ok(ty) => GenericArg::Type(ty), + Ok(ty) => { + // Since the type parser recovers from some malformed slice and array types and + // successfully returns a type, we need to look for `TyKind::Err`s in the + // type to determine if error recovery has occurred and if the input is not a + // syntactically valid type after all. + if let ast::TyKind::Slice(inner_ty) | ast::TyKind::Array(inner_ty, _) = &ty.kind + && let ast::TyKind::Err = inner_ty.kind + && let Some(snapshot) = snapshot + && let Some(expr) = self.recover_unbraced_const_arg_that_can_begin_ty(snapshot) + { + return Ok(Some(self.dummy_const_arg_needs_braces( + self.struct_span_err(expr.span, "invalid const generic expression"), + expr.span, + ))); + } + + GenericArg::Type(ty) + } Err(err) => { - if is_const_fn { - match (*snapshot).parse_expr_res(Restrictions::CONST_EXPR, None) { - Ok(expr) => { - self.restore_snapshot(snapshot); - return Ok(Some(self.dummy_const_arg_needs_braces(err, expr.span))); - } - Err(err) => { - err.cancel(); - } - } + if let Some(snapshot) = snapshot + && let Some(expr) = self.recover_unbraced_const_arg_that_can_begin_ty(snapshot) + { + return Ok(Some(self.dummy_const_arg_needs_braces( + err, + expr.span, + ))); } // Try to recover from possible `const` arg without braces. return self.recover_const_arg(start, err).map(Some); diff --git a/tests/ui/const-generics/bad-const-generic-exprs.rs b/tests/ui/const-generics/bad-const-generic-exprs.rs index ca91643edf727..423752ca25eba 100644 --- a/tests/ui/const-generics/bad-const-generic-exprs.rs +++ b/tests/ui/const-generics/bad-const-generic-exprs.rs @@ -13,10 +13,34 @@ fn main() { let _: Wow; //~^ ERROR expected one of //~| HELP expressions must be enclosed in braces to be used as const generic arguments - - // FIXME(compiler-errors): This one is still unsatisfying, - // and probably a case I could see someone typing by accident.. + let _: Wow<[]>; + //~^ ERROR expected type + //~| HELP expressions must be enclosed in braces to be used as const generic arguments let _: Wow<[12]>; - //~^ ERROR expected type, found - //~| ERROR type provided when a constant was expected + //~^ ERROR expected type + //~| ERROR invalid const generic expression + //~| HELP expressions must be enclosed in braces to be used as const generic arguments + let _: Wow<[0, 1, 3]>; + //~^ ERROR expected type + //~| HELP expressions must be enclosed in braces to be used as const generic arguments + let _: Wow<[0xff; 8]>; + //~^ ERROR expected type + //~| ERROR invalid const generic expression + //~| HELP expressions must be enclosed in braces to be used as const generic arguments + let _: Wow<[1, 2]>; // Regression test for issue #81698. + //~^ ERROR expected type + //~| HELP expressions must be enclosed in braces to be used as const generic arguments + let _: Wow<&0>; + //~^ ERROR expected type + //~| HELP expressions must be enclosed in braces to be used as const generic arguments + let _: Wow<("", 0)>; + //~^ ERROR expected type + //~| HELP expressions must be enclosed in braces to be used as const generic arguments + let _: Wow<(1 + 2) * 3>; + //~^ ERROR expected type + //~| HELP expressions must be enclosed in braces to be used as const generic arguments + // FIXME(fmease): This one is pretty bad. + let _: Wow; + //~^ ERROR expected one of + //~| HELP you might have meant to end the type parameters here } diff --git a/tests/ui/const-generics/bad-const-generic-exprs.stderr b/tests/ui/const-generics/bad-const-generic-exprs.stderr index 24668b08b8a56..17a63a96fe4fe 100644 --- a/tests/ui/const-generics/bad-const-generic-exprs.stderr +++ b/tests/ui/const-generics/bad-const-generic-exprs.stderr @@ -42,18 +42,118 @@ help: expressions must be enclosed in braces to be used as const generic argumen LL | let _: Wow<{ A.0 }>; | + + +error: expected type, found `]` + --> $DIR/bad-const-generic-exprs.rs:16:17 + | +LL | let _: Wow<[]>; + | ^ expected type + | +help: expressions must be enclosed in braces to be used as const generic arguments + | +LL | let _: Wow<{ [] }>; + | + + + error: expected type, found `12` --> $DIR/bad-const-generic-exprs.rs:19:17 | LL | let _: Wow<[12]>; | ^^ expected type -error[E0747]: type provided when a constant was expected +error: invalid const generic expression --> $DIR/bad-const-generic-exprs.rs:19:16 | LL | let _: Wow<[12]>; | ^^^^ + | +help: expressions must be enclosed in braces to be used as const generic arguments + | +LL | let _: Wow<{ [12] }>; + | + + + +error: expected type, found `0` + --> $DIR/bad-const-generic-exprs.rs:23:17 + | +LL | let _: Wow<[0, 1, 3]>; + | ^ expected type + | +help: expressions must be enclosed in braces to be used as const generic arguments + | +LL | let _: Wow<{ [0, 1, 3] }>; + | + + + +error: expected type, found `0xff` + --> $DIR/bad-const-generic-exprs.rs:26:17 + | +LL | let _: Wow<[0xff; 8]>; + | ^^^^ expected type + +error: invalid const generic expression + --> $DIR/bad-const-generic-exprs.rs:26:16 + | +LL | let _: Wow<[0xff; 8]>; + | ^^^^^^^^^ + | +help: expressions must be enclosed in braces to be used as const generic arguments + | +LL | let _: Wow<{ [0xff; 8] }>; + | + + + +error: expected type, found `1` + --> $DIR/bad-const-generic-exprs.rs:30:17 + | +LL | let _: Wow<[1, 2]>; // Regression test for issue #81698. + | ^ expected type + | +help: expressions must be enclosed in braces to be used as const generic arguments + | +LL | let _: Wow<{ [1, 2] }>; // Regression test for issue #81698. + | + + + +error: expected type, found `0` + --> $DIR/bad-const-generic-exprs.rs:33:17 + | +LL | let _: Wow<&0>; + | ^ expected type + | +help: expressions must be enclosed in braces to be used as const generic arguments + | +LL | let _: Wow<{ &0 }>; + | + + + +error: expected type, found `""` + --> $DIR/bad-const-generic-exprs.rs:36:17 + | +LL | let _: Wow<("", 0)>; + | ^^ expected type + | +help: expressions must be enclosed in braces to be used as const generic arguments + | +LL | let _: Wow<{ ("", 0) }>; + | + + + +error: expected type, found `1` + --> $DIR/bad-const-generic-exprs.rs:39:17 + | +LL | let _: Wow<(1 + 2) * 3>; + | ^ expected type + | +help: expressions must be enclosed in braces to be used as const generic arguments + | +LL | let _: Wow<{ (1 + 2) * 3 }>; + | + + + +error: expected one of `,` or `>`, found `0` + --> $DIR/bad-const-generic-exprs.rs:43:17 + | +LL | let _: Wow; + | - ^ expected one of `,` or `>` + | | + | while parsing the type for `_` + | +help: you might have meant to end the type parameters here + | +LL | let _: Wow0>; + | + -error: aborting due to 6 previous errors +error: aborting due to 15 previous errors -For more information about this error, try `rustc --explain E0747`. From caefec955f1226652b734a4a2cc46a8e9d405c24 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 11 Sep 2022 11:22:47 +0200 Subject: [PATCH 429/500] Do not abort compilation when failing to normalize opaque types. --- .../src/traits/error_reporting/mod.rs | 38 ++++++++++++++++--- .../src/traits/query/normalize.rs | 16 +++++--- 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index 98917430d241d..b167b9b566d6d 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -101,6 +101,18 @@ pub trait InferCtxtExt<'tcx> { } pub trait TypeErrCtxtExt<'tcx> { + fn build_overflow_error( + &self, + predicate: &T, + span: Span, + suggest_increasing_limit: bool, + ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> + where + T: fmt::Display + + TypeFoldable<'tcx> + + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>, + >>::Error: std::fmt::Debug; + fn report_overflow_error( &self, predicate: &T, @@ -478,6 +490,26 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { suggest_increasing_limit: bool, mutate: impl FnOnce(&mut Diagnostic), ) -> ! + where + T: fmt::Display + + TypeFoldable<'tcx> + + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>, + >>::Error: std::fmt::Debug, + { + let mut err = self.build_overflow_error(predicate, span, suggest_increasing_limit); + mutate(&mut err); + err.emit(); + + self.tcx.sess.abort_if_errors(); + bug!(); + } + + fn build_overflow_error( + &self, + predicate: &T, + span: Span, + suggest_increasing_limit: bool, + ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> where T: fmt::Display + TypeFoldable<'tcx> @@ -511,11 +543,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { self.suggest_new_overflow_limit(&mut err); } - mutate(&mut err); - - err.emit(); - self.tcx.sess.abort_if_errors(); - bug!(); + err } /// Reports that an overflow has occurred and halts compilation. We diff --git a/compiler/rustc_trait_selection/src/traits/query/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/normalize.rs index 27247271d1f4d..8249144f57aae 100644 --- a/compiler/rustc_trait_selection/src/traits/query/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/normalize.rs @@ -216,12 +216,16 @@ impl<'cx, 'tcx> FallibleTypeFolder<'tcx> for QueryNormalizer<'cx, 'tcx> { let substs = substs.try_fold_with(self)?; let recursion_limit = self.tcx().recursion_limit(); if !recursion_limit.value_within_limit(self.anon_depth) { - self.infcx.err_ctxt().report_overflow_error( - &ty, - self.cause.span, - true, - |_| {}, - ); + // A closure or generator may have itself as in its upvars. This + // should be checked handled by the recursion check for opaque types, + // but we may end up here before that check can happen. In that case, + // we delay a bug to mark the trip, and continue without revealing the + // opaque. + self.infcx + .err_ctxt() + .build_overflow_error(&ty, self.cause.span, true) + .delay_as_bug(); + return ty.try_super_fold_with(self); } let generic_ty = self.tcx().bound_type_of(def_id); From 2870ce01b858acf16dacab7877186a5c1f265c6b Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 11 Sep 2022 14:42:43 +0200 Subject: [PATCH 430/500] Impl HashStable/Encodable/Decodable for ObligationCause. --- compiler/rustc_hir/src/hir.rs | 4 +-- compiler/rustc_middle/src/traits/mod.rs | 28 ++++++++++------ compiler/rustc_middle/src/ty/adt.rs | 2 +- compiler/rustc_middle/src/ty/codec.rs | 33 +++++++++++++++++-- .../rustc_middle/src/ty/structural_impls.rs | 1 + 5 files changed, 53 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 5a620263e4299..b688922a31130 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2106,8 +2106,8 @@ pub enum LocalSource { } /// Hints at the original code for a `match _ { .. }`. -#[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)] -#[derive(HashStable_Generic)] +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] +#[derive(HashStable_Generic, Encodable, Decodable)] pub enum MatchSource { /// A `match _ { .. }`. Normal, diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index f6fae8ab55274..cf3dce4806492 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -37,7 +37,7 @@ pub use self::chalk::{ChalkEnvironmentAndGoal, RustInterner as ChalkRustInterner /// Depending on the stage of compilation, we want projection to be /// more or less conservative. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)] pub enum Reveal { /// At type-checking time, we refuse to project any associated /// type that is marked `default`. Non-`default` ("final") types @@ -90,7 +90,8 @@ pub enum Reveal { /// /// We do not want to intern this as there are a lot of obligation causes which /// only live for a short period of time. -#[derive(Clone, Debug, PartialEq, Eq, Lift)] +#[derive(Clone, Debug, PartialEq, Eq, Lift, HashStable, TyEncodable, TyDecodable)] +#[derive(TypeVisitable, TypeFoldable)] pub struct ObligationCause<'tcx> { pub span: Span, @@ -197,14 +198,16 @@ impl<'tcx> ObligationCause<'tcx> { } } -#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)] +#[derive(TypeVisitable, TypeFoldable)] pub struct UnifyReceiverContext<'tcx> { pub assoc_item: ty::AssocItem, pub param_env: ty::ParamEnv<'tcx>, pub substs: SubstsRef<'tcx>, } -#[derive(Clone, PartialEq, Eq, Hash, Lift, Default)] +#[derive(Clone, PartialEq, Eq, Hash, Lift, Default, HashStable)] +#[derive(TypeVisitable, TypeFoldable, TyEncodable, TyDecodable)] pub struct InternedObligationCauseCode<'tcx> { /// `None` for `ObligationCauseCode::MiscObligation` (a common case, occurs ~60% of /// the time). `Some` otherwise. @@ -239,7 +242,8 @@ impl<'tcx> std::ops::Deref for InternedObligationCauseCode<'tcx> { } } -#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)] +#[derive(TypeVisitable, TypeFoldable)] pub enum ObligationCauseCode<'tcx> { /// Not well classified or should be obvious from the span. MiscObligation, @@ -447,7 +451,8 @@ pub enum ObligationCauseCode<'tcx> { /// This information is used to obtain an `hir::Ty`, which /// we can walk in order to obtain precise spans for any /// 'nested' types (e.g. `Foo` in `Option`). -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)] +#[derive(TypeVisitable, TypeFoldable)] pub enum WellFormedLoc { /// Use the type of the provided definition. Ty(LocalDefId), @@ -464,7 +469,8 @@ pub enum WellFormedLoc { }, } -#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)] +#[derive(TypeVisitable, TypeFoldable)] pub struct ImplDerivedObligationCause<'tcx> { pub derived: DerivedObligationCause<'tcx>, pub impl_def_id: DefId, @@ -518,7 +524,8 @@ impl<'tcx> ty::Lift<'tcx> for StatementAsExpression { } } -#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)] +#[derive(TypeVisitable, TypeFoldable)] pub struct MatchExpressionArmCause<'tcx> { pub arm_block_id: Option, pub arm_ty: Ty<'tcx>, @@ -534,7 +541,7 @@ pub struct MatchExpressionArmCause<'tcx> { } #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] -#[derive(Lift, TypeFoldable, TypeVisitable)] +#[derive(Lift, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)] pub struct IfExpressionCause<'tcx> { pub then_id: hir::HirId, pub else_id: hir::HirId, @@ -544,7 +551,8 @@ pub struct IfExpressionCause<'tcx> { pub opt_suggest_box_span: Option, } -#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)] +#[derive(TypeVisitable, TypeFoldable)] pub struct DerivedObligationCause<'tcx> { /// The trait predicate of the parent obligation that led to the /// current obligation. Note that only trait obligations lead to diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index d3d667f68407f..099a784511827 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -188,7 +188,7 @@ impl<'tcx> AdtDef<'tcx> { } } -#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, TyEncodable, TyDecodable)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, HashStable, TyEncodable, TyDecodable)] pub enum AdtKind { Struct, Union, diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 8cc8286c1dbe6..b9a1e23879cca 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -157,6 +157,14 @@ impl<'tcx, E: TyEncoder>> Encodable for AllocId { } } +impl<'tcx, E: TyEncoder>> Encodable for ty::ParamEnv<'tcx> { + fn encode(&self, e: &mut E) { + self.caller_bounds().encode(e); + self.reveal().encode(e); + self.constness().encode(e); + } +} + #[inline] fn decode_arena_allocable< 'tcx, @@ -280,8 +288,17 @@ impl<'tcx, D: TyDecoder>> Decodable for ty::SymbolName<'tcx> } } +impl<'tcx, D: TyDecoder>> Decodable for ty::ParamEnv<'tcx> { + fn decode(d: &mut D) -> Self { + let caller_bounds = Decodable::decode(d); + let reveal = Decodable::decode(d); + let constness = Decodable::decode(d); + ty::ParamEnv::new(caller_bounds, reveal, constness) + } +} + macro_rules! impl_decodable_via_ref { - ($($t:ty),+) => { + ($($t:ty,)+) => { $(impl<'tcx, D: TyDecoder>> Decodable for $t { fn decode(decoder: &mut D) -> Self { RefDecodable::decode(decoder) @@ -373,6 +390,15 @@ impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for ty::List>> RefDecodable<'tcx, D> for ty::List> { + fn decode(decoder: &mut D) -> &'tcx Self { + let len = decoder.read_usize(); + let predicates: Vec<_> = + (0..len).map::, _>(|_| Decodable::decode(decoder)).collect(); + decoder.interner().intern_predicates(&predicates) + } +} + impl_decodable_via_ref! { &'tcx ty::TypeckResults<'tcx>, &'tcx ty::List>, @@ -382,7 +408,8 @@ impl_decodable_via_ref! { &'tcx mir::UnsafetyCheckResult, &'tcx mir::BorrowCheckResult<'tcx>, &'tcx mir::coverage::CodeRegion, - &'tcx ty::List + &'tcx ty::List, + &'tcx ty::List>, } #[macro_export] @@ -519,6 +546,8 @@ macro_rules! impl_binder_encode_decode { impl_binder_encode_decode! { &'tcx ty::List>, ty::FnSig<'tcx>, + ty::Predicate<'tcx>, + ty::TraitPredicate<'tcx>, ty::ExistentialPredicate<'tcx>, ty::TraitRef<'tcx>, Vec>, diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 2de886a3e817f..16915443ba818 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -201,6 +201,7 @@ TrivialTypeTraversalAndLiftImpls! { bool, usize, ::rustc_target::abi::VariantIdx, + u16, u32, u64, String, From cb873b2d93aa5f9eedc389268a14cebc2cb1db5c Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Wed, 28 Sep 2022 18:16:23 +0200 Subject: [PATCH 431/500] Separate trait selection from ambiguity reporting. --- compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs | 4 ++-- compiler/rustc_hir_typeck/src/lib.rs | 6 +++++- .../src/infer/canonical/query_response.rs | 2 +- compiler/rustc_infer/src/traits/engine.rs | 15 +++++++++++++-- .../rustc_trait_selection/src/solve/fulfill.rs | 7 +------ .../src/traits/chalk_fulfill.rs | 10 +--------- .../rustc_trait_selection/src/traits/fulfill.rs | 9 +-------- compiler/rustc_traits/src/codegen.rs | 2 +- 8 files changed, 25 insertions(+), 30 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index e9858aef6d0bf..42f4b49889a2d 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -525,8 +525,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } #[instrument(skip(self), level = "debug")] - pub(in super::super) fn select_all_obligations_or_error(&self) { - let mut errors = self.fulfillment_cx.borrow_mut().select_all_or_error(&self); + pub(in super::super) fn report_ambiguity_errors(&self) { + let mut errors = self.fulfillment_cx.borrow_mut().collect_remaining_errors(); if !errors.is_empty() { self.adjust_fulfillment_errors_for_expr_obligation(&mut errors); diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 04ac9c085ea21..899ec9ff9de0f 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -301,7 +301,11 @@ fn typeck_with_fallback<'tcx>( fcx.require_type_is_sized(ty, span, code); } - fcx.select_all_obligations_or_error(); + fcx.select_obligations_where_possible(|_| {}); + + if let None = fcx.infcx.tainted_by_errors() { + fcx.report_ambiguity_errors(); + } if let None = fcx.infcx.tainted_by_errors() { fcx.check_transmutes(); diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index 3d49182f0b817..9174bd524bee6 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -17,7 +17,7 @@ use crate::infer::region_constraints::{Constraint, RegionConstraintData}; use crate::infer::{InferCtxt, InferOk, InferResult, NllRegionVariableOrigin}; use crate::traits::query::{Fallible, NoSolution}; use crate::traits::{Obligation, ObligationCause, PredicateObligation}; -use crate::traits::{PredicateObligations, TraitEngine}; +use crate::traits::{PredicateObligations, TraitEngine, TraitEngineExt}; use rustc_data_structures::captures::Captures; use rustc_index::vec::Idx; use rustc_index::vec::IndexVec; diff --git a/compiler/rustc_infer/src/traits/engine.rs b/compiler/rustc_infer/src/traits/engine.rs index fcde00056cbf1..805eb95e31612 100644 --- a/compiler/rustc_infer/src/traits/engine.rs +++ b/compiler/rustc_infer/src/traits/engine.rs @@ -36,10 +36,10 @@ pub trait TraitEngine<'tcx>: 'tcx { obligation: PredicateObligation<'tcx>, ); - fn select_all_or_error(&mut self, infcx: &InferCtxt<'tcx>) -> Vec>; - fn select_where_possible(&mut self, infcx: &InferCtxt<'tcx>) -> Vec>; + fn collect_remaining_errors(&mut self) -> Vec>; + fn pending_obligations(&self) -> Vec>; } @@ -49,6 +49,8 @@ pub trait TraitEngineExt<'tcx> { infcx: &InferCtxt<'tcx>, obligations: impl IntoIterator>, ); + + fn select_all_or_error(&mut self, infcx: &InferCtxt<'tcx>) -> Vec>; } impl<'tcx, T: ?Sized + TraitEngine<'tcx>> TraitEngineExt<'tcx> for T { @@ -61,4 +63,13 @@ impl<'tcx, T: ?Sized + TraitEngine<'tcx>> TraitEngineExt<'tcx> for T { self.register_predicate_obligation(infcx, obligation); } } + + fn select_all_or_error(&mut self, infcx: &InferCtxt<'tcx>) -> Vec> { + let errors = self.select_where_possible(infcx); + if !errors.is_empty() { + return errors; + } + + self.collect_remaining_errors() + } } diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index 278024b22760a..45507ed4dcc9a 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -40,12 +40,7 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> { self.obligations.push(obligation); } - fn select_all_or_error(&mut self, infcx: &InferCtxt<'tcx>) -> Vec> { - let errors = self.select_where_possible(infcx); - if !errors.is_empty() { - return errors; - } - + fn collect_remaining_errors(&mut self) -> Vec> { self.obligations .drain(..) .map(|obligation| FulfillmentError { diff --git a/compiler/rustc_trait_selection/src/traits/chalk_fulfill.rs b/compiler/rustc_trait_selection/src/traits/chalk_fulfill.rs index 61d09189798ea..76e31845797aa 100644 --- a/compiler/rustc_trait_selection/src/traits/chalk_fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/chalk_fulfill.rs @@ -40,15 +40,7 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> { self.obligations.insert(obligation); } - fn select_all_or_error(&mut self, infcx: &InferCtxt<'tcx>) -> Vec> { - { - let errors = self.select_where_possible(infcx); - - if !errors.is_empty() { - return errors; - } - } - + fn collect_remaining_errors(&mut self) -> Vec> { // any remaining obligations are errors self.obligations .iter() diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index 5a58d37e18362..111a2d034daa7 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -132,14 +132,7 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> { .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] }); } - fn select_all_or_error(&mut self, infcx: &InferCtxt<'tcx>) -> Vec> { - { - let errors = self.select_where_possible(infcx); - if !errors.is_empty() { - return errors; - } - } - + fn collect_remaining_errors(&mut self) -> Vec> { self.predicates.to_errors(CodeAmbiguity).into_iter().map(to_fulfillment_error).collect() } diff --git a/compiler/rustc_traits/src/codegen.rs b/compiler/rustc_traits/src/codegen.rs index c0da8a8169e5b..6f81d343e0fd8 100644 --- a/compiler/rustc_traits/src/codegen.rs +++ b/compiler/rustc_traits/src/codegen.rs @@ -4,7 +4,7 @@ // general routines. use rustc_infer::infer::{DefiningAnchor, TyCtxtInferExt}; -use rustc_infer::traits::FulfillmentErrorCode; +use rustc_infer::traits::{FulfillmentErrorCode, TraitEngineExt as _}; use rustc_middle::traits::CodegenObligationError; use rustc_middle::ty::{self, TyCtxt}; use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt; From a20078f044d42241e14437368e8e1d0f288aa7c0 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 1 Oct 2022 11:33:16 +0200 Subject: [PATCH 432/500] Add `drop_tracking_mir` option. --- compiler/rustc_session/src/options.rs | 2 ++ tests/rustdoc-ui/z-help.stdout | 1 + 2 files changed, 3 insertions(+) diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 7b5fd6cc2a81d..66b100c103e45 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1290,6 +1290,8 @@ options! { (default: no)"), drop_tracking: bool = (false, parse_bool, [TRACKED], "enables drop tracking in generators (default: no)"), + drop_tracking_mir: bool = (false, parse_bool, [TRACKED], + "enables drop tracking on MIR in generators (default: no)"), dual_proc_macros: bool = (false, parse_bool, [TRACKED], "load proc macros for both target and host, but only link to the target (default: no)"), dump_dep_graph: bool = (false, parse_bool, [UNTRACKED], diff --git a/tests/rustdoc-ui/z-help.stdout b/tests/rustdoc-ui/z-help.stdout index 4bdecdc1b7944..546df947c0f91 100644 --- a/tests/rustdoc-ui/z-help.stdout +++ b/tests/rustdoc-ui/z-help.stdout @@ -20,6 +20,7 @@ -Z dlltool=val -- import library generation tool (windows-gnu only) -Z dont-buffer-diagnostics=val -- emit diagnostics rather than buffering (breaks NLL error downgrading, sorting) (default: no) -Z drop-tracking=val -- enables drop tracking in generators (default: no) + -Z drop-tracking-mir=val -- enables drop tracking on MIR in generators (default: no) -Z dual-proc-macros=val -- load proc macros for both target and host, but only link to the target (default: no) -Z dump-dep-graph=val -- dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv) (default: no) -Z dump-drop-tracking-cfg=val -- dump drop-tracking control-flow graph as a `.dot` file (default: no) From 9259da51edfb54a2dfb55a624005b7aa945cdcc6 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 1 Oct 2022 12:19:31 +0200 Subject: [PATCH 433/500] Test the 3 generator handling versions for generator/async tests. --- .../async-await-let-else.drop_tracking.stderr | 106 ++++++ ...nc-await-let-else.drop_tracking_mir.stderr | 90 +++++ ...ync-await-let-else.no_drop_tracking.stderr | 90 +++++ tests/ui/async-await/async-await-let-else.rs | 6 +- .../async-error-span.drop_tracking.stderr | 25 ++ .../async-error-span.drop_tracking_mir.stderr | 25 ++ .../async-error-span.no_drop_tracking.stderr | 25 ++ tests/ui/async-await/async-error-span.rs | 3 + tests/ui/async-await/async-error-span.stderr | 6 +- .../async-fn-nonsend.drop_tracking.stderr | 49 +++ .../async-fn-nonsend.drop_tracking_mir.stderr | 120 +++++++ .../async-fn-nonsend.no_drop_tracking.stderr | 120 +++++++ tests/ui/async-await/async-fn-nonsend.rs | 8 +- tests/ui/async-await/async-fn-nonsend.stderr | 12 +- tests/ui/async-await/default-struct-update.rs | 4 +- tests/ui/async-await/drop-and-assign.rs | 4 +- ...field-assign-nonsend.drop_tracking.stderr} | 6 +- ...ld-assign-nonsend.drop_tracking_mir.stderr | 25 ++ ...eld-assign-nonsend.no_drop_tracking.stderr | 25 ++ .../drop-track-field-assign-nonsend.rs | 4 +- .../ui/async-await/drop-track-field-assign.rs | 4 +- .../field-assign-nonsend.drop_tracking.stderr | 25 ++ ...ld-assign-nonsend.drop_tracking_mir.stderr | 25 ++ ...eld-assign-nonsend.no_drop_tracking.stderr | 25 ++ tests/ui/async-await/field-assign-nonsend.rs | 47 +++ tests/ui/async-await/field-assign.rs | 46 +++ .../issue-64130-1-sync.drop_tracking.stderr | 24 ++ ...ssue-64130-1-sync.drop_tracking_mir.stderr | 24 ++ ...issue-64130-1-sync.no_drop_tracking.stderr | 24 ++ tests/ui/async-await/issue-64130-1-sync.rs | 3 + .../ui/async-await/issue-64130-1-sync.stderr | 6 +- .../issue-64130-2-send.drop_tracking.stderr | 24 ++ ...ssue-64130-2-send.drop_tracking_mir.stderr | 24 ++ ...issue-64130-2-send.no_drop_tracking.stderr | 24 ++ tests/ui/async-await/issue-64130-2-send.rs | 3 + .../ui/async-await/issue-64130-2-send.stderr | 6 +- .../issue-64130-3-other.drop_tracking.stderr | 27 ++ ...sue-64130-3-other.drop_tracking_mir.stderr | 27 ++ ...ssue-64130-3-other.no_drop_tracking.stderr | 27 ++ tests/ui/async-await/issue-64130-3-other.rs | 3 + .../ui/async-await/issue-64130-3-other.stderr | 6 +- ...ue-64130-4-async-move.drop-tracking.stderr | 6 +- ...4130-4-async-move.drop_tracking_mir.stderr | 26 ++ ...64130-4-async-move.no_drop_tracking.stderr | 6 +- .../async-await/issue-64130-4-async-move.rs | 8 +- ...67252-unnamed-future.drop_tracking.stderr} | 8 +- ...52-unnamed-future.drop_tracking_mir.stderr | 28 ++ ...252-unnamed-future.no_drop_tracking.stderr | 28 ++ .../async-await/issue-67252-unnamed-future.rs | 3 + .../issue-68112.drop_tracking_mir.stderr | 82 +++++ tests/ui/async-await/issue-68112.rs | 6 +- .../issue-70818.drop_tracking.stderr | 18 + .../issue-70818.drop_tracking_mir.stderr | 18 + .../issue-70818.no_drop_tracking.stderr | 18 + tests/ui/async-await/issue-70818.rs | 3 + tests/ui/async-await/issue-70818.stderr | 4 +- ...e-70935-complex-spans.drop_tracking.stderr | 4 +- ...935-complex-spans.drop_tracking_mir.stderr | 21 ++ ...0935-complex-spans.no_drop_tracking.stderr | 4 +- .../async-await/issue-70935-complex-spans.rs | 7 +- ...ype-err-drop-tracking.drop_tracking.stderr | 11 + ...err-drop-tracking.drop_tracking_mir.stderr | 11 + ...-err-drop-tracking.no_drop_tracking.stderr | 11 + .../issue-73741-type-err-drop-tracking.rs | 5 +- .../issue-73741-type-err-drop-tracking.stderr | 2 +- ...tderr => issue-86507.drop_tracking.stderr} | 6 +- .../issue-86507.drop_tracking_mir.stderr | 23 ++ .../issue-86507.no_drop_tracking.stderr | 23 ++ tests/ui/async-await/issue-86507.rs | 3 + tests/ui/async-await/issue-93648.rs | 4 +- .../issues/auxiliary/issue_67893.rs | 3 + ...-raw-ptr-not-send.drop_tracking_mir.stderr | 33 ++ ...6-raw-ptr-not-send.no_drop_tracking.stderr | 7 +- .../issues/issue-65436-raw-ptr-not-send.rs | 7 +- .../issues/issue-67611-static-mut-refs.rs | 4 + .../ui/async-await/issues/issue-67893.stderr | 2 +- ...async-impl-trait-type.drop_tracking.stderr | 21 ++ ...c-impl-trait-type.drop_tracking_mir.stderr | 21 ++ ...nc-impl-trait-type.no_drop_tracking.stderr | 21 ++ ...utually-recursive-async-impl-trait-type.rs | 4 + ...lly-recursive-async-impl-trait-type.stderr | 4 +- tests/ui/async-await/non-trivial-drop.rs | 4 +- ...async-impl-trait-type.drop_tracking.stderr | 12 + ...c-impl-trait-type.drop_tracking_mir.stderr | 12 + ...nc-impl-trait-type.no_drop_tracking.stderr | 12 + .../recursive-async-impl-trait-type.rs | 3 + .../recursive-async-impl-trait-type.stderr | 2 +- ...unresolved_type_param.drop_tracking.stderr | 39 ++ ...solved_type_param.drop_tracking_mir.stderr | 39 ++ ...esolved_type_param.no_drop_tracking.stderr | 39 ++ tests/ui/async-await/unresolved_type_param.rs | 3 + .../async-await/unresolved_type_param.stderr | 12 +- tests/ui/generator/addassign-yield.rs | 3 + .../auto-trait-regions.drop_tracking.stderr | 47 +++ ...uto-trait-regions.drop_tracking_mir.stderr | 47 +++ ...auto-trait-regions.no_drop_tracking.stderr | 47 +++ tests/ui/generator/auto-trait-regions.rs | 3 + tests/ui/generator/auto-trait-regions.stderr | 8 +- .../generator/borrowing.drop_tracking.stderr | 31 ++ .../borrowing.drop_tracking_mir.stderr | 31 ++ .../borrowing.no_drop_tracking.stderr | 31 ++ tests/ui/generator/borrowing.rs | 4 + tests/ui/generator/borrowing.stderr | 4 +- ...ng-parent-expression.drop_tracking.stderr} | 24 +- ...parent-expression.drop_tracking_mir.stderr | 334 ++++++++++++++++++ ...-parent-expression.no_drop_tracking.stderr | 334 ++++++++++++++++++ .../drop-tracking-parent-expression.rs | 10 +- .../drop-tracking-yielding-in-match-guards.rs | 4 +- .../issue-57017.drop_tracking_mir.stderr | 248 +++++++++++++ .../issue-57017.no_drop_tracking.stderr | 248 +++++++++++++ tests/ui/generator/issue-57017.rs | 13 +- .../issue-57478.drop_tracking_mir.stderr | 32 ++ .../issue-57478.no_drop_tracking.stderr | 32 ++ tests/ui/generator/issue-57478.rs | 8 +- ...tderr => issue-68112.drop_tracking.stderr} | 18 +- .../issue-68112.drop_tracking_mir.stderr | 66 ++++ .../issue-68112.no_drop_tracking.stderr | 66 ++++ tests/ui/generator/issue-68112.rs | 3 + tests/ui/generator/issue-93161.rs | 4 +- ...err => not-send-sync.drop_tracking.stderr} | 14 +- .../not-send-sync.drop_tracking_mir.stderr | 58 +++ .../not-send-sync.no_drop_tracking.stderr | 58 +++ tests/ui/generator/not-send-sync.rs | 3 + .../parent-expression.drop_tracking.stderr | 128 +++++++ ...parent-expression.drop_tracking_mir.stderr | 334 ++++++++++++++++++ .../parent-expression.no_drop_tracking.stderr | 334 ++++++++++++++++++ tests/ui/generator/parent-expression.rs | 77 ++++ .../partial-drop.drop_tracking.stderr | 92 +++++ .../partial-drop.drop_tracking_mir.stderr | 92 +++++ .../partial-drop.no_drop_tracking.stderr | 92 +++++ tests/ui/generator/partial-drop.rs | 4 +- tests/ui/generator/partial-drop.stderr | 24 +- ...ator-print-verbose-1.drop_tracking.stderr} | 18 +- ...r-print-verbose-1.drop_tracking_mir.stderr | 64 ++++ ...or-print-verbose-1.no_drop_tracking.stderr | 64 ++++ .../print/generator-print-verbose-1.rs | 3 + ...ator-print-verbose-2.drop_tracking.stderr} | 12 +- ...r-print-verbose-2.drop_tracking_mir.stderr | 58 +++ ...or-print-verbose-2.no_drop_tracking.stderr | 58 +++ .../print/generator-print-verbose-2.rs | 3 + .../retain-resume-ref.drop_tracking.stderr | 13 + ...retain-resume-ref.drop_tracking_mir.stderr | 13 + .../retain-resume-ref.no_drop_tracking.stderr | 13 + tests/ui/generator/retain-resume-ref.rs | 4 + tests/ui/generator/retain-resume-ref.stderr | 2 +- .../static-mut-reference-across-yield.rs | 4 +- .../issue-55872-2.drop_tracking.stderr | 8 + .../issue-55872-2.drop_tracking_mir.stderr | 8 + .../issue-55872-2.no_drop_tracking.stderr | 8 + tests/ui/impl-trait/issue-55872-2.rs | 3 + tests/ui/impl-trait/issue-55872-2.stderr | 2 +- ...-trait-type-indirect.drop_tracking.stderr} | 40 +-- ...ait-type-indirect.drop_tracking_mir.stderr | 152 ++++++++ ...rait-type-indirect.no_drop_tracking.stderr | 152 ++++++++ .../recursive-impl-trait-type-indirect.rs | 4 + .../dedup.drop_tracking.stderr | 19 + .../dedup.drop_tracking_mir.stderr | 19 + .../dedup.no_drop_tracking.stderr | 19 + tests/ui/lint/must_not_suspend/dedup.rs | 3 + tests/ui/lint/must_not_suspend/dedup.stderr | 6 +- .../must_not_suspend/ref.drop_tracking.stderr | 8 +- .../ref.drop_tracking_mir.stderr | 27 ++ .../ref.no_drop_tracking.stderr | 8 +- tests/ui/lint/must_not_suspend/ref.rs | 7 +- .../trait.drop_tracking.stderr | 37 ++ .../trait.drop_tracking_mir.stderr | 37 ++ .../trait.no_drop_tracking.stderr | 37 ++ tests/ui/lint/must_not_suspend/trait.rs | 3 + tests/ui/lint/must_not_suspend/trait.stderr | 10 +- .../unit.drop_tracking.stderr | 26 ++ .../unit.drop_tracking_mir.stderr | 26 ++ .../unit.no_drop_tracking.stderr | 26 ++ tests/ui/lint/must_not_suspend/unit.rs | 3 + tests/ui/lint/must_not_suspend/unit.stderr | 8 +- .../warn.drop_tracking.stderr | 26 ++ .../warn.drop_tracking_mir.stderr | 26 ++ .../warn.no_drop_tracking.stderr | 26 ++ tests/ui/lint/must_not_suspend/warn.rs | 3 + tests/ui/lint/must_not_suspend/warn.stderr | 8 +- 179 files changed, 5816 insertions(+), 196 deletions(-) create mode 100644 tests/ui/async-await/async-await-let-else.drop_tracking.stderr create mode 100644 tests/ui/async-await/async-await-let-else.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/async-await-let-else.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/async-error-span.drop_tracking.stderr create mode 100644 tests/ui/async-await/async-error-span.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/async-error-span.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/async-fn-nonsend.drop_tracking.stderr create mode 100644 tests/ui/async-await/async-fn-nonsend.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/async-fn-nonsend.no_drop_tracking.stderr rename tests/ui/async-await/{drop-track-field-assign-nonsend.stderr => drop-track-field-assign-nonsend.drop_tracking.stderr} (84%) create mode 100644 tests/ui/async-await/drop-track-field-assign-nonsend.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/drop-track-field-assign-nonsend.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/field-assign-nonsend.drop_tracking.stderr create mode 100644 tests/ui/async-await/field-assign-nonsend.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/field-assign-nonsend.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/field-assign-nonsend.rs create mode 100644 tests/ui/async-await/field-assign.rs create mode 100644 tests/ui/async-await/issue-64130-1-sync.drop_tracking.stderr create mode 100644 tests/ui/async-await/issue-64130-1-sync.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/issue-64130-1-sync.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/issue-64130-2-send.drop_tracking.stderr create mode 100644 tests/ui/async-await/issue-64130-2-send.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/issue-64130-2-send.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/issue-64130-3-other.drop_tracking.stderr create mode 100644 tests/ui/async-await/issue-64130-3-other.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/issue-64130-3-other.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/issue-64130-4-async-move.drop_tracking_mir.stderr rename tests/ui/async-await/{issue-67252-unnamed-future.stderr => issue-67252-unnamed-future.drop_tracking.stderr} (81%) create mode 100644 tests/ui/async-await/issue-67252-unnamed-future.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/issue-67252-unnamed-future.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/issue-68112.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/issue-70818.drop_tracking.stderr create mode 100644 tests/ui/async-await/issue-70818.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/issue-70818.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/issue-70935-complex-spans.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/issue-73741-type-err-drop-tracking.drop_tracking.stderr create mode 100644 tests/ui/async-await/issue-73741-type-err-drop-tracking.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/issue-73741-type-err-drop-tracking.no_drop_tracking.stderr rename tests/ui/async-await/{issue-86507.stderr => issue-86507.drop_tracking.stderr} (86%) create mode 100644 tests/ui/async-await/issue-86507.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/issue-86507.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/mutually-recursive-async-impl-trait-type.drop_tracking.stderr create mode 100644 tests/ui/async-await/mutually-recursive-async-impl-trait-type.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/mutually-recursive-async-impl-trait-type.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/recursive-async-impl-trait-type.drop_tracking.stderr create mode 100644 tests/ui/async-await/recursive-async-impl-trait-type.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/recursive-async-impl-trait-type.no_drop_tracking.stderr create mode 100644 tests/ui/async-await/unresolved_type_param.drop_tracking.stderr create mode 100644 tests/ui/async-await/unresolved_type_param.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/unresolved_type_param.no_drop_tracking.stderr create mode 100644 tests/ui/generator/auto-trait-regions.drop_tracking.stderr create mode 100644 tests/ui/generator/auto-trait-regions.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/auto-trait-regions.no_drop_tracking.stderr create mode 100644 tests/ui/generator/borrowing.drop_tracking.stderr create mode 100644 tests/ui/generator/borrowing.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/borrowing.no_drop_tracking.stderr rename tests/ui/generator/{drop-tracking-parent-expression.stderr => drop-tracking-parent-expression.drop_tracking.stderr} (88%) create mode 100644 tests/ui/generator/drop-tracking-parent-expression.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/drop-tracking-parent-expression.no_drop_tracking.stderr create mode 100644 tests/ui/generator/issue-57017.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/issue-57017.no_drop_tracking.stderr create mode 100644 tests/ui/generator/issue-57478.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/issue-57478.no_drop_tracking.stderr rename tests/ui/generator/{issue-68112.stderr => issue-68112.drop_tracking.stderr} (89%) create mode 100644 tests/ui/generator/issue-68112.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/issue-68112.no_drop_tracking.stderr rename tests/ui/generator/{not-send-sync.stderr => not-send-sync.drop_tracking.stderr} (84%) create mode 100644 tests/ui/generator/not-send-sync.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/not-send-sync.no_drop_tracking.stderr create mode 100644 tests/ui/generator/parent-expression.drop_tracking.stderr create mode 100644 tests/ui/generator/parent-expression.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/parent-expression.no_drop_tracking.stderr create mode 100644 tests/ui/generator/parent-expression.rs create mode 100644 tests/ui/generator/partial-drop.drop_tracking.stderr create mode 100644 tests/ui/generator/partial-drop.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/partial-drop.no_drop_tracking.stderr rename tests/ui/generator/print/{generator-print-verbose-1.stderr => generator-print-verbose-1.drop_tracking.stderr} (86%) create mode 100644 tests/ui/generator/print/generator-print-verbose-1.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/print/generator-print-verbose-1.no_drop_tracking.stderr rename tests/ui/generator/print/{generator-print-verbose-2.stderr => generator-print-verbose-2.drop_tracking.stderr} (87%) create mode 100644 tests/ui/generator/print/generator-print-verbose-2.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/print/generator-print-verbose-2.no_drop_tracking.stderr create mode 100644 tests/ui/generator/retain-resume-ref.drop_tracking.stderr create mode 100644 tests/ui/generator/retain-resume-ref.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/retain-resume-ref.no_drop_tracking.stderr create mode 100644 tests/ui/impl-trait/issue-55872-2.drop_tracking.stderr create mode 100644 tests/ui/impl-trait/issue-55872-2.drop_tracking_mir.stderr create mode 100644 tests/ui/impl-trait/issue-55872-2.no_drop_tracking.stderr rename tests/ui/impl-trait/{recursive-impl-trait-type-indirect.stderr => recursive-impl-trait-type-indirect.drop_tracking.stderr} (80%) create mode 100644 tests/ui/impl-trait/recursive-impl-trait-type-indirect.drop_tracking_mir.stderr create mode 100644 tests/ui/impl-trait/recursive-impl-trait-type-indirect.no_drop_tracking.stderr create mode 100644 tests/ui/lint/must_not_suspend/dedup.drop_tracking.stderr create mode 100644 tests/ui/lint/must_not_suspend/dedup.drop_tracking_mir.stderr create mode 100644 tests/ui/lint/must_not_suspend/dedup.no_drop_tracking.stderr create mode 100644 tests/ui/lint/must_not_suspend/ref.drop_tracking_mir.stderr create mode 100644 tests/ui/lint/must_not_suspend/trait.drop_tracking.stderr create mode 100644 tests/ui/lint/must_not_suspend/trait.drop_tracking_mir.stderr create mode 100644 tests/ui/lint/must_not_suspend/trait.no_drop_tracking.stderr create mode 100644 tests/ui/lint/must_not_suspend/unit.drop_tracking.stderr create mode 100644 tests/ui/lint/must_not_suspend/unit.drop_tracking_mir.stderr create mode 100644 tests/ui/lint/must_not_suspend/unit.no_drop_tracking.stderr create mode 100644 tests/ui/lint/must_not_suspend/warn.drop_tracking.stderr create mode 100644 tests/ui/lint/must_not_suspend/warn.drop_tracking_mir.stderr create mode 100644 tests/ui/lint/must_not_suspend/warn.no_drop_tracking.stderr diff --git a/tests/ui/async-await/async-await-let-else.drop_tracking.stderr b/tests/ui/async-await/async-await-let-else.drop_tracking.stderr new file mode 100644 index 0000000000000..fb83ca90a3787 --- /dev/null +++ b/tests/ui/async-await/async-await-let-else.drop_tracking.stderr @@ -0,0 +1,106 @@ +error: future cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:48:13 + | +LL | is_send(foo(Some(true))); + | ^^^^^^^^^^^^^^^ future returned by `foo` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-await-let-else.rs:11:14 + | +LL | let r = Rc::new(()); + | - has type `Rc<()>` which is not `Send` +LL | bar().await + | ^^^^^^ await occurs here, with `r` maybe used later +LL | }; + | - `r` is later dropped here +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error[E0277]: `Rc<()>` cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:50:13 + | +LL | async fn foo2(x: Option) { + | - within this `impl Future` +... +LL | is_send(foo2(Some(true))); + | ------- ^^^^^^^^^^^^^^^^ `Rc<()>` cannot be sent between threads safely + | | + | required by a bound introduced by this call + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: required because it's used within this `async fn` body + --> $DIR/async-await-let-else.rs:27:29 + | +LL | async fn bar2(_: T) -> ! { + | _____________________________^ +LL | | panic!() +LL | | } + | |_^ + = note: required because it captures the following types: `ResumeTy`, `Option`, `impl Future`, `()` +note: required because it's used within this `async fn` body + --> $DIR/async-await-let-else.rs:21:32 + | +LL | async fn foo2(x: Option) { + | ________________________________^ +LL | | let Some(_) = x else { +LL | | bar2(Rc::new(())).await +LL | | }; +LL | | } + | |_^ +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error: future cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:52:13 + | +LL | is_send(foo3(Some(true))); + | ^^^^^^^^^^^^^^^^ future returned by `foo3` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-await-let-else.rs:33:28 + | +LL | (Rc::new(()), bar().await); + | ----------- ^^^^^^ - `Rc::new(())` is later dropped here + | | | + | | await occurs here, with `Rc::new(())` maybe used later + | has type `Rc<()>` which is not `Send` +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error: future cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:54:13 + | +LL | is_send(foo4(Some(true))); + | ^^^^^^^^^^^^^^^^ future returned by `foo4` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-await-let-else.rs:41:14 + | +LL | let r = Rc::new(()); + | - has type `Rc<()>` which is not `Send` +LL | bar().await; + | ^^^^^^ await occurs here, with `r` maybe used later +... +LL | }; + | - `r` is later dropped here +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/async-await-let-else.drop_tracking_mir.stderr b/tests/ui/async-await/async-await-let-else.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..d3c5e80a30df4 --- /dev/null +++ b/tests/ui/async-await/async-await-let-else.drop_tracking_mir.stderr @@ -0,0 +1,90 @@ +error: future cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:48:13 + | +LL | is_send(foo(Some(true))); + | ^^^^^^^^^^^^^^^ future returned by `foo` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-await-let-else.rs:11:14 + | +LL | let r = Rc::new(()); + | - has type `Rc<()>` which is not `Send` +LL | bar().await + | ^^^^^^ await occurs here, with `r` maybe used later +LL | }; + | - `r` is later dropped here +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error: future cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:50:13 + | +LL | is_send(foo2(Some(true))); + | ^^^^^^^^^^^^^^^^ future returned by `foo2` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-await-let-else.rs:23:26 + | +LL | bar2(Rc::new(())).await + | ----------- ^^^^^^ await occurs here, with `Rc::new(())` maybe used later + | | + | has type `Rc<()>` which is not `Send` +LL | }; + | - `Rc::new(())` is later dropped here +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error: future cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:52:13 + | +LL | is_send(foo3(Some(true))); + | ^^^^^^^^^^^^^^^^ future returned by `foo3` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-await-let-else.rs:33:28 + | +LL | (Rc::new(()), bar().await); + | ----------- ^^^^^^ - `Rc::new(())` is later dropped here + | | | + | | await occurs here, with `Rc::new(())` maybe used later + | has type `Rc<()>` which is not `Send` +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error: future cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:54:13 + | +LL | is_send(foo4(Some(true))); + | ^^^^^^^^^^^^^^^^ future returned by `foo4` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-await-let-else.rs:41:14 + | +LL | let r = Rc::new(()); + | - has type `Rc<()>` which is not `Send` +LL | bar().await; + | ^^^^^^ await occurs here, with `r` maybe used later +... +LL | }; + | - `r` is later dropped here +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error: aborting due to 4 previous errors + diff --git a/tests/ui/async-await/async-await-let-else.no_drop_tracking.stderr b/tests/ui/async-await/async-await-let-else.no_drop_tracking.stderr new file mode 100644 index 0000000000000..d3c5e80a30df4 --- /dev/null +++ b/tests/ui/async-await/async-await-let-else.no_drop_tracking.stderr @@ -0,0 +1,90 @@ +error: future cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:48:13 + | +LL | is_send(foo(Some(true))); + | ^^^^^^^^^^^^^^^ future returned by `foo` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-await-let-else.rs:11:14 + | +LL | let r = Rc::new(()); + | - has type `Rc<()>` which is not `Send` +LL | bar().await + | ^^^^^^ await occurs here, with `r` maybe used later +LL | }; + | - `r` is later dropped here +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error: future cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:50:13 + | +LL | is_send(foo2(Some(true))); + | ^^^^^^^^^^^^^^^^ future returned by `foo2` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-await-let-else.rs:23:26 + | +LL | bar2(Rc::new(())).await + | ----------- ^^^^^^ await occurs here, with `Rc::new(())` maybe used later + | | + | has type `Rc<()>` which is not `Send` +LL | }; + | - `Rc::new(())` is later dropped here +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error: future cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:52:13 + | +LL | is_send(foo3(Some(true))); + | ^^^^^^^^^^^^^^^^ future returned by `foo3` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-await-let-else.rs:33:28 + | +LL | (Rc::new(()), bar().await); + | ----------- ^^^^^^ - `Rc::new(())` is later dropped here + | | | + | | await occurs here, with `Rc::new(())` maybe used later + | has type `Rc<()>` which is not `Send` +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error: future cannot be sent between threads safely + --> $DIR/async-await-let-else.rs:54:13 + | +LL | is_send(foo4(Some(true))); + | ^^^^^^^^^^^^^^^^ future returned by `foo4` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-await-let-else.rs:41:14 + | +LL | let r = Rc::new(()); + | - has type `Rc<()>` which is not `Send` +LL | bar().await; + | ^^^^^^ await occurs here, with `r` maybe used later +... +LL | }; + | - `r` is later dropped here +note: required by a bound in `is_send` + --> $DIR/async-await-let-else.rs:19:15 + | +LL | fn is_send(_: T) {} + | ^^^^ required by this bound in `is_send` + +error: aborting due to 4 previous errors + diff --git a/tests/ui/async-await/async-await-let-else.rs b/tests/ui/async-await/async-await-let-else.rs index 3fb2142b9e5d8..113d576b5e762 100644 --- a/tests/ui/async-await/async-await-let-else.rs +++ b/tests/ui/async-await/async-await-let-else.rs @@ -1,7 +1,7 @@ // edition:2021 -// revisions: drop-tracking no-drop-tracking -// [drop-tracking] compile-flags: -Zdrop-tracking=yes -// [no-drop-tracking] compile-flags: -Zdrop-tracking=no +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir use std::rc::Rc; diff --git a/tests/ui/async-await/async-error-span.drop_tracking.stderr b/tests/ui/async-await/async-error-span.drop_tracking.stderr new file mode 100644 index 0000000000000..083da1cec7313 --- /dev/null +++ b/tests/ui/async-await/async-error-span.drop_tracking.stderr @@ -0,0 +1,25 @@ +error[E0277]: `()` is not a future + --> $DIR/async-error-span.rs:10:20 + | +LL | fn get_future() -> impl Future { + | ^^^^^^^^^^^^^^^^^^^^^^^^ `()` is not a future + | + = help: the trait `Future` is not implemented for `()` + = note: () must be a future or must implement `IntoFuture` to be awaited + +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/async-error-span.rs:16:9 + | +LL | let a; + | ^ cannot infer type + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/async-error-span.rs:17:17 + | +LL | get_future().await; + | ^^^^^^ + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0277, E0698. +For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/async-error-span.drop_tracking_mir.stderr b/tests/ui/async-await/async-error-span.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..083da1cec7313 --- /dev/null +++ b/tests/ui/async-await/async-error-span.drop_tracking_mir.stderr @@ -0,0 +1,25 @@ +error[E0277]: `()` is not a future + --> $DIR/async-error-span.rs:10:20 + | +LL | fn get_future() -> impl Future { + | ^^^^^^^^^^^^^^^^^^^^^^^^ `()` is not a future + | + = help: the trait `Future` is not implemented for `()` + = note: () must be a future or must implement `IntoFuture` to be awaited + +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/async-error-span.rs:16:9 + | +LL | let a; + | ^ cannot infer type + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/async-error-span.rs:17:17 + | +LL | get_future().await; + | ^^^^^^ + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0277, E0698. +For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/async-error-span.no_drop_tracking.stderr b/tests/ui/async-await/async-error-span.no_drop_tracking.stderr new file mode 100644 index 0000000000000..083da1cec7313 --- /dev/null +++ b/tests/ui/async-await/async-error-span.no_drop_tracking.stderr @@ -0,0 +1,25 @@ +error[E0277]: `()` is not a future + --> $DIR/async-error-span.rs:10:20 + | +LL | fn get_future() -> impl Future { + | ^^^^^^^^^^^^^^^^^^^^^^^^ `()` is not a future + | + = help: the trait `Future` is not implemented for `()` + = note: () must be a future or must implement `IntoFuture` to be awaited + +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/async-error-span.rs:16:9 + | +LL | let a; + | ^ cannot infer type + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/async-error-span.rs:17:17 + | +LL | get_future().await; + | ^^^^^^ + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0277, E0698. +For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/async-error-span.rs b/tests/ui/async-await/async-error-span.rs index 86d459bf084b1..29b58ebc3a420 100644 --- a/tests/ui/async-await/async-error-span.rs +++ b/tests/ui/async-await/async-error-span.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 // Regression test for issue #62382. diff --git a/tests/ui/async-await/async-error-span.stderr b/tests/ui/async-await/async-error-span.stderr index 7d4447b6d5578..083da1cec7313 100644 --- a/tests/ui/async-await/async-error-span.stderr +++ b/tests/ui/async-await/async-error-span.stderr @@ -1,5 +1,5 @@ error[E0277]: `()` is not a future - --> $DIR/async-error-span.rs:7:20 + --> $DIR/async-error-span.rs:10:20 | LL | fn get_future() -> impl Future { | ^^^^^^^^^^^^^^^^^^^^^^^^ `()` is not a future @@ -8,13 +8,13 @@ LL | fn get_future() -> impl Future { = note: () must be a future or must implement `IntoFuture` to be awaited error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/async-error-span.rs:13:9 + --> $DIR/async-error-span.rs:16:9 | LL | let a; | ^ cannot infer type | note: the type is part of the `async fn` body because of this `await` - --> $DIR/async-error-span.rs:14:17 + --> $DIR/async-error-span.rs:17:17 | LL | get_future().await; | ^^^^^^ diff --git a/tests/ui/async-await/async-fn-nonsend.drop_tracking.stderr b/tests/ui/async-await/async-fn-nonsend.drop_tracking.stderr new file mode 100644 index 0000000000000..0f0dc335e7f27 --- /dev/null +++ b/tests/ui/async-await/async-fn-nonsend.drop_tracking.stderr @@ -0,0 +1,49 @@ +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:72:17 + | +LL | assert_send(non_send_temporary_in_match()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_send_temporary_in_match` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:36:25 + | +LL | match Some(non_send()) { + | ---------------- has type `Option` which is not `Send` +LL | Some(_) => fut().await, + | ^^^^^^ await occurs here, with `Some(non_send())` maybe used later +... +LL | } + | - `Some(non_send())` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:74:17 + | +LL | assert_send(non_sync_with_method_call()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_sync_with_method_call` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `dyn std::fmt::Write` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:49:14 + | +LL | let f: &mut std::fmt::Formatter = &mut get_formatter(); + | --------------- has type `Formatter<'_>` which is not `Send` +... +LL | fut().await; + | ^^^^^^ await occurs here, with `get_formatter()` maybe used later +LL | } +LL | } + | - `get_formatter()` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to 2 previous errors + diff --git a/tests/ui/async-await/async-fn-nonsend.drop_tracking_mir.stderr b/tests/ui/async-await/async-fn-nonsend.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..5cec21d890ef1 --- /dev/null +++ b/tests/ui/async-await/async-fn-nonsend.drop_tracking_mir.stderr @@ -0,0 +1,120 @@ +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:70:17 + | +LL | assert_send(local_dropped_before_await()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `local_dropped_before_await` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:27:10 + | +LL | let x = non_send(); + | - has type `impl Debug` which is not `Send` +LL | drop(x); +LL | fut().await; + | ^^^^^^ await occurs here, with `x` maybe used later +LL | } + | - `x` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:72:17 + | +LL | assert_send(non_send_temporary_in_match()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_send_temporary_in_match` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:36:25 + | +LL | match Some(non_send()) { + | ---------- has type `impl Debug` which is not `Send` +LL | Some(_) => fut().await, + | ^^^^^^ await occurs here, with `non_send()` maybe used later +... +LL | } + | - `non_send()` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:74:17 + | +LL | assert_send(non_sync_with_method_call()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_sync_with_method_call` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `dyn std::fmt::Write` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:49:14 + | +LL | let f: &mut std::fmt::Formatter = &mut get_formatter(); + | --------------- has type `Formatter<'_>` which is not `Send` +... +LL | fut().await; + | ^^^^^^ await occurs here, with `get_formatter()` maybe used later +LL | } +LL | } + | - `get_formatter()` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:76:17 + | +LL | assert_send(non_sync_with_method_call_panic()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_sync_with_method_call_panic` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `dyn std::fmt::Write` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:56:14 + | +LL | let f: &mut std::fmt::Formatter = panic!(); + | - has type `&mut Formatter<'_>` which is not `Send` +LL | if non_sync().fmt(f).unwrap() == () { +LL | fut().await; + | ^^^^^^ await occurs here, with `f` maybe used later +LL | } +LL | } + | - `f` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:78:17 + | +LL | assert_send(non_sync_with_method_call_infinite_loop()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_sync_with_method_call_infinite_loop` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `dyn std::fmt::Write` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:63:14 + | +LL | let f: &mut std::fmt::Formatter = loop {}; + | - has type `&mut Formatter<'_>` which is not `Send` +LL | if non_sync().fmt(f).unwrap() == () { +LL | fut().await; + | ^^^^^^ await occurs here, with `f` maybe used later +LL | } +LL | } + | - `f` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to 5 previous errors + diff --git a/tests/ui/async-await/async-fn-nonsend.no_drop_tracking.stderr b/tests/ui/async-await/async-fn-nonsend.no_drop_tracking.stderr new file mode 100644 index 0000000000000..5cec21d890ef1 --- /dev/null +++ b/tests/ui/async-await/async-fn-nonsend.no_drop_tracking.stderr @@ -0,0 +1,120 @@ +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:70:17 + | +LL | assert_send(local_dropped_before_await()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `local_dropped_before_await` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:27:10 + | +LL | let x = non_send(); + | - has type `impl Debug` which is not `Send` +LL | drop(x); +LL | fut().await; + | ^^^^^^ await occurs here, with `x` maybe used later +LL | } + | - `x` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:72:17 + | +LL | assert_send(non_send_temporary_in_match()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_send_temporary_in_match` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:36:25 + | +LL | match Some(non_send()) { + | ---------- has type `impl Debug` which is not `Send` +LL | Some(_) => fut().await, + | ^^^^^^ await occurs here, with `non_send()` maybe used later +... +LL | } + | - `non_send()` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:74:17 + | +LL | assert_send(non_sync_with_method_call()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_sync_with_method_call` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `dyn std::fmt::Write` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:49:14 + | +LL | let f: &mut std::fmt::Formatter = &mut get_formatter(); + | --------------- has type `Formatter<'_>` which is not `Send` +... +LL | fut().await; + | ^^^^^^ await occurs here, with `get_formatter()` maybe used later +LL | } +LL | } + | - `get_formatter()` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:76:17 + | +LL | assert_send(non_sync_with_method_call_panic()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_sync_with_method_call_panic` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `dyn std::fmt::Write` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:56:14 + | +LL | let f: &mut std::fmt::Formatter = panic!(); + | - has type `&mut Formatter<'_>` which is not `Send` +LL | if non_sync().fmt(f).unwrap() == () { +LL | fut().await; + | ^^^^^^ await occurs here, with `f` maybe used later +LL | } +LL | } + | - `f` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: future cannot be sent between threads safely + --> $DIR/async-fn-nonsend.rs:78:17 + | +LL | assert_send(non_sync_with_method_call_infinite_loop()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_sync_with_method_call_infinite_loop` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `dyn std::fmt::Write` +note: future is not `Send` as this value is used across an await + --> $DIR/async-fn-nonsend.rs:63:14 + | +LL | let f: &mut std::fmt::Formatter = loop {}; + | - has type `&mut Formatter<'_>` which is not `Send` +LL | if non_sync().fmt(f).unwrap() == () { +LL | fut().await; + | ^^^^^^ await occurs here, with `f` maybe used later +LL | } +LL | } + | - `f` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/async-fn-nonsend.rs:67:24 + | +LL | fn assert_send(_: impl Send) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to 5 previous errors + diff --git a/tests/ui/async-await/async-fn-nonsend.rs b/tests/ui/async-await/async-fn-nonsend.rs index d7f8d7ac546c0..77c957d0592b7 100644 --- a/tests/ui/async-await/async-fn-nonsend.rs +++ b/tests/ui/async-await/async-fn-nonsend.rs @@ -1,5 +1,8 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 -// compile-flags: --crate-type lib -Zdrop-tracking +// compile-flags: --crate-type lib use std::{cell::RefCell, fmt::Debug, rc::Rc}; @@ -65,10 +68,13 @@ fn assert_send(_: impl Send) {} pub fn pass_assert() { assert_send(local_dropped_before_await()); + //[no_drop_tracking,drop_tracking_mir]~^ ERROR future cannot be sent between threads safely assert_send(non_send_temporary_in_match()); //~^ ERROR future cannot be sent between threads safely assert_send(non_sync_with_method_call()); //~^ ERROR future cannot be sent between threads safely assert_send(non_sync_with_method_call_panic()); + //[no_drop_tracking,drop_tracking_mir]~^ ERROR future cannot be sent between threads safely assert_send(non_sync_with_method_call_infinite_loop()); + //[no_drop_tracking,drop_tracking_mir]~^ ERROR future cannot be sent between threads safely } diff --git a/tests/ui/async-await/async-fn-nonsend.stderr b/tests/ui/async-await/async-fn-nonsend.stderr index a7b872fe4444a..0f0dc335e7f27 100644 --- a/tests/ui/async-await/async-fn-nonsend.stderr +++ b/tests/ui/async-await/async-fn-nonsend.stderr @@ -1,12 +1,12 @@ error: future cannot be sent between threads safely - --> $DIR/async-fn-nonsend.rs:68:17 + --> $DIR/async-fn-nonsend.rs:72:17 | LL | assert_send(non_send_temporary_in_match()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_send_temporary_in_match` is not `Send` | = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` note: future is not `Send` as this value is used across an await - --> $DIR/async-fn-nonsend.rs:33:25 + --> $DIR/async-fn-nonsend.rs:36:25 | LL | match Some(non_send()) { | ---------------- has type `Option` which is not `Send` @@ -16,20 +16,20 @@ LL | Some(_) => fut().await, LL | } | - `Some(non_send())` is later dropped here note: required by a bound in `assert_send` - --> $DIR/async-fn-nonsend.rs:64:24 + --> $DIR/async-fn-nonsend.rs:67:24 | LL | fn assert_send(_: impl Send) {} | ^^^^ required by this bound in `assert_send` error: future cannot be sent between threads safely - --> $DIR/async-fn-nonsend.rs:70:17 + --> $DIR/async-fn-nonsend.rs:74:17 | LL | assert_send(non_sync_with_method_call()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_sync_with_method_call` is not `Send` | = help: within `impl Future`, the trait `Send` is not implemented for `dyn std::fmt::Write` note: future is not `Send` as this value is used across an await - --> $DIR/async-fn-nonsend.rs:46:14 + --> $DIR/async-fn-nonsend.rs:49:14 | LL | let f: &mut std::fmt::Formatter = &mut get_formatter(); | --------------- has type `Formatter<'_>` which is not `Send` @@ -40,7 +40,7 @@ LL | } LL | } | - `get_formatter()` is later dropped here note: required by a bound in `assert_send` - --> $DIR/async-fn-nonsend.rs:64:24 + --> $DIR/async-fn-nonsend.rs:67:24 | LL | fn assert_send(_: impl Send) {} | ^^^^ required by this bound in `assert_send` diff --git a/tests/ui/async-await/default-struct-update.rs b/tests/ui/async-await/default-struct-update.rs index 64fb6280dd7bb..daee8469a1406 100644 --- a/tests/ui/async-await/default-struct-update.rs +++ b/tests/ui/async-await/default-struct-update.rs @@ -1,6 +1,8 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // build-pass // edition:2018 -// compile-flags: -Zdrop-tracking=y fn main() { let _ = foo(); diff --git a/tests/ui/async-await/drop-and-assign.rs b/tests/ui/async-await/drop-and-assign.rs index fa3f3303677da..e520dfbdccebb 100644 --- a/tests/ui/async-await/drop-and-assign.rs +++ b/tests/ui/async-await/drop-and-assign.rs @@ -1,5 +1,7 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2021 -// compile-flags: -Zdrop-tracking // build-pass struct A; diff --git a/tests/ui/async-await/drop-track-field-assign-nonsend.stderr b/tests/ui/async-await/drop-track-field-assign-nonsend.drop_tracking.stderr similarity index 84% rename from tests/ui/async-await/drop-track-field-assign-nonsend.stderr rename to tests/ui/async-await/drop-track-field-assign-nonsend.drop_tracking.stderr index d95483c81195c..e2bba812d05b1 100644 --- a/tests/ui/async-await/drop-track-field-assign-nonsend.stderr +++ b/tests/ui/async-await/drop-track-field-assign-nonsend.drop_tracking.stderr @@ -1,12 +1,12 @@ error: future cannot be sent between threads safely - --> $DIR/drop-track-field-assign-nonsend.rs:43:17 + --> $DIR/drop-track-field-assign-nonsend.rs:45:17 | LL | assert_send(agent.handle()); | ^^^^^^^^^^^^^^ future returned by `handle` is not `Send` | = help: within `impl Future`, the trait `Send` is not implemented for `Rc` note: future is not `Send` as this value is used across an await - --> $DIR/drop-track-field-assign-nonsend.rs:21:38 + --> $DIR/drop-track-field-assign-nonsend.rs:23:38 | LL | let mut info = self.info_result.clone(); | -------- has type `InfoResult` which is not `Send` @@ -16,7 +16,7 @@ LL | let _ = send_element(element).await; LL | } | - `mut info` is later dropped here note: required by a bound in `assert_send` - --> $DIR/drop-track-field-assign-nonsend.rs:38:19 + --> $DIR/drop-track-field-assign-nonsend.rs:40:19 | LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` diff --git a/tests/ui/async-await/drop-track-field-assign-nonsend.drop_tracking_mir.stderr b/tests/ui/async-await/drop-track-field-assign-nonsend.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..e2bba812d05b1 --- /dev/null +++ b/tests/ui/async-await/drop-track-field-assign-nonsend.drop_tracking_mir.stderr @@ -0,0 +1,25 @@ +error: future cannot be sent between threads safely + --> $DIR/drop-track-field-assign-nonsend.rs:45:17 + | +LL | assert_send(agent.handle()); + | ^^^^^^^^^^^^^^ future returned by `handle` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc` +note: future is not `Send` as this value is used across an await + --> $DIR/drop-track-field-assign-nonsend.rs:23:38 + | +LL | let mut info = self.info_result.clone(); + | -------- has type `InfoResult` which is not `Send` +... +LL | let _ = send_element(element).await; + | ^^^^^^ await occurs here, with `mut info` maybe used later +LL | } + | - `mut info` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/drop-track-field-assign-nonsend.rs:40:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/drop-track-field-assign-nonsend.no_drop_tracking.stderr b/tests/ui/async-await/drop-track-field-assign-nonsend.no_drop_tracking.stderr new file mode 100644 index 0000000000000..e2bba812d05b1 --- /dev/null +++ b/tests/ui/async-await/drop-track-field-assign-nonsend.no_drop_tracking.stderr @@ -0,0 +1,25 @@ +error: future cannot be sent between threads safely + --> $DIR/drop-track-field-assign-nonsend.rs:45:17 + | +LL | assert_send(agent.handle()); + | ^^^^^^^^^^^^^^ future returned by `handle` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc` +note: future is not `Send` as this value is used across an await + --> $DIR/drop-track-field-assign-nonsend.rs:23:38 + | +LL | let mut info = self.info_result.clone(); + | -------- has type `InfoResult` which is not `Send` +... +LL | let _ = send_element(element).await; + | ^^^^^^ await occurs here, with `mut info` maybe used later +LL | } + | - `mut info` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/drop-track-field-assign-nonsend.rs:40:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/drop-track-field-assign-nonsend.rs b/tests/ui/async-await/drop-track-field-assign-nonsend.rs index b6c0fda15216a..3e22280008fcf 100644 --- a/tests/ui/async-await/drop-track-field-assign-nonsend.rs +++ b/tests/ui/async-await/drop-track-field-assign-nonsend.rs @@ -1,6 +1,8 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // Derived from an ICE found in tokio-xmpp during a crater run. // edition:2021 -// compile-flags: -Zdrop-tracking #![allow(dead_code)] diff --git a/tests/ui/async-await/drop-track-field-assign.rs b/tests/ui/async-await/drop-track-field-assign.rs index 3a393cd164b99..dd0e3f11ccc01 100644 --- a/tests/ui/async-await/drop-track-field-assign.rs +++ b/tests/ui/async-await/drop-track-field-assign.rs @@ -1,6 +1,8 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // Derived from an ICE found in tokio-xmpp during a crater run. // edition:2021 -// compile-flags: -Zdrop-tracking // build-pass #![allow(dead_code)] diff --git a/tests/ui/async-await/field-assign-nonsend.drop_tracking.stderr b/tests/ui/async-await/field-assign-nonsend.drop_tracking.stderr new file mode 100644 index 0000000000000..ac461a671a82a --- /dev/null +++ b/tests/ui/async-await/field-assign-nonsend.drop_tracking.stderr @@ -0,0 +1,25 @@ +error: future cannot be sent between threads safely + --> $DIR/field-assign-nonsend.rs:45:17 + | +LL | assert_send(agent.handle()); + | ^^^^^^^^^^^^^^ future returned by `handle` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc` +note: future is not `Send` as this value is used across an await + --> $DIR/field-assign-nonsend.rs:23:38 + | +LL | let mut info = self.info_result.clone(); + | -------- has type `InfoResult` which is not `Send` +... +LL | let _ = send_element(element).await; + | ^^^^^^ await occurs here, with `mut info` maybe used later +LL | } + | - `mut info` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/field-assign-nonsend.rs:40:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/field-assign-nonsend.drop_tracking_mir.stderr b/tests/ui/async-await/field-assign-nonsend.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..ac461a671a82a --- /dev/null +++ b/tests/ui/async-await/field-assign-nonsend.drop_tracking_mir.stderr @@ -0,0 +1,25 @@ +error: future cannot be sent between threads safely + --> $DIR/field-assign-nonsend.rs:45:17 + | +LL | assert_send(agent.handle()); + | ^^^^^^^^^^^^^^ future returned by `handle` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc` +note: future is not `Send` as this value is used across an await + --> $DIR/field-assign-nonsend.rs:23:38 + | +LL | let mut info = self.info_result.clone(); + | -------- has type `InfoResult` which is not `Send` +... +LL | let _ = send_element(element).await; + | ^^^^^^ await occurs here, with `mut info` maybe used later +LL | } + | - `mut info` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/field-assign-nonsend.rs:40:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/field-assign-nonsend.no_drop_tracking.stderr b/tests/ui/async-await/field-assign-nonsend.no_drop_tracking.stderr new file mode 100644 index 0000000000000..ac461a671a82a --- /dev/null +++ b/tests/ui/async-await/field-assign-nonsend.no_drop_tracking.stderr @@ -0,0 +1,25 @@ +error: future cannot be sent between threads safely + --> $DIR/field-assign-nonsend.rs:45:17 + | +LL | assert_send(agent.handle()); + | ^^^^^^^^^^^^^^ future returned by `handle` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Rc` +note: future is not `Send` as this value is used across an await + --> $DIR/field-assign-nonsend.rs:23:38 + | +LL | let mut info = self.info_result.clone(); + | -------- has type `InfoResult` which is not `Send` +... +LL | let _ = send_element(element).await; + | ^^^^^^ await occurs here, with `mut info` maybe used later +LL | } + | - `mut info` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/field-assign-nonsend.rs:40:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/field-assign-nonsend.rs b/tests/ui/async-await/field-assign-nonsend.rs new file mode 100644 index 0000000000000..3e22280008fcf --- /dev/null +++ b/tests/ui/async-await/field-assign-nonsend.rs @@ -0,0 +1,47 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir +// Derived from an ICE found in tokio-xmpp during a crater run. +// edition:2021 + +#![allow(dead_code)] + +#[derive(Clone)] +struct InfoResult { + node: Option> +} + +struct Agent { + info_result: InfoResult +} + +impl Agent { + async fn handle(&mut self) { + let mut info = self.info_result.clone(); + info.node = None; + let element = parse_info(info); + let _ = send_element(element).await; + } +} + +struct Element { +} + +async fn send_element(_: Element) {} + +fn parse(_: &[u8]) -> Result<(), ()> { + Ok(()) +} + +fn parse_info(_: InfoResult) -> Element { + Element { } +} + +fn assert_send(_: T) {} + +fn main() { + let agent = Agent { info_result: InfoResult { node: None } }; + // FIXME: It would be nice for this to work. See #94067. + assert_send(agent.handle()); + //~^ cannot be sent between threads safely +} diff --git a/tests/ui/async-await/field-assign.rs b/tests/ui/async-await/field-assign.rs new file mode 100644 index 0000000000000..dd0e3f11ccc01 --- /dev/null +++ b/tests/ui/async-await/field-assign.rs @@ -0,0 +1,46 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir +// Derived from an ICE found in tokio-xmpp during a crater run. +// edition:2021 +// build-pass + +#![allow(dead_code)] + +#[derive(Clone)] +struct InfoResult { + node: Option +} + +struct Agent { + info_result: InfoResult +} + +impl Agent { + async fn handle(&mut self) { + let mut info = self.info_result.clone(); + info.node = Some("bar".into()); + let element = parse_info(info); + let _ = send_element(element).await; + } +} + +struct Element { +} + +async fn send_element(_: Element) {} + +fn parse(_: &[u8]) -> Result<(), ()> { + Ok(()) +} + +fn parse_info(_: InfoResult) -> Element { + Element { } +} + +fn main() { + let mut agent = Agent { + info_result: InfoResult { node: None } + }; + let _ = agent.handle(); +} diff --git a/tests/ui/async-await/issue-64130-1-sync.drop_tracking.stderr b/tests/ui/async-await/issue-64130-1-sync.drop_tracking.stderr new file mode 100644 index 0000000000000..8d5169a6302ee --- /dev/null +++ b/tests/ui/async-await/issue-64130-1-sync.drop_tracking.stderr @@ -0,0 +1,24 @@ +error: future cannot be shared between threads safely + --> $DIR/issue-64130-1-sync.rs:24:13 + | +LL | is_sync(bar()); + | ^^^^^ future returned by `bar` is not `Sync` + | + = help: within `impl Future`, the trait `Sync` is not implemented for `Foo` +note: future is not `Sync` as this value is used across an await + --> $DIR/issue-64130-1-sync.rs:18:10 + | +LL | let x = Foo; + | - has type `Foo` which is not `Sync` +LL | baz().await; + | ^^^^^^ await occurs here, with `x` maybe used later +LL | } + | - `x` is later dropped here +note: required by a bound in `is_sync` + --> $DIR/issue-64130-1-sync.rs:14:15 + | +LL | fn is_sync(t: T) { } + | ^^^^ required by this bound in `is_sync` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-64130-1-sync.drop_tracking_mir.stderr b/tests/ui/async-await/issue-64130-1-sync.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..8d5169a6302ee --- /dev/null +++ b/tests/ui/async-await/issue-64130-1-sync.drop_tracking_mir.stderr @@ -0,0 +1,24 @@ +error: future cannot be shared between threads safely + --> $DIR/issue-64130-1-sync.rs:24:13 + | +LL | is_sync(bar()); + | ^^^^^ future returned by `bar` is not `Sync` + | + = help: within `impl Future`, the trait `Sync` is not implemented for `Foo` +note: future is not `Sync` as this value is used across an await + --> $DIR/issue-64130-1-sync.rs:18:10 + | +LL | let x = Foo; + | - has type `Foo` which is not `Sync` +LL | baz().await; + | ^^^^^^ await occurs here, with `x` maybe used later +LL | } + | - `x` is later dropped here +note: required by a bound in `is_sync` + --> $DIR/issue-64130-1-sync.rs:14:15 + | +LL | fn is_sync(t: T) { } + | ^^^^ required by this bound in `is_sync` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-64130-1-sync.no_drop_tracking.stderr b/tests/ui/async-await/issue-64130-1-sync.no_drop_tracking.stderr new file mode 100644 index 0000000000000..8d5169a6302ee --- /dev/null +++ b/tests/ui/async-await/issue-64130-1-sync.no_drop_tracking.stderr @@ -0,0 +1,24 @@ +error: future cannot be shared between threads safely + --> $DIR/issue-64130-1-sync.rs:24:13 + | +LL | is_sync(bar()); + | ^^^^^ future returned by `bar` is not `Sync` + | + = help: within `impl Future`, the trait `Sync` is not implemented for `Foo` +note: future is not `Sync` as this value is used across an await + --> $DIR/issue-64130-1-sync.rs:18:10 + | +LL | let x = Foo; + | - has type `Foo` which is not `Sync` +LL | baz().await; + | ^^^^^^ await occurs here, with `x` maybe used later +LL | } + | - `x` is later dropped here +note: required by a bound in `is_sync` + --> $DIR/issue-64130-1-sync.rs:14:15 + | +LL | fn is_sync(t: T) { } + | ^^^^ required by this bound in `is_sync` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-64130-1-sync.rs b/tests/ui/async-await/issue-64130-1-sync.rs index 1714cec5221de..67c99c4817254 100644 --- a/tests/ui/async-await/issue-64130-1-sync.rs +++ b/tests/ui/async-await/issue-64130-1-sync.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir #![feature(negative_impls)] // edition:2018 diff --git a/tests/ui/async-await/issue-64130-1-sync.stderr b/tests/ui/async-await/issue-64130-1-sync.stderr index e205de4738f24..8d5169a6302ee 100644 --- a/tests/ui/async-await/issue-64130-1-sync.stderr +++ b/tests/ui/async-await/issue-64130-1-sync.stderr @@ -1,12 +1,12 @@ error: future cannot be shared between threads safely - --> $DIR/issue-64130-1-sync.rs:21:13 + --> $DIR/issue-64130-1-sync.rs:24:13 | LL | is_sync(bar()); | ^^^^^ future returned by `bar` is not `Sync` | = help: within `impl Future`, the trait `Sync` is not implemented for `Foo` note: future is not `Sync` as this value is used across an await - --> $DIR/issue-64130-1-sync.rs:15:10 + --> $DIR/issue-64130-1-sync.rs:18:10 | LL | let x = Foo; | - has type `Foo` which is not `Sync` @@ -15,7 +15,7 @@ LL | baz().await; LL | } | - `x` is later dropped here note: required by a bound in `is_sync` - --> $DIR/issue-64130-1-sync.rs:11:15 + --> $DIR/issue-64130-1-sync.rs:14:15 | LL | fn is_sync(t: T) { } | ^^^^ required by this bound in `is_sync` diff --git a/tests/ui/async-await/issue-64130-2-send.drop_tracking.stderr b/tests/ui/async-await/issue-64130-2-send.drop_tracking.stderr new file mode 100644 index 0000000000000..f6505cad69e21 --- /dev/null +++ b/tests/ui/async-await/issue-64130-2-send.drop_tracking.stderr @@ -0,0 +1,24 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-64130-2-send.rs:24:13 + | +LL | is_send(bar()); + | ^^^^^ future returned by `bar` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Foo` +note: future is not `Send` as this value is used across an await + --> $DIR/issue-64130-2-send.rs:18:10 + | +LL | let x = Foo; + | - has type `Foo` which is not `Send` +LL | baz().await; + | ^^^^^^ await occurs here, with `x` maybe used later +LL | } + | - `x` is later dropped here +note: required by a bound in `is_send` + --> $DIR/issue-64130-2-send.rs:14:15 + | +LL | fn is_send(t: T) { } + | ^^^^ required by this bound in `is_send` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-64130-2-send.drop_tracking_mir.stderr b/tests/ui/async-await/issue-64130-2-send.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..f6505cad69e21 --- /dev/null +++ b/tests/ui/async-await/issue-64130-2-send.drop_tracking_mir.stderr @@ -0,0 +1,24 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-64130-2-send.rs:24:13 + | +LL | is_send(bar()); + | ^^^^^ future returned by `bar` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Foo` +note: future is not `Send` as this value is used across an await + --> $DIR/issue-64130-2-send.rs:18:10 + | +LL | let x = Foo; + | - has type `Foo` which is not `Send` +LL | baz().await; + | ^^^^^^ await occurs here, with `x` maybe used later +LL | } + | - `x` is later dropped here +note: required by a bound in `is_send` + --> $DIR/issue-64130-2-send.rs:14:15 + | +LL | fn is_send(t: T) { } + | ^^^^ required by this bound in `is_send` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-64130-2-send.no_drop_tracking.stderr b/tests/ui/async-await/issue-64130-2-send.no_drop_tracking.stderr new file mode 100644 index 0000000000000..f6505cad69e21 --- /dev/null +++ b/tests/ui/async-await/issue-64130-2-send.no_drop_tracking.stderr @@ -0,0 +1,24 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-64130-2-send.rs:24:13 + | +LL | is_send(bar()); + | ^^^^^ future returned by `bar` is not `Send` + | + = help: within `impl Future`, the trait `Send` is not implemented for `Foo` +note: future is not `Send` as this value is used across an await + --> $DIR/issue-64130-2-send.rs:18:10 + | +LL | let x = Foo; + | - has type `Foo` which is not `Send` +LL | baz().await; + | ^^^^^^ await occurs here, with `x` maybe used later +LL | } + | - `x` is later dropped here +note: required by a bound in `is_send` + --> $DIR/issue-64130-2-send.rs:14:15 + | +LL | fn is_send(t: T) { } + | ^^^^ required by this bound in `is_send` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-64130-2-send.rs b/tests/ui/async-await/issue-64130-2-send.rs index 7a6e5952cb956..2cb379fe88150 100644 --- a/tests/ui/async-await/issue-64130-2-send.rs +++ b/tests/ui/async-await/issue-64130-2-send.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir #![feature(negative_impls)] // edition:2018 diff --git a/tests/ui/async-await/issue-64130-2-send.stderr b/tests/ui/async-await/issue-64130-2-send.stderr index 2225000e2e579..f6505cad69e21 100644 --- a/tests/ui/async-await/issue-64130-2-send.stderr +++ b/tests/ui/async-await/issue-64130-2-send.stderr @@ -1,12 +1,12 @@ error: future cannot be sent between threads safely - --> $DIR/issue-64130-2-send.rs:21:13 + --> $DIR/issue-64130-2-send.rs:24:13 | LL | is_send(bar()); | ^^^^^ future returned by `bar` is not `Send` | = help: within `impl Future`, the trait `Send` is not implemented for `Foo` note: future is not `Send` as this value is used across an await - --> $DIR/issue-64130-2-send.rs:15:10 + --> $DIR/issue-64130-2-send.rs:18:10 | LL | let x = Foo; | - has type `Foo` which is not `Send` @@ -15,7 +15,7 @@ LL | baz().await; LL | } | - `x` is later dropped here note: required by a bound in `is_send` - --> $DIR/issue-64130-2-send.rs:11:15 + --> $DIR/issue-64130-2-send.rs:14:15 | LL | fn is_send(t: T) { } | ^^^^ required by this bound in `is_send` diff --git a/tests/ui/async-await/issue-64130-3-other.drop_tracking.stderr b/tests/ui/async-await/issue-64130-3-other.drop_tracking.stderr new file mode 100644 index 0000000000000..cb36a3811b280 --- /dev/null +++ b/tests/ui/async-await/issue-64130-3-other.drop_tracking.stderr @@ -0,0 +1,27 @@ +error[E0277]: the trait bound `Foo: Qux` is not satisfied in `impl Future` + --> $DIR/issue-64130-3-other.rs:27:12 + | +LL | async fn bar() { + | - within this `impl Future` +... +LL | is_qux(bar()); + | ^^^^^ within `impl Future`, the trait `Qux` is not implemented for `Foo` + | +note: future does not implement `Qux` as this value is used across an await + --> $DIR/issue-64130-3-other.rs:21:10 + | +LL | let x = Foo; + | - has type `Foo` which does not implement `Qux` +LL | baz().await; + | ^^^^^^ await occurs here, with `x` maybe used later +LL | } + | - `x` is later dropped here +note: required by a bound in `is_qux` + --> $DIR/issue-64130-3-other.rs:17:14 + | +LL | fn is_qux(t: T) {} + | ^^^ required by this bound in `is_qux` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/issue-64130-3-other.drop_tracking_mir.stderr b/tests/ui/async-await/issue-64130-3-other.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..cb36a3811b280 --- /dev/null +++ b/tests/ui/async-await/issue-64130-3-other.drop_tracking_mir.stderr @@ -0,0 +1,27 @@ +error[E0277]: the trait bound `Foo: Qux` is not satisfied in `impl Future` + --> $DIR/issue-64130-3-other.rs:27:12 + | +LL | async fn bar() { + | - within this `impl Future` +... +LL | is_qux(bar()); + | ^^^^^ within `impl Future`, the trait `Qux` is not implemented for `Foo` + | +note: future does not implement `Qux` as this value is used across an await + --> $DIR/issue-64130-3-other.rs:21:10 + | +LL | let x = Foo; + | - has type `Foo` which does not implement `Qux` +LL | baz().await; + | ^^^^^^ await occurs here, with `x` maybe used later +LL | } + | - `x` is later dropped here +note: required by a bound in `is_qux` + --> $DIR/issue-64130-3-other.rs:17:14 + | +LL | fn is_qux(t: T) {} + | ^^^ required by this bound in `is_qux` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/issue-64130-3-other.no_drop_tracking.stderr b/tests/ui/async-await/issue-64130-3-other.no_drop_tracking.stderr new file mode 100644 index 0000000000000..cb36a3811b280 --- /dev/null +++ b/tests/ui/async-await/issue-64130-3-other.no_drop_tracking.stderr @@ -0,0 +1,27 @@ +error[E0277]: the trait bound `Foo: Qux` is not satisfied in `impl Future` + --> $DIR/issue-64130-3-other.rs:27:12 + | +LL | async fn bar() { + | - within this `impl Future` +... +LL | is_qux(bar()); + | ^^^^^ within `impl Future`, the trait `Qux` is not implemented for `Foo` + | +note: future does not implement `Qux` as this value is used across an await + --> $DIR/issue-64130-3-other.rs:21:10 + | +LL | let x = Foo; + | - has type `Foo` which does not implement `Qux` +LL | baz().await; + | ^^^^^^ await occurs here, with `x` maybe used later +LL | } + | - `x` is later dropped here +note: required by a bound in `is_qux` + --> $DIR/issue-64130-3-other.rs:17:14 + | +LL | fn is_qux(t: T) {} + | ^^^ required by this bound in `is_qux` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/issue-64130-3-other.rs b/tests/ui/async-await/issue-64130-3-other.rs index 630fb2c41cded..6c242a60e1c6e 100644 --- a/tests/ui/async-await/issue-64130-3-other.rs +++ b/tests/ui/async-await/issue-64130-3-other.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir #![feature(auto_traits)] #![feature(negative_impls)] // edition:2018 diff --git a/tests/ui/async-await/issue-64130-3-other.stderr b/tests/ui/async-await/issue-64130-3-other.stderr index 17867a6a3f62e..cb36a3811b280 100644 --- a/tests/ui/async-await/issue-64130-3-other.stderr +++ b/tests/ui/async-await/issue-64130-3-other.stderr @@ -1,5 +1,5 @@ error[E0277]: the trait bound `Foo: Qux` is not satisfied in `impl Future` - --> $DIR/issue-64130-3-other.rs:24:12 + --> $DIR/issue-64130-3-other.rs:27:12 | LL | async fn bar() { | - within this `impl Future` @@ -8,7 +8,7 @@ LL | is_qux(bar()); | ^^^^^ within `impl Future`, the trait `Qux` is not implemented for `Foo` | note: future does not implement `Qux` as this value is used across an await - --> $DIR/issue-64130-3-other.rs:18:10 + --> $DIR/issue-64130-3-other.rs:21:10 | LL | let x = Foo; | - has type `Foo` which does not implement `Qux` @@ -17,7 +17,7 @@ LL | baz().await; LL | } | - `x` is later dropped here note: required by a bound in `is_qux` - --> $DIR/issue-64130-3-other.rs:14:14 + --> $DIR/issue-64130-3-other.rs:17:14 | LL | fn is_qux(t: T) {} | ^^^ required by this bound in `is_qux` diff --git a/tests/ui/async-await/issue-64130-4-async-move.drop-tracking.stderr b/tests/ui/async-await/issue-64130-4-async-move.drop-tracking.stderr index f609e36362c44..884619f4dd69d 100644 --- a/tests/ui/async-await/issue-64130-4-async-move.drop-tracking.stderr +++ b/tests/ui/async-await/issue-64130-4-async-move.drop-tracking.stderr @@ -1,12 +1,12 @@ error: future cannot be sent between threads safely - --> $DIR/issue-64130-4-async-move.rs:19:17 + --> $DIR/issue-64130-4-async-move.rs:20:17 | LL | pub fn foo() -> impl Future + Send { | ^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` | = help: the trait `Sync` is not implemented for `(dyn Any + Send + 'static)` note: future is not `Send` as this value is used across an await - --> $DIR/issue-64130-4-async-move.rs:25:31 + --> $DIR/issue-64130-4-async-move.rs:27:31 | LL | match client.status() { | ------ has type `&Client` which is not `Send` @@ -17,7 +17,7 @@ LL | let _x = get().await; LL | } | - `client` is later dropped here help: consider moving this into a `let` binding to create a shorter lived borrow - --> $DIR/issue-64130-4-async-move.rs:23:15 + --> $DIR/issue-64130-4-async-move.rs:25:15 | LL | match client.status() { | ^^^^^^^^^^^^^^^ diff --git a/tests/ui/async-await/issue-64130-4-async-move.drop_tracking_mir.stderr b/tests/ui/async-await/issue-64130-4-async-move.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..884619f4dd69d --- /dev/null +++ b/tests/ui/async-await/issue-64130-4-async-move.drop_tracking_mir.stderr @@ -0,0 +1,26 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-64130-4-async-move.rs:20:17 + | +LL | pub fn foo() -> impl Future + Send { + | ^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` + | + = help: the trait `Sync` is not implemented for `(dyn Any + Send + 'static)` +note: future is not `Send` as this value is used across an await + --> $DIR/issue-64130-4-async-move.rs:27:31 + | +LL | match client.status() { + | ------ has type `&Client` which is not `Send` +LL | 200 => { +LL | let _x = get().await; + | ^^^^^^ await occurs here, with `client` maybe used later +... +LL | } + | - `client` is later dropped here +help: consider moving this into a `let` binding to create a shorter lived borrow + --> $DIR/issue-64130-4-async-move.rs:25:15 + | +LL | match client.status() { + | ^^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-64130-4-async-move.no_drop_tracking.stderr b/tests/ui/async-await/issue-64130-4-async-move.no_drop_tracking.stderr index f609e36362c44..884619f4dd69d 100644 --- a/tests/ui/async-await/issue-64130-4-async-move.no_drop_tracking.stderr +++ b/tests/ui/async-await/issue-64130-4-async-move.no_drop_tracking.stderr @@ -1,12 +1,12 @@ error: future cannot be sent between threads safely - --> $DIR/issue-64130-4-async-move.rs:19:17 + --> $DIR/issue-64130-4-async-move.rs:20:17 | LL | pub fn foo() -> impl Future + Send { | ^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` | = help: the trait `Sync` is not implemented for `(dyn Any + Send + 'static)` note: future is not `Send` as this value is used across an await - --> $DIR/issue-64130-4-async-move.rs:25:31 + --> $DIR/issue-64130-4-async-move.rs:27:31 | LL | match client.status() { | ------ has type `&Client` which is not `Send` @@ -17,7 +17,7 @@ LL | let _x = get().await; LL | } | - `client` is later dropped here help: consider moving this into a `let` binding to create a shorter lived borrow - --> $DIR/issue-64130-4-async-move.rs:23:15 + --> $DIR/issue-64130-4-async-move.rs:25:15 | LL | match client.status() { | ^^^^^^^^^^^^^^^ diff --git a/tests/ui/async-await/issue-64130-4-async-move.rs b/tests/ui/async-await/issue-64130-4-async-move.rs index a38428fc00f0b..13dceabb62f3b 100644 --- a/tests/ui/async-await/issue-64130-4-async-move.rs +++ b/tests/ui/async-await/issue-64130-4-async-move.rs @@ -1,8 +1,9 @@ // edition:2018 -// revisions: no_drop_tracking drop_tracking +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // [drop_tracking] check-pass -// [drop_tracking] compile-flags: -Zdrop-tracking=yes -// [no_drop_tracking] compile-flags: -Zdrop-tracking=no + use std::any::Any; use std::future::Future; @@ -18,6 +19,7 @@ async fn get() {} pub fn foo() -> impl Future + Send { //[no_drop_tracking]~^ ERROR future cannot be sent between threads safely + //[drop_tracking_mir]~^^ ERROR future cannot be sent between threads safely let client = Client(Box::new(true)); async move { match client.status() { diff --git a/tests/ui/async-await/issue-67252-unnamed-future.stderr b/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking.stderr similarity index 81% rename from tests/ui/async-await/issue-67252-unnamed-future.stderr rename to tests/ui/async-await/issue-67252-unnamed-future.drop_tracking.stderr index fcba4410ba9a5..e7a302fb3efcd 100644 --- a/tests/ui/async-await/issue-67252-unnamed-future.stderr +++ b/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking.stderr @@ -1,5 +1,5 @@ error: future cannot be sent between threads safely - --> $DIR/issue-67252-unnamed-future.rs:18:11 + --> $DIR/issue-67252-unnamed-future.rs:21:11 | LL | spawn(async { | ___________^ @@ -8,9 +8,9 @@ LL | | AFuture.await; LL | | }); | |_____^ future created by async block is not `Send` | - = help: within `[async block@$DIR/issue-67252-unnamed-future.rs:18:11: 21:6]`, the trait `Send` is not implemented for `*mut ()` + = help: within `[async block@$DIR/issue-67252-unnamed-future.rs:21:11: 24:6]`, the trait `Send` is not implemented for `*mut ()` note: future is not `Send` as this value is used across an await - --> $DIR/issue-67252-unnamed-future.rs:20:16 + --> $DIR/issue-67252-unnamed-future.rs:23:16 | LL | let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` | -- has type `*mut ()` which is not `Send` @@ -19,7 +19,7 @@ LL | AFuture.await; LL | }); | - `_a` is later dropped here note: required by a bound in `spawn` - --> $DIR/issue-67252-unnamed-future.rs:6:13 + --> $DIR/issue-67252-unnamed-future.rs:9:13 | LL | fn spawn(_: T) {} | ^^^^ required by this bound in `spawn` diff --git a/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking_mir.stderr b/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..e7a302fb3efcd --- /dev/null +++ b/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking_mir.stderr @@ -0,0 +1,28 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-67252-unnamed-future.rs:21:11 + | +LL | spawn(async { + | ___________^ +LL | | let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` +LL | | AFuture.await; +LL | | }); + | |_____^ future created by async block is not `Send` + | + = help: within `[async block@$DIR/issue-67252-unnamed-future.rs:21:11: 24:6]`, the trait `Send` is not implemented for `*mut ()` +note: future is not `Send` as this value is used across an await + --> $DIR/issue-67252-unnamed-future.rs:23:16 + | +LL | let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` + | -- has type `*mut ()` which is not `Send` +LL | AFuture.await; + | ^^^^^^ await occurs here, with `_a` maybe used later +LL | }); + | - `_a` is later dropped here +note: required by a bound in `spawn` + --> $DIR/issue-67252-unnamed-future.rs:9:13 + | +LL | fn spawn(_: T) {} + | ^^^^ required by this bound in `spawn` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-67252-unnamed-future.no_drop_tracking.stderr b/tests/ui/async-await/issue-67252-unnamed-future.no_drop_tracking.stderr new file mode 100644 index 0000000000000..e7a302fb3efcd --- /dev/null +++ b/tests/ui/async-await/issue-67252-unnamed-future.no_drop_tracking.stderr @@ -0,0 +1,28 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-67252-unnamed-future.rs:21:11 + | +LL | spawn(async { + | ___________^ +LL | | let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` +LL | | AFuture.await; +LL | | }); + | |_____^ future created by async block is not `Send` + | + = help: within `[async block@$DIR/issue-67252-unnamed-future.rs:21:11: 24:6]`, the trait `Send` is not implemented for `*mut ()` +note: future is not `Send` as this value is used across an await + --> $DIR/issue-67252-unnamed-future.rs:23:16 + | +LL | let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` + | -- has type `*mut ()` which is not `Send` +LL | AFuture.await; + | ^^^^^^ await occurs here, with `_a` maybe used later +LL | }); + | - `_a` is later dropped here +note: required by a bound in `spawn` + --> $DIR/issue-67252-unnamed-future.rs:9:13 + | +LL | fn spawn(_: T) {} + | ^^^^ required by this bound in `spawn` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-67252-unnamed-future.rs b/tests/ui/async-await/issue-67252-unnamed-future.rs index 1a7ff613341ec..658f059cf81cb 100644 --- a/tests/ui/async-await/issue-67252-unnamed-future.rs +++ b/tests/ui/async-await/issue-67252-unnamed-future.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 use std::future::Future; use std::pin::Pin; diff --git a/tests/ui/async-await/issue-68112.drop_tracking_mir.stderr b/tests/ui/async-await/issue-68112.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..35b7341f63a4d --- /dev/null +++ b/tests/ui/async-await/issue-68112.drop_tracking_mir.stderr @@ -0,0 +1,82 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-68112.rs:37:18 + | +LL | require_send(send_fut); + | ^^^^^^^^ future created by async block is not `Send` + | + = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead +note: future is not `Send` as it awaits another future which is not `Send` + --> $DIR/issue-68112.rs:34:17 + | +LL | let _ = non_send_fut.await; + | ^^^^^^^^^^^^ await occurs here on type `impl Future>>`, which is not `Send` +note: required by a bound in `require_send` + --> $DIR/issue-68112.rs:14:25 + | +LL | fn require_send(_: impl Send) {} + | ^^^^ required by this bound in `require_send` + +error: future cannot be sent between threads safely + --> $DIR/issue-68112.rs:46:18 + | +LL | require_send(send_fut); + | ^^^^^^^^ future created by async block is not `Send` + | + = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead +note: future is not `Send` as it awaits another future which is not `Send` + --> $DIR/issue-68112.rs:43:17 + | +LL | let _ = make_non_send_future1().await; + | ^^^^^^^^^^^^^^^^^^^^^^^ await occurs here on type `impl Future>>`, which is not `Send` +note: required by a bound in `require_send` + --> $DIR/issue-68112.rs:14:25 + | +LL | fn require_send(_: impl Send) {} + | ^^^^ required by this bound in `require_send` + +error[E0277]: `RefCell` cannot be shared between threads safely + --> $DIR/issue-68112.rs:65:18 + | +LL | require_send(send_fut); + | ------------ ^^^^^^^^ `RefCell` cannot be shared between threads safely + | | + | required by a bound introduced by this call + | + = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead + = note: required for `Arc>` to implement `Send` +note: required because it's used within this `async fn` body + --> $DIR/issue-68112.rs:50:31 + | +LL | async fn ready2(t: T) -> T { + | _______________________________^ +LL | | t +LL | | } + | |_^ +note: required because it appears within the type `impl Future>>` + --> $DIR/issue-68112.rs:53:31 + | +LL | fn make_non_send_future2() -> impl Future>> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required because it captures the following types: `ResumeTy`, `impl Future>>`, `()`, `i32`, `Ready` +note: required because it's used within this `async` block + --> $DIR/issue-68112.rs:60:20 + | +LL | let send_fut = async { + | ____________________^ +LL | | let non_send_fut = make_non_send_future2(); +LL | | let _ = non_send_fut.await; +LL | | ready(0).await; +LL | | }; + | |_____^ +note: required by a bound in `require_send` + --> $DIR/issue-68112.rs:14:25 + | +LL | fn require_send(_: impl Send) {} + | ^^^^ required by this bound in `require_send` + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/issue-68112.rs b/tests/ui/async-await/issue-68112.rs index 9c705137a1056..7f0a135a15961 100644 --- a/tests/ui/async-await/issue-68112.rs +++ b/tests/ui/async-await/issue-68112.rs @@ -1,7 +1,7 @@ // edition:2018 -// revisions: no_drop_tracking drop_tracking -// [drop_tracking] compile-flags: -Zdrop-tracking=yes -// [no_drop_tracking] compile-flags: -Zdrop-tracking=no +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir use std::{ cell::RefCell, diff --git a/tests/ui/async-await/issue-70818.drop_tracking.stderr b/tests/ui/async-await/issue-70818.drop_tracking.stderr new file mode 100644 index 0000000000000..ab0698c3ec213 --- /dev/null +++ b/tests/ui/async-await/issue-70818.drop_tracking.stderr @@ -0,0 +1,18 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-70818.rs:7:38 + | +LL | fn foo(ty: T, ty1: U) -> impl Future + Send { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` + | +note: captured value is not `Send` + --> $DIR/issue-70818.rs:9:18 + | +LL | async { (ty, ty1) } + | ^^^ has type `U` which is not `Send` +help: consider restricting type parameter `U` + | +LL | fn foo(ty: T, ty1: U) -> impl Future + Send { + | +++++++++++++++++++ + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-70818.drop_tracking_mir.stderr b/tests/ui/async-await/issue-70818.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..ab0698c3ec213 --- /dev/null +++ b/tests/ui/async-await/issue-70818.drop_tracking_mir.stderr @@ -0,0 +1,18 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-70818.rs:7:38 + | +LL | fn foo(ty: T, ty1: U) -> impl Future + Send { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` + | +note: captured value is not `Send` + --> $DIR/issue-70818.rs:9:18 + | +LL | async { (ty, ty1) } + | ^^^ has type `U` which is not `Send` +help: consider restricting type parameter `U` + | +LL | fn foo(ty: T, ty1: U) -> impl Future + Send { + | +++++++++++++++++++ + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-70818.no_drop_tracking.stderr b/tests/ui/async-await/issue-70818.no_drop_tracking.stderr new file mode 100644 index 0000000000000..ab0698c3ec213 --- /dev/null +++ b/tests/ui/async-await/issue-70818.no_drop_tracking.stderr @@ -0,0 +1,18 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-70818.rs:7:38 + | +LL | fn foo(ty: T, ty1: U) -> impl Future + Send { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` + | +note: captured value is not `Send` + --> $DIR/issue-70818.rs:9:18 + | +LL | async { (ty, ty1) } + | ^^^ has type `U` which is not `Send` +help: consider restricting type parameter `U` + | +LL | fn foo(ty: T, ty1: U) -> impl Future + Send { + | +++++++++++++++++++ + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-70818.rs b/tests/ui/async-await/issue-70818.rs index 019c56eb2fa3e..2941de0f57714 100644 --- a/tests/ui/async-await/issue-70818.rs +++ b/tests/ui/async-await/issue-70818.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 use std::future::Future; diff --git a/tests/ui/async-await/issue-70818.stderr b/tests/ui/async-await/issue-70818.stderr index 20109d4d1166a..ab0698c3ec213 100644 --- a/tests/ui/async-await/issue-70818.stderr +++ b/tests/ui/async-await/issue-70818.stderr @@ -1,11 +1,11 @@ error: future cannot be sent between threads safely - --> $DIR/issue-70818.rs:4:38 + --> $DIR/issue-70818.rs:7:38 | LL | fn foo(ty: T, ty1: U) -> impl Future + Send { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` | note: captured value is not `Send` - --> $DIR/issue-70818.rs:6:18 + --> $DIR/issue-70818.rs:9:18 | LL | async { (ty, ty1) } | ^^^ has type `U` which is not `Send` diff --git a/tests/ui/async-await/issue-70935-complex-spans.drop_tracking.stderr b/tests/ui/async-await/issue-70935-complex-spans.drop_tracking.stderr index 721234aa4a782..ea61daa5a1683 100644 --- a/tests/ui/async-await/issue-70935-complex-spans.drop_tracking.stderr +++ b/tests/ui/async-await/issue-70935-complex-spans.drop_tracking.stderr @@ -7,7 +7,7 @@ LL | fn foo(tx: std::sync::mpsc::Sender) -> impl Future + Send { = help: the trait `Sync` is not implemented for `Sender` = note: required for `&Sender` to implement `Send` note: required because it's used within this closure - --> $DIR/issue-70935-complex-spans.rs:17:13 + --> $DIR/issue-70935-complex-spans.rs:18:13 | LL | baz(|| async{ | ^^ @@ -20,7 +20,7 @@ LL | | } | |_^ = note: required because it captures the following types: `ResumeTy`, `impl Future`, `()` note: required because it's used within this `async` block - --> $DIR/issue-70935-complex-spans.rs:16:5 + --> $DIR/issue-70935-complex-spans.rs:17:5 | LL | / async move { LL | | baz(|| async{ diff --git a/tests/ui/async-await/issue-70935-complex-spans.drop_tracking_mir.stderr b/tests/ui/async-await/issue-70935-complex-spans.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..6c48e6db45777 --- /dev/null +++ b/tests/ui/async-await/issue-70935-complex-spans.drop_tracking_mir.stderr @@ -0,0 +1,21 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-70935-complex-spans.rs:13:45 + | +LL | fn foo(tx: std::sync::mpsc::Sender) -> impl Future + Send { + | ^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` + | + = help: the trait `Sync` is not implemented for `Sender` +note: future is not `Send` as this value is used across an await + --> $DIR/issue-70935-complex-spans.rs:20:11 + | +LL | baz(|| async{ + | _____________- +LL | | foo(tx.clone()); +LL | | }).await; + | | - ^^^^^^- the value is later dropped here + | | | | + | |_________| await occurs here, with the value maybe used later + | has type `[closure@$DIR/issue-70935-complex-spans.rs:18:13: 18:15]` which is not `Send` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-70935-complex-spans.no_drop_tracking.stderr b/tests/ui/async-await/issue-70935-complex-spans.no_drop_tracking.stderr index 8036d82daa4a3..6c48e6db45777 100644 --- a/tests/ui/async-await/issue-70935-complex-spans.no_drop_tracking.stderr +++ b/tests/ui/async-await/issue-70935-complex-spans.no_drop_tracking.stderr @@ -6,7 +6,7 @@ LL | fn foo(tx: std::sync::mpsc::Sender) -> impl Future + Send { | = help: the trait `Sync` is not implemented for `Sender` note: future is not `Send` as this value is used across an await - --> $DIR/issue-70935-complex-spans.rs:19:11 + --> $DIR/issue-70935-complex-spans.rs:20:11 | LL | baz(|| async{ | _____________- @@ -15,7 +15,7 @@ LL | | }).await; | | - ^^^^^^- the value is later dropped here | | | | | |_________| await occurs here, with the value maybe used later - | has type `[closure@$DIR/issue-70935-complex-spans.rs:17:13: 17:15]` which is not `Send` + | has type `[closure@$DIR/issue-70935-complex-spans.rs:18:13: 18:15]` which is not `Send` error: aborting due to previous error diff --git a/tests/ui/async-await/issue-70935-complex-spans.rs b/tests/ui/async-await/issue-70935-complex-spans.rs index b6d17f93a6675..76cd293b05b67 100644 --- a/tests/ui/async-await/issue-70935-complex-spans.rs +++ b/tests/ui/async-await/issue-70935-complex-spans.rs @@ -1,7 +1,7 @@ // edition:2018 -// revisions: no_drop_tracking drop_tracking -// [no_drop_tracking]compile-flags:-Zdrop-tracking=no -// [drop_tracking]compile-flags:-Zdrop-tracking +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // #70935: Check if we do not emit snippet // with newlines which lead complex diagnostics. @@ -13,6 +13,7 @@ async fn baz(_c: impl FnMut() -> T) where T: Future { fn foo(tx: std::sync::mpsc::Sender) -> impl Future + Send { //[no_drop_tracking]~^ ERROR future cannot be sent between threads safely //[drop_tracking]~^^ ERROR `Sender` cannot be shared between threads + //[drop_tracking_mir]~^^^ ERROR future cannot be sent between threads safely async move { baz(|| async{ foo(tx.clone()); diff --git a/tests/ui/async-await/issue-73741-type-err-drop-tracking.drop_tracking.stderr b/tests/ui/async-await/issue-73741-type-err-drop-tracking.drop_tracking.stderr new file mode 100644 index 0000000000000..6d19c3beb2fe1 --- /dev/null +++ b/tests/ui/async-await/issue-73741-type-err-drop-tracking.drop_tracking.stderr @@ -0,0 +1,11 @@ +error[E0070]: invalid left-hand side of assignment + --> $DIR/issue-73741-type-err-drop-tracking.rs:11:7 + | +LL | 1 = 2; + | - ^ + | | + | cannot assign to this expression + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0070`. diff --git a/tests/ui/async-await/issue-73741-type-err-drop-tracking.drop_tracking_mir.stderr b/tests/ui/async-await/issue-73741-type-err-drop-tracking.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..6d19c3beb2fe1 --- /dev/null +++ b/tests/ui/async-await/issue-73741-type-err-drop-tracking.drop_tracking_mir.stderr @@ -0,0 +1,11 @@ +error[E0070]: invalid left-hand side of assignment + --> $DIR/issue-73741-type-err-drop-tracking.rs:11:7 + | +LL | 1 = 2; + | - ^ + | | + | cannot assign to this expression + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0070`. diff --git a/tests/ui/async-await/issue-73741-type-err-drop-tracking.no_drop_tracking.stderr b/tests/ui/async-await/issue-73741-type-err-drop-tracking.no_drop_tracking.stderr new file mode 100644 index 0000000000000..6d19c3beb2fe1 --- /dev/null +++ b/tests/ui/async-await/issue-73741-type-err-drop-tracking.no_drop_tracking.stderr @@ -0,0 +1,11 @@ +error[E0070]: invalid left-hand side of assignment + --> $DIR/issue-73741-type-err-drop-tracking.rs:11:7 + | +LL | 1 = 2; + | - ^ + | | + | cannot assign to this expression + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0070`. diff --git a/tests/ui/async-await/issue-73741-type-err-drop-tracking.rs b/tests/ui/async-await/issue-73741-type-err-drop-tracking.rs index c3423ad629f16..1fa8d69143a22 100644 --- a/tests/ui/async-await/issue-73741-type-err-drop-tracking.rs +++ b/tests/ui/async-await/issue-73741-type-err-drop-tracking.rs @@ -1,5 +1,8 @@ // edition:2018 -// compile-flags: -Zdrop-tracking +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir +// // Regression test for issue #73741 // Ensures that we don't emit spurious errors when // a type error ocurrs in an `async fn` diff --git a/tests/ui/async-await/issue-73741-type-err-drop-tracking.stderr b/tests/ui/async-await/issue-73741-type-err-drop-tracking.stderr index d4e3b6c3bf40d..6d19c3beb2fe1 100644 --- a/tests/ui/async-await/issue-73741-type-err-drop-tracking.stderr +++ b/tests/ui/async-await/issue-73741-type-err-drop-tracking.stderr @@ -1,5 +1,5 @@ error[E0070]: invalid left-hand side of assignment - --> $DIR/issue-73741-type-err-drop-tracking.rs:8:7 + --> $DIR/issue-73741-type-err-drop-tracking.rs:11:7 | LL | 1 = 2; | - ^ diff --git a/tests/ui/async-await/issue-86507.stderr b/tests/ui/async-await/issue-86507.drop_tracking.stderr similarity index 86% rename from tests/ui/async-await/issue-86507.stderr rename to tests/ui/async-await/issue-86507.drop_tracking.stderr index 8c2c06da25cc4..5c8b7ef1b7135 100644 --- a/tests/ui/async-await/issue-86507.stderr +++ b/tests/ui/async-await/issue-86507.drop_tracking.stderr @@ -1,5 +1,5 @@ error: future cannot be sent between threads safely - --> $DIR/issue-86507.rs:17:13 + --> $DIR/issue-86507.rs:20:13 | LL | / Box::pin( LL | | async move { @@ -9,11 +9,11 @@ LL | | ) | |_____________^ future created by async block is not `Send` | note: captured value is not `Send` because `&` references cannot be sent unless their referent is `Sync` - --> $DIR/issue-86507.rs:19:29 + --> $DIR/issue-86507.rs:22:29 | LL | let x = x; | ^ has type `&T` which is not `Send`, because `T` is not `Sync` - = note: required for the cast from `[async block@$DIR/issue-86507.rs:18:17: 20:18]` to the object type `dyn Future + Send` + = note: required for the cast from `[async block@$DIR/issue-86507.rs:21:17: 23:18]` to the object type `dyn Future + Send` help: consider further restricting this bound | LL | fn bar<'me, 'async_trait, T: Send + std::marker::Sync>(x: &'me T) diff --git a/tests/ui/async-await/issue-86507.drop_tracking_mir.stderr b/tests/ui/async-await/issue-86507.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..5c8b7ef1b7135 --- /dev/null +++ b/tests/ui/async-await/issue-86507.drop_tracking_mir.stderr @@ -0,0 +1,23 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-86507.rs:20:13 + | +LL | / Box::pin( +LL | | async move { +LL | | let x = x; +LL | | } +LL | | ) + | |_____________^ future created by async block is not `Send` + | +note: captured value is not `Send` because `&` references cannot be sent unless their referent is `Sync` + --> $DIR/issue-86507.rs:22:29 + | +LL | let x = x; + | ^ has type `&T` which is not `Send`, because `T` is not `Sync` + = note: required for the cast from `[async block@$DIR/issue-86507.rs:21:17: 23:18]` to the object type `dyn Future + Send` +help: consider further restricting this bound + | +LL | fn bar<'me, 'async_trait, T: Send + std::marker::Sync>(x: &'me T) + | +++++++++++++++++++ + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-86507.no_drop_tracking.stderr b/tests/ui/async-await/issue-86507.no_drop_tracking.stderr new file mode 100644 index 0000000000000..5c8b7ef1b7135 --- /dev/null +++ b/tests/ui/async-await/issue-86507.no_drop_tracking.stderr @@ -0,0 +1,23 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-86507.rs:20:13 + | +LL | / Box::pin( +LL | | async move { +LL | | let x = x; +LL | | } +LL | | ) + | |_____________^ future created by async block is not `Send` + | +note: captured value is not `Send` because `&` references cannot be sent unless their referent is `Sync` + --> $DIR/issue-86507.rs:22:29 + | +LL | let x = x; + | ^ has type `&T` which is not `Send`, because `T` is not `Sync` + = note: required for the cast from `[async block@$DIR/issue-86507.rs:21:17: 23:18]` to the object type `dyn Future + Send` +help: consider further restricting this bound + | +LL | fn bar<'me, 'async_trait, T: Send + std::marker::Sync>(x: &'me T) + | +++++++++++++++++++ + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issue-86507.rs b/tests/ui/async-await/issue-86507.rs index 317f0317664b6..63c298dbe3dcb 100644 --- a/tests/ui/async-await/issue-86507.rs +++ b/tests/ui/async-await/issue-86507.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 use ::core::pin::Pin; diff --git a/tests/ui/async-await/issue-93648.rs b/tests/ui/async-await/issue-93648.rs index 4ce3ac1e87460..ec2249ca592b5 100644 --- a/tests/ui/async-await/issue-93648.rs +++ b/tests/ui/async-await/issue-93648.rs @@ -1,6 +1,8 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2021 // build-pass -// compile-flags: -Zdrop-tracking fn main() { let _ = async { diff --git a/tests/ui/async-await/issues/auxiliary/issue_67893.rs b/tests/ui/async-await/issues/auxiliary/issue_67893.rs index 387966a5064fa..d5394469806da 100644 --- a/tests/ui/async-await/issues/auxiliary/issue_67893.rs +++ b/tests/ui/async-await/issues/auxiliary/issue_67893.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 use std::sync::{Arc, Mutex}; diff --git a/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.drop_tracking_mir.stderr b/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..8b75d95a68eed --- /dev/null +++ b/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.drop_tracking_mir.stderr @@ -0,0 +1,33 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-65436-raw-ptr-not-send.rs:16:17 + | +LL | assert_send(async { + | _________________^ +LL | | +LL | | +LL | | bar(Foo(std::ptr::null())).await; +LL | | }) + | |_____^ future created by async block is not `Send` + | + = help: within `[async block@$DIR/issue-65436-raw-ptr-not-send.rs:16:17: 20:6]`, the trait `Send` is not implemented for `*const u8` +note: future is not `Send` as this value is used across an await + --> $DIR/issue-65436-raw-ptr-not-send.rs:19:35 + | +LL | bar(Foo(std::ptr::null())).await; + | ---------------- ^^^^^^- `std::ptr::null()` is later dropped here + | | | + | | await occurs here, with `std::ptr::null()` maybe used later + | has type `*const u8` which is not `Send` +help: consider moving this into a `let` binding to create a shorter lived borrow + --> $DIR/issue-65436-raw-ptr-not-send.rs:19:13 + | +LL | bar(Foo(std::ptr::null())).await; + | ^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `assert_send` + --> $DIR/issue-65436-raw-ptr-not-send.rs:13:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to previous error + diff --git a/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.no_drop_tracking.stderr b/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.no_drop_tracking.stderr index 1033fa6cc8b34..8b75d95a68eed 100644 --- a/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.no_drop_tracking.stderr +++ b/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.no_drop_tracking.stderr @@ -4,13 +4,14 @@ error: future cannot be sent between threads safely LL | assert_send(async { | _________________^ LL | | +LL | | LL | | bar(Foo(std::ptr::null())).await; LL | | }) | |_____^ future created by async block is not `Send` | - = help: within `[async block@$DIR/issue-65436-raw-ptr-not-send.rs:16:17: 19:6]`, the trait `Send` is not implemented for `*const u8` + = help: within `[async block@$DIR/issue-65436-raw-ptr-not-send.rs:16:17: 20:6]`, the trait `Send` is not implemented for `*const u8` note: future is not `Send` as this value is used across an await - --> $DIR/issue-65436-raw-ptr-not-send.rs:18:35 + --> $DIR/issue-65436-raw-ptr-not-send.rs:19:35 | LL | bar(Foo(std::ptr::null())).await; | ---------------- ^^^^^^- `std::ptr::null()` is later dropped here @@ -18,7 +19,7 @@ LL | bar(Foo(std::ptr::null())).await; | | await occurs here, with `std::ptr::null()` maybe used later | has type `*const u8` which is not `Send` help: consider moving this into a `let` binding to create a shorter lived borrow - --> $DIR/issue-65436-raw-ptr-not-send.rs:18:13 + --> $DIR/issue-65436-raw-ptr-not-send.rs:19:13 | LL | bar(Foo(std::ptr::null())).await; | ^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.rs b/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.rs index 91edbc10dc0d7..630e0e4eebe16 100644 --- a/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.rs +++ b/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.rs @@ -1,8 +1,8 @@ // edition:2018 -// revisions: no_drop_tracking drop_tracking +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // [drop_tracking] check-pass -// [drop_tracking] compile-flags: -Zdrop-tracking=yes -// [no_drop_tracking] compile-flags: -Zdrop-tracking=no struct Foo(*const u8); @@ -15,6 +15,7 @@ fn assert_send(_: T) {} fn main() { assert_send(async { //[no_drop_tracking]~^ ERROR future cannot be sent between threads safely + //[drop_tracking_mir]~^^ ERROR future cannot be sent between threads safely bar(Foo(std::ptr::null())).await; }) } diff --git a/tests/ui/async-await/issues/issue-67611-static-mut-refs.rs b/tests/ui/async-await/issues/issue-67611-static-mut-refs.rs index dda4a151dd2d6..c4f8f607d2579 100644 --- a/tests/ui/async-await/issues/issue-67611-static-mut-refs.rs +++ b/tests/ui/async-await/issues/issue-67611-static-mut-refs.rs @@ -1,6 +1,10 @@ // build-pass // edition:2018 +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir + static mut A: [i32; 5] = [1, 2, 3, 4, 5]; fn is_send_sync(_: T) {} diff --git a/tests/ui/async-await/issues/issue-67893.stderr b/tests/ui/async-await/issues/issue-67893.stderr index 2ce68a782918c..ce9424c8b252b 100644 --- a/tests/ui/async-await/issues/issue-67893.stderr +++ b/tests/ui/async-await/issues/issue-67893.stderr @@ -6,7 +6,7 @@ LL | g(issue_67893::run()) | = help: within `impl Future`, the trait `Send` is not implemented for `MutexGuard<'_, ()>` note: future is not `Send` as this value is used across an await - --> $DIR/auxiliary/issue_67893.rs:9:26 + --> $DIR/auxiliary/issue_67893.rs:12:26 | LL | f(*x.lock().unwrap()).await; | ----------------- ^^^^^^- `x.lock().unwrap()` is later dropped here diff --git a/tests/ui/async-await/mutually-recursive-async-impl-trait-type.drop_tracking.stderr b/tests/ui/async-await/mutually-recursive-async-impl-trait-type.drop_tracking.stderr new file mode 100644 index 0000000000000..8a7317bb95a70 --- /dev/null +++ b/tests/ui/async-await/mutually-recursive-async-impl-trait-type.drop_tracking.stderr @@ -0,0 +1,21 @@ +error[E0733]: recursion in an `async fn` requires boxing + --> $DIR/mutually-recursive-async-impl-trait-type.rs:9:18 + | +LL | async fn rec_1() { + | ^ recursive `async fn` + | + = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` + = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion + +error[E0733]: recursion in an `async fn` requires boxing + --> $DIR/mutually-recursive-async-impl-trait-type.rs:13:18 + | +LL | async fn rec_2() { + | ^ recursive `async fn` + | + = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` + = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0733`. diff --git a/tests/ui/async-await/mutually-recursive-async-impl-trait-type.drop_tracking_mir.stderr b/tests/ui/async-await/mutually-recursive-async-impl-trait-type.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..8a7317bb95a70 --- /dev/null +++ b/tests/ui/async-await/mutually-recursive-async-impl-trait-type.drop_tracking_mir.stderr @@ -0,0 +1,21 @@ +error[E0733]: recursion in an `async fn` requires boxing + --> $DIR/mutually-recursive-async-impl-trait-type.rs:9:18 + | +LL | async fn rec_1() { + | ^ recursive `async fn` + | + = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` + = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion + +error[E0733]: recursion in an `async fn` requires boxing + --> $DIR/mutually-recursive-async-impl-trait-type.rs:13:18 + | +LL | async fn rec_2() { + | ^ recursive `async fn` + | + = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` + = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0733`. diff --git a/tests/ui/async-await/mutually-recursive-async-impl-trait-type.no_drop_tracking.stderr b/tests/ui/async-await/mutually-recursive-async-impl-trait-type.no_drop_tracking.stderr new file mode 100644 index 0000000000000..8a7317bb95a70 --- /dev/null +++ b/tests/ui/async-await/mutually-recursive-async-impl-trait-type.no_drop_tracking.stderr @@ -0,0 +1,21 @@ +error[E0733]: recursion in an `async fn` requires boxing + --> $DIR/mutually-recursive-async-impl-trait-type.rs:9:18 + | +LL | async fn rec_1() { + | ^ recursive `async fn` + | + = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` + = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion + +error[E0733]: recursion in an `async fn` requires boxing + --> $DIR/mutually-recursive-async-impl-trait-type.rs:13:18 + | +LL | async fn rec_2() { + | ^ recursive `async fn` + | + = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` + = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0733`. diff --git a/tests/ui/async-await/mutually-recursive-async-impl-trait-type.rs b/tests/ui/async-await/mutually-recursive-async-impl-trait-type.rs index bb2a61f03ce1f..a241f30e73e6e 100644 --- a/tests/ui/async-await/mutually-recursive-async-impl-trait-type.rs +++ b/tests/ui/async-await/mutually-recursive-async-impl-trait-type.rs @@ -1,3 +1,7 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir + // edition:2018 // Test that impl trait does not allow creating recursive types that are // otherwise forbidden when using `async` and `await`. diff --git a/tests/ui/async-await/mutually-recursive-async-impl-trait-type.stderr b/tests/ui/async-await/mutually-recursive-async-impl-trait-type.stderr index f789ad2a05c7d..8a7317bb95a70 100644 --- a/tests/ui/async-await/mutually-recursive-async-impl-trait-type.stderr +++ b/tests/ui/async-await/mutually-recursive-async-impl-trait-type.stderr @@ -1,5 +1,5 @@ error[E0733]: recursion in an `async fn` requires boxing - --> $DIR/mutually-recursive-async-impl-trait-type.rs:5:18 + --> $DIR/mutually-recursive-async-impl-trait-type.rs:9:18 | LL | async fn rec_1() { | ^ recursive `async fn` @@ -8,7 +8,7 @@ LL | async fn rec_1() { = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion error[E0733]: recursion in an `async fn` requires boxing - --> $DIR/mutually-recursive-async-impl-trait-type.rs:9:18 + --> $DIR/mutually-recursive-async-impl-trait-type.rs:13:18 | LL | async fn rec_2() { | ^ recursive `async fn` diff --git a/tests/ui/async-await/non-trivial-drop.rs b/tests/ui/async-await/non-trivial-drop.rs index a3167215dc32b..d4df9d439c5f1 100644 --- a/tests/ui/async-await/non-trivial-drop.rs +++ b/tests/ui/async-await/non-trivial-drop.rs @@ -1,6 +1,8 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // build-pass // edition:2018 -// compile-flags: -Zdrop-tracking=y #![feature(generators)] diff --git a/tests/ui/async-await/recursive-async-impl-trait-type.drop_tracking.stderr b/tests/ui/async-await/recursive-async-impl-trait-type.drop_tracking.stderr new file mode 100644 index 0000000000000..7e63a8da55255 --- /dev/null +++ b/tests/ui/async-await/recursive-async-impl-trait-type.drop_tracking.stderr @@ -0,0 +1,12 @@ +error[E0733]: recursion in an `async fn` requires boxing + --> $DIR/recursive-async-impl-trait-type.rs:8:40 + | +LL | async fn recursive_async_function() -> () { + | ^^ recursive `async fn` + | + = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` + = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0733`. diff --git a/tests/ui/async-await/recursive-async-impl-trait-type.drop_tracking_mir.stderr b/tests/ui/async-await/recursive-async-impl-trait-type.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..7e63a8da55255 --- /dev/null +++ b/tests/ui/async-await/recursive-async-impl-trait-type.drop_tracking_mir.stderr @@ -0,0 +1,12 @@ +error[E0733]: recursion in an `async fn` requires boxing + --> $DIR/recursive-async-impl-trait-type.rs:8:40 + | +LL | async fn recursive_async_function() -> () { + | ^^ recursive `async fn` + | + = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` + = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0733`. diff --git a/tests/ui/async-await/recursive-async-impl-trait-type.no_drop_tracking.stderr b/tests/ui/async-await/recursive-async-impl-trait-type.no_drop_tracking.stderr new file mode 100644 index 0000000000000..7e63a8da55255 --- /dev/null +++ b/tests/ui/async-await/recursive-async-impl-trait-type.no_drop_tracking.stderr @@ -0,0 +1,12 @@ +error[E0733]: recursion in an `async fn` requires boxing + --> $DIR/recursive-async-impl-trait-type.rs:8:40 + | +LL | async fn recursive_async_function() -> () { + | ^^ recursive `async fn` + | + = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` + = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0733`. diff --git a/tests/ui/async-await/recursive-async-impl-trait-type.rs b/tests/ui/async-await/recursive-async-impl-trait-type.rs index edc4cb8ac5df3..60b34d3a17415 100644 --- a/tests/ui/async-await/recursive-async-impl-trait-type.rs +++ b/tests/ui/async-await/recursive-async-impl-trait-type.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 // Test that impl trait does not allow creating recursive types that are // otherwise forbidden when using `async` and `await`. diff --git a/tests/ui/async-await/recursive-async-impl-trait-type.stderr b/tests/ui/async-await/recursive-async-impl-trait-type.stderr index 63f64f4455749..7e63a8da55255 100644 --- a/tests/ui/async-await/recursive-async-impl-trait-type.stderr +++ b/tests/ui/async-await/recursive-async-impl-trait-type.stderr @@ -1,5 +1,5 @@ error[E0733]: recursion in an `async fn` requires boxing - --> $DIR/recursive-async-impl-trait-type.rs:5:40 + --> $DIR/recursive-async-impl-trait-type.rs:8:40 | LL | async fn recursive_async_function() -> () { | ^^ recursive `async fn` diff --git a/tests/ui/async-await/unresolved_type_param.drop_tracking.stderr b/tests/ui/async-await/unresolved_type_param.drop_tracking.stderr new file mode 100644 index 0000000000000..64a31b5fc32dc --- /dev/null +++ b/tests/ui/async-await/unresolved_type_param.drop_tracking.stderr @@ -0,0 +1,39 @@ +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/unresolved_type_param.rs:13:5 + | +LL | bar().await; + | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/unresolved_type_param.rs:13:10 + | +LL | bar().await; + | ^^^^^^ + +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/unresolved_type_param.rs:13:5 + | +LL | bar().await; + | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/unresolved_type_param.rs:13:10 + | +LL | bar().await; + | ^^^^^^ + +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/unresolved_type_param.rs:13:5 + | +LL | bar().await; + | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/unresolved_type_param.rs:13:10 + | +LL | bar().await; + | ^^^^^^ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0698`. diff --git a/tests/ui/async-await/unresolved_type_param.drop_tracking_mir.stderr b/tests/ui/async-await/unresolved_type_param.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..64a31b5fc32dc --- /dev/null +++ b/tests/ui/async-await/unresolved_type_param.drop_tracking_mir.stderr @@ -0,0 +1,39 @@ +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/unresolved_type_param.rs:13:5 + | +LL | bar().await; + | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/unresolved_type_param.rs:13:10 + | +LL | bar().await; + | ^^^^^^ + +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/unresolved_type_param.rs:13:5 + | +LL | bar().await; + | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/unresolved_type_param.rs:13:10 + | +LL | bar().await; + | ^^^^^^ + +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/unresolved_type_param.rs:13:5 + | +LL | bar().await; + | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/unresolved_type_param.rs:13:10 + | +LL | bar().await; + | ^^^^^^ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0698`. diff --git a/tests/ui/async-await/unresolved_type_param.no_drop_tracking.stderr b/tests/ui/async-await/unresolved_type_param.no_drop_tracking.stderr new file mode 100644 index 0000000000000..64a31b5fc32dc --- /dev/null +++ b/tests/ui/async-await/unresolved_type_param.no_drop_tracking.stderr @@ -0,0 +1,39 @@ +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/unresolved_type_param.rs:13:5 + | +LL | bar().await; + | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/unresolved_type_param.rs:13:10 + | +LL | bar().await; + | ^^^^^^ + +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/unresolved_type_param.rs:13:5 + | +LL | bar().await; + | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/unresolved_type_param.rs:13:10 + | +LL | bar().await; + | ^^^^^^ + +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/unresolved_type_param.rs:13:5 + | +LL | bar().await; + | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/unresolved_type_param.rs:13:10 + | +LL | bar().await; + | ^^^^^^ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0698`. diff --git a/tests/ui/async-await/unresolved_type_param.rs b/tests/ui/async-await/unresolved_type_param.rs index 6d6d806149104..c9e77f0c3ea7a 100644 --- a/tests/ui/async-await/unresolved_type_param.rs +++ b/tests/ui/async-await/unresolved_type_param.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // Provoke an unresolved type error (T). // Error message should pinpoint the type parameter T as needing to be bound // (rather than give a general error message) diff --git a/tests/ui/async-await/unresolved_type_param.stderr b/tests/ui/async-await/unresolved_type_param.stderr index 7236c681f341c..64a31b5fc32dc 100644 --- a/tests/ui/async-await/unresolved_type_param.stderr +++ b/tests/ui/async-await/unresolved_type_param.stderr @@ -1,35 +1,35 @@ error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:10:5 + --> $DIR/unresolved_type_param.rs:13:5 | LL | bar().await; | ^^^ cannot infer type for type parameter `T` declared on the function `bar` | note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:10:10 + --> $DIR/unresolved_type_param.rs:13:10 | LL | bar().await; | ^^^^^^ error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:10:5 + --> $DIR/unresolved_type_param.rs:13:5 | LL | bar().await; | ^^^ cannot infer type for type parameter `T` declared on the function `bar` | note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:10:10 + --> $DIR/unresolved_type_param.rs:13:10 | LL | bar().await; | ^^^^^^ error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:10:5 + --> $DIR/unresolved_type_param.rs:13:5 | LL | bar().await; | ^^^ cannot infer type for type parameter `T` declared on the function `bar` | note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:10:10 + --> $DIR/unresolved_type_param.rs:13:10 | LL | bar().await; | ^^^^^^ diff --git a/tests/ui/generator/addassign-yield.rs b/tests/ui/generator/addassign-yield.rs index 66f22bf31fc40..7211367afeee6 100644 --- a/tests/ui/generator/addassign-yield.rs +++ b/tests/ui/generator/addassign-yield.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // run-pass // Regression test for broken MIR error (#61442) // Due to the two possible evaluation orders for diff --git a/tests/ui/generator/auto-trait-regions.drop_tracking.stderr b/tests/ui/generator/auto-trait-regions.drop_tracking.stderr new file mode 100644 index 0000000000000..165748d44305a --- /dev/null +++ b/tests/ui/generator/auto-trait-regions.drop_tracking.stderr @@ -0,0 +1,47 @@ +error[E0716]: temporary value dropped while borrowed + --> $DIR/auto-trait-regions.rs:48:24 + | +LL | let a = A(&mut true, &mut true, No); + | ^^^^ - temporary value is freed at the end of this statement + | | + | creates a temporary value which is freed while still in use +... +LL | assert_foo(a); + | - borrow later used here + | + = note: consider using a `let` binding to create a longer lived value + +error[E0716]: temporary value dropped while borrowed + --> $DIR/auto-trait-regions.rs:48:35 + | +LL | let a = A(&mut true, &mut true, No); + | ^^^^ - temporary value is freed at the end of this statement + | | + | creates a temporary value which is freed while still in use +... +LL | assert_foo(a); + | - borrow later used here + | + = note: consider using a `let` binding to create a longer lived value + +error: implementation of `Foo` is not general enough + --> $DIR/auto-trait-regions.rs:34:5 + | +LL | assert_foo(gen); + | ^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough + | + = note: `&'0 OnlyFooIfStaticRef` must implement `Foo`, for any lifetime `'0`... + = note: ...but `Foo` is actually implemented for the type `&'static OnlyFooIfStaticRef` + +error: implementation of `Foo` is not general enough + --> $DIR/auto-trait-regions.rs:54:5 + | +LL | assert_foo(gen); + | ^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough + | + = note: `Foo` would have to be implemented for the type `A<'0, '1>`, for any two lifetimes `'0` and `'1`... + = note: ...but `Foo` is actually implemented for the type `A<'_, '2>`, for some specific lifetime `'2` + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0716`. diff --git a/tests/ui/generator/auto-trait-regions.drop_tracking_mir.stderr b/tests/ui/generator/auto-trait-regions.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..165748d44305a --- /dev/null +++ b/tests/ui/generator/auto-trait-regions.drop_tracking_mir.stderr @@ -0,0 +1,47 @@ +error[E0716]: temporary value dropped while borrowed + --> $DIR/auto-trait-regions.rs:48:24 + | +LL | let a = A(&mut true, &mut true, No); + | ^^^^ - temporary value is freed at the end of this statement + | | + | creates a temporary value which is freed while still in use +... +LL | assert_foo(a); + | - borrow later used here + | + = note: consider using a `let` binding to create a longer lived value + +error[E0716]: temporary value dropped while borrowed + --> $DIR/auto-trait-regions.rs:48:35 + | +LL | let a = A(&mut true, &mut true, No); + | ^^^^ - temporary value is freed at the end of this statement + | | + | creates a temporary value which is freed while still in use +... +LL | assert_foo(a); + | - borrow later used here + | + = note: consider using a `let` binding to create a longer lived value + +error: implementation of `Foo` is not general enough + --> $DIR/auto-trait-regions.rs:34:5 + | +LL | assert_foo(gen); + | ^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough + | + = note: `&'0 OnlyFooIfStaticRef` must implement `Foo`, for any lifetime `'0`... + = note: ...but `Foo` is actually implemented for the type `&'static OnlyFooIfStaticRef` + +error: implementation of `Foo` is not general enough + --> $DIR/auto-trait-regions.rs:54:5 + | +LL | assert_foo(gen); + | ^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough + | + = note: `Foo` would have to be implemented for the type `A<'0, '1>`, for any two lifetimes `'0` and `'1`... + = note: ...but `Foo` is actually implemented for the type `A<'_, '2>`, for some specific lifetime `'2` + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0716`. diff --git a/tests/ui/generator/auto-trait-regions.no_drop_tracking.stderr b/tests/ui/generator/auto-trait-regions.no_drop_tracking.stderr new file mode 100644 index 0000000000000..165748d44305a --- /dev/null +++ b/tests/ui/generator/auto-trait-regions.no_drop_tracking.stderr @@ -0,0 +1,47 @@ +error[E0716]: temporary value dropped while borrowed + --> $DIR/auto-trait-regions.rs:48:24 + | +LL | let a = A(&mut true, &mut true, No); + | ^^^^ - temporary value is freed at the end of this statement + | | + | creates a temporary value which is freed while still in use +... +LL | assert_foo(a); + | - borrow later used here + | + = note: consider using a `let` binding to create a longer lived value + +error[E0716]: temporary value dropped while borrowed + --> $DIR/auto-trait-regions.rs:48:35 + | +LL | let a = A(&mut true, &mut true, No); + | ^^^^ - temporary value is freed at the end of this statement + | | + | creates a temporary value which is freed while still in use +... +LL | assert_foo(a); + | - borrow later used here + | + = note: consider using a `let` binding to create a longer lived value + +error: implementation of `Foo` is not general enough + --> $DIR/auto-trait-regions.rs:34:5 + | +LL | assert_foo(gen); + | ^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough + | + = note: `&'0 OnlyFooIfStaticRef` must implement `Foo`, for any lifetime `'0`... + = note: ...but `Foo` is actually implemented for the type `&'static OnlyFooIfStaticRef` + +error: implementation of `Foo` is not general enough + --> $DIR/auto-trait-regions.rs:54:5 + | +LL | assert_foo(gen); + | ^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough + | + = note: `Foo` would have to be implemented for the type `A<'0, '1>`, for any two lifetimes `'0` and `'1`... + = note: ...but `Foo` is actually implemented for the type `A<'_, '2>`, for some specific lifetime `'2` + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0716`. diff --git a/tests/ui/generator/auto-trait-regions.rs b/tests/ui/generator/auto-trait-regions.rs index ea4b0d554cde1..fd13e41319f01 100644 --- a/tests/ui/generator/auto-trait-regions.rs +++ b/tests/ui/generator/auto-trait-regions.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir #![feature(generators)] #![feature(auto_traits)] #![feature(negative_impls)] diff --git a/tests/ui/generator/auto-trait-regions.stderr b/tests/ui/generator/auto-trait-regions.stderr index 0b1f34aeb96bd..165748d44305a 100644 --- a/tests/ui/generator/auto-trait-regions.stderr +++ b/tests/ui/generator/auto-trait-regions.stderr @@ -1,5 +1,5 @@ error[E0716]: temporary value dropped while borrowed - --> $DIR/auto-trait-regions.rs:45:24 + --> $DIR/auto-trait-regions.rs:48:24 | LL | let a = A(&mut true, &mut true, No); | ^^^^ - temporary value is freed at the end of this statement @@ -12,7 +12,7 @@ LL | assert_foo(a); = note: consider using a `let` binding to create a longer lived value error[E0716]: temporary value dropped while borrowed - --> $DIR/auto-trait-regions.rs:45:35 + --> $DIR/auto-trait-regions.rs:48:35 | LL | let a = A(&mut true, &mut true, No); | ^^^^ - temporary value is freed at the end of this statement @@ -25,7 +25,7 @@ LL | assert_foo(a); = note: consider using a `let` binding to create a longer lived value error: implementation of `Foo` is not general enough - --> $DIR/auto-trait-regions.rs:31:5 + --> $DIR/auto-trait-regions.rs:34:5 | LL | assert_foo(gen); | ^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough @@ -34,7 +34,7 @@ LL | assert_foo(gen); = note: ...but `Foo` is actually implemented for the type `&'static OnlyFooIfStaticRef` error: implementation of `Foo` is not general enough - --> $DIR/auto-trait-regions.rs:51:5 + --> $DIR/auto-trait-regions.rs:54:5 | LL | assert_foo(gen); | ^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough diff --git a/tests/ui/generator/borrowing.drop_tracking.stderr b/tests/ui/generator/borrowing.drop_tracking.stderr new file mode 100644 index 0000000000000..96e3c327f8b31 --- /dev/null +++ b/tests/ui/generator/borrowing.drop_tracking.stderr @@ -0,0 +1,31 @@ +error[E0597]: `a` does not live long enough + --> $DIR/borrowing.rs:13:33 + | +LL | let _b = { + | -- borrow later stored here +LL | let a = 3; +LL | Pin::new(&mut || yield &a).resume(()) + | -- ^ borrowed value does not live long enough + | | + | value captured here by generator +LL | +LL | }; + | - `a` dropped here while still borrowed + +error[E0597]: `a` does not live long enough + --> $DIR/borrowing.rs:20:20 + | +LL | let _b = { + | -- borrow later stored here +LL | let a = 3; +LL | || { + | -- value captured here by generator +LL | yield &a + | ^ borrowed value does not live long enough +... +LL | }; + | - `a` dropped here while still borrowed + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0597`. diff --git a/tests/ui/generator/borrowing.drop_tracking_mir.stderr b/tests/ui/generator/borrowing.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..96e3c327f8b31 --- /dev/null +++ b/tests/ui/generator/borrowing.drop_tracking_mir.stderr @@ -0,0 +1,31 @@ +error[E0597]: `a` does not live long enough + --> $DIR/borrowing.rs:13:33 + | +LL | let _b = { + | -- borrow later stored here +LL | let a = 3; +LL | Pin::new(&mut || yield &a).resume(()) + | -- ^ borrowed value does not live long enough + | | + | value captured here by generator +LL | +LL | }; + | - `a` dropped here while still borrowed + +error[E0597]: `a` does not live long enough + --> $DIR/borrowing.rs:20:20 + | +LL | let _b = { + | -- borrow later stored here +LL | let a = 3; +LL | || { + | -- value captured here by generator +LL | yield &a + | ^ borrowed value does not live long enough +... +LL | }; + | - `a` dropped here while still borrowed + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0597`. diff --git a/tests/ui/generator/borrowing.no_drop_tracking.stderr b/tests/ui/generator/borrowing.no_drop_tracking.stderr new file mode 100644 index 0000000000000..96e3c327f8b31 --- /dev/null +++ b/tests/ui/generator/borrowing.no_drop_tracking.stderr @@ -0,0 +1,31 @@ +error[E0597]: `a` does not live long enough + --> $DIR/borrowing.rs:13:33 + | +LL | let _b = { + | -- borrow later stored here +LL | let a = 3; +LL | Pin::new(&mut || yield &a).resume(()) + | -- ^ borrowed value does not live long enough + | | + | value captured here by generator +LL | +LL | }; + | - `a` dropped here while still borrowed + +error[E0597]: `a` does not live long enough + --> $DIR/borrowing.rs:20:20 + | +LL | let _b = { + | -- borrow later stored here +LL | let a = 3; +LL | || { + | -- value captured here by generator +LL | yield &a + | ^ borrowed value does not live long enough +... +LL | }; + | - `a` dropped here while still borrowed + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0597`. diff --git a/tests/ui/generator/borrowing.rs b/tests/ui/generator/borrowing.rs index d36592583cdc5..29f39437f8f55 100644 --- a/tests/ui/generator/borrowing.rs +++ b/tests/ui/generator/borrowing.rs @@ -1,3 +1,7 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir + #![feature(generators, generator_trait)] use std::ops::Generator; diff --git a/tests/ui/generator/borrowing.stderr b/tests/ui/generator/borrowing.stderr index 38e1ace8c4efb..96e3c327f8b31 100644 --- a/tests/ui/generator/borrowing.stderr +++ b/tests/ui/generator/borrowing.stderr @@ -1,5 +1,5 @@ error[E0597]: `a` does not live long enough - --> $DIR/borrowing.rs:9:33 + --> $DIR/borrowing.rs:13:33 | LL | let _b = { | -- borrow later stored here @@ -13,7 +13,7 @@ LL | }; | - `a` dropped here while still borrowed error[E0597]: `a` does not live long enough - --> $DIR/borrowing.rs:16:20 + --> $DIR/borrowing.rs:20:20 | LL | let _b = { | -- borrow later stored here diff --git a/tests/ui/generator/drop-tracking-parent-expression.stderr b/tests/ui/generator/drop-tracking-parent-expression.drop_tracking.stderr similarity index 88% rename from tests/ui/generator/drop-tracking-parent-expression.stderr rename to tests/ui/generator/drop-tracking-parent-expression.drop_tracking.stderr index fbf5d6e07256b..c07906ec37d30 100644 --- a/tests/ui/generator/drop-tracking-parent-expression.stderr +++ b/tests/ui/generator/drop-tracking-parent-expression.drop_tracking.stderr @@ -1,5 +1,5 @@ error: generator cannot be sent between threads safely - --> $DIR/drop-tracking-parent-expression.rs:24:25 + --> $DIR/drop-tracking-parent-expression.rs:27:25 | LL | assert_send(g); | ^ generator is not `Send` @@ -13,9 +13,9 @@ LL | | }; LL | | ); | |_____- in this macro invocation | - = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:18:21: 18:28]`, the trait `Send` is not implemented for `derived_drop::Client` + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `derived_drop::Client` note: generator is not `Send` as this value is used across a yield - --> $DIR/drop-tracking-parent-expression.rs:22:22 + --> $DIR/drop-tracking-parent-expression.rs:25:22 | LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { | ------------------------ has type `derived_drop::Client` which is not `Send` @@ -34,14 +34,14 @@ LL | | }; LL | | ); | |_____- in this macro invocation note: required by a bound in `assert_send` - --> $DIR/drop-tracking-parent-expression.rs:41:19 + --> $DIR/drop-tracking-parent-expression.rs:49:19 | LL | fn assert_send(_thing: T) {} | ^^^^ required by this bound in `assert_send` = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) error: generator cannot be sent between threads safely - --> $DIR/drop-tracking-parent-expression.rs:24:25 + --> $DIR/drop-tracking-parent-expression.rs:27:25 | LL | assert_send(g); | ^ generator is not `Send` @@ -55,9 +55,9 @@ LL | | }; LL | | ); | |_____- in this macro invocation | - = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:18:21: 18:28]`, the trait `Send` is not implemented for `significant_drop::Client` + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `significant_drop::Client` note: generator is not `Send` as this value is used across a yield - --> $DIR/drop-tracking-parent-expression.rs:22:22 + --> $DIR/drop-tracking-parent-expression.rs:25:22 | LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { | ------------------------ has type `significant_drop::Client` which is not `Send` @@ -76,14 +76,14 @@ LL | | }; LL | | ); | |_____- in this macro invocation note: required by a bound in `assert_send` - --> $DIR/drop-tracking-parent-expression.rs:41:19 + --> $DIR/drop-tracking-parent-expression.rs:49:19 | LL | fn assert_send(_thing: T) {} | ^^^^ required by this bound in `assert_send` = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) error: generator cannot be sent between threads safely - --> $DIR/drop-tracking-parent-expression.rs:24:25 + --> $DIR/drop-tracking-parent-expression.rs:27:25 | LL | assert_send(g); | ^ generator is not `Send` @@ -97,9 +97,9 @@ LL | | }; LL | | ); | |_____- in this macro invocation | - = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:18:21: 18:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` note: generator is not `Send` as this value is used across a yield - --> $DIR/drop-tracking-parent-expression.rs:22:22 + --> $DIR/drop-tracking-parent-expression.rs:25:22 | LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { | ------------------------ has type `insignificant_dtor::Client` which is not `Send` @@ -118,7 +118,7 @@ LL | | }; LL | | ); | |_____- in this macro invocation note: required by a bound in `assert_send` - --> $DIR/drop-tracking-parent-expression.rs:41:19 + --> $DIR/drop-tracking-parent-expression.rs:49:19 | LL | fn assert_send(_thing: T) {} | ^^^^ required by this bound in `assert_send` diff --git a/tests/ui/generator/drop-tracking-parent-expression.drop_tracking_mir.stderr b/tests/ui/generator/drop-tracking-parent-expression.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..1a05bfe4f0e6a --- /dev/null +++ b/tests/ui/generator/drop-tracking-parent-expression.drop_tracking_mir.stderr @@ -0,0 +1,334 @@ +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `copy::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `copy::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `copy::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `copy::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `derived_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `derived_drop::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `derived_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `derived_drop::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `significant_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `significant_drop::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `significant_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `significant_drop::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `insignificant_dtor::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `insignificant_dtor::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 8 previous errors + diff --git a/tests/ui/generator/drop-tracking-parent-expression.no_drop_tracking.stderr b/tests/ui/generator/drop-tracking-parent-expression.no_drop_tracking.stderr new file mode 100644 index 0000000000000..1a05bfe4f0e6a --- /dev/null +++ b/tests/ui/generator/drop-tracking-parent-expression.no_drop_tracking.stderr @@ -0,0 +1,334 @@ +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `copy::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `copy::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `copy::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `copy::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `derived_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `derived_drop::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `derived_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `derived_drop::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `significant_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `significant_drop::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `significant_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `significant_drop::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `insignificant_dtor::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/drop-tracking-parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/drop-tracking-parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `insignificant_dtor::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/drop-tracking-parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 8 previous errors + diff --git a/tests/ui/generator/drop-tracking-parent-expression.rs b/tests/ui/generator/drop-tracking-parent-expression.rs index d40f1b8f64d4a..61e81330b0920 100644 --- a/tests/ui/generator/drop-tracking-parent-expression.rs +++ b/tests/ui/generator/drop-tracking-parent-expression.rs @@ -1,4 +1,7 @@ -// compile-flags: -Zdrop-tracking +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir + #![feature(generators, negative_impls, rustc_attrs)] macro_rules! type_combinations { @@ -25,6 +28,7 @@ macro_rules! type_combinations { //~^ ERROR cannot be sent between threads //~| ERROR cannot be sent between threads //~| ERROR cannot be sent between threads + //[no_drop_tracking,drop_tracking_mir]~^^^^ ERROR cannot be sent between threads } // Simple owned value. This works because the Client is considered moved into `drop`, @@ -34,6 +38,10 @@ macro_rules! type_combinations { _ => yield, }; assert_send(g); + //[no_drop_tracking,drop_tracking_mir]~^ ERROR cannot be sent between threads + //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads + //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads + //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads } )* } } diff --git a/tests/ui/generator/drop-tracking-yielding-in-match-guards.rs b/tests/ui/generator/drop-tracking-yielding-in-match-guards.rs index 646365e435901..cbc291701cbc9 100644 --- a/tests/ui/generator/drop-tracking-yielding-in-match-guards.rs +++ b/tests/ui/generator/drop-tracking-yielding-in-match-guards.rs @@ -1,6 +1,8 @@ // build-pass // edition:2018 -// compile-flags: -Zdrop-tracking +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir #![feature(generators)] diff --git a/tests/ui/generator/issue-57017.drop_tracking_mir.stderr b/tests/ui/generator/issue-57017.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..4bba20bbae006 --- /dev/null +++ b/tests/ui/generator/issue-57017.drop_tracking_mir.stderr @@ -0,0 +1,248 @@ +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:30:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: the trait `Sync` is not implemented for `copy::unsync::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:28:28 + | +LL | let g = move || match drop(&$name::unsync::Client::default()) { + | --------------------------------- has type `©::unsync::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `&$name::unsync::Client::default()` maybe used later +LL | }; + | - `&$name::unsync::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:42:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `copy::unsend::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:40:28 + | +LL | let g = move || match drop($name::unsend::Client::default()) { + | -------------------------------- has type `copy::unsend::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `$name::unsend::Client::default()` maybe used later +LL | }; + | - `$name::unsend::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:30:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: the trait `Sync` is not implemented for `derived_drop::unsync::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:28:28 + | +LL | let g = move || match drop(&$name::unsync::Client::default()) { + | --------------------------------- has type `&derived_drop::unsync::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `&$name::unsync::Client::default()` maybe used later +LL | }; + | - `&$name::unsync::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:42:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `derived_drop::unsend::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:40:28 + | +LL | let g = move || match drop($name::unsend::Client::default()) { + | -------------------------------- has type `derived_drop::unsend::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `$name::unsend::Client::default()` maybe used later +LL | }; + | - `$name::unsend::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:30:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: the trait `Sync` is not implemented for `significant_drop::unsync::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:28:28 + | +LL | let g = move || match drop(&$name::unsync::Client::default()) { + | --------------------------------- has type `&significant_drop::unsync::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `&$name::unsync::Client::default()` maybe used later +LL | }; + | - `&$name::unsync::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:42:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `significant_drop::unsend::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:40:28 + | +LL | let g = move || match drop($name::unsend::Client::default()) { + | -------------------------------- has type `significant_drop::unsend::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `$name::unsend::Client::default()` maybe used later +LL | }; + | - `$name::unsend::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 6 previous errors + diff --git a/tests/ui/generator/issue-57017.no_drop_tracking.stderr b/tests/ui/generator/issue-57017.no_drop_tracking.stderr new file mode 100644 index 0000000000000..4bba20bbae006 --- /dev/null +++ b/tests/ui/generator/issue-57017.no_drop_tracking.stderr @@ -0,0 +1,248 @@ +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:30:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: the trait `Sync` is not implemented for `copy::unsync::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:28:28 + | +LL | let g = move || match drop(&$name::unsync::Client::default()) { + | --------------------------------- has type `©::unsync::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `&$name::unsync::Client::default()` maybe used later +LL | }; + | - `&$name::unsync::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:42:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `copy::unsend::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:40:28 + | +LL | let g = move || match drop($name::unsend::Client::default()) { + | -------------------------------- has type `copy::unsend::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `$name::unsend::Client::default()` maybe used later +LL | }; + | - `$name::unsend::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:30:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: the trait `Sync` is not implemented for `derived_drop::unsync::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:28:28 + | +LL | let g = move || match drop(&$name::unsync::Client::default()) { + | --------------------------------- has type `&derived_drop::unsync::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `&$name::unsync::Client::default()` maybe used later +LL | }; + | - `&$name::unsync::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:42:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `derived_drop::unsend::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:40:28 + | +LL | let g = move || match drop($name::unsend::Client::default()) { + | -------------------------------- has type `derived_drop::unsend::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `$name::unsend::Client::default()` maybe used later +LL | }; + | - `$name::unsend::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:30:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: the trait `Sync` is not implemented for `significant_drop::unsync::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:28:28 + | +LL | let g = move || match drop(&$name::unsync::Client::default()) { + | --------------------------------- has type `&significant_drop::unsync::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `&$name::unsync::Client::default()` maybe used later +LL | }; + | - `&$name::unsync::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/issue-57017.rs:42:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `significant_drop::unsend::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57017.rs:40:28 + | +LL | let g = move || match drop($name::unsend::Client::default()) { + | -------------------------------- has type `significant_drop::unsend::Client` which is not `Send` +LL | _status => yield, + | ^^^^^ yield occurs here, with `$name::unsend::Client::default()` maybe used later +LL | }; + | - `$name::unsend::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; +LL | | significant_drop => { +... | +LL | | } +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/issue-57017.rs:50:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 6 previous errors + diff --git a/tests/ui/generator/issue-57017.rs b/tests/ui/generator/issue-57017.rs index c0bde3b4473e1..bcd6d22678858 100644 --- a/tests/ui/generator/issue-57017.rs +++ b/tests/ui/generator/issue-57017.rs @@ -1,5 +1,8 @@ -// build-pass -// compile-flags: -Zdrop-tracking +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir +// [drop_tracking] build-pass + #![feature(generators, negative_impls)] macro_rules! type_combinations { @@ -25,6 +28,9 @@ macro_rules! type_combinations { _status => yield, }; assert_send(g); + //[no_drop_tracking,drop_tracking_mir]~^ ERROR generator cannot be sent between threads safely + //[no_drop_tracking,drop_tracking_mir]~| ERROR generator cannot be sent between threads safely + //[no_drop_tracking,drop_tracking_mir]~| ERROR generator cannot be sent between threads safely } // This tests that `Client` is properly considered to be dropped after moving it into the @@ -34,6 +40,9 @@ macro_rules! type_combinations { _status => yield, }; assert_send(g); + //[no_drop_tracking,drop_tracking_mir]~^ ERROR generator cannot be sent between threads safely + //[no_drop_tracking,drop_tracking_mir]~| ERROR generator cannot be sent between threads safely + //[no_drop_tracking,drop_tracking_mir]~| ERROR generator cannot be sent between threads safely } )* } } diff --git a/tests/ui/generator/issue-57478.drop_tracking_mir.stderr b/tests/ui/generator/issue-57478.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..a253cafe24d0d --- /dev/null +++ b/tests/ui/generator/issue-57478.drop_tracking_mir.stderr @@ -0,0 +1,32 @@ +error: generator cannot be sent between threads safely + --> $DIR/issue-57478.rs:12:17 + | +LL | assert_send(|| { + | _________________^ +LL | | +LL | | +LL | | let guard = Foo; +LL | | drop(guard); +LL | | yield; +LL | | }) + | |_____^ generator is not `Send` + | + = help: within `[generator@$DIR/issue-57478.rs:12:17: 12:19]`, the trait `Send` is not implemented for `Foo` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57478.rs:17:9 + | +LL | let guard = Foo; + | ----- has type `Foo` which is not `Send` +LL | drop(guard); +LL | yield; + | ^^^^^ yield occurs here, with `guard` maybe used later +LL | }) + | - `guard` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/issue-57478.rs:21:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to previous error + diff --git a/tests/ui/generator/issue-57478.no_drop_tracking.stderr b/tests/ui/generator/issue-57478.no_drop_tracking.stderr new file mode 100644 index 0000000000000..a253cafe24d0d --- /dev/null +++ b/tests/ui/generator/issue-57478.no_drop_tracking.stderr @@ -0,0 +1,32 @@ +error: generator cannot be sent between threads safely + --> $DIR/issue-57478.rs:12:17 + | +LL | assert_send(|| { + | _________________^ +LL | | +LL | | +LL | | let guard = Foo; +LL | | drop(guard); +LL | | yield; +LL | | }) + | |_____^ generator is not `Send` + | + = help: within `[generator@$DIR/issue-57478.rs:12:17: 12:19]`, the trait `Send` is not implemented for `Foo` +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-57478.rs:17:9 + | +LL | let guard = Foo; + | ----- has type `Foo` which is not `Send` +LL | drop(guard); +LL | yield; + | ^^^^^ yield occurs here, with `guard` maybe used later +LL | }) + | - `guard` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/issue-57478.rs:21:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to previous error + diff --git a/tests/ui/generator/issue-57478.rs b/tests/ui/generator/issue-57478.rs index 91407ea1844f5..cf5350ecbb996 100644 --- a/tests/ui/generator/issue-57478.rs +++ b/tests/ui/generator/issue-57478.rs @@ -1,5 +1,7 @@ -// check-pass -// compile-flags: -Zdrop-tracking +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir +// [drop_tracking] check-pass #![feature(negative_impls, generators)] @@ -8,6 +10,8 @@ impl !Send for Foo {} fn main() { assert_send(|| { + //[no_drop_tracking]~^ ERROR generator cannot be sent between threads safely + //[drop_tracking_mir]~^^ ERROR generator cannot be sent between threads safely let guard = Foo; drop(guard); yield; diff --git a/tests/ui/generator/issue-68112.stderr b/tests/ui/generator/issue-68112.drop_tracking.stderr similarity index 89% rename from tests/ui/generator/issue-68112.stderr rename to tests/ui/generator/issue-68112.drop_tracking.stderr index b42bc93d01f66..282eac1b686ef 100644 --- a/tests/ui/generator/issue-68112.stderr +++ b/tests/ui/generator/issue-68112.drop_tracking.stderr @@ -1,5 +1,5 @@ error: generator cannot be sent between threads safely - --> $DIR/issue-68112.rs:40:18 + --> $DIR/issue-68112.rs:43:18 | LL | require_send(send_gen); | ^^^^^^^^ generator is not `Send` @@ -7,7 +7,7 @@ LL | require_send(send_gen); = help: the trait `Sync` is not implemented for `RefCell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-68112.rs:36:9 + --> $DIR/issue-68112.rs:39:9 | LL | let _non_send_gen = make_non_send_generator(); | ------------- has type `impl Generator>>` which is not `Send` @@ -18,13 +18,13 @@ LL | yield; LL | }; | - `_non_send_gen` is later dropped here note: required by a bound in `require_send` - --> $DIR/issue-68112.rs:22:25 + --> $DIR/issue-68112.rs:25:25 | LL | fn require_send(_: impl Send) {} | ^^^^ required by this bound in `require_send` error[E0277]: `RefCell` cannot be shared between threads safely - --> $DIR/issue-68112.rs:64:18 + --> $DIR/issue-68112.rs:67:18 | LL | require_send(send_gen); | ------------ ^^^^^^^^ `RefCell` cannot be shared between threads safely @@ -35,28 +35,28 @@ LL | require_send(send_gen); = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead = note: required for `Arc>` to implement `Send` note: required because it's used within this generator - --> $DIR/issue-68112.rs:49:5 + --> $DIR/issue-68112.rs:52:5 | LL | || { | ^^ note: required because it appears within the type `impl Generator>>` - --> $DIR/issue-68112.rs:46:30 + --> $DIR/issue-68112.rs:49:30 | LL | pub fn make_gen2(t: T) -> impl Generator { | ^^^^^^^^^^^^^^^^^^^^^^^^^^ note: required because it appears within the type `impl Generator>>` - --> $DIR/issue-68112.rs:54:34 + --> $DIR/issue-68112.rs:57:34 | LL | fn make_non_send_generator2() -> impl Generator>> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required because it captures the following types: `impl Generator>>`, `()` note: required because it's used within this generator - --> $DIR/issue-68112.rs:60:20 + --> $DIR/issue-68112.rs:63:20 | LL | let send_gen = || { | ^^ note: required by a bound in `require_send` - --> $DIR/issue-68112.rs:22:25 + --> $DIR/issue-68112.rs:25:25 | LL | fn require_send(_: impl Send) {} | ^^^^ required by this bound in `require_send` diff --git a/tests/ui/generator/issue-68112.drop_tracking_mir.stderr b/tests/ui/generator/issue-68112.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..282eac1b686ef --- /dev/null +++ b/tests/ui/generator/issue-68112.drop_tracking_mir.stderr @@ -0,0 +1,66 @@ +error: generator cannot be sent between threads safely + --> $DIR/issue-68112.rs:43:18 + | +LL | require_send(send_gen); + | ^^^^^^^^ generator is not `Send` + | + = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-68112.rs:39:9 + | +LL | let _non_send_gen = make_non_send_generator(); + | ------------- has type `impl Generator>>` which is not `Send` +LL | +LL | yield; + | ^^^^^ yield occurs here, with `_non_send_gen` maybe used later +... +LL | }; + | - `_non_send_gen` is later dropped here +note: required by a bound in `require_send` + --> $DIR/issue-68112.rs:25:25 + | +LL | fn require_send(_: impl Send) {} + | ^^^^ required by this bound in `require_send` + +error[E0277]: `RefCell` cannot be shared between threads safely + --> $DIR/issue-68112.rs:67:18 + | +LL | require_send(send_gen); + | ------------ ^^^^^^^^ `RefCell` cannot be shared between threads safely + | | + | required by a bound introduced by this call + | + = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead + = note: required for `Arc>` to implement `Send` +note: required because it's used within this generator + --> $DIR/issue-68112.rs:52:5 + | +LL | || { + | ^^ +note: required because it appears within the type `impl Generator>>` + --> $DIR/issue-68112.rs:49:30 + | +LL | pub fn make_gen2(t: T) -> impl Generator { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required because it appears within the type `impl Generator>>` + --> $DIR/issue-68112.rs:57:34 + | +LL | fn make_non_send_generator2() -> impl Generator>> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required because it captures the following types: `impl Generator>>`, `()` +note: required because it's used within this generator + --> $DIR/issue-68112.rs:63:20 + | +LL | let send_gen = || { + | ^^ +note: required by a bound in `require_send` + --> $DIR/issue-68112.rs:25:25 + | +LL | fn require_send(_: impl Send) {} + | ^^^^ required by this bound in `require_send` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/issue-68112.no_drop_tracking.stderr b/tests/ui/generator/issue-68112.no_drop_tracking.stderr new file mode 100644 index 0000000000000..282eac1b686ef --- /dev/null +++ b/tests/ui/generator/issue-68112.no_drop_tracking.stderr @@ -0,0 +1,66 @@ +error: generator cannot be sent between threads safely + --> $DIR/issue-68112.rs:43:18 + | +LL | require_send(send_gen); + | ^^^^^^^^ generator is not `Send` + | + = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead +note: generator is not `Send` as this value is used across a yield + --> $DIR/issue-68112.rs:39:9 + | +LL | let _non_send_gen = make_non_send_generator(); + | ------------- has type `impl Generator>>` which is not `Send` +LL | +LL | yield; + | ^^^^^ yield occurs here, with `_non_send_gen` maybe used later +... +LL | }; + | - `_non_send_gen` is later dropped here +note: required by a bound in `require_send` + --> $DIR/issue-68112.rs:25:25 + | +LL | fn require_send(_: impl Send) {} + | ^^^^ required by this bound in `require_send` + +error[E0277]: `RefCell` cannot be shared between threads safely + --> $DIR/issue-68112.rs:67:18 + | +LL | require_send(send_gen); + | ------------ ^^^^^^^^ `RefCell` cannot be shared between threads safely + | | + | required by a bound introduced by this call + | + = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead + = note: required for `Arc>` to implement `Send` +note: required because it's used within this generator + --> $DIR/issue-68112.rs:52:5 + | +LL | || { + | ^^ +note: required because it appears within the type `impl Generator>>` + --> $DIR/issue-68112.rs:49:30 + | +LL | pub fn make_gen2(t: T) -> impl Generator { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required because it appears within the type `impl Generator>>` + --> $DIR/issue-68112.rs:57:34 + | +LL | fn make_non_send_generator2() -> impl Generator>> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required because it captures the following types: `impl Generator>>`, `()` +note: required because it's used within this generator + --> $DIR/issue-68112.rs:63:20 + | +LL | let send_gen = || { + | ^^ +note: required by a bound in `require_send` + --> $DIR/issue-68112.rs:25:25 + | +LL | fn require_send(_: impl Send) {} + | ^^^^ required by this bound in `require_send` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/issue-68112.rs b/tests/ui/generator/issue-68112.rs index 9def544e3d25c..c3fe09be57fb1 100644 --- a/tests/ui/generator/issue-68112.rs +++ b/tests/ui/generator/issue-68112.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir #![feature(generators, generator_trait)] use std::{ diff --git a/tests/ui/generator/issue-93161.rs b/tests/ui/generator/issue-93161.rs index 92305609c835c..8d3f7c62f3936 100644 --- a/tests/ui/generator/issue-93161.rs +++ b/tests/ui/generator/issue-93161.rs @@ -1,6 +1,8 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2021 // run-pass -// compile-flags: -Zdrop-tracking #![feature(never_type)] diff --git a/tests/ui/generator/not-send-sync.stderr b/tests/ui/generator/not-send-sync.drop_tracking.stderr similarity index 84% rename from tests/ui/generator/not-send-sync.stderr rename to tests/ui/generator/not-send-sync.drop_tracking.stderr index 1711df729b8c0..a15ee4044745c 100644 --- a/tests/ui/generator/not-send-sync.stderr +++ b/tests/ui/generator/not-send-sync.drop_tracking.stderr @@ -1,5 +1,5 @@ error[E0277]: `Cell` cannot be shared between threads safely - --> $DIR/not-send-sync.rs:16:17 + --> $DIR/not-send-sync.rs:19:17 | LL | assert_send(|| { | _____-----------_^ @@ -15,18 +15,18 @@ LL | | }); = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead = note: required for `&Cell` to implement `Send` note: required because it's used within this generator - --> $DIR/not-send-sync.rs:16:17 + --> $DIR/not-send-sync.rs:19:17 | LL | assert_send(|| { | ^^ note: required by a bound in `assert_send` - --> $DIR/not-send-sync.rs:7:23 + --> $DIR/not-send-sync.rs:10:23 | LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` error: generator cannot be shared between threads safely - --> $DIR/not-send-sync.rs:9:17 + --> $DIR/not-send-sync.rs:12:17 | LL | assert_sync(|| { | _________________^ @@ -36,10 +36,10 @@ LL | | yield; LL | | }); | |_____^ generator is not `Sync` | - = help: within `[generator@$DIR/not-send-sync.rs:9:17: 9:19]`, the trait `Sync` is not implemented for `Cell` + = help: within `[generator@$DIR/not-send-sync.rs:12:17: 12:19]`, the trait `Sync` is not implemented for `Cell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead note: generator is not `Sync` as this value is used across a yield - --> $DIR/not-send-sync.rs:12:9 + --> $DIR/not-send-sync.rs:15:9 | LL | let a = Cell::new(2); | - has type `Cell` which is not `Sync` @@ -48,7 +48,7 @@ LL | yield; LL | }); | - `a` is later dropped here note: required by a bound in `assert_sync` - --> $DIR/not-send-sync.rs:6:23 + --> $DIR/not-send-sync.rs:9:23 | LL | fn assert_sync(_: T) {} | ^^^^ required by this bound in `assert_sync` diff --git a/tests/ui/generator/not-send-sync.drop_tracking_mir.stderr b/tests/ui/generator/not-send-sync.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..a15ee4044745c --- /dev/null +++ b/tests/ui/generator/not-send-sync.drop_tracking_mir.stderr @@ -0,0 +1,58 @@ +error[E0277]: `Cell` cannot be shared between threads safely + --> $DIR/not-send-sync.rs:19:17 + | +LL | assert_send(|| { + | _____-----------_^ + | | | + | | required by a bound introduced by this call +LL | | +LL | | drop(&a); +LL | | yield; +LL | | }); + | |_____^ `Cell` cannot be shared between threads safely + | + = help: the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead + = note: required for `&Cell` to implement `Send` +note: required because it's used within this generator + --> $DIR/not-send-sync.rs:19:17 + | +LL | assert_send(|| { + | ^^ +note: required by a bound in `assert_send` + --> $DIR/not-send-sync.rs:10:23 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: generator cannot be shared between threads safely + --> $DIR/not-send-sync.rs:12:17 + | +LL | assert_sync(|| { + | _________________^ +LL | | +LL | | let a = Cell::new(2); +LL | | yield; +LL | | }); + | |_____^ generator is not `Sync` + | + = help: within `[generator@$DIR/not-send-sync.rs:12:17: 12:19]`, the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead +note: generator is not `Sync` as this value is used across a yield + --> $DIR/not-send-sync.rs:15:9 + | +LL | let a = Cell::new(2); + | - has type `Cell` which is not `Sync` +LL | yield; + | ^^^^^ yield occurs here, with `a` maybe used later +LL | }); + | - `a` is later dropped here +note: required by a bound in `assert_sync` + --> $DIR/not-send-sync.rs:9:23 + | +LL | fn assert_sync(_: T) {} + | ^^^^ required by this bound in `assert_sync` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/not-send-sync.no_drop_tracking.stderr b/tests/ui/generator/not-send-sync.no_drop_tracking.stderr new file mode 100644 index 0000000000000..a15ee4044745c --- /dev/null +++ b/tests/ui/generator/not-send-sync.no_drop_tracking.stderr @@ -0,0 +1,58 @@ +error[E0277]: `Cell` cannot be shared between threads safely + --> $DIR/not-send-sync.rs:19:17 + | +LL | assert_send(|| { + | _____-----------_^ + | | | + | | required by a bound introduced by this call +LL | | +LL | | drop(&a); +LL | | yield; +LL | | }); + | |_____^ `Cell` cannot be shared between threads safely + | + = help: the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead + = note: required for `&Cell` to implement `Send` +note: required because it's used within this generator + --> $DIR/not-send-sync.rs:19:17 + | +LL | assert_send(|| { + | ^^ +note: required by a bound in `assert_send` + --> $DIR/not-send-sync.rs:10:23 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: generator cannot be shared between threads safely + --> $DIR/not-send-sync.rs:12:17 + | +LL | assert_sync(|| { + | _________________^ +LL | | +LL | | let a = Cell::new(2); +LL | | yield; +LL | | }); + | |_____^ generator is not `Sync` + | + = help: within `[generator@$DIR/not-send-sync.rs:12:17: 12:19]`, the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead +note: generator is not `Sync` as this value is used across a yield + --> $DIR/not-send-sync.rs:15:9 + | +LL | let a = Cell::new(2); + | - has type `Cell` which is not `Sync` +LL | yield; + | ^^^^^ yield occurs here, with `a` maybe used later +LL | }); + | - `a` is later dropped here +note: required by a bound in `assert_sync` + --> $DIR/not-send-sync.rs:9:23 + | +LL | fn assert_sync(_: T) {} + | ^^^^ required by this bound in `assert_sync` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/not-send-sync.rs b/tests/ui/generator/not-send-sync.rs index 8ca5565fb2ab5..aadb2935701c7 100644 --- a/tests/ui/generator/not-send-sync.rs +++ b/tests/ui/generator/not-send-sync.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir #![feature(generators)] use std::cell::Cell; diff --git a/tests/ui/generator/parent-expression.drop_tracking.stderr b/tests/ui/generator/parent-expression.drop_tracking.stderr new file mode 100644 index 0000000000000..ef489088bf853 --- /dev/null +++ b/tests/ui/generator/parent-expression.drop_tracking.stderr @@ -0,0 +1,128 @@ +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `derived_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `derived_drop::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `significant_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `significant_drop::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `insignificant_dtor::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 3 previous errors + diff --git a/tests/ui/generator/parent-expression.drop_tracking_mir.stderr b/tests/ui/generator/parent-expression.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..2e1313a800487 --- /dev/null +++ b/tests/ui/generator/parent-expression.drop_tracking_mir.stderr @@ -0,0 +1,334 @@ +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `copy::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `copy::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `copy::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `copy::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `derived_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `derived_drop::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `derived_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `derived_drop::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `significant_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `significant_drop::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `significant_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `significant_drop::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `insignificant_dtor::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `insignificant_dtor::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 8 previous errors + diff --git a/tests/ui/generator/parent-expression.no_drop_tracking.stderr b/tests/ui/generator/parent-expression.no_drop_tracking.stderr new file mode 100644 index 0000000000000..2e1313a800487 --- /dev/null +++ b/tests/ui/generator/parent-expression.no_drop_tracking.stderr @@ -0,0 +1,334 @@ +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `copy::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `copy::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `copy::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `copy::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `derived_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `derived_drop::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `derived_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `derived_drop::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `significant_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `significant_drop::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `significant_drop::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `significant_drop::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:27:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:25:22 + | +LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { + | ------------------------ has type `insignificant_dtor::Client` which is not `Send` +... +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: generator cannot be sent between threads safely + --> $DIR/parent-expression.rs:40:25 + | +LL | assert_send(g); + | ^ generator is not `Send` +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation + | + = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` +note: generator is not `Send` as this value is used across a yield + --> $DIR/parent-expression.rs:38:22 + | +LL | let g = move || match drop($name::Client::default()) { + | ------------------------ has type `insignificant_dtor::Client` which is not `Send` +LL | _ => yield, + | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later +LL | }; + | - `$name::Client::default()` is later dropped here +... +LL | / type_combinations!( +LL | | // OK +LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; +LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though +... | +LL | | }; +LL | | ); + | |_____- in this macro invocation +note: required by a bound in `assert_send` + --> $DIR/parent-expression.rs:49:19 + | +LL | fn assert_send(_thing: T) {} + | ^^^^ required by this bound in `assert_send` + = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 8 previous errors + diff --git a/tests/ui/generator/parent-expression.rs b/tests/ui/generator/parent-expression.rs new file mode 100644 index 0000000000000..61e81330b0920 --- /dev/null +++ b/tests/ui/generator/parent-expression.rs @@ -0,0 +1,77 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir + +#![feature(generators, negative_impls, rustc_attrs)] + +macro_rules! type_combinations { + ( + $( $name:ident => { $( $tt:tt )* } );* $(;)? + ) => { $( + mod $name { + $( $tt )* + + impl !Sync for Client {} + impl !Send for Client {} + } + + // Struct update syntax. This fails because the Client used in the update is considered + // dropped *after* the yield. + { + let g = move || match drop($name::Client { ..$name::Client::default() }) { + //~^ `significant_drop::Client` which is not `Send` + //~| `insignificant_dtor::Client` which is not `Send` + //~| `derived_drop::Client` which is not `Send` + _ => yield, + }; + assert_send(g); + //~^ ERROR cannot be sent between threads + //~| ERROR cannot be sent between threads + //~| ERROR cannot be sent between threads + //[no_drop_tracking,drop_tracking_mir]~^^^^ ERROR cannot be sent between threads + } + + // Simple owned value. This works because the Client is considered moved into `drop`, + // even though the temporary expression doesn't end until after the yield. + { + let g = move || match drop($name::Client::default()) { + _ => yield, + }; + assert_send(g); + //[no_drop_tracking,drop_tracking_mir]~^ ERROR cannot be sent between threads + //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads + //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads + //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads + } + )* } +} + +fn assert_send(_thing: T) {} + +fn main() { + type_combinations!( + // OK + copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; + // NOT OK: MIR borrowck thinks that this is used after the yield, even though + // this has no `Drop` impl and only the drops of the fields are observable. + // FIXME: this should compile. + derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; + // NOT OK + significant_drop => { + #[derive(Default)] + pub struct Client; + impl Drop for Client { + fn drop(&mut self) {} + } + }; + // NOT OK (we need to agree with MIR borrowck) + insignificant_dtor => { + #[derive(Default)] + #[rustc_insignificant_dtor] + pub struct Client; + impl Drop for Client { + fn drop(&mut self) {} + } + }; + ); +} diff --git a/tests/ui/generator/partial-drop.drop_tracking.stderr b/tests/ui/generator/partial-drop.drop_tracking.stderr new file mode 100644 index 0000000000000..e3c19264ee857 --- /dev/null +++ b/tests/ui/generator/partial-drop.drop_tracking.stderr @@ -0,0 +1,92 @@ +error: generator cannot be sent between threads safely + --> $DIR/partial-drop.rs:16:17 + | +LL | assert_send(|| { + | _________________^ +LL | | +LL | | // FIXME: it would be nice to make this work. +LL | | let guard = Bar { foo: Foo, x: 42 }; +LL | | drop(guard.foo); +LL | | yield; +LL | | }); + | |_____^ generator is not `Send` + | + = help: within `[generator@$DIR/partial-drop.rs:16:17: 16:19]`, the trait `Send` is not implemented for `Foo` +note: generator is not `Send` as this value is used across a yield + --> $DIR/partial-drop.rs:21:9 + | +LL | let guard = Bar { foo: Foo, x: 42 }; + | ----- has type `Bar` which is not `Send` +LL | drop(guard.foo); +LL | yield; + | ^^^^^ yield occurs here, with `guard` maybe used later +LL | }); + | - `guard` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/partial-drop.rs:44:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: generator cannot be sent between threads safely + --> $DIR/partial-drop.rs:24:17 + | +LL | assert_send(|| { + | _________________^ +LL | | +LL | | // FIXME: it would be nice to make this work. +LL | | let guard = Bar { foo: Foo, x: 42 }; +... | +LL | | yield; +LL | | }); + | |_____^ generator is not `Send` + | + = help: within `[generator@$DIR/partial-drop.rs:24:17: 24:19]`, the trait `Send` is not implemented for `Foo` +note: generator is not `Send` as this value is used across a yield + --> $DIR/partial-drop.rs:31:9 + | +LL | let guard = Bar { foo: Foo, x: 42 }; + | ----- has type `Bar` which is not `Send` +... +LL | yield; + | ^^^^^ yield occurs here, with `guard` maybe used later +LL | }); + | - `guard` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/partial-drop.rs:44:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: generator cannot be sent between threads safely + --> $DIR/partial-drop.rs:34:17 + | +LL | assert_send(|| { + | _________________^ +LL | | +LL | | // FIXME: it would be nice to make this work. +LL | | let guard = Bar { foo: Foo, x: 42 }; +... | +LL | | yield; +LL | | }); + | |_____^ generator is not `Send` + | + = help: within `[generator@$DIR/partial-drop.rs:34:17: 34:19]`, the trait `Send` is not implemented for `Foo` +note: generator is not `Send` as this value is used across a yield + --> $DIR/partial-drop.rs:40:9 + | +LL | let guard = Bar { foo: Foo, x: 42 }; + | ----- has type `Bar` which is not `Send` +... +LL | yield; + | ^^^^^ yield occurs here, with `guard` maybe used later +LL | }); + | - `guard` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/partial-drop.rs:44:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to 3 previous errors + diff --git a/tests/ui/generator/partial-drop.drop_tracking_mir.stderr b/tests/ui/generator/partial-drop.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..fa901b1977a15 --- /dev/null +++ b/tests/ui/generator/partial-drop.drop_tracking_mir.stderr @@ -0,0 +1,92 @@ +error: generator cannot be sent between threads safely + --> $DIR/partial-drop.rs:16:17 + | +LL | assert_send(|| { + | _________________^ +LL | | +LL | | // FIXME: it would be nice to make this work. +LL | | let guard = Bar { foo: Foo, x: 42 }; +LL | | drop(guard.foo); +LL | | yield; +LL | | }); + | |_____^ generator is not `Send` + | + = help: within `[generator@$DIR/partial-drop.rs:16:17: 16:19]`, the trait `Send` is not implemented for `Foo` +note: generator is not `Send` as this value is used across a yield + --> $DIR/partial-drop.rs:21:9 + | +LL | let guard = Bar { foo: Foo, x: 42 }; + | ----- has type `Bar` which is not `Send` +LL | drop(guard.foo); +LL | yield; + | ^^^^^ yield occurs here, with `guard` maybe used later +LL | }); + | - `guard` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/partial-drop.rs:44:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: generator cannot be sent between threads safely + --> $DIR/partial-drop.rs:24:17 + | +LL | assert_send(|| { + | _________________^ +LL | | +LL | | // FIXME: it would be nice to make this work. +LL | | let guard = Bar { foo: Foo, x: 42 }; +... | +LL | | yield; +LL | | }); + | |_____^ generator is not `Send` + | + = help: within `[generator@$DIR/partial-drop.rs:24:17: 24:19]`, the trait `Send` is not implemented for `Foo` +note: generator is not `Send` as this value is used across a yield + --> $DIR/partial-drop.rs:31:9 + | +LL | let guard = Bar { foo: Foo, x: 42 }; + | ----- has type `Bar` which is not `Send` +... +LL | yield; + | ^^^^^ yield occurs here, with `guard` maybe used later +LL | }); + | - `guard` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/partial-drop.rs:44:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: generator cannot be sent between threads safely + --> $DIR/partial-drop.rs:34:17 + | +LL | assert_send(|| { + | _________________^ +LL | | +LL | | // FIXME: it would be nice to make this work. +LL | | let guard = Bar { foo: Foo, x: 42 }; +... | +LL | | yield; +LL | | }); + | |_____^ generator is not `Send` + | + = help: within `[generator@$DIR/partial-drop.rs:34:17: 34:19]`, the trait `Send` is not implemented for `Foo` +note: generator is not `Send` as this value is used across a yield + --> $DIR/partial-drop.rs:40:9 + | +LL | let Bar { foo, x } = guard; + | --- has type `Foo` which is not `Send` +LL | drop(foo); +LL | yield; + | ^^^^^ yield occurs here, with `foo` maybe used later +LL | }); + | - `foo` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/partial-drop.rs:44:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to 3 previous errors + diff --git a/tests/ui/generator/partial-drop.no_drop_tracking.stderr b/tests/ui/generator/partial-drop.no_drop_tracking.stderr new file mode 100644 index 0000000000000..fa901b1977a15 --- /dev/null +++ b/tests/ui/generator/partial-drop.no_drop_tracking.stderr @@ -0,0 +1,92 @@ +error: generator cannot be sent between threads safely + --> $DIR/partial-drop.rs:16:17 + | +LL | assert_send(|| { + | _________________^ +LL | | +LL | | // FIXME: it would be nice to make this work. +LL | | let guard = Bar { foo: Foo, x: 42 }; +LL | | drop(guard.foo); +LL | | yield; +LL | | }); + | |_____^ generator is not `Send` + | + = help: within `[generator@$DIR/partial-drop.rs:16:17: 16:19]`, the trait `Send` is not implemented for `Foo` +note: generator is not `Send` as this value is used across a yield + --> $DIR/partial-drop.rs:21:9 + | +LL | let guard = Bar { foo: Foo, x: 42 }; + | ----- has type `Bar` which is not `Send` +LL | drop(guard.foo); +LL | yield; + | ^^^^^ yield occurs here, with `guard` maybe used later +LL | }); + | - `guard` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/partial-drop.rs:44:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: generator cannot be sent between threads safely + --> $DIR/partial-drop.rs:24:17 + | +LL | assert_send(|| { + | _________________^ +LL | | +LL | | // FIXME: it would be nice to make this work. +LL | | let guard = Bar { foo: Foo, x: 42 }; +... | +LL | | yield; +LL | | }); + | |_____^ generator is not `Send` + | + = help: within `[generator@$DIR/partial-drop.rs:24:17: 24:19]`, the trait `Send` is not implemented for `Foo` +note: generator is not `Send` as this value is used across a yield + --> $DIR/partial-drop.rs:31:9 + | +LL | let guard = Bar { foo: Foo, x: 42 }; + | ----- has type `Bar` which is not `Send` +... +LL | yield; + | ^^^^^ yield occurs here, with `guard` maybe used later +LL | }); + | - `guard` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/partial-drop.rs:44:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: generator cannot be sent between threads safely + --> $DIR/partial-drop.rs:34:17 + | +LL | assert_send(|| { + | _________________^ +LL | | +LL | | // FIXME: it would be nice to make this work. +LL | | let guard = Bar { foo: Foo, x: 42 }; +... | +LL | | yield; +LL | | }); + | |_____^ generator is not `Send` + | + = help: within `[generator@$DIR/partial-drop.rs:34:17: 34:19]`, the trait `Send` is not implemented for `Foo` +note: generator is not `Send` as this value is used across a yield + --> $DIR/partial-drop.rs:40:9 + | +LL | let Bar { foo, x } = guard; + | --- has type `Foo` which is not `Send` +LL | drop(foo); +LL | yield; + | ^^^^^ yield occurs here, with `foo` maybe used later +LL | }); + | - `foo` is later dropped here +note: required by a bound in `assert_send` + --> $DIR/partial-drop.rs:44:19 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: aborting due to 3 previous errors + diff --git a/tests/ui/generator/partial-drop.rs b/tests/ui/generator/partial-drop.rs index c872fb7f3e630..e7f85df5877c5 100644 --- a/tests/ui/generator/partial-drop.rs +++ b/tests/ui/generator/partial-drop.rs @@ -1,4 +1,6 @@ -// compile-flags: -Zdrop-tracking +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir #![feature(negative_impls, generators)] diff --git a/tests/ui/generator/partial-drop.stderr b/tests/ui/generator/partial-drop.stderr index 9baafe54e84d4..e3c19264ee857 100644 --- a/tests/ui/generator/partial-drop.stderr +++ b/tests/ui/generator/partial-drop.stderr @@ -1,5 +1,5 @@ error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:14:17 + --> $DIR/partial-drop.rs:16:17 | LL | assert_send(|| { | _________________^ @@ -11,9 +11,9 @@ LL | | yield; LL | | }); | |_____^ generator is not `Send` | - = help: within `[generator@$DIR/partial-drop.rs:14:17: 14:19]`, the trait `Send` is not implemented for `Foo` + = help: within `[generator@$DIR/partial-drop.rs:16:17: 16:19]`, the trait `Send` is not implemented for `Foo` note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:19:9 + --> $DIR/partial-drop.rs:21:9 | LL | let guard = Bar { foo: Foo, x: 42 }; | ----- has type `Bar` which is not `Send` @@ -23,13 +23,13 @@ LL | yield; LL | }); | - `guard` is later dropped here note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:42:19 + --> $DIR/partial-drop.rs:44:19 | LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:22:17 + --> $DIR/partial-drop.rs:24:17 | LL | assert_send(|| { | _________________^ @@ -41,9 +41,9 @@ LL | | yield; LL | | }); | |_____^ generator is not `Send` | - = help: within `[generator@$DIR/partial-drop.rs:22:17: 22:19]`, the trait `Send` is not implemented for `Foo` + = help: within `[generator@$DIR/partial-drop.rs:24:17: 24:19]`, the trait `Send` is not implemented for `Foo` note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:29:9 + --> $DIR/partial-drop.rs:31:9 | LL | let guard = Bar { foo: Foo, x: 42 }; | ----- has type `Bar` which is not `Send` @@ -53,13 +53,13 @@ LL | yield; LL | }); | - `guard` is later dropped here note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:42:19 + --> $DIR/partial-drop.rs:44:19 | LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:32:17 + --> $DIR/partial-drop.rs:34:17 | LL | assert_send(|| { | _________________^ @@ -71,9 +71,9 @@ LL | | yield; LL | | }); | |_____^ generator is not `Send` | - = help: within `[generator@$DIR/partial-drop.rs:32:17: 32:19]`, the trait `Send` is not implemented for `Foo` + = help: within `[generator@$DIR/partial-drop.rs:34:17: 34:19]`, the trait `Send` is not implemented for `Foo` note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:38:9 + --> $DIR/partial-drop.rs:40:9 | LL | let guard = Bar { foo: Foo, x: 42 }; | ----- has type `Bar` which is not `Send` @@ -83,7 +83,7 @@ LL | yield; LL | }); | - `guard` is later dropped here note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:42:19 + --> $DIR/partial-drop.rs:44:19 | LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` diff --git a/tests/ui/generator/print/generator-print-verbose-1.stderr b/tests/ui/generator/print/generator-print-verbose-1.drop_tracking.stderr similarity index 86% rename from tests/ui/generator/print/generator-print-verbose-1.stderr rename to tests/ui/generator/print/generator-print-verbose-1.drop_tracking.stderr index 45d018b8ebad5..7d0a201699b5c 100644 --- a/tests/ui/generator/print/generator-print-verbose-1.stderr +++ b/tests/ui/generator/print/generator-print-verbose-1.drop_tracking.stderr @@ -1,5 +1,5 @@ error: generator cannot be sent between threads safely - --> $DIR/generator-print-verbose-1.rs:37:18 + --> $DIR/generator-print-verbose-1.rs:40:18 | LL | require_send(send_gen); | ^^^^^^^^ generator is not `Send` @@ -7,7 +7,7 @@ LL | require_send(send_gen); = help: the trait `Sync` is not implemented for `RefCell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead note: generator is not `Send` as this value is used across a yield - --> $DIR/generator-print-verbose-1.rs:35:9 + --> $DIR/generator-print-verbose-1.rs:38:9 | LL | let _non_send_gen = make_non_send_generator(); | ------------- has type `Opaque(DefId(0:34 ~ generator_print_verbose_1[749a]::make_non_send_generator::{opaque#0}), [])` which is not `Send` @@ -16,13 +16,13 @@ LL | yield; LL | }; | - `_non_send_gen` is later dropped here note: required by a bound in `require_send` - --> $DIR/generator-print-verbose-1.rs:26:25 + --> $DIR/generator-print-verbose-1.rs:29:25 | LL | fn require_send(_: impl Send) {} | ^^^^ required by this bound in `require_send` error[E0277]: `RefCell` cannot be shared between threads safely - --> $DIR/generator-print-verbose-1.rs:56:18 + --> $DIR/generator-print-verbose-1.rs:59:18 | LL | require_send(send_gen); | ------------ ^^^^^^^^ `RefCell` cannot be shared between threads safely @@ -33,28 +33,28 @@ LL | require_send(send_gen); = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead = note: required for `Arc>` to implement `Send` note: required because it's used within this generator - --> $DIR/generator-print-verbose-1.rs:42:5 + --> $DIR/generator-print-verbose-1.rs:45:5 | LL | || { | ^^ note: required because it appears within the type `Opaque(DefId(0:35 ~ generator_print_verbose_1[749a]::make_gen2::{opaque#0}), [Arc>])` - --> $DIR/generator-print-verbose-1.rs:41:30 + --> $DIR/generator-print-verbose-1.rs:44:30 | LL | pub fn make_gen2(t: T) -> impl Generator { | ^^^^^^^^^^^^^^^^^^^^^^^^^^ note: required because it appears within the type `Opaque(DefId(0:36 ~ generator_print_verbose_1[749a]::make_non_send_generator2::{opaque#0}), [])` - --> $DIR/generator-print-verbose-1.rs:47:34 + --> $DIR/generator-print-verbose-1.rs:50:34 | LL | fn make_non_send_generator2() -> impl Generator>> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required because it captures the following types: `Opaque(DefId(0:36 ~ generator_print_verbose_1[749a]::make_non_send_generator2::{opaque#0}), [])`, `()` note: required because it's used within this generator - --> $DIR/generator-print-verbose-1.rs:52:20 + --> $DIR/generator-print-verbose-1.rs:55:20 | LL | let send_gen = || { | ^^ note: required by a bound in `require_send` - --> $DIR/generator-print-verbose-1.rs:26:25 + --> $DIR/generator-print-verbose-1.rs:29:25 | LL | fn require_send(_: impl Send) {} | ^^^^ required by this bound in `require_send` diff --git a/tests/ui/generator/print/generator-print-verbose-1.drop_tracking_mir.stderr b/tests/ui/generator/print/generator-print-verbose-1.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..7d0a201699b5c --- /dev/null +++ b/tests/ui/generator/print/generator-print-verbose-1.drop_tracking_mir.stderr @@ -0,0 +1,64 @@ +error: generator cannot be sent between threads safely + --> $DIR/generator-print-verbose-1.rs:40:18 + | +LL | require_send(send_gen); + | ^^^^^^^^ generator is not `Send` + | + = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead +note: generator is not `Send` as this value is used across a yield + --> $DIR/generator-print-verbose-1.rs:38:9 + | +LL | let _non_send_gen = make_non_send_generator(); + | ------------- has type `Opaque(DefId(0:34 ~ generator_print_verbose_1[749a]::make_non_send_generator::{opaque#0}), [])` which is not `Send` +LL | yield; + | ^^^^^ yield occurs here, with `_non_send_gen` maybe used later +LL | }; + | - `_non_send_gen` is later dropped here +note: required by a bound in `require_send` + --> $DIR/generator-print-verbose-1.rs:29:25 + | +LL | fn require_send(_: impl Send) {} + | ^^^^ required by this bound in `require_send` + +error[E0277]: `RefCell` cannot be shared between threads safely + --> $DIR/generator-print-verbose-1.rs:59:18 + | +LL | require_send(send_gen); + | ------------ ^^^^^^^^ `RefCell` cannot be shared between threads safely + | | + | required by a bound introduced by this call + | + = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead + = note: required for `Arc>` to implement `Send` +note: required because it's used within this generator + --> $DIR/generator-print-verbose-1.rs:45:5 + | +LL | || { + | ^^ +note: required because it appears within the type `Opaque(DefId(0:35 ~ generator_print_verbose_1[749a]::make_gen2::{opaque#0}), [Arc>])` + --> $DIR/generator-print-verbose-1.rs:44:30 + | +LL | pub fn make_gen2(t: T) -> impl Generator { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required because it appears within the type `Opaque(DefId(0:36 ~ generator_print_verbose_1[749a]::make_non_send_generator2::{opaque#0}), [])` + --> $DIR/generator-print-verbose-1.rs:50:34 + | +LL | fn make_non_send_generator2() -> impl Generator>> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required because it captures the following types: `Opaque(DefId(0:36 ~ generator_print_verbose_1[749a]::make_non_send_generator2::{opaque#0}), [])`, `()` +note: required because it's used within this generator + --> $DIR/generator-print-verbose-1.rs:55:20 + | +LL | let send_gen = || { + | ^^ +note: required by a bound in `require_send` + --> $DIR/generator-print-verbose-1.rs:29:25 + | +LL | fn require_send(_: impl Send) {} + | ^^^^ required by this bound in `require_send` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/print/generator-print-verbose-1.no_drop_tracking.stderr b/tests/ui/generator/print/generator-print-verbose-1.no_drop_tracking.stderr new file mode 100644 index 0000000000000..7d0a201699b5c --- /dev/null +++ b/tests/ui/generator/print/generator-print-verbose-1.no_drop_tracking.stderr @@ -0,0 +1,64 @@ +error: generator cannot be sent between threads safely + --> $DIR/generator-print-verbose-1.rs:40:18 + | +LL | require_send(send_gen); + | ^^^^^^^^ generator is not `Send` + | + = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead +note: generator is not `Send` as this value is used across a yield + --> $DIR/generator-print-verbose-1.rs:38:9 + | +LL | let _non_send_gen = make_non_send_generator(); + | ------------- has type `Opaque(DefId(0:34 ~ generator_print_verbose_1[749a]::make_non_send_generator::{opaque#0}), [])` which is not `Send` +LL | yield; + | ^^^^^ yield occurs here, with `_non_send_gen` maybe used later +LL | }; + | - `_non_send_gen` is later dropped here +note: required by a bound in `require_send` + --> $DIR/generator-print-verbose-1.rs:29:25 + | +LL | fn require_send(_: impl Send) {} + | ^^^^ required by this bound in `require_send` + +error[E0277]: `RefCell` cannot be shared between threads safely + --> $DIR/generator-print-verbose-1.rs:59:18 + | +LL | require_send(send_gen); + | ------------ ^^^^^^^^ `RefCell` cannot be shared between threads safely + | | + | required by a bound introduced by this call + | + = help: the trait `Sync` is not implemented for `RefCell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead + = note: required for `Arc>` to implement `Send` +note: required because it's used within this generator + --> $DIR/generator-print-verbose-1.rs:45:5 + | +LL | || { + | ^^ +note: required because it appears within the type `Opaque(DefId(0:35 ~ generator_print_verbose_1[749a]::make_gen2::{opaque#0}), [Arc>])` + --> $DIR/generator-print-verbose-1.rs:44:30 + | +LL | pub fn make_gen2(t: T) -> impl Generator { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required because it appears within the type `Opaque(DefId(0:36 ~ generator_print_verbose_1[749a]::make_non_send_generator2::{opaque#0}), [])` + --> $DIR/generator-print-verbose-1.rs:50:34 + | +LL | fn make_non_send_generator2() -> impl Generator>> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required because it captures the following types: `Opaque(DefId(0:36 ~ generator_print_verbose_1[749a]::make_non_send_generator2::{opaque#0}), [])`, `()` +note: required because it's used within this generator + --> $DIR/generator-print-verbose-1.rs:55:20 + | +LL | let send_gen = || { + | ^^ +note: required by a bound in `require_send` + --> $DIR/generator-print-verbose-1.rs:29:25 + | +LL | fn require_send(_: impl Send) {} + | ^^^^ required by this bound in `require_send` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/print/generator-print-verbose-1.rs b/tests/ui/generator/print/generator-print-verbose-1.rs index 89124ad7289ac..d0acff8c93f94 100644 --- a/tests/ui/generator/print/generator-print-verbose-1.rs +++ b/tests/ui/generator/print/generator-print-verbose-1.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // compile-flags: -Zverbose // Same as: tests/ui/generator/issue-68112.stderr diff --git a/tests/ui/generator/print/generator-print-verbose-2.stderr b/tests/ui/generator/print/generator-print-verbose-2.drop_tracking.stderr similarity index 87% rename from tests/ui/generator/print/generator-print-verbose-2.stderr rename to tests/ui/generator/print/generator-print-verbose-2.drop_tracking.stderr index 59112ce0a79e6..0df978e47dca9 100644 --- a/tests/ui/generator/print/generator-print-verbose-2.stderr +++ b/tests/ui/generator/print/generator-print-verbose-2.drop_tracking.stderr @@ -1,5 +1,5 @@ error[E0277]: `Cell` cannot be shared between threads safely - --> $DIR/generator-print-verbose-2.rs:19:17 + --> $DIR/generator-print-verbose-2.rs:22:17 | LL | assert_send(|| { | _____-----------_^ @@ -15,18 +15,18 @@ LL | | }); = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead = note: required for `&'_#4r Cell` to implement `Send` note: required because it's used within this generator - --> $DIR/generator-print-verbose-2.rs:19:17 + --> $DIR/generator-print-verbose-2.rs:22:17 | LL | assert_send(|| { | ^^ note: required by a bound in `assert_send` - --> $DIR/generator-print-verbose-2.rs:10:23 + --> $DIR/generator-print-verbose-2.rs:13:23 | LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` error: generator cannot be shared between threads safely - --> $DIR/generator-print-verbose-2.rs:12:17 + --> $DIR/generator-print-verbose-2.rs:15:17 | LL | assert_sync(|| { | _________________^ @@ -39,7 +39,7 @@ LL | | }); = help: within `[main::{closure#0} upvar_tys=() {Cell, ()}]`, the trait `Sync` is not implemented for `Cell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead note: generator is not `Sync` as this value is used across a yield - --> $DIR/generator-print-verbose-2.rs:15:9 + --> $DIR/generator-print-verbose-2.rs:18:9 | LL | let a = Cell::new(2); | - has type `Cell` which is not `Sync` @@ -48,7 +48,7 @@ LL | yield; LL | }); | - `a` is later dropped here note: required by a bound in `assert_sync` - --> $DIR/generator-print-verbose-2.rs:9:23 + --> $DIR/generator-print-verbose-2.rs:12:23 | LL | fn assert_sync(_: T) {} | ^^^^ required by this bound in `assert_sync` diff --git a/tests/ui/generator/print/generator-print-verbose-2.drop_tracking_mir.stderr b/tests/ui/generator/print/generator-print-verbose-2.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..0df978e47dca9 --- /dev/null +++ b/tests/ui/generator/print/generator-print-verbose-2.drop_tracking_mir.stderr @@ -0,0 +1,58 @@ +error[E0277]: `Cell` cannot be shared between threads safely + --> $DIR/generator-print-verbose-2.rs:22:17 + | +LL | assert_send(|| { + | _____-----------_^ + | | | + | | required by a bound introduced by this call +LL | | +LL | | drop(&a); +LL | | yield; +LL | | }); + | |_____^ `Cell` cannot be shared between threads safely + | + = help: the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead + = note: required for `&'_#4r Cell` to implement `Send` +note: required because it's used within this generator + --> $DIR/generator-print-verbose-2.rs:22:17 + | +LL | assert_send(|| { + | ^^ +note: required by a bound in `assert_send` + --> $DIR/generator-print-verbose-2.rs:13:23 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: generator cannot be shared between threads safely + --> $DIR/generator-print-verbose-2.rs:15:17 + | +LL | assert_sync(|| { + | _________________^ +LL | | +LL | | let a = Cell::new(2); +LL | | yield; +LL | | }); + | |_____^ generator is not `Sync` + | + = help: within `[main::{closure#0} upvar_tys=() {Cell, ()}]`, the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead +note: generator is not `Sync` as this value is used across a yield + --> $DIR/generator-print-verbose-2.rs:18:9 + | +LL | let a = Cell::new(2); + | - has type `Cell` which is not `Sync` +LL | yield; + | ^^^^^ yield occurs here, with `a` maybe used later +LL | }); + | - `a` is later dropped here +note: required by a bound in `assert_sync` + --> $DIR/generator-print-verbose-2.rs:12:23 + | +LL | fn assert_sync(_: T) {} + | ^^^^ required by this bound in `assert_sync` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/print/generator-print-verbose-2.no_drop_tracking.stderr b/tests/ui/generator/print/generator-print-verbose-2.no_drop_tracking.stderr new file mode 100644 index 0000000000000..0df978e47dca9 --- /dev/null +++ b/tests/ui/generator/print/generator-print-verbose-2.no_drop_tracking.stderr @@ -0,0 +1,58 @@ +error[E0277]: `Cell` cannot be shared between threads safely + --> $DIR/generator-print-verbose-2.rs:22:17 + | +LL | assert_send(|| { + | _____-----------_^ + | | | + | | required by a bound introduced by this call +LL | | +LL | | drop(&a); +LL | | yield; +LL | | }); + | |_____^ `Cell` cannot be shared between threads safely + | + = help: the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead + = note: required for `&'_#4r Cell` to implement `Send` +note: required because it's used within this generator + --> $DIR/generator-print-verbose-2.rs:22:17 + | +LL | assert_send(|| { + | ^^ +note: required by a bound in `assert_send` + --> $DIR/generator-print-verbose-2.rs:13:23 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + +error: generator cannot be shared between threads safely + --> $DIR/generator-print-verbose-2.rs:15:17 + | +LL | assert_sync(|| { + | _________________^ +LL | | +LL | | let a = Cell::new(2); +LL | | yield; +LL | | }); + | |_____^ generator is not `Sync` + | + = help: within `[main::{closure#0} upvar_tys=() {Cell, ()}]`, the trait `Sync` is not implemented for `Cell` + = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead +note: generator is not `Sync` as this value is used across a yield + --> $DIR/generator-print-verbose-2.rs:18:9 + | +LL | let a = Cell::new(2); + | - has type `Cell` which is not `Sync` +LL | yield; + | ^^^^^ yield occurs here, with `a` maybe used later +LL | }); + | - `a` is later dropped here +note: required by a bound in `assert_sync` + --> $DIR/generator-print-verbose-2.rs:12:23 + | +LL | fn assert_sync(_: T) {} + | ^^^^ required by this bound in `assert_sync` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/print/generator-print-verbose-2.rs b/tests/ui/generator/print/generator-print-verbose-2.rs index d914719cb36bb..74b9811b50b2c 100644 --- a/tests/ui/generator/print/generator-print-verbose-2.rs +++ b/tests/ui/generator/print/generator-print-verbose-2.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // compile-flags: -Zverbose // Same as test/ui/generator/not-send-sync.rs diff --git a/tests/ui/generator/retain-resume-ref.drop_tracking.stderr b/tests/ui/generator/retain-resume-ref.drop_tracking.stderr new file mode 100644 index 0000000000000..7122a951e8070 --- /dev/null +++ b/tests/ui/generator/retain-resume-ref.drop_tracking.stderr @@ -0,0 +1,13 @@ +error[E0499]: cannot borrow `thing` as mutable more than once at a time + --> $DIR/retain-resume-ref.rs:27:25 + | +LL | gen.as_mut().resume(&mut thing); + | ---------- first mutable borrow occurs here +LL | gen.as_mut().resume(&mut thing); + | ------ ^^^^^^^^^^ second mutable borrow occurs here + | | + | first borrow later used by call + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0499`. diff --git a/tests/ui/generator/retain-resume-ref.drop_tracking_mir.stderr b/tests/ui/generator/retain-resume-ref.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..7122a951e8070 --- /dev/null +++ b/tests/ui/generator/retain-resume-ref.drop_tracking_mir.stderr @@ -0,0 +1,13 @@ +error[E0499]: cannot borrow `thing` as mutable more than once at a time + --> $DIR/retain-resume-ref.rs:27:25 + | +LL | gen.as_mut().resume(&mut thing); + | ---------- first mutable borrow occurs here +LL | gen.as_mut().resume(&mut thing); + | ------ ^^^^^^^^^^ second mutable borrow occurs here + | | + | first borrow later used by call + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0499`. diff --git a/tests/ui/generator/retain-resume-ref.no_drop_tracking.stderr b/tests/ui/generator/retain-resume-ref.no_drop_tracking.stderr new file mode 100644 index 0000000000000..7122a951e8070 --- /dev/null +++ b/tests/ui/generator/retain-resume-ref.no_drop_tracking.stderr @@ -0,0 +1,13 @@ +error[E0499]: cannot borrow `thing` as mutable more than once at a time + --> $DIR/retain-resume-ref.rs:27:25 + | +LL | gen.as_mut().resume(&mut thing); + | ---------- first mutable borrow occurs here +LL | gen.as_mut().resume(&mut thing); + | ------ ^^^^^^^^^^ second mutable borrow occurs here + | | + | first borrow later used by call + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0499`. diff --git a/tests/ui/generator/retain-resume-ref.rs b/tests/ui/generator/retain-resume-ref.rs index 0606ea71cdf37..0050d98d03ba6 100644 --- a/tests/ui/generator/retain-resume-ref.rs +++ b/tests/ui/generator/retain-resume-ref.rs @@ -1,3 +1,7 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir + //! This test ensures that a mutable reference cannot be passed as a resume argument twice. #![feature(generators, generator_trait)] diff --git a/tests/ui/generator/retain-resume-ref.stderr b/tests/ui/generator/retain-resume-ref.stderr index e33310d12d9ef..7122a951e8070 100644 --- a/tests/ui/generator/retain-resume-ref.stderr +++ b/tests/ui/generator/retain-resume-ref.stderr @@ -1,5 +1,5 @@ error[E0499]: cannot borrow `thing` as mutable more than once at a time - --> $DIR/retain-resume-ref.rs:23:25 + --> $DIR/retain-resume-ref.rs:27:25 | LL | gen.as_mut().resume(&mut thing); | ---------- first mutable borrow occurs here diff --git a/tests/ui/generator/static-mut-reference-across-yield.rs b/tests/ui/generator/static-mut-reference-across-yield.rs index 0fa6d9cdc77b6..4784ff49be2e9 100644 --- a/tests/ui/generator/static-mut-reference-across-yield.rs +++ b/tests/ui/generator/static-mut-reference-across-yield.rs @@ -1,6 +1,8 @@ // build-pass -// revisions: mir thir +// revisions: mir thir drop_tracking drop_tracking_mir // [thir]compile-flags: -Zthir-unsafeck +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir #![feature(generators)] diff --git a/tests/ui/impl-trait/issue-55872-2.drop_tracking.stderr b/tests/ui/impl-trait/issue-55872-2.drop_tracking.stderr new file mode 100644 index 0000000000000..477c964bd40fd --- /dev/null +++ b/tests/ui/impl-trait/issue-55872-2.drop_tracking.stderr @@ -0,0 +1,8 @@ +error: type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias + --> $DIR/issue-55872-2.rs:17:9 + | +LL | async {} + | ^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/impl-trait/issue-55872-2.drop_tracking_mir.stderr b/tests/ui/impl-trait/issue-55872-2.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..477c964bd40fd --- /dev/null +++ b/tests/ui/impl-trait/issue-55872-2.drop_tracking_mir.stderr @@ -0,0 +1,8 @@ +error: type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias + --> $DIR/issue-55872-2.rs:17:9 + | +LL | async {} + | ^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/impl-trait/issue-55872-2.no_drop_tracking.stderr b/tests/ui/impl-trait/issue-55872-2.no_drop_tracking.stderr new file mode 100644 index 0000000000000..477c964bd40fd --- /dev/null +++ b/tests/ui/impl-trait/issue-55872-2.no_drop_tracking.stderr @@ -0,0 +1,8 @@ +error: type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias + --> $DIR/issue-55872-2.rs:17:9 + | +LL | async {} + | ^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/impl-trait/issue-55872-2.rs b/tests/ui/impl-trait/issue-55872-2.rs index 4443d3c4d0df1..1696ead0d8d1b 100644 --- a/tests/ui/impl-trait/issue-55872-2.rs +++ b/tests/ui/impl-trait/issue-55872-2.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 #![feature(type_alias_impl_trait)] diff --git a/tests/ui/impl-trait/issue-55872-2.stderr b/tests/ui/impl-trait/issue-55872-2.stderr index 11b8485c8bbfe..477c964bd40fd 100644 --- a/tests/ui/impl-trait/issue-55872-2.stderr +++ b/tests/ui/impl-trait/issue-55872-2.stderr @@ -1,5 +1,5 @@ error: type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias - --> $DIR/issue-55872-2.rs:14:9 + --> $DIR/issue-55872-2.rs:17:9 | LL | async {} | ^^^^^^^^ diff --git a/tests/ui/impl-trait/recursive-impl-trait-type-indirect.stderr b/tests/ui/impl-trait/recursive-impl-trait-type-indirect.drop_tracking.stderr similarity index 80% rename from tests/ui/impl-trait/recursive-impl-trait-type-indirect.stderr rename to tests/ui/impl-trait/recursive-impl-trait-type-indirect.drop_tracking.stderr index ebb231ae14f0d..43118ae38540f 100644 --- a/tests/ui/impl-trait/recursive-impl-trait-type-indirect.stderr +++ b/tests/ui/impl-trait/recursive-impl-trait-type-indirect.drop_tracking.stderr @@ -1,5 +1,5 @@ error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:7:22 + --> $DIR/recursive-impl-trait-type-indirect.rs:11:22 | LL | fn option(i: i32) -> impl Sized { | ^^^^^^^^^^ recursive opaque type @@ -10,7 +10,7 @@ LL | if i < 0 { None } else { Some((option(i - 1), i)) } | returning here with type `Option<(impl Sized, i32)>` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:12:15 + --> $DIR/recursive-impl-trait-type-indirect.rs:16:15 | LL | fn tuple() -> impl Sized { | ^^^^^^^^^^ recursive opaque type @@ -19,7 +19,7 @@ LL | (tuple(),) | ---------- returning here with type `(impl Sized,)` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:17:15 + --> $DIR/recursive-impl-trait-type-indirect.rs:21:15 | LL | fn array() -> impl Sized { | ^^^^^^^^^^ recursive opaque type @@ -28,7 +28,7 @@ LL | [array()] | --------- returning here with type `[impl Sized; 1]` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:22:13 + --> $DIR/recursive-impl-trait-type-indirect.rs:26:13 | LL | fn ptr() -> impl Sized { | ^^^^^^^^^^ recursive opaque type @@ -37,7 +37,7 @@ LL | &ptr() as *const _ | ------------------ returning here with type `*const impl Sized` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:27:16 + --> $DIR/recursive-impl-trait-type-indirect.rs:31:16 | LL | fn fn_ptr() -> impl Sized { | ^^^^^^^^^^ recursive opaque type @@ -46,7 +46,7 @@ LL | fn_ptr as fn() -> _ | ------------------- returning here with type `fn() -> impl Sized` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:32:25 + --> $DIR/recursive-impl-trait-type-indirect.rs:36:25 | LL | fn closure_capture() -> impl Sized { | ^^^^^^^^^^ recursive opaque type @@ -55,10 +55,10 @@ LL | / move || { LL | | x; | | - closure captures itself here LL | | } - | |_____- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:35:5: 35:12]` + | |_____- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:39:5: 39:12]` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:40:29 + --> $DIR/recursive-impl-trait-type-indirect.rs:44:29 | LL | fn closure_ref_capture() -> impl Sized { | ^^^^^^^^^^ recursive opaque type @@ -67,28 +67,28 @@ LL | / move || { LL | | &x; | | - closure captures itself here LL | | } - | |_____- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:43:5: 43:12]` + | |_____- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:47:5: 47:12]` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:48:21 + --> $DIR/recursive-impl-trait-type-indirect.rs:52:21 | LL | fn closure_sig() -> impl Sized { | ^^^^^^^^^^ recursive opaque type LL | LL | || closure_sig() - | ---------------- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:50:5: 50:7]` + | ---------------- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:54:5: 54:7]` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:53:23 + --> $DIR/recursive-impl-trait-type-indirect.rs:57:23 | LL | fn generator_sig() -> impl Sized { | ^^^^^^^^^^ recursive opaque type LL | LL | || generator_sig() - | ------------------ returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:55:5: 55:7]` + | ------------------ returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:59:5: 59:7]` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:58:27 + --> $DIR/recursive-impl-trait-type-indirect.rs:62:27 | LL | fn generator_capture() -> impl Sized { | ^^^^^^^^^^ recursive opaque type @@ -98,10 +98,10 @@ LL | | yield; LL | | x; | | - generator captures itself here LL | | } - | |_____- returning here with type `[generator@$DIR/recursive-impl-trait-type-indirect.rs:61:5: 61:12]` + | |_____- returning here with type `[generator@$DIR/recursive-impl-trait-type-indirect.rs:65:5: 65:12]` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:67:35 + --> $DIR/recursive-impl-trait-type-indirect.rs:71:35 | LL | fn substs_change() -> impl Sized { | ^^^^^^^^^^ recursive opaque type @@ -110,7 +110,7 @@ LL | (substs_change::<&T>(),) | ------------------------ returning here with type `(impl Sized,)` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:72:24 + --> $DIR/recursive-impl-trait-type-indirect.rs:76:24 | LL | fn generator_hold() -> impl Sized { | ^^^^^^^^^^ recursive opaque type @@ -121,10 +121,10 @@ LL | | let x = generator_hold(); LL | | yield; LL | | x; LL | | } - | |_____- returning here with type `[generator@$DIR/recursive-impl-trait-type-indirect.rs:74:5: 74:12]` + | |_____- returning here with type `[generator@$DIR/recursive-impl-trait-type-indirect.rs:78:5: 78:12]` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:86:26 + --> $DIR/recursive-impl-trait-type-indirect.rs:90:26 | LL | fn mutual_recursion() -> impl Sync { | ^^^^^^^^^ recursive opaque type @@ -136,7 +136,7 @@ LL | fn mutual_recursion_b() -> impl Sized { | ---------- returning this opaque type `impl Sized` error[E0720]: cannot resolve opaque type - --> $DIR/recursive-impl-trait-type-indirect.rs:91:28 + --> $DIR/recursive-impl-trait-type-indirect.rs:95:28 | LL | fn mutual_recursion() -> impl Sync { | --------- returning this opaque type `impl Sync` diff --git a/tests/ui/impl-trait/recursive-impl-trait-type-indirect.drop_tracking_mir.stderr b/tests/ui/impl-trait/recursive-impl-trait-type-indirect.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..43118ae38540f --- /dev/null +++ b/tests/ui/impl-trait/recursive-impl-trait-type-indirect.drop_tracking_mir.stderr @@ -0,0 +1,152 @@ +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:11:22 + | +LL | fn option(i: i32) -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | if i < 0 { None } else { Some((option(i - 1), i)) } + | ---- ------------------------ returning here with type `Option<(impl Sized, i32)>` + | | + | returning here with type `Option<(impl Sized, i32)>` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:16:15 + | +LL | fn tuple() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | (tuple(),) + | ---------- returning here with type `(impl Sized,)` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:21:15 + | +LL | fn array() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | [array()] + | --------- returning here with type `[impl Sized; 1]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:26:13 + | +LL | fn ptr() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | &ptr() as *const _ + | ------------------ returning here with type `*const impl Sized` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:31:16 + | +LL | fn fn_ptr() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | fn_ptr as fn() -> _ + | ------------------- returning here with type `fn() -> impl Sized` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:36:25 + | +LL | fn closure_capture() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +... +LL | / move || { +LL | | x; + | | - closure captures itself here +LL | | } + | |_____- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:39:5: 39:12]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:44:29 + | +LL | fn closure_ref_capture() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +... +LL | / move || { +LL | | &x; + | | - closure captures itself here +LL | | } + | |_____- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:47:5: 47:12]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:52:21 + | +LL | fn closure_sig() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | || closure_sig() + | ---------------- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:54:5: 54:7]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:57:23 + | +LL | fn generator_sig() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | || generator_sig() + | ------------------ returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:59:5: 59:7]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:62:27 + | +LL | fn generator_capture() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +... +LL | / move || { +LL | | yield; +LL | | x; + | | - generator captures itself here +LL | | } + | |_____- returning here with type `[generator@$DIR/recursive-impl-trait-type-indirect.rs:65:5: 65:12]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:71:35 + | +LL | fn substs_change() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | (substs_change::<&T>(),) + | ------------------------ returning here with type `(impl Sized,)` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:76:24 + | +LL | fn generator_hold() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | / move || { +LL | | let x = generator_hold(); + | | - generator captures itself here +LL | | yield; +LL | | x; +LL | | } + | |_____- returning here with type `[generator@$DIR/recursive-impl-trait-type-indirect.rs:78:5: 78:12]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:90:26 + | +LL | fn mutual_recursion() -> impl Sync { + | ^^^^^^^^^ recursive opaque type +LL | +LL | mutual_recursion_b() + | -------------------- returning here with type `impl Sized` +... +LL | fn mutual_recursion_b() -> impl Sized { + | ---------- returning this opaque type `impl Sized` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:95:28 + | +LL | fn mutual_recursion() -> impl Sync { + | --------- returning this opaque type `impl Sync` +... +LL | fn mutual_recursion_b() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | mutual_recursion() + | ------------------ returning here with type `impl Sync` + +error: aborting due to 14 previous errors + +For more information about this error, try `rustc --explain E0720`. diff --git a/tests/ui/impl-trait/recursive-impl-trait-type-indirect.no_drop_tracking.stderr b/tests/ui/impl-trait/recursive-impl-trait-type-indirect.no_drop_tracking.stderr new file mode 100644 index 0000000000000..43118ae38540f --- /dev/null +++ b/tests/ui/impl-trait/recursive-impl-trait-type-indirect.no_drop_tracking.stderr @@ -0,0 +1,152 @@ +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:11:22 + | +LL | fn option(i: i32) -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | if i < 0 { None } else { Some((option(i - 1), i)) } + | ---- ------------------------ returning here with type `Option<(impl Sized, i32)>` + | | + | returning here with type `Option<(impl Sized, i32)>` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:16:15 + | +LL | fn tuple() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | (tuple(),) + | ---------- returning here with type `(impl Sized,)` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:21:15 + | +LL | fn array() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | [array()] + | --------- returning here with type `[impl Sized; 1]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:26:13 + | +LL | fn ptr() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | &ptr() as *const _ + | ------------------ returning here with type `*const impl Sized` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:31:16 + | +LL | fn fn_ptr() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | fn_ptr as fn() -> _ + | ------------------- returning here with type `fn() -> impl Sized` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:36:25 + | +LL | fn closure_capture() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +... +LL | / move || { +LL | | x; + | | - closure captures itself here +LL | | } + | |_____- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:39:5: 39:12]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:44:29 + | +LL | fn closure_ref_capture() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +... +LL | / move || { +LL | | &x; + | | - closure captures itself here +LL | | } + | |_____- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:47:5: 47:12]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:52:21 + | +LL | fn closure_sig() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | || closure_sig() + | ---------------- returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:54:5: 54:7]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:57:23 + | +LL | fn generator_sig() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | || generator_sig() + | ------------------ returning here with type `[closure@$DIR/recursive-impl-trait-type-indirect.rs:59:5: 59:7]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:62:27 + | +LL | fn generator_capture() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +... +LL | / move || { +LL | | yield; +LL | | x; + | | - generator captures itself here +LL | | } + | |_____- returning here with type `[generator@$DIR/recursive-impl-trait-type-indirect.rs:65:5: 65:12]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:71:35 + | +LL | fn substs_change() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | (substs_change::<&T>(),) + | ------------------------ returning here with type `(impl Sized,)` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:76:24 + | +LL | fn generator_hold() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | / move || { +LL | | let x = generator_hold(); + | | - generator captures itself here +LL | | yield; +LL | | x; +LL | | } + | |_____- returning here with type `[generator@$DIR/recursive-impl-trait-type-indirect.rs:78:5: 78:12]` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:90:26 + | +LL | fn mutual_recursion() -> impl Sync { + | ^^^^^^^^^ recursive opaque type +LL | +LL | mutual_recursion_b() + | -------------------- returning here with type `impl Sized` +... +LL | fn mutual_recursion_b() -> impl Sized { + | ---------- returning this opaque type `impl Sized` + +error[E0720]: cannot resolve opaque type + --> $DIR/recursive-impl-trait-type-indirect.rs:95:28 + | +LL | fn mutual_recursion() -> impl Sync { + | --------- returning this opaque type `impl Sync` +... +LL | fn mutual_recursion_b() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type +LL | +LL | mutual_recursion() + | ------------------ returning here with type `impl Sync` + +error: aborting due to 14 previous errors + +For more information about this error, try `rustc --explain E0720`. diff --git a/tests/ui/impl-trait/recursive-impl-trait-type-indirect.rs b/tests/ui/impl-trait/recursive-impl-trait-type-indirect.rs index ffc0cd9d10c34..630372e13ed58 100644 --- a/tests/ui/impl-trait/recursive-impl-trait-type-indirect.rs +++ b/tests/ui/impl-trait/recursive-impl-trait-type-indirect.rs @@ -1,3 +1,7 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir + // Test that impl trait does not allow creating recursive types that are // otherwise forbidden. diff --git a/tests/ui/lint/must_not_suspend/dedup.drop_tracking.stderr b/tests/ui/lint/must_not_suspend/dedup.drop_tracking.stderr new file mode 100644 index 0000000000000..18880f5a757e0 --- /dev/null +++ b/tests/ui/lint/must_not_suspend/dedup.drop_tracking.stderr @@ -0,0 +1,19 @@ +error: `No` held across a suspend point, but should not be + --> $DIR/dedup.rs:19:13 + | +LL | wheeee(&No {}).await; + | ^^^^^ ------ the value is held across this suspend point + | +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/dedup.rs:19:13 + | +LL | wheeee(&No {}).await; + | ^^^^^ +note: the lint level is defined here + --> $DIR/dedup.rs:6:9 + | +LL | #![deny(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/lint/must_not_suspend/dedup.drop_tracking_mir.stderr b/tests/ui/lint/must_not_suspend/dedup.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..18880f5a757e0 --- /dev/null +++ b/tests/ui/lint/must_not_suspend/dedup.drop_tracking_mir.stderr @@ -0,0 +1,19 @@ +error: `No` held across a suspend point, but should not be + --> $DIR/dedup.rs:19:13 + | +LL | wheeee(&No {}).await; + | ^^^^^ ------ the value is held across this suspend point + | +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/dedup.rs:19:13 + | +LL | wheeee(&No {}).await; + | ^^^^^ +note: the lint level is defined here + --> $DIR/dedup.rs:6:9 + | +LL | #![deny(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/lint/must_not_suspend/dedup.no_drop_tracking.stderr b/tests/ui/lint/must_not_suspend/dedup.no_drop_tracking.stderr new file mode 100644 index 0000000000000..18880f5a757e0 --- /dev/null +++ b/tests/ui/lint/must_not_suspend/dedup.no_drop_tracking.stderr @@ -0,0 +1,19 @@ +error: `No` held across a suspend point, but should not be + --> $DIR/dedup.rs:19:13 + | +LL | wheeee(&No {}).await; + | ^^^^^ ------ the value is held across this suspend point + | +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/dedup.rs:19:13 + | +LL | wheeee(&No {}).await; + | ^^^^^ +note: the lint level is defined here + --> $DIR/dedup.rs:6:9 + | +LL | #![deny(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/lint/must_not_suspend/dedup.rs b/tests/ui/lint/must_not_suspend/dedup.rs index 81a08579bb7bc..6e49ee52bd944 100644 --- a/tests/ui/lint/must_not_suspend/dedup.rs +++ b/tests/ui/lint/must_not_suspend/dedup.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 #![feature(must_not_suspend)] #![deny(must_not_suspend)] diff --git a/tests/ui/lint/must_not_suspend/dedup.stderr b/tests/ui/lint/must_not_suspend/dedup.stderr index f8978ba57f15b..18880f5a757e0 100644 --- a/tests/ui/lint/must_not_suspend/dedup.stderr +++ b/tests/ui/lint/must_not_suspend/dedup.stderr @@ -1,16 +1,16 @@ error: `No` held across a suspend point, but should not be - --> $DIR/dedup.rs:16:13 + --> $DIR/dedup.rs:19:13 | LL | wheeee(&No {}).await; | ^^^^^ ------ the value is held across this suspend point | help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/dedup.rs:16:13 + --> $DIR/dedup.rs:19:13 | LL | wheeee(&No {}).await; | ^^^^^ note: the lint level is defined here - --> $DIR/dedup.rs:3:9 + --> $DIR/dedup.rs:6:9 | LL | #![deny(must_not_suspend)] | ^^^^^^^^^^^^^^^^ diff --git a/tests/ui/lint/must_not_suspend/ref.drop_tracking.stderr b/tests/ui/lint/must_not_suspend/ref.drop_tracking.stderr index abf76711bf04f..e3628ca5e4934 100644 --- a/tests/ui/lint/must_not_suspend/ref.drop_tracking.stderr +++ b/tests/ui/lint/must_not_suspend/ref.drop_tracking.stderr @@ -1,5 +1,5 @@ error: reference to `Umm` held across a suspend point, but should not be - --> $DIR/ref.rs:21:13 + --> $DIR/ref.rs:22:13 | LL | let guard = &mut self.u; | ^^^^^ @@ -8,17 +8,17 @@ LL | other().await; | ------ the value is held across this suspend point | note: You gotta use Umm's, ya know? - --> $DIR/ref.rs:21:13 + --> $DIR/ref.rs:22:13 | LL | let guard = &mut self.u; | ^^^^^ help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/ref.rs:21:13 + --> $DIR/ref.rs:22:13 | LL | let guard = &mut self.u; | ^^^^^ note: the lint level is defined here - --> $DIR/ref.rs:6:9 + --> $DIR/ref.rs:7:9 | LL | #![deny(must_not_suspend)] | ^^^^^^^^^^^^^^^^ diff --git a/tests/ui/lint/must_not_suspend/ref.drop_tracking_mir.stderr b/tests/ui/lint/must_not_suspend/ref.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..e9bfa08b5ddd9 --- /dev/null +++ b/tests/ui/lint/must_not_suspend/ref.drop_tracking_mir.stderr @@ -0,0 +1,27 @@ +error: `Umm` held across a suspend point, but should not be + --> $DIR/ref.rs:22:26 + | +LL | let guard = &mut self.u; + | ^^^^^^ +LL | +LL | other().await; + | ------ the value is held across this suspend point + | +note: You gotta use Umm's, ya know? + --> $DIR/ref.rs:22:26 + | +LL | let guard = &mut self.u; + | ^^^^^^ +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/ref.rs:22:26 + | +LL | let guard = &mut self.u; + | ^^^^^^ +note: the lint level is defined here + --> $DIR/ref.rs:7:9 + | +LL | #![deny(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/lint/must_not_suspend/ref.no_drop_tracking.stderr b/tests/ui/lint/must_not_suspend/ref.no_drop_tracking.stderr index 41ac09ea72aaa..e9bfa08b5ddd9 100644 --- a/tests/ui/lint/must_not_suspend/ref.no_drop_tracking.stderr +++ b/tests/ui/lint/must_not_suspend/ref.no_drop_tracking.stderr @@ -1,5 +1,5 @@ error: `Umm` held across a suspend point, but should not be - --> $DIR/ref.rs:21:26 + --> $DIR/ref.rs:22:26 | LL | let guard = &mut self.u; | ^^^^^^ @@ -8,17 +8,17 @@ LL | other().await; | ------ the value is held across this suspend point | note: You gotta use Umm's, ya know? - --> $DIR/ref.rs:21:26 + --> $DIR/ref.rs:22:26 | LL | let guard = &mut self.u; | ^^^^^^ help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/ref.rs:21:26 + --> $DIR/ref.rs:22:26 | LL | let guard = &mut self.u; | ^^^^^^ note: the lint level is defined here - --> $DIR/ref.rs:6:9 + --> $DIR/ref.rs:7:9 | LL | #![deny(must_not_suspend)] | ^^^^^^^^^^^^^^^^ diff --git a/tests/ui/lint/must_not_suspend/ref.rs b/tests/ui/lint/must_not_suspend/ref.rs index f6b23746fef13..8784ffbc63461 100644 --- a/tests/ui/lint/must_not_suspend/ref.rs +++ b/tests/ui/lint/must_not_suspend/ref.rs @@ -1,7 +1,8 @@ // edition:2018 -// revisions: no_drop_tracking drop_tracking -// [drop_tracking] compile-flags: -Zdrop-tracking=yes -// [no_drop_tracking] compile-flags: -Zdrop-tracking=no +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir + #![feature(must_not_suspend)] #![deny(must_not_suspend)] diff --git a/tests/ui/lint/must_not_suspend/trait.drop_tracking.stderr b/tests/ui/lint/must_not_suspend/trait.drop_tracking.stderr new file mode 100644 index 0000000000000..6e62a228a43a5 --- /dev/null +++ b/tests/ui/lint/must_not_suspend/trait.drop_tracking.stderr @@ -0,0 +1,37 @@ +error: implementer of `Wow` held across a suspend point, but should not be + --> $DIR/trait.rs:24:9 + | +LL | let _guard1 = r#impl(); + | ^^^^^^^ +... +LL | other().await; + | ------ the value is held across this suspend point + | +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/trait.rs:24:9 + | +LL | let _guard1 = r#impl(); + | ^^^^^^^ +note: the lint level is defined here + --> $DIR/trait.rs:6:9 + | +LL | #![deny(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +error: boxed `Wow` trait object held across a suspend point, but should not be + --> $DIR/trait.rs:25:9 + | +LL | let _guard2 = r#dyn(); + | ^^^^^^^ +LL | +LL | other().await; + | ------ the value is held across this suspend point + | +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/trait.rs:25:9 + | +LL | let _guard2 = r#dyn(); + | ^^^^^^^ + +error: aborting due to 2 previous errors + diff --git a/tests/ui/lint/must_not_suspend/trait.drop_tracking_mir.stderr b/tests/ui/lint/must_not_suspend/trait.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..6e62a228a43a5 --- /dev/null +++ b/tests/ui/lint/must_not_suspend/trait.drop_tracking_mir.stderr @@ -0,0 +1,37 @@ +error: implementer of `Wow` held across a suspend point, but should not be + --> $DIR/trait.rs:24:9 + | +LL | let _guard1 = r#impl(); + | ^^^^^^^ +... +LL | other().await; + | ------ the value is held across this suspend point + | +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/trait.rs:24:9 + | +LL | let _guard1 = r#impl(); + | ^^^^^^^ +note: the lint level is defined here + --> $DIR/trait.rs:6:9 + | +LL | #![deny(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +error: boxed `Wow` trait object held across a suspend point, but should not be + --> $DIR/trait.rs:25:9 + | +LL | let _guard2 = r#dyn(); + | ^^^^^^^ +LL | +LL | other().await; + | ------ the value is held across this suspend point + | +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/trait.rs:25:9 + | +LL | let _guard2 = r#dyn(); + | ^^^^^^^ + +error: aborting due to 2 previous errors + diff --git a/tests/ui/lint/must_not_suspend/trait.no_drop_tracking.stderr b/tests/ui/lint/must_not_suspend/trait.no_drop_tracking.stderr new file mode 100644 index 0000000000000..6e62a228a43a5 --- /dev/null +++ b/tests/ui/lint/must_not_suspend/trait.no_drop_tracking.stderr @@ -0,0 +1,37 @@ +error: implementer of `Wow` held across a suspend point, but should not be + --> $DIR/trait.rs:24:9 + | +LL | let _guard1 = r#impl(); + | ^^^^^^^ +... +LL | other().await; + | ------ the value is held across this suspend point + | +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/trait.rs:24:9 + | +LL | let _guard1 = r#impl(); + | ^^^^^^^ +note: the lint level is defined here + --> $DIR/trait.rs:6:9 + | +LL | #![deny(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +error: boxed `Wow` trait object held across a suspend point, but should not be + --> $DIR/trait.rs:25:9 + | +LL | let _guard2 = r#dyn(); + | ^^^^^^^ +LL | +LL | other().await; + | ------ the value is held across this suspend point + | +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/trait.rs:25:9 + | +LL | let _guard2 = r#dyn(); + | ^^^^^^^ + +error: aborting due to 2 previous errors + diff --git a/tests/ui/lint/must_not_suspend/trait.rs b/tests/ui/lint/must_not_suspend/trait.rs index 6c911cb4b0f09..b6ccae0d249bb 100644 --- a/tests/ui/lint/must_not_suspend/trait.rs +++ b/tests/ui/lint/must_not_suspend/trait.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 #![feature(must_not_suspend)] #![deny(must_not_suspend)] diff --git a/tests/ui/lint/must_not_suspend/trait.stderr b/tests/ui/lint/must_not_suspend/trait.stderr index d64d25aae5274..6e62a228a43a5 100644 --- a/tests/ui/lint/must_not_suspend/trait.stderr +++ b/tests/ui/lint/must_not_suspend/trait.stderr @@ -1,5 +1,5 @@ error: implementer of `Wow` held across a suspend point, but should not be - --> $DIR/trait.rs:21:9 + --> $DIR/trait.rs:24:9 | LL | let _guard1 = r#impl(); | ^^^^^^^ @@ -8,18 +8,18 @@ LL | other().await; | ------ the value is held across this suspend point | help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/trait.rs:21:9 + --> $DIR/trait.rs:24:9 | LL | let _guard1 = r#impl(); | ^^^^^^^ note: the lint level is defined here - --> $DIR/trait.rs:3:9 + --> $DIR/trait.rs:6:9 | LL | #![deny(must_not_suspend)] | ^^^^^^^^^^^^^^^^ error: boxed `Wow` trait object held across a suspend point, but should not be - --> $DIR/trait.rs:22:9 + --> $DIR/trait.rs:25:9 | LL | let _guard2 = r#dyn(); | ^^^^^^^ @@ -28,7 +28,7 @@ LL | other().await; | ------ the value is held across this suspend point | help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/trait.rs:22:9 + --> $DIR/trait.rs:25:9 | LL | let _guard2 = r#dyn(); | ^^^^^^^ diff --git a/tests/ui/lint/must_not_suspend/unit.drop_tracking.stderr b/tests/ui/lint/must_not_suspend/unit.drop_tracking.stderr new file mode 100644 index 0000000000000..50ca292c2f6fd --- /dev/null +++ b/tests/ui/lint/must_not_suspend/unit.drop_tracking.stderr @@ -0,0 +1,26 @@ +error: `Umm` held across a suspend point, but should not be + --> $DIR/unit.rs:23:9 + | +LL | let _guard = bar(); + | ^^^^^^ +LL | other().await; + | ------ the value is held across this suspend point + | +note: You gotta use Umm's, ya know? + --> $DIR/unit.rs:23:9 + | +LL | let _guard = bar(); + | ^^^^^^ +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/unit.rs:23:9 + | +LL | let _guard = bar(); + | ^^^^^^ +note: the lint level is defined here + --> $DIR/unit.rs:6:9 + | +LL | #![deny(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/lint/must_not_suspend/unit.drop_tracking_mir.stderr b/tests/ui/lint/must_not_suspend/unit.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..50ca292c2f6fd --- /dev/null +++ b/tests/ui/lint/must_not_suspend/unit.drop_tracking_mir.stderr @@ -0,0 +1,26 @@ +error: `Umm` held across a suspend point, but should not be + --> $DIR/unit.rs:23:9 + | +LL | let _guard = bar(); + | ^^^^^^ +LL | other().await; + | ------ the value is held across this suspend point + | +note: You gotta use Umm's, ya know? + --> $DIR/unit.rs:23:9 + | +LL | let _guard = bar(); + | ^^^^^^ +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/unit.rs:23:9 + | +LL | let _guard = bar(); + | ^^^^^^ +note: the lint level is defined here + --> $DIR/unit.rs:6:9 + | +LL | #![deny(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/lint/must_not_suspend/unit.no_drop_tracking.stderr b/tests/ui/lint/must_not_suspend/unit.no_drop_tracking.stderr new file mode 100644 index 0000000000000..50ca292c2f6fd --- /dev/null +++ b/tests/ui/lint/must_not_suspend/unit.no_drop_tracking.stderr @@ -0,0 +1,26 @@ +error: `Umm` held across a suspend point, but should not be + --> $DIR/unit.rs:23:9 + | +LL | let _guard = bar(); + | ^^^^^^ +LL | other().await; + | ------ the value is held across this suspend point + | +note: You gotta use Umm's, ya know? + --> $DIR/unit.rs:23:9 + | +LL | let _guard = bar(); + | ^^^^^^ +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/unit.rs:23:9 + | +LL | let _guard = bar(); + | ^^^^^^ +note: the lint level is defined here + --> $DIR/unit.rs:6:9 + | +LL | #![deny(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/lint/must_not_suspend/unit.rs b/tests/ui/lint/must_not_suspend/unit.rs index d3a19f704324d..8903f8a6d0597 100644 --- a/tests/ui/lint/must_not_suspend/unit.rs +++ b/tests/ui/lint/must_not_suspend/unit.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 #![feature(must_not_suspend)] #![deny(must_not_suspend)] diff --git a/tests/ui/lint/must_not_suspend/unit.stderr b/tests/ui/lint/must_not_suspend/unit.stderr index c967dbac56c2c..50ca292c2f6fd 100644 --- a/tests/ui/lint/must_not_suspend/unit.stderr +++ b/tests/ui/lint/must_not_suspend/unit.stderr @@ -1,5 +1,5 @@ error: `Umm` held across a suspend point, but should not be - --> $DIR/unit.rs:20:9 + --> $DIR/unit.rs:23:9 | LL | let _guard = bar(); | ^^^^^^ @@ -7,17 +7,17 @@ LL | other().await; | ------ the value is held across this suspend point | note: You gotta use Umm's, ya know? - --> $DIR/unit.rs:20:9 + --> $DIR/unit.rs:23:9 | LL | let _guard = bar(); | ^^^^^^ help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/unit.rs:20:9 + --> $DIR/unit.rs:23:9 | LL | let _guard = bar(); | ^^^^^^ note: the lint level is defined here - --> $DIR/unit.rs:3:9 + --> $DIR/unit.rs:6:9 | LL | #![deny(must_not_suspend)] | ^^^^^^^^^^^^^^^^ diff --git a/tests/ui/lint/must_not_suspend/warn.drop_tracking.stderr b/tests/ui/lint/must_not_suspend/warn.drop_tracking.stderr new file mode 100644 index 0000000000000..7a422891ab102 --- /dev/null +++ b/tests/ui/lint/must_not_suspend/warn.drop_tracking.stderr @@ -0,0 +1,26 @@ +warning: `Umm` held across a suspend point, but should not be + --> $DIR/warn.rs:24:9 + | +LL | let _guard = bar(); + | ^^^^^^ +LL | other().await; + | ------ the value is held across this suspend point + | +note: You gotta use Umm's, ya know? + --> $DIR/warn.rs:24:9 + | +LL | let _guard = bar(); + | ^^^^^^ +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/warn.rs:24:9 + | +LL | let _guard = bar(); + | ^^^^^^ +note: the lint level is defined here + --> $DIR/warn.rs:7:9 + | +LL | #![warn(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +warning: 1 warning emitted + diff --git a/tests/ui/lint/must_not_suspend/warn.drop_tracking_mir.stderr b/tests/ui/lint/must_not_suspend/warn.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..7a422891ab102 --- /dev/null +++ b/tests/ui/lint/must_not_suspend/warn.drop_tracking_mir.stderr @@ -0,0 +1,26 @@ +warning: `Umm` held across a suspend point, but should not be + --> $DIR/warn.rs:24:9 + | +LL | let _guard = bar(); + | ^^^^^^ +LL | other().await; + | ------ the value is held across this suspend point + | +note: You gotta use Umm's, ya know? + --> $DIR/warn.rs:24:9 + | +LL | let _guard = bar(); + | ^^^^^^ +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/warn.rs:24:9 + | +LL | let _guard = bar(); + | ^^^^^^ +note: the lint level is defined here + --> $DIR/warn.rs:7:9 + | +LL | #![warn(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +warning: 1 warning emitted + diff --git a/tests/ui/lint/must_not_suspend/warn.no_drop_tracking.stderr b/tests/ui/lint/must_not_suspend/warn.no_drop_tracking.stderr new file mode 100644 index 0000000000000..7a422891ab102 --- /dev/null +++ b/tests/ui/lint/must_not_suspend/warn.no_drop_tracking.stderr @@ -0,0 +1,26 @@ +warning: `Umm` held across a suspend point, but should not be + --> $DIR/warn.rs:24:9 + | +LL | let _guard = bar(); + | ^^^^^^ +LL | other().await; + | ------ the value is held across this suspend point + | +note: You gotta use Umm's, ya know? + --> $DIR/warn.rs:24:9 + | +LL | let _guard = bar(); + | ^^^^^^ +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/warn.rs:24:9 + | +LL | let _guard = bar(); + | ^^^^^^ +note: the lint level is defined here + --> $DIR/warn.rs:7:9 + | +LL | #![warn(must_not_suspend)] + | ^^^^^^^^^^^^^^^^ + +warning: 1 warning emitted + diff --git a/tests/ui/lint/must_not_suspend/warn.rs b/tests/ui/lint/must_not_suspend/warn.rs index 7fdea66a23517..b5002cb9f60a5 100644 --- a/tests/ui/lint/must_not_suspend/warn.rs +++ b/tests/ui/lint/must_not_suspend/warn.rs @@ -1,3 +1,6 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // edition:2018 // run-pass #![feature(must_not_suspend)] diff --git a/tests/ui/lint/must_not_suspend/warn.stderr b/tests/ui/lint/must_not_suspend/warn.stderr index fe551c6521d49..7a422891ab102 100644 --- a/tests/ui/lint/must_not_suspend/warn.stderr +++ b/tests/ui/lint/must_not_suspend/warn.stderr @@ -1,5 +1,5 @@ warning: `Umm` held across a suspend point, but should not be - --> $DIR/warn.rs:21:9 + --> $DIR/warn.rs:24:9 | LL | let _guard = bar(); | ^^^^^^ @@ -7,17 +7,17 @@ LL | other().await; | ------ the value is held across this suspend point | note: You gotta use Umm's, ya know? - --> $DIR/warn.rs:21:9 + --> $DIR/warn.rs:24:9 | LL | let _guard = bar(); | ^^^^^^ help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/warn.rs:21:9 + --> $DIR/warn.rs:24:9 | LL | let _guard = bar(); | ^^^^^^ note: the lint level is defined here - --> $DIR/warn.rs:4:9 + --> $DIR/warn.rs:7:9 | LL | #![warn(must_not_suspend)] | ^^^^^^^^^^^^^^^^ From 03618d6afddd851bfa0bec5dc038a5252c297478 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 11 Sep 2022 17:22:38 +0200 Subject: [PATCH 434/500] Always require Drop for generators. --- compiler/rustc_ty_utils/src/needs_drop.rs | 7 +++++++ .../borrowing.drop_tracking_mir.stderr | 20 +++++++++++++------ ...retain-resume-ref.drop_tracking_mir.stderr | 7 ++++--- 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index 0df060fc5fb71..f519ea01a2c9d 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -109,6 +109,13 @@ where for component in components { match *component.kind() { + // The information required to determine whether a generator has drop is + // computed on MIR, while this very method is used to build MIR. To avoid + // cycles, we consider that generators always require drop. + ty::Generator(..) if tcx.sess.opts.unstable_opts.drop_tracking_mir => { + return Some(Err(AlwaysRequiresDrop)); + } + _ if component.is_copy_modulo_regions(tcx, self.param_env) => (), ty::Closure(_, substs) => { diff --git a/tests/ui/generator/borrowing.drop_tracking_mir.stderr b/tests/ui/generator/borrowing.drop_tracking_mir.stderr index 96e3c327f8b31..8fbad276db441 100644 --- a/tests/ui/generator/borrowing.drop_tracking_mir.stderr +++ b/tests/ui/generator/borrowing.drop_tracking_mir.stderr @@ -1,16 +1,24 @@ error[E0597]: `a` does not live long enough --> $DIR/borrowing.rs:13:33 | -LL | let _b = { - | -- borrow later stored here -LL | let a = 3; LL | Pin::new(&mut || yield &a).resume(()) - | -- ^ borrowed value does not live long enough - | | + | ----------^ + | | | + | | borrowed value does not live long enough | value captured here by generator + | a temporary with access to the borrow is created here ... LL | LL | }; - | - `a` dropped here while still borrowed + | -- ... and the borrow might be used here, when that temporary is dropped and runs the destructor for generator + | | + | `a` dropped here while still borrowed + | + = note: the temporary is part of an expression at the end of a block; + consider forcing this temporary to be dropped sooner, before the block's local variables are dropped +help: for example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block + | +LL | let x = Pin::new(&mut || yield &a).resume(()); x + | +++++++ +++ error[E0597]: `a` does not live long enough --> $DIR/borrowing.rs:20:20 diff --git a/tests/ui/generator/retain-resume-ref.drop_tracking_mir.stderr b/tests/ui/generator/retain-resume-ref.drop_tracking_mir.stderr index 7122a951e8070..736ed1fb60803 100644 --- a/tests/ui/generator/retain-resume-ref.drop_tracking_mir.stderr +++ b/tests/ui/generator/retain-resume-ref.drop_tracking_mir.stderr @@ -4,9 +4,10 @@ error[E0499]: cannot borrow `thing` as mutable more than once at a time LL | gen.as_mut().resume(&mut thing); | ---------- first mutable borrow occurs here LL | gen.as_mut().resume(&mut thing); - | ------ ^^^^^^^^^^ second mutable borrow occurs here - | | - | first borrow later used by call + | ^^^^^^^^^^ second mutable borrow occurs here +LL | +LL | } + | - first borrow might be used here, when `gen` is dropped and runs the destructor for generator error: aborting due to previous error From 1974b6b68dc168cac046039ce404c8311c4d8765 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 1 Oct 2022 14:56:24 +0200 Subject: [PATCH 435/500] Introduce GeneratorWitnessMIR. --- .../src/debuginfo/type_names.rs | 1 + .../src/const_eval/valtrees.rs | 3 +- .../src/interpret/intrinsics.rs | 1 + .../src/interpret/validity.rs | 1 + .../rustc_const_eval/src/util/type_name.rs | 1 + .../src/coherence/inherent_impls.rs | 1 + .../src/variance/constraints.rs | 12 +-- compiler/rustc_hir_typeck/src/cast.rs | 1 + .../src/infer/canonical/canonicalizer.rs | 1 + compiler/rustc_infer/src/infer/freshen.rs | 1 + .../src/infer/outlives/components.rs | 2 +- compiler/rustc_lint/src/types.rs | 1 + compiler/rustc_middle/src/ty/context.rs | 6 ++ compiler/rustc_middle/src/ty/error.rs | 5 +- compiler/rustc_middle/src/ty/fast_reject.rs | 8 +- compiler/rustc_middle/src/ty/flags.rs | 10 ++ compiler/rustc_middle/src/ty/layout.rs | 1 + compiler/rustc_middle/src/ty/opaque_types.rs | 95 ++++++++++--------- compiler/rustc_middle/src/ty/print/mod.rs | 1 + compiler/rustc_middle/src/ty/print/pretty.rs | 22 +++++ compiler/rustc_middle/src/ty/relate.rs | 10 ++ .../rustc_middle/src/ty/structural_impls.rs | 4 + compiler/rustc_middle/src/ty/sty.rs | 5 +- compiler/rustc_middle/src/ty/util.rs | 14 ++- compiler/rustc_middle/src/ty/visit.rs | 3 + compiler/rustc_middle/src/ty/walk.rs | 1 + compiler/rustc_privacy/src/lib.rs | 3 +- .../src/typeid/typeid_itanium_cxx_abi.rs | 2 + compiler/rustc_symbol_mangling/src/v0.rs | 1 + .../src/solve/assembly.rs | 2 + .../src/solve/project_goals.rs | 1 + .../solve/trait_goals/structural_traits.rs | 6 ++ .../src/traits/coherence.rs | 4 +- .../src/traits/error_reporting/mod.rs | 1 + .../src/traits/project.rs | 2 + .../src/traits/query/dropck_outlives.rs | 1 + .../src/traits/select/candidate_assembly.rs | 4 +- .../src/traits/select/confirmation.rs | 3 + .../src/traits/select/mod.rs | 9 ++ .../src/traits/structural_match.rs | 2 +- .../rustc_trait_selection/src/traits/wf.rs | 1 + compiler/rustc_traits/src/chalk/lowering.rs | 1 + compiler/rustc_traits/src/dropck_outlives.rs | 3 +- compiler/rustc_ty_utils/src/layout.rs | 5 +- compiler/rustc_ty_utils/src/ty.rs | 8 +- compiler/rustc_type_ir/src/lib.rs | 3 + compiler/rustc_type_ir/src/sty.rs | 53 +++++++++++ src/librustdoc/clean/mod.rs | 1 + .../passes/collect_intra_doc_links.rs | 1 + .../clippy/clippy_lints/src/dereference.rs | 1 + tests/ui/symbol-names/basic.legacy.stderr | 4 +- .../ui/symbol-names/issue-60925.legacy.stderr | 4 +- 52 files changed, 265 insertions(+), 72 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index 1599ccbb2594c..b0e007ce0097b 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -414,6 +414,7 @@ fn push_debuginfo_type_name<'tcx>( | ty::Placeholder(..) | ty::Alias(..) | ty::Bound(..) + | ty::GeneratorWitnessMIR(..) | ty::GeneratorWitness(..) => { bug!( "debuginfo: Trying to create type name for \ diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index 498c008738793..c52886b77e64b 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -151,7 +151,7 @@ pub(crate) fn const_to_valtree_inner<'tcx>( // FIXME(oli-obk): we can probably encode closures just like structs | ty::Closure(..) | ty::Generator(..) - | ty::GeneratorWitness(..) => Err(ValTreeCreationError::NonSupportedType), + | ty::GeneratorWitness(..) |ty::GeneratorWitnessMIR(..)=> Err(ValTreeCreationError::NonSupportedType), } } @@ -314,6 +314,7 @@ pub fn valtree_to_const_value<'tcx>( | ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::FnPtr(_) | ty::RawPtr(_) | ty::Str diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index f87e4fbc1a178..907f014dfb518 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -101,6 +101,7 @@ pub(crate) fn eval_nullary_intrinsic<'tcx>( | ty::Closure(_, _) | ty::Generator(_, _, _) | ty::GeneratorWitness(_) + | ty::GeneratorWitnessMIR(_, _) | ty::Never | ty::Tuple(_) | ty::Error(_) => ConstValue::from_machine_usize(0u64, &tcx), diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 19e359986a12e..aa539516d5e50 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -602,6 +602,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' | ty::Bound(..) | ty::Param(..) | ty::Alias(..) + | ty::GeneratorWitnessMIR(..) | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty), } } diff --git a/compiler/rustc_const_eval/src/util/type_name.rs b/compiler/rustc_const_eval/src/util/type_name.rs index c4122f6649814..4e80a28518668 100644 --- a/compiler/rustc_const_eval/src/util/type_name.rs +++ b/compiler/rustc_const_eval/src/util/type_name.rs @@ -64,6 +64,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { ty::Foreign(def_id) => self.print_def_path(def_id, &[]), ty::GeneratorWitness(_) => bug!("type_name: unexpected `GeneratorWitness`"), + ty::GeneratorWitnessMIR(..) => bug!("type_name: unexpected `GeneratorWitnessMIR`"), } } diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs index dfb9824094346..c1b0237b2d1f1 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs @@ -240,6 +240,7 @@ impl<'tcx> InherentCollect<'tcx> { | ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => { diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index 2cd2b6a5f7631..a1872822d365a 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -295,12 +295,12 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { // types, where we use Error as the Self type } - ty::Placeholder(..) | ty::GeneratorWitness(..) | ty::Bound(..) | ty::Infer(..) => { - bug!( - "unexpected type encountered in \ - variance inference: {}", - ty - ); + ty::Placeholder(..) + | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) + | ty::Bound(..) + | ty::Infer(..) => { + bug!("unexpected type encountered in variance inference: {}", ty); } } } diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index 712f9b87aed0a..8e21c084841d0 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -130,6 +130,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { | ty::Float(_) | ty::Array(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::RawPtr(_) | ty::Ref(..) | ty::FnDef(..) diff --git a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index 091635e6c73c0..87c6dfad5fa2b 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -435,6 +435,7 @@ impl<'cx, 'tcx> TypeFolder<'tcx> for Canonicalizer<'cx, 'tcx> { ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Bool | ty::Char | ty::Int(..) diff --git a/compiler/rustc_infer/src/infer/freshen.rs b/compiler/rustc_infer/src/infer/freshen.rs index 8f53b1ccdf458..83d71edc2abd9 100644 --- a/compiler/rustc_infer/src/infer/freshen.rs +++ b/compiler/rustc_infer/src/infer/freshen.rs @@ -209,6 +209,7 @@ impl<'a, 'tcx> TypeFolder<'tcx> for TypeFreshener<'a, 'tcx> { | ty::Foreign(..) | ty::Param(..) | ty::Closure(..) + | ty::GeneratorWitnessMIR(..) | ty::GeneratorWitness(..) => t.super_fold_with(self), ty::Placeholder(..) | ty::Bound(..) => bug!("unexpected type {:?}", t), diff --git a/compiler/rustc_infer/src/infer/outlives/components.rs b/compiler/rustc_infer/src/infer/outlives/components.rs index 3d86279b03cc6..e3d9566917125 100644 --- a/compiler/rustc_infer/src/infer/outlives/components.rs +++ b/compiler/rustc_infer/src/infer/outlives/components.rs @@ -112,7 +112,7 @@ fn compute_components<'tcx>( } // All regions are bound inside a witness - ty::GeneratorWitness(..) => (), + ty::GeneratorWitness(..) | ty::GeneratorWitnessMIR(..) => (), // OutlivesTypeParameterEnv -- the actual checking that `X:'a` // is implied by the environment is done in regionck. diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 9be4b577aeb10..c32aeaa872236 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1107,6 +1107,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { | ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Placeholder(..) | ty::FnDef(..) => bug!("unexpected type in foreign function: {:?}", ty), } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index a60c55e8af4d2..c680eeb1fdaf0 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1306,6 +1306,7 @@ impl<'tcx> TyCtxt<'tcx> { Placeholder, Generator, GeneratorWitness, + GeneratorWitnessMIR, Dynamic, Closure, Tuple, @@ -1815,6 +1816,11 @@ impl<'tcx> TyCtxt<'tcx> { self.mk_mut_ref(self.lifetimes.re_erased, context_ty) } + #[inline] + pub fn mk_generator_witness_mir(self, id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { + self.mk_ty(GeneratorWitnessMIR(id, substs)) + } + #[inline] pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> { self.mk_ty_infer(TyVar(v)) diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index c8a700c4e280d..d83fc95ac4eeb 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -325,7 +325,8 @@ impl<'tcx> Ty<'tcx> { ty::Dynamic(..) => "trait object".into(), ty::Closure(..) => "closure".into(), ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(), - ty::GeneratorWitness(..) => "generator witness".into(), + ty::GeneratorWitness(..) | + ty::GeneratorWitnessMIR(..) => "generator witness".into(), ty::Tuple(..) => "tuple".into(), ty::Infer(ty::TyVar(_)) => "inferred type".into(), ty::Infer(ty::IntVar(_)) => "integer".into(), @@ -373,7 +374,7 @@ impl<'tcx> Ty<'tcx> { ty::Dynamic(..) => "trait object".into(), ty::Closure(..) => "closure".into(), ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(), - ty::GeneratorWitness(..) => "generator witness".into(), + ty::GeneratorWitness(..) | ty::GeneratorWitnessMIR(..) => "generator witness".into(), ty::Tuple(..) => "tuple".into(), ty::Placeholder(..) => "higher-ranked type".into(), ty::Bound(..) => "bound type variable".into(), diff --git a/compiler/rustc_middle/src/ty/fast_reject.rs b/compiler/rustc_middle/src/ty/fast_reject.rs index f785fb5c4b9be..9afa37e9ef3ee 100644 --- a/compiler/rustc_middle/src/ty/fast_reject.rs +++ b/compiler/rustc_middle/src/ty/fast_reject.rs @@ -32,6 +32,7 @@ pub enum SimplifiedType { ClosureSimplifiedType(DefId), GeneratorSimplifiedType(DefId), GeneratorWitnessSimplifiedType(usize), + GeneratorWitnessMIRSimplifiedType(DefId), FunctionSimplifiedType(usize), PlaceholderSimplifiedType, } @@ -108,6 +109,7 @@ pub fn simplify_type<'tcx>( ty::FnDef(def_id, _) | ty::Closure(def_id, _) => Some(ClosureSimplifiedType(def_id)), ty::Generator(def_id, _, _) => Some(GeneratorSimplifiedType(def_id)), ty::GeneratorWitness(tys) => Some(GeneratorWitnessSimplifiedType(tys.skip_binder().len())), + ty::GeneratorWitnessMIR(def_id, _) => Some(GeneratorWitnessMIRSimplifiedType(def_id)), ty::Never => Some(NeverSimplifiedType), ty::Tuple(tys) => Some(TupleSimplifiedType(tys.len())), ty::FnPtr(f) => Some(FunctionSimplifiedType(f.skip_binder().inputs().len())), @@ -139,7 +141,8 @@ impl SimplifiedType { | ForeignSimplifiedType(d) | TraitSimplifiedType(d) | ClosureSimplifiedType(d) - | GeneratorSimplifiedType(d) => Some(d), + | GeneratorSimplifiedType(d) + | GeneratorWitnessMIRSimplifiedType(d) => Some(d), _ => None, } } @@ -208,6 +211,7 @@ impl DeepRejectCtxt { | ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => bug!("unexpected impl_ty: {impl_ty}"), @@ -306,7 +310,7 @@ impl DeepRejectCtxt { ty::Error(_) => true, - ty::GeneratorWitness(..) | ty::Bound(..) => { + ty::GeneratorWitness(..) | ty::GeneratorWitnessMIR(..) | ty::Bound(..) => { bug!("unexpected obligation type: {:?}", obligation_ty) } } diff --git a/compiler/rustc_middle/src/ty/flags.rs b/compiler/rustc_middle/src/ty/flags.rs index b7eafc4b43738..dc6f5851b7d88 100644 --- a/compiler/rustc_middle/src/ty/flags.rs +++ b/compiler/rustc_middle/src/ty/flags.rs @@ -125,6 +125,16 @@ impl FlagComputation { self.bound_computation(ts, |flags, ts| flags.add_tys(ts)); } + &ty::GeneratorWitnessMIR(_, ref substs) => { + let should_remove_further_specializable = + !self.flags.contains(TypeFlags::STILL_FURTHER_SPECIALIZABLE); + self.add_substs(substs); + if should_remove_further_specializable { + self.flags -= TypeFlags::STILL_FURTHER_SPECIALIZABLE; + } + self.add_flags(TypeFlags::HAS_TY_GENERATOR); + } + &ty::Closure(_, substs) => { let substs = substs.as_closure(); let should_remove_further_specializable = diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 66b9d96e69577..cdcd6281f209b 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -645,6 +645,7 @@ where | ty::Never | ty::FnDef(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Foreign(..) | ty::Dynamic(_, _, ty::Dyn) => { bug!("TyAndLayout::field({:?}): not applicable", this) diff --git a/compiler/rustc_middle/src/ty/opaque_types.rs b/compiler/rustc_middle/src/ty/opaque_types.rs index 98cd92007c2b2..7ff58f02623dc 100644 --- a/compiler/rustc_middle/src/ty/opaque_types.rs +++ b/compiler/rustc_middle/src/ty/opaque_types.rs @@ -3,6 +3,7 @@ use crate::ty::fold::{TypeFolder, TypeSuperFoldable}; use crate::ty::subst::{GenericArg, GenericArgKind}; use crate::ty::{self, Ty, TyCtxt, TypeFoldable}; use rustc_data_structures::fx::FxHashMap; +use rustc_span::def_id::DefId; use rustc_span::Span; /// Converts generic params of a TypeFoldable from one @@ -47,6 +48,47 @@ impl<'tcx> ReverseMapper<'tcx> { assert!(!self.do_not_error); kind.fold_with(self) } + + fn fold_closure_substs( + &mut self, + def_id: DefId, + substs: ty::SubstsRef<'tcx>, + ) -> ty::SubstsRef<'tcx> { + // I am a horrible monster and I pray for death. When + // we encounter a closure here, it is always a closure + // from within the function that we are currently + // type-checking -- one that is now being encapsulated + // in an opaque type. Ideally, we would + // go through the types/lifetimes that it references + // and treat them just like we would any other type, + // which means we would error out if we find any + // reference to a type/region that is not in the + // "reverse map". + // + // **However,** in the case of closures, there is a + // somewhat subtle (read: hacky) consideration. The + // problem is that our closure types currently include + // all the lifetime parameters declared on the + // enclosing function, even if they are unused by the + // closure itself. We can't readily filter them out, + // so here we replace those values with `'empty`. This + // can't really make a difference to the rest of the + // compiler; those regions are ignored for the + // outlives relation, and hence don't affect trait + // selection or auto traits, and they are erased + // during codegen. + + let generics = self.tcx.generics_of(def_id); + self.tcx.mk_substs(substs.iter().enumerate().map(|(index, kind)| { + if index < generics.parent_count { + // Accommodate missing regions in the parent kinds... + self.fold_kind_no_missing_regions_error(kind) + } else { + // ...but not elsewhere. + self.fold_kind_normally(kind) + } + })) + } } impl<'tcx> TypeFolder<'tcx> for ReverseMapper<'tcx> { @@ -104,59 +146,20 @@ impl<'tcx> TypeFolder<'tcx> for ReverseMapper<'tcx> { fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { match *ty.kind() { ty::Closure(def_id, substs) => { - // I am a horrible monster and I pray for death. When - // we encounter a closure here, it is always a closure - // from within the function that we are currently - // type-checking -- one that is now being encapsulated - // in an opaque type. Ideally, we would - // go through the types/lifetimes that it references - // and treat them just like we would any other type, - // which means we would error out if we find any - // reference to a type/region that is not in the - // "reverse map". - // - // **However,** in the case of closures, there is a - // somewhat subtle (read: hacky) consideration. The - // problem is that our closure types currently include - // all the lifetime parameters declared on the - // enclosing function, even if they are unused by the - // closure itself. We can't readily filter them out, - // so here we replace those values with `'empty`. This - // can't really make a difference to the rest of the - // compiler; those regions are ignored for the - // outlives relation, and hence don't affect trait - // selection or auto traits, and they are erased - // during codegen. - - let generics = self.tcx.generics_of(def_id); - let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, kind)| { - if index < generics.parent_count { - // Accommodate missing regions in the parent kinds... - self.fold_kind_no_missing_regions_error(kind) - } else { - // ...but not elsewhere. - self.fold_kind_normally(kind) - } - })); - + let substs = self.fold_closure_substs(def_id, substs); self.tcx.mk_closure(def_id, substs) } ty::Generator(def_id, substs, movability) => { - let generics = self.tcx.generics_of(def_id); - let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, kind)| { - if index < generics.parent_count { - // Accommodate missing regions in the parent kinds... - self.fold_kind_no_missing_regions_error(kind) - } else { - // ...but not elsewhere. - self.fold_kind_normally(kind) - } - })); - + let substs = self.fold_closure_substs(def_id, substs); self.tcx.mk_generator(def_id, substs, movability) } + ty::GeneratorWitnessMIR(def_id, substs) => { + let substs = self.fold_closure_substs(def_id, substs); + self.tcx.mk_generator_witness_mir(def_id, substs) + } + ty::Param(param) => { // Look it up in the substitution list. match self.map.get(&ty.into()).map(|k| k.unpack()) { diff --git a/compiler/rustc_middle/src/ty/print/mod.rs b/compiler/rustc_middle/src/ty/print/mod.rs index c302c461195aa..90bf3288ccf54 100644 --- a/compiler/rustc_middle/src/ty/print/mod.rs +++ b/compiler/rustc_middle/src/ty/print/mod.rs @@ -265,6 +265,7 @@ fn characteristic_def_id_of_type_cached<'a>( ty::FnDef(def_id, _) | ty::Closure(def_id, _) | ty::Generator(def_id, _, _) + | ty::GeneratorWitnessMIR(def_id, _) | ty::Foreign(def_id) => Some(def_id), ty::Bool diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 2f30dbebbc22c..f2abec216b7b3 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -811,6 +811,28 @@ pub trait PrettyPrinter<'tcx>: ty::GeneratorWitness(types) => { p!(in_binder(&types)); } + ty::GeneratorWitnessMIR(did, substs) => { + p!(write("[")); + if !self.tcx().sess.verbose() { + p!("generator witness"); + // FIXME(eddyb) should use `def_span`. + if let Some(did) = did.as_local() { + let span = self.tcx().def_span(did); + p!(write( + "@{}", + // This may end up in stderr diagnostics but it may also be emitted + // into MIR. Hence we use the remapped path if available + self.tcx().sess.source_map().span_to_embeddable_string(span) + )); + } else { + p!(write("@"), print_def_path(did, substs)); + } + } else { + p!(print_def_path(did, substs)); + } + + p!("]") + } ty::Closure(did, substs) => { p!(write("[")); if !self.should_print_verbose() { diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index 65fd8d9753de1..7122e864cf231 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -473,6 +473,16 @@ pub fn super_relate_tys<'tcx, R: TypeRelation<'tcx>>( Ok(tcx.mk_generator_witness(types)) } + (&ty::GeneratorWitnessMIR(a_id, a_substs), &ty::GeneratorWitnessMIR(b_id, b_substs)) + if a_id == b_id => + { + // All GeneratorWitness types with the same id represent + // the (anonymous) type of the same generator expression. So + // all of their regions should be equated. + let substs = relation.relate(a_substs, b_substs)?; + Ok(tcx.mk_generator_witness_mir(a_id, substs)) + } + (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => { // All Closure types with the same id represent // the (anonymous) type of the same closure expression. So diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 16915443ba818..034aab0c38ea3 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -656,6 +656,9 @@ impl<'tcx> TypeSuperFoldable<'tcx> for Ty<'tcx> { ty::Generator(did, substs.try_fold_with(folder)?, movability) } ty::GeneratorWitness(types) => ty::GeneratorWitness(types.try_fold_with(folder)?), + ty::GeneratorWitnessMIR(did, substs) => { + ty::GeneratorWitnessMIR(did, substs.try_fold_with(folder)?) + } ty::Closure(did, substs) => ty::Closure(did, substs.try_fold_with(folder)?), ty::Alias(kind, data) => ty::Alias(kind, data.try_fold_with(folder)?), @@ -701,6 +704,7 @@ impl<'tcx> TypeSuperVisitable<'tcx> for Ty<'tcx> { } ty::Generator(_did, ref substs, _) => substs.visit_with(visitor), ty::GeneratorWitness(ref types) => types.visit_with(visitor), + ty::GeneratorWitnessMIR(_did, ref substs) => substs.visit_with(visitor), ty::Closure(_did, ref substs) => substs.visit_with(visitor), ty::Alias(_, ref data) => data.visit_with(visitor), diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 0656c77d0b51c..eba65e34023a9 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -2175,6 +2175,7 @@ impl<'tcx> Ty<'tcx> { | ty::Dynamic(..) | ty::Closure(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Never | ty::Tuple(_) | ty::Error(_) @@ -2210,6 +2211,7 @@ impl<'tcx> Ty<'tcx> { | ty::Ref(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Array(..) | ty::Closure(..) | ty::Never @@ -2296,6 +2298,7 @@ impl<'tcx> Ty<'tcx> { | ty::Ref(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Array(..) | ty::Closure(..) | ty::Never @@ -2360,7 +2363,7 @@ impl<'tcx> Ty<'tcx> { // anything with custom metadata it might be more complicated. ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => false, - ty::Generator(..) | ty::GeneratorWitness(..) => false, + ty::Generator(..) | ty::GeneratorWitness(..) | ty::GeneratorWitnessMIR(..) => false, // Might be, but not "trivial" so just giving the safe answer. ty::Adt(..) | ty::Closure(..) => false, diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 54ea63bb4cff7..3ed3b9f09459d 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -896,6 +896,7 @@ impl<'tcx> Ty<'tcx> { | ty::Foreign(_) | ty::Generator(..) | ty::GeneratorWitness(_) + | ty::GeneratorWitnessMIR(..) | ty::Infer(_) | ty::Alias(..) | ty::Param(_) @@ -935,6 +936,7 @@ impl<'tcx> Ty<'tcx> { | ty::Foreign(_) | ty::Generator(..) | ty::GeneratorWitness(_) + | ty::GeneratorWitnessMIR(..) | ty::Infer(_) | ty::Alias(..) | ty::Param(_) @@ -1062,7 +1064,10 @@ impl<'tcx> Ty<'tcx> { false } - ty::Foreign(_) | ty::GeneratorWitness(..) | ty::Error(_) => false, + ty::Foreign(_) + | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) + | ty::Error(_) => false, } } @@ -1158,6 +1163,7 @@ pub fn needs_drop_components<'tcx>( | ty::FnPtr(_) | ty::Char | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::RawPtr(_) | ty::Ref(..) | ty::Str => Ok(SmallVec::new()), @@ -1228,7 +1234,11 @@ pub fn is_trivially_const_drop(ty: Ty<'_>) -> bool { // Not trivial because they have components, and instead of looking inside, // we'll just perform trait selection. - ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(_) | ty::Adt(..) => false, + ty::Closure(..) + | ty::Generator(..) + | ty::GeneratorWitness(_) + | ty::GeneratorWitnessMIR(..) + | ty::Adt(..) => false, ty::Array(ty, _) | ty::Slice(ty) => is_trivially_const_drop(ty), diff --git a/compiler/rustc_middle/src/ty/visit.rs b/compiler/rustc_middle/src/ty/visit.rs index bee3cc4d7cb9b..d7b7a09473726 100644 --- a/compiler/rustc_middle/src/ty/visit.rs +++ b/compiler/rustc_middle/src/ty/visit.rs @@ -100,6 +100,9 @@ pub trait TypeVisitable<'tcx>: fmt::Debug + Clone { fn has_opaque_types(&self) -> bool { self.has_type_flags(TypeFlags::HAS_TY_OPAQUE) } + fn has_generators(&self) -> bool { + self.has_type_flags(TypeFlags::HAS_TY_GENERATOR) + } fn references_error(&self) -> bool { self.has_type_flags(TypeFlags::HAS_ERROR) } diff --git a/compiler/rustc_middle/src/ty/walk.rs b/compiler/rustc_middle/src/ty/walk.rs index 708a5e4d059e8..182945b9c3db1 100644 --- a/compiler/rustc_middle/src/ty/walk.rs +++ b/compiler/rustc_middle/src/ty/walk.rs @@ -190,6 +190,7 @@ fn push_inner<'tcx>(stack: &mut TypeWalkerStack<'tcx>, parent: GenericArg<'tcx>) ty::Adt(_, substs) | ty::Closure(_, substs) | ty::Generator(_, substs, _) + | ty::GeneratorWitnessMIR(_, substs) | ty::FnDef(_, substs) => { stack.extend(substs.iter().rev()); } diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index e969bb6db9ec4..59972b2e408bc 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -271,7 +271,8 @@ where | ty::FnPtr(..) | ty::Param(..) | ty::Error(_) - | ty::GeneratorWitness(..) => {} + | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) => {} ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => { bug!("unexpected type: {:?}", ty) } diff --git a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs index 0759b95bd94c8..c9b4ab0a38d6e 100644 --- a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs +++ b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs @@ -640,6 +640,7 @@ fn encode_ty<'tcx>( ty::Bound(..) | ty::Error(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Infer(..) | ty::Alias(..) | ty::Param(..) @@ -793,6 +794,7 @@ fn transform_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, options: TransformTyOptio ty::Bound(..) | ty::Error(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Infer(..) | ty::Alias(..) | ty::Param(..) diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 0d446d654dc5c..00d1ff5ceedf7 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -490,6 +490,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { } ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"), + ty::GeneratorWitnessMIR(..) => bug!("symbol_names: unexpected `GeneratorWitnessMIR`"), } // Only cache types that do not refer to an enclosing diff --git a/compiler/rustc_trait_selection/src/solve/assembly.rs b/compiler/rustc_trait_selection/src/solve/assembly.rs index d23b550621e17..0c18fc355e9ed 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly.rs @@ -331,6 +331,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { | ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(_) + | ty::GeneratorWitnessMIR(..) | ty::Never | ty::Tuple(_) | ty::Param(_) @@ -382,6 +383,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { | ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(_) + | ty::GeneratorWitnessMIR(..) | ty::Never | ty::Tuple(_) | ty::Param(_) diff --git a/compiler/rustc_trait_selection/src/solve/project_goals.rs b/compiler/rustc_trait_selection/src/solve/project_goals.rs index b583705ac4369..b4626f492bc15 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals.rs @@ -414,6 +414,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Never | ty::Foreign(..) => tcx.types.unit, diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs b/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs index 6cab0bc6a4b25..5007a019e1892 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals/structural_traits.rs @@ -57,6 +57,8 @@ pub(super) fn instantiate_constituent_tys_for_auto_trait<'tcx>( Ok(infcx.replace_bound_vars_with_placeholders(types).to_vec()) } + ty::GeneratorWitnessMIR(..) => todo!(), + // For `PhantomData`, we pass `T`. ty::Adt(def, substs) if def.is_phantom_data() => Ok(vec![substs.type_at(0)]), @@ -88,6 +90,7 @@ pub(super) fn instantiate_constituent_tys_for_sized_trait<'tcx>( | ty::Ref(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Array(..) | ty::Closure(..) | ty::Never @@ -173,6 +176,8 @@ pub(super) fn instantiate_constituent_tys_for_copy_clone_trait<'tcx>( ty::GeneratorWitness(types) => { Ok(infcx.replace_bound_vars_with_placeholders(types).to_vec()) } + + ty::GeneratorWitnessMIR(..) => todo!(), } } @@ -215,6 +220,7 @@ pub(crate) fn extract_tupled_inputs_and_output_from_callable<'tcx>( | ty::Dynamic(_, _, _) | ty::Generator(_, _, _) | ty::GeneratorWitness(_) + | ty::GeneratorWitnessMIR(..) | ty::Never | ty::Tuple(_) | ty::Alias(_, _) diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index ecee0bf7a6d1b..61f508a7a0750 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -696,7 +696,9 @@ impl<'tcx> TypeVisitor<'tcx> for OrphanChecker<'tcx> { // This should only be created when checking whether we have to check whether some // auto trait impl applies. There will never be multiple impls, so we can just // act as if it were a local type here. - ty::GeneratorWitness(_) => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)), + ty::GeneratorWitness(_) | ty::GeneratorWitnessMIR(..) => { + ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)) + } ty::Alias(ty::Opaque, ..) => { // This merits some explanation. // Normally, opaque types are not involved when performing diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index b167b9b566d6d..e9842b2cba516 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -1919,6 +1919,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ty::Generator(..) => Some(16), ty::Foreign(..) => Some(17), ty::GeneratorWitness(..) => Some(18), + ty::GeneratorWitnessMIR(..) => Some(19), ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None, } } diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index fbc7eccedc883..a11c5e8196952 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -1605,6 +1605,7 @@ fn assemble_candidates_from_impls<'cx, 'tcx>( | ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Never | ty::Tuple(..) // Integers and floats always have `u8` as their discriminant. @@ -1654,6 +1655,7 @@ fn assemble_candidates_from_impls<'cx, 'tcx>( | ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Never // Extern types have unit metadata, according to RFC 2850 | ty::Foreign(_) diff --git a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs index 0f21813bc40ae..455b53bfb7d8f 100644 --- a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs @@ -31,6 +31,7 @@ pub fn trivial_dropck_outlives<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { | ty::FnPtr(_) | ty::Char | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::RawPtr(_) | ty::Ref(..) | ty::Str diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 87d574ff107b2..52f4d29181d29 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -765,7 +765,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { | ty::Closure(..) | ty::Generator(..) | ty::Tuple(_) - | ty::GeneratorWitness(_) => { + | ty::GeneratorWitness(_) + | ty::GeneratorWitnessMIR(..) => { // These are built-in, and cannot have a custom `impl const Destruct`. candidates.vec.push(ConstDestructCandidate(None)); } @@ -826,6 +827,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { | ty::Closure(_, _) | ty::Generator(_, _, _) | ty::GeneratorWitness(_) + | ty::GeneratorWitnessMIR(..) | ty::Never | ty::Alias(..) | ty::Param(_) diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 82a59831be30a..996a33cdd689a 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -1285,6 +1285,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::GeneratorWitness(tys) => { stack.extend(tcx.erase_late_bound_regions(tys).to_vec()); } + ty::GeneratorWitnessMIR(..) => { + todo!() + } // If we have a projection type, make sure to normalize it so we replace it // with a fresh infer variable diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 1d23634b6aacf..ba62d99f01a6c 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2066,6 +2066,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { | ty::Ref(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Array(..) | ty::Closure(..) | ty::Never @@ -2182,6 +2183,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { Where(ty::Binder::bind_with_vars(witness_tys.to_vec(), all_vars)) } + ty::GeneratorWitnessMIR(..) => { + todo!() + } + ty::Closure(_, substs) => { // (*) binder moved here let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty()); @@ -2279,6 +2284,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { types.map_bound(|types| types.to_vec()) } + ty::GeneratorWitnessMIR(..) => { + todo!() + } + // For `PhantomData`, we pass `T`. ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()), diff --git a/compiler/rustc_trait_selection/src/traits/structural_match.rs b/compiler/rustc_trait_selection/src/traits/structural_match.rs index f398fb06c187a..69b965f3a389a 100644 --- a/compiler/rustc_trait_selection/src/traits/structural_match.rs +++ b/compiler/rustc_trait_selection/src/traits/structural_match.rs @@ -101,7 +101,7 @@ impl<'tcx> TypeVisitor<'tcx> for Search<'tcx> { ty::Closure(..) => { return ControlFlow::Break(ty); } - ty::Generator(..) | ty::GeneratorWitness(..) => { + ty::Generator(..) | ty::GeneratorWitness(..) | ty::GeneratorWitnessMIR(..) => { return ControlFlow::Break(ty); } ty::FnDef(..) => { diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 767e31ddf781a..7c5e147a950f1 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -551,6 +551,7 @@ impl<'tcx> WfPredicates<'tcx> { | ty::Error(_) | ty::Str | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Never | ty::Param(_) | ty::Bound(..) diff --git a/compiler/rustc_traits/src/chalk/lowering.rs b/compiler/rustc_traits/src/chalk/lowering.rs index 9712abb708f27..3a25410516209 100644 --- a/compiler/rustc_traits/src/chalk/lowering.rs +++ b/compiler/rustc_traits/src/chalk/lowering.rs @@ -343,6 +343,7 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::Ty>> for Ty<'tcx> { substs.lower_into(interner), ), ty::GeneratorWitness(_) => unimplemented!(), + ty::GeneratorWitnessMIR(..) => unimplemented!(), ty::Never => chalk_ir::TyKind::Never, ty::Tuple(types) => { chalk_ir::TyKind::Tuple(types.len(), types.as_substs().lower_into(interner)) diff --git a/compiler/rustc_traits/src/dropck_outlives.rs b/compiler/rustc_traits/src/dropck_outlives.rs index 481b56e111ea0..8b7f8033bface 100644 --- a/compiler/rustc_traits/src/dropck_outlives.rs +++ b/compiler/rustc_traits/src/dropck_outlives.rs @@ -164,7 +164,8 @@ fn dtorck_constraint_for_ty<'tcx>( | ty::Ref(..) | ty::FnDef(..) | ty::FnPtr(_) - | ty::GeneratorWitness(..) => { + | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) => { // these types never have a destructor } diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 0f25579c7bfa1..44c8569baa985 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -470,7 +470,10 @@ fn layout_of_uncached<'tcx>( return Err(LayoutError::Unknown(ty)); } - ty::Placeholder(..) | ty::GeneratorWitness(..) | ty::Infer(_) => { + ty::Placeholder(..) + | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) + | ty::Infer(_) => { bug!("Layout::compute: unexpected type `{}`", ty) } diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index 77986ad48613d..89abffebdc684 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -16,7 +16,13 @@ fn sized_constraint_for_ty<'tcx>( Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..) | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![], - Str | Dynamic(..) | Slice(_) | Foreign(..) | Error(_) | GeneratorWitness(..) => { + Str + | Dynamic(..) + | Slice(_) + | Foreign(..) + | Error(_) + | GeneratorWitness(..) + | GeneratorWitnessMIR(..) => { // these are never sized - return the target type vec![ty] } diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index 44004cb0be1e9..d5de457a82ce9 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -265,6 +265,9 @@ bitflags! { /// Does this value have `InferConst::Fresh`? const HAS_CT_FRESH = 1 << 21; + + /// Does this have `Generator` or `GeneratorWitness`? + const HAS_TY_GENERATOR = 1 << 22; } } diff --git a/compiler/rustc_type_ir/src/sty.rs b/compiler/rustc_type_ir/src/sty.rs index 5f29588ae4d26..843a75aacdb0c 100644 --- a/compiler/rustc_type_ir/src/sty.rs +++ b/compiler/rustc_type_ir/src/sty.rs @@ -160,6 +160,32 @@ pub enum TyKind { /// ``` GeneratorWitness(I::BinderListTy), + /// A type representing the types stored inside a generator. + /// This should only appear as part of the `GeneratorSubsts`. + /// + /// Unlike upvars, the witness can reference lifetimes from + /// inside of the generator itself. To deal with them in + /// the type of the generator, we convert them to higher ranked + /// lifetimes bound by the witness itself. + /// + /// This variant is only using when `drop_tracking_mir` is set. + /// This contains the `DefId` and the `SubstRef` of the generator. + /// The actual witness types are computed on MIR by the `mir_generator_info` query. + /// + /// Looking at the following example, the witness for this generator + /// may end up as something like `for<'a> [Vec, &'a Vec]`: + /// + /// ```ignore UNSOLVED (ask @compiler-errors, should this error? can we just swap the yields?) + /// #![feature(generators)] + /// |a| { + /// let x = &vec![3]; + /// yield a; + /// yield x[0]; + /// } + /// # ; + /// ``` + GeneratorWitnessMIR(I::DefId, I::SubstsRef), + /// The never type `!`. Never, @@ -241,6 +267,7 @@ const fn tykind_discriminant(value: &TyKind) -> usize { Placeholder(_) => 23, Infer(_) => 24, Error(_) => 25, + GeneratorWitnessMIR(_, _) => 26, } } @@ -266,6 +293,7 @@ impl Clone for TyKind { Closure(d, s) => Closure(d.clone(), s.clone()), Generator(d, s, m) => Generator(d.clone(), s.clone(), m.clone()), GeneratorWitness(g) => GeneratorWitness(g.clone()), + GeneratorWitnessMIR(d, s) => GeneratorWitnessMIR(d.clone(), s.clone()), Never => Never, Tuple(t) => Tuple(t.clone()), Alias(k, p) => Alias(*k, p.clone()), @@ -303,6 +331,10 @@ impl PartialEq for TyKind { a_d == b_d && a_s == b_s && a_m == b_m } (GeneratorWitness(a_g), GeneratorWitness(b_g)) => a_g == b_g, + ( + &GeneratorWitnessMIR(ref a_d, ref a_s), + &GeneratorWitnessMIR(ref b_d, ref b_s), + ) => a_d == b_d && a_s == b_s, (Tuple(a_t), Tuple(b_t)) => a_t == b_t, (Alias(a_i, a_p), Alias(b_i, b_p)) => a_i == b_i && a_p == b_p, (Param(a_p), Param(b_p)) => a_p == b_p, @@ -360,6 +392,13 @@ impl Ord for TyKind { a_d.cmp(b_d).then_with(|| a_s.cmp(b_s).then_with(|| a_m.cmp(b_m))) } (GeneratorWitness(a_g), GeneratorWitness(b_g)) => a_g.cmp(b_g), + ( + &GeneratorWitnessMIR(ref a_d, ref a_s), + &GeneratorWitnessMIR(ref b_d, ref b_s), + ) => match Ord::cmp(a_d, b_d) { + Ordering::Equal => Ord::cmp(a_s, b_s), + cmp => cmp, + }, (Tuple(a_t), Tuple(b_t)) => a_t.cmp(b_t), (Alias(a_i, a_p), Alias(b_i, b_p)) => a_i.cmp(b_i).then_with(|| a_p.cmp(b_p)), (Param(a_p), Param(b_p)) => a_p.cmp(b_p), @@ -421,6 +460,10 @@ impl hash::Hash for TyKind { m.hash(state) } GeneratorWitness(g) => g.hash(state), + GeneratorWitnessMIR(d, s) => { + d.hash(state); + s.hash(state); + } Tuple(t) => t.hash(state), Alias(i, p) => { i.hash(state); @@ -461,6 +504,7 @@ impl fmt::Debug for TyKind { Closure(d, s) => f.debug_tuple_field2_finish("Closure", d, s), Generator(d, s, m) => f.debug_tuple_field3_finish("Generator", d, s, m), GeneratorWitness(g) => f.debug_tuple_field1_finish("GeneratorWitness", g), + GeneratorWitnessMIR(d, s) => f.debug_tuple_field2_finish("GeneratorWitnessMIR", d, s), Never => f.write_str("Never"), Tuple(t) => f.debug_tuple_field1_finish("Tuple", t), Alias(i, a) => f.debug_tuple_field2_finish("Alias", i, a), @@ -559,6 +603,10 @@ where GeneratorWitness(b) => e.emit_enum_variant(disc, |e| { b.encode(e); }), + GeneratorWitnessMIR(def_id, substs) => e.emit_enum_variant(disc, |e| { + def_id.encode(e); + substs.encode(e); + }), Never => e.emit_enum_variant(disc, |_| {}), Tuple(substs) => e.emit_enum_variant(disc, |e| { substs.encode(e); @@ -641,6 +689,7 @@ where 23 => Placeholder(Decodable::decode(d)), 24 => Infer(Decodable::decode(d)), 25 => Error(Decodable::decode(d)), + 26 => GeneratorWitnessMIR(Decodable::decode(d), Decodable::decode(d)), _ => panic!( "{}", format!( @@ -742,6 +791,10 @@ where GeneratorWitness(b) => { b.hash_stable(__hcx, __hasher); } + GeneratorWitnessMIR(def_id, substs) => { + def_id.hash_stable(__hcx, __hasher); + substs.hash_stable(__hcx, __hasher); + } Never => {} Tuple(substs) => { substs.hash_stable(__hcx, __hasher); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index a4d86981c262c..204d4127c8f06 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1855,6 +1855,7 @@ pub(crate) fn clean_middle_ty<'tcx>( ty::Bound(..) => panic!("Bound"), ty::Placeholder(..) => panic!("Placeholder"), ty::GeneratorWitness(..) => panic!("GeneratorWitness"), + ty::GeneratorWitnessMIR(..) => panic!("GeneratorWitnessMIR"), ty::Infer(..) => panic!("Infer"), ty::Error(_) => rustc_errors::FatalError.raise(), } diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index e42921c080945..8435972bb11f2 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -542,6 +542,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { | ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(_) + | ty::GeneratorWitnessMIR(..) | ty::Dynamic(..) | ty::Param(_) | ty::Bound(..) diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index fa3e5aa6b7213..8e921839e8b2f 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -1419,6 +1419,7 @@ fn ty_auto_deref_stability<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, precedenc | ty::FnDef(..) | ty::Generator(..) | ty::GeneratorWitness(..) + | ty::GeneratorWitnessMIR(..) | ty::Closure(..) | ty::Never | ty::Tuple(_) diff --git a/tests/ui/symbol-names/basic.legacy.stderr b/tests/ui/symbol-names/basic.legacy.stderr index 3ad4ed24cf7fc..fe490a6000d7b 100644 --- a/tests/ui/symbol-names/basic.legacy.stderr +++ b/tests/ui/symbol-names/basic.legacy.stderr @@ -1,10 +1,10 @@ -error: symbol-name(_ZN5basic4main17hcbad207c0eeb0b3bE) +error: symbol-name(_ZN5basic4main17he9f658e438f1cac0E) --> $DIR/basic.rs:8:1 | LL | #[rustc_symbol_name] | ^^^^^^^^^^^^^^^^^^^^ -error: demangling(basic::main::hcbad207c0eeb0b3b) +error: demangling(basic::main::he9f658e438f1cac0) --> $DIR/basic.rs:8:1 | LL | #[rustc_symbol_name] diff --git a/tests/ui/symbol-names/issue-60925.legacy.stderr b/tests/ui/symbol-names/issue-60925.legacy.stderr index 21bf21ee71c6f..29b42f48d803a 100644 --- a/tests/ui/symbol-names/issue-60925.legacy.stderr +++ b/tests/ui/symbol-names/issue-60925.legacy.stderr @@ -1,10 +1,10 @@ -error: symbol-name(_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo17h2f2efcf580c9b1eeE) +error: symbol-name(_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo17h13209029be24b923E) --> $DIR/issue-60925.rs:21:9 | LL | #[rustc_symbol_name] | ^^^^^^^^^^^^^^^^^^^^ -error: demangling(issue_60925::foo::Foo::foo::h2f2efcf580c9b1ee) +error: demangling(issue_60925::foo::Foo::foo::h13209029be24b923) --> $DIR/issue-60925.rs:21:9 | LL | #[rustc_symbol_name] From e2387ad484b35c77941f8ad5687ddac55493606c Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 11 Sep 2022 17:24:53 +0200 Subject: [PATCH 436/500] Remember where a type was kept in MIR. --- compiler/rustc_const_eval/src/transform/validate.rs | 4 ++-- compiler/rustc_middle/src/mir/query.rs | 11 ++++++++++- compiler/rustc_middle/src/ty/sty.rs | 6 +++--- compiler/rustc_mir_transform/src/generator.rs | 13 +++++++++++-- compiler/rustc_mir_transform/src/inline.rs | 4 ++-- compiler/rustc_ty_utils/src/layout.rs | 4 ++-- ...op_cleanup.main-{closure#0}.generator_drop.0.mir | 9 ++++++++- ...tor_tiny.main-{closure#0}.generator_resume.0.mir | 9 ++++++++- 8 files changed, 46 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_const_eval/src/transform/validate.rs b/compiler/rustc_const_eval/src/transform/validate.rs index 3f83d40755ad8..fab92f6f6f3ba 100644 --- a/compiler/rustc_const_eval/src/transform/validate.rs +++ b/compiler/rustc_const_eval/src/transform/validate.rs @@ -372,12 +372,12 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { return; }; - let Some(&f_ty) = layout.field_tys.get(local) else { + let Some(f_ty) = layout.field_tys.get(local) else { self.fail(location, format!("Out of bounds local {:?} for {:?}", local, parent_ty)); return; }; - f_ty + f_ty.ty } else { let Some(f_ty) = substs.as_generator().prefix_tys().nth(f.index()) else { fail_out_of_bounds(self, location); diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index a8a4532223c2d..ebeefa862778a 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -135,11 +135,20 @@ rustc_index::newtype_index! { pub struct GeneratorSavedLocal {} } +#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)] +pub struct GeneratorSavedTy<'tcx> { + pub ty: Ty<'tcx>, + /// Source info corresponding to the local in the original MIR body. + pub source_info: SourceInfo, + /// Whether the local was introduced as a raw pointer to a static. + pub is_static_ptr: bool, +} + /// The layout of generator state. #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)] pub struct GeneratorLayout<'tcx> { /// The type of every local stored inside the generator. - pub field_tys: IndexVec>, + pub field_tys: IndexVec>, /// Which of the above fields are in each variant. Note that one field may /// be stored in multiple variants. diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index eba65e34023a9..f97d2e753a3b6 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -571,9 +571,9 @@ impl<'tcx> GeneratorSubsts<'tcx> { ) -> impl Iterator> + Captures<'tcx>> { let layout = tcx.generator_layout(def_id).unwrap(); layout.variant_fields.iter().map(move |variant| { - variant - .iter() - .map(move |field| ty::EarlyBinder(layout.field_tys[*field]).subst(tcx, self.substs)) + variant.iter().map(move |field| { + ty::EarlyBinder(layout.field_tys[*field].ty).subst(tcx, self.substs) + }) }) } diff --git a/compiler/rustc_mir_transform/src/generator.rs b/compiler/rustc_mir_transform/src/generator.rs index 39c61a34afcbd..e94eaeaaa2b3f 100644 --- a/compiler/rustc_mir_transform/src/generator.rs +++ b/compiler/rustc_mir_transform/src/generator.rs @@ -916,7 +916,15 @@ fn compute_layout<'tcx>( let mut tys = IndexVec::::new(); for (saved_local, local) in saved_locals.iter_enumerated() { locals.push(local); - tys.push(body.local_decls[local].ty); + let decl = &body.local_decls[local]; + let decl = GeneratorSavedTy { + ty: decl.ty, + source_info: decl.source_info, + is_static_ptr: decl.internal + && decl.ty.is_unsafe_ptr() + && matches!(decl.local_info.as_deref(), Some(LocalInfo::StaticRef { .. })), + }; + tys.push(decl); debug!("generator saved local {:?} => {:?}", saved_local, local); } @@ -947,7 +955,7 @@ fn compute_layout<'tcx>( // just use the first one here. That's fine; fields do not move // around inside generators, so it doesn't matter which variant // index we access them by. - remap.entry(locals[saved_local]).or_insert((tys[saved_local], variant_index, idx)); + remap.entry(locals[saved_local]).or_insert((tys[saved_local].ty, variant_index, idx)); } variant_fields.push(fields); variant_source_info.push(source_info_at_suspension_points[suspension_point_idx]); @@ -957,6 +965,7 @@ fn compute_layout<'tcx>( let layout = GeneratorLayout { field_tys: tys, variant_fields, variant_source_info, storage_conflicts }; + debug!(?layout); (remap, layout, storage_liveness) } diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 69627fc5cb24a..84640b703c802 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -947,12 +947,12 @@ impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> { return; }; - let Some(&f_ty) = layout.field_tys.get(local) else { + let Some(f_ty) = layout.field_tys.get(local) else { self.validation = Err("malformed MIR"); return; }; - f_ty + f_ty.ty } else { let Some(f_ty) = substs.as_generator().prefix_tys().nth(f.index()) else { self.validation = Err("malformed MIR"); diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 44c8569baa985..378cd5a99ed86 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -643,7 +643,7 @@ fn generator_layout<'tcx>( let promoted_layouts = ineligible_locals .iter() - .map(|local| subst_field(info.field_tys[local])) + .map(|local| subst_field(info.field_tys[local].ty)) .map(|ty| tcx.mk_maybe_uninit(ty)) .map(|ty| cx.layout_of(ty)); let prefix_layouts = substs @@ -713,7 +713,7 @@ fn generator_layout<'tcx>( Assigned(_) => bug!("assignment does not match variant"), Ineligible(_) => false, }) - .map(|local| subst_field(info.field_tys[*local])); + .map(|local| subst_field(info.field_tys[*local].ty)); let mut variant = univariant_uninterned( cx, diff --git a/tests/mir-opt/generator_drop_cleanup.main-{closure#0}.generator_drop.0.mir b/tests/mir-opt/generator_drop_cleanup.main-{closure#0}.generator_drop.0.mir index a8e090020c3d3..862dfc9006284 100644 --- a/tests/mir-opt/generator_drop_cleanup.main-{closure#0}.generator_drop.0.mir +++ b/tests/mir-opt/generator_drop_cleanup.main-{closure#0}.generator_drop.0.mir @@ -1,7 +1,14 @@ // MIR for `main::{closure#0}` 0 generator_drop /* generator_layout = GeneratorLayout { field_tys: { - _0: std::string::String, + _0: GeneratorSavedTy { + ty: std::string::String, + source_info: SourceInfo { + span: $DIR/generator_drop_cleanup.rs:11:13: 11:15 (#0), + scope: scope[0], + }, + is_static_ptr: false, + }, }, variant_fields: { Unresumed(0): [], diff --git a/tests/mir-opt/generator_tiny.main-{closure#0}.generator_resume.0.mir b/tests/mir-opt/generator_tiny.main-{closure#0}.generator_resume.0.mir index b3d3c768a5dd9..0d262f75c1ac9 100644 --- a/tests/mir-opt/generator_tiny.main-{closure#0}.generator_resume.0.mir +++ b/tests/mir-opt/generator_tiny.main-{closure#0}.generator_resume.0.mir @@ -1,7 +1,14 @@ // MIR for `main::{closure#0}` 0 generator_resume /* generator_layout = GeneratorLayout { field_tys: { - _0: HasDrop, + _0: GeneratorSavedTy { + ty: HasDrop, + source_info: SourceInfo { + span: $DIR/generator_tiny.rs:20:13: 20:15 (#0), + scope: scope[0], + }, + is_static_ptr: false, + }, }, variant_fields: { Unresumed(0): [], From 400cb9aa41815f874d7d29a545e6e6f8539459de Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Tue, 26 Jul 2022 20:37:25 +0200 Subject: [PATCH 437/500] Separate witness type computation from the generator transform. --- .../src/rmeta/decoder/cstore_impl.rs | 1 + compiler/rustc_metadata/src/rmeta/encoder.rs | 4 + compiler/rustc_metadata/src/rmeta/mod.rs | 1 + compiler/rustc_middle/src/query/mod.rs | 7 + compiler/rustc_middle/src/ty/parameterized.rs | 1 + .../rustc_mir_build/src/build/matches/mod.rs | 5 +- compiler/rustc_mir_transform/src/generator.rs | 310 ++++++++++++++++-- compiler/rustc_mir_transform/src/lib.rs | 4 + compiler/rustc_type_ir/src/sty.rs | 2 +- 9 files changed, 304 insertions(+), 31 deletions(-) diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index e5d0bb87edf66..9b1401f4a44df 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -202,6 +202,7 @@ provide! { tcx, def_id, other, cdata, thir_abstract_const => { table } optimized_mir => { table } mir_for_ctfe => { table } + mir_generator_witnesses => { table } promoted_mir => { table } def_span => { table } def_ident_span => { table } diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index f46050dedc20c..a72089338ee32 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1414,6 +1414,10 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { debug!("EntryBuilder::encode_mir({:?})", def_id); if encode_opt { record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id)); + + if let DefKind::Generator = self.tcx.def_kind(def_id) { + record!(self.tables.mir_generator_witnesses[def_id.to_def_id()] <- tcx.mir_generator_witnesses(def_id)); + } } if encode_const { record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- tcx.mir_for_ctfe(def_id)); diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index cf735e5bd17b4..37af9e64e9a3d 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -376,6 +376,7 @@ define_tables! { object_lifetime_default: Table>, optimized_mir: Table>>, mir_for_ctfe: Table>>, + mir_generator_witnesses: Table>>, promoted_mir: Table>>>, // FIXME(compiler-errors): Why isn't this a LazyArray? thir_abstract_const: Table>>, diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index dc626c2433c4e..3f5c28743394b 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -471,6 +471,13 @@ rustc_queries! { } } + query mir_generator_witnesses(key: DefId) -> mir::GeneratorLayout<'tcx> { + arena_cache + desc { |tcx| "generator witness types for `{}`", tcx.def_path_str(key) } + cache_on_disk_if { key.is_local() } + separate_provide_extern + } + /// MIR after our optimization passes have run. This is MIR that is ready /// for codegen. This is also the only query that can fetch non-local MIR, at present. query optimized_mir(key: DefId) -> &'tcx mir::Body<'tcx> { diff --git a/compiler/rustc_middle/src/ty/parameterized.rs b/compiler/rustc_middle/src/ty/parameterized.rs index 24f3d1acff188..84edb5f2a4288 100644 --- a/compiler/rustc_middle/src/ty/parameterized.rs +++ b/compiler/rustc_middle/src/ty/parameterized.rs @@ -117,6 +117,7 @@ macro_rules! parameterized_over_tcx { parameterized_over_tcx! { crate::middle::exported_symbols::ExportedSymbol, crate::mir::Body, + crate::mir::GeneratorLayout, ty::Ty, ty::FnSig, ty::GenericPredicates, diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/build/matches/mod.rs index 0961ce11e2f9a..2a2fe791d8c59 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/build/matches/mod.rs @@ -1747,8 +1747,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { }; let fake_borrow_deref_ty = matched_place.ty(&self.local_decls, tcx).ty; let fake_borrow_ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty); - let fake_borrow_temp = - self.local_decls.push(LocalDecl::new(fake_borrow_ty, temp_span)); + let mut fake_borrow_temp = LocalDecl::new(fake_borrow_ty, temp_span); + fake_borrow_temp.internal = self.local_decls[matched_place.local].internal; + let fake_borrow_temp = self.local_decls.push(fake_borrow_temp); (matched_place, fake_borrow_temp) }) diff --git a/compiler/rustc_mir_transform/src/generator.rs b/compiler/rustc_mir_transform/src/generator.rs index e94eaeaaa2b3f..25f270b188696 100644 --- a/compiler/rustc_mir_transform/src/generator.rs +++ b/compiler/rustc_mir_transform/src/generator.rs @@ -54,7 +54,8 @@ use crate::deref_separator::deref_finder; use crate::simplify; use crate::util::expand_aggregate; use crate::MirPass; -use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_errors::pluralize; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_hir::GeneratorKind; @@ -70,6 +71,9 @@ use rustc_mir_dataflow::impls::{ }; use rustc_mir_dataflow::storage::always_storage_live_locals; use rustc_mir_dataflow::{self, Analysis}; +use rustc_span::def_id::DefId; +use rustc_span::symbol::sym; +use rustc_span::Span; use rustc_target::abi::VariantIdx; use rustc_target::spec::PanicStrategy; use std::{iter, ops}; @@ -854,7 +858,7 @@ fn sanitize_witness<'tcx>( body: &Body<'tcx>, witness: Ty<'tcx>, upvars: Vec>, - saved_locals: &GeneratorSavedLocals, + layout: &GeneratorLayout<'tcx>, ) { let did = body.source.def_id(); let param_env = tcx.param_env(did); @@ -873,31 +877,35 @@ fn sanitize_witness<'tcx>( } }; - for (local, decl) in body.local_decls.iter_enumerated() { - // Ignore locals which are internal or not saved between yields. - if !saved_locals.contains(local) || decl.internal { + let mut mismatches = Vec::new(); + for fty in &layout.field_tys { + if fty.is_static_ptr { continue; } - let decl_ty = tcx.normalize_erasing_regions(param_env, decl.ty); + let decl_ty = tcx.normalize_erasing_regions(param_env, fty.ty); // Sanity check that typeck knows about the type of locals which are // live across a suspension point if !allowed.contains(&decl_ty) && !allowed_upvars.contains(&decl_ty) { - span_bug!( - body.span, - "Broken MIR: generator contains type {} in MIR, \ - but typeck only knows about {} and {:?}", - decl_ty, - allowed, - allowed_upvars - ); + mismatches.push(decl_ty); } } + + if !mismatches.is_empty() { + span_bug!( + body.span, + "Broken MIR: generator contains type {:?} in MIR, \ + but typeck only knows about {} and {:?}", + mismatches, + allowed, + allowed_upvars + ); + } } fn compute_layout<'tcx>( liveness: LivenessInfo, - body: &mut Body<'tcx>, + body: &Body<'tcx>, ) -> ( FxHashMap, VariantIdx, usize)>, GeneratorLayout<'tcx>, @@ -920,9 +928,7 @@ fn compute_layout<'tcx>( let decl = GeneratorSavedTy { ty: decl.ty, source_info: decl.source_info, - is_static_ptr: decl.internal - && decl.ty.is_unsafe_ptr() - && matches!(decl.local_info.as_deref(), Some(LocalInfo::StaticRef { .. })), + is_static_ptr: decl.internal, }; tys.push(decl); debug!("generator saved local {:?} => {:?}", saved_local, local); @@ -1360,6 +1366,52 @@ fn create_cases<'tcx>( .collect() } +#[instrument(level = "debug", skip(tcx), ret)] +pub(crate) fn mir_generator_witnesses<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: DefId, +) -> GeneratorLayout<'tcx> { + let def_id = def_id.expect_local(); + + let (body, _) = tcx.mir_promoted(ty::WithOptConstParam::unknown(def_id)); + let body = body.borrow(); + let body = &*body; + + // The first argument is the generator type passed by value + let gen_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty; + + // Get the interior types and substs which typeck computed + let (upvars, interior, movable) = match *gen_ty.kind() { + ty::Generator(_, substs, movability) => { + let substs = substs.as_generator(); + ( + substs.upvar_tys().collect::>(), + substs.witness(), + movability == hir::Movability::Movable, + ) + } + _ => span_bug!(body.span, "unexpected generator type {}", gen_ty), + }; + + // When first entering the generator, move the resume argument into its new local. + let always_live_locals = always_storage_live_locals(&body); + + let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable); + + // Extract locals which are live across suspension point into `layout` + // `remap` gives a mapping from local indices onto generator struct indices + // `storage_liveness` tells us which locals have live storage at suspension points + let (_, generator_layout, _) = compute_layout(liveness_info, body); + + if tcx.sess.opts.unstable_opts.drop_tracking_mir { + check_suspend_tys(tcx, &generator_layout, &body); + } else { + sanitize_witness(tcx, body, interior, upvars, &generator_layout); + } + + generator_layout +} + impl<'tcx> MirPass<'tcx> for StateTransform { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let Some(yield_ty) = body.yield_ty() else { @@ -1372,16 +1424,11 @@ impl<'tcx> MirPass<'tcx> for StateTransform { // The first argument is the generator type passed by value let gen_ty = body.local_decls.raw[1].ty; - // Get the interior types and substs which typeck computed - let (upvars, interior, discr_ty, movable) = match *gen_ty.kind() { + // Get the discriminant type and substs which typeck computed + let (discr_ty, movable) = match *gen_ty.kind() { ty::Generator(_, substs, movability) => { let substs = substs.as_generator(); - ( - substs.upvar_tys().collect(), - substs.witness(), - substs.discr_ty(tcx), - movability == hir::Movability::Movable, - ) + (substs.discr_ty(tcx), movability == hir::Movability::Movable) } _ => { tcx.sess @@ -1443,8 +1490,6 @@ impl<'tcx> MirPass<'tcx> for StateTransform { let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable); - sanitize_witness(tcx, body, interior, upvars, &liveness_info.saved_locals); - if tcx.sess.opts.unstable_opts.validate_mir { let mut vis = EnsureGeneratorFieldAssignmentsNeverAlias { assigned_local: None, @@ -1640,3 +1685,212 @@ impl<'tcx> Visitor<'tcx> for EnsureGeneratorFieldAssignmentsNeverAlias<'_> { } } } + +fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &GeneratorLayout<'tcx>, body: &Body<'tcx>) { + let mut linted_tys = FxHashSet::default(); + + // We want a user-facing param-env. + let param_env = tcx.param_env(body.source.def_id()); + + for (variant, yield_source_info) in + layout.variant_fields.iter().zip(&layout.variant_source_info) + { + debug!(?variant); + for &local in variant { + let decl = &layout.field_tys[local]; + debug!(?decl); + + if !decl.is_static_ptr && linted_tys.insert(decl.ty) { + let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else { continue }; + + check_must_not_suspend_ty( + tcx, + decl.ty, + hir_id, + param_env, + SuspendCheckData { + source_span: decl.source_info.span, + yield_span: yield_source_info.span, + plural_len: 1, + ..Default::default() + }, + ); + } + } + } +} + +#[derive(Default)] +struct SuspendCheckData<'a> { + source_span: Span, + yield_span: Span, + descr_pre: &'a str, + descr_post: &'a str, + plural_len: usize, +} + +// Returns whether it emitted a diagnostic or not +// Note that this fn and the proceeding one are based on the code +// for creating must_use diagnostics +// +// Note that this technique was chosen over things like a `Suspend` marker trait +// as it is simpler and has precedent in the compiler +fn check_must_not_suspend_ty<'tcx>( + tcx: TyCtxt<'tcx>, + ty: Ty<'tcx>, + hir_id: hir::HirId, + param_env: ty::ParamEnv<'tcx>, + data: SuspendCheckData<'_>, +) -> bool { + if ty.is_unit() { + return false; + } + + let plural_suffix = pluralize!(data.plural_len); + + debug!("Checking must_not_suspend for {}", ty); + + match *ty.kind() { + ty::Adt(..) if ty.is_box() => { + let boxed_ty = ty.boxed_ty(); + let descr_pre = &format!("{}boxed ", data.descr_pre); + check_must_not_suspend_ty( + tcx, + boxed_ty, + hir_id, + param_env, + SuspendCheckData { descr_pre, ..data }, + ) + } + ty::Adt(def, _) => check_must_not_suspend_def(tcx, def.did(), hir_id, data), + // FIXME: support adding the attribute to TAITs + ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => { + let mut has_emitted = false; + for &(predicate, _) in tcx.explicit_item_bounds(def) { + // We only look at the `DefId`, so it is safe to skip the binder here. + if let ty::PredicateKind::Clause(ty::Clause::Trait(ref poly_trait_predicate)) = + predicate.kind().skip_binder() + { + let def_id = poly_trait_predicate.trait_ref.def_id; + let descr_pre = &format!("{}implementer{} of ", data.descr_pre, plural_suffix); + if check_must_not_suspend_def( + tcx, + def_id, + hir_id, + SuspendCheckData { descr_pre, ..data }, + ) { + has_emitted = true; + break; + } + } + } + has_emitted + } + ty::Dynamic(binder, _, _) => { + let mut has_emitted = false; + for predicate in binder.iter() { + if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() { + let def_id = trait_ref.def_id; + let descr_post = &format!(" trait object{}{}", plural_suffix, data.descr_post); + if check_must_not_suspend_def( + tcx, + def_id, + hir_id, + SuspendCheckData { descr_post, ..data }, + ) { + has_emitted = true; + break; + } + } + } + has_emitted + } + ty::Tuple(fields) => { + let mut has_emitted = false; + for (i, ty) in fields.iter().enumerate() { + let descr_post = &format!(" in tuple element {i}"); + if check_must_not_suspend_ty( + tcx, + ty, + hir_id, + param_env, + SuspendCheckData { descr_post, ..data }, + ) { + has_emitted = true; + } + } + has_emitted + } + ty::Array(ty, len) => { + let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix); + check_must_not_suspend_ty( + tcx, + ty, + hir_id, + param_env, + SuspendCheckData { + descr_pre, + plural_len: len.try_eval_usize(tcx, param_env).unwrap_or(0) as usize + 1, + ..data + }, + ) + } + // If drop tracking is enabled, we want to look through references, since the referrent + // may not be considered live across the await point. + ty::Ref(_region, ty, _mutability) => { + let descr_pre = &format!("{}reference{} to ", data.descr_pre, plural_suffix); + check_must_not_suspend_ty( + tcx, + ty, + hir_id, + param_env, + SuspendCheckData { descr_pre, ..data }, + ) + } + _ => false, + } +} + +fn check_must_not_suspend_def( + tcx: TyCtxt<'_>, + def_id: DefId, + hir_id: hir::HirId, + data: SuspendCheckData<'_>, +) -> bool { + if let Some(attr) = tcx.get_attr(def_id, sym::must_not_suspend) { + let msg = format!( + "{}`{}`{} held across a suspend point, but should not be", + data.descr_pre, + tcx.def_path_str(def_id), + data.descr_post, + ); + tcx.struct_span_lint_hir( + rustc_session::lint::builtin::MUST_NOT_SUSPEND, + hir_id, + data.source_span, + msg, + |lint| { + // add span pointing to the offending yield/await + lint.span_label(data.yield_span, "the value is held across this suspend point"); + + // Add optional reason note + if let Some(note) = attr.value_str() { + // FIXME(guswynn): consider formatting this better + lint.span_note(data.source_span, note.as_str()); + } + + // Add some quick suggestions on what to do + // FIXME: can `drop` work as a suggestion here as well? + lint.span_help( + data.source_span, + "consider using a block (`{ ... }`) \ + to shrink the value's scope, ending before the suspend point", + ) + }, + ); + + true + } else { + false + } +} diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 4a598862d10f8..fe3d5b1cce458 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -123,6 +123,7 @@ pub fn provide(providers: &mut Providers) { mir_drops_elaborated_and_const_checked, mir_for_ctfe, mir_for_ctfe_of_const_arg, + mir_generator_witnesses: generator::mir_generator_witnesses, optimized_mir, is_mir_available, is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did), @@ -425,6 +426,9 @@ fn mir_drops_elaborated_and_const_checked( return tcx.mir_drops_elaborated_and_const_checked(def); } + if tcx.generator_kind(def.did).is_some() { + tcx.ensure().mir_generator_witnesses(def.did); + } let mir_borrowck = tcx.mir_borrowck_opt_const_arg(def); let is_fn_like = tcx.def_kind(def.did).is_fn_like(); diff --git a/compiler/rustc_type_ir/src/sty.rs b/compiler/rustc_type_ir/src/sty.rs index 843a75aacdb0c..e7bb30553736c 100644 --- a/compiler/rustc_type_ir/src/sty.rs +++ b/compiler/rustc_type_ir/src/sty.rs @@ -170,7 +170,7 @@ pub enum TyKind { /// /// This variant is only using when `drop_tracking_mir` is set. /// This contains the `DefId` and the `SubstRef` of the generator. - /// The actual witness types are computed on MIR by the `mir_generator_info` query. + /// The actual witness types are computed on MIR by the `mir_generator_witnesses` query. /// /// Looking at the following example, the witness for this generator /// may end up as something like `for<'a> [Vec, &'a Vec]`: From 454c473599aab480b704a470407eb9ab59a7fe27 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Fri, 27 Jan 2023 20:22:54 +0100 Subject: [PATCH 438/500] Remove `BOOL_TY_FOR_UNIT_TESTING` It is not used anymore for unit testing. --- compiler/rustc_middle/src/ty/mod.rs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 4af29fcbfb586..6fe1676bb7428 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -453,18 +453,6 @@ pub struct CReaderCacheKey { #[rustc_pass_by_value] pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo>>); -impl<'tcx> TyCtxt<'tcx> { - /// A "bool" type used in rustc_mir_transform unit tests when we - /// have not spun up a TyCtxt. - pub const BOOL_TY_FOR_UNIT_TESTING: Ty<'tcx> = - Ty(Interned::new_unchecked(&WithCachedTypeInfo { - internee: ty::Bool, - stable_hash: Fingerprint::ZERO, - flags: TypeFlags::empty(), - outer_exclusive_binder: DebruijnIndex::from_usize(0), - })); -} - impl ty::EarlyBoundRegion { /// Does this early bound region have a name? Early bound regions normally /// always have names except when using anonymous lifetimes (`'_`). From 1f403e9ab96e12f374dfdd9e8967eea940122ce7 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Fri, 27 Jan 2023 20:26:48 +0100 Subject: [PATCH 439/500] Bump nightly version -> 2023-01-27 --- rust-toolchain | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain b/rust-toolchain index 40a6f47095ec2..4e7fc565a322a 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2023-01-12" +channel = "nightly-2023-01-27" components = ["cargo", "llvm-tools", "rust-src", "rust-std", "rustc", "rustc-dev", "rustfmt"] From 6f9c70a2015aadd1dc1b77d1e988217aeebd75c5 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Fri, 27 Jan 2023 20:27:00 +0100 Subject: [PATCH 440/500] Bump Clippy version -> 0.1.69 --- Cargo.toml | 2 +- clippy_lints/Cargo.toml | 2 +- clippy_utils/Cargo.toml | 2 +- declare_clippy_lint/Cargo.toml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e1b15cc49da4c..dc94b1045249e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "clippy" -version = "0.1.68" +version = "0.1.69" description = "A bunch of helpful lints to avoid common pitfalls in Rust" repository = "https://github.com/rust-lang/rust-clippy" readme = "README.md" diff --git a/clippy_lints/Cargo.toml b/clippy_lints/Cargo.toml index 38a87017635ba..7278ad13d568a 100644 --- a/clippy_lints/Cargo.toml +++ b/clippy_lints/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "clippy_lints" -version = "0.1.68" +version = "0.1.69" description = "A bunch of helpful lints to avoid common pitfalls in Rust" repository = "https://github.com/rust-lang/rust-clippy" readme = "README.md" diff --git a/clippy_utils/Cargo.toml b/clippy_utils/Cargo.toml index ac6a566b9cd3a..173469f6cdc7d 100644 --- a/clippy_utils/Cargo.toml +++ b/clippy_utils/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "clippy_utils" -version = "0.1.68" +version = "0.1.69" edition = "2021" publish = false diff --git a/declare_clippy_lint/Cargo.toml b/declare_clippy_lint/Cargo.toml index c01e1062cb544..80eee368178e1 100644 --- a/declare_clippy_lint/Cargo.toml +++ b/declare_clippy_lint/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "declare_clippy_lint" -version = "0.1.68" +version = "0.1.69" edition = "2021" publish = false From 29901e027c8f343e0366e308a9bf7edb2618c867 Mon Sep 17 00:00:00 2001 From: Boxy Date: Fri, 27 Jan 2023 19:29:04 +0000 Subject: [PATCH 441/500] yeet --- compiler/rustc_infer/src/infer/combine.rs | 114 +++++----------------- 1 file changed, 26 insertions(+), 88 deletions(-) diff --git a/compiler/rustc_infer/src/infer/combine.rs b/compiler/rustc_infer/src/infer/combine.rs index 72676b718fabe..a567b6acdbeeb 100644 --- a/compiler/rustc_infer/src/infer/combine.rs +++ b/compiler/rustc_infer/src/infer/combine.rs @@ -37,7 +37,10 @@ use rustc_middle::traits::ObligationCause; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::relate::{self, Relate, RelateResult, TypeRelation}; use rustc_middle::ty::subst::SubstsRef; -use rustc_middle::ty::{self, InferConst, Ty, TyCtxt, TypeVisitable}; +use rustc_middle::ty::{ + self, FallibleTypeFolder, InferConst, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, + TypeVisitable, +}; use rustc_middle::ty::{IntType, UintType}; use rustc_span::{Span, DUMMY_SP}; @@ -140,8 +143,6 @@ impl<'tcx> InferCtxt<'tcx> { let a = self.shallow_resolve(a); let b = self.shallow_resolve(b); - let a_is_expected = relation.a_is_expected(); - match (a.kind(), b.kind()) { ( ty::ConstKind::Infer(InferConst::Var(a_vid)), @@ -158,11 +159,11 @@ impl<'tcx> InferCtxt<'tcx> { } (ty::ConstKind::Infer(InferConst::Var(vid)), _) => { - return self.unify_const_variable(relation.param_env(), vid, b, a_is_expected); + return self.unify_const_variable(vid, b); } (_, ty::ConstKind::Infer(InferConst::Var(vid))) => { - return self.unify_const_variable(relation.param_env(), vid, a, !a_is_expected); + return self.unify_const_variable(vid, a); } (ty::ConstKind::Unevaluated(..), _) if self.tcx.lazy_normalization() => { // FIXME(#59490): Need to remove the leak check to accommodate @@ -223,10 +224,8 @@ impl<'tcx> InferCtxt<'tcx> { #[instrument(level = "debug", skip(self))] fn unify_const_variable( &self, - param_env: ty::ParamEnv<'tcx>, target_vid: ty::ConstVid<'tcx>, ct: ty::Const<'tcx>, - vid_is_expected: bool, ) -> RelateResult<'tcx, ty::Const<'tcx>> { let (for_universe, span) = { let mut inner = self.inner.borrow_mut(); @@ -239,8 +238,12 @@ impl<'tcx> InferCtxt<'tcx> { ConstVariableValue::Unknown { universe } => (universe, var_value.origin.span), } }; - let value = ConstInferUnifier { infcx: self, span, param_env, for_universe, target_vid } - .relate(ct, ct)?; + let value = ct.try_fold_with(&mut ConstInferUnifier { + infcx: self, + span, + for_universe, + target_vid, + })?; self.inner.borrow_mut().const_unification_table().union_value( target_vid, @@ -800,8 +803,6 @@ struct ConstInferUnifier<'cx, 'tcx> { span: Span, - param_env: ty::ParamEnv<'tcx>, - for_universe: ty::UniverseIndex, /// The vid of the const variable that is in the process of being @@ -810,61 +811,15 @@ struct ConstInferUnifier<'cx, 'tcx> { target_vid: ty::ConstVid<'tcx>, } -// We use `TypeRelation` here to propagate `RelateResult` upwards. -// -// Both inputs are expected to be the same. -impl<'tcx> TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> { - fn tcx(&self) -> TyCtxt<'tcx> { - self.infcx.tcx - } - - fn intercrate(&self) -> bool { - assert!(!self.infcx.intercrate); - false - } - - fn param_env(&self) -> ty::ParamEnv<'tcx> { - self.param_env - } - - fn tag(&self) -> &'static str { - "ConstInferUnifier" - } - - fn a_is_expected(&self) -> bool { - true - } - - fn mark_ambiguous(&mut self) { - bug!() - } - - fn relate_with_variance>( - &mut self, - _variance: ty::Variance, - _info: ty::VarianceDiagInfo<'tcx>, - a: T, - b: T, - ) -> RelateResult<'tcx, T> { - // We don't care about variance here. - self.relate(a, b) - } +impl<'tcx> FallibleTypeFolder<'tcx> for ConstInferUnifier<'_, 'tcx> { + type Error = TypeError<'tcx>; - fn binders( - &mut self, - a: ty::Binder<'tcx, T>, - b: ty::Binder<'tcx, T>, - ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> - where - T: Relate<'tcx>, - { - Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?)) + fn tcx<'a>(&'a self) -> TyCtxt<'tcx> { + self.infcx.tcx } #[instrument(level = "debug", skip(self), ret)] - fn tys(&mut self, t: Ty<'tcx>, _t: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { - debug_assert_eq!(t, _t); - + fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result, TypeError<'tcx>> { match t.kind() { &ty::Infer(ty::TyVar(vid)) => { let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid); @@ -872,7 +827,7 @@ impl<'tcx> TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> { match probe { TypeVariableValue::Known { value: u } => { debug!("ConstOccursChecker: known value {:?}", u); - self.tys(u, u) + u.try_fold_with(self) } TypeVariableValue::Unknown { universe } => { if self.for_universe.can_name(universe) { @@ -892,16 +847,15 @@ impl<'tcx> TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> { } } ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => Ok(t), - _ => relate::super_relate_tys(self, t, t), + _ => t.try_super_fold_with(self), } } - fn regions( + #[instrument(level = "debug", skip(self), ret)] + fn try_fold_region( &mut self, r: ty::Region<'tcx>, - _r: ty::Region<'tcx>, - ) -> RelateResult<'tcx, ty::Region<'tcx>> { - debug_assert_eq!(r, _r); + ) -> Result, TypeError<'tcx>> { debug!("ConstInferUnifier: r={:?}", r); match *r { @@ -930,14 +884,8 @@ impl<'tcx> TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> { } } - #[instrument(level = "debug", skip(self))] - fn consts( - &mut self, - c: ty::Const<'tcx>, - _c: ty::Const<'tcx>, - ) -> RelateResult<'tcx, ty::Const<'tcx>> { - debug_assert_eq!(c, _c); - + #[instrument(level = "debug", skip(self), ret)] + fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result, TypeError<'tcx>> { match c.kind() { ty::ConstKind::Infer(InferConst::Var(vid)) => { // Check if the current unification would end up @@ -958,7 +906,7 @@ impl<'tcx> TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> { let var_value = self.infcx.inner.borrow_mut().const_unification_table().probe_value(vid); match var_value.val { - ConstVariableValue::Known { value: u } => self.consts(u, u), + ConstVariableValue::Known { value: u } => u.try_fold_with(self), ConstVariableValue::Unknown { universe } => { if self.for_universe.can_name(universe) { Ok(c) @@ -977,17 +925,7 @@ impl<'tcx> TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> { } } } - ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => { - let substs = self.relate_with_variance( - ty::Variance::Invariant, - ty::VarianceDiagInfo::default(), - substs, - substs, - )?; - - Ok(self.tcx().mk_const(ty::UnevaluatedConst { def, substs }, c.ty())) - } - _ => relate::super_relate_consts(self, c, c), + _ => c.try_super_fold_with(self), } } } From 5152e84024cd9bbeeebd7bf27d048628cfc0cd95 Mon Sep 17 00:00:00 2001 From: nils <48135649+Nilstrieb@users.noreply.github.com> Date: Fri, 27 Jan 2023 20:58:54 +0100 Subject: [PATCH 442/500] Remove unused import --- compiler/rustc_middle/src/ty/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 6fe1676bb7428..7001f81aa7750 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -31,7 +31,6 @@ pub use generics::*; use rustc_ast as ast; use rustc_ast::node_id::NodeMap; use rustc_attr as attr; -use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; From ff2413db1b72b78137c7c0c7295eab112c0192d9 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 27 Jan 2023 04:00:37 +0000 Subject: [PATCH 443/500] No need to probe when computing goals --- .../rustc_trait_selection/src/solve/mod.rs | 38 +++++++++---------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_trait_selection/src/solve/mod.rs b/compiler/rustc_trait_selection/src/solve/mod.rs index f44648c95d742..2b42cfde9100e 100644 --- a/compiler/rustc_trait_selection/src/solve/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/mod.rs @@ -337,15 +337,13 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { // That won't actually reflect in the query response, so it seems moot. self.make_canonical_response(Certainty::AMBIGUOUS) } else { - self.infcx.probe(|_| { - let InferOk { value: (), obligations } = self - .infcx - .at(&ObligationCause::dummy(), goal.param_env) - .sub(goal.predicate.a, goal.predicate.b)?; - self.evaluate_all_and_make_canonical_response( - obligations.into_iter().map(|pred| pred.into()).collect(), - ) - }) + let InferOk { value: (), obligations } = self + .infcx + .at(&ObligationCause::dummy(), goal.param_env) + .sub(goal.predicate.a, goal.predicate.b)?; + self.evaluate_all_and_make_canonical_response( + obligations.into_iter().map(|pred| pred.into()).collect(), + ) } } @@ -378,18 +376,16 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { &mut self, goal: Goal<'tcx, ty::GenericArg<'tcx>>, ) -> QueryResult<'tcx> { - self.infcx.probe(|_| { - match crate::traits::wf::unnormalized_obligations( - self.infcx, - goal.param_env, - goal.predicate, - ) { - Some(obligations) => self.evaluate_all_and_make_canonical_response( - obligations.into_iter().map(|o| o.into()).collect(), - ), - None => self.make_canonical_response(Certainty::AMBIGUOUS), - } - }) + match crate::traits::wf::unnormalized_obligations( + self.infcx, + goal.param_env, + goal.predicate, + ) { + Some(obligations) => self.evaluate_all_and_make_canonical_response( + obligations.into_iter().map(|o| o.into()).collect(), + ), + None => self.make_canonical_response(Certainty::AMBIGUOUS), + } } } From 0654374750bb7b2606396e8dce7cf93820c69ec1 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 27 Jan 2023 04:31:51 +0000 Subject: [PATCH 444/500] Add some comments --- .../src/solve/assembly.rs | 25 +++++++++++++++++++ .../rustc_trait_selection/src/solve/mod.rs | 6 +++++ 2 files changed, 31 insertions(+) diff --git a/compiler/rustc_trait_selection/src/solve/assembly.rs b/compiler/rustc_trait_selection/src/solve/assembly.rs index d23b550621e17..61319a3ed7c19 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly.rs @@ -1,6 +1,8 @@ //! Code shared by trait and projection goals for candidate assembly. use super::infcx_ext::InferCtxtExt; +#[cfg(doc)] +use super::trait_goals::structural_traits::*; use super::{CanonicalResponse, Certainty, EvalCtxt, Goal, QueryResult}; use rustc_hir::def_id::DefId; use rustc_infer::traits::query::NoSolution; @@ -98,52 +100,75 @@ pub(super) trait GoalKind<'tcx>: TypeFoldable<'tcx> + Copy + Eq { assumption: ty::Predicate<'tcx>, ) -> QueryResult<'tcx>; + // A type implements an `auto trait` if its components do as well. These components + // are given by built-in rules from [`instantiate_constituent_tys_for_auto_trait`]. fn consider_auto_trait_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; + // A trait alias holds if the RHS traits and `where` clauses hold. fn consider_trait_alias_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; + // A type is `Copy` or `Clone` if its components are `Sized`. These components + // are given by built-in rules from [`instantiate_constituent_tys_for_sized_trait`]. fn consider_builtin_sized_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; + // A type is `Copy` or `Clone` if its components are `Copy` or `Clone`. These + // components are given by built-in rules from [`instantiate_constituent_tys_for_copy_clone_trait`]. fn consider_builtin_copy_clone_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; + // A type is `PointerSized` if we can compute its layout, and that layout + // matches the layout of `usize`. fn consider_builtin_pointer_sized_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; + // A callable type (a closure, fn def, or fn ptr) is known to implement the `Fn` + // family of traits where `A` is given by the signature of the type. fn consider_builtin_fn_trait_candidates( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, kind: ty::ClosureKind, ) -> QueryResult<'tcx>; + // `Tuple` is implemented if the `Self` type is a tuple. fn consider_builtin_tuple_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; + // `Pointee` is always implemented. + // + // See the projection implementation for the `Metadata` types for all of + // the built-in types. For structs, the metadata type is given by the struct + // tail. fn consider_builtin_pointee_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; + // A generator (that comes from an `async` desugaring) is known to implement + // `Future`, where `O` is given by the generator's return type + // that was computed during type-checking. fn consider_builtin_future_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; + // A generator (that doesn't come from an `async` desugaring) is known to + // implement `Generator`, given the resume, yield, + // and return types of the generator computed during type-checking. fn consider_builtin_generator_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, diff --git a/compiler/rustc_trait_selection/src/solve/mod.rs b/compiler/rustc_trait_selection/src/solve/mod.rs index 2b42cfde9100e..cc7bb94537673 100644 --- a/compiler/rustc_trait_selection/src/solve/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/mod.rs @@ -390,6 +390,8 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { } impl<'tcx> EvalCtxt<'_, 'tcx> { + // Recursively evaluates a list of goals to completion, returning the certainty + // of all of the goals. fn evaluate_all( &mut self, mut goals: Vec>>, @@ -426,6 +428,10 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { }) } + // Recursively evaluates a list of goals to completion, making a query response. + // + // This is just a convenient way of calling [`EvalCtxt::evaluate_all`], + // then [`EvalCtxt::make_canonical_response`]. fn evaluate_all_and_make_canonical_response( &mut self, goals: Vec>>, From 8a0b2156d5b899f740f128dfeb6090e0f408d33b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 27 Jan 2023 04:32:12 +0000 Subject: [PATCH 445/500] Micro-optimization in consider_assumption --- compiler/rustc_trait_selection/src/solve/project_goals.rs | 4 +++- compiler/rustc_trait_selection/src/solve/trait_goals.rs | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_trait_selection/src/solve/project_goals.rs b/compiler/rustc_trait_selection/src/solve/project_goals.rs index b583705ac4369..9da464f283ef3 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals.rs @@ -296,7 +296,9 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { goal: Goal<'tcx, Self>, assumption: ty::Predicate<'tcx>, ) -> QueryResult<'tcx> { - if let Some(poly_projection_pred) = assumption.to_opt_poly_projection_pred() { + if let Some(poly_projection_pred) = assumption.to_opt_poly_projection_pred() + && poly_projection_pred.projection_def_id() == goal.predicate.def_id() + { ecx.infcx.probe(|_| { let assumption_projection_pred = ecx.infcx.instantiate_bound_vars_with_infer(poly_projection_pred); diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals.rs b/compiler/rustc_trait_selection/src/solve/trait_goals.rs index d74857dc4b480..45b6a5f4ec578 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals.rs @@ -65,7 +65,9 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { goal: Goal<'tcx, Self>, assumption: ty::Predicate<'tcx>, ) -> QueryResult<'tcx> { - if let Some(poly_trait_pred) = assumption.to_opt_poly_trait_pred() { + if let Some(poly_trait_pred) = assumption.to_opt_poly_trait_pred() + && poly_trait_pred.def_id() == goal.predicate.def_id() + { // FIXME: Constness and polarity ecx.infcx.probe(|_| { let assumption_trait_pred = From c71062a324329712ae87bcdb4eec97cc9a7d62c5 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Fri, 27 Jan 2023 21:09:23 +0100 Subject: [PATCH 446/500] Update Cargo.lock --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 23b01f23c50ea..48c5a4d5feb78 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -724,7 +724,7 @@ dependencies = [ [[package]] name = "clippy" -version = "0.1.68" +version = "0.1.69" dependencies = [ "clippy_lints", "clippy_utils", @@ -766,7 +766,7 @@ dependencies = [ [[package]] name = "clippy_lints" -version = "0.1.68" +version = "0.1.69" dependencies = [ "cargo_metadata 0.14.0", "clippy_utils", @@ -789,7 +789,7 @@ dependencies = [ [[package]] name = "clippy_utils" -version = "0.1.68" +version = "0.1.69" dependencies = [ "arrayvec", "if_chain", @@ -1168,7 +1168,7 @@ checksum = "a0afaad2b26fa326569eb264b1363e8ae3357618c43982b3f285f0774ce76b69" [[package]] name = "declare_clippy_lint" -version = "0.1.68" +version = "0.1.69" dependencies = [ "itertools", "quote", From 60e04d1e8c3afd392551db103651e0ac55b4bd7e Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 1 Oct 2022 15:57:22 +0200 Subject: [PATCH 447/500] Compute generator saved locals on MIR. --- .../rustc_hir_analysis/src/check/check.rs | 38 +++++++++- compiler/rustc_hir_analysis/src/check/mod.rs | 1 + compiler/rustc_hir_typeck/src/check.rs | 2 +- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 61 ++++++++++++++- compiler/rustc_hir_typeck/src/inherited.rs | 2 +- compiler/rustc_hir_typeck/src/lib.rs | 8 +- compiler/rustc_hir_typeck/src/writeback.rs | 4 + compiler/rustc_infer/src/traits/engine.rs | 8 ++ compiler/rustc_interface/src/passes.rs | 9 +++ compiler/rustc_middle/src/query/mod.rs | 4 + .../rustc_middle/src/ty/typeck_results.rs | 7 ++ compiler/rustc_middle/src/ty/util.rs | 74 ++++++++++++++++++- .../src/solve/fulfill.rs | 7 ++ .../src/traits/chalk_fulfill.rs | 7 ++ .../src/traits/error_reporting/suggestions.rs | 52 ++++++++++++- .../src/traits/fulfill.rs | 49 ++++++++++++ .../src/traits/select/confirmation.rs | 11 ++- .../src/traits/select/mod.rs | 67 ++++++++++++++++- 18 files changed, 392 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 6c7482b40c3d2..c89db538aa6d3 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -14,7 +14,7 @@ use rustc_hir::{ItemKind, Node, PathSegment}; use rustc_infer::infer::opaque_types::ConstrainOpaqueTypeRegionVisitor; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{DefiningAnchor, RegionVariableOrigin, TyCtxtInferExt}; -use rustc_infer::traits::Obligation; +use rustc_infer::traits::{Obligation, TraitEngineExt as _}; use rustc_lint::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS; use rustc_middle::hir::nested_filter; use rustc_middle::middle::stability::EvalResult; @@ -28,7 +28,7 @@ use rustc_span::{self, Span}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits::error_reporting::on_unimplemented::OnUnimplementedDirective; use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _; -use rustc_trait_selection::traits::{self, ObligationCtxt}; +use rustc_trait_selection::traits::{self, ObligationCtxt, TraitEngine, TraitEngineExt as _}; use std::ops::ControlFlow; @@ -1460,7 +1460,8 @@ fn opaque_type_cycle_error( for def_id in visitor.opaques { let ty_span = tcx.def_span(def_id); if !seen.contains(&ty_span) { - err.span_label(ty_span, &format!("returning this opaque type `{ty}`")); + let descr = if ty.is_impl_trait() { "opaque " } else { "" }; + err.span_label(ty_span, &format!("returning this {descr}type `{ty}`")); seen.insert(ty_span); } err.span_label(sp, &format!("returning here with type `{ty}`")); @@ -1507,3 +1508,34 @@ fn opaque_type_cycle_error( } err.emit() } + +pub(super) fn check_generator_obligations(tcx: TyCtxt<'_>, def_id: LocalDefId) { + debug_assert!(tcx.sess.opts.unstable_opts.drop_tracking_mir); + debug_assert!(matches!(tcx.def_kind(def_id), DefKind::Generator)); + + let typeck = tcx.typeck(def_id); + let param_env = tcx.param_env(def_id); + + let generator_interior_predicates = &typeck.generator_interior_predicates[&def_id]; + debug!(?generator_interior_predicates); + + let infcx = tcx + .infer_ctxt() + // typeck writeback gives us predicates with their regions erased. + // As borrowck already has checked lifetimes, we do not need to do it again. + .ignoring_regions() + // Bind opaque types to `def_id` as they should have been checked by borrowck. + .with_opaque_type_inference(DefiningAnchor::Bind(def_id)) + .build(); + + let mut fulfillment_cx = >::new(infcx.tcx); + for (predicate, cause) in generator_interior_predicates { + let obligation = Obligation::new(tcx, cause.clone(), param_env, *predicate); + fulfillment_cx.register_predicate_obligation(&infcx, obligation); + } + let errors = fulfillment_cx.select_all_or_error(&infcx); + debug!(?errors); + if !errors.is_empty() { + infcx.err_ctxt().report_fulfillment_errors(&errors, None); + } +} diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index 2f2ee702837bc..bec693439a46c 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -105,6 +105,7 @@ pub fn provide(providers: &mut Providers) { region_scope_tree, collect_return_position_impl_trait_in_trait_tys, compare_impl_const: compare_impl_item::compare_impl_const_raw, + check_generator_obligations: check::check_generator_obligations, ..*providers }; } diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index 8bbbf04c0cd47..17f736475dd37 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -130,7 +130,7 @@ pub(super) fn check_fn<'a, 'tcx>( let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) { let interior = fcx .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span }); - fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind)); + fcx.deferred_generator_interiors.borrow_mut().push((fn_id, body.id(), interior, gen_kind)); let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap(); Some(GeneratorTypes { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 42f4b49889a2d..126355c5bfa27 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -517,10 +517,67 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } pub(in super::super) fn resolve_generator_interiors(&self, def_id: DefId) { + if self.tcx.sess.opts.unstable_opts.drop_tracking_mir { + self.save_generator_interior_predicates(def_id); + return; + } + + self.select_obligations_where_possible(|_| {}); + let mut generators = self.deferred_generator_interiors.borrow_mut(); - for (body_id, interior, kind) in generators.drain(..) { - self.select_obligations_where_possible(|_| {}); + for (_, body_id, interior, kind) in generators.drain(..) { crate::generator_interior::resolve_interior(self, def_id, body_id, interior, kind); + self.select_obligations_where_possible(|_| {}); + } + } + + /// Unify the inference variables corresponding to generator witnesses, and save all the + /// predicates that were stalled on those inference variables. + /// + /// This process allows to conservatively save all predicates that do depend on the generator + /// interior types, for later processing by `check_generator_obligations`. + /// + /// We must not attempt to select obligations after this method has run, or risk query cycle + /// ICE. + #[instrument(level = "debug", skip(self))] + fn save_generator_interior_predicates(&self, def_id: DefId) { + // Try selecting all obligations that are not blocked on inference variables. + // Once we start unifying generator witnesses, trying to select obligations on them will + // trigger query cycle ICEs, as doing so requires MIR. + self.select_obligations_where_possible(|_| {}); + + let generators = std::mem::take(&mut *self.deferred_generator_interiors.borrow_mut()); + debug!(?generators); + + for &(expr_hir_id, body_id, interior, _) in generators.iter() { + let expr_def_id = self.tcx.hir().local_def_id(expr_hir_id); + debug!(?expr_def_id); + + // Create the `GeneratorWitness` type that we will unify with `interior`. + let substs = ty::InternalSubsts::identity_for_item( + self.tcx, + self.tcx.typeck_root_def_id(expr_def_id.to_def_id()), + ); + let witness = self.tcx.mk_generator_witness_mir(expr_def_id.to_def_id(), substs); + + // Unify `interior` with `witness` and collect all the resulting obligations. + let span = self.tcx.hir().body(body_id).value.span; + let ok = self + .at(&self.misc(span), self.param_env) + .eq(interior, witness) + .expect("Failed to unify generator interior type"); + let mut obligations = ok.obligations; + + // Also collect the obligations that were unstalled by this unification. + obligations + .extend(self.fulfillment_cx.borrow_mut().drain_unstalled_obligations(&self.infcx)); + + let obligations = obligations.into_iter().map(|o| (o.predicate, o.cause)).collect(); + debug!(?obligations); + self.typeck_results + .borrow_mut() + .generator_interior_predicates + .insert(expr_def_id, obligations); } } diff --git a/compiler/rustc_hir_typeck/src/inherited.rs b/compiler/rustc_hir_typeck/src/inherited.rs index ba34f299453ec..c6ce2f450d915 100644 --- a/compiler/rustc_hir_typeck/src/inherited.rs +++ b/compiler/rustc_hir_typeck/src/inherited.rs @@ -56,7 +56,7 @@ pub struct Inherited<'tcx> { pub(super) deferred_asm_checks: RefCell, hir::HirId)>>, pub(super) deferred_generator_interiors: - RefCell, hir::GeneratorKind)>>, + RefCell, hir::GeneratorKind)>>, pub(super) body_id: Option, diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 899ec9ff9de0f..323bacf70ab9c 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -294,7 +294,6 @@ fn typeck_with_fallback<'tcx>( // Before the generator analysis, temporary scopes shall be marked to provide more // precise information on types to be captured. fcx.resolve_rvalue_scopes(def_id.to_def_id()); - fcx.resolve_generator_interiors(def_id.to_def_id()); for (ty, span, code) in fcx.deferred_sized_obligations.borrow_mut().drain(..) { let ty = fcx.normalize(span, ty); @@ -303,6 +302,13 @@ fn typeck_with_fallback<'tcx>( fcx.select_obligations_where_possible(|_| {}); + debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations()); + + // This must be the last thing before `report_ambiguity_errors`. + fcx.resolve_generator_interiors(def_id.to_def_id()); + + debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations()); + if let None = fcx.infcx.tainted_by_errors() { fcx.report_ambiguity_errors(); } diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index 250f4cd3f65fb..20d6ce5ed516d 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -545,6 +545,10 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); self.typeck_results.generator_interior_types = fcx_typeck_results.generator_interior_types.clone(); + for (&expr_def_id, predicates) in fcx_typeck_results.generator_interior_predicates.iter() { + let predicates = self.resolve(predicates.clone(), &self.fcx.tcx.def_span(expr_def_id)); + self.typeck_results.generator_interior_predicates.insert(expr_def_id, predicates); + } } #[instrument(skip(self), level = "debug")] diff --git a/compiler/rustc_infer/src/traits/engine.rs b/compiler/rustc_infer/src/traits/engine.rs index 805eb95e31612..ef2fee02e083e 100644 --- a/compiler/rustc_infer/src/traits/engine.rs +++ b/compiler/rustc_infer/src/traits/engine.rs @@ -41,6 +41,14 @@ pub trait TraitEngine<'tcx>: 'tcx { fn collect_remaining_errors(&mut self) -> Vec>; fn pending_obligations(&self) -> Vec>; + + /// Among all pending obligations, collect those are stalled on a inference variable which has + /// changed since the last call to `select_where_possible`. Those obligations are marked as + /// successful and returned. + fn drain_unstalled_obligations( + &mut self, + infcx: &InferCtxt<'tcx>, + ) -> Vec>; } pub trait TraitEngineExt<'tcx> { diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 37b381c534ea0..60b60edd2c811 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -893,6 +893,15 @@ fn analysis(tcx: TyCtxt<'_>, (): ()) -> Result<()> { } }); + if tcx.sess.opts.unstable_opts.drop_tracking_mir { + tcx.hir().par_body_owners(|def_id| { + if let rustc_hir::def::DefKind::Generator = tcx.def_kind(def_id) { + tcx.ensure().mir_generator_witnesses(def_id); + tcx.ensure().check_generator_obligations(def_id); + } + }); + } + sess.time("layout_testing", || layout_test::test_layout(tcx)); // Avoid overwhelming user with errors if borrow checking failed. diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 3f5c28743394b..e4df309e0089b 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -478,6 +478,10 @@ rustc_queries! { separate_provide_extern } + query check_generator_obligations(key: LocalDefId) { + desc { |tcx| "verify auto trait bounds for generator interior type `{}`", tcx.def_path_str(key.to_def_id()) } + } + /// MIR after our optimization passes have run. This is MIR that is ready /// for codegen. This is also the only query that can fetch non-local MIR, at present. query optimized_mir(key: DefId) -> &'tcx mir::Body<'tcx> { diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index 2902c6dc556e4..79a6c730d7159 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -1,6 +1,7 @@ use crate::{ hir::place::Place as HirPlace, infer::canonical::Canonical, + traits::ObligationCause, ty::{ self, tls, BindingMode, BoundVar, CanonicalPolyFnSig, ClosureSizeProfileData, GenericArgKind, InternalSubsts, SubstsRef, Ty, UserSubsts, @@ -193,6 +194,11 @@ pub struct TypeckResults<'tcx> { /// that are live across the yield of this generator (if a generator). pub generator_interior_types: ty::Binder<'tcx, Vec>>, + /// Stores the predicates that apply on generator witness types. + /// formatting modified file tests/ui/generator/retain-resume-ref.rs + pub generator_interior_predicates: + FxHashMap, ObligationCause<'tcx>)>>, + /// We sometimes treat byte string literals (which are of type `&[u8; N]`) /// as `&[u8]`, depending on the pattern in which they are used. /// This hashset records all instances where we behave @@ -271,6 +277,7 @@ impl<'tcx> TypeckResults<'tcx> { closure_fake_reads: Default::default(), rvalue_scopes: Default::default(), generator_interior_types: ty::Binder::dummy(Default::default()), + generator_interior_predicates: Default::default(), treat_byte_string_as_slice: Default::default(), closure_size_eval: Default::default(), } diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 3ed3b9f09459d..ce87931dbea02 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -615,6 +615,36 @@ impl<'tcx> TyCtxt<'tcx> { } } + /// Return the set of types that should be taken into accound when checking + /// trait bounds on a generator's internal state. + pub fn generator_hidden_types( + self, + def_id: DefId, + ) -> impl Iterator>> { + let generator_layout = &self.mir_generator_witnesses(def_id); + generator_layout + .field_tys + .iter() + .filter(|decl| !decl.is_static_ptr) + .map(|decl| ty::EarlyBinder(decl.ty)) + } + + /// Normalizes all opaque types in the given value, replacing them + /// with their underlying types. + pub fn expand_opaque_types(self, val: Ty<'tcx>) -> Ty<'tcx> { + let mut visitor = OpaqueTypeExpander { + seen_opaque_tys: FxHashSet::default(), + expanded_cache: FxHashMap::default(), + primary_def_id: None, + found_recursion: false, + found_any_recursion: false, + check_recursion: false, + expand_generators: false, + tcx: self, + }; + val.fold_with(&mut visitor) + } + /// Expands the given impl trait type, stopping if the type is recursive. #[instrument(skip(self), level = "debug", ret)] pub fn try_expand_impl_trait_type( @@ -629,6 +659,7 @@ impl<'tcx> TyCtxt<'tcx> { found_recursion: false, found_any_recursion: false, check_recursion: true, + expand_generators: true, tcx: self, }; @@ -741,6 +772,7 @@ struct OpaqueTypeExpander<'tcx> { primary_def_id: Option, found_recursion: bool, found_any_recursion: bool, + expand_generators: bool, /// Whether or not to check for recursive opaque types. /// This is `true` when we're explicitly checking for opaque type /// recursion, and 'false' otherwise to avoid unnecessary work. @@ -777,6 +809,37 @@ impl<'tcx> OpaqueTypeExpander<'tcx> { None } } + + fn expand_generator(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option> { + if self.found_any_recursion { + return None; + } + let substs = substs.fold_with(self); + if !self.check_recursion || self.seen_opaque_tys.insert(def_id) { + let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) { + Some(expanded_ty) => *expanded_ty, + None => { + for bty in self.tcx.generator_hidden_types(def_id) { + let hidden_ty = bty.subst(self.tcx, substs); + self.fold_ty(hidden_ty); + } + let expanded_ty = self.tcx.mk_generator_witness_mir(def_id, substs); + self.expanded_cache.insert((def_id, substs), expanded_ty); + expanded_ty + } + }; + if self.check_recursion { + self.seen_opaque_tys.remove(&def_id); + } + Some(expanded_ty) + } else { + // If another opaque type that we contain is recursive, then it + // will report the error, so we don't have to. + self.found_any_recursion = true; + self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap(); + None + } + } } impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> { @@ -785,13 +848,19 @@ impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> { } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { - if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) = *t.kind() { + let mut t = if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) = *t.kind() { self.expand_opaque_ty(def_id, substs).unwrap_or(t) - } else if t.has_opaque_types() { + } else if t.has_opaque_types() || t.has_generators() { t.super_fold_with(self) } else { t + }; + if self.expand_generators { + if let ty::GeneratorWitnessMIR(def_id, substs) = *t.kind() { + t = self.expand_generator(def_id, substs).unwrap_or(t); + } } + t } } @@ -1299,6 +1368,7 @@ pub fn reveal_opaque_types_in_bounds<'tcx>( found_recursion: false, found_any_recursion: false, check_recursion: false, + expand_generators: false, tcx, }; val.fold_with(&mut visitor) diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index 45507ed4dcc9a..a2c15123b4fbd 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -139,4 +139,11 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> { fn pending_obligations(&self) -> Vec> { self.obligations.clone() } + + fn drain_unstalled_obligations( + &mut self, + _: &InferCtxt<'tcx>, + ) -> Vec> { + unimplemented!() + } } diff --git a/compiler/rustc_trait_selection/src/traits/chalk_fulfill.rs b/compiler/rustc_trait_selection/src/traits/chalk_fulfill.rs index 76e31845797aa..e26bef0b8b7f5 100644 --- a/compiler/rustc_trait_selection/src/traits/chalk_fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/chalk_fulfill.rs @@ -135,6 +135,13 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> { errors } + fn drain_unstalled_obligations( + &mut self, + _: &InferCtxt<'tcx>, + ) -> Vec> { + unimplemented!() + } + fn pending_obligations(&self) -> Vec> { self.obligations.iter().cloned().collect() } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index bf5e77e6ce12f..827806442d2da 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -2226,7 +2226,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ); match *ty.kind() { - ty::Generator(did, ..) => { + ty::Generator(did, ..) | ty::GeneratorWitnessMIR(did, _) => { generator = generator.or(Some(did)); outer_generator = Some(did); } @@ -2256,7 +2256,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ); match *ty.kind() { - ty::Generator(did, ..) => { + ty::Generator(did, ..) | ty::GeneratorWitnessMIR(did, ..) => { generator = generator.or(Some(did)); outer_generator = Some(did); } @@ -2345,6 +2345,11 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { _ => return false, }; + let generator_within_in_progress_typeck = match &self.typeck_results { + Some(t) => t.hir_owner.to_def_id() == generator_did_root, + _ => false, + }; + let mut interior_or_upvar_span = None; let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches); @@ -2364,6 +2369,35 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { *span, Some((*scope_span, *yield_span, *expr, from_awaited_ty)), )); + + if interior_or_upvar_span.is_none() && generator_data.is_foreign() { + interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span, None)); + } + } else if self.tcx.sess.opts.unstable_opts.drop_tracking_mir + // Avoid disclosing internal information to downstream crates. + && generator_did.is_local() + // Try to avoid cycles. + && !generator_within_in_progress_typeck + { + let generator_info = &self.tcx.mir_generator_witnesses(generator_did); + debug!(?generator_info); + + 'find_source: for (variant, source_info) in + generator_info.variant_fields.iter().zip(&generator_info.variant_source_info) + { + debug!(?variant); + for &local in variant { + let decl = &generator_info.field_tys[local]; + debug!(?decl); + if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.is_static_ptr { + interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior( + decl.source_info.span, + Some((None, source_info.span, None, from_awaited_ty)), + )); + break 'find_source; + } + } + } } if interior_or_upvar_span.is_none() { @@ -3012,6 +3046,20 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } err.note(msg.trim_end_matches(", ")) } + ty::GeneratorWitnessMIR(def_id, substs) => { + use std::fmt::Write; + + // FIXME: this is kind of an unusual format for rustc, can we make it more clear? + // Maybe we should just remove this note altogether? + // FIXME: only print types which don't meet the trait requirement + let mut msg = + "required because it captures the following types: ".to_owned(); + for bty in tcx.generator_hidden_types(*def_id) { + let ty = bty.subst(tcx, substs); + write!(msg, "`{}`, ", ty).unwrap(); + } + err.note(msg.trim_end_matches(", ")) + } ty::Generator(def_id, _, _) => { let sp = self.tcx.def_span(def_id); diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index 111a2d034daa7..6c18bf8d22df8 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -141,6 +141,55 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> { self.select(selcx) } + fn drain_unstalled_obligations( + &mut self, + infcx: &InferCtxt<'tcx>, + ) -> Vec> { + let mut processor = DrainProcessor { removed_predicates: Vec::new(), infcx }; + let outcome: Outcome<_, _> = self.predicates.process_obligations(&mut processor); + assert!(outcome.errors.is_empty()); + return processor.removed_predicates; + + struct DrainProcessor<'a, 'tcx> { + infcx: &'a InferCtxt<'tcx>, + removed_predicates: Vec>, + } + + impl<'tcx> ObligationProcessor for DrainProcessor<'_, 'tcx> { + type Obligation = PendingPredicateObligation<'tcx>; + type Error = !; + type OUT = Outcome; + + fn needs_process_obligation(&self, pending_obligation: &Self::Obligation) -> bool { + pending_obligation + .stalled_on + .iter() + .any(|&var| self.infcx.ty_or_const_infer_var_changed(var)) + } + + fn process_obligation( + &mut self, + pending_obligation: &mut PendingPredicateObligation<'tcx>, + ) -> ProcessResult, !> { + assert!(self.needs_process_obligation(pending_obligation)); + self.removed_predicates.push(pending_obligation.obligation.clone()); + ProcessResult::Changed(vec![]) + } + + fn process_backedge<'c, I>( + &mut self, + cycle: I, + _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>, + ) -> Result<(), !> + where + I: Clone + Iterator>, + { + self.removed_predicates.extend(cycle.map(|c| c.obligation.clone())); + Ok(()) + } + } + } + fn pending_obligations(&self) -> Vec> { self.predicates.map_pending_obligations(|o| o.obligation.clone()) } diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 996a33cdd689a..61d3531cfc44e 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -13,7 +13,7 @@ use rustc_infer::infer::InferOk; use rustc_infer::infer::LateBoundRegionConversionTime::HigherRankedType; use rustc_middle::ty::{ self, Binder, GenericArg, GenericArgKind, GenericParamDefKind, InternalSubsts, SubstsRef, - ToPolyTraitRef, ToPredicate, TraitRef, Ty, TyCtxt, + ToPolyTraitRef, ToPredicate, TraitRef, Ty, TyCtxt, TypeVisitable, }; use rustc_session::config::TraitSolver; use rustc_span::def_id::DefId; @@ -1285,8 +1285,13 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::GeneratorWitness(tys) => { stack.extend(tcx.erase_late_bound_regions(tys).to_vec()); } - ty::GeneratorWitnessMIR(..) => { - todo!() + ty::GeneratorWitnessMIR(def_id, substs) => { + let tcx = self.tcx(); + stack.extend(tcx.generator_hidden_types(def_id).map(|bty| { + let ty = bty.subst(tcx, substs); + debug_assert!(!ty.has_late_bound_regions()); + ty + })) } // If we have a projection type, make sure to normalize it so we replace it diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index ba62d99f01a6c..efd21b979ceb5 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2183,8 +2183,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { Where(ty::Binder::bind_with_vars(witness_tys.to_vec(), all_vars)) } - ty::GeneratorWitnessMIR(..) => { - todo!() + ty::GeneratorWitnessMIR(def_id, ref substs) => { + let hidden_types = bind_generator_hidden_types_above( + self.infcx, + def_id, + substs, + obligation.predicate.bound_vars(), + ); + Where(hidden_types) } ty::Closure(_, substs) => { @@ -2284,8 +2290,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { types.map_bound(|types| types.to_vec()) } - ty::GeneratorWitnessMIR(..) => { - todo!() + ty::GeneratorWitnessMIR(def_id, ref substs) => { + bind_generator_hidden_types_above(self.infcx, def_id, substs, t.bound_vars()) } // For `PhantomData`, we pass `T`. @@ -2930,3 +2936,56 @@ pub enum ProjectionMatchesProjection { Ambiguous, No, } + +/// Replace all regions inside the generator interior with late bound regions. +/// Note that each region slot in the types gets a new fresh late bound region, which means that +/// none of the regions inside relate to any other, even if typeck had previously found constraints +/// that would cause them to be related. +#[instrument(level = "trace", skip(infcx), ret)] +fn bind_generator_hidden_types_above<'tcx>( + infcx: &InferCtxt<'tcx>, + def_id: DefId, + substs: ty::SubstsRef<'tcx>, + bound_vars: &ty::List, +) -> ty::Binder<'tcx, Vec>> { + let tcx = infcx.tcx; + let mut seen_tys = FxHashSet::default(); + + let considering_regions = infcx.considering_regions; + + let num_bound_variables = bound_vars.len() as u32; + let mut counter = num_bound_variables; + + let hidden_types: Vec<_> = tcx + .generator_hidden_types(def_id) + // Deduplicate tys to avoid repeated work. + .filter(|bty| seen_tys.insert(*bty)) + .map(|bty| { + let mut ty = bty.subst(tcx, substs); + + // Only remap erased regions if we use them. + if considering_regions { + ty = tcx.fold_regions(ty, |mut r, current_depth| { + if let ty::ReErased = r.kind() { + let br = ty::BoundRegion { + var: ty::BoundVar::from_u32(counter), + kind: ty::BrAnon(counter, None), + }; + counter += 1; + r = tcx.mk_region(ty::ReLateBound(current_depth, br)); + } + r + }) + } + + ty + }) + .collect(); + if considering_regions { + debug_assert!(!hidden_types.has_erased_regions()); + } + let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.iter().chain( + (num_bound_variables..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i, None))), + )); + ty::Binder::bind_with_vars(hidden_types, bound_vars) +} From 0e52a671d41a787fe236cfa158d004ee28836b11 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Thu, 26 Jan 2023 03:51:26 +0000 Subject: [PATCH 448/500] Bless tests. --- ...nc-await-let-else.drop_tracking_mir.stderr | 48 ++-- .../async-error-span.drop_tracking.stderr | 2 +- .../async-error-span.drop_tracking_mir.stderr | 13 +- .../async-error-span.no_drop_tracking.stderr | 2 +- tests/ui/async-await/async-error-span.rs | 4 +- tests/ui/async-await/async-error-span.stderr | 25 -- .../async-fn-nonsend.drop_tracking_mir.stderr | 83 +----- tests/ui/async-await/async-fn-nonsend.rs | 6 +- ...ld-assign-nonsend.drop_tracking_mir.stderr | 2 - ...ld-assign-nonsend.drop_tracking_mir.stderr | 2 - .../issue-64130-1-sync.drop_tracking.stderr | 3 +- ...ssue-64130-1-sync.drop_tracking_mir.stderr | 4 +- ...issue-64130-1-sync.no_drop_tracking.stderr | 3 +- tests/ui/async-await/issue-64130-1-sync.rs | 1 + .../issue-64130-2-send.drop_tracking.stderr | 10 +- ...ssue-64130-2-send.drop_tracking_mir.stderr | 12 +- ...issue-64130-2-send.no_drop_tracking.stderr | 10 +- tests/ui/async-await/issue-64130-2-send.rs | 2 +- .../issue-64130-3-other.drop_tracking.stderr | 4 +- ...sue-64130-3-other.drop_tracking_mir.stderr | 6 +- ...ssue-64130-3-other.no_drop_tracking.stderr | 4 +- tests/ui/async-await/issue-64130-3-other.rs | 2 +- ...4130-4-async-move.drop_tracking_mir.stderr | 26 -- ...64130-4-async-move.no_drop_tracking.stderr | 2 +- .../async-await/issue-64130-4-async-move.rs | 2 +- ...-67252-unnamed-future.drop_tracking.stderr | 14 +- ...52-unnamed-future.drop_tracking_mir.stderr | 20 +- ...252-unnamed-future.no_drop_tracking.stderr | 14 +- .../async-await/issue-67252-unnamed-future.rs | 3 +- .../issue-68112.drop_tracking_mir.stderr | 16 +- tests/ui/async-await/issue-68112.rs | 2 +- ...e-70935-complex-spans.drop_tracking.stderr | 4 +- ...935-complex-spans.drop_tracking_mir.stderr | 33 ++- ...0935-complex-spans.no_drop_tracking.stderr | 4 +- .../async-await/issue-70935-complex-spans.rs | 3 +- ...-raw-ptr-not-send.drop_tracking_mir.stderr | 33 --- ...6-raw-ptr-not-send.no_drop_tracking.stderr | 7 +- .../issues/issue-65436-raw-ptr-not-send.rs | 2 +- .../async-await/send-bound-async-closure.rs | 37 +++ ...unresolved_type_param.drop_tracking.stderr | 12 +- ...solved_type_param.drop_tracking_mir.stderr | 41 +-- ...esolved_type_param.no_drop_tracking.stderr | 38 ++- tests/ui/async-await/unresolved_type_param.rs | 35 ++- ...parent-expression.drop_tracking_mir.stderr | 226 +--------------- .../drop-tracking-parent-expression.rs | 12 +- .../issue-57017.drop_tracking_mir.stderr | 248 ------------------ .../issue-57017.no_drop_tracking.stderr | 42 +-- tests/ui/generator/issue-57017.rs | 13 +- .../issue-57478.drop_tracking_mir.stderr | 32 --- .../issue-57478.no_drop_tracking.stderr | 5 +- tests/ui/generator/issue-57478.rs | 2 +- .../issue-68112.drop_tracking_mir.stderr | 15 +- tests/ui/generator/issue-68112.rs | 6 +- .../not-send-sync.drop_tracking.stderr | 72 ++--- .../not-send-sync.drop_tracking_mir.stderr | 74 ++---- .../not-send-sync.no_drop_tracking.stderr | 72 ++--- tests/ui/generator/not-send-sync.rs | 16 +- ...parent-expression.drop_tracking_mir.stderr | 226 +--------------- tests/ui/generator/parent-expression.rs | 10 +- .../partial-drop.drop_tracking.stderr | 47 +--- .../partial-drop.drop_tracking_mir.stderr | 92 ------- .../partial-drop.no_drop_tracking.stderr | 47 +--- tests/ui/generator/partial-drop.rs | 17 +- tests/ui/generator/partial-drop.stderr | 92 ------- ...r-print-verbose-1.drop_tracking_mir.stderr | 14 +- .../print/generator-print-verbose-1.rs | 2 +- ...rator-print-verbose-2.drop_tracking.stderr | 72 ++--- ...r-print-verbose-2.drop_tracking_mir.stderr | 74 ++---- ...or-print-verbose-2.no_drop_tracking.stderr | 72 ++--- .../print/generator-print-verbose-2.rs | 16 +- .../issue-55872-2.drop_tracking_mir.stderr | 8 +- tests/ui/impl-trait/issue-55872-2.rs | 1 + .../infinite-impl-trait-issue-38064.stderr | 4 +- ...ait-type-indirect.drop_tracking_mir.stderr | 12 +- .../dedup.drop_tracking.stderr | 14 +- .../dedup.drop_tracking_mir.stderr | 14 +- .../dedup.no_drop_tracking.stderr | 28 +- tests/ui/lint/must_not_suspend/dedup.rs | 4 +- .../ref.drop_tracking_mir.stderr | 14 +- tests/ui/lint/must_not_suspend/ref.rs | 1 + tests/ui/lint/must_not_suspend/trait.rs | 3 + .../unit.drop_tracking.stderr | 6 +- .../unit.drop_tracking_mir.stderr | 6 +- .../unit.no_drop_tracking.stderr | 6 +- tests/ui/lint/must_not_suspend/unit.rs | 2 +- tests/ui/lint/must_not_suspend/warn.rs | 1 + 86 files changed, 643 insertions(+), 1693 deletions(-) delete mode 100644 tests/ui/async-await/async-error-span.stderr delete mode 100644 tests/ui/async-await/issue-64130-4-async-move.drop_tracking_mir.stderr delete mode 100644 tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.drop_tracking_mir.stderr create mode 100644 tests/ui/async-await/send-bound-async-closure.rs delete mode 100644 tests/ui/generator/issue-57017.drop_tracking_mir.stderr delete mode 100644 tests/ui/generator/issue-57478.drop_tracking_mir.stderr delete mode 100644 tests/ui/generator/partial-drop.drop_tracking_mir.stderr delete mode 100644 tests/ui/generator/partial-drop.stderr diff --git a/tests/ui/async-await/async-await-let-else.drop_tracking_mir.stderr b/tests/ui/async-await/async-await-let-else.drop_tracking_mir.stderr index d3c5e80a30df4..c284bbfb1cc66 100644 --- a/tests/ui/async-await/async-await-let-else.drop_tracking_mir.stderr +++ b/tests/ui/async-await/async-await-let-else.drop_tracking_mir.stderr @@ -12,30 +12,43 @@ LL | let r = Rc::new(()); | - has type `Rc<()>` which is not `Send` LL | bar().await | ^^^^^^ await occurs here, with `r` maybe used later -LL | }; - | - `r` is later dropped here note: required by a bound in `is_send` --> $DIR/async-await-let-else.rs:19:15 | LL | fn is_send(_: T) {} | ^^^^ required by this bound in `is_send` -error: future cannot be sent between threads safely +error[E0277]: `Rc<()>` cannot be sent between threads safely --> $DIR/async-await-let-else.rs:50:13 | +LL | async fn foo2(x: Option) { + | - within this `impl Future` +... LL | is_send(foo2(Some(true))); - | ^^^^^^^^^^^^^^^^ future returned by `foo2` is not `Send` + | ------- ^^^^^^^^^^^^^^^^ `Rc<()>` cannot be sent between threads safely + | | + | required by a bound introduced by this call | = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` -note: future is not `Send` as this value is used across an await - --> $DIR/async-await-let-else.rs:23:26 - | -LL | bar2(Rc::new(())).await - | ----------- ^^^^^^ await occurs here, with `Rc::new(())` maybe used later - | | - | has type `Rc<()>` which is not `Send` -LL | }; - | - `Rc::new(())` is later dropped here +note: required because it's used within this `async fn` body + --> $DIR/async-await-let-else.rs:27:29 + | +LL | async fn bar2(_: T) -> ! { + | _____________________________^ +LL | | panic!() +LL | | } + | |_^ + = note: required because it captures the following types: `impl Future` +note: required because it's used within this `async fn` body + --> $DIR/async-await-let-else.rs:21:32 + | +LL | async fn foo2(x: Option) { + | ________________________________^ +LL | | let Some(_) = x else { +LL | | bar2(Rc::new(())).await +LL | | }; +LL | | } + | |_^ note: required by a bound in `is_send` --> $DIR/async-await-let-else.rs:19:15 | @@ -53,9 +66,8 @@ note: future is not `Send` as this value is used across an await --> $DIR/async-await-let-else.rs:33:28 | LL | (Rc::new(()), bar().await); - | ----------- ^^^^^^ - `Rc::new(())` is later dropped here - | | | - | | await occurs here, with `Rc::new(())` maybe used later + | ----------- ^^^^^^ await occurs here, with `Rc::new(())` maybe used later + | | | has type `Rc<()>` which is not `Send` note: required by a bound in `is_send` --> $DIR/async-await-let-else.rs:19:15 @@ -77,9 +89,6 @@ LL | let r = Rc::new(()); | - has type `Rc<()>` which is not `Send` LL | bar().await; | ^^^^^^ await occurs here, with `r` maybe used later -... -LL | }; - | - `r` is later dropped here note: required by a bound in `is_send` --> $DIR/async-await-let-else.rs:19:15 | @@ -88,3 +97,4 @@ LL | fn is_send(_: T) {} error: aborting due to 4 previous errors +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/async-error-span.drop_tracking.stderr b/tests/ui/async-await/async-error-span.drop_tracking.stderr index 083da1cec7313..c6257cb324d9a 100644 --- a/tests/ui/async-await/async-error-span.drop_tracking.stderr +++ b/tests/ui/async-await/async-error-span.drop_tracking.stderr @@ -14,7 +14,7 @@ LL | let a; | ^ cannot infer type | note: the type is part of the `async fn` body because of this `await` - --> $DIR/async-error-span.rs:17:17 + --> $DIR/async-error-span.rs:19:17 | LL | get_future().await; | ^^^^^^ diff --git a/tests/ui/async-await/async-error-span.drop_tracking_mir.stderr b/tests/ui/async-await/async-error-span.drop_tracking_mir.stderr index 083da1cec7313..2f29ee6cdb0a1 100644 --- a/tests/ui/async-await/async-error-span.drop_tracking_mir.stderr +++ b/tests/ui/async-await/async-error-span.drop_tracking_mir.stderr @@ -7,19 +7,18 @@ LL | fn get_future() -> impl Future { = help: the trait `Future` is not implemented for `()` = note: () must be a future or must implement `IntoFuture` to be awaited -error[E0698]: type inside `async fn` body must be known in this context +error[E0282]: type annotations needed --> $DIR/async-error-span.rs:16:9 | LL | let a; - | ^ cannot infer type + | ^ | -note: the type is part of the `async fn` body because of this `await` - --> $DIR/async-error-span.rs:17:17 +help: consider giving `a` an explicit type | -LL | get_future().await; - | ^^^^^^ +LL | let a: /* Type */; + | ++++++++++++ error: aborting due to 2 previous errors -Some errors have detailed explanations: E0277, E0698. +Some errors have detailed explanations: E0277, E0282. For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/async-error-span.no_drop_tracking.stderr b/tests/ui/async-await/async-error-span.no_drop_tracking.stderr index 083da1cec7313..c6257cb324d9a 100644 --- a/tests/ui/async-await/async-error-span.no_drop_tracking.stderr +++ b/tests/ui/async-await/async-error-span.no_drop_tracking.stderr @@ -14,7 +14,7 @@ LL | let a; | ^ cannot infer type | note: the type is part of the `async fn` body because of this `await` - --> $DIR/async-error-span.rs:17:17 + --> $DIR/async-error-span.rs:19:17 | LL | get_future().await; | ^^^^^^ diff --git a/tests/ui/async-await/async-error-span.rs b/tests/ui/async-await/async-error-span.rs index 29b58ebc3a420..c9ecf359e3de5 100644 --- a/tests/ui/async-await/async-error-span.rs +++ b/tests/ui/async-await/async-error-span.rs @@ -13,7 +13,9 @@ fn get_future() -> impl Future { } async fn foo() { - let a; //~ ERROR type inside `async fn` body must be known in this context + let a; + //[no_drop_tracking,drop_tracking]~^ ERROR type inside `async fn` body must be known in this context + //[drop_tracking_mir]~^^ ERROR type annotations needed get_future().await; } diff --git a/tests/ui/async-await/async-error-span.stderr b/tests/ui/async-await/async-error-span.stderr deleted file mode 100644 index 083da1cec7313..0000000000000 --- a/tests/ui/async-await/async-error-span.stderr +++ /dev/null @@ -1,25 +0,0 @@ -error[E0277]: `()` is not a future - --> $DIR/async-error-span.rs:10:20 - | -LL | fn get_future() -> impl Future { - | ^^^^^^^^^^^^^^^^^^^^^^^^ `()` is not a future - | - = help: the trait `Future` is not implemented for `()` - = note: () must be a future or must implement `IntoFuture` to be awaited - -error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/async-error-span.rs:16:9 - | -LL | let a; - | ^ cannot infer type - | -note: the type is part of the `async fn` body because of this `await` - --> $DIR/async-error-span.rs:17:17 - | -LL | get_future().await; - | ^^^^^^ - -error: aborting due to 2 previous errors - -Some errors have detailed explanations: E0277, E0698. -For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/async-fn-nonsend.drop_tracking_mir.stderr b/tests/ui/async-await/async-fn-nonsend.drop_tracking_mir.stderr index 5cec21d890ef1..57a0128014554 100644 --- a/tests/ui/async-await/async-fn-nonsend.drop_tracking_mir.stderr +++ b/tests/ui/async-await/async-fn-nonsend.drop_tracking_mir.stderr @@ -1,26 +1,3 @@ -error: future cannot be sent between threads safely - --> $DIR/async-fn-nonsend.rs:70:17 - | -LL | assert_send(local_dropped_before_await()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `local_dropped_before_await` is not `Send` - | - = help: within `impl Future`, the trait `Send` is not implemented for `Rc<()>` -note: future is not `Send` as this value is used across an await - --> $DIR/async-fn-nonsend.rs:27:10 - | -LL | let x = non_send(); - | - has type `impl Debug` which is not `Send` -LL | drop(x); -LL | fut().await; - | ^^^^^^ await occurs here, with `x` maybe used later -LL | } - | - `x` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/async-fn-nonsend.rs:67:24 - | -LL | fn assert_send(_: impl Send) {} - | ^^^^ required by this bound in `assert_send` - error: future cannot be sent between threads safely --> $DIR/async-fn-nonsend.rs:72:17 | @@ -32,12 +9,9 @@ note: future is not `Send` as this value is used across an await --> $DIR/async-fn-nonsend.rs:36:25 | LL | match Some(non_send()) { - | ---------- has type `impl Debug` which is not `Send` + | ---------------- has type `Option` which is not `Send` LL | Some(_) => fut().await, - | ^^^^^^ await occurs here, with `non_send()` maybe used later -... -LL | } - | - `non_send()` is later dropped here + | ^^^^^^ await occurs here, with `Some(non_send())` maybe used later note: required by a bound in `assert_send` --> $DIR/async-fn-nonsend.rs:67:24 | @@ -59,62 +33,11 @@ LL | let f: &mut std::fmt::Formatter = &mut get_formatter(); ... LL | fut().await; | ^^^^^^ await occurs here, with `get_formatter()` maybe used later -LL | } -LL | } - | - `get_formatter()` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/async-fn-nonsend.rs:67:24 - | -LL | fn assert_send(_: impl Send) {} - | ^^^^ required by this bound in `assert_send` - -error: future cannot be sent between threads safely - --> $DIR/async-fn-nonsend.rs:76:17 - | -LL | assert_send(non_sync_with_method_call_panic()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_sync_with_method_call_panic` is not `Send` - | - = help: within `impl Future`, the trait `Send` is not implemented for `dyn std::fmt::Write` -note: future is not `Send` as this value is used across an await - --> $DIR/async-fn-nonsend.rs:56:14 - | -LL | let f: &mut std::fmt::Formatter = panic!(); - | - has type `&mut Formatter<'_>` which is not `Send` -LL | if non_sync().fmt(f).unwrap() == () { -LL | fut().await; - | ^^^^^^ await occurs here, with `f` maybe used later -LL | } -LL | } - | - `f` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/async-fn-nonsend.rs:67:24 - | -LL | fn assert_send(_: impl Send) {} - | ^^^^ required by this bound in `assert_send` - -error: future cannot be sent between threads safely - --> $DIR/async-fn-nonsend.rs:78:17 - | -LL | assert_send(non_sync_with_method_call_infinite_loop()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `non_sync_with_method_call_infinite_loop` is not `Send` - | - = help: within `impl Future`, the trait `Send` is not implemented for `dyn std::fmt::Write` -note: future is not `Send` as this value is used across an await - --> $DIR/async-fn-nonsend.rs:63:14 - | -LL | let f: &mut std::fmt::Formatter = loop {}; - | - has type `&mut Formatter<'_>` which is not `Send` -LL | if non_sync().fmt(f).unwrap() == () { -LL | fut().await; - | ^^^^^^ await occurs here, with `f` maybe used later -LL | } -LL | } - | - `f` is later dropped here note: required by a bound in `assert_send` --> $DIR/async-fn-nonsend.rs:67:24 | LL | fn assert_send(_: impl Send) {} | ^^^^ required by this bound in `assert_send` -error: aborting due to 5 previous errors +error: aborting due to 2 previous errors diff --git a/tests/ui/async-await/async-fn-nonsend.rs b/tests/ui/async-await/async-fn-nonsend.rs index 77c957d0592b7..ed440bd0182a6 100644 --- a/tests/ui/async-await/async-fn-nonsend.rs +++ b/tests/ui/async-await/async-fn-nonsend.rs @@ -68,13 +68,13 @@ fn assert_send(_: impl Send) {} pub fn pass_assert() { assert_send(local_dropped_before_await()); - //[no_drop_tracking,drop_tracking_mir]~^ ERROR future cannot be sent between threads safely + //[no_drop_tracking]~^ ERROR future cannot be sent between threads safely assert_send(non_send_temporary_in_match()); //~^ ERROR future cannot be sent between threads safely assert_send(non_sync_with_method_call()); //~^ ERROR future cannot be sent between threads safely assert_send(non_sync_with_method_call_panic()); - //[no_drop_tracking,drop_tracking_mir]~^ ERROR future cannot be sent between threads safely + //[no_drop_tracking]~^ ERROR future cannot be sent between threads safely assert_send(non_sync_with_method_call_infinite_loop()); - //[no_drop_tracking,drop_tracking_mir]~^ ERROR future cannot be sent between threads safely + //[no_drop_tracking]~^ ERROR future cannot be sent between threads safely } diff --git a/tests/ui/async-await/drop-track-field-assign-nonsend.drop_tracking_mir.stderr b/tests/ui/async-await/drop-track-field-assign-nonsend.drop_tracking_mir.stderr index e2bba812d05b1..b89d868040750 100644 --- a/tests/ui/async-await/drop-track-field-assign-nonsend.drop_tracking_mir.stderr +++ b/tests/ui/async-await/drop-track-field-assign-nonsend.drop_tracking_mir.stderr @@ -13,8 +13,6 @@ LL | let mut info = self.info_result.clone(); ... LL | let _ = send_element(element).await; | ^^^^^^ await occurs here, with `mut info` maybe used later -LL | } - | - `mut info` is later dropped here note: required by a bound in `assert_send` --> $DIR/drop-track-field-assign-nonsend.rs:40:19 | diff --git a/tests/ui/async-await/field-assign-nonsend.drop_tracking_mir.stderr b/tests/ui/async-await/field-assign-nonsend.drop_tracking_mir.stderr index ac461a671a82a..8c9d14d624cd9 100644 --- a/tests/ui/async-await/field-assign-nonsend.drop_tracking_mir.stderr +++ b/tests/ui/async-await/field-assign-nonsend.drop_tracking_mir.stderr @@ -13,8 +13,6 @@ LL | let mut info = self.info_result.clone(); ... LL | let _ = send_element(element).await; | ^^^^^^ await occurs here, with `mut info` maybe used later -LL | } - | - `mut info` is later dropped here note: required by a bound in `assert_send` --> $DIR/field-assign-nonsend.rs:40:19 | diff --git a/tests/ui/async-await/issue-64130-1-sync.drop_tracking.stderr b/tests/ui/async-await/issue-64130-1-sync.drop_tracking.stderr index 8d5169a6302ee..c4c7f26c7c70b 100644 --- a/tests/ui/async-await/issue-64130-1-sync.drop_tracking.stderr +++ b/tests/ui/async-await/issue-64130-1-sync.drop_tracking.stderr @@ -1,5 +1,5 @@ error: future cannot be shared between threads safely - --> $DIR/issue-64130-1-sync.rs:24:13 + --> $DIR/issue-64130-1-sync.rs:25:13 | LL | is_sync(bar()); | ^^^^^ future returned by `bar` is not `Sync` @@ -12,6 +12,7 @@ LL | let x = Foo; | - has type `Foo` which is not `Sync` LL | baz().await; | ^^^^^^ await occurs here, with `x` maybe used later +LL | drop(x); LL | } | - `x` is later dropped here note: required by a bound in `is_sync` diff --git a/tests/ui/async-await/issue-64130-1-sync.drop_tracking_mir.stderr b/tests/ui/async-await/issue-64130-1-sync.drop_tracking_mir.stderr index 8d5169a6302ee..6f43b568a7a68 100644 --- a/tests/ui/async-await/issue-64130-1-sync.drop_tracking_mir.stderr +++ b/tests/ui/async-await/issue-64130-1-sync.drop_tracking_mir.stderr @@ -1,5 +1,5 @@ error: future cannot be shared between threads safely - --> $DIR/issue-64130-1-sync.rs:24:13 + --> $DIR/issue-64130-1-sync.rs:25:13 | LL | is_sync(bar()); | ^^^^^ future returned by `bar` is not `Sync` @@ -12,8 +12,6 @@ LL | let x = Foo; | - has type `Foo` which is not `Sync` LL | baz().await; | ^^^^^^ await occurs here, with `x` maybe used later -LL | } - | - `x` is later dropped here note: required by a bound in `is_sync` --> $DIR/issue-64130-1-sync.rs:14:15 | diff --git a/tests/ui/async-await/issue-64130-1-sync.no_drop_tracking.stderr b/tests/ui/async-await/issue-64130-1-sync.no_drop_tracking.stderr index 8d5169a6302ee..c4c7f26c7c70b 100644 --- a/tests/ui/async-await/issue-64130-1-sync.no_drop_tracking.stderr +++ b/tests/ui/async-await/issue-64130-1-sync.no_drop_tracking.stderr @@ -1,5 +1,5 @@ error: future cannot be shared between threads safely - --> $DIR/issue-64130-1-sync.rs:24:13 + --> $DIR/issue-64130-1-sync.rs:25:13 | LL | is_sync(bar()); | ^^^^^ future returned by `bar` is not `Sync` @@ -12,6 +12,7 @@ LL | let x = Foo; | - has type `Foo` which is not `Sync` LL | baz().await; | ^^^^^^ await occurs here, with `x` maybe used later +LL | drop(x); LL | } | - `x` is later dropped here note: required by a bound in `is_sync` diff --git a/tests/ui/async-await/issue-64130-1-sync.rs b/tests/ui/async-await/issue-64130-1-sync.rs index 67c99c4817254..44646e0e5f27b 100644 --- a/tests/ui/async-await/issue-64130-1-sync.rs +++ b/tests/ui/async-await/issue-64130-1-sync.rs @@ -16,6 +16,7 @@ fn is_sync(t: T) { } async fn bar() { let x = Foo; baz().await; + drop(x); } async fn baz() { } diff --git a/tests/ui/async-await/issue-64130-2-send.drop_tracking.stderr b/tests/ui/async-await/issue-64130-2-send.drop_tracking.stderr index f6505cad69e21..b6a73c2a5cb83 100644 --- a/tests/ui/async-await/issue-64130-2-send.drop_tracking.stderr +++ b/tests/ui/async-await/issue-64130-2-send.drop_tracking.stderr @@ -4,12 +4,12 @@ error: future cannot be sent between threads safely LL | is_send(bar()); | ^^^^^ future returned by `bar` is not `Send` | - = help: within `impl Future`, the trait `Send` is not implemented for `Foo` + = note: the trait bound `Unique: Send` is not satisfied note: future is not `Send` as this value is used across an await --> $DIR/issue-64130-2-send.rs:18:10 | -LL | let x = Foo; - | - has type `Foo` which is not `Send` +LL | let x = Box::new(Foo); + | - has type `Box` which is not `Send` LL | baz().await; | ^^^^^^ await occurs here, with `x` maybe used later LL | } @@ -19,6 +19,10 @@ note: required by a bound in `is_send` | LL | fn is_send(t: T) { } | ^^^^ required by this bound in `is_send` +help: consider borrowing here + | +LL | is_send(&bar()); + | + error: aborting due to previous error diff --git a/tests/ui/async-await/issue-64130-2-send.drop_tracking_mir.stderr b/tests/ui/async-await/issue-64130-2-send.drop_tracking_mir.stderr index f6505cad69e21..560560f60366e 100644 --- a/tests/ui/async-await/issue-64130-2-send.drop_tracking_mir.stderr +++ b/tests/ui/async-await/issue-64130-2-send.drop_tracking_mir.stderr @@ -4,21 +4,23 @@ error: future cannot be sent between threads safely LL | is_send(bar()); | ^^^^^ future returned by `bar` is not `Send` | - = help: within `impl Future`, the trait `Send` is not implemented for `Foo` + = note: the trait bound `Unique: Send` is not satisfied note: future is not `Send` as this value is used across an await --> $DIR/issue-64130-2-send.rs:18:10 | -LL | let x = Foo; - | - has type `Foo` which is not `Send` +LL | let x = Box::new(Foo); + | - has type `Box` which is not `Send` LL | baz().await; | ^^^^^^ await occurs here, with `x` maybe used later -LL | } - | - `x` is later dropped here note: required by a bound in `is_send` --> $DIR/issue-64130-2-send.rs:14:15 | LL | fn is_send(t: T) { } | ^^^^ required by this bound in `is_send` +help: consider borrowing here + | +LL | is_send(&bar()); + | + error: aborting due to previous error diff --git a/tests/ui/async-await/issue-64130-2-send.no_drop_tracking.stderr b/tests/ui/async-await/issue-64130-2-send.no_drop_tracking.stderr index f6505cad69e21..b6a73c2a5cb83 100644 --- a/tests/ui/async-await/issue-64130-2-send.no_drop_tracking.stderr +++ b/tests/ui/async-await/issue-64130-2-send.no_drop_tracking.stderr @@ -4,12 +4,12 @@ error: future cannot be sent between threads safely LL | is_send(bar()); | ^^^^^ future returned by `bar` is not `Send` | - = help: within `impl Future`, the trait `Send` is not implemented for `Foo` + = note: the trait bound `Unique: Send` is not satisfied note: future is not `Send` as this value is used across an await --> $DIR/issue-64130-2-send.rs:18:10 | -LL | let x = Foo; - | - has type `Foo` which is not `Send` +LL | let x = Box::new(Foo); + | - has type `Box` which is not `Send` LL | baz().await; | ^^^^^^ await occurs here, with `x` maybe used later LL | } @@ -19,6 +19,10 @@ note: required by a bound in `is_send` | LL | fn is_send(t: T) { } | ^^^^ required by this bound in `is_send` +help: consider borrowing here + | +LL | is_send(&bar()); + | + error: aborting due to previous error diff --git a/tests/ui/async-await/issue-64130-2-send.rs b/tests/ui/async-await/issue-64130-2-send.rs index 2cb379fe88150..d6d855bac0762 100644 --- a/tests/ui/async-await/issue-64130-2-send.rs +++ b/tests/ui/async-await/issue-64130-2-send.rs @@ -14,7 +14,7 @@ impl !Send for Foo {} fn is_send(t: T) { } async fn bar() { - let x = Foo; + let x = Box::new(Foo); baz().await; } diff --git a/tests/ui/async-await/issue-64130-3-other.drop_tracking.stderr b/tests/ui/async-await/issue-64130-3-other.drop_tracking.stderr index cb36a3811b280..d65aae8cc3fdd 100644 --- a/tests/ui/async-await/issue-64130-3-other.drop_tracking.stderr +++ b/tests/ui/async-await/issue-64130-3-other.drop_tracking.stderr @@ -10,8 +10,8 @@ LL | is_qux(bar()); note: future does not implement `Qux` as this value is used across an await --> $DIR/issue-64130-3-other.rs:21:10 | -LL | let x = Foo; - | - has type `Foo` which does not implement `Qux` +LL | let x = Box::new(Foo); + | - has type `Box` which does not implement `Qux` LL | baz().await; | ^^^^^^ await occurs here, with `x` maybe used later LL | } diff --git a/tests/ui/async-await/issue-64130-3-other.drop_tracking_mir.stderr b/tests/ui/async-await/issue-64130-3-other.drop_tracking_mir.stderr index cb36a3811b280..8fed69d9d8898 100644 --- a/tests/ui/async-await/issue-64130-3-other.drop_tracking_mir.stderr +++ b/tests/ui/async-await/issue-64130-3-other.drop_tracking_mir.stderr @@ -10,12 +10,10 @@ LL | is_qux(bar()); note: future does not implement `Qux` as this value is used across an await --> $DIR/issue-64130-3-other.rs:21:10 | -LL | let x = Foo; - | - has type `Foo` which does not implement `Qux` +LL | let x = Box::new(Foo); + | - has type `Box` which does not implement `Qux` LL | baz().await; | ^^^^^^ await occurs here, with `x` maybe used later -LL | } - | - `x` is later dropped here note: required by a bound in `is_qux` --> $DIR/issue-64130-3-other.rs:17:14 | diff --git a/tests/ui/async-await/issue-64130-3-other.no_drop_tracking.stderr b/tests/ui/async-await/issue-64130-3-other.no_drop_tracking.stderr index cb36a3811b280..d65aae8cc3fdd 100644 --- a/tests/ui/async-await/issue-64130-3-other.no_drop_tracking.stderr +++ b/tests/ui/async-await/issue-64130-3-other.no_drop_tracking.stderr @@ -10,8 +10,8 @@ LL | is_qux(bar()); note: future does not implement `Qux` as this value is used across an await --> $DIR/issue-64130-3-other.rs:21:10 | -LL | let x = Foo; - | - has type `Foo` which does not implement `Qux` +LL | let x = Box::new(Foo); + | - has type `Box` which does not implement `Qux` LL | baz().await; | ^^^^^^ await occurs here, with `x` maybe used later LL | } diff --git a/tests/ui/async-await/issue-64130-3-other.rs b/tests/ui/async-await/issue-64130-3-other.rs index 6c242a60e1c6e..92d3b7c81fb62 100644 --- a/tests/ui/async-await/issue-64130-3-other.rs +++ b/tests/ui/async-await/issue-64130-3-other.rs @@ -17,7 +17,7 @@ impl !Qux for Foo {} fn is_qux(t: T) {} async fn bar() { - let x = Foo; + let x = Box::new(Foo); baz().await; } diff --git a/tests/ui/async-await/issue-64130-4-async-move.drop_tracking_mir.stderr b/tests/ui/async-await/issue-64130-4-async-move.drop_tracking_mir.stderr deleted file mode 100644 index 884619f4dd69d..0000000000000 --- a/tests/ui/async-await/issue-64130-4-async-move.drop_tracking_mir.stderr +++ /dev/null @@ -1,26 +0,0 @@ -error: future cannot be sent between threads safely - --> $DIR/issue-64130-4-async-move.rs:20:17 - | -LL | pub fn foo() -> impl Future + Send { - | ^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` - | - = help: the trait `Sync` is not implemented for `(dyn Any + Send + 'static)` -note: future is not `Send` as this value is used across an await - --> $DIR/issue-64130-4-async-move.rs:27:31 - | -LL | match client.status() { - | ------ has type `&Client` which is not `Send` -LL | 200 => { -LL | let _x = get().await; - | ^^^^^^ await occurs here, with `client` maybe used later -... -LL | } - | - `client` is later dropped here -help: consider moving this into a `let` binding to create a shorter lived borrow - --> $DIR/issue-64130-4-async-move.rs:25:15 - | -LL | match client.status() { - | ^^^^^^^^^^^^^^^ - -error: aborting due to previous error - diff --git a/tests/ui/async-await/issue-64130-4-async-move.no_drop_tracking.stderr b/tests/ui/async-await/issue-64130-4-async-move.no_drop_tracking.stderr index 884619f4dd69d..0bc7cb2f2acda 100644 --- a/tests/ui/async-await/issue-64130-4-async-move.no_drop_tracking.stderr +++ b/tests/ui/async-await/issue-64130-4-async-move.no_drop_tracking.stderr @@ -1,5 +1,5 @@ error: future cannot be sent between threads safely - --> $DIR/issue-64130-4-async-move.rs:20:17 + --> $DIR/issue-64130-4-async-move.rs:21:17 | LL | pub fn foo() -> impl Future + Send { | ^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` diff --git a/tests/ui/async-await/issue-64130-4-async-move.rs b/tests/ui/async-await/issue-64130-4-async-move.rs index 13dceabb62f3b..bcb297aaa0258 100644 --- a/tests/ui/async-await/issue-64130-4-async-move.rs +++ b/tests/ui/async-await/issue-64130-4-async-move.rs @@ -2,6 +2,7 @@ // revisions: no_drop_tracking drop_tracking drop_tracking_mir // [drop_tracking] compile-flags: -Zdrop-tracking // [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir +// [drop_tracking_mir] check-pass // [drop_tracking] check-pass use std::any::Any; @@ -19,7 +20,6 @@ async fn get() {} pub fn foo() -> impl Future + Send { //[no_drop_tracking]~^ ERROR future cannot be sent between threads safely - //[drop_tracking_mir]~^^ ERROR future cannot be sent between threads safely let client = Client(Box::new(true)); async move { match client.status() { diff --git a/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking.stderr b/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking.stderr index e7a302fb3efcd..fc8bcc8ae7964 100644 --- a/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking.stderr +++ b/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking.stderr @@ -3,21 +3,23 @@ error: future cannot be sent between threads safely | LL | spawn(async { | ___________^ -LL | | let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` +LL | | let a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` LL | | AFuture.await; +LL | | drop(a); LL | | }); | |_____^ future created by async block is not `Send` | - = help: within `[async block@$DIR/issue-67252-unnamed-future.rs:21:11: 24:6]`, the trait `Send` is not implemented for `*mut ()` + = help: within `[async block@$DIR/issue-67252-unnamed-future.rs:21:11: 25:6]`, the trait `Send` is not implemented for `*mut ()` note: future is not `Send` as this value is used across an await --> $DIR/issue-67252-unnamed-future.rs:23:16 | -LL | let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` - | -- has type `*mut ()` which is not `Send` +LL | let a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` + | - has type `*mut ()` which is not `Send` LL | AFuture.await; - | ^^^^^^ await occurs here, with `_a` maybe used later + | ^^^^^^ await occurs here, with `a` maybe used later +LL | drop(a); LL | }); - | - `_a` is later dropped here + | - `a` is later dropped here note: required by a bound in `spawn` --> $DIR/issue-67252-unnamed-future.rs:9:13 | diff --git a/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking_mir.stderr b/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking_mir.stderr index e7a302fb3efcd..a3ef7add11669 100644 --- a/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking_mir.stderr +++ b/tests/ui/async-await/issue-67252-unnamed-future.drop_tracking_mir.stderr @@ -1,23 +1,17 @@ error: future cannot be sent between threads safely - --> $DIR/issue-67252-unnamed-future.rs:21:11 + --> $DIR/issue-67252-unnamed-future.rs:21:5 | -LL | spawn(async { - | ___________^ -LL | | let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` -LL | | AFuture.await; -LL | | }); - | |_____^ future created by async block is not `Send` +LL | spawn(async { + | ^^^^^ future created by async block is not `Send` | - = help: within `[async block@$DIR/issue-67252-unnamed-future.rs:21:11: 24:6]`, the trait `Send` is not implemented for `*mut ()` + = help: within `[async block@$DIR/issue-67252-unnamed-future.rs:21:11: 25:6]`, the trait `Send` is not implemented for `*mut ()` note: future is not `Send` as this value is used across an await --> $DIR/issue-67252-unnamed-future.rs:23:16 | -LL | let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` - | -- has type `*mut ()` which is not `Send` +LL | let a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` + | - has type `*mut ()` which is not `Send` LL | AFuture.await; - | ^^^^^^ await occurs here, with `_a` maybe used later -LL | }); - | - `_a` is later dropped here + | ^^^^^^ await occurs here, with `a` maybe used later note: required by a bound in `spawn` --> $DIR/issue-67252-unnamed-future.rs:9:13 | diff --git a/tests/ui/async-await/issue-67252-unnamed-future.no_drop_tracking.stderr b/tests/ui/async-await/issue-67252-unnamed-future.no_drop_tracking.stderr index e7a302fb3efcd..fc8bcc8ae7964 100644 --- a/tests/ui/async-await/issue-67252-unnamed-future.no_drop_tracking.stderr +++ b/tests/ui/async-await/issue-67252-unnamed-future.no_drop_tracking.stderr @@ -3,21 +3,23 @@ error: future cannot be sent between threads safely | LL | spawn(async { | ___________^ -LL | | let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` +LL | | let a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` LL | | AFuture.await; +LL | | drop(a); LL | | }); | |_____^ future created by async block is not `Send` | - = help: within `[async block@$DIR/issue-67252-unnamed-future.rs:21:11: 24:6]`, the trait `Send` is not implemented for `*mut ()` + = help: within `[async block@$DIR/issue-67252-unnamed-future.rs:21:11: 25:6]`, the trait `Send` is not implemented for `*mut ()` note: future is not `Send` as this value is used across an await --> $DIR/issue-67252-unnamed-future.rs:23:16 | -LL | let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` - | -- has type `*mut ()` which is not `Send` +LL | let a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` + | - has type `*mut ()` which is not `Send` LL | AFuture.await; - | ^^^^^^ await occurs here, with `_a` maybe used later + | ^^^^^^ await occurs here, with `a` maybe used later +LL | drop(a); LL | }); - | - `_a` is later dropped here + | - `a` is later dropped here note: required by a bound in `spawn` --> $DIR/issue-67252-unnamed-future.rs:9:13 | diff --git a/tests/ui/async-await/issue-67252-unnamed-future.rs b/tests/ui/async-await/issue-67252-unnamed-future.rs index 658f059cf81cb..bb9ad77cef31d 100644 --- a/tests/ui/async-await/issue-67252-unnamed-future.rs +++ b/tests/ui/async-await/issue-67252-unnamed-future.rs @@ -19,8 +19,9 @@ impl Future for AFuture{ async fn foo() { spawn(async { //~ ERROR future cannot be sent between threads safely - let _a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` + let a = std::ptr::null_mut::<()>(); // `*mut ()` is not `Send` AFuture.await; + drop(a); }); } diff --git a/tests/ui/async-await/issue-68112.drop_tracking_mir.stderr b/tests/ui/async-await/issue-68112.drop_tracking_mir.stderr index 35b7341f63a4d..7a9242cbaf591 100644 --- a/tests/ui/async-await/issue-68112.drop_tracking_mir.stderr +++ b/tests/ui/async-await/issue-68112.drop_tracking_mir.stderr @@ -1,8 +1,8 @@ error: future cannot be sent between threads safely - --> $DIR/issue-68112.rs:37:18 + --> $DIR/issue-68112.rs:37:5 | LL | require_send(send_fut); - | ^^^^^^^^ future created by async block is not `Send` + | ^^^^^^^^^^^^ future created by async block is not `Send` | = help: the trait `Sync` is not implemented for `RefCell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead @@ -18,10 +18,10 @@ LL | fn require_send(_: impl Send) {} | ^^^^ required by this bound in `require_send` error: future cannot be sent between threads safely - --> $DIR/issue-68112.rs:46:18 + --> $DIR/issue-68112.rs:46:5 | LL | require_send(send_fut); - | ^^^^^^^^ future created by async block is not `Send` + | ^^^^^^^^^^^^ future created by async block is not `Send` | = help: the trait `Sync` is not implemented for `RefCell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead @@ -37,12 +37,10 @@ LL | fn require_send(_: impl Send) {} | ^^^^ required by this bound in `require_send` error[E0277]: `RefCell` cannot be shared between threads safely - --> $DIR/issue-68112.rs:65:18 + --> $DIR/issue-68112.rs:65:5 | LL | require_send(send_fut); - | ------------ ^^^^^^^^ `RefCell` cannot be shared between threads safely - | | - | required by a bound introduced by this call + | ^^^^^^^^^^^^ `RefCell` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `RefCell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead @@ -60,7 +58,7 @@ note: required because it appears within the type `impl Future impl Future>> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: required because it captures the following types: `ResumeTy`, `impl Future>>`, `()`, `i32`, `Ready` + = note: required because it captures the following types: `impl Future>>`, `Ready` note: required because it's used within this `async` block --> $DIR/issue-68112.rs:60:20 | diff --git a/tests/ui/async-await/issue-68112.rs b/tests/ui/async-await/issue-68112.rs index 7f0a135a15961..19119ae0fc127 100644 --- a/tests/ui/async-await/issue-68112.rs +++ b/tests/ui/async-await/issue-68112.rs @@ -14,7 +14,7 @@ use std::{ fn require_send(_: impl Send) {} struct Ready(Option); -impl Future for Ready { +impl Future for Ready { type Output = T; fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll { Poll::Ready(self.0.take().unwrap()) diff --git a/tests/ui/async-await/issue-70935-complex-spans.drop_tracking.stderr b/tests/ui/async-await/issue-70935-complex-spans.drop_tracking.stderr index ea61daa5a1683..721234aa4a782 100644 --- a/tests/ui/async-await/issue-70935-complex-spans.drop_tracking.stderr +++ b/tests/ui/async-await/issue-70935-complex-spans.drop_tracking.stderr @@ -7,7 +7,7 @@ LL | fn foo(tx: std::sync::mpsc::Sender) -> impl Future + Send { = help: the trait `Sync` is not implemented for `Sender` = note: required for `&Sender` to implement `Send` note: required because it's used within this closure - --> $DIR/issue-70935-complex-spans.rs:18:13 + --> $DIR/issue-70935-complex-spans.rs:17:13 | LL | baz(|| async{ | ^^ @@ -20,7 +20,7 @@ LL | | } | |_^ = note: required because it captures the following types: `ResumeTy`, `impl Future`, `()` note: required because it's used within this `async` block - --> $DIR/issue-70935-complex-spans.rs:17:5 + --> $DIR/issue-70935-complex-spans.rs:16:5 | LL | / async move { LL | | baz(|| async{ diff --git a/tests/ui/async-await/issue-70935-complex-spans.drop_tracking_mir.stderr b/tests/ui/async-await/issue-70935-complex-spans.drop_tracking_mir.stderr index 6c48e6db45777..c636be15a585c 100644 --- a/tests/ui/async-await/issue-70935-complex-spans.drop_tracking_mir.stderr +++ b/tests/ui/async-await/issue-70935-complex-spans.drop_tracking_mir.stderr @@ -1,21 +1,34 @@ -error: future cannot be sent between threads safely +error[E0277]: `Sender` cannot be shared between threads safely --> $DIR/issue-70935-complex-spans.rs:13:45 | LL | fn foo(tx: std::sync::mpsc::Sender) -> impl Future + Send { - | ^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` + | ^^^^^^^^^^^^^^^^^^ `Sender` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `Sender` -note: future is not `Send` as this value is used across an await - --> $DIR/issue-70935-complex-spans.rs:20:11 + = note: required for `&Sender` to implement `Send` +note: required because it's used within this closure + --> $DIR/issue-70935-complex-spans.rs:17:13 | -LL | baz(|| async{ - | _____________- +LL | baz(|| async{ + | ^^ +note: required because it's used within this `async fn` body + --> $DIR/issue-70935-complex-spans.rs:10:67 + | +LL | async fn baz(_c: impl FnMut() -> T) where T: Future { + | ___________________________________________________________________^ +LL | | } + | |_^ + = note: required because it captures the following types: `impl Future` +note: required because it's used within this `async` block + --> $DIR/issue-70935-complex-spans.rs:16:5 + | +LL | / async move { +LL | | baz(|| async{ LL | | foo(tx.clone()); LL | | }).await; - | | - ^^^^^^- the value is later dropped here - | | | | - | |_________| await occurs here, with the value maybe used later - | has type `[closure@$DIR/issue-70935-complex-spans.rs:18:13: 18:15]` which is not `Send` +LL | | } + | |_____^ error: aborting due to previous error +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/async-await/issue-70935-complex-spans.no_drop_tracking.stderr b/tests/ui/async-await/issue-70935-complex-spans.no_drop_tracking.stderr index 6c48e6db45777..8036d82daa4a3 100644 --- a/tests/ui/async-await/issue-70935-complex-spans.no_drop_tracking.stderr +++ b/tests/ui/async-await/issue-70935-complex-spans.no_drop_tracking.stderr @@ -6,7 +6,7 @@ LL | fn foo(tx: std::sync::mpsc::Sender) -> impl Future + Send { | = help: the trait `Sync` is not implemented for `Sender` note: future is not `Send` as this value is used across an await - --> $DIR/issue-70935-complex-spans.rs:20:11 + --> $DIR/issue-70935-complex-spans.rs:19:11 | LL | baz(|| async{ | _____________- @@ -15,7 +15,7 @@ LL | | }).await; | | - ^^^^^^- the value is later dropped here | | | | | |_________| await occurs here, with the value maybe used later - | has type `[closure@$DIR/issue-70935-complex-spans.rs:18:13: 18:15]` which is not `Send` + | has type `[closure@$DIR/issue-70935-complex-spans.rs:17:13: 17:15]` which is not `Send` error: aborting due to previous error diff --git a/tests/ui/async-await/issue-70935-complex-spans.rs b/tests/ui/async-await/issue-70935-complex-spans.rs index 76cd293b05b67..78625bd393d25 100644 --- a/tests/ui/async-await/issue-70935-complex-spans.rs +++ b/tests/ui/async-await/issue-70935-complex-spans.rs @@ -12,8 +12,7 @@ async fn baz(_c: impl FnMut() -> T) where T: Future { fn foo(tx: std::sync::mpsc::Sender) -> impl Future + Send { //[no_drop_tracking]~^ ERROR future cannot be sent between threads safely - //[drop_tracking]~^^ ERROR `Sender` cannot be shared between threads - //[drop_tracking_mir]~^^^ ERROR future cannot be sent between threads safely + //[drop_tracking,drop_tracking_mir]~^^ ERROR `Sender` cannot be shared between threads async move { baz(|| async{ foo(tx.clone()); diff --git a/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.drop_tracking_mir.stderr b/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.drop_tracking_mir.stderr deleted file mode 100644 index 8b75d95a68eed..0000000000000 --- a/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.drop_tracking_mir.stderr +++ /dev/null @@ -1,33 +0,0 @@ -error: future cannot be sent between threads safely - --> $DIR/issue-65436-raw-ptr-not-send.rs:16:17 - | -LL | assert_send(async { - | _________________^ -LL | | -LL | | -LL | | bar(Foo(std::ptr::null())).await; -LL | | }) - | |_____^ future created by async block is not `Send` - | - = help: within `[async block@$DIR/issue-65436-raw-ptr-not-send.rs:16:17: 20:6]`, the trait `Send` is not implemented for `*const u8` -note: future is not `Send` as this value is used across an await - --> $DIR/issue-65436-raw-ptr-not-send.rs:19:35 - | -LL | bar(Foo(std::ptr::null())).await; - | ---------------- ^^^^^^- `std::ptr::null()` is later dropped here - | | | - | | await occurs here, with `std::ptr::null()` maybe used later - | has type `*const u8` which is not `Send` -help: consider moving this into a `let` binding to create a shorter lived borrow - --> $DIR/issue-65436-raw-ptr-not-send.rs:19:13 - | -LL | bar(Foo(std::ptr::null())).await; - | ^^^^^^^^^^^^^^^^^^^^^ -note: required by a bound in `assert_send` - --> $DIR/issue-65436-raw-ptr-not-send.rs:13:19 - | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: aborting due to previous error - diff --git a/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.no_drop_tracking.stderr b/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.no_drop_tracking.stderr index 8b75d95a68eed..8745bdd973bea 100644 --- a/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.no_drop_tracking.stderr +++ b/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.no_drop_tracking.stderr @@ -1,15 +1,14 @@ error: future cannot be sent between threads safely - --> $DIR/issue-65436-raw-ptr-not-send.rs:16:17 + --> $DIR/issue-65436-raw-ptr-not-send.rs:17:17 | LL | assert_send(async { | _________________^ LL | | -LL | | LL | | bar(Foo(std::ptr::null())).await; LL | | }) | |_____^ future created by async block is not `Send` | - = help: within `[async block@$DIR/issue-65436-raw-ptr-not-send.rs:16:17: 20:6]`, the trait `Send` is not implemented for `*const u8` + = help: within `[async block@$DIR/issue-65436-raw-ptr-not-send.rs:17:17: 20:6]`, the trait `Send` is not implemented for `*const u8` note: future is not `Send` as this value is used across an await --> $DIR/issue-65436-raw-ptr-not-send.rs:19:35 | @@ -24,7 +23,7 @@ help: consider moving this into a `let` binding to create a shorter lived borrow LL | bar(Foo(std::ptr::null())).await; | ^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `assert_send` - --> $DIR/issue-65436-raw-ptr-not-send.rs:13:19 + --> $DIR/issue-65436-raw-ptr-not-send.rs:14:19 | LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` diff --git a/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.rs b/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.rs index 630e0e4eebe16..d7ef929517c74 100644 --- a/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.rs +++ b/tests/ui/async-await/issues/issue-65436-raw-ptr-not-send.rs @@ -3,6 +3,7 @@ // [drop_tracking] compile-flags: -Zdrop-tracking // [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // [drop_tracking] check-pass +// [drop_tracking_mir] check-pass struct Foo(*const u8); @@ -15,7 +16,6 @@ fn assert_send(_: T) {} fn main() { assert_send(async { //[no_drop_tracking]~^ ERROR future cannot be sent between threads safely - //[drop_tracking_mir]~^^ ERROR future cannot be sent between threads safely bar(Foo(std::ptr::null())).await; }) } diff --git a/tests/ui/async-await/send-bound-async-closure.rs b/tests/ui/async-await/send-bound-async-closure.rs new file mode 100644 index 0000000000000..4e9e7309be091 --- /dev/null +++ b/tests/ui/async-await/send-bound-async-closure.rs @@ -0,0 +1,37 @@ +// edition: 2021 +// check-pass + +// This test verifies that we do not create a query cycle when typechecking has several inference +// variables that point to the same generator interior type. + +use std::future::Future; +use std::pin::Pin; +use std::task::{Context, Poll}; + +type ChannelTask = Pin + Send>>; + +pub fn register_message_type() -> ChannelTask { + Box::pin(async move { + let f = |__cx: &mut Context<'_>| Poll::<()>::Pending; + PollFn { f }.await + }) +} + +struct PollFn { + f: F, +} + +impl Unpin for PollFn {} + +impl Future for PollFn +where + F: FnMut(&mut Context<'_>) -> Poll, +{ + type Output = T; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + (&mut self.f)(cx) + } +} + +fn main() {} diff --git a/tests/ui/async-await/unresolved_type_param.drop_tracking.stderr b/tests/ui/async-await/unresolved_type_param.drop_tracking.stderr index 64a31b5fc32dc..912e2b34c0541 100644 --- a/tests/ui/async-await/unresolved_type_param.drop_tracking.stderr +++ b/tests/ui/async-await/unresolved_type_param.drop_tracking.stderr @@ -1,35 +1,35 @@ error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:13:5 + --> $DIR/unresolved_type_param.rs:12:5 | LL | bar().await; | ^^^ cannot infer type for type parameter `T` declared on the function `bar` | note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:13:10 + --> $DIR/unresolved_type_param.rs:12:10 | LL | bar().await; | ^^^^^^ error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:13:5 + --> $DIR/unresolved_type_param.rs:12:5 | LL | bar().await; | ^^^ cannot infer type for type parameter `T` declared on the function `bar` | note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:13:10 + --> $DIR/unresolved_type_param.rs:12:10 | LL | bar().await; | ^^^^^^ error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:13:5 + --> $DIR/unresolved_type_param.rs:12:5 | LL | bar().await; | ^^^ cannot infer type for type parameter `T` declared on the function `bar` | note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:13:10 + --> $DIR/unresolved_type_param.rs:12:10 | LL | bar().await; | ^^^^^^ diff --git a/tests/ui/async-await/unresolved_type_param.drop_tracking_mir.stderr b/tests/ui/async-await/unresolved_type_param.drop_tracking_mir.stderr index 64a31b5fc32dc..95c799468314f 100644 --- a/tests/ui/async-await/unresolved_type_param.drop_tracking_mir.stderr +++ b/tests/ui/async-await/unresolved_type_param.drop_tracking_mir.stderr @@ -1,39 +1,14 @@ -error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:13:5 +error[E0282]: type annotations needed + --> $DIR/unresolved_type_param.rs:12:5 | LL | bar().await; - | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | ^^^ cannot infer type of the type parameter `T` declared on the function `bar` | -note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:13:10 +help: consider specifying the generic argument | -LL | bar().await; - | ^^^^^^ - -error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:13:5 - | -LL | bar().await; - | ^^^ cannot infer type for type parameter `T` declared on the function `bar` - | -note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:13:10 - | -LL | bar().await; - | ^^^^^^ - -error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:13:5 - | -LL | bar().await; - | ^^^ cannot infer type for type parameter `T` declared on the function `bar` - | -note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:13:10 - | -LL | bar().await; - | ^^^^^^ +LL | bar::().await; + | +++++ -error: aborting due to 3 previous errors +error: aborting due to previous error -For more information about this error, try `rustc --explain E0698`. +For more information about this error, try `rustc --explain E0282`. diff --git a/tests/ui/async-await/unresolved_type_param.no_drop_tracking.stderr b/tests/ui/async-await/unresolved_type_param.no_drop_tracking.stderr index 64a31b5fc32dc..16d618caa5713 100644 --- a/tests/ui/async-await/unresolved_type_param.no_drop_tracking.stderr +++ b/tests/ui/async-await/unresolved_type_param.no_drop_tracking.stderr @@ -1,39 +1,63 @@ error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:13:5 + --> $DIR/unresolved_type_param.rs:12:5 | LL | bar().await; | ^^^ cannot infer type for type parameter `T` declared on the function `bar` | note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:13:10 + --> $DIR/unresolved_type_param.rs:12:10 | LL | bar().await; | ^^^^^^ error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:13:5 + --> $DIR/unresolved_type_param.rs:12:5 | LL | bar().await; | ^^^ cannot infer type for type parameter `T` declared on the function `bar` | note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:13:10 + --> $DIR/unresolved_type_param.rs:12:10 | LL | bar().await; | ^^^^^^ error[E0698]: type inside `async fn` body must be known in this context - --> $DIR/unresolved_type_param.rs:13:5 + --> $DIR/unresolved_type_param.rs:12:5 | LL | bar().await; | ^^^ cannot infer type for type parameter `T` declared on the function `bar` | note: the type is part of the `async fn` body because of this `await` - --> $DIR/unresolved_type_param.rs:13:10 + --> $DIR/unresolved_type_param.rs:12:10 | LL | bar().await; | ^^^^^^ -error: aborting due to 3 previous errors +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/unresolved_type_param.rs:12:5 + | +LL | bar().await; + | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/unresolved_type_param.rs:12:10 + | +LL | bar().await; + | ^^^^^^ + +error[E0698]: type inside `async fn` body must be known in this context + --> $DIR/unresolved_type_param.rs:12:5 + | +LL | bar().await; + | ^^^ cannot infer type for type parameter `T` declared on the function `bar` + | +note: the type is part of the `async fn` body because of this `await` + --> $DIR/unresolved_type_param.rs:12:10 + | +LL | bar().await; + | ^^^^^^ + +error: aborting due to 5 previous errors For more information about this error, try `rustc --explain E0698`. diff --git a/tests/ui/async-await/unresolved_type_param.rs b/tests/ui/async-await/unresolved_type_param.rs index c9e77f0c3ea7a..ca0a92b943473 100644 --- a/tests/ui/async-await/unresolved_type_param.rs +++ b/tests/ui/async-await/unresolved_type_param.rs @@ -5,23 +5,32 @@ // Error message should pinpoint the type parameter T as needing to be bound // (rather than give a general error message) // edition:2018 -// compile-flags: -Zdrop-tracking async fn bar() -> () {} async fn foo() { bar().await; - //~^ ERROR type inside `async fn` body must be known in this context - //~| ERROR type inside `async fn` body must be known in this context - //~| ERROR type inside `async fn` body must be known in this context - //~| NOTE cannot infer type for type parameter `T` - //~| NOTE cannot infer type for type parameter `T` - //~| NOTE cannot infer type for type parameter `T` - //~| NOTE the type is part of the `async fn` body because of this `await` - //~| NOTE the type is part of the `async fn` body because of this `await` - //~| NOTE the type is part of the `async fn` body because of this `await` - //~| NOTE in this expansion of desugaring of `await` - //~| NOTE in this expansion of desugaring of `await` - //~| NOTE in this expansion of desugaring of `await` + //[drop_tracking_mir]~^ ERROR type annotations needed + //[drop_tracking_mir]~| NOTE cannot infer type of the type parameter `T` + //[no_drop_tracking,drop_tracking]~^^^ ERROR type inside `async fn` body must be known in this context + //[no_drop_tracking,drop_tracking]~| ERROR type inside `async fn` body must be known in this context + //[no_drop_tracking,drop_tracking]~| ERROR type inside `async fn` body must be known in this context + //[no_drop_tracking,drop_tracking]~| NOTE cannot infer type for type parameter `T` + //[no_drop_tracking,drop_tracking]~| NOTE cannot infer type for type parameter `T` + //[no_drop_tracking,drop_tracking]~| NOTE cannot infer type for type parameter `T` + //[no_drop_tracking,drop_tracking]~| NOTE the type is part of the `async fn` body because of this `await` + //[no_drop_tracking,drop_tracking]~| NOTE the type is part of the `async fn` body because of this `await` + //[no_drop_tracking,drop_tracking]~| NOTE the type is part of the `async fn` body because of this `await` + //[no_drop_tracking,drop_tracking]~| NOTE in this expansion of desugaring of `await` + //[no_drop_tracking,drop_tracking]~| NOTE in this expansion of desugaring of `await` + //[no_drop_tracking,drop_tracking]~| NOTE in this expansion of desugaring of `await` + //[no_drop_tracking]~^^^^^^^^^^^^^^^ ERROR type inside `async fn` body must be known in this context + //[no_drop_tracking]~| ERROR type inside `async fn` body must be known in this context + //[no_drop_tracking]~| NOTE cannot infer type for type parameter `T` + //[no_drop_tracking]~| NOTE cannot infer type for type parameter `T` + //[no_drop_tracking]~| NOTE the type is part of the `async fn` body because of this `await` + //[no_drop_tracking]~| NOTE the type is part of the `async fn` body because of this `await` + //[no_drop_tracking]~| NOTE in this expansion of desugaring of `await` + //[no_drop_tracking]~| NOTE in this expansion of desugaring of `await` } fn main() {} diff --git a/tests/ui/generator/drop-tracking-parent-expression.drop_tracking_mir.stderr b/tests/ui/generator/drop-tracking-parent-expression.drop_tracking_mir.stderr index 1a05bfe4f0e6a..35698a98dbd62 100644 --- a/tests/ui/generator/drop-tracking-parent-expression.drop_tracking_mir.stderr +++ b/tests/ui/generator/drop-tracking-parent-expression.drop_tracking_mir.stderr @@ -1,91 +1,8 @@ error: generator cannot be sent between threads safely - --> $DIR/drop-tracking-parent-expression.rs:27:25 + --> $DIR/drop-tracking-parent-expression.rs:27:13 | LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `copy::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/drop-tracking-parent-expression.rs:25:22 - | -LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { - | ------------------------ has type `copy::Client` which is not `Send` -... -LL | _ => yield, - | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/drop-tracking-parent-expression.rs:49:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/drop-tracking-parent-expression.rs:40:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `copy::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/drop-tracking-parent-expression.rs:38:22 - | -LL | let g = move || match drop($name::Client::default()) { - | ------------------------ has type `copy::Client` which is not `Send` -LL | _ => yield, - | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/drop-tracking-parent-expression.rs:49:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/drop-tracking-parent-expression.rs:27:25 - | -LL | assert_send(g); - | ^ generator is not `Send` + | ^^^^^^^^^^^ generator is not `Send` ... LL | / type_combinations!( LL | | // OK @@ -105,49 +22,6 @@ LL | let g = move || match drop($name::Client { ..$name::Client::d ... LL | _ => yield, | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/drop-tracking-parent-expression.rs:49:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/drop-tracking-parent-expression.rs:40:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `derived_drop::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/drop-tracking-parent-expression.rs:38:22 - | -LL | let g = move || match drop($name::Client::default()) { - | ------------------------ has type `derived_drop::Client` which is not `Send` -LL | _ => yield, - | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here ... LL | / type_combinations!( LL | | // OK @@ -165,10 +39,10 @@ LL | fn assert_send(_thing: T) {} = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) error: generator cannot be sent between threads safely - --> $DIR/drop-tracking-parent-expression.rs:27:25 + --> $DIR/drop-tracking-parent-expression.rs:27:13 | LL | assert_send(g); - | ^ generator is not `Send` + | ^^^^^^^^^^^ generator is not `Send` ... LL | / type_combinations!( LL | | // OK @@ -188,49 +62,6 @@ LL | let g = move || match drop($name::Client { ..$name::Client::d ... LL | _ => yield, | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/drop-tracking-parent-expression.rs:49:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/drop-tracking-parent-expression.rs:40:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `significant_drop::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/drop-tracking-parent-expression.rs:38:22 - | -LL | let g = move || match drop($name::Client::default()) { - | ------------------------ has type `significant_drop::Client` which is not `Send` -LL | _ => yield, - | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here ... LL | / type_combinations!( LL | | // OK @@ -248,10 +79,10 @@ LL | fn assert_send(_thing: T) {} = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) error: generator cannot be sent between threads safely - --> $DIR/drop-tracking-parent-expression.rs:27:25 + --> $DIR/drop-tracking-parent-expression.rs:27:13 | LL | assert_send(g); - | ^ generator is not `Send` + | ^^^^^^^^^^^ generator is not `Send` ... LL | / type_combinations!( LL | | // OK @@ -271,49 +102,6 @@ LL | let g = move || match drop($name::Client { ..$name::Client::d ... LL | _ => yield, | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/drop-tracking-parent-expression.rs:49:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/drop-tracking-parent-expression.rs:40:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/drop-tracking-parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/drop-tracking-parent-expression.rs:38:22 - | -LL | let g = move || match drop($name::Client::default()) { - | ------------------------ has type `insignificant_dtor::Client` which is not `Send` -LL | _ => yield, - | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here ... LL | / type_combinations!( LL | | // OK @@ -330,5 +118,5 @@ LL | fn assert_send(_thing: T) {} | ^^^^ required by this bound in `assert_send` = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 8 previous errors +error: aborting due to 3 previous errors diff --git a/tests/ui/generator/drop-tracking-parent-expression.rs b/tests/ui/generator/drop-tracking-parent-expression.rs index 61e81330b0920..ed9ac6d11adb1 100644 --- a/tests/ui/generator/drop-tracking-parent-expression.rs +++ b/tests/ui/generator/drop-tracking-parent-expression.rs @@ -21,14 +21,14 @@ macro_rules! type_combinations { let g = move || match drop($name::Client { ..$name::Client::default() }) { //~^ `significant_drop::Client` which is not `Send` //~| `insignificant_dtor::Client` which is not `Send` - //~| `derived_drop::Client` which is not `Send` + //[no_drop_tracking,drop_tracking]~| `derived_drop::Client` which is not `Send` _ => yield, }; assert_send(g); //~^ ERROR cannot be sent between threads //~| ERROR cannot be sent between threads //~| ERROR cannot be sent between threads - //[no_drop_tracking,drop_tracking_mir]~^^^^ ERROR cannot be sent between threads + //[no_drop_tracking]~| ERROR cannot be sent between threads } // Simple owned value. This works because the Client is considered moved into `drop`, @@ -38,10 +38,10 @@ macro_rules! type_combinations { _ => yield, }; assert_send(g); - //[no_drop_tracking,drop_tracking_mir]~^ ERROR cannot be sent between threads - //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads - //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads - //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads + //[no_drop_tracking]~^ ERROR cannot be sent between threads + //[no_drop_tracking]~| ERROR cannot be sent between threads + //[no_drop_tracking]~| ERROR cannot be sent between threads + //[no_drop_tracking]~| ERROR cannot be sent between threads } )* } } diff --git a/tests/ui/generator/issue-57017.drop_tracking_mir.stderr b/tests/ui/generator/issue-57017.drop_tracking_mir.stderr deleted file mode 100644 index 4bba20bbae006..0000000000000 --- a/tests/ui/generator/issue-57017.drop_tracking_mir.stderr +++ /dev/null @@ -1,248 +0,0 @@ -error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:30:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation - | - = help: the trait `Sync` is not implemented for `copy::unsync::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:28:28 - | -LL | let g = move || match drop(&$name::unsync::Client::default()) { - | --------------------------------- has type `©::unsync::Client` which is not `Send` -LL | _status => yield, - | ^^^^^ yield occurs here, with `&$name::unsync::Client::default()` maybe used later -LL | }; - | - `&$name::unsync::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:42:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `copy::unsend::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:40:28 - | -LL | let g = move || match drop($name::unsend::Client::default()) { - | -------------------------------- has type `copy::unsend::Client` which is not `Send` -LL | _status => yield, - | ^^^^^ yield occurs here, with `$name::unsend::Client::default()` maybe used later -LL | }; - | - `$name::unsend::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:30:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation - | - = help: the trait `Sync` is not implemented for `derived_drop::unsync::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:28:28 - | -LL | let g = move || match drop(&$name::unsync::Client::default()) { - | --------------------------------- has type `&derived_drop::unsync::Client` which is not `Send` -LL | _status => yield, - | ^^^^^ yield occurs here, with `&$name::unsync::Client::default()` maybe used later -LL | }; - | - `&$name::unsync::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:42:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `derived_drop::unsend::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:40:28 - | -LL | let g = move || match drop($name::unsend::Client::default()) { - | -------------------------------- has type `derived_drop::unsend::Client` which is not `Send` -LL | _status => yield, - | ^^^^^ yield occurs here, with `$name::unsend::Client::default()` maybe used later -LL | }; - | - `$name::unsend::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:30:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation - | - = help: the trait `Sync` is not implemented for `significant_drop::unsync::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:28:28 - | -LL | let g = move || match drop(&$name::unsync::Client::default()) { - | --------------------------------- has type `&significant_drop::unsync::Client` which is not `Send` -LL | _status => yield, - | ^^^^^ yield occurs here, with `&$name::unsync::Client::default()` maybe used later -LL | }; - | - `&$name::unsync::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:42:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `significant_drop::unsend::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:40:28 - | -LL | let g = move || match drop($name::unsend::Client::default()) { - | -------------------------------- has type `significant_drop::unsend::Client` which is not `Send` -LL | _status => yield, - | ^^^^^ yield occurs here, with `$name::unsend::Client::default()` maybe used later -LL | }; - | - `$name::unsend::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | derived_drop => { #[derive(Default)] pub struct Client { pub nickname: String } }; -LL | | significant_drop => { -... | -LL | | } -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: aborting due to 6 previous errors - diff --git a/tests/ui/generator/issue-57017.no_drop_tracking.stderr b/tests/ui/generator/issue-57017.no_drop_tracking.stderr index 4bba20bbae006..06d2d23b9efb1 100644 --- a/tests/ui/generator/issue-57017.no_drop_tracking.stderr +++ b/tests/ui/generator/issue-57017.no_drop_tracking.stderr @@ -1,5 +1,5 @@ error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:30:25 + --> $DIR/issue-57017.rs:31:25 | LL | assert_send(g); | ^ generator is not `Send` @@ -15,7 +15,7 @@ LL | | ); | = help: the trait `Sync` is not implemented for `copy::unsync::Client` note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:28:28 + --> $DIR/issue-57017.rs:29:28 | LL | let g = move || match drop(&$name::unsync::Client::default()) { | --------------------------------- has type `©::unsync::Client` which is not `Send` @@ -33,14 +33,14 @@ LL | | } LL | | ); | |_____- in this macro invocation note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 + --> $DIR/issue-57017.rs:51:19 | LL | fn assert_send(_thing: T) {} | ^^^^ required by this bound in `assert_send` = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:42:25 + --> $DIR/issue-57017.rs:43:25 | LL | assert_send(g); | ^ generator is not `Send` @@ -54,9 +54,9 @@ LL | | } LL | | ); | |_____- in this macro invocation | - = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `copy::unsend::Client` + = help: within `[generator@$DIR/issue-57017.rs:40:21: 40:28]`, the trait `Send` is not implemented for `copy::unsend::Client` note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:40:28 + --> $DIR/issue-57017.rs:41:28 | LL | let g = move || match drop($name::unsend::Client::default()) { | -------------------------------- has type `copy::unsend::Client` which is not `Send` @@ -74,14 +74,14 @@ LL | | } LL | | ); | |_____- in this macro invocation note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 + --> $DIR/issue-57017.rs:51:19 | LL | fn assert_send(_thing: T) {} | ^^^^ required by this bound in `assert_send` = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:30:25 + --> $DIR/issue-57017.rs:31:25 | LL | assert_send(g); | ^ generator is not `Send` @@ -97,7 +97,7 @@ LL | | ); | = help: the trait `Sync` is not implemented for `derived_drop::unsync::Client` note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:28:28 + --> $DIR/issue-57017.rs:29:28 | LL | let g = move || match drop(&$name::unsync::Client::default()) { | --------------------------------- has type `&derived_drop::unsync::Client` which is not `Send` @@ -115,14 +115,14 @@ LL | | } LL | | ); | |_____- in this macro invocation note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 + --> $DIR/issue-57017.rs:51:19 | LL | fn assert_send(_thing: T) {} | ^^^^ required by this bound in `assert_send` = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:42:25 + --> $DIR/issue-57017.rs:43:25 | LL | assert_send(g); | ^ generator is not `Send` @@ -136,9 +136,9 @@ LL | | } LL | | ); | |_____- in this macro invocation | - = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `derived_drop::unsend::Client` + = help: within `[generator@$DIR/issue-57017.rs:40:21: 40:28]`, the trait `Send` is not implemented for `derived_drop::unsend::Client` note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:40:28 + --> $DIR/issue-57017.rs:41:28 | LL | let g = move || match drop($name::unsend::Client::default()) { | -------------------------------- has type `derived_drop::unsend::Client` which is not `Send` @@ -156,14 +156,14 @@ LL | | } LL | | ); | |_____- in this macro invocation note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 + --> $DIR/issue-57017.rs:51:19 | LL | fn assert_send(_thing: T) {} | ^^^^ required by this bound in `assert_send` = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:30:25 + --> $DIR/issue-57017.rs:31:25 | LL | assert_send(g); | ^ generator is not `Send` @@ -179,7 +179,7 @@ LL | | ); | = help: the trait `Sync` is not implemented for `significant_drop::unsync::Client` note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:28:28 + --> $DIR/issue-57017.rs:29:28 | LL | let g = move || match drop(&$name::unsync::Client::default()) { | --------------------------------- has type `&significant_drop::unsync::Client` which is not `Send` @@ -197,14 +197,14 @@ LL | | } LL | | ); | |_____- in this macro invocation note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 + --> $DIR/issue-57017.rs:51:19 | LL | fn assert_send(_thing: T) {} | ^^^^ required by this bound in `assert_send` = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) error: generator cannot be sent between threads safely - --> $DIR/issue-57017.rs:42:25 + --> $DIR/issue-57017.rs:43:25 | LL | assert_send(g); | ^ generator is not `Send` @@ -218,9 +218,9 @@ LL | | } LL | | ); | |_____- in this macro invocation | - = help: within `[generator@$DIR/issue-57017.rs:39:21: 39:28]`, the trait `Send` is not implemented for `significant_drop::unsend::Client` + = help: within `[generator@$DIR/issue-57017.rs:40:21: 40:28]`, the trait `Send` is not implemented for `significant_drop::unsend::Client` note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57017.rs:40:28 + --> $DIR/issue-57017.rs:41:28 | LL | let g = move || match drop($name::unsend::Client::default()) { | -------------------------------- has type `significant_drop::unsend::Client` which is not `Send` @@ -238,7 +238,7 @@ LL | | } LL | | ); | |_____- in this macro invocation note: required by a bound in `assert_send` - --> $DIR/issue-57017.rs:50:19 + --> $DIR/issue-57017.rs:51:19 | LL | fn assert_send(_thing: T) {} | ^^^^ required by this bound in `assert_send` diff --git a/tests/ui/generator/issue-57017.rs b/tests/ui/generator/issue-57017.rs index bcd6d22678858..03b00ac99ad22 100644 --- a/tests/ui/generator/issue-57017.rs +++ b/tests/ui/generator/issue-57017.rs @@ -2,6 +2,7 @@ // [drop_tracking] compile-flags: -Zdrop-tracking // [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // [drop_tracking] build-pass +// [drop_tracking_mir] build-pass #![feature(generators, negative_impls)] @@ -28,9 +29,9 @@ macro_rules! type_combinations { _status => yield, }; assert_send(g); - //[no_drop_tracking,drop_tracking_mir]~^ ERROR generator cannot be sent between threads safely - //[no_drop_tracking,drop_tracking_mir]~| ERROR generator cannot be sent between threads safely - //[no_drop_tracking,drop_tracking_mir]~| ERROR generator cannot be sent between threads safely + //[no_drop_tracking]~^ ERROR generator cannot be sent between threads safely + //[no_drop_tracking]~| ERROR generator cannot be sent between threads safely + //[no_drop_tracking]~| ERROR generator cannot be sent between threads safely } // This tests that `Client` is properly considered to be dropped after moving it into the @@ -40,9 +41,9 @@ macro_rules! type_combinations { _status => yield, }; assert_send(g); - //[no_drop_tracking,drop_tracking_mir]~^ ERROR generator cannot be sent between threads safely - //[no_drop_tracking,drop_tracking_mir]~| ERROR generator cannot be sent between threads safely - //[no_drop_tracking,drop_tracking_mir]~| ERROR generator cannot be sent between threads safely + //[no_drop_tracking]~^ ERROR generator cannot be sent between threads safely + //[no_drop_tracking]~| ERROR generator cannot be sent between threads safely + //[no_drop_tracking]~| ERROR generator cannot be sent between threads safely } )* } } diff --git a/tests/ui/generator/issue-57478.drop_tracking_mir.stderr b/tests/ui/generator/issue-57478.drop_tracking_mir.stderr deleted file mode 100644 index a253cafe24d0d..0000000000000 --- a/tests/ui/generator/issue-57478.drop_tracking_mir.stderr +++ /dev/null @@ -1,32 +0,0 @@ -error: generator cannot be sent between threads safely - --> $DIR/issue-57478.rs:12:17 - | -LL | assert_send(|| { - | _________________^ -LL | | -LL | | -LL | | let guard = Foo; -LL | | drop(guard); -LL | | yield; -LL | | }) - | |_____^ generator is not `Send` - | - = help: within `[generator@$DIR/issue-57478.rs:12:17: 12:19]`, the trait `Send` is not implemented for `Foo` -note: generator is not `Send` as this value is used across a yield - --> $DIR/issue-57478.rs:17:9 - | -LL | let guard = Foo; - | ----- has type `Foo` which is not `Send` -LL | drop(guard); -LL | yield; - | ^^^^^ yield occurs here, with `guard` maybe used later -LL | }) - | - `guard` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/issue-57478.rs:21:19 - | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: aborting due to previous error - diff --git a/tests/ui/generator/issue-57478.no_drop_tracking.stderr b/tests/ui/generator/issue-57478.no_drop_tracking.stderr index a253cafe24d0d..612dd9c37f701 100644 --- a/tests/ui/generator/issue-57478.no_drop_tracking.stderr +++ b/tests/ui/generator/issue-57478.no_drop_tracking.stderr @@ -1,17 +1,16 @@ error: generator cannot be sent between threads safely - --> $DIR/issue-57478.rs:12:17 + --> $DIR/issue-57478.rs:13:17 | LL | assert_send(|| { | _________________^ LL | | -LL | | LL | | let guard = Foo; LL | | drop(guard); LL | | yield; LL | | }) | |_____^ generator is not `Send` | - = help: within `[generator@$DIR/issue-57478.rs:12:17: 12:19]`, the trait `Send` is not implemented for `Foo` + = help: within `[generator@$DIR/issue-57478.rs:13:17: 13:19]`, the trait `Send` is not implemented for `Foo` note: generator is not `Send` as this value is used across a yield --> $DIR/issue-57478.rs:17:9 | diff --git a/tests/ui/generator/issue-57478.rs b/tests/ui/generator/issue-57478.rs index cf5350ecbb996..3c23b5992710e 100644 --- a/tests/ui/generator/issue-57478.rs +++ b/tests/ui/generator/issue-57478.rs @@ -2,6 +2,7 @@ // [drop_tracking] compile-flags: -Zdrop-tracking // [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir // [drop_tracking] check-pass +// [drop_tracking_mir] check-pass #![feature(negative_impls, generators)] @@ -11,7 +12,6 @@ impl !Send for Foo {} fn main() { assert_send(|| { //[no_drop_tracking]~^ ERROR generator cannot be sent between threads safely - //[drop_tracking_mir]~^^ ERROR generator cannot be sent between threads safely let guard = Foo; drop(guard); yield; diff --git a/tests/ui/generator/issue-68112.drop_tracking_mir.stderr b/tests/ui/generator/issue-68112.drop_tracking_mir.stderr index 282eac1b686ef..a83522b714d53 100644 --- a/tests/ui/generator/issue-68112.drop_tracking_mir.stderr +++ b/tests/ui/generator/issue-68112.drop_tracking_mir.stderr @@ -1,8 +1,8 @@ error: generator cannot be sent between threads safely - --> $DIR/issue-68112.rs:43:18 + --> $DIR/issue-68112.rs:43:5 | LL | require_send(send_gen); - | ^^^^^^^^ generator is not `Send` + | ^^^^^^^^^^^^ generator is not `Send` | = help: the trait `Sync` is not implemented for `RefCell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead @@ -14,9 +14,6 @@ LL | let _non_send_gen = make_non_send_generator(); LL | LL | yield; | ^^^^^ yield occurs here, with `_non_send_gen` maybe used later -... -LL | }; - | - `_non_send_gen` is later dropped here note: required by a bound in `require_send` --> $DIR/issue-68112.rs:25:25 | @@ -24,12 +21,10 @@ LL | fn require_send(_: impl Send) {} | ^^^^ required by this bound in `require_send` error[E0277]: `RefCell` cannot be shared between threads safely - --> $DIR/issue-68112.rs:67:18 + --> $DIR/issue-68112.rs:67:5 | LL | require_send(send_gen); - | ------------ ^^^^^^^^ `RefCell` cannot be shared between threads safely - | | - | required by a bound introduced by this call + | ^^^^^^^^^^^^ `RefCell` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `RefCell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead @@ -49,7 +44,7 @@ note: required because it appears within the type `impl Generator impl Generator>> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: required because it captures the following types: `impl Generator>>`, `()` + = note: required because it captures the following types: `impl Generator>>` note: required because it's used within this generator --> $DIR/issue-68112.rs:63:20 | diff --git a/tests/ui/generator/issue-68112.rs b/tests/ui/generator/issue-68112.rs index c3fe09be57fb1..48b53b7693d41 100644 --- a/tests/ui/generator/issue-68112.rs +++ b/tests/ui/generator/issue-68112.rs @@ -11,7 +11,7 @@ use std::{ }; pub struct Ready(Option); -impl Generator<()> for Ready { +impl Generator<()> for Ready { type Return = T; type Yield = (); fn resume(mut self: Pin<&mut Self>, _args: ()) -> GeneratorState<(), T> { @@ -39,7 +39,7 @@ fn test1() { yield; //~^ NOTE yield occurs here //~| NOTE value is used across a yield - }; //~ NOTE later dropped here + }; //[no_drop_tracking,drop_tracking]~ NOTE later dropped here require_send(send_gen); //~^ ERROR generator cannot be sent between threads //~| NOTE not `Send` @@ -68,7 +68,7 @@ fn test2() { //~^ ERROR `RefCell` cannot be shared between threads safely //~| NOTE `RefCell` cannot be shared between threads safely //~| NOTE required for - //~| NOTE required by a bound introduced by this call + //[no_drop_tracking,drop_tracking]~| NOTE required by a bound introduced by this call //~| NOTE captures the following types //~| NOTE use `std::sync::RwLock` instead } diff --git a/tests/ui/generator/not-send-sync.drop_tracking.stderr b/tests/ui/generator/not-send-sync.drop_tracking.stderr index a15ee4044745c..718fd42245ad3 100644 --- a/tests/ui/generator/not-send-sync.drop_tracking.stderr +++ b/tests/ui/generator/not-send-sync.drop_tracking.stderr @@ -1,58 +1,60 @@ -error[E0277]: `Cell` cannot be shared between threads safely - --> $DIR/not-send-sync.rs:19:17 +error: generator cannot be shared between threads safely + --> $DIR/not-send-sync.rs:17:17 | -LL | assert_send(|| { - | _____-----------_^ - | | | - | | required by a bound introduced by this call +LL | assert_sync(|| { + | _________________^ LL | | -LL | | drop(&a); +LL | | let a = NotSync; LL | | yield; +LL | | drop(a); LL | | }); - | |_____^ `Cell` cannot be shared between threads safely + | |_____^ generator is not `Sync` | - = help: the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead - = note: required for `&Cell` to implement `Send` -note: required because it's used within this generator - --> $DIR/not-send-sync.rs:19:17 + = help: within `[generator@$DIR/not-send-sync.rs:17:17: 17:19]`, the trait `Sync` is not implemented for `NotSync` +note: generator is not `Sync` as this value is used across a yield + --> $DIR/not-send-sync.rs:20:9 | -LL | assert_send(|| { - | ^^ -note: required by a bound in `assert_send` - --> $DIR/not-send-sync.rs:10:23 +LL | let a = NotSync; + | - has type `NotSync` which is not `Sync` +LL | yield; + | ^^^^^ yield occurs here, with `a` maybe used later +LL | drop(a); +LL | }); + | - `a` is later dropped here +note: required by a bound in `assert_sync` + --> $DIR/not-send-sync.rs:14:23 | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` +LL | fn assert_sync(_: T) {} + | ^^^^ required by this bound in `assert_sync` -error: generator cannot be shared between threads safely - --> $DIR/not-send-sync.rs:12:17 +error: generator cannot be sent between threads safely + --> $DIR/not-send-sync.rs:24:17 | -LL | assert_sync(|| { +LL | assert_send(|| { | _________________^ LL | | -LL | | let a = Cell::new(2); +LL | | let a = NotSend; LL | | yield; +LL | | drop(a); LL | | }); - | |_____^ generator is not `Sync` + | |_____^ generator is not `Send` | - = help: within `[generator@$DIR/not-send-sync.rs:12:17: 12:19]`, the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead -note: generator is not `Sync` as this value is used across a yield - --> $DIR/not-send-sync.rs:15:9 + = help: within `[generator@$DIR/not-send-sync.rs:24:17: 24:19]`, the trait `Send` is not implemented for `NotSend` +note: generator is not `Send` as this value is used across a yield + --> $DIR/not-send-sync.rs:27:9 | -LL | let a = Cell::new(2); - | - has type `Cell` which is not `Sync` +LL | let a = NotSend; + | - has type `NotSend` which is not `Send` LL | yield; | ^^^^^ yield occurs here, with `a` maybe used later +LL | drop(a); LL | }); | - `a` is later dropped here -note: required by a bound in `assert_sync` - --> $DIR/not-send-sync.rs:9:23 +note: required by a bound in `assert_send` + --> $DIR/not-send-sync.rs:15:23 | -LL | fn assert_sync(_: T) {} - | ^^^^ required by this bound in `assert_sync` +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/not-send-sync.drop_tracking_mir.stderr b/tests/ui/generator/not-send-sync.drop_tracking_mir.stderr index a15ee4044745c..66f01ae37d81a 100644 --- a/tests/ui/generator/not-send-sync.drop_tracking_mir.stderr +++ b/tests/ui/generator/not-send-sync.drop_tracking_mir.stderr @@ -1,58 +1,42 @@ -error[E0277]: `Cell` cannot be shared between threads safely - --> $DIR/not-send-sync.rs:19:17 - | -LL | assert_send(|| { - | _____-----------_^ - | | | - | | required by a bound introduced by this call -LL | | -LL | | drop(&a); -LL | | yield; -LL | | }); - | |_____^ `Cell` cannot be shared between threads safely - | - = help: the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead - = note: required for `&Cell` to implement `Send` -note: required because it's used within this generator - --> $DIR/not-send-sync.rs:19:17 +error: generator cannot be shared between threads safely + --> $DIR/not-send-sync.rs:17:5 | -LL | assert_send(|| { - | ^^ -note: required by a bound in `assert_send` - --> $DIR/not-send-sync.rs:10:23 +LL | assert_sync(|| { + | ^^^^^^^^^^^ generator is not `Sync` | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: generator cannot be shared between threads safely - --> $DIR/not-send-sync.rs:12:17 - | -LL | assert_sync(|| { - | _________________^ -LL | | -LL | | let a = Cell::new(2); -LL | | yield; -LL | | }); - | |_____^ generator is not `Sync` - | - = help: within `[generator@$DIR/not-send-sync.rs:12:17: 12:19]`, the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead + = help: within `[generator@$DIR/not-send-sync.rs:17:17: 17:19]`, the trait `Sync` is not implemented for `NotSync` note: generator is not `Sync` as this value is used across a yield - --> $DIR/not-send-sync.rs:15:9 + --> $DIR/not-send-sync.rs:20:9 | -LL | let a = Cell::new(2); - | - has type `Cell` which is not `Sync` +LL | let a = NotSync; + | - has type `NotSync` which is not `Sync` LL | yield; | ^^^^^ yield occurs here, with `a` maybe used later -LL | }); - | - `a` is later dropped here note: required by a bound in `assert_sync` - --> $DIR/not-send-sync.rs:9:23 + --> $DIR/not-send-sync.rs:14:23 | LL | fn assert_sync(_: T) {} | ^^^^ required by this bound in `assert_sync` +error: generator cannot be sent between threads safely + --> $DIR/not-send-sync.rs:24:5 + | +LL | assert_send(|| { + | ^^^^^^^^^^^ generator is not `Send` + | + = help: within `[generator@$DIR/not-send-sync.rs:24:17: 24:19]`, the trait `Send` is not implemented for `NotSend` +note: generator is not `Send` as this value is used across a yield + --> $DIR/not-send-sync.rs:27:9 + | +LL | let a = NotSend; + | - has type `NotSend` which is not `Send` +LL | yield; + | ^^^^^ yield occurs here, with `a` maybe used later +note: required by a bound in `assert_send` + --> $DIR/not-send-sync.rs:15:23 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/not-send-sync.no_drop_tracking.stderr b/tests/ui/generator/not-send-sync.no_drop_tracking.stderr index a15ee4044745c..718fd42245ad3 100644 --- a/tests/ui/generator/not-send-sync.no_drop_tracking.stderr +++ b/tests/ui/generator/not-send-sync.no_drop_tracking.stderr @@ -1,58 +1,60 @@ -error[E0277]: `Cell` cannot be shared between threads safely - --> $DIR/not-send-sync.rs:19:17 +error: generator cannot be shared between threads safely + --> $DIR/not-send-sync.rs:17:17 | -LL | assert_send(|| { - | _____-----------_^ - | | | - | | required by a bound introduced by this call +LL | assert_sync(|| { + | _________________^ LL | | -LL | | drop(&a); +LL | | let a = NotSync; LL | | yield; +LL | | drop(a); LL | | }); - | |_____^ `Cell` cannot be shared between threads safely + | |_____^ generator is not `Sync` | - = help: the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead - = note: required for `&Cell` to implement `Send` -note: required because it's used within this generator - --> $DIR/not-send-sync.rs:19:17 + = help: within `[generator@$DIR/not-send-sync.rs:17:17: 17:19]`, the trait `Sync` is not implemented for `NotSync` +note: generator is not `Sync` as this value is used across a yield + --> $DIR/not-send-sync.rs:20:9 | -LL | assert_send(|| { - | ^^ -note: required by a bound in `assert_send` - --> $DIR/not-send-sync.rs:10:23 +LL | let a = NotSync; + | - has type `NotSync` which is not `Sync` +LL | yield; + | ^^^^^ yield occurs here, with `a` maybe used later +LL | drop(a); +LL | }); + | - `a` is later dropped here +note: required by a bound in `assert_sync` + --> $DIR/not-send-sync.rs:14:23 | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` +LL | fn assert_sync(_: T) {} + | ^^^^ required by this bound in `assert_sync` -error: generator cannot be shared between threads safely - --> $DIR/not-send-sync.rs:12:17 +error: generator cannot be sent between threads safely + --> $DIR/not-send-sync.rs:24:17 | -LL | assert_sync(|| { +LL | assert_send(|| { | _________________^ LL | | -LL | | let a = Cell::new(2); +LL | | let a = NotSend; LL | | yield; +LL | | drop(a); LL | | }); - | |_____^ generator is not `Sync` + | |_____^ generator is not `Send` | - = help: within `[generator@$DIR/not-send-sync.rs:12:17: 12:19]`, the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead -note: generator is not `Sync` as this value is used across a yield - --> $DIR/not-send-sync.rs:15:9 + = help: within `[generator@$DIR/not-send-sync.rs:24:17: 24:19]`, the trait `Send` is not implemented for `NotSend` +note: generator is not `Send` as this value is used across a yield + --> $DIR/not-send-sync.rs:27:9 | -LL | let a = Cell::new(2); - | - has type `Cell` which is not `Sync` +LL | let a = NotSend; + | - has type `NotSend` which is not `Send` LL | yield; | ^^^^^ yield occurs here, with `a` maybe used later +LL | drop(a); LL | }); | - `a` is later dropped here -note: required by a bound in `assert_sync` - --> $DIR/not-send-sync.rs:9:23 +note: required by a bound in `assert_send` + --> $DIR/not-send-sync.rs:15:23 | -LL | fn assert_sync(_: T) {} - | ^^^^ required by this bound in `assert_sync` +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/not-send-sync.rs b/tests/ui/generator/not-send-sync.rs index aadb2935701c7..8794db452b465 100644 --- a/tests/ui/generator/not-send-sync.rs +++ b/tests/ui/generator/not-send-sync.rs @@ -2,8 +2,13 @@ // [drop_tracking] compile-flags: -Zdrop-tracking // [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir #![feature(generators)] +#![feature(negative_impls)] -use std::cell::Cell; +struct NotSend; +struct NotSync; + +impl !Send for NotSend {} +impl !Sync for NotSync {} fn main() { fn assert_sync(_: T) {} @@ -11,14 +16,15 @@ fn main() { assert_sync(|| { //~^ ERROR: generator cannot be shared between threads safely - let a = Cell::new(2); + let a = NotSync; yield; + drop(a); }); - let a = Cell::new(2); assert_send(|| { - //~^ ERROR: E0277 - drop(&a); + //~^ ERROR: generator cannot be sent between threads safely + let a = NotSend; yield; + drop(a); }); } diff --git a/tests/ui/generator/parent-expression.drop_tracking_mir.stderr b/tests/ui/generator/parent-expression.drop_tracking_mir.stderr index 2e1313a800487..bf814456427e0 100644 --- a/tests/ui/generator/parent-expression.drop_tracking_mir.stderr +++ b/tests/ui/generator/parent-expression.drop_tracking_mir.stderr @@ -1,91 +1,8 @@ error: generator cannot be sent between threads safely - --> $DIR/parent-expression.rs:27:25 + --> $DIR/parent-expression.rs:27:13 | LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/parent-expression.rs:21:21: 21:28]`, the trait `Send` is not implemented for `copy::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/parent-expression.rs:25:22 - | -LL | let g = move || match drop($name::Client { ..$name::Client::default() }) { - | ------------------------ has type `copy::Client` which is not `Send` -... -LL | _ => yield, - | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/parent-expression.rs:49:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/parent-expression.rs:40:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `copy::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/parent-expression.rs:38:22 - | -LL | let g = move || match drop($name::Client::default()) { - | ------------------------ has type `copy::Client` which is not `Send` -LL | _ => yield, - | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/parent-expression.rs:49:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/parent-expression.rs:27:25 - | -LL | assert_send(g); - | ^ generator is not `Send` + | ^^^^^^^^^^^ generator is not `Send` ... LL | / type_combinations!( LL | | // OK @@ -105,49 +22,6 @@ LL | let g = move || match drop($name::Client { ..$name::Client::d ... LL | _ => yield, | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/parent-expression.rs:49:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/parent-expression.rs:40:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `derived_drop::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/parent-expression.rs:38:22 - | -LL | let g = move || match drop($name::Client::default()) { - | ------------------------ has type `derived_drop::Client` which is not `Send` -LL | _ => yield, - | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here ... LL | / type_combinations!( LL | | // OK @@ -165,10 +39,10 @@ LL | fn assert_send(_thing: T) {} = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) error: generator cannot be sent between threads safely - --> $DIR/parent-expression.rs:27:25 + --> $DIR/parent-expression.rs:27:13 | LL | assert_send(g); - | ^ generator is not `Send` + | ^^^^^^^^^^^ generator is not `Send` ... LL | / type_combinations!( LL | | // OK @@ -188,49 +62,6 @@ LL | let g = move || match drop($name::Client { ..$name::Client::d ... LL | _ => yield, | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/parent-expression.rs:49:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/parent-expression.rs:40:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `significant_drop::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/parent-expression.rs:38:22 - | -LL | let g = move || match drop($name::Client::default()) { - | ------------------------ has type `significant_drop::Client` which is not `Send` -LL | _ => yield, - | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here ... LL | / type_combinations!( LL | | // OK @@ -248,10 +79,10 @@ LL | fn assert_send(_thing: T) {} = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) error: generator cannot be sent between threads safely - --> $DIR/parent-expression.rs:27:25 + --> $DIR/parent-expression.rs:27:13 | LL | assert_send(g); - | ^ generator is not `Send` + | ^^^^^^^^^^^ generator is not `Send` ... LL | / type_combinations!( LL | | // OK @@ -271,49 +102,6 @@ LL | let g = move || match drop($name::Client { ..$name::Client::d ... LL | _ => yield, | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation -note: required by a bound in `assert_send` - --> $DIR/parent-expression.rs:49:19 - | -LL | fn assert_send(_thing: T) {} - | ^^^^ required by this bound in `assert_send` - = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: generator cannot be sent between threads safely - --> $DIR/parent-expression.rs:40:25 - | -LL | assert_send(g); - | ^ generator is not `Send` -... -LL | / type_combinations!( -LL | | // OK -LL | | copy => { #[derive(Copy, Clone, Default)] pub struct Client; }; -LL | | // NOT OK: MIR borrowck thinks that this is used after the yield, even though -... | -LL | | }; -LL | | ); - | |_____- in this macro invocation - | - = help: within `[generator@$DIR/parent-expression.rs:37:21: 37:28]`, the trait `Send` is not implemented for `insignificant_dtor::Client` -note: generator is not `Send` as this value is used across a yield - --> $DIR/parent-expression.rs:38:22 - | -LL | let g = move || match drop($name::Client::default()) { - | ------------------------ has type `insignificant_dtor::Client` which is not `Send` -LL | _ => yield, - | ^^^^^ yield occurs here, with `$name::Client::default()` maybe used later -LL | }; - | - `$name::Client::default()` is later dropped here ... LL | / type_combinations!( LL | | // OK @@ -330,5 +118,5 @@ LL | fn assert_send(_thing: T) {} | ^^^^ required by this bound in `assert_send` = note: this error originates in the macro `type_combinations` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 8 previous errors +error: aborting due to 3 previous errors diff --git a/tests/ui/generator/parent-expression.rs b/tests/ui/generator/parent-expression.rs index 61e81330b0920..239034e3d4e8a 100644 --- a/tests/ui/generator/parent-expression.rs +++ b/tests/ui/generator/parent-expression.rs @@ -28,7 +28,7 @@ macro_rules! type_combinations { //~^ ERROR cannot be sent between threads //~| ERROR cannot be sent between threads //~| ERROR cannot be sent between threads - //[no_drop_tracking,drop_tracking_mir]~^^^^ ERROR cannot be sent between threads + //[no_drop_tracking]~^^^^ ERROR cannot be sent between threads } // Simple owned value. This works because the Client is considered moved into `drop`, @@ -38,10 +38,10 @@ macro_rules! type_combinations { _ => yield, }; assert_send(g); - //[no_drop_tracking,drop_tracking_mir]~^ ERROR cannot be sent between threads - //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads - //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads - //[no_drop_tracking,drop_tracking_mir]~| ERROR cannot be sent between threads + //[no_drop_tracking]~^ ERROR cannot be sent between threads + //[no_drop_tracking]~| ERROR cannot be sent between threads + //[no_drop_tracking]~| ERROR cannot be sent between threads + //[no_drop_tracking]~| ERROR cannot be sent between threads } )* } } diff --git a/tests/ui/generator/partial-drop.drop_tracking.stderr b/tests/ui/generator/partial-drop.drop_tracking.stderr index e3c19264ee857..f1b25cb8c34e9 100644 --- a/tests/ui/generator/partial-drop.drop_tracking.stderr +++ b/tests/ui/generator/partial-drop.drop_tracking.stderr @@ -1,17 +1,16 @@ error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:16:17 + --> $DIR/partial-drop.rs:17:17 | LL | assert_send(|| { | _________________^ LL | | -LL | | // FIXME: it would be nice to make this work. LL | | let guard = Bar { foo: Foo, x: 42 }; LL | | drop(guard.foo); LL | | yield; LL | | }); | |_____^ generator is not `Send` | - = help: within `[generator@$DIR/partial-drop.rs:16:17: 16:19]`, the trait `Send` is not implemented for `Foo` + = help: within `[generator@$DIR/partial-drop.rs:17:17: 17:19]`, the trait `Send` is not implemented for `Foo` note: generator is not `Send` as this value is used across a yield --> $DIR/partial-drop.rs:21:9 | @@ -23,7 +22,7 @@ LL | yield; LL | }); | - `guard` is later dropped here note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 + --> $DIR/partial-drop.rs:33:19 | LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` @@ -34,16 +33,16 @@ error: generator cannot be sent between threads safely LL | assert_send(|| { | _________________^ LL | | -LL | | // FIXME: it would be nice to make this work. LL | | let guard = Bar { foo: Foo, x: 42 }; -... | +LL | | let Bar { foo, x } = guard; +LL | | drop(foo); LL | | yield; LL | | }); | |_____^ generator is not `Send` | = help: within `[generator@$DIR/partial-drop.rs:24:17: 24:19]`, the trait `Send` is not implemented for `Foo` note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:31:9 + --> $DIR/partial-drop.rs:29:9 | LL | let guard = Bar { foo: Foo, x: 42 }; | ----- has type `Bar` which is not `Send` @@ -53,40 +52,10 @@ LL | yield; LL | }); | - `guard` is later dropped here note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 + --> $DIR/partial-drop.rs:33:19 | LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` -error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:34:17 - | -LL | assert_send(|| { - | _________________^ -LL | | -LL | | // FIXME: it would be nice to make this work. -LL | | let guard = Bar { foo: Foo, x: 42 }; -... | -LL | | yield; -LL | | }); - | |_____^ generator is not `Send` - | - = help: within `[generator@$DIR/partial-drop.rs:34:17: 34:19]`, the trait `Send` is not implemented for `Foo` -note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:40:9 - | -LL | let guard = Bar { foo: Foo, x: 42 }; - | ----- has type `Bar` which is not `Send` -... -LL | yield; - | ^^^^^ yield occurs here, with `guard` maybe used later -LL | }); - | - `guard` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 - | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors diff --git a/tests/ui/generator/partial-drop.drop_tracking_mir.stderr b/tests/ui/generator/partial-drop.drop_tracking_mir.stderr deleted file mode 100644 index fa901b1977a15..0000000000000 --- a/tests/ui/generator/partial-drop.drop_tracking_mir.stderr +++ /dev/null @@ -1,92 +0,0 @@ -error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:16:17 - | -LL | assert_send(|| { - | _________________^ -LL | | -LL | | // FIXME: it would be nice to make this work. -LL | | let guard = Bar { foo: Foo, x: 42 }; -LL | | drop(guard.foo); -LL | | yield; -LL | | }); - | |_____^ generator is not `Send` - | - = help: within `[generator@$DIR/partial-drop.rs:16:17: 16:19]`, the trait `Send` is not implemented for `Foo` -note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:21:9 - | -LL | let guard = Bar { foo: Foo, x: 42 }; - | ----- has type `Bar` which is not `Send` -LL | drop(guard.foo); -LL | yield; - | ^^^^^ yield occurs here, with `guard` maybe used later -LL | }); - | - `guard` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 - | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:24:17 - | -LL | assert_send(|| { - | _________________^ -LL | | -LL | | // FIXME: it would be nice to make this work. -LL | | let guard = Bar { foo: Foo, x: 42 }; -... | -LL | | yield; -LL | | }); - | |_____^ generator is not `Send` - | - = help: within `[generator@$DIR/partial-drop.rs:24:17: 24:19]`, the trait `Send` is not implemented for `Foo` -note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:31:9 - | -LL | let guard = Bar { foo: Foo, x: 42 }; - | ----- has type `Bar` which is not `Send` -... -LL | yield; - | ^^^^^ yield occurs here, with `guard` maybe used later -LL | }); - | - `guard` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 - | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:34:17 - | -LL | assert_send(|| { - | _________________^ -LL | | -LL | | // FIXME: it would be nice to make this work. -LL | | let guard = Bar { foo: Foo, x: 42 }; -... | -LL | | yield; -LL | | }); - | |_____^ generator is not `Send` - | - = help: within `[generator@$DIR/partial-drop.rs:34:17: 34:19]`, the trait `Send` is not implemented for `Foo` -note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:40:9 - | -LL | let Bar { foo, x } = guard; - | --- has type `Foo` which is not `Send` -LL | drop(foo); -LL | yield; - | ^^^^^ yield occurs here, with `foo` maybe used later -LL | }); - | - `foo` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 - | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: aborting due to 3 previous errors - diff --git a/tests/ui/generator/partial-drop.no_drop_tracking.stderr b/tests/ui/generator/partial-drop.no_drop_tracking.stderr index fa901b1977a15..91152b5ea6f3d 100644 --- a/tests/ui/generator/partial-drop.no_drop_tracking.stderr +++ b/tests/ui/generator/partial-drop.no_drop_tracking.stderr @@ -1,17 +1,16 @@ error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:16:17 + --> $DIR/partial-drop.rs:17:17 | LL | assert_send(|| { | _________________^ LL | | -LL | | // FIXME: it would be nice to make this work. LL | | let guard = Bar { foo: Foo, x: 42 }; LL | | drop(guard.foo); LL | | yield; LL | | }); | |_____^ generator is not `Send` | - = help: within `[generator@$DIR/partial-drop.rs:16:17: 16:19]`, the trait `Send` is not implemented for `Foo` + = help: within `[generator@$DIR/partial-drop.rs:17:17: 17:19]`, the trait `Send` is not implemented for `Foo` note: generator is not `Send` as this value is used across a yield --> $DIR/partial-drop.rs:21:9 | @@ -23,7 +22,7 @@ LL | yield; LL | }); | - `guard` is later dropped here note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 + --> $DIR/partial-drop.rs:33:19 | LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` @@ -34,46 +33,16 @@ error: generator cannot be sent between threads safely LL | assert_send(|| { | _________________^ LL | | -LL | | // FIXME: it would be nice to make this work. LL | | let guard = Bar { foo: Foo, x: 42 }; -... | +LL | | let Bar { foo, x } = guard; +LL | | drop(foo); LL | | yield; LL | | }); | |_____^ generator is not `Send` | = help: within `[generator@$DIR/partial-drop.rs:24:17: 24:19]`, the trait `Send` is not implemented for `Foo` note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:31:9 - | -LL | let guard = Bar { foo: Foo, x: 42 }; - | ----- has type `Bar` which is not `Send` -... -LL | yield; - | ^^^^^ yield occurs here, with `guard` maybe used later -LL | }); - | - `guard` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 - | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:34:17 - | -LL | assert_send(|| { - | _________________^ -LL | | -LL | | // FIXME: it would be nice to make this work. -LL | | let guard = Bar { foo: Foo, x: 42 }; -... | -LL | | yield; -LL | | }); - | |_____^ generator is not `Send` - | - = help: within `[generator@$DIR/partial-drop.rs:34:17: 34:19]`, the trait `Send` is not implemented for `Foo` -note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:40:9 + --> $DIR/partial-drop.rs:29:9 | LL | let Bar { foo, x } = guard; | --- has type `Foo` which is not `Send` @@ -83,10 +52,10 @@ LL | yield; LL | }); | - `foo` is later dropped here note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 + --> $DIR/partial-drop.rs:33:19 | LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors diff --git a/tests/ui/generator/partial-drop.rs b/tests/ui/generator/partial-drop.rs index e7f85df5877c5..1d3ae075d43af 100644 --- a/tests/ui/generator/partial-drop.rs +++ b/tests/ui/generator/partial-drop.rs @@ -1,6 +1,7 @@ // revisions: no_drop_tracking drop_tracking drop_tracking_mir // [drop_tracking] compile-flags: -Zdrop-tracking // [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir +// [drop_tracking_mir] check-pass #![feature(negative_impls, generators)] @@ -14,26 +15,14 @@ struct Bar { fn main() { assert_send(|| { - //~^ ERROR generator cannot be sent between threads safely - // FIXME: it would be nice to make this work. + //[no_drop_tracking,drop_tracking]~^ ERROR generator cannot be sent between threads safely let guard = Bar { foo: Foo, x: 42 }; drop(guard.foo); yield; }); assert_send(|| { - //~^ ERROR generator cannot be sent between threads safely - // FIXME: it would be nice to make this work. - let guard = Bar { foo: Foo, x: 42 }; - drop(guard); - guard.foo = Foo; - guard.x = 23; - yield; - }); - - assert_send(|| { - //~^ ERROR generator cannot be sent between threads safely - // FIXME: it would be nice to make this work. + //[no_drop_tracking,drop_tracking]~^ ERROR generator cannot be sent between threads safely let guard = Bar { foo: Foo, x: 42 }; let Bar { foo, x } = guard; drop(foo); diff --git a/tests/ui/generator/partial-drop.stderr b/tests/ui/generator/partial-drop.stderr deleted file mode 100644 index e3c19264ee857..0000000000000 --- a/tests/ui/generator/partial-drop.stderr +++ /dev/null @@ -1,92 +0,0 @@ -error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:16:17 - | -LL | assert_send(|| { - | _________________^ -LL | | -LL | | // FIXME: it would be nice to make this work. -LL | | let guard = Bar { foo: Foo, x: 42 }; -LL | | drop(guard.foo); -LL | | yield; -LL | | }); - | |_____^ generator is not `Send` - | - = help: within `[generator@$DIR/partial-drop.rs:16:17: 16:19]`, the trait `Send` is not implemented for `Foo` -note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:21:9 - | -LL | let guard = Bar { foo: Foo, x: 42 }; - | ----- has type `Bar` which is not `Send` -LL | drop(guard.foo); -LL | yield; - | ^^^^^ yield occurs here, with `guard` maybe used later -LL | }); - | - `guard` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 - | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:24:17 - | -LL | assert_send(|| { - | _________________^ -LL | | -LL | | // FIXME: it would be nice to make this work. -LL | | let guard = Bar { foo: Foo, x: 42 }; -... | -LL | | yield; -LL | | }); - | |_____^ generator is not `Send` - | - = help: within `[generator@$DIR/partial-drop.rs:24:17: 24:19]`, the trait `Send` is not implemented for `Foo` -note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:31:9 - | -LL | let guard = Bar { foo: Foo, x: 42 }; - | ----- has type `Bar` which is not `Send` -... -LL | yield; - | ^^^^^ yield occurs here, with `guard` maybe used later -LL | }); - | - `guard` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 - | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: generator cannot be sent between threads safely - --> $DIR/partial-drop.rs:34:17 - | -LL | assert_send(|| { - | _________________^ -LL | | -LL | | // FIXME: it would be nice to make this work. -LL | | let guard = Bar { foo: Foo, x: 42 }; -... | -LL | | yield; -LL | | }); - | |_____^ generator is not `Send` - | - = help: within `[generator@$DIR/partial-drop.rs:34:17: 34:19]`, the trait `Send` is not implemented for `Foo` -note: generator is not `Send` as this value is used across a yield - --> $DIR/partial-drop.rs:40:9 - | -LL | let guard = Bar { foo: Foo, x: 42 }; - | ----- has type `Bar` which is not `Send` -... -LL | yield; - | ^^^^^ yield occurs here, with `guard` maybe used later -LL | }); - | - `guard` is later dropped here -note: required by a bound in `assert_send` - --> $DIR/partial-drop.rs:44:19 - | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: aborting due to 3 previous errors - diff --git a/tests/ui/generator/print/generator-print-verbose-1.drop_tracking_mir.stderr b/tests/ui/generator/print/generator-print-verbose-1.drop_tracking_mir.stderr index 7d0a201699b5c..c045b1441c146 100644 --- a/tests/ui/generator/print/generator-print-verbose-1.drop_tracking_mir.stderr +++ b/tests/ui/generator/print/generator-print-verbose-1.drop_tracking_mir.stderr @@ -1,8 +1,8 @@ error: generator cannot be sent between threads safely - --> $DIR/generator-print-verbose-1.rs:40:18 + --> $DIR/generator-print-verbose-1.rs:40:5 | LL | require_send(send_gen); - | ^^^^^^^^ generator is not `Send` + | ^^^^^^^^^^^^ generator is not `Send` | = help: the trait `Sync` is not implemented for `RefCell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead @@ -13,8 +13,6 @@ LL | let _non_send_gen = make_non_send_generator(); | ------------- has type `Opaque(DefId(0:34 ~ generator_print_verbose_1[749a]::make_non_send_generator::{opaque#0}), [])` which is not `Send` LL | yield; | ^^^^^ yield occurs here, with `_non_send_gen` maybe used later -LL | }; - | - `_non_send_gen` is later dropped here note: required by a bound in `require_send` --> $DIR/generator-print-verbose-1.rs:29:25 | @@ -22,12 +20,10 @@ LL | fn require_send(_: impl Send) {} | ^^^^ required by this bound in `require_send` error[E0277]: `RefCell` cannot be shared between threads safely - --> $DIR/generator-print-verbose-1.rs:59:18 + --> $DIR/generator-print-verbose-1.rs:59:5 | LL | require_send(send_gen); - | ------------ ^^^^^^^^ `RefCell` cannot be shared between threads safely - | | - | required by a bound introduced by this call + | ^^^^^^^^^^^^ `RefCell` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `RefCell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead @@ -47,7 +43,7 @@ note: required because it appears within the type `Opaque(DefId(0:36 ~ generator | LL | fn make_non_send_generator2() -> impl Generator>> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: required because it captures the following types: `Opaque(DefId(0:36 ~ generator_print_verbose_1[749a]::make_non_send_generator2::{opaque#0}), [])`, `()` + = note: required because it captures the following types: `Opaque(DefId(0:36 ~ generator_print_verbose_1[749a]::make_non_send_generator2::{opaque#0}), [])` note: required because it's used within this generator --> $DIR/generator-print-verbose-1.rs:55:20 | diff --git a/tests/ui/generator/print/generator-print-verbose-1.rs b/tests/ui/generator/print/generator-print-verbose-1.rs index d0acff8c93f94..c7052c7d1b04d 100644 --- a/tests/ui/generator/print/generator-print-verbose-1.rs +++ b/tests/ui/generator/print/generator-print-verbose-1.rs @@ -15,7 +15,7 @@ use std::{ }; pub struct Ready(Option); -impl Generator<()> for Ready { +impl Generator<()> for Ready { type Return = T; type Yield = (); fn resume(mut self: Pin<&mut Self>, _args: ()) -> GeneratorState<(), T> { diff --git a/tests/ui/generator/print/generator-print-verbose-2.drop_tracking.stderr b/tests/ui/generator/print/generator-print-verbose-2.drop_tracking.stderr index 0df978e47dca9..1f2e530f6f577 100644 --- a/tests/ui/generator/print/generator-print-verbose-2.drop_tracking.stderr +++ b/tests/ui/generator/print/generator-print-verbose-2.drop_tracking.stderr @@ -1,58 +1,60 @@ -error[E0277]: `Cell` cannot be shared between threads safely - --> $DIR/generator-print-verbose-2.rs:22:17 +error: generator cannot be shared between threads safely + --> $DIR/generator-print-verbose-2.rs:20:17 | -LL | assert_send(|| { - | _____-----------_^ - | | | - | | required by a bound introduced by this call +LL | assert_sync(|| { + | _________________^ LL | | -LL | | drop(&a); +LL | | let a = NotSync; LL | | yield; +LL | | drop(a); LL | | }); - | |_____^ `Cell` cannot be shared between threads safely + | |_____^ generator is not `Sync` | - = help: the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead - = note: required for `&'_#4r Cell` to implement `Send` -note: required because it's used within this generator - --> $DIR/generator-print-verbose-2.rs:22:17 + = help: within `[main::{closure#0} upvar_tys=() {NotSync, ()}]`, the trait `Sync` is not implemented for `NotSync` +note: generator is not `Sync` as this value is used across a yield + --> $DIR/generator-print-verbose-2.rs:23:9 | -LL | assert_send(|| { - | ^^ -note: required by a bound in `assert_send` - --> $DIR/generator-print-verbose-2.rs:13:23 +LL | let a = NotSync; + | - has type `NotSync` which is not `Sync` +LL | yield; + | ^^^^^ yield occurs here, with `a` maybe used later +LL | drop(a); +LL | }); + | - `a` is later dropped here +note: required by a bound in `assert_sync` + --> $DIR/generator-print-verbose-2.rs:17:23 | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` +LL | fn assert_sync(_: T) {} + | ^^^^ required by this bound in `assert_sync` -error: generator cannot be shared between threads safely - --> $DIR/generator-print-verbose-2.rs:15:17 +error: generator cannot be sent between threads safely + --> $DIR/generator-print-verbose-2.rs:27:17 | -LL | assert_sync(|| { +LL | assert_send(|| { | _________________^ LL | | -LL | | let a = Cell::new(2); +LL | | let a = NotSend; LL | | yield; +LL | | drop(a); LL | | }); - | |_____^ generator is not `Sync` + | |_____^ generator is not `Send` | - = help: within `[main::{closure#0} upvar_tys=() {Cell, ()}]`, the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead -note: generator is not `Sync` as this value is used across a yield - --> $DIR/generator-print-verbose-2.rs:18:9 + = help: within `[main::{closure#1} upvar_tys=() {NotSend, ()}]`, the trait `Send` is not implemented for `NotSend` +note: generator is not `Send` as this value is used across a yield + --> $DIR/generator-print-verbose-2.rs:30:9 | -LL | let a = Cell::new(2); - | - has type `Cell` which is not `Sync` +LL | let a = NotSend; + | - has type `NotSend` which is not `Send` LL | yield; | ^^^^^ yield occurs here, with `a` maybe used later +LL | drop(a); LL | }); | - `a` is later dropped here -note: required by a bound in `assert_sync` - --> $DIR/generator-print-verbose-2.rs:12:23 +note: required by a bound in `assert_send` + --> $DIR/generator-print-verbose-2.rs:18:23 | -LL | fn assert_sync(_: T) {} - | ^^^^ required by this bound in `assert_sync` +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/print/generator-print-verbose-2.drop_tracking_mir.stderr b/tests/ui/generator/print/generator-print-verbose-2.drop_tracking_mir.stderr index 0df978e47dca9..354369f195402 100644 --- a/tests/ui/generator/print/generator-print-verbose-2.drop_tracking_mir.stderr +++ b/tests/ui/generator/print/generator-print-verbose-2.drop_tracking_mir.stderr @@ -1,58 +1,42 @@ -error[E0277]: `Cell` cannot be shared between threads safely - --> $DIR/generator-print-verbose-2.rs:22:17 - | -LL | assert_send(|| { - | _____-----------_^ - | | | - | | required by a bound introduced by this call -LL | | -LL | | drop(&a); -LL | | yield; -LL | | }); - | |_____^ `Cell` cannot be shared between threads safely - | - = help: the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead - = note: required for `&'_#4r Cell` to implement `Send` -note: required because it's used within this generator - --> $DIR/generator-print-verbose-2.rs:22:17 +error: generator cannot be shared between threads safely + --> $DIR/generator-print-verbose-2.rs:20:5 | -LL | assert_send(|| { - | ^^ -note: required by a bound in `assert_send` - --> $DIR/generator-print-verbose-2.rs:13:23 +LL | assert_sync(|| { + | ^^^^^^^^^^^ generator is not `Sync` | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` - -error: generator cannot be shared between threads safely - --> $DIR/generator-print-verbose-2.rs:15:17 - | -LL | assert_sync(|| { - | _________________^ -LL | | -LL | | let a = Cell::new(2); -LL | | yield; -LL | | }); - | |_____^ generator is not `Sync` - | - = help: within `[main::{closure#0} upvar_tys=() {Cell, ()}]`, the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead + = help: within `[main::{closure#0} upvar_tys=() [main::{closure#0}]]`, the trait `Sync` is not implemented for `NotSync` note: generator is not `Sync` as this value is used across a yield - --> $DIR/generator-print-verbose-2.rs:18:9 + --> $DIR/generator-print-verbose-2.rs:23:9 | -LL | let a = Cell::new(2); - | - has type `Cell` which is not `Sync` +LL | let a = NotSync; + | - has type `NotSync` which is not `Sync` LL | yield; | ^^^^^ yield occurs here, with `a` maybe used later -LL | }); - | - `a` is later dropped here note: required by a bound in `assert_sync` - --> $DIR/generator-print-verbose-2.rs:12:23 + --> $DIR/generator-print-verbose-2.rs:17:23 | LL | fn assert_sync(_: T) {} | ^^^^ required by this bound in `assert_sync` +error: generator cannot be sent between threads safely + --> $DIR/generator-print-verbose-2.rs:27:5 + | +LL | assert_send(|| { + | ^^^^^^^^^^^ generator is not `Send` + | + = help: within `[main::{closure#1} upvar_tys=() [main::{closure#1}]]`, the trait `Send` is not implemented for `NotSend` +note: generator is not `Send` as this value is used across a yield + --> $DIR/generator-print-verbose-2.rs:30:9 + | +LL | let a = NotSend; + | - has type `NotSend` which is not `Send` +LL | yield; + | ^^^^^ yield occurs here, with `a` maybe used later +note: required by a bound in `assert_send` + --> $DIR/generator-print-verbose-2.rs:18:23 + | +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` + error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/print/generator-print-verbose-2.no_drop_tracking.stderr b/tests/ui/generator/print/generator-print-verbose-2.no_drop_tracking.stderr index 0df978e47dca9..1f2e530f6f577 100644 --- a/tests/ui/generator/print/generator-print-verbose-2.no_drop_tracking.stderr +++ b/tests/ui/generator/print/generator-print-verbose-2.no_drop_tracking.stderr @@ -1,58 +1,60 @@ -error[E0277]: `Cell` cannot be shared between threads safely - --> $DIR/generator-print-verbose-2.rs:22:17 +error: generator cannot be shared between threads safely + --> $DIR/generator-print-verbose-2.rs:20:17 | -LL | assert_send(|| { - | _____-----------_^ - | | | - | | required by a bound introduced by this call +LL | assert_sync(|| { + | _________________^ LL | | -LL | | drop(&a); +LL | | let a = NotSync; LL | | yield; +LL | | drop(a); LL | | }); - | |_____^ `Cell` cannot be shared between threads safely + | |_____^ generator is not `Sync` | - = help: the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead - = note: required for `&'_#4r Cell` to implement `Send` -note: required because it's used within this generator - --> $DIR/generator-print-verbose-2.rs:22:17 + = help: within `[main::{closure#0} upvar_tys=() {NotSync, ()}]`, the trait `Sync` is not implemented for `NotSync` +note: generator is not `Sync` as this value is used across a yield + --> $DIR/generator-print-verbose-2.rs:23:9 | -LL | assert_send(|| { - | ^^ -note: required by a bound in `assert_send` - --> $DIR/generator-print-verbose-2.rs:13:23 +LL | let a = NotSync; + | - has type `NotSync` which is not `Sync` +LL | yield; + | ^^^^^ yield occurs here, with `a` maybe used later +LL | drop(a); +LL | }); + | - `a` is later dropped here +note: required by a bound in `assert_sync` + --> $DIR/generator-print-verbose-2.rs:17:23 | -LL | fn assert_send(_: T) {} - | ^^^^ required by this bound in `assert_send` +LL | fn assert_sync(_: T) {} + | ^^^^ required by this bound in `assert_sync` -error: generator cannot be shared between threads safely - --> $DIR/generator-print-verbose-2.rs:15:17 +error: generator cannot be sent between threads safely + --> $DIR/generator-print-verbose-2.rs:27:17 | -LL | assert_sync(|| { +LL | assert_send(|| { | _________________^ LL | | -LL | | let a = Cell::new(2); +LL | | let a = NotSend; LL | | yield; +LL | | drop(a); LL | | }); - | |_____^ generator is not `Sync` + | |_____^ generator is not `Send` | - = help: within `[main::{closure#0} upvar_tys=() {Cell, ()}]`, the trait `Sync` is not implemented for `Cell` - = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead -note: generator is not `Sync` as this value is used across a yield - --> $DIR/generator-print-verbose-2.rs:18:9 + = help: within `[main::{closure#1} upvar_tys=() {NotSend, ()}]`, the trait `Send` is not implemented for `NotSend` +note: generator is not `Send` as this value is used across a yield + --> $DIR/generator-print-verbose-2.rs:30:9 | -LL | let a = Cell::new(2); - | - has type `Cell` which is not `Sync` +LL | let a = NotSend; + | - has type `NotSend` which is not `Send` LL | yield; | ^^^^^ yield occurs here, with `a` maybe used later +LL | drop(a); LL | }); | - `a` is later dropped here -note: required by a bound in `assert_sync` - --> $DIR/generator-print-verbose-2.rs:12:23 +note: required by a bound in `assert_send` + --> $DIR/generator-print-verbose-2.rs:18:23 | -LL | fn assert_sync(_: T) {} - | ^^^^ required by this bound in `assert_sync` +LL | fn assert_send(_: T) {} + | ^^^^ required by this bound in `assert_send` error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/print/generator-print-verbose-2.rs b/tests/ui/generator/print/generator-print-verbose-2.rs index 74b9811b50b2c..ab29db6e09c96 100644 --- a/tests/ui/generator/print/generator-print-verbose-2.rs +++ b/tests/ui/generator/print/generator-print-verbose-2.rs @@ -5,8 +5,13 @@ // Same as test/ui/generator/not-send-sync.rs #![feature(generators)] +#![feature(negative_impls)] -use std::cell::Cell; +struct NotSend; +struct NotSync; + +impl !Send for NotSend {} +impl !Sync for NotSync {} fn main() { fn assert_sync(_: T) {} @@ -14,14 +19,15 @@ fn main() { assert_sync(|| { //~^ ERROR: generator cannot be shared between threads safely - let a = Cell::new(2); + let a = NotSync; yield; + drop(a); }); - let a = Cell::new(2); assert_send(|| { - //~^ ERROR: E0277 - drop(&a); + //~^ ERROR: generator cannot be sent between threads safely + let a = NotSend; yield; + drop(a); }); } diff --git a/tests/ui/impl-trait/issue-55872-2.drop_tracking_mir.stderr b/tests/ui/impl-trait/issue-55872-2.drop_tracking_mir.stderr index 477c964bd40fd..c14bb5cc9142d 100644 --- a/tests/ui/impl-trait/issue-55872-2.drop_tracking_mir.stderr +++ b/tests/ui/impl-trait/issue-55872-2.drop_tracking_mir.stderr @@ -4,5 +4,11 @@ error: type parameter `T` is part of concrete type but not used in parameter lis LL | async {} | ^^^^^^^^ -error: aborting due to previous error +error: type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias + --> $DIR/issue-55872-2.rs:17:9 + | +LL | async {} + | ^^^^^^^^ + +error: aborting due to 2 previous errors diff --git a/tests/ui/impl-trait/issue-55872-2.rs b/tests/ui/impl-trait/issue-55872-2.rs index 1696ead0d8d1b..cbc7b5d62e138 100644 --- a/tests/ui/impl-trait/issue-55872-2.rs +++ b/tests/ui/impl-trait/issue-55872-2.rs @@ -16,6 +16,7 @@ impl Bar for S { fn foo() -> Self::E { async {} //~^ ERROR type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias + //[drop_tracking_mir]~^^ ERROR type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias } } diff --git a/tests/ui/impl-trait/issues/infinite-impl-trait-issue-38064.stderr b/tests/ui/impl-trait/issues/infinite-impl-trait-issue-38064.stderr index 16a1262ec27b3..92a3290622ef2 100644 --- a/tests/ui/impl-trait/issues/infinite-impl-trait-issue-38064.stderr +++ b/tests/ui/impl-trait/issues/infinite-impl-trait-issue-38064.stderr @@ -8,13 +8,13 @@ LL | Foo(bar()) | ---------- returning here with type `Foo` ... LL | fn bar() -> impl Quux { - | --------- returning this opaque type `Foo` + | --------- returning this type `Foo` error[E0720]: cannot resolve opaque type --> $DIR/infinite-impl-trait-issue-38064.rs:14:13 | LL | fn foo() -> impl Quux { - | --------- returning this opaque type `Bar` + | --------- returning this type `Bar` ... LL | fn bar() -> impl Quux { | ^^^^^^^^^ recursive opaque type diff --git a/tests/ui/impl-trait/recursive-impl-trait-type-indirect.drop_tracking_mir.stderr b/tests/ui/impl-trait/recursive-impl-trait-type-indirect.drop_tracking_mir.stderr index 43118ae38540f..662c74bcdc0d0 100644 --- a/tests/ui/impl-trait/recursive-impl-trait-type-indirect.drop_tracking_mir.stderr +++ b/tests/ui/impl-trait/recursive-impl-trait-type-indirect.drop_tracking_mir.stderr @@ -112,16 +112,8 @@ LL | (substs_change::<&T>(),) error[E0720]: cannot resolve opaque type --> $DIR/recursive-impl-trait-type-indirect.rs:76:24 | -LL | fn generator_hold() -> impl Sized { - | ^^^^^^^^^^ recursive opaque type -LL | -LL | / move || { -LL | | let x = generator_hold(); - | | - generator captures itself here -LL | | yield; -LL | | x; -LL | | } - | |_____- returning here with type `[generator@$DIR/recursive-impl-trait-type-indirect.rs:78:5: 78:12]` +LL | fn generator_hold() -> impl Sized { + | ^^^^^^^^^^ recursive opaque type error[E0720]: cannot resolve opaque type --> $DIR/recursive-impl-trait-type-indirect.rs:90:26 diff --git a/tests/ui/lint/must_not_suspend/dedup.drop_tracking.stderr b/tests/ui/lint/must_not_suspend/dedup.drop_tracking.stderr index 18880f5a757e0..262657da5fe6f 100644 --- a/tests/ui/lint/must_not_suspend/dedup.drop_tracking.stderr +++ b/tests/ui/lint/must_not_suspend/dedup.drop_tracking.stderr @@ -1,14 +1,16 @@ error: `No` held across a suspend point, but should not be - --> $DIR/dedup.rs:19:13 + --> $DIR/dedup.rs:19:9 | -LL | wheeee(&No {}).await; - | ^^^^^ ------ the value is held across this suspend point +LL | let no = No {}; + | ^^ +LL | wheeee(&no).await; + | ------ the value is held across this suspend point | help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/dedup.rs:19:13 + --> $DIR/dedup.rs:19:9 | -LL | wheeee(&No {}).await; - | ^^^^^ +LL | let no = No {}; + | ^^ note: the lint level is defined here --> $DIR/dedup.rs:6:9 | diff --git a/tests/ui/lint/must_not_suspend/dedup.drop_tracking_mir.stderr b/tests/ui/lint/must_not_suspend/dedup.drop_tracking_mir.stderr index 18880f5a757e0..262657da5fe6f 100644 --- a/tests/ui/lint/must_not_suspend/dedup.drop_tracking_mir.stderr +++ b/tests/ui/lint/must_not_suspend/dedup.drop_tracking_mir.stderr @@ -1,14 +1,16 @@ error: `No` held across a suspend point, but should not be - --> $DIR/dedup.rs:19:13 + --> $DIR/dedup.rs:19:9 | -LL | wheeee(&No {}).await; - | ^^^^^ ------ the value is held across this suspend point +LL | let no = No {}; + | ^^ +LL | wheeee(&no).await; + | ------ the value is held across this suspend point | help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/dedup.rs:19:13 + --> $DIR/dedup.rs:19:9 | -LL | wheeee(&No {}).await; - | ^^^^^ +LL | let no = No {}; + | ^^ note: the lint level is defined here --> $DIR/dedup.rs:6:9 | diff --git a/tests/ui/lint/must_not_suspend/dedup.no_drop_tracking.stderr b/tests/ui/lint/must_not_suspend/dedup.no_drop_tracking.stderr index 18880f5a757e0..7ed43d2571989 100644 --- a/tests/ui/lint/must_not_suspend/dedup.no_drop_tracking.stderr +++ b/tests/ui/lint/must_not_suspend/dedup.no_drop_tracking.stderr @@ -1,19 +1,33 @@ error: `No` held across a suspend point, but should not be - --> $DIR/dedup.rs:19:13 + --> $DIR/dedup.rs:19:9 | -LL | wheeee(&No {}).await; - | ^^^^^ ------ the value is held across this suspend point +LL | let no = No {}; + | ^^ +LL | wheeee(&no).await; + | ------ the value is held across this suspend point | help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/dedup.rs:19:13 + --> $DIR/dedup.rs:19:9 | -LL | wheeee(&No {}).await; - | ^^^^^ +LL | let no = No {}; + | ^^ note: the lint level is defined here --> $DIR/dedup.rs:6:9 | LL | #![deny(must_not_suspend)] | ^^^^^^^^^^^^^^^^ -error: aborting due to previous error +error: `No` held across a suspend point, but should not be + --> $DIR/dedup.rs:20:13 + | +LL | wheeee(&no).await; + | ^^ ------ the value is held across this suspend point + | +help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point + --> $DIR/dedup.rs:20:13 + | +LL | wheeee(&no).await; + | ^^ + +error: aborting due to 2 previous errors diff --git a/tests/ui/lint/must_not_suspend/dedup.rs b/tests/ui/lint/must_not_suspend/dedup.rs index 6e49ee52bd944..96bdb7715b183 100644 --- a/tests/ui/lint/must_not_suspend/dedup.rs +++ b/tests/ui/lint/must_not_suspend/dedup.rs @@ -16,7 +16,9 @@ async fn wheeee(t: T) { } async fn yes() { - wheeee(&No {}).await; //~ ERROR `No` held across + let no = No {}; //~ ERROR `No` held across + wheeee(&no).await; //[no_drop_tracking]~ ERROR `No` held across + drop(no); } fn main() { diff --git a/tests/ui/lint/must_not_suspend/ref.drop_tracking_mir.stderr b/tests/ui/lint/must_not_suspend/ref.drop_tracking_mir.stderr index e9bfa08b5ddd9..e3628ca5e4934 100644 --- a/tests/ui/lint/must_not_suspend/ref.drop_tracking_mir.stderr +++ b/tests/ui/lint/must_not_suspend/ref.drop_tracking_mir.stderr @@ -1,22 +1,22 @@ -error: `Umm` held across a suspend point, but should not be - --> $DIR/ref.rs:22:26 +error: reference to `Umm` held across a suspend point, but should not be + --> $DIR/ref.rs:22:13 | LL | let guard = &mut self.u; - | ^^^^^^ + | ^^^^^ LL | LL | other().await; | ------ the value is held across this suspend point | note: You gotta use Umm's, ya know? - --> $DIR/ref.rs:22:26 + --> $DIR/ref.rs:22:13 | LL | let guard = &mut self.u; - | ^^^^^^ + | ^^^^^ help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/ref.rs:22:26 + --> $DIR/ref.rs:22:13 | LL | let guard = &mut self.u; - | ^^^^^^ + | ^^^^^ note: the lint level is defined here --> $DIR/ref.rs:7:9 | diff --git a/tests/ui/lint/must_not_suspend/ref.rs b/tests/ui/lint/must_not_suspend/ref.rs index 8784ffbc63461..d05dcb83ac57c 100644 --- a/tests/ui/lint/must_not_suspend/ref.rs +++ b/tests/ui/lint/must_not_suspend/ref.rs @@ -23,6 +23,7 @@ impl Bar { other().await; + let _g = &*guard; *guard = Umm { i: 2 } } } diff --git a/tests/ui/lint/must_not_suspend/trait.rs b/tests/ui/lint/must_not_suspend/trait.rs index b6ccae0d249bb..cc3ae298dbba7 100644 --- a/tests/ui/lint/must_not_suspend/trait.rs +++ b/tests/ui/lint/must_not_suspend/trait.rs @@ -25,6 +25,9 @@ pub async fn uhoh() { let _guard2 = r#dyn(); //~ ERROR boxed `Wow` trait object held across other().await; + + drop(_guard1); + drop(_guard2); } fn main() { diff --git a/tests/ui/lint/must_not_suspend/unit.drop_tracking.stderr b/tests/ui/lint/must_not_suspend/unit.drop_tracking.stderr index 50ca292c2f6fd..f89b3e341fd8c 100644 --- a/tests/ui/lint/must_not_suspend/unit.drop_tracking.stderr +++ b/tests/ui/lint/must_not_suspend/unit.drop_tracking.stderr @@ -1,5 +1,5 @@ error: `Umm` held across a suspend point, but should not be - --> $DIR/unit.rs:23:9 + --> $DIR/unit.rs:22:9 | LL | let _guard = bar(); | ^^^^^^ @@ -7,12 +7,12 @@ LL | other().await; | ------ the value is held across this suspend point | note: You gotta use Umm's, ya know? - --> $DIR/unit.rs:23:9 + --> $DIR/unit.rs:22:9 | LL | let _guard = bar(); | ^^^^^^ help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/unit.rs:23:9 + --> $DIR/unit.rs:22:9 | LL | let _guard = bar(); | ^^^^^^ diff --git a/tests/ui/lint/must_not_suspend/unit.drop_tracking_mir.stderr b/tests/ui/lint/must_not_suspend/unit.drop_tracking_mir.stderr index 50ca292c2f6fd..f89b3e341fd8c 100644 --- a/tests/ui/lint/must_not_suspend/unit.drop_tracking_mir.stderr +++ b/tests/ui/lint/must_not_suspend/unit.drop_tracking_mir.stderr @@ -1,5 +1,5 @@ error: `Umm` held across a suspend point, but should not be - --> $DIR/unit.rs:23:9 + --> $DIR/unit.rs:22:9 | LL | let _guard = bar(); | ^^^^^^ @@ -7,12 +7,12 @@ LL | other().await; | ------ the value is held across this suspend point | note: You gotta use Umm's, ya know? - --> $DIR/unit.rs:23:9 + --> $DIR/unit.rs:22:9 | LL | let _guard = bar(); | ^^^^^^ help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/unit.rs:23:9 + --> $DIR/unit.rs:22:9 | LL | let _guard = bar(); | ^^^^^^ diff --git a/tests/ui/lint/must_not_suspend/unit.no_drop_tracking.stderr b/tests/ui/lint/must_not_suspend/unit.no_drop_tracking.stderr index 50ca292c2f6fd..f89b3e341fd8c 100644 --- a/tests/ui/lint/must_not_suspend/unit.no_drop_tracking.stderr +++ b/tests/ui/lint/must_not_suspend/unit.no_drop_tracking.stderr @@ -1,5 +1,5 @@ error: `Umm` held across a suspend point, but should not be - --> $DIR/unit.rs:23:9 + --> $DIR/unit.rs:22:9 | LL | let _guard = bar(); | ^^^^^^ @@ -7,12 +7,12 @@ LL | other().await; | ------ the value is held across this suspend point | note: You gotta use Umm's, ya know? - --> $DIR/unit.rs:23:9 + --> $DIR/unit.rs:22:9 | LL | let _guard = bar(); | ^^^^^^ help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/unit.rs:23:9 + --> $DIR/unit.rs:22:9 | LL | let _guard = bar(); | ^^^^^^ diff --git a/tests/ui/lint/must_not_suspend/unit.rs b/tests/ui/lint/must_not_suspend/unit.rs index 8903f8a6d0597..fbc51b366817c 100644 --- a/tests/ui/lint/must_not_suspend/unit.rs +++ b/tests/ui/lint/must_not_suspend/unit.rs @@ -10,7 +10,6 @@ struct Umm { i: i64 } - fn bar() -> Umm { Umm { i: 1 @@ -22,6 +21,7 @@ async fn other() {} pub async fn uhoh() { let _guard = bar(); //~ ERROR `Umm` held across other().await; + drop(_guard); } fn main() { diff --git a/tests/ui/lint/must_not_suspend/warn.rs b/tests/ui/lint/must_not_suspend/warn.rs index b5002cb9f60a5..5a4863169ea35 100644 --- a/tests/ui/lint/must_not_suspend/warn.rs +++ b/tests/ui/lint/must_not_suspend/warn.rs @@ -23,6 +23,7 @@ async fn other() {} pub async fn uhoh() { let _guard = bar(); //~ WARNING `Umm` held across other().await; + drop(_guard); } fn main() { From c51fc382bda4b268bccb746f007d46ae615f105a Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 1 Oct 2022 19:57:39 +0200 Subject: [PATCH 449/500] Bless ui-fulldeps. --- .../internal-lints/ty_tykind_usage.rs | 1 + .../internal-lints/ty_tykind_usage.stderr | 32 +++++++++++-------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/tests/ui-fulldeps/internal-lints/ty_tykind_usage.rs b/tests/ui-fulldeps/internal-lints/ty_tykind_usage.rs index 3f7429a5fccf8..bf655510a5ad8 100644 --- a/tests/ui-fulldeps/internal-lints/ty_tykind_usage.rs +++ b/tests/ui-fulldeps/internal-lints/ty_tykind_usage.rs @@ -31,6 +31,7 @@ fn main() { TyKind::Closure(..) => (), //~ ERROR usage of `ty::TyKind::` TyKind::Generator(..) => (), //~ ERROR usage of `ty::TyKind::` TyKind::GeneratorWitness(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::GeneratorWitnessMIR(..) => (), //~ ERROR usage of `ty::TyKind::` TyKind::Never => (), //~ ERROR usage of `ty::TyKind::` TyKind::Tuple(..) => (), //~ ERROR usage of `ty::TyKind::` TyKind::Alias(..) => (), //~ ERROR usage of `ty::TyKind::` diff --git a/tests/ui-fulldeps/internal-lints/ty_tykind_usage.stderr b/tests/ui-fulldeps/internal-lints/ty_tykind_usage.stderr index 1f49d6b64646f..9f8c0bea0eeff 100644 --- a/tests/ui-fulldeps/internal-lints/ty_tykind_usage.stderr +++ b/tests/ui-fulldeps/internal-lints/ty_tykind_usage.stderr @@ -121,59 +121,65 @@ LL | TyKind::GeneratorWitness(..) => (), error: usage of `ty::TyKind::` --> $DIR/ty_tykind_usage.rs:34:9 | -LL | TyKind::Never => (), +LL | TyKind::GeneratorWitnessMIR(..) => (), | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` --> $DIR/ty_tykind_usage.rs:35:9 | -LL | TyKind::Tuple(..) => (), +LL | TyKind::Never => (), | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` --> $DIR/ty_tykind_usage.rs:36:9 | -LL | TyKind::Alias(..) => (), +LL | TyKind::Tuple(..) => (), | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` --> $DIR/ty_tykind_usage.rs:37:9 | -LL | TyKind::Param(..) => (), +LL | TyKind::Alias(..) => (), | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` --> $DIR/ty_tykind_usage.rs:38:9 | -LL | TyKind::Bound(..) => (), +LL | TyKind::Param(..) => (), | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` --> $DIR/ty_tykind_usage.rs:39:9 | -LL | TyKind::Placeholder(..) => (), +LL | TyKind::Bound(..) => (), | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` --> $DIR/ty_tykind_usage.rs:40:9 | -LL | TyKind::Infer(..) => (), +LL | TyKind::Placeholder(..) => (), | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` --> $DIR/ty_tykind_usage.rs:41:9 | +LL | TyKind::Infer(..) => (), + | ^^^^^^ help: try using `ty::` directly: `ty` + +error: usage of `ty::TyKind::` + --> $DIR/ty_tykind_usage.rs:42:9 + | LL | TyKind::Error(_) => (), | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:46:12 + --> $DIR/ty_tykind_usage.rs:47:12 | LL | if let TyKind::Int(int_ty) = kind {} | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind` - --> $DIR/ty_tykind_usage.rs:48:24 + --> $DIR/ty_tykind_usage.rs:49:24 | LL | fn ty_kind(ty_bad: TyKind<'_>, ty_good: Ty<'_>) {} | ^^^^^^^^^^ @@ -181,7 +187,7 @@ LL | fn ty_kind(ty_bad: TyKind<'_>, ty_good: Ty<'_>) {} = help: try using `Ty` instead error: usage of `ty::TyKind` - --> $DIR/ty_tykind_usage.rs:50:37 + --> $DIR/ty_tykind_usage.rs:51:37 | LL | fn ir_ty_kind(bad: IrTyKind) -> IrTyKind { | ^^^^^^^^^^^ @@ -189,7 +195,7 @@ LL | fn ir_ty_kind(bad: IrTyKind) -> IrTyKind { = help: try using `Ty` instead error: usage of `ty::TyKind` - --> $DIR/ty_tykind_usage.rs:50:53 + --> $DIR/ty_tykind_usage.rs:51:53 | LL | fn ir_ty_kind(bad: IrTyKind) -> IrTyKind { | ^^^^^^^^^^^ @@ -197,12 +203,12 @@ LL | fn ir_ty_kind(bad: IrTyKind) -> IrTyKind { = help: try using `Ty` instead error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:53:9 + --> $DIR/ty_tykind_usage.rs:54:9 | LL | IrTyKind::Bool | --------^^^^^^ | | | help: try using `ty::` directly: `ty` -error: aborting due to 32 previous errors +error: aborting due to 33 previous errors From 92f2d27d1b5ec6b81299edf0e55bb1f0fc45ae9b Mon Sep 17 00:00:00 2001 From: b-naber Date: Fri, 27 Jan 2023 22:13:55 +0100 Subject: [PATCH 450/500] address review --- compiler/rustc_middle/src/thir/print.rs | 14 ++--- compiler/rustc_middle/src/ty/adt.rs | 6 +- tests/ui/thir-print/thir-flat.rs | 4 ++ tests/ui/thir-print/thir-flat.stdout | 56 +++++++++++++++++++ tests/ui/{ => thir-print}/thir-tree-match.rs | 0 .../{ => thir-print}/thir-tree-match.stdout | 0 tests/ui/{ => thir-print}/thir-tree.rs | 0 tests/ui/{ => thir-print}/thir-tree.stdout | 0 8 files changed, 70 insertions(+), 10 deletions(-) create mode 100644 tests/ui/thir-print/thir-flat.rs create mode 100644 tests/ui/thir-print/thir-flat.stdout rename tests/ui/{ => thir-print}/thir-tree-match.rs (100%) rename tests/ui/{ => thir-print}/thir-tree-match.stdout (100%) rename tests/ui/{ => thir-print}/thir-tree.rs (100%) rename tests/ui/{ => thir-print}/thir-tree.stdout (100%) diff --git a/compiler/rustc_middle/src/thir/print.rs b/compiler/rustc_middle/src/thir/print.rs index 28ef768ade6f7..60b903e99066b 100644 --- a/compiler/rustc_middle/src/thir/print.rs +++ b/compiler/rustc_middle/src/thir/print.rs @@ -522,7 +522,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { fn print_adt_expr(&mut self, adt_expr: &AdtExpr<'tcx>, depth_lvl: usize) { print_indented!(self, "adt_def:", depth_lvl); - self.print_adt_def(&*adt_expr.adt_def.0, depth_lvl + 1); + self.print_adt_def(adt_expr.adt_def, depth_lvl + 1); print_indented!( self, format!("variant_index: {:?}", adt_expr.variant_index), @@ -544,12 +544,12 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { } } - fn print_adt_def(&mut self, adt_def: &ty::AdtDefData, depth_lvl: usize) { + fn print_adt_def(&mut self, adt_def: ty::AdtDef<'tcx>, depth_lvl: usize) { print_indented!(self, "AdtDef {", depth_lvl); - print_indented!(self, format!("did: {:?}", adt_def.did), depth_lvl + 1); - print_indented!(self, format!("variants: {:?}", adt_def.variants), depth_lvl + 1); - print_indented!(self, format!("flags: {:?}", adt_def.flags), depth_lvl + 1); - print_indented!(self, format!("repr: {:?}", adt_def.repr), depth_lvl + 1); + print_indented!(self, format!("did: {:?}", adt_def.did()), depth_lvl + 1); + print_indented!(self, format!("variants: {:?}", adt_def.variants()), depth_lvl + 1); + print_indented!(self, format!("flags: {:?}", adt_def.flags()), depth_lvl + 1); + print_indented!(self, format!("repr: {:?}", adt_def.repr()), depth_lvl + 1); } fn print_fru_info(&mut self, fru_info: &FruInfo<'tcx>, depth_lvl: usize) { @@ -633,7 +633,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { PatKind::Variant { adt_def, substs, variant_index, subpatterns } => { print_indented!(self, "Variant {", depth_lvl + 1); print_indented!(self, "adt_def: ", depth_lvl + 2); - self.print_adt_def(&*adt_def.0, depth_lvl + 3); + self.print_adt_def(*adt_def, depth_lvl + 3); print_indented!(self, format!("substs: {:?}", substs), depth_lvl + 2); print_indented!(self, format!("variant_index: {:?}", variant_index), depth_lvl + 2); diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index 3d6da7fe792e7..d3d667f68407f 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -90,11 +90,11 @@ pub struct AdtDefData { /// The `DefId` of the struct, enum or union item. pub did: DefId, /// Variants of the ADT. If this is a struct or union, then there will be a single variant. - pub(crate) variants: IndexVec, + variants: IndexVec, /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?). - pub(crate) flags: AdtFlags, + flags: AdtFlags, /// Repr options provided by the user. - pub(crate) repr: ReprOptions, + repr: ReprOptions, } impl PartialOrd for AdtDefData { diff --git a/tests/ui/thir-print/thir-flat.rs b/tests/ui/thir-print/thir-flat.rs new file mode 100644 index 0000000000000..8fa95ce62b5ef --- /dev/null +++ b/tests/ui/thir-print/thir-flat.rs @@ -0,0 +1,4 @@ +// compile-flags: -Z unpretty=thir-flat +// check-pass + +pub fn main() {} diff --git a/tests/ui/thir-print/thir-flat.stdout b/tests/ui/thir-print/thir-flat.stdout new file mode 100644 index 0000000000000..c399fa66b6a03 --- /dev/null +++ b/tests/ui/thir-print/thir-flat.stdout @@ -0,0 +1,56 @@ +DefId(0:3 ~ thir_flat[45a6]::main): +Thir { + arms: [], + blocks: [ + Block { + targeted_by_break: false, + region_scope: Node(1), + opt_destruction_scope: None, + span: $DIR/thir-flat.rs:4:15: 4:17 (#0), + stmts: [], + expr: None, + safety_mode: Safe, + }, + ], + exprs: [ + Expr { + ty: (), + temp_lifetime: Some( + Node(2), + ), + span: $DIR/thir-flat.rs:4:15: 4:17 (#0), + kind: Block { + block: b0, + }, + }, + Expr { + ty: (), + temp_lifetime: Some( + Node(2), + ), + span: $DIR/thir-flat.rs:4:15: 4:17 (#0), + kind: Scope { + region_scope: Node(2), + lint_level: Explicit( + HirId(DefId(0:3 ~ thir_flat[45a6]::main).2), + ), + value: e0, + }, + }, + Expr { + ty: (), + temp_lifetime: Some( + Node(2), + ), + span: $DIR/thir-flat.rs:4:15: 4:17 (#0), + kind: Scope { + region_scope: Destruction(2), + lint_level: Inherited, + value: e1, + }, + }, + ], + stmts: [], + params: [], +} + diff --git a/tests/ui/thir-tree-match.rs b/tests/ui/thir-print/thir-tree-match.rs similarity index 100% rename from tests/ui/thir-tree-match.rs rename to tests/ui/thir-print/thir-tree-match.rs diff --git a/tests/ui/thir-tree-match.stdout b/tests/ui/thir-print/thir-tree-match.stdout similarity index 100% rename from tests/ui/thir-tree-match.stdout rename to tests/ui/thir-print/thir-tree-match.stdout diff --git a/tests/ui/thir-tree.rs b/tests/ui/thir-print/thir-tree.rs similarity index 100% rename from tests/ui/thir-tree.rs rename to tests/ui/thir-print/thir-tree.rs diff --git a/tests/ui/thir-tree.stdout b/tests/ui/thir-print/thir-tree.stdout similarity index 100% rename from tests/ui/thir-tree.stdout rename to tests/ui/thir-print/thir-tree.stdout From 65c3c90f3ecaa011bd7067efd562397de219facf Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 21 Jan 2023 10:03:12 +0000 Subject: [PATCH 451/500] Restrict amount of ignored locals. --- compiler/rustc_middle/src/mir/mod.rs | 2 + compiler/rustc_middle/src/mir/query.rs | 4 +- compiler/rustc_middle/src/ty/util.rs | 2 +- .../rustc_mir_build/src/build/matches/mod.rs | 1 + compiler/rustc_mir_transform/src/generator.rs | 37 ++++++++++---- .../src/traits/error_reporting/suggestions.rs | 2 +- .../issue-105084.drop_tracking_mir.stderr | 51 +++++++++++++++++++ tests/ui/generator/issue-105084.rs | 49 ++++++++++++++++++ 8 files changed, 135 insertions(+), 13 deletions(-) create mode 100644 tests/ui/generator/issue-105084.drop_tracking_mir.stderr create mode 100644 tests/ui/generator/issue-105084.rs diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 4da893e4c0716..63b8dd055bd5b 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -902,6 +902,8 @@ pub enum LocalInfo<'tcx> { AggregateTemp, /// A temporary created during the pass `Derefer` to avoid it's retagging DerefTemp, + /// A temporary created for borrow checking. + FakeBorrow, } impl<'tcx> LocalDecl<'tcx> { diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index ebeefa862778a..6155f2bb56ce9 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -140,8 +140,8 @@ pub struct GeneratorSavedTy<'tcx> { pub ty: Ty<'tcx>, /// Source info corresponding to the local in the original MIR body. pub source_info: SourceInfo, - /// Whether the local was introduced as a raw pointer to a static. - pub is_static_ptr: bool, + /// Whether the local should be ignored for trait bound computations. + pub ignore_for_traits: bool, } /// The layout of generator state. diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index ce87931dbea02..796164b0d6af3 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -625,7 +625,7 @@ impl<'tcx> TyCtxt<'tcx> { generator_layout .field_tys .iter() - .filter(|decl| !decl.is_static_ptr) + .filter(|decl| !decl.ignore_for_traits) .map(|decl| ty::EarlyBinder(decl.ty)) } diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/build/matches/mod.rs index 2a2fe791d8c59..6b960ebdb16f1 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/build/matches/mod.rs @@ -1749,6 +1749,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let fake_borrow_ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty); let mut fake_borrow_temp = LocalDecl::new(fake_borrow_ty, temp_span); fake_borrow_temp.internal = self.local_decls[matched_place.local].internal; + fake_borrow_temp.local_info = Some(Box::new(LocalInfo::FakeBorrow)); let fake_borrow_temp = self.local_decls.push(fake_borrow_temp); (matched_place, fake_borrow_temp) diff --git a/compiler/rustc_mir_transform/src/generator.rs b/compiler/rustc_mir_transform/src/generator.rs index 25f270b188696..e8871ff37f24a 100644 --- a/compiler/rustc_mir_transform/src/generator.rs +++ b/compiler/rustc_mir_transform/src/generator.rs @@ -879,7 +879,7 @@ fn sanitize_witness<'tcx>( let mut mismatches = Vec::new(); for fty in &layout.field_tys { - if fty.is_static_ptr { + if fty.ignore_for_traits { continue; } let decl_ty = tcx.normalize_erasing_regions(param_env, fty.ty); @@ -904,6 +904,7 @@ fn sanitize_witness<'tcx>( } fn compute_layout<'tcx>( + tcx: TyCtxt<'tcx>, liveness: LivenessInfo, body: &Body<'tcx>, ) -> ( @@ -923,15 +924,33 @@ fn compute_layout<'tcx>( let mut locals = IndexVec::::new(); let mut tys = IndexVec::::new(); for (saved_local, local) in saved_locals.iter_enumerated() { + debug!("generator saved local {:?} => {:?}", saved_local, local); + locals.push(local); let decl = &body.local_decls[local]; - let decl = GeneratorSavedTy { - ty: decl.ty, - source_info: decl.source_info, - is_static_ptr: decl.internal, + debug!(?decl); + + let ignore_for_traits = if tcx.sess.opts.unstable_opts.drop_tracking_mir { + match decl.local_info { + // Do not include raw pointers created from accessing `static` items, as those could + // well be re-created by another access to the same static. + Some(box LocalInfo::StaticRef { is_thread_local, .. }) => !is_thread_local, + // Fake borrows are only read by fake reads, so do not have any reality in + // post-analysis MIR. + Some(box LocalInfo::FakeBorrow) => true, + _ => false, + } + } else { + // FIXME(#105084) HIR-based drop tracking does not account for all the temporaries that + // MIR building may introduce. This leads to wrongly ignored types, but this is + // necessary for internal consistency and to avoid ICEs. + decl.internal }; + let decl = + GeneratorSavedTy { ty: decl.ty, source_info: decl.source_info, ignore_for_traits }; + debug!(?decl); + tys.push(decl); - debug!("generator saved local {:?} => {:?}", saved_local, local); } // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states. @@ -1401,7 +1420,7 @@ pub(crate) fn mir_generator_witnesses<'tcx>( // Extract locals which are live across suspension point into `layout` // `remap` gives a mapping from local indices onto generator struct indices // `storage_liveness` tells us which locals have live storage at suspension points - let (_, generator_layout, _) = compute_layout(liveness_info, body); + let (_, generator_layout, _) = compute_layout(tcx, liveness_info, body); if tcx.sess.opts.unstable_opts.drop_tracking_mir { check_suspend_tys(tcx, &generator_layout, &body); @@ -1503,7 +1522,7 @@ impl<'tcx> MirPass<'tcx> for StateTransform { // Extract locals which are live across suspension point into `layout` // `remap` gives a mapping from local indices onto generator struct indices // `storage_liveness` tells us which locals have live storage at suspension points - let (remap, layout, storage_liveness) = compute_layout(liveness_info, body); + let (remap, layout, storage_liveness) = compute_layout(tcx, liveness_info, body); let can_return = can_return(tcx, body, tcx.param_env(body.source.def_id())); @@ -1700,7 +1719,7 @@ fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &GeneratorLayout<'tcx>, bo let decl = &layout.field_tys[local]; debug!(?decl); - if !decl.is_static_ptr && linted_tys.insert(decl.ty) { + if !decl.ignore_for_traits && linted_tys.insert(decl.ty) { let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else { continue }; check_must_not_suspend_ty( diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 827806442d2da..f7f787dea95b4 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -2389,7 +2389,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { for &local in variant { let decl = &generator_info.field_tys[local]; debug!(?decl); - if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.is_static_ptr { + if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits { interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior( decl.source_info.span, Some((None, source_info.span, None, from_awaited_ty)), diff --git a/tests/ui/generator/issue-105084.drop_tracking_mir.stderr b/tests/ui/generator/issue-105084.drop_tracking_mir.stderr new file mode 100644 index 0000000000000..cfc0cf7cdd701 --- /dev/null +++ b/tests/ui/generator/issue-105084.drop_tracking_mir.stderr @@ -0,0 +1,51 @@ +error[E0382]: borrow of moved value: `g` + --> $DIR/issue-105084.rs:44:14 + | +LL | let mut g = || { + | ----- move occurs because `g` has type `[generator@$DIR/issue-105084.rs:22:17: 22:19]`, which does not implement the `Copy` trait +... +LL | let mut h = copy(g); + | - value moved here +... +LL | Pin::new(&mut g).resume(()); + | ^^^^^^ value borrowed here after move + | +note: consider changing this parameter type in function `copy` to borrow instead if owning the value isn't necessary + --> $DIR/issue-105084.rs:17:21 + | +LL | fn copy(x: T) -> T { + | ---- ^ this parameter takes ownership of the value + | | + | in this function +help: consider cloning the value if the performance cost is acceptable + | +LL | let mut h = copy(g.clone()); + | ++++++++ + +error[E0277]: the trait bound `Box<(i32, ())>: Copy` is not satisfied in `[generator@$DIR/issue-105084.rs:22:17: 22:19]` + --> $DIR/issue-105084.rs:38:17 + | +LL | let mut g = || { + | -- within this `[generator@$DIR/issue-105084.rs:22:17: 22:19]` +... +LL | let mut h = copy(g); + | ^^^^ within `[generator@$DIR/issue-105084.rs:22:17: 22:19]`, the trait `Copy` is not implemented for `Box<(i32, ())>` + | +note: generator does not implement `Copy` as this value is used across a yield + --> $DIR/issue-105084.rs:28:25 + | +LL | let t = box (5, yield); + | --------^^^^^- + | | | + | | yield occurs here, with `box (5, yield)` maybe used later + | has type `Box<(i32, ())>` which does not implement `Copy` +note: required by a bound in `copy` + --> $DIR/issue-105084.rs:17:12 + | +LL | fn copy(x: T) -> T { + | ^^^^ required by this bound in `copy` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0277, E0382. +For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/generator/issue-105084.rs b/tests/ui/generator/issue-105084.rs new file mode 100644 index 0000000000000..7c9a97b40a5dc --- /dev/null +++ b/tests/ui/generator/issue-105084.rs @@ -0,0 +1,49 @@ +// revisions: no_drop_tracking drop_tracking drop_tracking_mir +// [drop_tracking] compile-flags: -Zdrop-tracking +// [drop_tracking_mir] compile-flags: -Zdrop-tracking-mir +// [no_drop_tracking] known-bug: #105084 +// [no_drop_tracking] check-pass +// [drop_tracking] known-bug: #105084 +// [drop_tracking] check-pass + +#![feature(generators)] +#![feature(generator_clone)] +#![feature(generator_trait)] +#![feature(box_syntax)] + +use std::ops::Generator; +use std::pin::Pin; + +fn copy(x: T) -> T { + x +} + +fn main() { + let mut g = || { + // This is desuraged as 4 stages: + // - allocate a `*mut u8` with `exchange_malloc`; + // - create a Box that is ignored for trait computations; + // - compute fields (and yields); + // - assign to `t`. + let t = box (5, yield); + drop(t); + }; + + // Allocate the temporary box. + Pin::new(&mut g).resume(()); + + // The temporary box is in generator locals. + // As it is not taken into account for trait computation, + // the generator is `Copy`. + let mut h = copy(g); + //[drop_tracking_mir]~^ ERROR the trait bound `Box<(i32, ())>: Copy` is not satisfied in + + // We now have 2 boxes with the same backing allocation: + // one inside `g` and one inside `h`. + // Proceed and drop `t` in `g`. + Pin::new(&mut g).resume(()); + //[drop_tracking_mir]~^ ERROR borrow of moved value: `g` + + // Proceed and drop `t` in `h` -> double free! + Pin::new(&mut h).resume(()); +} From de110f920844f5dd299c6db9ea182efacf7800cf Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 21 Jan 2023 10:12:11 +0000 Subject: [PATCH 452/500] Pacify tidy. --- compiler/rustc_infer/src/traits/engine.rs | 2 +- .../src/traits/query/normalize.rs | 10 +++++----- compiler/rustc_ty_utils/src/needs_drop.rs | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_infer/src/traits/engine.rs b/compiler/rustc_infer/src/traits/engine.rs index ef2fee02e083e..f75344f20b6d9 100644 --- a/compiler/rustc_infer/src/traits/engine.rs +++ b/compiler/rustc_infer/src/traits/engine.rs @@ -43,7 +43,7 @@ pub trait TraitEngine<'tcx>: 'tcx { fn pending_obligations(&self) -> Vec>; /// Among all pending obligations, collect those are stalled on a inference variable which has - /// changed since the last call to `select_where_possible`. Those obligations are marked as + /// changed since the last call to `select_where_possible`. Those obligations are marked as /// successful and returned. fn drain_unstalled_obligations( &mut self, diff --git a/compiler/rustc_trait_selection/src/traits/query/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/normalize.rs index 8249144f57aae..1b2533a5cf649 100644 --- a/compiler/rustc_trait_selection/src/traits/query/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/normalize.rs @@ -216,11 +216,11 @@ impl<'cx, 'tcx> FallibleTypeFolder<'tcx> for QueryNormalizer<'cx, 'tcx> { let substs = substs.try_fold_with(self)?; let recursion_limit = self.tcx().recursion_limit(); if !recursion_limit.value_within_limit(self.anon_depth) { - // A closure or generator may have itself as in its upvars. This - // should be checked handled by the recursion check for opaque types, - // but we may end up here before that check can happen. In that case, - // we delay a bug to mark the trip, and continue without revealing the - // opaque. + // A closure or generator may have itself as in its upvars. + // This should be checked handled by the recursion check for opaque + // types, but we may end up here before that check can happen. + // In that case, we delay a bug to mark the trip, and continue without + // revealing the opaque. self.infcx .err_ctxt() .build_overflow_error(&ty, self.cause.span, true) diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index f519ea01a2c9d..cd1475391a4d9 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -110,8 +110,8 @@ where for component in components { match *component.kind() { // The information required to determine whether a generator has drop is - // computed on MIR, while this very method is used to build MIR. To avoid - // cycles, we consider that generators always require drop. + // computed on MIR, while this very method is used to build MIR. + // To avoid cycles, we consider that generators always require drop. ty::Generator(..) if tcx.sess.opts.unstable_opts.drop_tracking_mir => { return Some(Err(AlwaysRequiresDrop)); } From d3d626920abf2a4c93bd50640a9d66ce9d5a9009 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 21 Jan 2023 14:26:44 +0000 Subject: [PATCH 453/500] Bless mir-opt tests. --- ..._await.b-{closure#0}.generator_resume.0.mir | 18 ++++++++++++++++-- ...eanup.main-{closure#0}.generator_drop.0.mir | 2 +- ...iny.main-{closure#0}.generator_resume.0.mir | 2 +- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/tests/mir-opt/building/async_await.b-{closure#0}.generator_resume.0.mir b/tests/mir-opt/building/async_await.b-{closure#0}.generator_resume.0.mir index 05edc4797d4e5..1449247aedad3 100644 --- a/tests/mir-opt/building/async_await.b-{closure#0}.generator_resume.0.mir +++ b/tests/mir-opt/building/async_await.b-{closure#0}.generator_resume.0.mir @@ -1,8 +1,22 @@ // MIR for `b::{closure#0}` 0 generator_resume /* generator_layout = GeneratorLayout { field_tys: { - _0: impl std::future::Future, - _1: impl std::future::Future, + _0: GeneratorSavedTy { + ty: impl std::future::Future, + source_info: SourceInfo { + span: $DIR/async_await.rs:15:8: 15:14 (#9), + scope: scope[0], + }, + ignore_for_traits: false, + }, + _1: GeneratorSavedTy { + ty: impl std::future::Future, + source_info: SourceInfo { + span: $DIR/async_await.rs:16:8: 16:14 (#12), + scope: scope[0], + }, + ignore_for_traits: false, + }, }, variant_fields: { Unresumed(0): [], diff --git a/tests/mir-opt/generator_drop_cleanup.main-{closure#0}.generator_drop.0.mir b/tests/mir-opt/generator_drop_cleanup.main-{closure#0}.generator_drop.0.mir index 862dfc9006284..afe518642146f 100644 --- a/tests/mir-opt/generator_drop_cleanup.main-{closure#0}.generator_drop.0.mir +++ b/tests/mir-opt/generator_drop_cleanup.main-{closure#0}.generator_drop.0.mir @@ -7,7 +7,7 @@ span: $DIR/generator_drop_cleanup.rs:11:13: 11:15 (#0), scope: scope[0], }, - is_static_ptr: false, + ignore_for_traits: false, }, }, variant_fields: { diff --git a/tests/mir-opt/generator_tiny.main-{closure#0}.generator_resume.0.mir b/tests/mir-opt/generator_tiny.main-{closure#0}.generator_resume.0.mir index 0d262f75c1ac9..2f096c3e0a189 100644 --- a/tests/mir-opt/generator_tiny.main-{closure#0}.generator_resume.0.mir +++ b/tests/mir-opt/generator_tiny.main-{closure#0}.generator_resume.0.mir @@ -7,7 +7,7 @@ span: $DIR/generator_tiny.rs:20:13: 20:15 (#0), scope: scope[0], }, - is_static_ptr: false, + ignore_for_traits: false, }, }, variant_fields: { From 0959149323bd025905cd8b2572426e6fe443b420 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Fri, 27 Jan 2023 14:23:28 -0700 Subject: [PATCH 454/500] rustdoc: remove inline javascript from copy-path button --- src/librustdoc/html/static/js/main.js | 6 +++++- src/librustdoc/html/templates/print_item.html | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/librustdoc/html/static/js/main.js b/src/librustdoc/html/static/js/main.js index 604ab147f6a16..b9ad8ef70e917 100644 --- a/src/librustdoc/html/static/js/main.js +++ b/src/librustdoc/html/static/js/main.js @@ -1142,7 +1142,11 @@ function loadCss(cssUrl) { (function() { let reset_button_timeout = null; - window.copy_path = but => { + const but = document.getElementById("copy-path"); + if (!but) { + return; + } + but.onclick = () => { const parent = but.parentElement; const path = []; diff --git a/src/librustdoc/html/templates/print_item.html b/src/librustdoc/html/templates/print_item.html index ee2880bf6d195..3a1867b7feba3 100644 --- a/src/librustdoc/html/templates/print_item.html +++ b/src/librustdoc/html/templates/print_item.html @@ -6,7 +6,7 @@

{#- -#} {{component.name}}:: {%- endfor -%} {{name}} {#- -#} -