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