1 //! A higher level attributes based on TokenTree, with also some shortcuts.
4 convert::{TryFrom, TryInto},
10 use cfg::{CfgExpr, CfgOptions};
12 use hir_expand::{hygiene::Hygiene, name::AsName, AstId, InFile};
13 use itertools::Itertools;
14 use la_arena::ArenaMap;
15 use mbe::{syntax_node_to_token_tree, DelimiterKind};
16 use smallvec::{smallvec, SmallVec};
18 ast::{self, AstNode, AttrsOwner},
19 match_ast, AstPtr, AstToken, SmolStr, SyntaxNode, TextRange, TextSize,
26 item_tree::{ItemTreeId, ItemTreeNode},
27 nameres::ModuleSource,
28 path::{ModPath, PathKind},
29 src::{HasChildSource, HasSource},
30 AdtId, AttrDefId, EnumId, GenericParamId, HasModule, LocalEnumVariantId, LocalFieldId, Lookup,
34 /// Holds documentation
35 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
36 pub struct Documentation(String);
39 pub fn new(s: String) -> Self {
43 pub fn as_str(&self) -> &str {
48 impl From<Documentation> for String {
49 fn from(Documentation(string): Documentation) -> Self {
54 /// Syntactical attributes, without filtering of `cfg_attr`s.
55 #[derive(Default, Debug, Clone, PartialEq, Eq)]
56 pub(crate) struct RawAttrs {
57 entries: Option<Arc<[Attr]>>,
60 #[derive(Default, Debug, Clone, PartialEq, Eq)]
61 pub struct Attrs(RawAttrs);
63 #[derive(Debug, Clone, PartialEq, Eq)]
64 pub struct AttrsWithOwner {
69 impl ops::Deref for RawAttrs {
72 fn deref(&self) -> &[Attr] {
80 impl ops::Deref for Attrs {
83 fn deref(&self) -> &[Attr] {
84 match &self.0.entries {
91 impl ops::Deref for AttrsWithOwner {
94 fn deref(&self) -> &Attrs {
100 pub(crate) const EMPTY: Self = Self { entries: None };
103 db: &dyn DefDatabase,
104 owner: &dyn ast::AttrsOwner,
107 let entries = collect_attrs(owner)
108 .flat_map(|(id, attr)| match attr {
109 Either::Left(attr) => {
110 attr.meta().and_then(|meta| Attr::from_src(db, meta, hygiene, id))
112 Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
114 input: Some(Interned::new(AttrInput::Literal(SmolStr::new(doc)))),
115 path: Interned::new(ModPath::from(hir_expand::name!(doc))),
118 .collect::<Arc<_>>();
120 Self { entries: if entries.is_empty() { None } else { Some(entries) } }
123 fn from_attrs_owner(db: &dyn DefDatabase, owner: InFile<&dyn ast::AttrsOwner>) -> Self {
124 let hygiene = Hygiene::new(db.upcast(), owner.file_id);
125 Self::new(db, owner.value, &hygiene)
128 pub(crate) fn merge(&self, other: Self) -> Self {
129 // FIXME: This needs to fixup `AttrId`s
130 match (&self.entries, &other.entries) {
131 (None, None) => Self::EMPTY,
132 (Some(entries), None) | (None, Some(entries)) => {
133 Self { entries: Some(entries.clone()) }
135 (Some(a), Some(b)) => {
136 Self { entries: Some(a.iter().chain(b.iter()).cloned().collect()) }
141 /// Processes `cfg_attr`s, returning the resulting semantic `Attrs`.
142 pub(crate) fn filter(self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
143 let has_cfg_attrs = self.iter().any(|attr| {
144 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr])
150 let crate_graph = db.crate_graph();
153 .flat_map(|attr| -> SmallVec<[_; 1]> {
155 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr]);
157 return smallvec![attr.clone()];
160 let subtree = match attr.input.as_deref() {
161 Some(AttrInput::TokenTree(it)) => it,
162 _ => return smallvec![attr.clone()],
165 // Input subtree is: `(cfg, $(attr),+)`
166 // Split it up into a `cfg` subtree and the `attr` subtrees.
167 // FIXME: There should be a common API for this.
168 let mut parts = subtree.token_trees.split(
169 |tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ','),
171 let cfg = parts.next().unwrap();
172 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
173 let cfg = CfgExpr::parse(&cfg);
175 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
176 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
178 let hygiene = Hygiene::new_unhygienic();
179 Attr::from_tt(db, &tree, &hygiene, index)
182 let cfg_options = &crate_graph[krate].cfg_options;
183 if cfg_options.check(&cfg) == Some(false) {
186 cov_mark::hit!(cfg_attr_active);
193 Attrs(RawAttrs { entries: Some(new_attrs) })
198 pub const EMPTY: Self = Self(RawAttrs::EMPTY);
200 pub(crate) fn variants_attrs_query(
201 db: &dyn DefDatabase,
203 ) -> Arc<ArenaMap<LocalEnumVariantId, Attrs>> {
204 let krate = e.lookup(db).container.krate;
205 let src = e.child_source(db);
206 let mut res = ArenaMap::default();
208 for (id, var) in src.value.iter() {
209 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(var as &dyn ast::AttrsOwner))
212 res.insert(id, attrs)
218 pub(crate) fn fields_attrs_query(
219 db: &dyn DefDatabase,
221 ) -> Arc<ArenaMap<LocalFieldId, Attrs>> {
222 let krate = v.module(db).krate;
223 let src = v.child_source(db);
224 let mut res = ArenaMap::default();
226 for (id, fld) in src.value.iter() {
227 let owner: &dyn AttrsOwner = match fld {
228 Either::Left(tuple) => tuple,
229 Either::Right(record) => record,
231 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(owner)).filter(db, krate);
233 res.insert(id, attrs);
239 pub fn by_key(&self, key: &'static str) -> AttrQuery<'_> {
240 AttrQuery { attrs: self, key }
243 pub fn cfg(&self) -> Option<CfgExpr> {
244 let mut cfgs = self.by_key("cfg").tt_values().map(CfgExpr::parse).collect::<Vec<_>>();
247 1 => Some(cfgs.pop().unwrap()),
248 _ => Some(CfgExpr::All(cfgs)),
251 pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool {
254 Some(cfg) => cfg_options.check(&cfg) != Some(false),
258 pub fn docs(&self) -> Option<Documentation> {
259 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
260 AttrInput::Literal(s) => Some(s),
261 AttrInput::TokenTree(_) => None,
265 .flat_map(|s| s.lines())
266 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
267 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
270 let mut buf = String::new();
272 // str::lines doesn't yield anything for the empty string
274 buf.extend(Itertools::intersperse(
275 doc.lines().map(|line| {
278 .map_or(line, |(offset, _)| &line[offset..])
290 Some(Documentation(buf))
294 pub fn has_doc_hidden(&self) -> bool {
295 self.by_key("doc").tt_values().any(|tt| {
296 tt.delimiter_kind() == Some(DelimiterKind::Parenthesis) &&
297 matches!(&*tt.token_trees, [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "hidden")
302 impl AttrsWithOwner {
303 pub(crate) fn attrs_query(db: &dyn DefDatabase, def: AttrDefId) -> Self {
304 // FIXME: this should use `Trace` to avoid duplication in `source_map` below
305 let raw_attrs = match def {
306 AttrDefId::ModuleId(module) => {
307 let def_map = module.def_map(db);
308 let mod_data = &def_map[module.local_id];
309 match mod_data.declaration_source(db) {
311 let raw_attrs = RawAttrs::from_attrs_owner(
313 it.as_ref().map(|it| it as &dyn ast::AttrsOwner),
315 match mod_data.definition_source(db) {
316 InFile { file_id, value: ModuleSource::SourceFile(file) } => raw_attrs
317 .merge(RawAttrs::from_attrs_owner(db, InFile::new(file_id, &file))),
321 None => RawAttrs::from_attrs_owner(
323 mod_data.definition_source(db).as_ref().map(|src| match src {
324 ModuleSource::SourceFile(file) => file as &dyn ast::AttrsOwner,
325 ModuleSource::Module(module) => module as &dyn ast::AttrsOwner,
326 ModuleSource::BlockExpr(block) => block as &dyn ast::AttrsOwner,
331 AttrDefId::FieldId(it) => {
332 return Self { attrs: db.fields_attrs(it.parent)[it.local_id].clone(), owner: def };
334 AttrDefId::EnumVariantId(it) => {
336 attrs: db.variants_attrs(it.parent)[it.local_id].clone(),
340 AttrDefId::AdtId(it) => match it {
341 AdtId::StructId(it) => attrs_from_item_tree(it.lookup(db).id, db),
342 AdtId::EnumId(it) => attrs_from_item_tree(it.lookup(db).id, db),
343 AdtId::UnionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
345 AttrDefId::TraitId(it) => attrs_from_item_tree(it.lookup(db).id, db),
346 AttrDefId::MacroDefId(it) => it
348 .either(|ast_id| attrs_from_ast(ast_id, db), |ast_id| attrs_from_ast(ast_id, db)),
349 AttrDefId::ImplId(it) => attrs_from_item_tree(it.lookup(db).id, db),
350 AttrDefId::ConstId(it) => attrs_from_item_tree(it.lookup(db).id, db),
351 AttrDefId::StaticId(it) => attrs_from_item_tree(it.lookup(db).id, db),
352 AttrDefId::FunctionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
353 AttrDefId::TypeAliasId(it) => attrs_from_item_tree(it.lookup(db).id, db),
354 AttrDefId::GenericParamId(it) => match it {
355 GenericParamId::TypeParamId(it) => {
356 let src = it.parent.child_source(db);
357 RawAttrs::from_attrs_owner(
360 src.value[it.local_id].as_ref().either(|it| it as _, |it| it as _),
364 GenericParamId::LifetimeParamId(it) => {
365 let src = it.parent.child_source(db);
366 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
368 GenericParamId::ConstParamId(it) => {
369 let src = it.parent.child_source(db);
370 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
375 let attrs = raw_attrs.filter(db, def.krate(db));
376 Self { attrs, owner: def }
379 pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
380 let owner = match self.owner {
381 AttrDefId::ModuleId(module) => {
382 // Modules can have 2 attribute owners (the `mod x;` item, and the module file itself).
384 let def_map = module.def_map(db);
385 let mod_data = &def_map[module.local_id];
386 match mod_data.declaration_source(db) {
388 let mut map = AttrSourceMap::new(InFile::new(it.file_id, &it.value));
389 if let InFile { file_id, value: ModuleSource::SourceFile(file) } =
390 mod_data.definition_source(db)
392 map.merge(AttrSourceMap::new(InFile::new(file_id, &file)));
397 let InFile { file_id, value } = mod_data.definition_source(db);
398 let attrs_owner = match &value {
399 ModuleSource::SourceFile(file) => file as &dyn ast::AttrsOwner,
400 ModuleSource::Module(module) => module as &dyn ast::AttrsOwner,
401 ModuleSource::BlockExpr(block) => block as &dyn ast::AttrsOwner,
403 return AttrSourceMap::new(InFile::new(file_id, attrs_owner));
407 AttrDefId::FieldId(id) => {
408 let map = db.fields_attrs_source_map(id.parent);
409 let file_id = id.parent.file_id(db);
410 let root = db.parse_or_expand(file_id).unwrap();
411 let owner = match &map[id.local_id] {
412 Either::Left(it) => ast::AttrsOwnerNode::new(it.to_node(&root)),
413 Either::Right(it) => ast::AttrsOwnerNode::new(it.to_node(&root)),
415 InFile::new(file_id, owner)
417 AttrDefId::AdtId(adt) => match adt {
418 AdtId::StructId(id) => id.lookup(db).source(db).map(ast::AttrsOwnerNode::new),
419 AdtId::UnionId(id) => id.lookup(db).source(db).map(ast::AttrsOwnerNode::new),
420 AdtId::EnumId(id) => id.lookup(db).source(db).map(ast::AttrsOwnerNode::new),
422 AttrDefId::FunctionId(id) => id.lookup(db).source(db).map(ast::AttrsOwnerNode::new),
423 AttrDefId::EnumVariantId(id) => {
424 let map = db.variants_attrs_source_map(id.parent);
425 let file_id = id.parent.lookup(db).id.file_id();
426 let root = db.parse_or_expand(file_id).unwrap();
427 InFile::new(file_id, ast::AttrsOwnerNode::new(map[id.local_id].to_node(&root)))
429 AttrDefId::StaticId(id) => id.lookup(db).source(db).map(ast::AttrsOwnerNode::new),
430 AttrDefId::ConstId(id) => id.lookup(db).source(db).map(ast::AttrsOwnerNode::new),
431 AttrDefId::TraitId(id) => id.lookup(db).source(db).map(ast::AttrsOwnerNode::new),
432 AttrDefId::TypeAliasId(id) => id.lookup(db).source(db).map(ast::AttrsOwnerNode::new),
433 AttrDefId::MacroDefId(id) => id.ast_id().either(
434 |it| it.with_value(ast::AttrsOwnerNode::new(it.to_node(db.upcast()))),
435 |it| it.with_value(ast::AttrsOwnerNode::new(it.to_node(db.upcast()))),
437 AttrDefId::ImplId(id) => id.lookup(db).source(db).map(ast::AttrsOwnerNode::new),
438 AttrDefId::GenericParamId(id) => match id {
439 GenericParamId::TypeParamId(id) => {
440 id.parent.child_source(db).map(|source| match &source[id.local_id] {
441 Either::Left(id) => ast::AttrsOwnerNode::new(id.clone()),
442 Either::Right(id) => ast::AttrsOwnerNode::new(id.clone()),
445 GenericParamId::LifetimeParamId(id) => id
448 .map(|source| ast::AttrsOwnerNode::new(source[id.local_id].clone())),
449 GenericParamId::ConstParamId(id) => id
452 .map(|source| ast::AttrsOwnerNode::new(source[id.local_id].clone())),
456 AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn AttrsOwner))
459 pub fn docs_with_rangemap(
461 db: &dyn DefDatabase,
462 ) -> Option<(Documentation, DocsRangeMap)> {
463 // FIXME: code duplication in `docs` above
464 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
465 AttrInput::Literal(s) => Some((s, attr.id)),
466 AttrInput::TokenTree(_) => None,
470 .flat_map(|(s, _)| s.lines())
471 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
472 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
475 let mut buf = String::new();
476 let mut mapping = Vec::new();
477 for (doc, idx) in docs {
479 let mut base_offset = 0;
480 for raw_line in doc.split('\n') {
481 let line = raw_line.trim_end();
482 let line_len = line.len();
483 let (offset, line) = match line.char_indices().nth(indent) {
484 Some((offset, _)) => (offset, &line[offset..]),
487 let buf_offset = buf.len();
490 TextRange::new(buf_offset.try_into().ok()?, buf.len().try_into().ok()?),
493 (base_offset + offset).try_into().ok()?,
494 line_len.try_into().ok()?,
498 base_offset += raw_line.len() + 1;
508 Some((Documentation(buf), DocsRangeMap { mapping, source_map: self.source_map(db) }))
515 ) -> Option<(impl Iterator<Item = ast::Attr>, impl Iterator<Item = ast::Comment>)> {
516 let (attrs, docs) = match_ast! {
518 ast::SourceFile(it) => (it.attrs(), ast::CommentIter::from_syntax_node(it.syntax())),
519 ast::ExternBlock(it) => {
520 let extern_item_list = it.extern_item_list()?;
521 (extern_item_list.attrs(), ast::CommentIter::from_syntax_node(extern_item_list.syntax()))
524 let body = it.body()?;
525 (body.attrs(), ast::CommentIter::from_syntax_node(body.syntax()))
528 let assoc_item_list = it.assoc_item_list()?;
529 (assoc_item_list.attrs(), ast::CommentIter::from_syntax_node(assoc_item_list.syntax()))
532 let item_list = it.item_list()?;
533 (item_list.attrs(), ast::CommentIter::from_syntax_node(item_list.syntax()))
535 // FIXME: BlockExpr's only accept inner attributes in specific cases
536 // Excerpt from the reference:
537 // Block expressions accept outer and inner attributes, but only when they are the outer
538 // expression of an expression statement or the final expression of another block expression.
539 ast::BlockExpr(_it) => return None,
543 let attrs = attrs.filter(|attr| attr.kind().is_inner());
544 let docs = docs.filter(|doc| doc.is_inner());
548 pub struct AttrSourceMap {
549 attrs: Vec<InFile<ast::Attr>>,
550 doc_comments: Vec<InFile<ast::Comment>>,
554 fn new(owner: InFile<&dyn ast::AttrsOwner>) -> Self {
555 let mut attrs = Vec::new();
556 let mut doc_comments = Vec::new();
557 for (_, attr) in collect_attrs(owner.value) {
559 Either::Left(attr) => attrs.push(owner.with_value(attr)),
560 Either::Right(comment) => doc_comments.push(owner.with_value(comment)),
564 Self { attrs, doc_comments }
567 fn merge(&mut self, other: Self) {
568 self.attrs.extend(other.attrs);
569 self.doc_comments.extend(other.doc_comments);
572 /// Maps the lowered `Attr` back to its original syntax node.
574 /// `attr` must come from the `owner` used for AttrSourceMap
576 /// Note that the returned syntax node might be a `#[cfg_attr]`, or a doc comment, instead of
577 /// the attribute represented by `Attr`.
578 pub fn source_of(&self, attr: &Attr) -> InFile<Either<ast::Attr, ast::Comment>> {
579 self.source_of_id(attr.id)
582 fn source_of_id(&self, id: AttrId) -> InFile<Either<ast::Attr, ast::Comment>> {
583 if id.is_doc_comment {
585 .get(id.ast_index as usize)
586 .unwrap_or_else(|| panic!("cannot find doc comment at index {:?}", id))
591 .get(id.ast_index as usize)
592 .unwrap_or_else(|| panic!("cannot find `Attr` at index {:?}", id))
599 /// A struct to map text ranges from [`Documentation`] back to TextRanges in the syntax tree.
600 pub struct DocsRangeMap {
601 source_map: AttrSourceMap,
602 // (docstring-line-range, attr_index, attr-string-range)
603 // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
604 // the original (untrimmed) syntax doc line
605 mapping: Vec<(TextRange, AttrId, TextRange)>,
609 pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
610 let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
611 let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
612 if !line_docs_range.contains_range(range) {
616 let relative_range = range - line_docs_range.start();
618 let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
620 Either::Left(_) => None, // FIXME, figure out a nice way to handle doc attributes here
621 // as well as for whats done in syntax highlight doc injection
622 Either::Right(comment) => {
623 let text_range = comment.syntax().text_range();
624 let range = TextRange::at(
626 + TextSize::try_from(comment.prefix().len()).ok()?
627 + original_line_src_range.start()
628 + relative_range.start(),
629 text_range.len().min(range.len()),
631 Some(InFile { file_id, value: range })
637 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
638 pub(crate) struct AttrId {
639 is_doc_comment: bool,
640 pub(crate) ast_index: u32,
643 #[derive(Debug, Clone, PartialEq, Eq)]
645 pub(crate) id: AttrId,
646 pub(crate) path: Interned<ModPath>,
647 pub(crate) input: Option<Interned<AttrInput>>,
650 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
652 /// `#[attr = "string"]`
654 /// `#[attr(subtree)]`
658 impl fmt::Display for AttrInput {
659 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661 AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
662 AttrInput::TokenTree(subtree) => subtree.fmt(f),
669 db: &dyn DefDatabase,
674 let path = Interned::new(ModPath::from_src(db, ast.path()?, hygiene)?);
675 let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
676 let value = match lit.kind() {
677 ast::LiteralKind::String(string) => string.value()?.into(),
678 _ => lit.syntax().first_token()?.text().trim_matches('"').into(),
680 Some(Interned::new(AttrInput::Literal(value)))
681 } else if let Some(tt) = ast.token_tree() {
682 Some(Interned::new(AttrInput::TokenTree(syntax_node_to_token_tree(tt.syntax()).0)))
686 Some(Attr { id, path, input })
690 db: &dyn DefDatabase,
696 mbe::token_tree_to_syntax_node(tt, hir_expand::FragmentKind::MetaItem).ok()?;
697 let ast = ast::Meta::cast(parse.syntax_node())?;
699 Self::from_src(db, ast, hygiene, id)
702 /// Parses this attribute as a `#[derive]`, returns an iterator that yields all contained paths
703 /// to derive macros.
705 /// Returns `None` when the attribute is not a well-formed `#[derive]` attribute.
706 pub(crate) fn parse_derive(&self) -> Option<impl Iterator<Item = ModPath>> {
707 if self.path.as_ident() != Some(&hir_expand::name![derive]) {
711 match self.input.as_deref() {
712 Some(AttrInput::TokenTree(args)) => {
717 .group_by(move |tt| {
719 tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ',' => {
728 let segments = tts.filter_map(|tt| match tt {
729 tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
732 ModPath::from_segments(PathKind::Plain, segments)
734 .collect::<Vec<_>>();
736 Some(paths.into_iter())
742 pub fn string_value(&self) -> Option<&SmolStr> {
743 match self.input.as_deref()? {
744 AttrInput::Literal(it) => Some(it),
750 #[derive(Debug, Clone, Copy)]
751 pub struct AttrQuery<'a> {
756 impl<'a> AttrQuery<'a> {
757 pub fn tt_values(self) -> impl Iterator<Item = &'a Subtree> {
758 self.attrs().filter_map(|attr| match attr.input.as_deref()? {
759 AttrInput::TokenTree(it) => Some(it),
764 pub fn string_value(self) -> Option<&'a SmolStr> {
765 self.attrs().find_map(|attr| match attr.input.as_deref()? {
766 AttrInput::Literal(it) => Some(it),
771 pub fn exists(self) -> bool {
772 self.attrs().next().is_some()
775 pub fn attrs(self) -> impl Iterator<Item = &'a Attr> + Clone {
779 .filter(move |attr| attr.path.as_ident().map_or(false, |s| s.to_string() == key))
783 fn attrs_from_ast<N>(src: AstId<N>, db: &dyn DefDatabase) -> RawAttrs
787 let src = InFile::new(src.file_id, src.to_node(db.upcast()));
788 RawAttrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn ast::AttrsOwner))
791 fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase) -> RawAttrs {
792 let tree = id.item_tree(db);
793 let mod_item = N::id_to_mod_item(id.value);
794 tree.raw_attrs(mod_item.into()).clone()
798 owner: &dyn ast::AttrsOwner,
799 ) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
800 let (inner_attrs, inner_docs) = inner_attributes(owner.syntax())
801 .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs)));
803 let outer_attrs = owner.attrs().filter(|attr| attr.kind().is_outer());
805 outer_attrs.chain(inner_attrs.into_iter().flatten()).enumerate().map(|(idx, attr)| {
807 AttrId { ast_index: idx as u32, is_doc_comment: false },
808 attr.syntax().text_range().start(),
814 ast::CommentIter::from_syntax_node(owner.syntax()).filter(ast::Comment::is_outer);
816 outer_docs.chain(inner_docs.into_iter().flatten()).enumerate().map(|(idx, docs_text)| {
818 AttrId { ast_index: idx as u32, is_doc_comment: true },
819 docs_text.syntax().text_range().start(),
820 Either::Right(docs_text),
823 // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved
824 docs.chain(attrs).sorted_by_key(|&(_, offset, _)| offset).map(|(id, _, attr)| (id, attr))
827 pub(crate) fn variants_attrs_source_map(
828 db: &dyn DefDatabase,
830 ) -> Arc<ArenaMap<LocalEnumVariantId, AstPtr<ast::Variant>>> {
831 let mut res = ArenaMap::default();
832 let child_source = def.child_source(db);
834 for (idx, variant) in child_source.value.iter() {
835 res.insert(idx, AstPtr::new(variant));
841 pub(crate) fn fields_attrs_source_map(
842 db: &dyn DefDatabase,
844 ) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>> {
845 let mut res = ArenaMap::default();
846 let child_source = def.child_source(db);
848 for (idx, variant) in child_source.value.iter() {
853 .either(|l| Either::Left(AstPtr::new(l)), |r| Either::Right(AstPtr::new(r))),