Skip to content

Commit b157552

Browse files
committed
Move doc comment handling into ide-db
1 parent 0bf0563 commit b157552

File tree

26 files changed

+342
-266
lines changed

26 files changed

+342
-266
lines changed

crates/hir-def/src/attr.rs

+3-170
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,11 @@ use hir_expand::{
1414
attrs::{collect_attrs, Attr, AttrId, RawAttrs},
1515
HirFileId, InFile,
1616
};
17-
use itertools::Itertools;
1817
use la_arena::{ArenaMap, Idx, RawIdx};
1918
use mbe::DelimiterKind;
2019
use syntax::{
21-
ast::{self, HasAttrs, IsString},
22-
AstPtr, AstToken, SmolStr, TextRange, TextSize,
20+
ast::{self, HasAttrs},
21+
AstPtr, SmolStr,
2322
};
2423
use triomphe::Arc;
2524

@@ -33,26 +32,6 @@ use crate::{
3332
LocalFieldId, Lookup, MacroId, VariantId,
3433
};
3534

36-
/// Holds documentation
37-
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
38-
pub struct Documentation(String);
39-
40-
impl Documentation {
41-
pub fn new(s: String) -> Self {
42-
Documentation(s)
43-
}
44-
45-
pub fn as_str(&self) -> &str {
46-
&self.0
47-
}
48-
}
49-
50-
impl From<Documentation> for String {
51-
fn from(Documentation(string): Documentation) -> Self {
52-
string
53-
}
54-
}
55-
5635
#[derive(Default, Debug, Clone, PartialEq, Eq)]
5736
pub struct Attrs(RawAttrs);
5837

@@ -221,33 +200,6 @@ impl Attrs {
221200
self.by_key("lang").string_value().and_then(|it| LangItem::from_str(it))
222201
}
223202

224-
pub fn docs(&self) -> Option<Documentation> {
225-
let docs = self.by_key("doc").attrs().filter_map(|attr| attr.string_value());
226-
let indent = doc_indent(self);
227-
let mut buf = String::new();
228-
for doc in docs {
229-
// str::lines doesn't yield anything for the empty string
230-
if !doc.is_empty() {
231-
buf.extend(Itertools::intersperse(
232-
doc.lines().map(|line| {
233-
line.char_indices()
234-
.nth(indent)
235-
.map_or(line, |(offset, _)| &line[offset..])
236-
.trim_end()
237-
}),
238-
"\n",
239-
));
240-
}
241-
buf.push('\n');
242-
}
243-
buf.pop();
244-
if buf.is_empty() {
245-
None
246-
} else {
247-
Some(Documentation(buf))
248-
}
249-
}
250-
251203
pub fn has_doc_hidden(&self) -> bool {
252204
self.by_key("doc").tt_values().any(|tt| {
253205
tt.delimiter.kind == DelimiterKind::Parenthesis &&
@@ -574,62 +526,6 @@ impl AttrsWithOwner {
574526

575527
AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn HasAttrs))
576528
}
577-
578-
pub fn docs_with_rangemap(
579-
&self,
580-
db: &dyn DefDatabase,
581-
) -> Option<(Documentation, DocsRangeMap)> {
582-
let docs =
583-
self.by_key("doc").attrs().filter_map(|attr| attr.string_value().map(|s| (s, attr.id)));
584-
let indent = doc_indent(self);
585-
let mut buf = String::new();
586-
let mut mapping = Vec::new();
587-
for (doc, idx) in docs {
588-
if !doc.is_empty() {
589-
let mut base_offset = 0;
590-
for raw_line in doc.split('\n') {
591-
let line = raw_line.trim_end();
592-
let line_len = line.len();
593-
let (offset, line) = match line.char_indices().nth(indent) {
594-
Some((offset, _)) => (offset, &line[offset..]),
595-
None => (0, line),
596-
};
597-
let buf_offset = buf.len();
598-
buf.push_str(line);
599-
mapping.push((
600-
TextRange::new(buf_offset.try_into().ok()?, buf.len().try_into().ok()?),
601-
idx,
602-
TextRange::at(
603-
(base_offset + offset).try_into().ok()?,
604-
line_len.try_into().ok()?,
605-
),
606-
));
607-
buf.push('\n');
608-
base_offset += raw_line.len() + 1;
609-
}
610-
} else {
611-
buf.push('\n');
612-
}
613-
}
614-
buf.pop();
615-
if buf.is_empty() {
616-
None
617-
} else {
618-
Some((Documentation(buf), DocsRangeMap { mapping, source_map: self.source_map(db) }))
619-
}
620-
}
621-
}
622-
623-
fn doc_indent(attrs: &Attrs) -> usize {
624-
attrs
625-
.by_key("doc")
626-
.attrs()
627-
.filter_map(|attr| attr.string_value())
628-
.flat_map(|s| s.lines())
629-
.filter(|line| !line.chars().all(|c| c.is_whitespace()))
630-
.map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
631-
.min()
632-
.unwrap_or(0)
633529
}
634530

