diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/attr.rs | 4 | ||||
| -rw-r--r-- | src/chains.rs | 2 | ||||
| -rw-r--r-- | src/expr.rs | 6 | ||||
| -rw-r--r-- | src/formatting.rs | 3 | ||||
| -rw-r--r-- | src/items.rs | 17 | ||||
| -rw-r--r-- | src/macros.rs | 14 | ||||
| -rw-r--r-- | src/matches.rs | 2 | ||||
| -rw-r--r-- | src/modules.rs | 125 | ||||
| -rw-r--r-- | src/modules/visitor.rs | 12 | ||||
| -rw-r--r-- | src/patterns.rs | 4 | ||||
| -rw-r--r-- | src/spanned.rs | 2 | ||||
| -rw-r--r-- | src/stmt.rs | 2 | ||||
| -rw-r--r-- | src/syntux/parser.rs | 75 | ||||
| -rw-r--r-- | src/syntux/session.rs | 7 | ||||
| -rw-r--r-- | src/types.rs | 2 | ||||
| -rw-r--r-- | src/utils.rs | 2 | ||||
| -rw-r--r-- | src/visitor.rs | 12 |
17 files changed, 156 insertions, 135 deletions
diff --git a/src/attr.rs b/src/attr.rs index b913d917b30..74195eb2a94 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -23,7 +23,7 @@ pub(crate) fn get_attrs_from_stmt(stmt: &ast::Stmt) -> Option<&[ast::Attribute]> ast::StmtKind::Local(ref local) => Some(&local.attrs), ast::StmtKind::Item(ref item) => Some(&item.attrs), ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(&expr.attrs), - ast::StmtKind::Mac(ref mac) => Some(&mac.2), + ast::StmtKind::MacCall(ref mac) => Some(&mac.2), ast::StmtKind::Empty => None, } } @@ -33,7 +33,7 @@ pub(crate) fn get_span_without_attrs(stmt: &ast::Stmt) -> Span { ast::StmtKind::Local(ref local) => local.span, ast::StmtKind::Item(ref item) => item.span, ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => expr.span, - ast::StmtKind::Mac(ref mac) => { + ast::StmtKind::MacCall(ref mac) => { let (ref mac, _, _) = **mac; mac.span() } diff --git a/src/chains.rs b/src/chains.rs index a7a9127cbbd..e8becfbab8a 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -403,7 +403,7 @@ impl Chain { fn convert_try(expr: &ast::Expr, context: &RewriteContext<'_>) -> ast::Expr { match expr.kind { - ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => { + ast::ExprKind::MacCall(ref mac) if context.config.use_try_shorthand() => { if let Some(subexpr) = convert_try_mac(mac, context) { subexpr } else { diff --git a/src/expr.rs b/src/expr.rs index 608425b34bd..6a581e6c054 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -199,7 +199,7 @@ pub(crate) fn format_expr( ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => { rewrite_chain(expr, context, shape) } - ast::ExprKind::Mac(ref mac) => { + ast::ExprKind::MacCall(ref mac) => { rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| { wrap_str( context.snippet(expr.span).to_owned(), @@ -1312,7 +1312,7 @@ pub(crate) fn can_be_overflowed_expr( context.config.overflow_delimited_expr() || (context.use_block_indent() && args_len == 1) } - ast::ExprKind::Mac(ref mac) => { + ast::ExprKind::MacCall(ref mac) => { match ( syntax::ast::MacDelimiter::from_token(mac.args.delim()), context.config.overflow_delimited_expr(), @@ -1340,7 +1340,7 @@ pub(crate) fn can_be_overflowed_expr( pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool { match expr.kind { - ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true, + ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true, ast::ExprKind::AddrOf(_, _, ref expr) | ast::ExprKind::Box(ref expr) | ast::ExprKind::Try(ref expr) diff --git a/src/formatting.rs b/src/formatting.rs index 104e631f441..583d72272f2 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -91,10 +91,11 @@ fn format_project<T: FormatHandler>( let files = modules::ModResolver::new( &context.parse_session, directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaMod), - !(input_is_stdin || config.skip_children()), + !input_is_stdin && !config.skip_children(), ) .visit_crate(&krate) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; + for (path, module) in files { let should_ignore = !input_is_stdin && context.ignore_file(&path); if (config.skip_children() && path != main_file) || should_ignore { diff --git a/src/items.rs b/src/items.rs index 9bd254250cc..31c1c193c4b 100644 --- a/src/items.rs +++ b/src/items.rs @@ -645,7 +645,7 @@ impl<'a> FmtVisitor<'a> { { a.ident.as_str().cmp(&b.ident.as_str()) } - (Const(..), Const(..)) | (Macro(..), Macro(..)) => { + (Const(..), Const(..)) | (MacCall(..), MacCall(..)) => { a.ident.as_str().cmp(&b.ident.as_str()) } (Fn(..), Fn(..)) => a.span.lo().cmp(&b.span.lo()), @@ -655,8 +655,8 @@ impl<'a> FmtVisitor<'a> { (_, TyAlias(..)) => Ordering::Greater, (Const(..), _) => Ordering::Less, (_, Const(..)) => Ordering::Greater, - (Macro(..), _) => Ordering::Less, - (_, Macro(..)) => Ordering::Greater, + (MacCall(..), _) => Ordering::Less, + (_, MacCall(..)) => Ordering::Greater, }); let mut prev_kind = None; for (buf, item) in buffer { @@ -868,10 +868,9 @@ fn format_impl_ref_and_type( let generics_str = rewrite_generics(context, "impl", generics, shape)?; result.push_str(&generics_str); - let polarity_str = if polarity == ast::ImplPolarity::Negative { - "!" - } else { - "" + let polarity_str = match polarity { + ast::ImplPolarity::Negative(_) => "!", + ast::ImplPolarity::Positive => "", }; if let Some(ref trait_ref) = *trait_ref { @@ -1730,7 +1729,7 @@ impl<'a> StaticParts<'a> { ty, mutability, expr_opt: expr.as_ref(), - defaultness: defaultness, + defaultness, span: item.span, } } @@ -3120,7 +3119,7 @@ impl Rewrite for ast::ForeignItem { rewrite_ident(context, self.ident) )) } - ast::ForeignItemKind::Macro(ref mac) => { + ast::ForeignItemKind::MacCall(ref mac) => { rewrite_macro(mac, None, context, shape, MacroPosition::Item) } }?; diff --git a/src/macros.rs b/src/macros.rs index 482b680310c..240a33773c0 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -187,7 +187,7 @@ fn return_macro_parse_failure_fallback( } pub(crate) fn rewrite_macro( - mac: &ast::Mac, + mac: &ast::MacCall, extra_ident: Option<ast::Ident>, context: &RewriteContext<'_>, shape: Shape, @@ -239,7 +239,7 @@ fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> { } fn rewrite_macro_inner( - mac: &ast::Mac, + mac: &ast::MacCall, extra_ident: Option<ast::Ident>, context: &RewriteContext<'_>, shape: Shape, @@ -495,7 +495,7 @@ pub(crate) fn rewrite_macro_def( None => return snippet, }; - let mut result = if def.legacy { + let mut result = if def.macro_rules { String::from("macro_rules!") } else { format!("{}macro", format_visibility(context, vis)) @@ -504,7 +504,7 @@ pub(crate) fn rewrite_macro_def( result += " "; result += rewrite_ident(context, ident); - let multi_branch_style = def.legacy || parsed_def.branches.len() != 1; + let multi_branch_style = def.macro_rules || parsed_def.branches.len() != 1; let arm_shape = if multi_branch_style { shape @@ -537,7 +537,7 @@ pub(crate) fn rewrite_macro_def( .collect::<Vec<_>>(); let fmt = ListFormatting::new(arm_shape, context.config) - .separator(if def.legacy { ";" } else { "" }) + .separator(if def.macro_rules { ";" } else { "" }) .trailing_separator(SeparatorTactic::Always) .preserve_newline(true); @@ -1186,7 +1186,7 @@ fn next_space(tok: &TokenKind) -> SpaceState { /// Tries to convert a macro use into a short hand try expression. Returns `None` /// when the macro is not an instance of `try!` (or parsing the inner expression /// failed). -pub(crate) fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext<'_>) -> Option<ast::Expr> { +pub(crate) fn convert_try_mac(mac: &ast::MacCall, context: &RewriteContext<'_>) -> Option<ast::Expr> { let path = &pprust::path_to_string(&mac.path); if path == "try" || path == "r#try" { let ts = mac.args.inner_tokens(); @@ -1203,7 +1203,7 @@ pub(crate) fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext<'_>) -> O } } -pub(crate) fn macro_style(mac: &ast::Mac, context: &RewriteContext<'_>) -> DelimToken { +pub(crate) fn macro_style(mac: &ast::MacCall, context: &RewriteContext<'_>) -> DelimToken { let snippet = context.snippet(mac.span()); let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value()); let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value()); diff --git a/src/matches.rs b/src/matches.rs index 792b3bfd466..5f2d9d9e85e 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -559,7 +559,7 @@ fn can_flatten_block_around_this(body: &ast::Expr) -> bool { | ast::ExprKind::Array(..) | ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) - | ast::ExprKind::Mac(..) + | ast::ExprKind::MacCall(..) | ast::ExprKind::Struct(..) | ast::ExprKind::Tup(..) => true, ast::ExprKind::AddrOf(_, _, ref expr) diff --git a/src/modules.rs b/src/modules.rs index bb0effedfa8..b7e110d6013 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -32,7 +32,7 @@ pub(crate) struct ModResolver<'ast, 'sess> { #[derive(Clone)] enum SubModKind<'a, 'ast> { /// `mod foo;` - External(PathBuf, DirectoryOwnership), + External(PathBuf, DirectoryOwnership, Cow<'ast, ast::Mod>), /// `mod foo;` with multiple sources. MultiExternal(Vec<(PathBuf, DirectoryOwnership, Cow<'ast, ast::Mod>)>), /// `#[path = "..."] mod foo {}` @@ -82,7 +82,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { /// Visit `cfg_if` macro and look for module declarations. fn visit_cfg_if(&mut self, item: Cow<'ast, ast::Item>) -> Result<(), String> { - let mut visitor = visitor::CfgIfVisitor::new(self.parse_sess, &self.directory); + let mut visitor = visitor::CfgIfVisitor::new(self.parse_sess); visitor.visit_item(&item); for module_item in visitor.mods() { if let ast::ItemKind::Mod(ref sub_mod) = module_item.item.kind { @@ -150,7 +150,6 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { // mod foo; // Look for an extern file. self.find_external_module(item.ident, &item.attrs, sub_mod) - .map(Some) } else { // An internal module (`mod foo { /* ... */ }`); if let Some(path) = find_path_value(&item.attrs) { @@ -165,15 +164,19 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { fn insert_sub_mod( &mut self, sub_mod_kind: SubModKind<'c, 'ast>, - sub_mod: Cow<'ast, ast::Mod>, + _sub_mod: Cow<'ast, ast::Mod>, ) -> Result<(), String> { match sub_mod_kind { - SubModKind::External(mod_path, _) => { - self.file_map.insert(FileName::Real(mod_path), sub_mod); + SubModKind::External(mod_path, _, sub_mod) => { + self.file_map + .entry(FileName::Real(mod_path)) + .or_insert(sub_mod); } SubModKind::MultiExternal(mods) => { for (mod_path, _, sub_mod) in mods { - self.file_map.insert(FileName::Real(mod_path), sub_mod); + self.file_map + .entry(FileName::Real(mod_path)) + .or_insert(sub_mod); } } _ => (), @@ -187,7 +190,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { sub_mod_kind: SubModKind<'c, 'ast>, ) -> Result<(), String> { match sub_mod_kind { - SubModKind::External(mod_path, directory_ownership) => { + SubModKind::External(mod_path, directory_ownership, sub_mod) => { let directory = Directory { path: mod_path.parent().unwrap().to_path_buf(), ownership: directory_ownership, @@ -239,43 +242,97 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { mod_name: ast::Ident, attrs: &[ast::Attribute], sub_mod: &Cow<'ast, ast::Mod>, - ) -> Result<SubModKind<'c, 'ast>, String> { + ) -> Result<Option<SubModKind<'c, 'ast>>, String> { + let relative = match self.directory.ownership { + DirectoryOwnership::Owned { relative } => relative, + DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None, + }; if let Some(path) = Parser::submod_path_from_attr(attrs, &self.directory.path) { - return Ok(SubModKind::External( - path, - DirectoryOwnership::Owned { relative: None }, - )); + if self.parse_sess.is_file_parsed(&path) { + return Ok(None); + } + return match Parser::parse_file_as_module( + self.parse_sess, + &path, + sub_mod.inner, + ) { + Some(m) => Ok(Some(SubModKind::External( + path, + DirectoryOwnership::Owned { relative: None }, + Cow::Owned(m), + ))), + None => Err(format!( + "Failed to find module {} in {:?} {:?}", + mod_name, self.directory.path, relative, + )), + }; } // Look for nested path, like `#[cfg_attr(feature = "foo", path = "bar.rs")]`. let mut mods_outside_ast = self.find_mods_outside_of_ast(attrs, sub_mod); - let relative = match self.directory.ownership { - DirectoryOwnership::Owned { relative } => relative, - DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None, - }; match self .parse_sess .default_submod_path(mod_name, relative, &self.directory.path) .result { Ok(ModulePathSuccess { - path, - directory_ownership, - .. - }) => Ok(if mods_outside_ast.is_empty() { - SubModKind::External(path, directory_ownership) - } else { - mods_outside_ast.push((path, directory_ownership, sub_mod.clone())); - SubModKind::MultiExternal(mods_outside_ast) - }), - Err(_) if !mods_outside_ast.is_empty() => { - Ok(SubModKind::MultiExternal(mods_outside_ast)) + path, ownership, .. + }) => { + let outside_mods_empty = mods_outside_ast.is_empty(); + let should_insert = !mods_outside_ast + .iter() + .any(|(outside_path, _, _)| outside_path == &path); + if self.parse_sess.is_file_parsed(&path) { + if outside_mods_empty { + return Ok(None); + } else { + if should_insert { + mods_outside_ast.push((path, ownership, sub_mod.clone())); + } + return Ok(Some(SubModKind::MultiExternal(mods_outside_ast))); + } + } + match Parser::parse_file_as_module( + self.parse_sess, + &path, + sub_mod.inner, + ) { + Some(m) if outside_mods_empty => Ok(Some(SubModKind::External( + path, + ownership, + Cow::Owned(m), + ))), + Some(m) => { + mods_outside_ast.push((path.clone(), ownership, Cow::Owned(m))); + if should_insert { + mods_outside_ast.push((path, ownership, sub_mod.clone())); + } + Ok(Some(SubModKind::MultiExternal(mods_outside_ast))) + } + None if outside_mods_empty => Err(format!( + "Failed to find module {} in {:?} {:?}", + mod_name, self.directory.path, relative, + )), + None => { + if should_insert { + mods_outside_ast.push((path, ownership, sub_mod.clone())); + } + Ok(Some(SubModKind::MultiExternal(mods_outside_ast))) + }, + } + } + Err(mut e) if !mods_outside_ast.is_empty() => { + e.cancel(); + Ok(Some(SubModKind::MultiExternal(mods_outside_ast))) + } + Err(mut e) => { + e.cancel(); + Err(format!( + "Failed to find module {} in {:?} {:?}", + mod_name, self.directory.path, relative, + )) } - Err(_) => Err(format!( - "Failed to find module {} in {:?} {:?}", - mod_name, self.directory.path, relative, - )), } } @@ -329,9 +386,9 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { continue; } let m = match Parser::parse_file_as_module( - self.directory.ownership, self.parse_sess, &actual_path, + sub_mod.inner, ) { Some(m) => m, None => continue, @@ -364,7 +421,7 @@ fn find_path_value(attrs: &[ast::Attribute]) -> Option<Symbol> { fn is_cfg_if(item: &ast::Item) -> bool { match item.kind { - ast::ItemKind::Mac(ref mac) => { + ast::ItemKind::MacCall(ref mac) => { if let Some(first_segment) = mac.path.segments.first() { if first_segment.ident.name == *CFG_IF { return true; diff --git a/src/modules/visitor.rs b/src/modules/visitor.rs index ad9111f7a9f..b4d32747b17 100644 --- a/src/modules/visitor.rs +++ b/src/modules/visitor.rs @@ -3,7 +3,7 @@ use syntax::ast; use syntax::visit::Visitor; use crate::attr::MetaVisitor; -use crate::syntux::parser::{Directory, Parser}; +use crate::syntux::parser::Parser; use crate::syntux::session::ParseSess; pub(crate) struct ModItem { @@ -14,15 +14,13 @@ pub(crate) struct ModItem { pub(crate) struct CfgIfVisitor<'a> { parse_sess: &'a ParseSess, mods: Vec<ModItem>, - base_dir: &'a Directory, } impl<'a> CfgIfVisitor<'a> { - pub(crate) fn new(parse_sess: &'a ParseSess, base_dir: &'a Directory) -> CfgIfVisitor<'a> { + pub(crate) fn new(parse_sess: &'a ParseSess) -> CfgIfVisitor<'a> { CfgIfVisitor { mods: vec![], parse_sess, - base_dir, } } @@ -32,7 +30,7 @@ impl<'a> CfgIfVisitor<'a> { } impl<'a, 'ast: 'a> Visitor<'ast> for CfgIfVisitor<'a> { - fn visit_mac(&mut self, mac: &'ast ast::Mac) { + fn visit_mac(&mut self, mac: &'ast ast::MacCall) { match self.visit_mac_inner(mac) { Ok(()) => (), Err(e) => debug!("{}", e), @@ -41,7 +39,7 @@ impl<'a, 'ast: 'a> Visitor<'ast> for CfgIfVisitor<'a> { } impl<'a, 'ast: 'a> CfgIfVisitor<'a> { - fn visit_mac_inner(&mut self, mac: &'ast ast::Mac) -> Result<(), &'static str> { + fn visit_mac_inner(&mut self, mac: &'ast ast::MacCall) -> Result<(), &'static str> { // Support both: // ``` // extern crate cfg_if; @@ -64,7 +62,7 @@ impl<'a, 'ast: 'a> CfgIfVisitor<'a> { } }; - let items = Parser::parse_cfg_if(self.parse_sess, mac, &self.base_dir)?; + let items = Parser::parse_cfg_if(self.parse_sess, mac)?; self.mods .append(&mut items.into_iter().map(|item| ModItem { item }).collect()); diff --git a/src/patterns.rs b/src/patterns.rs index 1ef3bd5337b..0c57f111761 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -40,7 +40,7 @@ fn is_short_pattern_inner(pat: &ast::Pat) -> bool { ast::PatKind::Rest | ast::PatKind::Wild | ast::PatKind::Lit(_) => true, ast::PatKind::Ident(_, _, ref pat) => pat.is_none(), ast::PatKind::Struct(..) - | ast::PatKind::Mac(..) + | ast::PatKind::MacCall(..) | ast::PatKind::Slice(..) | ast::PatKind::Path(..) | ast::PatKind::Range(..) => false, @@ -231,7 +231,7 @@ impl Rewrite for Pat { PatKind::Struct(ref path, ref fields, ellipsis) => { rewrite_struct_pat(path, fields, ellipsis, self.span, context, shape) } - PatKind::Mac(ref mac) => rewrite_macro(mac, None, context, shape, MacroPosition::Pat), + PatKind::MacCall(ref mac) => rewrite_macro(mac, None, context, shape, MacroPosition::Pat), PatKind::Paren(ref pat) => pat .rewrite(context, shape.offset_left(1)?.sub_width(1)?) .map(|inner_pat| format!("({})", inner_pat)), diff --git a/src/spanned.rs b/src/spanned.rs index 324594f7760..618a8b179fd 100644 --- a/src/spanned.rs +++ b/src/spanned.rs @@ -66,7 +66,7 @@ impl Spanned for ast::Stmt { ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => { mk_sp(expr.span().lo(), self.span.hi()) } - ast::StmtKind::Mac(ref mac) => { + ast::StmtKind::MacCall(ref mac) => { let (_, _, ref attrs) = **mac; if attrs.is_empty() { self.span diff --git a/src/stmt.rs b/src/stmt.rs index c9bfe64d59d..30006512906 100644 --- a/src/stmt.rs +++ b/src/stmt.rs @@ -106,7 +106,7 @@ fn format_stmt( let shape = shape.sub_width(suffix.len())?; format_expr(ex, expr_type, context, shape).map(|s| s + suffix) } - ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) | ast::StmtKind::Empty => None, + ast::StmtKind::MacCall(..) | ast::StmtKind::Item(..) | ast::StmtKind::Empty => None, }; result.and_then(|res| recover_comment_removed(res, stmt.span(), context)) } diff --git a/src/syntux/parser.rs b/src/syntux/parser.rs index 6e3cd5e2375..7859c9e38aa 100644 --- a/src/syntux/parser.rs +++ b/src/syntux/parser.rs @@ -2,16 +2,16 @@ use std::panic::{catch_unwind, AssertUnwindSafe}; use std::path::{Path, PathBuf}; use rustc_errors::{Diagnostic, PResult}; -use rustc_parse::{new_sub_parser_from_file, parser::Parser as RawParser}; -use rustc_span::{symbol::kw, Span, DUMMY_SP}; +use rustc_parse::{new_parser_from_file, parser::Parser as RawParser}; +use rustc_span::{symbol::kw, Span}; use syntax::ast; use syntax::token::{DelimToken, TokenKind}; use crate::syntux::session::ParseSess; use crate::{Config, Input}; -pub(crate) type DirectoryOwnership = rustc_parse::DirectoryOwnership; -pub(crate) type ModulePathSuccess = rustc_parse::parser::ModulePathSuccess; +pub(crate) type DirectoryOwnership = rustc_expand::module::DirectoryOwnership; +pub(crate) type ModulePathSuccess = rustc_expand::module::ModulePathSuccess; #[derive(Clone)] pub(crate) struct Directory { @@ -19,15 +19,6 @@ pub(crate) struct Directory { pub(crate) ownership: DirectoryOwnership, } -impl<'a> Directory { - fn to_syntax_directory(&'a self) -> rustc_parse::Directory { - rustc_parse::Directory { - path: self.path.clone(), - ownership: self.ownership, - } - } -} - /// A parser for Rust source code. pub(crate) struct Parser<'a> { parser: RawParser<'a>, @@ -68,11 +59,10 @@ impl<'a> ParserBuilder<'a> { } pub(crate) fn build(self) -> Result<Parser<'a>, ParserError> { - let config = self.config.ok_or(ParserError::NoConfig)?; let sess = self.sess.ok_or(ParserError::NoParseSess)?; let input = self.input.ok_or(ParserError::NoInput)?; - let mut parser = match Self::parser(sess.inner(), input, self.directory_ownership) { + let parser = match Self::parser(sess.inner(), input) { Ok(p) => p, Err(db) => { sess.emit_diagnostics(db); @@ -80,47 +70,26 @@ impl<'a> ParserBuilder<'a> { } }; - parser.cfg_mods = false; - if config.skip_children() { - parser.recurse_into_file_modules = false; - } - Ok(Parser { parser, sess }) } fn parser( sess: &'a rustc_session::parse::ParseSess, input: Input, - directory_ownership: Option<DirectoryOwnership>, ) -> Result<rustc_parse::parser::Parser<'a>, Vec<Diagnostic>> { match input { - Input::File(ref file) => Ok(if let Some(directory_ownership) = directory_ownership { - rustc_parse::new_sub_parser_from_file( - sess, - file, - directory_ownership, - None, - DUMMY_SP, - ) - } else { - rustc_parse::new_parser_from_file(sess, file) - }), + Input::File(ref file) => Ok(new_parser_from_file(sess, file, None)), Input::Text(text) => rustc_parse::maybe_new_parser_from_source_str( sess, rustc_span::FileName::Custom("stdin".to_owned()), text, - ) - .map(|mut parser| { - parser.recurse_into_file_modules = false; - parser - }), + ), } } } #[derive(Debug, PartialEq)] pub(crate) enum ParserError { - NoConfig, NoParseSess, NoInput, ParserCreationError, @@ -130,7 +99,7 @@ pub(crate) enum ParserError { impl<'a> Parser<'a> { pub(crate) fn submod_path_from_attr(attrs: &[ast::Attribute], path: &Path) -> Option<PathBuf> { - rustc_parse::parser::Parser::submod_path_from_attr(attrs, path) + rustc_expand::module::submod_path_from_attr(attrs, path) } // FIXME(topecongiro) Use the method from libsyntax[1] once it become public. @@ -176,6 +145,11 @@ impl<'a> Parser<'a> { items.push(item); } + // Handle extern mods that are empty files/files with only comments. + if items.is_empty() { + parser.parse_mod(&TokenKind::Eof)?; + } + let hi = if parser.token.span.is_dummy() { span } else { @@ -190,15 +164,13 @@ impl<'a> Parser<'a> { } pub(crate) fn parse_file_as_module( - directory_ownership: DirectoryOwnership, sess: &'a ParseSess, path: &Path, + span: Span, ) -> Option<ast::Mod> { - let result = catch_unwind(AssertUnwindSafe(|| { - let mut parser = - new_sub_parser_from_file(sess.inner(), &path, directory_ownership, None, DUMMY_SP); + let result = catch_unwind(AssertUnwindSafe(|| { + let mut parser = new_parser_from_file(sess.inner(), &path, Some(span)); - parser.cfg_mods = false; let lo = parser.token.span; // FIXME(topecongiro) Format inner attributes (#3606). match Parser::parse_inner_attrs(&mut parser) { @@ -267,11 +239,10 @@ impl<'a> Parser<'a> { pub(crate) fn parse_cfg_if( sess: &'a ParseSess, - mac: &'a ast::Mac, - base_dir: &Directory, + mac: &'a ast::MacCall, ) -> Result<Vec<ast::Item>, &'static str> { match catch_unwind(AssertUnwindSafe(|| { - Parser::parse_cfg_if_inner(sess, mac, base_dir) + Parser::parse_cfg_if_inner(sess, mac) })) { Ok(Ok(items)) => Ok(items), Ok(err @ Err(_)) => err, @@ -281,17 +252,11 @@ impl<'a> Parser<'a> { fn parse_cfg_if_inner( sess: &'a ParseSess, - mac: &'a ast::Mac, - base_dir: &Directory, + mac: &'a ast::MacCall, ) -> Result<Vec<ast::Item>, &'static str> { let token_stream = mac.args.inner_tokens(); - let mut parser = rustc_parse::stream_to_parser_with_base_dir( - sess.inner(), - token_stream.clone(), - base_dir.to_syntax_directory(), - ); + let mut parser = rustc_parse::stream_to_parser(sess.inner(),token_stream.clone(),Some("")); - parser.cfg_mods = false; let mut items = vec![]; let mut process_if_cfg = true; diff --git a/src/syntux/session.rs b/src/syntux/session.rs index 9ec85efb109..0e6b0073793 100644 --- a/src/syntux/session.rs +++ b/src/syntux/session.rs @@ -150,12 +150,13 @@ impl ParseSess { id: ast::Ident, relative: Option<ast::Ident>, dir_path: &Path, - ) -> rustc_parse::parser::ModulePath { - rustc_parse::parser::Parser::default_submod_path( + ) -> rustc_expand::module::ModulePath<'_> { + rustc_expand::module::default_submod_path( + &self.parse_sess, id, + rustc_span::DUMMY_SP, relative, dir_path, - self.parse_sess.source_map(), ) } diff --git a/src/types.rs b/src/types.rs index d30693fd388..500ccaf6275 100644 --- a/src/types.rs +++ b/src/types.rs @@ -732,7 +732,7 @@ impl Rewrite for ast::Ty { } ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape), ast::TyKind::Never => Some(String::from("!")), - ast::TyKind::Mac(ref mac) => { + ast::TyKind::MacCall(ref mac) => { rewrite_macro(mac, None, context, shape, MacroPosition::Expression) } ast::TyKind::ImplicitSelf => Some(String::from("")), diff --git a/src/utils.rs b/src/utils.rs index 7e287a4b80a..494d4d0e33f 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -456,7 +456,7 @@ pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool { // parens, braces, and brackets in its idiomatic formatting. pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool { match expr.kind { - ast::ExprKind::Mac(..) + ast::ExprKind::MacCall(..) | ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Array(..) diff --git a/src/visitor.rs b/src/visitor.rs index fe489f32a16..7dd594a304f 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -151,7 +151,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.push_rewrite(stmt.span(), rewrite) } } - ast::StmtKind::Mac(ref mac) => { + ast::StmtKind::MacCall(ref mac) => { let (ref mac, _macro_style, ref attrs) = **mac; if self.visit_attrs(attrs, ast::AttrStyle::Outer) { self.push_skipped_with_span( @@ -504,7 +504,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.format_missing_with_indent(source!(self, item.span).lo()); self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline); } - ast::ItemKind::Mac(ref mac) => { + ast::ItemKind::MacCall(ref mac) => { self.visit_mac(mac, Some(item.ident), MacroPosition::Item); } ast::ItemKind::ForeignMod(ref foreign_mod) => { @@ -619,7 +619,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ); self.push_rewrite(ti.span, rewrite); } - ast::AssocItemKind::Macro(ref mac) => { + ast::AssocItemKind::MacCall(ref mac) => { self.visit_mac(mac, Some(ti.ident), MacroPosition::Item); } } @@ -669,7 +669,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { Some(generic_bounds) => rewrite_opaque_impl_type( &self.get_context(), ii.ident, - &generics, + generics, generic_bounds, self.block_indent, ), @@ -678,13 +678,13 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { }; self.push_rewrite(ii.span, rewrite); } - ast::AssocItemKind::Macro(ref mac) => { + ast::AssocItemKind::MacCall(ref mac) => { self.visit_mac(mac, Some(ii.ident), MacroPosition::Item); } } } - fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) { + fn visit_mac(&mut self, mac: &ast::MacCall, ident: Option<ast::Ident>, pos: MacroPosition) { skip_out_of_file_lines_range_visitor!(self, mac.span()); // 1 = ; |
