rust/src/librustc_parse/parser/module.rs

300 lines
12 KiB
Rust
Raw Normal View History

2019-10-08 07:46:06 +00:00
use super::diagnostics::Error;
2019-12-22 22:42:04 +00:00
use super::item::ItemInfo;
use super::Parser;
2019-08-11 16:34:42 +00:00
use crate::{new_sub_parser_from_file, DirectoryOwnership};
use rustc_ast::ast::{self, Attribute, Crate, Ident, ItemKind, Mod};
use rustc_ast::attr;
use rustc_ast::token::{self, TokenKind};
2019-12-05 05:38:06 +00:00
use rustc_errors::PResult;
use rustc_span::source_map::{FileName, SourceMap, Span, DUMMY_SP};
use rustc_span::symbol::sym;
2019-10-11 11:06:36 +00:00
2019-08-11 16:34:42 +00:00
use std::path::{self, Path, PathBuf};
/// Information about the path to a module.
2020-01-11 19:19:57 +00:00
// Public for rustfmt usage.
pub struct ModulePath {
2019-08-11 16:34:42 +00:00
name: String,
path_exists: bool,
pub result: Result<ModulePathSuccess, Error>,
}
2020-01-11 19:19:57 +00:00
// Public for rustfmt usage.
pub struct ModulePathSuccess {
2019-08-11 16:34:42 +00:00
pub path: PathBuf,
pub directory_ownership: DirectoryOwnership,
}
impl<'a> Parser<'a> {
/// Parses a source module as a crate. This is the main entry point for the parser.
2019-10-16 11:23:46 +00:00
pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
2019-08-11 16:34:42 +00:00
let lo = self.token.span;
let krate = Ok(ast::Crate {
attrs: self.parse_inner_attributes()?,
module: self.parse_mod_items(&token::Eof, lo)?,
span: lo.to(self.token.span),
// Filled in by proc_macro_harness::inject()
proc_macros: Vec::new(),
2019-08-11 16:34:42 +00:00
});
krate
}
/// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
pub(super) fn parse_item_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
let in_cfg = crate::config::process_configure_mod(self.sess, self.cfg_mods, attrs);
2019-08-11 16:34:42 +00:00
let id = self.parse_ident()?;
let (module, mut inner_attrs) = if self.eat(&token::Semi) {
2019-08-11 16:34:42 +00:00
if in_cfg && self.recurse_into_file_modules {
// This mod is in an external file. Let's go get it!
2019-08-03 15:42:17 +00:00
let ModulePathSuccess { path, directory_ownership } =
2020-03-07 18:41:24 +00:00
self.submod_path(id, &attrs)?;
self.eval_src_mod(path, directory_ownership, id.to_string(), id.span)?
2019-08-11 16:34:42 +00:00
} else {
(ast::Mod { inner: DUMMY_SP, items: Vec::new(), inline: false }, Vec::new())
2019-08-11 16:34:42 +00:00
}
} else {
let old_directory = self.directory.clone();
self.push_directory(id, &attrs);
2019-08-11 16:34:42 +00:00
self.expect(&token::OpenDelim(token::Brace))?;
let mod_inner_lo = self.token.span;
let inner_attrs = self.parse_inner_attributes()?;
2019-08-11 16:34:42 +00:00
let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
self.directory = old_directory;
(module, inner_attrs)
};
attrs.append(&mut inner_attrs);
Ok((id, ItemKind::Mod(module)))
2019-08-11 16:34:42 +00:00
}
/// Given a termination token, parses all of the items in a module.
fn parse_mod_items(&mut self, term: &TokenKind, inner_lo: Span) -> PResult<'a, Mod> {
let mut items = vec![];
while let Some(item) = self.parse_item()? {
items.push(item);
self.maybe_consume_incorrect_semicolon(&items);
}
if !self.eat(term) {
2019-12-07 02:07:35 +00:00
let token_str = super::token_descr(&self.token);
2019-08-11 16:34:42 +00:00
if !self.maybe_consume_incorrect_semicolon(&items) {
2019-12-31 00:28:10 +00:00
let msg = &format!("expected item, found {}", token_str);
let mut err = self.struct_span_err(self.token.span, msg);
2019-08-11 16:34:42 +00:00
err.span_label(self.token.span, "expected item");
return Err(err);
}
}
let hi = if self.token.span.is_dummy() { inner_lo } else { self.prev_token.span };
2019-08-11 16:34:42 +00:00
2019-12-22 22:42:04 +00:00
Ok(Mod { inner: inner_lo.to(hi), items, inline: true })
2019-08-11 16:34:42 +00:00
}
fn submod_path(
&mut self,
id: ast::Ident,
outer_attrs: &[Attribute],
) -> PResult<'a, ModulePathSuccess> {
if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
2020-03-07 18:20:31 +00:00
let directory_ownership = match path.file_name().and_then(|s| s.to_str()) {
// All `#[path]` files are treated as though they are a `mod.rs` file.
// This means that `mod foo;` declarations inside `#[path]`-included
// files are siblings,
//
// Note that this will produce weirdness when a file named `foo.rs` is
// `#[path]` included and contains a `mod foo;` declaration.
// If you encounter this, it's your own darn fault :P
Some(_) => DirectoryOwnership::Owned { relative: None },
_ => DirectoryOwnership::UnownedViaMod,
};
return Ok(ModulePathSuccess { directory_ownership, path });
2019-08-11 16:34:42 +00:00
}
let relative = match self.directory.ownership {
DirectoryOwnership::Owned { relative } => relative,
2019-12-22 22:42:04 +00:00
DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
2019-08-11 16:34:42 +00:00
};
2019-12-22 22:42:04 +00:00
let paths =
Parser::default_submod_path(id, relative, &self.directory.path, self.sess.source_map());
2019-08-11 16:34:42 +00:00
match self.directory.ownership {
DirectoryOwnership::Owned { .. } => {
2020-03-07 18:41:24 +00:00
paths.result.map_err(|err| self.span_fatal_err(id.span, err))
2019-12-22 22:42:04 +00:00
}
2020-03-07 18:41:24 +00:00
DirectoryOwnership::UnownedViaBlock => self.error_decl_mod_in_block(id.span, paths),
DirectoryOwnership::UnownedViaMod => self.error_cannot_declare_mod_here(id.span, paths),
2020-03-07 18:11:47 +00:00
}
}
2020-03-07 18:15:35 +00:00
fn error_decl_mod_in_block<T>(&self, id_sp: Span, paths: ModulePath) -> PResult<'a, T> {
let msg =
"Cannot declare a non-inline module inside a block unless it has a path attribute";
let mut err = self.struct_span_err(id_sp, msg);
if paths.path_exists {
let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", paths.name);
err.span_note(id_sp, &msg);
}
Err(err)
}
2020-03-07 18:11:47 +00:00
fn error_cannot_declare_mod_here<T>(&self, id_sp: Span, paths: ModulePath) -> PResult<'a, T> {
let mut err = self.struct_span_err(id_sp, "cannot declare a new module at this location");
if !id_sp.is_dummy() {
if let FileName::Real(src_path) = self.sess.source_map().span_to_filename(id_sp) {
if let Some(stem) = src_path.file_stem() {
let mut dest_path = src_path.clone();
dest_path.set_file_name(stem);
dest_path.push("mod.rs");
2019-12-22 22:42:04 +00:00
err.span_note(
id_sp,
&format!(
2020-03-07 18:11:47 +00:00
"maybe move this module `{}` to its own \
directory via `{}`",
src_path.display(),
dest_path.display()
2019-12-22 22:42:04 +00:00
),
);
2019-08-11 16:34:42 +00:00
}
}
}
2020-03-07 18:11:47 +00:00
if paths.path_exists {
err.span_note(
id_sp,
&format!(
"... or maybe `use` the module `{}` instead \
of possibly redeclaring it",
paths.name
),
);
}
Err(err)
2019-08-11 16:34:42 +00:00
}
/// Derive a submodule path from the first found `#[path = "path_string"]`.
/// The provided `dir_path` is joined with the `path_string`.
2020-01-11 19:19:57 +00:00
// Public for rustfmt usage.
pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
// Extract path string from first `#[path = "path_string"]` attribute.
let path_string = attr::first_attr_value_str_by_name(attrs, sym::path)?;
let path_string = path_string.as_str();
// On windows, the base path might have the form
// `\\?\foo\bar` in which case it does not tolerate
// mixed `/` and `\` separators, so canonicalize
// `/` to `\`.
#[cfg(windows)]
let path_string = path_string.replace("/", "\\");
Some(dir_path.join(&*path_string))
2019-08-11 16:34:42 +00:00
}
/// Returns a path to a module.
2020-01-11 19:19:57 +00:00
// Public for rustfmt usage.
pub fn default_submod_path(
2019-08-11 16:34:42 +00:00
id: ast::Ident,
relative: Option<ast::Ident>,
dir_path: &Path,
2019-12-22 22:42:04 +00:00
source_map: &SourceMap,
) -> ModulePath {
2019-08-11 16:34:42 +00:00
// If we're in a foo.rs file instead of a mod.rs file,
// we need to look for submodules in
// `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
// `./<id>.rs` and `./<id>/mod.rs`.
let relative_prefix_string;
let relative_prefix = if let Some(ident) = relative {
relative_prefix_string = format!("{}{}", ident.name, path::MAIN_SEPARATOR);
2019-08-11 16:34:42 +00:00
&relative_prefix_string
} else {
""
};
let mod_name = id.name.to_string();
2019-08-11 16:34:42 +00:00
let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
2019-12-22 22:42:04 +00:00
let secondary_path_str =
format!("{}{}{}mod.rs", relative_prefix, mod_name, path::MAIN_SEPARATOR);
2019-08-11 16:34:42 +00:00
let default_path = dir_path.join(&default_path_str);
let secondary_path = dir_path.join(&secondary_path_str);
let default_exists = source_map.file_exists(&default_path);
let secondary_exists = source_map.file_exists(&secondary_path);
let result = match (default_exists, secondary_exists) {
(true, false) => Ok(ModulePathSuccess {
path: default_path,
2019-12-22 22:42:04 +00:00
directory_ownership: DirectoryOwnership::Owned { relative: Some(id) },
2019-08-11 16:34:42 +00:00
}),
(false, true) => Ok(ModulePathSuccess {
path: secondary_path,
2019-12-22 22:42:04 +00:00
directory_ownership: DirectoryOwnership::Owned { relative: None },
2019-08-11 16:34:42 +00:00
}),
(false, false) => {
Err(Error::FileNotFoundForModule { mod_name: mod_name.clone(), default_path })
}
2019-08-11 16:34:42 +00:00
(true, true) => Err(Error::DuplicatePaths {
mod_name: mod_name.clone(),
default_path: default_path_str,
secondary_path: secondary_path_str,
}),
};
2019-12-22 22:42:04 +00:00
ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }
2019-08-11 16:34:42 +00:00
}
/// Reads a module from a source file.
fn eval_src_mod(
&mut self,
path: PathBuf,
directory_ownership: DirectoryOwnership,
name: String,
id_sp: Span,
) -> PResult<'a, (Mod, Vec<Attribute>)> {
let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
let mut err = String::from("circular modules: ");
let len = included_mod_stack.len();
2019-12-22 22:42:04 +00:00
for p in &included_mod_stack[i..len] {
2019-08-11 16:34:42 +00:00
err.push_str(&p.to_string_lossy());
err.push_str(" -> ");
}
err.push_str(&path.to_string_lossy());
2019-12-30 23:20:41 +00:00
return Err(self.struct_span_err(id_sp, &err[..]));
2019-08-11 16:34:42 +00:00
}
included_mod_stack.push(path.clone());
drop(included_mod_stack);
let mut p0 =
new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
p0.cfg_mods = self.cfg_mods;
let mod_inner_lo = p0.token.span;
let mod_attrs = p0.parse_inner_attributes()?;
let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
m0.inline = false;
self.sess.included_mod_stack.borrow_mut().pop();
Ok((m0, mod_attrs))
}
fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
self.directory.path.push(&*path.as_str());
2019-08-11 16:34:42 +00:00
self.directory.ownership = DirectoryOwnership::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 DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
2019-12-22 22:42:04 +00:00
if let Some(ident) = relative.take() {
// remove the relative offset
self.directory.path.push(&*ident.as_str());
2019-08-11 16:34:42 +00:00
}
}
self.directory.path.push(&*id.as_str());
2019-08-11 16:34:42 +00:00
}
}
}