Skip to content

Commit 108b953

Browse files
committed
Remove local documentation link rewriting
1 parent 5f52a51 commit 108b953

File tree

5 files changed

+22
-105
lines changed

5 files changed

+22
-105
lines changed

crates/ra_ide/src/hover.rs

Lines changed: 19 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
use std::iter::once;
2-
use std::path::PathBuf;
3-
use std::sync::Arc;
42

53
use hir::{
64
Adt, AsAssocItem, AssocItemContainer, FieldSource, HasSource, HirDisplay, ModuleDef,
7-
ModuleSource, Semantics, Documentation, AttrDef, Crate, GenericDef, ModPath, Hygiene
5+
ModuleSource, Semantics, Documentation, AttrDef, Crate, ModPath, Hygiene
86
};
97
use itertools::Itertools;
108
use ra_db::SourceDatabase;
@@ -13,11 +11,9 @@ use ra_ide_db::{
1311
RootDatabase,
1412
};
1513
use ra_syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, SyntaxNode, TokenAtOffset, ast::Path};
16-
use ra_project_model::ProjectWorkspace;
17-
use ra_hir_def::{item_scope::ItemInNs, db::DefDatabase, GenericDefId, ModuleId, resolver::HasResolver};
14+
use ra_hir_def::{item_scope::ItemInNs, db::DefDatabase, resolver::HasResolver};
1815
use ra_tt::{Literal, Ident, Punct, TokenTree, Leaf};
1916
use ra_hir_expand::name::AsName;
20-
use ra_parser::FragmentKind;
2117
use maplit::{hashset, hashmap};
2218

