]> git.lizzy.rs Git - rust.git/commitdiff
Provide navigations to parent modules
authorrainy-me <github@yue.coffee>
Wed, 13 Oct 2021 22:16:42 +0000 (07:16 +0900)
committerrainy-me <github@yue.coffee>
Wed, 13 Oct 2021 22:16:42 +0000 (07:16 +0900)
crates/project_model/src/cargo_workspace.rs
crates/rust-analyzer/src/handlers.rs
editors/code/src/commands.ts
editors/code/src/lsp_ext.ts

index 1417ac2fa1d1b0f357768b8175d1a7ead90f8730..a55901a8f7524046982902c16fd9a5e1e4687fb9 100644 (file)
@@ -1,6 +1,6 @@
 //! See [`CargoWorkspace`].
 
-use std::convert::TryInto;
+use std::convert::{TryFrom, TryInto};
 use std::iter;
 use std::path::PathBuf;
 use std::{ops, process::Command};
@@ -400,6 +400,39 @@ pub fn package_flag(&self, package: &PackageData) -> String {
         }
     }
 
+    pub fn parent_manifests(&self, manifest_path: &ManifestPath) -> Option<Vec<ManifestPath>> {
+        let mut found = false;
+        let parent_manifests = self
+            .packages()
+            .filter_map(|pkg| {
+                if !found && &self[pkg].manifest == manifest_path {
+                    found = true
+                }
+                self[pkg].dependencies.iter().find_map(|dep| {
+                    if &self[dep.pkg].manifest == manifest_path {
+                        return Some(self[pkg].manifest.clone());
+                    }
+                    None
+                })
+            })
+            .collect::<Vec<ManifestPath>>();
+
+        // some packages has this pkg as dep. return their manifests
+        if parent_manifests.len() > 0 {
+            return Some(parent_manifests);
+        }
+
+        // this pkg is inside this cargo workspace, fallback to workspace root
+        if found {
+            return Some(vec![
+                ManifestPath::try_from(self.workspace_root().join("Cargo.toml")).ok()?
+            ]);
+        }
+
+        // not in this workspace
+        None
+    }
+
     fn is_unique(&self, name: &str) -> bool {
         self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
     }
index 306de0425172596a4d3450063071d94579be88ea..0105496ba2adb98b5177cbb102f6cc40fc41e43f 100644 (file)
@@ -3,6 +3,7 @@
 //! `ide` crate.
 
 use std::{
+    convert::TryFrom,
     io::Write as _,
     process::{self, Stdio},
 };
     SemanticTokensRangeResult, SemanticTokensResult, SymbolInformation, SymbolTag,
     TextDocumentIdentifier, Url, WorkspaceEdit,
 };
-use project_model::{ProjectWorkspace, TargetKind};
+use project_model::{ManifestPath, ProjectWorkspace, TargetKind};
 use serde_json::json;
 use stdx::{format_to, never};
 use syntax::{algo, ast, AstNode, TextRange, TextSize, T};
+use vfs::AbsPathBuf;
 
 use crate::{
     cargo_target_spec::CargoTargetSpec,
@@ -606,28 +608,30 @@ pub(crate) fn handle_parent_module(
     let _p = profile::span("handle_parent_module");
     if let Ok(file_path) = &params.text_document.uri.to_file_path() {
         if file_path.file_name().unwrap_or_default() == "Cargo.toml" {
-            // search parent workspace and collect a list of `LocationLink`path,
-            // since cargo.toml doesn't have file_id
+            // search workspaces for parent packages or fallback to workspace root
+            let abs_path_buf = match AbsPathBuf::try_from(file_path.to_path_buf()).ok() {
+                Some(abs_path_buf) => abs_path_buf,
+                None => return Ok(None),
+            };
+
+            let manifest_path = match ManifestPath::try_from(abs_path_buf).ok() {
+                Some(manifest_path) => manifest_path,
+                None => return Ok(None),
+            };
+
             let links: Vec<LocationLink> = snap
                 .workspaces
                 .iter()
                 .filter_map(|ws| match ws {
-                    ProjectWorkspace::Cargo { cargo, .. } => cargo
-                        .packages()
-                        .find(|&pkg| cargo[pkg].manifest.as_ref() == file_path)
-                        .and_then(|_| Some(cargo)),
+                    ProjectWorkspace::Cargo { cargo, .. } => cargo.parent_manifests(&manifest_path),
                     _ => None,
                 })
-                .map(|ws| {
-                    let target_cargo_toml_path = ws.workspace_root().join("Cargo.toml");
-                    let target_cargo_toml_url =
-                        to_proto::url_from_abs_path(&target_cargo_toml_path);
-                    LocationLink {
-                        origin_selection_range: None,
-                        target_uri: target_cargo_toml_url,
-                        target_range: Range::default(),
-                        target_selection_range: Range::default(),
-                    }
+                .flatten()
+                .map(|parent_manifest_path| LocationLink {
+                    origin_selection_range: None,
+                    target_uri: to_proto::url_from_abs_path(&parent_manifest_path),
+                    target_range: Range::default(),
+                    target_selection_range: Range::default(),
                 })
                 .collect::<_>();
             return Ok(Some(links.into()));
index 623e33c7efb2064a2bc8b905c83b90474c954195..c9385361f88c9eabc203aa0cfb45848940608238 100644 (file)
@@ -189,12 +189,14 @@ export function parentModule(ctx: Ctx): Cmd {
         const client = ctx.client;
         if (!editor || !client) return;
         if (!(isRustDocument(editor.document) || isCargoTomlDocument(editor.document))) return;
+
         const locations = await client.sendRequest(ra.parentModule, {
             textDocument: ctx.client.code2ProtocolConverter.asTextDocumentIdentifier(editor.document),
             position: client.code2ProtocolConverter.asPosition(
                 editor.selection.active,
             ),
         });
+        if (!locations) return;
 
         if (locations.length === 1) {
             const loc = locations[0];
index ac632a0156767ac14265c2e2b48479a23ab18b90..90796e611e69e48d3e1f8511efc9c523a3d93018 100644 (file)
@@ -62,7 +62,7 @@ export interface MatchingBraceParams {
 }
 export const matchingBrace = new lc.RequestType<MatchingBraceParams, lc.Position[], void>("experimental/matchingBrace");
 
-export const parentModule = new lc.RequestType<lc.TextDocumentPositionParams, lc.LocationLink[], void>("experimental/parentModule");
+export const parentModule = new lc.RequestType<lc.TextDocumentPositionParams, lc.LocationLink[] | null, void>("experimental/parentModule");
 
 export interface JoinLinesParams {
     textDocument: lc.TextDocumentIdentifier;