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
;
16 use util
::nodemap
::{NodeMap, FnvHashMap}
;
17 use mir
::transform
as mir_pass
;
19 use syntax
::ast
::{NodeId, NodeIdAssigner, Name}
;
20 use syntax
::codemap
::{Span, MultiSpan}
;
21 use syntax
::errors
::{self, DiagnosticBuilder}
;
22 use syntax
::errors
::emitter
::{Emitter, BasicEmitter, EmitterWriter}
;
23 use syntax
::errors
::json
::JsonEmitter
;
24 use syntax
::diagnostics
;
25 use syntax
::feature_gate
;
27 use syntax
::parse
::ParseSess
;
28 use syntax
::parse
::token
;
29 use syntax
::{ast, codemap}
;
30 use syntax
::feature_gate
::AttributeType
;
32 use rustc_back
::target
::Target
;
34 use std
::path
::{Path, PathBuf}
;
35 use std
::cell
::{Cell, RefCell}
;
36 use std
::collections
::{HashMap, HashSet}
;
45 // Represents the data associated with a compilation
46 // session for a single crate.
48 pub target
: config
::Config
,
50 pub opts
: config
::Options
,
51 pub cstore
: Rc
<for<'a
> CrateStore
<'a
>>,
52 pub parse_sess
: ParseSess
,
53 // For a library crate, this is always none
54 pub entry_fn
: RefCell
<Option
<(NodeId
, Span
)>>,
55 pub entry_type
: Cell
<Option
<config
::EntryFnType
>>,
56 pub plugin_registrar_fn
: Cell
<Option
<ast
::NodeId
>>,
57 pub default_sysroot
: Option
<PathBuf
>,
58 // The name of the root source file of the crate, in the local file system.
59 // The path is always expected to be absolute. `None` means that there is no
61 pub local_crate_source_file
: Option
<PathBuf
>,
62 pub working_dir
: PathBuf
,
63 pub lint_store
: RefCell
<lint
::LintStore
>,
64 pub lints
: RefCell
<NodeMap
<Vec
<(lint
::LintId
, Span
, String
)>>>,
65 pub plugin_llvm_passes
: RefCell
<Vec
<String
>>,
66 pub mir_passes
: RefCell
<mir_pass
::Passes
>,
67 pub plugin_attributes
: RefCell
<Vec
<(String
, AttributeType
)>>,
68 pub crate_types
: RefCell
<Vec
<config
::CrateType
>>,
69 pub dependency_formats
: RefCell
<dependency_format
::Dependencies
>,
70 // The crate_disambiguator is constructed out of all the `-C metadata`
71 // arguments passed to the compiler. Its value together with the crate-name
72 // forms a unique global identifier for the crate. It is used to allow
73 // multiple crates with the same name to coexist. See the
74 // trans::back::symbol_names module for more information.
75 pub crate_disambiguator
: Cell
<ast
::Name
>,
76 pub features
: RefCell
<feature_gate
::Features
>,
78 /// The maximum recursion limit for potentially infinitely recursive
79 /// operations such as auto-dereference and monomorphization.
80 pub recursion_limit
: Cell
<usize>,
82 /// The metadata::creader module may inject an allocator dependency if it
83 /// didn't already find one, and this tracks what was injected.
84 pub injected_allocator
: Cell
<Option
<ast
::CrateNum
>>,
86 /// Names of all bang-style macros and syntax extensions
87 /// available in this crate
88 pub available_macros
: RefCell
<HashSet
<Name
>>,
90 /// Map from imported macro spans (which consist of
91 /// the localized span for the macro body) to the
92 /// macro name and defintion span in the source crate.
93 pub imported_macro_spans
: RefCell
<HashMap
<Span
, (String
, Span
)>>,
95 next_node_id
: Cell
<ast
::NodeId
>,
99 pub fn struct_span_warn
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
102 -> DiagnosticBuilder
<'a
> {
103 self.diagnostic().struct_span_warn(sp
, msg
)
105 pub fn struct_span_warn_with_code
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
109 -> DiagnosticBuilder
<'a
> {
110 self.diagnostic().struct_span_warn_with_code(sp
, msg
, code
)
112 pub fn struct_warn
<'a
>(&'a
self, msg
: &str) -> DiagnosticBuilder
<'a
> {
113 self.diagnostic().struct_warn(msg
)
115 pub fn struct_span_err
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
118 -> DiagnosticBuilder
<'a
> {
119 match split_msg_into_multilines(msg
) {
120 Some(ref msg
) => self.diagnostic().struct_span_err(sp
, msg
),
121 None
=> self.diagnostic().struct_span_err(sp
, msg
),
124 pub fn struct_span_err_with_code
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
128 -> DiagnosticBuilder
<'a
> {
129 match split_msg_into_multilines(msg
) {
130 Some(ref msg
) => self.diagnostic().struct_span_err_with_code(sp
, msg
, code
),
131 None
=> self.diagnostic().struct_span_err_with_code(sp
, msg
, code
),
134 pub fn struct_err
<'a
>(&'a
self, msg
: &str) -> DiagnosticBuilder
<'a
> {
135 self.diagnostic().struct_err(msg
)
137 pub fn struct_span_fatal
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
140 -> DiagnosticBuilder
<'a
> {
141 self.diagnostic().struct_span_fatal(sp
, msg
)
143 pub fn struct_span_fatal_with_code
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
147 -> DiagnosticBuilder
<'a
> {
148 self.diagnostic().struct_span_fatal_with_code(sp
, msg
, code
)
150 pub fn struct_fatal
<'a
>(&'a
self, msg
: &str) -> DiagnosticBuilder
<'a
> {
151 self.diagnostic().struct_fatal(msg
)
154 pub fn span_fatal
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) -> ! {
155 panic
!(self.diagnostic().span_fatal(sp
, msg
))
157 pub fn span_fatal_with_code
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str, code
: &str) -> ! {
158 panic
!(self.diagnostic().span_fatal_with_code(sp
, msg
, code
))
160 pub fn fatal(&self, msg
: &str) -> ! {
161 panic
!(self.diagnostic().fatal(msg
))
163 pub fn span_err_or_warn
<S
: Into
<MultiSpan
>>(&self, is_warning
: bool
, sp
: S
, msg
: &str) {
165 self.span_warn(sp
, msg
);
167 self.span_err(sp
, msg
);
170 pub fn span_err
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
171 match split_msg_into_multilines(msg
) {
172 Some(msg
) => self.diagnostic().span_err(sp
, &msg
),
173 None
=> self.diagnostic().span_err(sp
, msg
)
176 pub fn span_err_with_code
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str, code
: &str) {
177 match split_msg_into_multilines(msg
) {
178 Some(msg
) => self.diagnostic().span_err_with_code(sp
, &msg
, code
),
179 None
=> self.diagnostic().span_err_with_code(sp
, msg
, code
)
182 pub fn err(&self, msg
: &str) {
183 self.diagnostic().err(msg
)
185 pub fn err_count(&self) -> usize {
186 self.diagnostic().err_count()
188 pub fn has_errors(&self) -> bool
{
189 self.diagnostic().has_errors()
191 pub fn abort_if_errors(&self) {
192 self.diagnostic().abort_if_errors();
194 pub fn track_errors
<F
, T
>(&self, f
: F
) -> Result
<T
, usize>
195 where F
: FnOnce() -> T
197 let old_count
= self.err_count();
199 let errors
= self.err_count() - old_count
;
206 pub fn span_warn
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
207 self.diagnostic().span_warn(sp
, msg
)
209 pub fn span_warn_with_code
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str, code
: &str) {
210 self.diagnostic().span_warn_with_code(sp
, msg
, code
)
212 pub fn warn(&self, msg
: &str) {
213 self.diagnostic().warn(msg
)
215 pub fn opt_span_warn
<S
: Into
<MultiSpan
>>(&self, opt_sp
: Option
<S
>, msg
: &str) {
217 Some(sp
) => self.span_warn(sp
, msg
),
218 None
=> self.warn(msg
),
221 /// Delay a span_bug() call until abort_if_errors()
222 pub fn delay_span_bug
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
223 self.diagnostic().delay_span_bug(sp
, msg
)
225 pub fn note_without_error(&self, msg
: &str) {
226 self.diagnostic().note_without_error(msg
)
228 pub fn span_note_without_error
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
229 self.diagnostic().span_note_without_error(sp
, msg
)
231 pub fn span_unimpl
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) -> ! {
232 self.diagnostic().span_unimpl(sp
, msg
)
234 pub fn unimpl(&self, msg
: &str) -> ! {
235 self.diagnostic().unimpl(msg
)
237 pub fn add_lint(&self,
238 lint
: &'
static lint
::Lint
,
242 let lint_id
= lint
::LintId
::of(lint
);
243 let mut lints
= self.lints
.borrow_mut();
244 match lints
.get_mut(&id
) {
246 let tuple
= (lint_id
, sp
, msg
);
247 if !arr
.contains(&tuple
) {
254 lints
.insert(id
, vec
!((lint_id
, sp
, msg
)));
256 pub fn reserve_node_ids(&self, count
: ast
::NodeId
) -> ast
::NodeId
{
257 let id
= self.next_node_id
.get();
259 match id
.checked_add(count
) {
260 Some(next
) => self.next_node_id
.set(next
),
261 None
=> bug
!("Input too large, ran out of node ids!")
266 pub fn diagnostic
<'a
>(&'a
self) -> &'a errors
::Handler
{
267 &self.parse_sess
.span_diagnostic
269 pub fn codemap
<'a
>(&'a
self) -> &'a codemap
::CodeMap
{
270 self.parse_sess
.codemap()
272 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
273 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
274 pub fn count_llvm_insns(&self) -> bool
{
275 self.opts
.debugging_opts
.count_llvm_insns
277 pub fn count_type_sizes(&self) -> bool
{
278 self.opts
.debugging_opts
.count_type_sizes
280 pub fn time_llvm_passes(&self) -> bool
{
281 self.opts
.debugging_opts
.time_llvm_passes
283 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
284 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
285 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
286 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
287 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
288 pub fn print_llvm_passes(&self) -> bool
{
289 self.opts
.debugging_opts
.print_llvm_passes
291 pub fn lto(&self) -> bool
{
294 pub fn no_landing_pads(&self) -> bool
{
295 self.opts
.debugging_opts
.no_landing_pads
297 pub fn unstable_options(&self) -> bool
{
298 self.opts
.debugging_opts
.unstable_options
300 pub fn print_enum_sizes(&self) -> bool
{
301 self.opts
.debugging_opts
.print_enum_sizes
303 pub fn nonzeroing_move_hints(&self) -> bool
{
304 self.opts
.debugging_opts
.enable_nonzeroing_move_hints
306 pub fn sysroot
<'a
>(&'a
self) -> &'a Path
{
307 match self.opts
.maybe_sysroot
{
308 Some (ref sysroot
) => sysroot
,
309 None
=> self.default_sysroot
.as_ref()
310 .expect("missing sysroot and default_sysroot in Session")
313 pub fn target_filesearch(&self, kind
: PathKind
) -> filesearch
::FileSearch
{
314 filesearch
::FileSearch
::new(self.sysroot(),
315 &self.opts
.target_triple
,
316 &self.opts
.search_paths
,
319 pub fn host_filesearch(&self, kind
: PathKind
) -> filesearch
::FileSearch
{
320 filesearch
::FileSearch
::new(
322 config
::host_triple(),
323 &self.opts
.search_paths
,
328 impl NodeIdAssigner
for Session
{
329 fn next_node_id(&self) -> NodeId
{
330 self.reserve_node_ids(1)
333 fn peek_node_id(&self) -> NodeId
{
334 self.next_node_id
.get().checked_add(1).unwrap()
337 fn diagnostic(&self) -> &errors
::Handler
{
342 fn split_msg_into_multilines(msg
: &str) -> Option
<String
> {
343 // Conditions for enabling multi-line errors:
344 if !msg
.contains("mismatched types") &&
345 !msg
.contains("type mismatch resolving") &&
346 !msg
.contains("if and else have incompatible types") &&
347 !msg
.contains("if may be missing an else clause") &&
348 !msg
.contains("match arms have incompatible types") &&
349 !msg
.contains("structure constructor specifies a structure of type") &&
350 !msg
.contains("has an incompatible type for trait") {
353 let first
= msg
.match_indices("expected").filter(|s
| {
354 let last
= msg
[..s
.0].chars().rev().next();
355 last
== Some(' '
) || last
== Some('
('
)
356 }).map(|(a
, b
)| (a
- 1, a
+ b
.len()));
357 let second
= msg
.match_indices("found").filter(|s
| {
358 msg
[..s
.0].chars().rev().next() == Some(' '
)
359 }).map(|(a
, b
)| (a
- 1, a
+ b
.len()));
361 let mut new_msg
= String
::new();
364 // Insert `\n` before expected and found.
365 for (pos1
, pos2
) in first
.zip(second
) {
367 // A `(` may be preceded by a space and it should be trimmed
368 msg
[head
..pos1
.0
].trim_right() + // prefix
369 "\n" + // insert before first
370 &msg
[pos1
.0
..pos1
.1
] + // insert what first matched
371 &msg
[pos1
.1
..pos2
.0
] + // between matches
372 "\n " + // insert before second
374 // `expected` is 3 char longer than `found`. To align the types,
375 // `found` gets 3 spaces prepended.
376 &msg
[pos2
.0
..pos2
.1
]; // insert what second matched
381 let mut tail
= &msg
[head
..];
382 let third
= tail
.find("(values differ")
383 .or(tail
.find("(lifetime"))
384 .or(tail
.find("(cyclic type of infinite size"));
385 // Insert `\n` before any remaining messages which match.
386 if let Some(pos
) = third
{
387 // The end of the message may just be wrapped in `()` without
388 // `expected`/`found`. Push this also to a new line and add the
391 // `(` is usually preceded by a space and should be trimmed.
392 tail
[..pos
].trim_right() + // prefix
393 "\n" + // insert before paren
394 &tail
[pos
..]; // append the tail
399 new_msg
.push_str(tail
);
400 return Some(new_msg
);
403 pub fn build_session(sopts
: config
::Options
,
404 local_crate_source_file
: Option
<PathBuf
>,
405 registry
: diagnostics
::registry
::Registry
,
406 cstore
: Rc
<for<'a
> CrateStore
<'a
>>)
408 // FIXME: This is not general enough to make the warning lint completely override
409 // normal diagnostic warnings, since the warning lint can also be denied and changed
410 // later via the source code.
411 let can_print_warnings
= sopts
.lint_opts
413 .filter(|&&(ref key
, _
)| *key
== "warnings")
414 .map(|&(_
, ref level
)| *level
!= lint
::Allow
)
417 let treat_err_as_bug
= sopts
.treat_err_as_bug
;
419 let codemap
= Rc
::new(codemap
::CodeMap
::new());
420 let emitter
: Box
<Emitter
> = match sopts
.error_format
{
421 config
::ErrorOutputType
::HumanReadable(color_config
) => {
422 Box
::new(EmitterWriter
::stderr(color_config
, Some(registry
), codemap
.clone()))
424 config
::ErrorOutputType
::Json
=> {
425 Box
::new(JsonEmitter
::stderr(Some(registry
), codemap
.clone()))
429 let diagnostic_handler
=
430 errors
::Handler
::with_emitter(can_print_warnings
,
434 build_session_(sopts
, local_crate_source_file
, diagnostic_handler
, codemap
, cstore
)
437 pub fn build_session_(sopts
: config
::Options
,
438 local_crate_source_file
: Option
<PathBuf
>,
439 span_diagnostic
: errors
::Handler
,
440 codemap
: Rc
<codemap
::CodeMap
>,
441 cstore
: Rc
<for<'a
> CrateStore
<'a
>>)
443 let host
= match Target
::search(config
::host_triple()) {
446 panic
!(span_diagnostic
.fatal(&format
!("Error loading host specification: {}", e
)));
449 let target_cfg
= config
::build_target_config(&sopts
, &span_diagnostic
);
450 let p_s
= parse
::ParseSess
::with_span_handler(span_diagnostic
, codemap
);
451 let default_sysroot
= match sopts
.maybe_sysroot
{
453 None
=> Some(filesearch
::get_or_default_sysroot())
456 // Make the path absolute, if necessary
457 let local_crate_source_file
= local_crate_source_file
.map(|path
|
458 if path
.is_absolute() {
461 env
::current_dir().unwrap().join(&path
)
471 // For a library crate, this is always none
472 entry_fn
: RefCell
::new(None
),
473 entry_type
: Cell
::new(None
),
474 plugin_registrar_fn
: Cell
::new(None
),
475 default_sysroot
: default_sysroot
,
476 local_crate_source_file
: local_crate_source_file
,
477 working_dir
: env
::current_dir().unwrap(),
478 lint_store
: RefCell
::new(lint
::LintStore
::new()),
479 lints
: RefCell
::new(NodeMap()),
480 plugin_llvm_passes
: RefCell
::new(Vec
::new()),
481 mir_passes
: RefCell
::new(mir_pass
::Passes
::new()),
482 plugin_attributes
: RefCell
::new(Vec
::new()),
483 crate_types
: RefCell
::new(Vec
::new()),
484 dependency_formats
: RefCell
::new(FnvHashMap()),
485 crate_disambiguator
: Cell
::new(token
::intern("")),
486 features
: RefCell
::new(feature_gate
::Features
::new()),
487 recursion_limit
: Cell
::new(64),
488 next_node_id
: Cell
::new(1),
489 injected_allocator
: Cell
::new(None
),
490 available_macros
: RefCell
::new(HashSet
::new()),
491 imported_macro_spans
: RefCell
::new(HashMap
::new()),
497 pub fn early_error(output
: config
::ErrorOutputType
, msg
: &str) -> ! {
498 let mut emitter
: Box
<Emitter
> = match output
{
499 config
::ErrorOutputType
::HumanReadable(color_config
) => {
500 Box
::new(BasicEmitter
::stderr(color_config
))
502 config
::ErrorOutputType
::Json
=> Box
::new(JsonEmitter
::basic()),
504 emitter
.emit(None
, msg
, None
, errors
::Level
::Fatal
);
505 panic
!(errors
::FatalError
);
508 pub fn early_warn(output
: config
::ErrorOutputType
, msg
: &str) {
509 let mut emitter
: Box
<Emitter
> = match output
{
510 config
::ErrorOutputType
::HumanReadable(color_config
) => {
511 Box
::new(BasicEmitter
::stderr(color_config
))
513 config
::ErrorOutputType
::Json
=> Box
::new(JsonEmitter
::basic()),
515 emitter
.emit(None
, msg
, None
, errors
::Level
::Warning
);
518 // Err(0) means compilation was stopped, but no errors were found.
519 // This would be better as a dedicated enum, but using try! is so convenient.
520 pub type CompileResult
= Result
<(), usize>;
522 pub fn compile_result_from_err_count(err_count
: usize) -> CompileResult
{
532 pub fn bug_fmt(file
: &'
static str, line
: u32, args
: fmt
::Arguments
) -> ! {
533 // this wrapper mostly exists so I don't have to write a fully
534 // qualified path of None::<Span> inside the bug!() macro defintion
535 opt_span_bug_fmt(file
, line
, None
::<Span
>, args
);
540 pub fn span_bug_fmt
<S
: Into
<MultiSpan
>>(file
: &'
static str,
543 args
: fmt
::Arguments
) -> ! {
544 opt_span_bug_fmt(file
, line
, Some(span
), args
);
547 fn opt_span_bug_fmt
<S
: Into
<MultiSpan
>>(file
: &'
static str,
550 args
: fmt
::Arguments
) -> ! {
551 tls
::with_opt(move |tcx
| {
552 let msg
= format
!("{}:{}: {}", file
, line
, args
);
554 (Some(tcx
), Some(span
)) => tcx
.sess
.diagnostic().span_bug(span
, &msg
),
555 (Some(tcx
), None
) => tcx
.sess
.diagnostic().bug(&msg
),
556 (None
, _
) => panic
!(msg
)