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, HirFileId, 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 pub fn get(&self, id: AttrId) -> Option<&Attr> {
77 (**self).iter().find(|attr| attr.id == id)
81 impl ops::Deref for Attrs {
84 fn deref(&self) -> &[Attr] {
85 match &self.0.entries {
92 impl ops::Deref for AttrsWithOwner {
95 fn deref(&self) -> &Attrs {
101 pub(crate) const EMPTY: Self = Self { entries: None };
103 pub(crate) fn new(db: &dyn DefDatabase, owner: &dyn ast::HasAttrs, hygiene: &Hygiene) -> Self {
104 let entries = collect_attrs(owner)
105 .filter_map(|(id, attr)| match attr {
106 Either::Left(attr) => {
107 attr.meta().and_then(|meta| Attr::from_src(db, meta, hygiene, id))
109 Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
111 input: Some(Interned::new(AttrInput::Literal(SmolStr::new(doc)))),
112 path: Interned::new(ModPath::from(hir_expand::name!(doc))),
115 .collect::<Arc<_>>();
117 Self { entries: if entries.is_empty() { None } else { Some(entries) } }
120 fn from_attrs_owner(db: &dyn DefDatabase, owner: InFile<&dyn ast::HasAttrs>) -> Self {
121 let hygiene = Hygiene::new(db.upcast(), owner.file_id);
122 Self::new(db, owner.value, &hygiene)
125 pub(crate) fn merge(&self, other: Self) -> Self {
126 // FIXME: This needs to fixup `AttrId`s
127 match (&self.entries, &other.entries) {
128 (None, None) => Self::EMPTY,
129 (Some(entries), None) | (None, Some(entries)) => {
130 Self { entries: Some(entries.clone()) }
132 (Some(a), Some(b)) => {
133 Self { entries: Some(a.iter().chain(b.iter()).cloned().collect()) }
138 /// Processes `cfg_attr`s, returning the resulting semantic `Attrs`.
139 pub(crate) fn filter(self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
140 let has_cfg_attrs = self.iter().any(|attr| {
141 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr])
147 let crate_graph = db.crate_graph();
150 .flat_map(|attr| -> SmallVec<[_; 1]> {
152 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr]);
154 return smallvec![attr.clone()];
157 let subtree = match attr.input.as_deref() {
158 Some(AttrInput::TokenTree(it, _)) => it,
159 _ => return smallvec![attr.clone()],
162 // Input subtree is: `(cfg, $(attr),+)`
163 // Split it up into a `cfg` subtree and the `attr` subtrees.
164 // FIXME: There should be a common API for this.
165 let mut parts = subtree.token_trees.split(
166 |tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ','),
168 let cfg = parts.next().unwrap();
169 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
170 let cfg = CfgExpr::parse(&cfg);
172 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
173 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
175 let hygiene = Hygiene::new_unhygienic();
176 Attr::from_tt(db, &tree, &hygiene, index)
179 let cfg_options = &crate_graph[krate].cfg_options;
180 if cfg_options.check(&cfg) == Some(false) {
183 cov_mark::hit!(cfg_attr_active);
190 Attrs(RawAttrs { entries: Some(new_attrs) })
195 pub const EMPTY: Self = Self(RawAttrs::EMPTY);
197 pub(crate) fn variants_attrs_query(
198 db: &dyn DefDatabase,
200 ) -> Arc<ArenaMap<LocalEnumVariantId, Attrs>> {
201 let krate = e.lookup(db).container.krate;
202 let src = e.child_source(db);
203 let mut res = ArenaMap::default();
205 for (id, var) in src.value.iter() {
206 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(var as &dyn ast::HasAttrs))
209 res.insert(id, attrs)
215 pub(crate) fn fields_attrs_query(
216 db: &dyn DefDatabase,
218 ) -> Arc<ArenaMap<LocalFieldId, Attrs>> {
219 let krate = v.module(db).krate;
220 let src = v.child_source(db);
221 let mut res = ArenaMap::default();
223 for (id, fld) in src.value.iter() {
224 let owner: &dyn HasAttrs = match fld {
225 Either::Left(tuple) => tuple,
226 Either::Right(record) => record,
228 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(owner)).filter(db, krate);
230 res.insert(id, attrs);
236 pub fn by_key(&self, key: &'static str) -> AttrQuery<'_> {
237 AttrQuery { attrs: self, key }
240 pub fn cfg(&self) -> Option<CfgExpr> {
241 let mut cfgs = self.by_key("cfg").tt_values().map(CfgExpr::parse).collect::<Vec<_>>();
244 1 => Some(cfgs.pop().unwrap()),
245 _ => Some(CfgExpr::All(cfgs)),
248 pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool {
251 Some(cfg) => cfg_options.check(&cfg) != Some(false),
255 pub fn lang(&self) -> Option<&SmolStr> {
256 self.by_key("lang").string_value()
259 pub fn docs(&self) -> Option<Documentation> {
260 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
261 AttrInput::Literal(s) => Some(s),
262 AttrInput::TokenTree(..) => None,
266 .flat_map(|s| s.lines())
267 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
268 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
271 let mut buf = String::new();
273 // str::lines doesn't yield anything for the empty string
275 buf.extend(Itertools::intersperse(
276 doc.lines().map(|line| {
279 .map_or(line, |(offset, _)| &line[offset..])
291 Some(Documentation(buf))
295 pub fn has_doc_hidden(&self) -> bool {
296 self.by_key("doc").tt_values().any(|tt| {
297 tt.delimiter_kind() == Some(DelimiterKind::Parenthesis) &&
298 matches!(&*tt.token_trees, [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "hidden")
303 impl AttrsWithOwner {
304 pub(crate) fn attrs_query(db: &dyn DefDatabase, def: AttrDefId) -> Self {
305 // FIXME: this should use `Trace` to avoid duplication in `source_map` below
306 let raw_attrs = match def {
307 AttrDefId::ModuleId(module) => {
308 let def_map = module.def_map(db);
309 let mod_data = &def_map[module.local_id];
310 match mod_data.declaration_source(db) {
312 let raw_attrs = RawAttrs::from_attrs_owner(
314 it.as_ref().map(|it| it as &dyn ast::HasAttrs),
316 match mod_data.definition_source(db) {
317 InFile { file_id, value: ModuleSource::SourceFile(file) } => raw_attrs
318 .merge(RawAttrs::from_attrs_owner(db, InFile::new(file_id, &file))),
322 None => RawAttrs::from_attrs_owner(
324 mod_data.definition_source(db).as_ref().map(|src| match src {
325 ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
326 ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
327 ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
332 AttrDefId::FieldId(it) => {
333 return Self { attrs: db.fields_attrs(it.parent)[it.local_id].clone(), owner: def };
335 AttrDefId::EnumVariantId(it) => {
337 attrs: db.variants_attrs(it.parent)[it.local_id].clone(),
341 AttrDefId::AdtId(it) => match it {
342 AdtId::StructId(it) => attrs_from_item_tree(it.lookup(db).id, db),
343 AdtId::EnumId(it) => attrs_from_item_tree(it.lookup(db).id, db),
344 AdtId::UnionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
346 AttrDefId::TraitId(it) => attrs_from_item_tree(it.lookup(db).id, db),
347 AttrDefId::MacroDefId(it) => it
349 .either(|ast_id| attrs_from_ast(ast_id, db), |ast_id| attrs_from_ast(ast_id, db)),
350 AttrDefId::ImplId(it) => attrs_from_item_tree(it.lookup(db).id, db),
351 AttrDefId::ConstId(it) => attrs_from_item_tree(it.lookup(db).id, db),
352 AttrDefId::StaticId(it) => attrs_from_item_tree(it.lookup(db).id, db),
353 AttrDefId::FunctionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
354 AttrDefId::TypeAliasId(it) => attrs_from_item_tree(it.lookup(db).id, db),
355 AttrDefId::GenericParamId(it) => match it {
356 GenericParamId::TypeParamId(it) => {
357 let src = it.parent.child_source(db);
358 RawAttrs::from_attrs_owner(
361 src.value[it.local_id].as_ref().either(|it| it as _, |it| it as _),
365 GenericParamId::LifetimeParamId(it) => {
366 let src = it.parent.child_source(db);
367 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
369 GenericParamId::ConstParamId(it) => {
370 let src = it.parent.child_source(db);
371 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
374 AttrDefId::ExternBlockId(it) => attrs_from_item_tree(it.lookup(db).id, db),
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.append_module_inline_attrs(AttrSourceMap::new(InFile::new(
401 let InFile { file_id, value } = mod_data.definition_source(db);
402 let attrs_owner = match &value {
403 ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
404 ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
405 ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
407 return AttrSourceMap::new(InFile::new(file_id, attrs_owner));
411 AttrDefId::FieldId(id) => {
412 let map = db.fields_attrs_source_map(id.parent);
413 let file_id = id.parent.file_id(db);
414 let root = db.parse_or_expand(file_id).unwrap();
415 let owner = match &map[id.local_id] {
416 Either::Left(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
417 Either::Right(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
419 InFile::new(file_id, owner)
421 AttrDefId::AdtId(adt) => match adt {
422 AdtId::StructId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
423 AdtId::UnionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
424 AdtId::EnumId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
426 AttrDefId::FunctionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
427 AttrDefId::EnumVariantId(id) => {
428 let map = db.variants_attrs_source_map(id.parent);
429 let file_id = id.parent.lookup(db).id.file_id();
430 let root = db.parse_or_expand(file_id).unwrap();
431 InFile::new(file_id, ast::AnyHasAttrs::new(map[id.local_id].to_node(&root)))
433 AttrDefId::StaticId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
434 AttrDefId::ConstId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
435 AttrDefId::TraitId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
436 AttrDefId::TypeAliasId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
437 AttrDefId::MacroDefId(id) => id.ast_id().either(
438 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
439 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
441 AttrDefId::ImplId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
442 AttrDefId::GenericParamId(id) => match id {
443 GenericParamId::TypeParamId(id) => {
444 id.parent.child_source(db).map(|source| match &source[id.local_id] {
445 Either::Left(id) => ast::AnyHasAttrs::new(id.clone()),
446 Either::Right(id) => ast::AnyHasAttrs::new(id.clone()),
449 GenericParamId::LifetimeParamId(id) => id
452 .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
453 GenericParamId::ConstParamId(id) => id
456 .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
458 AttrDefId::ExternBlockId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
461 AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn HasAttrs))
464 pub fn docs_with_rangemap(
466 db: &dyn DefDatabase,
467 ) -> Option<(Documentation, DocsRangeMap)> {
468 // FIXME: code duplication in `docs` above
469 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
470 AttrInput::Literal(s) => Some((s, attr.id)),
471 AttrInput::TokenTree(..) => None,
475 .flat_map(|(s, _)| s.lines())
476 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
477 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
480 let mut buf = String::new();
481 let mut mapping = Vec::new();
482 for (doc, idx) in docs {
484 let mut base_offset = 0;
485 for raw_line in doc.split('\n') {
486 let line = raw_line.trim_end();
487 let line_len = line.len();
488 let (offset, line) = match line.char_indices().nth(indent) {
489 Some((offset, _)) => (offset, &line[offset..]),
492 let buf_offset = buf.len();
495 TextRange::new(buf_offset.try_into().ok()?, buf.len().try_into().ok()?),
498 (base_offset + offset).try_into().ok()?,
499 line_len.try_into().ok()?,
503 base_offset += raw_line.len() + 1;
513 Some((Documentation(buf), DocsRangeMap { mapping, source_map: self.source_map(db) }))
520 ) -> Option<impl Iterator<Item = Either<ast::Attr, ast::Comment>>> {
521 let node = match_ast! {
523 ast::SourceFile(_) => syntax.clone(),
524 ast::ExternBlock(it) => it.extern_item_list()?.syntax().clone(),
525 ast::Fn(it) => it.body()?.stmt_list()?.syntax().clone(),
526 ast::Impl(it) => it.assoc_item_list()?.syntax().clone(),
527 ast::Module(it) => it.item_list()?.syntax().clone(),
528 ast::BlockExpr(it) => {
529 use syntax::SyntaxKind::{BLOCK_EXPR , EXPR_STMT};
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 let may_carry_attributes = matches!(
533 it.syntax().parent().map(|it| it.kind()),
534 Some(BLOCK_EXPR | EXPR_STMT)
536 if !may_carry_attributes {
545 let attrs = ast::AttrDocCommentIter::from_syntax_node(&node).filter(|el| match el {
546 Either::Left(attr) => attr.kind().is_inner(),
547 Either::Right(comment) => comment.is_inner(),
553 pub struct AttrSourceMap {
554 source: Vec<Either<ast::Attr, ast::Comment>>,
556 /// If this map is for a module, this will be the [`HirFileId`] of the module's definition site,
557 /// while `file_id` will be the one of the module declaration site.
558 /// The usize is the index into `source` from which point on the entries reside in the def site
560 mod_def_site_file_id: Option<(HirFileId, usize)>,
564 fn new(owner: InFile<&dyn ast::HasAttrs>) -> Self {
566 source: collect_attrs(owner.value).map(|(_, it)| it).collect(),
567 file_id: owner.file_id,
568 mod_def_site_file_id: None,
572 /// Append a second source map to this one, this is required for modules, whose outline and inline
573 /// attributes can reside in different files
574 fn append_module_inline_attrs(&mut self, other: Self) {
575 assert!(self.mod_def_site_file_id.is_none() && other.mod_def_site_file_id.is_none());
576 let len = self.source.len();
577 self.source.extend(other.source);
578 if other.file_id != self.file_id {
579 self.mod_def_site_file_id = Some((other.file_id, len));
583 /// Maps the lowered `Attr` back to its original syntax node.
585 /// `attr` must come from the `owner` used for AttrSourceMap
587 /// Note that the returned syntax node might be a `#[cfg_attr]`, or a doc comment, instead of
588 /// the attribute represented by `Attr`.
589 pub fn source_of(&self, attr: &Attr) -> InFile<&Either<ast::Attr, ast::Comment>> {
590 self.source_of_id(attr.id)
593 fn source_of_id(&self, id: AttrId) -> InFile<&Either<ast::Attr, ast::Comment>> {
594 let ast_idx = id.ast_index as usize;
595 let file_id = match self.mod_def_site_file_id {
596 Some((file_id, def_site_cut)) if def_site_cut <= ast_idx => file_id,
602 .map(|it| InFile::new(file_id, it))
603 .unwrap_or_else(|| panic!("cannot find attr at index {:?}", id))
607 /// A struct to map text ranges from [`Documentation`] back to TextRanges in the syntax tree.
609 pub struct DocsRangeMap {
610 source_map: AttrSourceMap,
611 // (docstring-line-range, attr_index, attr-string-range)
612 // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
613 // the original (untrimmed) syntax doc line
614 mapping: Vec<(TextRange, AttrId, TextRange)>,
618 /// Maps a [`TextRange`] relative to the documentation string back to its AST range
619 pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
620 let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
621 let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
622 if !line_docs_range.contains_range(range) {
626 let relative_range = range - line_docs_range.start();
628 let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
630 Either::Left(attr) => {
631 let string = get_doc_string_in_attr(&attr)?;
632 let text_range = string.open_quote_text_range()?;
633 let range = TextRange::at(
634 text_range.end() + original_line_src_range.start() + relative_range.start(),
635 string.syntax().text_range().len().min(range.len()),
637 Some(InFile { file_id, value: range })
639 Either::Right(comment) => {
640 let text_range = comment.syntax().text_range();
641 let range = TextRange::at(
643 + TextSize::try_from(comment.prefix().len()).ok()?
644 + original_line_src_range.start()
645 + relative_range.start(),
646 text_range.len().min(range.len()),
648 Some(InFile { file_id, value: range })
654 fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
657 Some(ast::Expr::Literal(lit)) => match lit.kind() {
658 ast::LiteralKind::String(it) => Some(it),
661 // #[cfg_attr(..., doc = "", ...)]
663 // FIXME: See highlight injection for what to do here
670 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
672 pub(crate) ast_index: u32,
675 #[derive(Debug, Clone, PartialEq, Eq)]
677 pub(crate) id: AttrId,
678 pub(crate) path: Interned<ModPath>,
679 pub(crate) input: Option<Interned<AttrInput>>,
682 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
684 /// `#[attr = "string"]`
686 /// `#[attr(subtree)]`
687 TokenTree(tt::Subtree, mbe::TokenMap),
690 impl fmt::Display for AttrInput {
691 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
693 AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
694 AttrInput::TokenTree(subtree, _) => subtree.fmt(f),
701 db: &dyn DefDatabase,
706 let path = Interned::new(ModPath::from_src(db.upcast(), ast.path()?, hygiene)?);
707 let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
708 let value = match lit.kind() {
709 ast::LiteralKind::String(string) => string.value()?.into(),
710 _ => lit.syntax().first_token()?.text().trim_matches('"').into(),
712 Some(Interned::new(AttrInput::Literal(value)))
713 } else if let Some(tt) = ast.token_tree() {
714 let (tree, map) = syntax_node_to_token_tree(tt.syntax());
715 Some(Interned::new(AttrInput::TokenTree(tree, map)))
719 Some(Attr { id, path, input })
723 db: &dyn DefDatabase,
728 let (parse, _) = mbe::token_tree_to_syntax_node(tt, mbe::TopEntryPoint::MetaItem);
729 let ast = ast::Meta::cast(parse.syntax_node())?;
731 Self::from_src(db, ast, hygiene, id)
734 /// Parses this attribute as a token tree consisting of comma separated paths.
735 pub fn parse_path_comma_token_tree(&self) -> Option<impl Iterator<Item = ModPath> + '_> {
736 let args = match self.input.as_deref() {
737 Some(AttrInput::TokenTree(args, _)) => args,
741 if args.delimiter_kind() != Some(DelimiterKind::Parenthesis) {
748 matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. })))
751 .filter(|(comma, _)| !*comma)
753 let segments = tts.filter_map(|tt| match tt {
754 tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
757 ModPath::from_segments(PathKind::Plain, segments)
759 .collect::<Vec<_>>();
761 Some(paths.into_iter())
764 pub fn path(&self) -> &ModPath {
768 pub fn string_value(&self) -> Option<&SmolStr> {
769 match self.input.as_deref()? {
770 AttrInput::Literal(it) => Some(it),
776 #[derive(Debug, Clone, Copy)]
777 pub struct AttrQuery<'attr> {
782 impl<'attr> AttrQuery<'attr> {
783 pub fn tt_values(self) -> impl Iterator<Item = &'attr Subtree> {
784 self.attrs().filter_map(|attr| match attr.input.as_deref()? {
785 AttrInput::TokenTree(it, _) => Some(it),
790 pub fn string_value(self) -> Option<&'attr SmolStr> {
791 self.attrs().find_map(|attr| match attr.input.as_deref()? {
792 AttrInput::Literal(it) => Some(it),
797 pub fn exists(self) -> bool {
798 self.attrs().next().is_some()
801 pub fn attrs(self) -> impl Iterator<Item = &'attr Attr> + Clone {
805 .filter(move |attr| attr.path.as_ident().map_or(false, |s| s.to_smol_str() == key))
809 fn attrs_from_ast<N>(src: AstId<N>, db: &dyn DefDatabase) -> RawAttrs
813 let src = InFile::new(src.file_id, src.to_node(db.upcast()));
814 RawAttrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn ast::HasAttrs))
817 fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase) -> RawAttrs {
818 let tree = id.item_tree(db);
819 let mod_item = N::id_to_mod_item(id.value);
820 tree.raw_attrs(mod_item.into()).clone()
824 owner: &dyn ast::HasAttrs,
825 ) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
826 let inner_attrs = inner_attributes(owner.syntax()).into_iter().flatten();
828 ast::AttrDocCommentIter::from_syntax_node(owner.syntax()).filter(|el| match el {
829 Either::Left(attr) => attr.kind().is_outer(),
830 Either::Right(comment) => comment.is_outer(),
835 .map(|(id, attr)| (AttrId { ast_index: id as u32 }, attr))
838 pub(crate) fn variants_attrs_source_map(
839 db: &dyn DefDatabase,
841 ) -> Arc<ArenaMap<LocalEnumVariantId, AstPtr<ast::Variant>>> {
842 let mut res = ArenaMap::default();
843 let child_source = def.child_source(db);
845 for (idx, variant) in child_source.value.iter() {
846 res.insert(idx, AstPtr::new(variant));
852 pub(crate) fn fields_attrs_source_map(
853 db: &dyn DefDatabase,
855 ) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>> {
856 let mut res = ArenaMap::default();
857 let child_source = def.child_source(db);
859 for (idx, variant) in child_source.value.iter() {
864 .either(|l| Either::Left(AstPtr::new(l)), |r| Either::Right(AstPtr::new(r))),