Treat other items as functions for the purpose of type-based search

constants and statics are nullary functions, and struct fields are unary functions.

functions (along with methods and trait methods) are prioritized over other
items, like fields and constants.
This commit is contained in:
binarycat 2025-01-13 15:31:15 -06:00
parent d8a64098c9
commit 9397d133f6
6 changed files with 71 additions and 2 deletions

View File

@ -52,9 +52,10 @@ methods on the allocator or free functions.
[`Layout`]: ../../alloc/index.html?search=Layout&filter-crate=alloc
## Searching By Type Signature for functions
## Searching By Type Signature
If you know more specifically what the function you want to look at does,
or you want to know how to get from one type to another,
Rustdoc can search by more than one type at once in the parameters and return
value. Multiple parameters are separated by `,` commas, and the return value
is written with after a `->` arrow.
@ -86,6 +87,17 @@ the standard library and functions that are included in the results list:
[iterasslice]: ../../std/vec/struct.Vec.html?search=vec%3A%3Aintoiter<T>%20->%20[T]&filter-crate=std
[iterreduce]: ../../std/index.html?search=iterator<T>%2C%20fnmut%20->%20T&filter-crate=std
### Non-functions in type-based search
Certain items that are not functions are treated as though they
were a semantically equivelent function.
For example, struct fields are treated as though they were getter methods.
This means that a search for `CpuidResult -> u32` will show
the `CpuidResult::eax` field in the results.
Additionally, `const` and `static` items are treated as nullary functions,
so `-> u32` will match `u32::MAX`.
### How type-based search works
In a complex type-based search, Rustdoc always treats every item's name as literal.

View File

@ -840,6 +840,22 @@ pub(crate) fn get_function_type_for_search(
| clean::RequiredMethodItem(ref f) => {
get_fn_inputs_and_outputs(f, tcx, impl_or_trait_generics, cache)
}
clean::ConstantItem(ref c) => make_nullary_fn(&c.type_),
clean::StaticItem(ref s) => make_nullary_fn(&s.type_),
clean::StructFieldItem(ref t) => {
let Some(parent) = parent else {
return None;
};
let mut rgen: FxIndexMap<SimplifiedParam, (isize, Vec<RenderType>)> =
Default::default();
let output = get_index_type(t, vec![], &mut rgen);
let input = RenderType {
id: Some(RenderTypeId::DefId(parent)),
generics: None,
bindings: None,
};
(vec![input], vec![output], vec![], vec![])
}
_ => return None,
};
@ -1353,6 +1369,17 @@ fn simplify_fn_constraint<'a>(
res.push((ty_constrained_assoc, ty_constraints));
}
/// Create a fake nullary function.
///
/// Used to allow type-based search on constants and statics.
fn make_nullary_fn(
clean_type: &clean::Type,
) -> (Vec<RenderType>, Vec<RenderType>, Vec<Symbol>, Vec<Vec<RenderType>>) {
let mut rgen: FxIndexMap<SimplifiedParam, (isize, Vec<RenderType>)> = Default::default();
let output = get_index_type(clean_type, vec![], &mut rgen);
(vec![], vec![output], vec![], vec![])
}
/// Return the full list of types when bounds have been resolved.
///
/// i.e. `fn foo<A: Display, B: Option<A>>(x: u32, y: B)` will return

View File

@ -63,6 +63,9 @@ const TY_PRIMITIVE = itemTypes.indexOf("primitive");
const TY_GENERIC = itemTypes.indexOf("generic");
const TY_IMPORT = itemTypes.indexOf("import");
const TY_TRAIT = itemTypes.indexOf("trait");
const TY_FN = itemTypes.indexOf("fn");
const TY_METHOD = itemTypes.indexOf("method");
const TY_TYMETHOD = itemTypes.indexOf("tymethod");
const ROOT_PATH = typeof window !== "undefined" ? window.rootPath : "../";
// Hard limit on how deep to recurse into generics when doing type-driven search.
@ -191,6 +194,10 @@ function isEndCharacter(c) {
return "=,>-])".indexOf(c) !== -1;
}
function isFnLikeTy(ty) {
return ty === TY_FN || ty === TY_METHOD || ty === TY_TYMETHOD;
}
/**
* Returns `true` if the given `c` character is a separator.
*
@ -2766,6 +2773,15 @@ class DocSearch {
return a - b;
}
// in type based search, put functions first
if (parsedQuery.hasReturnArrow) {
a = !isFnLikeTy(aaa.item.ty);
b = !isFnLikeTy(bbb.item.ty);
if (a !== b) {
return a - b;
}
}
// Sort by distance in the path part, if specified
// (less changes required to match means higher rankings)
a = aaa.path_dist;

View File

@ -79,7 +79,7 @@ set-window-size: (851, 600)
// Check the size and count in tabs
assert-text: ("#search-tabs > button:nth-child(1) > .count", "(26)")
assert-text: ("#search-tabs > button:nth-child(2) > .count", "(6)")
assert-text: ("#search-tabs > button:nth-child(2) > .count", "(7)")
assert-text: ("#search-tabs > button:nth-child(3) > .count", "(0)")
store-property: ("#search-tabs > button:nth-child(1)", {"offsetWidth": buttonWidth})
assert-property: ("#search-tabs > button:nth-child(2)", {"offsetWidth": |buttonWidth|})

View File

@ -0,0 +1,7 @@
const EXPECTED = {
'query': '-> char',
'others': [
{ 'path': 'std::char', 'name': 'from_digit' },
{ 'path': 'std::char', 'name': 'MAX' },
],
}

View File

@ -0,0 +1,7 @@
const EXPECTED = {
// one of the only non-generic structs with public fields
'query': 'CpuidResult -> u32',
'others': [
{ 'path': 'core::arch::x86::CpuidResult', 'name': 'eax' },
],
}