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.
13 use metadata::cstore::CStore;
14 use metadata::filesearch;
15 use session::search_paths::PathKind;
16 use util::nodemap::NodeMap;
20 use syntax::ast::NodeId;
21 use syntax::codemap::Span;
22 use syntax::diagnostic::{self, Emitter};
23 use syntax::diagnostics;
24 use syntax::feature_gate;
26 use syntax::parse::token;
27 use syntax::parse::ParseSess;
28 use syntax::{ast, codemap};
30 use rustc_back::target::Target;
33 use std::cell::{Cell, RefCell};
38 // Represents the data associated with a compilation
39 // session for a single crate.
41 pub target: config::Config,
43 pub opts: config::Options,
45 pub parse_sess: ParseSess,
46 // For a library crate, this is always none
47 pub entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
48 pub entry_type: Cell<Option<config::EntryFnType>>,
49 pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
50 pub default_sysroot: Option<Path>,
51 // The name of the root source file of the crate, in the local file system. The path is always
52 // expected to be absolute. `None` means that there is no source file.
53 pub local_crate_source_file: Option<Path>,
54 pub working_dir: Path,
55 pub lint_store: RefCell<lint::LintStore>,
56 pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
57 pub crate_types: RefCell<Vec<config::CrateType>>,
58 pub crate_metadata: RefCell<Vec<String>>,
59 pub features: RefCell<feature_gate::Features>,
61 /// The maximum recursion limit for potentially infinitely recursive
62 /// operations such as auto-dereference and monomorphization.
63 pub recursion_limit: Cell<uint>,
65 pub can_print_warnings: bool
69 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
70 self.diagnostic().span_fatal(sp, msg)
72 pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! {
73 self.diagnostic().span_fatal_with_code(sp, msg, code)
75 pub fn fatal(&self, msg: &str) -> ! {
76 self.diagnostic().handler().fatal(msg)
78 pub fn span_err(&self, sp: Span, msg: &str) {
79 match split_msg_into_multilines(msg) {
80 Some(msg) => self.diagnostic().span_err(sp, &msg[]),
81 None => self.diagnostic().span_err(sp, msg)
84 pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
85 match split_msg_into_multilines(msg) {
86 Some(msg) => self.diagnostic().span_err_with_code(sp, &msg[], code),
87 None => self.diagnostic().span_err_with_code(sp, msg, code)
90 pub fn err(&self, msg: &str) {
91 self.diagnostic().handler().err(msg)
93 pub fn err_count(&self) -> uint {
94 self.diagnostic().handler().err_count()
96 pub fn has_errors(&self) -> bool {
97 self.diagnostic().handler().has_errors()
99 pub fn abort_if_errors(&self) {
100 self.diagnostic().handler().abort_if_errors()
102 pub fn span_warn(&self, sp: Span, msg: &str) {
103 if self.can_print_warnings {
104 self.diagnostic().span_warn(sp, msg)
107 pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
108 if self.can_print_warnings {
109 self.diagnostic().span_warn_with_code(sp, msg, code)
112 pub fn warn(&self, msg: &str) {
113 if self.can_print_warnings {
114 self.diagnostic().handler().warn(msg)
117 pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
119 Some(sp) => self.span_warn(sp, msg),
120 None => self.warn(msg),
123 pub fn span_note(&self, sp: Span, msg: &str) {
124 self.diagnostic().span_note(sp, msg)
126 pub fn span_end_note(&self, sp: Span, msg: &str) {
127 self.diagnostic().span_end_note(sp, msg)
129 pub fn span_help(&self, sp: Span, msg: &str) {
130 self.diagnostic().span_help(sp, msg)
132 pub fn fileline_note(&self, sp: Span, msg: &str) {
133 self.diagnostic().fileline_note(sp, msg)
135 pub fn fileline_help(&self, sp: Span, msg: &str) {
136 self.diagnostic().fileline_help(sp, msg)
138 pub fn note(&self, msg: &str) {
139 self.diagnostic().handler().note(msg)
141 pub fn help(&self, msg: &str) {
142 self.diagnostic().handler().note(msg)
144 pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
146 Some(sp) => self.span_bug(sp, msg),
147 None => self.bug(msg),
150 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
151 self.diagnostic().span_bug(sp, msg)
153 pub fn bug(&self, msg: &str) -> ! {
154 self.diagnostic().handler().bug(msg)
156 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
157 self.diagnostic().span_unimpl(sp, msg)
159 pub fn unimpl(&self, msg: &str) -> ! {
160 self.diagnostic().handler().unimpl(msg)
162 pub fn add_lint(&self,
163 lint: &'static lint::Lint,
167 let lint_id = lint::LintId::of(lint);
168 let mut lints = self.lints.borrow_mut();
169 match lints.get_mut(&id) {
170 Some(arr) => { arr.push((lint_id, sp, msg)); return; }
173 lints.insert(id, vec!((lint_id, sp, msg)));
175 pub fn next_node_id(&self) -> ast::NodeId {
176 self.parse_sess.next_node_id()
178 pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
179 self.parse_sess.reserve_node_ids(count)
181 pub fn diagnostic<'a>(&'a self) -> &'a diagnostic::SpanHandler {
182 &self.parse_sess.span_diagnostic
184 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
185 &self.parse_sess.span_diagnostic.cm
187 // This exists to help with refactoring to eliminate impossible
189 pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
191 &format!("impossible case reached: {}", msg)[]);
193 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
194 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
195 pub fn count_llvm_insns(&self) -> bool {
196 self.opts.debugging_opts.count_llvm_insns
198 pub fn count_type_sizes(&self) -> bool {
199 self.opts.debugging_opts.count_type_sizes
201 pub fn time_llvm_passes(&self) -> bool {
202 self.opts.debugging_opts.time_llvm_passes
204 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
205 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
206 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
207 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
208 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
209 pub fn print_llvm_passes(&self) -> bool {
210 self.opts.debugging_opts.print_llvm_passes
212 pub fn lto(&self) -> bool {
215 pub fn no_landing_pads(&self) -> bool {
216 self.opts.debugging_opts.no_landing_pads
218 pub fn unstable_options(&self) -> bool {
219 self.opts.debugging_opts.unstable_options
221 pub fn print_enum_sizes(&self) -> bool {
222 self.opts.debugging_opts.print_enum_sizes
224 pub fn sysroot<'a>(&'a self) -> &'a Path {
225 match self.opts.maybe_sysroot {
226 Some (ref sysroot) => sysroot,
227 None => self.default_sysroot.as_ref()
228 .expect("missing sysroot and default_sysroot in Session")
231 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
232 filesearch::FileSearch::new(self.sysroot(),
233 &self.opts.target_triple[],
234 &self.opts.search_paths,
237 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
238 filesearch::FileSearch::new(
240 config::host_triple(),
241 &self.opts.search_paths,
246 fn split_msg_into_multilines(msg: &str) -> Option<String> {
247 // Conditions for enabling multi-line errors:
248 if !msg.contains("mismatched types") &&
249 !msg.contains("type mismatch resolving") &&
250 !msg.contains("if and else have incompatible types") &&
251 !msg.contains("if may be missing an else clause") &&
252 !msg.contains("match arms have incompatible types") &&
253 !msg.contains("structure constructor specifies a structure of type") {
257 let first = Regex::new(r"[( ]expected").unwrap();
258 let second = Regex::new(r" found").unwrap();
259 let third = Regex::new(
260 r"\((values differ|lifetime|cyclic type of infinite size)").unwrap();
262 let mut new_msg = String::new();
265 // Insert `\n` before expected and found.
266 for (pos1, pos2) in first.find_iter(msg).zip(
267 second.find_iter(msg)) {
269 // A `(` may be preceded by a space and it should be trimmed
270 msg[head..pos1.0].trim_right() + // prefix
271 "\n" + // insert before first
272 &msg[pos1.0..pos1.1] + // insert what first matched
273 &msg[pos1.1..pos2.0] + // between matches
274 "\n " + // insert before second
276 // `expected` is 3 char longer than `found`. To align the types, `found` gets
277 // 3 spaces prepended.
278 &msg[pos2.0..pos2.1]; // insert what second matched
283 let mut tail = &msg[head..];
284 // Insert `\n` before any remaining messages which match.
285 for pos in third.find_iter(tail).take(1) {
286 // The end of the message may just be wrapped in `()` without `expected`/`found`.
287 // Push this also to a new line and add the final tail after.
289 // `(` is usually preceded by a space and should be trimmed.
290 tail[..pos.0].trim_right() + // prefix
291 "\n" + // insert before paren
292 &tail[pos.0..]; // append the tail
297 new_msg.push_str(tail);
302 pub fn build_session(sopts: config::Options,
303 local_crate_source_file: Option<Path>,
304 registry: diagnostics::registry::Registry)
306 let codemap = codemap::CodeMap::new();
307 let diagnostic_handler =
308 diagnostic::default_handler(sopts.color, Some(registry));
309 let span_diagnostic_handler =
310 diagnostic::mk_span_handler(diagnostic_handler, codemap);
312 build_session_(sopts, local_crate_source_file, span_diagnostic_handler)
315 pub fn build_session_(sopts: config::Options,
316 local_crate_source_file: Option<Path>,
317 span_diagnostic: diagnostic::SpanHandler)
319 let host = match Target::search(config::host_triple()) {
322 span_diagnostic.handler()
323 .fatal((format!("Error loading host specification: {}", e)).as_slice());
326 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
327 let p_s = parse::new_parse_sess_special_handler(span_diagnostic);
328 let default_sysroot = match sopts.maybe_sysroot {
330 None => Some(filesearch::get_or_default_sysroot())
333 // Make the path absolute, if necessary
334 let local_crate_source_file = local_crate_source_file.map(|path|
335 if path.is_absolute() {
338 os::getcwd().unwrap().join(&path)
342 let can_print_warnings = sopts.lint_opts
344 .filter(|&&(ref key, _)| *key == "warnings")
345 .map(|&(_, ref level)| *level != lint::Allow)
353 cstore: CStore::new(token::get_ident_interner()),
355 // For a library crate, this is always none
356 entry_fn: RefCell::new(None),
357 entry_type: Cell::new(None),
358 plugin_registrar_fn: Cell::new(None),
359 default_sysroot: default_sysroot,
360 local_crate_source_file: local_crate_source_file,
361 working_dir: os::getcwd().unwrap(),
362 lint_store: RefCell::new(lint::LintStore::new()),
363 lints: RefCell::new(NodeMap()),
364 crate_types: RefCell::new(Vec::new()),
365 crate_metadata: RefCell::new(Vec::new()),
366 features: RefCell::new(feature_gate::Features::new()),
367 recursion_limit: Cell::new(64),
368 can_print_warnings: can_print_warnings
371 sess.lint_store.borrow_mut().register_builtin(Some(&sess));
375 // Seems out of place, but it uses session, so I'm putting it here
376 pub fn expect<T, M>(sess: &Session, opt: Option<T>, msg: M) -> T where
377 M: FnOnce() -> String,
379 diagnostic::expect(sess.diagnostic(), opt, msg)
382 pub fn early_error(msg: &str) -> ! {
383 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
384 emitter.emit(None, msg, None, diagnostic::Fatal);
385 panic!(diagnostic::FatalError);
388 pub fn early_warn(msg: &str) {
389 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
390 emitter.emit(None, msg, None, diagnostic::Warning);