]> git.lizzy.rs Git - rust.git/blobdiff - compiler/rustc_expand/src/module.rs
use full path for E0761
[rust.git] / compiler / rustc_expand / src / module.rs
index 607c68f82dfa91ed42bc720e31428d39c334cd9e..993522d01d86744bec64592c31f698d58a0e7ae2 100644 (file)
@@ -1,7 +1,7 @@
 use crate::base::ModuleData;
 use rustc_ast::ptr::P;
-use rustc_ast::{token, Attribute, Item};
-use rustc_errors::{struct_span_err, PResult};
+use rustc_ast::{token, Attribute, Inline, Item};
+use rustc_errors::{struct_span_err, DiagnosticBuilder};
 use rustc_parse::new_parser_from_file;
 use rustc_session::parse::ParseSess;
 use rustc_session::Session;
@@ -19,14 +19,6 @@ pub enum DirOwnership {
     UnownedViaBlock,
 }
 
-/// Information about the path to a module.
-// Public for rustfmt usage.
-pub struct ModulePath<'a> {
-    name: String,
-    path_exists: bool,
-    pub result: PResult<'a, ModulePathSuccess>,
-}
-
 // Public for rustfmt usage.
 pub struct ModulePathSuccess {
     pub file_path: PathBuf,
@@ -41,6 +33,14 @@ pub struct ModulePathSuccess {
     pub dir_ownership: DirOwnership,
 }
 
+pub enum ModError<'a> {
+    CircularInclusion(Vec<PathBuf>),
+    ModInBlock(Option<Ident>),
+    FileNotFound(Ident, PathBuf),
+    MultipleCandidates(Ident, PathBuf, PathBuf),
+    ParserError(DiagnosticBuilder<'a>),
+}
+
 crate fn parse_external_mod(
     sess: &Session,
     ident: Ident,
@@ -50,22 +50,26 @@ pub struct ModulePathSuccess {
     attrs: &mut Vec<Attribute>,
 ) -> ParsedExternalMod {
     // We bail on the first error, but that error does not cause a fatal error... (1)
-    let result: PResult<'_, _> = try {
+    let result: Result<_, ModError<'_>> = try {
         // Extract the file path and the new ownership.
-        let mp = mod_file_path(sess, ident, span, &attrs, &module.dir_path, dir_ownership)?;
+        let mp = mod_file_path(sess, ident, &attrs, &module.dir_path, dir_ownership)?;
         dir_ownership = mp.dir_ownership;
 
         // Ensure file paths are acyclic.
-        error_on_circular_module(&sess.parse_sess, span, &mp.file_path, &module.file_path_stack)?;
+        if let Some(pos) = module.file_path_stack.iter().position(|p| p == &mp.file_path) {
+            Err(ModError::CircularInclusion(module.file_path_stack[pos..].to_vec()))?;
+        }
 
         // Actually parse the external file as a module.
         let mut parser = new_parser_from_file(&sess.parse_sess, &mp.file_path, Some(span));
-        let (mut inner_attrs, items, inner_span) = parser.parse_mod(&token::Eof)?;
+        let (mut inner_attrs, items, inner_span) =
+            parser.parse_mod(&token::Eof).map_err(|err| ModError::ParserError(err))?;
         attrs.append(&mut inner_attrs);
         (items, inner_span, mp.file_path)
     };
     // (1) ...instead, we return a dummy module.
-    let (items, inner_span, file_path) = result.map_err(|mut err| err.emit()).unwrap_or_default();
+    let (items, inner_span, file_path) =
+        result.map_err(|err| err.report(sess, span)).unwrap_or_default();
 
     // Extract the directory path for submodules of the module.
     let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
@@ -73,62 +77,64 @@ pub struct ModulePathSuccess {
     ParsedExternalMod { items, inner_span, file_path, dir_path, dir_ownership }
 }
 
-fn error_on_circular_module<'a>(
-    sess: &'a ParseSess,
-    span: Span,
-    file_path: &Path,
-    file_path_stack: &[PathBuf],
-) -> PResult<'a, ()> {
-    if let Some(i) = file_path_stack.iter().position(|p| *p == file_path) {
-        let mut err = String::from("circular modules: ");
-        for p in &file_path_stack[i..] {
-            err.push_str(&p.to_string_lossy());
-            err.push_str(" -> ");
-        }
-        err.push_str(&file_path.to_string_lossy());
-        return Err(sess.span_diagnostic.struct_span_err(span, &err[..]));
-    }
-    Ok(())
-}
-
 crate fn mod_dir_path(
     sess: &Session,
     ident: Ident,
     attrs: &[Attribute],
     module: &ModuleData,
     mut dir_ownership: DirOwnership,
+    inline: Inline,
 ) -> (PathBuf, DirOwnership) {
-    let mut dir_path = module.dir_path.clone();
-    if let Some(file_path) = sess.first_attr_value_str_by_name(attrs, sym::path) {
-        dir_path.push(&*file_path.as_str());
-        dir_ownership = DirOwnership::Owned { relative: None };
-    } else {
-        // We have to push on the current module name in the case of relative
-        // paths in order to ensure that any additional module paths from inline
-        // `mod x { ... }` come after the relative extension.
-        //
-        // For example, a `mod z { ... }` inside `x/y.rs` should set the current
-        // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
-        if let DirOwnership::Owned { relative } = &mut dir_ownership {
-            if let Some(ident) = relative.take() {
-                // Remove the relative offset.
-                dir_path.push(&*ident.as_str());
+    match inline {
+        Inline::Yes => {
+            if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) {
+                // For inline modules file path from `#[path]` is actually the directory path
+                // for historical reasons, so we don't pop the last segment here.
+                return (file_path, DirOwnership::Owned { relative: None });
             }
+
+            // We have to push on the current module name in the case of relative
+            // paths in order to ensure that any additional module paths from inline
+            // `mod x { ... }` come after the relative extension.
+            //
+            // For example, a `mod z { ... }` inside `x/y.rs` should set the current
+            // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
+            let mut dir_path = module.dir_path.clone();
+            if let DirOwnership::Owned { relative } = &mut dir_ownership {
+                if let Some(ident) = relative.take() {
+                    // Remove the relative offset.
+                    dir_path.push(&*ident.as_str());
+                }
+            }
+            dir_path.push(&*ident.as_str());
+
+            (dir_path, dir_ownership)
         }
-        dir_path.push(&*ident.as_str());
-    }
+        Inline::No => {
+            // FIXME: This is a subset of `parse_external_mod` without actual parsing,
+            // check whether the logic for unloaded, loaded and inline modules can be unified.
+            let file_path = mod_file_path(sess, ident, &attrs, &module.dir_path, dir_ownership)
+                .map(|mp| {
+                    dir_ownership = mp.dir_ownership;
+                    mp.file_path
+                })
+                .unwrap_or_default();
+
+            // Extract the directory path for submodules of the module.
+            let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
 
-    (dir_path, dir_ownership)
+            (dir_path, dir_ownership)
+        }
+    }
 }
 
 fn mod_file_path<'a>(
     sess: &'a Session,
     ident: Ident,
-    span: Span,
     attrs: &[Attribute],
     dir_path: &Path,
     dir_ownership: DirOwnership,
-) -> PResult<'a, ModulePathSuccess> {
+) -> Result<ModulePathSuccess, ModError<'a>> {
     if let Some(file_path) = mod_file_path_from_attr(sess, attrs, dir_path) {
         // All `#[path]` files are treated as though they are a `mod.rs` file.
         // This means that `mod foo;` declarations inside `#[path]`-included
@@ -145,32 +151,16 @@ fn mod_file_path<'a>(
         DirOwnership::Owned { relative } => relative,
         DirOwnership::UnownedViaBlock => None,
     };
