]> git.lizzy.rs Git - rust.git/blobdiff - src/formatting.rs
Merge pull request #3129 from otavio/issue-3104
[rust.git] / src / formatting.rs
index ee2539a2fa501e0391f51780b66978616e6d240b..039276ba6e886b39a54b1581d3ef459ce30833f7 100644 (file)
@@ -7,19 +7,19 @@
 use std::time::{Duration, Instant};
 
 use syntax::ast;
-use syntax::codemap::{CodeMap, FilePathMapping, Span};
 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
 use syntax::errors::Handler;
 use syntax::parse::{self, ParseSess};
+use syntax::source_map::{FilePathMapping, SourceMap, Span};
 
 use comment::{CharClasses, FullCodeCharKind};
-use config::{Config, FileName, NewlineStyle, Verbosity};
+use config::{Config, FileName, Verbosity};
 use issues::BadIssueSeeker;
 use visitor::{FmtVisitor, SnippetProvider};
-use {filemap, modules, ErrorKind, FormatReport, Input, Session};
+use {modules, source_file, ErrorKind, FormatReport, Input, Session};
 
 // A map of the files of a crate, with their new content
-pub(crate) type FileMap = Vec<FileRecord>;
+pub(crate) type SourceFile = Vec<FileRecord>;
 pub(crate) type FileRecord = (FileName, String);
 
 impl<'b, T: Write + 'b> Session<'b, T> {
@@ -46,8 +46,12 @@ pub(crate) fn format_input_inner(&mut self, input: Input) -> Result<FormatReport
             let config = &self.config.clone();
             let format_result = format_project(input, config, self);
 
-            format_result.map(|(report, summary)| {
-                self.summary.add(summary);
+            format_result.map(|report| {
+                {
+                    let new_errors = &report.internal.borrow().1;
+
+                    self.errors.add(new_errors);
+                }
                 report
             })
         })
