Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 35 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ hir = { path = "./crates/hir", version = "0.0.0" }
hir-def = { path = "./crates/hir-def", version = "0.0.0" }
hir-expand = { path = "./crates/hir-expand", version = "0.0.0" }
hir-ty = { path = "./crates/hir-ty", version = "0.0.0" }
hir-ide = { path = "./crates/hir-ide", version = "0.0.0" }
ide = { path = "./crates/ide", version = "0.0.0" }
ide-assists = { path = "./crates/ide-assists", version = "0.0.0" }
ide-completion = { path = "./crates/ide-completion", version = "0.0.0" }
Expand Down
1 change: 1 addition & 0 deletions crates/hir-def/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ pub mod unstable_features;
pub mod expr_store;
pub mod hir;
pub mod resolver;
pub mod upvars;

pub mod nameres;

Expand Down
106 changes: 51 additions & 55 deletions crates/hir-ty/src/upvars.rs → crates/hir-def/src/upvars.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
//! A simple query to collect tall locals (upvars) a closure use.

use hir_def::{
use base_db::SourceDatabase;
use hir_expand::mod_path::PathKind;
use rustc_hash::{FxHashMap, FxHashSet};

use crate::{
DefWithBodyId, ExpressionStoreOwnerId, GenericDefId, VariantId,
expr_store::{ExpressionStore, StoreVisitor, StoreVisitorExt, path::Path},
hir::{BindingId, Expr, ExprId, PatId},
resolver::{HasResolver, Resolver, ValueNs},
type_ref::TypeRefId,
};
use hir_expand::mod_path::PathKind;
use rustc_hash::{FxHashMap, FxHashSet};

use crate::db::HirDatabase;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
// Kept sorted.
Expand Down Expand Up @@ -72,7 +72,7 @@ impl UpvarsRef<'_> {

/// Returns a map from `Expr::Closure` to its upvars.
pub fn upvars_mentioned(
db: &dyn HirDatabase,
db: &dyn SourceDatabase,
owner: ExpressionStoreOwnerId,
) -> Option<&FxHashMap<ExprId, Upvars>> {
return match owner {
Expand All @@ -83,31 +83,31 @@ pub fn upvars_mentioned(

#[salsa::tracked(returns(as_deref))]
pub fn signature_upvars_mentioned(
db: &dyn HirDatabase,
db: &dyn SourceDatabase,
owner: GenericDefId,
) -> Option<Box<FxHashMap<ExprId, Upvars>>> {
upvars_mentioned_impl(db, owner.into())
}

#[salsa::tracked(returns(as_deref))]
pub fn body_upvars_mentioned(
db: &dyn HirDatabase,
db: &dyn SourceDatabase,
owner: DefWithBodyId,
) -> Option<Box<FxHashMap<ExprId, Upvars>>> {
upvars_mentioned_impl(db, owner.into())
}

#[salsa::tracked(returns(as_deref))]
pub fn variant_fields_upvars_mentioned(
db: &dyn HirDatabase,
db: &dyn SourceDatabase,
owner: VariantId,
) -> Option<Box<FxHashMap<ExprId, Upvars>>> {
upvars_mentioned_impl(db, owner.into())
}
}

pub fn upvars_mentioned_impl(
db: &dyn HirDatabase,
db: &dyn SourceDatabase,
owner: ExpressionStoreOwnerId,
) -> Option<Box<FxHashMap<ExprId, Upvars>>> {
let store = ExpressionStore::of(db, owner);
Expand All @@ -132,7 +132,7 @@ pub fn upvars_mentioned_impl(
}

struct UpvarsMentionedVisitor<'db> {
db: &'db dyn HirDatabase,
db: &'db dyn SourceDatabase,
resolver: Resolver<'db>,
owner: ExpressionStoreOwnerId,
store: &'db ExpressionStore,
Expand Down Expand Up @@ -226,58 +226,54 @@ impl StoreVisitor for UpvarsMentionedVisitor<'_> {
#[cfg(test)]
mod tests {
use expect_test::{Expect, expect};
use hir_def::{
AssocItemId, DefWithBodyId, ModuleDefId, expr_store::Body, nameres::crate_def_map,
};
use itertools::Itertools;
use span::Edition;
use test_fixture::WithFixture;

use crate::{test_db::TestDB, upvars::upvars_mentioned};
use crate::{
AssocItemId, DefWithBodyId, ModuleDefId, expr_store::Body, nameres::crate_def_map,
test_db::TestDB, upvars::upvars_mentioned,
};

#[track_caller]
fn check(#[rust_analyzer::rust_fixture] ra_fixture: &str, expectation: Expect) {
let db = TestDB::with_files(ra_fixture);
crate::attach_db(&db, || {
let def_map = crate_def_map(&db, db.test_crate());
let func = def_map
.modules()
.flat_map(|(_, module)| module.scope.declarations())
.filter_map(|decl| match decl {
ModuleDefId::FunctionId(func) => Some(func),
_ => None,
})
.chain(def_map.modules().flat_map(|(_, module)| {
module.scope.impls().flat_map(|impl_| &*impl_.impl_items(&db).items).filter_map(
|&(_, item)| match item {
AssocItemId::FunctionId(it) => Some(it),
_ => None,
},
)
}))
.exactly_one()
.unwrap_or_else(|_| panic!("expected one function"));
let (body, source_map) = Body::with_source_map(&db, func.into());
let Some(upvars) = upvars_mentioned(&db, DefWithBodyId::from(func).into()) else {
expectation.assert_eq("");
return;
};
let mut closures = Vec::new();
for (&closure, upvars) in upvars {
let closure_range = source_map.expr_syntax(closure).unwrap().value.text_range();
let upvars = upvars
.iter()
.map(|local| body[local].name.display(&db, Edition::CURRENT))
.join(", ");
closures.push((closure_range, upvars));
}
closures.sort_unstable_by_key(|(range, _)| (range.start(), range.end()));
let closures = closures
.into_iter()
.map(|(range, upvars)| format!("{range:?}: {upvars}"))
.join("\n");
expectation.assert_eq(&closures);
});
let def_map = crate_def_map(&db, db.test_crate());
let func = def_map
.modules()
.flat_map(|(_, module)| module.scope.declarations())
.filter_map(|decl| match decl {
ModuleDefId::FunctionId(func) => Some(func),
_ => None,
})
.chain(def_map.modules().flat_map(|(_, module)| {
module.scope.impls().flat_map(|impl_| &*impl_.impl_items(&db).items).filter_map(
|&(_, item)| match item {
AssocItemId::FunctionId(it) => Some(it),
_ => None,
},
)
}))
.exactly_one()
.unwrap_or_else(|_| panic!("expected one function"));
let (body, source_map) = Body::with_source_map(&db, func.into());
let Some(upvars) = upvars_mentioned(&db, DefWithBodyId::from(func).into()) else {
expectation.assert_eq("");
return;
};
let mut closures = Vec::new();
for (&closure, upvars) in upvars {
let closure_range = source_map.expr_syntax(closure).unwrap().value.text_range();
let upvars = upvars
.iter()
.map(|local| body[local].name.display(&db, Edition::CURRENT))
.join(", ");
closures.push((closure_range, upvars));
}
closures.sort_unstable_by_key(|(range, _)| (range.start(), range.end()));
let closures =
closures.into_iter().map(|(range, upvars)| format!("{range:?}: {upvars}")).join("\n");
expectation.assert_eq(&closures);
}

#[test]
Expand Down
56 changes: 56 additions & 0 deletions crates/hir-ide/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
[package]
name = "hir-ide"
version = "0.0.0"
repository.workspace = true
description = "The final bits of analysis; Display, extra diagnostics, and tests."

authors.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true

[lib]
doctest = false

[dependencies]
cov-mark = "2.0.0"
itertools.workspace = true
smallvec.workspace = true
either.workspace = true
tracing = { workspace = true, features = ["attributes"] }
rustc-hash.workspace = true
la-arena.workspace = true
triomphe.workspace = true
typed-arena = "2.0.2"
rustc_apfloat = "0.2.3"
salsa.workspace = true

ra-ap-rustc_abi.workspace = true
ra-ap-rustc_pattern_analysis.workspace = true
ra-ap-rustc_ast_ir.workspace = true
ra-ap-rustc_type_ir.workspace = true

# local deps
stdx.workspace = true
macros.workspace = true
intern.workspace = true
hir-def.workspace = true
hir-expand.workspace = true
base-db.workspace = true
syntax.workspace = true
span.workspace = true
hir-ty.workspace = true

[dev-dependencies]
expect-test = "1.5.1"
project-model.workspace = true

# local deps
test-utils.workspace = true
test-fixture.workspace = true

[features]
in-rust-tree = ["hir-expand/in-rust-tree"]

[lints]
workspace = true
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,9 @@ use span::Edition;
use stdx::{always, never, variance::PhantomCovariantLifetime};

use crate::{
ByRef, InferenceResult,
BindingMode, ByRef, InferenceResult,
db::HirDatabase,
display::{HirDisplay, HirDisplayError, HirFormatter},
infer::BindingMode,
next_solver::{GenericArgs, Mutability, Ty, TyKind},
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::{
use base_db::{Crate, FxIndexMap};
use either::Either;
use hir_def::{
ExpressionStoreOwnerId, FindPathConfig, GenericDefId, GenericParamId, HasModule,
CallableDefId, ExpressionStoreOwnerId, FindPathConfig, GenericDefId, GenericParamId, HasModule,
ItemContainerId, LocalFieldId, Lookup, ModuleDefId, ModuleId, TraitId, TypeAliasId,
expr_store::{ExpressionStore, path::Path},
find_path::{self, PrefixKind},
Expand Down Expand Up @@ -51,11 +51,10 @@ use span::Edition;
use stdx::never;

use crate::{
CallableDefId, FieldType, ImplTraitId, MemoryMap, ParamEnvAndCrate, consteval,
FieldType, GenericPredicates, ImplTraitId, MemoryMap, ParamEnvAndCrate, consteval,
db::{GeneralConstId, HirDatabase},
generics::{ProvenanceSplit, generics},
layout::Layout,
lower::GenericPredicates,
mir::{IsSigned, pad16},
next_solver::{
AliasTy, Allocation, Clause, ClauseKind, Const, ConstKind, DbInterner,
Expand Down
Loading