-    let ModulePath { path_exists, name, result } =
-        default_submod_path(&sess.parse_sess, ident, span, relative, dir_path);
+    let result = default_submod_path(&sess.parse_sess, ident, relative, dir_path);
     match dir_ownership {
-        DirOwnership::Owned { .. } => Ok(result?),
-        DirOwnership::UnownedViaBlock => {
-            let _ = result.map_err(|mut err| err.cancel());
-            error_decl_mod_in_block(&sess.parse_sess, span, path_exists, &name)
-        }
+        DirOwnership::Owned { .. } => result,
+        DirOwnership::UnownedViaBlock => Err(ModError::ModInBlock(match result {
+            Ok(_) | Err(ModError::MultipleCandidates(..)) => Some(ident),
+            _ => None,
+        })),
     }
 }
 
-fn error_decl_mod_in_block<'a, T>(
-    sess: &'a ParseSess,
-    span: Span,
-    path_exists: bool,
-    name: &str,
-) -> PResult<'a, T> {
-    let msg = "Cannot declare a non-inline module inside a block unless it has a path attribute";
-    let mut err = sess.span_diagnostic.struct_span_err(span, msg);
-    if path_exists {
-        let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
-        err.span_note(span, &msg);
-    }
-    Err(err)
-}
-
 /// Derive a submodule path from the first found `#[path = "path_string"]`.
 /// The provided `dir_path` is joined with the `path_string`.
 fn mod_file_path_from_attr(
@@ -179,8 +169,7 @@ fn mod_file_path_from_attr(
     dir_path: &Path,
 ) -> Option<PathBuf> {
     // Extract path string from first `#[path = "path_string"]` attribute.
-    let path_string = sess.first_attr_value_str_by_name(attrs, sym::path)?;
-    let path_string = path_string.as_str();
+    let path_string = sess.first_attr_value_str_by_name(attrs, sym::path)?.as_str();
 
     // On windows, the base path might have the form
     // `\\?\foo\bar` in which case it does not tolerate
@@ -197,10 +186,9 @@ fn mod_file_path_from_attr(
 pub fn default_submod_path<'a>(
     sess: &'a ParseSess,
     ident: Ident,
-    span: Span,
     relative: Option<Ident>,
     dir_path: &Path,
-) -> ModulePath<'a> {
+) -> Result<ModulePathSuccess, ModError<'a>> {
     // If we're in a foo.rs file instead of a mod.rs file,
     // we need to look for submodules in
     // `./foo/<ident>.rs` and `./foo/<ident>/mod.rs` rather than
@@ -222,7 +210,7 @@ pub fn default_submod_path<'a>(
     let default_exists = sess.source_map().file_exists(&default_path);
     let secondary_exists = sess.source_map().file_exists(&secondary_path);
 
-    let result = match (default_exists, secondary_exists) {
+    match (default_exists, secondary_exists) {
         (true, false) => Ok(ModulePathSuccess {
             file_path: default_path,
             dir_ownership: DirOwnership::Owned { relative: Some(ident) },
@@ -231,35 +219,63 @@ pub fn default_submod_path<'a>(
             file_path: secondary_path,
             dir_ownership: DirOwnership::Owned { relative: None },
         }),
-        (false, false) => {
-            let mut err = struct_span_err!(
-                sess.span_diagnostic,
-                span,
-                E0583,
-                "file not found for module `{}`",
-                mod_name,
-            );
-            err.help(&format!(
-                "to create the module `{}`, create file \"{}\"",
-                mod_name,
-                default_path.display(),
-            ));
-            Err(err)
-        }
-        (true, true) => {
-            let mut err = struct_span_err!(
-                sess.span_diagnostic,
-                span,
-                E0761,
-                "file for module `{}` found at both {} and {}",
-                mod_name,
-                default_path_str,
-                secondary_path_str,
-            );
-            err.help("delete or rename one of them to remove the ambiguity");
-            Err(err)
-        }
-    };
+        (false, false) => Err(ModError::FileNotFound(ident, default_path)),
+        (true, true) => Err(ModError::MultipleCandidates(ident, default_path, secondary_path)),
+    }
+}
 