635531
#[derive(Debug)]
@@ -673,7 +569,7 @@ impl AttrSourceMap {
673569
self.source_of_id(attr.id)
674570
}
675571

676-
fn source_of_id(&self, id: AttrId) -> InFile<&Either<ast::Attr, ast::Comment>> {
572+
pub fn source_of_id(&self, id: AttrId) -> InFile<&Either<ast::Attr, ast::Comment>> {
677573
let ast_idx = id.ast_index();
678574
let file_id = match self.mod_def_site_file_id {
679575
Some((file_id, def_site_cut)) if def_site_cut <= ast_idx => file_id,
@@ -687,69 +583,6 @@ impl AttrSourceMap {
687583
}
688584
}
689585

690-
/// A struct to map text ranges from [`Documentation`] back to TextRanges in the syntax tree.
691-
#[derive(Debug)]
692-
pub struct DocsRangeMap {
693-
source_map: AttrSourceMap,
694-
// (docstring-line-range, attr_index, attr-string-range)
695-
// a mapping from the text range of a line of the [`Documentation`] to the attribute index and
696-
// the original (untrimmed) syntax doc line
697-
mapping: Vec<(TextRange, AttrId, TextRange)>,
698-
}
699-
700-
impl DocsRangeMap {
701-
/// Maps a [`TextRange`] relative to the documentation string back to its AST range
702-
pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
703-
let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
704-
let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
705-
if !line_docs_range.contains_range(range) {
706-
return None;
707-
}
708-
709-
let relative_range = range - line_docs_range.start();
710-
711-
let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
712-
match source {
713-
Either::Left(attr) => {
714-
let string = get_doc_string_in_attr(attr)?;
715-
let text_range = string.open_quote_text_range()?;
716-
let range = TextRange::at(
717-
text_range.end() + original_line_src_range.start() + relative_range.start(),
718-
string.syntax().text_range().len().min(range.len()),
719-
);
720-
Some(InFile { file_id, value: range })
721-
}
722-
Either::Right(comment) => {
723-
let text_range = comment.syntax().text_range();
724-
let range = TextRange::at(
725-
text_range.start()
726-
+ TextSize::try_from(comment.prefix().len()).ok()?
727-
+ original_line_src_range.start()
728-
+ relative_range.start(),
729-
text_range.len().min(range.len()),
730-
);
731-
Some(InFile { file_id, value: range })
732-
}
733-
}
734-
}
735-
}
736-
737-
fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
738-
match it.expr() {
739-
// #[doc = lit]
740-
Some(ast::Expr::Literal(lit)) => match lit.kind() {
741-
ast::LiteralKind::String(it) => Some(it),
742-
_ => None,
743-
},
744-
// #[cfg_attr(..., doc = "", ...)]
745-
None => {
746-
// FIXME: See highlight injection for what to do here
747-
None
748-
}
749-
_ => None,
750-
}
751-
}
752-
753586
#[derive(Debug, Clone, Copy)]
754587
pub struct AttrQuery<'attr> {
755588
attrs: &'attr Attrs,

