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.
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.
12 use middle::cstore::CrateStore;
13 use middle::dependency_format;
14 use session::search_paths::PathKind;
15 use util::nodemap::{NodeMap, FnvHashMap};
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;
25 use syntax::parse::ParseSess;
26 use syntax::{ast, codemap};
27 use syntax::feature_gate::AttributeType;
29 use rustc_back::target::Target;
31 use std::path::{Path, PathBuf};
32 use std::cell::{Cell, RefCell};
33 use std::collections::HashSet;
41 // Represents the data associated with a compilation
42 // session for a single crate.
44 pub target: config::Config,
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
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>,
68 /// The maximum recursion limit for potentially infinitely recursive
69 /// operations such as auto-dereference and monomorphization.
70 pub recursion_limit: Cell<usize>,
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>>,
76 /// Names of all bang-style macros and syntax extensions
77 /// available in this crate
78 pub available_macros: RefCell<HashSet<Name>>,
80 next_node_id: Cell<ast::NodeId>,
84 pub fn struct_span_warn<'a>(&'a self,
87 -> DiagnosticBuilder<'a> {
88 self.diagnostic().struct_span_warn(sp, msg)
90 pub fn struct_span_warn_with_code<'a>(&'a self,
94 -> DiagnosticBuilder<'a> {
95 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
97 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
98 self.diagnostic().struct_warn(msg)
100 pub fn struct_span_err<'a>(&'a self,
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),
109 pub fn struct_span_err_with_code<'a>(&'a self,
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),
119 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
120 self.diagnostic().struct_err(msg)
122 pub fn struct_span_fatal<'a>(&'a self,
125 -> DiagnosticBuilder<'a> {
126 self.diagnostic().struct_span_fatal(sp, msg)
128 pub fn struct_span_fatal_with_code<'a>(&'a self,
132 -> DiagnosticBuilder<'a> {
133 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
135 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
136 self.diagnostic().struct_fatal(msg)
139 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
140 panic!(self.diagnostic().span_fatal(sp, msg))
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))
145 pub fn fatal(&self, msg: &str) -> ! {
146 panic!(self.diagnostic().fatal(msg))
148 pub fn span_err_or_warn(&self, is_warning: bool, sp: Span, msg: &str) {
150 self.span_warn(sp, msg);
152 self.span_err(sp, msg);
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)
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)
167 pub fn err(&self, msg: &str) {
168 self.diagnostic().err(msg)
170 pub fn err_count(&self) -> usize {
171 self.diagnostic().err_count()
173 pub fn has_errors(&self) -> bool {
174 self.diagnostic().has_errors()
176 pub fn abort_if_errors(&self) {
177 self.diagnostic().abort_if_errors();
179 pub fn abort_if_new_errors<F>(&self, mut f: F)
182 let count = self.err_count();
184 if self.err_count() > count {
185 self.abort_if_errors();
188 pub fn span_warn(&self, sp: Span, msg: &str) {
189 self.diagnostic().span_warn(sp, msg)
191 pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
192 self.diagnostic().span_warn_with_code(sp, msg, code)
194 pub fn warn(&self, msg: &str) {
195 self.diagnostic().warn(msg)
197 pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
199 Some(sp) => self.span_warn(sp, msg),
200 None => self.warn(msg),
203 pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
205 Some(sp) => self.span_bug(sp, msg),
206 None => self.bug(msg),
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)
213 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
214 self.diagnostic().span_bug(sp, msg)
216 pub fn bug(&self, msg: &str) -> ! {
217 self.diagnostic().bug(msg)
219 pub fn note_without_error(&self, msg: &str) {
220 self.diagnostic().note_without_error(msg)
222 pub fn span_note_without_error(&self, sp: Span, msg: &str) {
223 self.diagnostic().span_note_without_error(sp, msg)
225 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
226 self.diagnostic().span_unimpl(sp, msg)
228 pub fn unimpl(&self, msg: &str) -> ! {
229 self.diagnostic().unimpl(msg)
231 pub fn add_lint(&self,
232 lint: &'static lint::Lint,
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; }
242 lints.insert(id, vec!((lint_id, sp, msg)));
244 pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
245 let id = self.next_node_id.get();
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!")
254 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
255 &self.parse_sess.span_diagnostic
257 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
258 self.parse_sess.codemap()
260 // This exists to help with refactoring to eliminate impossible
262 pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
263 self.span_bug(sp, &format!("impossible case reached: {}", msg));
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
270 pub fn count_type_sizes(&self) -> bool {
271 self.opts.debugging_opts.count_type_sizes
273 pub fn time_llvm_passes(&self) -> bool {
274 self.opts.debugging_opts.time_llvm_passes
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
284 pub fn lto(&self) -> bool {
287 pub fn no_landing_pads(&self) -> bool {
288 self.opts.debugging_opts.no_landing_pads
290 pub fn unstable_options(&self) -> bool {
291 self.opts.debugging_opts.unstable_options
293 pub fn print_enum_sizes(&self) -> bool {
294 self.opts.debugging_opts.print_enum_sizes
296 pub fn nonzeroing_move_hints(&self) -> bool {
297 self.opts.debugging_opts.enable_nonzeroing_move_hints
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")
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,
312 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
313 filesearch::FileSearch::new(
315 config::host_triple(),
316 &self.opts.search_paths,
321 impl NodeIdAssigner for Session {
322 fn next_node_id(&self) -> NodeId {
323 self.reserve_node_ids(1)
326 fn peek_node_id(&self) -> NodeId {
327 self.next_node_id.get().checked_add(1).unwrap()
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") {
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()));
350 let mut new_msg = String::new();
353 // Insert `\n` before expected and found.
354 for (pos1, pos2) in first.zip(second) {
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
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
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
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
388 new_msg.push_str(tail);
389 return Some(new_msg);
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>>)
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
402 .filter(|&&(ref key, _)| *key == "warnings")
403 .map(|&(_, ref level)| *level != lint::Allow)
406 let treat_err_as_bug = sopts.treat_err_as_bug;
408 let codemap = Rc::new(codemap::CodeMap::new());
409 let emitter: Box<Emitter> = match sopts.output {
410 config::ErrorOutputType::Tty(color_config) => {
411 Box::new(EmitterWriter::stderr(color_config, Some(registry), codemap.clone()))
413 config::ErrorOutputType::Json => {
414 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
418 let diagnostic_handler =
419 errors::Handler::with_emitter(can_print_warnings,
423 build_session_(sopts, local_crate_source_file, diagnostic_handler, codemap, cstore)
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>>)
432 let host = match Target::search(config::host_triple()) {
435 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
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 {
442 None => Some(filesearch::get_or_default_sysroot())
445 // Make the path absolute, if necessary
446 let local_crate_source_file = local_crate_source_file.map(|path|
447 if path.is_absolute() {
450 env::current_dir().unwrap().join(&path)
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()),
484 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
485 let mut emitter: Box<Emitter> = match output {
486 config::ErrorOutputType::Tty(color_config) => Box::new(BasicEmitter::stderr(color_config)),
487 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
489 emitter.emit(None, msg, None, errors::Level::Fatal);
490 panic!(errors::FatalError);
493 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
494 let mut emitter: Box<Emitter> = match output {
495 config::ErrorOutputType::Tty(color_config) => Box::new(BasicEmitter::stderr(color_config)),
496 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
498 emitter.emit(None, msg, None, errors::Level::Warning);