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