crates/hir/src/attrs.rs

+1-34
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Attributes & documentation for hir types.
22
33
use hir_def::{
4-
attr::{AttrsWithOwner, Documentation},
4+
attr::AttrsWithOwner,
55
item_scope::ItemInNs,
66
path::{ModPath, Path},
77
per_ns::Namespace,
@@ -20,7 +20,6 @@ use crate::{
2020

2121
pub trait HasAttrs {
2222
fn attrs(self, db: &dyn HirDatabase) -> AttrsWithOwner;
23-
fn docs(self, db: &dyn HirDatabase) -> Option<Documentation>;
2423
fn resolve_doc_path(
2524
self,
2625
db: &dyn HirDatabase,
@@ -43,10 +42,6 @@ macro_rules! impl_has_attrs {
4342
let def = AttrDefId::$def_id(self.into());
4443
db.attrs_with_owner(def)
4544
}
46-
fn docs(self, db: &dyn HirDatabase) -> Option<Documentation> {
47-
let def = AttrDefId::$def_id(self.into());
48-
db.attrs(def).docs()
49-
}
5045
fn resolve_doc_path(
5146
self,
5247
db: &dyn HirDatabase,
@@ -82,9 +77,6 @@ macro_rules! impl_has_attrs_enum {
8277
fn attrs(self, db: &dyn HirDatabase) -> AttrsWithOwner {
8378
$enum::$variant(self).attrs(db)
8479
}
85-
fn docs(self, db: &dyn HirDatabase) -> Option<Documentation> {
86-
$enum::$variant(self).docs(db)
87-
}
8880
fn resolve_doc_path(
8981
self,
9082
db: &dyn HirDatabase,
@@ -109,14 +101,6 @@ impl HasAttrs for AssocItem {
109101
}
110102
}
111103

112-
fn docs(self, db: &dyn HirDatabase) -> Option<Documentation> {
113-
match self {
114-
AssocItem::Function(it) => it.docs(db),
115-
AssocItem::Const(it) => it.docs(db),
116-
AssocItem::TypeAlias(it) => it.docs(db),
117-
}
118-
}
119-
120104
fn resolve_doc_path(
121105
self,
122106
db: &dyn HirDatabase,
@@ -136,23 +120,6 @@ impl HasAttrs for ExternCrateDecl {
136120
let def = AttrDefId::ExternCrateId(self.into());
137121
db.attrs_with_owner(def)
138122
}
139-
fn docs(self, db: &dyn HirDatabase) -> Option<Documentation> {
140-
let crate_docs = self.resolved_crate(db)?.root_module().attrs(db).docs().map(String::from);
141-
let def = AttrDefId::ExternCrateId(self.into());
142-
let decl_docs = db.attrs(def).docs().map(String::from);
143-
match (decl_docs, crate_docs) {
144-
(None, None) => None,
145-
(Some(decl_docs), None) => Some(decl_docs),
146-
(None, Some(crate_docs)) => Some(crate_docs),
147-
(Some(mut decl_docs), Some(crate_docs)) => {
148-
decl_docs.push('\n');
149-
decl_docs.push('\n');
150-
decl_docs += &crate_docs;
151-
Some(decl_docs)
152-
}
153-
}
154-
.map(Documentation::new)
155-
}
156123
fn resolve_doc_path(
157124
self,
158125
db: &dyn HirDatabase,

crates/hir/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ pub use crate::{
115115
pub use {
116116
cfg::{CfgAtom, CfgExpr, CfgOptions},
117117
hir_def::{
118-
attr::{builtin::AttributeTemplate, Attrs, AttrsWithOwner, Documentation},
118+
attr::{builtin::AttributeTemplate, AttrSourceMap, Attrs, AttrsWithOwner},
119119
data::adt::StructKind,
120120
find_path::PrefixKind,
121121
import_map,
@@ -130,7 +130,7 @@ pub use {
130130
{AdtId, ModuleDefId},
131131
},
132132
hir_expand::{
133-
attrs::Attr,
133+
attrs::{Attr, AttrId},
134134
name::{known, Name},
135135
ExpandResult, HirFileId, InFile, MacroFile, Origin,
136136
},

crates/ide-completion/src/completions/attribute/derive.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Completion for derives
2-
use hir::{HasAttrs, ScopeDef};
3-
use ide_db::SymbolKind;
2+
use hir::ScopeDef;
3+
use ide_db::{documentation::HasDocs, SymbolKind};
44
use itertools::Itertools;
55
use syntax::SmolStr;
66

crates/ide-completion/src/completions/attribute/lint.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
//! Completion for lints
2-
use ide_db::{generated::lints::Lint, SymbolKind};
2+
use ide_db::{documentation::Documentation, generated::lints::Lint, SymbolKind};
33
use syntax::ast;
44

55
use crate::{context::CompletionContext, item::CompletionItem, Completions};
@@ -55,7 +55,7 @@ pub(super) fn complete_lint(
5555
_ => name.to_owned(),
5656
};
5757
let mut item = CompletionItem::new(SymbolKind::Attribute, ctx.source_range(), label);
58-
item.documentation(hir::Documentation::new(description.to_owned()));
58+
item.documentation(Documentation::new(description.to_owned()));
5959
item.add_to(acc, ctx.db)
6060
}
6161
}

crates/ide-completion/src/completions/extern_crate.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Completion for extern crates
22
3-
use hir::{HasAttrs, Name};
4-
use ide_db::SymbolKind;
3+
use hir::Name;
4+
use ide_db::{documentation::HasDocs, SymbolKind};
55

66
use crate::{context::CompletionContext, CompletionItem, CompletionItemKind};
77

crates/ide-completion/src/completions/item_list/trait_impl.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@
3333
3434
use hir::{self, HasAttrs};
3535
use ide_db::{
36-
path_transform::PathTransform, syntax_helpers::insert_whitespace_into_node,
37-
traits::get_missing_assoc_items, SymbolKind,
36+
documentation::HasDocs, path_transform::PathTransform,
37+
syntax_helpers::insert_whitespace_into_node, traits::get_missing_assoc_items, SymbolKind,
3838
};
3939
use syntax::{
4040
ast::{self, edit_in_place::AttrsOwnerEdit, HasTypeBounds},

crates/ide-completion/src/completions/postfix.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,12 @@
22
33
mod format_like;
44

5-
use hir::{Documentation, HasAttrs};
6-
use ide_db::{imports::insert_use::ImportScope, ty_filter::TryEnum, SnippetCap};
5+
use ide_db::{
6+
documentation::{Documentation, HasDocs},
7+
imports::insert_use::ImportScope,
8+
ty_filter::TryEnum,
9+
SnippetCap,
10+
};
711
use syntax::{
812
ast::{self, make, AstNode, AstToken},
913
SyntaxKind::{BLOCK_EXPR, EXPR_STMT, FOR_EXPR, IF_EXPR, LOOP_EXPR, STMT_LIST, WHILE_EXPR},

crates/ide-completion/src/completions/snippet.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
//! This file provides snippet completions, like `pd` => `eprintln!(...)`.
22
3-
use hir::Documentation;
4-
use ide_db::{imports::insert_use::ImportScope, SnippetCap};
3+
use ide_db::{documentation::Documentation, imports::insert_use::ImportScope, SnippetCap};
54

65
use crate::{
76
context::{ExprCtx, ItemListKind, PathCompletionCtx, Qualified},

crates/ide-completion/src/item.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22
33
use std::fmt;
44

5-
use hir::{Documentation, Mutability};
6-
use ide_db::{imports::import_assets::LocatedImport, RootDatabase, SnippetCap, SymbolKind};
5+
use hir::Mutability;
6+
use ide_db::{
7+
documentation::Documentation, imports::import_assets::LocatedImport, RootDatabase, SnippetCap,
8+
SymbolKind,
9+
};
710
use itertools::Itertools;
811
use smallvec::SmallVec;
912
use stdx::{impl_from, never};

0 commit comments

Comments
 (0)