Skip to content

Commit 957dc8d

Browse files
committed
Auto merge of #46531 - cramertj:no-mo-modrs, r=nikomatsakis
Implement non-mod.rs mod statements Fixes #45385, cc #44660 This will fail tidy right now because it doesn't recognize my UI tests as feature-gate tests. However, I'm not sure if compile-fail will work out either because compile-fail usually requires there to be error patterns in the top-level file, which isn't possible with this feature. What's the recommended way to handle this?
2 parents a12706c + 1d5977b commit 957dc8d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+609
-63
lines changed

src/libsyntax/ext/base.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -687,7 +687,7 @@ impl<'a> ExtCtxt<'a> {
687687
mark: Mark::root(),
688688
depth: 0,
689689
module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
690-
directory_ownership: DirectoryOwnership::Owned,
690+
directory_ownership: DirectoryOwnership::Owned { relative: None },
691691
},
692692
expansions: HashMap::new(),
693693
}

src/libsyntax/ext/expand.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -976,7 +976,8 @@ impl<'a, 'b> Folder for InvocationCollector<'a, 'b> {
976976

977977
if inline_module {
978978
if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, "path") {
979-
self.cx.current_expansion.directory_ownership = DirectoryOwnership::Owned;
979+
self.cx.current_expansion.directory_ownership =
980+
DirectoryOwnership::Owned { relative: None };
980981
module.directory.push(&*path.as_str());
981982
} else {
982983
module.directory.push(&*item.ident.name.as_str());
@@ -988,8 +989,11 @@ impl<'a, 'b> Folder for InvocationCollector<'a, 'b> {
988989
other => PathBuf::from(other.to_string()),
989990
};
990991
let directory_ownership = match path.file_name().unwrap().to_str() {
991-
Some("mod.rs") => DirectoryOwnership::Owned,
992-
_ => DirectoryOwnership::UnownedViaMod(false),
992+
Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
993+
Some(_) => DirectoryOwnership::Owned {
994+
relative: Some(item.ident),
995+
},
996+
None => DirectoryOwnership::UnownedViaMod(false),
993997
};
994998
path.pop();
995999
module.directory = path;

src/libsyntax/ext/source_util.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[tokenstream::T
100100
};
101101
// The file will be added to the code map by the parser
102102
let path = res_rel_file(cx, sp, file);
103-
let directory_ownership = DirectoryOwnership::Owned;
103+
let directory_ownership = DirectoryOwnership::Owned { relative: None };
104104
let p = parse::new_sub_parser_from_file(cx.parse_sess(), &path, directory_ownership, None, sp);
105105

106106
struct ExpandResult<'a> {

src/libsyntax/feature_gate.rs

+32-2
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ use visit::{self, FnKind, Visitor};
3535
use parse::ParseSess;
3636
use symbol::{keywords, Symbol};
3737

38-
use std::env;
38+
use std::{env, path};
3939

4040
macro_rules! set {
4141
(proc_macro) => {{
@@ -438,6 +438,9 @@ declare_features! (
438438

439439
// Resolve absolute paths as paths from other crates
440440
(active, extern_absolute_paths, "1.24.0", Some(44660)),
441+
442+
// `foo.rs` as an alternative to `foo/mod.rs`
443+
(active, non_modrs_mods, "1.24.0", Some(44660)),
441444
);
442445

443446
declare_features! (
@@ -1311,6 +1314,31 @@ fn contains_novel_literal(item: &ast::MetaItem) -> bool {
13111314
}
13121315
}
13131316

1317+
impl<'a> PostExpansionVisitor<'a> {
1318+
fn whole_crate_feature_gates(&mut self) {
1319+
for &(ident, span) in &*self.context.parse_sess.non_modrs_mods.borrow() {
1320+
if !span.allows_unstable() {
1321+
let cx = &self.context;
1322+
let level = GateStrength::Hard;
1323+
let has_feature = cx.features.non_modrs_mods;
1324+
let name = "non_modrs_mods";
1325+
debug!("gate_feature(feature = {:?}, span = {:?}); has? {}",
1326+
name, span, has_feature);
1327+
1328+
if !has_feature && !span.allows_unstable() {
1329+
leveled_feature_err(
1330+
cx.parse_sess, name, span, GateIssue::Language,
1331+
"mod statements in non-mod.rs files are unstable", level
1332+
)
1333+
.help(&format!("on stable builds, rename this file to {}{}mod.rs",
1334+
ident, path::MAIN_SEPARATOR))
1335+
.emit();
1336+
}
1337+
}
1338+
}
1339+
}
1340+
}
1341+
13141342
impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
13151343
fn visit_attribute(&mut self, attr: &ast::Attribute) {
13161344
if !attr.span.allows_unstable() {
@@ -1863,7 +1891,9 @@ pub fn check_crate(krate: &ast::Crate,
18631891
parse_sess: sess,
18641892
plugin_attributes,
18651893
};
1866-
visit::walk_crate(&mut PostExpansionVisitor { context: &ctx }, krate);
1894+
let visitor = &mut PostExpansionVisitor { context: &ctx };
1895+
visitor.whole_crate_feature_gates();
1896+
visit::walk_crate(visitor, krate);
18671897
}
18681898

18691899
#[derive(Clone, Copy, PartialEq, Eq, Hash)]

src/libsyntax/parse/lexer/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,7 @@ mod tests {
17541754
included_mod_stack: RefCell::new(Vec::new()),
17551755
code_map: cm,
17561756
missing_fragment_specifiers: RefCell::new(HashSet::new()),
1757+
non_modrs_mods: RefCell::new(vec![]),
17571758
}
17581759
}
17591760

src/libsyntax/parse/mod.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ pub struct ParseSess {
4747
pub unstable_features: UnstableFeatures,
4848
pub config: CrateConfig,
4949
pub missing_fragment_specifiers: RefCell<HashSet<Span>>,
50+
// Spans where a `mod foo;` statement was included in a non-mod.rs file.
51+
// These are used to issue errors if the non_modrs_mods feature is not enabled.
52+
pub non_modrs_mods: RefCell<Vec<(ast::Ident, Span)>>,
5053
/// Used to determine and report recursive mod inclusions
5154
included_mod_stack: RefCell<Vec<PathBuf>>,
5255
code_map: Rc<CodeMap>,
@@ -70,6 +73,7 @@ impl ParseSess {
7073
missing_fragment_specifiers: RefCell::new(HashSet::new()),
7174
included_mod_stack: RefCell::new(vec![]),
7275
code_map,
76+
non_modrs_mods: RefCell::new(vec![]),
7377
}
7478
}
7579

@@ -86,7 +90,10 @@ pub struct Directory {
8690

8791
#[derive(Copy, Clone)]
8892
pub enum DirectoryOwnership {
89-
Owned,
93+
Owned {
94+
// None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
95+
relative: Option<ast::Ident>,
96+
},
9097
UnownedViaBlock,
9198
UnownedViaMod(bool /* legacy warnings? */),
9299
}

src/libsyntax/parse/parser.rs

+90-42
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,10 @@ impl<'a> Parser<'a> {
514514
restrictions: Restrictions::empty(),
515515
obsolete_set: HashSet::new(),
516516
recurse_into_file_modules,
517-
directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
517+
directory: Directory {
518+
path: PathBuf::new(),
519+
ownership: DirectoryOwnership::Owned { relative: None }
520+
},
518521
root_module_name: None,
519522
expected_tokens: Vec::new(),
520523
token_cursor: TokenCursor {
@@ -5731,7 +5734,7 @@ impl<'a> Parser<'a> {
57315734
fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
57325735
if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
57335736
self.directory.path.push(&path.as_str());
5734-
self.directory.ownership = DirectoryOwnership::Owned;
5737+
self.directory.ownership = DirectoryOwnership::Owned { relative: None };
57355738
} else {
57365739
self.directory.path.push(&id.name.as_str());
57375740
}
@@ -5742,10 +5745,28 @@ impl<'a> Parser<'a> {
57425745
}
57435746

57445747
/// Returns either a path to a module, or .
5745-
pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5748+
pub fn default_submod_path(
5749+
id: ast::Ident,
5750+
relative: Option<ast::Ident>,
5751+
dir_path: &Path,
5752+
codemap: &CodeMap) -> ModulePath
5753+
{
5754+
// If we're in a foo.rs file instead of a mod.rs file,
5755+
// we need to look for submodules in
5756+
// `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
5757+
// `./<id>.rs` and `./<id>/mod.rs`.
5758+
let relative_prefix_string;
5759+
let relative_prefix = if let Some(ident) = relative {
5760+
relative_prefix_string = format!("{}{}", ident.name.as_str(), path::MAIN_SEPARATOR);
5761+
&relative_prefix_string
5762+
} else {
5763+
""
5764+
};
5765+
57465766
let mod_name = id.to_string();
5747-
let default_path_str = format!("{}.rs", mod_name);
5748-
let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5767+
let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
5768+
let secondary_path_str = format!("{}{}{}mod.rs",
5769+
relative_prefix, mod_name, path::MAIN_SEPARATOR);
57495770
let default_path = dir_path.join(&default_path_str);
57505771
let secondary_path = dir_path.join(&secondary_path_str);
57515772
let default_exists = codemap.file_exists(&default_path);
@@ -5754,12 +5775,16 @@ impl<'a> Parser<'a> {
57545775
let result = match (default_exists, secondary_exists) {
57555776
(true, false) => Ok(ModulePathSuccess {
57565777
path: default_path,
5757-
directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5778+
directory_ownership: DirectoryOwnership::Owned {
5779+
relative: Some(id),
5780+
},
57585781
warn: false,
57595782
}),
57605783
(false, true) => Ok(ModulePathSuccess {
57615784
path: secondary_path,
5762-
directory_ownership: DirectoryOwnership::Owned,
5785+
directory_ownership: DirectoryOwnership::Owned {
5786+
relative: None,
5787+
},
57635788
warn: false,
57645789
}),
57655790
(false, false) => Err(Error::FileNotFoundForModule {
@@ -5790,57 +5815,80 @@ impl<'a> Parser<'a> {
57905815
if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
57915816
return Ok(ModulePathSuccess {
57925817
directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5793-
Some("mod.rs") => DirectoryOwnership::Owned,
5818+
Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
5819+
Some(_) => {
5820+
DirectoryOwnership::Owned { relative: Some(id) }
5821+
}
57945822
_ => DirectoryOwnership::UnownedViaMod(true),
57955823
},
57965824
path,
57975825
warn: false,
57985826
});
57995827
}
58005828

5801-
let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5829+
let relative = match self.directory.ownership {
5830+
DirectoryOwnership::Owned { relative } => {
5831+
// Push the usage onto the list of non-mod.rs mod uses.
5832+
// This is used later for feature-gate error reporting.
5833+
if let Some(cur_file_ident) = relative {
5834+
self.sess
5835+
.non_modrs_mods.borrow_mut()
5836+
.push((cur_file_ident, id_sp));
5837+
}
5838+
relative
5839+
},
5840+
DirectoryOwnership::UnownedViaBlock |
5841+
DirectoryOwnership::UnownedViaMod(_) => None,
5842+
};
5843+
let paths = Parser::default_submod_path(
5844+
id, relative, &self.directory.path, self.sess.codemap());
58025845

5803-
if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5804-
let msg =
5805-
"Cannot declare a non-inline module inside a block unless it has a path attribute";
5806-
let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5807-
if paths.path_exists {
5808-
let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5809-
paths.name);
5810-
err.span_note(id_sp, &msg);
5811-
}
5812-
Err(err)
5813-
} else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5814-
if warn {
5815-
if let Ok(result) = paths.result {
5816-
return Ok(ModulePathSuccess { warn: true, ..result });
5846+
match self.directory.ownership {
5847+
DirectoryOwnership::Owned { .. } => {
5848+
paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5849+
},
5850+
DirectoryOwnership::UnownedViaBlock => {
5851+
let msg =
5852+
"Cannot declare a non-inline module inside a block \
5853+
unless it has a path attribute";
5854+
let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5855+
if paths.path_exists {
5856+
let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5857+
paths.name);
5858+
err.span_note(id_sp, &msg);
58175859
}
5860+
Err(err)
58185861
}
5819-
let mut err = self.diagnostic().struct_span_err(id_sp,
5820-
"cannot declare a new module at this location");
5821-
if id_sp != syntax_pos::DUMMY_SP {
5822-
let src_path = self.sess.codemap().span_to_filename(id_sp);
5823-
if let FileName::Real(src_path) = src_path {
5824-
if let Some(stem) = src_path.file_stem() {
5825-
let mut dest_path = src_path.clone();
5826-
dest_path.set_file_name(stem);
5827-
dest_path.push("mod.rs");
5828-
err.span_note(id_sp,
5862+
DirectoryOwnership::UnownedViaMod(warn) => {
5863+
if warn {
5864+
if let Ok(result) = paths.result {
5865+
return Ok(ModulePathSuccess { warn: true, ..result });
5866+
}
5867+
}
5868+
let mut err = self.diagnostic().struct_span_err(id_sp,
5869+
"cannot declare a new module at this location");
5870+
if id_sp != syntax_pos::DUMMY_SP {
5871+
let src_path = self.sess.codemap().span_to_filename(id_sp);
5872+
if let FileName::Real(src_path) = src_path {
5873+
if let Some(stem) = src_path.file_stem() {
5874+
let mut dest_path = src_path.clone();
5875+
dest_path.set_file_name(stem);
5876+
dest_path.push("mod.rs");
5877+
err.span_note(id_sp,
58295878
&format!("maybe move this module `{}` to its own \
58305879
directory via `{}`", src_path.display(),
58315880
dest_path.display()));
5881+
}
58325882
}
58335883
}
5884+
if paths.path_exists {
5885+
err.span_note(id_sp,
5886+
&format!("... or maybe `use` the module `{}` instead \
5887+
of possibly redeclaring it",
5888+
paths.name));
5889+
}
5890+
Err(err)
58345891
}
5835-
if paths.path_exists {
5836-
err.span_note(id_sp,
5837-
&format!("... or maybe `use` the module `{}` instead \
5838-
of possibly redeclaring it",
5839-
paths.name));
5840-
}
5841-
Err(err)
5842-
} else {
5843-
paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
58445892
}
58455893
}
58465894

src/test/compile-fail/directory_ownership/backcompat-warnings.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11-
// error-pattern: cannot declare a new module at this location
12-
// error-pattern: will become a hard error
11+
// error-pattern: mod statements in non-mod.rs files are unstable
1312

1413
#[path="mod_file_not_owning_aux3.rs"]
1514
mod foo;

src/test/compile-fail/directory_ownership/foo/compiletest-ignore-dir

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.

src/test/compile-fail/directory_ownership/mod_file_not_owning.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11-
// error-pattern: cannot declare a new module at this location
11+
// error-pattern: mod statements in non-mod.rs files are unstable
1212

1313
mod mod_file_not_owning_aux1;
1414

src/test/compile-fail/directory_ownership/mod_file_not_owning_aux1/compiletest-ignore-dir

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.

src/test/compile-fail/directory_ownership/unowned_mod_with_path.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11-
// error-pattern: cannot declare a new module at this location
11+
// error-pattern: mod statements in non-mod.rs files are unstable
1212

1313
// This is not a directory owner since the file name is not "mod.rs".
1414
#[path = "mod_file_not_owning_aux1.rs"]

0 commit comments

Comments
 (0)