mirror of
https://github.com/rust-lang/rust-analyzer.git
synced 2025-09-26 11:59:49 +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_abi",
|
||||||
"hkalbasi-rustc-ap-rustc_index",
|
"hkalbasi-rustc-ap-rustc_index",
|
||||||
"indexmap",
|
"indexmap",
|
||||||
|
"intern",
|
||||||
"itertools",
|
"itertools",
|
||||||
"la-arena",
|
"la-arena",
|
||||||
"limit",
|
"limit",
|
||||||
|
@ -544,6 +545,7 @@ dependencies = [
|
||||||
"either",
|
"either",
|
||||||
"expect-test",
|
"expect-test",
|
||||||
"hashbrown",
|
"hashbrown",
|
||||||
|
"intern",
|
||||||
"itertools",
|
"itertools",
|
||||||
"la-arena",
|
"la-arena",
|
||||||
"limit",
|
"limit",
|
||||||
|
@ -574,6 +576,7 @@ dependencies = [
|
||||||
"hir-def",
|
"hir-def",
|
||||||
"hir-expand",
|
"hir-expand",
|
||||||
"hkalbasi-rustc-ap-rustc_index",
|
"hkalbasi-rustc-ap-rustc_index",
|
||||||
|
"intern",
|
||||||
"itertools",
|
"itertools",
|
||||||
"la-arena",
|
"la-arena",
|
||||||
"limit",
|
"limit",
|
||||||
|
@ -803,6 +806,16 @@ dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "intern"
|
||||||
|
version = "0.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"dashmap",
|
||||||
|
"hashbrown",
|
||||||
|
"once_cell",
|
||||||
|
"rustc-hash",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itertools"
|
name = "itertools"
|
||||||
version = "0.10.5"
|
version = "0.10.5"
|
||||||
|
|
|
@ -29,6 +29,7 @@ smallvec = "1.10.0"
|
||||||
tracing = "0.1.35"
|
tracing = "0.1.35"
|
||||||
|
|
||||||
stdx = { path = "../stdx", version = "0.0.0" }
|
stdx = { path = "../stdx", version = "0.0.0" }
|
||||||
|
intern = { path = "../intern", version = "0.0.0" }
|
||||||
base-db = { path = "../base-db", version = "0.0.0" }
|
base-db = { path = "../base-db", version = "0.0.0" }
|
||||||
syntax = { path = "../syntax", version = "0.0.0" }
|
syntax = { path = "../syntax", version = "0.0.0" }
|
||||||
profile = { path = "../profile", version = "0.0.0" }
|
profile = { path = "../profile", version = "0.0.0" }
|
||||||
|
|
|
@ -8,6 +8,7 @@ use hir_expand::{
|
||||||
name::{AsName, Name},
|
name::{AsName, Name},
|
||||||
HirFileId, InFile,
|
HirFileId, InFile,
|
||||||
};
|
};
|
||||||
|
use intern::Interned;
|
||||||
use la_arena::{Arena, ArenaMap};
|
use la_arena::{Arena, ArenaMap};
|
||||||
use rustc_abi::{Integer, IntegerType};
|
use rustc_abi::{Integer, IntegerType};
|
||||||
use syntax::ast::{self, HasName, HasVisibility};
|
use syntax::ast::{self, HasName, HasVisibility};
|
||||||
|
@ -17,7 +18,6 @@ use crate::{
|
||||||
body::{CfgExpander, LowerCtx},
|
body::{CfgExpander, LowerCtx},
|
||||||
builtin_type::{BuiltinInt, BuiltinUint},
|
builtin_type::{BuiltinInt, BuiltinUint},
|
||||||
db::DefDatabase,
|
db::DefDatabase,
|
||||||
intern::Interned,
|
|
||||||
item_tree::{AttrOwner, Field, FieldAstId, Fields, ItemTree, ModItem, RawVisibilityId},
|
item_tree::{AttrOwner, Field, FieldAstId, Fields, ItemTree, ModItem, RawVisibilityId},
|
||||||
layout::{Align, ReprFlags, ReprOptions},
|
layout::{Align, ReprFlags, ReprOptions},
|
||||||
nameres::diagnostics::DefDiagnostic,
|
nameres::diagnostics::DefDiagnostic,
|
||||||
|
|
|
@ -1,27 +1,27 @@
|
||||||
//! A higher level attributes based on TokenTree, with also some shortcuts.
|
//! 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 base_db::CrateId;
|
||||||
use cfg::{CfgExpr, CfgOptions};
|
use cfg::{CfgExpr, CfgOptions};
|
||||||
use either::Either;
|
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 itertools::Itertools;
|
||||||
use la_arena::{ArenaMap, Idx, RawIdx};
|
use la_arena::{ArenaMap, Idx, RawIdx};
|
||||||
use mbe::{syntax_node_to_token_tree, DelimiterKind, Punct};
|
use mbe::DelimiterKind;
|
||||||
use smallvec::{smallvec, SmallVec};
|
|
||||||
use syntax::{
|
use syntax::{
|
||||||
ast::{self, AstNode, HasAttrs, IsString},
|
ast::{self, HasAttrs, IsString},
|
||||||
match_ast, AstPtr, AstToken, SmolStr, SyntaxNode, TextRange, TextSize,
|
AstPtr, AstToken, SmolStr, TextRange, TextSize,
|
||||||
};
|
};
|
||||||
use tt::Subtree;
|
use tt::Subtree;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
db::DefDatabase,
|
db::DefDatabase,
|
||||||
intern::Interned,
|
|
||||||
item_tree::{AttrOwner, Fields, ItemTreeId, ItemTreeNode},
|
item_tree::{AttrOwner, Fields, ItemTreeId, ItemTreeNode},
|
||||||
nameres::{ModuleOrigin, ModuleSource},
|
nameres::{ModuleOrigin, ModuleSource},
|
||||||
path::{ModPath, PathKind},
|
|
||||||
src::{HasChildSource, HasSource},
|
src::{HasChildSource, HasSource},
|
||||||
AdtId, AttrDefId, EnumId, GenericParamId, LocalEnumVariantId, LocalFieldId, Lookup, MacroId,
|
AdtId, AttrDefId, EnumId, GenericParamId, LocalEnumVariantId, LocalFieldId, Lookup, MacroId,
|
||||||
VariantId,
|
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)]
|
#[derive(Default, Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct Attrs(RawAttrs);
|
pub struct Attrs(RawAttrs);
|
||||||
|
|
||||||
|
@ -62,30 +56,21 @@ pub struct AttrsWithOwner {
|
||||||
owner: AttrDefId,
|
owner: AttrDefId,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ops::Deref for RawAttrs {
|
|
||||||
type Target = [Attr];
|
|
||||||
|
|
||||||
fn deref(&self) -> &[Attr] {
|
|
||||||
match &self.entries {
|
|
||||||
Some(it) => &*it,
|
|
||||||
None => &[],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl Attrs {
|
impl Attrs {
|
||||||
pub fn get(&self, id: AttrId) -> Option<&Attr> {
|
pub fn get(&self, id: AttrId) -> Option<&Attr> {
|
||||||
(**self).iter().find(|attr| attr.id == id)
|
(**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 {
|
impl ops::Deref for Attrs {
|
||||||
type Target = [Attr];
|
type Target = [Attr];
|
||||||
|
|
||||||
fn deref(&self) -> &[Attr] {
|
fn deref(&self) -> &[Attr] {
|
||||||
match &self.0.entries {
|
&self.0
|
||||||
Some(it) => &*it,
|
|
||||||
None => &[],
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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 {
|
impl Attrs {
|
||||||
pub const EMPTY: Self = Self(RawAttrs::EMPTY);
|
pub const EMPTY: Self = Self(RawAttrs::EMPTY);
|
||||||
|
|
||||||
|
@ -403,7 +280,7 @@ impl AttrsWithOwner {
|
||||||
.raw_attrs(AttrOwner::ModItem(definition_tree_id.value.into()))
|
.raw_attrs(AttrOwner::ModItem(definition_tree_id.value.into()))
|
||||||
.clone(),
|
.clone(),
|
||||||
ModuleOrigin::BlockExpr { block } => RawAttrs::from_attrs_owner(
|
ModuleOrigin::BlockExpr { block } => RawAttrs::from_attrs_owner(
|
||||||
db,
|
db.upcast(),
|
||||||
InFile::new(block.file_id, block.to_node(db.upcast()))
|
InFile::new(block.file_id, block.to_node(db.upcast()))
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|it| it as &dyn ast::HasAttrs),
|
.map(|it| it as &dyn ast::HasAttrs),
|
||||||
|
@ -439,7 +316,7 @@ impl AttrsWithOwner {
|
||||||
GenericParamId::ConstParamId(it) => {
|
GenericParamId::ConstParamId(it) => {
|
||||||
let src = it.parent().child_source(db);
|
let src = it.parent().child_source(db);
|
||||||
RawAttrs::from_attrs_owner(
|
RawAttrs::from_attrs_owner(
|
||||||
db,
|
db.upcast(),
|
||||||
src.with_value(src.value[it.local_id()].as_ref().either(
|
src.with_value(src.value[it.local_id()].as_ref().either(
|
||||||
|it| match it {
|
|it| match it {
|
||||||
ast::TypeOrConstParam::Type(it) => it as _,
|
ast::TypeOrConstParam::Type(it) => it as _,
|
||||||
|
@ -452,7 +329,7 @@ impl AttrsWithOwner {
|
||||||
GenericParamId::TypeParamId(it) => {
|
GenericParamId::TypeParamId(it) => {
|
||||||
let src = it.parent().child_source(db);
|
let src = it.parent().child_source(db);
|
||||||
RawAttrs::from_attrs_owner(
|
RawAttrs::from_attrs_owner(
|
||||||
db,
|
db.upcast(),
|
||||||
src.with_value(src.value[it.local_id()].as_ref().either(
|
src.with_value(src.value[it.local_id()].as_ref().either(
|
||||||
|it| match it {
|
|it| match it {
|
||||||
ast::TypeOrConstParam::Type(it) => it as _,
|
ast::TypeOrConstParam::Type(it) => it as _,
|
||||||
|
@ -464,14 +341,14 @@ impl AttrsWithOwner {
|
||||||
}
|
}
|
||||||
GenericParamId::LifetimeParamId(it) => {
|
GenericParamId::LifetimeParamId(it) => {
|
||||||
let src = it.parent.child_source(db);
|
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),
|
AttrDefId::ExternBlockId(it) => attrs_from_item_tree(it.lookup(db).id, db),
|
||||||
};
|
};
|
||||||
|
|
||||||
let attrs = raw_attrs.filter(db, def.krate(db));
|
let attrs = raw_attrs.filter(db.upcast(), def.krate(db));
|
||||||
Self { attrs, owner: def }
|
Self { attrs: Attrs(attrs), owner: def }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
|
pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
|
||||||
|
@ -627,40 +504,6 @@ fn doc_indent(attrs: &Attrs) -> usize {
|
||||||
.unwrap_or(0)
|
.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)]
|
#[derive(Debug)]
|
||||||
pub struct AttrSourceMap {
|
pub struct AttrSourceMap {
|
||||||
source: Vec<Either<ast::Attr, ast::Comment>>,
|
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)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
pub struct AttrQuery<'attr> {
|
pub struct AttrQuery<'attr> {
|
||||||
attrs: &'attr Attrs,
|
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()
|
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(
|
pub(crate) fn variants_attrs_source_map(
|
||||||
db: &dyn DefDatabase,
|
db: &dyn DefDatabase,
|
||||||
def: EnumId,
|
def: EnumId,
|
||||||
|
|
|
@ -12,7 +12,9 @@ use base_db::CrateId;
|
||||||
use cfg::{CfgExpr, CfgOptions};
|
use cfg::{CfgExpr, CfgOptions};
|
||||||
use drop_bomb::DropBomb;
|
use drop_bomb::DropBomb;
|
||||||
use either::Either;
|
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 la_arena::{Arena, ArenaMap};
|
||||||
use limit::Limit;
|
use limit::Limit;
|
||||||
use profile::Count;
|
use profile::Count;
|
||||||
|
@ -20,7 +22,7 @@ use rustc_hash::FxHashMap;
|
||||||
use syntax::{ast, AstPtr, SyntaxNodePtr};
|
use syntax::{ast, AstPtr, SyntaxNodePtr};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
attr::{Attrs, RawAttrs},
|
attr::Attrs,
|
||||||
db::DefDatabase,
|
db::DefDatabase,
|
||||||
expr::{dummy_expr_id, Expr, ExprId, Label, LabelId, Pat, PatId},
|
expr::{dummy_expr_id, Expr, ExprId, Label, LabelId, Pat, PatId},
|
||||||
item_scope::BuiltinShadowMode,
|
item_scope::BuiltinShadowMode,
|
||||||
|
@ -64,7 +66,7 @@ impl CfgExpander {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
|
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 {
|
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},
|
name::{name, AsName, Name},
|
||||||
AstId, ExpandError, HirFileId, InFile,
|
AstId, ExpandError, HirFileId, InFile,
|
||||||
};
|
};
|
||||||
|
use intern::Interned;
|
||||||
use la_arena::Arena;
|
use la_arena::Arena;
|
||||||
use once_cell::unsync::OnceCell;
|
use once_cell::unsync::OnceCell;
|
||||||
use profile::Count;
|
use profile::Count;
|
||||||
|
@ -33,7 +34,6 @@ use crate::{
|
||||||
Label, LabelId, Literal, MatchArm, Movability, Pat, PatId, RecordFieldPat, RecordLitField,
|
Label, LabelId, Literal, MatchArm, Movability, Pat, PatId, RecordFieldPat, RecordLitField,
|
||||||
Statement,
|
Statement,
|
||||||
},
|
},
|
||||||
intern::Interned,
|
|
||||||
item_scope::BuiltinShadowMode,
|
item_scope::BuiltinShadowMode,
|
||||||
path::{GenericArgs, Path},
|
path::{GenericArgs, Path},
|
||||||
type_ref::{Mutability, Rawness, TypeRef},
|
type_ref::{Mutability, Rawness, TypeRef},
|
||||||
|
|
|
@ -3,6 +3,7 @@
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use hir_expand::{name::Name, AstId, ExpandResult, HirFileId, InFile, MacroCallId, MacroDefKind};
|
use hir_expand::{name::Name, AstId, ExpandResult, HirFileId, InFile, MacroCallId, MacroDefKind};
|
||||||
|
use intern::Interned;
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
use syntax::ast;
|
use syntax::ast;
|
||||||
|
|
||||||
|
@ -10,7 +11,6 @@ use crate::{
|
||||||
attr::Attrs,
|
attr::Attrs,
|
||||||
body::{Expander, Mark},
|
body::{Expander, Mark},
|
||||||
db::DefDatabase,
|
db::DefDatabase,
|
||||||
intern::Interned,
|
|
||||||
item_tree::{self, AssocItem, FnFlags, ItemTree, ItemTreeId, ModItem, Param, TreeId},
|
item_tree::{self, AssocItem, FnFlags, ItemTree, ItemTreeId, ModItem, Param, TreeId},
|
||||||
nameres::{
|
nameres::{
|
||||||
attr_resolution::ResolvedAttr,
|
attr_resolution::ResolvedAttr,
|
||||||
|
|
|
@ -4,6 +4,7 @@ use std::sync::Arc;
|
||||||
use base_db::{salsa, CrateId, SourceDatabase, Upcast};
|
use base_db::{salsa, CrateId, SourceDatabase, Upcast};
|
||||||
use either::Either;
|
use either::Either;
|
||||||
use hir_expand::{db::AstDatabase, HirFileId};
|
use hir_expand::{db::AstDatabase, HirFileId};
|
||||||
|
use intern::Interned;
|
||||||
use la_arena::ArenaMap;
|
use la_arena::ArenaMap;
|
||||||
use syntax::{ast, AstPtr, SmolStr};
|
use syntax::{ast, AstPtr, SmolStr};
|
||||||
|
|
||||||
|
@ -17,7 +18,6 @@ use crate::{
|
||||||
},
|
},
|
||||||
generics::GenericParams,
|
generics::GenericParams,
|
||||||
import_map::ImportMap,
|
import_map::ImportMap,
|
||||||
intern::Interned,
|
|
||||||
item_tree::{AttrOwner, ItemTree},
|
item_tree::{AttrOwner, ItemTree},
|
||||||
lang_item::{LangItemTarget, LangItems},
|
lang_item::{LangItemTarget, LangItems},
|
||||||
nameres::{diagnostics::DefDiagnostic, DefMap},
|
nameres::{diagnostics::DefDiagnostic, DefMap},
|
||||||
|
|
|
@ -15,11 +15,11 @@
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
use hir_expand::name::Name;
|
use hir_expand::name::Name;
|
||||||
|
use intern::Interned;
|
||||||
use la_arena::{Idx, RawIdx};
|
use la_arena::{Idx, RawIdx};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
|
builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
|
||||||
intern::Interned,
|
|
||||||
path::{GenericArgs, Path},
|
path::{GenericArgs, Path},
|
||||||
type_ref::{Mutability, Rawness, TypeRef},
|
type_ref::{Mutability, Rawness, TypeRef},
|
||||||
BlockId,
|
BlockId,
|
||||||
|
|
|
@ -9,6 +9,7 @@ use hir_expand::{
|
||||||
name::{AsName, Name},
|
name::{AsName, Name},
|
||||||
ExpandResult, HirFileId, InFile,
|
ExpandResult, HirFileId, InFile,
|
||||||
};
|
};
|
||||||
|
use intern::Interned;
|
||||||
use la_arena::{Arena, ArenaMap, Idx};
|
use la_arena::{Arena, ArenaMap, Idx};
|
||||||
use once_cell::unsync::Lazy;
|
use once_cell::unsync::Lazy;
|
||||||
use std::ops::DerefMut;
|
use std::ops::DerefMut;
|
||||||
|
@ -20,7 +21,6 @@ use crate::{
|
||||||
child_by_source::ChildBySource,
|
child_by_source::ChildBySource,
|
||||||
db::DefDatabase,
|
db::DefDatabase,
|
||||||
dyn_map::DynMap,
|
dyn_map::DynMap,
|
||||||
intern::Interned,
|
|
||||||
keys,
|
keys,
|
||||||
src::{HasChildSource, HasSource},
|
src::{HasChildSource, HasSource},
|
||||||
type_ref::{LifetimeRef, TypeBound, TypeRef},
|
type_ref::{LifetimeRef, TypeBound, TypeRef},
|
||||||
|
|
|
@ -4,7 +4,7 @@
|
||||||
use std::collections::hash_map::Entry;
|
use std::collections::hash_map::Entry;
|
||||||
|
|
||||||
use base_db::CrateId;
|
use base_db::CrateId;
|
||||||
use hir_expand::{name::Name, AstId, MacroCallId};
|
use hir_expand::{attrs::AttrId, name::Name, AstId, MacroCallId};
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use profile::Count;
|
use profile::Count;
|
||||||
|
@ -14,8 +14,8 @@ use stdx::format_to;
|
||||||
use syntax::ast;
|
use syntax::ast;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
attr::AttrId, db::DefDatabase, per_ns::PerNs, visibility::Visibility, AdtId, BuiltinType,
|
db::DefDatabase, per_ns::PerNs, visibility::Visibility, AdtId, BuiltinType, ConstId, HasModule,
|
||||||
ConstId, HasModule, ImplId, LocalModuleId, MacroId, ModuleDefId, ModuleId, TraitId,
|
ImplId, LocalModuleId, MacroId, ModuleDefId, ModuleId, TraitId,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug)]
|
#[derive(Copy, Clone, Debug)]
|
||||||
|
|
|
@ -48,10 +48,12 @@ use base_db::CrateId;
|
||||||
use either::Either;
|
use either::Either;
|
||||||
use hir_expand::{
|
use hir_expand::{
|
||||||
ast_id_map::FileAstId,
|
ast_id_map::FileAstId,
|
||||||
|
attrs::RawAttrs,
|
||||||
hygiene::Hygiene,
|
hygiene::Hygiene,
|
||||||
name::{name, AsName, Name},
|
name::{name, AsName, Name},
|
||||||
ExpandTo, HirFileId, InFile,
|
ExpandTo, HirFileId, InFile,
|
||||||
};
|
};
|
||||||
|
use intern::Interned;
|
||||||
use la_arena::{Arena, Idx, IdxRange, RawIdx};
|
use la_arena::{Arena, Idx, IdxRange, RawIdx};
|
||||||
use profile::Count;
|
use profile::Count;
|
||||||
use rustc_hash::FxHashMap;
|
use rustc_hash::FxHashMap;
|
||||||
|
@ -60,10 +62,9 @@ use stdx::never;
|
||||||
use syntax::{ast, match_ast, SyntaxKind};
|
use syntax::{ast, match_ast, SyntaxKind};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
attr::{Attrs, RawAttrs},
|
attr::Attrs,
|
||||||
db::DefDatabase,
|
db::DefDatabase,
|
||||||
generics::GenericParams,
|
generics::GenericParams,
|
||||||
intern::Interned,
|
|
||||||
path::{path, AssociatedTypeBinding, GenericArgs, ImportAlias, ModPath, Path, PathKind},
|
path::{path, AssociatedTypeBinding, GenericArgs, ImportAlias, ModPath, Path, PathKind},
|
||||||
type_ref::{Mutability, TraitRef, TypeBound, TypeRef},
|
type_ref::{Mutability, TraitRef, TypeBound, TypeRef},
|
||||||
visibility::RawVisibility,
|
visibility::RawVisibility,
|
||||||
|
@ -120,7 +121,7 @@ impl ItemTree {
|
||||||
let mut item_tree = match_ast! {
|
let mut item_tree = match_ast! {
|
||||||
match syntax {
|
match syntax {
|
||||||
ast::SourceFile(file) => {
|
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)
|
ctx.lower_module_items(&file)
|
||||||
},
|
},
|
||||||
ast::MacroItems(items) => {
|
ast::MacroItems(items) => {
|
||||||
|
@ -152,7 +153,11 @@ impl ItemTree {
|
||||||
|
|
||||||
/// Returns the inner attributes of the source file.
|
/// Returns the inner attributes of the source file.
|
||||||
pub fn top_level_attrs(&self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
|
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 {
|
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 {
|
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 {
|
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> {
|
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 {
|
let item: ModItem = match item {
|
||||||
ast::Item::Struct(ast) => self.lower_struct(ast)?.into(),
|
ast::Item::Struct(ast) => self.lower_struct(ast)?.into(),
|
||||||
ast::Item::Union(ast) => self.lower_union(ast)?.into(),
|
ast::Item::Union(ast) => self.lower_union(ast)?.into(),
|
||||||
|
@ -173,7 +173,7 @@ impl<'a> Ctx<'a> {
|
||||||
for field in fields.fields() {
|
for field in fields.fields() {
|
||||||
if let Some(data) = self.lower_record_field(&field) {
|
if let Some(data) = self.lower_record_field(&field) {
|
||||||
let idx = self.data().fields.alloc(data);
|
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();
|
let end = self.next_field_idx();
|
||||||
|
@ -194,7 +194,7 @@ impl<'a> Ctx<'a> {
|
||||||
for (i, field) in fields.fields().enumerate() {
|
for (i, field) in fields.fields().enumerate() {
|
||||||
let data = self.lower_tuple_field(i, &field);
|
let data = self.lower_tuple_field(i, &field);
|
||||||
let idx = self.data().fields.alloc(data);
|
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();
|
let end = self.next_field_idx();
|
||||||
IdxRange::new(start..end)
|
IdxRange::new(start..end)
|
||||||
|
@ -239,7 +239,10 @@ impl<'a> Ctx<'a> {
|
||||||
for variant in variants.variants() {
|
for variant in variants.variants() {
|
||||||
if let Some(data) = self.lower_variant(&variant) {
|
if let Some(data) = self.lower_variant(&variant) {
|
||||||
let idx = self.data().variants.alloc(data);
|
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();
|
let end = self.next_variant_idx();
|
||||||
|
@ -283,7 +286,10 @@ impl<'a> Ctx<'a> {
|
||||||
};
|
};
|
||||||
let ty = Interned::new(self_type);
|
let ty = Interned::new(self_type);
|
||||||
let idx = self.data().params.alloc(Param::Normal(None, ty));
|
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;
|
has_self_param = true;
|
||||||
}
|
}
|
||||||
for param in param_list.params() {
|
for param in param_list.params() {
|
||||||
|
@ -307,7 +313,7 @@ impl<'a> Ctx<'a> {
|
||||||
self.data().params.alloc(Param::Normal(name, ty))
|
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();
|
let end_param = self.next_param_idx();
|
||||||
|
@ -442,7 +448,7 @@ impl<'a> Ctx<'a> {
|
||||||
let items = trait_def.assoc_item_list().map(|list| {
|
let items = trait_def.assoc_item_list().map(|list| {
|
||||||
list.assoc_items()
|
list.assoc_items()
|
||||||
.filter_map(|item| {
|
.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.lower_assoc_item(&item).map(|item| {
|
||||||
self.add_attrs(ModItem::from(item).into(), attrs);
|
self.add_attrs(ModItem::from(item).into(), attrs);
|
||||||
item
|
item
|
||||||
|
@ -471,7 +477,7 @@ impl<'a> Ctx<'a> {
|
||||||
.flat_map(|it| it.assoc_items())
|
.flat_map(|it| it.assoc_items())
|
||||||
.filter_map(|item| {
|
.filter_map(|item| {
|
||||||
let assoc = self.lower_assoc_item(&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);
|
self.add_attrs(ModItem::from(assoc).into(), attrs);
|
||||||
Some(assoc)
|
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).
|
// (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
|
// 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.
|
// 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 {
|
let id: ModItem = match item {
|
||||||
ast::ExternItem::Fn(ast) => self.lower_function(&ast)?.into(),
|
ast::ExternItem::Fn(ast) => self.lower_function(&ast)?.into(),
|
||||||
ast::ExternItem::Static(ast) => self.lower_static(&ast)?.into(),
|
ast::ExternItem::Static(ast) => self.lower_static(&ast)?.into(),
|
||||||
|
|
|
@ -3,7 +3,6 @@
|
||||||
use std::fmt::{self, Write};
|
use std::fmt::{self, Write};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
attr::RawAttrs,
|
|
||||||
generics::{TypeOrConstParamData, WherePredicate, WherePredicateTypeTarget},
|
generics::{TypeOrConstParamData, WherePredicate, WherePredicateTypeTarget},
|
||||||
pretty::{print_path, print_type_bounds, print_type_ref},
|
pretty::{print_path, print_type_bounds, print_type_ref},
|
||||||
visibility::RawVisibility,
|
visibility::RawVisibility,
|
||||||
|
|
|
@ -2,12 +2,11 @@
|
||||||
|
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
use hir_expand::MacroCallId;
|
use hir_expand::{attrs::AttrId, MacroCallId};
|
||||||
use rustc_hash::FxHashMap;
|
use rustc_hash::FxHashMap;
|
||||||
use syntax::{ast, AstNode, AstPtr};
|
use syntax::{ast, AstNode, AstPtr};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
attr::AttrId,
|
|
||||||
dyn_map::{DynMap, Policy},
|
dyn_map::{DynMap, Policy},
|
||||||
ConstId, EnumId, EnumVariantId, FieldId, FunctionId, ImplId, LifetimeParamId, Macro2Id,
|
ConstId, EnumId, EnumVariantId, FieldId, FunctionId, ImplId, LifetimeParamId, Macro2Id,
|
||||||
MacroRulesId, ProcMacroId, StaticId, StructId, TraitId, TypeAliasId, TypeOrConstParamId,
|
MacroRulesId, ProcMacroId, StaticId, StructId, TraitId, TypeAliasId, TypeOrConstParamId,
|
||||||
|
|
|
@ -28,7 +28,6 @@ pub mod dyn_map;
|
||||||
pub mod keys;
|
pub mod keys;
|
||||||
|
|
||||||
pub mod item_tree;
|
pub mod item_tree;
|
||||||
pub mod intern;
|
|
||||||
|
|
||||||
pub mod adt;
|
pub mod adt;
|
||||||
pub mod data;
|
pub mod data;
|
||||||
|
@ -61,10 +60,10 @@ use std::{
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
};
|
};
|
||||||
|
|
||||||
use attr::Attr;
|
|
||||||
use base_db::{impl_intern_key, salsa, CrateId, ProcMacroKind};
|
use base_db::{impl_intern_key, salsa, CrateId, ProcMacroKind};
|
||||||
use hir_expand::{
|
use hir_expand::{
|
||||||
ast_id_map::FileAstId,
|
ast_id_map::FileAstId,
|
||||||
|
attrs::{Attr, AttrId, AttrInput},
|
||||||
builtin_attr_macro::BuiltinAttrExpander,
|
builtin_attr_macro::BuiltinAttrExpander,
|
||||||
builtin_derive_macro::BuiltinDeriveExpander,
|
builtin_derive_macro::BuiltinDeriveExpander,
|
||||||
builtin_fn_macro::{BuiltinFnLikeExpander, EagerExpander},
|
builtin_fn_macro::{BuiltinFnLikeExpander, EagerExpander},
|
||||||
|
@ -82,7 +81,6 @@ use syntax::ast;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
adt::VariantData,
|
adt::VariantData,
|
||||||
attr::AttrId,
|
|
||||||
builtin_type::BuiltinType,
|
builtin_type::BuiltinType,
|
||||||
item_tree::{
|
item_tree::{
|
||||||
Const, Enum, Function, Impl, ItemTreeId, ItemTreeNode, MacroDef, MacroRules, ModItem,
|
Const, Enum, Function, Impl, ItemTreeId, ItemTreeNode, MacroDef, MacroRules, ModItem,
|
||||||
|
@ -971,7 +969,7 @@ fn attr_macro_as_call_id(
|
||||||
is_derive: bool,
|
is_derive: bool,
|
||||||
) -> MacroCallId {
|
) -> MacroCallId {
|
||||||
let mut arg = match macro_attr.input.as_deref() {
|
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(),
|
_ => Default::default(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -990,3 +988,10 @@ fn attr_macro_as_call_id(
|
||||||
);
|
);
|
||||||
res
|
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.
|
//! Post-nameres attribute resolution.
|
||||||
|
|
||||||
use hir_expand::MacroCallId;
|
use hir_expand::{attrs::Attr, MacroCallId};
|
||||||
use syntax::{ast, SmolStr};
|
use syntax::{ast, SmolStr};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
attr::Attr,
|
|
||||||
attr_macro_as_call_id, builtin_attr,
|
attr_macro_as_call_id, builtin_attr,
|
||||||
db::DefDatabase,
|
db::DefDatabase,
|
||||||
item_scope::BuiltinShadowMode,
|
item_scope::BuiltinShadowMode,
|
||||||
|
|
|
@ -10,6 +10,7 @@ use cfg::{CfgExpr, CfgOptions};
|
||||||
use either::Either;
|
use either::Either;
|
||||||
use hir_expand::{
|
use hir_expand::{
|
||||||
ast_id_map::FileAstId,
|
ast_id_map::FileAstId,
|
||||||
|
attrs::{Attr, AttrId},
|
||||||
builtin_attr_macro::find_builtin_attr,
|
builtin_attr_macro::find_builtin_attr,
|
||||||
builtin_derive_macro::find_builtin_derive,
|
builtin_derive_macro::find_builtin_derive,
|
||||||
builtin_fn_macro::find_builtin_macro,
|
builtin_fn_macro::find_builtin_macro,
|
||||||
|
@ -26,7 +27,7 @@ use stdx::always;
|
||||||
use syntax::{ast, SmolStr};
|
use syntax::{ast, SmolStr};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
attr::{Attr, AttrId, Attrs},
|
attr::Attrs,
|
||||||
attr_macro_as_call_id,
|
attr_macro_as_call_id,
|
||||||
db::DefDatabase,
|
db::DefDatabase,
|
||||||
derive_macro_as_call_id,
|
derive_macro_as_call_id,
|
||||||
|
|
|
@ -2,12 +2,11 @@
|
||||||
|
|
||||||
use base_db::CrateId;
|
use base_db::CrateId;
|
||||||
use cfg::{CfgExpr, CfgOptions};
|
use cfg::{CfgExpr, CfgOptions};
|
||||||
use hir_expand::MacroCallKind;
|
use hir_expand::{attrs::AttrId, MacroCallKind};
|
||||||
use la_arena::Idx;
|
use la_arena::Idx;
|
||||||
use syntax::ast::{self, AnyHasAttrs};
|
use syntax::ast::{self, AnyHasAttrs};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
attr::AttrId,
|
|
||||||
item_tree::{self, ItemTreeId},
|
item_tree::{self, ItemTreeId},
|
||||||
nameres::LocalModuleId,
|
nameres::LocalModuleId,
|
||||||
path::ModPath,
|
path::ModPath,
|
||||||
|
|
|
@ -8,10 +8,10 @@ use std::{
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
body::LowerCtx,
|
body::LowerCtx,
|
||||||
intern::Interned,
|
|
||||||
type_ref::{ConstScalarOrPath, LifetimeRef},
|
type_ref::{ConstScalarOrPath, LifetimeRef},
|
||||||
};
|
};
|
||||||
use hir_expand::name::Name;
|
use hir_expand::name::Name;
|
||||||
|
use intern::Interned;
|
||||||
use syntax::ast;
|
use syntax::ast;
|
||||||
|
|
||||||
use crate::type_ref::{TypeBound, TypeRef};
|
use crate::type_ref::{TypeBound, TypeRef};
|
||||||
|
|
|
@ -1,9 +1,10 @@
|
||||||
//! Transforms syntax into `Path` objects, ideally with accounting for hygiene
|
//! 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 either::Either;
|
||||||
use hir_expand::name::{name, AsName};
|
use hir_expand::name::{name, AsName};
|
||||||
|
use intern::Interned;
|
||||||
use syntax::ast::{self, AstNode, HasTypeBounds};
|
use syntax::ast::{self, AstNode, HasTypeBounds};
|
||||||
|
|
||||||
use super::AssociatedTypeBinding;
|
use super::AssociatedTypeBinding;
|
||||||
|
|
|
@ -3,10 +3,10 @@
|
||||||
use std::fmt::{self, Write};
|
use std::fmt::{self, Write};
|
||||||
|
|
||||||
use hir_expand::mod_path::PathKind;
|
use hir_expand::mod_path::PathKind;
|
||||||
|
use intern::Interned;
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
intern::Interned,
|
|
||||||
path::{GenericArg, GenericArgs, Path},
|
path::{GenericArg, GenericArgs, Path},
|
||||||
type_ref::{Mutability, TraitBoundModifier, TypeBound, TypeRef},
|
type_ref::{Mutability, TraitBoundModifier, TypeBound, TypeRef},
|
||||||
};
|
};
|
||||||
|
|
|
@ -4,6 +4,7 @@ use std::{hash::BuildHasherDefault, sync::Arc};
|
||||||
use base_db::CrateId;
|
use base_db::CrateId;
|
||||||
use hir_expand::name::{name, Name};
|
use hir_expand::name::{name, Name};
|
||||||
use indexmap::IndexMap;
|
use indexmap::IndexMap;
|
||||||
|
use intern::Interned;
|
||||||
use rustc_hash::FxHashSet;
|
use rustc_hash::FxHashSet;
|
||||||
use smallvec::{smallvec, SmallVec};
|
use smallvec::{smallvec, SmallVec};
|
||||||
|
|
||||||
|
@ -13,7 +14,6 @@ use crate::{
|
||||||
db::DefDatabase,
|
db::DefDatabase,
|
||||||
expr::{ExprId, LabelId, PatId},
|
expr::{ExprId, LabelId, PatId},
|
||||||
generics::{GenericParams, TypeOrConstParamData},
|
generics::{GenericParams, TypeOrConstParamData},
|
||||||
intern::Interned,
|
|
||||||
item_scope::{BuiltinShadowMode, BUILTIN_SCOPE},
|
item_scope::{BuiltinShadowMode, BUILTIN_SCOPE},
|
||||||
nameres::DefMap,
|
nameres::DefMap,
|
||||||
path::{ModPath, PathKind},
|
path::{ModPath, PathKind},
|
||||||
|
|
|
@ -7,13 +7,13 @@ use hir_expand::{
|
||||||
name::{AsName, Name},
|
name::{AsName, Name},
|
||||||
AstId,
|
AstId,
|
||||||
};
|
};
|
||||||
|
use intern::Interned;
|
||||||
use syntax::ast::{self, HasName};
|
use syntax::ast::{self, HasName};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
body::LowerCtx,
|
body::LowerCtx,
|
||||||
builtin_type::{BuiltinInt, BuiltinType, BuiltinUint},
|
builtin_type::{BuiltinInt, BuiltinType, BuiltinUint},
|
||||||
expr::Literal,
|
expr::Literal,
|
||||||
intern::Interned,
|
|
||||||
path::Path,
|
path::Path,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -22,6 +22,7 @@ hashbrown = { version = "0.12.1", features = [
|
||||||
smallvec = { version = "1.10.0", features = ["const_new"] }
|
smallvec = { version = "1.10.0", features = ["const_new"] }
|
||||||
|
|
||||||
stdx = { path = "../stdx", version = "0.0.0" }
|
stdx = { path = "../stdx", version = "0.0.0" }
|
||||||
|
intern = { path = "../intern", version = "0.0.0" }
|
||||||
base-db = { path = "../base-db", version = "0.0.0" }
|
base-db = { path = "../base-db", version = "0.0.0" }
|
||||||
cfg = { path = "../cfg", version = "0.0.0" }
|
cfg = { path = "../cfg", version = "0.0.0" }
|
||||||
syntax = { path = "../syntax", 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 quote;
|
||||||
pub mod eager;
|
pub mod eager;
|
||||||
pub mod mod_path;
|
pub mod mod_path;
|
||||||
|
pub mod attrs;
|
||||||
mod fixup;
|
mod fixup;
|
||||||
|
|
||||||
pub use mbe::{Origin, ValueResult};
|
pub use mbe::{Origin, ValueResult};
|
||||||
|
@ -1031,3 +1032,5 @@ impl ExpandTo {
|
||||||
pub struct UnresolvedMacro {
|
pub struct UnresolvedMacro {
|
||||||
pub path: ModPath,
|
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 }
|
rustc_index = { version = "0.0.20221221", package = "hkalbasi-rustc-ap-rustc_index", default-features = false }
|
||||||
|
|
||||||
stdx = { path = "../stdx", version = "0.0.0" }
|
stdx = { path = "../stdx", version = "0.0.0" }
|
||||||
|
intern = { path = "../intern", version = "0.0.0" }
|
||||||
hir-def = { path = "../hir-def", version = "0.0.0" }
|
hir-def = { path = "../hir-def", version = "0.0.0" }
|
||||||
hir-expand = { path = "../hir-expand", version = "0.0.0" }
|
hir-expand = { path = "../hir-expand", version = "0.0.0" }
|
||||||
base-db = { path = "../base-db", version = "0.0.0" }
|
base-db = { path = "../base-db", version = "0.0.0" }
|
||||||
|
|
|
@ -11,7 +11,6 @@ use hir_def::{
|
||||||
db::DefDatabase,
|
db::DefDatabase,
|
||||||
find_path,
|
find_path,
|
||||||
generics::{TypeOrConstParamData, TypeParamProvenance},
|
generics::{TypeOrConstParamData, TypeParamProvenance},
|
||||||
intern::{Internable, Interned},
|
|
||||||
item_scope::ItemInNs,
|
item_scope::ItemInNs,
|
||||||
path::{Path, PathKind},
|
path::{Path, PathKind},
|
||||||
type_ref::{ConstScalar, TraitBoundModifier, TypeBound, TypeRef},
|
type_ref::{ConstScalar, TraitBoundModifier, TypeBound, TypeRef},
|
||||||
|
@ -19,6 +18,7 @@ use hir_def::{
|
||||||
HasModule, ItemContainerId, Lookup, ModuleDefId, ModuleId, TraitId,
|
HasModule, ItemContainerId, Lookup, ModuleDefId, ModuleId, TraitId,
|
||||||
};
|
};
|
||||||
use hir_expand::{hygiene::Hygiene, name::Name};
|
use hir_expand::{hygiene::Hygiene, name::Name};
|
||||||
|
use intern::{Internable, Interned};
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
use syntax::SmolStr;
|
use syntax::SmolStr;
|
||||||
|
|
|
@ -4,11 +4,8 @@
|
||||||
use crate::{chalk_db, tls, GenericArg};
|
use crate::{chalk_db, tls, GenericArg};
|
||||||
use base_db::salsa::InternId;
|
use base_db::salsa::InternId;
|
||||||
use chalk_ir::{Goal, GoalData};
|
use chalk_ir::{Goal, GoalData};
|
||||||
use hir_def::{
|
use hir_def::{type_ref::ConstScalar, TypeAliasId};
|
||||||
intern::{impl_internable, InternStorage, Internable, Interned},
|
use intern::{impl_internable, Interned};
|
||||||
type_ref::ConstScalar,
|
|
||||||
TypeAliasId,
|
|
||||||
};
|
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
use std::{fmt, sync::Arc};
|
use std::{fmt, sync::Arc};
|
||||||
|
|
||||||
|
|
|
@ -23,7 +23,6 @@ use hir_def::{
|
||||||
generics::{
|
generics::{
|
||||||
TypeOrConstParamData, TypeParamProvenance, WherePredicate, WherePredicateTypeTarget,
|
TypeOrConstParamData, TypeParamProvenance, WherePredicate, WherePredicateTypeTarget,
|
||||||
},
|
},
|
||||||
intern::Interned,
|
|
||||||
lang_item::lang_attr,
|
lang_item::lang_attr,
|
||||||
path::{GenericArg, ModPath, Path, PathKind, PathSegment, PathSegments},
|
path::{GenericArg, ModPath, Path, PathKind, PathSegment, PathSegments},
|
||||||
resolver::{HasResolver, Resolver, TypeNs},
|
resolver::{HasResolver, Resolver, TypeNs},
|
||||||
|
@ -35,6 +34,7 @@ use hir_def::{
|
||||||
TypeAliasId, TypeOrConstParamId, TypeParamId, UnionId, VariantId,
|
TypeAliasId, TypeOrConstParamId, TypeParamId, UnionId, VariantId,
|
||||||
};
|
};
|
||||||
use hir_expand::{name::Name, ExpandResult};
|
use hir_expand::{name::Name, ExpandResult};
|
||||||
|
use intern::Interned;
|
||||||
use itertools::Either;
|
use itertools::Either;
|
||||||
use la_arena::ArenaMap;
|
use la_arena::ArenaMap;
|
||||||
use rustc_hash::FxHashSet;
|
use rustc_hash::FxHashSet;
|
||||||
|
|
|
@ -11,13 +11,13 @@ use hir_def::{
|
||||||
GenericParams, TypeOrConstParamData, TypeParamProvenance, WherePredicate,
|
GenericParams, TypeOrConstParamData, TypeParamProvenance, WherePredicate,
|
||||||
WherePredicateTypeTarget,
|
WherePredicateTypeTarget,
|
||||||
},
|
},
|
||||||
intern::Interned,
|
|
||||||
resolver::{HasResolver, TypeNs},
|
resolver::{HasResolver, TypeNs},
|
||||||
type_ref::{TraitBoundModifier, TypeRef},
|
type_ref::{TraitBoundModifier, TypeRef},
|
||||||
ConstParamId, FunctionId, GenericDefId, ItemContainerId, Lookup, TraitId, TypeAliasId,
|
ConstParamId, FunctionId, GenericDefId, ItemContainerId, Lookup, TraitId, TypeAliasId,
|
||||||
TypeOrConstParamId, TypeParamId,
|
TypeOrConstParamId, TypeParamId,
|
||||||
};
|
};
|
||||||
use hir_expand::name::Name;
|
use hir_expand::name::Name;
|
||||||
|
use intern::Interned;
|
||||||
use itertools::Either;
|
use itertools::Either;
|
||||||
use rustc_hash::FxHashSet;
|
use rustc_hash::FxHashSet;
|
||||||
use smallvec::{smallvec, SmallVec};
|
use smallvec::{smallvec, SmallVec};
|
||||||
|
|
|
@ -107,7 +107,7 @@ pub use {
|
||||||
cfg::{CfgAtom, CfgExpr, CfgOptions},
|
cfg::{CfgAtom, CfgExpr, CfgOptions},
|
||||||
hir_def::{
|
hir_def::{
|
||||||
adt::StructKind,
|
adt::StructKind,
|
||||||
attr::{Attr, Attrs, AttrsWithOwner, Documentation},
|
attr::{Attrs, AttrsWithOwner, Documentation},
|
||||||
builtin_attr::AttributeTemplate,
|
builtin_attr::AttributeTemplate,
|
||||||
find_path::PrefixKind,
|
find_path::PrefixKind,
|
||||||
import_map,
|
import_map,
|
||||||
|
@ -122,6 +122,7 @@ pub use {
|
||||||
ModuleDefId,
|
ModuleDefId,
|
||||||
},
|
},
|
||||||
hir_expand::{
|
hir_expand::{
|
||||||
|
attrs::Attr,
|
||||||
name::{known, Name},
|
name::{known, Name},
|
||||||
ExpandResult, HirFileId, InFile, MacroFile, Origin,
|
ExpandResult, HirFileId, InFile, MacroFile, Origin,
|
||||||
},
|
},
|
||||||
|
|
|
@ -87,7 +87,6 @@
|
||||||
|
|
||||||
use base_db::FileId;
|
use base_db::FileId;
|
||||||
use hir_def::{
|
use hir_def::{
|
||||||
attr::AttrId,
|
|
||||||
child_by_source::ChildBySource,
|
child_by_source::ChildBySource,
|
||||||
dyn_map::DynMap,
|
dyn_map::DynMap,
|
||||||
expr::{LabelId, PatId},
|
expr::{LabelId, PatId},
|
||||||
|
@ -96,7 +95,7 @@ use hir_def::{
|
||||||
GenericDefId, GenericParamId, ImplId, LifetimeParamId, MacroId, ModuleId, StaticId, StructId,
|
GenericDefId, GenericParamId, ImplId, LifetimeParamId, MacroId, ModuleId, StaticId, StructId,
|
||||||
TraitId, TypeAliasId, TypeParamId, UnionId, VariantId,
|
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 rustc_hash::FxHashMap;
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
use stdx::impl_from;
|
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 once_cell::sync::OnceCell;
|
||||||
use rustc_hash::FxHasher;
|
use rustc_hash::FxHasher;
|
||||||
|
|
||||||
use crate::generics::GenericParams;
|
|
||||||
|
|
||||||
type InternMap<T> = DashMap<Arc<T>, (), BuildHasherDefault<FxHasher>>;
|
type InternMap<T> = DashMap<Arc<T>, (), BuildHasherDefault<FxHasher>>;
|
||||||
type Guard<T> = dashmap::RwLockWriteGuard<
|
type Guard<T> = dashmap::RwLockWriteGuard<
|
||||||
'static,
|
'static,
|
||||||
|
@ -204,9 +202,9 @@ pub trait Internable: Hash + Eq + 'static {
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
macro_rules! _impl_internable {
|
macro_rules! _impl_internable {
|
||||||
( $($t:path),+ $(,)? ) => { $(
|
( $($t:path),+ $(,)? ) => { $(
|
||||||
impl Internable for $t {
|
impl $crate::Internable for $t {
|
||||||
fn storage() -> &'static InternStorage<Self> {
|
fn storage() -> &'static $crate::InternStorage<Self> {
|
||||||
static STORAGE: InternStorage<$t> = InternStorage::new();
|
static STORAGE: $crate::InternStorage<$t> = $crate::InternStorage::new();
|
||||||
&STORAGE
|
&STORAGE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -215,13 +213,4 @@ macro_rules! _impl_internable {
|
||||||
|
|
||||||
pub use crate::_impl_internable as impl_internable;
|
pub use crate::_impl_internable as impl_internable;
|
||||||
|
|
||||||
impl_internable!(
|
impl_internable!(str,);
|
||||||
crate::type_ref::TypeRef,
|
|
||||||
crate::type_ref::TraitRef,
|
|
||||||
crate::type_ref::TypeBound,
|
|
||||||
crate::path::ModPath,
|
|
||||||
crate::path::GenericArgs,
|
|
||||||
crate::attr::AttrInput,
|
|
||||||
GenericParams,
|
|
||||||
str,
|
|
||||||
);
|
|
Loading…
Add table
Add a link
Reference in a new issue