Skip to content

unify format_string and format_file #921

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 11, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 29 additions & 54 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ extern crate term;

use syntax::ast;
use syntax::codemap::{mk_sp, CodeMap, Span};
use syntax::errors::Handler;
use syntax::errors::{Handler, DiagnosticBuilder};
use syntax::errors::emitter::{ColorConfig, EmitterWriter};
use syntax::parse::{self, ParseSess};

Expand Down Expand Up @@ -263,11 +263,11 @@ impl fmt::Display for FormatReport {
}

// Formatting which depends on the AST.
fn fmt_ast(krate: &ast::Crate,
parse_session: &ParseSess,
main_file: &Path,
config: &Config)
-> FileMap {
fn format_ast(krate: &ast::Crate,
parse_session: &ParseSess,
main_file: &Path,
config: &Config)
-> FileMap {
let mut file_map = FileMap::new();
for (path, module) in modules::list_files(krate, parse_session.codemap()) {
if config.skip_children && path.as_path() != main_file {
Expand Down Expand Up @@ -367,43 +367,18 @@ fn format_lines(file_map: &mut FileMap, config: &Config) -> FormatReport {
report
}

fn format_string(input: String, config: &Config) -> FileMap {
let path = "stdin";
let codemap = Rc::new(CodeMap::new());

let tty_handler = Handler::with_tty_emitter(ColorConfig::Auto,
None,
true,
false,
codemap.clone());
let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());

let krate = parse::parse_crate_from_source_str(path.to_owned(),
input,
Vec::new(),
&parse_session)
.unwrap();

// Suppress error output after parsing.
let silent_emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None, codemap.clone()));
parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);

// FIXME: we still use a FileMap even though we only have
// one file, because fmt_lines requires a FileMap
let mut file_map = FileMap::new();

// do the actual formatting
let mut visitor = FmtVisitor::from_codemap(&parse_session, config);
visitor.format_separate_mod(&krate.module);

// append final newline
visitor.buffer.push_str("\n");
file_map.insert(path.to_owned(), visitor.buffer);
fn parse_input(input: Input, parse_session: &ParseSess) -> Result<ast::Crate, DiagnosticBuilder> {
let krate = match input {
Input::File(file) => parse::parse_crate_from_file(&file, Vec::new(), &parse_session),
Input::Text(text) => {
parse::parse_crate_from_source_str("stdin".to_owned(), text, Vec::new(), &parse_session)
}
};

file_map
krate
}

fn format_file(file: &Path, config: &Config) -> FileMap {
pub fn format_input(input: Input, config: &Config) -> (FileMap, FormatReport) {
let codemap = Rc::new(CodeMap::new());

let tty_handler = Handler::with_tty_emitter(ColorConfig::Auto,
Expand All @@ -413,27 +388,29 @@ fn format_file(file: &Path, config: &Config) -> FileMap {
codemap.clone());
let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());

let krate = parse::parse_crate_from_file(file, Vec::new(), &parse_session).unwrap();
let main_file = match input {
Input::File(ref file) => file.clone(),
Input::Text(..) => PathBuf::from("stdin"),
};

let krate = match parse_input(input, &parse_session) {
Ok(krate) => krate,
Err(mut diagnostic) => {
diagnostic.emit();
panic!("Unrecoverable parse error");
}
};
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unwrap used to be here. However DiagnosticBuilder panics in the drop, if it wasn't canceled or emited, so this unwrap caused panic wile panicking. Now there is only one panic, which is an improvement I think :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we return a Result rather than panicking here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returning Result here won't be super straightforward because diagnostic lifetime is bound to parse_session which is a local variable.

I plan to tackle this when implementing non-zero exit status.

And actually I don't think that returning Result will be a proper way to handle errors here (I'm not sure about this though). I think that rustfmt should be a robust tool, and that it should try to format as much as possible in spite of errors. So it seems not practical to return Results with one error, because there may be several errors present. Instead I propose to report errors right away, continue execution if possible and return a flag that there were some errors. In this particular case I'd emit a diagnostic and return an empty FileMap and FormatReport.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, seems fine.


// Suppress error output after parsing.
let silent_emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None, codemap.clone()));
parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);

let mut file_map = fmt_ast(&krate, &parse_session, file, config);
let mut file_map = format_ast(&krate, &parse_session, &main_file, config);

// For some reason, the codemap does not include terminating
// newlines so we must add one on for each file. This is sad.
filemap::append_newlines(&mut file_map);

file_map
}

pub fn format_input(input: Input, config: &Config) -> (FileMap, FormatReport) {
let mut file_map = match input {
Input::File(ref file) => format_file(file, config),
Input::Text(text) => format_string(text, config),
};

let report = format_lines(&mut file_map, config);
(file_map, report)
}
Expand All @@ -455,8 +432,6 @@ pub fn run(input: Input, config: &Config) {
let write_result = filemap::write_all_files(&file_map, &mut out, config);

if let Err(msg) = write_result {
if !ignore_errors {
msg!("Error writing files: {}", msg);
}
msg!("Error writing files: {}", msg);
}
}
8 changes: 8 additions & 0 deletions tests/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,14 @@ fn self_tests() {
warnings);
}

#[test]
fn stdin_formatting_smoke_test() {
let input = Input::Text("fn main () {}".to_owned());
let config = Config::default();
let (file_map, _report) = format_input(input, &config);
assert_eq!(file_map["stdin"].to_string(), "fn main() {}\n")
}

// For each file, run rustfmt and collect the output.
// Returns the number of files checked and the number of failures.
fn check_files<I>(files: I) -> (Vec<FormatReport>, u32, u32)
Expand Down