syntex_errors/
diagnostic_builder.rs

1// Copyright 2012-2015 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
11use Diagnostic;
12use DiagnosticStyledString;
13
14use Level;
15use Handler;
16use std::fmt::{self, Debug};
17use std::ops::{Deref, DerefMut};
18use std::thread::panicking;
19use syntax_pos::{MultiSpan, Span};
20
21/// Used for emitting structured error messages and other diagnostic information.
22#[must_use]
23#[derive(Clone)]
24pub struct DiagnosticBuilder<'a> {
25    handler: &'a Handler,
26    diagnostic: Diagnostic,
27}
28
29/// In general, the `DiagnosticBuilder` uses deref to allow access to
30/// the fields and methods of the embedded `diagnostic` in a
31/// transparent way.  *However,* many of the methods are intended to
32/// be used in a chained way, and hence ought to return `self`. In
33/// that case, we can't just naively forward to the method on the
34/// `diagnostic`, because the return type would be a `&Diagnostic`
35/// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
36/// it easy to declare such methods on the builder.
37macro_rules! forward {
38    // Forward pattern for &self -> &Self
39    (pub fn $n:ident(&self, $($name:ident: $ty:ty),*) -> &Self) => {
40        pub fn $n(&self, $($name: $ty),*) -> &Self {
41            self.diagnostic.$n($($name),*);
42            self
43        }
44    };
45
46    // Forward pattern for &mut self -> &mut Self
47    (pub fn $n:ident(&mut self, $($name:ident: $ty:ty),*) -> &mut Self) => {
48        pub fn $n(&mut self, $($name: $ty),*) -> &mut Self {
49            self.diagnostic.$n($($name),*);
50            self
51        }
52    };
53
54    // Forward pattern for &mut self -> &mut Self, with S: Into<MultiSpan>
55    // type parameter. No obvious way to make this more generic.
56    (pub fn $n:ident<S: Into<MultiSpan>>(&mut self, $($name:ident: $ty:ty),*) -> &mut Self) => {
57        pub fn $n<S: Into<MultiSpan>>(&mut self, $($name: $ty),*) -> &mut Self {
58            self.diagnostic.$n($($name),*);
59            self
60        }
61    };
62}
63
64impl<'a> Deref for DiagnosticBuilder<'a> {
65    type Target = Diagnostic;
66
67    fn deref(&self) -> &Diagnostic {
68        &self.diagnostic
69    }
70}
71
72impl<'a> DerefMut for DiagnosticBuilder<'a> {
73    fn deref_mut(&mut self) -> &mut Diagnostic {
74        &mut self.diagnostic
75    }
76}
77
78impl<'a> DiagnosticBuilder<'a> {
79    /// Emit the diagnostic.
80    pub fn emit(&mut self) {
81        if self.cancelled() {
82            return;
83        }
84
85        match self.level {
86            Level::Bug |
87            Level::Fatal |
88            Level::PhaseFatal |
89            Level::Error => {
90                self.handler.bump_err_count();
91            }
92
93            Level::Warning |
94            Level::Note |
95            Level::Help |
96            Level::Cancelled => {
97            }
98        }
99
100        self.handler.emitter.borrow_mut().emit(&self);
101        self.cancel();
102
103        if self.level == Level::Error {
104            self.handler.panic_if_treat_err_as_bug();
105        }
106
107        // if self.is_fatal() {
108        //     panic!(FatalError);
109        // }
110    }
111
112    /// Add a span/label to be included in the resulting snippet.
113    /// This is pushed onto the `MultiSpan` that was created when the
114    /// diagnostic was first built. If you don't call this function at
115    /// all, and you just supplied a `Span` to create the diagnostic,
116    /// then the snippet will just include that `Span`, which is
117    /// called the primary span.
118    pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
119        self.diagnostic.span_label(span, label);
120        self
121    }
122
123    forward!(pub fn note_expected_found(&mut self,
124                                        label: &fmt::Display,
125                                        expected: DiagnosticStyledString,
126                                        found: DiagnosticStyledString)
127                                        -> &mut Self);
128
129    forward!(pub fn note_expected_found_extra(&mut self,
130                                              label: &fmt::Display,
131                                              expected: DiagnosticStyledString,
132                                              found: DiagnosticStyledString,
133                                              expected_extra: &fmt::Display,
134                                              found_extra: &fmt::Display)
135                                              -> &mut Self);
136
137    forward!(pub fn note(&mut self, msg: &str) -> &mut Self);
138    forward!(pub fn span_note<S: Into<MultiSpan>>(&mut self,
139                                                  sp: S,
140                                                  msg: &str)
141                                                  -> &mut Self);
142    forward!(pub fn warn(&mut self, msg: &str) -> &mut Self);
143    forward!(pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self);
144    forward!(pub fn help(&mut self , msg: &str) -> &mut Self);
145    forward!(pub fn span_help<S: Into<MultiSpan>>(&mut self,
146                                                  sp: S,
147                                                  msg: &str)
148                                                  -> &mut Self);
149    forward!(pub fn span_suggestion(&mut self,
150                                    sp: Span,
151                                    msg: &str,
152                                    suggestion: String)
153                                    -> &mut Self);
154    forward!(pub fn span_suggestions(&mut self,
155                                     sp: Span,
156                                     msg: &str,
157                                     suggestions: Vec<String>)
158                                     -> &mut Self);
159    forward!(pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self);
160    forward!(pub fn code(&mut self, s: String) -> &mut Self);
161
162    /// Convenience function for internal use, clients should use one of the
163    /// struct_* methods on Handler.
164    pub fn new(handler: &'a Handler, level: Level, message: &str) -> DiagnosticBuilder<'a> {
165        DiagnosticBuilder::new_with_code(handler, level, None, message)
166    }
167
168    /// Convenience function for internal use, clients should use one of the
169    /// struct_* methods on Handler.
170    pub fn new_with_code(handler: &'a Handler,
171                         level: Level,
172                         code: Option<String>,
173                         message: &str)
174                         -> DiagnosticBuilder<'a> {
175        DiagnosticBuilder {
176            handler: handler,
177            diagnostic: Diagnostic::new_with_code(level, code, message)
178        }
179    }
180
181    pub fn into_diagnostic(mut self) -> Diagnostic {
182        // annoyingly, the Drop impl means we can't actually move
183        let result = self.diagnostic.clone();
184        self.cancel();
185        result
186    }
187}
188
189impl<'a> Debug for DiagnosticBuilder<'a> {
190    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
191        self.diagnostic.fmt(f)
192    }
193}
194
195/// Destructor bomb - a `DiagnosticBuilder` must be either emitted or cancelled
196/// or we emit a bug.
197impl<'a> Drop for DiagnosticBuilder<'a> {
198    fn drop(&mut self) {
199        if !panicking() && !self.cancelled() {
200            let mut db = DiagnosticBuilder::new(self.handler,
201                                                Level::Bug,
202                                                "Error constructed but not emitted");
203            db.emit();
204            panic!();
205        }
206    }
207}
208