Skip to content

Commit fa2f273

Browse files
added children modules
1 parent fe84446 commit fa2f273

File tree

11 files changed

+197
-1
lines changed

11 files changed

+197
-1
lines changed

crates/ide/src/children_modules.rs

+116
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
use hir::Semantics;
2+
use ide_db::{FilePosition, RootDatabase};
3+
use syntax::{
4+
algo::find_node_at_offset,
5+
ast::{self, AstNode},
6+
};
7+
8+
use crate::NavigationTarget;
9+
10+
/// This returns `Vec` because a module may be included from several places.
11+
pub(crate) fn children_modules(db: &RootDatabase, position: FilePosition) -> Vec<NavigationTarget> {
12+
let sema = Semantics::new(db);
13+
let source_file = sema.parse_guess_edition(position.file_id);
14+
// First go to the parent module which contains the cursor
15+
let module = find_node_at_offset::<ast::Module>(source_file.syntax(), position.offset);
16+
17+
match module {
18+
Some(module) => {
19+
// Return all the children module inside the ItemList of the parent module
20+
sema.to_def(&module)
21+
.into_iter()
22+
.flat_map(|module| module.children(db))
23+
.map(|module| NavigationTarget::from_module_to_decl(db, module).call_site())
24+
.collect()
25+
}
26+
None => {
27+
// Return all the children module inside the source file
28+
sema.file_to_module_defs(position.file_id)
29+
.flat_map(|module| module.children(db))
30+
.map(|module| NavigationTarget::from_module_to_decl(db, module).call_site())
31+
.collect()
32+
}
33+
}
34+
}
35+
36+
#[cfg(test)]
37+
mod tests {
38+
use ide_db::FileRange;
39+
40+
use crate::fixture;
41+
42+
fn check_children_module(#[rust_analyzer::rust_fixture] ra_fixture: &str) {
43+
let (analysis, position, expected) = fixture::annotations(ra_fixture);
44+
let navs = analysis.children_modules(position).unwrap();
45+
let navs = navs
46+
.iter()
47+
.map(|nav| FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
48+
.collect::<Vec<_>>();
49+
assert_eq!(expected.into_iter().map(|(fr, _)| fr).collect::<Vec<_>>(), navs);
50+
}
51+
52+
#[test]
53+
fn test_resolve_children_module() {
54+
check_children_module(
55+
r#"
56+
//- /lib.rs
57+
$0
58+
mod foo;
59+
//^^^
60+
61+
//- /foo.rs
62+
// empty
63+
"#,
64+
);
65+
}
66+
67+
#[test]
68+
fn test_resolve_children_module_on_module_decl() {
69+
check_children_module(
70+
r#"
71+
//- /lib.rs
72+
mod $0foo;
73+
//- /foo.rs
74+
mod bar;
75+
//^^^
76+
77+
//- /foo/bar.rs
78+
// empty
79+
"#,
80+
);
81+
}
82+
83+
#[test]
84+
fn test_resolve_children_module_for_inline() {
85+
check_children_module(
86+
r#"
87+
//- /lib.rs
88+
mod foo {
89+
mod $0bar {
90+
mod baz {}
91+
} //^^^
92+
}
93+
"#,
94+
);
95+
}
96+
97+
#[test]
98+
fn test_resolve_multi_child_module() {
99+
check_children_module(
100+
r#"
101+
//- /main.rs
102+
$0
103+
mod foo;
104+
//^^^
105+
mod bar;
106+
//^^^
107+
108+
//- /foo.rs
109+
// empty
110+
111+
//- /bar.rs
112+
// empty
113+
"#,
114+
);
115+
}
116+
}

crates/ide/src/lib.rs

+6
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ mod navigation_target;
2020

2121
mod annotations;
2222
mod call_hierarchy;
23+
mod children_modules;
2324
mod doc_links;
2425
mod expand_macro;
2526
mod extend_selection;
@@ -577,6 +578,11 @@ impl Analysis {
577578
self.with_db(|db| parent_module::parent_module(db, position))
578579
}
579580

581+
/// Returns vec of `mod name;` declaration which are created by the current module.
582+
pub fn children_modules(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
583+
self.with_db(|db| children_modules::children_modules(db, position))
584+
}
585+
580586
/// Returns crates that this file belongs to.
581587
pub fn crates_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>> {
582588
self.with_db(|db| parent_module::crates_for(db, file_id))

crates/rust-analyzer/src/handlers/request.rs

+12
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,18 @@ pub(crate) fn handle_parent_module(
920920
Ok(Some(res))
921921
}
922922

923+
pub(crate) fn handle_children_modules(
924+
snap: GlobalStateSnapshot,
925+
params: lsp_types::TextDocumentPositionParams,
926+
) -> anyhow::Result<Option<lsp_types::GotoDefinitionResponse>> {
927+
let _p = tracing::info_span!("handle_children_module").entered();
928+
// locate children module by semantics
929+
let position = try_default!(from_proto::file_position(&snap, params)?);
930+
let navs = snap.analysis.children_modules(position)?;
931+
let res = to_proto::goto_definition_response(&snap, None, navs)?;
932+
Ok(Some(res))
933+
}
934+
923935
pub(crate) fn handle_runnables(
924936
snap: GlobalStateSnapshot,
925937
params: lsp_ext::RunnablesParams,

crates/rust-analyzer/src/lsp/capabilities.rs

+1
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ pub fn server_capabilities(config: &Config) -> ServerCapabilities {
157157
"onEnter": true,
158158
"openCargoToml": true,
159159
"parentModule": true,
160+
"childrenModules": true,
160161
"runnables": {
161162
"kinds": [ "cargo" ],
162163
},

crates/rust-analyzer/src/lsp/ext.rs

+8
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,14 @@ impl Request for ParentModule {
399399
const METHOD: &'static str = "experimental/parentModule";
400400
}
401401

402+
pub enum ChildrenModules {}
403+
404+
impl Request for ChildrenModules {
405+
type Params = lsp_types::TextDocumentPositionParams;
406+
type Result = Option<lsp_types::GotoDefinitionResponse>;
407+
const METHOD: &'static str = "experimental/childrenModule";
408+
}
409+
402410
pub enum JoinLines {}
403411

404412
impl Request for JoinLines {

crates/rust-analyzer/src/main_loop.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1170,6 +1170,7 @@ impl GlobalState {
11701170
.on::<NO_RETRY, lsp_ext::InterpretFunction>(handlers::handle_interpret_function)
11711171
.on::<NO_RETRY, lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
11721172
.on::<NO_RETRY, lsp_ext::ParentModule>(handlers::handle_parent_module)
1173+
.on::<NO_RETRY, lsp_ext::ChildrenModules>(handlers::handle_children_modules)
11731174
.on::<NO_RETRY, lsp_ext::Runnables>(handlers::handle_runnables)
11741175
.on::<NO_RETRY, lsp_ext::RelatedTests>(handlers::handle_related_tests)
11751176
.on::<NO_RETRY, lsp_ext::CodeActionRequest>(handlers::handle_code_action)

docs/book/src/assists_generated.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -2258,7 +2258,7 @@ fn bar() {
22582258

22592259

22602260
### `inline_local_variable`
2261-
**Source:** [inline_local_variable.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-assists/src/handlers/inline_local_variable.rs#L17)
2261+
**Source:** [inline_local_variable.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-assists/src/handlers/inline_local_variable.rs#L21)
22622262

22632263
Inlines a local variable.
22642264

editors/code/package.json

+9
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,11 @@
170170
"title": "Locate parent module",
171171
"category": "rust-analyzer"
172172
},
173+
{
174+
"command": "rust-analyzer.childrenModules",
175+
"title": "Locate children modules",
176+
"category": "rust-analyzer"
177+
},
173178
{
174179
"command": "rust-analyzer.joinLines",
175180
"title": "Join lines",
@@ -3368,6 +3373,10 @@
33683373
"command": "rust-analyzer.parentModule",
33693374
"when": "inRustProject"
33703375
},
3376+
{
3377+
"command": "rust-analyzer.childrenModule",
3378+
"when": "inRustProject"
3379+
},
33713380
{
33723381
"command": "rust-analyzer.joinLines",
33733382
"when": "inRustProject"

editors/code/src/commands.ts

+37
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,43 @@ export function parentModule(ctx: CtxInit): Cmd {
266266
};
267267
}
268268

269+
export function childrenModules(ctx: CtxInit): Cmd {
270+
return async () => {
271+
const editor = vscode.window.activeTextEditor;
272+
if (!editor) return;
273+
if (!(isRustDocument(editor.document) || isCargoTomlDocument(editor.document))) return;
274+
275+
const client = ctx.client;
276+
277+
const locations = await client.sendRequest(ra.childrenModules, {
278+
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(editor.document),
279+
position: client.code2ProtocolConverter.asPosition(editor.selection.active),
280+
});
281+
if (!locations) return;
282+
283+
if (locations.length === 1) {
284+
const loc = unwrapUndefinable(locations[0]);
285+
286+
const uri = client.protocol2CodeConverter.asUri(loc.targetUri);
287+
const range = client.protocol2CodeConverter.asRange(loc.targetRange);
288+
289+
const doc = await vscode.workspace.openTextDocument(uri);
290+
const e = await vscode.window.showTextDocument(doc);
291+
e.selection = new vscode.Selection(range.start, range.start);
292+
e.revealRange(range, vscode.TextEditorRevealType.InCenter);
293+
} else {
294+
const uri = editor.document.uri.toString();
295+
const position = client.code2ProtocolConverter.asPosition(editor.selection.active);
296+
await showReferencesImpl(
297+
client,
298+
uri,
299+
position,
300+
locations.map((loc) => lc.Location.create(loc.targetUri, loc.targetRange)),
301+
);
302+
}
303+
};
304+
}
305+
269306
export function openCargoToml(ctx: CtxInit): Cmd {
270307
return async () => {
271308
const editor = ctx.activeRustEditor;

editors/code/src/lsp_ext.ts

+5
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,11 @@ export const parentModule = new lc.RequestType<
194194
lc.LocationLink[] | null,
195195
void
196196
>("experimental/parentModule");
197+
export const childrenModules = new lc.RequestType<
198+
lc.TextDocumentPositionParams,
199+
lc.LocationLink[] | null,
200+
void
201+
>("experimental/childrenModule");
197202
export const runnables = new lc.RequestType<RunnablesParams, Runnable[], void>(
198203
"experimental/runnables",
199204
);

editors/code/src/main.ts

+1
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ function createCommands(): Record<string, CommandFactory> {
158158
matchingBrace: { enabled: commands.matchingBrace },
159159
joinLines: { enabled: commands.joinLines },
160160
parentModule: { enabled: commands.parentModule },
161+
childrenModules: { enabled: commands.childrenModules },
161162
viewHir: { enabled: commands.viewHir },
162163
viewMir: { enabled: commands.viewMir },
163164
interpretFunction: { enabled: commands.interpretFunction },

0 commit comments

Comments
 (0)