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 metadata::cstore::CStore;
13 use metadata::filesearch;
14 use session::search_paths::PathKind;
15 use util::nodemap::NodeMap;
17 use syntax::ast::NodeId;
18 use syntax::codemap::Span;
19 use syntax::diagnostic::{self, Emitter};
20 use syntax::diagnostics;
21 use syntax::feature_gate;
23 use syntax::parse::token;
24 use syntax::parse::ParseSess;
25 use syntax::{ast, codemap};
27 use rustc_back::target::Target;
29 use std::path::{Path, PathBuf};
30 use std::cell::{Cell, RefCell};
36 // Represents the data associated with a compilation
37 // session for a single crate.
39 pub target: config::Config,
41 pub opts: config::Options,
43 pub parse_sess: ParseSess,
44 // For a library crate, this is always none
45 pub entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
46 pub entry_type: Cell<Option<config::EntryFnType>>,
47 pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
48 pub default_sysroot: Option<PathBuf>,
49 // The name of the root source file of the crate, in the local file system. The path is always
50 // expected to be absolute. `None` means that there is no source file.
51 pub local_crate_source_file: Option<PathBuf>,
52 pub working_dir: PathBuf,
53 pub lint_store: RefCell<lint::LintStore>,
54 pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
55 pub plugin_llvm_passes: RefCell<Vec<String>>,
56 pub crate_types: RefCell<Vec<config::CrateType>>,
57 pub crate_metadata: RefCell<Vec<String>>,
58 pub features: RefCell<feature_gate::Features>,
60 /// The maximum recursion limit for potentially infinitely recursive
61 /// operations such as auto-dereference and monomorphization.
62 pub recursion_limit: Cell<usize>,
64 pub can_print_warnings: bool
68 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
69 if self.opts.treat_err_as_bug {
70 self.span_bug(sp, msg);
72 panic!(self.diagnostic().span_fatal(sp, msg))
74 pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! {
75 if self.opts.treat_err_as_bug {
76 self.span_bug(sp, msg);
78 panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
80 pub fn fatal(&self, msg: &str) -> ! {
81 if self.opts.treat_err_as_bug {
84 self.diagnostic().handler().fatal(msg)
86 pub fn span_err(&self, sp: Span, msg: &str) {
87 if self.opts.treat_err_as_bug {
88 self.span_bug(sp, msg);
90 match split_msg_into_multilines(msg) {
91 Some(msg) => self.diagnostic().span_err(sp, &msg[..]),
92 None => self.diagnostic().span_err(sp, msg)
95 pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
96 if self.opts.treat_err_as_bug {
97 self.span_bug(sp, msg);
99 match split_msg_into_multilines(msg) {
100 Some(msg) => self.diagnostic().span_err_with_code(sp, &msg[..], code),
101 None => self.diagnostic().span_err_with_code(sp, msg, code)
104 pub fn err(&self, msg: &str) {
105 if self.opts.treat_err_as_bug {
108 self.diagnostic().handler().err(msg)
110 pub fn err_count(&self) -> usize {
111 self.diagnostic().handler().err_count()
113 pub fn has_errors(&self) -> bool {
114 self.diagnostic().handler().has_errors()
116 pub fn abort_if_errors(&self) {
117 self.diagnostic().handler().abort_if_errors()
119 pub fn span_warn(&self, sp: Span, msg: &str) {
120 if self.can_print_warnings {
121 self.diagnostic().span_warn(sp, msg)
124 pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
125 if self.can_print_warnings {
126 self.diagnostic().span_warn_with_code(sp, msg, code)
129 pub fn warn(&self, msg: &str) {
130 if self.can_print_warnings {
131 self.diagnostic().handler().warn(msg)
134 pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
136 Some(sp) => self.span_warn(sp, msg),
137 None => self.warn(msg),
140 pub fn span_note(&self, sp: Span, msg: &str) {
141 self.diagnostic().span_note(sp, msg)
143 pub fn span_end_note(&self, sp: Span, msg: &str) {
144 self.diagnostic().span_end_note(sp, msg)
147 /// Prints out a message with a suggested edit of the code.
149 /// See `diagnostic::RenderSpan::Suggestion` for more information.
150 pub fn span_suggestion(&self, sp: Span, msg: &str, suggestion: String) {
151 self.diagnostic().span_suggestion(sp, msg, suggestion)
153 pub fn span_help(&self, sp: Span, msg: &str) {
154 self.diagnostic().span_help(sp, msg)
156 pub fn fileline_note(&self, sp: Span, msg: &str) {
157 self.diagnostic().fileline_note(sp, msg)
159 pub fn fileline_help(&self, sp: Span, msg: &str) {
160 self.diagnostic().fileline_help(sp, msg)
162 pub fn note(&self, msg: &str) {
163 self.diagnostic().handler().note(msg)
165 pub fn help(&self, msg: &str) {
166 self.diagnostic().handler().help(msg)
168 pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
170 Some(sp) => self.span_bug(sp, msg),
171 None => self.bug(msg),
174 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
175 self.diagnostic().span_bug(sp, msg)
177 pub fn bug(&self, msg: &str) -> ! {
178 self.diagnostic().handler().bug(msg)
180 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
181 self.diagnostic().span_unimpl(sp, msg)
183 pub fn unimpl(&self, msg: &str) -> ! {
184 self.diagnostic().handler().unimpl(msg)
186 pub fn add_lint(&self,
187 lint: &'static lint::Lint,
191 let lint_id = lint::LintId::of(lint);
192 let mut lints = self.lints.borrow_mut();
193 match lints.get_mut(&id) {
194 Some(arr) => { arr.push((lint_id, sp, msg)); return; }
197 lints.insert(id, vec!((lint_id, sp, msg)));
199 pub fn next_node_id(&self) -> ast::NodeId {
200 self.parse_sess.next_node_id()
202 pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
203 self.parse_sess.reserve_node_ids(count)
205 pub fn diagnostic<'a>(&'a self) -> &'a diagnostic::SpanHandler {
206 &self.parse_sess.span_diagnostic
208 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
209 &self.parse_sess.span_diagnostic.cm
211 // This exists to help with refactoring to eliminate impossible
213 pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
215 &format!("impossible case reached: {}", msg));
217 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
218 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
219 pub fn count_llvm_insns(&self) -> bool {
220 self.opts.debugging_opts.count_llvm_insns
222 pub fn count_type_sizes(&self) -> bool {
223 self.opts.debugging_opts.count_type_sizes
225 pub fn time_llvm_passes(&self) -> bool {
226 self.opts.debugging_opts.time_llvm_passes
228 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
229 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
230 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
231 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
232 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
233 pub fn print_llvm_passes(&self) -> bool {
234 self.opts.debugging_opts.print_llvm_passes
236 pub fn lto(&self) -> bool {
239 pub fn no_landing_pads(&self) -> bool {
240 self.opts.debugging_opts.no_landing_pads
242 pub fn unstable_options(&self) -> bool {
243 self.opts.debugging_opts.unstable_options
245 pub fn print_enum_sizes(&self) -> bool {
246 self.opts.debugging_opts.print_enum_sizes
248 pub fn sysroot<'a>(&'a self) -> &'a Path {
249 match self.opts.maybe_sysroot {
250 Some (ref sysroot) => sysroot,
251 None => self.default_sysroot.as_ref()
252 .expect("missing sysroot and default_sysroot in Session")
255 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
256 filesearch::FileSearch::new(self.sysroot(),
257 &self.opts.target_triple,
258 &self.opts.search_paths,
261 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
262 filesearch::FileSearch::new(
264 config::host_triple(),
265 &self.opts.search_paths,
270 fn split_msg_into_multilines(msg: &str) -> Option<String> {
271 // Conditions for enabling multi-line errors:
272 if !msg.contains("mismatched types") &&
273 !msg.contains("type mismatch resolving") &&
274 !msg.contains("if and else have incompatible types") &&
275 !msg.contains("if may be missing an else clause") &&
276 !msg.contains("match arms have incompatible types") &&
277 !msg.contains("structure constructor specifies a structure of type") {
280 let first = msg.match_indices("expected").filter(|s| {
281 s.0 > 0 && (msg.char_at_reverse(s.0) == ' ' ||
282 msg.char_at_reverse(s.0) == '(')
283 }).map(|(a, b)| (a - 1, b));
284 let second = msg.match_indices("found").filter(|s| {
285 msg.char_at_reverse(s.0) == ' '
286 }).map(|(a, b)| (a - 1, b));
288 let mut new_msg = String::new();
291 // Insert `\n` before expected and found.
292 for (pos1, pos2) in first.zip(second) {
294 // A `(` may be preceded by a space and it should be trimmed
295 msg[head..pos1.0].trim_right() + // prefix
296 "\n" + // insert before first
297 &msg[pos1.0..pos1.1] + // insert what first matched
298 &msg[pos1.1..pos2.0] + // between matches
299 "\n " + // insert before second
301 // `expected` is 3 char longer than `found`. To align the types,
302 // `found` gets 3 spaces prepended.
303 &msg[pos2.0..pos2.1]; // insert what second matched
308 let mut tail = &msg[head..];
309 let third = tail.find("(values differ")
310 .or(tail.find("(lifetime"))
311 .or(tail.find("(cyclic type of infinite size"));
312 // Insert `\n` before any remaining messages which match.
313 if let Some(pos) = third {
314 // The end of the message may just be wrapped in `()` without
315 // `expected`/`found`. Push this also to a new line and add the
318 // `(` is usually preceded by a space and should be trimmed.
319 tail[..pos].trim_right() + // prefix
320 "\n" + // insert before paren
321 &tail[pos..]; // append the tail
326 new_msg.push_str(tail);
327 return Some(new_msg);
330 pub fn build_session(sopts: config::Options,
331 local_crate_source_file: Option<PathBuf>,
332 registry: diagnostics::registry::Registry)
334 // FIXME: This is not general enough to make the warning lint completely override
335 // normal diagnostic warnings, since the warning lint can also be denied and changed
336 // later via the source code.
337 let can_print_warnings = sopts.lint_opts
339 .filter(|&&(ref key, _)| *key == "warnings")
340 .map(|&(_, ref level)| *level != lint::Allow)
344 let codemap = codemap::CodeMap::new();
345 let diagnostic_handler =
346 diagnostic::default_handler(sopts.color, Some(registry), can_print_warnings);
347 let span_diagnostic_handler =
348 diagnostic::mk_span_handler(diagnostic_handler, codemap);
350 build_session_(sopts, local_crate_source_file, span_diagnostic_handler)
353 pub fn build_session_(sopts: config::Options,
354 local_crate_source_file: Option<PathBuf>,
355 span_diagnostic: diagnostic::SpanHandler)
357 let host = match Target::search(config::host_triple()) {
360 span_diagnostic.handler()
361 .fatal(&format!("Error loading host specification: {}", e));
364 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
365 let p_s = parse::new_parse_sess_special_handler(span_diagnostic);
366 let default_sysroot = match sopts.maybe_sysroot {
368 None => Some(filesearch::get_or_default_sysroot())
371 // Make the path absolute, if necessary
372 let local_crate_source_file = local_crate_source_file.map(|path|
373 if path.is_absolute() {
376 env::current_dir().unwrap().join(&path)
380 let can_print_warnings = sopts.lint_opts
382 .filter(|&&(ref key, _)| *key == "warnings")
383 .map(|&(_, ref level)| *level != lint::Allow)
391 cstore: CStore::new(token::get_ident_interner()),
393 // For a library crate, this is always none
394 entry_fn: RefCell::new(None),
395 entry_type: Cell::new(None),
396 plugin_registrar_fn: Cell::new(None),
397 default_sysroot: default_sysroot,
398 local_crate_source_file: local_crate_source_file,
399 working_dir: env::current_dir().unwrap(),
400 lint_store: RefCell::new(lint::LintStore::new()),
401 lints: RefCell::new(NodeMap()),
402 plugin_llvm_passes: RefCell::new(Vec::new()),
403 crate_types: RefCell::new(Vec::new()),
404 crate_metadata: RefCell::new(Vec::new()),
405 features: RefCell::new(feature_gate::Features::new()),
406 recursion_limit: Cell::new(64),
407 can_print_warnings: can_print_warnings
413 // Seems out of place, but it uses session, so I'm putting it here
414 pub fn expect<T, M>(sess: &Session, opt: Option<T>, msg: M) -> T where
415 M: FnOnce() -> String,
417 diagnostic::expect(sess.diagnostic(), opt, msg)
420 pub fn early_error(msg: &str) -> ! {
421 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
422 emitter.emit(None, msg, None, diagnostic::Fatal);
423 panic!(diagnostic::FatalError);
426 pub fn early_warn(msg: &str) {
427 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
428 emitter.emit(None, msg, None, diagnostic::Warning);