]> git.lizzy.rs Git - rust.git/commitdiff
remove last traces of source roots from hir
authorAleksey Kladov <aleksey.kladov@gmail.com>
Wed, 9 Oct 2019 11:27:37 +0000 (14:27 +0300)
committerAleksey Kladov <aleksey.kladov@gmail.com>
Fri, 11 Oct 2019 07:48:46 +0000 (10:48 +0300)
crates/ra_db/src/lib.rs
crates/ra_hir/src/debug.rs
crates/ra_hir/src/nameres/collector.rs
crates/ra_hir/src/nameres/mod_resolution.rs
crates/ra_ide_api/src/diagnostics.rs

index 603daed3746e15cf119247779a8c2ccbdb153661..4d3a9c03628a2865cfa977ba2652936b8eca2079 100644 (file)
@@ -6,7 +6,7 @@
 
 use ra_prof::profile;
 use ra_syntax::{ast, Parse, SourceFile, TextRange, TextUnit};
-use relative_path::RelativePathBuf;
+use relative_path::{RelativePath, RelativePathBuf};
 
 pub use crate::{
     cancellation::Canceled,
@@ -71,6 +71,11 @@ pub trait SourceDatabase: CheckCanceled + std::fmt::Debug {
     /// Text of the file.
     #[salsa::input]
     fn file_text(&self, file_id: FileId) -> Arc<String>;
+
+    #[salsa::transparent]
+    fn resolve_relative_path(&self, anchor: FileId, relative_path: &RelativePath)
+        -> Option<FileId>;
+
     // Parses the file into the syntax tree.
     #[salsa::invoke(parse_query)]
     fn parse(&self, file_id: FileId) -> Parse<ast::SourceFile>;
@@ -89,6 +94,25 @@ pub trait SourceDatabase: CheckCanceled + std::fmt::Debug {
     fn crate_graph(&self) -> Arc<CrateGraph>;
 }
 
+fn resolve_relative_path(
+    db: &impl SourceDatabase,
+    anchor: FileId,
+    relative_path: &RelativePath,
+) -> Option<FileId> {
+    let path = {
+        let mut path = db.file_relative_path(anchor);
+        // Workaround for relative path API: turn `lib.rs` into ``.
+        if !path.pop() {
+            path = RelativePathBuf::default();
+        }
+        path.push(relative_path);
+        path.normalize()
+    };
+    let source_root = db.file_source_root(anchor);
+    let source_root = db.source_root(source_root);
+    source_root.file_by_relative_path(&path)
+}
+
 fn source_root_crates(db: &impl SourceDatabase, id: SourceRootId) -> Arc<Vec<CrateId>> {
     let root = db.source_root(id);
     let graph = db.crate_graph();
index 87f3180c3ad584e1bf17c6149bbe88e9213c4d97..48b69000bcdc8ff25d60c108bf5144bd46d7efe9 100644 (file)
@@ -22,7 +22,7 @@
 
 use ra_db::{CrateId, FileId};
 
-use crate::{db::HirDatabase, Crate, Module, Name};
+use crate::{db::HirDatabase, Crate, HirFileId, Module, Name};
 
 impl Crate {
     pub fn debug(self, db: &impl HirDebugDatabase) -> impl fmt::Debug + '_ {
@@ -36,6 +36,12 @@ pub fn debug(self, db: &impl HirDebugDatabase) -> impl fmt::Debug + '_ {
     }
 }
 
+impl HirFileId {
+    pub fn debug(self, db: &impl HirDebugDatabase) -> impl fmt::Debug + '_ {
+        debug_fn(move |fmt| db.debug_hir_file_id(self, fmt))
+    }
+}
+
 pub trait HirDebugHelper: HirDatabase {
     fn crate_name(&self, _krate: CrateId) -> Option<String> {
         None
@@ -48,6 +54,7 @@ fn file_path(&self, _file_id: FileId) -> Option<String> {
 pub trait HirDebugDatabase {
     fn debug_crate(&self, krate: Crate, fmt: &mut fmt::Formatter<'_>) -> fmt::Result;
     fn debug_module(&self, module: Module, fmt: &mut fmt::Formatter<'_>) -> fmt::Result;
+    fn debug_hir_file_id(&self, file_id: HirFileId, fmt: &mut fmt::Formatter<'_>) -> fmt::Result;
 }
 
 impl<DB: HirDebugHelper> HirDebugDatabase for DB {
@@ -62,12 +69,19 @@ fn debug_crate(&self, krate: Crate, fmt: &mut fmt::Formatter<'_>) -> fmt::Result
 
     fn debug_module(&self, module: Module, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         let file_id = module.definition_source(self).file_id.original_file(self);
-        let path = self.file_path(file_id);
+        let path = self.file_path(file_id).unwrap_or_else(|| "N/A".to_string());
         fmt.debug_struct("Module")
             .field("name", &module.name(self).unwrap_or_else(Name::missing))
-            .field("path", &path.unwrap_or_else(|| "N/A".to_string()))
+            .field("path", &path)
             .finish()
     }
+
+    fn debug_hir_file_id(&self, file_id: HirFileId, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
+        let original = file_id.original_file(self);
+        let path = self.file_path(original).unwrap_or_else(|| "N/A".to_string());
+        let is_macro = file_id != original.into();
+        fmt.debug_struct("HirFileId").field("path", &path).field("macro", &is_macro).finish()
+    }
 }
 
 fn debug_fn(f: impl Fn(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Debug {
index aa5885f045bce011b547112322e7539ef5cd6556..b5fe16bfa4d439528df6519cf212b52dbecc5ae5 100644 (file)
@@ -584,7 +584,7 @@ fn collect_module(&mut self, module: &raw::ModuleData, attrs: &[Attr]) {
             // out of line module, resolve, parse and recurse
             raw::ModuleData::Declaration { name, ast_id } => {
                 let ast_id = ast_id.with_file_id(self.file_id);
-                match self.mod_dir.resolve_submodule(
+                match self.mod_dir.resolve_declaration(
                     self.def_collector.db,
                     self.file_id,
                     name,
index f50f9abe609a77f76cb5809cfd30d04d8005f125..e8b8085142c702365cb0c904d18763a9bffe0cb5 100644 (file)
@@ -1,9 +1,7 @@
 //! This module resolves `mod foo;` declaration to file.
-use std::borrow::Cow;
-
 use ra_db::FileId;
 use ra_syntax::SmolStr;
-use relative_path::{RelativePath, RelativePathBuf};
+use relative_path::RelativePathBuf;
 
 use crate::{db::DefDatabase, HirFileId, Name};
 
@@ -28,23 +26,22 @@ pub(super) fn descend_into_definition(
         attr_path: Option<&SmolStr>,
     ) -> ModDir {
         let mut path = self.path.clone();
-        match attr_path {
+        match attr_to_path(attr_path) {
             None => path.push(&name.to_string()),
             Some(attr_path) => {
                 if self.root_non_dir_owner {
-                    path = path
-                        .parent()
-                        .map(|it| it.to_relative_path_buf())
-                        .unwrap_or_else(RelativePathBuf::new);
+                    // Workaround for relative path API: turn `lib.rs` into ``.
+                    if !path.pop() {
+                        path = RelativePathBuf::default();
+                    }
                 }
-                let attr_path = &*normalize_attribute_path(attr_path);
-                path.push(RelativePath::new(attr_path));
+                path.push(attr_path);
             }
         }
         ModDir { path, root_non_dir_owner: false }
     }
 
-    pub(super) fn resolve_submodule(
+    pub(super) fn resolve_declaration(
         &self,
         db: &impl DefDatabase,
         file_id: HirFileId,
@@ -53,32 +50,25 @@ pub(super) fn resolve_submodule(
     ) -> Result<(FileId, ModDir), RelativePathBuf> {
         let empty_path = RelativePathBuf::default();
         let file_id = file_id.original_file(db);
-        let base_dir = {
-            let path = db.file_relative_path(file_id);
-            path.parent().unwrap_or(&empty_path).join(&self.path)
-        };
 
         let mut candidate_files = Vec::new();
-        match attr_path {
-            Some(attr) => {
+        match attr_to_path(attr_path) {
+            Some(attr_path) => {
                 let base = if self.root_non_dir_owner {
-                    base_dir.parent().unwrap_or(&empty_path)
+                    self.path.parent().unwrap_or(&empty_path)
                 } else {
-                    &base_dir
+                    &self.path
                 };
-                candidate_files.push(base.join(&*normalize_attribute_path(attr)))
+                candidate_files.push(base.join(attr_path))
             }
             None => {
-                candidate_files.push(base_dir.join(&format!("{}.rs", name)));
-                candidate_files.push(base_dir.join(&format!("{}/mod.rs", name)));
+                candidate_files.push(self.path.join(&format!("{}.rs", name)));
+                candidate_files.push(self.path.join(&format!("{}/mod.rs", name)));
             }
         };
 
-        let source_root_id = db.file_source_root(file_id);
-        let source_root = db.source_root(source_root_id);
         for candidate in candidate_files.iter() {
-            let candidate = candidate.normalize();
-            if let Some(file_id) = source_root.file_by_relative_path(&candidate) {
+            if let Some(file_id) = db.resolve_relative_path(file_id, candidate) {
                 let mut root_non_dir_owner = false;
                 let mut mod_path = RelativePathBuf::new();
                 if !(candidate.ends_with("mod.rs") || attr_path.is_some()) {
@@ -88,22 +78,10 @@ pub(super) fn resolve_submodule(
                 return Ok((file_id, ModDir { path: mod_path, root_non_dir_owner }));
             }
         }
-        let suggestion = candidate_files.first().unwrap();
-        Err(base_dir.join(suggestion))
+        Err(candidate_files.remove(0))
     }
 }
 
-fn normalize_attribute_path(file_path: &str) -> Cow<str> {
-    let current_dir = "./";
-    let windows_path_separator = r#"\"#;
-    let current_dir_normalize = if file_path.starts_with(current_dir) {
-        &file_path[current_dir.len()..]
-    } else {
-        file_path
-    };
-    if current_dir_normalize.contains(windows_path_separator) {
-        Cow::Owned(current_dir_normalize.replace(windows_path_separator, "/"))
-    } else {
-        Cow::Borrowed(current_dir_normalize)
-    }
+fn attr_to_path(attr: Option<&SmolStr>) -> Option<RelativePathBuf> {
+    attr.and_then(|it| RelativePathBuf::from_path(&it.replace("\\", "/")).ok())
 }
index 0435188c8488cbe68c86de1ee3a2857d4f9cfa28..65f061443aee4aa2172559ef611de8732d26667f 100644 (file)
@@ -12,6 +12,7 @@
     Location, SyntaxNode, TextRange, T,
 };
 use ra_text_edit::{TextEdit, TextEditBuilder};
+use relative_path::RelativePath;
 
 use crate::{db::RootDatabase, Diagnostic, FileId, FileSystemEdit, SourceChange, SourceFileEdit};
 
@@ -47,8 +48,14 @@ pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic>
         })
     })
     .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
-        let source_root = db.file_source_root(d.source().file_id.original_file(db));
-        let create_file = FileSystemEdit::CreateFile { source_root, path: d.candidate.clone() };
+        let original_file = d.source().file_id.original_file(db);
+        let source_root = db.file_source_root(original_file);
+        let path = db
+            .file_relative_path(original_file)
+            .parent()
+            .unwrap_or_else(|| RelativePath::new(""))
+            .join(&d.candidate);
+        let create_file = FileSystemEdit::CreateFile { source_root, path };
         let fix = SourceChange::file_system_edit("create module", create_file);
         res.borrow_mut().push(Diagnostic {
             range: d.highlight_range(),