]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/doc_links.rs
Merge #10928
[rust.git] / crates / ide / src / doc_links.rs
1 //! Extracts, resolves and rewrites links and intra-doc links in markdown documentation.
2
3 mod intra_doc_links;
4
5 use either::Either;
6 use pulldown_cmark::{BrokenLink, CowStr, Event, InlineStr, LinkType, Options, Parser, Tag};
7 use pulldown_cmark_to_cmark::{cmark_with_options, Options as CMarkOptions};
8 use stdx::format_to;
9 use url::Url;
10
11 use hir::{db::HirDatabase, Adt, AsAssocItem, AssocItem, AssocItemContainer, Crate, HasAttrs};
12 use ide_db::{
13     defs::{Definition, NameClass, NameRefClass},
14     helpers::pick_best_token,
15     RootDatabase,
16 };
17 use syntax::{
18     ast::{self, IsString},
19     match_ast, AstNode, AstToken,
20     SyntaxKind::*,
21     SyntaxNode, SyntaxToken, TextRange, TextSize, T,
22 };
23
24 use crate::{
25     doc_links::intra_doc_links::{parse_intra_doc_link, strip_prefixes_suffixes},
26     FilePosition, Semantics,
27 };
28
29 /// Weblink to an item's documentation.
30 pub(crate) type DocumentationLink = String;
31
32 const MARKDOWN_OPTIONS: Options =
33     Options::ENABLE_FOOTNOTES.union(Options::ENABLE_TABLES).union(Options::ENABLE_TASKLISTS);
34
35 /// Rewrite documentation links in markdown to point to an online host (e.g. docs.rs)
36 pub(crate) fn rewrite_links(db: &RootDatabase, markdown: &str, definition: Definition) -> String {
37     let mut cb = broken_link_clone_cb;
38     let doc = Parser::new_with_broken_link_callback(markdown, MARKDOWN_OPTIONS, Some(&mut cb));
39
40     let doc = map_links(doc, |target, title| {
41         // This check is imperfect, there's some overlap between valid intra-doc links
42         // and valid URLs so we choose to be too eager to try to resolve what might be
43         // a URL.
44         if target.contains("://") {
45             (target.to_string(), title.to_string())
46         } else {
47             // Two possibilities:
48             // * path-based links: `../../module/struct.MyStruct.html`
49             // * module-based links (AKA intra-doc links): `super::super::module::MyStruct`
50             if let Some(rewritten) = rewrite_intra_doc_link(db, definition, target, title) {
51                 return rewritten;
52             }
53             if let Some(target) = rewrite_url_link(db, definition, target) {
54                 return (target, title.to_string());
55             }
56
57             (target.to_string(), title.to_string())
58         }
59     });
60     let mut out = String::new();
61     cmark_with_options(
62         doc,
63         &mut out,
64         None,
65         CMarkOptions { code_block_token_count: 3, ..Default::default() },
66     )
67     .ok();
68     out
69 }
70
71 /// Remove all links in markdown documentation.
72 pub(crate) fn remove_links(markdown: &str) -> String {
73     let mut drop_link = false;
74
75     let mut cb = |_: BrokenLink| {
76         let empty = InlineStr::try_from("").unwrap();
77         Some((CowStr::Inlined(empty), CowStr::Inlined(empty)))
78     };
79     let doc = Parser::new_with_broken_link_callback(markdown, MARKDOWN_OPTIONS, Some(&mut cb));
80     let doc = doc.filter_map(move |evt| match evt {
81         Event::Start(Tag::Link(link_type, target, title)) => {
82             if link_type == LinkType::Inline && target.contains("://") {
83                 Some(Event::Start(Tag::Link(link_type, target, title)))
84             } else {
85                 drop_link = true;
86                 None
87             }
88         }
89         Event::End(_) if drop_link => {
90             drop_link = false;
91             None
92         }
93         _ => Some(evt),
94     });
95
96     let mut out = String::new();
97     cmark_with_options(
98         doc,
99         &mut out,
100         None,
101         CMarkOptions { code_block_token_count: 3, ..Default::default() },
102     )
103     .ok();
104     out
105 }
106
107 /// Retrieve a link to documentation for the given symbol.
108 pub(crate) fn external_docs(
109     db: &RootDatabase,
110     position: &FilePosition,
111 ) -> Option<DocumentationLink> {
112     let sema = &Semantics::new(db);
113     let file = sema.parse(position.file_id).syntax().clone();
114     let token = pick_best_token(file.token_at_offset(position.offset), |kind| match kind {
115         IDENT | INT_NUMBER | T![self] => 3,
116         T!['('] | T![')'] => 2,
117         kind if kind.is_trivia() => 0,
118         _ => 1,
119     })?;
120     let token = sema.descend_into_macros_single(token);
121
122     let node = token.parent()?;
123     let definition = match_ast! {
124         match node {
125             ast::NameRef(name_ref) => match NameRefClass::classify(sema, &name_ref)? {
126                 NameRefClass::Definition(def) => def,
127                 NameRefClass::FieldShorthand { local_ref: _, field_ref } => {
128                     Definition::Field(field_ref)
129                 }
130             },
131             ast::Name(name) => match NameClass::classify(sema, &name)? {
132                 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
133                 NameClass::PatFieldShorthand { local_def: _, field_ref } => Definition::Field(field_ref),
134             },
135             _ => return None,
136         }
137     };
138
139     get_doc_link(db, definition)
140 }
141
142 /// Extracts all links from a given markdown text returning the definition text range, link-text
143 /// and the namespace if known.
144 pub(crate) fn extract_definitions_from_docs(
145     docs: &hir::Documentation,
146 ) -> Vec<(TextRange, String, Option<hir::Namespace>)> {
147     Parser::new_with_broken_link_callback(
148         docs.as_str(),
149         MARKDOWN_OPTIONS,
150         Some(&mut broken_link_clone_cb),
151     )
152     .into_offset_iter()
153     .filter_map(|(event, range)| match event {
154         Event::Start(Tag::Link(_, target, _)) => {
155             let (link, ns) = parse_intra_doc_link(&target);
156             Some((
157                 TextRange::new(range.start.try_into().ok()?, range.end.try_into().ok()?),
158                 link.to_string(),
159                 ns,
160             ))
161         }
162         _ => None,
163     })
164     .collect()
165 }
166
167 pub(crate) fn resolve_doc_path_for_def(
168     db: &dyn HirDatabase,
169     def: Definition,
170     link: &str,
171     ns: Option<hir::Namespace>,
172 ) -> Option<Definition> {
173     let def = match def {
174         Definition::Module(it) => it.resolve_doc_path(db, link, ns),
175         Definition::Function(it) => it.resolve_doc_path(db, link, ns),
176         Definition::Adt(it) => it.resolve_doc_path(db, link, ns),
177         Definition::Variant(it) => it.resolve_doc_path(db, link, ns),
178         Definition::Const(it) => it.resolve_doc_path(db, link, ns),
179         Definition::Static(it) => it.resolve_doc_path(db, link, ns),
180         Definition::Trait(it) => it.resolve_doc_path(db, link, ns),
181         Definition::TypeAlias(it) => it.resolve_doc_path(db, link, ns),
182         Definition::Macro(it) => it.resolve_doc_path(db, link, ns),
183         Definition::Field(it) => it.resolve_doc_path(db, link, ns),
184         Definition::BuiltinAttr(_)
185         | Definition::ToolModule(_)
186         | Definition::BuiltinType(_)
187         | Definition::SelfType(_)
188         | Definition::Local(_)
189         | Definition::GenericParam(_)
190         | Definition::Label(_) => None,
191     }?;
192     match def {
193         Either::Left(def) => Some(Definition::from(def)),
194         Either::Right(def) => Some(Definition::Macro(def)),
195     }
196 }
197
198 pub(crate) fn doc_attributes(
199     sema: &Semantics<RootDatabase>,
200     node: &SyntaxNode,
201 ) -> Option<(hir::AttrsWithOwner, Definition)> {
202     match_ast! {
203         match node {
204             ast::SourceFile(it)  => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Module(def))),
205             ast::Module(it)      => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Module(def))),
206             ast::Fn(it)          => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Function(def))),
207             ast::Struct(it)      => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Adt(hir::Adt::Struct(def)))),
208             ast::Union(it)       => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Adt(hir::Adt::Union(def)))),
209             ast::Enum(it)        => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Adt(hir::Adt::Enum(def)))),
210             ast::Variant(it)     => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Variant(def))),
211             ast::Trait(it)       => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Trait(def))),
212             ast::Static(it)      => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Static(def))),
213             ast::Const(it)       => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Const(def))),
214             ast::TypeAlias(it)   => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::TypeAlias(def))),
215             ast::Impl(it)        => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::SelfType(def))),
216             ast::RecordField(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Field(def))),
217             ast::TupleField(it)  => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Field(def))),
218             ast::Macro(it)       => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Macro(def))),
219             // ast::Use(it) => sema.to_def(&it).map(|def| (Box::new(it) as _, def.attrs(sema.db))),
220             _ => None
221         }
222     }
223 }
224
225 pub(crate) struct DocCommentToken {
226     doc_token: SyntaxToken,
227     prefix_len: TextSize,
228 }
229
230 pub(crate) fn token_as_doc_comment(doc_token: &SyntaxToken) -> Option<DocCommentToken> {
231     (match_ast! {
232         match doc_token {
233             ast::Comment(comment) => TextSize::try_from(comment.prefix().len()).ok(),
234             ast::String(string) => doc_token.ancestors().find_map(ast::Attr::cast)
235                 .filter(|attr| attr.simple_name().as_deref() == Some("doc")).and_then(|_| string.open_quote_text_range().map(|it| it.len())),
236             _ => None,
237         }
238     }).map(|prefix_len| DocCommentToken { prefix_len, doc_token: doc_token.clone() })
239 }
240
241 impl DocCommentToken {
242     pub(crate) fn get_definition_with_descend_at<T>(
243         self,
244         sema: &Semantics<RootDatabase>,
245         offset: TextSize,
246         // Definition, CommentOwner, range of intra doc link in original file
247         mut cb: impl FnMut(Definition, SyntaxNode, TextRange) -> Option<T>,
248     ) -> Option<T> {
249         let DocCommentToken { prefix_len, doc_token } = self;
250         // offset relative to the comments contents
251         let original_start = doc_token.text_range().start();
252         let relative_comment_offset = offset - original_start - prefix_len;
253
254         sema.descend_into_macros(doc_token).into_iter().find_map(|t| {
255             let (node, descended_prefix_len) = match_ast! {
256                 match t {
257                     ast::Comment(comment) => (t.parent()?, TextSize::try_from(comment.prefix().len()).ok()?),
258                     ast::String(string) => (t.ancestors().skip_while(|n| n.kind() != ATTR).nth(1)?, string.open_quote_text_range()?.len()),
259                     _ => return None,
260                 }
261             };
262             let token_start = t.text_range().start();
263             let abs_in_expansion_offset = token_start + relative_comment_offset + descended_prefix_len;
264
265             let (attributes, def) = doc_attributes(sema, &node)?;
266             let (docs, doc_mapping) = attributes.docs_with_rangemap(sema.db)?;
267             let (in_expansion_range, link, ns) =
268                 extract_definitions_from_docs(&docs).into_iter().find_map(|(range, link, ns)| {
269                     let mapped = doc_mapping.map(range)?;
270                     (mapped.value.contains(abs_in_expansion_offset)).then(|| (mapped.value, link, ns))
271                 })?;
272             // get the relative range to the doc/attribute in the expansion
273             let in_expansion_relative_range = in_expansion_range - descended_prefix_len - token_start;
274             // Apply relative range to the original input comment
275             let absolute_range = in_expansion_relative_range + original_start + prefix_len;
276             let def = resolve_doc_path_for_def(sema.db, def, &link, ns)?;
277             cb(def, node, absolute_range)
278         })
279     }
280 }
281
282 fn broken_link_clone_cb<'a, 'b>(link: BrokenLink<'a>) -> Option<(CowStr<'b>, CowStr<'b>)> {
283     // These allocations are actually unnecessary but the lifetimes on BrokenLinkCallback are wrong
284     // this is fixed in the repo but not on the crates.io release yet
285     Some((
286         /*url*/ link.reference.to_owned().into(),
287         /*title*/ link.reference.to_owned().into(),
288     ))
289 }
290
291 // FIXME:
292 // BUG: For Option::Some
293 // Returns https://doc.rust-lang.org/nightly/core/prelude/v1/enum.Option.html#variant.Some
294 // Instead of https://doc.rust-lang.org/nightly/core/option/enum.Option.html
295 //
296 // This should cease to be a problem if RFC2988 (Stable Rustdoc URLs) is implemented
297 // https://github.com/rust-lang/rfcs/pull/2988
298 fn get_doc_link(db: &RootDatabase, def: Definition) -> Option<String> {
299     let (target, file, frag) = filename_and_frag_for_def(db, def)?;
300
301     let krate = crate_of_def(db, target)?;
302     let mut url = get_doc_base_url(db, &krate)?;
303
304     if let Some(path) = mod_path_of_def(db, target) {
305         url = url.join(&path).ok()?;
306     }
307
308     url = url.join(&file).ok()?;
309     url.set_fragment(frag.as_deref());
310
311     Some(url.into())
312 }
313
314 fn rewrite_intra_doc_link(
315     db: &RootDatabase,
316     def: Definition,
317     target: &str,
318     title: &str,
319 ) -> Option<(String, String)> {
320     let (link, ns) = parse_intra_doc_link(target);
321
322     let resolved = resolve_doc_path_for_def(db, def, link, ns)?;
323     let krate = crate_of_def(db, resolved)?;
324     let mut url = get_doc_base_url(db, &krate)?;
325
326     let (_, file, frag) = filename_and_frag_for_def(db, resolved)?;
327     if let Some(path) = mod_path_of_def(db, resolved) {
328         url = url.join(&path).ok()?;
329     }
330
331     url = url.join(&file).ok()?;
332     url.set_fragment(frag.as_deref());
333
334     Some((url.into(), strip_prefixes_suffixes(title).to_string()))
335 }
336
337 /// Try to resolve path to local documentation via path-based links (i.e. `../gateway/struct.Shard.html`).
338 fn rewrite_url_link(db: &RootDatabase, def: Definition, target: &str) -> Option<String> {
339     if !(target.contains('#') || target.contains(".html")) {
340         return None;
341     }
342
343     let krate = crate_of_def(db, def)?;
344     let mut url = get_doc_base_url(db, &krate)?;
345     let (def, file, frag) = filename_and_frag_for_def(db, def)?;
346
347     if let Some(path) = mod_path_of_def(db, def) {
348         url = url.join(&path).ok()?;
349     }
350
351     url = url.join(&file).ok()?;
352     url.set_fragment(frag.as_deref());
353     url.join(target).ok().map(Into::into)
354 }
355
356 fn crate_of_def(db: &RootDatabase, def: Definition) -> Option<Crate> {
357     let krate = match def {
358         // Definition::module gives back the parent module, we don't want that as it fails for root modules
359         Definition::Module(module) => module.krate(),
360         def => def.module(db)?.krate(),
361     };
362     Some(krate)
363 }
364
365 fn mod_path_of_def(db: &RootDatabase, def: Definition) -> Option<String> {
366     def.canonical_module_path(db).map(|it| {
367         let mut path = String::new();
368         it.flat_map(|it| it.name(db)).for_each(|name| format_to!(path, "{}/", name));
369         path
370     })
371 }
372
373 /// Rewrites a markdown document, applying 'callback' to each link.
374 fn map_links<'e>(
375     events: impl Iterator<Item = Event<'e>>,
376     callback: impl Fn(&str, &str) -> (String, String),
377 ) -> impl Iterator<Item = Event<'e>> {
378     let mut in_link = false;
379     let mut link_target: Option<CowStr> = None;
380
381     events.map(move |evt| match evt {
382         Event::Start(Tag::Link(_, ref target, _)) => {
383             in_link = true;
384             link_target = Some(target.clone());
385             evt
386         }
387         Event::End(Tag::Link(link_type, target, _)) => {
388             in_link = false;
389             Event::End(Tag::Link(
390                 link_type,
391                 link_target.take().unwrap_or(target),
392                 CowStr::Borrowed(""),
393             ))
394         }
395         Event::Text(s) if in_link => {
396             let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s);
397             link_target = Some(CowStr::Boxed(link_target_s.into()));
398             Event::Text(CowStr::Boxed(link_name.into()))
399         }
400         Event::Code(s) if in_link => {
401             let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s);
402             link_target = Some(CowStr::Boxed(link_target_s.into()));
403             Event::Code(CowStr::Boxed(link_name.into()))
404         }
405         _ => evt,
406     })
407 }
408
409 /// Get the root URL for the documentation of a crate.
410 ///
411 /// ```ignore
412 /// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next
413 /// ^^^^^^^^^^^^^^^^^^^^^^^^^^
414 /// ```
415 fn get_doc_base_url(db: &RootDatabase, krate: &Crate) -> Option<Url> {
416     let display_name = krate.display_name(db)?;
417     let base = match &**display_name.crate_name() {
418         // std and co do not specify `html_root_url` any longer so we gotta handwrite this ourself.
419         // FIXME: Use the toolchains channel instead of nightly
420         name @ ("core" | "std" | "alloc" | "proc_macro" | "test") => {
421             format!("https://doc.rust-lang.org/nightly/{}", name)
422         }
423         _ => {
424             krate.get_html_root_url(db).or_else(|| {
425                 let version = krate.version(db);
426                 // Fallback to docs.rs. This uses `display_name` and can never be
427                 // correct, but that's what fallbacks are about.
428                 //
429                 // FIXME: clicking on the link should just open the file in the editor,
430                 // instead of falling back to external urls.
431                 Some(format!(
432                     "https://docs.rs/{krate}/{version}/",
433                     krate = display_name,
434                     version = version.as_deref().unwrap_or("*")
435                 ))
436             })?
437         }
438     };
439     Url::parse(&base).ok()?.join(&format!("{}/", display_name)).ok()
440 }
441
442 /// Get the filename and extension generated for a symbol by rustdoc.
443 ///
444 /// ```ignore
445 /// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next
446 ///                                    ^^^^^^^^^^^^^^^^^^^
447 /// ```
448 fn filename_and_frag_for_def(
449     db: &dyn HirDatabase,
450     def: Definition,
451 ) -> Option<(Definition, String, Option<String>)> {
452     if let Some(assoc_item) = def.as_assoc_item(db) {
453         let def = match assoc_item.container(db) {
454             AssocItemContainer::Trait(t) => t.into(),
455             AssocItemContainer::Impl(i) => i.self_ty(db).as_adt()?.into(),
456         };
457         let (_, file, _) = filename_and_frag_for_def(db, def)?;
458         let frag = get_assoc_item_fragment(db, assoc_item)?;
459         return Some((def, file, Some(frag)));
460     }
461
462     let res = match def {
463         Definition::Adt(adt) => match adt {
464             Adt::Struct(s) => format!("struct.{}.html", s.name(db)),
465             Adt::Enum(e) => format!("enum.{}.html", e.name(db)),
466             Adt::Union(u) => format!("union.{}.html", u.name(db)),
467         },
468         Definition::Module(m) => match m.name(db) {
469             Some(name) => format!("{}/index.html", name),
470             None => String::from("index.html"),
471         },
472         Definition::Trait(t) => format!("trait.{}.html", t.name(db)),
473         Definition::TypeAlias(t) => format!("type.{}.html", t.name(db)),
474         Definition::BuiltinType(t) => format!("primitive.{}.html", t.name()),
475         Definition::Function(f) => format!("fn.{}.html", f.name(db)),
476         Definition::Variant(ev) => {
477             format!("enum.{}.html#variant.{}", ev.parent_enum(db).name(db), ev.name(db))
478         }
479         Definition::Const(c) => format!("const.{}.html", c.name(db)?),
480         Definition::Static(s) => format!("static.{}.html", s.name(db)),
481         Definition::Macro(mac) => format!("macro.{}.html", mac.name(db)?),
482         Definition::Field(field) => {
483             let def = match field.parent_def(db) {
484                 hir::VariantDef::Struct(it) => Definition::Adt(it.into()),
485                 hir::VariantDef::Union(it) => Definition::Adt(it.into()),
486                 hir::VariantDef::Variant(it) => Definition::Variant(it),
487             };
488             let (_, file, _) = filename_and_frag_for_def(db, def)?;
489             return Some((def, file, Some(format!("structfield.{}", field.name(db)))));
490         }
491         Definition::SelfType(impl_) => {
492             let adt = impl_.self_ty(db).as_adt()?.into();
493             let (_, file, _) = filename_and_frag_for_def(db, adt)?;
494             // FIXME fragment numbering
495             return Some((adt, file, Some(String::from("impl"))));
496         }
497         Definition::Local(_)
498         | Definition::GenericParam(_)
499         | Definition::Label(_)
500         | Definition::BuiltinAttr(_)
501         | Definition::ToolModule(_) => return None,
502     };
503
504     Some((def, res, None))
505 }
506
507 /// Get the fragment required to link to a specific field, method, associated type, or associated constant.
508 ///
509 /// ```ignore
510 /// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next
511 ///                                                       ^^^^^^^^^^^^^^
512 /// ```
513 fn get_assoc_item_fragment(db: &dyn HirDatabase, assoc_item: hir::AssocItem) -> Option<String> {
514     Some(match assoc_item {
515         AssocItem::Function(function) => {
516             let is_trait_method =
517                 function.as_assoc_item(db).and_then(|assoc| assoc.containing_trait(db)).is_some();
518             // This distinction may get more complicated when specialization is available.
519             // Rustdoc makes this decision based on whether a method 'has defaultness'.
520             // Currently this is only the case for provided trait methods.
521             if is_trait_method && !function.has_body(db) {
522                 format!("tymethod.{}", function.name(db))
523             } else {
524                 format!("method.{}", function.name(db))
525             }
526         }
527         AssocItem::Const(constant) => format!("associatedconstant.{}", constant.name(db)?),
528         AssocItem::TypeAlias(ty) => format!("associatedtype.{}", ty.name(db)),
529     })
530 }
531
532 #[cfg(test)]
533 mod tests {
534     use expect_test::{expect, Expect};
535     use ide_db::base_db::FileRange;
536     use itertools::Itertools;
537
538     use crate::{fixture, TryToNav};
539
540     use super::*;
541
542     #[test]
543     fn external_docs_doc_url_crate() {
544         check_external_docs(
545             r#"
546 //- /main.rs crate:main deps:foo
547 use foo$0::Foo;
548 //- /lib.rs crate:foo
549 pub struct Foo;
550 "#,
551             expect![[r#"https://docs.rs/foo/*/foo/index.html"#]],
552         );
553     }
554
555     #[test]
556     fn external_docs_doc_url_std_crate() {
557         check_external_docs(
558             r#"
559 //- /main.rs crate:std
560 use self$0;
561 "#,
562             expect![[r#"https://doc.rust-lang.org/nightly/std/index.html"#]],
563         );
564     }
565
566     #[test]
567     fn external_docs_doc_url_struct() {
568         check_external_docs(
569             r#"
570 //- /main.rs crate:foo
571 pub struct Fo$0o;
572 "#,
573             expect![[r#"https://docs.rs/foo/*/foo/struct.Foo.html"#]],
574         );
575     }
576
577     #[test]
578     fn external_docs_doc_url_struct_field() {
579         check_external_docs(
580             r#"
581 //- /main.rs crate:foo
582 pub struct Foo {
583     field$0: ()
584 }
585 "#,
586             expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#structfield.field"##]],
587         );
588     }
589
590     #[test]
591     fn external_docs_doc_url_fn() {
592         check_external_docs(
593             r#"
594 //- /main.rs crate:foo
595 pub fn fo$0o() {}
596 "#,
597             expect![[r#"https://docs.rs/foo/*/foo/fn.foo.html"#]],
598         );
599     }
600
601     #[test]
602     fn external_docs_doc_url_impl_assoc() {
603         check_external_docs(
604             r#"
605 //- /main.rs crate:foo
606 pub struct Foo;
607 impl Foo {
608     pub fn method$0() {}
609 }
610 "#,
611             expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#method.method"##]],
612         );
613         check_external_docs(
614             r#"
615 //- /main.rs crate:foo
616 pub struct Foo;
617 impl Foo {
618     const CONST$0: () = ();
619 }
620 "#,
621             expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#associatedconstant.CONST"##]],
622         );
623     }
624
625     #[test]
626     fn external_docs_doc_url_impl_trait_assoc() {
627         check_external_docs(
628             r#"
629 //- /main.rs crate:foo
630 pub struct Foo;
631 pub trait Trait {
632     fn method() {}
633 }
634 impl Trait for Foo {
635     pub fn method$0() {}
636 }
637 "#,
638             expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#method.method"##]],
639         );
640         check_external_docs(
641             r#"
642 //- /main.rs crate:foo
643 pub struct Foo;
644 pub trait Trait {
645     const CONST: () = ();
646 }
647 impl Trait for Foo {
648     const CONST$0: () = ();
649 }
650 "#,
651             expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#associatedconstant.CONST"##]],
652         );
653         check_external_docs(
654             r#"
655 //- /main.rs crate:foo
656 pub struct Foo;
657 pub trait Trait {
658     type Type;
659 }
660 impl Trait for Foo {
661     type Type$0 = ();
662 }
663 "#,
664             expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#associatedtype.Type"##]],
665         );
666     }
667
668     #[test]
669     fn external_docs_doc_url_trait_assoc() {
670         check_external_docs(
671             r#"
672 //- /main.rs crate:foo
673 pub trait Foo {
674     fn method$0();
675 }
676 "#,
677             expect![[r##"https://docs.rs/foo/*/foo/trait.Foo.html#tymethod.method"##]],
678         );
679         check_external_docs(
680             r#"
681 //- /main.rs crate:foo
682 pub trait Foo {
683     const CONST$0: ();
684 }
685 "#,
686             expect![[r##"https://docs.rs/foo/*/foo/trait.Foo.html#associatedconstant.CONST"##]],
687         );
688         check_external_docs(
689             r#"
690 //- /main.rs crate:foo
691 pub trait Foo {
692     type Type$0;
693 }
694 "#,
695             expect![[r##"https://docs.rs/foo/*/foo/trait.Foo.html#associatedtype.Type"##]],
696         );
697     }
698
699     #[test]
700     fn external_docs_trait() {
701         check_external_docs(
702             r#"
703 //- /main.rs crate:foo
704 trait Trait$0 {}
705 "#,
706             expect![[r#"https://docs.rs/foo/*/foo/trait.Trait.html"#]],
707         )
708     }
709
710     #[test]
711     fn external_docs_module() {
712         check_external_docs(
713             r#"
714 //- /main.rs crate:foo
715 pub mod foo {
716     pub mod ba$0r {}
717 }
718 "#,
719             expect![[r#"https://docs.rs/foo/*/foo/foo/bar/index.html"#]],
720         )
721     }
722
723     #[test]
724     fn external_docs_reexport_order() {
725         check_external_docs(
726             r#"
727 //- /main.rs crate:foo
728 pub mod wrapper {
729     pub use module::Item;
730
731     pub mod module {
732         pub struct Item;
733     }
734 }
735
736 fn foo() {
737     let bar: wrapper::It$0em;
738 }
739         "#,
740             expect![[r#"https://docs.rs/foo/*/foo/wrapper/module/struct.Item.html"#]],
741         )
742     }
743
744     #[test]
745     fn test_trait_items() {
746         check_doc_links(
747             r#"
748 /// [`Trait`]
749 /// [`Trait::Type`]
750 /// [`Trait::CONST`]
751 /// [`Trait::func`]
752 trait Trait$0 {
753    // ^^^^^ Trait
754     type Type;
755       // ^^^^ Trait::Type
756     const CONST: usize;
757        // ^^^^^ Trait::CONST
758     fn func();
759     // ^^^^ Trait::func
760 }
761         "#,
762         )
763     }
764
765     #[test]
766     fn rewrite_html_root_url() {
767         check_rewrite(
768             r#"
769 //- /main.rs crate:foo
770 #![doc(arbitrary_attribute = "test", html_root_url = "https:/example.com", arbitrary_attribute2)]
771
772 pub mod foo {
773     pub struct Foo;
774 }
775 /// [Foo](foo::Foo)
776 pub struct B$0ar
777 "#,
778             expect![[r#"[Foo](https://example.com/foo/foo/struct.Foo.html)"#]],
779         );
780     }
781
782     #[test]
783     fn rewrite_on_field() {
784         check_rewrite(
785             r#"
786 //- /main.rs crate:foo
787 pub struct Foo {
788     /// [Foo](struct.Foo.html)
789     fie$0ld: ()
790 }
791 "#,
792             expect![[r#"[Foo](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
793         );
794     }
795
796     #[test]
797     fn rewrite_struct() {
798         check_rewrite(
799             r#"
800 //- /main.rs crate:foo
801 /// [Foo]
802 pub struct $0Foo;
803 "#,
804             expect![[r#"[Foo](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
805         );
806         check_rewrite(
807             r#"
808 //- /main.rs crate:foo
809 /// [`Foo`]
810 pub struct $0Foo;
811 "#,
812             expect![[r#"[`Foo`](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
813         );
814         check_rewrite(
815             r#"
816 //- /main.rs crate:foo
817 /// [Foo](struct.Foo.html)
818 pub struct $0Foo;
819 "#,
820             expect![[r#"[Foo](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
821         );
822         check_rewrite(
823             r#"
824 //- /main.rs crate:foo
825 /// [struct Foo](struct.Foo.html)
826 pub struct $0Foo;
827 "#,
828             expect![[r#"[struct Foo](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
829         );
830         check_rewrite(
831             r#"
832 //- /main.rs crate:foo
833 /// [my Foo][foo]
834 ///
835 /// [foo]: Foo
836 pub struct $0Foo;
837 "#,
838             expect![[r#"[my Foo](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
839         );
840     }
841
842     fn check_external_docs(ra_fixture: &str, expect: Expect) {
843         let (analysis, position) = fixture::position(ra_fixture);
844         let url = analysis.external_docs(position).unwrap().expect("could not find url for symbol");
845
846         expect.assert_eq(&url)
847     }
848
849     fn check_rewrite(ra_fixture: &str, expect: Expect) {
850         let (analysis, position) = fixture::position(ra_fixture);
851         let sema = &Semantics::new(&*analysis.db);
852         let (cursor_def, docs) = def_under_cursor(sema, &position);
853         let res = rewrite_links(sema.db, docs.as_str(), cursor_def);
854         expect.assert_eq(&res)
855     }
856
857     fn check_doc_links(ra_fixture: &str) {
858         let key_fn = |&(FileRange { file_id, range }, _): &_| (file_id, range.start());
859
860         let (analysis, position, mut expected) = fixture::annotations(ra_fixture);
861         expected.sort_by_key(key_fn);
862         let sema = &Semantics::new(&*analysis.db);
863         let (cursor_def, docs) = def_under_cursor(sema, &position);
864         let defs = extract_definitions_from_docs(&docs);
865         let actual: Vec<_> = defs
866             .into_iter()
867             .map(|(_, link, ns)| {
868                 let def = resolve_doc_path_for_def(sema.db, cursor_def, &link, ns)
869                     .unwrap_or_else(|| panic!("Failed to resolve {}", link));
870                 let nav_target = def.try_to_nav(sema.db).unwrap();
871                 let range = FileRange {
872                     file_id: nav_target.file_id,
873                     range: nav_target.focus_or_full_range(),
874                 };
875                 (range, link)
876             })
877             .sorted_by_key(key_fn)
878             .collect();
879         assert_eq!(expected, actual);
880     }
881
882     fn def_under_cursor(
883         sema: &Semantics<RootDatabase>,
884         position: &FilePosition,
885     ) -> (Definition, hir::Documentation) {
886         let (docs, def) = sema
887             .parse(position.file_id)
888             .syntax()
889             .token_at_offset(position.offset)
890             .left_biased()
891             .unwrap()
892             .ancestors()
893             .find_map(|it| node_to_def(sema, &it))
894             .expect("no def found")
895             .unwrap();
896         let docs = docs.expect("no docs found for cursor def");
897         (def, docs)
898     }
899
900     fn node_to_def(
901         sema: &Semantics<RootDatabase>,
902         node: &SyntaxNode,
903     ) -> Option<Option<(Option<hir::Documentation>, Definition)>> {
904         Some(match_ast! {
905             match node {
906                 ast::SourceFile(it)  => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Module(def))),
907                 ast::Module(it)      => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Module(def))),
908                 ast::Fn(it)          => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Function(def))),
909                 ast::Struct(it)      => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Adt(hir::Adt::Struct(def)))),
910                 ast::Union(it)       => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Adt(hir::Adt::Union(def)))),
911                 ast::Enum(it)        => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Adt(hir::Adt::Enum(def)))),
912                 ast::Variant(it)     => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Variant(def))),
913                 ast::Trait(it)       => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Trait(def))),
914                 ast::Static(it)      => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Static(def))),
915                 ast::Const(it)       => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Const(def))),
916                 ast::TypeAlias(it)   => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::TypeAlias(def))),
917                 ast::Impl(it)        => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::SelfType(def))),
918                 ast::RecordField(it) => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Field(def))),
919                 ast::TupleField(it)  => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Field(def))),
920                 ast::Macro(it)       => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Macro(def))),
921                 // ast::Use(it) => sema.to_def(&it).map(|def| (Box::new(it) as _, def.attrs(sema.db))),
922                 _ => return None,
923             }
924         })
925     }
926 }