diff --git a/compiler/rustc_attr_parsing/src/attributes/lint.rs b/compiler/rustc_attr_parsing/src/attributes/lint.rs index 45cbcf4664404..bb53dd6995feb 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint.rs @@ -28,6 +28,7 @@ impl LintParser { fn parse(&mut self, kind: LintCheckKind, cx: &mut AcceptContext<'_, '_>, args: &ArgParser) { let attr_span = cx.attr_span; let attr_id = cx.attr_id.expect("no `AttrId` for lint attribute"); + let mut has_invalid_reason_key = false; if let Some(list) = cx.expect_list(args, cx.attr_span) { let mut parsers = list.sub_parsers(); @@ -37,16 +38,16 @@ impl LintParser { let p = parsers.last()?.meta_item()?; let nv = p.args().as_name_value()?; if !p.path().word_is(sym::reason) { - // FIXME: We should recommend `reason` here + has_invalid_reason_key = true; cx.emit_err(MalformedLintAttributeInput { span: p.span(), - help: MalformedLintAttributeInputHelp::Other { kind: kind.sym() }, + help: MalformedLintAttributeInputHelp::Reason { + reason_span: p.path().span(), + }, kind: kind.sym(), }); - } else { - parsers = &parsers[..(parsers.len() - 1)]; } - + parsers = &parsers[..(parsers.len() - 1)]; let reason = nv.expect_string_literal(cx)?; reason }; @@ -110,7 +111,7 @@ impl LintParser { // FIXME(164898) Lint attributes are unique because they're parsed twice with `ShouldEmit::ErrorsAndLints` // To avoid emitting the lint twice, we check `cx.parse_filter`, which will be `Some` during AST linting - if parsers.is_empty() && cx.parse_filter.is_none() { + if parsers.is_empty() && cx.parse_filter.is_none() && !has_invalid_reason_key { cx.emit_lint( UNUSED_ATTRIBUTES, diagnostics::Unused { diff --git a/compiler/rustc_attr_parsing/src/diagnostics.rs b/compiler/rustc_attr_parsing/src/diagnostics.rs index 12b2fe8cff6e8..a4d37b74beb52 100644 --- a/compiler/rustc_attr_parsing/src/diagnostics.rs +++ b/compiler/rustc_attr_parsing/src/diagnostics.rs @@ -2233,6 +2233,16 @@ pub(crate) struct MalformedLintAttributeInput { pub(crate) enum MalformedLintAttributeInputHelp { #[help("try using `#[{$kind}({$sym})]`")] StrLit { sym: Symbol, kind: Symbol }, + #[suggestion( + "to provide a reason, use `reason = \"\"`", + code = "reason", + applicability = "machine-applicable", + style = "verbose" + )] + Reason { + #[primary_span] + reason_span: Span, + }, #[help("for example, write `#[{$kind}(dead_code)]` for `dead_code`")] Other { kind: Symbol }, } diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index e60b1829e56de..fc8cf733136b4 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -1,7 +1,7 @@ use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; -use std::{iter, mem}; +use std::{iter, mem, slice}; use rustc_ast::mut_visit::*; use rustc_ast::tokenstream::TokenStream; @@ -2228,17 +2228,34 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { // Run attributes through the attribute parser // since they will not be detected after macro expansion. fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) { - AttributeParser::parse_limited_all( - self.cx.sess, - attrs, - None, - AstTarget::MacroCall, - call.span(), - self.cx.current_expansion.lint_node_id, - Some(self.cx.ecfg.features), - ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, - Some(self.cx.resolver.registered_attr_tools()), - ); + let parse = |group| { + AttributeParser::parse_limited_all( + self.cx.sess, + group, + None, + AstTarget::MacroCall, + call.span(), + self.cx.current_expansion.lint_node_id, + Some(self.cx.ecfg.features), + ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, + Some(self.cx.resolver.registered_attr_tools()), + ) + }; + + let mut doc_attrs = vec![]; + for attr in attrs { + if matches!(attr.kind, AttrKind::DocComment(..)) { + doc_attrs.push(attr.clone()); + continue; + } + parse(slice::from_ref(attr)); + } + + // Parse all doc comments together in a group, to prevent a group of + // unused doc comments from emitting multiple lints + if !doc_attrs.is_empty() { + parse(doc_attrs.as_slice()); + } } fn expand_cfg_true( diff --git a/compiler/rustc_target/src/spec/base/linux_musl.rs b/compiler/rustc_target/src/spec/base/linux_musl.rs index 6d3124b559b11..c7286f79ea124 100644 --- a/compiler/rustc_target/src/spec/base/linux_musl.rs +++ b/compiler/rustc_target/src/spec/base/linux_musl.rs @@ -6,6 +6,7 @@ pub(crate) fn opts() -> TargetOptions { pre_link_objects_self_contained: crt_objects::pre_musl_self_contained(), post_link_objects_self_contained: crt_objects::post_musl_self_contained(), link_self_contained: LinkSelfContainedDefault::InferredForMusl, + static_position_independent_executables: true, ..base::linux::opts() } } diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs index a664f22479913..8c82639c599ac 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs @@ -9,7 +9,6 @@ pub(crate) fn target() -> Target { base.max_atomic_width = Some(64); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64"]); base.stack_probes = StackProbeType::Inline; - base.static_position_independent_executables = true; base.supported_sanitizers = SanitizerSet::ADDRESS | SanitizerSet::CFI | SanitizerSet::LEAK diff --git a/src/ci/citool/src/jobs.rs b/src/ci/citool/src/jobs.rs index b94f12a37cc77..6ca6cd10815ba 100644 --- a/src/ci/citool/src/jobs.rs +++ b/src/ci/citool/src/jobs.rs @@ -29,8 +29,6 @@ pub struct Job { pub free_disk: Option, /// Documentation link to a resource that could help people debug this CI job. pub doc_url: Option, - /// Whether the job is executed on AWS CodeBuild. - pub codebuild: Option, /// Which Python version (if any) is required. On Windows, this is typically required to run /// LLDB. #[serde(default)] @@ -170,7 +168,6 @@ fn validate_job_database(db: &JobDatabase) -> anyhow::Result<()> { only_on_channel, free_disk, doc_url, - codebuild, required_python_version, // Carve-out configs allowed to be different. @@ -183,7 +180,6 @@ fn validate_job_database(db: &JobDatabase) -> anyhow::Result<()> { && *only_on_channel == auto_job.only_on_channel && *free_disk == auto_job.free_disk && *doc_url == auto_job.doc_url - && *codebuild == auto_job.codebuild && *required_python_version == auto_job.required_python_version { Ok(()) @@ -249,14 +245,12 @@ struct GithubActionsJob { #[serde(skip_serializing_if = "Option::is_none")] doc_url: Option, #[serde(skip_serializing_if = "Option::is_none")] - codebuild: Option, - #[serde(skip_serializing_if = "Option::is_none")] required_python_version: Option, } /// Replace GitHub context variables with environment variables in job configs. -/// Used for codebuild jobs like -/// `codebuild-ubuntu-22-8c-$github.run_id-$github.run_attempt` +/// +/// This is used for self-hosted runner jobs to loosely tie an instance to a particular GHA job. fn substitute_github_vars(jobs: Vec) -> anyhow::Result> { let run_id = load_env_var("GITHUB_RUN_ID")?; let run_attempt = load_env_var("GITHUB_RUN_ATTEMPT")?; @@ -382,7 +376,6 @@ fn calculate_jobs( continue_on_error: job.continue_on_error, free_disk: job.free_disk, doc_url: job.doc_url, - codebuild: job.codebuild, required_python_version: job.required_python_version, } }) diff --git a/src/ci/citool/src/jobs/tests.rs b/src/ci/citool/src/jobs/tests.rs index 65990d35d61b1..0179157d85c58 100644 --- a/src/ci/citool/src/jobs/tests.rs +++ b/src/ci/citool/src/jobs/tests.rs @@ -81,73 +81,6 @@ fn check_pattern(db: &JobDatabase, pattern: &str, expected: &[&str]) { assert_eq!(jobs, expected); } -/// Validate that CodeBuild jobs use Docker images from ghcr.io registry. -/// This is needed because otherwise from CodeBuild we get rate limited by Docker Hub. -fn validate_codebuild_image(job: &Job) -> anyhow::Result<()> { - let is_job_on_codebuild = job.codebuild.unwrap_or(false); - if !is_job_on_codebuild { - // Jobs in GitHub Actions don't get rate limited by Docker Hub. - return Ok(()); - } - - let image_name = job.image(); - // we hardcode host-x86_64 here, because in codebuild we only run jobs for this architecture. - let dockerfile_path = - Path::new(DOCKER_DIRECTORY).join("host-x86_64").join(&image_name).join("Dockerfile"); - - if !dockerfile_path.exists() { - return Err(anyhow::anyhow!( - "Dockerfile not found for CodeBuild job '{}' at path: {}", - job.name, - dockerfile_path.display() - )); - } - - let dockerfile_content = utils::read_to_string(&dockerfile_path)?; - - // Check if all FROM statement uses ghcr.io registry - let has_ghcr_from = dockerfile_content - .lines() - .filter(|line| line.trim_start().to_lowercase().starts_with("from ")) - .all(|line| line.contains("ghcr.io")); - - if !has_ghcr_from { - return Err(anyhow::anyhow!( - "CodeBuild job '{}' must use ghcr.io registry in its Dockerfile FROM statement. \ - Dockerfile path: {dockerfile_path:?}", - job.name, - )); - } - - Ok(()) -} - -#[test] -fn validate_jobs() { - let db = { - let default_jobs_file = Path::new(JOBS_YML_PATH); - let db_str = utils::read_to_string(default_jobs_file).unwrap(); - load_job_db(&db_str).expect("Failed to load job database") - }; - - let all_jobs = db - .pr_jobs - .iter() - .chain(db.try_jobs.iter()) - .chain(db.auto_jobs.iter()) - .chain(db.optional_jobs.iter()) - .collect::>(); - - let errors: Vec = - all_jobs.into_iter().filter_map(|job| validate_codebuild_image(job).err()).collect(); - - if !errors.is_empty() { - let error_messages = - errors.into_iter().map(|e| format!("- {e}")).collect::>().join("\n"); - panic!("Job validation failed:\n{error_messages}"); - } -} - #[test] fn pr_job_implies_auto_job() { let db = load_job_db( diff --git a/src/ci/scripts/free-disk-space-linux.sh b/src/ci/scripts/free-disk-space-linux.sh index 1498bc0a24f2c..36c9505327157 100755 --- a/src/ci/scripts/free-disk-space-linux.sh +++ b/src/ci/scripts/free-disk-space-linux.sh @@ -21,7 +21,7 @@ isX86() { } # Check if we're on a GitHub hosted runner. -# In aws codebuild, the variable RUNNER_ENVIRONMENT is "self-hosted". +# In self hosted runners, the variable RUNNER_ENVIRONMENT is "self-hosted". isGitHubRunner() { # `:-` means "use the value of RUNNER_ENVIRONMENT if it exists, otherwise use an empty string". if [[ "${RUNNER_ENVIRONMENT:-}" == "github-hosted" ]]; then diff --git a/src/tools/rust-analyzer/.github/workflows/autopublish.yaml b/src/tools/rust-analyzer/.github/workflows/autopublish.yaml index ec5671b10bf37..56cbde5ef5cb9 100644 --- a/src/tools/rust-analyzer/.github/workflows/autopublish.yaml +++ b/src/tools/rust-analyzer/.github/workflows/autopublish.yaml @@ -23,6 +23,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 + persist-credentials: false # https://github.com/jlumbroso/free-disk-space/blob/main/action.yml - name: Free up some disk space diff --git a/src/tools/rust-analyzer/.github/workflows/ci.yaml b/src/tools/rust-analyzer/.github/workflows/ci.yaml index eb8863ce783bd..02440e0ea109d 100644 --- a/src/tools/rust-analyzer/.github/workflows/ci.yaml +++ b/src/tools/rust-analyzer/.github/workflows/ci.yaml @@ -31,6 +31,8 @@ jobs: typescript: ${{ steps.filter.outputs.typescript }} steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: filter with: @@ -52,6 +54,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false - name: Install rustup-toolchain-install-master run: cargo install --locked rustup-toolchain-install-master@1.11.0 @@ -95,6 +98,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false - name: Install Rust toolchain run: | @@ -145,6 +149,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | @@ -173,6 +179,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | @@ -189,6 +197,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false # Note that clippy output is currently dependent on whether rust-src is installed, # https://github.com/rust-lang/rust-clippy/issues/14625 @@ -211,6 +221,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | @@ -241,19 +253,27 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | rustup update --no-self-update stable - rustup target add ${{ matrix.target }} + rustup target add ${TARGET} + env: + TARGET: ${{ matrix.target }} # - name: Cache Dependencies # uses: Swatinem/rust-cache@9d47c6ad4b02e050fd481d890b2ea34778fd09d6 - - run: cargo check --target=${{ matrix.target }} --all-targets -p ide + - run: cargo check --target=${TARGET} --all-targets -p ide if: ${{ matrix.ide-only }} - - run: cargo check --target=${{ matrix.target }} --all-targets + env: + TARGET: ${{ matrix.target }} + - run: cargo check --target=${TARGET} --all-targets if: ${{ !matrix.ide-only }} + env: + TARGET: ${{ matrix.target }} typescript: needs: changes @@ -269,6 +289,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Nodejs uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 @@ -330,6 +352,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false - name: check for typos run: typos @@ -360,9 +383,11 @@ jobs: - name: Conclusion run: | # Print the dependent jobs to see them in the CI log - jq -C <<< '${{ toJson(needs) }}' + jq -C <<< "${JSON_NEEDS}" # Check if all jobs that we depend on (in the needs array) were successful (or have been skipped). - jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< '${{ toJson(needs) }}' + jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< "${JSON_NEEDS}" + env: + JSON_NEEDS: ${{ toJson(needs) }} cancel-if-matrix-failed: needs: rust @@ -371,13 +396,16 @@ jobs: steps: - name: Cancel parallel jobs run: | - if jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< '${{ toJson(needs) }}'; then + if jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< "${JSON_NEEDS}"; then exit 0 fi # https://docs.github.com/en/rest/actions/workflow-runs?apiVersion=2022-11-28#cancel-a-workflow-run curl -L \ -X POST \ -H "Accept: application/vnd.github.v3+json" \ - -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \ + -H "Authorization: Bearer ${GITHUB_TOKEN}" \ -H "X-GitHub-Api-Version: 2022-11-28" \ - https://api.github.com/repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/cancel + "https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/cancel" + env: + JSON_NEEDS: ${{ toJson(needs) }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/src/tools/rust-analyzer/.github/workflows/coverage.yaml b/src/tools/rust-analyzer/.github/workflows/coverage.yaml index 19a132a496778..875335bccac51 100644 --- a/src/tools/rust-analyzer/.github/workflows/coverage.yaml +++ b/src/tools/rust-analyzer/.github/workflows/coverage.yaml @@ -16,6 +16,8 @@ jobs: RUSTC_BOOTSTRAP: 1 steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | diff --git a/src/tools/rust-analyzer/.github/workflows/fuzz.yml b/src/tools/rust-analyzer/.github/workflows/fuzz.yml index 8742cdf6103a3..15ac3007d7bab 100644 --- a/src/tools/rust-analyzer/.github/workflows/fuzz.yml +++ b/src/tools/rust-analyzer/.github/workflows/fuzz.yml @@ -31,6 +31,7 @@ jobs: with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 1 + persist-credentials: false - name: Install Rust toolchain run: | diff --git a/src/tools/rust-analyzer/.github/workflows/metrics.yaml b/src/tools/rust-analyzer/.github/workflows/metrics.yaml index 413e97dadad6d..d75455c628e74 100644 --- a/src/tools/rust-analyzer/.github/workflows/metrics.yaml +++ b/src/tools/rust-analyzer/.github/workflows/metrics.yaml @@ -24,6 +24,8 @@ jobs: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Cache cargo uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 @@ -67,6 +69,8 @@ jobs: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Restore target cache uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 @@ -75,7 +79,9 @@ jobs: key: ${{ runner.os }}-target-${{ github.sha }} - name: Collect metrics - run: cargo xtask metrics "${{ matrix.names }}" + run: cargo xtask metrics "${NAMES}" + env: + NAMES: ${{ matrix.names }} - name: Upload metrics uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -90,6 +96,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Download metrics uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 @@ -100,7 +108,7 @@ jobs: - name: Combine json run: | mkdir ~/.ssh - echo "${{ secrets.METRICS_DEPLOY_KEY }}" > ~/.ssh/id_ed25519 + echo "${METRICS_DEPLOY_KEY}" > ~/.ssh/id_ed25519 chmod 600 ~/.ssh/id_ed25519 chmod 700 ~/.ssh @@ -110,3 +118,5 @@ jobs: git add . git -c user.name=Bot -c user.email=dummy@example.com commit --message 📈 git push origin master + env: + METRICS_DEPLOY_KEY: ${{ secrets.METRICS_DEPLOY_KEY }} diff --git a/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml b/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml index 4b459d6a96704..2c11073bfa95f 100644 --- a/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml +++ b/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml @@ -21,6 +21,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 + persist-credentials: false - name: Install Rust toolchain run: rustup update --no-self-update stable diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index 29a4020baf743..88afab204d6ec 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -10,6 +10,8 @@ on: - release - trigger-nightly +permissions: {} + env: CARGO_INCREMENTAL: 0 CARGO_NET_RETRY: 10 @@ -72,8 +74,13 @@ jobs: runs-on: ${{ matrix.os }} container: ${{ matrix.container }} + defaults: + run: + shell: bash + env: RA_TARGET: ${{ matrix.target }} + CODE_TARGET: ${{ matrix.code-target }} ALLOCATOR_FLAG: ${{ matrix.allocator != 'system' && format('--{0}', matrix.allocator) || '' }} steps: @@ -81,6 +88,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - name: Install target dependencies if: ${{ matrix.target == 'arm-unknown-linux-gnueabihf' }} @@ -106,23 +114,27 @@ jobs: run: | rustup update --no-self-update stable # llvm-tools contain the llvm-profdata tool which is needed for PGO - rustup component add rust-src ${{ matrix.pgo && 'llvm-tools' || '' }} - rustup target add ${{ matrix.target }} + rustup component add rust-src ${MAYBE_LLVM_TOOLS} + rustup target add ${RA_TARGET} + env: + MAYBE_LLVM_TOOLS: ${{ matrix.pgo && 'llvm-tools' || '' }} - name: Dist - run: cargo xtask dist --client-patch-version ${{ github.run_number }} ${{ env.ALLOCATOR_FLAG }} ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} + run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} ${ALLOCATOR_FLAG} ${MAYBE_PGO} + env: + MAYBE_PGO: ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} - run: npm ci working-directory: editors/code - name: Package Extension (release) if: github.ref == 'refs/heads/release' && matrix.code-target - run: npx vsce package -o "../../dist/rust-analyzer-${{ matrix.code-target }}.vsix" --target ${{ matrix.code-target }} + run: npx vsce package -o "../../dist/rust-analyzer-${CODE_TARGET}.vsix" --target ${CODE_TARGET} working-directory: editors/code - name: Package Extension (nightly) if: github.ref != 'refs/heads/release' && matrix.code-target - run: npx vsce package -o "../../dist/rust-analyzer-${{ matrix.code-target }}.vsix" --target ${{ matrix.code-target }} --pre-release + run: npx vsce package -o "../../dist/rust-analyzer-${CODE_TARGET}.vsix" --target ${CODE_TARGET} --pre-release working-directory: editors/code - if: matrix.target == 'x86_64-unknown-linux-gnu' @@ -138,13 +150,13 @@ jobs: - name: Run analysis-stats on rust-analyzer if: matrix.target == 'x86_64-unknown-linux-gnu' - run: target/${{ matrix.target }}/release/rust-analyzer analysis-stats . -q + run: target/${RA_TARGET}/release/rust-analyzer analysis-stats . -q - name: Run analysis-stats on rust std library if: matrix.target == 'x86_64-unknown-linux-gnu' env: RUSTC_BOOTSTRAP: 1 - run: target/${{ matrix.target }}/release/rust-analyzer analysis-stats --with-deps --no-sysroot --no-test $(rustc --print sysroot)/lib/rustlib/src/rust/library/std -q + run: target/${RA_TARGET}/release/rust-analyzer analysis-stats --with-deps --no-sysroot --no-test $(rustc --print sysroot)/lib/rustlib/src/rust/library/std -q - name: Upload artifacts uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -173,9 +185,10 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - name: Dist - run: cargo xtask dist --client-patch-version ${{ github.run_number }} --jemalloc + run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} --jemalloc - run: npm ci working-directory: editors/code @@ -201,16 +214,19 @@ jobs: publish: if: ${{ github.repository == 'rust-lang/rust-analyzer' || github.event_name == 'workflow_dispatch' }} runs-on: ubuntu-latest + permissions: + contents: write needs: ["dist", "dist-x86_64-unknown-linux-musl"] steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - name: Set release tag run: | - if [ "${{ github.ref }}" = "refs/heads/release" ]; then + if [ "${GITHUB_REF}" = "refs/heads/release" ]; then git fetch --tags today=$(date --iso -u) last_tag=$(git tag -l "${today}*" | sort -V | tail -n1) @@ -248,12 +264,18 @@ jobs: name: publish-extension (${{ matrix.cmd }}) runs-on: ubuntu-latest needs: publish + environment: publish-extension + permissions: + contents: read + id-token: write strategy: fail-fast: false matrix: include: - cmd: vsce + authentication: --oidc - cmd: ovsx + authentication: --trusted-publishing steps: - name: Install Nodejs uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 @@ -264,6 +286,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: @@ -277,7 +300,9 @@ jobs: - name: Publish Extension if: github.repository == 'rust-lang/rust-analyzer' env: - PUBLISH_PAT: ${{ (matrix.cmd == 'vsce' && secrets.MARKETPLACE_TOKEN) || (matrix.cmd == 'ovsx' && secrets.OPENVSX_TOKEN) }} + COMMAND: ${{ matrix.cmd }} + MAYBE_PRE_RELEASE: ${{ github.ref != 'refs/heads/release' && '--pre-release' || '' }} + AUTHENTICATION: ${{ matrix.authentication }} working-directory: ./editors/code - run: npx ${{ matrix.cmd }} publish --skip-duplicate --pat "$PUBLISH_PAT" --packagePath ../../dist/rust-analyzer-*.vsix ${{ github.ref != 'refs/heads/release' && '--pre-release' || '' }} + run: npx ${COMMAND} publish --skip-duplicate ${AUTHENTICATION} --packagePath ../../dist/rust-analyzer-*.vsix ${MAYBE_PRE_RELEASE} timeout-minutes: 2 diff --git a/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml b/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml index 29f03ffcc92fb..2458f64caed70 100644 --- a/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml +++ b/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml @@ -22,6 +22,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: rustup update --no-self-update stable diff --git a/src/tools/rust-analyzer/.github/workflows/update-generated.yml b/src/tools/rust-analyzer/.github/workflows/update-generated.yml index 611d7d40bc6a2..963645b02d7be 100644 --- a/src/tools/rust-analyzer/.github/workflows/update-generated.yml +++ b/src/tools/rust-analyzer/.github/workflows/update-generated.yml @@ -19,6 +19,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install nightly run: rustup default nightly diff --git a/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs b/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs index 84559b46cc5b7..b54fb90b8ec84 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs @@ -1411,6 +1411,7 @@ fn next_doc_expr(it: &mut Peekable) -> Option { return None; } } + Some(NodeOrToken::Node(_)) if name == "notable_trait" => DocAtom::Flag(name), Some(NodeOrToken::Node(subtree)) => { if name != "alias" { return None; diff --git a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs index 01363f5f2105a..97f7532b017d2 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs @@ -2,7 +2,7 @@ //! //! This attribute to tell the compiler about semi built-in std library //! features, such as Fn family of traits. -use base_db::SourceDatabase; +use base_db::{SourceDatabase, TargetKind}; use hir_expand::name::Name; use intern::{Symbol, sym}; use rustc_hash::FxHashMap; @@ -108,6 +108,8 @@ pub fn crate_lang_items(db: &dyn SourceDatabase, krate: Crate) -> Option Box<[Cra // Some crates declares themselves as extern crate like `extern crate self as core`. // Ignore these to prevent cycles. krate != start_crate + // Exclude proc macro dependencies, they have their own sysroot that could conflict. + && krate.data(db).target_kind != TargetKind::Lib { is_proc_macro: true } }) .collect() } @@ -393,6 +397,16 @@ impl LangItems { self.solver_adt[lang_item as usize] = Some(def); self.reverse_solver_adt.insert(def, lang_item); } + + /// FIXME: Remove this when we have MSRV >= 1.102.0. + /// See comments on [`LangItems::Rust1_102PartialEqHack`]. + fn rust_1_102_partial_eq_hack(&mut self) { + if self.Rust1_102PartialEqHack.is_none() { + return; + } + self.Eq = self.PartialEq; + self.PartialEq = self.Rust1_102PartialEqHack; + } } #[salsa::tracked(returns(as_deref))] @@ -851,6 +865,10 @@ language_item_table! { $ LangItems => AsyncGenReady, sym::AsyncGenReady, FunctionId; PartialEq, sym::eq, TraitId; + // FIXME: `PartialEq`'s lang item attribute has been changed into `partial_eq` and `eq` has + // been assigned to `Eq` in 1.102.0. Remove this and move `Eq` here once we bump our + // MSRV >= 1.102.0. + Rust1_102PartialEqHack, sym::partial_eq, TraitId; PartialOrd, sym::partial_ord, TraitId; CVoid, sym::c_void, EnumId; @@ -1046,10 +1064,66 @@ language_item_table! { $ LangItems => PartialOrd_ge, FunctionId; PartialOrd_gt, FunctionId; Drop_drop, FunctionId; - Drop_pin_drop, FunctionId; + Drop_pin_drop, FunctionId; Debug_fmt, FunctionId; Deref_deref, FunctionId; DerefMut_deref_mut, FunctionId; Index_index, FunctionId; IndexMut_index_mut, FunctionId; } + +#[cfg(test)] +mod tests { + use base_db::all_crates; + use rustc_hash::FxHashMap; + use test_fixture::WithFixture; + + use crate::{test_db::TestDB, unstable_features::UnstableFeatures}; + + /// Ensures each crate can only have up to one transitive dependency with `#![feature(lang_items)]`. + /// + /// In reality there can be multiple (std, alloc, core) but this is a representative of bugs we had. + fn ensure_single_lang_items_owner(#[rust_analyzer::rust_fixture] ra_fixture: &str) { + let mut lang_items_owner_count = FxHashMap::default(); + + let db = TestDB::with_files(ra_fixture); + // `all_crates()` is in topological order, so we can just loop over it. + for &krate in all_crates(&db).iter() { + let mut lang_items_count = u32::from(UnstableFeatures::query(&db, krate).lang_items); + lang_items_count += super::crate_extern_prelude(&db, krate) + .iter() + .map(|dep| lang_items_owner_count[dep]) + .sum::(); + lang_items_owner_count.insert(krate, lang_items_count); + } + + let invalid_crates = lang_items_owner_count + .iter() + .filter(|(_, count)| **count > 1) + .map(|(krate, _)| match &krate.extra_data(&db).display_name { + Some(name) => name.crate_name().to_string(), + None => format!("{krate:?}"), + }) + .collect::>(); + if !invalid_crates.is_empty() { + panic!("crates [{}] have more than one lang items owner", invalid_crates.join(", ")); + } + } + + #[test] + fn proc_macros_not_included() { + ensure_single_lang_items_owner( + r#" +//- /core1.rs crate:core1 +#![feature(lang_items)] + +//- /proc_macro.rs crate:proc-macro:proc_macro deps:core1 + +//- /core2.rs crate:core2 +#![feature(lang_items)] + +//- /main.rs crate:main deps:core2,proc_macro + "#, + ); + } +} diff --git a/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs b/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs index 7db1e8c947665..52b9a79684268 100644 --- a/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs +++ b/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs @@ -44,7 +44,7 @@ use crate::{ Adjustment, InferBodyId, InferenceDiagnostic, InferenceResult, db::{AnonConstId, HirDatabase}, display::{DisplayTarget, HirDisplay}, - next_solver::Ty, + next_solver::{TermRefId, Ty}, setup_tracing, test_db::TestDB, }; @@ -196,6 +196,7 @@ fn check_impl( let mut had_annotations = false; let mut mismatches = FxHashMap::default(); let mut types = FxHashMap::default(); + let mut consts = FxHashMap::default(); let mut adjustments = FxHashMap::default(); for (file_id, annotations) in db.extract_annotations() { for (range, expected) in annotations { @@ -204,6 +205,8 @@ fn check_impl( types.insert(file_range, expected); } else if let Some(ty) = expected.strip_prefix("type: ") { types.insert(file_range, ty.to_owned()); + } else if let Some(const_) = expected.strip_prefix("const: ") { + consts.insert(file_range, const_.to_owned()); } else if expected.starts_with("expected") { mismatches.insert(file_range, expected); } else if let Some(adjs) = expected.strip_prefix("adjustments:") { @@ -300,21 +303,27 @@ fn check_impl( } } - for (type_ref, ty) in inference_result.placeholder_types() { - let node = match type_node(source_map, type_ref, &db) { - Some(value) => value, - None => continue, + for (term_ref, term) in inference_result.term_of_term_placeholders() { + let node = match term_ref.unpack() { + TermRefId::TypeRefId(type_ref) => type_node(source_map, type_ref, &db), + TermRefId::ConstRef(const_ref) => expr_node(source_map, const_ref.expr, &db), }; + let Some(node) = node else { continue }; let range = node.as_ref().original_file_range_rooted(&db); - if let Some(expected) = types.remove(&range) { + if let Some(expected) = types.remove(&range).or_else(|| consts.remove(&range)) { let actual = salsa::attach(&db, || { if display_source { - ty.display_source_code(&db, def.module(&db), true).unwrap() + term.display_source_code(&db, def.module(&db), true).unwrap() } else { - ty.display_test(&db, display_target).to_string() + term.display_test(&db, display_target).to_string() } }); assert_eq!(actual, expected, "type annotation differs at {:#?}", range.range); + assert_eq!( + actual, expected, + "placeholder annotation differs at {:#?}", + range.range + ); } } } @@ -335,6 +344,12 @@ fn check_impl( format_to!(buf, "{:?}: type {}\n", t.0.range, t.1); } } + if !consts.is_empty() { + format_to!(buf, "Unchecked const annotations:\n"); + for c in consts { + format_to!(buf, "{:?}: const {}\n", c.0.range, c.1); + } + } if !adjustments.is_empty() { format_to!(buf, "Unchecked adjustments annotations:\n"); for t in adjustments { diff --git a/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs b/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs index db21c4cf949aa..bee40d74f5298 100644 --- a/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs +++ b/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs @@ -1,4 +1,4 @@ -use super::check_types_source_code; +use super::{check, check_types_source_code}; #[test] fn qualify_path_to_submodule() { @@ -261,19 +261,21 @@ fn test() { } #[test] -fn type_placeholder_type() { - check_types_source_code( +fn term_placeholders() { + check( r#" -struct S(T); +struct S([T; N]); fn test() { - let f: S<_> = S(3); - //^ i32 + let f: S<_, _> = S([1, 2]); + //^ type: i32 + //^ const: 2 let f: [_; _] = [4_u32, 5, 6]; - //^ u32 + //^ type: u32 + //^ const: 3 let f: (_, _, _) = (1_u32, 1_i32, false); - //^ u32 - //^ i32 - //^ bool + //^ type: u32 + //^ type: i32 + //^ type: bool } "#, ); diff --git a/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs b/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs index 5332bebae4d0d..f027dd9b223de 100644 --- a/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs +++ b/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs @@ -1422,7 +1422,7 @@ fn foo() -> (impl FnOnce(&str, T), impl Trait) { } "#, expect![[r#" - 134..165 '{ ...(C)) }': (impl FnOnce(&'? str, T), impl Trait) + 134..165 '{ ...(C)) }': (impl FnOnce(&'? str, T), Bar) 140..163 '(|inpu...ar(C))': (impl FnOnce(&'? str, T), Bar) 141..154 '|input, t| {}': impl FnOnce(&'? str, T) 142..147 'input': &'? str diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs index d044fbb22ae53..31c8f28fb694c 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs @@ -102,7 +102,7 @@ use crate::{ method_resolution::CandidateId, next_solver::{ AliasTy, Const, ConstKind, DbInterner, GenericArgs, Region, StoredFnSig, StoredGenericArg, - StoredGenericArgs, StoredTy, StoredTys, Term, Ty, TyKind, Tys, + StoredGenericArgs, StoredTerm, StoredTy, StoredTys, Term, TermRefIdPacked, Ty, TyKind, Tys, abi::Safety, default_types, infer::{InferCtxt, ObligationInspector, traits::ObligationCause}, @@ -778,7 +778,7 @@ pub struct InferenceResult<'db> { /// unresolved or missing subpatterns or subpatterns of mismatched types. pub type_of_pat: ArenaMap, pub type_of_binding: ArenaMap, - pub type_of_type_placeholder: ThinFxHashMap, + pub term_of_term_placeholders: ThinFxHashMap, pub type_of_opaque: ThinFxHashMap, StoredTy>, /// Whether there are any type-mismatching errors in the result. @@ -1134,7 +1134,7 @@ impl<'db> InferenceResult<'db> { type_of_expr: Default::default(), type_of_pat: Default::default(), type_of_binding: Default::default(), - type_of_type_placeholder: Default::default(), + term_of_term_placeholders: Default::default(), type_of_opaque: Default::default(), skipped_ref_pats: Default::default(), has_errors: Default::default(), @@ -1201,11 +1201,13 @@ impl<'db> InferenceResult<'db> { pub fn has_type_mismatches(&self) -> bool { !self.nodes_with_type_mismatches.is_empty() } - pub fn placeholder_types<'a>(&self) -> impl Iterator)> { - self.type_of_type_placeholder.iter().map(|(&type_ref, ty)| (type_ref, ty.as_ref())) + pub fn term_of_term_placeholders<'a>( + &self, + ) -> impl Iterator)> { + self.term_of_term_placeholders.iter().map(|(&term_ref, term)| (term_ref, term.as_ref())) } - pub fn type_of_type_placeholder<'a>(&self, type_ref: TypeRefId) -> Option> { - self.type_of_type_placeholder.get(&type_ref).map(|ty| ty.as_ref()) + pub fn term_of_term_placeholder<'a>(&self, term_ref: TermRefIdPacked) -> Option> { + self.term_of_term_placeholders.get(&term_ref).map(|term| term.as_ref()) } pub fn type_of_expr_or_pat<'a>(&self, id: ExprOrPatId) -> Option> { match id { @@ -1484,7 +1486,7 @@ impl<'db> InferenceContext<'db> { type_of_expr, type_of_pat, type_of_binding, - type_of_type_placeholder, + term_of_term_placeholders: placeholders, type_of_opaque, has_errors: _, diagnostics: _, @@ -1514,7 +1516,7 @@ impl<'db> InferenceContext<'db> { merge_arena_maps(type_of_expr, &other.type_of_expr); merge_arena_maps(type_of_pat, &other.type_of_pat); merge_arena_maps(type_of_binding, &other.type_of_binding); - merge_thin_hash_maps(type_of_type_placeholder, &other.type_of_type_placeholder); + merge_thin_hash_maps(placeholders, &other.term_of_term_placeholders); merge_thin_hash_maps(type_of_opaque, &other.type_of_opaque); merge_hash_maps(expr_adjustments, &other.expr_adjustments); merge_thin_hash_maps(pat_adjustments, &other.pat_adjustments); @@ -1662,7 +1664,7 @@ impl<'db> InferenceContext<'db> { type_of_expr, type_of_pat, type_of_binding, - type_of_type_placeholder, + term_of_term_placeholders, type_of_opaque, skipped_ref_pats, closures_data, @@ -1696,10 +1698,10 @@ impl<'db> InferenceContext<'db> { resolver.resolve_completely(ty); } type_of_binding.shrink_to_fit(); - for ty in type_of_type_placeholder.values_mut() { - resolver.resolve_completely(ty); + for term in term_of_term_placeholders.values_mut() { + resolver.resolve_completely(term); } - type_of_type_placeholder.shrink_to_fit(); + term_of_term_placeholders.shrink_to_fit(); type_of_opaque.shrink_to_fit(); if !nodes_with_type_mismatches.is_empty() { @@ -1955,7 +1957,7 @@ impl<'db> InferenceContext<'db> { fn with_ty_lowering(&mut self, f: impl FnOnce(&mut TyLoweringContext<'db, '_>) -> R) -> R { let mut infer_vars = InferenceTyLoweringVarsCtx { table: &mut self.table, - type_of_type_placeholder: &mut self.result.type_of_type_placeholder, + term_of_term_placeholders: &mut self.result.term_of_term_placeholders, }; let mut ctx = TyLoweringContext::new( self.db, @@ -2262,7 +2264,7 @@ impl<'db> InferenceContext<'db> { let interner = self.interner(); let mut vars_ctx = InferenceTyLoweringVarsCtx { table: &mut self.table, - type_of_type_placeholder: &mut self.result.type_of_type_placeholder, + term_of_term_placeholders: &mut self.result.term_of_term_placeholders, }; let mut ctx = TyLoweringContext::new( self.db, diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs index f3bea3a653c8c..965ff8954106d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs @@ -6,9 +6,10 @@ use std::cell::{OnceCell, RefCell}; use std::ops::{Deref, DerefMut}; use either::Either; +use hir_def::expr_store::ExpressionStore; use hir_def::expr_store::path::Path; +use hir_def::type_ref::ConstRef; use hir_def::{ExpressionStoreOwnerId, GenericDefId}; -use hir_def::{expr_store::ExpressionStore, type_ref::TypeRefId}; use hir_def::{ hir::{ExprId, ExprOrPatIdPacked}, resolver::Resolver, @@ -16,6 +17,7 @@ use hir_def::{ use la_arena::RawIdx; use thin_vec::ThinVec; +use crate::next_solver::{StoredTerm, Term}; use crate::{ InferenceDiagnostic, Span, ThinFxHashMap, TyLoweringDiagnostic, db::{AnonConstId, HirDatabase}, @@ -26,7 +28,7 @@ use crate::{ TyLoweringInferVarsCtx, path::{PathDiagnosticCallback, PathLoweringContext}, }, - next_solver::{Const, Region, StoredTy, Ty}, + next_solver::{Const, Region, TermRefIdPacked, Ty}, }; // Unfortunately, this struct needs to use interior mutability (but we encapsulate it) @@ -63,7 +65,7 @@ pub(crate) struct PathDiagnosticCallbackData<'a> { pub(super) struct InferenceTyLoweringVarsCtx<'a, 'db> { pub(super) table: &'a mut InferenceTable<'db>, - pub(super) type_of_type_placeholder: &'a mut ThinFxHashMap, + pub(super) term_of_term_placeholders: &'a mut ThinFxHashMap, } impl<'db> TyLoweringInferVarsCtx<'db> for InferenceTyLoweringVarsCtx<'_, 'db> { @@ -71,13 +73,24 @@ impl<'db> TyLoweringInferVarsCtx<'db> for InferenceTyLoweringVarsCtx<'_, 'db> { let ty = self.table.infer_ctxt.next_ty_var(span); if let Span::TypeRefId(type_ref) = span { - self.type_of_type_placeholder.insert(type_ref, ty.store()); + self.term_of_term_placeholders.insert(type_ref.into(), Term::from(ty).store()); } ty } fn next_const_var(&mut self, span: Span) -> Const<'db> { - self.table.infer_ctxt.next_const_var(span) + let const_ = self.table.infer_ctxt.next_const_var(span); + + let term_ref = match span { + Span::ExprId(expr) => Some(ConstRef { expr }.into()), + Span::TypeRefId(type_ref) => Some(type_ref.into()), + _ => None, + }; + if let Some(key) = term_ref { + self.term_of_term_placeholders.insert(key, Term::from(const_).store()); + } + + const_ } fn next_region_var(&mut self, span: Span) -> Region<'db> { self.table.infer_ctxt.next_region_var(span) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs index ec0788b43b573..47c06891202bf 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs @@ -152,7 +152,7 @@ impl<'db> InferenceContext<'db> { // Don't use `self.make_ty()` here as we need `orig_ns`. let mut vars_ctx = InferenceTyLoweringVarsCtx { table: &mut self.table, - type_of_type_placeholder: &mut self.result.type_of_type_placeholder, + term_of_term_placeholders: &mut self.result.term_of_term_placeholders, }; let mut ctx = TyLoweringContext::new( self.db, diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs b/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs index 23cf4fbe38599..cf056fdebc03e 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs @@ -1288,23 +1288,16 @@ pub(crate) fn substs_from_args_and_bindings<'db>( params.next(); force_infer_lt = Some((arg_idx as u32, param_id)); } - (HirGenericArg::Type(type_ref), GenericParamDataRef::ConstParamData(_)) => { - if let Some(konst) = type_looks_like_const(store, *type_ref) { - let GenericParamId::ConstParamId(param_id) = param_id else { - panic!("unmatching param kinds"); - }; - let const_ty = const_param_ty(db, param_id); - substs - .push(ctx.provided_type_like_const(*type_ref, const_ty, konst).into()); - args.next(); - params.next(); - } else { - // See the `_ => { ... }` branch. - if !had_count_error { - ctx.report_arg_mismatch(param_id, arg_idx as u32, has_self_arg); - } - while args.next().is_some() {} - } + (HirGenericArg::Type(type_ref), GenericParamDataRef::ConstParamData(_)) + if let Some(konst) = type_looks_like_const(store, *type_ref) => + { + let GenericParamId::ConstParamId(param_id) = param_id else { + panic!("unmatching param kinds"); + }; + let const_ty = const_param_ty(db, param_id); + substs.push(ctx.provided_type_like_const(*type_ref, const_ty, konst).into()); + args.next(); + params.next(); } _ => { // We expected one kind of parameter, but the user provided diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs index c45387b6894bc..dc609b0cff26d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs @@ -4,10 +4,12 @@ use hir_def::{ AdtId, AttrDefId, BuiltinDeriveImplId, CallableDefId, ConstId, DefWithBodyId, EnumId, EnumVariantId, ExpressionStoreOwnerId, FunctionId, GenericDefId, ImplId, StaticId, StructId, TraitId, TypeAliasId, UnionId, VariantId, + hir::ExprId, signatures::{ ConstSignature, EnumSignature, FunctionSignature, StaticSignature, StructSignature, TraitSignature, TypeAliasSignature, UnionSignature, }, + type_ref::{ConstRef, TypeRefId}, }; use rustc_type_ir::inherent; use salsa::SalsaValue; @@ -541,6 +543,58 @@ impl<'db> From for SolverDefId<'db> { } } +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum TermRefId { + TypeRefId(TypeRefId), + ConstRef(ConstRef), +} +impl_from!(TypeRefId, ConstRef for TermRefId); + +#[derive(Copy, Clone, Hash, PartialEq, Eq)] +pub struct TermRefIdPacked(u32); + +const _: () = assert!(std::mem::size_of::() == std::mem::size_of::()); + +impl TermRefIdPacked { + const CONST_REF_BIT: u32 = 1 << (u32::BITS - 1); + const INDEX_MASK: u32 = !Self::CONST_REF_BIT; + + pub fn unpack(self) -> TermRefId { + let is_const_ref = self.0 & Self::CONST_REF_BIT != 0; + match is_const_ref { + true => { + let expr = ExprId::from_raw((self.0 & Self::INDEX_MASK).into()); + TermRefId::ConstRef(ConstRef { expr }) + } + false => TermRefId::TypeRefId(TypeRefId::from_raw(self.0.into())), + } + } +} + +impl std::fmt::Debug for TermRefIdPacked { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.unpack().fmt(f) + } +} + +impl From for TermRefIdPacked { + fn from(value: TypeRefId) -> Self { + let value = value.into_raw().into_u32(); + // virtually impossible to have IDs that high + debug_assert_eq!(value & Self::CONST_REF_BIT, 0); + Self(value) + } +} + +impl From for TermRefIdPacked { + fn from(value: ConstRef) -> Self { + let value = value.expr.into_raw().into_u32(); + // virtually impossible to have IDs that high + debug_assert_eq!(value & Self::CONST_REF_BIT, 0); + Self(value | Self::CONST_REF_BIT) + } +} + #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct GeneralConstIdWrapper<'db>(pub GeneralConstId<'db>); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs index 81d36c2bb037c..db93276f7e32f 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs @@ -280,6 +280,57 @@ impl<'db> From> for GenericArg<'db> { } } +#[derive(PartialEq, Eq, Hash)] +pub struct StoredTerm { + ptr: GenericArgImpl<'static>, +} + +impl Clone for StoredTerm { + #[inline] + fn clone(&self) -> Self { + match self.ptr.term_kind() { + TermKind::Ty(it) => std::mem::forget(it.interned.to_owned()), + TermKind::Const(it) => std::mem::forget(it.interned.to_owned()), + } + Self { ptr: self.ptr } + } +} + +impl Drop for StoredTerm { + #[inline] + fn drop(&mut self) { + unsafe { + match self.ptr.term_kind() { + TermKind::Ty(it) => it.interned.decrement_refcount(), + TermKind::Const(it) => it.interned.decrement_refcount(), + } + } + } +} + +impl StoredTerm { + #[inline] + fn new(value: Term<'_>) -> Self { + let result = Self { ptr: GenericArgImpl { ptr: value.ptr.ptr, _marker: PhantomData } }; + // Increase refcount. + std::mem::forget(result.clone()); + result + } + + #[inline] + pub fn as_ref<'db>(&self) -> Term<'db> { + Term { ptr: self.ptr } + } +} + +impl std::fmt::Debug for StoredTerm { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.as_ref().fmt(f) + } +} + +impl_foldable_for_stored_type!(StoredTerm); + #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Term<'db> { ptr: GenericArgImpl<'db>, @@ -295,6 +346,11 @@ impl<'db> std::fmt::Debug for Term<'db> { } impl<'db> Term<'db> { + #[inline] + pub fn store(self) -> StoredTerm { + StoredTerm::new(self) + } + #[inline] pub fn kind(self) -> TermKind<'db> { self.ptr.term_kind() diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs index fb652d035eaca..6709da7afb212 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs @@ -97,7 +97,7 @@ impl<'db> SolverDelegate for SolverContext<'db> { >, > { // FIXME(next-solver): - None + Some(Vec::new()) } fn make_deduplicated_region_constraints( diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs b/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs index 621eed47be4ec..38e6eb54ba826 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs @@ -116,7 +116,7 @@ static AARCH64_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ &[], ), // FEAT_FP8 - ("fp8", Unstable(sym::aarch64_unstable_target_feature), &["faminmax", "lut", "bf16"]), + ("fp8", Unstable(sym::aarch64_unstable_target_feature), &["neon"]), // FEAT_FP8DOT2 ("fp8dot2", Unstable(sym::aarch64_unstable_target_feature), &["fp8dot4"]), // FEAT_FP8DOT4 diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index b4223a72ad723..68d625b588042 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -1530,7 +1530,7 @@ impl Function { // because it has not `CallableDefId`. // FIXME: This does not account for replacing `Self`. Do we really need that? let Some(trait_method) = method.trait_method(db, impl_) else { - return Type::unknown(); + return Type::unknown(db); }; Function::from(trait_method).ty(db) } @@ -1551,7 +1551,7 @@ impl Function { // because it has not `CallableDefId`. // FIXME: This does not account for replacing `Self`. Do we really need that? let Some(trait_method) = method.trait_method(db, impl_) else { - return Type::unknown(); + return Type::unknown(db); }; Function::from(trait_method).fn_ptr_type(db) } @@ -4506,7 +4506,7 @@ impl<'db> Type<'db> { fn from_value_def(db: &'db dyn HirDatabase, def: impl Into) -> Self { let def = def.into(); let Some(ty) = db.value_ty(def) else { - return Type::unknown(); + return Type::unknown(db); }; let def = match def { ValueTyDefId::ConstId(it) => GenericDefId::ConstId(it), @@ -4524,8 +4524,8 @@ impl<'db> Type<'db> { } /// Replace any generic parameters with error types. - pub fn instantiate_with_errors(&self) -> Self { - let interner = DbInterner::conjure(); + pub fn instantiate_with_errors(&self, db: &'db dyn HirDatabase) -> Self { + let interner = DbInterner::new_no_crate(db); let krate = self.krate(interner.db()); let args = match self.owner { TypeOwnerId::GenericDefId(def) => GenericArgs::error_for_item(interner, def.into()), @@ -4538,8 +4538,12 @@ impl<'db> Type<'db> { } // FIXME: Find some way with const params, maybe even lifetimes? - pub fn instantiate(&self, args: impl IntoIterator>>) -> Type<'db> { - let interner = DbInterner::conjure(); + pub fn instantiate( + &self, + db: &'db dyn HirDatabase, + args: impl IntoIterator>>, + ) -> Type<'db> { + let interner = DbInterner::new_no_crate(db); let (args, owner) = match self.owner { TypeOwnerId::GenericDefId(def) => generic_args_from_tys(interner, def.into(), args), TypeOwnerId::BuiltinDeriveImplId(def) => { @@ -4596,7 +4600,7 @@ impl<'db> Type<'db> { db: &'db dyn HirDatabase, rebase_into: &Type<'db>, ) -> Type<'db> { - self.try_rebase_into(db, rebase_into).unwrap_or_else(|| self.instantiate_with_errors()) + self.try_rebase_into(db, rebase_into).unwrap_or_else(|| self.instantiate_with_errors(db)) } pub fn try_rebase_into_owner( @@ -4617,15 +4621,13 @@ impl<'db> Type<'db> { db: &'db dyn HirDatabase, new_owner: GenericDef, ) -> Self { - self.try_rebase_into_owner(db, new_owner).unwrap_or_else(|| self.instantiate_with_errors()) + self.try_rebase_into_owner(db, new_owner) + .unwrap_or_else(|| self.instantiate_with_errors(db)) } - pub fn unknown() -> Self { - let interner = DbInterner::conjure(); - Type::no_params( - Self::builtin_type_crate(interner.db()), - Ty::new_error(interner, ErrorGuaranteed), - ) + pub fn unknown(db: &'db dyn HirDatabase) -> Self { + let interner = DbInterner::new_no_crate(db); + Type::no_params(Self::builtin_type_crate(db), Ty::new_error(interner, ErrorGuaranteed)) } pub fn new_slice(db: &'db dyn HirDatabase, ty: Self) -> Self { @@ -4657,9 +4659,9 @@ impl<'db> Type<'db> { Type { owner, ty } } - pub fn new_unit() -> Self { - let interner = DbInterner::conjure(); - Type::no_params(Self::builtin_type_crate(interner.db()), Ty::new_unit(interner)) + pub fn new_unit(db: &'db dyn HirDatabase) -> Self { + let interner = DbInterner::new_no_crate(db); + Type::no_params(Self::builtin_type_crate(db), Ty::new_unit(interner)) } pub fn is_unit(&self) -> bool { diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index ff9fa659a928e..888a4ca84dd66 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -25,7 +25,7 @@ use hir_def::{ lang_item::LangItems, nameres::MacroSubNs, resolver::{ResolveValueResult, Resolver, TypeNs, ValueNs, resolver_for_scope}, - type_ref::{Mutability, TypeRefId}, + type_ref::{ConstRef, Mutability, TypeRefId}, visibility::Visibility, }; use hir_expand::{ @@ -53,7 +53,7 @@ use itertools::Itertools; use rustc_hash::FxHashSet; use rustc_type_ir::{ AliasTyKind, - inherent::{IntoKind, Ty as _}, + inherent::{IntoKind, Term as _, Ty as _}, }; use smallvec::SmallVec; use stdx::never; @@ -481,17 +481,27 @@ impl<'db> SourceAnalyzer<'db> { impl<'db> TyLoweringInferVarsCtx<'db> for VarsCtx<'_, 'db> { fn next_ty_var(&mut self, span: hir_ide::Span) -> Ty<'db> { - if let hir_ide::Span::TypeRefId(type_ref) = span - && let Some(ty) = - self.infer.and_then(|infer| infer.type_of_type_placeholder(type_ref)) - { - ty - } else { - self.types.types.error - } + let term_ref = match span { + hir_ide::Span::TypeRefId(type_ref) => type_ref.into(), + _ => return self.types.types.error, + }; + + self.infer + .and_then(|infer| infer.term_of_term_placeholder(term_ref)) + .and_then(|term| term.as_type()) + .unwrap_or(self.types.types.error) } - fn next_const_var(&mut self, _span: hir_ide::Span) -> hir_ide::next_solver::Const<'db> { - self.types.consts.error + fn next_const_var(&mut self, span: hir_ide::Span) -> hir_ide::next_solver::Const<'db> { + let term_ref = match span { + hir_ide::Span::TypeRefId(type_ref) => type_ref.into(), + hir_ide::Span::ExprId(expr) => ConstRef { expr }.into(), + _ => return self.types.consts.error, + }; + + self.infer + .and_then(|infer| infer.term_of_term_placeholder(term_ref)) + .and_then(|generic_arg| generic_arg.as_const()) + .unwrap_or(self.types.consts.error) } fn next_region_var(&mut self, _span: hir_ide::Span) -> Region<'db> { self.types.regions.error diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search.rs b/src/tools/rust-analyzer/crates/hir/src/term_search.rs index 37cad14ea2d39..072f495f81912 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search.rs @@ -87,8 +87,9 @@ impl<'db> AlternativeExprs<'db> { /// iteration as well as keeping track of which `ScopeDef` items have been used. /// Both of them are to speed up the term search by leaving out types / ScopeDefs that likely do /// not produce any new results. -#[derive(Default, Debug)] +#[derive(Debug)] struct LookupTable<'db> { + db: &'db dyn HirDatabase, /// All the `Expr`s in "value" produce the type of "key" data: FxHashMap, AlternativeExprs<'db>>, /// New types reached since last query by the `NewTypesKey` @@ -101,20 +102,25 @@ struct LookupTable<'db> { impl<'db> LookupTable<'db> { /// Initialize lookup table - fn new(many_threshold: usize, goal: Type<'db>) -> Self { - let mut res = Self { many_threshold, ..Default::default() }; - res.new_types.insert(NewTypesKey::ImplMethod, Vec::new()); - res.new_types.insert(NewTypesKey::StructProjection, Vec::new()); - res.types_wishlist.insert(goal); - res + fn new(db: &'db dyn HirDatabase, many_threshold: usize, goal: Type<'db>) -> Self { + Self { + db, + many_threshold, + data: Default::default(), + types_wishlist: FxHashSet::from_iter([goal]), + new_types: FxHashMap::from_iter([ + (NewTypesKey::ImplMethod, Vec::new()), + (NewTypesKey::StructProjection, Vec::new()), + ]), + } } /// Find all `Expr`s that unify with the `ty` - fn find(&mut self, db: &'db dyn HirDatabase, ty: &Type<'db>) -> Option>> { + fn find(&mut self, ty: &Type<'db>) -> Option>> { let res = self .data .get_key_value(ty) - .or_else(|| self.data.iter().find(|(t, _)| t.could_unify_with_deeply(db, ty))) + .or_else(|| self.data.iter().find(|(t, _)| t.could_unify_with_deeply(self.db, ty))) .map(|(t, tts)| tts.exprs(t)); if res.is_none() { @@ -175,7 +181,7 @@ impl<'db> LookupTable<'db> { /// transitive. For example `Vec` and `FxHashSet` both unify with `Iterator`, /// but they clearly do not unify themselves. fn insert(&mut self, ty: Type<'db>, exprs: impl Iterator>) { - let ty = ty.instantiate_with_errors(); + let ty = ty.instantiate_with_errors(self.db); match self.data.get_mut(&ty) { Some(it) => { it.extend_with_threshold(self.many_threshold, exprs); @@ -271,7 +277,8 @@ pub fn term_search<'db, DB: HirDatabase>(ctx: &TermSearchCtx<'_, 'db, DB>) -> Ve defs.insert(def); }); - let mut lookup = LookupTable::new(ctx.config.many_alternatives_threshold, ctx.goal.clone()); + let mut lookup = + LookupTable::new(ctx.sema.db, ctx.config.many_alternatives_threshold, ctx.goal.clone()); let fuel = std::cell::Cell::new(ctx.config.fuel); let should_continue = &|| { diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs b/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs index dc6a6b269744c..6ea1f4e2a2b41 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs @@ -310,18 +310,20 @@ impl<'db> Expr<'db> { Expr::Local(it) => it.ty(db), Expr::ConstParam(it) => it.ty(db), Expr::FamousType { ty, .. } => ty.clone(), - Expr::Function { func, generics, .. } => func.ret_type(db).instantiate(generics), + Expr::Function { func, generics, .. } => func.ret_type(db).instantiate(db, generics), Expr::Method { func, generics, target, .. } => func .ret_type(db) - .instantiate(target.ty(db).type_arguments().chain(generics.iter().cloned())), + .instantiate(db, target.ty(db).type_arguments().chain(generics.iter().cloned())), Expr::Variant { variant, generics, .. } => { - Adt::from(variant.parent_enum(db)).ty(db).instantiate(generics) + Adt::from(variant.parent_enum(db)).ty(db).instantiate(db, generics) } Expr::Struct { strukt, generics, .. } => { - Adt::from(*strukt).ty(db).instantiate(generics) + Adt::from(*strukt).ty(db).instantiate(db, generics) } Expr::Tuple { ty, .. } => ty.clone(), - Expr::Field { expr, field } => field.ty(db).instantiate(expr.ty(db).type_arguments()), + Expr::Field { expr, field } => { + field.ty(db).instantiate(db, expr.ty(db).type_arguments()) + } Expr::Reference(it) => it.ty(db), Expr::Many(ty) => ty.clone(), } diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs index dab80c28c4c3b..6059220bb0e00 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs @@ -57,7 +57,7 @@ pub(super) fn trivial<'a, 'lt, 'db, DB: HirDatabase>( lookup.insert(ty.clone(), std::iter::once(expr.clone())); - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(expr) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(expr) }) } @@ -107,7 +107,7 @@ pub(super) fn assoc_const<'a, 'lt, 'db, DB: HirDatabase>( lookup.insert(ty.clone(), std::iter::once(expr.clone())); - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(expr) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(expr) }) } @@ -169,7 +169,7 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( let param_exprs: Vec>> = fields .into_iter() .map(|field| { - lookup.find(db, &field.ty(db).instantiate(generics.iter().cloned())) + lookup.find(&field.ty(db).instantiate(db, generics.iter().cloned())) }) .collect::>()?; @@ -215,7 +215,7 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( .fields(db) .into_iter() .map(|field| { - lookup.find(db, &field.ty(db).instantiate(generics.iter().cloned())) + lookup.find(&field.ty(db).instantiate(db, generics.iter().cloned())) }) .collect::>()?; @@ -249,7 +249,7 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( Adt::Union(_) => None, }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -329,7 +329,7 @@ pub(super) fn free_function<'a, 'lt, 'db, DB: HirDatabase>( }) .collect::>()?; - let ret_ty = it.ret_type(db).instantiate(generics.iter().cloned()); + let ret_ty = it.ret_type(db).instantiate(db, generics.iter().cloned()); // Filter out private and unsafe functions if !it.is_visible_from(db, module) || it.is_unsafe_to_call( @@ -348,7 +348,7 @@ pub(super) fn free_function<'a, 'lt, 'db, DB: HirDatabase>( .params_without_self(db) .into_iter() .map(|field| { - let ty = &field.ty().instantiate(&generics); + let ty = &field.ty().instantiate(db, &generics); match ty.is_mutable_reference() { true => None, false => lookup.find_autoref(db, ty), @@ -383,7 +383,7 @@ pub(super) fn free_function<'a, 'lt, 'db, DB: HirDatabase>( }) .flatten() .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -459,28 +459,33 @@ pub(super) fn impl_method<'a, 'lt, 'db, DB: HirDatabase>( return None; } - let ret_ty = it.ret_type(db).instantiate(ty.type_arguments()); + let ret_ty = it.ret_type(db).instantiate(db, ty.type_arguments()); // Ignore functions that do not change the type - if ty.instantiate_with_errors().could_unify_with_deeply(db, &ret_ty) { + if ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ret_ty) { return None; } - let self_ty = - it.self_param(db).expect("No self param").ty(db).instantiate(ty.type_arguments()); + let self_ty = it + .self_param(db) + .expect("No self param") + .ty(db) + .instantiate(db, ty.type_arguments()); // Ignore functions that have different self type if !self_ty.autoderef(db).any(|s_ty| ty == s_ty) { return None; } - let target_type_exprs = lookup.find(db, &ty).expect("Type not in lookup"); + let target_type_exprs = lookup.find(&ty).expect("Type not in lookup"); // Early exit if some param cannot be filled from lookup let param_exprs: Vec>> = it .params_without_self(db) .into_iter() - .map(|field| lookup.find_autoref(db, &field.ty().instantiate(ty.type_arguments()))) + .map(|field| { + lookup.find_autoref(db, &field.ty().instantiate(db, ty.type_arguments())) + }) .collect::>()?; let generics: Vec<_> = ty.type_arguments().collect(); @@ -502,7 +507,7 @@ pub(super) fn impl_method<'a, 'lt, 'db, DB: HirDatabase>( Some((ret_ty, fn_exprs)) }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -530,7 +535,7 @@ pub(super) fn struct_projection<'a, 'lt, 'db, DB: HirDatabase>( lookup .new_types(NewTypesKey::StructProjection) .into_iter() - .map(|ty| (ty.clone(), lookup.find(db, &ty).expect("Expr not in lookup"))) + .map(|ty| (ty.clone(), lookup.find(&ty).expect("Expr not in lookup"))) .filter(|_| should_continue()) .flat_map(move |(ty, targets)| { ty.fields(db).into_iter().filter_map(move |(field, filed_ty)| { @@ -545,7 +550,7 @@ pub(super) fn struct_projection<'a, 'lt, 'db, DB: HirDatabase>( }) }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -570,7 +575,7 @@ pub(super) fn famous_types<'a, 'lt, 'db, DB: HirDatabase>( ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { let db = ctx.sema.db; let bool_ty = BuiltinType::bool().ty(db); - let unit_ty = Type::new_unit(); + let unit_ty = Type::new_unit(db); [ Expr::FamousType { ty: bool_ty.clone(), value: "true" }, Expr::FamousType { ty: bool_ty, value: "false" }, @@ -580,7 +585,7 @@ pub(super) fn famous_types<'a, 'lt, 'db, DB: HirDatabase>( .inspect(|exprs| { lookup.insert(exprs.ty(db), std::iter::once(exprs.clone())); }) - .filter(|expr| expr.ty(db).instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal)) + .filter(|expr| expr.ty(db).instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal)) } /// # Impl static method (without self type) tactic @@ -654,13 +659,15 @@ pub(super) fn impl_static_method<'a, 'lt, 'db, DB: HirDatabase>( return None; } - let ret_ty = it.ret_type(db).instantiate(ty.type_arguments()); + let ret_ty = it.ret_type(db).instantiate(db, ty.type_arguments()); // Early exit if some param cannot be filled from lookup let param_exprs: Vec>> = it .params_without_self(db) .into_iter() - .map(|field| lookup.find_autoref(db, &field.ty().instantiate(ty.type_arguments()))) + .map(|field| { + lookup.find_autoref(db, &field.ty().instantiate(db, ty.type_arguments())) + }) .collect::>()?; // Note that we need special case for 0 param constructors because of multi cartesian @@ -681,7 +688,7 @@ pub(super) fn impl_static_method<'a, 'lt, 'db, DB: HirDatabase>( Some((ret_ty, fn_exprs)) }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -720,7 +727,7 @@ pub(super) fn make_tuple<'a, 'lt, 'db, DB: HirDatabase>( // Early exit if some param cannot be filled from lookup let param_exprs: Vec>> = - ty.type_arguments().map(|field| lookup.find(db, &field)).collect::>()?; + ty.type_arguments().map(|field| lookup.find(&field)).collect::>()?; let exprs: Vec> = param_exprs .into_iter() @@ -741,7 +748,7 @@ pub(super) fn make_tuple<'a, 'lt, 'db, DB: HirDatabase>( .flatten() .filter_map(|expr| { expr.ty(db) - .instantiate_with_errors() + .instantiate_with_errors(db) .could_unify_with_deeply(db, &ctx.goal) .then_some(expr) }) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs index dd082476d2d62..95052faf93d31 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs @@ -293,7 +293,7 @@ pub(crate) fn relevance_score( if let Some(ty) = ty { if ty == *expected { score = 100000; - } else if ty.could_unify_with(ctx.db(), &expected.instantiate_with_errors()) { + } else if ty.could_unify_with(ctx.db(), &expected.instantiate_with_errors(ctx.db())) { score = 10000; } } @@ -2093,4 +2093,44 @@ fn main() { "#, ); } + + #[test] + fn carries_cfg_attr_from_macro() { + check_assist( + auto_import, + r#" +//- /lib.rs crate:std +pub mod time { + pub struct Instant; +} + +//- /main.rs crate:main deps:std +// comment comment comment comment + +macro_rules! m { + ($t: path) => { + #[cfg(anything)] + fn f() -> $t {} + }; +} + +m! {Instant$0} +"#, + r#" +// comment comment comment comment + +#[cfg(anything)] +use std::time::Instant; + +macro_rules! m { + ($t: path) => { + #[cfg(anything)] + fn f() -> $t {} + }; +} + +m! {Instant} +"#, + ); + } } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs index a378256b598aa..b95fab4fe88c8 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs @@ -426,6 +426,48 @@ fn main() { ) } + #[test] + fn inferred_array_length() { + check_assist( + extract_type_alias, + r#" +fn main() { + let a: $0[i32; _]$0 = [1, 2, 3]; +} + "#, + r#" +type $0Type = [i32; 3]; + +fn main() { + let a: Type = [1, 2, 3]; +} + "#, + ) + } + + #[test] + fn inferred_generic_const_parameter() { + check_assist( + extract_type_alias, + r#" +struct Wrap([i32; N]); + +fn main() { + let wrap: $0Wrap<_>$0 = Wrap([1, 2, 3]); +} + "#, + r#" +struct Wrap([i32; N]); + +type $0Type = Wrap<3>; + +fn main() { + let wrap: Type = Wrap([1, 2, 3]); +} + "#, + ) + } + #[test] fn inferred_type() { check_assist( diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs index a414db0a6c8d0..1ccc8917f0c65 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs @@ -72,7 +72,7 @@ pub(crate) fn replace_with_lazy_method( .is_some_and(|result| { result .ty(ctx.db()) - .instantiate_with_errors() + .instantiate_with_errors(ctx.db()) .could_unify_with(ctx.db(), &receiver_ty) }), _ => false, diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs index 032cc28858c29..867d71deb097a 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs @@ -92,7 +92,9 @@ pub(crate) fn wrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_, '_>) - }; let semantic_ty = ty_constructor .map(|ty_constructor| { - hir::Adt::from(ty_constructor).ty(ctx.db()).instantiate([ty.clone()]) + hir::Adt::from(ty_constructor) + .ty(ctx.db()) + .instantiate(ctx.db(), [ty.clone()]) }) .unwrap_or_else(|| ty.clone()); (ast_ty, semantic_ty) @@ -255,8 +257,9 @@ fn wrapper_alias<'db>( make.path_segment_generics(make.name_ref(name.as_str()), generic_arg_list), ); - let new_ty = - hir::Adt::from(enum_ty).ty(ctx.db()).instantiate([semantic_ret_type.clone()]); + let new_ty = hir::Adt::from(enum_ty) + .ty(ctx.db()) + .instantiate(ctx.db(), [semantic_ret_type.clone()]); Some((make.ty_path(path), new_ty)) }) diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs index 6937d241b7b77..a6fd2e8042fd0 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs @@ -185,7 +185,7 @@ pub(crate) fn complete_expr_path<'db>( }; // Note: this is not *required* here, we do it to also find methods that require // the type to be instantiated with specific types. - let ty = ty.instantiate_with_errors(); + let ty = ty.instantiate_with_errors(ctx.db); if let Some(hir::Adt::Enum(e)) = ty.as_adt() { cov_mark::hit!(completes_variant_through_alias); diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/context.rs b/src/tools/rust-analyzer/crates/ide-completion/src/context.rs index 80e07ff9323df..e397e95503b13 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/context.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/context.rs @@ -791,7 +791,7 @@ impl<'db> CompletionContext<'_, 'db> { self.scope .generic_def() .and_then(|def| ty.try_rebase_into_owner(self.db, def)) - .unwrap_or_else(|| ty.instantiate_with_errors()) + .unwrap_or_else(|| ty.instantiate_with_errors(self.db)) } } diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs b/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs index 9330e70b1cb02..4aed1e514f57f 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs @@ -658,7 +658,7 @@ fn expected_type_and_name<'db>( let def = *generic_def .get_or_insert_with(|| sema.scope(&node).and_then(|scope| scope.generic_def())); def.and_then(|def| ty.try_rebase_into_owner(sema.db, def)) - .unwrap_or_else(|| ty.instantiate_with_errors()) + .unwrap_or_else(|| ty.instantiate_with_errors(sema.db)) } }; let (ty, name) = loop { diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs b/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs index 0e9b5d0086f84..a4fb3e97d1b86 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs @@ -246,8 +246,11 @@ pub(super) fn add_call_parens<'b>( Some(n) => { let smol_str = n.display_no_db(ctx.edition).to_smolstr(); let text = smol_str.as_str().trim_start_matches('_'); - let ref_ = - ref_of_param(ctx, text, ¶m.ty().instantiate_with_errors()); + let ref_ = ref_of_param( + ctx, + text, + ¶m.ty().instantiate_with_errors(ctx.db), + ); f(&format_args!("${{{}:{ref_}{text}}}", index + offset)) } None => { diff --git a/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs b/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs index 119af3ab8615b..3403e41247029 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs @@ -5403,6 +5403,22 @@ The tracking issue for this feature is: [#87555] [#87555]: https://github.com/rust-lang/rust/issues/87555 +------------------------ +"##, + default_severity: Severity::Allow, + warn_since: None, + deny_since: None, + }, + Lint { + label: "const_abort", + description: r##"# `const_abort` + + + +The tracking issue for this feature is: [#166193] + +[#166193]: https://github.com/rust-lang/rust/issues/166193 + ------------------------ "##, default_severity: Severity::Allow, @@ -8525,6 +8541,22 @@ The tracking issue for this feature is: [#164793] [#164793]: https://github.com/rust-lang/rust/issues/164793 +------------------------ +"##, + default_severity: Severity::Allow, + warn_since: None, + deny_since: None, + }, + Lint { + label: "extern_item_default_impls", + description: r##"# `extern_item_default_impls` + +Externally implementable items with default impls + +The tracking issue for this feature is: [#125418] + +[#125418]: https://github.com/rust-lang/rust/issues/125418 + ------------------------ "##, default_severity: Severity::Allow, @@ -10550,22 +10582,6 @@ The tracking issue for this feature is: [#157081] [#157081]: https://github.com/rust-lang/rust/issues/157081 ------------------------- -"##, - default_severity: Severity::Allow, - warn_since: None, - deny_since: None, - }, - Lint { - label: "int_from_ascii", - description: r##"# `int_from_ascii` - - - -The tracking issue for this feature is: [#134821] - -[#134821]: https://github.com/rust-lang/rust/issues/134821 - ------------------------ "##, default_severity: Severity::Allow, @@ -18119,6 +18135,22 @@ The tracking issue for this feature is: [#148227] [#148227]: https://github.com/rust-lang/rust/issues/148227 +------------------------ +"##, + default_severity: Severity::Allow, + warn_since: None, + deny_since: None, + }, + Lint { + label: "vec_repeat", + description: r##"# `vec_repeat` + + + +The tracking issue for this feature is: [#164215] + +[#164215]: https://github.com/rust-lang/rust/issues/164215 + ------------------------ "##, default_severity: Severity::Allow, diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs index 4256b7dae51c5..af6c9de8fcabc 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs @@ -198,7 +198,7 @@ fn add_missing_ok_or_some( let variant_name = if Some(expected_enum) == core_result { "Ok" } else { "Some" }; - let wrapped_actual_ty = expected_adt.ty(ctx.db()).instantiate([d.actual.clone()]); + let wrapped_actual_ty = expected_adt.ty(ctx.db()).instantiate(ctx.db(), [d.actual.clone()]); if !d.expected.could_unify_with(ctx.db(), &wrapped_actual_ty) { return None; @@ -296,7 +296,7 @@ fn remove_unnecessary_wrapper( return None; } - let inner_type = variant.fields(db).first()?.ty(db).instantiate(d.actual.type_arguments()); + let inner_type = variant.fields(db).first()?.ty(db).instantiate(db, d.actual.type_arguments()); if !d.expected.could_unify_with(db, &inner_type) { return None; } diff --git a/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs b/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs index e14e9d512b7bf..5c35b9e26559c 100644 --- a/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs +++ b/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs @@ -9580,7 +9580,7 @@ fn notable_ranged() { r#" //- minicore: future, iterator struct S; -#[doc(notable_trait)] +#[doc(notable_trait(color = "transparent"))] trait Notable {} impl Notable for S {} impl core::future::Future for S { diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs index 566dde7775c84..6e77f182bf36b 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs @@ -868,16 +868,22 @@ fn hint_iterator<'db>( let db = sema.db; let strukt = ty.strip_references().as_adt()?; let krate = strukt.module(db).krate(db); - if krate != famous_defs.core()? { - return None; - } let iter_trait = famous_defs.core_iter_Iterator()?; let iter_mod = famous_defs.core_iter()?; - // Assert that this struct comes from `core::iter`. - if !(strukt.visibility(db) == hir::Visibility::Public - && strukt.module(db).path_to_root(db).contains(&iter_mod)) - { + let is_core_adapter = Some(krate) == famous_defs.core() + && strukt.visibility(db) == hir::Visibility::Public + && strukt.module(db).path_to_root(db).contains(&iter_mod); + let is_custom_adapter = || { + let params = hir::GenericDef::Adt(strukt).type_or_const_params(db); + params + .iter() + .filter_map(|it| it.as_type_param(db)) + .any(|it| it.trait_bounds(db).contains(&iter_trait)) + }; + + // Assert that this struct iterator adapter, excludes like `Range`. + if !is_core_adapter && !is_custom_adapter() { return None; } diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs index e008a7b940662..c818a1ef5fe10 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs @@ -775,4 +775,123 @@ fn make() -> Foo { "#]], ); } + + #[test] + fn custom_iterator_adapter_chaining() { + check_expect_clear_loc( + InlayHintsConfig { chaining_hints: true, ..DISABLED_CONFIG }, + r#" +//- minicore: iterators +fn main() { + [1, 2, 3].into_iter() + .merge_by([2, 4, 6], |a,b|a { + left: I, + right: J, + cmp_fn: F, +} +impl Iterator for MergeBy +where + I: Iterator, + J: Iterator, + F: FnMut(&I::Item, &J::Item) -> bool, +{ + type Item = I::Item; + + fn next(&mut self) -> Option { loop {} } +} + +trait Itertools: Iterator { + fn merge_by(self, other: J, is_first: F) -> MergeBy + where + Self: Sized, + J: IntoIterator, + F: FnMut(&Self::Item, &Self::Item) -> bool, + { + MergeBy { left: self, right: other.into_iter(), cmp_fn: is_first } + } +} +impl Itertools for I {} +"#, + expect![[r#" + [ + ( + 16..76, + [ + "impl ", + InlayHintLabelPart { + text: "Iterator", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + "<", + InlayHintLabelPart { + text: "Item", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + " = i32>", + ], + ), + ( + 16..37, + [ + "impl ", + InlayHintLabelPart { + text: "Iterator", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + "<", + InlayHintLabelPart { + text: "Item", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + " = i32>", + ], + ), + ] + "#]], + ); + } } diff --git a/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs b/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs index e33446e4a148b..dfa8aef3012b9 100644 --- a/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs +++ b/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs @@ -475,6 +475,7 @@ define_symbols! { panic, Param, parse, + partial_eq, partial_ord, PartialEq, PartialOrd, diff --git a/src/tools/rust-analyzer/crates/paths/src/lib.rs b/src/tools/rust-analyzer/crates/paths/src/lib.rs index d6d9ed4676c16..5ded23c149bbb 100644 --- a/src/tools/rust-analyzer/crates/paths/src/lib.rs +++ b/src/tools/rust-analyzer/crates/paths/src/lib.rs @@ -308,6 +308,12 @@ impl AbsPath { self.0.components() } // endregion:delegate-methods + + /// `"/a/b/c/d/e".short_relative_by("b/c")` -> `"d/e"` + pub fn short_relative_by(&self, dummy: impl AsRef) -> Option<&RelPath> { + let prefix = self.0.ancestors().find(|prefix| prefix.ends_with(&dummy))?; + self.strip_prefix(AbsPath::assert(prefix)) + } } impl fmt::Display for AbsPath { diff --git a/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs b/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs index 126c0b41bb9f4..8ad210724cd0b 100644 --- a/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs +++ b/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs @@ -196,7 +196,8 @@ pub(crate) fn make_lockfile_copy( let temp_dir = NamedTempDir::new("rust-analyzer").ok()?; let path = temp_dir.path().join("Cargo.lock"); - std::fs::copy(lockfile_path.as_std_path(), &path).ok()?; + // `fs::read` + `fs::write` instead of `fs::copy` to avoid copying permission bits. + std::fs::write(&path, std::fs::read(lockfile_path.as_std_path()).ok()?).ok()?; Some(LockfileCopy { path: Utf8PathBuf::from_path_buf(path).ok()?, usage, _temp_dir: temp_dir }) } diff --git a/src/tools/rust-analyzer/crates/project-model/src/workspace.rs b/src/tools/rust-analyzer/crates/project-model/src/workspace.rs index db3cecb5b2a31..56c1b8ff1acd8 100644 --- a/src/tools/rust-analyzer/crates/project-model/src/workspace.rs +++ b/src/tools/rust-analyzer/crates/project-model/src/workspace.rs @@ -791,7 +791,7 @@ impl ProjectWorkspace { RustLibSrcWorkspace::Json(project_json) => project_json .crates() .map(|(_, krate)| PackageRoot { - is_local: false, + is_local: krate.is_workspace_member, include: krate.include.clone(), exclude: krate.exclude.clone(), }) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs index 3cd7a9ac9282e..68d7164698a2b 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs @@ -1034,11 +1034,15 @@ impl GlobalState { let mut message = format!("{n_done}/{n_total}"); if let Some(dir) = dir { + let common_std = "lib/rustlib/src/rust"; message += &format!( ": {}", match dir.strip_prefix(self.config.workspace_root_for(&dir)) { Some(relative_path) => relative_path.as_utf8_path(), - None => dir.as_ref(), + None => match dir.short_relative_by(common_std) { + Some(short) => short.as_ref(), + None => dir.as_ref(), + }, } ); } diff --git a/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs b/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs index 1ef6954e5a6ce..932dec3b37d85 100644 --- a/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs +++ b/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs @@ -37,6 +37,7 @@ pub struct Pool { struct Job { requested_intent: ThreadIntent, f: Box, + wg: Option, } impl Pool { @@ -67,6 +68,7 @@ impl Pool { // discard the panic, we should've logged the backtrace already drop(panic::catch_unwind(job.f)); extant_tasks.fetch_sub(1, Ordering::SeqCst); + drop(job.wg); } } }) @@ -89,7 +91,7 @@ impl Pool { f(); }); - let job = Job { requested_intent: intent, f }; + let job = Job { requested_intent: intent, f, wg: None }; self.extant_tasks.fetch_add(1, Ordering::SeqCst); self.job_sender.send(job).unwrap(); } @@ -127,15 +129,14 @@ impl<'scope> Scope<'_, 'scope> { where F: 'scope + FnOnce() + Send + UnwindSafe, { - let wg = self.wg.clone(); let f = Box::new(move || { if cfg!(debug_assertions) { intent.assert_is_used_on_current_thread(); } f(); - drop(wg); }); + let wg = self.wg.clone(); let job = Job { requested_intent: intent, f: unsafe { @@ -144,8 +145,134 @@ impl<'scope> Scope<'_, 'scope> { Box, >(f) }, + wg: Some(wg), }; self.pool.extant_tasks.fetch_add(1, Ordering::SeqCst); self.pool.job_sender.send(job).unwrap(); } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }; + + fn spawn_scoped_worker(pool: &Pool) { + pool.scoped(|scope| scope.spawn(ThreadIntent::Worker, || {})); + } + + #[test] + fn new_creates_empty_pool() { + let pool = Pool::new(2); + assert_eq!(pool.len(), 0); + assert!(pool.is_empty()); + } + + #[test] + fn spawn_executes_function() { + let pool = Pool::new(1); + let executed = Arc::new(AtomicBool::new(false)); + let executed_clone = Arc::clone(&executed); + pool.spawn(ThreadIntent::Worker, move || { + executed_clone.store(true, Ordering::SeqCst); + }); + spawn_scoped_worker(&pool); + assert!(executed.load(Ordering::SeqCst)); + } + + #[test] + fn spawn_changes_thread_intent() { + let pool = Pool::new(1); + let count = Arc::new(AtomicUsize::new(0)); + let first = Arc::clone(&count); + pool.spawn(ThreadIntent::Worker, move || { + first.fetch_add(669, Ordering::SeqCst); + }); + let second = Arc::clone(&count); + pool.spawn(ThreadIntent::LatencySensitive, move || { + second.fetch_add(668, Ordering::SeqCst); + }); + spawn_scoped_worker(&pool); + assert_eq!(count.load(Ordering::SeqCst), 1337); + } + + #[test] + fn spawn_handles_panicking_function() { + let pool = Pool::new(1); + pool.spawn(ThreadIntent::Worker, || panic!()); + let executed = Arc::new(AtomicBool::new(false)); + let executed_clone = Arc::clone(&executed); + pool.spawn(ThreadIntent::Worker, move || { + executed_clone.store(true, Ordering::SeqCst); + }); + spawn_scoped_worker(&pool); + assert!(executed.load(Ordering::SeqCst)); + } + + #[test] + fn scoped_executes_borrowing_function() { + let pool = Pool::new(1); + let value = 42; + let ran = AtomicBool::new(false); + let result = pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || { + ran.store(true, Ordering::SeqCst); + }); + value + 1 + }); + assert_eq!(result, 43); + assert!(ran.load(Ordering::SeqCst)); + } + + #[test] + fn scoped_executes_multiple_functions() { + let pool = Pool::new(2); + let value = AtomicUsize::new(0); + pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || { + value.fetch_add(9, Ordering::SeqCst); + }); + scope.spawn(ThreadIntent::LatencySensitive, || { + value.fetch_add(10, Ordering::SeqCst); + }); + }); + assert_eq!(value.load(Ordering::SeqCst), 19); + } + + #[test] + fn scoped_handles_panicking_function() { + let pool = Pool::new(1); + pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || panic!()); + }); + let ran = AtomicBool::new(false); + pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || ran.store(true, Ordering::SeqCst)); + }); + assert!(ran.load(Ordering::SeqCst)); + } + + #[test] + fn scoped_returns_result_after_tasks_finish() { + let pool = Pool::new(2); + let value = AtomicUsize::new(0); + let result = pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || { + value.store(19991005, Ordering::SeqCst); + }); + 0xC0FFEE + }); + assert_eq!(result, 0xC0FFEE); + assert_eq!(value.load(Ordering::SeqCst), 19991005); + } + + #[test] + fn zero_thread_pool_starts_empty() { + let pool = Pool::new(0); + assert_eq!(pool.len(), 0); + assert!(pool.is_empty()); + } +} diff --git a/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs b/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs index 7c2ba4d53d913..237bb64e8e771 100644 --- a/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs +++ b/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs @@ -1317,7 +1317,7 @@ pub mod range { pub mod cmp { use crate::marker::PointeeSized; - #[lang = "eq"] + #[lang = "partial_eq"] pub trait PartialEq: PointeeSized { fn eq(&self, other: &Rhs) -> bool; fn ne(&self, other: &Rhs) -> bool { @@ -1325,6 +1325,7 @@ pub mod cmp { } } + #[lang = "eq"] pub trait Eq: PartialEq + PointeeSized {} // region:builtin_impls diff --git a/src/tools/rust-analyzer/josh-sync.toml b/src/tools/rust-analyzer/josh-sync.toml index a12cfa1b5cbd5..5cd30792f9aac 100644 --- a/src/tools/rust-analyzer/josh-sync.toml +++ b/src/tools/rust-analyzer/josh-sync.toml @@ -4,3 +4,6 @@ filter = ":rev(55d9a533b309119c8acd13061581b43ae8840823:prefix=src/tools/rust-an [[post-pull]] cmd = ["cargo", "fmt"] commit-message = "Format code" + +[push-pr] +suffix = "r? @ghost" diff --git a/src/tools/rust-analyzer/rust-version b/src/tools/rust-analyzer/rust-version index 2ab8919989008..188d50ebbcd66 100644 --- a/src/tools/rust-analyzer/rust-version +++ b/src/tools/rust-analyzer/rust-version @@ -1 +1 @@ -4c46afa63688fb473618f9b3553d70b0c15a88eb +e3b9a8345a8a58fda3ac9446c532625d5a59acd8 diff --git a/tests/ui/attributes/attr-on-mac-call.rs b/tests/ui/attributes/attr-on-mac-call.rs index da57853f4bddd..514542994d4b1 100644 --- a/tests/ui/attributes/attr-on-mac-call.rs +++ b/tests/ui/attributes/attr-on-mac-call.rs @@ -151,4 +151,12 @@ fn main() { }] //~^^^ ERROR attribute value must be a literal unreachable!(); + + #[deprecated] + //~^ WARN cannot be used on + //~| WARN previously accepted + #[deprecated] + //~^ WARN cannot be used on + //~| WARN previously accepted + unreachable!(); } diff --git a/tests/ui/attributes/attr-on-mac-call.stderr b/tests/ui/attributes/attr-on-mac-call.stderr index d51f3ef574688..816e58608f949 100644 --- a/tests/ui/attributes/attr-on-mac-call.stderr +++ b/tests/ui/attributes/attr-on-mac-call.stderr @@ -436,6 +436,30 @@ LL | unreachable!(); = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion -error: aborting due to 8 previous errors; 30 warnings emitted +warning: the `deprecated` attribute cannot be used on macro calls + --> $DIR/attr-on-mac-call.rs:155:7 + | +LL | #[deprecated] + | ^^^^^^^^^^ +... +LL | unreachable!(); + | + = help: the `deprecated` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, foreign statics, functions, inherent impl blocks, macro defs, modules, statics, struct fields, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion + +warning: the `deprecated` attribute cannot be used on macro calls + --> $DIR/attr-on-mac-call.rs:158:7 + | +LL | #[deprecated] + | ^^^^^^^^^^ +... +LL | unreachable!(); + | + = help: the `deprecated` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, foreign statics, functions, inherent impl blocks, macro defs, modules, statics, struct fields, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion + +error: aborting due to 8 previous errors; 32 warnings emitted For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/attributes/malformed-lint-reason.rs b/tests/ui/attributes/malformed-lint-reason.rs new file mode 100644 index 0000000000000..05d4e5d9c6f89 --- /dev/null +++ b/tests/ui/attributes/malformed-lint-reason.rs @@ -0,0 +1,7 @@ +// Test that an invalid name-value argument suggests `reason`. +#![allow(dead_code, note = "testing")] +//~^ ERROR malformed `allow` attribute input +//~| ERROR malformed `allow` attribute input +//~| ERROR malformed `allow` attribute input + +fn main() {} diff --git a/tests/ui/attributes/malformed-lint-reason.stderr b/tests/ui/attributes/malformed-lint-reason.stderr new file mode 100644 index 0000000000000..c18f9b0ef4729 --- /dev/null +++ b/tests/ui/attributes/malformed-lint-reason.stderr @@ -0,0 +1,40 @@ +error: malformed `allow` attribute input + --> $DIR/malformed-lint-reason.rs:2:21 + | +LL | #![allow(dead_code, note = "testing")] + | ^^^^^^^^^^^^^^^^ not the name of a lint + | +help: to provide a reason, use `reason = ""` + | +LL - #![allow(dead_code, note = "testing")] +LL + #![allow(dead_code, reason = "testing")] + | + +error: malformed `allow` attribute input + --> $DIR/malformed-lint-reason.rs:2:21 + | +LL | #![allow(dead_code, note = "testing")] + | ^^^^^^^^^^^^^^^^ not the name of a lint + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +help: to provide a reason, use `reason = ""` + | +LL - #![allow(dead_code, note = "testing")] +LL + #![allow(dead_code, reason = "testing")] + | + +error: malformed `allow` attribute input + --> $DIR/malformed-lint-reason.rs:2:21 + | +LL | #![allow(dead_code, note = "testing")] + | ^^^^^^^^^^^^^^^^ not the name of a lint + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +help: to provide a reason, use `reason = ""` + | +LL - #![allow(dead_code, note = "testing")] +LL + #![allow(dead_code, reason = "testing")] + | + +error: aborting due to 3 previous errors + diff --git a/tests/ui/error-codes/E0452.rs b/tests/ui/error-codes/E0452.rs index 6a0437df7b14e..947f8f1237bf5 100644 --- a/tests/ui/error-codes/E0452.rs +++ b/tests/ui/error-codes/E0452.rs @@ -1,8 +1,6 @@ -#![allow(foo = "")] //~ ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed -fn main() { -} +#![allow(foo = "")] +//~^ ERROR malformed +//~| ERROR malformed +//~| ERROR malformed + +fn main() {} diff --git a/tests/ui/error-codes/E0452.stderr b/tests/ui/error-codes/E0452.stderr index c34d9a2a01b28..0244de4a7bc81 100644 --- a/tests/ui/error-codes/E0452.stderr +++ b/tests/ui/error-codes/E0452.stderr @@ -4,16 +4,11 @@ error: malformed `allow` attribute input LL | #![allow(foo = "")] | ^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - -error: malformed `allow` attribute input - --> $DIR/E0452.rs:1:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(foo = "")] - | ^^^^^^^^ not the name of a lint +LL - #![allow(foo = "")] +LL + #![allow(reason = "")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: malformed `allow` attribute input --> $DIR/E0452.rs:1:10 @@ -21,17 +16,12 @@ error: malformed `allow` attribute input LL | #![allow(foo = "")] | ^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: malformed `allow` attribute input - --> $DIR/E0452.rs:1:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(foo = "")] - | ^^^^^^^^ not the name of a lint +LL - #![allow(foo = "")] +LL + #![allow(reason = "")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: malformed `allow` attribute input --> $DIR/E0452.rs:1:10 @@ -39,17 +29,12 @@ error: malformed `allow` attribute input LL | #![allow(foo = "")] | ^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: malformed `allow` attribute input - --> $DIR/E0452.rs:1:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(foo = "")] - | ^^^^^^^^ not the name of a lint +LL - #![allow(foo = "")] +LL + #![allow(reason = "")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 6 previous errors +error: aborting due to 3 previous errors diff --git a/tests/ui/lint/lint-malformed.rs b/tests/ui/lint/lint-malformed.rs index 5fd92170363f0..e5a64cbf764f9 100644 --- a/tests/ui/lint/lint-malformed.rs +++ b/tests/ui/lint/lint-malformed.rs @@ -1,8 +1,7 @@ #![deny = "foo"] //~ ERROR malformed `deny` attribute input -#![allow(bar = "baz")] //~ ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed -fn main() { } +#![allow(bar = "baz")] +//~^ ERROR malformed +//~| ERROR malformed +//~| ERROR malformed + +fn main() {} diff --git a/tests/ui/lint/lint-malformed.stderr b/tests/ui/lint/lint-malformed.stderr index ceb7fe105bcd3..8afd9ac54e438 100644 --- a/tests/ui/lint/lint-malformed.stderr +++ b/tests/ui/lint/lint-malformed.stderr @@ -4,16 +4,11 @@ error: malformed `allow` attribute input LL | #![allow(bar = "baz")] | ^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - -error: malformed `allow` attribute input - --> $DIR/lint-malformed.rs:2:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(bar = "baz")] - | ^^^^^^^^^^^ not the name of a lint +LL - #![allow(bar = "baz")] +LL + #![allow(reason = "baz")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: malformed `allow` attribute input --> $DIR/lint-malformed.rs:2:10 @@ -21,17 +16,12 @@ error: malformed `allow` attribute input LL | #![allow(bar = "baz")] | ^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: malformed `allow` attribute input - --> $DIR/lint-malformed.rs:2:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(bar = "baz")] - | ^^^^^^^^^^^ not the name of a lint +LL - #![allow(bar = "baz")] +LL + #![allow(reason = "baz")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0539]: malformed `deny` attribute input --> $DIR/lint-malformed.rs:1:4 @@ -60,18 +50,13 @@ error: malformed `allow` attribute input LL | #![allow(bar = "baz")] | ^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: malformed `allow` attribute input - --> $DIR/lint-malformed.rs:2:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(bar = "baz")] - | ^^^^^^^^^^^ not the name of a lint +LL - #![allow(bar = "baz")] +LL + #![allow(reason = "baz")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 7 previous errors +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0539`. diff --git a/tests/ui/lint/reasons-erroneous.stderr b/tests/ui/lint/reasons-erroneous.stderr index 3c52a0d8e25b4..1288a9fa5d601 100644 --- a/tests/ui/lint/reasons-erroneous.stderr +++ b/tests/ui/lint/reasons-erroneous.stderr @@ -35,7 +35,11 @@ error: malformed `warn` attribute input LL | #![warn(bare_trait_objects, reasons = "leaders to no sure land, guides their bearings lost")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[warn(dead_code)]` for `dead_code` +help: to provide a reason, use `reason = ""` + | +LL - #![warn(bare_trait_objects, reasons = "leaders to no sure land, guides their bearings lost")] +LL + #![warn(bare_trait_objects, reason = "leaders to no sure land, guides their bearings lost")] + | error: malformed `warn` attribute input --> $DIR/reasons-erroneous.rs:13:22 @@ -43,7 +47,11 @@ error: malformed `warn` attribute input LL | #![warn(unsafe_code, blerp = "or in league with robbers have reversed the signposts")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[warn(dead_code)]` for `dead_code` +help: to provide a reason, use `reason = ""` + | +LL - #![warn(unsafe_code, blerp = "or in league with robbers have reversed the signposts")] +LL + #![warn(unsafe_code, reason = "or in league with robbers have reversed the signposts")] + | error: malformed `warn` attribute input --> $DIR/reasons-erroneous.rs:16:36