Skip to content

Commit 1fd3a36

Browse files
committed
Auto merge of rust-lang#17023 - Veykril:cleanup, r=Veykril
internal: Some cleanup and perf
2 parents c8985f4 + ab25be4 commit 1fd3a36

File tree

23 files changed

+243
-227
lines changed

23 files changed

+243
-227
lines changed

src/tools/rust-analyzer/crates/base-db/src/input.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -285,9 +285,9 @@ pub struct CrateData {
285285
/// For purposes of analysis, crates are anonymous (only names in
286286
/// `Dependency` matters), this name should only be used for UI.
287287
pub display_name: Option<CrateDisplayName>,
288-
pub cfg_options: CfgOptions,
288+
pub cfg_options: Arc<CfgOptions>,
289289
/// The cfg options that could be used by the crate
290-
pub potential_cfg_options: Option<CfgOptions>,
290+
pub potential_cfg_options: Option<Arc<CfgOptions>>,
291291
pub env: Env,
292292
pub dependencies: Vec<Dependency>,
293293
pub origin: CrateOrigin,
@@ -328,8 +328,8 @@ impl CrateGraph {
328328
edition: Edition,
329329
display_name: Option<CrateDisplayName>,
330330
version: Option<String>,
331-
cfg_options: CfgOptions,
332-
potential_cfg_options: Option<CfgOptions>,
331+
cfg_options: Arc<CfgOptions>,
332+
potential_cfg_options: Option<Arc<CfgOptions>>,
333333
env: Env,
334334
is_proc_macro: bool,
335335
origin: CrateOrigin,

src/tools/rust-analyzer/crates/hir-def/src/data.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -737,7 +737,7 @@ impl<'a> AssocItemCollector<'a> {
737737
&AstIdWithPath::new(file_id, ast_id, Clone::clone(path)),
738738
ctxt,
739739
expand_to,
740-
self.expander.module.krate(),
740+
self.expander.krate(),
741741
resolver,
742742
) {
743743
Ok(Some(call_id)) => {

src/tools/rust-analyzer/crates/hir-def/src/data/adt.rs

+3-8
Original file line numberDiff line numberDiff line change
@@ -191,8 +191,6 @@ impl StructData {
191191
let krate = loc.container.krate;
192192
let item_tree = loc.id.item_tree(db);
193193
let repr = repr_from_value(db, krate, &item_tree, ModItem::from(loc.id.value).into());
194-
let cfg_options = db.crate_graph()[krate].cfg_options.clone();
195-
196194
let attrs = item_tree.attrs(db, krate, ModItem::from(loc.id.value).into());
197195

198196
let mut flags = StructFlags::NO_FLAGS;
@@ -219,7 +217,7 @@ impl StructData {
219217
loc.id.file_id(),
220218
loc.container.local_id,
221219
&item_tree,
222-
&cfg_options,
220+
&db.crate_graph()[krate].cfg_options,
223221
&strukt.fields,
224222
None,
225223
);
@@ -248,8 +246,6 @@ impl StructData {
248246
let krate = loc.container.krate;
249247
let item_tree = loc.id.item_tree(db);
250248
let repr = repr_from_value(db, krate, &item_tree, ModItem::from(loc.id.value).into());
251-
let cfg_options = db.crate_graph()[krate].cfg_options.clone();
252-
253249
let attrs = item_tree.attrs(db, krate, ModItem::from(loc.id.value).into());
254250
let mut flags = StructFlags::NO_FLAGS;
255251
if attrs.by_key("rustc_has_incoherent_inherent_impls").exists() {
@@ -266,7 +262,7 @@ impl StructData {
266262
loc.id.file_id(),
267263
loc.container.local_id,
268264
&item_tree,
269-
&cfg_options,
265+
&db.crate_graph()[krate].cfg_options,
270266
&union.fields,
271267
None,
272268
);
@@ -338,7 +334,6 @@ impl EnumVariantData {
338334
let container = loc.parent.lookup(db).container;
339335
let krate = container.krate;
340336
let item_tree = loc.id.item_tree(db);
341-
let cfg_options = db.crate_graph()[krate].cfg_options.clone();
342337
let variant = &item_tree[loc.id.value];
343338

344339
let (var_data, diagnostics) = lower_fields(
@@ -347,7 +342,7 @@ impl EnumVariantData {
347342
loc.id.file_id(),
348343
container.local_id,
349344
&item_tree,
350-
&cfg_options,
345+
&db.crate_graph()[krate].cfg_options,
351346
&variant.fields,
352347
Some(item_tree[loc.parent.lookup(db).id.value].visibility),
353348
);

src/tools/rust-analyzer/crates/hir-def/src/expander.rs

+7-4
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use hir_expand::{
1111
};
1212
use limit::Limit;
1313
use syntax::{ast, Parse};
14+
use triomphe::Arc;
1415

1516
use crate::{
1617
attr::Attrs, db::DefDatabase, lower::LowerCtx, path::Path, AsMacroCall, MacroId, ModuleId,
@@ -19,9 +20,8 @@ use crate::{
1920

2021
#[derive(Debug)]
2122
pub struct Expander {
22-
cfg_options: CfgOptions,
23+
cfg_options: Arc<CfgOptions>,
2324
span_map: OnceCell<SpanMap>,
24-
krate: CrateId,
2525
current_file_id: HirFileId,
2626
pub(crate) module: ModuleId,
2727
/// `recursion_depth == usize::MAX` indicates that the recursion limit has been reached.
@@ -45,10 +45,13 @@ impl Expander {
4545
recursion_limit,
4646
cfg_options: db.crate_graph()[module.krate].cfg_options.clone(),
4747
span_map: OnceCell::new(),
48-
krate: module.krate,
4948
}
5049
}
5150

51+
pub fn krate(&self) -> CrateId {
52+
self.module.krate
53+
}
54+
5255
pub fn enter_expand<T: ast::AstNode>(
5356
&mut self,
5457
db: &dyn DefDatabase,
@@ -112,7 +115,7 @@ impl Expander {
112115
pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
113116
Attrs::filter(
114117
db,
115-
self.krate,
118+
self.krate(),
116119
RawAttrs::new(
117120
db.upcast(),
118121
owner,

src/tools/rust-analyzer/crates/hir-def/src/generics.rs

+23-7
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
//! generic parameters. See also the `Generics` type and the `generics_of` query
44
//! in rustc.
55
6+
use std::ops;
7+
68
use either::Either;
79
use hir_expand::{
810
name::{AsName, Name},
911
ExpandResult,
1012
};
1113
use intern::Interned;
12-
use la_arena::{Arena, Idx};
14+
use la_arena::Arena;
1315
use once_cell::unsync::Lazy;
1416
use stdx::impl_from;
1517
use syntax::ast::{self, HasGenericParams, HasName, HasTypeBounds};
@@ -23,7 +25,7 @@ use crate::{
2325
nameres::{DefMap, MacroSubNs},
2426
type_ref::{ConstRef, LifetimeRef, TypeBound, TypeRef},
2527
AdtId, ConstParamId, GenericDefId, HasModule, ItemTreeLoc, LifetimeParamId,
26-
LocalTypeOrConstParamId, Lookup, TypeOrConstParamId, TypeParamId,
28+
LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup, TypeOrConstParamId, TypeParamId,
2729
};
2830

2931
/// Data about a generic type parameter (to a function, struct, impl, ...).
@@ -158,6 +160,20 @@ pub struct GenericParams {
158160
pub where_predicates: Box<[WherePredicate]>,
159161
}
160162

163+
impl ops::Index<LocalTypeOrConstParamId> for GenericParams {
164+
type Output = TypeOrConstParamData;
165+
fn index(&self, index: LocalTypeOrConstParamId) -> &TypeOrConstParamData {
166+
&self.type_or_consts[index]
167+
}
168+
}
169+
170+
impl ops::Index<LocalLifetimeParamId> for GenericParams {
171+
type Output = LifetimeParamData;
172+
fn index(&self, index: LocalLifetimeParamId) -> &LifetimeParamData {
173+
&self.lifetimes[index]
174+
}
175+
}
176+
161177
/// A single predicate from a where clause, i.e. `where Type: Trait`. Combined
162178
/// where clauses like `where T: Foo + Bar` are turned into multiple of these.
163179
/// It might still result in multiple actual predicates though, because of
@@ -199,7 +215,7 @@ impl GenericParamsCollector {
199215
lower_ctx: &LowerCtx<'_>,
200216
node: &dyn HasGenericParams,
201217
add_param_attrs: impl FnMut(
202-
Either<Idx<TypeOrConstParamData>, Idx<LifetimeParamData>>,
218+
Either<LocalTypeOrConstParamId, LocalLifetimeParamId>,
203219
ast::GenericParam,
204220
),
205221
) {
@@ -227,7 +243,7 @@ impl GenericParamsCollector {
227243
lower_ctx: &LowerCtx<'_>,
228244
params: ast::GenericParamList,
229245
mut add_param_attrs: impl FnMut(
230-
Either<Idx<TypeOrConstParamData>, Idx<LifetimeParamData>>,
246+
Either<LocalTypeOrConstParamId, LocalLifetimeParamId>,
231247
ast::GenericParam,
232248
),
233249
) {
@@ -416,16 +432,16 @@ impl GenericParams {
416432
}
417433

418434
/// Iterator of type_or_consts field
419-
pub fn iter(
435+
pub fn iter_type_or_consts(
420436
&self,
421-
) -> impl DoubleEndedIterator<Item = (Idx<TypeOrConstParamData>, &TypeOrConstParamData)> {
437+
) -> impl DoubleEndedIterator<Item = (LocalTypeOrConstParamId, &TypeOrConstParamData)> {
422438
self.type_or_consts.iter()
423439
}
424440

425441
/// Iterator of lifetimes field
426442
pub fn iter_lt(
427443
&self,
428-
) -> impl DoubleEndedIterator<Item = (Idx<LifetimeParamData>, &LifetimeParamData)> {
444+
) -> impl DoubleEndedIterator<Item = (LocalLifetimeParamId, &LifetimeParamData)> {
429445
self.lifetimes.iter()
430446
}
431447

src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs

+18-15
Original file line numberDiff line numberDiff line change
@@ -77,30 +77,32 @@ pub(crate) fn path_to_const(
7777
resolver: &Resolver,
7878
path: &Path,
7979
mode: ParamLoweringMode,
80-
args_lazy: impl FnOnce() -> Generics,
80+
args: impl FnOnce() -> Option<Generics>,
8181
debruijn: DebruijnIndex,
8282
expected_ty: Ty,
8383
) -> Option<Const> {
8484
match resolver.resolve_path_in_value_ns_fully(db.upcast(), path) {
8585
Some(ValueNs::GenericParam(p)) => {
8686
let ty = db.const_param_ty(p);
87-
let args = args_lazy();
8887
let value = match mode {
8988
ParamLoweringMode::Placeholder => {
9089
ConstValue::Placeholder(to_placeholder_idx(db, p.into()))
9190
}
92-
ParamLoweringMode::Variable => match args.param_idx(p.into()) {
93-
Some(it) => ConstValue::BoundVar(BoundVar::new(debruijn, it)),
94-
None => {
95-
never!(
96-
"Generic list doesn't contain this param: {:?}, {:?}, {:?}",
97-
args,
98-
path,
99-
p
100-
);
101-
return None;
91+
ParamLoweringMode::Variable => {
92+
let args = args();
93+
match args.as_ref().and_then(|args| args.type_or_const_param_idx(p.into())) {
94+
Some(it) => ConstValue::BoundVar(BoundVar::new(debruijn, it)),
95+
None => {
96+
never!(
97+
"Generic list doesn't contain this param: {:?}, {:?}, {:?}",
98+
args,
99+
path,
100+
p
101+
);
102+
return None;
103+
}
102104
}
103-
},
105+
}
104106
};
105107
Some(ConstData { ty, value }.intern(Interner))
106108
}
@@ -285,7 +287,6 @@ pub(crate) fn eval_to_const(
285287
expr: ExprId,
286288
mode: ParamLoweringMode,
287289
ctx: &mut InferenceContext<'_>,
288-
args: impl FnOnce() -> Generics,
289290
debruijn: DebruijnIndex,
290291
) -> Const {
291292
let db = ctx.db;
@@ -304,7 +305,9 @@ pub(crate) fn eval_to_const(
304305
}
305306
if let Expr::Path(p) = &ctx.body.exprs[expr] {
306307
let resolver = &ctx.resolver;
307-
if let Some(c) = path_to_const(db, resolver, p, mode, args, debruijn, infer[expr].clone()) {
308+
if let Some(c) =
309+
path_to_const(db, resolver, p, mode, || ctx.generics(), debruijn, infer[expr].clone())
310+
{
308311
return c;
309312
}
310313
}

src/tools/rust-analyzer/crates/hir-ty/src/display.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -453,7 +453,7 @@ impl HirDisplay for Const {
453453
ConstValue::Placeholder(idx) => {
454454
let id = from_placeholder_idx(f.db, *idx);
455455
let generics = generics(f.db.upcast(), id.parent);
456-
let param_data = &generics.params.type_or_consts[id.local_id];
456+
let param_data = &generics.params[id.local_id];
457457
write!(f, "{}", param_data.name().unwrap().display(f.db.upcast()))?;
458458
Ok(())
459459
}
@@ -1176,7 +1176,7 @@ impl HirDisplay for Ty {
11761176
TyKind::Placeholder(idx) => {
11771177
let id = from_placeholder_idx(db, *idx);
11781178
let generics = generics(db.upcast(), id.parent);
1179-
let param_data = &generics.params.type_or_consts[id.local_id];
1179+
let param_data = &generics.params[id.local_id];
11801180
match param_data {
11811181
TypeOrConstParamData::TypeParamData(p) => match p.provenance {
11821182
TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
@@ -1724,7 +1724,7 @@ impl HirDisplay for LifetimeData {
17241724
LifetimeData::Placeholder(idx) => {
17251725
let id = lt_from_placeholder_idx(f.db, *idx);
17261726
let generics = generics(f.db.upcast(), id.parent);
1727-
let param_data = &generics.params.lifetimes[id.local_id];
1727+
let param_data = &generics.params[id.local_id];
17281728
write!(f, "{}", param_data.name.display(f.db.upcast()))?;
17291729
Ok(())
17301730
}

src/tools/rust-analyzer/crates/hir-ty/src/infer.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ use crate::{
6060
lower::ImplTraitLoweringMode,
6161
to_assoc_type_id,
6262
traits::FnTrait,
63-
utils::{InTypeConstIdMetadata, UnevaluatedConstEvaluatorFolder},
63+
utils::{Generics, InTypeConstIdMetadata, UnevaluatedConstEvaluatorFolder},
6464
AliasEq, AliasTy, Binders, ClosureId, Const, DomainGoal, GenericArg, Goal, ImplTraitId,
6565
ImplTraitIdx, InEnvironment, Interner, Lifetime, OpaqueTyId, ProjectionTy, Substitution,
6666
TraitEnvironment, Ty, TyBuilder, TyExt,
@@ -630,6 +630,10 @@ impl<'a> InferenceContext<'a> {
630630
}
631631
}
632632

633+
pub(crate) fn generics(&self) -> Option<Generics> {
634+
Some(crate::utils::generics(self.db.upcast(), self.resolver.generic_def()?))
635+
}
636+
633637
// FIXME: This function should be private in module. It is currently only used in the consteval, since we need
634638
// `InferenceResult` in the middle of inference. See the fixme comment in `consteval::eval_to_const`. If you
635639
// used this function for another workaround, mention it here. If you really need this function and believe that

src/tools/rust-analyzer/crates/hir-ty/src/infer/cast.rs

-4
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,6 @@ impl CastCheck {
1919
let expr_ty = table.resolve_ty_shallow(&self.expr_ty);
2020
let cast_ty = table.resolve_ty_shallow(&self.cast_ty);
2121

22-
if expr_ty.contains_unknown() || cast_ty.contains_unknown() {
23-
return;
24-
}
25-
2622
if table.coerce(&expr_ty, &cast_ty).is_ok() {
2723
return;
2824
}

src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs

+8-12
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use crate::{
2626
mir::{BorrowKind, MirSpan, MutBorrowKind, ProjectionElem},
2727
to_chalk_trait_id,
2828
traits::FnTrait,
29-
utils::{self, elaborate_clause_supertraits, generics, Generics},
29+
utils::{self, elaborate_clause_supertraits, Generics},
3030
Adjust, Adjustment, AliasEq, AliasTy, Binders, BindingMode, ChalkTraitId, ClosureId, DynTy,
3131
DynTyExt, FnAbi, FnPointer, FnSig, Interner, OpaqueTy, ProjectionTyExt, Substitution, Ty,
3232
TyExt, WhereClause,
@@ -331,14 +331,10 @@ impl CapturedItemWithoutTy {
331331
place: self.place,
332332
kind: self.kind,
333333
span: self.span,
334-
ty: replace_placeholder_with_binder(ctx.db, ctx.owner, ty),
334+
ty: replace_placeholder_with_binder(ctx, ty),
335335
};
336336

337-
fn replace_placeholder_with_binder(
338-
db: &dyn HirDatabase,
339-
owner: DefWithBodyId,
340-
ty: Ty,
341-
) -> Binders<Ty> {
337+
fn replace_placeholder_with_binder(ctx: &mut InferenceContext<'_>, ty: Ty) -> Binders<Ty> {
342338
struct Filler<'a> {
343339
db: &'a dyn HirDatabase,
344340
generics: Generics,
@@ -361,7 +357,7 @@ impl CapturedItemWithoutTy {
361357
outer_binder: DebruijnIndex,
362358
) -> Result<chalk_ir::Const<Interner>, Self::Error> {
363359
let x = from_placeholder_idx(self.db, idx);
364-
let Some(idx) = self.generics.param_idx(x) else {
360+
let Some(idx) = self.generics.type_or_const_param_idx(x) else {
365361
return Err(());
366362
};
367363
Ok(BoundVar::new(outer_binder, idx).to_const(Interner, ty))
@@ -373,18 +369,18 @@ impl CapturedItemWithoutTy {
373369
outer_binder: DebruijnIndex,
374370
) -> std::result::Result<Ty, Self::Error> {
375371
let x = from_placeholder_idx(self.db, idx);
376-
let Some(idx) = self.generics.param_idx(x) else {
372+
let Some(idx) = self.generics.type_or_const_param_idx(x) else {
377373
return Err(());
378374
};
379375
Ok(BoundVar::new(outer_binder, idx).to_ty(Interner))
380376
}
381377
}
382-
let Some(generic_def) = owner.as_generic_def_id() else {
378+
let Some(generics) = ctx.generics() else {
383379
return Binders::empty(Interner, ty);
384380
};
385-
let filler = &mut Filler { db, generics: generics(db.upcast(), generic_def) };
381+
let filler = &mut Filler { db: ctx.db, generics };
386382
let result = ty.clone().try_fold_with(filler, DebruijnIndex::INNERMOST).unwrap_or(ty);
387-
make_binders(db, &filler.generics, result)
383+
make_binders(ctx.db, &filler.generics, result)
388384
}
389385
}
390386
}

0 commit comments

Comments
 (0)