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, T>(&self, f: F) -> T
180 where F: FnOnce() -> T
182 let count = self.err_count();
184 if self.err_count() > count {
185 self.abort_if_errors();
189 pub fn span_warn(&self, sp: Span, msg: &str) {
190 self.diagnostic().span_warn(sp, msg)
192 pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
193 self.diagnostic().span_warn_with_code(sp, msg, code)
195 pub fn warn(&self, msg: &str) {
196 self.diagnostic().warn(msg)
198 pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
200 Some(sp) => self.span_warn(sp, msg),
201 None => self.warn(msg),
204 pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
206 Some(sp) => self.span_bug(sp, msg),
207 None => self.bug(msg),
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)
214 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
215 self.diagnostic().span_bug(sp, msg)
217 pub fn bug(&self, msg: &str) -> ! {
218 self.diagnostic().bug(msg)
220 pub fn note_without_error(&self, msg: &str) {
221 self.diagnostic().note_without_error(msg)
223 pub fn span_note_without_error(&self, sp: Span, msg: &str) {
224 self.diagnostic().span_note_without_error(sp, msg)
226 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
227 self.diagnostic().span_unimpl(sp, msg)
229 pub fn unimpl(&self, msg: &str) -> ! {
230 self.diagnostic().unimpl(msg)
232 pub fn add_lint(&self,
233 lint: &'static lint::Lint,
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; }
243 lints.insert(id, vec!((lint_id, sp, msg)));
245 pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
246 let id = self.next_node_id.get();
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!")
255 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
256 &self.parse_sess.span_diagnostic
258 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
259 self.parse_sess.codemap()
261 // This exists to help with refactoring to eliminate impossible
263 pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
264 self.span_bug(sp, &format!("impossible case reached: {}", msg));
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
271 pub fn count_type_sizes(&self) -> bool {
272 self.opts.debugging_opts.count_type_sizes
274 pub fn time_llvm_passes(&self) -> bool {
275 self.opts.debugging_opts.time_llvm_passes
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
285 pub fn lto(&self) -> bool {
288 pub fn no_landing_pads(&self) -> bool {
289 self.opts.debugging_opts.no_landing_pads
291 pub fn unstable_options(&self) -> bool {
292 self.opts.debugging_opts.unstable_options
294 pub fn print_enum_sizes(&self) -> bool {
295 self.opts.debugging_opts.print_enum_sizes
297 pub fn nonzeroing_move_hints(&self) -> bool {
298 self.opts.debugging_opts.enable_nonzeroing_move_hints
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")
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,
313 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
314 filesearch::FileSearch::new(
316 config::host_triple(),
317 &self.opts.search_paths,
322 impl NodeIdAssigner for Session {
323 fn next_node_id(&self) -> NodeId {
324 self.reserve_node_ids(1)
327 fn peek_node_id(&self) -> NodeId {
328 self.next_node_id.get().checked_add(1).unwrap()
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") {
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()));
351 let mut new_msg = String::new();
354 // Insert `\n` before expected and found.
355 for (pos1, pos2) in first.zip(second) {
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
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
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
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
389 new_msg.push_str(tail);
390 return Some(new_msg);
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>>)
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
403 .filter(|&&(ref key, _)| *key == "warnings")
404 .map(|&(_, ref level)| *level != lint::Allow)
407 let treat_err_as_bug = sopts.treat_err_as_bug;
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()))
414 config::ErrorOutputType::Json => {
415 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
419 let diagnostic_handler =
420 errors::Handler::with_emitter(can_print_warnings,
424 build_session_(sopts, local_crate_source_file, diagnostic_handler, codemap, cstore)
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>>)
433 let host = match Target::search(config::host_triple()) {
436 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
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 {
443 None => Some(filesearch::get_or_default_sysroot())
446 // Make the path absolute, if necessary
447 let local_crate_source_file = local_crate_source_file.map(|path|
448 if path.is_absolute() {
451 env::current_dir().unwrap().join(&path)
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()),
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))
490 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
492 emitter.emit(None, msg, None, errors::Level::Fatal);
493 panic!(errors::FatalError);
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))
501 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
503 emitter.emit(None, msg, None, errors::Level::Warning);