1 //! A higher level attributes based on TokenTree, with also some shortcuts.
3 use std::{fmt, hash::Hash, ops, sync::Arc};
6 use cfg::{CfgExpr, CfgOptions};
8 use hir_expand::{hygiene::Hygiene, name::AsName, AstId, InFile};
9 use itertools::Itertools;
10 use la_arena::ArenaMap;
11 use mbe::{syntax_node_to_token_tree, DelimiterKind, Punct};
12 use smallvec::{smallvec, SmallVec};
14 ast::{self, AstNode, HasAttrs, IsString},
15 match_ast, AstPtr, AstToken, SmolStr, SyntaxNode, TextRange, TextSize,
22 item_tree::{ItemTreeId, ItemTreeNode},
23 nameres::ModuleSource,
24 path::{ModPath, PathKind},
25 src::{HasChildSource, HasSource},
26 AdtId, AttrDefId, EnumId, GenericParamId, HasModule, LocalEnumVariantId, LocalFieldId, Lookup,
30 /// Holds documentation
31 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
32 pub struct Documentation(String);
35 pub fn new(s: String) -> Self {
39 pub fn as_str(&self) -> &str {
44 impl From<Documentation> for String {
45 fn from(Documentation(string): Documentation) -> Self {
50 /// Syntactical attributes, without filtering of `cfg_attr`s.
51 #[derive(Default, Debug, Clone, PartialEq, Eq)]
52 pub(crate) struct RawAttrs {
53 entries: Option<Arc<[Attr]>>,
56 #[derive(Default, Debug, Clone, PartialEq, Eq)]
57 pub struct Attrs(RawAttrs);
59 #[derive(Debug, Clone, PartialEq, Eq)]
60 pub struct AttrsWithOwner {
65 impl ops::Deref for RawAttrs {
68 fn deref(&self) -> &[Attr] {
76 impl ops::Deref for Attrs {
79 fn deref(&self) -> &[Attr] {
80 match &self.0.entries {
87 impl ops::Deref for AttrsWithOwner {
90 fn deref(&self) -> &Attrs {
96 pub(crate) const EMPTY: Self = Self { entries: None };
98 pub(crate) fn new(db: &dyn DefDatabase, owner: &dyn ast::HasAttrs, hygiene: &Hygiene) -> Self {
99 let entries = collect_attrs(owner)
100 .flat_map(|(id, attr)| match attr {
101 Either::Left(attr) => {
102 attr.meta().and_then(|meta| Attr::from_src(db, meta, hygiene, id))
104 Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
106 input: Some(Interned::new(AttrInput::Literal(SmolStr::new(doc)))),
107 path: Interned::new(ModPath::from(hir_expand::name!(doc))),
110 .collect::<Arc<_>>();
112 Self { entries: if entries.is_empty() { None } else { Some(entries) } }
115 fn from_attrs_owner(db: &dyn DefDatabase, owner: InFile<&dyn ast::HasAttrs>) -> Self {
116 let hygiene = Hygiene::new(db.upcast(), owner.file_id);
117 Self::new(db, owner.value, &hygiene)
120 pub(crate) fn merge(&self, other: Self) -> Self {
121 // FIXME: This needs to fixup `AttrId`s
122 match (&self.entries, &other.entries) {
123 (None, None) => Self::EMPTY,
124 (Some(entries), None) | (None, Some(entries)) => {
125 Self { entries: Some(entries.clone()) }
127 (Some(a), Some(b)) => {
128 Self { entries: Some(a.iter().chain(b.iter()).cloned().collect()) }
133 /// Processes `cfg_attr`s, returning the resulting semantic `Attrs`.
134 pub(crate) fn filter(self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
135 let has_cfg_attrs = self.iter().any(|attr| {
136 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr])
142 let crate_graph = db.crate_graph();
145 .flat_map(|attr| -> SmallVec<[_; 1]> {
147 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr]);
149 return smallvec![attr.clone()];
152 let subtree = match attr.input.as_deref() {
153 Some(AttrInput::TokenTree(it, _)) => it,
154 _ => return smallvec![attr.clone()],
157 // Input subtree is: `(cfg, $(attr),+)`
158 // Split it up into a `cfg` subtree and the `attr` subtrees.
159 // FIXME: There should be a common API for this.
160 let mut parts = subtree.token_trees.split(
161 |tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ','),
163 let cfg = parts.next().unwrap();
164 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
165 let cfg = CfgExpr::parse(&cfg);
167 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
168 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
170 let hygiene = Hygiene::new_unhygienic();
171 Attr::from_tt(db, &tree, &hygiene, index)
174 let cfg_options = &crate_graph[krate].cfg_options;
175 if cfg_options.check(&cfg) == Some(false) {
178 cov_mark::hit!(cfg_attr_active);
185 Attrs(RawAttrs { entries: Some(new_attrs) })
190 pub const EMPTY: Self = Self(RawAttrs::EMPTY);
192 pub(crate) fn variants_attrs_query(
193 db: &dyn DefDatabase,
195 ) -> Arc<ArenaMap<LocalEnumVariantId, Attrs>> {
196 let krate = e.lookup(db).container.krate;
197 let src = e.child_source(db);
198 let mut res = ArenaMap::default();
200 for (id, var) in src.value.iter() {
201 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(var as &dyn ast::HasAttrs))
204 res.insert(id, attrs)
210 pub(crate) fn fields_attrs_query(
211 db: &dyn DefDatabase,
213 ) -> Arc<ArenaMap<LocalFieldId, Attrs>> {
214 let krate = v.module(db).krate;
215 let src = v.child_source(db);
216 let mut res = ArenaMap::default();
218 for (id, fld) in src.value.iter() {
219 let owner: &dyn HasAttrs = match fld {
220 Either::Left(tuple) => tuple,
221 Either::Right(record) => record,
223 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(owner)).filter(db, krate);
225 res.insert(id, attrs);
231 pub fn by_key(&self, key: &'static str) -> AttrQuery<'_> {
232 AttrQuery { attrs: self, key }
235 pub fn cfg(&self) -> Option<CfgExpr> {
236 let mut cfgs = self.by_key("cfg").tt_values().map(CfgExpr::parse).collect::<Vec<_>>();
239 1 => Some(cfgs.pop().unwrap()),
240 _ => Some(CfgExpr::All(cfgs)),
243 pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool {
246 Some(cfg) => cfg_options.check(&cfg) != Some(false),
250 pub fn docs(&self) -> Option<Documentation> {
251 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
252 AttrInput::Literal(s) => Some(s),
253 AttrInput::TokenTree(..) => None,
257 .flat_map(|s| s.lines())
258 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
259 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
262 let mut buf = String::new();
264 // str::lines doesn't yield anything for the empty string
266 buf.extend(Itertools::intersperse(
267 doc.lines().map(|line| {
270 .map_or(line, |(offset, _)| &line[offset..])
282 Some(Documentation(buf))
286 pub fn has_doc_hidden(&self) -> bool {
287 self.by_key("doc").tt_values().any(|tt| {
288 tt.delimiter_kind() == Some(DelimiterKind::Parenthesis) &&
289 matches!(&*tt.token_trees, [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "hidden")
294 impl AttrsWithOwner {
295 pub(crate) fn attrs_query(db: &dyn DefDatabase, def: AttrDefId) -> Self {
296 // FIXME: this should use `Trace` to avoid duplication in `source_map` below
297 let raw_attrs = match def {
298 AttrDefId::ModuleId(module) => {
299 let def_map = module.def_map(db);
300 let mod_data = &def_map[module.local_id];
301 match mod_data.declaration_source(db) {
303 let raw_attrs = RawAttrs::from_attrs_owner(
305 it.as_ref().map(|it| it as &dyn ast::HasAttrs),
307 match mod_data.definition_source(db) {
308 InFile { file_id, value: ModuleSource::SourceFile(file) } => raw_attrs
309 .merge(RawAttrs::from_attrs_owner(db, InFile::new(file_id, &file))),
313 None => RawAttrs::from_attrs_owner(
315 mod_data.definition_source(db).as_ref().map(|src| match src {
316 ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
317 ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
318 ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
323 AttrDefId::FieldId(it) => {
324 return Self { attrs: db.fields_attrs(it.parent)[it.local_id].clone(), owner: def };
326 AttrDefId::EnumVariantId(it) => {
328 attrs: db.variants_attrs(it.parent)[it.local_id].clone(),
332 AttrDefId::AdtId(it) => match it {
333 AdtId::StructId(it) => attrs_from_item_tree(it.lookup(db).id, db),
334 AdtId::EnumId(it) => attrs_from_item_tree(it.lookup(db).id, db),
335 AdtId::UnionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
337 AttrDefId::TraitId(it) => attrs_from_item_tree(it.lookup(db).id, db),
338 AttrDefId::MacroDefId(it) => it
340 .either(|ast_id| attrs_from_ast(ast_id, db), |ast_id| attrs_from_ast(ast_id, db)),
341 AttrDefId::ImplId(it) => attrs_from_item_tree(it.lookup(db).id, db),
342 AttrDefId::ConstId(it) => attrs_from_item_tree(it.lookup(db).id, db),
343 AttrDefId::StaticId(it) => attrs_from_item_tree(it.lookup(db).id, db),
344 AttrDefId::FunctionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
345 AttrDefId::TypeAliasId(it) => attrs_from_item_tree(it.lookup(db).id, db),
346 AttrDefId::GenericParamId(it) => match it {
347 GenericParamId::TypeParamId(it) => {
348 let src = it.parent.child_source(db);
349 RawAttrs::from_attrs_owner(
352 src.value[it.local_id].as_ref().either(|it| it as _, |it| it as _),
356 GenericParamId::LifetimeParamId(it) => {
357 let src = it.parent.child_source(db);
358 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
360 GenericParamId::ConstParamId(it) => {
361 let src = it.parent.child_source(db);
362 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
367 let attrs = raw_attrs.filter(db, def.krate(db));
368 Self { attrs, owner: def }
371 pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
372 let owner = match self.owner {
373 AttrDefId::ModuleId(module) => {
374 // Modules can have 2 attribute owners (the `mod x;` item, and the module file itself).
376 let def_map = module.def_map(db);
377 let mod_data = &def_map[module.local_id];
378 match mod_data.declaration_source(db) {
380 let mut map = AttrSourceMap::new(InFile::new(it.file_id, &it.value));
381 if let InFile { file_id, value: ModuleSource::SourceFile(file) } =
382 mod_data.definition_source(db)
384 map.merge(AttrSourceMap::new(InFile::new(file_id, &file)));
389 let InFile { file_id, value } = mod_data.definition_source(db);
390 let attrs_owner = match &value {
391 ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
392 ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
393 ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
395 return AttrSourceMap::new(InFile::new(file_id, attrs_owner));
399 AttrDefId::FieldId(id) => {
400 let map = db.fields_attrs_source_map(id.parent);
401 let file_id = id.parent.file_id(db);
402 let root = db.parse_or_expand(file_id).unwrap();
403 let owner = match &map[id.local_id] {
404 Either::Left(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
405 Either::Right(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
407 InFile::new(file_id, owner)
409 AttrDefId::AdtId(adt) => match adt {
410 AdtId::StructId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
411 AdtId::UnionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
412 AdtId::EnumId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
414 AttrDefId::FunctionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
415 AttrDefId::EnumVariantId(id) => {
416 let map = db.variants_attrs_source_map(id.parent);
417 let file_id = id.parent.lookup(db).id.file_id();
418 let root = db.parse_or_expand(file_id).unwrap();
419 InFile::new(file_id, ast::AnyHasAttrs::new(map[id.local_id].to_node(&root)))
421 AttrDefId::StaticId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
422 AttrDefId::ConstId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
423 AttrDefId::TraitId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
424 AttrDefId::TypeAliasId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
425 AttrDefId::MacroDefId(id) => id.ast_id().either(
426 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
427 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
429 AttrDefId::ImplId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
430 AttrDefId::GenericParamId(id) => match id {
431 GenericParamId::TypeParamId(id) => {
432 id.parent.child_source(db).map(|source| match &source[id.local_id] {
433 Either::Left(id) => ast::AnyHasAttrs::new(id.clone()),
434 Either::Right(id) => ast::AnyHasAttrs::new(id.clone()),
437 GenericParamId::LifetimeParamId(id) => id
440 .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
441 GenericParamId::ConstParamId(id) => id
444 .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
448 AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn HasAttrs))
451 pub fn docs_with_rangemap(
453 db: &dyn DefDatabase,
454 ) -> Option<(Documentation, DocsRangeMap)> {
455 // FIXME: code duplication in `docs` above
456 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
457 AttrInput::Literal(s) => Some((s, attr.id)),
458 AttrInput::TokenTree(..) => None,
462 .flat_map(|(s, _)| s.lines())
463 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
464 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
467 let mut buf = String::new();
468 let mut mapping = Vec::new();
469 for (doc, idx) in docs {
471 let mut base_offset = 0;
472 for raw_line in doc.split('\n') {
473 let line = raw_line.trim_end();
474 let line_len = line.len();
475 let (offset, line) = match line.char_indices().nth(indent) {
476 Some((offset, _)) => (offset, &line[offset..]),
479 let buf_offset = buf.len();
482 TextRange::new(buf_offset.try_into().ok()?, buf.len().try_into().ok()?),
485 (base_offset + offset).try_into().ok()?,
486 line_len.try_into().ok()?,
490 base_offset += raw_line.len() + 1;
500 Some((Documentation(buf), DocsRangeMap { mapping, source_map: self.source_map(db) }))
507 ) -> Option<(impl Iterator<Item = ast::Attr>, impl Iterator<Item = ast::Comment>)> {
508 let (attrs, docs) = match_ast! {
510 ast::SourceFile(it) => (it.attrs(), ast::CommentIter::from_syntax_node(it.syntax())),
511 ast::ExternBlock(it) => {
512 let extern_item_list = it.extern_item_list()?;
513 (extern_item_list.attrs(), ast::CommentIter::from_syntax_node(extern_item_list.syntax()))
516 let body = it.body()?;
517 let stmt_list = body.stmt_list()?;
518 (stmt_list.attrs(), ast::CommentIter::from_syntax_node(body.syntax()))
521 let assoc_item_list = it.assoc_item_list()?;
522 (assoc_item_list.attrs(), ast::CommentIter::from_syntax_node(assoc_item_list.syntax()))
525 let item_list = it.item_list()?;
526 (item_list.attrs(), ast::CommentIter::from_syntax_node(item_list.syntax()))
528 // FIXME: BlockExpr's only accept inner attributes in specific cases
529 // Excerpt from the reference:
530 // Block expressions accept outer and inner attributes, but only when they are the outer
531 // expression of an expression statement or the final expression of another block expression.
532 ast::BlockExpr(_it) => return None,
536 let attrs = attrs.filter(|attr| attr.kind().is_inner());
537 let docs = docs.filter(|doc| doc.is_inner());
542 pub struct AttrSourceMap {
543 attrs: Vec<InFile<ast::Attr>>,
544 doc_comments: Vec<InFile<ast::Comment>>,
548 fn new(owner: InFile<&dyn ast::HasAttrs>) -> Self {
549 let mut attrs = Vec::new();
550 let mut doc_comments = Vec::new();
551 for (_, attr) in collect_attrs(owner.value) {
553 Either::Left(attr) => attrs.push(owner.with_value(attr)),
554 Either::Right(comment) => doc_comments.push(owner.with_value(comment)),
558 Self { attrs, doc_comments }
561 fn merge(&mut self, other: Self) {
562 self.attrs.extend(other.attrs);
563 self.doc_comments.extend(other.doc_comments);
566 /// Maps the lowered `Attr` back to its original syntax node.
568 /// `attr` must come from the `owner` used for AttrSourceMap
570 /// Note that the returned syntax node might be a `#[cfg_attr]`, or a doc comment, instead of
571 /// the attribute represented by `Attr`.
572 pub fn source_of(&self, attr: &Attr) -> InFile<Either<ast::Attr, ast::Comment>> {
573 self.source_of_id(attr.id)
576 fn source_of_id(&self, id: AttrId) -> InFile<Either<ast::Attr, ast::Comment>> {
577 if id.is_doc_comment {
579 .get(id.ast_index as usize)
580 .unwrap_or_else(|| panic!("cannot find doc comment at index {:?}", id))
585 .get(id.ast_index as usize)
586 .unwrap_or_else(|| panic!("cannot find `Attr` at index {:?}", id))
593 /// A struct to map text ranges from [`Documentation`] back to TextRanges in the syntax tree.
595 pub struct DocsRangeMap {
596 source_map: AttrSourceMap,
597 // (docstring-line-range, attr_index, attr-string-range)
598 // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
599 // the original (untrimmed) syntax doc line
600 mapping: Vec<(TextRange, AttrId, TextRange)>,
604 /// Maps a [`TextRange`] relative to the documentation string back to its AST range
605 pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
606 let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
607 let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
608 if !line_docs_range.contains_range(range) {
612 let relative_range = range - line_docs_range.start();
614 let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
616 Either::Left(attr) => {
617 let string = get_doc_string_in_attr(&attr)?;
618 let text_range = string.open_quote_text_range()?;
619 let range = TextRange::at(
620 text_range.end() + original_line_src_range.start() + relative_range.start(),
621 string.syntax().text_range().len().min(range.len()),
623 Some(InFile { file_id, value: range })
625 Either::Right(comment) => {
626 let text_range = comment.syntax().text_range();
627 let range = TextRange::at(
629 + TextSize::try_from(comment.prefix().len()).ok()?
630 + original_line_src_range.start()
631 + relative_range.start(),
632 text_range.len().min(range.len()),
634 Some(InFile { file_id, value: range })
640 fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
643 Some(ast::Expr::Literal(lit)) => match lit.kind() {
644 ast::LiteralKind::String(it) => Some(it),
647 // #[cfg_attr(..., doc = "", ...)]
649 // FIXME: See highlight injection for what to do here
656 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
657 pub(crate) struct AttrId {
658 is_doc_comment: bool,
659 pub(crate) ast_index: u32,
662 #[derive(Debug, Clone, PartialEq, Eq)]
664 pub(crate) id: AttrId,
665 pub(crate) path: Interned<ModPath>,
666 pub(crate) input: Option<Interned<AttrInput>>,
669 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
671 /// `#[attr = "string"]`
673 /// `#[attr(subtree)]`
674 TokenTree(tt::Subtree, mbe::TokenMap),
677 impl fmt::Display for AttrInput {
678 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
680 AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
681 AttrInput::TokenTree(subtree, _) => subtree.fmt(f),
688 db: &dyn DefDatabase,
693 let path = Interned::new(ModPath::from_src(db, ast.path()?, hygiene)?);
694 let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
695 let value = match lit.kind() {
696 ast::LiteralKind::String(string) => string.value()?.into(),
697 _ => lit.syntax().first_token()?.text().trim_matches('"').into(),
699 Some(Interned::new(AttrInput::Literal(value)))
700 } else if let Some(tt) = ast.token_tree() {
701 let (tree, map) = syntax_node_to_token_tree(tt.syntax());
702 Some(Interned::new(AttrInput::TokenTree(tree, map)))
706 Some(Attr { id, path, input })
710 db: &dyn DefDatabase,
716 mbe::token_tree_to_syntax_node(tt, mbe::ParserEntryPoint::MetaItem).ok()?;
717 let ast = ast::Meta::cast(parse.syntax_node())?;
719 Self::from_src(db, ast, hygiene, id)
722 /// Parses this attribute as a `#[derive]`, returns an iterator that yields all contained paths
723 /// to derive macros.
725 /// Returns `None` when the attribute does not have a well-formed `#[derive]` attribute input.
726 pub(crate) fn parse_derive(&self) -> Option<impl Iterator<Item = ModPath> + '_> {
727 let args = match self.input.as_deref() {
728 Some(AttrInput::TokenTree(args, _)) => args,
732 if args.delimiter_kind() != Some(DelimiterKind::Parenthesis) {
739 matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. })))
743 let segments = tts.filter_map(|tt| match tt {
744 tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
747 ModPath::from_segments(PathKind::Plain, segments)
749 .collect::<Vec<_>>();
751 return Some(paths.into_iter());
754 pub fn string_value(&self) -> Option<&SmolStr> {
755 match self.input.as_deref()? {
756 AttrInput::Literal(it) => Some(it),
762 #[derive(Debug, Clone, Copy)]
763 pub struct AttrQuery<'a> {
768 impl<'a> AttrQuery<'a> {
769 pub fn tt_values(self) -> impl Iterator<Item = &'a Subtree> {
770 self.attrs().filter_map(|attr| match attr.input.as_deref()? {
771 AttrInput::TokenTree(it, _) => Some(it),
776 pub fn string_value(self) -> Option<&'a SmolStr> {
777 self.attrs().find_map(|attr| match attr.input.as_deref()? {
778 AttrInput::Literal(it) => Some(it),
783 pub fn exists(self) -> bool {
784 self.attrs().next().is_some()
787 pub fn attrs(self) -> impl Iterator<Item = &'a Attr> + Clone {
791 .filter(move |attr| attr.path.as_ident().map_or(false, |s| s.to_smol_str() == key))
795 fn attrs_from_ast<N>(src: AstId<N>, db: &dyn DefDatabase) -> RawAttrs
799 let src = InFile::new(src.file_id, src.to_node(db.upcast()));
800 RawAttrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn ast::HasAttrs))
803 fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase) -> RawAttrs {
804 let tree = id.item_tree(db);
805 let mod_item = N::id_to_mod_item(id.value);
806 tree.raw_attrs(mod_item.into()).clone()
810 owner: &dyn ast::HasAttrs,
811 ) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
812 let (inner_attrs, inner_docs) = inner_attributes(owner.syntax())
813 .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs)));
815 let outer_attrs = owner.attrs().filter(|attr| attr.kind().is_outer());
817 outer_attrs.chain(inner_attrs.into_iter().flatten()).enumerate().map(|(idx, attr)| {
819 AttrId { ast_index: idx as u32, is_doc_comment: false },
820 attr.syntax().text_range().start(),
826 ast::CommentIter::from_syntax_node(owner.syntax()).filter(ast::Comment::is_outer);
828 outer_docs.chain(inner_docs.into_iter().flatten()).enumerate().map(|(idx, docs_text)| {
830 AttrId { ast_index: idx as u32, is_doc_comment: true },
831 docs_text.syntax().text_range().start(),
832 Either::Right(docs_text),
835 // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved
836 docs.chain(attrs).sorted_by_key(|&(_, offset, _)| offset).map(|(id, _, attr)| (id, attr))
839 pub(crate) fn variants_attrs_source_map(
840 db: &dyn DefDatabase,
842 ) -> Arc<ArenaMap<LocalEnumVariantId, AstPtr<ast::Variant>>> {
843 let mut res = ArenaMap::default();
844 let child_source = def.child_source(db);
846 for (idx, variant) in child_source.value.iter() {
847 res.insert(idx, AstPtr::new(variant));
853 pub(crate) fn fields_attrs_source_map(
854 db: &dyn DefDatabase,
856 ) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>> {
857 let mut res = ArenaMap::default();
858 let child_source = def.child_source(db);
860 for (idx, variant) in child_source.value.iter() {
865 .either(|l| Either::Left(AstPtr::new(l)), |r| Either::Right(AstPtr::new(r))),