1 //! A higher level attributes based on TokenTree, with also some shortcuts.
4 convert::{TryFrom, TryInto},
12 use cfg::{CfgExpr, CfgOptions};
14 use hir_expand::{hygiene::Hygiene, name::AsName, AstId, InFile};
15 use itertools::Itertools;
16 use la_arena::ArenaMap;
17 use mbe::{syntax_node_to_token_tree, DelimiterKind};
18 use smallvec::{smallvec, SmallVec};
20 ast::{self, AstNode, AttrsOwner},
21 match_ast, AstPtr, AstToken, SmolStr, SyntaxNode, TextRange, TextSize,
28 item_tree::{ItemTreeId, ItemTreeNode},
29 nameres::ModuleSource,
30 path::{ModPath, PathKind},
31 src::{HasChildSource, HasSource},
32 AdtId, AttrDefId, EnumId, GenericParamId, HasModule, LocalEnumVariantId, LocalFieldId, Lookup,
36 /// Holds documentation
37 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
38 pub struct Documentation(String);
41 pub fn new(s: String) -> Self {
45 pub fn as_str(&self) -> &str {
50 impl From<Documentation> for String {
51 fn from(Documentation(string): Documentation) -> Self {
56 /// Syntactical attributes, without filtering of `cfg_attr`s.
57 #[derive(Default, Debug, Clone, PartialEq, Eq)]
58 pub(crate) struct RawAttrs {
59 entries: Option<Arc<[Attr]>>,
62 #[derive(Default, Debug, Clone, PartialEq, Eq)]
63 pub struct Attrs(RawAttrs);
65 #[derive(Debug, Clone, PartialEq, Eq)]
66 pub struct AttrsWithOwner {
71 impl ops::Deref for RawAttrs {
74 fn deref(&self) -> &[Attr] {
82 impl ops::Deref for Attrs {
85 fn deref(&self) -> &[Attr] {
86 match &self.0.entries {
93 impl ops::Deref for AttrsWithOwner {
96 fn deref(&self) -> &Attrs {
102 pub(crate) const EMPTY: Self = Self { entries: None };
105 db: &dyn DefDatabase,
106 owner: &dyn ast::AttrsOwner,
109 let entries = collect_attrs(owner)
110 .flat_map(|(id, attr)| match attr {
111 Either::Left(attr) => {
112 attr.meta().and_then(|meta| Attr::from_src(db, meta, hygiene, id))
114 Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
116 input: Some(Interned::new(AttrInput::Literal(SmolStr::new(doc)))),
117 path: Interned::new(ModPath::from(hir_expand::name!(doc))),
120 .collect::<Arc<_>>();
122 Self { entries: if entries.is_empty() { None } else { Some(entries) } }
125 fn from_attrs_owner(db: &dyn DefDatabase, owner: InFile<&dyn ast::AttrsOwner>) -> Self {
126 let hygiene = Hygiene::new(db.upcast(), owner.file_id);
127 Self::new(db, owner.value, &hygiene)
130 pub(crate) fn merge(&self, other: Self) -> Self {
131 // FIXME: This needs to fixup `AttrId`s
132 match (&self.entries, &other.entries) {
133 (None, None) => Self::EMPTY,
134 (Some(entries), None) | (None, Some(entries)) => {
135 Self { entries: Some(entries.clone()) }
137 (Some(a), Some(b)) => {
138 Self { entries: Some(a.iter().chain(b.iter()).cloned().collect()) }
143 /// Processes `cfg_attr`s, returning the resulting semantic `Attrs`.
144 pub(crate) fn filter(self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
145 let has_cfg_attrs = self.iter().any(|attr| {
146 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr])
152 let crate_graph = db.crate_graph();
155 .flat_map(|attr| -> SmallVec<[_; 1]> {
157 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr]);
159 return smallvec![attr.clone()];
162 let subtree = match attr.input.as_deref() {
163 Some(AttrInput::TokenTree(it, _)) => it,
164 _ => return smallvec![attr.clone()],
167 // Input subtree is: `(cfg, $(attr),+)`
168 // Split it up into a `cfg` subtree and the `attr` subtrees.
169 // FIXME: There should be a common API for this.
170 let mut parts = subtree.token_trees.split(
171 |tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ','),
173 let cfg = parts.next().unwrap();
174 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
175 let cfg = CfgExpr::parse(&cfg);
177 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
178 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
180 let hygiene = Hygiene::new_unhygienic();
181 Attr::from_tt(db, &tree, &hygiene, index)
184 let cfg_options = &crate_graph[krate].cfg_options;
185 if cfg_options.check(&cfg) == Some(false) {
188 cov_mark::hit!(cfg_attr_active);
195 Attrs(RawAttrs { entries: Some(new_attrs) })
200 pub const EMPTY: Self = Self(RawAttrs::EMPTY);
202 pub(crate) fn variants_attrs_query(
203 db: &dyn DefDatabase,
205 ) -> Arc<ArenaMap<LocalEnumVariantId, Attrs>> {
206 let krate = e.lookup(db).container.krate;
207 let src = e.child_source(db);
208 let mut res = ArenaMap::default();
210 for (id, var) in src.value.iter() {
211 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(var as &dyn ast::AttrsOwner))
214 res.insert(id, attrs)
220 pub(crate) fn fields_attrs_query(
221 db: &dyn DefDatabase,
223 ) -> Arc<ArenaMap<LocalFieldId, Attrs>> {
224 let krate = v.module(db).krate;
225 let src = v.child_source(db);
226 let mut res = ArenaMap::default();
228 for (id, fld) in src.value.iter() {
229 let owner: &dyn AttrsOwner = match fld {
230 Either::Left(tuple) => tuple,
231 Either::Right(record) => record,
233 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(owner)).filter(db, krate);
235 res.insert(id, attrs);
241 pub fn by_key(&self, key: &'static str) -> AttrQuery<'_> {
242 AttrQuery { attrs: self, key }
245 pub fn cfg(&self) -> Option<CfgExpr> {
246 let mut cfgs = self.by_key("cfg").tt_values().map(CfgExpr::parse).collect::<Vec<_>>();
249 1 => Some(cfgs.pop().unwrap()),
250 _ => Some(CfgExpr::All(cfgs)),
253 pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool {
256 Some(cfg) => cfg_options.check(&cfg) != Some(false),
260 pub fn docs(&self) -> Option<Documentation> {
261 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
262 AttrInput::Literal(s) => Some(s),
263 AttrInput::TokenTree(..) => None,
267 .flat_map(|s| s.lines())
268 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
269 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
272 let mut buf = String::new();
274 // str::lines doesn't yield anything for the empty string
276 buf.extend(Itertools::intersperse(
277 doc.lines().map(|line| {
280 .map_or(line, |(offset, _)| &line[offset..])
292 Some(Documentation(buf))
296 pub fn has_doc_hidden(&self) -> bool {
297 self.by_key("doc").tt_values().any(|tt| {
298 tt.delimiter_kind() == Some(DelimiterKind::Parenthesis) &&
299 matches!(&*tt.token_trees, [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "hidden")
304 impl AttrsWithOwner {
305 pub(crate) fn attrs_query(db: &dyn DefDatabase, def: AttrDefId) -> Self {
306 // FIXME: this should use `Trace` to avoid duplication in `source_map` below
307 let raw_attrs = match def {
308 AttrDefId::ModuleId(module) => {
309 let def_map = module.def_map(db);
310 let mod_data = &def_map[module.local_id];
311 match mod_data.declaration_source(db) {
313 let raw_attrs = RawAttrs::from_attrs_owner(
315 it.as_ref().map(|it| it as &dyn ast::AttrsOwner),
317 match mod_data.definition_source(db) {
318 InFile { file_id, value: ModuleSource::SourceFile(file) } => raw_attrs
319 .merge(RawAttrs::from_attrs_owner(db, InFile::new(file_id, &file))),
323 None => RawAttrs::from_attrs_owner(
325 mod_data.definition_source(db).as_ref().map(|src| match src {
326 ModuleSource::SourceFile(file) => file as &dyn ast::AttrsOwner,
327 ModuleSource::Module(module) => module as &dyn ast::AttrsOwner,
328 ModuleSource::BlockExpr(block) => block as &dyn ast::AttrsOwner,
333 AttrDefId::FieldId(it) => {
334 return Self { attrs: db.fields_attrs(it.parent)[it.local_id].clone(), owner: def };
336 AttrDefId::EnumVariantId(it) => {
338 attrs: db.variants_attrs(it.parent)[it.local_id].clone(),
342 AttrDefId::AdtId(it) => match it {
343 AdtId::StructId(it) => attrs_from_item_tree(it.lookup(db).id, db),
344 AdtId::EnumId(it) => attrs_from_item_tree(it.lookup(db).id, db),
345 AdtId::UnionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
347 AttrDefId::TraitId(it) => attrs_from_item_tree(it.lookup(db).id, db),
348 AttrDefId::MacroDefId(it) => it
350 .either(|ast_id| attrs_from_ast(ast_id, db), |ast_id| attrs_from_ast(ast_id, db)),
351 AttrDefId::ImplId(it) => attrs_from_item_tree(it.lookup(db).id, db),
352 AttrDefId::ConstId(it) => attrs_from_item_tree(it.lookup(db).id, db),
353 AttrDefId::StaticId(it) => attrs_from_item_tree(it.lookup(db).id, db),
354 AttrDefId::FunctionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
355 AttrDefId::TypeAliasId(it) => attrs_from_item_tree(it.lookup(db).id, db),
356 AttrDefId::GenericParamId(it) => match it {
357 GenericParamId::TypeParamId(it) => {
358 let src = it.parent.child_source(db);
359 RawAttrs::from_attrs_owner(
362 src.value[it.local_id].as_ref().either(|it| it as _, |it| it as _),
366 GenericParamId::LifetimeParamId(it) => {
367 let src = it.parent.child_source(db);
368 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
370 GenericParamId::ConstParamId(it) => {
371 let src = it.parent.child_source(db);
372 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
377 let attrs = raw_attrs.filter(db, def.krate(db));
378 Self { attrs, owner: def }
381 pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
382 let owner = match self.owner {
383 AttrDefId::ModuleId(module) => {
384 // Modules can have 2 attribute owners (the `mod x;` item, and the module file itself).
386 let def_map = module.def_map(db);
387 let mod_data = &def_map[module.local_id];
388 match mod_data.declaration_source(db) {
390 let mut map = AttrSourceMap::new(InFile::new(it.file_id, &it.value));
391 if let InFile { file_id, value: ModuleSource::SourceFile(file) } =
392 mod_data.definition_source(db)
394 map.merge(AttrSourceMap::new(InFile::new(file_id, &file)));
399 let InFile { file_id, value } = mod_data.definition_source(db);
400 let attrs_owner = match &value {
401 ModuleSource::SourceFile(file) => file as &dyn ast::AttrsOwner,
402 ModuleSource::Module(module) => module as &dyn ast::AttrsOwner,
403 ModuleSource::BlockExpr(block) => block as &dyn ast::AttrsOwner,
405 return AttrSourceMap::new(InFile::new(file_id, attrs_owner));
409 AttrDefId::FieldId(id) => {
410 let map = db.fields_attrs_source_map(id.parent);
411 let file_id = id.parent.file_id(db);
412 let root = db.parse_or_expand(file_id).unwrap();
413 let owner = match &map[id.local_id] {
414 Either::Left(it) => ast::DynAttrsOwner::new(it.to_node(&root)),
415 Either::Right(it) => ast::DynAttrsOwner::new(it.to_node(&root)),
417 InFile::new(file_id, owner)
419 AttrDefId::AdtId(adt) => match adt {
420 AdtId::StructId(id) => id.lookup(db).source(db).map(ast::DynAttrsOwner::new),
421 AdtId::UnionId(id) => id.lookup(db).source(db).map(ast::DynAttrsOwner::new),
422 AdtId::EnumId(id) => id.lookup(db).source(db).map(ast::DynAttrsOwner::new),
424 AttrDefId::FunctionId(id) => id.lookup(db).source(db).map(ast::DynAttrsOwner::new),
425 AttrDefId::EnumVariantId(id) => {
426 let map = db.variants_attrs_source_map(id.parent);
427 let file_id = id.parent.lookup(db).id.file_id();
428 let root = db.parse_or_expand(file_id).unwrap();
429 InFile::new(file_id, ast::DynAttrsOwner::new(map[id.local_id].to_node(&root)))
431 AttrDefId::StaticId(id) => id.lookup(db).source(db).map(ast::DynAttrsOwner::new),
432 AttrDefId::ConstId(id) => id.lookup(db).source(db).map(ast::DynAttrsOwner::new),
433 AttrDefId::TraitId(id) => id.lookup(db).source(db).map(ast::DynAttrsOwner::new),
434 AttrDefId::TypeAliasId(id) => id.lookup(db).source(db).map(ast::DynAttrsOwner::new),
435 AttrDefId::MacroDefId(id) => id.ast_id().either(
436 |it| it.with_value(ast::DynAttrsOwner::new(it.to_node(db.upcast()))),
437 |it| it.with_value(ast::DynAttrsOwner::new(it.to_node(db.upcast()))),
439 AttrDefId::ImplId(id) => id.lookup(db).source(db).map(ast::DynAttrsOwner::new),
440 AttrDefId::GenericParamId(id) => match id {
441 GenericParamId::TypeParamId(id) => {
442 id.parent.child_source(db).map(|source| match &source[id.local_id] {
443 Either::Left(id) => ast::DynAttrsOwner::new(id.clone()),
444 Either::Right(id) => ast::DynAttrsOwner::new(id.clone()),
447 GenericParamId::LifetimeParamId(id) => id
450 .map(|source| ast::DynAttrsOwner::new(source[id.local_id].clone())),
451 GenericParamId::ConstParamId(id) => id
454 .map(|source| ast::DynAttrsOwner::new(source[id.local_id].clone())),
458 AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn AttrsOwner))
461 pub fn docs_with_rangemap(
463 db: &dyn DefDatabase,
464 ) -> Option<(Documentation, DocsRangeMap)> {
465 // FIXME: code duplication in `docs` above
466 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
467 AttrInput::Literal(s) => Some((s, attr.id)),
468 AttrInput::TokenTree(..) => None,
472 .flat_map(|(s, _)| s.lines())
473 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
474 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
477 let mut buf = String::new();
478 let mut mapping = Vec::new();
479 for (doc, idx) in docs {
481 let mut base_offset = 0;
482 for raw_line in doc.split('\n') {
483 let line = raw_line.trim_end();
484 let line_len = line.len();
485 let (offset, line) = match line.char_indices().nth(indent) {
486 Some((offset, _)) => (offset, &line[offset..]),
489 let buf_offset = buf.len();
492 TextRange::new(buf_offset.try_into().ok()?, buf.len().try_into().ok()?),
495 (base_offset + offset).try_into().ok()?,
496 line_len.try_into().ok()?,
500 base_offset += raw_line.len() + 1;
510 Some((Documentation(buf), DocsRangeMap { mapping, source_map: self.source_map(db) }))
517 ) -> Option<(impl Iterator<Item = ast::Attr>, impl Iterator<Item = ast::Comment>)> {
518 let (attrs, docs) = match_ast! {
520 ast::SourceFile(it) => (it.attrs(), ast::CommentIter::from_syntax_node(it.syntax())),
521 ast::ExternBlock(it) => {
522 let extern_item_list = it.extern_item_list()?;
523 (extern_item_list.attrs(), ast::CommentIter::from_syntax_node(extern_item_list.syntax()))
526 let body = it.body()?;
527 (body.attrs(), ast::CommentIter::from_syntax_node(body.syntax()))
530 let assoc_item_list = it.assoc_item_list()?;
531 (assoc_item_list.attrs(), ast::CommentIter::from_syntax_node(assoc_item_list.syntax()))
534 let item_list = it.item_list()?;
535 (item_list.attrs(), ast::CommentIter::from_syntax_node(item_list.syntax()))
537 // FIXME: BlockExpr's only accept inner attributes in specific cases
538 // Excerpt from the reference:
539 // Block expressions accept outer and inner attributes, but only when they are the outer
540 // expression of an expression statement or the final expression of another block expression.
541 ast::BlockExpr(_it) => return None,
545 let attrs = attrs.filter(|attr| attr.kind().is_inner());
546 let docs = docs.filter(|doc| doc.is_inner());
551 pub struct AttrSourceMap {
552 attrs: Vec<InFile<ast::Attr>>,
553 doc_comments: Vec<InFile<ast::Comment>>,
557 fn new(owner: InFile<&dyn ast::AttrsOwner>) -> Self {
558 let mut attrs = Vec::new();
559 let mut doc_comments = Vec::new();
560 for (_, attr) in collect_attrs(owner.value) {
562 Either::Left(attr) => attrs.push(owner.with_value(attr)),
563 Either::Right(comment) => doc_comments.push(owner.with_value(comment)),
567 Self { attrs, doc_comments }
570 fn merge(&mut self, other: Self) {
571 self.attrs.extend(other.attrs);
572 self.doc_comments.extend(other.doc_comments);
575 /// Maps the lowered `Attr` back to its original syntax node.
577 /// `attr` must come from the `owner` used for AttrSourceMap
579 /// Note that the returned syntax node might be a `#[cfg_attr]`, or a doc comment, instead of
580 /// the attribute represented by `Attr`.
581 pub fn source_of(&self, attr: &Attr) -> InFile<Either<ast::Attr, ast::Comment>> {
582 self.source_of_id(attr.id)
585 fn source_of_id(&self, id: AttrId) -> InFile<Either<ast::Attr, ast::Comment>> {
586 if id.is_doc_comment {
588 .get(id.ast_index as usize)
589 .unwrap_or_else(|| panic!("cannot find doc comment at index {:?}", id))
594 .get(id.ast_index as usize)
595 .unwrap_or_else(|| panic!("cannot find `Attr` at index {:?}", id))
602 /// A struct to map text ranges from [`Documentation`] back to TextRanges in the syntax tree.
604 pub struct DocsRangeMap {
605 source_map: AttrSourceMap,
606 // (docstring-line-range, attr_index, attr-string-range)
607 // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
608 // the original (untrimmed) syntax doc line
609 mapping: Vec<(TextRange, AttrId, TextRange)>,
613 pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
614 let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
615 let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
616 if !line_docs_range.contains_range(range) {
620 let relative_range = range - line_docs_range.start();
622 let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
624 Either::Left(_) => None, // FIXME, figure out a nice way to handle doc attributes here
625 // as well as for whats done in syntax highlight doc injection
626 Either::Right(comment) => {
627 let text_range = comment.syntax().text_range();
628 let range = TextRange::at(
630 + TextSize::try_from(comment.prefix().len()).ok()?
631 + original_line_src_range.start()
632 + relative_range.start(),
633 text_range.len().min(range.len()),
635 Some(InFile { file_id, value: range })
641 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
642 pub(crate) struct AttrId {
643 is_doc_comment: bool,
644 pub(crate) ast_index: u32,
647 #[derive(Debug, Clone, PartialEq, Eq)]
649 pub(crate) id: AttrId,
650 pub(crate) path: Interned<ModPath>,
651 pub(crate) input: Option<Interned<AttrInput>>,
654 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
656 /// `#[attr = "string"]`
658 /// `#[attr(subtree)]`
659 TokenTree(tt::Subtree, mbe::TokenMap),
662 impl fmt::Display for AttrInput {
663 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
665 AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
666 AttrInput::TokenTree(subtree, _) => subtree.fmt(f),
673 db: &dyn DefDatabase,
678 let path = Interned::new(ModPath::from_src(db, ast.path()?, hygiene)?);
679 let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
680 let value = match lit.kind() {
681 ast::LiteralKind::String(string) => string.value()?.into(),
682 _ => lit.syntax().first_token()?.text().trim_matches('"').into(),
684 Some(Interned::new(AttrInput::Literal(value)))
685 } else if let Some(tt) = ast.token_tree() {
686 let (tree, map) = syntax_node_to_token_tree(tt.syntax());
687 Some(Interned::new(AttrInput::TokenTree(tree, map)))
691 Some(Attr { id, path, input })
695 db: &dyn DefDatabase,
701 mbe::token_tree_to_syntax_node(tt, mbe::ParserEntryPoint::MetaItem).ok()?;
702 let ast = ast::Meta::cast(parse.syntax_node())?;
704 Self::from_src(db, ast, hygiene, id)
707 /// Parses this attribute as a `#[derive]`, returns an iterator that yields all contained paths
708 /// to derive macros.
710 /// Returns `None` when the attribute is not a well-formed `#[derive]` attribute.
711 pub(crate) fn parse_derive(&self) -> Option<impl Iterator<Item = ModPath>> {
712 if self.path.as_ident() != Some(&hir_expand::name![derive]) {
716 match self.input.as_deref() {
717 Some(AttrInput::TokenTree(args, _)) => {
722 .group_by(move |tt| {
724 tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ',' => {
733 let segments = tts.filter_map(|tt| match tt {
734 tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
737 ModPath::from_segments(PathKind::Plain, segments)
739 .collect::<Vec<_>>();
741 Some(paths.into_iter())
747 pub fn string_value(&self) -> Option<&SmolStr> {
748 match self.input.as_deref()? {
749 AttrInput::Literal(it) => Some(it),
755 #[derive(Debug, Clone, Copy)]
756 pub struct AttrQuery<'a> {
761 impl<'a> AttrQuery<'a> {
762 pub fn tt_values(self) -> impl Iterator<Item = &'a Subtree> {
763 self.attrs().filter_map(|attr| match attr.input.as_deref()? {
764 AttrInput::TokenTree(it, _) => Some(it),
769 pub fn string_value(self) -> Option<&'a SmolStr> {
770 self.attrs().find_map(|attr| match attr.input.as_deref()? {
771 AttrInput::Literal(it) => Some(it),
776 pub fn exists(self) -> bool {
777 self.attrs().next().is_some()
780 pub fn attrs(self) -> impl Iterator<Item = &'a Attr> + Clone {
784 .filter(move |attr| attr.path.as_ident().map_or(false, |s| s.to_string() == key))
788 fn attrs_from_ast<N>(src: AstId<N>, db: &dyn DefDatabase) -> RawAttrs
792 let src = InFile::new(src.file_id, src.to_node(db.upcast()));
793 RawAttrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn ast::AttrsOwner))
796 fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase) -> RawAttrs {
797 let tree = id.item_tree(db);
798 let mod_item = N::id_to_mod_item(id.value);
799 tree.raw_attrs(mod_item.into()).clone()
803 owner: &dyn ast::AttrsOwner,
804 ) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
805 let (inner_attrs, inner_docs) = inner_attributes(owner.syntax())
806 .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs)));
808 let outer_attrs = owner.attrs().filter(|attr| attr.kind().is_outer());
810 outer_attrs.chain(inner_attrs.into_iter().flatten()).enumerate().map(|(idx, attr)| {
812 AttrId { ast_index: idx as u32, is_doc_comment: false },
813 attr.syntax().text_range().start(),
819 ast::CommentIter::from_syntax_node(owner.syntax()).filter(ast::Comment::is_outer);
821 outer_docs.chain(inner_docs.into_iter().flatten()).enumerate().map(|(idx, docs_text)| {
823 AttrId { ast_index: idx as u32, is_doc_comment: true },
824 docs_text.syntax().text_range().start(),
825 Either::Right(docs_text),
828 // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved
829 docs.chain(attrs).sorted_by_key(|&(_, offset, _)| offset).map(|(id, _, attr)| (id, attr))
832 pub(crate) fn variants_attrs_source_map(
833 db: &dyn DefDatabase,
835 ) -> Arc<ArenaMap<LocalEnumVariantId, AstPtr<ast::Variant>>> {
836 let mut res = ArenaMap::default();
837 let child_source = def.child_source(db);
839 for (idx, variant) in child_source.value.iter() {
840 res.insert(idx, AstPtr::new(variant));
846 pub(crate) fn fields_attrs_source_map(
847 db: &dyn DefDatabase,
849 ) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>> {
850 let mut res = ArenaMap::default();
851 let child_source = def.child_source(db);
853 for (idx, variant) in child_source.value.iter() {
858 .either(|l| Either::Left(AstPtr::new(l)), |r| Either::Right(AstPtr::new(r))),