mirror of
https://github.com/rust-lang/rust-analyzer
synced 2024-12-27 05:23:24 +00:00
Split out hir-def attribute handling parts into hir-expand
This commit is contained in:
parent
d33fa38cc9
commit
68723043db
36 changed files with 435 additions and 382 deletions
13
Cargo.lock
generated
13
Cargo.lock
generated
|
@ -519,6 +519,7 @@ dependencies = [
|
|||
"hkalbasi-rustc-ap-rustc_abi",
|
||||
"hkalbasi-rustc-ap-rustc_index",
|
||||
"indexmap",
|
||||
"intern",
|
||||
"itertools",
|
||||
"la-arena",
|
||||
"limit",
|
||||
|
@ -544,6 +545,7 @@ dependencies = [
|
|||
"either",
|
||||
"expect-test",
|
||||
"hashbrown",
|
||||
"intern",
|
||||
"itertools",
|
||||
"la-arena",
|
||||
"limit",
|
||||
|
@ -574,6 +576,7 @@ dependencies = [
|
|||
"hir-def",
|
||||
"hir-expand",
|
||||
"hkalbasi-rustc-ap-rustc_index",
|
||||
"intern",
|
||||
"itertools",
|
||||
"la-arena",
|
||||
"limit",
|
||||
|
@ -803,6 +806,16 @@ dependencies = [
|
|||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "intern"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"dashmap",
|
||||
"hashbrown",
|
||||
"once_cell",
|
||||
"rustc-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.10.5"
|
||||
|
|
|
@ -29,6 +29,7 @@ smallvec = "1.10.0"
|
|||
tracing = "0.1.35"
|
||||
|
||||
stdx = { path = "../stdx", version = "0.0.0" }
|
||||
intern = { path = "../intern", version = "0.0.0" }
|
||||
base-db = { path = "../base-db", version = "0.0.0" }
|
||||
syntax = { path = "../syntax", version = "0.0.0" }
|
||||
profile = { path = "../profile", version = "0.0.0" }
|
||||
|
|
|
@ -8,6 +8,7 @@ use hir_expand::{
|
|||
name::{AsName, Name},
|
||||
HirFileId, InFile,
|
||||
};
|
||||
use intern::Interned;
|
||||
use la_arena::{Arena, ArenaMap};
|
||||
use rustc_abi::{Integer, IntegerType};
|
||||
use syntax::ast::{self, HasName, HasVisibility};
|
||||
|
@ -17,7 +18,6 @@ use crate::{
|
|||
body::{CfgExpander, LowerCtx},
|
||||
builtin_type::{BuiltinInt, BuiltinUint},
|
||||
db::DefDatabase,
|
||||
intern::Interned,
|
||||
item_tree::{AttrOwner, Field, FieldAstId, Fields, ItemTree, ModItem, RawVisibilityId},
|
||||
layout::{Align, ReprFlags, ReprOptions},
|
||||
nameres::diagnostics::DefDiagnostic,
|
||||
|
|
|
@ -1,27 +1,27 @@
|
|||
//! A higher level attributes based on TokenTree, with also some shortcuts.
|
||||
|
||||
use std::{fmt, hash::Hash, ops, sync::Arc};
|
||||
use std::{hash::Hash, ops, sync::Arc};
|
||||
|
||||
use base_db::CrateId;
|
||||
use cfg::{CfgExpr, CfgOptions};
|
||||
use either::Either;
|
||||
use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile};
|
||||
use hir_expand::{
|
||||
attrs::{collect_attrs, Attr, AttrId, RawAttrs},
|
||||
HirFileId, InFile,
|
||||
};
|
||||
use itertools::Itertools;
|
||||
use la_arena::{ArenaMap, Idx, RawIdx};
|
||||
use mbe::{syntax_node_to_token_tree, DelimiterKind, Punct};
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use mbe::DelimiterKind;
|
||||
use syntax::{
|
||||
ast::{self, AstNode, HasAttrs, IsString},
|
||||
match_ast, AstPtr, AstToken, SmolStr, SyntaxNode, TextRange, TextSize,
|
||||
ast::{self, HasAttrs, IsString},
|
||||
AstPtr, AstToken, SmolStr, TextRange, TextSize,
|
||||
};
|
||||
use tt::Subtree;
|
||||
|
||||
use crate::{
|
||||
db::DefDatabase,
|
||||
intern::Interned,
|
||||
item_tree::{AttrOwner, Fields, ItemTreeId, ItemTreeNode},
|
||||
nameres::{ModuleOrigin, ModuleSource},
|
||||
path::{ModPath, PathKind},
|
||||
src::{HasChildSource, HasSource},
|
||||
AdtId, AttrDefId, EnumId, GenericParamId, LocalEnumVariantId, LocalFieldId, Lookup, MacroId,
|
||||
VariantId,
|
||||
|
@ -47,12 +47,6 @@ impl From<Documentation> for String {
|
|||
}
|
||||
}
|
||||
|
||||
/// Syntactical attributes, without filtering of `cfg_attr`s.
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct RawAttrs {
|
||||
entries: Option<Arc<[Attr]>>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Attrs(RawAttrs);
|
||||
|
||||
|
@ -62,30 +56,21 @@ pub struct AttrsWithOwner {
|
|||
owner: AttrDefId,
|
||||
}
|
||||
|
||||
impl ops::Deref for RawAttrs {
|
||||
type Target = [Attr];
|
||||
|
||||
fn deref(&self) -> &[Attr] {
|
||||
match &self.entries {
|
||||
Some(it) => &*it,
|
||||
None => &[],
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Attrs {
|
||||
pub fn get(&self, id: AttrId) -> Option<&Attr> {
|
||||
(**self).iter().find(|attr| attr.id == id)
|
||||
}
|
||||
|
||||
pub(crate) fn filter(db: &dyn DefDatabase, krate: CrateId, raw_attrs: RawAttrs) -> Attrs {
|
||||
Attrs(raw_attrs.filter(db.upcast(), krate))
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Deref for Attrs {
|
||||
type Target = [Attr];
|
||||
|
||||
fn deref(&self) -> &[Attr] {
|
||||
match &self.0.entries {
|
||||
Some(it) => &*it,
|
||||
None => &[],
|
||||
}
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -97,114 +82,6 @@ impl ops::Deref for AttrsWithOwner {
|
|||
}
|
||||
}
|
||||
|
||||
impl RawAttrs {
|
||||
pub(crate) const EMPTY: Self = Self { entries: None };
|
||||
|
||||
pub(crate) fn new(db: &dyn DefDatabase, owner: &dyn ast::HasAttrs, hygiene: &Hygiene) -> Self {
|
||||
let entries = collect_attrs(owner)
|
||||
.filter_map(|(id, attr)| match attr {
|
||||
Either::Left(attr) => {
|
||||
attr.meta().and_then(|meta| Attr::from_src(db, meta, hygiene, id))
|
||||
}
|
||||
Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
|
||||
id,
|
||||
input: Some(Interned::new(AttrInput::Literal(SmolStr::new(doc)))),
|
||||
path: Interned::new(ModPath::from(hir_expand::name!(doc))),
|
||||
}),
|
||||
})
|
||||
.collect::<Arc<_>>();
|
||||
|
||||
Self { entries: if entries.is_empty() { None } else { Some(entries) } }
|
||||
}
|
||||
|
||||
fn from_attrs_owner(db: &dyn DefDatabase, owner: InFile<&dyn ast::HasAttrs>) -> Self {
|
||||
let hygiene = Hygiene::new(db.upcast(), owner.file_id);
|
||||
Self::new(db, owner.value, &hygiene)
|
||||
}
|
||||
|
||||
pub(crate) fn merge(&self, other: Self) -> Self {
|
||||
// FIXME: This needs to fixup `AttrId`s
|
||||
match (&self.entries, other.entries) {
|
||||
(None, None) => Self::EMPTY,
|
||||
(None, entries @ Some(_)) => Self { entries },
|
||||
(Some(entries), None) => Self { entries: Some(entries.clone()) },
|
||||
(Some(a), Some(b)) => {
|
||||
let last_ast_index = a.last().map_or(0, |it| it.id.ast_index + 1);
|
||||
Self {
|
||||
entries: Some(
|
||||
a.iter()
|
||||
.cloned()
|
||||
.chain(b.iter().map(|it| {
|
||||
let mut it = it.clone();
|
||||
it.id.ast_index += last_ast_index;
|
||||
it
|
||||
}))
|
||||
.collect(),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Processes `cfg_attr`s, returning the resulting semantic `Attrs`.
|
||||
pub(crate) fn filter(self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
|
||||
let has_cfg_attrs = self.iter().any(|attr| {
|
||||
attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr])
|
||||
});
|
||||
if !has_cfg_attrs {
|
||||
return Attrs(self);
|
||||
}
|
||||
|
||||
let crate_graph = db.crate_graph();
|
||||
let new_attrs = self
|
||||
.iter()
|
||||
.flat_map(|attr| -> SmallVec<[_; 1]> {
|
||||
let is_cfg_attr =
|
||||
attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr]);
|
||||
if !is_cfg_attr {
|
||||
return smallvec![attr.clone()];
|
||||
}
|
||||
|
||||
let subtree = match attr.token_tree_value() {
|
||||
Some(it) => it,
|
||||
_ => return smallvec![attr.clone()],
|
||||
};
|
||||
|
||||
// Input subtree is: `(cfg, $(attr),+)`
|
||||
// Split it up into a `cfg` subtree and the `attr` subtrees.
|
||||
// FIXME: There should be a common API for this.
|
||||
let mut parts = subtree.token_trees.split(|tt| {
|
||||
matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. })))
|
||||
});
|
||||
let cfg = match parts.next() {
|
||||
Some(it) => it,
|
||||
None => return smallvec![],
|
||||
};
|
||||
let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
|
||||
let cfg = CfgExpr::parse(&cfg);
|
||||
let index = attr.id;
|
||||
let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
|
||||
let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
|
||||
// FIXME hygiene
|
||||
let hygiene = Hygiene::new_unhygienic();
|
||||
Attr::from_tt(db, &tree, &hygiene, index)
|
||||
});
|
||||
|
||||
let cfg_options = &crate_graph[krate].cfg_options;
|
||||
if cfg_options.check(&cfg) == Some(false) {
|
||||
smallvec![]
|
||||
} else {
|
||||
cov_mark::hit!(cfg_attr_active);
|
||||
|
||||
attrs.collect()
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
Attrs(RawAttrs { entries: Some(new_attrs) })
|
||||
}
|
||||
}
|
||||
|
||||
impl Attrs {
|
||||
pub const EMPTY: Self = Self(RawAttrs::EMPTY);
|
||||
|
||||
|
@ -403,7 +280,7 @@ impl AttrsWithOwner {
|
|||
.raw_attrs(AttrOwner::ModItem(definition_tree_id.value.into()))
|
||||
.clone(),
|
||||
ModuleOrigin::BlockExpr { block } => RawAttrs::from_attrs_owner(
|
||||
db,
|
||||
db.upcast(),
|
||||
InFile::new(block.file_id, block.to_node(db.upcast()))
|
||||
.as_ref()
|
||||
.map(|it| it as &dyn ast::HasAttrs),
|
||||
|
@ -439,7 +316,7 @@ impl AttrsWithOwner {
|
|||
GenericParamId::ConstParamId(it) => {
|
||||
let src = it.parent().child_source(db);
|
||||
RawAttrs::from_attrs_owner(
|
||||
db,
|
||||
db.upcast(),
|
||||
src.with_value(src.value[it.local_id()].as_ref().either(
|
||||
|it| match it {
|
||||
ast::TypeOrConstParam::Type(it) => it as _,
|
||||
|
@ -452,7 +329,7 @@ impl AttrsWithOwner {
|
|||
GenericParamId::TypeParamId(it) => {
|
||||
let src = it.parent().child_source(db);
|
||||
RawAttrs::from_attrs_owner(
|
||||
db,
|
||||
db.upcast(),
|
||||
src.with_value(src.value[it.local_id()].as_ref().either(
|
||||
|it| match it {
|
||||
ast::TypeOrConstParam::Type(it) => it as _,
|
||||
|
@ -464,14 +341,14 @@ impl AttrsWithOwner {
|
|||
}
|
||||
GenericParamId::LifetimeParamId(it) => {
|
||||
let src = it.parent.child_source(db);
|
||||
RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
|
||||
RawAttrs::from_attrs_owner(db.upcast(), src.with_value(&src.value[it.local_id]))
|
||||
}
|
||||
},
|
||||
AttrDefId::ExternBlockId(it) => attrs_from_item_tree(it.lookup(db).id, db),
|
||||
};
|
||||
|
||||
let attrs = raw_attrs.filter(db, def.krate(db));
|
||||
Self { attrs, owner: def }
|
||||
let attrs = raw_attrs.filter(db.upcast(), def.krate(db));
|
||||
Self { attrs: Attrs(attrs), owner: def }
|
||||
}
|
||||
|
||||
pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
|
||||
|
@ -627,40 +504,6 @@ fn doc_indent(attrs: &Attrs) -> usize {
|
|||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn inner_attributes(
|
||||
syntax: &SyntaxNode,
|
||||
) -> Option<impl Iterator<Item = Either<ast::Attr, ast::Comment>>> {
|
||||
let node = match_ast! {
|
||||
match syntax {
|
||||
ast::SourceFile(_) => syntax.clone(),
|
||||
ast::ExternBlock(it) => it.extern_item_list()?.syntax().clone(),
|
||||
ast::Fn(it) => it.body()?.stmt_list()?.syntax().clone(),
|
||||
ast::Impl(it) => it.assoc_item_list()?.syntax().clone(),
|
||||
ast::Module(it) => it.item_list()?.syntax().clone(),
|
||||
ast::BlockExpr(it) => {
|
||||
use syntax::SyntaxKind::{BLOCK_EXPR , EXPR_STMT};
|
||||
// Block expressions accept outer and inner attributes, but only when they are the outer
|
||||
// expression of an expression statement or the final expression of another block expression.
|
||||
let may_carry_attributes = matches!(
|
||||
it.syntax().parent().map(|it| it.kind()),
|
||||
Some(BLOCK_EXPR | EXPR_STMT)
|
||||
);
|
||||
if !may_carry_attributes {
|
||||
return None
|
||||
}
|
||||
syntax.clone()
|
||||
},
|
||||
_ => return None,
|
||||
}
|
||||
};
|
||||
|
||||
let attrs = ast::AttrDocCommentIter::from_syntax_node(&node).filter(|el| match el {
|
||||
Either::Left(attr) => attr.kind().is_inner(),
|
||||
Either::Right(comment) => comment.is_inner(),
|
||||
});
|
||||
Some(attrs)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AttrSourceMap {
|
||||
source: Vec<Either<ast::Attr, ast::Comment>>,
|
||||
|
@ -779,128 +622,6 @@ fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct AttrId {
|
||||
pub(crate) ast_index: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Attr {
|
||||
pub(crate) id: AttrId,
|
||||
pub(crate) path: Interned<ModPath>,
|
||||
pub(crate) input: Option<Interned<AttrInput>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum AttrInput {
|
||||
/// `#[attr = "string"]`
|
||||
Literal(SmolStr),
|
||||
/// `#[attr(subtree)]`
|
||||
TokenTree(tt::Subtree, mbe::TokenMap),
|
||||
}
|
||||
|
||||
impl fmt::Display for AttrInput {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
|
||||
AttrInput::TokenTree(subtree, _) => subtree.fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Attr {
|
||||
fn from_src(
|
||||
db: &dyn DefDatabase,
|
||||
ast: ast::Meta,
|
||||
hygiene: &Hygiene,
|
||||
id: AttrId,
|
||||
) -> Option<Attr> {
|
||||
let path = Interned::new(ModPath::from_src(db.upcast(), ast.path()?, hygiene)?);
|
||||
let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
|
||||
let value = match lit.kind() {
|
||||
ast::LiteralKind::String(string) => string.value()?.into(),
|
||||
_ => lit.syntax().first_token()?.text().trim_matches('"').into(),
|
||||
};
|
||||
Some(Interned::new(AttrInput::Literal(value)))
|
||||
} else if let Some(tt) = ast.token_tree() {
|
||||
let (tree, map) = syntax_node_to_token_tree(tt.syntax());
|
||||
Some(Interned::new(AttrInput::TokenTree(tree, map)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(Attr { id, path, input })
|
||||
}
|
||||
|
||||
fn from_tt(
|
||||
db: &dyn DefDatabase,
|
||||
tt: &tt::Subtree,
|
||||
hygiene: &Hygiene,
|
||||
id: AttrId,
|
||||
) -> Option<Attr> {
|
||||
let (parse, _) = mbe::token_tree_to_syntax_node(tt, mbe::TopEntryPoint::MetaItem);
|
||||
let ast = ast::Meta::cast(parse.syntax_node())?;
|
||||
|
||||
Self::from_src(db, ast, hygiene, id)
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &ModPath {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl Attr {
|
||||
/// #[path = "string"]
|
||||
pub fn string_value(&self) -> Option<&SmolStr> {
|
||||
match self.input.as_deref()? {
|
||||
AttrInput::Literal(it) => Some(it),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// #[path(ident)]
|
||||
pub fn single_ident_value(&self) -> Option<&tt::Ident> {
|
||||
match self.input.as_deref()? {
|
||||
AttrInput::TokenTree(subtree, _) => match &*subtree.token_trees {
|
||||
[tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] => Some(ident),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// #[path TokenTree]
|
||||
pub fn token_tree_value(&self) -> Option<&Subtree> {
|
||||
match self.input.as_deref()? {
|
||||
AttrInput::TokenTree(subtree, _) => Some(subtree),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses this attribute as a token tree consisting of comma separated paths.
|
||||
pub fn parse_path_comma_token_tree(&self) -> Option<impl Iterator<Item = ModPath> + '_> {
|
||||
let args = self.token_tree_value()?;
|
||||
|
||||
if args.delimiter_kind() != Some(DelimiterKind::Parenthesis) {
|
||||
return None;
|
||||
}
|
||||
let paths = args
|
||||
.token_trees
|
||||
.split(|tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. }))))
|
||||
.filter_map(|tts| {
|
||||
if tts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let segments = tts.iter().filter_map(|tt| match tt {
|
||||
tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
|
||||
_ => None,
|
||||
});
|
||||
Some(ModPath::from_segments(PathKind::Plain, segments))
|
||||
});
|
||||
|
||||
Some(paths)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct AttrQuery<'attr> {
|
||||
attrs: &'attr Attrs,
|
||||
|
@ -953,21 +674,6 @@ fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase
|
|||
tree.raw_attrs(mod_item.into()).clone()
|
||||
}
|
||||
|
||||
fn collect_attrs(
|
||||
owner: &dyn ast::HasAttrs,
|
||||
) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
|
||||
let inner_attrs = inner_attributes(owner.syntax()).into_iter().flatten();
|
||||
let outer_attrs =
|
||||
ast::AttrDocCommentIter::from_syntax_node(owner.syntax()).filter(|el| match el {
|
||||
Either::Left(attr) => attr.kind().is_outer(),
|
||||
Either::Right(comment) => comment.is_outer(),
|
||||
});
|
||||
outer_attrs
|
||||
.chain(inner_attrs)
|
||||
.enumerate()
|
||||
.map(|(id, attr)| (AttrId { ast_index: id as u32 }, attr))
|
||||
}
|
||||
|
||||
pub(crate) fn variants_attrs_source_map(
|
||||
db: &dyn DefDatabase,
|
||||
def: EnumId,
|
||||
|
|
|
@ -12,7 +12,9 @@ use base_db::CrateId;
|
|||
use cfg::{CfgExpr, CfgOptions};
|
||||
use drop_bomb::DropBomb;
|
||||
use either::Either;
|
||||
use hir_expand::{hygiene::Hygiene, ExpandError, ExpandResult, HirFileId, InFile, MacroCallId};
|
||||
use hir_expand::{
|
||||
attrs::RawAttrs, hygiene::Hygiene, ExpandError, ExpandResult, HirFileId, InFile, MacroCallId,
|
||||
};
|
||||
use la_arena::{Arena, ArenaMap};
|
||||
use limit::Limit;
|
||||
use profile::Count;
|
||||
|
@ -20,7 +22,7 @@ use rustc_hash::FxHashMap;
|
|||
use syntax::{ast, AstPtr, SyntaxNodePtr};
|
||||
|
||||
use crate::{
|
||||
attr::{Attrs, RawAttrs},
|
||||
attr::Attrs,
|
||||
db::DefDatabase,
|
||||
expr::{dummy_expr_id, Expr, ExprId, Label, LabelId, Pat, PatId},
|
||||
item_scope::BuiltinShadowMode,
|
||||
|
@ -64,7 +66,7 @@ impl CfgExpander {
|
|||
}
|
||||
|
||||
pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
|
||||
RawAttrs::new(db, owner, &self.hygiene).filter(db, self.krate)
|
||||
Attrs::filter(db, self.krate, RawAttrs::new(db.upcast(), owner, &self.hygiene))
|
||||
}
|
||||
|
||||
pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> bool {
|
||||
|
|
|
@ -10,6 +10,7 @@ use hir_expand::{
|
|||
name::{name, AsName, Name},
|
||||
AstId, ExpandError, HirFileId, InFile,
|
||||
};
|
||||
use intern::Interned;
|
||||
use la_arena::Arena;
|
||||
use once_cell::unsync::OnceCell;
|
||||
use profile::Count;
|
||||
|
@ -33,7 +34,6 @@ use crate::{
|
|||
Label, LabelId, Literal, MatchArm, Movability, Pat, PatId, RecordFieldPat, RecordLitField,
|
||||
Statement,
|
||||
},
|
||||
intern::Interned,
|
||||
item_scope::BuiltinShadowMode,
|
||||
path::{GenericArgs, Path},
|
||||
type_ref::{Mutability, Rawness, TypeRef},
|
||||
|
|
|
@ -3,6 +3,7 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use hir_expand::{name::Name, AstId, ExpandResult, HirFileId, InFile, MacroCallId, MacroDefKind};
|
||||
use intern::Interned;
|
||||
use smallvec::SmallVec;
|
||||
use syntax::ast;
|
||||
|
||||
|
@ -10,7 +11,6 @@ use crate::{
|
|||
attr::Attrs,
|
||||
body::{Expander, Mark},
|
||||
db::DefDatabase,
|
||||
intern::Interned,
|
||||
item_tree::{self, AssocItem, FnFlags, ItemTree, ItemTreeId, ModItem, Param, TreeId},
|
||||
nameres::{
|
||||
attr_resolution::ResolvedAttr,
|
||||
|
|
|
@ -4,6 +4,7 @@ use std::sync::Arc;
|
|||
use base_db::{salsa, CrateId, SourceDatabase, Upcast};
|
||||
use either::Either;
|
||||
use hir_expand::{db::AstDatabase, HirFileId};
|
||||
use intern::Interned;
|
||||
use la_arena::ArenaMap;
|
||||
use syntax::{ast, AstPtr, SmolStr};
|
||||
|
||||
|
@ -17,7 +18,6 @@ use crate::{
|
|||
},
|
||||
generics::GenericParams,
|
||||
import_map::ImportMap,
|
||||
intern::Interned,
|
||||
item_tree::{AttrOwner, ItemTree},
|
||||
lang_item::{LangItemTarget, LangItems},
|
||||
nameres::{diagnostics::DefDiagnostic, DefMap},
|
||||
|
|
|
@ -15,11 +15,11 @@
|
|||
use std::fmt;
|
||||
|
||||
use hir_expand::name::Name;
|
||||
use intern::Interned;
|
||||
use la_arena::{Idx, RawIdx};
|
||||
|
||||
use crate::{
|
||||
builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
|
||||
intern::Interned,
|
||||
path::{GenericArgs, Path},
|
||||
type_ref::{Mutability, Rawness, TypeRef},
|
||||
BlockId,
|
||||
|
|
|
@ -9,6 +9,7 @@ use hir_expand::{
|
|||
name::{AsName, Name},
|
||||
ExpandResult, HirFileId, InFile,
|
||||
};
|
||||
use intern::Interned;
|
||||
use la_arena::{Arena, ArenaMap, Idx};
|
||||
use once_cell::unsync::Lazy;
|
||||
use std::ops::DerefMut;
|
||||
|
@ -20,7 +21,6 @@ use crate::{
|
|||
child_by_source::ChildBySource,
|
||||
db::DefDatabase,
|
||||
dyn_map::DynMap,
|
||||
intern::Interned,
|
||||
keys,
|
||||
src::{HasChildSource, HasSource},
|
||||
type_ref::{LifetimeRef, TypeBound, TypeRef},
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
use std::collections::hash_map::Entry;
|
||||
|
||||
use base_db::CrateId;
|
||||
use hir_expand::{name::Name, AstId, MacroCallId};
|
||||
use hir_expand::{attrs::AttrId, name::Name, AstId, MacroCallId};
|
||||
use itertools::Itertools;
|
||||
use once_cell::sync::Lazy;
|
||||
use profile::Count;
|
||||
|
@ -14,8 +14,8 @@ use stdx::format_to;
|
|||
use syntax::ast;
|
||||
|
||||
use crate::{
|
||||
attr::AttrId, db::DefDatabase, per_ns::PerNs, visibility::Visibility, AdtId, BuiltinType,
|
||||
ConstId, HasModule, ImplId, LocalModuleId, MacroId, ModuleDefId, ModuleId, TraitId,
|
||||
db::DefDatabase, per_ns::PerNs, visibility::Visibility, AdtId, BuiltinType, ConstId, HasModule,
|
||||
ImplId, LocalModuleId, MacroId, ModuleDefId, ModuleId, TraitId,
|
||||
};
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
|
|
|
@ -48,10 +48,12 @@ use base_db::CrateId;
|
|||
use either::Either;
|
||||
use hir_expand::{
|
||||
ast_id_map::FileAstId,
|
||||
attrs::RawAttrs,
|
||||
hygiene::Hygiene,
|
||||
name::{name, AsName, Name},
|
||||
ExpandTo, HirFileId, InFile,
|
||||
};
|
||||
use intern::Interned;
|
||||
use la_arena::{Arena, Idx, IdxRange, RawIdx};
|
||||
use profile::Count;
|
||||
use rustc_hash::FxHashMap;
|
||||
|
@ -60,10 +62,9 @@ use stdx::never;
|
|||
use syntax::{ast, match_ast, SyntaxKind};
|
||||
|
||||
use crate::{
|
||||
attr::{Attrs, RawAttrs},
|
||||
attr::Attrs,
|
||||
db::DefDatabase,
|
||||
generics::GenericParams,
|
||||
intern::Interned,
|
||||
path::{path, AssociatedTypeBinding, GenericArgs, ImportAlias, ModPath, Path, PathKind},
|
||||
type_ref::{Mutability, TraitRef, TypeBound, TypeRef},
|
||||
visibility::RawVisibility,
|
||||
|
@ -120,7 +121,7 @@ impl ItemTree {
|
|||
let mut item_tree = match_ast! {
|
||||
match syntax {
|
||||
ast::SourceFile(file) => {
|
||||
top_attrs = Some(RawAttrs::new(db, &file, ctx.hygiene()));
|
||||
top_attrs = Some(RawAttrs::new(db.upcast(), &file, ctx.hygiene()));
|
||||
ctx.lower_module_items(&file)
|
||||
},
|
||||
ast::MacroItems(items) => {
|
||||
|
@ -152,7 +153,11 @@ impl ItemTree {
|
|||
|
||||
/// Returns the inner attributes of the source file.
|
||||
pub fn top_level_attrs(&self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
|
||||
self.attrs.get(&AttrOwner::TopLevel).unwrap_or(&RawAttrs::EMPTY).clone().filter(db, krate)
|
||||
Attrs::filter(
|
||||
db,
|
||||
krate,
|
||||
self.attrs.get(&AttrOwner::TopLevel).unwrap_or(&RawAttrs::EMPTY).clone(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn raw_attrs(&self, of: AttrOwner) -> &RawAttrs {
|
||||
|
@ -160,7 +165,7 @@ impl ItemTree {
|
|||
}
|
||||
|
||||
pub(crate) fn attrs(&self, db: &dyn DefDatabase, krate: CrateId, of: AttrOwner) -> Attrs {
|
||||
self.raw_attrs(of).clone().filter(db, krate)
|
||||
Attrs::filter(db, krate, self.raw_attrs(of).clone())
|
||||
}
|
||||
|
||||
pub fn pretty_print(&self) -> String {
|
||||
|
|
|
@ -99,7 +99,7 @@ impl<'a> Ctx<'a> {
|
|||
}
|
||||
|
||||
fn lower_mod_item(&mut self, item: &ast::Item) -> Option<ModItem> {
|
||||
let attrs = RawAttrs::new(self.db, item, self.hygiene());
|
||||
let attrs = RawAttrs::new(self.db.upcast(), item, self.hygiene());
|
||||
let item: ModItem = match item {
|
||||
ast::Item::Struct(ast) => self.lower_struct(ast)?.into(),
|
||||
ast::Item::Union(ast) => self.lower_union(ast)?.into(),
|
||||
|
@ -173,7 +173,7 @@ impl<'a> Ctx<'a> {
|
|||
for field in fields.fields() {
|
||||
if let Some(data) = self.lower_record_field(&field) {
|
||||
let idx = self.data().fields.alloc(data);
|
||||
self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, self.hygiene()));
|
||||
self.add_attrs(idx.into(), RawAttrs::new(self.db.upcast(), &field, self.hygiene()));
|
||||
}
|
||||
}
|
||||
let end = self.next_field_idx();
|
||||
|
@ -194,7 +194,7 @@ impl<'a> Ctx<'a> {
|
|||
for (i, field) in fields.fields().enumerate() {
|
||||
let data = self.lower_tuple_field(i, &field);
|
||||
let idx = self.data().fields.alloc(data);
|
||||
self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, self.hygiene()));
|
||||
self.add_attrs(idx.into(), RawAttrs::new(self.db.upcast(), &field, self.hygiene()));
|
||||
}
|
||||
let end = self.next_field_idx();
|
||||
IdxRange::new(start..end)
|
||||
|
@ -239,7 +239,10 @@ impl<'a> Ctx<'a> {
|
|||
for variant in variants.variants() {
|
||||
if let Some(data) = self.lower_variant(&variant) {
|
||||
let idx = self.data().variants.alloc(data);
|
||||
self.add_attrs(idx.into(), RawAttrs::new(self.db, &variant, self.hygiene()));
|
||||
self.add_attrs(
|
||||
idx.into(),
|
||||
RawAttrs::new(self.db.upcast(), &variant, self.hygiene()),
|
||||
);
|
||||
}
|
||||
}
|
||||
let end = self.next_variant_idx();
|
||||
|
@ -283,7 +286,10 @@ impl<'a> Ctx<'a> {
|
|||
};
|
||||
let ty = Interned::new(self_type);
|
||||
let idx = self.data().params.alloc(Param::Normal(None, ty));
|
||||
self.add_attrs(idx.into(), RawAttrs::new(self.db, &self_param, self.hygiene()));
|
||||
self.add_attrs(
|
||||
idx.into(),
|
||||
RawAttrs::new(self.db.upcast(), &self_param, self.hygiene()),
|
||||
);
|
||||
has_self_param = true;
|
||||
}
|
||||
for param in param_list.params() {
|
||||
|
@ -307,7 +313,7 @@ impl<'a> Ctx<'a> {
|
|||
self.data().params.alloc(Param::Normal(name, ty))
|
||||
}
|
||||
};
|
||||
self.add_attrs(idx.into(), RawAttrs::new(self.db, ¶m, self.hygiene()));
|
||||
self.add_attrs(idx.into(), RawAttrs::new(self.db.upcast(), ¶m, self.hygiene()));
|
||||
}
|
||||
}
|
||||
let end_param = self.next_param_idx();
|
||||
|
@ -442,7 +448,7 @@ impl<'a> Ctx<'a> {
|
|||
let items = trait_def.assoc_item_list().map(|list| {
|
||||
list.assoc_items()
|
||||
.filter_map(|item| {
|
||||
let attrs = RawAttrs::new(self.db, &item, self.hygiene());
|
||||
let attrs = RawAttrs::new(self.db.upcast(), &item, self.hygiene());
|
||||
self.lower_assoc_item(&item).map(|item| {
|
||||
self.add_attrs(ModItem::from(item).into(), attrs);
|
||||
item
|
||||
|
@ -471,7 +477,7 @@ impl<'a> Ctx<'a> {
|
|||
.flat_map(|it| it.assoc_items())
|
||||
.filter_map(|item| {
|
||||
let assoc = self.lower_assoc_item(&item)?;
|
||||
let attrs = RawAttrs::new(self.db, &item, self.hygiene());
|
||||
let attrs = RawAttrs::new(self.db.upcast(), &item, self.hygiene());
|
||||
self.add_attrs(ModItem::from(assoc).into(), attrs);
|
||||
Some(assoc)
|
||||
})
|
||||
|
@ -541,7 +547,7 @@ impl<'a> Ctx<'a> {
|
|||
// (in other words, the knowledge that they're in an extern block must not be used).
|
||||
// This is because an extern block can contain macros whose ItemTree's top-level items
|
||||
// should be considered to be in an extern block too.
|
||||
let attrs = RawAttrs::new(self.db, &item, self.hygiene());
|
||||
let attrs = RawAttrs::new(self.db.upcast(), &item, self.hygiene());
|
||||
let id: ModItem = match item {
|
||||
ast::ExternItem::Fn(ast) => self.lower_function(&ast)?.into(),
|
||||
ast::ExternItem::Static(ast) => self.lower_static(&ast)?.into(),
|
||||
|
|
|
@ -3,7 +3,6 @@
|
|||
use std::fmt::{self, Write};
|
||||
|
||||
use crate::{
|
||||
attr::RawAttrs,
|
||||
generics::{TypeOrConstParamData, WherePredicate, WherePredicateTypeTarget},
|
||||
pretty::{print_path, print_type_bounds, print_type_ref},
|
||||
visibility::RawVisibility,
|
||||
|
|
|
@ -2,12 +2,11 @@
|
|||
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use hir_expand::MacroCallId;
|
||||
use hir_expand::{attrs::AttrId, MacroCallId};
|
||||
use rustc_hash::FxHashMap;
|
||||
use syntax::{ast, AstNode, AstPtr};
|
||||
|
||||
use crate::{
|
||||
attr::AttrId,
|
||||
dyn_map::{DynMap, Policy},
|
||||
ConstId, EnumId, EnumVariantId, FieldId, FunctionId, ImplId, LifetimeParamId, Macro2Id,
|
||||
MacroRulesId, ProcMacroId, StaticId, StructId, TraitId, TypeAliasId, TypeOrConstParamId,
|
||||
|
|
|
@ -28,7 +28,6 @@ pub mod dyn_map;
|
|||
pub mod keys;
|
||||
|
||||
pub mod item_tree;
|
||||
pub mod intern;
|
||||
|
||||
pub mod adt;
|
||||
pub mod data;
|
||||
|
@ -61,10 +60,10 @@ use std::{
|
|||
sync::Arc,
|
||||
};
|
||||
|
||||
use attr::Attr;
|
||||
use base_db::{impl_intern_key, salsa, CrateId, ProcMacroKind};
|
||||
use hir_expand::{
|
||||
ast_id_map::FileAstId,
|
||||
attrs::{Attr, AttrId, AttrInput},
|
||||
builtin_attr_macro::BuiltinAttrExpander,
|
||||
builtin_derive_macro::BuiltinDeriveExpander,
|
||||
builtin_fn_macro::{BuiltinFnLikeExpander, EagerExpander},
|
||||
|
@ -82,7 +81,6 @@ use syntax::ast;
|
|||
|
||||
use crate::{
|
||||
adt::VariantData,
|
||||
attr::AttrId,
|
||||
builtin_type::BuiltinType,
|
||||
item_tree::{
|
||||
Const, Enum, Function, Impl, ItemTreeId, ItemTreeNode, MacroDef, MacroRules, ModItem,
|
||||
|
@ -971,7 +969,7 @@ fn attr_macro_as_call_id(
|
|||
is_derive: bool,
|
||||
) -> MacroCallId {
|
||||
let mut arg = match macro_attr.input.as_deref() {
|
||||
Some(attr::AttrInput::TokenTree(tt, map)) => (tt.clone(), map.clone()),
|
||||
Some(AttrInput::TokenTree(tt, map)) => (tt.clone(), map.clone()),
|
||||
_ => Default::default(),
|
||||
};
|
||||
|
||||
|
@ -990,3 +988,10 @@ fn attr_macro_as_call_id(
|
|||
);
|
||||
res
|
||||
}
|
||||
intern::impl_internable!(
|
||||
crate::type_ref::TypeRef,
|
||||
crate::type_ref::TraitRef,
|
||||
crate::type_ref::TypeBound,
|
||||
crate::path::GenericArgs,
|
||||
generics::GenericParams,
|
||||
);
|
||||
|
|
|
@ -1,10 +1,9 @@
|
|||
//! Post-nameres attribute resolution.
|
||||
|
||||
use hir_expand::MacroCallId;
|
||||
use hir_expand::{attrs::Attr, MacroCallId};
|
||||
use syntax::{ast, SmolStr};
|
||||
|
||||
use crate::{
|
||||
attr::Attr,
|
||||
attr_macro_as_call_id, builtin_attr,
|
||||
db::DefDatabase,
|
||||
item_scope::BuiltinShadowMode,
|
||||
|
|
|
@ -10,6 +10,7 @@ use cfg::{CfgExpr, CfgOptions};
|
|||
use either::Either;
|
||||
use hir_expand::{
|
||||
ast_id_map::FileAstId,
|
||||
attrs::{Attr, AttrId},
|
||||
builtin_attr_macro::find_builtin_attr,
|
||||
builtin_derive_macro::find_builtin_derive,
|
||||
builtin_fn_macro::find_builtin_macro,
|
||||
|
@ -26,7 +27,7 @@ use stdx::always;
|
|||
use syntax::{ast, SmolStr};
|
||||
|
||||
use crate::{
|
||||
attr::{Attr, AttrId, Attrs},
|
||||
attr::Attrs,
|
||||
attr_macro_as_call_id,
|
||||
db::DefDatabase,
|
||||
derive_macro_as_call_id,
|
||||
|
|
|
@ -2,12 +2,11 @@
|
|||
|
||||
use base_db::CrateId;
|
||||
use cfg::{CfgExpr, CfgOptions};
|
||||
use hir_expand::MacroCallKind;
|
||||
use hir_expand::{attrs::AttrId, MacroCallKind};
|
||||
use la_arena::Idx;
|
||||
use syntax::ast::{self, AnyHasAttrs};
|
||||
|
||||
use crate::{
|
||||
attr::AttrId,
|
||||
item_tree::{self, ItemTreeId},
|
||||
nameres::LocalModuleId,
|
||||
path::ModPath,
|
||||
|
|
|
@ -8,10 +8,10 @@ use std::{
|
|||
|
||||
use crate::{
|
||||
body::LowerCtx,
|
||||
intern::Interned,
|
||||
type_ref::{ConstScalarOrPath, LifetimeRef},
|
||||
};
|
||||
use hir_expand::name::Name;
|
||||
use intern::Interned;
|
||||
use syntax::ast;
|
||||
|
||||
use crate::type_ref::{TypeBound, TypeRef};
|
||||
|
|
|
@ -1,9 +1,10 @@
|
|||
//! Transforms syntax into `Path` objects, ideally with accounting for hygiene
|
||||
|
||||
use crate::{intern::Interned, type_ref::ConstScalarOrPath};
|
||||
use crate::type_ref::ConstScalarOrPath;
|
||||
|
||||
use either::Either;
|
||||
use hir_expand::name::{name, AsName};
|
||||
use intern::Interned;
|
||||
use syntax::ast::{self, AstNode, HasTypeBounds};
|
||||
|
||||
use super::AssociatedTypeBinding;
|
||||
|
|
|
@ -3,10 +3,10 @@
|
|||
use std::fmt::{self, Write};
|
||||
|
||||
use hir_expand::mod_path::PathKind;
|
||||
use intern::Interned;
|
||||
use itertools::Itertools;
|
||||
|
||||
use crate::{
|
||||
intern::Interned,
|
||||
path::{GenericArg, GenericArgs, Path},
|
||||
type_ref::{Mutability, TraitBoundModifier, TypeBound, TypeRef},
|
||||
};
|
||||
|
|
|
@ -4,6 +4,7 @@ use std::{hash::BuildHasherDefault, sync::Arc};
|
|||
use base_db::CrateId;
|
||||
use hir_expand::name::{name, Name};
|
||||
use indexmap::IndexMap;
|
||||
use intern::Interned;
|
||||
use rustc_hash::FxHashSet;
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
|
||||
|
@ -13,7 +14,6 @@ use crate::{
|
|||
db::DefDatabase,
|
||||
expr::{ExprId, LabelId, PatId},
|
||||
generics::{GenericParams, TypeOrConstParamData},
|
||||
intern::Interned,
|
||||
item_scope::{BuiltinShadowMode, BUILTIN_SCOPE},
|
||||
nameres::DefMap,
|
||||
path::{ModPath, PathKind},
|
||||
|
|
|
@ -7,13 +7,13 @@ use hir_expand::{
|
|||
name::{AsName, Name},
|
||||
AstId,
|
||||
};
|
||||
use intern::Interned;
|
||||
use syntax::ast::{self, HasName};
|
||||
|
||||
use crate::{
|
||||
body::LowerCtx,
|
||||
builtin_type::{BuiltinInt, BuiltinType, BuiltinUint},
|
||||
expr::Literal,
|
||||
intern::Interned,
|
||||
path::Path,
|
||||
};
|
||||
|
||||
|
|
|
@ -22,6 +22,7 @@ hashbrown = { version = "0.12.1", features = [
|
|||
smallvec = { version = "1.10.0", features = ["const_new"] }
|
||||
|
||||
stdx = { path = "../stdx", version = "0.0.0" }
|
||||
intern = { path = "../intern", version = "0.0.0" }
|
||||
base-db = { path = "../base-db", version = "0.0.0" }
|
||||
cfg = { path = "../cfg", version = "0.0.0" }
|
||||
syntax = { path = "../syntax", version = "0.0.0" }
|
||||
|
|
313
crates/hir-expand/src/attrs.rs
Normal file
313
crates/hir-expand/src/attrs.rs
Normal file
|
@ -0,0 +1,313 @@
|
|||
use std::{fmt, ops, sync::Arc};
|
||||
|
||||
use base_db::CrateId;
|
||||
use cfg::CfgExpr;
|
||||
use either::Either;
|
||||
use intern::Interned;
|
||||
use mbe::{syntax_node_to_token_tree, DelimiterKind, Punct};
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use syntax::{ast, match_ast, AstNode, SmolStr, SyntaxNode};
|
||||
use tt::Subtree;
|
||||
|
||||
use crate::{
|
||||
db::AstDatabase,
|
||||
hygiene::Hygiene,
|
||||
mod_path::{ModPath, PathKind},
|
||||
name::AsName,
|
||||
InFile,
|
||||
};
|
||||
|
||||
/// Syntactical attributes, without filtering of `cfg_attr`s.
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RawAttrs {
|
||||
entries: Option<Arc<[Attr]>>,
|
||||
}
|
||||
|
||||
impl ops::Deref for RawAttrs {
|
||||
type Target = [Attr];
|
||||
|
||||
fn deref(&self) -> &[Attr] {
|
||||
match &self.entries {
|
||||
Some(it) => &*it,
|
||||
None => &[],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RawAttrs {
|
||||
pub const EMPTY: Self = Self { entries: None };
|
||||
|
||||
pub fn new(db: &dyn AstDatabase, owner: &dyn ast::HasAttrs, hygiene: &Hygiene) -> Self {
|
||||
let entries = collect_attrs(owner)
|
||||
.filter_map(|(id, attr)| match attr {
|
||||
Either::Left(attr) => {
|
||||
attr.meta().and_then(|meta| Attr::from_src(db, meta, hygiene, id))
|
||||
}
|
||||
Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
|
||||
id,
|
||||
input: Some(Interned::new(AttrInput::Literal(SmolStr::new(doc)))),
|
||||
path: Interned::new(ModPath::from(crate::name!(doc))),
|
||||
}),
|
||||
})
|
||||
.collect::<Arc<_>>();
|
||||
|
||||
Self { entries: if entries.is_empty() { None } else { Some(entries) } }
|
||||
}
|
||||
|
||||
pub fn from_attrs_owner(db: &dyn AstDatabase, owner: InFile<&dyn ast::HasAttrs>) -> Self {
|
||||
let hygiene = Hygiene::new(db, owner.file_id);
|
||||
Self::new(db, owner.value, &hygiene)
|
||||
}
|
||||
|
||||
pub fn merge(&self, other: Self) -> Self {
|
||||
match (&self.entries, other.entries) {
|
||||
(None, None) => Self::EMPTY,
|
||||
(None, entries @ Some(_)) => Self { entries },
|
||||
(Some(entries), None) => Self { entries: Some(entries.clone()) },
|
||||
(Some(a), Some(b)) => {
|
||||
let last_ast_index = a.last().map_or(0, |it| it.id.ast_index + 1);
|
||||
Self {
|
||||
entries: Some(
|
||||
a.iter()
|
||||
.cloned()
|
||||
.chain(b.iter().map(|it| {
|
||||
let mut it = it.clone();
|
||||
it.id.ast_index += last_ast_index;
|
||||
it
|
||||
}))
|
||||
.collect(),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Processes `cfg_attr`s, returning the resulting semantic `Attrs`.
|
||||
pub fn filter(self, db: &dyn AstDatabase, krate: CrateId) -> RawAttrs {
|
||||
let has_cfg_attrs = self
|
||||
.iter()
|
||||
.any(|attr| attr.path.as_ident().map_or(false, |name| *name == crate::name![cfg_attr]));
|
||||
if !has_cfg_attrs {
|
||||
return self;
|
||||
}
|
||||
|
||||
let crate_graph = db.crate_graph();
|
||||
let new_attrs = self
|
||||
.iter()
|
||||
.flat_map(|attr| -> SmallVec<[_; 1]> {
|
||||
let is_cfg_attr =
|
||||
attr.path.as_ident().map_or(false, |name| *name == crate::name![cfg_attr]);
|
||||
if !is_cfg_attr {
|
||||
return smallvec![attr.clone()];
|
||||
}
|
||||
|
||||
let subtree = match attr.token_tree_value() {
|
||||
Some(it) => it,
|
||||
_ => return smallvec![attr.clone()],
|
||||
};
|
||||
|
||||
// Input subtree is: `(cfg, $(attr),+)`
|
||||
// Split it up into a `cfg` subtree and the `attr` subtrees.
|
||||
// FIXME: There should be a common API for this.
|
||||
let mut parts = subtree.token_trees.split(|tt| {
|
||||
matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. })))
|
||||
});
|
||||
let cfg = match parts.next() {
|
||||
Some(it) => it,
|
||||
None => return smallvec![],
|
||||
};
|
||||
let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
|
||||
let cfg = CfgExpr::parse(&cfg);
|
||||
let index = attr.id;
|
||||
let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
|
||||
let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
|
||||
// FIXME hygiene
|
||||
let hygiene = Hygiene::new_unhygienic();
|
||||
Attr::from_tt(db, &tree, &hygiene, index)
|
||||
});
|
||||
|
||||
let cfg_options = &crate_graph[krate].cfg_options;
|
||||
if cfg_options.check(&cfg) == Some(false) {
|
||||
smallvec![]
|
||||
} else {
|
||||
cov_mark::hit!(cfg_attr_active);
|
||||
|
||||
attrs.collect()
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
RawAttrs { entries: Some(new_attrs) }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct AttrId {
|
||||
pub ast_index: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Attr {
|
||||
pub id: AttrId,
|
||||
pub path: Interned<ModPath>,
|
||||
pub input: Option<Interned<AttrInput>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum AttrInput {
|
||||
/// `#[attr = "string"]`
|
||||
Literal(SmolStr),
|
||||
/// `#[attr(subtree)]`
|
||||
TokenTree(tt::Subtree, mbe::TokenMap),
|
||||
}
|
||||
|
||||
impl fmt::Display for AttrInput {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
|
||||
AttrInput::TokenTree(subtree, _) => subtree.fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Attr {
|
||||
fn from_src(
|
||||
db: &dyn AstDatabase,
|
||||
ast: ast::Meta,
|
||||
hygiene: &Hygiene,
|
||||
id: AttrId,
|
||||
) -> Option<Attr> {
|
||||
let path = Interned::new(ModPath::from_src(db, ast.path()?, hygiene)?);
|
||||
let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
|
||||
let value = match lit.kind() {
|
||||
ast::LiteralKind::String(string) => string.value()?.into(),
|
||||
_ => lit.syntax().first_token()?.text().trim_matches('"').into(),
|
||||
};
|
||||
Some(Interned::new(AttrInput::Literal(value)))
|
||||
} else if let Some(tt) = ast.token_tree() {
|
||||
let (tree, map) = syntax_node_to_token_tree(tt.syntax());
|
||||
Some(Interned::new(AttrInput::TokenTree(tree, map)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(Attr { id, path, input })
|
||||
}
|
||||
|
||||
fn from_tt(
|
||||
db: &dyn AstDatabase,
|
||||
tt: &tt::Subtree,
|
||||
hygiene: &Hygiene,
|
||||
id: AttrId,
|
||||
) -> Option<Attr> {
|
||||
let (parse, _) = mbe::token_tree_to_syntax_node(tt, mbe::TopEntryPoint::MetaItem);
|
||||
let ast = ast::Meta::cast(parse.syntax_node())?;
|
||||
|
||||
Self::from_src(db, ast, hygiene, id)
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &ModPath {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl Attr {
|
||||
/// #[path = "string"]
|
||||
pub fn string_value(&self) -> Option<&SmolStr> {
|
||||
match self.input.as_deref()? {
|
||||
AttrInput::Literal(it) => Some(it),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// #[path(ident)]
|
||||
pub fn single_ident_value(&self) -> Option<&tt::Ident> {
|
||||
match self.input.as_deref()? {
|
||||
AttrInput::TokenTree(subtree, _) => match &*subtree.token_trees {
|
||||
[tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] => Some(ident),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// #[path TokenTree]
|
||||
pub fn token_tree_value(&self) -> Option<&Subtree> {
|
||||
match self.input.as_deref()? {
|
||||
AttrInput::TokenTree(subtree, _) => Some(subtree),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses this attribute as a token tree consisting of comma separated paths.
|
||||
pub fn parse_path_comma_token_tree(&self) -> Option<impl Iterator<Item = ModPath> + '_> {
|
||||
let args = self.token_tree_value()?;
|
||||
|
||||
if args.delimiter_kind() != Some(DelimiterKind::Parenthesis) {
|
||||
return None;
|
||||
}
|
||||
let paths = args
|
||||
.token_trees
|
||||
.split(|tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. }))))
|
||||
.filter_map(|tts| {
|
||||
if tts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let segments = tts.iter().filter_map(|tt| match tt {
|
||||
tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
|
||||
_ => None,
|
||||
});
|
||||
Some(ModPath::from_segments(PathKind::Plain, segments))
|
||||
});
|
||||
|
||||
Some(paths)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn collect_attrs(
|
||||
owner: &dyn ast::HasAttrs,
|
||||
) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
|
||||
let inner_attrs = inner_attributes(owner.syntax()).into_iter().flatten();
|
||||
let outer_attrs =
|
||||
ast::AttrDocCommentIter::from_syntax_node(owner.syntax()).filter(|el| match el {
|
||||
Either::Left(attr) => attr.kind().is_outer(),
|
||||
Either::Right(comment) => comment.is_outer(),
|
||||
});
|
||||
outer_attrs
|
||||
.chain(inner_attrs)
|
||||
.enumerate()
|
||||
.map(|(id, attr)| (AttrId { ast_index: id as u32 }, attr))
|
||||
}
|
||||
|
||||
fn inner_attributes(
|
||||
syntax: &SyntaxNode,
|
||||
) -> Option<impl Iterator<Item = Either<ast::Attr, ast::Comment>>> {
|
||||
let node = match_ast! {
|
||||
match syntax {
|
||||
ast::SourceFile(_) => syntax.clone(),
|
||||
ast::ExternBlock(it) => it.extern_item_list()?.syntax().clone(),
|
||||
ast::Fn(it) => it.body()?.stmt_list()?.syntax().clone(),
|
||||
ast::Impl(it) => it.assoc_item_list()?.syntax().clone(),
|
||||
ast::Module(it) => it.item_list()?.syntax().clone(),
|
||||
ast::BlockExpr(it) => {
|
||||
use syntax::SyntaxKind::{BLOCK_EXPR , EXPR_STMT};
|
||||
// Block expressions accept outer and inner attributes, but only when they are the outer
|
||||
// expression of an expression statement or the final expression of another block expression.
|
||||
let may_carry_attributes = matches!(
|
||||
it.syntax().parent().map(|it| it.kind()),
|
||||
Some(BLOCK_EXPR | EXPR_STMT)
|
||||
);
|
||||
if !may_carry_attributes {
|
||||
return None
|
||||
}
|
||||
syntax.clone()
|
||||
},
|
||||
_ => return None,
|
||||
}
|
||||
};
|
||||
|
||||
let attrs = ast::AttrDocCommentIter::from_syntax_node(&node).filter(|el| match el {
|
||||
Either::Left(attr) => attr.kind().is_inner(),
|
||||
Either::Right(comment) => comment.is_inner(),
|
||||
});
|
||||
Some(attrs)
|
||||
}
|
|
@ -17,6 +17,7 @@ pub mod proc_macro;
|
|||
pub mod quote;
|
||||
pub mod eager;
|
||||
pub mod mod_path;
|
||||
pub mod attrs;
|
||||
mod fixup;
|
||||
|
||||
pub use mbe::{Origin, ValueResult};
|
||||
|
@ -1031,3 +1032,5 @@ impl ExpandTo {
|
|||
pub struct UnresolvedMacro {
|
||||
pub path: ModPath,
|
||||
}
|
||||
|
||||
intern::impl_internable!(ModPath, attrs::AttrInput);
|
||||
|
|
|
@ -29,6 +29,7 @@ typed-arena = "2.0.1"
|
|||
rustc_index = { version = "0.0.20221221", package = "hkalbasi-rustc-ap-rustc_index", default-features = false }
|
||||
|
||||
stdx = { path = "../stdx", version = "0.0.0" }
|
||||
intern = { path = "../intern", version = "0.0.0" }
|
||||
hir-def = { path = "../hir-def", version = "0.0.0" }
|
||||
hir-expand = { path = "../hir-expand", version = "0.0.0" }
|
||||
base-db = { path = "../base-db", version = "0.0.0" }
|
||||
|
|
|
@ -11,7 +11,6 @@ use hir_def::{
|
|||
db::DefDatabase,
|
||||
find_path,
|
||||
generics::{TypeOrConstParamData, TypeParamProvenance},
|
||||
intern::{Internable, Interned},
|
||||
item_scope::ItemInNs,
|
||||
path::{Path, PathKind},
|
||||
type_ref::{ConstScalar, TraitBoundModifier, TypeBound, TypeRef},
|
||||
|
@ -19,6 +18,7 @@ use hir_def::{
|
|||
HasModule, ItemContainerId, Lookup, ModuleDefId, ModuleId, TraitId,
|
||||
};
|
||||
use hir_expand::{hygiene::Hygiene, name::Name};
|
||||
use intern::{Internable, Interned};
|
||||
use itertools::Itertools;
|
||||
use smallvec::SmallVec;
|
||||
use syntax::SmolStr;
|
||||
|
|
|
@ -4,11 +4,8 @@
|
|||
use crate::{chalk_db, tls, GenericArg};
|
||||
use base_db::salsa::InternId;
|
||||
use chalk_ir::{Goal, GoalData};
|
||||
use hir_def::{
|
||||
intern::{impl_internable, InternStorage, Internable, Interned},
|
||||
type_ref::ConstScalar,
|
||||
TypeAliasId,
|
||||
};
|
||||
use hir_def::{type_ref::ConstScalar, TypeAliasId};
|
||||
use intern::{impl_internable, Interned};
|
||||
use smallvec::SmallVec;
|
||||
use std::{fmt, sync::Arc};
|
||||
|
||||
|
|
|
@ -23,7 +23,6 @@ use hir_def::{
|
|||
generics::{
|
||||
TypeOrConstParamData, TypeParamProvenance, WherePredicate, WherePredicateTypeTarget,
|
||||
},
|
||||
intern::Interned,
|
||||
lang_item::lang_attr,
|
||||
path::{GenericArg, ModPath, Path, PathKind, PathSegment, PathSegments},
|
||||
resolver::{HasResolver, Resolver, TypeNs},
|
||||
|
@ -35,6 +34,7 @@ use hir_def::{
|
|||
TypeAliasId, TypeOrConstParamId, TypeParamId, UnionId, VariantId,
|
||||
};
|
||||
use hir_expand::{name::Name, ExpandResult};
|
||||
use intern::Interned;
|
||||
use itertools::Either;
|
||||
use la_arena::ArenaMap;
|
||||
use rustc_hash::FxHashSet;
|
||||
|
|
|
@ -11,13 +11,13 @@ use hir_def::{
|
|||
GenericParams, TypeOrConstParamData, TypeParamProvenance, WherePredicate,
|
||||
WherePredicateTypeTarget,
|
||||
},
|
||||
intern::Interned,
|
||||
resolver::{HasResolver, TypeNs},
|
||||
type_ref::{TraitBoundModifier, TypeRef},
|
||||
ConstParamId, FunctionId, GenericDefId, ItemContainerId, Lookup, TraitId, TypeAliasId,
|
||||
TypeOrConstParamId, TypeParamId,
|
||||
};
|
||||
use hir_expand::name::Name;
|
||||
use intern::Interned;
|
||||
use itertools::Either;
|
||||
use rustc_hash::FxHashSet;
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
|
|
|
@ -107,7 +107,7 @@ pub use {
|
|||
cfg::{CfgAtom, CfgExpr, CfgOptions},
|
||||
hir_def::{
|
||||
adt::StructKind,
|
||||
attr::{Attr, Attrs, AttrsWithOwner, Documentation},
|
||||
attr::{Attrs, AttrsWithOwner, Documentation},
|
||||
builtin_attr::AttributeTemplate,
|
||||
find_path::PrefixKind,
|
||||
import_map,
|
||||
|
@ -122,6 +122,7 @@ pub use {
|
|||
ModuleDefId,
|
||||
},
|
||||
hir_expand::{
|
||||
attrs::Attr,
|
||||
name::{known, Name},
|
||||
ExpandResult, HirFileId, InFile, MacroFile, Origin,
|
||||
},
|
||||
|
|
|
@ -87,7 +87,6 @@
|
|||
|
||||
use base_db::FileId;
|
||||
use hir_def::{
|
||||
attr::AttrId,
|
||||
child_by_source::ChildBySource,
|
||||
dyn_map::DynMap,
|
||||
expr::{LabelId, PatId},
|
||||
|
@ -96,7 +95,7 @@ use hir_def::{
|
|||
GenericDefId, GenericParamId, ImplId, LifetimeParamId, MacroId, ModuleId, StaticId, StructId,
|
||||
TraitId, TypeAliasId, TypeParamId, UnionId, VariantId,
|
||||
};
|
||||
use hir_expand::{name::AsName, HirFileId, MacroCallId};
|
||||
use hir_expand::{attrs::AttrId, name::AsName, HirFileId, MacroCallId};
|
||||
use rustc_hash::FxHashMap;
|
||||
use smallvec::SmallVec;
|
||||
use stdx::impl_from;
|
||||
|
|
13
crates/intern/Cargo.toml
Normal file
13
crates/intern/Cargo.toml
Normal file
|
@ -0,0 +1,13 @@
|
|||
[package]
|
||||
name = "intern"
|
||||
version = "0.0.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
# We need to freeze the version of the crate, as the raw-api feature is considered unstable
|
||||
dashmap = { version = "=5.4.0", features = ["raw-api"] }
|
||||
hashbrown = { version = "0.12.1", default-features = false }
|
||||
once_cell = "1.15.0"
|
||||
rustc-hash = "1.1.0"
|
|
@ -14,8 +14,6 @@ use hashbrown::HashMap;
|
|||
use once_cell::sync::OnceCell;
|
||||
use rustc_hash::FxHasher;
|
||||
|
||||
use crate::generics::GenericParams;
|
||||
|
||||
type InternMap<T> = DashMap<Arc<T>, (), BuildHasherDefault<FxHasher>>;
|
||||
type Guard<T> = dashmap::RwLockWriteGuard<
|
||||
'static,
|
||||
|
@ -204,9 +202,9 @@ pub trait Internable: Hash + Eq + 'static {
|
|||
#[doc(hidden)]
|
||||
macro_rules! _impl_internable {
|
||||
( $($t:path),+ $(,)? ) => { $(
|
||||
impl Internable for $t {
|
||||
fn storage() -> &'static InternStorage<Self> {
|
||||
static STORAGE: InternStorage<$t> = InternStorage::new();
|
||||
impl $crate::Internable for $t {
|
||||
fn storage() -> &'static $crate::InternStorage<Self> {
|
||||
static STORAGE: $crate::InternStorage<$t> = $crate::InternStorage::new();
|
||||
&STORAGE
|
||||
}
|
||||
}
|
||||
|
@ -215,13 +213,4 @@ macro_rules! _impl_internable {
|
|||
|
||||
pub use crate::_impl_internable as impl_internable;
|
||||
|
||||
impl_internable!(
|
||||
crate::type_ref::TypeRef,
|
||||
crate::type_ref::TraitRef,
|
||||
crate::type_ref::TypeBound,
|
||||
crate::path::ModPath,
|
||||
crate::path::GenericArgs,
|
||||
crate::attr::AttrInput,
|
||||
GenericParams,
|
||||
str,
|
||||
);
|
||||
impl_internable!(str,);
|
Loading…
Reference in a new issue