aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorZac Pullar-Strecker <[email protected]>2020-08-01 01:55:04 +0100
committerZac Pullar-Strecker <[email protected]>2020-08-01 01:55:04 +0100
commit19c2830ff86b8765754827b03826870f8640dec2 (patch)
tree51181cac8b44608bc647c41707fcccabedf6a1db
parenta7a00a87fd20a8b697a603d68e60e6ffbc59aac8 (diff)
move into separate module
-rw-r--r--crates/ra_ide/src/hover.rs302
-rw-r--r--crates/ra_ide/src/lib.rs1
-rw-r--r--crates/ra_ide/src/link_rewrite.rs302
-rw-r--r--xtask/tests/tidy.rs1
4 files changed, 308 insertions, 298 deletions
diff --git a/crates/ra_ide/src/hover.rs b/crates/ra_ide/src/hover.rs
index 784a1e77c..7e78ee597 100644
--- a/crates/ra_ide/src/hover.rs
+++ b/crates/ra_ide/src/hover.rs
@@ -1,26 +1,20 @@
1use std::iter::once;
2
3use hir::{ 1use hir::{
4 db::DefDatabase, Adt, AsAssocItem, AsName, AssocItemContainer, AttrDef, Crate, Documentation, 2 Adt, AsAssocItem, AssocItemContainer, Documentation, FieldSource, HasSource, HirDisplay,
5 FieldSource, HasSource, HirDisplay, Hygiene, ItemInNs, ModPath, Module, ModuleDef, 3 Module, ModuleDef, ModuleSource, Semantics,
6 ModuleSource, Semantics,
7}; 4};
8use itertools::Itertools; 5use itertools::Itertools;
9use pulldown_cmark::{CowStr, Event, Options, Parser, Tag};
10use pulldown_cmark_to_cmark::cmark;
11use ra_db::SourceDatabase; 6use ra_db::SourceDatabase;
12use ra_ide_db::{ 7use ra_ide_db::{
13 defs::{classify_name, classify_name_ref, Definition}, 8 defs::{classify_name, classify_name_ref, Definition},
14 RootDatabase, 9 RootDatabase,
15}; 10};
16use ra_syntax::{ast, ast::Path, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset, T}; 11use ra_syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset, T};
17use ra_tt::{Ident, Leaf, Literal, TokenTree};
18use stdx::format_to; 12use stdx::format_to;
19use test_utils::mark; 13use test_utils::mark;
20use url::Url;
21 14
22use crate::{ 15use crate::{
23 display::{macro_label, ShortLabel, ToNav, TryToNav}, 16 display::{macro_label, ShortLabel, ToNav, TryToNav},
17 link_rewrite::rewrite_links,
24 markup::Markup, 18 markup::Markup,
25 runnables::runnable, 19 runnables::runnable,
26 FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, 20 FileId, FilePosition, NavigationTarget, RangeInfo, Runnable,
@@ -343,294 +337,6 @@ fn hover_for_definition(db: &RootDatabase, def: Definition) -> Option<Markup> {
343 } 337 }
344} 338}
345 339
346// Rewrites a markdown document, resolving links using `callback` and additionally striping prefixes/suffixes on link titles.
347fn map_links<'e>(
348 events: impl Iterator<Item = Event<'e>>,
349 callback: impl Fn(&str, &str) -> (String, String),
350) -> impl Iterator<Item = Event<'e>> {
351 let mut in_link = false;
352 let mut link_target: Option<CowStr> = None;
353
354 events.map(move |evt| match evt {
355 Event::Start(Tag::Link(_link_type, ref target, _)) => {
356 in_link = true;
357 link_target = Some(target.clone());
358 evt
359 }
360 Event::End(Tag::Link(link_type, _target, _)) => {
361 in_link = false;
362 Event::End(Tag::Link(link_type, link_target.take().unwrap(), CowStr::Borrowed("")))
363 }
364 Event::Text(s) if in_link => {
365 let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s);
366 link_target = Some(CowStr::Boxed(link_target_s.into()));
367 Event::Text(CowStr::Boxed(link_name.into()))
368 }
369 Event::Code(s) if in_link => {
370 let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s);
371 link_target = Some(CowStr::Boxed(link_target_s.into()));
372 Event::Code(CowStr::Boxed(link_name.into()))
373 }
374 _ => evt,
375 })
376}
377
378/// Rewrite documentation links in markdown to point to an online host (e.g. docs.rs)
379fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition) -> String {
380 let doc = Parser::new_with_broken_link_callback(
381 markdown,
382 Options::empty(),
383 Some(&|label, _| Some((/*url*/ label.to_string(), /*title*/ label.to_string()))),
384 );
385
386 let doc = map_links(doc, |target, title: &str| {
387 // This check is imperfect, there's some overlap between valid intra-doc links
388 // and valid URLs so we choose to be too eager to try to resolve what might be
389 // a URL.
390 if target.contains("://") {
391 (target.to_string(), title.to_string())
392 } else {
393 // Two posibilities:
394 // * path-based links: `../../module/struct.MyStruct.html`
395 // * module-based links (AKA intra-doc links): `super::super::module::MyStruct`
396 let resolved = try_resolve_intra(db, definition, title, &target).or_else(|| {
397 try_resolve_path(db, definition, &target).map(|target| (target, title.to_string()))
398 });
399
400 match resolved {
401 Some((target, title)) => (target, title),
402 None => (target.to_string(), title.to_string()),
403 }
404 }
405 });
406 let mut out = String::new();
407 cmark(doc, &mut out, None).ok();
408 out
409}
410
411#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
412enum Namespace {
413 Types,
414 Values,
415 Macros,
416}
417
418static TYPES: ([&str; 7], [&str; 0]) =
419 (["type", "struct", "enum", "mod", "trait", "union", "module"], []);
420static VALUES: ([&str; 8], [&str; 1]) =
421 (["value", "function", "fn", "method", "const", "static", "mod", "module"], ["()"]);
422static MACROS: ([&str; 1], [&str; 1]) = (["macro"], ["!"]);
423
424impl Namespace {
425 /// Extract the specified namespace from an intra-doc-link if one exists.
426 ///
427 /// # Examples
428 ///
429 /// * `struct MyStruct` -> `Namespace::Types`
430 /// * `panic!` -> `Namespace::Macros`
431 /// * `fn@from_intra_spec` -> `Namespace::Values`
432 fn from_intra_spec(s: &str) -> Option<Self> {
433 [
434 (Namespace::Types, (TYPES.0.iter(), TYPES.1.iter())),
435 (Namespace::Values, (VALUES.0.iter(), VALUES.1.iter())),
436 (Namespace::Macros, (MACROS.0.iter(), MACROS.1.iter())),
437 ]
438 .iter()
439 .filter(|(_ns, (prefixes, suffixes))| {
440 prefixes
441 .clone()
442 .map(|prefix| {
443 s.starts_with(*prefix)
444 && s.chars()
445 .nth(prefix.len() + 1)
446 .map(|c| c == '@' || c == ' ')
447 .unwrap_or(false)
448 })
449 .any(|cond| cond)
450 || suffixes
451 .clone()
452 .map(|suffix| {
453 s.starts_with(*suffix)
454 && s.chars()
455 .nth(suffix.len() + 1)
456 .map(|c| c == '@' || c == ' ')
457 .unwrap_or(false)
458 })
459 .any(|cond| cond)
460 })
461 .map(|(ns, (_, _))| *ns)
462 .next()
463 }
464}
465
466// Strip prefixes, suffixes, and inline code marks from the given string.
467fn strip_prefixes_suffixes(mut s: &str) -> &str {
468 s = s.trim_matches('`');
469
470 [
471 (TYPES.0.iter(), TYPES.1.iter()),
472 (VALUES.0.iter(), VALUES.1.iter()),
473 (MACROS.0.iter(), MACROS.1.iter()),
474 ]
475 .iter()
476 .for_each(|(prefixes, suffixes)| {
477 prefixes.clone().for_each(|prefix| s = s.trim_start_matches(*prefix));
478 suffixes.clone().for_each(|suffix| s = s.trim_end_matches(*suffix));
479 });
480 s.trim_start_matches("@").trim()
481}
482
483/// Try to resolve path to local documentation via intra-doc-links (i.e. `super::gateway::Shard`).
484///
485/// See [RFC1946](https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md).
486fn try_resolve_intra(
487 db: &RootDatabase,
488 definition: &Definition,
489 link_text: &str,
490 link_target: &str,
491) -> Option<(String, String)> {
492 eprintln!("resolving intra");
493
494 // Set link_target for implied shortlinks
495 let link_target =
496 if link_target.is_empty() { link_text.trim_matches('`') } else { link_target };
497
498 // Namespace disambiguation
499 let namespace = Namespace::from_intra_spec(link_target);
500
501 // Strip prefixes/suffixes
502 let link_target = strip_prefixes_suffixes(link_target);
503
504 // Parse link as a module path
505 let path = Path::parse(link_target).ok()?;
506 let modpath = ModPath::from_src(path, &Hygiene::new_unhygienic()).unwrap();
507
508 // Resolve it relative to symbol's location (according to the RFC this should consider small scopes
509 let resolver = definition.resolver(db)?;
510
511 let resolved = resolver.resolve_module_path_in_items(db, &modpath);
512 let (defid, namespace) = match namespace {
513 // FIXME: .or(resolved.macros)
514 None => resolved
515 .types
516 .map(|t| (t.0, Namespace::Types))
517 .or(resolved.values.map(|t| (t.0, Namespace::Values)))?,
518 Some(ns @ Namespace::Types) => (resolved.types?.0, ns),
519 Some(ns @ Namespace::Values) => (resolved.values?.0, ns),
520 // FIXME:
521 Some(Namespace::Macros) => None?,
522 };
523
524 // Get the filepath of the final symbol
525 let def: ModuleDef = defid.into();
526 let module = def.module(db)?;
527 let krate = module.krate();
528 let ns = match namespace {
529 Namespace::Types => ItemInNs::Types(defid),
530 Namespace::Values => ItemInNs::Values(defid),
531 // FIXME:
532 Namespace::Macros => None?,
533 };
534 let import_map = db.import_map(krate.into());
535 let path = import_map.path_of(ns)?;
536
537 Some((
538 get_doc_url(db, &krate)?
539 .join(&format!("{}/", krate.display_name(db)?))
540 .ok()?
541 .join(&path.segments.iter().map(|name| name.to_string()).join("/"))
542 .ok()?
543 .join(&get_symbol_filename(db, &Definition::ModuleDef(def))?)
544 .ok()?
545 .into_string(),
546 strip_prefixes_suffixes(link_text).to_string(),
547 ))
548}
549
550/// Try to resolve path to local documentation via path-based links (i.e. `../gateway/struct.Shard.html`).
551fn try_resolve_path(db: &RootDatabase, definition: &Definition, link: &str) -> Option<String> {
552 eprintln!("resolving path");
553
554 if !link.contains("#") && !link.contains(".html") {
555 return None;
556 }
557 let ns = if let Definition::ModuleDef(moddef) = definition {
558 ItemInNs::Types(moddef.clone().into())
559 } else {
560 return None;
561 };
562 let module = definition.module(db)?;
563 let krate = module.krate();
564 let import_map = db.import_map(krate.into());
565 let base = once(format!("{}", krate.display_name(db)?))
566 .chain(import_map.path_of(ns)?.segments.iter().map(|name| format!("{}", name)))
567 .join("/");
568
569 get_doc_url(db, &krate)
570 .and_then(|url| url.join(&base).ok())
571 .and_then(|url| {
572 get_symbol_filename(db, definition).as_deref().map(|f| url.join(f).ok()).flatten()
573 })
574 .and_then(|url| url.join(link).ok())
575 .map(|url| url.into_string())
576}
577
578/// Try to get the root URL of the documentation of a crate.
579fn get_doc_url(db: &RootDatabase, krate: &Crate) -> Option<Url> {
580 // Look for #![doc(html_root_url = "...")]
581 let attrs = db.attrs(AttrDef::from(krate.root_module(db)?).into());
582 let doc_attr_q = attrs.by_key("doc");
583
584 let doc_url = if doc_attr_q.exists() {
585 doc_attr_q.tt_values().map(|tt| {
586 let name = tt.token_trees.iter()
587 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
588 .skip(2)
589 .next();
590
591 match name {
592 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
593 _ => None
594 }
595 }).flat_map(|t| t).next().map(|s| s.to_string())
596 } else {
597 // Fallback to docs.rs
598 // FIXME: Specify an exact version here (from Cargo.lock)
599 Some(format!("https://docs.rs/{}/*", krate.display_name(db)?))
600 };
601
602 doc_url
603 .map(|s| s.trim_matches('"').trim_end_matches("/").to_owned() + "/")
604 .and_then(|s| Url::parse(&s).ok())
605}
606
607/// Get the filename and extension generated for a symbol by rustdoc.
608///
609/// Example: `struct.Shard.html`
610fn get_symbol_filename(db: &RootDatabase, definition: &Definition) -> Option<String> {
611 Some(match definition {
612 Definition::ModuleDef(def) => match def {
613 ModuleDef::Adt(adt) => match adt {
614 Adt::Struct(s) => format!("struct.{}.html", s.name(db)),
615 Adt::Enum(e) => format!("enum.{}.html", e.name(db)),
616 Adt::Union(u) => format!("union.{}.html", u.name(db)),
617 },
618 ModuleDef::Module(_) => "index.html".to_string(),
619 ModuleDef::Trait(t) => format!("trait.{}.html", t.name(db)),
620 ModuleDef::TypeAlias(t) => format!("type.{}.html", t.name(db)),
621 ModuleDef::BuiltinType(t) => format!("primitive.{}.html", t.as_name()),
622 ModuleDef::Function(f) => format!("fn.{}.html", f.name(db)),
623 ModuleDef::EnumVariant(ev) => {
624 format!("enum.{}.html#variant.{}", ev.parent_enum(db).name(db), ev.name(db))
625 }
626 ModuleDef::Const(c) => format!("const.{}.html", c.name(db)?),
627 ModuleDef::Static(s) => format!("static.{}.html", s.name(db)?),
628 },
629 Definition::Macro(m) => format!("macro.{}.html", m.name(db)?),
630 _ => None?,
631 })
632}
633
634fn pick_best(tokens: TokenAtOffset<SyntaxToken>) -> Option<SyntaxToken> { 340fn pick_best(tokens: TokenAtOffset<SyntaxToken>) -> Option<SyntaxToken> {
635 return tokens.max_by_key(priority); 341 return tokens.max_by_key(priority);
636 fn priority(n: &SyntaxToken) -> usize { 342 fn priority(n: &SyntaxToken) -> usize {
diff --git a/crates/ra_ide/src/lib.rs b/crates/ra_ide/src/lib.rs
index 0fede0d87..e615e993a 100644
--- a/crates/ra_ide/src/lib.rs
+++ b/crates/ra_ide/src/lib.rs
@@ -44,6 +44,7 @@ mod status;
44mod syntax_highlighting; 44mod syntax_highlighting;
45mod syntax_tree; 45mod syntax_tree;
46mod typing; 46mod typing;
47mod link_rewrite;
47 48
48use std::sync::Arc; 49use std::sync::Arc;
49 50
diff --git a/crates/ra_ide/src/link_rewrite.rs b/crates/ra_ide/src/link_rewrite.rs
new file mode 100644
index 000000000..85e6188e8
--- /dev/null
+++ b/crates/ra_ide/src/link_rewrite.rs
@@ -0,0 +1,302 @@
1//! Resolves and rewrites links in markdown documentation for hovers/completion windows.
2
3use std::iter::once;
4
5use itertools::Itertools;
6use pulldown_cmark::{CowStr, Event, Options, Parser, Tag};
7use pulldown_cmark_to_cmark::cmark;
8use url::Url;
9
10use hir::{Adt, AsName, AttrDef, Crate, Hygiene, ItemInNs, ModPath, ModuleDef};
11use ra_hir_def::db::DefDatabase;
12use ra_ide_db::{defs::Definition, RootDatabase};
13use ra_syntax::ast::Path;
14use ra_tt::{Ident, Leaf, Literal, TokenTree};
15
16/// Rewrite documentation links in markdown to point to an online host (e.g. docs.rs)
17pub fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition) -> String {
18 let doc = Parser::new_with_broken_link_callback(
19 markdown,
20 Options::empty(),
21 Some(&|label, _| Some((/*url*/ label.to_string(), /*title*/ label.to_string()))),
22 );
23
24 let doc = map_links(doc, |target, title: &str| {
25 // This check is imperfect, there's some overlap between valid intra-doc links
26 // and valid URLs so we choose to be too eager to try to resolve what might be
27 // a URL.
28 if target.contains("://") {
29 (target.to_string(), title.to_string())
30 } else {
31 // Two posibilities:
32 // * path-based links: `../../module/struct.MyStruct.html`
33 // * module-based links (AKA intra-doc links): `super::super::module::MyStruct`
34 let resolved = try_resolve_intra(db, definition, title, &target).or_else(|| {
35 try_resolve_path(db, definition, &target).map(|target| (target, title.to_string()))
36 });
37
38 match resolved {
39 Some((target, title)) => (target, title),
40 None => (target.to_string(), title.to_string()),
41 }
42 }
43 });
44 let mut out = String::new();
45 cmark(doc, &mut out, None).ok();
46 out
47}
48
49// Rewrites a markdown document, resolving links using `callback` and additionally striping prefixes/suffixes on link titles.
50fn map_links<'e>(
51 events: impl Iterator<Item = Event<'e>>,
52 callback: impl Fn(&str, &str) -> (String, String),
53) -> impl Iterator<Item = Event<'e>> {
54 let mut in_link = false;
55 let mut link_target: Option<CowStr> = None;
56
57 events.map(move |evt| match evt {
58 Event::Start(Tag::Link(_link_type, ref target, _)) => {
59 in_link = true;
60 link_target = Some(target.clone());
61 evt
62 }
63 Event::End(Tag::Link(link_type, _target, _)) => {
64 in_link = false;
65 Event::End(Tag::Link(link_type, link_target.take().unwrap(), CowStr::Borrowed("")))
66 }
67 Event::Text(s) if in_link => {
68 let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s);
69 link_target = Some(CowStr::Boxed(link_target_s.into()));
70 Event::Text(CowStr::Boxed(link_name.into()))
71 }
72 Event::Code(s) if in_link => {
73 let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s);
74 link_target = Some(CowStr::Boxed(link_target_s.into()));
75 Event::Code(CowStr::Boxed(link_name.into()))
76 }
77 _ => evt,
78 })
79}
80
81#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
82enum Namespace {
83 Types,
84 Values,
85 Macros,
86}
87
88static TYPES: ([&str; 7], [&str; 0]) =
89 (["type", "struct", "enum", "mod", "trait", "union", "module"], []);
90static VALUES: ([&str; 8], [&str; 1]) =
91 (["value", "function", "fn", "method", "const", "static", "mod", "module"], ["()"]);
92static MACROS: ([&str; 1], [&str; 1]) = (["macro"], ["!"]);
93
94impl Namespace {
95 /// Extract the specified namespace from an intra-doc-link if one exists.
96 ///
97 /// # Examples
98 ///
99 /// * `struct MyStruct` -> `Namespace::Types`
100 /// * `panic!` -> `Namespace::Macros`
101 /// * `fn@from_intra_spec` -> `Namespace::Values`
102 fn from_intra_spec(s: &str) -> Option<Self> {
103 [
104 (Namespace::Types, (TYPES.0.iter(), TYPES.1.iter())),
105 (Namespace::Values, (VALUES.0.iter(), VALUES.1.iter())),
106 (Namespace::Macros, (MACROS.0.iter(), MACROS.1.iter())),
107 ]
108 .iter()
109 .filter(|(_ns, (prefixes, suffixes))| {
110 prefixes
111 .clone()
112 .map(|prefix| {
113 s.starts_with(*prefix)
114 && s.chars()
115 .nth(prefix.len() + 1)
116 .map(|c| c == '@' || c == ' ')
117 .unwrap_or(false)
118 })
119 .any(|cond| cond)
120 || suffixes
121 .clone()
122 .map(|suffix| {
123 s.starts_with(*suffix)
124 && s.chars()
125 .nth(suffix.len() + 1)
126 .map(|c| c == '@' || c == ' ')
127 .unwrap_or(false)
128 })
129 .any(|cond| cond)
130 })
131 .map(|(ns, (_, _))| *ns)
132 .next()
133 }
134}
135
136// Strip prefixes, suffixes, and inline code marks from the given string.
137fn strip_prefixes_suffixes(mut s: &str) -> &str {
138 s = s.trim_matches('`');
139
140 [
141 (TYPES.0.iter(), TYPES.1.iter()),
142 (VALUES.0.iter(), VALUES.1.iter()),
143 (MACROS.0.iter(), MACROS.1.iter()),
144 ]
145 .iter()
146 .for_each(|(prefixes, suffixes)| {
147 prefixes.clone().for_each(|prefix| s = s.trim_start_matches(*prefix));
148 suffixes.clone().for_each(|suffix| s = s.trim_end_matches(*suffix));
149 });
150 s.trim_start_matches("@").trim()
151}
152
153/// Try to resolve path to local documentation via intra-doc-links (i.e. `super::gateway::Shard`).
154///
155/// See [RFC1946](https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md).
156fn try_resolve_intra(
157 db: &RootDatabase,
158 definition: &Definition,
159 link_text: &str,
160 link_target: &str,
161) -> Option<(String, String)> {
162 eprintln!("resolving intra");
163
164 // Set link_target for implied shortlinks
165 let link_target =
166 if link_target.is_empty() { link_text.trim_matches('`') } else { link_target };
167
168 // Namespace disambiguation
169 let namespace = Namespace::from_intra_spec(link_target);
170
171 // Strip prefixes/suffixes
172 let link_target = strip_prefixes_suffixes(link_target);
173
174 // Parse link as a module path
175 let path = Path::parse(link_target).ok()?;
176 let modpath = ModPath::from_src(path, &Hygiene::new_unhygienic()).unwrap();
177
178 // Resolve it relative to symbol's location (according to the RFC this should consider small scopes
179 let resolver = definition.resolver(db)?;
180
181 let resolved = resolver.resolve_module_path_in_items(db, &modpath);
182 let (defid, namespace) = match namespace {
183 // FIXME: .or(resolved.macros)
184 None => resolved
185 .types
186 .map(|t| (t.0, Namespace::Types))
187 .or(resolved.values.map(|t| (t.0, Namespace::Values)))?,
188 Some(ns @ Namespace::Types) => (resolved.types?.0, ns),
189 Some(ns @ Namespace::Values) => (resolved.values?.0, ns),
190 // FIXME:
191 Some(Namespace::Macros) => None?,
192 };
193
194 // Get the filepath of the final symbol
195 let def: ModuleDef = defid.into();
196 let module = def.module(db)?;
197 let krate = module.krate();
198 let ns = match namespace {
199 Namespace::Types => ItemInNs::Types(defid),
200 Namespace::Values => ItemInNs::Values(defid),
201 // FIXME:
202 Namespace::Macros => None?,
203 };
204 let import_map = db.import_map(krate.into());
205 let path = import_map.path_of(ns)?;
206
207 Some((
208 get_doc_url(db, &krate)?
209 .join(&format!("{}/", krate.display_name(db)?))
210 .ok()?
211 .join(&path.segments.iter().map(|name| name.to_string()).join("/"))
212 .ok()?
213 .join(&get_symbol_filename(db, &Definition::ModuleDef(def))?)
214 .ok()?
215 .into_string(),
216 strip_prefixes_suffixes(link_text).to_string(),
217 ))
218}
219
220/// Try to resolve path to local documentation via path-based links (i.e. `../gateway/struct.Shard.html`).
221fn try_resolve_path(db: &RootDatabase, definition: &Definition, link: &str) -> Option<String> {
222 eprintln!("resolving path");
223
224 if !link.contains("#") && !link.contains(".html") {
225 return None;
226 }
227 let ns = if let Definition::ModuleDef(moddef) = definition {
228 ItemInNs::Types(moddef.clone().into())
229 } else {
230 return None;
231 };
232 let module = definition.module(db)?;
233 let krate = module.krate();
234 let import_map = db.import_map(krate.into());
235 let base = once(format!("{}", krate.display_name(db)?))
236 .chain(import_map.path_of(ns)?.segments.iter().map(|name| format!("{}", name)))
237 .join("/");
238
239 get_doc_url(db, &krate)
240 .and_then(|url| url.join(&base).ok())
241 .and_then(|url| {
242 get_symbol_filename(db, definition).as_deref().map(|f| url.join(f).ok()).flatten()
243 })
244 .and_then(|url| url.join(link).ok())
245 .map(|url| url.into_string())
246}
247
248/// Try to get the root URL of the documentation of a crate.
249fn get_doc_url(db: &RootDatabase, krate: &Crate) -> Option<Url> {
250 // Look for #![doc(html_root_url = "...")]
251 let attrs = db.attrs(AttrDef::from(krate.root_module(db)?).into());
252 let doc_attr_q = attrs.by_key("doc");
253
254 let doc_url = if doc_attr_q.exists() {
255 doc_attr_q.tt_values().map(|tt| {
256 let name = tt.token_trees.iter()
257 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
258 .skip(2)
259 .next();
260
261 match name {
262 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
263 _ => None
264 }
265 }).flat_map(|t| t).next().map(|s| s.to_string())
266 } else {
267 // Fallback to docs.rs
268 // FIXME: Specify an exact version here (from Cargo.lock)
269 Some(format!("https://docs.rs/{}/*", krate.display_name(db)?))
270 };
271
272 doc_url
273 .map(|s| s.trim_matches('"').trim_end_matches("/").to_owned() + "/")
274 .and_then(|s| Url::parse(&s).ok())
275}
276
277/// Get the filename and extension generated for a symbol by rustdoc.
278///
279/// Example: `struct.Shard.html`
280fn get_symbol_filename(db: &RootDatabase, definition: &Definition) -> Option<String> {
281 Some(match definition {
282 Definition::ModuleDef(def) => match def {
283 ModuleDef::Adt(adt) => match adt {
284 Adt::Struct(s) => format!("struct.{}.html", s.name(db)),
285 Adt::Enum(e) => format!("enum.{}.html", e.name(db)),
286 Adt::Union(u) => format!("union.{}.html", u.name(db)),
287 },
288 ModuleDef::Module(_) => "index.html".to_string(),
289 ModuleDef::Trait(t) => format!("trait.{}.html", t.name(db)),
290 ModuleDef::TypeAlias(t) => format!("type.{}.html", t.name(db)),
291 ModuleDef::BuiltinType(t) => format!("primitive.{}.html", t.as_name()),
292 ModuleDef::Function(f) => format!("fn.{}.html", f.name(db)),
293 ModuleDef::EnumVariant(ev) => {
294 format!("enum.{}.html#variant.{}", ev.parent_enum(db).name(db), ev.name(db))
295 }
296 ModuleDef::Const(c) => format!("const.{}.html", c.name(db)?),
297 ModuleDef::Static(s) => format!("static.{}.html", s.name(db)?),
298 },
299 Definition::Macro(m) => format!("macro.{}.html", m.name(db)?),
300 _ => None?,
301 })
302}
diff --git a/xtask/tests/tidy.rs b/xtask/tests/tidy.rs
index d65a2acbc..2096a14a2 100644
--- a/xtask/tests/tidy.rs
+++ b/xtask/tests/tidy.rs
@@ -53,6 +53,7 @@ fn rust_files_are_tidy() {
53fn check_licenses() { 53fn check_licenses() {
54 let expected = " 54 let expected = "
550BSD OR MIT OR Apache-2.0 550BSD OR MIT OR Apache-2.0
56Apache-2.0
56Apache-2.0 OR BSL-1.0 57Apache-2.0 OR BSL-1.0
57Apache-2.0 OR MIT 58Apache-2.0 OR MIT
58Apache-2.0/MIT 59Apache-2.0/MIT