aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide/src/link_rewrite.rs
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 /crates/ra_ide/src/link_rewrite.rs
parenta7a00a87fd20a8b697a603d68e60e6ffbc59aac8 (diff)
move into separate module
Diffstat (limited to 'crates/ra_ide/src/link_rewrite.rs')
-rw-r--r--crates/ra_ide/src/link_rewrite.rs302
1 files changed, 302 insertions, 0 deletions
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}