Rollup merge of #37257 - srinivasreddy:librustc_errors, r=eddyb

run rustfmt on librustc_errors folder
This commit is contained in:
Eduard-Mihai Burtescu 2016-10-19 08:00:04 +03:00 committed by GitHub
commit 903e1f9657
6 changed files with 172 additions and 180 deletions

View File

@ -51,8 +51,8 @@ impl ColorConfig {
fn use_color(&self) -> bool { fn use_color(&self) -> bool {
match *self { match *self {
ColorConfig::Always => true, ColorConfig::Always => true,
ColorConfig::Never => false, ColorConfig::Never => false,
ColorConfig::Auto => stderr_isatty(), ColorConfig::Auto => stderr_isatty(),
} }
} }
} }
@ -83,22 +83,22 @@ macro_rules! println_maybe_styled {
} }
impl EmitterWriter { impl EmitterWriter {
pub fn stderr(color_config: ColorConfig, pub fn stderr(color_config: ColorConfig, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
code_map: Option<Rc<CodeMapper>>)
-> EmitterWriter {
if color_config.use_color() { if color_config.use_color() {
let dst = Destination::from_stderr(); let dst = Destination::from_stderr();
EmitterWriter { dst: dst, EmitterWriter {
cm: code_map} dst: dst,
cm: code_map,
}
} else { } else {
EmitterWriter { dst: Raw(Box::new(io::stderr())), EmitterWriter {
cm: code_map} dst: Raw(Box::new(io::stderr())),
cm: code_map,
}
} }
} }
pub fn new(dst: Box<Write + Send>, pub fn new(dst: Box<Write + Send>, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
code_map: Option<Rc<CodeMapper>>)
-> EmitterWriter {
EmitterWriter { EmitterWriter {
dst: Raw(dst), dst: Raw(dst),
cm: code_map, cm: code_map,
@ -107,9 +107,9 @@ impl EmitterWriter {
fn preprocess_annotations(&self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> { fn preprocess_annotations(&self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>, fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
file: Rc<FileMap>, file: Rc<FileMap>,
line_index: usize, line_index: usize,
ann: Annotation) { ann: Annotation) {
for slot in file_vec.iter_mut() { for slot in file_vec.iter_mut() {
// Look through each of our files for the one we're adding to // Look through each of our files for the one we're adding to
@ -168,15 +168,15 @@ impl EmitterWriter {
} }
add_annotation_to_file(&mut output, add_annotation_to_file(&mut output,
lo.file, lo.file,
lo.line, lo.line,
Annotation { Annotation {
start_col: lo.col.0, start_col: lo.col.0,
end_col: hi.col.0, end_col: hi.col.0,
is_primary: span_label.is_primary, is_primary: span_label.is_primary,
is_minimized: is_minimized, is_minimized: is_minimized,
label: span_label.label.clone(), label: span_label.label.clone(),
}); });
} }
} }
output output
@ -237,9 +237,7 @@ impl EmitterWriter {
'^', '^',
Style::UnderlinePrimary); Style::UnderlinePrimary);
if !annotation.is_minimized { if !annotation.is_minimized {
buffer.set_style(line_offset, buffer.set_style(line_offset, width_offset + p, Style::UnderlinePrimary);
width_offset + p,
Style::UnderlinePrimary);
} }
} else { } else {
buffer.putc(line_offset + 1, buffer.putc(line_offset + 1,
@ -247,9 +245,7 @@ impl EmitterWriter {
'-', '-',
Style::UnderlineSecondary); Style::UnderlineSecondary);
if !annotation.is_minimized { if !annotation.is_minimized {
buffer.set_style(line_offset, buffer.set_style(line_offset, width_offset + p, Style::UnderlineSecondary);
width_offset + p,
Style::UnderlineSecondary);
} }
} }
} }
@ -429,8 +425,7 @@ impl EmitterWriter {
} }
// Check to make sure we're not in any <*macros> // Check to make sure we're not in any <*macros>
if !cm.span_to_filename(def_site).contains("macros>") && if !cm.span_to_filename(def_site).contains("macros>") &&
!trace.macro_decl_name.starts_with("#[") !trace.macro_decl_name.starts_with("#[") {
{
new_labels.push((trace.call_site, new_labels.push((trace.call_site,
"in this macro invocation".to_string())); "in this macro invocation".to_string()));
break; break;
@ -475,10 +470,10 @@ impl EmitterWriter {
if spans_updated { if spans_updated {
children.push(SubDiagnostic { children.push(SubDiagnostic {
level: Level::Note, level: Level::Note,
message:"this error originates in a macro outside of the current \ message: "this error originates in a macro outside of the current crate"
crate".to_string(), .to_string(),
span: MultiSpan::new(), span: MultiSpan::new(),
render_span: None render_span: None,
}); });
} }
} }
@ -502,8 +497,7 @@ impl EmitterWriter {
buffer.append(0, &level.to_string(), Style::HeaderMsg); buffer.append(0, &level.to_string(), Style::HeaderMsg);
buffer.append(0, ": ", Style::NoStyle); buffer.append(0, ": ", Style::NoStyle);
buffer.append(0, msg, Style::NoStyle); buffer.append(0, msg, Style::NoStyle);
} } else {
else {
buffer.append(0, &level.to_string(), Style::Level(level.clone())); buffer.append(0, &level.to_string(), Style::Level(level.clone()));
match code { match code {
&Some(ref code) => { &Some(ref code) => {
@ -522,23 +516,21 @@ impl EmitterWriter {
let mut annotated_files = self.preprocess_annotations(msp); let mut annotated_files = self.preprocess_annotations(msp);
// Make sure our primary file comes first // Make sure our primary file comes first
let primary_lo = let primary_lo = if let (Some(ref cm), Some(ref primary_span)) =
if let (Some(ref cm), Some(ref primary_span)) = (self.cm.as_ref(), (self.cm.as_ref(), msp.primary_span().as_ref()) {
msp.primary_span().as_ref()) { if primary_span != &&DUMMY_SP && primary_span != &&COMMAND_LINE_SP {
if primary_span != &&DUMMY_SP && primary_span != &&COMMAND_LINE_SP { cm.lookup_char_pos(primary_span.lo)
cm.lookup_char_pos(primary_span.lo)
}
else {
emit_to_destination(&buffer.render(), level, &mut self.dst)?;
return Ok(());
}
} else { } else {
// If we don't have span information, emit and exit
emit_to_destination(&buffer.render(), level, &mut self.dst)?; emit_to_destination(&buffer.render(), level, &mut self.dst)?;
return Ok(()); return Ok(());
}; }
} else {
// If we don't have span information, emit and exit
emit_to_destination(&buffer.render(), level, &mut self.dst)?;
return Ok(());
};
if let Ok(pos) = if let Ok(pos) =
annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) { annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
annotated_files.swap(0, pos); annotated_files.swap(0, pos);
} }
@ -554,8 +546,8 @@ impl EmitterWriter {
buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber); buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
let loc = primary_lo.clone(); let loc = primary_lo.clone();
buffer.append(buffer_msg_line_offset, buffer.append(buffer_msg_line_offset,
&format!("{}:{}:{}", loc.file.name, loc.line, loc.col.0 + 1), &format!("{}:{}:{}", loc.file.name, loc.line, loc.col.0 + 1),
Style::LineAndColumn); Style::LineAndColumn);
for _ in 0..max_line_num_len { for _ in 0..max_line_num_len {
buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle); buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
} }
@ -569,8 +561,8 @@ impl EmitterWriter {
// Then, the secondary file indicator // Then, the secondary file indicator
buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber); buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
buffer.append(buffer_msg_line_offset + 1, buffer.append(buffer_msg_line_offset + 1,
&annotated_file.file.name, &annotated_file.file.name,
Style::LineAndColumn); Style::LineAndColumn);
for _ in 0..max_line_num_len { for _ in 0..max_line_num_len {
buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle); buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
} }
@ -591,7 +583,7 @@ impl EmitterWriter {
// this annotated line and the next one // this annotated line and the next one
if line_idx < (annotated_file.lines.len() - 1) { if line_idx < (annotated_file.lines.len() - 1) {
let line_idx_delta = annotated_file.lines[line_idx + 1].line_index - let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
annotated_file.lines[line_idx].line_index; annotated_file.lines[line_idx].line_index;
if line_idx_delta > 2 { if line_idx_delta > 2 {
let last_buffer_line_num = buffer.num_lines(); let last_buffer_line_num = buffer.num_lines();
buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber); buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
@ -672,12 +664,7 @@ impl EmitterWriter {
let max_line_num = self.get_max_line_num(span, children); let max_line_num = self.get_max_line_num(span, children);
let max_line_num_len = max_line_num.to_string().len(); let max_line_num_len = max_line_num.to_string().len();
match self.emit_message_default(span, match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
message,
code,
level,
max_line_num_len,
false) {
Ok(()) => { Ok(()) => {
if !children.is_empty() { if !children.is_empty() {
let mut buffer = StyledBuffer::new(); let mut buffer = StyledBuffer::new();
@ -723,13 +710,15 @@ impl EmitterWriter {
} }
} }
} }
Err(e) => panic!("failed to emit error: {}", e) Err(e) => panic!("failed to emit error: {}", e),
} }
match write!(&mut self.dst, "\n") { match write!(&mut self.dst, "\n") {
Err(e) => panic!("failed to emit error: {}", e), Err(e) => panic!("failed to emit error: {}", e),
_ => match self.dst.flush() { _ => {
Err(e) => panic!("failed to emit error: {}", e), match self.dst.flush() {
_ => () Err(e) => panic!("failed to emit error: {}", e),
_ => (),
}
} }
} }
} }
@ -753,8 +742,9 @@ fn overlaps(a1: &Annotation, a2: &Annotation) -> bool {
} }
fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>, fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
lvl: &Level, lvl: &Level,
dst: &mut Destination) -> io::Result<()> { dst: &mut Destination)
-> io::Result<()> {
use lock; use lock;
// In order to prevent error message interleaving, where multiple error lines get intermixed // In order to prevent error message interleaving, where multiple error lines get intermixed
@ -795,8 +785,7 @@ fn stderr_isatty() -> bool {
const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD; const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
extern "system" { extern "system" {
fn GetStdHandle(which: DWORD) -> HANDLE; fn GetStdHandle(which: DWORD) -> HANDLE;
fn GetConsoleMode(hConsoleHandle: HANDLE, fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
lpMode: *mut DWORD) -> BOOL;
} }
unsafe { unsafe {
let handle = GetStdHandle(STD_ERROR_HANDLE); let handle = GetStdHandle(STD_ERROR_HANDLE);
@ -824,9 +813,7 @@ impl BufferedWriter {
// note: we use _new because the conditional compilation at its use site may make this // note: we use _new because the conditional compilation at its use site may make this
// this function unused on some platforms // this function unused on some platforms
fn _new() -> BufferedWriter { fn _new() -> BufferedWriter {
BufferedWriter { BufferedWriter { buffer: vec![] }
buffer: vec![]
}
} }
} }
@ -853,35 +840,34 @@ impl Destination {
/// When not on Windows, prefer the buffered terminal so that we can buffer an entire error /// When not on Windows, prefer the buffered terminal so that we can buffer an entire error
/// to be emitted at one time. /// to be emitted at one time.
fn from_stderr() -> Destination { fn from_stderr() -> Destination {
let stderr: Option<Box<BufferedStderr>> = let stderr: Option<Box<BufferedStderr>> =
term::TerminfoTerminal::new(BufferedWriter::_new()) term::TerminfoTerminal::new(BufferedWriter::_new())
.map(|t| Box::new(t) as Box<BufferedStderr>); .map(|t| Box::new(t) as Box<BufferedStderr>);
match stderr { match stderr {
Some(t) => BufferedTerminal(t), Some(t) => BufferedTerminal(t),
None => Raw(Box::new(io::stderr())), None => Raw(Box::new(io::stderr())),
} }
} }
#[cfg(windows)] #[cfg(windows)]
/// Return a normal, unbuffered terminal when on Windows. /// Return a normal, unbuffered terminal when on Windows.
fn from_stderr() -> Destination { fn from_stderr() -> Destination {
let stderr: Option<Box<term::StderrTerminal>> = let stderr: Option<Box<term::StderrTerminal>> = term::TerminfoTerminal::new(io::stderr())
term::TerminfoTerminal::new(io::stderr()) .map(|t| Box::new(t) as Box<term::StderrTerminal>)
.map(|t| Box::new(t) as Box<term::StderrTerminal>) .or_else(|| {
.or_else(|| term::WinConsole::new(io::stderr()).ok() term::WinConsole::new(io::stderr())
.map(|t| Box::new(t) as Box<term::StderrTerminal>)); .ok()
.map(|t| Box::new(t) as Box<term::StderrTerminal>)
});
match stderr { match stderr {
Some(t) => Terminal(t), Some(t) => Terminal(t),
None => Raw(Box::new(io::stderr())), None => Raw(Box::new(io::stderr())),
} }
} }
fn apply_style(&mut self, fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
lvl: Level,
style: Style)
-> io::Result<()> {
match style { match style {
Style::FileNameStyle | Style::LineAndColumn => {} Style::FileNameStyle | Style::LineAndColumn => {}
Style::LineNumber => { Style::LineNumber => {
@ -931,18 +917,26 @@ impl Destination {
fn start_attr(&mut self, attr: term::Attr) -> io::Result<()> { fn start_attr(&mut self, attr: term::Attr) -> io::Result<()> {
match *self { match *self {
Terminal(ref mut t) => { t.attr(attr)?; } Terminal(ref mut t) => {
BufferedTerminal(ref mut t) => { t.attr(attr)?; } t.attr(attr)?;
Raw(_) => { } }
BufferedTerminal(ref mut t) => {
t.attr(attr)?;
}
Raw(_) => {}
} }
Ok(()) Ok(())
} }
fn reset_attrs(&mut self) -> io::Result<()> { fn reset_attrs(&mut self) -> io::Result<()> {
match *self { match *self {
Terminal(ref mut t) => { t.reset()?; } Terminal(ref mut t) => {
BufferedTerminal(ref mut t) => { t.reset()?; } t.reset()?;
Raw(_) => { } }
BufferedTerminal(ref mut t) => {
t.reset()?;
}
Raw(_) => {}
} }
Ok(()) Ok(())
} }

View File

@ -28,8 +28,10 @@
extern crate serialize; extern crate serialize;
extern crate term; extern crate term;
#[macro_use] extern crate log; #[macro_use]
#[macro_use] extern crate libc; extern crate log;
#[macro_use]
extern crate libc;
extern crate rustc_unicode; extern crate rustc_unicode;
extern crate serialize as rustc_serialize; // used by deriving extern crate serialize as rustc_serialize; // used by deriving
extern crate syntax_pos; extern crate syntax_pos;
@ -52,8 +54,8 @@ pub mod registry;
pub mod styled_buffer; pub mod styled_buffer;
mod lock; mod lock;
use syntax_pos::{BytePos, Loc, FileLinesResult, FileName, MultiSpan, Span, NO_EXPANSION }; use syntax_pos::{BytePos, Loc, FileLinesResult, FileName, MultiSpan, Span, NO_EXPANSION};
use syntax_pos::{MacroBacktrace}; use syntax_pos::MacroBacktrace;
#[derive(Clone)] #[derive(Clone)]
pub enum RenderSpan { pub enum RenderSpan {
@ -89,9 +91,11 @@ impl CodeSuggestion {
pub fn splice_lines(&self, cm: &CodeMapper) -> String { pub fn splice_lines(&self, cm: &CodeMapper) -> String {
use syntax_pos::{CharPos, Loc, Pos}; use syntax_pos::{CharPos, Loc, Pos};
fn push_trailing(buf: &mut String, line_opt: Option<&str>, fn push_trailing(buf: &mut String,
lo: &Loc, hi_opt: Option<&Loc>) { line_opt: Option<&str>,
let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi|hi.col.to_usize())); lo: &Loc,
hi_opt: Option<&Loc>) {
let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
if let Some(line) = line_opt { if let Some(line) = line_opt {
if line.len() > lo { if line.len() > lo {
buf.push_str(match hi_opt { buf.push_str(match hi_opt {
@ -119,7 +123,11 @@ impl CodeSuggestion {
// Find the bounding span. // Find the bounding span.
let lo = primary_spans.iter().map(|sp| sp.lo).min().unwrap(); let lo = primary_spans.iter().map(|sp| sp.lo).min().unwrap();
let hi = primary_spans.iter().map(|sp| sp.hi).min().unwrap(); let hi = primary_spans.iter().map(|sp| sp.hi).min().unwrap();
let bounding_span = Span { lo: lo, hi: hi, expn_id: NO_EXPANSION }; let bounding_span = Span {
lo: lo,
hi: hi,
expn_id: NO_EXPANSION,
};
let lines = cm.span_to_lines(bounding_span).unwrap(); let lines = cm.span_to_lines(bounding_span).unwrap();
assert!(!lines.lines.is_empty()); assert!(!lines.lines.is_empty());
@ -153,7 +161,7 @@ impl CodeSuggestion {
} }
} }
if let Some(cur_line) = fm.get_line(cur_lo.line - 1) { if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
buf.push_str(&cur_line[.. cur_lo.col.to_usize()]); buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
} }
} }
buf.push_str(substitute); buf.push_str(substitute);
@ -263,8 +271,7 @@ impl<'a> DiagnosticBuilder<'a> {
/// all, and you just supplied a `Span` to create the diagnostic, /// all, and you just supplied a `Span` to create the diagnostic,
/// then the snippet will just include that `Span`, which is /// then the snippet will just include that `Span`, which is
/// called the primary span. /// called the primary span.
pub fn span_label(&mut self, span: Span, label: &fmt::Display) pub fn span_label(&mut self, span: Span, label: &fmt::Display) -> &mut DiagnosticBuilder<'a> {
-> &mut DiagnosticBuilder<'a> {
self.span.push_span_label(span, format!("{}", label)); self.span.push_span_label(span, format!("{}", label));
self self
} }
@ -273,8 +280,7 @@ impl<'a> DiagnosticBuilder<'a> {
label: &fmt::Display, label: &fmt::Display,
expected: &fmt::Display, expected: &fmt::Display,
found: &fmt::Display) found: &fmt::Display)
-> &mut DiagnosticBuilder<'a> -> &mut DiagnosticBuilder<'a> {
{
self.note_expected_found_extra(label, expected, found, &"", &"") self.note_expected_found_extra(label, expected, found, &"", &"")
} }
@ -284,8 +290,7 @@ impl<'a> DiagnosticBuilder<'a> {
found: &fmt::Display, found: &fmt::Display,
expected_extra: &fmt::Display, expected_extra: &fmt::Display,
found_extra: &fmt::Display) found_extra: &fmt::Display)
-> &mut DiagnosticBuilder<'a> -> &mut DiagnosticBuilder<'a> {
{
// For now, just attach these as notes // For now, just attach these as notes
self.note(&format!("expected {} `{}`{}", label, expected, expected_extra)); self.note(&format!("expected {} `{}`{}", label, expected, expected_extra));
self.note(&format!(" found {} `{}`{}", label, found, found_extra)); self.note(&format!(" found {} `{}`{}", label, found, found_extra));
@ -314,7 +319,7 @@ impl<'a> DiagnosticBuilder<'a> {
self.sub(Level::Warning, msg, sp.into(), None); self.sub(Level::Warning, msg, sp.into(), None);
self self
} }
pub fn help(&mut self , msg: &str) -> &mut DiagnosticBuilder<'a> { pub fn help(&mut self, msg: &str) -> &mut DiagnosticBuilder<'a> {
self.sub(Level::Help, msg, MultiSpan::new(), None); self.sub(Level::Help, msg, MultiSpan::new(), None);
self self
} }
@ -333,10 +338,13 @@ impl<'a> DiagnosticBuilder<'a> {
msg: &str, msg: &str,
suggestion: String) suggestion: String)
-> &mut DiagnosticBuilder<'a> { -> &mut DiagnosticBuilder<'a> {
self.sub(Level::Help, msg, MultiSpan::new(), Some(Suggestion(CodeSuggestion { self.sub(Level::Help,
msp: sp.into(), msg,
substitutes: vec![suggestion], MultiSpan::new(),
}))); Some(Suggestion(CodeSuggestion {
msp: sp.into(),
substitutes: vec![suggestion],
})));
self self
} }
@ -360,18 +368,17 @@ impl<'a> DiagnosticBuilder<'a> {
/// Convenience function for internal use, clients should use one of the /// Convenience function for internal use, clients should use one of the
/// struct_* methods on Handler. /// struct_* methods on Handler.
fn new(handler: &'a Handler, fn new(handler: &'a Handler, level: Level, message: &str) -> DiagnosticBuilder<'a> {
level: Level,
message: &str) -> DiagnosticBuilder<'a> {
DiagnosticBuilder::new_with_code(handler, level, None, message) DiagnosticBuilder::new_with_code(handler, level, None, message)
} }
/// Convenience function for internal use, clients should use one of the /// Convenience function for internal use, clients should use one of the
/// struct_* methods on Handler. /// struct_* methods on Handler.
fn new_with_code(handler: &'a Handler, fn new_with_code(handler: &'a Handler,
level: Level, level: Level,
code: Option<String>, code: Option<String>,
message: &str) -> DiagnosticBuilder<'a> { message: &str)
-> DiagnosticBuilder<'a> {
DiagnosticBuilder { DiagnosticBuilder {
handler: handler, handler: handler,
level: level, level: level,
@ -410,9 +417,8 @@ impl<'a> fmt::Debug for DiagnosticBuilder<'a> {
impl<'a> Drop for DiagnosticBuilder<'a> { impl<'a> Drop for DiagnosticBuilder<'a> {
fn drop(&mut self) { fn drop(&mut self) {
if !panicking() && !self.cancelled() { if !panicking() && !self.cancelled() {
let mut db = DiagnosticBuilder::new(self.handler, let mut db =
Bug, DiagnosticBuilder::new(self.handler, Bug, "Error constructed but not emitted");
"Error constructed but not emitted");
db.emit(); db.emit();
panic!(); panic!();
} }
@ -443,7 +449,8 @@ impl Handler {
pub fn with_emitter(can_emit_warnings: bool, pub fn with_emitter(can_emit_warnings: bool,
treat_err_as_bug: bool, treat_err_as_bug: bool,
e: Box<Emitter>) -> Handler { e: Box<Emitter>)
-> Handler {
Handler { Handler {
err_count: Cell::new(0), err_count: Cell::new(0),
emitter: RefCell::new(e), emitter: RefCell::new(e),
@ -544,10 +551,10 @@ impl Handler {
pub fn cancel(&self, err: &mut DiagnosticBuilder) { pub fn cancel(&self, err: &mut DiagnosticBuilder) {
if err.level == Level::Error || err.level == Level::Fatal { if err.level == Level::Error || err.level == Level::Fatal {
self.err_count.set( self.err_count.set(self.err_count
self.err_count.get().checked_sub(1) .get()
.expect("cancelled an error but err_count is 0") .checked_sub(1)
); .expect("cancelled an error but err_count is 0"));
} }
err.cancel(); err.cancel();
} }
@ -558,14 +565,16 @@ impl Handler {
} }
} }
pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
-> FatalError {
self.emit(&sp.into(), msg, Fatal); self.emit(&sp.into(), msg, Fatal);
self.bump_err_count(); self.bump_err_count();
self.panic_if_treat_err_as_bug(); self.panic_if_treat_err_as_bug();
return FatalError; return FatalError;
} }
pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
sp: S,
msg: &str,
code: &str)
-> FatalError { -> FatalError {
self.emit_with_code(&sp.into(), msg, code, Fatal); self.emit_with_code(&sp.into(), msg, code, Fatal);
self.bump_err_count(); self.bump_err_count();
@ -619,9 +628,7 @@ impl Handler {
if self.treat_err_as_bug { if self.treat_err_as_bug {
self.bug(msg); self.bug(msg);
} }
let mut db = DiagnosticBuilder::new(self, let mut db = DiagnosticBuilder::new(self, Fatal, msg);
Fatal,
msg);
db.emit(); db.emit();
self.bump_err_count(); self.bump_err_count();
FatalError FatalError
@ -630,28 +637,20 @@ impl Handler {
if self.treat_err_as_bug { if self.treat_err_as_bug {
self.bug(msg); self.bug(msg);
} }
let mut db = DiagnosticBuilder::new(self, let mut db = DiagnosticBuilder::new(self, Error, msg);
Error,
msg);
db.emit(); db.emit();
self.bump_err_count(); self.bump_err_count();
} }
pub fn warn(&self, msg: &str) { pub fn warn(&self, msg: &str) {
let mut db = DiagnosticBuilder::new(self, let mut db = DiagnosticBuilder::new(self, Warning, msg);
Warning,
msg);
db.emit(); db.emit();
} }
pub fn note_without_error(&self, msg: &str) { pub fn note_without_error(&self, msg: &str) {
let mut db = DiagnosticBuilder::new(self, let mut db = DiagnosticBuilder::new(self, Note, msg);
Note,
msg);
db.emit(); db.emit();
} }
pub fn bug(&self, msg: &str) -> ! { pub fn bug(&self, msg: &str) -> ! {
let mut db = DiagnosticBuilder::new(self, let mut db = DiagnosticBuilder::new(self, Bug, msg);
Bug,
msg);
db.emit(); db.emit();
panic!(ExplicitBug); panic!(ExplicitBug);
} }
@ -678,44 +677,41 @@ impl Handler {
match *delayed_bug { match *delayed_bug {
Some((ref span, ref errmsg)) => { Some((ref span, ref errmsg)) => {
self.span_bug(span.clone(), errmsg); self.span_bug(span.clone(), errmsg);
}, }
_ => {} _ => {}
} }
return; return;
} }
1 => s = "aborting due to previous error".to_string(), 1 => s = "aborting due to previous error".to_string(),
_ => { _ => {
s = format!("aborting due to {} previous errors", s = format!("aborting due to {} previous errors", self.err_count.get());
self.err_count.get());
} }
} }
panic!(self.fatal(&s)); panic!(self.fatal(&s));
} }
pub fn emit(&self, pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
msp: &MultiSpan, if lvl == Warning && !self.can_emit_warnings {
msg: &str, return;
lvl: Level) { }
if lvl == Warning && !self.can_emit_warnings { return }
let mut db = DiagnosticBuilder::new(self, lvl, msg); let mut db = DiagnosticBuilder::new(self, lvl, msg);
db.set_span(msp.clone()); db.set_span(msp.clone());
db.emit(); db.emit();
if !self.continue_after_error.get() { self.abort_if_errors(); } if !self.continue_after_error.get() {
self.abort_if_errors();
}
} }
pub fn emit_with_code(&self, pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: &str, lvl: Level) {
msp: &MultiSpan, if lvl == Warning && !self.can_emit_warnings {
msg: &str, return;
code: &str, }
lvl: Level) { let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code.to_owned()), msg);
if lvl == Warning && !self.can_emit_warnings { return }
let mut db = DiagnosticBuilder::new_with_code(self,
lvl,
Some(code.to_owned()),
msg);
db.set_span(msp.clone()); db.set_span(msp.clone());
db.emit(); db.emit();
if !self.continue_after_error.get() { self.abort_if_errors(); } if !self.continue_after_error.get() {
self.abort_if_errors();
}
} }
} }
@ -750,7 +746,7 @@ impl Level {
} else { } else {
term::color::YELLOW term::color::YELLOW
} }
}, }
Note => term::color::BRIGHT_GREEN, Note => term::color::BRIGHT_GREEN,
Help => term::color::BRIGHT_CYAN, Help => term::color::BRIGHT_CYAN,
Cancelled => unreachable!(), Cancelled => unreachable!(),
@ -769,8 +765,8 @@ impl Level {
} }
} }
pub fn expect<T, M>(diag: &Handler, opt: Option<T>, msg: M) -> T where pub fn expect<T, M>(diag: &Handler, opt: Option<T>, msg: M) -> T
M: FnOnce() -> String, where M: FnOnce() -> String
{ {
match opt { match opt {
Some(t) => t, Some(t) => t,

View File

@ -40,9 +40,9 @@ pub fn acquire_global_lock(name: &str) -> Box<Any> {
extern "system" { extern "system" {
fn CreateMutexA(lpMutexAttributes: LPSECURITY_ATTRIBUTES, fn CreateMutexA(lpMutexAttributes: LPSECURITY_ATTRIBUTES,
bInitialOwner: BOOL, bInitialOwner: BOOL,
lpName: LPCSTR) -> HANDLE; lpName: LPCSTR)
fn WaitForSingleObject(hHandle: HANDLE, -> HANDLE;
dwMilliseconds: DWORD) -> DWORD; fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
fn ReleaseMutex(hMutex: HANDLE) -> BOOL; fn ReleaseMutex(hMutex: HANDLE) -> BOOL;
fn CloseHandle(hObject: HANDLE) -> BOOL; fn CloseHandle(hObject: HANDLE) -> BOOL;
} }
@ -76,7 +76,8 @@ pub fn acquire_global_lock(name: &str) -> Box<Any> {
// open up a handle to one if it already exists. // open up a handle to one if it already exists.
let mutex = CreateMutexA(0 as *mut _, 0, cname.as_ptr() as *const u8); let mutex = CreateMutexA(0 as *mut _, 0, cname.as_ptr() as *const u8);
if mutex.is_null() { if mutex.is_null() {
panic!("failed to create global mutex named `{}`: {}", name, panic!("failed to create global mutex named `{}`: {}",
name,
io::Error::last_os_error()); io::Error::last_os_error());
} }
let mutex = Handle(mutex); let mutex = Handle(mutex);
@ -96,8 +97,10 @@ pub fn acquire_global_lock(name: &str) -> Box<Any> {
WAIT_OBJECT_0 | WAIT_ABANDONED => {} WAIT_OBJECT_0 | WAIT_ABANDONED => {}
code => { code => {
panic!("WaitForSingleObject failed on global mutex named \ panic!("WaitForSingleObject failed on global mutex named \
`{}`: {} (ret={:x})", name, `{}`: {} (ret={:x})",
io::Error::last_os_error(), code); name,
io::Error::last_os_error(),
code);
} }
} }

View File

@ -12,7 +12,7 @@ use std::collections::HashMap;
#[derive(Clone)] #[derive(Clone)]
pub struct Registry { pub struct Registry {
descriptions: HashMap<&'static str, &'static str> descriptions: HashMap<&'static str, &'static str>,
} }
impl Registry { impl Registry {

View File

@ -13,12 +13,12 @@
use syntax_pos::{Span, FileMap}; use syntax_pos::{Span, FileMap};
use CodeMapper; use CodeMapper;
use std::rc::Rc; use std::rc::Rc;
use {Level}; use Level;
#[derive(Clone)] #[derive(Clone)]
pub struct SnippetData { pub struct SnippetData {
codemap: Rc<CodeMapper>, codemap: Rc<CodeMapper>,
files: Vec<FileInfo> files: Vec<FileInfo>,
} }
#[derive(Clone)] #[derive(Clone)]

View File

@ -28,10 +28,9 @@ impl StyledBuffer {
pub fn copy_tabs(&mut self, row: usize) { pub fn copy_tabs(&mut self, row: usize) {
if row < self.text.len() { if row < self.text.len() {
for i in row+1..self.text.len() { for i in row + 1..self.text.len() {
for j in 0..self.text[i].len() { for j in 0..self.text[i].len() {
if self.text[row].len() > j && if self.text[row].len() > j && self.text[row][j] == '\t' &&
self.text[row][j] == '\t' &&
self.text[i][j] == ' ' { self.text[i][j] == ' ' {
self.text[i][j] = '\t'; self.text[i][j] = '\t';
} }
@ -44,7 +43,7 @@ impl StyledBuffer {
let mut output: Vec<Vec<StyledString>> = vec![]; let mut output: Vec<Vec<StyledString>> = vec![];
let mut styled_vec: Vec<StyledString> = vec![]; let mut styled_vec: Vec<StyledString> = vec![];
//before we render, do a little patch-up work to support tabs // before we render, do a little patch-up work to support tabs
self.copy_tabs(3); self.copy_tabs(3);
for (row, row_style) in self.text.iter().zip(&self.styles) { for (row, row_style) in self.text.iter().zip(&self.styles) {