Rollup merge of #26838 - P1start:refactor-diagnostic, r=alexcrichton

This commit is contained in:
Manish Goregaokar 2015-07-16 14:13:10 +05:30
commit 38e875aa80

View file

@ -308,63 +308,6 @@ impl Level {
}
}
fn print_maybe_styled(w: &mut EmitterWriter,
msg: &str,
color: term::attr::Attr) -> io::Result<()> {
match w.dst {
Terminal(ref mut t) => {
try!(t.attr(color));
// If `msg` ends in a newline, we need to reset the color before
// the newline. We're making the assumption that we end up writing
// to a `LineBufferedWriter`, which means that emitting the reset
// after the newline ends up buffering the reset until we print
// another line or exit. Buffering the reset is a problem if we're
// sharing the terminal with any other programs (e.g. other rustc
// instances via `make -jN`).
//
// Note that if `msg` contains any internal newlines, this will
// result in the `LineBufferedWriter` flushing twice instead of
// once, which still leaves the opportunity for interleaved output
// to be miscolored. We assume this is rare enough that we don't
// have to worry about it.
if msg.ends_with("\n") {
try!(t.write_all(msg[..msg.len()-1].as_bytes()));
try!(t.reset());
try!(t.write_all(b"\n"));
} else {
try!(t.write_all(msg.as_bytes()));
try!(t.reset());
}
Ok(())
}
Raw(ref mut w) => w.write_all(msg.as_bytes()),
}
}
fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level,
msg: &str, code: Option<&str>) -> io::Result<()> {
if !topic.is_empty() {
try!(write!(&mut dst.dst, "{} ", topic));
}
try!(print_maybe_styled(dst,
&format!("{}: ", lvl.to_string()),
term::attr::ForegroundColor(lvl.color())));
try!(print_maybe_styled(dst,
&format!("{}", msg),
term::attr::Bold));
match code {
Some(code) => {
let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
try!(print_maybe_styled(dst, &format!(" [{}]", code.clone()), style));
}
None => ()
}
try!(write!(&mut dst.dst, "\n"));
Ok(())
}
pub struct EmitterWriter {
dst: Destination,
registry: Option<diagnostics::registry::Registry>
@ -401,70 +344,63 @@ impl EmitterWriter {
registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
EmitterWriter { dst: Raw(dst), registry: registry }
}
}
#[cfg(unix)]
fn stderr_isatty() -> bool {
unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
fn print_maybe_styled(&mut self,
msg: &str,
color: term::attr::Attr) -> io::Result<()> {
match self.dst {
Terminal(ref mut t) => {
try!(t.attr(color));
// If `msg` ends in a newline, we need to reset the color before
// the newline. We're making the assumption that we end up writing
// to a `LineBufferedWriter`, which means that emitting the reset
// after the newline ends up buffering the reset until we print
// another line or exit. Buffering the reset is a problem if we're
// sharing the terminal with any other programs (e.g. other rustc
// instances via `make -jN`).
//
// Note that if `msg` contains any internal newlines, this will
// result in the `LineBufferedWriter` flushing twice instead of
// once, which still leaves the opportunity for interleaved output
// to be miscolored. We assume this is rare enough that we don't
// have to worry about it.
if msg.ends_with("\n") {
try!(t.write_all(msg[..msg.len()-1].as_bytes()));
try!(t.reset());
try!(t.write_all(b"\n"));
} else {
try!(t.write_all(msg.as_bytes()));
try!(t.reset());
}
#[cfg(windows)]
fn stderr_isatty() -> bool {
const STD_ERROR_HANDLE: libc::DWORD = -12i32 as libc::DWORD;
extern "system" {
fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE;
fn GetConsoleMode(hConsoleHandle: libc::HANDLE,
lpMode: libc::LPDWORD) -> libc::BOOL;
Ok(())
}
unsafe {
let handle = GetStdHandle(STD_ERROR_HANDLE);
let mut out = 0;
GetConsoleMode(handle, &mut out) != 0
Raw(ref mut w) => w.write_all(msg.as_bytes()),
}
}
impl Write for Destination {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match *self {
Terminal(ref mut t) => t.write(bytes),
Raw(ref mut w) => w.write(bytes),
}
}
fn flush(&mut self) -> io::Result<()> {
match *self {
Terminal(ref mut t) => t.flush(),
Raw(ref mut w) => w.flush(),
}
}
fn print_diagnostic(&mut self, topic: &str, lvl: Level,
msg: &str, code: Option<&str>) -> io::Result<()> {
if !topic.is_empty() {
try!(write!(&mut self.dst, "{} ", topic));
}
impl Emitter for EmitterWriter {
fn emit(&mut self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str, code: Option<&str>, lvl: Level) {
let error = match cmsp {
Some((cm, COMMAND_LINE_SP)) => emit(self, cm,
FileLine(COMMAND_LINE_SP),
msg, code, lvl),
Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl),
None => print_diagnostic(self, "", lvl, msg, code),
};
try!(self.print_maybe_styled(&format!("{}: ", lvl.to_string()),
term::attr::ForegroundColor(lvl.color())));
try!(self.print_maybe_styled(&format!("{}", msg),
term::attr::Bold));
match error {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
match code {
Some(code) => {
let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
try!(self.print_maybe_styled(&format!(" [{}]", code.clone()), style));
}
None => ()
}
try!(write!(&mut self.dst, "\n"));
Ok(())
}
fn custom_emit(&mut self, cm: &codemap::CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
match emit(self, cm, sp, msg, None, lvl) {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
}
}
}
fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
fn emit_(&mut self, cm: &codemap::CodeMap, rsp: RenderSpan,
msg: &str, code: Option<&str>, lvl: Level) -> io::Result<()> {
let sp = rsp.span();
@ -479,20 +415,20 @@ fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
cm.span_to_string(sp)
};
try!(print_diagnostic(dst, &ss[..], lvl, msg, code));
try!(self.print_diagnostic(&ss[..], lvl, msg, code));
match rsp {
FullSpan(_) => {
try!(highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
try!(print_macro_backtrace(dst, cm, sp));
try!(self.highlight_lines(cm, sp, lvl, cm.span_to_lines(sp)));
try!(self.print_macro_backtrace(cm, sp));
}
EndSpan(_) => {
try!(end_highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
try!(print_macro_backtrace(dst, cm, sp));
try!(self.end_highlight_lines(cm, sp, lvl, cm.span_to_lines(sp)));
try!(self.print_macro_backtrace(cm, sp));
}
Suggestion(_, ref suggestion) => {
try!(highlight_suggestion(dst, cm, sp, suggestion));
try!(print_macro_backtrace(dst, cm, sp));
try!(self.highlight_suggestion(cm, sp, suggestion));
try!(self.print_macro_backtrace(cm, sp));
}
FileLine(..) => {
// no source text in this case!
@ -501,11 +437,11 @@ fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
match code {
Some(code) =>
match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) {
match self.registry.as_ref().and_then(|registry| registry.find_description(code)) {
Some(_) => {
try!(print_diagnostic(dst, &ss[..], Help,
&format!("run `rustc --explain {}` to see a detailed \
explanation", code), None));
try!(self.print_diagnostic(&ss[..], Help,
&format!("run `rustc --explain {}` to see a \
detailed explanation", code), None));
}
None => ()
},
@ -514,7 +450,7 @@ fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
Ok(())
}
fn highlight_suggestion(err: &mut EmitterWriter,
fn highlight_suggestion(&mut self,
cm: &codemap::CodeMap,
sp: Span,
suggestion: &str)
@ -547,21 +483,21 @@ fn highlight_suggestion(err: &mut EmitterWriter,
let mut lines = complete.lines();
for (line, line_index) in lines.by_ref().take(MAX_LINES).zip(first_line.line_index..) {
let elided_line_num = format!("{}", line_index+1);
try!(write!(&mut err.dst, "{0}:{1:2$} {3}\n",
try!(write!(&mut self.dst, "{0}:{1:2$} {3}\n",
fm.name, "", elided_line_num.len(), line));
}
// if we elided some lines, add an ellipsis
if lines.next().is_some() {
let elided_line_num = format!("{}", first_line.line_index + MAX_LINES + 1);
try!(write!(&mut err.dst, "{0:1$} {0:2$} ...\n",
try!(write!(&mut self.dst, "{0:1$} {0:2$} ...\n",
"", fm.name.len(), elided_line_num.len()));
}
Ok(())
}
fn highlight_lines(err: &mut EmitterWriter,
fn highlight_lines(&mut self,
cm: &codemap::CodeMap,
sp: Span,
lvl: Level,
@ -571,7 +507,7 @@ fn highlight_lines(err: &mut EmitterWriter,
let lines = match lines {
Ok(lines) => lines,
Err(_) => {
try!(write!(&mut err.dst, "(internal compiler error: unprintable span)\n"));
try!(write!(&mut self.dst, "(internal compiler error: unprintable span)\n"));
return Ok(());
}
};
@ -605,7 +541,7 @@ fn highlight_lines(err: &mut EmitterWriter,
// Print the offending lines
for (line_info, line) in display_line_infos.iter().zip(display_line_strings) {
try!(write!(&mut err.dst, "{}:{:>width$} {}\n",
try!(write!(&mut self.dst, "{}:{:>width$} {}\n",
fm.name,
line_info.line_index + 1,
line,
@ -616,7 +552,7 @@ fn highlight_lines(err: &mut EmitterWriter,
if display_lines < all_lines {
let last_line_index = display_line_infos.last().unwrap().line_index;
let s = format!("{}:{} ", fm.name, last_line_index + 1);
try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
try!(write!(&mut self.dst, "{0:1$}...\n", "", s.len()));
}
// FIXME (#3260)
@ -659,7 +595,7 @@ fn highlight_lines(err: &mut EmitterWriter,
}
}
try!(write!(&mut err.dst, "{}", s));
try!(write!(&mut self.dst, "{}", s));
let mut s = String::from("^");
let count = match lastc {
// Most terminals have a tab stop every eight columns by default
@ -687,8 +623,7 @@ fn highlight_lines(err: &mut EmitterWriter,
s.pop();
}
try!(print_maybe_styled(err,
&format!("{}\n", s),
try!(self.print_maybe_styled(&format!("{}\n", s),
term::attr::ForegroundColor(lvl.color())));
}
}
@ -702,7 +637,7 @@ fn highlight_lines(err: &mut EmitterWriter,
/// dot dot dot, then last line, whereas `highlight_lines` prints the first
/// six lines.
#[allow(deprecated)]
fn end_highlight_lines(w: &mut EmitterWriter,
fn end_highlight_lines(&mut self,
cm: &codemap::CodeMap,
sp: Span,
lvl: Level,
@ -711,7 +646,7 @@ fn end_highlight_lines(w: &mut EmitterWriter,
let lines = match lines {
Ok(lines) => lines,
Err(_) => {
try!(write!(&mut w.dst, "(internal compiler error: unprintable span)\n"));
try!(write!(&mut self.dst, "(internal compiler error: unprintable span)\n"));
return Ok(());
}
};
@ -721,19 +656,19 @@ fn end_highlight_lines(w: &mut EmitterWriter,
let lines = &lines.lines[..];
if lines.len() > MAX_LINES {
if let Some(line) = fm.get_line(lines[0].line_index) {
try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
try!(write!(&mut self.dst, "{}:{} {}\n", fm.name,
lines[0].line_index + 1, line));
}
try!(write!(&mut w.dst, "...\n"));
try!(write!(&mut self.dst, "...\n"));
let last_line_index = lines[lines.len() - 1].line_index;
if let Some(last_line) = fm.get_line(last_line_index) {
try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
try!(write!(&mut self.dst, "{}:{} {}\n", fm.name,
last_line_index + 1, last_line));
}
} else {
for line_info in lines {
if let Some(line) = fm.get_line(line_info.line_index) {
try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
try!(write!(&mut self.dst, "{}:{} {}\n", fm.name,
line_info.line_index + 1, line));
}
}
@ -762,12 +697,11 @@ fn end_highlight_lines(w: &mut EmitterWriter,
}
s.push('^');
s.push('\n');
print_maybe_styled(w,
&s[..],
self.print_maybe_styled(&s[..],
term::attr::ForegroundColor(lvl.color()))
}
fn print_macro_backtrace(w: &mut EmitterWriter,
fn print_macro_backtrace(&mut self,
cm: &codemap::CodeMap,
sp: Span)
-> io::Result<()> {
@ -781,20 +715,82 @@ fn print_macro_backtrace(w: &mut EmitterWriter,
codemap::MacroBang => ("", "!"),
codemap::CompilerExpansion => ("", ""),
};
try!(print_diagnostic(w, &ss, Note,
try!(self.print_diagnostic(&ss, Note,
&format!("in expansion of {}{}{}",
pre,
ei.callee.name,
post),
None));
let ss = cm.span_to_string(ei.call_site);
try!(print_diagnostic(w, &ss, Note, "expansion site", None));
try!(self.print_diagnostic(&ss, Note, "expansion site", None));
Ok(Some(ei.call_site))
}
None => Ok(None)
}
}));
cs.map_or(Ok(()), |call_site| print_macro_backtrace(w, cm, call_site))
cs.map_or(Ok(()), |call_site| self.print_macro_backtrace(cm, call_site))
}
}
#[cfg(unix)]
fn stderr_isatty() -> bool {
unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
}
#[cfg(windows)]
fn stderr_isatty() -> bool {
const STD_ERROR_HANDLE: libc::DWORD = -12i32 as libc::DWORD;
extern "system" {
fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE;
fn GetConsoleMode(hConsoleHandle: libc::HANDLE,
lpMode: libc::LPDWORD) -> libc::BOOL;
}
unsafe {
let handle = GetStdHandle(STD_ERROR_HANDLE);
let mut out = 0;
GetConsoleMode(handle, &mut out) != 0
}
}
impl Write for Destination {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match *self {
Terminal(ref mut t) => t.write(bytes),
Raw(ref mut w) => w.write(bytes),
}
}
fn flush(&mut self) -> io::Result<()> {
match *self {
Terminal(ref mut t) => t.flush(),
Raw(ref mut w) => w.flush(),
}
}
}
impl Emitter for EmitterWriter {
fn emit(&mut self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str, code: Option<&str>, lvl: Level) {
let error = match cmsp {
Some((cm, COMMAND_LINE_SP)) => self.emit_(cm,
FileLine(COMMAND_LINE_SP),
msg, code, lvl),
Some((cm, sp)) => self.emit_(cm, FullSpan(sp), msg, code, lvl),
None => self.print_diagnostic("", lvl, msg, code),
};
match error {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
}
}
fn custom_emit(&mut self, cm: &codemap::CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
match self.emit_(cm, sp, msg, None, lvl) {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
}
}
}
pub fn expect<T, M>(diag: &SpanHandler, opt: Option<T>, msg: M) -> T where
@ -808,7 +804,7 @@ pub fn expect<T, M>(diag: &SpanHandler, opt: Option<T>, msg: M) -> T where
#[cfg(test)]
mod test {
use super::{EmitterWriter, highlight_lines, Level};
use super::{EmitterWriter, Level};
use codemap::{mk_sp, CodeMap, BytePos};
use std::sync::{Arc, Mutex};
use std::io::{self, Write};
@ -854,7 +850,7 @@ mod test {
println!("span_to_lines");
let lines = cm.span_to_lines(sp);
println!("highlight_lines");
highlight_lines(&mut ew, &cm, sp, lvl, lines).unwrap();
ew.highlight_lines(&cm, sp, lvl, lines).unwrap();
println!("done");
let vec = data.lock().unwrap().clone();
let vec: &[u8] = &vec;