]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
Structured diagnostics
[rust.git] / src / librustc / session / mod.rs
1 // Copyright 2012-2013 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
11 use lint;
12 use middle::cstore::CrateStore;
13 use middle::dependency_format;
14 use session::search_paths::PathKind;
15 use util::nodemap::{NodeMap, FnvHashMap};
16
17 use syntax::ast::{NodeId, NodeIdAssigner, Name};
18 use syntax::codemap::Span;
19 use syntax::errors::{self, DiagnosticBuilder};
20 use syntax::errors::emitter::{Emitter, BasicEmitter};
21 use syntax::diagnostics;
22 use syntax::feature_gate;
23 use syntax::parse;
24 use syntax::parse::ParseSess;
25 use syntax::{ast, codemap};
26 use syntax::feature_gate::AttributeType;
27
28 use rustc_back::target::Target;
29
30 use std::path::{Path, PathBuf};
31 use std::cell::{Cell, RefCell};
32 use std::collections::HashSet;
33 use std::env;
34 use std::rc::Rc;
35
36 pub mod config;
37 pub mod filesearch;
38 pub mod search_paths;
39
40 // Represents the data associated with a compilation
41 // session for a single crate.
42 pub struct Session {
43     pub target: config::Config,
44     pub host: Target,
45     pub opts: config::Options,
46     pub cstore: Rc<for<'a> CrateStore<'a>>,
47     pub parse_sess: ParseSess,
48     // For a library crate, this is always none
49     pub entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
50     pub entry_type: Cell<Option<config::EntryFnType>>,
51     pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
52     pub default_sysroot: Option<PathBuf>,
53     // The name of the root source file of the crate, in the local file system.
54     // The path is always expected to be absolute. `None` means that there is no
55     // source file.
56     pub local_crate_source_file: Option<PathBuf>,
57     pub working_dir: PathBuf,
58     pub lint_store: RefCell<lint::LintStore>,
59     pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
60     pub plugin_llvm_passes: RefCell<Vec<String>>,
61     pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
62     pub crate_types: RefCell<Vec<config::CrateType>>,
63     pub dependency_formats: RefCell<dependency_format::Dependencies>,
64     pub crate_metadata: RefCell<Vec<String>>,
65     pub features: RefCell<feature_gate::Features>,
66
67     /// The maximum recursion limit for potentially infinitely recursive
68     /// operations such as auto-dereference and monomorphization.
69     pub recursion_limit: Cell<usize>,
70
71     /// The metadata::creader module may inject an allocator dependency if it
72     /// didn't already find one, and this tracks what was injected.
73     pub injected_allocator: Cell<Option<ast::CrateNum>>,
74
75     /// Names of all bang-style macros and syntax extensions
76     /// available in this crate
77     pub available_macros: RefCell<HashSet<Name>>,
78
79     next_node_id: Cell<ast::NodeId>,
80 }
81
82 impl Session {
83     pub fn struct_span_warn<'a, 'b>(&'a self,
84                                     sp: Span,
85                                     msg: &'b str)
86                                     -> Box<DiagnosticBuilder<'a, 'b>> {
87         self.diagnostic().struct_span_warn(sp, msg)
88     }
89     pub fn struct_span_warn_with_code<'a, 'b>(&'a self,
90                                               sp: Span,
91                                               msg: &'b str,
92                                               code: &str)
93                                               -> Box<DiagnosticBuilder<'a, 'b>> {
94         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
95     }
96     pub fn struct_warn<'a, 'b>(&'a self, msg: &'b str) -> Box<DiagnosticBuilder<'a, 'b>> {
97         self.diagnostic().struct_warn(msg)
98     }
99     pub fn struct_span_err<'a, 'b>(&'a self,
100                                    sp: Span,
101                                    msg: &'b str)
102                                    -> Box<DiagnosticBuilder<'a, 'b>> {
103         self.diagnostic().struct_span_err(sp, msg)
104     }
105     pub fn struct_span_err_with_code<'a, 'b>(&'a self,
106                                              sp: Span,
107                                              msg: &'b str,
108                                              code: &str)
109                                              -> Box<DiagnosticBuilder<'a, 'b>> {
110         self.diagnostic().struct_span_err_with_code(sp, msg, code)
111     }
112     pub fn struct_err<'a, 'b>(&'a self, msg: &'b str) -> Box<DiagnosticBuilder<'a, 'b>> {
113         self.diagnostic().struct_err(msg)
114     }
115     pub fn struct_span_fatal<'a, 'b>(&'a self,
116                                      sp: Span,
117                                      msg: &'b str)
118                                      -> Box<DiagnosticBuilder<'a, 'b>> {
119         self.diagnostic().struct_span_fatal(sp, msg)
120     }
121     pub fn struct_span_fatal_with_code<'a, 'b>(&'a self,
122                                                sp: Span,
123                                                msg: &'b str,
124                                                code: &str)
125                                                -> Box<DiagnosticBuilder<'a, 'b>> {
126         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
127     }
128     pub fn struct_fatal<'a, 'b>(&'a self, msg: &'b str) -> Box<DiagnosticBuilder<'a, 'b>> {
129         self.diagnostic().struct_fatal(msg)
130     }
131
132     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
133         panic!(self.diagnostic().span_fatal(sp, msg))
134     }
135     pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! {
136         panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
137     }
138     pub fn fatal(&self, msg: &str) -> ! {
139         panic!(self.diagnostic().fatal(msg))
140     }
141     pub fn span_err_or_warn(&self, is_warning: bool, sp: Span, msg: &str) {
142         if is_warning {
143             self.span_warn(sp, msg);
144         } else {
145             self.span_err(sp, msg);
146         }
147     }
148     pub fn span_err(&self, sp: Span, msg: &str) {
149         match split_msg_into_multilines(msg) {
150             Some(msg) => self.diagnostic().span_err(sp, &msg[..]),
151             None => self.diagnostic().span_err(sp, msg)
152         }
153     }
154     pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
155         match split_msg_into_multilines(msg) {
156             Some(msg) => self.diagnostic().span_err_with_code(sp, &msg[..], code),
157             None => self.diagnostic().span_err_with_code(sp, msg, code)
158         }
159     }
160     pub fn err(&self, msg: &str) {
161         self.diagnostic().err(msg)
162     }
163     pub fn err_count(&self) -> usize {
164         self.diagnostic().err_count()
165     }
166     pub fn has_errors(&self) -> bool {
167         self.diagnostic().has_errors()
168     }
169     pub fn abort_if_errors(&self) {
170         self.diagnostic().abort_if_errors();
171     }
172     pub fn abort_if_new_errors<F>(&self, mut f: F)
173         where F: FnMut()
174     {
175         let count = self.err_count();
176         f();
177         if self.err_count() > count {
178             self.abort_if_errors();
179         }
180     }
181     pub fn span_warn(&self, sp: Span, msg: &str) {
182         self.diagnostic().span_warn(sp, msg)
183     }
184     pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
185         self.diagnostic().span_warn_with_code(sp, msg, code)
186     }
187     pub fn warn(&self, msg: &str) {
188         self.diagnostic().warn(msg)
189     }
190     pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
191         match opt_sp {
192             Some(sp) => self.span_warn(sp, msg),
193             None => self.warn(msg),
194         }
195     }
196     pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
197         match opt_sp {
198             Some(sp) => self.span_bug(sp, msg),
199             None => self.bug(msg),
200         }
201     }
202     /// Delay a span_bug() call until abort_if_errors()
203     pub fn delay_span_bug(&self, sp: Span, msg: &str) {
204         self.diagnostic().delay_span_bug(sp, msg)
205     }
206     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
207         self.diagnostic().span_bug(sp, msg)
208     }
209     pub fn bug(&self, msg: &str) -> ! {
210         self.diagnostic().bug(msg)
211     }
212     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
213         self.diagnostic().span_unimpl(sp, msg)
214     }
215     pub fn unimpl(&self, msg: &str) -> ! {
216         self.diagnostic().unimpl(msg)
217     }
218     pub fn add_lint(&self,
219                     lint: &'static lint::Lint,
220                     id: ast::NodeId,
221                     sp: Span,
222                     msg: String) {
223         let lint_id = lint::LintId::of(lint);
224         let mut lints = self.lints.borrow_mut();
225         match lints.get_mut(&id) {
226             Some(arr) => { arr.push((lint_id, sp, msg)); return; }
227             None => {}
228         }
229         lints.insert(id, vec!((lint_id, sp, msg)));
230     }
231     pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
232         let id = self.next_node_id.get();
233
234         match id.checked_add(count) {
235             Some(next) => self.next_node_id.set(next),
236             None => self.bug("Input too large, ran out of node ids!")
237         }
238
239         id
240     }
241     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
242         &self.parse_sess.span_diagnostic
243     }
244     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
245         self.parse_sess.codemap()
246     }
247     // This exists to help with refactoring to eliminate impossible
248     // cases later on
249     pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
250         self.span_bug(sp, &format!("impossible case reached: {}", msg));
251     }
252     pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
253     pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
254     pub fn count_llvm_insns(&self) -> bool {
255         self.opts.debugging_opts.count_llvm_insns
256     }
257     pub fn count_type_sizes(&self) -> bool {
258         self.opts.debugging_opts.count_type_sizes
259     }
260     pub fn time_llvm_passes(&self) -> bool {
261         self.opts.debugging_opts.time_llvm_passes
262     }
263     pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
264     pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
265     pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
266     pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
267     pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
268     pub fn print_llvm_passes(&self) -> bool {
269         self.opts.debugging_opts.print_llvm_passes
270     }
271     pub fn lto(&self) -> bool {
272         self.opts.cg.lto
273     }
274     pub fn no_landing_pads(&self) -> bool {
275         self.opts.debugging_opts.no_landing_pads
276     }
277     pub fn unstable_options(&self) -> bool {
278         self.opts.debugging_opts.unstable_options
279     }
280     pub fn print_enum_sizes(&self) -> bool {
281         self.opts.debugging_opts.print_enum_sizes
282     }
283     pub fn nonzeroing_move_hints(&self) -> bool {
284         self.opts.debugging_opts.enable_nonzeroing_move_hints
285     }
286     pub fn sysroot<'a>(&'a self) -> &'a Path {
287         match self.opts.maybe_sysroot {
288             Some (ref sysroot) => sysroot,
289             None => self.default_sysroot.as_ref()
290                         .expect("missing sysroot and default_sysroot in Session")
291         }
292     }
293     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
294         filesearch::FileSearch::new(self.sysroot(),
295                                     &self.opts.target_triple,
296                                     &self.opts.search_paths,
297                                     kind)
298     }
299     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
300         filesearch::FileSearch::new(
301             self.sysroot(),
302             config::host_triple(),
303             &self.opts.search_paths,
304             kind)
305     }
306 }
307
308 impl NodeIdAssigner for Session {
309     fn next_node_id(&self) -> NodeId {
310         self.reserve_node_ids(1)
311     }
312
313     fn peek_node_id(&self) -> NodeId {
314         self.next_node_id.get().checked_add(1).unwrap()
315     }
316 }
317
318 fn split_msg_into_multilines(msg: &str) -> Option<String> {
319     // Conditions for enabling multi-line errors:
320     if !msg.contains("mismatched types") &&
321         !msg.contains("type mismatch resolving") &&
322         !msg.contains("if and else have incompatible types") &&
323         !msg.contains("if may be missing an else clause") &&
324         !msg.contains("match arms have incompatible types") &&
325         !msg.contains("structure constructor specifies a structure of type") &&
326         !msg.contains("has an incompatible type for trait") {
327             return None
328     }
329     let first = msg.match_indices("expected").filter(|s| {
330         s.0 > 0 && (msg.char_at_reverse(s.0) == ' ' ||
331                     msg.char_at_reverse(s.0) == '(')
332     }).map(|(a, b)| (a - 1, a + b.len()));
333     let second = msg.match_indices("found").filter(|s| {
334         msg.char_at_reverse(s.0) == ' '
335     }).map(|(a, b)| (a - 1, a + b.len()));
336
337     let mut new_msg = String::new();
338     let mut head = 0;
339
340     // Insert `\n` before expected and found.
341     for (pos1, pos2) in first.zip(second) {
342         new_msg = new_msg +
343         // A `(` may be preceded by a space and it should be trimmed
344                   msg[head..pos1.0].trim_right() + // prefix
345                   "\n" +                           // insert before first
346                   &msg[pos1.0..pos1.1] +           // insert what first matched
347                   &msg[pos1.1..pos2.0] +           // between matches
348                   "\n   " +                        // insert before second
349         //           123
350         // `expected` is 3 char longer than `found`. To align the types,
351         // `found` gets 3 spaces prepended.
352                   &msg[pos2.0..pos2.1];            // insert what second matched
353
354         head = pos2.1;
355     }
356
357     let mut tail = &msg[head..];
358     let third = tail.find("(values differ")
359                    .or(tail.find("(lifetime"))
360                    .or(tail.find("(cyclic type of infinite size"));
361     // Insert `\n` before any remaining messages which match.
362     if let Some(pos) = third {
363         // The end of the message may just be wrapped in `()` without
364         // `expected`/`found`.  Push this also to a new line and add the
365         // final tail after.
366         new_msg = new_msg +
367         // `(` is usually preceded by a space and should be trimmed.
368                   tail[..pos].trim_right() + // prefix
369                   "\n" +                     // insert before paren
370                   &tail[pos..];              // append the tail
371
372         tail = "";
373     }
374
375     new_msg.push_str(tail);
376     return Some(new_msg);
377 }
378
379 pub fn build_session(sopts: config::Options,
380                      local_crate_source_file: Option<PathBuf>,
381                      registry: diagnostics::registry::Registry,
382                      cstore: Rc<for<'a> CrateStore<'a>>)
383                      -> Session {
384     // FIXME: This is not general enough to make the warning lint completely override
385     // normal diagnostic warnings, since the warning lint can also be denied and changed
386     // later via the source code.
387     let can_print_warnings = sopts.lint_opts
388         .iter()
389         .filter(|&&(ref key, _)| *key == "warnings")
390         .map(|&(_, ref level)| *level != lint::Allow)
391         .last()
392         .unwrap_or(true);
393     let treat_err_as_bug = sopts.treat_err_as_bug;
394
395     let codemap = Rc::new(codemap::CodeMap::new());
396     let diagnostic_handler =
397         errors::Handler::new(sopts.color,
398                              Some(registry),
399                              can_print_warnings,
400                              treat_err_as_bug,
401                              codemap.clone());
402
403     build_session_(sopts, local_crate_source_file, diagnostic_handler, codemap, cstore)
404 }
405
406 pub fn build_session_(sopts: config::Options,
407                       local_crate_source_file: Option<PathBuf>,
408                       span_diagnostic: errors::Handler,
409                       codemap: Rc<codemap::CodeMap>,
410                       cstore: Rc<for<'a> CrateStore<'a>>)
411                       -> Session {
412     let host = match Target::search(config::host_triple()) {
413         Ok(t) => t,
414         Err(e) => {
415             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
416     }
417     };
418     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
419     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
420     let default_sysroot = match sopts.maybe_sysroot {
421         Some(_) => None,
422         None => Some(filesearch::get_or_default_sysroot())
423     };
424
425     // Make the path absolute, if necessary
426     let local_crate_source_file = local_crate_source_file.map(|path|
427         if path.is_absolute() {
428             path.clone()
429         } else {
430             env::current_dir().unwrap().join(&path)
431         }
432     );
433
434     let sess = Session {
435         target: target_cfg,
436         host: host,
437         opts: sopts,
438         cstore: cstore,
439         parse_sess: p_s,
440         // For a library crate, this is always none
441         entry_fn: RefCell::new(None),
442         entry_type: Cell::new(None),
443         plugin_registrar_fn: Cell::new(None),
444         default_sysroot: default_sysroot,
445         local_crate_source_file: local_crate_source_file,
446         working_dir: env::current_dir().unwrap(),
447         lint_store: RefCell::new(lint::LintStore::new()),
448         lints: RefCell::new(NodeMap()),
449         plugin_llvm_passes: RefCell::new(Vec::new()),
450         plugin_attributes: RefCell::new(Vec::new()),
451         crate_types: RefCell::new(Vec::new()),
452         dependency_formats: RefCell::new(FnvHashMap()),
453         crate_metadata: RefCell::new(Vec::new()),
454         features: RefCell::new(feature_gate::Features::new()),
455         recursion_limit: Cell::new(64),
456         next_node_id: Cell::new(1),
457         injected_allocator: Cell::new(None),
458         available_macros: RefCell::new(HashSet::new()),
459     };
460
461     sess
462 }
463
464 pub fn early_error(color: errors::ColorConfig, msg: &str) -> ! {
465     let mut emitter = BasicEmitter::stderr(color);
466     emitter.emit(None, msg, None, errors::Level::Fatal);
467     panic!(errors::FatalError);
468 }
469
470 pub fn early_warn(color: errors::ColorConfig, msg: &str) {
471     let mut emitter = BasicEmitter::stderr(color);
472     emitter.emit(None, msg, None, errors::Level::Warning);
473 }