-    ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }
+impl ModError<'_> {
+    fn report(self, sess: &Session, span: Span) {
+        let diag = &sess.parse_sess.span_diagnostic;
+        match self {
+            ModError::CircularInclusion(file_paths) => {
+                let mut msg = String::from("circular modules: ");
+                for file_path in &file_paths {
+                    msg.push_str(&file_path.display().to_string());
+                    msg.push_str(" -> ");
+                }
+                msg.push_str(&file_paths[0].display().to_string());
+                diag.struct_span_err(span, &msg)
+            }
+            ModError::ModInBlock(ident) => {
+                let msg = "cannot declare a non-inline module inside a block unless it has a path attribute";
+                let mut err = diag.struct_span_err(span, msg);
+                if let Some(ident) = ident {
+                    let note =
+                        format!("maybe `use` the module `{}` instead of redeclaring it", ident);
+                    err.span_note(span, &note);
+                }
+                err
+            }
+            ModError::FileNotFound(ident, default_path) => {
+                let mut err = struct_span_err!(
+                    diag,
+                    span,
+                    E0583,
+                    "file not found for module `{}`",
+                    ident,
+                );
+                err.help(&format!(
+                    "to create the module `{}`, create file \"{}\"",
+                    ident,
+                    default_path.display(),
+                ));
+                err
+            }
+            ModError::MultipleCandidates(ident, default_path, secondary_path) => {
+                let mut err = struct_span_err!(
+                    diag,
+                    span,
+                    E0761,
+                    "file for module `{}` found at both \"{}\" and \"{}\"",
+                    ident,
+                    default_path.display(),
+                    secondary_path.display(),
+                );
+                err.help("delete or rename one of them to remove the ambiguity");
+                err
+            }
+            ModError::ParserError(err) => err,
+        }.emit()
+    }
 }