]> git.proxmox.com Git - rustc.git/blame - src/libsyntax/diagnostic.rs
Imported Upstream version 1.2.0+dfsg1
[rustc.git] / src / libsyntax / diagnostic.rs
CommitLineData
223e47cc
LB
1// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
1a4d82fc
JJ
11pub use self::Level::*;
12pub use self::RenderSpan::*;
13pub use self::ColorConfig::*;
14use self::Destination::*;
15
d9579d0f 16use codemap::{self, COMMAND_LINE_SP, COMMAND_LINE_EXPN, Pos, Span};
1a4d82fc 17use diagnostics;
223e47cc 18
1a4d82fc 19use std::cell::{RefCell, Cell};
d9579d0f 20use std::{cmp, error, fmt};
c34b1796
AL
21use std::io::prelude::*;
22use std::io;
d9579d0f 23use term::{self, WriterWrapper};
c34b1796 24use libc;
1a4d82fc
JJ
25
26/// maximum number of lines we will print for each error; arbitrary.
c34b1796 27const MAX_LINES: usize = 6;
1a4d82fc 28
9346a6ac 29#[derive(Clone)]
1a4d82fc
JJ
30pub enum RenderSpan {
31 /// A FullSpan renders with both with an initial line for the
32 /// message, prefixed by file:linenum, followed by a summary of
33 /// the source code covered by the span.
34 FullSpan(Span),
35
9346a6ac
AL
36 /// Similar to a FullSpan, but the cited position is the end of
37 /// the span, instead of the start. Used, at least, for telling
38 /// compiletest/runtest to look at the last line of the span
39 /// (since `end_highlight_lines` displays an arrow to the end
40 /// of the span).
41 EndSpan(Span),
42
43 /// A suggestion renders with both with an initial line for the
44 /// message, prefixed by file:linenum, followed by a summary
45 /// of hypothetical source code, where the `String` is spliced
46 /// into the lines in place of the code covered by the span.
47 Suggestion(Span, String),
48
1a4d82fc
JJ
49 /// A FileLine renders with just a line for the message prefixed
50 /// by file:linenum.
51 FileLine(Span),
52}
53
54impl RenderSpan {
9346a6ac
AL
55 fn span(&self) -> Span {
56 match *self {
57 FullSpan(s) |
58 Suggestion(s, _) |
59 EndSpan(s) |
60 FileLine(s) =>
61 s
1a4d82fc
JJ
62 }
63 }
223e47cc
LB
64}
65
1a4d82fc
JJ
66#[derive(Clone, Copy)]
67pub enum ColorConfig {
68 Auto,
69 Always,
70 Never
223e47cc
LB
71}
72
1a4d82fc
JJ
73pub trait Emitter {
74 fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>,
75 msg: &str, code: Option<&str>, lvl: Level);
76 fn custom_emit(&mut self, cm: &codemap::CodeMap,
77 sp: RenderSpan, msg: &str, lvl: Level);
223e47cc
LB
78}
79
9346a6ac
AL
80/// Used as a return value to signify a fatal error occurred. (It is also
81/// used as the argument to panic at the moment, but that will eventually
82/// not be true.)
d9579d0f 83#[derive(Copy, Clone, Debug)]
9346a6ac 84#[must_use]
1a4d82fc
JJ
85pub struct FatalError;
86
d9579d0f
AL
87impl fmt::Display for FatalError {
88 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
89 write!(f, "parser fatal error")
90 }
91}
92
93impl error::Error for FatalError {
94 fn description(&self) -> &str {
95 "The parser has encountered a fatal error"
96 }
97}
98
1a4d82fc
JJ
99/// Signifies that the compiler died with an explicit call to `.bug`
100/// or `.span_bug` rather than a failed assertion, etc.
d9579d0f 101#[derive(Copy, Clone, Debug)]
1a4d82fc
JJ
102pub struct ExplicitBug;
103
d9579d0f
AL
104impl fmt::Display for ExplicitBug {
105 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
106 write!(f, "parser internal bug")
107 }
108}
109
110impl error::Error for ExplicitBug {
111 fn description(&self) -> &str {
112 "The parser has encountered an internal bug"
113 }
114}
115
1a4d82fc
JJ
116/// A span-handler is like a handler but also
117/// accepts span information for source-location
118/// reporting.
119pub struct SpanHandler {
120 pub handler: Handler,
121 pub cm: codemap::CodeMap,
223e47cc
LB
122}
123
1a4d82fc 124impl SpanHandler {
62682a34
SL
125 pub fn new(handler: Handler, cm: codemap::CodeMap) -> SpanHandler {
126 SpanHandler {
127 handler: handler,
128 cm: cm,
129 }
130 }
9346a6ac 131 pub fn span_fatal(&self, sp: Span, msg: &str) -> FatalError {
1a4d82fc 132 self.handler.emit(Some((&self.cm, sp)), msg, Fatal);
9346a6ac 133 return FatalError;
223e47cc 134 }
9346a6ac 135 pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> FatalError {
85aaf69f 136 self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Fatal);
9346a6ac 137 return FatalError;
85aaf69f 138 }
1a4d82fc
JJ
139 pub fn span_err(&self, sp: Span, msg: &str) {
140 self.handler.emit(Some((&self.cm, sp)), msg, Error);
223e47cc
LB
141 self.handler.bump_err_count();
142 }
1a4d82fc
JJ
143 pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
144 self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Error);
145 self.handler.bump_err_count();
146 }
147 pub fn span_warn(&self, sp: Span, msg: &str) {
148 self.handler.emit(Some((&self.cm, sp)), msg, Warning);
149 }
150 pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
151 self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Warning);
223e47cc 152 }
1a4d82fc
JJ
153 pub fn span_note(&self, sp: Span, msg: &str) {
154 self.handler.emit(Some((&self.cm, sp)), msg, Note);
223e47cc 155 }
1a4d82fc 156 pub fn span_end_note(&self, sp: Span, msg: &str) {
9346a6ac 157 self.handler.custom_emit(&self.cm, EndSpan(sp), msg, Note);
223e47cc 158 }
1a4d82fc
JJ
159 pub fn span_help(&self, sp: Span, msg: &str) {
160 self.handler.emit(Some((&self.cm, sp)), msg, Help);
223e47cc 161 }
9346a6ac
AL
162 /// Prints out a message with a suggested edit of the code.
163 ///
164 /// See `diagnostic::RenderSpan::Suggestion` for more information.
165 pub fn span_suggestion(&self, sp: Span, msg: &str, suggestion: String) {
166 self.handler.custom_emit(&self.cm, Suggestion(sp, suggestion), msg, Help);
167 }
1a4d82fc
JJ
168 pub fn fileline_note(&self, sp: Span, msg: &str) {
169 self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
223e47cc 170 }
85aaf69f
SL
171 pub fn fileline_help(&self, sp: Span, msg: &str) {
172 self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help);
173 }
1a4d82fc
JJ
174 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
175 self.handler.emit(Some((&self.cm, sp)), msg, Bug);
176 panic!(ExplicitBug);
177 }
178 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
85aaf69f 179 self.span_bug(sp, &format!("unimplemented {}", msg));
1a4d82fc
JJ
180 }
181 pub fn handler<'a>(&'a self) -> &'a Handler {
182 &self.handler
183 }
184}
185
186/// A handler deals with errors; certain errors
187/// (fatal, bug, unimpl) may cause immediate exit,
188/// others log errors for later reporting.
189pub struct Handler {
85aaf69f 190 err_count: Cell<usize>,
1a4d82fc 191 emit: RefCell<Box<Emitter + Send>>,
85aaf69f 192 pub can_emit_warnings: bool
223e47cc
LB
193}
194
1a4d82fc 195impl Handler {
62682a34
SL
196 pub fn new(color_config: ColorConfig,
197 registry: Option<diagnostics::registry::Registry>,
198 can_emit_warnings: bool) -> Handler {
199 let emitter = Box::new(EmitterWriter::stderr(color_config, registry));
200 Handler::with_emitter(can_emit_warnings, emitter)
201 }
202 pub fn with_emitter(can_emit_warnings: bool, e: Box<Emitter + Send>) -> Handler {
203 Handler {
204 err_count: Cell::new(0),
205 emit: RefCell::new(e),
206 can_emit_warnings: can_emit_warnings
207 }
208 }
1a4d82fc
JJ
209 pub fn fatal(&self, msg: &str) -> ! {
210 self.emit.borrow_mut().emit(None, msg, None, Fatal);
211 panic!(FatalError);
223e47cc 212 }
1a4d82fc
JJ
213 pub fn err(&self, msg: &str) {
214 self.emit.borrow_mut().emit(None, msg, None, Error);
223e47cc
LB
215 self.bump_err_count();
216 }
1a4d82fc 217 pub fn bump_err_count(&self) {
85aaf69f 218 self.err_count.set(self.err_count.get() + 1);
223e47cc 219 }
85aaf69f 220 pub fn err_count(&self) -> usize {
1a4d82fc 221 self.err_count.get()
970d7e83 222 }
1a4d82fc 223 pub fn has_errors(&self) -> bool {
85aaf69f 224 self.err_count.get() > 0
970d7e83 225 }
1a4d82fc 226 pub fn abort_if_errors(&self) {
223e47cc 227 let s;
1a4d82fc 228 match self.err_count.get() {
85aaf69f
SL
229 0 => return,
230 1 => s = "aborting due to previous error".to_string(),
231 _ => {
1a4d82fc
JJ
232 s = format!("aborting due to {} previous errors",
233 self.err_count.get());
223e47cc
LB
234 }
235 }
85aaf69f 236 self.fatal(&s[..]);
223e47cc 237 }
1a4d82fc
JJ
238 pub fn warn(&self, msg: &str) {
239 self.emit.borrow_mut().emit(None, msg, None, Warning);
223e47cc 240 }
1a4d82fc
JJ
241 pub fn note(&self, msg: &str) {
242 self.emit.borrow_mut().emit(None, msg, None, Note);
223e47cc 243 }
1a4d82fc
JJ
244 pub fn help(&self, msg: &str) {
245 self.emit.borrow_mut().emit(None, msg, None, Help);
223e47cc 246 }
1a4d82fc
JJ
247 pub fn bug(&self, msg: &str) -> ! {
248 self.emit.borrow_mut().emit(None, msg, None, Bug);
249 panic!(ExplicitBug);
223e47cc 250 }
1a4d82fc 251 pub fn unimpl(&self, msg: &str) -> ! {
85aaf69f 252 self.bug(&format!("unimplemented {}", msg));
1a4d82fc
JJ
253 }
254 pub fn emit(&self,
255 cmsp: Option<(&codemap::CodeMap, Span)>,
256 msg: &str,
257 lvl: Level) {
85aaf69f 258 if lvl == Warning && !self.can_emit_warnings { return }
1a4d82fc
JJ
259 self.emit.borrow_mut().emit(cmsp, msg, None, lvl);
260 }
261 pub fn emit_with_code(&self,
262 cmsp: Option<(&codemap::CodeMap, Span)>,
263 msg: &str,
264 code: &str,
265 lvl: Level) {
85aaf69f 266 if lvl == Warning && !self.can_emit_warnings { return }
1a4d82fc
JJ
267 self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl);
268 }
269 pub fn custom_emit(&self, cm: &codemap::CodeMap,
270 sp: RenderSpan, msg: &str, lvl: Level) {
85aaf69f 271 if lvl == Warning && !self.can_emit_warnings { return }
1a4d82fc 272 self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl);
223e47cc
LB
273 }
274}
275
85aaf69f 276#[derive(Copy, PartialEq, Clone, Debug)]
1a4d82fc
JJ
277pub enum Level {
278 Bug,
279 Fatal,
280 Error,
281 Warning,
282 Note,
283 Help,
223e47cc
LB
284}
285
85aaf69f 286impl fmt::Display for Level {
1a4d82fc 287 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85aaf69f 288 use std::fmt::Display;
1a4d82fc
JJ
289
290 match *self {
291 Bug => "error: internal compiler error".fmt(f),
292 Fatal | Error => "error".fmt(f),
293 Warning => "warning".fmt(f),
294 Note => "note".fmt(f),
295 Help => "help".fmt(f),
296 }
297 }
223e47cc
LB
298}
299
1a4d82fc
JJ
300impl Level {
301 fn color(self) -> term::color::Color {
302 match self {
303 Bug | Fatal | Error => term::color::BRIGHT_RED,
304 Warning => term::color::BRIGHT_YELLOW,
305 Note => term::color::BRIGHT_GREEN,
306 Help => term::color::BRIGHT_CYAN,
307 }
223e47cc
LB
308 }
309}
310
1a4d82fc
JJ
311fn print_maybe_styled(w: &mut EmitterWriter,
312 msg: &str,
c34b1796 313 color: term::attr::Attr) -> io::Result<()> {
1a4d82fc
JJ
314 match w.dst {
315 Terminal(ref mut t) => {
316 try!(t.attr(color));
317 // If `msg` ends in a newline, we need to reset the color before
318 // the newline. We're making the assumption that we end up writing
319 // to a `LineBufferedWriter`, which means that emitting the reset
320 // after the newline ends up buffering the reset until we print
321 // another line or exit. Buffering the reset is a problem if we're
322 // sharing the terminal with any other programs (e.g. other rustc
323 // instances via `make -jN`).
324 //
325 // Note that if `msg` contains any internal newlines, this will
326 // result in the `LineBufferedWriter` flushing twice instead of
327 // once, which still leaves the opportunity for interleaved output
328 // to be miscolored. We assume this is rare enough that we don't
329 // have to worry about it.
330 if msg.ends_with("\n") {
c34b1796 331 try!(t.write_all(msg[..msg.len()-1].as_bytes()));
1a4d82fc 332 try!(t.reset());
c34b1796 333 try!(t.write_all(b"\n"));
1a4d82fc 334 } else {
c34b1796 335 try!(t.write_all(msg.as_bytes()));
1a4d82fc
JJ
336 try!(t.reset());
337 }
338 Ok(())
339 }
c34b1796 340 Raw(ref mut w) => w.write_all(msg.as_bytes()),
223e47cc
LB
341 }
342}
343
1a4d82fc 344fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level,
c34b1796 345 msg: &str, code: Option<&str>) -> io::Result<()> {
1a4d82fc
JJ
346 if !topic.is_empty() {
347 try!(write!(&mut dst.dst, "{} ", topic));
348 }
970d7e83 349
1a4d82fc 350 try!(print_maybe_styled(dst,
85aaf69f 351 &format!("{}: ", lvl.to_string()),
1a4d82fc
JJ
352 term::attr::ForegroundColor(lvl.color())));
353 try!(print_maybe_styled(dst,
85aaf69f 354 &format!("{}", msg),
1a4d82fc 355 term::attr::Bold));
970d7e83 356
1a4d82fc
JJ
357 match code {
358 Some(code) => {
359 let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
85aaf69f 360 try!(print_maybe_styled(dst, &format!(" [{}]", code.clone()), style));
1a4d82fc
JJ
361 }
362 None => ()
223e47cc 363 }
c34b1796 364 try!(write!(&mut dst.dst, "\n"));
1a4d82fc 365 Ok(())
970d7e83
LB
366}
367
1a4d82fc
JJ
368pub struct EmitterWriter {
369 dst: Destination,
370 registry: Option<diagnostics::registry::Registry>
371}
970d7e83 372
1a4d82fc
JJ
373enum Destination {
374 Terminal(Box<term::Terminal<WriterWrapper> + Send>),
c34b1796 375 Raw(Box<Write + Send>),
1a4d82fc
JJ
376}
377
378impl EmitterWriter {
379 pub fn stderr(color_config: ColorConfig,
380 registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
c34b1796 381 let stderr = io::stderr();
1a4d82fc
JJ
382
383 let use_color = match color_config {
384 Always => true,
385 Never => false,
c34b1796 386 Auto => stderr_isatty(),
1a4d82fc
JJ
387 };
388
389 if use_color {
390 let dst = match term::stderr() {
391 Some(t) => Terminal(t),
c34b1796 392 None => Raw(Box::new(stderr)),
1a4d82fc
JJ
393 };
394 EmitterWriter { dst: dst, registry: registry }
395 } else {
c34b1796 396 EmitterWriter { dst: Raw(Box::new(stderr)), registry: registry }
1a4d82fc
JJ
397 }
398 }
399
c34b1796 400 pub fn new(dst: Box<Write + Send>,
1a4d82fc
JJ
401 registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
402 EmitterWriter { dst: Raw(dst), registry: registry }
223e47cc 403 }
1a4d82fc 404}
970d7e83 405
c34b1796
AL
406#[cfg(unix)]
407fn stderr_isatty() -> bool {
408 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
409}
410#[cfg(windows)]
411fn stderr_isatty() -> bool {
412 const STD_ERROR_HANDLE: libc::DWORD = -12i32 as libc::DWORD;
413 extern "system" {
414 fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE;
415 fn GetConsoleMode(hConsoleHandle: libc::HANDLE,
416 lpMode: libc::LPDWORD) -> libc::BOOL;
417 }
418 unsafe {
419 let handle = GetStdHandle(STD_ERROR_HANDLE);
420 let mut out = 0;
421 GetConsoleMode(handle, &mut out) != 0
422 }
423}
424
425impl Write for Destination {
426 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
427 match *self {
428 Terminal(ref mut t) => t.write(bytes),
429 Raw(ref mut w) => w.write(bytes),
430 }
431 }
432 fn flush(&mut self) -> io::Result<()> {
1a4d82fc 433 match *self {
c34b1796
AL
434 Terminal(ref mut t) => t.flush(),
435 Raw(ref mut w) => w.flush(),
1a4d82fc
JJ
436 }
437 }
223e47cc
LB
438}
439
1a4d82fc
JJ
440impl Emitter for EmitterWriter {
441 fn emit(&mut self,
442 cmsp: Option<(&codemap::CodeMap, Span)>,
443 msg: &str, code: Option<&str>, lvl: Level) {
444 let error = match cmsp {
445 Some((cm, COMMAND_LINE_SP)) => emit(self, cm,
446 FileLine(COMMAND_LINE_SP),
9346a6ac
AL
447 msg, code, lvl),
448 Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl),
1a4d82fc
JJ
449 None => print_diagnostic(self, "", lvl, msg, code),
450 };
451
452 match error {
453 Ok(()) => {}
454 Err(e) => panic!("failed to print diagnostics: {:?}", e),
455 }
456 }
457
458 fn custom_emit(&mut self, cm: &codemap::CodeMap,
459 sp: RenderSpan, msg: &str, lvl: Level) {
9346a6ac 460 match emit(self, cm, sp, msg, None, lvl) {
1a4d82fc
JJ
461 Ok(()) => {}
462 Err(e) => panic!("failed to print diagnostics: {:?}", e),
463 }
464 }
223e47cc
LB
465}
466
1a4d82fc 467fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
9346a6ac 468 msg: &str, code: Option<&str>, lvl: Level) -> io::Result<()> {
1a4d82fc 469 let sp = rsp.span();
85aaf69f
SL
470
471 // We cannot check equality directly with COMMAND_LINE_SP
472 // since PartialEq is manually implemented to ignore the ExpnId
473 let ss = if sp.expn_id == COMMAND_LINE_EXPN {
1a4d82fc 474 "<command line option>".to_string()
9346a6ac
AL
475 } else if let EndSpan(_) = rsp {
476 let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id};
477 cm.span_to_string(span_end)
1a4d82fc
JJ
478 } else {
479 cm.span_to_string(sp)
480 };
9346a6ac
AL
481
482 try!(print_diagnostic(dst, &ss[..], lvl, msg, code));
483
484 match rsp {
485 FullSpan(_) => {
1a4d82fc 486 try!(highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
9346a6ac
AL
487 try!(print_macro_backtrace(dst, cm, sp));
488 }
489 EndSpan(_) => {
490 try!(end_highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
491 try!(print_macro_backtrace(dst, cm, sp));
492 }
493 Suggestion(_, ref suggestion) => {
494 try!(highlight_suggestion(dst, cm, sp, suggestion));
495 try!(print_macro_backtrace(dst, cm, sp));
496 }
497 FileLine(..) => {
498 // no source text in this case!
1a4d82fc
JJ
499 }
500 }
9346a6ac 501
1a4d82fc
JJ
502 match code {
503 Some(code) =>
504 match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) {
505 Some(_) => {
85aaf69f 506 try!(print_diagnostic(dst, &ss[..], Help,
d9579d0f 507 &format!("run `rustc --explain {}` to see a detailed \
85aaf69f 508 explanation", code), None));
1a4d82fc
JJ
509 }
510 None => ()
511 },
512 None => (),
223e47cc 513 }
1a4d82fc 514 Ok(())
223e47cc
LB
515}
516
9346a6ac
AL
517fn highlight_suggestion(err: &mut EmitterWriter,
518 cm: &codemap::CodeMap,
519 sp: Span,
520 suggestion: &str)
521 -> io::Result<()>
522{
d9579d0f 523 let lines = cm.span_to_lines(sp).unwrap();
9346a6ac
AL
524 assert!(!lines.lines.is_empty());
525
526 // To build up the result, we want to take the snippet from the first
527 // line that precedes the span, prepend that with the suggestion, and
528 // then append the snippet from the last line that trails the span.
529 let fm = &lines.file;
530
531 let first_line = &lines.lines[0];
532 let prefix = fm.get_line(first_line.line_index)
533 .map(|l| &l[..first_line.start_col.0])
534 .unwrap_or("");
535
536 let last_line = lines.lines.last().unwrap();
537 let suffix = fm.get_line(last_line.line_index)
538 .map(|l| &l[last_line.end_col.0..])
539 .unwrap_or("");
540
541 let complete = format!("{}{}{}", prefix, suggestion, suffix);
542
543 // print the suggestion without any line numbers, but leave
544 // space for them. This helps with lining up with previous
545 // snippets from the actual error being reported.
546 let fm = &*lines.file;
547 let mut lines = complete.lines();
548 for (line, line_index) in lines.by_ref().take(MAX_LINES).zip(first_line.line_index..) {
549 let elided_line_num = format!("{}", line_index+1);
550 try!(write!(&mut err.dst, "{0}:{1:2$} {3}\n",
551 fm.name, "", elided_line_num.len(), line));
552 }
553
554 // if we elided some lines, add an ellipsis
555 if lines.next().is_some() {
556 let elided_line_num = format!("{}", first_line.line_index + MAX_LINES + 1);
557 try!(write!(&mut err.dst, "{0:1$} {0:2$} ...\n",
558 "", fm.name.len(), elided_line_num.len()));
559 }
560
561 Ok(())
562}
563
1a4d82fc
JJ
564fn highlight_lines(err: &mut EmitterWriter,
565 cm: &codemap::CodeMap,
566 sp: Span,
567 lvl: Level,
d9579d0f 568 lines: codemap::FileLinesResult)
9346a6ac
AL
569 -> io::Result<()>
570{
d9579d0f
AL
571 let lines = match lines {
572 Ok(lines) => lines,
573 Err(_) => {
574 try!(write!(&mut err.dst, "(internal compiler error: unprintable span)\n"));
575 return Ok(());
576 }
577 };
578
1a4d82fc 579 let fm = &*lines.file;
223e47cc 580
9346a6ac
AL
581 let line_strings: Option<Vec<&str>> =
582 lines.lines.iter()
583 .map(|info| fm.get_line(info.line_index))
584 .collect();
585
586 let line_strings = match line_strings {
587 None => { return Ok(()); }
588 Some(line_strings) => line_strings
589 };
590
591 // Display only the first MAX_LINES lines.
592 let all_lines = lines.lines.len();
593 let display_lines = cmp::min(all_lines, MAX_LINES);
594 let display_line_infos = &lines.lines[..display_lines];
595 let display_line_strings = &line_strings[..display_lines];
596
223e47cc 597 // Print the offending lines
62682a34 598 for (line_info, line) in display_line_infos.iter().zip(display_line_strings) {
9346a6ac
AL
599 try!(write!(&mut err.dst, "{}:{} {}\n",
600 fm.name,
601 line_info.line_index + 1,
602 line));
223e47cc 603 }
9346a6ac
AL
604
605 // If we elided something, put an ellipsis.
606 if display_lines < all_lines {
607 let last_line_index = display_line_infos.last().unwrap().line_index;
608 let s = format!("{}:{} ", fm.name, last_line_index + 1);
1a4d82fc 609 try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
223e47cc
LB
610 }
611
612 // FIXME (#3260)
613 // If there's one line at fault we can easily point to the problem
85aaf69f 614 if lines.lines.len() == 1 {
223e47cc 615 let lo = cm.lookup_char_pos(sp.lo);
85aaf69f 616 let mut digits = 0;
9346a6ac 617 let mut num = (lines.lines[0].line_index + 1) / 10;
223e47cc
LB
618
619 // how many digits must be indent past?
85aaf69f 620 while num > 0 { num /= 10; digits += 1; }
223e47cc 621
1a4d82fc 622 let mut s = String::new();
223e47cc
LB
623 // Skip is the number of characters we need to skip because they are
624 // part of the 'filename:line ' part of the previous line.
d9579d0f 625 let skip = fm.name.chars().count() + digits + 3;
85aaf69f 626 for _ in 0..skip {
1a4d82fc 627 s.push(' ');
223e47cc 628 }
9346a6ac 629 if let Some(orig) = fm.get_line(lines.lines[0].line_index) {
85aaf69f
SL
630 let mut col = skip;
631 let mut lastc = ' ';
632 let mut iter = orig.chars().enumerate();
633 for (pos, ch) in iter.by_ref() {
634 lastc = ch;
635 if pos >= lo.col.to_usize() { break; }
1a4d82fc
JJ
636 // Whenever a tab occurs on the previous line, we insert one on
637 // the error-point-squiggly-line as well (instead of a space).
638 // That way the squiggly line will usually appear in the correct
639 // position.
85aaf69f
SL
640 match ch {
641 '\t' => {
642 col += 8 - col%8;
643 s.push('\t');
644 },
d9579d0f 645 _ => {
85aaf69f
SL
646 col += 1;
647 s.push(' ');
648 },
649 }
650 }
651
652 try!(write!(&mut err.dst, "{}", s));
d9579d0f 653 let mut s = String::from("^");
85aaf69f
SL
654 let count = match lastc {
655 // Most terminals have a tab stop every eight columns by default
656 '\t' => 8 - col%8,
d9579d0f 657 _ => 1,
85aaf69f
SL
658 };
659 col += count;
660 s.extend(::std::iter::repeat('~').take(count));
661
662 let hi = cm.lookup_char_pos(sp.hi);
663 if hi.col != lo.col {
664 for (pos, ch) in iter {
665 if pos >= hi.col.to_usize() { break; }
666 let count = match ch {
667 '\t' => 8 - col%8,
d9579d0f 668 _ => 1,
85aaf69f
SL
669 };
670 col += count;
671 s.extend(::std::iter::repeat('~').take(count));
672 }
1a4d82fc 673 }
1a4d82fc 674
85aaf69f
SL
675 if s.len() > 1 {
676 // One extra squiggly is replaced by a "^"
677 s.pop();
970d7e83 678 }
85aaf69f
SL
679
680 try!(print_maybe_styled(err,
681 &format!("{}\n", s),
682 term::attr::ForegroundColor(lvl.color())));
223e47cc 683 }
223e47cc 684 }
1a4d82fc 685 Ok(())
223e47cc
LB
686}
687
1a4d82fc 688/// Here are the differences between this and the normal `highlight_lines`:
9346a6ac 689/// `end_highlight_lines` will always put arrow on the last byte of the
1a4d82fc 690/// span (instead of the first byte). Also, when the span is too long (more
9346a6ac 691/// than 6 lines), `end_highlight_lines` will print the first line, then
1a4d82fc
JJ
692/// dot dot dot, then last line, whereas `highlight_lines` prints the first
693/// six lines.
d9579d0f 694#[allow(deprecated)]
9346a6ac 695fn end_highlight_lines(w: &mut EmitterWriter,
1a4d82fc
JJ
696 cm: &codemap::CodeMap,
697 sp: Span,
698 lvl: Level,
d9579d0f 699 lines: codemap::FileLinesResult)
c34b1796 700 -> io::Result<()> {
d9579d0f
AL
701 let lines = match lines {
702 Ok(lines) => lines,
703 Err(_) => {
704 try!(write!(&mut w.dst, "(internal compiler error: unprintable span)\n"));
705 return Ok(());
706 }
707 };
708
1a4d82fc
JJ
709 let fm = &*lines.file;
710
85aaf69f 711 let lines = &lines.lines[..];
1a4d82fc 712 if lines.len() > MAX_LINES {
9346a6ac 713 if let Some(line) = fm.get_line(lines[0].line_index) {
1a4d82fc 714 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
9346a6ac 715 lines[0].line_index + 1, line));
1a4d82fc
JJ
716 }
717 try!(write!(&mut w.dst, "...\n"));
9346a6ac
AL
718 let last_line_index = lines[lines.len() - 1].line_index;
719 if let Some(last_line) = fm.get_line(last_line_index) {
1a4d82fc 720 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
9346a6ac 721 last_line_index + 1, last_line));
1a4d82fc
JJ
722 }
723 } else {
9346a6ac
AL
724 for line_info in lines {
725 if let Some(line) = fm.get_line(line_info.line_index) {
1a4d82fc 726 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
9346a6ac 727 line_info.line_index + 1, line));
1a4d82fc
JJ
728 }
729 }
223e47cc 730 }
9346a6ac 731 let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1].line_index + 1);
1a4d82fc 732 let hi = cm.lookup_char_pos(sp.hi);
d9579d0f 733 let skip = last_line_start.chars().count();
1a4d82fc 734 let mut s = String::new();
85aaf69f 735 for _ in 0..skip {
1a4d82fc
JJ
736 s.push(' ');
737 }
9346a6ac 738 if let Some(orig) = fm.get_line(lines[0].line_index) {
85aaf69f
SL
739 let iter = orig.chars().enumerate();
740 for (pos, ch) in iter {
741 // Span seems to use half-opened interval, so subtract 1
742 if pos >= hi.col.to_usize() - 1 { break; }
743 // Whenever a tab occurs on the previous line, we insert one on
744 // the error-point-squiggly-line as well (instead of a space).
745 // That way the squiggly line will usually appear in the correct
746 // position.
747 match ch {
748 '\t' => s.push('\t'),
d9579d0f 749 _ => s.push(' '),
85aaf69f
SL
750 }
751 }
752 }
1a4d82fc
JJ
753 s.push('^');
754 s.push('\n');
755 print_maybe_styled(w,
85aaf69f 756 &s[..],
1a4d82fc
JJ
757 term::attr::ForegroundColor(lvl.color()))
758}
759
760fn print_macro_backtrace(w: &mut EmitterWriter,
761 cm: &codemap::CodeMap,
762 sp: Span)
c34b1796
AL
763 -> io::Result<()> {
764 let cs = try!(cm.with_expn_info(sp.expn_id, |expn_info| -> io::Result<_> {
85aaf69f
SL
765 match expn_info {
766 Some(ei) => {
767 let ss = ei.callee.span.map_or(String::new(),
768 |span| cm.span_to_string(span));
769 let (pre, post) = match ei.callee.format {
770 codemap::MacroAttribute => ("#[", "]"),
d9579d0f
AL
771 codemap::MacroBang => ("", "!"),
772 codemap::CompilerExpansion => ("", ""),
85aaf69f
SL
773 };
774 try!(print_diagnostic(w, &ss, Note,
d9579d0f
AL
775 &format!("in expansion of {}{}{}",
776 pre,
777 ei.callee.name,
778 post),
779 None));
85aaf69f
SL
780 let ss = cm.span_to_string(ei.call_site);
781 try!(print_diagnostic(w, &ss, Note, "expansion site", None));
782 Ok(Some(ei.call_site))
783 }
784 None => Ok(None)
785 }
1a4d82fc
JJ
786 }));
787 cs.map_or(Ok(()), |call_site| print_macro_backtrace(w, cm, call_site))
223e47cc
LB
788}
789
1a4d82fc
JJ
790pub fn expect<T, M>(diag: &SpanHandler, opt: Option<T>, msg: M) -> T where
791 M: FnOnce() -> String,
792{
223e47cc 793 match opt {
1a4d82fc 794 Some(t) => t,
85aaf69f 795 None => diag.handler().bug(&msg()),
223e47cc
LB
796 }
797}