2319
use comrak::{parse_document,format_commonmark, ComrakOptions, Arena};
@@ -130,7 +126,7 @@ impl HoverResult {
130126
//
131127
// Shows additional information, like type of an expression or documentation for definition when "focusing" code.
132128
// Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
133-
pub(crate) fn hover(db: &RootDatabase, position: FilePosition, workspaces: Arc<Vec<ProjectWorkspace>>) -> Option<RangeInfo<HoverResult>> {
129+
pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeInfo<HoverResult>> {
134130
let sema = Semantics::new(db);
135131
let file = sema.parse(position.file_id).syntax().clone();
136132
let token = pick_best(file.token_at_offset(position.offset))?;
@@ -150,7 +146,7 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition, workspaces: Arc<V
150146
}
151147
} {
152148
let range = sema.original_range(&node).range;
153-
let text = hover_text_from_name_kind(db, name_kind.clone()).map(|text| rewrite_links(db, &text, &name_kind, workspaces).unwrap_or(text));
149+
let text = hover_text_from_name_kind(db, name_kind.clone()).map(|text| rewrite_links(db, &text, &name_kind).unwrap_or(text));
154150
res.extend(text);
155151

156152
if !res.is_empty() {
@@ -393,15 +389,9 @@ fn hover_text_from_name_kind(db: &RootDatabase, def: Definition) -> Option<Strin
393389
}
394390

395391
/// Rewrite documentation links in markdown to point to local documentation/docs.rs
396-
fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition, workspaces: Arc<Vec<ProjectWorkspace>>) -> Option<String> {
392+
fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition) -> Option<String> {
397393
let arena = Arena::new();
398394
let doc = parse_document(&arena, markdown, &ComrakOptions::default());
399-
let doc_target_dirs = workspaces
400-
.iter()
401-
.filter_map(|workspace| if let ProjectWorkspace::Cargo{cargo: cargo_workspace, ..} = workspace {Some(cargo_workspace)} else {None})
402-
.map(|workspace| workspace.workspace_root())
403-
// TODO: `target` is configurable in cargo config, we should respect it
404-
.map(|root| root.join("target/doc"));
405395

406396
iter_nodes(doc, &|node| {
407397
match &mut node.data.borrow_mut().value {
@@ -415,8 +405,8 @@ fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition, wor
415405
Err(_) => {
416406
let link_str = String::from_utf8(link.url.clone()).unwrap();
417407
let link_text = String::from_utf8(link.title.clone()).unwrap();
418-
let resolved = try_resolve_path(db, &mut doc_target_dirs.clone(), definition, &link_str, UrlMode::Url)
419-
.or_else(|| try_resolve_intra(db, &mut doc_target_dirs.clone(), definition, &link_text, &link_str));
408+
let resolved = try_resolve_path(db, definition, &link_str)
409+
.or_else(|| try_resolve_intra(db, definition, &link_text, &link_str));
420410

421411
if let Some(resolved) = resolved {
422412
link.url = resolved.as_bytes().to_vec();
@@ -451,7 +441,7 @@ impl Namespace {
451441

452442
ns_map
453443
.iter()
454-
.filter(|(ns, (prefixes, suffixes))| {
444+
.filter(|(_ns, (prefixes, suffixes))| {
455445
prefixes.iter().map(|prefix| s.starts_with(prefix) && s.chars().nth(prefix.len()+1).map(|c| c == '@' || c == ' ').unwrap_or(false)).any(|cond| cond) ||
456446
suffixes.iter().map(|suffix| s.starts_with(suffix) && s.chars().nth(suffix.len()+1).map(|c| c == '@' || c == ' ').unwrap_or(false)).any(|cond| cond)
457447
})
@@ -463,7 +453,7 @@ impl Namespace {
463453
/// Try to resolve path to local documentation via intra-doc-links (i.e. `super::gateway::Shard`).
464454
///
465455
/// See [RFC1946](https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md).
466-
fn try_resolve_intra(db: &RootDatabase, doc_target_dirs: impl Iterator<Item = PathBuf>, definition: &Definition, link_text: &str, link_target: &str) -> Option<String> {
456+
fn try_resolve_intra(db: &RootDatabase, definition: &Definition, link_text: &str, link_target: &str) -> Option<String> {
467457
eprintln!("try_resolve_intra");
468458

469459
// Set link_target for implied shortlinks
@@ -496,13 +486,13 @@ fn try_resolve_intra(db: &RootDatabase, doc_target_dirs: impl Iterator<Item = Pa
496486
ModuleDef::Trait(t) => Into::<TraitId>::into(t.clone()).resolver(db),
497487
ModuleDef::TypeAlias(t) => Into::<ModuleId>::into(t.module(db)).resolver(db),
498488
// TODO: This should be a resolver relative to `std`
499-
ModuleDef::BuiltinType(t) => Into::<ModuleId>::into(definition.module(db)?).resolver(db)
489+
ModuleDef::BuiltinType(_t) => Into::<ModuleId>::into(definition.module(db)?).resolver(db)
500490
},
501491
Definition::Field(field) => Into::<VariantId>::into(Into::<VariantDef>::into(field.parent_def(db))).resolver(db),
502492
Definition::Macro(m) => Into::<ModuleId>::into(m.module(db)?).resolver(db),
503493
Definition::SelfType(imp) => Into::<ImplId>::into(imp.clone()).resolver(db),
504494
// it's possible, read probable, that other arms of this are also unreachable
505-
Definition::Local(local) => unreachable!(),
495+
Definition::Local(_local) => unreachable!(),
506496
Definition::TypeParam(tp) => Into::<ModuleId>::into(tp.module(db)).resolver(db)
507497
}
508498
};
@@ -542,13 +532,8 @@ fn try_resolve_intra(db: &RootDatabase, doc_target_dirs: impl Iterator<Item = Pa
542532
)
543533
}
544534

545-
enum UrlMode {
546-
Url,
547-
File
548-
}
549-
550535
/// Try to resolve path to local documentation via path-based links (i.e. `../gateway/struct.Shard.html`).
551-
fn try_resolve_path(db: &RootDatabase, doc_target_dirs: impl Iterator<Item = PathBuf>, definition: &Definition, link: &str, mode: UrlMode) -> Option<String> {
536+
fn try_resolve_path(db: &RootDatabase, definition: &Definition, link: &str) -> Option<String> {
552537
eprintln!("try_resolve_path");
553538
let ns = if let Definition::ModuleDef(moddef) = definition {
554539
ItemInNs::Types(moddef.clone().into())
@@ -561,29 +546,13 @@ fn try_resolve_path(db: &RootDatabase, doc_target_dirs: impl Iterator<Item = Pat
561546
// TODO: It should be possible to fall back to not-necessarilly-public paths if we can't find a public one,
562547
// then hope rustdoc was run locally with `--document-private-items`
563548
let base = import_map.path_of(ns)?;
564-
let mut base = once(format!("{}", krate.display_name(db)?)).chain(base.segments.iter().map(|name| format!("{}", name)));
565-
566-
match mode {
567-
UrlMode::Url => {
568-
let mut base = base.join("/");
569-
get_doc_url(db, &krate)
570-
.and_then(|url| url.join(&base).ok())
571-
.and_then(|url| get_symbol_filename(db, definition).as_deref().map(|f| url.join(f).ok()).flatten())
572-
.and_then(|url| url.join(link).ok())
573-
.map(|url| url.into_string())
574-
},
575-
UrlMode::File => {
576-
let base = base.collect::<PathBuf>();
577-
doc_target_dirs
578-
.map(|dir| dir.join(format!("{}", krate.display_name(db).unwrap())).join(base.join("..").join(link)))
579-
.inspect(|path| eprintln!("candidate {}", path.display()))
580-
.filter(|path| path.exists())
581-
.map(|path| format!("file:///{}", path.display()))
582-
// \. is treated as an escape in vscode's markdown hover rendering
583-
.map(|path_str| path_str.replace("\\", "/"))
584-
.next()
585-
}
586-
}
549+
let base = once(format!("{}", krate.display_name(db)?)).chain(base.segments.iter().map(|name| format!("{}", name))).join("/");
550+
551+
get_doc_url(db, &krate)
552+
.and_then(|url| url.join(&base).ok())
553+
.and_then(|url| get_symbol_filename(db, definition).as_deref().map(|f| url.join(f).ok()).flatten())
554+
.and_then(|url| url.join(link).ok())
555+
.map(|url| url.into_string())
587556
}
588557

589558
/// Try to get the root URL of the documentation of a crate.

crates/ra_ide/src/lib.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ use ra_ide_db::{
5454
LineIndexDatabase,
5555
};
5656
use ra_syntax::{SourceFile, TextRange, TextSize};
57-
use ra_project_model::ProjectWorkspace;
5857

5958
use crate::display::ToNav;
6059

@@ -390,8 +389,8 @@ impl Analysis {
390389
}
391390

392391
/// Returns a short text describing element at position.
393-
pub fn hover(&self, position: FilePosition, workspaces: Arc<Vec<ProjectWorkspace>>) -> Cancelable<Option<RangeInfo<HoverResult>>> {
394-
self.with_db(|db| hover::hover(db, position, workspaces))
392+
pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<HoverResult>>> {
393+
self.with_db(|db| hover::hover(db, position))
395394
}
396395

397396
/// Computes parameter information for the given call expression.

crates/ra_syntax/src/ast/test.txt

Lines changed: 0 additions & 15 deletions
This file was deleted.

crates/ra_syntax/src/ast/traits.rs

Lines changed: 0 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -146,39 +146,3 @@ impl Iterator for CommentIter {
146146
self.iter.by_ref().find_map(|el| el.into_token().and_then(ast::Comment::cast))
147147
}
148148
}
149-
150-
#[cfg(test)]
151-
mod tests {
152-
use comrak::{parse_document,format_commonmark, ComrakOptions, Arena};
153-
use comrak::nodes::{AstNode, NodeValue};
154-
155-
fn iter_nodes<'a, F>(node: &'a AstNode<'a>, f: &F)
156-
where F : Fn(&'a AstNode<'a>) {
157-
f(node);
158-
for c in node.children() {
159-
iter_nodes(c, f);
160-
}
161-
}
162-
163-
#[allow(non_snake_case)]
164-
#[test]
165-
fn test_link_rewrite() {
166-
let src = include_str!("./test.txt");
167-
168-
let arena = Arena::new();
169-
let doc = parse_document(&arena, src, &ComrakOptions::default());
170-
171-
iter_nodes(doc, &|node| {
172-
match &mut node.data.borrow_mut().value {
173-
&mut NodeValue::Link(ref mut link) => {
174-
link.url = "https://www.google.com".as_bytes().to_vec();
175-
},
176-
_ => ()
177-
}
178-
});
179-
180-
let mut out = Vec::new();
181-
format_commonmark(doc, &ComrakOptions::default(), &mut out);
182-
panic!("{}", String::from_utf8(out).unwrap());
183-
}
184-
}

crates/rust-analyzer/src/handlers.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,7 @@ pub(crate) fn handle_hover(
548548
) -> Result<Option<lsp_ext::Hover>> {
549549
let _p = profile("handle_hover");
550550
let position = from_proto::file_position(&snap, params.text_document_position_params)?;
551-
let info = match snap.analysis.hover(position)? {
551+
let info = match snap.analysis().hover(position)? {
552552
None => return Ok(None),
553553
Some(info) => info,
554554
};

0 commit comments

Comments
 (0)