Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle #[cfg]s on generic parameters #15350

Merged
merged 4 commits into from
Aug 8, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 18 additions & 1 deletion crates/hir-def/src/generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use crate::{
db::DefDatabase,
dyn_map::{keys, DynMap},
expander::Expander,
item_tree::ItemTree,
lower::LowerCtx,
nameres::{DefMap, MacroSubNs},
src::{HasChildSource, HasSource},
Expand Down Expand Up @@ -154,12 +155,28 @@ impl GenericParams {
def: GenericDefId,
) -> Interned<GenericParams> {
let _p = profile::span("generic_params_query");

let krate = def.module(db).krate;
let cfg_options = db.crate_graph();
let cfg_options = &cfg_options[krate].cfg_options;
let enabled_params = |params: &GenericParams, item_tree: &ItemTree| {
let enabled = |param| item_tree.attrs(db, krate, param).is_cfg_enabled(cfg_options);
Interned::new(GenericParams {
type_or_consts: (params.type_or_consts.iter())
.filter_map(|(idx, param)| enabled(idx.into()).then(|| param.clone()))
.collect(),
lifetimes: (params.lifetimes.iter())
.filter_map(|(idx, param)| enabled(idx.into()).then(|| param.clone()))
.collect(),
where_predicates: params.where_predicates.clone(),
})
max-heller marked this conversation as resolved.
Show resolved Hide resolved
};
macro_rules! id_to_generics {
($id:ident) => {{
let id = $id.lookup(db).id;
let tree = id.item_tree(db);
let item = &tree[id.value];
item.generic_params.clone()
enabled_params(&item.generic_params, &tree)
}};
}

Expand Down
15 changes: 12 additions & 3 deletions crates/hir-def/src/item_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ use triomphe::Arc;
use crate::{
attr::Attrs,
db::DefDatabase,
generics::GenericParams,
generics::{GenericParams, LifetimeParamData, TypeOrConstParamData},
path::{path, AssociatedTypeBinding, GenericArgs, ImportAlias, ModPath, Path, PathKind},
type_ref::{Mutability, TraitRef, TypeBound, TypeRef},
visibility::RawVisibility,
Expand Down Expand Up @@ -296,10 +296,12 @@ pub enum AttrOwner {
Variant(Idx<Variant>),
Field(Idx<Field>),
Param(Idx<Param>),
TypeOrConstParamData(Idx<TypeOrConstParamData>),
LifetimeParamData(Idx<LifetimeParamData>),
}

macro_rules! from_attrs {
( $( $var:ident($t:ty) ),+ ) => {
( $( $var:ident($t:ty) ),+ $(,)? ) => {
$(
impl From<$t> for AttrOwner {
fn from(t: $t) -> AttrOwner {
Expand All @@ -310,7 +312,14 @@ macro_rules! from_attrs {
};
}

from_attrs!(ModItem(ModItem), Variant(Idx<Variant>), Field(Idx<Field>), Param(Idx<Param>));
from_attrs!(
ModItem(ModItem),
Variant(Idx<Variant>),
Field(Idx<Field>),
Param(Idx<Param>),
TypeOrConstParamData(Idx<TypeOrConstParamData>),
LifetimeParamData(Idx<LifetimeParamData>),
);

/// Trait implemented by all item nodes in the item tree.
pub trait ItemTreeNode: Clone {
Expand Down
35 changes: 35 additions & 0 deletions crates/hir-def/src/item_tree/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,41 @@ impl<'a> Ctx<'a> {
generics.fill(&self.body_ctx, node);

generics.shrink_to_fit();

if let Some(params) = node.generic_param_list() {
let params_by_name: FxHashMap<_, _> = params
.generic_params()
.filter_map(|param| {
let name = match &param {
ast::GenericParam::ConstParam(param) => param.name()?.as_name(),
ast::GenericParam::LifetimeParam(param) => {
Name::new_lifetime(&param.lifetime()?)
}
ast::GenericParam::TypeParam(param) => param.name()?.as_name(),
};
Some((name, param))
})
.collect();
for (idx, param) in generics.type_or_consts.iter() {
if let Some(name) = param.name() {
if let Some(param) = params_by_name.get(name) {
self.add_attrs(
idx.into(),
RawAttrs::new(self.db.upcast(), param, self.hygiene()),
);
}
}
}
for (idx, param) in generics.lifetimes.iter() {
if let Some(param) = params_by_name.get(&param.name) {
self.add_attrs(
idx.into(),
RawAttrs::new(self.db.upcast(), param, self.hygiene()),
);
}
}
}
max-heller marked this conversation as resolved.
Show resolved Hide resolved

Interned::new(generics)
}

Expand Down
27 changes: 15 additions & 12 deletions crates/hir-def/src/item_tree/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub(super) fn print_item_tree(db: &dyn ExpandDatabase, tree: &ItemTree) -> Strin
let mut p = Printer { db, tree, buf: String::new(), indent_level: 0, needs_indent: true };

if let Some(attrs) = tree.attrs.get(&AttrOwner::TopLevel) {
p.print_attrs(attrs, true);
p.print_attrs(attrs, true, "\n");
}
p.blank();

Expand Down Expand Up @@ -84,22 +84,23 @@ impl Printer<'_> {
}
}

fn print_attrs(&mut self, attrs: &RawAttrs, inner: bool) {
fn print_attrs(&mut self, attrs: &RawAttrs, inner: bool, separated_by: &str) {
let inner = if inner { "!" } else { "" };
for attr in &**attrs {
wln!(
w!(
self,
"#{}[{}{}]",
"#{}[{}{}]{}",
inner,
attr.path.display(self.db),
attr.input.as_ref().map(|it| it.to_string()).unwrap_or_default(),
separated_by,
);
}
}

fn print_attrs_of(&mut self, of: impl Into<AttrOwner>) {
fn print_attrs_of(&mut self, of: impl Into<AttrOwner>, separated_by: &str) {
if let Some(attrs) = self.tree.attrs.get(&of.into()) {
self.print_attrs(attrs, false);
self.print_attrs(attrs, false, separated_by);
}
}

Expand All @@ -118,7 +119,7 @@ impl Printer<'_> {
self.indented(|this| {
for field in fields.clone() {
let Field { visibility, name, type_ref, ast_id: _ } = &this.tree[field];
this.print_attrs_of(field);
this.print_attrs_of(field, "\n");
this.print_visibility(*visibility);
w!(this, "{}: ", name.display(self.db));
this.print_type_ref(type_ref);
Expand All @@ -132,7 +133,7 @@ impl Printer<'_> {
self.indented(|this| {
for field in fields.clone() {
let Field { visibility, name, type_ref, ast_id: _ } = &this.tree[field];
this.print_attrs_of(field);
this.print_attrs_of(field, "\n");
this.print_visibility(*visibility);
w!(this, "{}: ", name.display(self.db));
this.print_type_ref(type_ref);
Expand Down Expand Up @@ -195,7 +196,7 @@ impl Printer<'_> {
}

fn print_mod_item(&mut self, item: ModItem) {
self.print_attrs_of(item);
self.print_attrs_of(item, "\n");

match item {
ModItem::Import(it) => {
Expand Down Expand Up @@ -261,7 +262,7 @@ impl Printer<'_> {
if !params.is_empty() {
self.indented(|this| {
for param in params.clone() {
this.print_attrs_of(param);
this.print_attrs_of(param, "\n");
match &this.tree[param] {
Param::Normal(ty) => {
if flags.contains(FnFlags::HAS_SELF_PARAM) {
Expand Down Expand Up @@ -319,7 +320,7 @@ impl Printer<'_> {
self.indented(|this| {
for variant in variants.clone() {
let Variant { name, fields, ast_id: _ } = &this.tree[variant];
this.print_attrs_of(variant);
this.print_attrs_of(variant, "\n");
w!(this, "{}", name.display(self.db));
this.print_fields(fields);
wln!(this, ",");
Expand Down Expand Up @@ -484,18 +485,20 @@ impl Printer<'_> {

w!(self, "<");
let mut first = true;
for (_, lt) in params.lifetimes.iter() {
for (idx, lt) in params.lifetimes.iter() {
if !first {
w!(self, ", ");
}
first = false;
self.print_attrs_of(idx, " ");
w!(self, "{}", lt.name.display(self.db));
}
for (idx, x) in params.type_or_consts.iter() {
if !first {
w!(self, ", ");
}
first = false;
self.print_attrs_of(idx, " ");
match x {
TypeOrConstParamData::TypeParamData(ty) => match &ty.name {
Some(name) => w!(self, "{}", name.display(self.db)),
Expand Down
12 changes: 12 additions & 0 deletions crates/hir-def/src/item_tree/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,3 +358,15 @@ trait Tr<'a, T: 'a>: Super where Self: for<'a> Tr<'a, T> {}
"#]],
)
}

#[test]
fn generics_with_attributes() {
check(
r#"
struct S<#[cfg(never)] T>;
"#,
expect![[r#"
pub(self) struct S<#[cfg(never)] T>;
"#]],
)
}
19 changes: 19 additions & 0 deletions crates/ide/src/hover/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6451,3 +6451,22 @@ fn test() {
"#]],
);
}

#[test]
fn generic_params_disabled_by_cfg() {
check(
r#"
struct S<#[cfg(never)] T>;
fn test() {
let s$0: S = S;
}
"#,
expect![[r#"
*s*

```rust
let s: S // size = 0, align = 1
```
"#]],
);
}