Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/doc/rustdoc/src/read-documentation/search.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
27 changes: 27 additions & 0 deletions src/librustdoc/html/render/search_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};

Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions src/librustdoc/html/static/js/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion tests/rustdoc-gui/search-tab.goml
Original file line number Diff line number Diff line change
Expand Up @@ -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|})
Expand Down
7 changes: 7 additions & 0 deletions tests/rustdoc-js-std/const-is-nullary-func.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const EXPECTED = {
'query': '-> char',
'others': [
{ 'path': 'std::char', 'name': 'from_digit' },
{ 'path': 'std::char', 'name': 'MAX' },
],
}
7 changes: 7 additions & 0 deletions tests/rustdoc-js-std/field-is-unary-func.js
Original file line number Diff line number Diff line change
@@ -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' },
],
}
Loading