aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_ide')
-rw-r--r--crates/ra_ide/Cargo.toml6
-rw-r--r--crates/ra_ide/src/link_rewrite.rs241
2 files changed, 11 insertions, 236 deletions
diff --git a/crates/ra_ide/Cargo.toml b/crates/ra_ide/Cargo.toml
index 485aa9081..de606f57e 100644
--- a/crates/ra_ide/Cargo.toml
+++ b/crates/ra_ide/Cargo.toml
@@ -17,10 +17,9 @@ indexmap = "1.3.2"
17itertools = "0.9.0" 17itertools = "0.9.0"
18log = "0.4.8" 18log = "0.4.8"
19rustc-hash = "1.1.0" 19rustc-hash = "1.1.0"
20url = "2.1.1" 20oorandom = "11.1.2"
21pulldown-cmark-to-cmark = "5.0.0" 21pulldown-cmark-to-cmark = "5.0.0"
22pulldown-cmark = {version = "0.7.2", default-features = false} 22pulldown-cmark = {version = "0.7.2", default-features = false}
23oorandom = "11.1.2"
24 23
25stdx = { path = "../stdx" } 24stdx = { path = "../stdx" }
26 25
@@ -34,9 +33,6 @@ ra_prof = { path = "../ra_prof" }
34test_utils = { path = "../test_utils" } 33test_utils = { path = "../test_utils" }
35ra_assists = { path = "../ra_assists" } 34ra_assists = { path = "../ra_assists" }
36ra_ssr = { path = "../ra_ssr" } 35ra_ssr = { path = "../ra_ssr" }
37ra_hir_def = { path = "../ra_hir_def" }
38ra_tt = { path = "../ra_tt" }
39ra_parser = { path = "../ra_parser" }
40 36
41# ra_ide should depend only on the top-level `hir` package. if you need 37# ra_ide should depend only on the top-level `hir` package. if you need
42# something from some `hir_xxx` subpackage, reexport the API via `hir`. 38# something from some `hir_xxx` subpackage, reexport the API via `hir`.
diff --git a/crates/ra_ide/src/link_rewrite.rs b/crates/ra_ide/src/link_rewrite.rs
index 37d695bb8..94d2c31c2 100644
--- a/crates/ra_ide/src/link_rewrite.rs
+++ b/crates/ra_ide/src/link_rewrite.rs
@@ -1,17 +1,10 @@
1//! Resolves and rewrites links in markdown documentation for hovers/completion windows. 1//! This is a wrapper around [`hir::link_rewrite`] connecting it to the markdown parser.
2 2
3use std::iter::once;
4
5use itertools::Itertools;
6use pulldown_cmark::{CowStr, Event, Options, Parser, Tag}; 3use pulldown_cmark::{CowStr, Event, Options, Parser, Tag};
7use pulldown_cmark_to_cmark::{cmark_with_options, Options as CmarkOptions}; 4use pulldown_cmark_to_cmark::{cmark_with_options, Options as CmarkOptions};
8use url::Url;
9 5
10use hir::{Adt, AsName, AttrDef, Crate, Hygiene, ItemInNs, ModPath, ModuleDef}; 6use hir::resolve_doc_link;
11use ra_hir_def::db::DefDatabase;
12use ra_ide_db::{defs::Definition, RootDatabase}; 7use ra_ide_db::{defs::Definition, RootDatabase};
13use ra_syntax::ast::Path;
14use ra_tt::{Ident, Leaf, Literal, TokenTree};
15 8
16/// Rewrite documentation links in markdown to point to an online host (e.g. docs.rs) 9/// 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 { 10pub fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition) -> String {
@@ -31,9 +24,14 @@ pub fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition)
31 // Two posibilities: 24 // Two posibilities:
32 // * path-based links: `../../module/struct.MyStruct.html` 25 // * path-based links: `../../module/struct.MyStruct.html`
33 // * module-based links (AKA intra-doc links): `super::super::module::MyStruct` 26 // * module-based links (AKA intra-doc links): `super::super::module::MyStruct`
34 let resolved = try_resolve_intra(db, definition, title, &target).or_else(|| { 27 let resolved = match definition {
35 try_resolve_path(db, definition, &target).map(|target| (target, title.to_string())) 28 Definition::ModuleDef(t) => resolve_doc_link(db, t, title, target),
36 }); 29 Definition::Macro(t) => resolve_doc_link(db, t, title, target),
30 Definition::Field(t) => resolve_doc_link(db, t, title, target),
31 Definition::SelfType(t) => resolve_doc_link(db, t, title, target),
32 Definition::Local(t) => resolve_doc_link(db, t, title, target),
33 Definition::TypeParam(t) => resolve_doc_link(db, t, title, target),
34 };
37 35
38 match resolved { 36 match resolved {
39 Some((target, title)) => (target, title), 37 Some((target, title)) => (target, title),
@@ -79,222 +77,3 @@ fn map_links<'e>(
79 _ => evt, 77 _ => evt,
80 }) 78 })
81} 79}
82
83#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
84enum Namespace {
85 Types,
86 Values,
87 Macros,
88}
89
90static TYPES: ([&str; 7], [&str; 0]) =
91 (["type", "struct", "enum", "mod", "trait", "union", "module"], []);
92static VALUES: ([&str; 8], [&str; 1]) =
93 (["value", "function", "fn", "method", "const", "static", "mod", "module"], ["()"]);
94static MACROS: ([&str; 1], [&str; 1]) = (["macro"], ["!"]);
95
96impl Namespace {
97 /// Extract the specified namespace from an intra-doc-link if one exists.
98 ///
99 /// # Examples
100 ///
101 /// * `struct MyStruct` -> `Namespace::Types`
102 /// * `panic!` -> `Namespace::Macros`
103 /// * `fn@from_intra_spec` -> `Namespace::Values`
104 fn from_intra_spec(s: &str) -> Option<Self> {
105 [
106 (Namespace::Types, (TYPES.0.iter(), TYPES.1.iter())),
107 (Namespace::Values, (VALUES.0.iter(), VALUES.1.iter())),
108 (Namespace::Macros, (MACROS.0.iter(), MACROS.1.iter())),
109 ]
110 .iter()
111 .filter(|(_ns, (prefixes, suffixes))| {
112 prefixes
113 .clone()
114 .map(|prefix| {
115 s.starts_with(*prefix)
116 && s.chars()
117 .nth(prefix.len() + 1)
118 .map(|c| c == '@' || c == ' ')
119 .unwrap_or(false)
120 })
121 .any(|cond| cond)
122 || suffixes
123 .clone()
124 .map(|suffix| {
125 s.starts_with(*suffix)
126 && s.chars()
127 .nth(suffix.len() + 1)
128 .map(|c| c == '@' || c == ' ')
129 .unwrap_or(false)
130 })
131 .any(|cond| cond)
132 })
133 .map(|(ns, (_, _))| *ns)
134 .next()
135 }
136}
137
138// Strip prefixes, suffixes, and inline code marks from the given string.
139fn strip_prefixes_suffixes(mut s: &str) -> &str {
140 s = s.trim_matches('`');
141
142 [
143 (TYPES.0.iter(), TYPES.1.iter()),
144 (VALUES.0.iter(), VALUES.1.iter()),
145 (MACROS.0.iter(), MACROS.1.iter()),
146 ]
147 .iter()
148 .for_each(|(prefixes, suffixes)| {
149 prefixes.clone().for_each(|prefix| s = s.trim_start_matches(*prefix));
150 suffixes.clone().for_each(|suffix| s = s.trim_end_matches(*suffix));
151 });
152 s.trim_start_matches("@").trim()
153}
154
155/// Try to resolve path to local documentation via intra-doc-links (i.e. `super::gateway::Shard`).
156///
157/// See [RFC1946](https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md).
158fn try_resolve_intra(
159 db: &RootDatabase,
160 definition: &Definition,
161 link_text: &str,
162 link_target: &str,
163) -> Option<(String, String)> {
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 if !link.contains("#") && !link.contains(".html") {
223 return None;
224 }
225 let ns = if let Definition::ModuleDef(moddef) = definition {
226 ItemInNs::Types(moddef.clone().into())
227 } else {
228 return None;
229 };
230 let module = definition.module(db)?;
231 let krate = module.krate();
232 let import_map = db.import_map(krate.into());
233 let base = once(format!("{}", krate.display_name(db)?))
234 .chain(import_map.path_of(ns)?.segments.iter().map(|name| format!("{}", name)))
235 .join("/");
236
237 get_doc_url(db, &krate)
238 .and_then(|url| url.join(&base).ok())
239 .and_then(|url| {
240 get_symbol_filename(db, definition).as_deref().map(|f| url.join(f).ok()).flatten()
241 })
242 .and_then(|url| url.join(link).ok())
243 .map(|url| url.into_string())
244}
245
246/// Try to get the root URL of the documentation of a crate.
247fn get_doc_url(db: &RootDatabase, krate: &Crate) -> Option<Url> {
248 // Look for #![doc(html_root_url = "...")]
249 let attrs = db.attrs(AttrDef::from(krate.root_module(db)?).into());
250 let doc_attr_q = attrs.by_key("doc");
251
252 let doc_url = if doc_attr_q.exists() {
253 doc_attr_q.tt_values().map(|tt| {
254 let name = tt.token_trees.iter()
255 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
256 .skip(2)
257 .next();
258
259 match name {
260 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
261 _ => None
262 }
263 }).flat_map(|t| t).next().map(|s| s.to_string())
264 } else {
265 // Fallback to docs.rs
266 // FIXME: Specify an exact version here (from Cargo.lock)
267 Some(format!("https://docs.rs/{}/*", krate.display_name(db)?))
268 };
269
270 doc_url
271 .map(|s| s.trim_matches('"').trim_end_matches("/").to_owned() + "/")
272 .and_then(|s| Url::parse(&s).ok())
273}
274
275/// Get the filename and extension generated for a symbol by rustdoc.
276///
277/// Example: `struct.Shard.html`
278fn get_symbol_filename(db: &RootDatabase, definition: &Definition) -> Option<String> {
279 Some(match definition {
280 Definition::ModuleDef(def) => match def {
281 ModuleDef::Adt(adt) => match adt {
282 Adt::Struct(s) => format!("struct.{}.html", s.name(db)),
283 Adt::Enum(e) => format!("enum.{}.html", e.name(db)),
284 Adt::Union(u) => format!("union.{}.html", u.name(db)),
285 },
286 ModuleDef::Module(_) => "index.html".to_string(),
287 ModuleDef::Trait(t) => format!("trait.{}.html", t.name(db)),
288 ModuleDef::TypeAlias(t) => format!("type.{}.html", t.name(db)),
289 ModuleDef::BuiltinType(t) => format!("primitive.{}.html", t.as_name()),
290 ModuleDef::Function(f) => format!("fn.{}.html", f.name(db)),
291 ModuleDef::EnumVariant(ev) => {
292 format!("enum.{}.html#variant.{}", ev.parent_enum(db).name(db), ev.name(db))
293 }
294 ModuleDef::Const(c) => format!("const.{}.html", c.name(db)?),
295 ModuleDef::Static(s) => format!("static.{}.html", s.name(db)?),
296 },
297 Definition::Macro(m) => format!("macro.{}.html", m.name(db)?),
298 _ => None?,
299 })
300}