]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
975ec0e709b7d272605e9c31b6f9c2fe057c6511
[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, T>(&self, f: F) -> T
180         where F: FnOnce() -> T
181     {
182         let count = self.err_count();
183         let result = f();
184         if self.err_count() > count {
185             self.abort_if_errors();
186         }
187         result
188     }
189     pub fn span_warn(&self, sp: Span, msg: &str) {
190         self.diagnostic().span_warn(sp, msg)
191     }
192     pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
193         self.diagnostic().span_warn_with_code(sp, msg, code)
194     }
195     pub fn warn(&self, msg: &str) {
196         self.diagnostic().warn(msg)
197     }
198     pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
199         match opt_sp {
200             Some(sp) => self.span_warn(sp, msg),
201             None => self.warn(msg),
202         }
203     }
204     pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
205         match opt_sp {
206             Some(sp) => self.span_bug(sp, msg),
207             None => self.bug(msg),
208         }
209     }
210     /// Delay a span_bug() call until abort_if_errors()
211     pub fn delay_span_bug(&self, sp: Span, msg: &str) {
212         self.diagnostic().delay_span_bug(sp, msg)
213     }
214     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
215         self.diagnostic().span_bug(sp, msg)
216     }
217     pub fn bug(&self, msg: &str) -> ! {
218         self.diagnostic().bug(msg)
219     }
220     pub fn note_without_error(&self, msg: &str) {
221         self.diagnostic().note_without_error(msg)
222     }
223     pub fn span_note_without_error(&self, sp: Span, msg: &str) {
224         self.diagnostic().span_note_without_error(sp, msg)
225     }
226     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
227         self.diagnostic().span_unimpl(sp, msg)
228     }
229     pub fn unimpl(&self, msg: &str) -> ! {
230         self.diagnostic().unimpl(msg)
231     }
232     pub fn add_lint(&self,
233                     lint: &'static lint::Lint,
234                     id: ast::NodeId,
235                     sp: Span,
236                     msg: String) {
237         let lint_id = lint::LintId::of(lint);
238         let mut lints = self.lints.borrow_mut();
239         match lints.get_mut(&id) {
240             Some(arr) => { arr.push((lint_id, sp, msg)); return; }
241             None => {}
242         }
243         lints.insert(id, vec!((lint_id, sp, msg)));
244     }
245     pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
246         let id = self.next_node_id.get();
247
248         match id.checked_add(count) {
249             Some(next) => self.next_node_id.set(next),
250             None => self.bug("Input too large, ran out of node ids!")
251         }
252
253         id
254     }
255     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
256         &self.parse_sess.span_diagnostic
257     }
258     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
259         self.parse_sess.codemap()
260     }
261     // This exists to help with refactoring to eliminate impossible
262     // cases later on
263     pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
264         self.span_bug(sp, &format!("impossible case reached: {}", msg));
265     }
266     pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
267     pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
268     pub fn count_llvm_insns(&self) -> bool {
269         self.opts.debugging_opts.count_llvm_insns
270     }
271     pub fn count_type_sizes(&self) -> bool {
272         self.opts.debugging_opts.count_type_sizes
273     }
274     pub fn time_llvm_passes(&self) -> bool {
275         self.opts.debugging_opts.time_llvm_passes
276     }
277     pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
278     pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
279     pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
280     pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
281     pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
282     pub fn print_llvm_passes(&self) -> bool {
283         self.opts.debugging_opts.print_llvm_passes
284     }
285     pub fn lto(&self) -> bool {
286         self.opts.cg.lto
287     }
288     pub fn no_landing_pads(&self) -> bool {
289         self.opts.debugging_opts.no_landing_pads
290     }
291     pub fn unstable_options(&self) -> bool {
292         self.opts.debugging_opts.unstable_options
293     }
294     pub fn print_enum_sizes(&self) -> bool {
295         self.opts.debugging_opts.print_enum_sizes
296     }
297     pub fn nonzeroing_move_hints(&self) -> bool {
298         self.opts.debugging_opts.enable_nonzeroing_move_hints
299     }
300     pub fn sysroot<'a>(&'a self) -> &'a Path {
301         match self.opts.maybe_sysroot {
302             Some (ref sysroot) => sysroot,
303             None => self.default_sysroot.as_ref()
304                         .expect("missing sysroot and default_sysroot in Session")
305         }
306     }
307     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
308         filesearch::FileSearch::new(self.sysroot(),
309                                     &self.opts.target_triple,
310                                     &self.opts.search_paths,
311                                     kind)
312     }
313     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
314         filesearch::FileSearch::new(
315             self.sysroot(),
316             config::host_triple(),
317             &self.opts.search_paths,
318             kind)
319     }
320 }
321
322 impl NodeIdAssigner for Session {
323     fn next_node_id(&self) -> NodeId {
324         self.reserve_node_ids(1)
325     }
326
327     fn peek_node_id(&self) -> NodeId {
328         self.next_node_id.get().checked_add(1).unwrap()
329     }
330 }
331
332 fn split_msg_into_multilines(msg: &str) -> Option<String> {
333     // Conditions for enabling multi-line errors:
334     if !msg.contains("mismatched types") &&
335         !msg.contains("type mismatch resolving") &&
336         !msg.contains("if and else have incompatible types") &&
337         !msg.contains("if may be missing an else clause") &&
338         !msg.contains("match arms have incompatible types") &&
339         !msg.contains("structure constructor specifies a structure of type") &&
340         !msg.contains("has an incompatible type for trait") {
341             return None
342     }
343     let first = msg.match_indices("expected").filter(|s| {
344         s.0 > 0 && (msg.char_at_reverse(s.0) == ' ' ||
345                     msg.char_at_reverse(s.0) == '(')
346     }).map(|(a, b)| (a - 1, a + b.len()));
347     let second = msg.match_indices("found").filter(|s| {
348         msg.char_at_reverse(s.0) == ' '
349     }).map(|(a, b)| (a - 1, a + b.len()));
350
351     let mut new_msg = String::new();
352     let mut head = 0;
353
354     // Insert `\n` before expected and found.
355     for (pos1, pos2) in first.zip(second) {
356         new_msg = new_msg +
357         // A `(` may be preceded by a space and it should be trimmed
358                   msg[head..pos1.0].trim_right() + // prefix
359                   "\n" +                           // insert before first
360                   &msg[pos1.0..pos1.1] +           // insert what first matched
361                   &msg[pos1.1..pos2.0] +           // between matches
362                   "\n   " +                        // insert before second
363         //           123
364         // `expected` is 3 char longer than `found`. To align the types,
365         // `found` gets 3 spaces prepended.
366                   &msg[pos2.0..pos2.1];            // insert what second matched
367
368         head = pos2.1;
369     }
370
371     let mut tail = &msg[head..];
372     let third = tail.find("(values differ")
373                    .or(tail.find("(lifetime"))
374                    .or(tail.find("(cyclic type of infinite size"));
375     // Insert `\n` before any remaining messages which match.
376     if let Some(pos) = third {
377         // The end of the message may just be wrapped in `()` without
378         // `expected`/`found`.  Push this also to a new line and add the
379         // final tail after.
380         new_msg = new_msg +
381         // `(` is usually preceded by a space and should be trimmed.
382                   tail[..pos].trim_right() + // prefix
383                   "\n" +                     // insert before paren
384                   &tail[pos..];              // append the tail
385
386         tail = "";
387     }
388
389     new_msg.push_str(tail);
390     return Some(new_msg);
391 }
392
393 pub fn build_session(sopts: config::Options,
394                      local_crate_source_file: Option<PathBuf>,
395                      registry: diagnostics::registry::Registry,
396                      cstore: Rc<for<'a> CrateStore<'a>>)
397                      -> Session {
398     // FIXME: This is not general enough to make the warning lint completely override
399     // normal diagnostic warnings, since the warning lint can also be denied and changed
400     // later via the source code.
401     let can_print_warnings = sopts.lint_opts
402         .iter()
403         .filter(|&&(ref key, _)| *key == "warnings")
404         .map(|&(_, ref level)| *level != lint::Allow)
405         .last()
406         .unwrap_or(true);
407     let treat_err_as_bug = sopts.treat_err_as_bug;
408
409     let codemap = Rc::new(codemap::CodeMap::new());
410     let emitter: Box<Emitter> = match sopts.error_format {
411         config::ErrorOutputType::HumanReadable(color_config) => {
412             Box::new(EmitterWriter::stderr(color_config, Some(registry), codemap.clone()))
413         }
414         config::ErrorOutputType::Json => {
415             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
416         }
417     };
418
419     let diagnostic_handler =
420         errors::Handler::with_emitter(can_print_warnings,
421                                       treat_err_as_bug,
422                                       emitter);
423
424     build_session_(sopts, local_crate_source_file, diagnostic_handler, codemap, cstore)
425 }
426
427 pub fn build_session_(sopts: config::Options,
428                       local_crate_source_file: Option<PathBuf>,
429                       span_diagnostic: errors::Handler,
430                       codemap: Rc<codemap::CodeMap>,
431                       cstore: Rc<for<'a> CrateStore<'a>>)
432                       -> Session {
433     let host = match Target::search(config::host_triple()) {
434         Ok(t) => t,
435         Err(e) => {
436             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
437     }
438     };
439     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
440     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
441     let default_sysroot = match sopts.maybe_sysroot {
442         Some(_) => None,
443         None => Some(filesearch::get_or_default_sysroot())
444     };
445
446     // Make the path absolute, if necessary
447     let local_crate_source_file = local_crate_source_file.map(|path|
448         if path.is_absolute() {
449             path.clone()
450         } else {
451             env::current_dir().unwrap().join(&path)
452         }
453     );
454
455     let sess = Session {
456         target: target_cfg,
457         host: host,
458         opts: sopts,
459         cstore: cstore,
460         parse_sess: p_s,
461         // For a library crate, this is always none
462         entry_fn: RefCell::new(None),
463         entry_type: Cell::new(None),
464         plugin_registrar_fn: Cell::new(None),
465         default_sysroot: default_sysroot,
466         local_crate_source_file: local_crate_source_file,
467         working_dir: env::current_dir().unwrap(),
468         lint_store: RefCell::new(lint::LintStore::new()),
469         lints: RefCell::new(NodeMap()),
470         plugin_llvm_passes: RefCell::new(Vec::new()),
471         plugin_attributes: RefCell::new(Vec::new()),
472         crate_types: RefCell::new(Vec::new()),
473         dependency_formats: RefCell::new(FnvHashMap()),
474         crate_metadata: RefCell::new(Vec::new()),
475         features: RefCell::new(feature_gate::Features::new()),
476         recursion_limit: Cell::new(64),
477         next_node_id: Cell::new(1),
478         injected_allocator: Cell::new(None),
479         available_macros: RefCell::new(HashSet::new()),
480     };
481
482     sess
483 }
484
485 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
486     let mut emitter: Box<Emitter> = match output {
487         config::ErrorOutputType::HumanReadable(color_config) => {
488             Box::new(BasicEmitter::stderr(color_config))
489         }
490         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
491     };
492     emitter.emit(None, msg, None, errors::Level::Fatal);
493     panic!(errors::FatalError);
494 }
495
496 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
497     let mut emitter: Box<Emitter> = match output {
498         config::ErrorOutputType::HumanReadable(color_config) => {
499             Box::new(BasicEmitter::stderr(color_config))
500         }
501         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
502     };
503     emitter.emit(None, msg, None, errors::Level::Warning);
504 }