From bfda0d25834250a3adbcd0d26953a1cdc6662e7f Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Sun, 30 Aug 2020 20:02:29 +1200 Subject: WIP: Command to open docs under cursor --- crates/ide/src/lib.rs | 8 +++++ crates/ide/src/link_rewrite.rs | 82 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 89 insertions(+), 1 deletion(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index 57f3581b6..645369597 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs @@ -382,6 +382,14 @@ impl Analysis { self.with_db(|db| hover::hover(db, position, links_in_hover, markdown)) } + /// Return URL(s) for the documentation of the symbol under the cursor. + pub fn get_doc_url( + &self, + position: FilePosition, + ) -> Cancelable> { + self.with_db(|db| link_rewrite::get_doc_url(db, &position)) + } + /// Computes parameter information for the given call expression. pub fn call_info(&self, position: FilePosition) -> Cancelable> { self.with_db(|db| call_info::call_info(db, position)) diff --git a/crates/ide/src/link_rewrite.rs b/crates/ide/src/link_rewrite.rs index c317a2379..80005c06e 100644 --- a/crates/ide/src/link_rewrite.rs +++ b/crates/ide/src/link_rewrite.rs @@ -8,6 +8,16 @@ use pulldown_cmark::{CowStr, Event, LinkType, Options, Parser, Tag}; use pulldown_cmark_to_cmark::{cmark_with_options, Options as CmarkOptions}; use url::Url; +use crate::{FilePosition, Semantics}; +use hir::{get_doc_link, resolve_doc_link}; +use ide_db::{ + defs::{classify_name, classify_name_ref, Definition}, + RootDatabase, +}; +use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset, T}; + +pub type DocumentationLink = String; + /// Rewrite documentation links in markdown to point to an online host (e.g. docs.rs) pub fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition) -> String { let doc = Parser::new_with_broken_link_callback( @@ -80,6 +90,37 @@ pub fn remove_links(markdown: &str) -> String { out } +pub fn get_doc_link(db: &dyn HirDatabase, definition: &T) -> Option { + eprintln!("hir::doc_links::get_doc_link"); + let module_def = definition.clone().try_into_module_def()?; + + get_doc_link_impl(db, &module_def) +} + +// TODO: +// BUG: For Option +// Returns https://doc.rust-lang.org/nightly/core/prelude/v1/enum.Option.html#variant.Some +// Instead of https://doc.rust-lang.org/nightly/core/option/enum.Option.html +// +// BUG: For methods +// import_map.path_of(ns) fails, is not designed to resolve methods +fn get_doc_link_impl(db: &dyn HirDatabase, moddef: &ModuleDef) -> Option { + eprintln!("get_doc_link_impl: {:#?}", moddef); + let ns = ItemInNs::Types(moddef.clone().into()); + + let module = moddef.module(db)?; + let krate = module.krate(); + let import_map = db.import_map(krate.into()); + let base = once(krate.display_name(db).unwrap()) + .chain(import_map.path_of(ns).unwrap().segments.iter().map(|name| format!("{}", name))) + .join("/"); + + get_doc_url(db, &krate) + .and_then(|url| url.join(&base).ok()) + .and_then(|url| get_symbol_filename(db, &moddef).as_deref().and_then(|f| url.join(f).ok())) + .map(|url| url.into_string()) +} + fn rewrite_intra_doc_link( db: &RootDatabase, def: Definition, @@ -138,7 +179,34 @@ fn rewrite_url_link(db: &RootDatabase, def: ModuleDef, target: &str) -> Option Option { + let sema = Semantics::new(db); + let file = sema.parse(position.file_id).syntax().clone(); + let token = pick_best(file.token_at_offset(position.offset))?; + let token = sema.descend_into_macros(token); + + let node = token.parent(); + let definition = match_ast! { + match node { + ast::NameRef(name_ref) => classify_name_ref(&sema, &name_ref).map(|d| d.definition(sema.db)), + ast::Name(name) => classify_name(&sema, &name).map(|d| d.definition(sema.db)), + _ => None, + } + }; + + match definition? { + Definition::Macro(t) => get_doc_link(db, &t), + Definition::Field(t) => get_doc_link(db, &t), + Definition::ModuleDef(t) => get_doc_link(db, &t), + Definition::SelfType(t) => get_doc_link(db, &t), + Definition::Local(t) => get_doc_link(db, &t), + Definition::TypeParam(t) => get_doc_link(db, &t), + } +} + +/// Rewrites a markdown document, applying 'callback' to each link. fn map_links<'e>( events: impl Iterator>, callback: impl Fn(&str, &str) -> (String, String), @@ -275,3 +343,15 @@ fn get_symbol_filename(db: &RootDatabase, definition: &ModuleDef) -> Option format!("static.{}.html", s.name(db)?), }) } + +fn pick_best(tokens: TokenAtOffset) -> Option { + return tokens.max_by_key(priority); + fn priority(n: &SyntaxToken) -> usize { + match n.kind() { + IDENT | INT_NUMBER => 3, + T!['('] | T![')'] => 2, + kind if kind.is_trivia() => 0, + _ => 1, + } + } +} -- cgit v1.2.3 From a06d736b77770e4c1e738086c81b4fd60fcfcb23 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Mon, 31 Aug 2020 20:26:55 +1200 Subject: Add support for struct & trait methods --- crates/ide/src/link_rewrite.rs | 90 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 83 insertions(+), 7 deletions(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/link_rewrite.rs b/crates/ide/src/link_rewrite.rs index 80005c06e..1e102997f 100644 --- a/crates/ide/src/link_rewrite.rs +++ b/crates/ide/src/link_rewrite.rs @@ -91,7 +91,6 @@ pub fn remove_links(markdown: &str) -> String { } pub fn get_doc_link(db: &dyn HirDatabase, definition: &T) -> Option { - eprintln!("hir::doc_links::get_doc_link"); let module_def = definition.clone().try_into_module_def()?; get_doc_link_impl(db, &module_def) @@ -105,8 +104,31 @@ pub fn get_doc_link(db: &dyn HirDatabase, definition: &T) // BUG: For methods // import_map.path_of(ns) fails, is not designed to resolve methods fn get_doc_link_impl(db: &dyn HirDatabase, moddef: &ModuleDef) -> Option { - eprintln!("get_doc_link_impl: {:#?}", moddef); - let ns = ItemInNs::Types(moddef.clone().into()); + // Get the outermost definition for the moduledef. This is used to resolve the public path to the type, + // then we can join the method, field, etc onto it if required. + let target_def: ModuleDef = match moddef { + ModuleDef::Function(f) => match f.as_assoc_item(db).map(|assoc| assoc.container(db)) { + Some(AssocItemContainer::Trait(t)) => t.into(), + Some(AssocItemContainer::ImplDef(imp)) => { + let resolver = ModuleId::from(imp.module(db)).resolver(db.upcast()); + let ctx = TyLoweringContext::new(db, &resolver); + Adt::from( + Ty::from_hir( + &ctx, + &imp.target_trait(db).unwrap_or_else(|| imp.target_type(db)), + ) + .as_adt() + .map(|t| t.0) + .unwrap(), + ) + .into() + } + None => ModuleDef::Function(*f), + }, + moddef => *moddef, + }; + + let ns = ItemInNs::Types(target_def.clone().into()); let module = moddef.module(db)?; let krate = module.krate(); @@ -117,7 +139,28 @@ fn get_doc_link_impl(db: &dyn HirDatabase, moddef: &ModuleDef) -> Option get_doc_url(db, &krate) .and_then(|url| url.join(&base).ok()) - .and_then(|url| get_symbol_filename(db, &moddef).as_deref().and_then(|f| url.join(f).ok())) + .and_then(|url| { + get_symbol_filename(db, &target_def).as_deref().and_then(|f| url.join(f).ok()) + }) + .and_then(|url| match moddef { + ModuleDef::Function(f) => { + get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Function(*f))) + .as_deref() + .and_then(|f| url.join(f).ok()) + } + ModuleDef::Const(c) => { + get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Const(*c))) + .as_deref() + .and_then(|f| url.join(f).ok()) + } + ModuleDef::TypeAlias(ty) => { + get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::TypeAlias(*ty))) + .as_deref() + .and_then(|f| url.join(f).ok()) + } + // TODO: Field <- this requires passing in a definition or something + _ => Some(url), + }) .map(|url| url.into_string()) } @@ -307,6 +350,12 @@ fn ns_from_intra_spec(s: &str) -> Option { .next() } +/// Get the root URL for the documentation of a crate. +/// +/// ``` +/// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next +/// ^^^^^^^^^^^^^^^^^^^^^^^^^^ +/// ``` fn get_doc_url(db: &RootDatabase, krate: &Crate) -> Option { krate .get_html_root_url(db) @@ -323,8 +372,11 @@ fn get_doc_url(db: &RootDatabase, krate: &Crate) -> Option { /// Get the filename and extension generated for a symbol by rustdoc. /// -/// Example: `struct.Shard.html` -fn get_symbol_filename(db: &RootDatabase, definition: &ModuleDef) -> Option { +/// ``` +/// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next +/// ^^^^^^^^^^^^^^^^^^^ +/// ``` +fn get_symbol_filename(db: &dyn HirDatabase, definition: &ModuleDef) -> Option { Some(match definition { ModuleDef::Adt(adt) => match adt { Adt::Struct(s) => format!("struct.{}.html", s.name(db)), @@ -334,7 +386,7 @@ fn get_symbol_filename(db: &RootDatabase, definition: &ModuleDef) -> Option "index.html".to_string(), ModuleDef::Trait(t) => format!("trait.{}.html", t.name(db)), ModuleDef::TypeAlias(t) => format!("type.{}.html", t.name(db)), - ModuleDef::BuiltinType(t) => format!("primitive.{}.html", t), + ModuleDef::BuiltinType(t) => format!("primitive.{}.html", t.as_name()), ModuleDef::Function(f) => format!("fn.{}.html", f.name(db)), ModuleDef::EnumVariant(ev) => { format!("enum.{}.html#variant.{}", ev.parent_enum(db).name(db), ev.name(db)) @@ -344,6 +396,30 @@ fn get_symbol_filename(db: &RootDatabase, definition: &ModuleDef) -> Option Option { + Some(match field_or_assoc { + FieldOrAssocItem::Field(field) => format!("#structfield.{}", field.name(db)), + FieldOrAssocItem::AssocItem(assoc) => match assoc { + // TODO: Rustdoc sometimes uses tymethod instead of method. This case needs to be investigated. + AssocItem::Function(function) => format!("#method.{}", function.name(db)), + // TODO: This might be the old method for documenting associated constants, i32::MAX uses a separate page... + AssocItem::Const(constant) => format!("#associatedconstant.{}", constant.name(db)?), + AssocItem::TypeAlias(ty) => format!("#associatedtype.{}", ty.name(db)), + }, + }) +} + fn pick_best(tokens: TokenAtOffset) -> Option { return tokens.max_by_key(priority); fn priority(n: &SyntaxToken) -> usize { -- cgit v1.2.3 From 8c32bdea3662f4c65810e2d92569b0cb4e3872d9 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Mon, 31 Aug 2020 20:38:10 +1200 Subject: Rename ide::link_rewrite -> ide::doc_links & tidy imports --- crates/ide/src/doc_links.rs | 433 +++++++++++++++++++++++++++++++++++++++++ crates/ide/src/hover.rs | 2 +- crates/ide/src/lib.rs | 6 +- crates/ide/src/link_rewrite.rs | 433 ----------------------------------------- 4 files changed, 437 insertions(+), 437 deletions(-) create mode 100644 crates/ide/src/doc_links.rs delete mode 100644 crates/ide/src/link_rewrite.rs (limited to 'crates/ide/src') 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 @@ +//! Resolves and rewrites links in markdown documentation. +//! +//! Most of the implementation can be found in [`hir::doc_links`]. + +use hir::{Adt, Crate, HasAttrs, ModuleDef}; +use ide_db::{defs::Definition, RootDatabase}; +use pulldown_cmark::{CowStr, Event, LinkType, Options, Parser, Tag}; +use pulldown_cmark_to_cmark::{cmark_with_options, Options as CmarkOptions}; +use url::Url; + +use crate::{FilePosition, Semantics}; +use hir::{get_doc_link, resolve_doc_link}; +use ide_db::{ + defs::{classify_name, classify_name_ref, Definition}, + RootDatabase, +}; +use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset, T}; + +pub type DocumentationLink = String; + +/// Rewrite documentation links in markdown to point to an online host (e.g. docs.rs) +pub fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition) -> String { + let doc = Parser::new_with_broken_link_callback( + markdown, + Options::empty(), + Some(&|label, _| Some((/*url*/ label.to_string(), /*title*/ label.to_string()))), + ); + + let doc = map_links(doc, |target, title: &str| { + // This check is imperfect, there's some overlap between valid intra-doc links + // and valid URLs so we choose to be too eager to try to resolve what might be + // a URL. + if target.contains("://") { + (target.to_string(), title.to_string()) + } else { + // Two posibilities: + // * path-based links: `../../module/struct.MyStruct.html` + // * module-based links (AKA intra-doc links): `super::super::module::MyStruct` + if let Some(rewritten) = rewrite_intra_doc_link(db, *definition, target, title) { + return rewritten; + } + if let Definition::ModuleDef(def) = *definition { + if let Some(target) = rewrite_url_link(db, def, target) { + return (target, title.to_string()); + } + } + + (target.to_string(), title.to_string()) + } + }); + let mut out = String::new(); + let mut options = CmarkOptions::default(); + options.code_block_backticks = 3; + cmark_with_options(doc, &mut out, None, options).ok(); + out +} + +/// Remove all links in markdown documentation. +pub fn remove_links(markdown: &str) -> String { + let mut drop_link = false; + + let mut opts = Options::empty(); + opts.insert(Options::ENABLE_FOOTNOTES); + + let doc = Parser::new_with_broken_link_callback( + markdown, + opts, + Some(&|_, _| Some((String::new(), String::new()))), + ); + let doc = doc.filter_map(move |evt| match evt { + Event::Start(Tag::Link(link_type, ref target, ref title)) => { + if link_type == LinkType::Inline && target.contains("://") { + Some(Event::Start(Tag::Link(link_type, target.clone(), title.clone()))) + } else { + drop_link = true; + None + } + } + Event::End(_) if drop_link => { + drop_link = false; + None + } + _ => Some(evt), + }); + + let mut out = String::new(); + let mut options = CmarkOptions::default(); + options.code_block_backticks = 3; + cmark_with_options(doc, &mut out, None, options).ok(); + out +} + +pub fn get_doc_link(db: &dyn HirDatabase, definition: &T) -> Option { + let module_def = definition.clone().try_into_module_def()?; + + get_doc_link_impl(db, &module_def) +} + +// TODO: +// BUG: For Option +// Returns https://doc.rust-lang.org/nightly/core/prelude/v1/enum.Option.html#variant.Some +// Instead of https://doc.rust-lang.org/nightly/core/option/enum.Option.html +// +// BUG: For methods +// import_map.path_of(ns) fails, is not designed to resolve methods +fn get_doc_link_impl(db: &dyn HirDatabase, moddef: &ModuleDef) -> Option { + // Get the outermost definition for the moduledef. This is used to resolve the public path to the type, + // then we can join the method, field, etc onto it if required. + let target_def: ModuleDef = match moddef { + ModuleDef::Function(f) => match f.as_assoc_item(db).map(|assoc| assoc.container(db)) { + Some(AssocItemContainer::Trait(t)) => t.into(), + Some(AssocItemContainer::ImplDef(imp)) => { + let resolver = ModuleId::from(imp.module(db)).resolver(db.upcast()); + let ctx = TyLoweringContext::new(db, &resolver); + Adt::from( + Ty::from_hir( + &ctx, + &imp.target_trait(db).unwrap_or_else(|| imp.target_type(db)), + ) + .as_adt() + .map(|t| t.0) + .unwrap(), + ) + .into() + } + None => ModuleDef::Function(*f), + }, + moddef => *moddef, + }; + + let ns = ItemInNs::Types(target_def.clone().into()); + + let module = moddef.module(db)?; + let krate = module.krate(); + let import_map = db.import_map(krate.into()); + let base = once(krate.display_name(db).unwrap()) + .chain(import_map.path_of(ns).unwrap().segments.iter().map(|name| format!("{}", name))) + .join("/"); + + get_doc_url(db, &krate) + .and_then(|url| url.join(&base).ok()) + .and_then(|url| { + get_symbol_filename(db, &target_def).as_deref().and_then(|f| url.join(f).ok()) + }) + .and_then(|url| match moddef { + ModuleDef::Function(f) => { + get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Function(*f))) + .as_deref() + .and_then(|f| url.join(f).ok()) + } + ModuleDef::Const(c) => { + get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Const(*c))) + .as_deref() + .and_then(|f| url.join(f).ok()) + } + ModuleDef::TypeAlias(ty) => { + get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::TypeAlias(*ty))) + .as_deref() + .and_then(|f| url.join(f).ok()) + } + // TODO: Field <- this requires passing in a definition or something + _ => Some(url), + }) + .map(|url| url.into_string()) +} + +fn rewrite_intra_doc_link( + db: &RootDatabase, + def: Definition, + target: &str, + title: &str, +) -> Option<(String, String)> { + let link = if target.is_empty() { title } else { target }; + let (link, ns) = parse_link(link); + let resolved = match def { + Definition::ModuleDef(def) => match def { + ModuleDef::Module(it) => it.resolve_doc_path(db, link, ns), + ModuleDef::Function(it) => it.resolve_doc_path(db, link, ns), + ModuleDef::Adt(it) => it.resolve_doc_path(db, link, ns), + ModuleDef::EnumVariant(it) => it.resolve_doc_path(db, link, ns), + ModuleDef::Const(it) => it.resolve_doc_path(db, link, ns), + ModuleDef::Static(it) => it.resolve_doc_path(db, link, ns), + ModuleDef::Trait(it) => it.resolve_doc_path(db, link, ns), + ModuleDef::TypeAlias(it) => it.resolve_doc_path(db, link, ns), + ModuleDef::BuiltinType(_) => return None, + }, + Definition::Macro(it) => it.resolve_doc_path(db, link, ns), + Definition::Field(it) => it.resolve_doc_path(db, link, ns), + Definition::SelfType(_) | Definition::Local(_) | Definition::TypeParam(_) => return None, + }?; + let krate = resolved.module(db)?.krate(); + let canonical_path = resolved.canonical_path(db)?; + let new_target = get_doc_url(db, &krate)? + .join(&format!("{}/", krate.declaration_name(db)?)) + .ok()? + .join(&canonical_path.replace("::", "/")) + .ok()? + .join(&get_symbol_filename(db, &resolved)?) + .ok()? + .into_string(); + let new_title = strip_prefixes_suffixes(title); + Some((new_target, new_title.to_string())) +} + +/// Try to resolve path to local documentation via path-based links (i.e. `../gateway/struct.Shard.html`). +fn rewrite_url_link(db: &RootDatabase, def: ModuleDef, target: &str) -> Option { + if !(target.contains('#') || target.contains(".html")) { + return None; + } + + let module = def.module(db)?; + let krate = module.krate(); + let canonical_path = def.canonical_path(db)?; + let base = format!("{}/{}", krate.declaration_name(db)?, canonical_path.replace("::", "/")); + + get_doc_url(db, &krate) + .and_then(|url| url.join(&base).ok()) + .and_then(|url| { + get_symbol_filename(db, &def).as_deref().map(|f| url.join(f).ok()).flatten() + }) + .and_then(|url| url.join(target).ok()) + .map(|url| url.into_string()) +} + +// FIXME: This should either be moved, or the module should be renamed. +/// Retrieve a link to documentation for the given symbol. +pub fn get_doc_url(db: &RootDatabase, position: &FilePosition) -> Option { + let sema = Semantics::new(db); + let file = sema.parse(position.file_id).syntax().clone(); + let token = pick_best(file.token_at_offset(position.offset))?; + let token = sema.descend_into_macros(token); + + let node = token.parent(); + let definition = match_ast! { + match node { + ast::NameRef(name_ref) => classify_name_ref(&sema, &name_ref).map(|d| d.definition(sema.db)), + ast::Name(name) => classify_name(&sema, &name).map(|d| d.definition(sema.db)), + _ => None, + } + }; + + match definition? { + Definition::Macro(t) => get_doc_link(db, &t), + Definition::Field(t) => get_doc_link(db, &t), + Definition::ModuleDef(t) => get_doc_link(db, &t), + Definition::SelfType(t) => get_doc_link(db, &t), + Definition::Local(t) => get_doc_link(db, &t), + Definition::TypeParam(t) => get_doc_link(db, &t), + } +} + +/// Rewrites a markdown document, applying 'callback' to each link. +fn map_links<'e>( + events: impl Iterator>, + callback: impl Fn(&str, &str) -> (String, String), +) -> impl Iterator> { + let mut in_link = false; + let mut link_target: Option = None; + + events.map(move |evt| match evt { + Event::Start(Tag::Link(_link_type, ref target, _)) => { + in_link = true; + link_target = Some(target.clone()); + evt + } + Event::End(Tag::Link(link_type, _target, _)) => { + in_link = false; + Event::End(Tag::Link(link_type, link_target.take().unwrap(), CowStr::Borrowed(""))) + } + Event::Text(s) if in_link => { + let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s); + link_target = Some(CowStr::Boxed(link_target_s.into())); + Event::Text(CowStr::Boxed(link_name.into())) + } + Event::Code(s) if in_link => { + let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s); + link_target = Some(CowStr::Boxed(link_target_s.into())); + Event::Code(CowStr::Boxed(link_name.into())) + } + _ => evt, + }) +} + +fn parse_link(s: &str) -> (&str, Option) { + let path = strip_prefixes_suffixes(s); + let ns = ns_from_intra_spec(s); + (path, ns) +} + +/// Strip prefixes, suffixes, and inline code marks from the given string. +fn strip_prefixes_suffixes(mut s: &str) -> &str { + s = s.trim_matches('`'); + + [ + (TYPES.0.iter(), TYPES.1.iter()), + (VALUES.0.iter(), VALUES.1.iter()), + (MACROS.0.iter(), MACROS.1.iter()), + ] + .iter() + .for_each(|(prefixes, suffixes)| { + prefixes.clone().for_each(|prefix| s = s.trim_start_matches(*prefix)); + suffixes.clone().for_each(|suffix| s = s.trim_end_matches(*suffix)); + }); + s.trim_start_matches('@').trim() +} + +static TYPES: ([&str; 7], [&str; 0]) = + (["type", "struct", "enum", "mod", "trait", "union", "module"], []); +static VALUES: ([&str; 8], [&str; 1]) = + (["value", "function", "fn", "method", "const", "static", "mod", "module"], ["()"]); +static MACROS: ([&str; 1], [&str; 1]) = (["macro"], ["!"]); + +/// Extract the specified namespace from an intra-doc-link if one exists. +/// +/// # Examples +/// +/// * `struct MyStruct` -> `Namespace::Types` +/// * `panic!` -> `Namespace::Macros` +/// * `fn@from_intra_spec` -> `Namespace::Values` +fn ns_from_intra_spec(s: &str) -> Option { + [ + (hir::Namespace::Types, (TYPES.0.iter(), TYPES.1.iter())), + (hir::Namespace::Values, (VALUES.0.iter(), VALUES.1.iter())), + (hir::Namespace::Macros, (MACROS.0.iter(), MACROS.1.iter())), + ] + .iter() + .filter(|(_ns, (prefixes, suffixes))| { + prefixes + .clone() + .map(|prefix| { + s.starts_with(*prefix) + && s.chars() + .nth(prefix.len() + 1) + .map(|c| c == '@' || c == ' ') + .unwrap_or(false) + }) + .any(|cond| cond) + || suffixes + .clone() + .map(|suffix| { + s.starts_with(*suffix) + && s.chars() + .nth(suffix.len() + 1) + .map(|c| c == '@' || c == ' ') + .unwrap_or(false) + }) + .any(|cond| cond) + }) + .map(|(ns, (_, _))| *ns) + .next() +} + +/// Get the root URL for the documentation of a crate. +/// +/// ``` +/// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next +/// ^^^^^^^^^^^^^^^^^^^^^^^^^^ +/// ``` +fn get_doc_url(db: &RootDatabase, krate: &Crate) -> Option { + krate + .get_html_root_url(db) + .or_else(|| { + // Fallback to docs.rs. This uses `display_name` and can never be + // correct, but that's what fallbacks are about. + // + // FIXME: clicking on the link should just open the file in the editor, + // instead of falling back to external urls. + Some(format!("https://docs.rs/{}/*/", krate.declaration_name(db)?)) + }) + .and_then(|s| Url::parse(&s).ok()) +} + +/// Get the filename and extension generated for a symbol by rustdoc. +/// +/// ``` +/// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next +/// ^^^^^^^^^^^^^^^^^^^ +/// ``` +fn get_symbol_filename(db: &dyn HirDatabase, definition: &ModuleDef) -> Option { + Some(match definition { + ModuleDef::Adt(adt) => match adt { + Adt::Struct(s) => format!("struct.{}.html", s.name(db)), + Adt::Enum(e) => format!("enum.{}.html", e.name(db)), + Adt::Union(u) => format!("union.{}.html", u.name(db)), + }, + ModuleDef::Module(_) => "index.html".to_string(), + ModuleDef::Trait(t) => format!("trait.{}.html", t.name(db)), + ModuleDef::TypeAlias(t) => format!("type.{}.html", t.name(db)), + ModuleDef::BuiltinType(t) => format!("primitive.{}.html", t.as_name()), + ModuleDef::Function(f) => format!("fn.{}.html", f.name(db)), + ModuleDef::EnumVariant(ev) => { + format!("enum.{}.html#variant.{}", ev.parent_enum(db).name(db), ev.name(db)) + } + ModuleDef::Const(c) => format!("const.{}.html", c.name(db)?), + ModuleDef::Static(s) => format!("static.{}.html", s.name(db)?), + }) +} + +enum FieldOrAssocItem { + Field(Field), + AssocItem(AssocItem), +} + +/// Get the fragment required to link to a specific field, method, associated type, or associated constant. +/// +/// ``` +/// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next +/// ^^^^^^^^^^^^^^ +/// ``` +fn get_symbol_fragment(db: &dyn HirDatabase, field_or_assoc: &FieldOrAssocItem) -> Option { + Some(match field_or_assoc { + FieldOrAssocItem::Field(field) => format!("#structfield.{}", field.name(db)), + FieldOrAssocItem::AssocItem(assoc) => match assoc { + // TODO: Rustdoc sometimes uses tymethod instead of method. This case needs to be investigated. + AssocItem::Function(function) => format!("#method.{}", function.name(db)), + // TODO: This might be the old method for documenting associated constants, i32::MAX uses a separate page... + AssocItem::Const(constant) => format!("#associatedconstant.{}", constant.name(db)?), + AssocItem::TypeAlias(ty) => format!("#associatedtype.{}", ty.name(db)), + }, + }) +} + +fn pick_best(tokens: TokenAtOffset) -> Option { + return tokens.max_by_key(priority); + fn priority(n: &SyntaxToken) -> usize { + match n.kind() { + IDENT | INT_NUMBER => 3, + T!['('] | T![')'] => 2, + kind if kind.is_trivia() => 0, + _ => 1, + } + } +} diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs index 53265488e..a53359d03 100644 --- a/crates/ide/src/hover.rs +++ b/crates/ide/src/hover.rs @@ -14,8 +14,8 @@ use test_utils::mark; use crate::{ display::{macro_label, ShortLabel, ToNav, TryToNav}, - link_rewrite::{remove_links, rewrite_links}, markdown_remove::remove_markdown, + doc_links::{remove_links, rewrite_links}, markup::Markup, runnables::runnable, FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index 645369597..b92e6d9ea 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs @@ -45,8 +45,8 @@ mod status; mod syntax_highlighting; mod syntax_tree; mod typing; -mod link_rewrite; mod markdown_remove; +mod doc_links; use std::sync::Arc; @@ -386,8 +386,8 @@ impl Analysis { pub fn get_doc_url( &self, position: FilePosition, - ) -> Cancelable> { - self.with_db(|db| link_rewrite::get_doc_url(db, &position)) + ) -> Cancelable> { + self.with_db(|db| doc_links::get_doc_url(db, &position)) } /// Computes parameter information for the given call expression. diff --git a/crates/ide/src/link_rewrite.rs b/crates/ide/src/link_rewrite.rs deleted file mode 100644 index 1e102997f..000000000 --- a/crates/ide/src/link_rewrite.rs +++ /dev/null @@ -1,433 +0,0 @@ -//! Resolves and rewrites links in markdown documentation. -//! -//! Most of the implementation can be found in [`hir::doc_links`]. - -use hir::{Adt, Crate, HasAttrs, ModuleDef}; -use ide_db::{defs::Definition, RootDatabase}; -use pulldown_cmark::{CowStr, Event, LinkType, Options, Parser, Tag}; -use pulldown_cmark_to_cmark::{cmark_with_options, Options as CmarkOptions}; -use url::Url; - -use crate::{FilePosition, Semantics}; -use hir::{get_doc_link, resolve_doc_link}; -use ide_db::{ - defs::{classify_name, classify_name_ref, Definition}, - RootDatabase, -}; -use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset, T}; - -pub type DocumentationLink = String; - -/// Rewrite documentation links in markdown to point to an online host (e.g. docs.rs) -pub fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition) -> String { - let doc = Parser::new_with_broken_link_callback( - markdown, - Options::empty(), - Some(&|label, _| Some((/*url*/ label.to_string(), /*title*/ label.to_string()))), - ); - - let doc = map_links(doc, |target, title: &str| { - // This check is imperfect, there's some overlap between valid intra-doc links - // and valid URLs so we choose to be too eager to try to resolve what might be - // a URL. - if target.contains("://") { - (target.to_string(), title.to_string()) - } else { - // Two posibilities: - // * path-based links: `../../module/struct.MyStruct.html` - // * module-based links (AKA intra-doc links): `super::super::module::MyStruct` - if let Some(rewritten) = rewrite_intra_doc_link(db, *definition, target, title) { - return rewritten; - } - if let Definition::ModuleDef(def) = *definition { - if let Some(target) = rewrite_url_link(db, def, target) { - return (target, title.to_string()); - } - } - - (target.to_string(), title.to_string()) - } - }); - let mut out = String::new(); - let mut options = CmarkOptions::default(); - options.code_block_backticks = 3; - cmark_with_options(doc, &mut out, None, options).ok(); - out -} - -/// Remove all links in markdown documentation. -pub fn remove_links(markdown: &str) -> String { - let mut drop_link = false; - - let mut opts = Options::empty(); - opts.insert(Options::ENABLE_FOOTNOTES); - - let doc = Parser::new_with_broken_link_callback( - markdown, - opts, - Some(&|_, _| Some((String::new(), String::new()))), - ); - let doc = doc.filter_map(move |evt| match evt { - Event::Start(Tag::Link(link_type, ref target, ref title)) => { - if link_type == LinkType::Inline && target.contains("://") { - Some(Event::Start(Tag::Link(link_type, target.clone(), title.clone()))) - } else { - drop_link = true; - None - } - } - Event::End(_) if drop_link => { - drop_link = false; - None - } - _ => Some(evt), - }); - - let mut out = String::new(); - let mut options = CmarkOptions::default(); - options.code_block_backticks = 3; - cmark_with_options(doc, &mut out, None, options).ok(); - out -} - -pub fn get_doc_link(db: &dyn HirDatabase, definition: &T) -> Option { - let module_def = definition.clone().try_into_module_def()?; - - get_doc_link_impl(db, &module_def) -} - -// TODO: -// BUG: For Option -// Returns https://doc.rust-lang.org/nightly/core/prelude/v1/enum.Option.html#variant.Some -// Instead of https://doc.rust-lang.org/nightly/core/option/enum.Option.html -// -// BUG: For methods -// import_map.path_of(ns) fails, is not designed to resolve methods -fn get_doc_link_impl(db: &dyn HirDatabase, moddef: &ModuleDef) -> Option { - // Get the outermost definition for the moduledef. This is used to resolve the public path to the type, - // then we can join the method, field, etc onto it if required. - let target_def: ModuleDef = match moddef { - ModuleDef::Function(f) => match f.as_assoc_item(db).map(|assoc| assoc.container(db)) { - Some(AssocItemContainer::Trait(t)) => t.into(), - Some(AssocItemContainer::ImplDef(imp)) => { - let resolver = ModuleId::from(imp.module(db)).resolver(db.upcast()); - let ctx = TyLoweringContext::new(db, &resolver); - Adt::from( - Ty::from_hir( - &ctx, - &imp.target_trait(db).unwrap_or_else(|| imp.target_type(db)), - ) - .as_adt() - .map(|t| t.0) - .unwrap(), - ) - .into() - } - None => ModuleDef::Function(*f), - }, - moddef => *moddef, - }; - - let ns = ItemInNs::Types(target_def.clone().into()); - - let module = moddef.module(db)?; - let krate = module.krate(); - let import_map = db.import_map(krate.into()); - let base = once(krate.display_name(db).unwrap()) - .chain(import_map.path_of(ns).unwrap().segments.iter().map(|name| format!("{}", name))) - .join("/"); - - get_doc_url(db, &krate) - .and_then(|url| url.join(&base).ok()) - .and_then(|url| { - get_symbol_filename(db, &target_def).as_deref().and_then(|f| url.join(f).ok()) - }) - .and_then(|url| match moddef { - ModuleDef::Function(f) => { - get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Function(*f))) - .as_deref() - .and_then(|f| url.join(f).ok()) - } - ModuleDef::Const(c) => { - get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Const(*c))) - .as_deref() - .and_then(|f| url.join(f).ok()) - } - ModuleDef::TypeAlias(ty) => { - get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::TypeAlias(*ty))) - .as_deref() - .and_then(|f| url.join(f).ok()) - } - // TODO: Field <- this requires passing in a definition or something - _ => Some(url), - }) - .map(|url| url.into_string()) -} - -fn rewrite_intra_doc_link( - db: &RootDatabase, - def: Definition, - target: &str, - title: &str, -) -> Option<(String, String)> { - let link = if target.is_empty() { title } else { target }; - let (link, ns) = parse_link(link); - let resolved = match def { - Definition::ModuleDef(def) => match def { - ModuleDef::Module(it) => it.resolve_doc_path(db, link, ns), - ModuleDef::Function(it) => it.resolve_doc_path(db, link, ns), - ModuleDef::Adt(it) => it.resolve_doc_path(db, link, ns), - ModuleDef::EnumVariant(it) => it.resolve_doc_path(db, link, ns), - ModuleDef::Const(it) => it.resolve_doc_path(db, link, ns), - ModuleDef::Static(it) => it.resolve_doc_path(db, link, ns), - ModuleDef::Trait(it) => it.resolve_doc_path(db, link, ns), - ModuleDef::TypeAlias(it) => it.resolve_doc_path(db, link, ns), - ModuleDef::BuiltinType(_) => return None, - }, - Definition::Macro(it) => it.resolve_doc_path(db, link, ns), - Definition::Field(it) => it.resolve_doc_path(db, link, ns), - Definition::SelfType(_) | Definition::Local(_) | Definition::TypeParam(_) => return None, - }?; - let krate = resolved.module(db)?.krate(); - let canonical_path = resolved.canonical_path(db)?; - let new_target = get_doc_url(db, &krate)? - .join(&format!("{}/", krate.declaration_name(db)?)) - .ok()? - .join(&canonical_path.replace("::", "/")) - .ok()? - .join(&get_symbol_filename(db, &resolved)?) - .ok()? - .into_string(); - let new_title = strip_prefixes_suffixes(title); - Some((new_target, new_title.to_string())) -} - -/// Try to resolve path to local documentation via path-based links (i.e. `../gateway/struct.Shard.html`). -fn rewrite_url_link(db: &RootDatabase, def: ModuleDef, target: &str) -> Option { - if !(target.contains('#') || target.contains(".html")) { - return None; - } - - let module = def.module(db)?; - let krate = module.krate(); - let canonical_path = def.canonical_path(db)?; - let base = format!("{}/{}", krate.declaration_name(db)?, canonical_path.replace("::", "/")); - - get_doc_url(db, &krate) - .and_then(|url| url.join(&base).ok()) - .and_then(|url| { - get_symbol_filename(db, &def).as_deref().map(|f| url.join(f).ok()).flatten() - }) - .and_then(|url| url.join(target).ok()) - .map(|url| url.into_string()) -} - -// FIXME: This should either be moved, or the module should be renamed. -/// Retrieve a link to documentation for the given symbol. -pub fn get_doc_url(db: &RootDatabase, position: &FilePosition) -> Option { - let sema = Semantics::new(db); - let file = sema.parse(position.file_id).syntax().clone(); - let token = pick_best(file.token_at_offset(position.offset))?; - let token = sema.descend_into_macros(token); - - let node = token.parent(); - let definition = match_ast! { - match node { - ast::NameRef(name_ref) => classify_name_ref(&sema, &name_ref).map(|d| d.definition(sema.db)), - ast::Name(name) => classify_name(&sema, &name).map(|d| d.definition(sema.db)), - _ => None, - } - }; - - match definition? { - Definition::Macro(t) => get_doc_link(db, &t), - Definition::Field(t) => get_doc_link(db, &t), - Definition::ModuleDef(t) => get_doc_link(db, &t), - Definition::SelfType(t) => get_doc_link(db, &t), - Definition::Local(t) => get_doc_link(db, &t), - Definition::TypeParam(t) => get_doc_link(db, &t), - } -} - -/// Rewrites a markdown document, applying 'callback' to each link. -fn map_links<'e>( - events: impl Iterator>, - callback: impl Fn(&str, &str) -> (String, String), -) -> impl Iterator> { - let mut in_link = false; - let mut link_target: Option = None; - - events.map(move |evt| match evt { - Event::Start(Tag::Link(_link_type, ref target, _)) => { - in_link = true; - link_target = Some(target.clone()); - evt - } - Event::End(Tag::Link(link_type, _target, _)) => { - in_link = false; - Event::End(Tag::Link(link_type, link_target.take().unwrap(), CowStr::Borrowed(""))) - } - Event::Text(s) if in_link => { - let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s); - link_target = Some(CowStr::Boxed(link_target_s.into())); - Event::Text(CowStr::Boxed(link_name.into())) - } - Event::Code(s) if in_link => { - let (link_target_s, link_name) = callback(&link_target.take().unwrap(), &s); - link_target = Some(CowStr::Boxed(link_target_s.into())); - Event::Code(CowStr::Boxed(link_name.into())) - } - _ => evt, - }) -} - -fn parse_link(s: &str) -> (&str, Option) { - let path = strip_prefixes_suffixes(s); - let ns = ns_from_intra_spec(s); - (path, ns) -} - -/// Strip prefixes, suffixes, and inline code marks from the given string. -fn strip_prefixes_suffixes(mut s: &str) -> &str { - s = s.trim_matches('`'); - - [ - (TYPES.0.iter(), TYPES.1.iter()), - (VALUES.0.iter(), VALUES.1.iter()), - (MACROS.0.iter(), MACROS.1.iter()), - ] - .iter() - .for_each(|(prefixes, suffixes)| { - prefixes.clone().for_each(|prefix| s = s.trim_start_matches(*prefix)); - suffixes.clone().for_each(|suffix| s = s.trim_end_matches(*suffix)); - }); - s.trim_start_matches('@').trim() -} - -static TYPES: ([&str; 7], [&str; 0]) = - (["type", "struct", "enum", "mod", "trait", "union", "module"], []); -static VALUES: ([&str; 8], [&str; 1]) = - (["value", "function", "fn", "method", "const", "static", "mod", "module"], ["()"]); -static MACROS: ([&str; 1], [&str; 1]) = (["macro"], ["!"]); - -/// Extract the specified namespace from an intra-doc-link if one exists. -/// -/// # Examples -/// -/// * `struct MyStruct` -> `Namespace::Types` -/// * `panic!` -> `Namespace::Macros` -/// * `fn@from_intra_spec` -> `Namespace::Values` -fn ns_from_intra_spec(s: &str) -> Option { - [ - (hir::Namespace::Types, (TYPES.0.iter(), TYPES.1.iter())), - (hir::Namespace::Values, (VALUES.0.iter(), VALUES.1.iter())), - (hir::Namespace::Macros, (MACROS.0.iter(), MACROS.1.iter())), - ] - .iter() - .filter(|(_ns, (prefixes, suffixes))| { - prefixes - .clone() - .map(|prefix| { - s.starts_with(*prefix) - && s.chars() - .nth(prefix.len() + 1) - .map(|c| c == '@' || c == ' ') - .unwrap_or(false) - }) - .any(|cond| cond) - || suffixes - .clone() - .map(|suffix| { - s.starts_with(*suffix) - && s.chars() - .nth(suffix.len() + 1) - .map(|c| c == '@' || c == ' ') - .unwrap_or(false) - }) - .any(|cond| cond) - }) - .map(|(ns, (_, _))| *ns) - .next() -} - -/// Get the root URL for the documentation of a crate. -/// -/// ``` -/// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next -/// ^^^^^^^^^^^^^^^^^^^^^^^^^^ -/// ``` -fn get_doc_url(db: &RootDatabase, krate: &Crate) -> Option { - krate - .get_html_root_url(db) - .or_else(|| { - // Fallback to docs.rs. This uses `display_name` and can never be - // correct, but that's what fallbacks are about. - // - // FIXME: clicking on the link should just open the file in the editor, - // instead of falling back to external urls. - Some(format!("https://docs.rs/{}/*/", krate.declaration_name(db)?)) - }) - .and_then(|s| Url::parse(&s).ok()) -} - -/// Get the filename and extension generated for a symbol by rustdoc. -/// -/// ``` -/// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next -/// ^^^^^^^^^^^^^^^^^^^ -/// ``` -fn get_symbol_filename(db: &dyn HirDatabase, definition: &ModuleDef) -> Option { - Some(match definition { - ModuleDef::Adt(adt) => match adt { - Adt::Struct(s) => format!("struct.{}.html", s.name(db)), - Adt::Enum(e) => format!("enum.{}.html", e.name(db)), - Adt::Union(u) => format!("union.{}.html", u.name(db)), - }, - ModuleDef::Module(_) => "index.html".to_string(), - ModuleDef::Trait(t) => format!("trait.{}.html", t.name(db)), - ModuleDef::TypeAlias(t) => format!("type.{}.html", t.name(db)), - ModuleDef::BuiltinType(t) => format!("primitive.{}.html", t.as_name()), - ModuleDef::Function(f) => format!("fn.{}.html", f.name(db)), - ModuleDef::EnumVariant(ev) => { - format!("enum.{}.html#variant.{}", ev.parent_enum(db).name(db), ev.name(db)) - } - ModuleDef::Const(c) => format!("const.{}.html", c.name(db)?), - ModuleDef::Static(s) => format!("static.{}.html", s.name(db)?), - }) -} - -enum FieldOrAssocItem { - Field(Field), - AssocItem(AssocItem), -} - -/// Get the fragment required to link to a specific field, method, associated type, or associated constant. -/// -/// ``` -/// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next -/// ^^^^^^^^^^^^^^ -/// ``` -fn get_symbol_fragment(db: &dyn HirDatabase, field_or_assoc: &FieldOrAssocItem) -> Option { - Some(match field_or_assoc { - FieldOrAssocItem::Field(field) => format!("#structfield.{}", field.name(db)), - FieldOrAssocItem::AssocItem(assoc) => match assoc { - // TODO: Rustdoc sometimes uses tymethod instead of method. This case needs to be investigated. - AssocItem::Function(function) => format!("#method.{}", function.name(db)), - // TODO: This might be the old method for documenting associated constants, i32::MAX uses a separate page... - AssocItem::Const(constant) => format!("#associatedconstant.{}", constant.name(db)?), - AssocItem::TypeAlias(ty) => format!("#associatedtype.{}", ty.name(db)), - }, - }) -} - -fn pick_best(tokens: TokenAtOffset) -> Option { - return tokens.max_by_key(priority); - fn priority(n: &SyntaxToken) -> usize { - match n.kind() { - IDENT | INT_NUMBER => 3, - T!['('] | T![')'] => 2, - kind if kind.is_trivia() => 0, - _ => 1, - } - } -} -- cgit v1.2.3 From a14194b428efdb09cc45f9862ec34bef0038cd35 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Tue, 1 Sep 2020 11:38:32 +1200 Subject: Changes from review --- crates/ide/src/doc_links.rs | 3 --- crates/ide/src/lib.rs | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 1e102997f..7fe88577d 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -100,9 +100,6 @@ pub fn get_doc_link(db: &dyn HirDatabase, definition: &T) // BUG: For Option // Returns https://doc.rust-lang.org/nightly/core/prelude/v1/enum.Option.html#variant.Some // Instead of https://doc.rust-lang.org/nightly/core/option/enum.Option.html -// -// BUG: For methods -// import_map.path_of(ns) fails, is not designed to resolve methods fn get_doc_link_impl(db: &dyn HirDatabase, moddef: &ModuleDef) -> Option { // Get the outermost definition for the moduledef. This is used to resolve the public path to the type, // then we can join the method, field, etc onto it if required. diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index b92e6d9ea..0580d2979 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs @@ -383,7 +383,7 @@ impl Analysis { } /// Return URL(s) for the documentation of the symbol under the cursor. - pub fn get_doc_url( + pub fn external_docs( &self, position: FilePosition, ) -> Cancelable> { -- cgit v1.2.3 From 974518fde7975b839ed4ccd4c5ce1d48cd6db3c7 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Tue, 1 Sep 2020 20:26:10 +1200 Subject: Code reorganisation and field support --- crates/ide/src/doc_links.rs | 99 +++++++++++++++++++++------------------------ crates/ide/src/lib.rs | 2 +- 2 files changed, 47 insertions(+), 54 deletions(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 7fe88577d..512c42c4d 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -2,20 +2,27 @@ //! //! Most of the implementation can be found in [`hir::doc_links`]. -use hir::{Adt, Crate, HasAttrs, ModuleDef}; -use ide_db::{defs::Definition, RootDatabase}; -use pulldown_cmark::{CowStr, Event, LinkType, Options, Parser, Tag}; +use std::iter::once; + +use itertools::Itertools; use pulldown_cmark_to_cmark::{cmark_with_options, Options as CmarkOptions}; +use pulldown_cmark::{CowStr, Event, LinkType, Options, Parser, Tag}; use url::Url; -use crate::{FilePosition, Semantics}; -use hir::{get_doc_link, resolve_doc_link}; +use ide_db::{defs::Definition, RootDatabase}; + +use hir::{ + db::{DefDatabase, HirDatabase}, + Adt, AsName, AssocItem, Crate, Field, HasAttrs, ItemInNs, ModuleDef, +}; use ide_db::{ defs::{classify_name, classify_name_ref, Definition}, RootDatabase, }; use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset, T}; +use crate::{FilePosition, Semantics}; + pub type DocumentationLink = String; /// Rewrite documentation links in markdown to point to an online host (e.g. docs.rs) @@ -100,64 +107,58 @@ pub fn get_doc_link(db: &dyn HirDatabase, definition: &T) // BUG: For Option // Returns https://doc.rust-lang.org/nightly/core/prelude/v1/enum.Option.html#variant.Some // Instead of https://doc.rust-lang.org/nightly/core/option/enum.Option.html -fn get_doc_link_impl(db: &dyn HirDatabase, moddef: &ModuleDef) -> Option { +// This could be worked around by turning the `EnumVariant` into `Enum` before attempting resolution, +// but it's really just working around the problem. Ideally we need to implement a slightly different +// version of import map which follows the same process as rustdoc. Otherwise there'll always be some +// edge cases where we select the wrong import path. +fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option { // Get the outermost definition for the moduledef. This is used to resolve the public path to the type, // then we can join the method, field, etc onto it if required. - let target_def: ModuleDef = match moddef { - ModuleDef::Function(f) => match f.as_assoc_item(db).map(|assoc| assoc.container(db)) { - Some(AssocItemContainer::Trait(t)) => t.into(), - Some(AssocItemContainer::ImplDef(imp)) => { - let resolver = ModuleId::from(imp.module(db)).resolver(db.upcast()); - let ctx = TyLoweringContext::new(db, &resolver); - Adt::from( - Ty::from_hir( - &ctx, - &imp.target_trait(db).unwrap_or_else(|| imp.target_type(db)), - ) - .as_adt() - .map(|t| t.0) - .unwrap(), - ) - .into() + let target_def: ModuleDef = match definition { + Definition::ModuleDef(moddef) => match moddef { + ModuleDef::Function(f) => { + f.parent_def(db).map(|mowner| mowner.into()).unwrap_or_else(|| f.clone().into()) } - None => ModuleDef::Function(*f), + moddef => moddef, }, - moddef => *moddef, + Definition::Field(f) => f.parent_def(db).into(), + // FIXME: Handle macros + _ => return None, }; let ns = ItemInNs::Types(target_def.clone().into()); - let module = moddef.module(db)?; + let module = definition.module(db)?; let krate = module.krate(); let import_map = db.import_map(krate.into()); let base = once(krate.display_name(db).unwrap()) .chain(import_map.path_of(ns).unwrap().segments.iter().map(|name| format!("{}", name))) .join("/"); - get_doc_url(db, &krate) - .and_then(|url| url.join(&base).ok()) - .and_then(|url| { - get_symbol_filename(db, &target_def).as_deref().and_then(|f| url.join(f).ok()) - }) - .and_then(|url| match moddef { + let filename = get_symbol_filename(db, &target_def); + let fragment = match definition { + Definition::ModuleDef(moddef) => match moddef { ModuleDef::Function(f) => { - get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Function(*f))) - .as_deref() - .and_then(|f| url.join(f).ok()) + get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Function(f))) } ModuleDef::Const(c) => { - get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Const(*c))) - .as_deref() - .and_then(|f| url.join(f).ok()) + get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::Const(c))) } ModuleDef::TypeAlias(ty) => { - get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::TypeAlias(*ty))) - .as_deref() - .and_then(|f| url.join(f).ok()) + get_symbol_fragment(db, &FieldOrAssocItem::AssocItem(AssocItem::TypeAlias(ty))) } - // TODO: Field <- this requires passing in a definition or something - _ => Some(url), - }) + _ => None, + }, + Definition::Field(field) => get_symbol_fragment(db, &FieldOrAssocItem::Field(field)), + _ => None, + }; + + get_doc_url(db, &krate) + .and_then(|url| url.join(&base).ok()) + .and_then(|url| filename.as_deref().and_then(|f| url.join(f).ok())) + .and_then( + |url| if let Some(fragment) = fragment { url.join(&fragment).ok() } else { Some(url) }, + ) .map(|url| url.into_string()) } @@ -219,9 +220,8 @@ fn rewrite_url_link(db: &RootDatabase, def: ModuleDef, target: &str) -> Option Option { +pub fn external_docs(db: &RootDatabase, position: &FilePosition) -> Option { let sema = Semantics::new(db); let file = sema.parse(position.file_id).syntax().clone(); let token = pick_best(file.token_at_offset(position.offset))?; @@ -236,14 +236,7 @@ pub fn get_doc_url(db: &RootDatabase, position: &FilePosition) -> Option get_doc_link(db, &t), - Definition::Field(t) => get_doc_link(db, &t), - Definition::ModuleDef(t) => get_doc_link(db, &t), - Definition::SelfType(t) => get_doc_link(db, &t), - Definition::Local(t) => get_doc_link(db, &t), - Definition::TypeParam(t) => get_doc_link(db, &t), - } + get_doc_link(db, definition?) } /// Rewrites a markdown document, applying 'callback' to each link. diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index 0580d2979..5db6e1311 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs @@ -387,7 +387,7 @@ impl Analysis { &self, position: FilePosition, ) -> Cancelable> { - self.with_db(|db| doc_links::get_doc_url(db, &position)) + self.with_db(|db| doc_links::external_docs(db, &position)) } /// Computes parameter information for the given call expression. -- cgit v1.2.3 From c648884397bfdb779c447fa31964dc1fce94bd95 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Thu, 3 Sep 2020 19:55:24 +1200 Subject: Differentiate method/tymethod by determining 'defaultness' Currently a method only has defaultness if it is a provided trait method, but this will change when specialisation is available and may need to become a concept known to hir. I opted to go for a 'fewest changes' approach given specialisation is still under development. --- crates/ide/src/doc_links.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 512c42c4d..2f6c59c40 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -13,7 +13,7 @@ use ide_db::{defs::Definition, RootDatabase}; use hir::{ db::{DefDatabase, HirDatabase}, - Adt, AsName, AssocItem, Crate, Field, HasAttrs, ItemInNs, ModuleDef, + Adt, AsName, AssocItem, Crate, Field, HasAttrs, ItemInNs, MethodOwner, ModuleDef, }; use ide_db::{ defs::{classify_name, classify_name_ref, Definition}, @@ -117,7 +117,7 @@ fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option { let target_def: ModuleDef = match definition { Definition::ModuleDef(moddef) => match moddef { ModuleDef::Function(f) => { - f.parent_def(db).map(|mowner| mowner.into()).unwrap_or_else(|| f.clone().into()) + f.method_owner(db).map(|mowner| mowner.into()).unwrap_or_else(|| f.clone().into()) } moddef => moddef, }, @@ -401,9 +401,18 @@ fn get_symbol_fragment(db: &dyn HirDatabase, field_or_assoc: &FieldOrAssocItem) Some(match field_or_assoc { FieldOrAssocItem::Field(field) => format!("#structfield.{}", field.name(db)), FieldOrAssocItem::AssocItem(assoc) => match assoc { - // TODO: Rustdoc sometimes uses tymethod instead of method. This case needs to be investigated. - AssocItem::Function(function) => format!("#method.{}", function.name(db)), - // TODO: This might be the old method for documenting associated constants, i32::MAX uses a separate page... + AssocItem::Function(function) => { + let is_trait_method = + matches!(function.method_owner(db), Some(MethodOwner::Trait(..))); + // This distinction may get more complicated when specialisation is available. + // In particular this decision is made based on whether a method 'has defaultness'. + // Currently this is only the case for provided trait methods. + if is_trait_method && !function.has_body(db) { + format!("#tymethod.{}", function.name(db)) + } else { + format!("#method.{}", function.name(db)) + } + } AssocItem::Const(constant) => format!("#associatedconstant.{}", constant.name(db)?), AssocItem::TypeAlias(ty) => format!("#associatedtype.{}", ty.name(db)), }, -- cgit v1.2.3 From 26086faab2dab6baeaa050f73a7f64b83ead6807 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Thu, 3 Sep 2020 20:09:36 +1200 Subject: Change Option::Some bug to a fixme note IMO this is too much work to be worth fixing at the moment. --- crates/ide/src/doc_links.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 2f6c59c40..0608c2ac6 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -103,8 +103,8 @@ pub fn get_doc_link(db: &dyn HirDatabase, definition: &T) get_doc_link_impl(db, &module_def) } -// TODO: -// BUG: For Option +// FIXME: +// BUG: For Option::Some // Returns https://doc.rust-lang.org/nightly/core/prelude/v1/enum.Option.html#variant.Some // Instead of https://doc.rust-lang.org/nightly/core/option/enum.Option.html // This could be worked around by turning the `EnumVariant` into `Enum` before attempting resolution, @@ -405,7 +405,7 @@ fn get_symbol_fragment(db: &dyn HirDatabase, field_or_assoc: &FieldOrAssocItem) let is_trait_method = matches!(function.method_owner(db), Some(MethodOwner::Trait(..))); // This distinction may get more complicated when specialisation is available. - // In particular this decision is made based on whether a method 'has defaultness'. + // Rustdoc makes this decision based on whether a method 'has defaultness'. // Currently this is only the case for provided trait methods. if is_trait_method && !function.has_body(db) { format!("#tymethod.{}", function.name(db)) -- cgit v1.2.3 From 37a4d060a7709da42a67fe1631d5786f7e106884 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Thu, 3 Sep 2020 21:27:46 +1200 Subject: Add tests --- crates/ide/src/doc_links.rs | 96 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 94 insertions(+), 2 deletions(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 0608c2ac6..b9d53bcd4 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -112,6 +112,7 @@ pub fn get_doc_link(db: &dyn HirDatabase, definition: &T) // version of import map which follows the same process as rustdoc. Otherwise there'll always be some // edge cases where we select the wrong import path. fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option { + eprintln!("enter"); // Get the outermost definition for the moduledef. This is used to resolve the public path to the type, // then we can join the method, field, etc onto it if required. let target_def: ModuleDef = match definition { @@ -131,8 +132,8 @@ fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option { let module = definition.module(db)?; let krate = module.krate(); let import_map = db.import_map(krate.into()); - let base = once(krate.display_name(db).unwrap()) - .chain(import_map.path_of(ns).unwrap().segments.iter().map(|name| format!("{}", name))) + let base = once(krate.display_name(db)?) + .chain(import_map.path_of(ns)?.segments.iter().map(|name| format!("{}", name))) .join("/"); let filename = get_symbol_filename(db, &target_def); @@ -152,6 +153,7 @@ fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option { Definition::Field(field) => get_symbol_fragment(db, &FieldOrAssocItem::Field(field)), _ => None, }; + eprintln!("end-ish"); get_doc_url(db, &krate) .and_then(|url| url.join(&base).ok()) @@ -430,3 +432,93 @@ fn pick_best(tokens: TokenAtOffset) -> Option { } } } + +#[cfg(test)] +mod tests { + use expect_test::{expect, Expect}; + + use crate::mock_analysis::analysis_and_position; + + fn check(ra_fixture: &str, expect: Expect) { + let (analysis, position) = analysis_and_position(ra_fixture); + let url = analysis.external_docs(position).unwrap().unwrap(); + + expect.assert_eq(&url) + } + + #[test] + fn test_doc_url_struct() { + check( + r#" +pub struct Fo<|>o; +"#, + expect![[r#"https://docs.rs/test/*/test/struct.Foo.html"#]], + ); + } + + // TODO: Fix this test. Fails on `import_map.path_of(ns)` + #[test] + fn test_doc_url_fn() { + check( + r#" +pub fn fo<|>o() {} +"#, + expect![[r#""#]], + ); + } + + #[test] + fn test_doc_url_inherent_method() { + check( + r#" +pub struct Foo; + +impl Foo { + pub fn met<|>hod() {} +} + +"#, + expect![[r##"https://docs.rs/test/*/test/struct.Foo.html#method.method"##]], + ); + } + + #[test] + fn test_doc_url_trait_provided_method() { + check( + r#" +pub trait Bar { + fn met<|>hod() {} +} + +"#, + expect![[r##"https://docs.rs/test/*/test/trait.Bar.html#method.method"##]], + ); + } + + #[test] + fn test_doc_url_trait_required_method() { + check( + r#" +pub trait Foo { + fn met<|>hod(); +} + +"#, + expect![[r##"https://docs.rs/test/*/test/trait.Foo.html#tymethod.method"##]], + ); + } + + + #[test] + fn test_doc_url_field() { + check( + r#" +pub struct Foo { + pub fie<|>ld: () +} + +"#, + expect![[r##"https://docs.rs/test/*/test/struct.Foo.html#structfield.field"##]], + ); + } +} -- cgit v1.2.3 From 6cae6b8f3cf284f9f386ea8ce7e347043fe9a040 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Sat, 5 Sep 2020 16:58:04 +1200 Subject: Fix namespace detection & function test --- crates/ide/src/doc_links.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index b9d53bcd4..101466014 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -112,7 +112,6 @@ pub fn get_doc_link(db: &dyn HirDatabase, definition: &T) // version of import map which follows the same process as rustdoc. Otherwise there'll always be some // edge cases where we select the wrong import path. fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option { - eprintln!("enter"); // Get the outermost definition for the moduledef. This is used to resolve the public path to the type, // then we can join the method, field, etc onto it if required. let target_def: ModuleDef = match definition { @@ -127,7 +126,7 @@ fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option { _ => return None, }; - let ns = ItemInNs::Types(target_def.clone().into()); + let ns = ItemInNs::from(target_def.clone()); let module = definition.module(db)?; let krate = module.krate(); @@ -153,7 +152,6 @@ fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option { Definition::Field(field) => get_symbol_fragment(db, &FieldOrAssocItem::Field(field)), _ => None, }; - eprintln!("end-ish"); get_doc_url(db, &krate) .and_then(|url| url.join(&base).ok()) @@ -456,14 +454,13 @@ pub struct Fo<|>o; ); } - // TODO: Fix this test. Fails on `import_map.path_of(ns)` #[test] fn test_doc_url_fn() { check( r#" pub fn fo<|>o() {} "#, - expect![[r#""#]], + expect![[r##"https://docs.rs/test/*/test/fn.foo.html#method.foo"##]], ); } @@ -508,7 +505,6 @@ pub trait Foo { ); } - #[test] fn test_doc_url_field() { check( -- cgit v1.2.3 From f6759ba3bbc2c17771735327238c4ed936d5cdc9 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Sat, 5 Sep 2020 17:21:52 +1200 Subject: Add ignored test to demonstrate ImportMap bug --- crates/ide/src/doc_links.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 101466014..164783e14 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -439,7 +439,7 @@ mod tests { fn check(ra_fixture: &str, expect: Expect) { let (analysis, position) = analysis_and_position(ra_fixture); - let url = analysis.external_docs(position).unwrap().unwrap(); + let url = analysis.external_docs(position).unwrap().expect("could not find url for symbol"); expect.assert_eq(&url) } @@ -517,4 +517,29 @@ pub struct Foo { expect![[r##"https://docs.rs/test/*/test/struct.Foo.html#structfield.field"##]], ); } + + // FIXME: ImportMap will return re-export paths instead of public module + // paths. The correct path to documentation will never be a re-export. + // This problem stops us from resolving stdlib items included in the prelude + // such as `Option::Some` correctly. + #[ignore = "ImportMap may return re-exports"] + #[test] + fn test_reexport_order() { + check( + r#" +pub mod wrapper { + pub use module::Item; + + pub mod module { + pub struct Item; + } +} + +fn foo() { + let bar: wrapper::It<|>em; +} + "#, + expect![[r#"https://docs.rs/test/*/test/wrapper/module/struct.Item.html"#]], + ) + } } -- cgit v1.2.3 From e4a787fcbc865cd66921f8052a9cccad33a13b92 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Sat, 5 Sep 2020 17:37:27 +1200 Subject: Remove outdated part of doc_links module docs --- crates/ide/src/doc_links.rs | 2 -- 1 file changed, 2 deletions(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 164783e14..34dc122a8 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -1,6 +1,4 @@ //! Resolves and rewrites links in markdown documentation. -//! -//! Most of the implementation can be found in [`hir::doc_links`]. use std::iter::once; -- cgit v1.2.3 From d2c68809ea3243ca68811e9b2e0f1592e2dc33fe Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Thu, 8 Oct 2020 14:54:44 +1300 Subject: Changes from review --- crates/ide/src/doc_links.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 34dc122a8..6b2ecf725 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -11,7 +11,7 @@ use ide_db::{defs::Definition, RootDatabase}; use hir::{ db::{DefDatabase, HirDatabase}, - Adt, AsName, AssocItem, Crate, Field, HasAttrs, ItemInNs, MethodOwner, ModuleDef, + Adt, AsName, AssocItem, Crate, Field, HasAttrs, ItemInNs, MethodOwner, ModuleDef, AssocItemContainer, AsAssocItem }; use ide_db::{ defs::{classify_name, classify_name_ref, Definition}, @@ -219,7 +219,7 @@ fn rewrite_url_link(db: &RootDatabase, def: ModuleDef, target: &str) -> Option Option { +pub(crate) fn external_docs(db: &RootDatabase, position: &FilePosition) -> Option { let sema = Semantics::new(db); let file = sema.parse(position.file_id).syntax().clone(); let token = pick_best(file.token_at_offset(position.offset))?; @@ -401,7 +401,7 @@ fn get_symbol_fragment(db: &dyn HirDatabase, field_or_assoc: &FieldOrAssocItem) FieldOrAssocItem::AssocItem(assoc) => match assoc { AssocItem::Function(function) => { let is_trait_method = - matches!(function.method_owner(db), Some(MethodOwner::Trait(..))); + matches!(function.as_assoc_item(db).map(|assoc| assoc.container(db)), Some(AssocItemContainer::Trait(..))); // This distinction may get more complicated when specialisation is available. // Rustdoc makes this decision based on whether a method 'has defaultness'. // Currently this is only the case for provided trait methods. -- cgit v1.2.3 From 8af1dd733760c51abadda8f2bd20139e11ebba04 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Thu, 8 Oct 2020 15:22:57 +1300 Subject: Rebase fixes --- crates/ide/src/doc_links.rs | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 6b2ecf725..5ef708647 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -7,11 +7,9 @@ use pulldown_cmark_to_cmark::{cmark_with_options, Options as CmarkOptions}; use pulldown_cmark::{CowStr, Event, LinkType, Options, Parser, Tag}; use url::Url; -use ide_db::{defs::Definition, RootDatabase}; - use hir::{ db::{DefDatabase, HirDatabase}, - Adt, AsName, AssocItem, Crate, Field, HasAttrs, ItemInNs, MethodOwner, ModuleDef, AssocItemContainer, AsAssocItem + Adt, AsName, AssocItem, Crate, Field, HasAttrs, ItemInNs, ModuleDef, AssocItemContainer, AsAssocItem }; use ide_db::{ defs::{classify_name, classify_name_ref, Definition}, @@ -95,12 +93,6 @@ pub fn remove_links(markdown: &str) -> String { out } -pub fn get_doc_link(db: &dyn HirDatabase, definition: &T) -> Option { - let module_def = definition.clone().try_into_module_def()?; - - get_doc_link_impl(db, &module_def) -} - // FIXME: // BUG: For Option::Some // Returns https://doc.rust-lang.org/nightly/core/prelude/v1/enum.Option.html#variant.Some @@ -129,8 +121,8 @@ fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option { let module = definition.module(db)?; let krate = module.krate(); let import_map = db.import_map(krate.into()); - let base = once(krate.display_name(db)?) - .chain(import_map.path_of(ns)?.segments.iter().map(|name| format!("{}", name))) + let base = once(krate.declaration_name(db)?.to_string()) + .chain(import_map.path_of(ns)?.segments.iter().map(|name| name.to_string())) .join("/"); let filename = get_symbol_filename(db, &target_def); @@ -433,10 +425,10 @@ fn pick_best(tokens: TokenAtOffset) -> Option { mod tests { use expect_test::{expect, Expect}; - use crate::mock_analysis::analysis_and_position; + use crate::fixture; fn check(ra_fixture: &str, expect: Expect) { - let (analysis, position) = analysis_and_position(ra_fixture); + let (analysis, position) = fixture::position(ra_fixture); let url = analysis.external_docs(position).unwrap().expect("could not find url for symbol"); expect.assert_eq(&url) -- cgit v1.2.3 From 3bd4fe96dce17eb2bff380389b24ea325bf54803 Mon Sep 17 00:00:00 2001 From: Zac Pullar-Strecker Date: Thu, 8 Oct 2020 15:44:52 +1300 Subject: Remove methodowner & fix formatting --- crates/ide/src/doc_links.rs | 35 +++++++++++++++++++++++------------ crates/ide/src/hover.rs | 2 +- 2 files changed, 24 insertions(+), 13 deletions(-) (limited to 'crates/ide/src') diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 5ef708647..06af36b73 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -3,13 +3,14 @@ use std::iter::once; use itertools::Itertools; -use pulldown_cmark_to_cmark::{cmark_with_options, Options as CmarkOptions}; use pulldown_cmark::{CowStr, Event, LinkType, Options, Parser, Tag}; +use pulldown_cmark_to_cmark::{cmark_with_options, Options as CmarkOptions}; use url::Url; use hir::{ db::{DefDatabase, HirDatabase}, - Adt, AsName, AssocItem, Crate, Field, HasAttrs, ItemInNs, ModuleDef, AssocItemContainer, AsAssocItem + Adt, AsAssocItem, AsName, AssocItem, AssocItemContainer, Crate, Field, HasAttrs, ItemInNs, + ModuleDef, }; use ide_db::{ defs::{classify_name, classify_name_ref, Definition}, @@ -97,18 +98,23 @@ pub fn remove_links(markdown: &str) -> String { // BUG: For Option::Some // Returns https://doc.rust-lang.org/nightly/core/prelude/v1/enum.Option.html#variant.Some // Instead of https://doc.rust-lang.org/nightly/core/option/enum.Option.html -// This could be worked around by turning the `EnumVariant` into `Enum` before attempting resolution, -// but it's really just working around the problem. Ideally we need to implement a slightly different -// version of import map which follows the same process as rustdoc. Otherwise there'll always be some -// edge cases where we select the wrong import path. +// +// This should cease to be a problem if RFC2988 (Stable Rustdoc URLs) is implemented +// https://github.com/rust-lang/rfcs/pull/2988 fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option { // Get the outermost definition for the moduledef. This is used to resolve the public path to the type, // then we can join the method, field, etc onto it if required. let target_def: ModuleDef = match definition { Definition::ModuleDef(moddef) => match moddef { - ModuleDef::Function(f) => { - f.method_owner(db).map(|mowner| mowner.into()).unwrap_or_else(|| f.clone().into()) - } + ModuleDef::Function(f) => f + .as_assoc_item(db) + .and_then(|assoc| match assoc.container(db) { + AssocItemContainer::Trait(t) => Some(t.into()), + AssocItemContainer::ImplDef(impld) => { + impld.target_ty(db).as_adt().map(|adt| adt.into()) + } + }) + .unwrap_or_else(|| f.clone().into()), moddef => moddef, }, Definition::Field(f) => f.parent_def(db).into(), @@ -211,7 +217,10 @@ fn rewrite_url_link(db: &RootDatabase, def: ModuleDef, target: &str) -> Option Option { +pub(crate) fn external_docs( + db: &RootDatabase, + position: &FilePosition, +) -> Option { let sema = Semantics::new(db); let file = sema.parse(position.file_id).syntax().clone(); let token = pick_best(file.token_at_offset(position.offset))?; @@ -392,8 +401,10 @@ fn get_symbol_fragment(db: &dyn HirDatabase, field_or_assoc: &FieldOrAssocItem) FieldOrAssocItem::Field(field) => format!("#structfield.{}", field.name(db)), FieldOrAssocItem::AssocItem(assoc) => match assoc { AssocItem::Function(function) => { - let is_trait_method = - matches!(function.as_assoc_item(db).map(|assoc| assoc.container(db)), Some(AssocItemContainer::Trait(..))); + let is_trait_method = matches!( + function.as_assoc_item(db).map(|assoc| assoc.container(db)), + Some(AssocItemContainer::Trait(..)) + ); // This distinction may get more complicated when specialisation is available. // Rustdoc makes this decision based on whether a method 'has defaultness'. // Currently this is only the case for provided trait methods. diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs index a53359d03..6290b35bd 100644 --- a/crates/ide/src/hover.rs +++ b/crates/ide/src/hover.rs @@ -14,8 +14,8 @@ use test_utils::mark; use crate::{ display::{macro_label, ShortLabel, ToNav, TryToNav}, - markdown_remove::remove_markdown, doc_links::{remove_links, rewrite_links}, + markdown_remove::remove_markdown, markup::Markup, runnables::runnable, FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, -- cgit v1.2.3