Skip to content

Commit 30e1f9a

Browse files
committed
Auto merge of #23289 - mihneadb:rustdoc-search-by-type, r=alexcrichton
This adds search by type (for functions/methods) support to Rustdoc. Target issue is at rust-lang/rfcs#658. I've described my approach here: rust-lang/rfcs#658 (comment). I'll copy the text in here as well: --- Hi, it took me longer than I wished, but I have implemented this in a not-too-complex way that I think can be extended to support more complex features (like the ones mentioned [here](#12866 (comment))). The idea is to generate a JSON representation of the types of methods/functions in the existing index, and then make the JS understand when it should look by type (and not by name). I tried to come up with a JSON representation that can be extended to support generics, bounds, ref/mut annotations and so on. Here are a few samples: Function: ```rust fn to_uppercase(c: char) -> char ``` ```json { "inputs": [ {"name": "char"} ], "output": { "name": "char", } } ``` Method (implemented or defined in trait): ```rust // in struct Vec // self is considered an argument as well fn capacity(&self) -> usize ``` ```json { "inputs": [ {"name": "vec"} ], "output": { "name": "usize" } } ``` This simple format can be extended by adding more fields, like `generic: bool`, a `bounds` mapping and so on. I have a working implementation in master...mihneadb:rustdoc-search-by-type. You can check out a live demo [here](http://data.mihneadb.net/doc/std/index.html?search=charext%20-%3E%20char). ![screenshot from 2015-02-28 00 54 00](https://cloud.githubusercontent.com/assets/643127/6422722/7e5374ee-bee4-11e4-99a6-9aac3c9d5068.png) The feature list is not that long: - search by types (you *can* use generics as well, as long as you use the exact name - e.g. [`vec,t -> `](http://data.mihneadb.net/doc/std/index.html?search=vec%2C%20t%20-%3E)) - order of arguments does not matter - `self` is took into account as well (e.g. search for `vec -> usize`) - does not use "complex" annotations (e.g. you don't search for `&char -> char` but for `char -> char`) My goal is to get a working, minimal "base" merged so that others can build upon it. How should I proceed? Do I open a PR (badly in need of code review since this is my first non "hello world"-ish rust code)? ---
2 parents 3400c9e + 7b7b938 commit 30e1f9a

File tree

2 files changed

+142
-3
lines changed

2 files changed

+142
-3
lines changed

src/librustdoc/html/render.rs

+107-1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
//! both occur before the crate is rendered.
3535
pub use self::ExternalLocation::*;
3636

37+
use std::ascii::OwnedAsciiExt;
3738
use std::cell::RefCell;
3839
use std::cmp::Ordering;
3940
use std::collections::{HashMap, HashSet};
@@ -239,6 +240,51 @@ struct IndexItem {
239240
path: String,
240241
desc: String,
241242
parent: Option<ast::DefId>,
243+
search_type: Option<IndexItemFunctionType>,
244+
}
245+
246+
/// A type used for the search index.
247+
struct Type {
248+
name: Option<String>,
249+
}
250+
251+
impl fmt::Display for Type {
252+
/// Formats type as {name: $name}.
253+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
254+
// Wrapping struct fmt should never call us when self.name is None,
255+
// but just to be safe we write `null` in that case.
256+
match self.name {
257+
Some(ref n) => write!(f, "{{\"name\":\"{}\"}}", n),
258+
None => write!(f, "null")
259+
}
260+
}
261+
}
262+
263+
/// Full type of functions/methods in the search index.
264+
struct IndexItemFunctionType {
265+
inputs: Vec<Type>,
266+
output: Option<Type>
267+
}
268+
269+
impl fmt::Display for IndexItemFunctionType {
270+
/// Formats a full fn type as a JSON {inputs: [Type], outputs: Type/null}.
271+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
272+
// If we couldn't figure out a type, just write `null`.
273+
if self.inputs.iter().any(|ref i| i.name.is_none()) ||
274+
(self.output.is_some() && self.output.as_ref().unwrap().name.is_none()) {
275+
return write!(f, "null")
276+
}
277+
278+
let inputs: Vec<String> = self.inputs.iter().map(|ref t| format!("{}", t)).collect();
279+
try!(write!(f, "{{\"inputs\":[{}],\"output\":", inputs.connect(",")));
280+
281+
match self.output {
282+
Some(ref t) => try!(write!(f, "{}", t)),
283+
None => try!(write!(f, "null"))
284+
};
285+
286+
Ok(try!(write!(f, "}}")))
287+
}
242288
}
243289

