Skip to content

Commit 61bb0cf

Browse files
bors[bot]Veykril
andauthored
Merge #10320
10320: feat: Hover/GotoDef works in macro invocations and on doc attribute strings r=Veykril a=Veykril ![image](https://user-images.githubusercontent.com/3757771/134554781-b903d33d-674f-4ed4-8acb-71ff5913f1cb.png) cc #10271 Co-authored-by: Lukas Wirth <[email protected]>
2 parents eb727c7 + 22c6f0a commit 61bb0cf

File tree

5 files changed

+177
-55
lines changed

5 files changed

+177
-55
lines changed

crates/hir_def/src/attr.rs

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use la_arena::ArenaMap;
1717
use mbe::{syntax_node_to_token_tree, DelimiterKind};
1818
use smallvec::{smallvec, SmallVec};
1919
use syntax::{
20-
ast::{self, AstNode, AttrsOwner},
20+
ast::{self, AstNode, AttrsOwner, IsString},
2121
match_ast, AstPtr, AstToken, SmolStr, SyntaxNode, TextRange, TextSize,
2222
};
2323
use tt::Subtree;
@@ -610,6 +610,7 @@ pub struct DocsRangeMap {
610610
}
611611

612612
impl DocsRangeMap {
613+
/// Maps a [`TextRange`] relative to the documentation string back to its AST range
613614
pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
614615
let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
615616
let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
@@ -621,8 +622,15 @@ impl DocsRangeMap {
621622

622623
let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
623624
match source {
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
625+
Either::Left(attr) => {
626+
let string = get_doc_string_in_attr(&attr)?;
627+
let text_range = string.open_quote_text_range()?;
628+
let range = TextRange::at(
629+
text_range.end() + original_line_src_range.start() + relative_range.start(),
630+
string.syntax().text_range().len().min(range.len()),
631+
);
632+
Some(InFile { file_id, value: range })
633+
}
626634
Either::Right(comment) => {
627635
let text_range = comment.syntax().text_range();
628636
let range = TextRange::at(
@@ -638,6 +646,22 @@ impl DocsRangeMap {
638646
}
639647
}
640648

649+
fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
650+
match it.expr() {
651+
// #[doc = lit]
652+
Some(ast::Expr::Literal(lit)) => match lit.kind() {
653+
ast::LiteralKind::String(it) => Some(it),
654+
_ => None,
655+
},
656+
// #[cfg_attr(..., doc = "", ...)]
657+
None => {
658+
// FIXME: See highlight injection for what to do here
659+
None
660+
}
661+
_ => None,
662+
}
663+
}
664+
641665
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
642666
pub(crate) struct AttrId {
643667
is_doc_comment: bool,

crates/ide/src/doc_links.rs

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,12 @@ use ide_db::{
1919
helpers::pick_best_token,
2020
RootDatabase,
2121
};
22-
use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxNode, TextRange, T};
22+
use syntax::{
23+
ast::{self, IsString},
24+
match_ast, AstNode, AstToken,
25+
SyntaxKind::*,
26+
SyntaxNode, SyntaxToken, TextRange, TextSize, T,
27+
};
2328

2429
use crate::{
2530
doc_links::intra_doc_links::{parse_intra_doc_link, strip_prefixes_suffixes},
@@ -220,6 +225,66 @@ pub(crate) fn doc_attributes(
220225
}
221226
}
222227

228+
pub(crate) struct DocCommentToken {
229+
doc_token: SyntaxToken,
230+
prefix_len: TextSize,
231+
}
232+
233+
pub(crate) fn token_as_doc_comment(doc_token: &SyntaxToken) -> Option<DocCommentToken> {
234+
(match_ast! {
235+
match doc_token {
236+
ast::Comment(comment) => TextSize::try_from(comment.prefix().len()).ok(),
237+
ast::String(string) => doc_token.ancestors().find_map(ast::Attr::cast)
238+
.filter(|attr| attr.simple_name().as_deref() == Some("doc")).and_then(|_| string.open_quote_text_range().map(|it| it.len())),
239+
_ => None,
240+
}
241+
}).map(|prefix_len| DocCommentToken { prefix_len, doc_token: doc_token.clone() })
242+
}
243+
244+
impl DocCommentToken {
245+
pub(crate) fn get_definition_with_descend_at<T>(
246+
self,
247+
sema: &Semantics<RootDatabase>,
248+
offset: TextSize,
249+
// Definition, CommentOwner, range of intra doc link in original file
250+
mut cb: impl FnMut(Definition, SyntaxNode, TextRange) -> Option<T>,
251+
) -> Option<T> {
252+
let DocCommentToken { prefix_len, doc_token } = self;
253+
// offset relative to the comments contents
254+
let original_start = doc_token.text_range().start();
255+
let relative_comment_offset = offset - original_start - prefix_len;
256+
257+
sema.descend_into_macros_many(doc_token.clone()).into_iter().find_map(|t| {
258+
let (node, descended_prefix_len) = match_ast! {
259+
match t {
260+
ast::Comment(comment) => (t.parent()?, TextSize::try_from(comment.prefix().len()).ok()?),
261+
ast::String(string) => (t.ancestors().skip_while(|n| n.kind() != ATTR).nth(1)?, string.open_quote_text_range()?.len()),
262+
_ => return None,
263+
}
264+
};
265+
let token_start = t.text_range().start();
266+
let abs_in_expansion_offset = token_start + relative_comment_offset + descended_prefix_len;
267+
268+
let (attributes, def) = doc_attributes(sema, &node)?;
269+
let (docs, doc_mapping) = attributes.docs_with_rangemap(sema.db)?;
270+
let (in_expansion_range, link, ns) =
271+
extract_definitions_from_docs(&docs).into_iter().find_map(|(range, link, ns)| {
272+
let mapped = doc_mapping.map(range)?;
273+
(mapped.value.contains(abs_in_expansion_offset)).then(|| (mapped.value, link, ns))
274+
})?;
275+
// get the relative range to the doc/attribute in the expansion
276+
let in_expansion_relative_range = in_expansion_range - descended_prefix_len - token_start;
277+
// Apply relative range to the original input comment
278+
let absolute_range = in_expansion_relative_range + original_start + prefix_len;
279+
let def = match resolve_doc_path_for_def(sema.db, def, &link, ns)? {
280+
Either::Left(it) => Definition::ModuleDef(it),
281+
Either::Right(it) => Definition::Macro(it),
282+
};
283+
cb(def, node, absolute_range)
284+
})
285+
}
286+
}
287+
223288
fn broken_link_clone_cb<'a, 'b>(link: BrokenLink<'a>) -> Option<(CowStr<'b>, CowStr<'b>)> {
224289
// These allocations are actually unnecessary but the lifetimes on BrokenLinkCallback are wrong
225290
// this is fixed in the repo but not on the crates.io release yet

crates/ide/src/goto_definition.rs

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
use std::convert::TryInto;
22

33
use crate::{
4-
display::TryToNav,
5-
doc_links::{doc_attributes, extract_definitions_from_docs, resolve_doc_path_for_def},
6-
FilePosition, NavigationTarget, RangeInfo,
4+
display::TryToNav, doc_links::token_as_doc_comment, FilePosition, NavigationTarget, RangeInfo,
75
};
8-
use hir::{AsAssocItem, InFile, ModuleDef, Semantics};
6+
use hir::{AsAssocItem, ModuleDef, Semantics};
97
use ide_db::{
108
base_db::{AnchoredPath, FileId, FileLoader},
119
defs::Definition,
@@ -30,26 +28,19 @@ pub(crate) fn goto_definition(
3028
db: &RootDatabase,
3129
position: FilePosition,
3230
) -> Option<RangeInfo<Vec<NavigationTarget>>> {
33-
let sema = Semantics::new(db);
31+
let sema = &Semantics::new(db);
3432
let file = sema.parse(position.file_id).syntax().clone();
3533
let original_token =
3634
pick_best_token(file.token_at_offset(position.offset), |kind| match kind {
3735
IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] | COMMENT => 2,
3836
kind if kind.is_trivia() => 0,
3937
_ => 1,
4038
})?;
41-
if let Some(_) = ast::Comment::cast(original_token.clone()) {
42-
let parent = original_token.parent()?;
43-
let (attributes, def) = doc_attributes(&sema, &parent)?;
44-
let (docs, doc_mapping) = attributes.docs_with_rangemap(db)?;
45-
let (_, link, ns) =
46-
extract_definitions_from_docs(&docs).into_iter().find(|&(range, ..)| {
47-
doc_mapping.map(range).map_or(false, |InFile { file_id, value: range }| {
48-
file_id == position.file_id.into() && range.contains(position.offset)
49-
})
50-
})?;
51-
let nav = resolve_doc_path_for_def(db, def, &link, ns)?.try_to_nav(db)?;
52-
return Some(RangeInfo::new(original_token.text_range(), vec![nav]));
39+
if let Some(doc_comment) = token_as_doc_comment(&original_token) {
40+
return doc_comment.get_definition_with_descend_at(sema, position.offset, |def, _, _| {
41+
let nav = def.try_to_nav(db)?;
42+
Some(RangeInfo::new(original_token.text_range(), vec![nav]))
43+
});
5344
}
5445
let navs = sema
5546
.descend_into_macros_many(original_token.clone())

crates/ide/src/hover.rs

Lines changed: 64 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,7 @@ use syntax::{
2020

2121
use crate::{
2222
display::{macro_label, TryToNav},
23-
doc_links::{
24-
doc_attributes, extract_definitions_from_docs, remove_links, resolve_doc_path_for_def,
25-
rewrite_links,
26-
},
23+
doc_links::{remove_links, rewrite_links, token_as_doc_comment},
2724
markdown_remove::remove_markdown,
2825
markup::Markup,
2926
runnables::{runnable_fn, runnable_mod},
@@ -114,40 +111,15 @@ pub(crate) fn hover(
114111
_ => 1,
115112
})?;
116113

117-
let descended = sema.descend_into_macros_many(original_token.clone());
118-
119-
// FIXME handle doc attributes? TokenMap currently doesn't work with comments
120-
if original_token.kind() == COMMENT {
121-
let relative_comment_offset = offset - original_token.text_range().start();
122-
// intra-doc links
114+
if let Some(doc_comment) = token_as_doc_comment(&original_token) {
123115
cov_mark::hit!(no_highlight_on_comment_hover);
124-
return descended.iter().find_map(|t| {
125-
match t.kind() {
126-
COMMENT => (),
127-
TOKEN_TREE => {}
128-
_ => return None,
129-
}
130-
let node = t.parent()?;
131-
let absolute_comment_offset = t.text_range().start() + relative_comment_offset;
132-
let (attributes, def) = doc_attributes(sema, &node)?;
133-
let (docs, doc_mapping) = attributes.docs_with_rangemap(sema.db)?;
134-
let (idl_range, link, ns) = extract_definitions_from_docs(&docs).into_iter().find_map(
135-
|(range, link, ns)| {
136-
let mapped = doc_mapping.map(range)?;
137-
(mapped.file_id == file_id.into()
138-
&& mapped.value.contains(absolute_comment_offset))
139-
.then(|| (mapped.value, link, ns))
140-
},
141-
)?;
142-
let def = match resolve_doc_path_for_def(sema.db, def, &link, ns)? {
143-
Either::Left(it) => Definition::ModuleDef(it),
144-
Either::Right(it) => Definition::Macro(it),
145-
};
116+
return doc_comment.get_definition_with_descend_at(sema, offset, |def, node, range| {
146117
let res = hover_for_definition(sema, file_id, def, &node, config)?;
147-
Some(RangeInfo::new(idl_range, res))
118+
Some(RangeInfo::new(range, res))
148119
});
149120
}
150121

122+
let descended = sema.descend_into_macros_many(original_token.clone());
151123
// attributes, require special machinery as they are mere ident tokens
152124

153125
// FIXME: Definition should include known lints and the like instead of having this special case here
@@ -4941,4 +4913,63 @@ fn foo() {
49414913
"#]],
49424914
);
49434915
}
4916+
4917+
#[test]
4918+
fn hover_intra_in_macro() {
4919+
check(
4920+
r#"
4921+
macro_rules! foo_macro {
4922+
($(#[$attr:meta])* $name:ident) => {
4923+
$(#[$attr])*
4924+
pub struct $name;
4925+
}
4926+
}
4927+
4928+
foo_macro!(
4929+
/// Doc comment for [`Foo$0`]
4930+
Foo
4931+
);
4932+
"#,
4933+
expect![[r#"
4934+
*[`Foo`]*
4935+
4936+
```rust
4937+
test
4938+
```
4939+
4940+
```rust
4941+
pub struct Foo
4942+
```
4943+
4944+
---
4945+
4946+
Doc comment for [`Foo`](https://docs.rs/test/*/test/struct.Foo.html)
4947+
"#]],
4948+
);
4949+
}
4950+
4951+
#[test]
4952+
fn hover_intra_in_attr() {
4953+
check(
4954+
r#"
4955+
#[doc = "Doc comment for [`Foo$0`]"]
4956+
pub struct Foo;
4957+
"#,
4958+
expect![[r#"
4959+
*[`Foo`]*
4960+
4961+
```rust
4962+
test
4963+
```
4964+
4965+
```rust
4966+
pub struct Foo
4967+
```
4968+
4969+
---
4970+
4971+
Doc comment for [`Foo`](https://docs.rs/test/*/test/struct.Foo.html)
4972+
"#]],
4973+
);
4974+
}
49444975
}

crates/mbe/src/syntax_bridge.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,18 @@ fn convert_tokens<C: TokenConvertor>(conv: &mut C) -> tt::Subtree {
149149
let k: SyntaxKind = token.kind();
150150
if k == COMMENT {
151151
if let Some(tokens) = conv.convert_doc_comment(&token) {
152-
result.extend(tokens);
152+
// FIXME: There has to be a better way to do this
153+
// Add the comments token id to the converted doc string
154+
let id = conv.id_alloc().alloc(range);
155+
result.extend(tokens.into_iter().map(|mut tt| {
156+
if let tt::TokenTree::Subtree(sub) = &mut tt {
157+
if let tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) = &mut sub.token_trees[2]
158+
{
159+
lit.id = id
160+
}
161+
}
162+
tt
163+
}));
153164
}
154165
continue;
155166
}

0 commit comments

Comments
 (0)