@@ -59,44 +63,37 @@ fn format_project<T: FormatHandler>(
     input: Input,
     config: &Config,
     handler: &mut T,
-) -> Result<(FormatReport, Summary), ErrorKind> {
-    let mut summary = Summary::default();
-    let mut timer = Timer::Initialized(Instant::now());
+) -> Result<FormatReport, ErrorKind> {
+    let mut timer = Timer::start();
 
     let main_file = input.file_name();
     let input_is_stdin = main_file == FileName::Stdin;
 
     // Parse the crate.
-    let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
-    let mut parse_session = make_parse_sess(codemap.clone(), config);
-    let krate = parse_crate(input, &parse_session, config, &mut summary)?;
+    let source_map = Rc::new(SourceMap::new(FilePathMapping::empty()));
+    let mut parse_session = make_parse_sess(source_map.clone(), config);
+    let mut report = FormatReport::new();
+    let krate = parse_crate(input, &parse_session, config, &mut report)?;
     timer = timer.done_parsing();
 
     // Suppress error output if we have to do any further parsing.
-    let silent_emitter = silent_emitter(codemap);
+    let silent_emitter = silent_emitter(source_map);
     parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
 
-    let mut context = FormatContext::new(
-        &krate,
-        FormatReport::new(),
-        summary,
-        parse_session,
-        config,
-        handler,
-    );
+    let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
 
-    let files = modules::list_files(&krate, context.parse_session.codemap())?;
+    let files = modules::list_files(&krate, context.parse_session.source_map())?;
     for (path, module) in files {
         if (config.skip_children() && path != main_file) || config.ignore().skip_file(&path) {
             continue;
         }
-        should_emit_verbose(!input_is_stdin, config, || println!("Formatting {}", path));
+        should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
         let is_root = path == main_file;
         context.format_file(path, module, is_root)?;
     }
     timer = timer.done_formatting();
 
-    should_emit_verbose(!input_is_stdin, config, || {
+    should_emit_verbose(input_is_stdin, config, || {
         println!(
             "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
             timer.get_parse_time(),
@@ -104,8 +101,7 @@ fn format_project<T: FormatHandler>(
         )
     });
 
-    context.summarise_errors();
-    Ok((context.report, context.summary))
+    Ok(context.report)
 }
 
 // Used for formatting files.
@@ -113,27 +109,12 @@ fn format_project<T: FormatHandler>(
 struct FormatContext<'a, T: FormatHandler + 'a> {
     krate: &'a ast::Crate,
     report: FormatReport,
-    summary: Summary,
     parse_session: ParseSess,
     config: &'a Config,
     handler: &'a mut T,
 }
 
 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
-    // Moves errors from the report to the summary.
-    fn summarise_errors(&mut self) {
-        if self.report.has_warnings() {
-            self.summary.add_formatting_error();
-        }
-        let report_errs = &self.report.internal.borrow().1;
-        if report_errs.has_check_errors {
-            self.summary.add_check_error();
-        }
-        if report_errs.has_operational_errors {
-            self.summary.add_operational_error();
-        }
-    }
-
     // Formats a single file/module.
     fn format_file(
         &mut self,
@@ -141,14 +122,14 @@ fn format_file(
         module: &ast::Mod,
         is_root: bool,
     ) -> Result<(), ErrorKind> {
-        let filemap = self
+        let source_file = self
             .parse_session
-            .codemap()
+            .source_map()
             .lookup_char_pos(module.inner.lo())
             .file;
-        let big_snippet = filemap.src.as_ref().unwrap();
-        let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
-        let mut visitor = FmtVisitor::from_codemap(
+        let big_snippet = source_file.src.as_ref().unwrap();
+        let snippet_provider = SnippetProvider::new(source_file.start_pos, big_snippet);
+        let mut visitor = FmtVisitor::from_source_map(
             &self.parse_session,
             &self.config,
             &snippet_provider,
@@ -157,16 +138,16 @@ fn format_file(
 
         // Format inner attributes if available.
         if !self.krate.attrs.is_empty() && is_root {
-            visitor.skip_empty_lines(filemap.end_pos);
+            visitor.skip_empty_lines(source_file.end_pos);
             if visitor.visit_attrs(&self.krate.attrs, ast::AttrStyle::Inner) {
                 visitor.push_rewrite(module.inner, None);
             } else {
-                visitor.format_separate_mod(module, &*filemap);
+                visitor.format_separate_mod(module, &*source_file);
             }
         } else {
-            visitor.last_pos = filemap.start_pos;
-            visitor.skip_empty_lines(filemap.end_pos);
-            visitor.format_separate_mod(module, &*filemap);
+            visitor.last_pos = source_file.start_pos;
+            visitor.skip_empty_lines(source_file.end_pos);
+            visitor.format_separate_mod(module, &*source_file);
         };
 
         debug_assert_eq!(
@@ -174,9 +155,9 @@ fn format_file(
             ::utils::count_newlines(&visitor.buffer)
         );
 
-        // For some reason, the codemap does not include terminating
+        // For some reason, the source_map does not include terminating
         // newlines so we must add one on for each file. This is sad.
-        filemap::append_newline(&mut visitor.buffer);
+        source_file::append_newline(&mut visitor.buffer);
 
         format_lines(
             &mut visitor.buffer,
@@ -185,19 +166,29 @@ fn format_file(
             &self.config,
             &self.report,
         );
-        replace_with_system_newlines(&mut visitor.buffer, &self.config);
+        self.config
+            .newline_style()
+            .apply(&mut visitor.buffer, &big_snippet);
 
         if visitor.macro_rewrite_failure {
-            self.summary.add_macro_format_failure();
+            self.report.add_macro_format_failure();
         }
+        self.report
+            .add_non_formatted_ranges(visitor.skipped_range.clone());
 
-        self.handler.handle_formatted_file(path, visitor.buffer)
+        self.handler
+            .handle_formatted_file(path, visitor.buffer.to_owned(), &mut self.report)
     }
 }
 
 // Handle the results of formatting.
 trait FormatHandler {
-    fn handle_formatted_file(&mut self, path: FileName, result: String) -> Result<(), ErrorKind>;
+    fn handle_formatted_file(
+        &mut self,
+        path: FileName,
+        result: String,
+        report: &mut FormatReport,
+    ) -> Result<(), ErrorKind>;
 }
 
 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
@@ -205,11 +196,12 @@ impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
     fn handle_formatted_file(
         &mut self,
         path: FileName,
-        mut result: String,
+        result: String,
+        report: &mut FormatReport,
     ) -> Result<(), ErrorKind> {
         if let Some(ref mut out) = self.out {
-            match filemap::write_file(&mut result, &path, out, &self.config) {
-                Ok(b) if b => self.summary.add_diff(),
+            match source_file::write_file(&result, &path, out, &self.config) {
+                Ok(b) if b => report.add_diff(),
                 Err(e) => {
                     // Create a new error with path_str to help users see which files failed
                     let err_msg = format!("{}: {}", path, e);
@@ -219,7 +211,7 @@ fn handle_formatted_file(
             }
         }
 
-        self.filemap.push((path, result));
+        self.source_file.push((path, result));
         Ok(())
     }
 }
@@ -233,21 +225,25 @@ pub(crate) struct FormattingError {
 }
 
 impl FormattingError {
-    pub(crate) fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
+    pub(crate) fn from_span(
+        span: Span,
+        source_map: &SourceMap,
+        kind: ErrorKind,
+    ) -> FormattingError {
         FormattingError {
-            line: codemap.lookup_char_pos(span.lo()).line,
+            line: source_map.lookup_char_pos(span.lo()).line,
             is_comment: kind.is_comment(),
             kind,
             is_string: false,
-            line_buffer: codemap
-                .span_to_lines(*span)
+            line_buffer: source_map
+                .span_to_lines(span)
                 .ok()
                 .and_then(|fl| {
                     fl.file
                         .get_line(fl.lines[0].line_index)
                         .map(|l| l.into_owned())
                 })
-                .unwrap_or_else(|| String::new()),
+                .unwrap_or_else(String::new),
         }
     }
 
@@ -278,6 +274,7 @@ pub(crate) fn format_len(&self) -> (usize, usize) {
             ErrorKind::LineOverflow(found, max) => (max, found - max),
             ErrorKind::TrailingWhitespace
             | ErrorKind::DeprecatedAttr
+            | ErrorKind::BadIssue(_)
             | ErrorKind::BadAttr
             | ErrorKind::LostComment => {
                 let trailing_ws_start = self
@@ -299,124 +296,75 @@ pub(crate) fn format_len(&self) -> (usize, usize) {
 
 #[derive(Default, Debug)]
 pub(crate) struct ReportedErrors {
-    pub(crate) has_operational_errors: bool,
-    pub(crate) has_check_errors: bool,
-}
-
-/// A single span of changed lines, with 0 or more removed lines
-/// and a vector of 0 or more inserted lines.
-#[derive(Debug, PartialEq, Eq)]
-pub(crate) struct ModifiedChunk {
-    /// The first to be removed from the original text
-    pub line_number_orig: u32,
-    /// The number of lines which have been replaced
-    pub lines_removed: u32,
-    /// The new lines
-    pub lines: Vec<String>,
-}
-
-/// Set of changed sections of a file.
-#[derive(Debug, PartialEq, Eq)]
-pub(crate) struct ModifiedLines {
-    /// The set of changed chunks.
-    pub chunks: Vec<ModifiedChunk>,
-}
-
-/// A summary of a Rustfmt run.
-#[derive(Debug, Default, Clone, Copy)]
-pub struct Summary {
     // Encountered e.g. an IO error.
-    has_operational_errors: bool,
+    pub(crate) has_operational_errors: bool,
 
     // Failed to reformat code because of parsing errors.
-    has_parsing_errors: bool,
+    pub(crate) has_parsing_errors: bool,
 
     // Code is valid, but it is impossible to format it properly.
-    has_formatting_errors: bool,
+    pub(crate) has_formatting_errors: bool,
 
     // Code contains macro call that was unable to format.
     pub(crate) has_macro_format_failure: bool,
 
     // Failed a check, such as the license check or other opt-in checking.
-    has_check_errors: bool,
+    pub(crate) has_check_errors: bool,
 
     /// Formatted code differs from existing code (--check only).
-    pub has_diff: bool,
+    pub(crate) has_diff: bool,
 }
 
-impl Summary {
-    pub fn has_operational_errors(&self) -> bool {
-        self.has_operational_errors
-    }
-
-    pub fn has_parsing_errors(&self) -> bool {
-        self.has_parsing_errors
-    }
-
-    pub fn has_formatting_errors(&self) -> bool {
-        self.has_formatting_errors
-    }
-
-    pub fn has_check_errors(&self) -> bool {
-        self.has_check_errors
-    }
-
-    pub(crate) fn has_macro_formatting_failure(&self) -> bool {
-        self.has_macro_format_failure
-    }
-
-    pub fn add_operational_error(&mut self) {
-        self.has_operational_errors = true;
-    }
-
-    pub(crate) fn add_parsing_error(&mut self) {
-        self.has_parsing_errors = true;
-    }
-
-    pub(crate) fn add_formatting_error(&mut self) {
-        self.has_formatting_errors = true;
-    }
-
-    pub(crate) fn add_check_error(&mut self) {
-        self.has_check_errors = true;
-    }
-
-    pub(crate) fn add_diff(&mut self) {
-        self.has_diff = true;
-    }
-
-    pub(crate) fn add_macro_format_failure(&mut self) {
-        self.has_macro_format_failure = true;
-    }
-
-    pub fn has_no_errors(&self) -> bool {
-        !(self.has_operational_errors
-            || self.has_parsing_errors
-            || self.has_formatting_errors
-            || self.has_diff)
-    }
-
+impl ReportedErrors {
     /// Combine two summaries together.
-    pub fn add(&mut self, other: Summary) {
+    pub fn add(&mut self, other: &ReportedErrors) {
         self.has_operational_errors |= other.has_operational_errors;
+        self.has_parsing_errors |= other.has_parsing_errors;
         self.has_formatting_errors |= other.has_formatting_errors;
         self.has_macro_format_failure |= other.has_macro_format_failure;
-        self.has_parsing_errors |= other.has_parsing_errors;
         self.has_check_errors |= other.has_check_errors;
         self.has_diff |= other.has_diff;
     }
 }
 
+/// A single span of changed lines, with 0 or more removed lines
+/// and a vector of 0 or more inserted lines.
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) struct ModifiedChunk {
+    /// The first to be removed from the original text
+    pub line_number_orig: u32,
+    /// The number of lines which have been replaced
+    pub lines_removed: u32,
+    /// The new lines
+    pub lines: Vec<String>,
+}
+
+/// Set of changed sections of a file.
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) struct ModifiedLines {
+    /// The set of changed chunks.
+    pub chunks: Vec<ModifiedChunk>,
+}
+
 #[derive(Clone, Copy, Debug)]
 enum Timer {
+    Disabled,
     Initialized(Instant),
     DoneParsing(Instant, Instant),
     DoneFormatting(Instant, Instant, Instant),
 }
 
 impl Timer {
+    fn start() -> Timer {
+        if cfg!(target_arch = "wasm32") {
+            Timer::Disabled
+        } else {
+            Timer::Initialized(Instant::now())
+        }
+    }
     fn done_parsing(self) -> Self {
         match self {
+            Timer::Disabled => Timer::Disabled,
             Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
             _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
         }
@@ -424,6 +372,7 @@ fn done_parsing(self) -> Self {
 
     fn done_formatting(self) -> Self {
         match self {
+            Timer::Disabled => Timer::Disabled,
             Timer::DoneParsing(init_time, parse_time) => {
                 Timer::DoneFormatting(init_time, parse_time, Instant::now())
             }
@@ -434,6 +383,7 @@ fn done_formatting(self) -> Self {
     /// Returns the time it took to parse the source files in seconds.
     fn get_parse_time(&self) -> f32 {
         match *self {
+            Timer::Disabled => panic!("this platform cannot time execution"),
             Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
                 // This should never underflow since `Instant::now()` guarantees monotonicity.
                 Self::duration_to_f32(parse_time.duration_since(init))
@@ -446,6 +396,7 @@ fn get_parse_time(&self) -> f32 {
     /// not included.
     fn get_format_time(&self) -> f32 {
         match *self {
+            Timer::Disabled => panic!("this platform cannot time execution"),
             Timer::DoneFormatting(_init, parse_time, format_time) => {
                 Self::duration_to_f32(format_time.duration_since(parse_time))
             }
@@ -579,7 +530,8 @@ fn new_line(&mut self, kind: FullCodeCharKind) {
                 && !self.is_skipped_line()
                 && self.should_report_error(kind, &error_kind)
             {
-                self.push_err(error_kind, kind.is_comment(), self.is_string);
+                let is_string = self.is_string;
+                self.push_err(error_kind, kind.is_comment(), is_string);
             }
         }
 
@@ -648,7 +600,7 @@ fn parse_crate(
     input: Input,
     parse_session: &ParseSess,
     config: &Config,
-    summary: &mut Summary,
+    report: &mut FormatReport,
 ) -> Result<ast::Crate, ErrorKind> {
     let input_is_stdin = input.is_text();
 
@@ -656,7 +608,7 @@ fn parse_crate(
         Input::File(file) => parse::new_parser_from_file(parse_session, &file),
         Input::Text(text) => parse::new_parser_from_source_str(
             parse_session,
-            syntax::codemap::FileName::Custom("stdin".to_owned()),
+            syntax::source_map::FileName::Custom("stdin".to_owned()),
             text,
         ),
     };
@@ -680,28 +632,28 @@ fn parse_crate(
             // Note that if you see this message and want more information,
             // then run the `parse_crate_mod` function above without
             // `catch_unwind` so rustfmt panics and you can get a backtrace.
-            should_emit_verbose(!input_is_stdin, config, || {
+            should_emit_verbose(input_is_stdin, config, || {
                 println!("The Rust parser panicked")
             });
         }
     }
 
-    summary.add_parsing_error();
+    report.add_parsing_error();
     Err(ErrorKind::ParseError)
 }
 
-fn silent_emitter(codemap: Rc<CodeMap>) -> Box<EmitterWriter> {
+fn silent_emitter(source_map: Rc<SourceMap>) -> Box<EmitterWriter> {
     Box::new(EmitterWriter::new(
         Box::new(Vec::new()),
-        Some(codemap),
+        Some(source_map),
         false,
         false,
     ))
 }
 
-fn make_parse_sess(codemap: Rc<CodeMap>, config: &Config) -> ParseSess {
+fn make_parse_sess(source_map: Rc<SourceMap>, config: &Config) -> ParseSess {
     let tty_handler = if config.hide_parse_errors() {
-        let silent_emitter = silent_emitter(codemap.clone());
+        let silent_emitter = silent_emitter(source_map.clone());
         Handler::with_emitter(true, false, silent_emitter)
     } else {
         let supports_color = term::stderr().map_or(false, |term| term.supports_color());
@@ -710,38 +662,10 @@ fn make_parse_sess(codemap: Rc<CodeMap>, config: &Config) -> ParseSess {
         } else {
             ColorConfig::Never
         };
-        Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
+        Handler::with_tty_emitter(color_cfg, true, false, Some(source_map.clone()))
     };
 
-    ParseSess::with_span_handler(tty_handler, codemap)
-}
-
-fn replace_with_system_newlines(text: &mut String, config: &Config) -> () {
-    let style = if config.newline_style() == NewlineStyle::Native {
-        if cfg!(windows) {
-            NewlineStyle::Windows
-        } else {
-            NewlineStyle::Unix
-        }
-    } else {
-        config.newline_style()
-    };
-
-    match style {
-        NewlineStyle::Unix => return,
-        NewlineStyle::Windows => {
-            let mut transformed = String::with_capacity(text.capacity());
-            for c in text.chars() {
-                match c {
-                    '\n' => transformed.push_str("\r\n"),
-                    '\r' => continue,
-                    c => transformed.push(c),
-                }
-            }
-            *text = transformed;
-        }
-        NewlineStyle::Native => unreachable!(),
-    }
+    ParseSess::with_span_handler(tty_handler, source_map)
 }
 
 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)