244290
// TLS keys used to carry information around during rendering.
@@ -409,6 +455,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::Result<String> {
409455
path: fqp[..fqp.len() - 1].connect("::"),
410456
desc: shorter(item.doc_value()).to_string(),
411457
parent: Some(did),
458+
search_type: None,
412459
});
413460
},
414461
None => {}
@@ -458,7 +505,11 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::Result<String> {
458505
let pathid = *nodeid_to_pathid.get(&nodeid).unwrap();
459506
try!(write!(&mut w, ",{}", pathid));
460507
}
461-
None => {}
508+
None => try!(write!(&mut w, ",null"))
509+
}
510+
match item.search_type {
511+
Some(ref t) => try!(write!(&mut w, ",{}", t)),
512+
None => try!(write!(&mut w, ",null"))
462513
}
463514
try!(write!(&mut w, "]"));
464515
}
@@ -872,12 +923,21 @@ impl DocFolder for Cache {
872923

873924
match parent {
874925
(parent, Some(path)) if is_method || (!self.privmod && !hidden_field) => {
926+
// Needed to determine `self` type.
927+
let parent_basename = self.parent_stack.first().and_then(|parent| {
928+
match self.paths.get(parent) {
929+
Some(&(ref fqp, _)) => Some(fqp[fqp.len() - 1].clone()),
930+
_ => None
931+
}
932+
});
933+
875934
self.search_index.push(IndexItem {
876935
ty: shortty(&item),
877936
name: s.to_string(),
878937
path: path.connect("::").to_string(),
879938
desc: shorter(item.doc_value()).to_string(),
880939
parent: parent,
940+
search_type: get_index_search_type(&item, parent_basename),
881941
});
882942
}
883943
(Some(parent), None) if is_method || (!self.privmod && !hidden_field)=> {
@@ -2307,6 +2367,52 @@ fn make_item_keywords(it: &clean::Item) -> String {
23072367
format!("{}, {}", get_basic_keywords(), it.name.as_ref().unwrap())
23082368
}
23092369

2370+
fn get_index_search_type(item: &clean::Item,
2371+
parent: Option<String>) -> Option<IndexItemFunctionType> {
2372+
let decl = match item.inner {
2373+
clean::FunctionItem(ref f) => &f.decl,
2374+
clean::MethodItem(ref m) => &m.decl,
2375+
clean::TyMethodItem(ref m) => &m.decl,
2376+
_ => return None
2377+
};
2378+
2379+
let mut inputs = Vec::new();
2380+
2381+
// Consider `self` an argument as well.
2382+
if let Some(name) = parent {
2383+
inputs.push(Type { name: Some(name.into_ascii_lowercase()) });
2384+
}
2385+
2386+
inputs.extend(&mut decl.inputs.values.iter().map(|arg| {
2387+
get_index_type(&arg.type_)
2388+
}));
2389+
2390+
let output = match decl.output {
2391+
clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
2392+
_ => None
2393+
};
2394+
2395+
Some(IndexItemFunctionType { inputs: inputs, output: output })
2396+
}
2397+
2398+
fn get_index_type(clean_type: &clean::Type) -> Type {
2399+
Type { name: get_index_type_name(clean_type).map(|s| s.into_ascii_lowercase()) }
2400+
}
2401+
2402+
fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
2403+
match *clean_type {
2404+
clean::ResolvedPath { ref path, .. } => {
2405+
let segments = &path.segments;
2406+
Some(segments[segments.len() - 1].name.clone())
2407+
},
2408+
clean::Generic(ref s) => Some(s.clone()),
2409+
clean::Primitive(ref p) => Some(format!("{:?}", p)),
2410+
clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
2411+
// FIXME: add all from clean::Type.
2412+
_ => None
2413+
}
2414+
}
2415+
23102416
pub fn cache() -> Arc<Cache> {
23112417
CACHE_KEY.with(|c| c.borrow().clone())
23122418
}

src/librustdoc/html/static/main.js

+35-2
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,33 @@
209209
break;
210210
}
211211
}
212+
// searching by type
213+
} else if (val.search("->") > -1) {
214+
var trimmer = function (s) { return s.trim(); };
215+
var parts = val.split("->").map(trimmer);
216+
var input = parts[0];
217+
// sort inputs so that order does not matter
218+
var inputs = input.split(",").map(trimmer).sort();
219+
var output = parts[1];
220+
221+
for (var i = 0; i < nSearchWords; ++i) {
222+
var type = searchIndex[i].type;
223+
if (!type) {
224+
continue;
225+
}
226+
227+
// sort index inputs so that order does not matter
228+
var typeInputs = type.inputs.map(function (input) {
229+
return input.name;
230+
}).sort();
231+
232+
// allow searching for void (no output) functions as well
233+
var typeOutput = type.output ? type.output.name : "";
234+
if (inputs.toString() === typeInputs.toString() &&
235+
output == typeOutput) {
236+
results.push({id: i, index: -1, dontValidate: true});
237+
}
238+
}
212239
} else {
213240
// gather matching search results up to a certain maximum
214241
val = val.replace(/\_/g, "");
@@ -329,6 +356,11 @@
329356
path = result.item.path.toLowerCase(),
330357
parent = result.item.parent;
331358

359+
// this validation does not make sense when searching by types
360+
if (result.dontValidate) {
361+
continue;
362+
}
363+
332364
var valid = validateResult(name, path, split, parent);
333365
if (!valid) {
334366
result.id = -1;
@@ -573,7 +605,8 @@
573605
// (String) name,
574606
// (String) full path or empty string for previous path,
575607
// (String) description,
576-
// (optional Number) the parent path index to `paths`]
608+
// (Number | null) the parent path index to `paths`]
609+
// (Object | null) the type of the function (if any)
577610
var items = rawSearchIndex[crate].items;
578611
// an array of [(Number) item type,
579612
// (String) name]
@@ -598,7 +631,7 @@
598631
var rawRow = items[i];
599632
var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
600633
path: rawRow[2] || lastPath, desc: rawRow[3],
601-
parent: paths[rawRow[4]]};
634+
parent: paths[rawRow[4]], type: rawRow[5]};
602635
searchIndex.push(row);
603636
if (typeof row.name === "string") {
604637
var word = row.name.toLowerCase();

0 commit comments

Comments
 (0)