diff options
author | Zac Pullar-Strecker <[email protected]> | 2020-08-31 09:38:10 +0100 |
---|---|---|
committer | Zac Pullar-Strecker <[email protected]> | 2020-10-08 03:01:30 +0100 |
commit | 8c32bdea3662f4c65810e2d92569b0cb4e3872d9 (patch) | |
tree | e5f5fec86a7c766eefd3a34501ef944bd2088651 /crates/ide/src/doc_links.rs | |
parent | a06d736b77770e4c1e738086c81b4fd60fcfcb23 (diff) |
Rename ide::link_rewrite -> ide::doc_links & tidy imports
Diffstat (limited to 'crates/ide/src/doc_links.rs')
-rw-r--r-- | crates/ide/src/doc_links.rs | 433 |
1 files changed, 433 insertions, 0 deletions
diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs new file mode 100644 index 000000000..1e102997f --- /dev/null +++ b/crates/ide/src/doc_links.rs | |||
@@ -0,0 +1,433 @@ | |||
1 | //! Resolves and rewrites links in markdown documentation. | ||
2 | //! | ||
3 | //! Most of the implementation can be found in [`hir::doc_links`]. | ||
4 | |||
5 | use hir::{Adt, Crate, HasAttrs, ModuleDef}; | ||
6 | use ide_db::{defs::Definition, RootDatabase}; | ||
7 | use pulldown_cmark::{CowStr, Event, LinkType, Options, Parser, Tag}; | ||
8 | use pulldown_cmark_to_cmark::{cmark_with_options, Options as CmarkOptions}; | ||
9 | use url::Url; | ||
10 | |||
11 | use crate::{FilePosition, Semantics}; | ||
12 | use hir::{get_doc_link, resolve_doc_link}; | ||
13 | use ide_db::{ | ||
14 | defs::{classify_name, classify_name_ref, Definition}, | ||
15 | RootDatabase, | ||
16 | }; | ||
17 | use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset, T}; | ||
18 | |||
19 | pub type DocumentationLink = String; | ||
20 | |||
21 | /// Rewrite documentation links in markdown to point to an online host (e.g. docs.rs) | ||
22 | pub fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition) -> String { | ||
23 | let doc = Parser::new_with_broken_link_callback( | ||
24 | markdown, | ||
25 | Options::empty(), | ||
26 | Some(&|label, _| Some((/*url*/ label.to_string(), /*title*/ label.to_string()))), | ||
27 | ); | ||
28 | |||
29 | let doc = map_links(doc, |target, title: &str| { | ||
30 | // This check is imperfect, there's some overlap between valid intra-doc links | ||
31 | // and valid URLs so we choose to be too eager to try to resolve what might be | ||
32 | // a URL. | ||
33 | if target.contains("://") { | ||
34 | (target.to_string(), title.to_string()) | ||
35 | } else { | ||
36 | // Two posibilities: | ||
37 | // * path-based links: `../../module/struct.MyStruct.html` | ||
38 | // * module-based links (AKA intra-doc links): `super::super::module::MyStruct` | ||
39 | if let Some(rewritten) = rewrite_intra_doc_link(db, *definition, target, title) { | ||
40 | return rewritten; | ||
41 | } | ||
42 | if let Definition::ModuleDef(def) = *definition { | ||
43 | if let Some(target) = rewrite_url_link(db, def, target) { | ||
44 | return (target, title.to_string()); | ||
45 | } | ||
46 | } | ||
47 | |||
48 | (target.to_string(), title.to_string()) | ||
49 | } | ||
50 | }); | ||
51 | let mut out = String::new(); | ||
52 | let mut options = CmarkOptions::default(); | ||
53 | options.code_block_backticks = 3; | ||
54 | cmark_with_options(doc, &mut out, None, options).ok(); | ||
55 | out | ||
56 | } | ||
57 | |||
58 | /// Remove all links in markdown documentation. | ||
59 | pub fn remove_links(markdown: &str) -> String { | ||
60 | let mut drop_link = false; | ||
61 | |||
62 | let mut opts = Options::empty(); | ||
63 | opts.insert(Options::ENABLE_FOOTNOTES); | ||
64 | |||
65 | let doc = Parser::new_with_broken_link_callback( | ||
66 | markdown, | ||
67 | opts, | ||
68 | Some(&|_, _| Some((String::new(), String::new()))), | ||
69 | ); | ||
70 | let doc = doc.filter_map(move |evt| match evt { | ||
71 | Event::Start(Tag::Link(link_type, ref target, ref title)) => { | ||
72 | if link_type == LinkType::Inline && target.contains("://") { | ||
73 | Some(Event::Start(Tag::Link(link_type, target.clone(), title.clone()))) | ||
74 | } else { | ||
75 | drop_link = true; | ||
76 | None | ||
77 | } | ||
78 | } | ||
79 | Event::End(_) if drop_link => { | ||
80 | drop_link = false; | ||
81 | None | ||
82 | } | ||
83 | _ => Some(evt), | ||
84 | }); | ||
85 | |||
86 | let mut out = String::new(); | ||
87 | let mut options = CmarkOptions::default(); | ||
88 | options.code_block_backticks = 3; | ||
89 | cmark_with_options(doc, &mut out, None, options).ok(); | ||
90 | out | ||
91 | } | ||
92 | |||
93 | pub fn get_doc_link<T: Resolvable + Clone>(db: &dyn HirDatabase, definition: &T) -> Option<String> { | ||
94 | let module_def = definition.clone().try_into_module_def()?; | ||
95 | |||
96 | get_doc_link_impl(db, &module_def) | ||
97 | } | ||
98 | |||
99 | // TODO: | ||
100 | // BUG: For Option | ||
101 | // Returns https://doc.rust-lang.org/nightly/core/prelude/v1/enum.Option.html#variant.Some | ||
102 | // Instead of https://doc.rust-lang.org/nightly/core/option/enum.Option.html | ||
103 | // | ||
104 | // BUG: For methods | ||
105 | // import_map.path_of(ns) fails, is not designed to resolve methods | ||
106 | fn get_doc_link_impl(db: &dyn HirDatabase, moddef: &ModuleDef) -> Option<String> { | ||
107 | // Get the outermost definition for the moduledef. This is used to resolve the public path to the type, | ||
108 | // then we can join the method, field, etc onto it if required. | ||
109 | let target_def: ModuleDef = match moddef { | ||
110 | ModuleDef::Function(f) => match f.as_assoc_item(db).map(|assoc| assoc.container(db)) { | ||
111 | Some(AssocItemContainer::Trait(t)) => t.into(), | ||
112 | Some(AssocItemContainer::ImplDef(imp)) => { | ||
113 | let resolver = ModuleId::from(imp.module(db)).resolver(db.upcast()); | ||
114 | let ctx = TyLoweringContext::new(db, &resolver); | ||
115 | Adt::from( | ||
116 | Ty::from_hir( | ||
117 | &ctx, | ||
118 | &imp.target_trait(db).unwrap_or_else(|| imp.target_type(db)), | ||
119 | ) | ||
120 | .as_adt() | ||
121 | .map(|t| t.0) | ||
122 | .unwrap(), | ||
123 | ) | ||
124 | .into() | ||
125 | } | ||
126 | None => ModuleDef::Function(*f), | ||
127 | }, | ||
128 | moddef => *moddef, | ||
129 | }; | ||
130 | |||
131 | let ns = ItemInNs::Types(target_def.clone().into()); | ||
132 | |||
133 | let module = moddef.module(db)?; | ||
134 | let krate = module.krate(); | ||
135 | let import_map = db.import_map(krate.into()); | ||
136 | let base = once(krate.display_name(db).unwrap()) | ||
137 | .chain(import_map.path_of(ns).unwrap().segments.iter().map(|name| format!("{}", name))) | ||
138 | .join("/"); | ||
139 | |||
140 | get_doc_url(db, &krate) | ||
141 | .and_then(|url| url.join(&base).ok()) | ||
142 | .and_then(|url| { | ||
143 | get_symbol_filename(db, &target_def).as_deref().and_then(|f| url.join(f).ok()) | ||
144 | }) | ||
145 | .and_then(|url| match moddef { | ||
146 | ModuleDef::Function(f) => { | ||
147 | get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Function(*f))) | ||
148 | .as_deref() | ||
149 | .and_then(|f| url.join(f).ok()) | ||
150 | } | ||
151 | ModuleDef::Const(c) => { | ||
152 | get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Const(*c))) | ||
153 | .as_deref() | ||
154 | .and_then(|f| url.join(f).ok()) | ||
155 | } | ||
156 | ModuleDef::TypeAlias(ty) => { | ||
157 | get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::TypeAlias(*ty))) | ||
158 | .as_deref() | ||
159 | .and_then(|f| url.join(f).ok()) | ||
160 | } | ||
161 | // TODO: Field <- this requires passing in a definition or something | ||
162 | _ => Some(url), | ||
163 | }) | ||
164 | .map(|url| url.into_string()) | ||
165 | } | ||
166 | |||
167 | fn rewrite_intra_doc_link( | ||
168 | db: &RootDatabase, | ||
169 | def: Definition, | ||
170 | target: &str, | ||
171 | title: &str, | ||
172 | ) -> Option<(String, String)> { | ||
173 | let link = if target.is_empty() { title } else { target }; | ||
174 | let (link, ns) = parse_link(link); | ||
175 | let resolved = match def { | ||
176 | Definition::ModuleDef(def) => match def { | ||
177 | ModuleDef::Module(it) => it.resolve_doc_path(db, link, ns), | ||
178 | ModuleDef::Function(it) => it.resolve_doc_path(db, link, ns), | ||
179 | ModuleDef::Adt(it) => it.resolve_doc_path(db, link, ns), | ||
180 | ModuleDef::EnumVariant(it) => it.resolve_doc_path(db, link, ns), | ||
181 | ModuleDef::Const(it) => it.resolve_doc_path(db, link, ns), | ||
182 | ModuleDef::Static(it) => it.resolve_doc_path(db, link, ns), | ||
183 | ModuleDef::Trait(it) => it.resolve_doc_path(db, link, ns), | ||
184 | ModuleDef::TypeAlias(it) => it.resolve_doc_path(db, link, ns), | ||
185 | ModuleDef::BuiltinType(_) => return None, | ||
186 | }, | ||
187 | Definition::Macro(it) => it.resolve_doc_path(db, link, ns), | ||
188 | Definition::Field(it) => it.resolve_doc_path(db, link, ns), | ||
189 | Definition::SelfType(_) | Definition::Local(_) | Definition::TypeParam(_) => return None, | ||
190 | }?; | ||
191 | let krate = resolved.module(db)?.krate(); | ||
192 | let canonical_path = resolved.canonical_path(db)?; | ||
193 | let new_target = get_doc_url(db, &krate)? | ||
194 | .join(&format!("{}/", krate.declaration_name(db)?)) | ||
195 | .ok()? | ||
196 | .join(&canonical_path.replace("::", "/")) | ||
197 | .ok()? | ||
198 | .join(&get_symbol_filename(db, &resolved)?) | ||
199 | .ok()? | ||
200 | .into_string(); | ||
201 | let new_title = strip_prefixes_suffixes(title); | ||
202 | Some((new_target, new_title.to_string())) | ||
203 | } | ||
204 | |||
205 | /// Try to resolve path to local documentation via path-based links (i.e. `../gateway/struct.Shard.html`). | ||
206 | fn rewrite_url_link(db: &RootDatabase, def: ModuleDef, target: &str) -> Option<String> { | ||
207 | if !(target.contains('#') || target.contains(".html")) { | ||
208 | return None; | ||
209 | } | ||
210 | |||
211 | let module = def.module(db)?; | ||
212 | let krate = module.krate(); | ||
213 | let canonical_path = def.canonical_path(db)?; | ||
214 | let base = format!("{}/{}", krate.declaration_name(db)?, canonical_path.replace("::", "/")); | ||
215 | |||
216 | get_doc_url(db, &krate) | ||
217 | .and_then(|url| url.join(&base).ok()) | ||
218 | .and_then(|url| { | ||
219 | get_symbol_filename(db, &def).as_deref().map(|f| url.join(f).ok()).flatten() | ||
220 | }) | ||
221 | .and_then(|url| url.join(target).ok()) | ||
222 | .map(|url| url.into_string()) | ||
223 | } | ||
224 | |||
225 | // FIXME: This should either be moved, or the module should be renamed. | ||
226 | /// Retrieve a link to documentation for the given symbol. | ||
227 | pub fn get_doc_url(db: &RootDatabase, position: &FilePosition) -> Option<DocumentationLink> { | ||
228 | let sema = Semantics::new(db); | ||
229 | let file = sema.parse(position.file_id).syntax().clone(); | ||
230 | let token = pick_best(file.token_at_offset(position.offset))?; | ||
231 | let token = sema.descend_into_macros(token); | ||
232 | |||
233 | let node = token.parent(); | ||
234 | let definition = match_ast! { | ||
235 | match node { | ||
236 | ast::NameRef(name_ref) => classify_name_ref(&sema, &name_ref).map(|d| d.definition(sema.db)), | ||
237 | ast::Name(name) => classify_name(&sema, &name).map(|d| d.definition(sema.db)), | ||
238 | _ => None, | ||
239 | } | ||
240 | }; | ||
241 | |||
242 | match definition? { | ||
243 | Definition::Macro(t) => get_doc_link(db, &t), | ||
244 | Definition::Field(t) => get_doc_link(db, &t), | ||
245 | Definition::ModuleDef(t) => get_doc_link(db, &t), | ||
246 | Definition::SelfType(t) => get_doc_link(db, &t), | ||
247 | Definition::Local(t) => get_doc_link(db, &t), | ||
248 | Definition::TypeParam(t) => get_doc_link(db, &t), | ||
249 | } | ||
250 | } | ||
251 | |||
252 | /// Rewrites a markdown document, applying 'callback' to each link. | ||
253 | fn map_links<'e>( | ||
254 | events: impl Iterator<Item = Event<'e>>, | ||
255 | callback: impl Fn(&str, &str) -> (String, String), | ||
256 | ) -> impl Iterator<Item = Event<'e>> { | ||
257 | let mut in_link = false; | ||
258 | let mut link_target: Option<CowStr> = None; | ||
259 | |||
260 | events.map(move |evt| match evt { | ||
261 | Event::Start(Tag::Link(_link_type, ref target, _)) => { | ||
262 | in_link = true; | ||
263 | link_target = Some(target.clone()); | ||
264 | evt | ||
265 | } | ||
266 | Event::End(Tag::Link(link_type, _target, _)) => { | ||
267 | in_link = false; | ||
268 | Event::End(Tag::Link(link_type, link_target.take().unwrap(), CowStr::Borrowed(""))) | ||
269 | } | ||
270 | Event::Text(s) if in_link => { | ||
271 | let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s); | ||
272 | link_target = Some(CowStr::Boxed(link_target_s.into())); | ||
273 | Event::Text(CowStr::Boxed(link_name.into())) | ||
274 | } | ||
275 | Event::Code(s) if in_link => { | ||
276 | let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s); | ||
277 | link_target = Some(CowStr::Boxed(link_target_s.into())); | ||
278 | Event::Code(CowStr::Boxed(link_name.into())) | ||
279 | } | ||
280 | _ => evt, | ||
281 | }) | ||
282 | } | ||
283 | |||
284 | fn parse_link(s: &str) -> (&str, Option<hir::Namespace>) { | ||
285 | let path = strip_prefixes_suffixes(s); | ||
286 | let ns = ns_from_intra_spec(s); | ||
287 | (path, ns) | ||
288 | } | ||
289 | |||
290 | /// Strip prefixes, suffixes, and inline code marks from the given string. | ||
291 | fn strip_prefixes_suffixes(mut s: &str) -> &str { | ||
292 | s = s.trim_matches('`'); | ||
293 | |||
294 | [ | ||
295 | (TYPES.0.iter(), TYPES.1.iter()), | ||
296 | (VALUES.0.iter(), VALUES.1.iter()), | ||
297 | (MACROS.0.iter(), MACROS.1.iter()), | ||
298 | ] | ||
299 | .iter() | ||
300 | .for_each(|(prefixes, suffixes)| { | ||
301 | prefixes.clone().for_each(|prefix| s = s.trim_start_matches(*prefix)); | ||
302 | suffixes.clone().for_each(|suffix| s = s.trim_end_matches(*suffix)); | ||
303 | }); | ||
304 | s.trim_start_matches('@').trim() | ||
305 | } | ||
306 | |||
307 | static TYPES: ([&str; 7], [&str; 0]) = | ||
308 | (["type", "struct", "enum", "mod", "trait", "union", "module"], []); | ||
309 | static VALUES: ([&str; 8], [&str; 1]) = | ||
310 | (["value", "function", "fn", "method", "const", "static", "mod", "module"], ["()"]); | ||
311 | static MACROS: ([&str; 1], [&str; 1]) = (["macro"], ["!"]); | ||
312 | |||
313 | /// Extract the specified namespace from an intra-doc-link if one exists. | ||
314 | /// | ||
315 | /// # Examples | ||
316 | /// | ||
317 | /// * `struct MyStruct` -> `Namespace::Types` | ||
318 | /// * `panic!` -> `Namespace::Macros` | ||
319 | /// * `fn@from_intra_spec` -> `Namespace::Values` | ||
320 | fn ns_from_intra_spec(s: &str) -> Option<hir::Namespace> { | ||
321 | [ | ||
322 | (hir::Namespace::Types, (TYPES.0.iter(), TYPES.1.iter())), | ||
323 | (hir::Namespace::Values, (VALUES.0.iter(), VALUES.1.iter())), | ||
324 | (hir::Namespace::Macros, (MACROS.0.iter(), MACROS.1.iter())), | ||
325 | ] | ||
326 | .iter() | ||
327 | .filter(|(_ns, (prefixes, suffixes))| { | ||
328 | prefixes | ||
329 | .clone() | ||
330 | .map(|prefix| { | ||
331 | s.starts_with(*prefix) | ||
332 | && s.chars() | ||
333 | .nth(prefix.len() + 1) | ||
334 | .map(|c| c == '@' || c == ' ') | ||
335 | .unwrap_or(false) | ||
336 | }) | ||
337 | .any(|cond| cond) | ||
338 | || suffixes | ||
339 | .clone() | ||
340 | .map(|suffix| { | ||
341 | s.starts_with(*suffix) | ||
342 | && s.chars() | ||
343 | .nth(suffix.len() + 1) | ||
344 | .map(|c| c == '@' || c == ' ') | ||
345 | .unwrap_or(false) | ||
346 | }) | ||
347 | .any(|cond| cond) | ||
348 | }) | ||
349 | .map(|(ns, (_, _))| *ns) | ||
350 | .next() | ||
351 | } | ||
352 | |||
353 | /// Get the root URL for the documentation of a crate. | ||
354 | /// | ||
355 | /// ``` | ||
356 | /// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next | ||
357 | /// ^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
358 | /// ``` | ||
359 | fn get_doc_url(db: &RootDatabase, krate: &Crate) -> Option<Url> { | ||
360 | krate | ||
361 | .get_html_root_url(db) | ||
362 | .or_else(|| { | ||
363 | // Fallback to docs.rs. This uses `display_name` and can never be | ||
364 | // correct, but that's what fallbacks are about. | ||
365 | // | ||
366 | // FIXME: clicking on the link should just open the file in the editor, | ||
367 | // instead of falling back to external urls. | ||
368 | Some(format!("https://docs.rs/{}/*/", krate.declaration_name(db)?)) | ||
369 | }) | ||
370 | .and_then(|s| Url::parse(&s).ok()) | ||
371 | } | ||
372 | |||
373 | /// Get the filename and extension generated for a symbol by rustdoc. | ||
374 | /// | ||
375 | /// ``` | ||
376 | /// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next | ||
377 | /// ^^^^^^^^^^^^^^^^^^^ | ||
378 | /// ``` | ||
379 | fn get_symbol_filename(db: &dyn HirDatabase, definition: &ModuleDef) -> Option<String> { | ||
380 | Some(match definition { | ||
381 | ModuleDef::Adt(adt) => match adt { | ||
382 | Adt::Struct(s) => format!("struct.{}.html", s.name(db)), | ||
383 | Adt::Enum(e) => format!("enum.{}.html", e.name(db)), | ||
384 | Adt::Union(u) => format!("union.{}.html", u.name(db)), | ||
385 | }, | ||
386 | ModuleDef::Module(_) => "index.html".to_string(), | ||
387 | ModuleDef::Trait(t) => format!("trait.{}.html", t.name(db)), | ||
388 | ModuleDef::TypeAlias(t) => format!("type.{}.html", t.name(db)), | ||
389 | ModuleDef::BuiltinType(t) => format!("primitive.{}.html", t.as_name()), | ||
390 | ModuleDef::Function(f) => format!("fn.{}.html", f.name(db)), | ||
391 | ModuleDef::EnumVariant(ev) => { | ||
392 | format!("enum.{}.html#variant.{}", ev.parent_enum(db).name(db), ev.name(db)) | ||
393 | } | ||
394 | ModuleDef::Const(c) => format!("const.{}.html", c.name(db)?), | ||
395 | ModuleDef::Static(s) => format!("static.{}.html", s.name(db)?), | ||
396 | }) | ||
397 | } | ||
398 | |||
399 | enum FieldOrAssocItem { | ||
400 | Field(Field), | ||
401 | AssocItem(AssocItem), | ||
402 | } | ||
403 | |||
404 | /// Get the fragment required to link to a specific field, method, associated type, or associated constant. | ||
405 | /// | ||
406 | /// ``` | ||
407 | /// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next | ||
408 | /// ^^^^^^^^^^^^^^ | ||
409 | /// ``` | ||
410 | fn get_symbol_fragment(db: &dyn HirDatabase, field_or_assoc: &FieldOrAssocItem) -> Option<String> { | ||
411 | Some(match field_or_assoc { | ||
412 | FieldOrAssocItem::Field(field) => format!("#structfield.{}", field.name(db)), | ||
413 | FieldOrAssocItem::AssocItem(assoc) => match assoc { | ||
414 | // TODO: Rustdoc sometimes uses tymethod instead of method. This case needs to be investigated. | ||
415 | AssocItem::Function(function) => format!("#method.{}", function.name(db)), | ||
416 | // TODO: This might be the old method for documenting associated constants, i32::MAX uses a separate page... | ||
417 | AssocItem::Const(constant) => format!("#associatedconstant.{}", constant.name(db)?), | ||
418 | AssocItem::TypeAlias(ty) => format!("#associatedtype.{}", ty.name(db)), | ||
419 | }, | ||
420 | }) | ||
421 | } | ||
422 | |||
423 | fn pick_best(tokens: TokenAtOffset<SyntaxToken>) -> Option<SyntaxToken> { | ||
424 | return tokens.max_by_key(priority); | ||
425 | fn priority(n: &SyntaxToken) -> usize { | ||
426 | match n.kind() { | ||
427 | IDENT | INT_NUMBER => 3, | ||
428 | T!['('] | T![')'] => 2, | ||
429 | kind if kind.is_trivia() => 0, | ||
430 | _ => 1, | ||
431 | } | ||
432 | } | ||
433 | } | ||