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.
11 use dep_graph
::DepGraph
;
12 use hir
::def_id
::DefIndex
;
15 use middle
::cstore
::CrateStore
;
16 use middle
::dependency_format
;
17 use session
::search_paths
::PathKind
;
18 use session
::config
::{DebugInfoLevel, PanicStrategy}
;
20 use util
::nodemap
::{NodeMap, FnvHashMap}
;
21 use mir
::transform
as mir_pass
;
23 use syntax
::ast
::{NodeId, Name}
;
24 use errors
::{self, DiagnosticBuilder}
;
25 use errors
::emitter
::{Emitter, EmitterWriter}
;
26 use syntax
::json
::JsonEmitter
;
27 use syntax
::feature_gate
;
29 use syntax
::parse
::ParseSess
;
30 use syntax
::parse
::token
;
31 use syntax
::{ast, codemap}
;
32 use syntax
::feature_gate
::AttributeType
;
33 use syntax_pos
::{Span, MultiSpan}
;
35 use rustc_back
::target
::Target
;
38 use std
::path
::{Path, PathBuf}
;
39 use std
::cell
::{Cell, RefCell}
;
40 use std
::collections
::{HashMap, HashSet}
;
42 use std
::ffi
::CString
;
51 // Represents the data associated with a compilation
52 // session for a single crate.
54 pub dep_graph
: DepGraph
,
55 pub target
: config
::Config
,
57 pub opts
: config
::Options
,
58 pub cstore
: Rc
<for<'a
> CrateStore
<'a
>>,
59 pub parse_sess
: ParseSess
,
60 // For a library crate, this is always none
61 pub entry_fn
: RefCell
<Option
<(NodeId
, Span
)>>,
62 pub entry_type
: Cell
<Option
<config
::EntryFnType
>>,
63 pub plugin_registrar_fn
: Cell
<Option
<ast
::NodeId
>>,
64 pub default_sysroot
: Option
<PathBuf
>,
65 // The name of the root source file of the crate, in the local file system.
66 // The path is always expected to be absolute. `None` means that there is no
68 pub local_crate_source_file
: Option
<PathBuf
>,
69 pub working_dir
: PathBuf
,
70 pub lint_store
: RefCell
<lint
::LintStore
>,
71 pub lints
: RefCell
<NodeMap
<Vec
<(lint
::LintId
, Span
, String
)>>>,
72 pub plugin_llvm_passes
: RefCell
<Vec
<String
>>,
73 pub mir_passes
: RefCell
<mir_pass
::Passes
>,
74 pub plugin_attributes
: RefCell
<Vec
<(String
, AttributeType
)>>,
75 pub crate_types
: RefCell
<Vec
<config
::CrateType
>>,
76 pub dependency_formats
: RefCell
<dependency_format
::Dependencies
>,
77 // The crate_disambiguator is constructed out of all the `-C metadata`
78 // arguments passed to the compiler. Its value together with the crate-name
79 // forms a unique global identifier for the crate. It is used to allow
80 // multiple crates with the same name to coexist. See the
81 // trans::back::symbol_names module for more information.
82 pub crate_disambiguator
: RefCell
<token
::InternedString
>,
83 pub features
: RefCell
<feature_gate
::Features
>,
85 /// The maximum recursion limit for potentially infinitely recursive
86 /// operations such as auto-dereference and monomorphization.
87 pub recursion_limit
: Cell
<usize>,
89 /// The metadata::creader module may inject an allocator/panic_runtime
90 /// dependency if it didn't already find one, and this tracks what was
92 pub injected_allocator
: Cell
<Option
<ast
::CrateNum
>>,
93 pub injected_panic_runtime
: Cell
<Option
<ast
::CrateNum
>>,
95 /// Names of all bang-style macros and syntax extensions
96 /// available in this crate
97 pub available_macros
: RefCell
<HashSet
<Name
>>,
99 /// Map from imported macro spans (which consist of
100 /// the localized span for the macro body) to the
101 /// macro name and defintion span in the source crate.
102 pub imported_macro_spans
: RefCell
<HashMap
<Span
, (String
, Span
)>>,
104 next_node_id
: Cell
<ast
::NodeId
>,
108 pub fn local_crate_disambiguator(&self) -> token
::InternedString
{
109 self.crate_disambiguator
.borrow().clone()
111 pub fn struct_span_warn
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
114 -> DiagnosticBuilder
<'a
> {
115 self.diagnostic().struct_span_warn(sp
, msg
)
117 pub fn struct_span_warn_with_code
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
121 -> DiagnosticBuilder
<'a
> {
122 self.diagnostic().struct_span_warn_with_code(sp
, msg
, code
)
124 pub fn struct_warn
<'a
>(&'a
self, msg
: &str) -> DiagnosticBuilder
<'a
> {
125 self.diagnostic().struct_warn(msg
)
127 pub fn struct_span_err
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
130 -> DiagnosticBuilder
<'a
> {
131 self.diagnostic().struct_span_err(sp
, msg
)
133 pub fn struct_span_err_with_code
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
137 -> DiagnosticBuilder
<'a
> {
138 self.diagnostic().struct_span_err_with_code(sp
, msg
, code
)
140 pub fn struct_err
<'a
>(&'a
self, msg
: &str) -> DiagnosticBuilder
<'a
> {
141 self.diagnostic().struct_err(msg
)
143 pub fn struct_span_fatal
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
146 -> DiagnosticBuilder
<'a
> {
147 self.diagnostic().struct_span_fatal(sp
, msg
)
149 pub fn struct_span_fatal_with_code
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
153 -> DiagnosticBuilder
<'a
> {
154 self.diagnostic().struct_span_fatal_with_code(sp
, msg
, code
)
156 pub fn struct_fatal
<'a
>(&'a
self, msg
: &str) -> DiagnosticBuilder
<'a
> {
157 self.diagnostic().struct_fatal(msg
)
160 pub fn span_fatal
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) -> ! {
161 panic
!(self.diagnostic().span_fatal(sp
, msg
))
163 pub fn span_fatal_with_code
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str, code
: &str) -> ! {
164 panic
!(self.diagnostic().span_fatal_with_code(sp
, msg
, code
))
166 pub fn fatal(&self, msg
: &str) -> ! {
167 panic
!(self.diagnostic().fatal(msg
))
169 pub fn span_err_or_warn
<S
: Into
<MultiSpan
>>(&self, is_warning
: bool
, sp
: S
, msg
: &str) {
171 self.span_warn(sp
, msg
);
173 self.span_err(sp
, msg
);
176 pub fn span_err
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
177 self.diagnostic().span_err(sp
, msg
)
179 pub fn span_err_with_code
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str, code
: &str) {
180 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 if let Some(arr
) = lints
.get_mut(&id
) {
245 let tuple
= (lint_id
, sp
, msg
);
246 if !arr
.contains(&tuple
) {
251 lints
.insert(id
, vec
!((lint_id
, sp
, msg
)));
253 pub fn reserve_node_ids(&self, count
: ast
::NodeId
) -> ast
::NodeId
{
254 let id
= self.next_node_id
.get();
256 match id
.checked_add(count
) {
257 Some(next
) => self.next_node_id
.set(next
),
258 None
=> bug
!("Input too large, ran out of node ids!")
263 pub fn next_node_id(&self) -> NodeId
{
264 self.reserve_node_ids(1)
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 time_llvm_passes(&self) -> bool
{
278 self.opts
.debugging_opts
.time_llvm_passes
280 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
281 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
282 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
283 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
284 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
285 pub fn print_llvm_passes(&self) -> bool
{
286 self.opts
.debugging_opts
.print_llvm_passes
288 pub fn lto(&self) -> bool
{
291 pub fn no_landing_pads(&self) -> bool
{
292 self.opts
.debugging_opts
.no_landing_pads
||
293 self.opts
.cg
.panic
== PanicStrategy
::Abort
295 pub fn unstable_options(&self) -> bool
{
296 self.opts
.debugging_opts
.unstable_options
298 pub fn nonzeroing_move_hints(&self) -> bool
{
299 self.opts
.debugging_opts
.enable_nonzeroing_move_hints
302 pub fn must_not_eliminate_frame_pointers(&self) -> bool
{
303 self.opts
.debuginfo
!= DebugInfoLevel
::NoDebugInfo
||
304 !self.target
.target
.options
.eliminate_frame_pointer
307 /// Returns the symbol name for the registrar function,
308 /// given the crate Svh and the function DefIndex.
309 pub fn generate_plugin_registrar_symbol(&self, svh
: &Svh
, index
: DefIndex
)
311 format
!("__rustc_plugin_registrar__{}_{}", svh
, index
.as_usize())
314 pub fn sysroot
<'a
>(&'a
self) -> &'a Path
{
315 match self.opts
.maybe_sysroot
{
316 Some (ref sysroot
) => sysroot
,
317 None
=> self.default_sysroot
.as_ref()
318 .expect("missing sysroot and default_sysroot in Session")
321 pub fn target_filesearch(&self, kind
: PathKind
) -> filesearch
::FileSearch
{
322 filesearch
::FileSearch
::new(self.sysroot(),
323 &self.opts
.target_triple
,
324 &self.opts
.search_paths
,
327 pub fn host_filesearch(&self, kind
: PathKind
) -> filesearch
::FileSearch
{
328 filesearch
::FileSearch
::new(
330 config
::host_triple(),
331 &self.opts
.search_paths
,
336 pub fn build_session(sopts
: config
::Options
,
337 dep_graph
: &DepGraph
,
338 local_crate_source_file
: Option
<PathBuf
>,
339 registry
: errors
::registry
::Registry
,
340 cstore
: Rc
<for<'a
> CrateStore
<'a
>>)
342 build_session_with_codemap(sopts
,
344 local_crate_source_file
,
347 Rc
::new(codemap
::CodeMap
::new()))
350 pub fn build_session_with_codemap(sopts
: config
::Options
,
351 dep_graph
: &DepGraph
,
352 local_crate_source_file
: Option
<PathBuf
>,
353 registry
: errors
::registry
::Registry
,
354 cstore
: Rc
<for<'a
> CrateStore
<'a
>>,
355 codemap
: Rc
<codemap
::CodeMap
>)
357 // FIXME: This is not general enough to make the warning lint completely override
358 // normal diagnostic warnings, since the warning lint can also be denied and changed
359 // later via the source code.
360 let can_print_warnings
= sopts
.lint_opts
362 .filter(|&&(ref key
, _
)| *key
== "warnings")
363 .map(|&(_
, ref level
)| *level
!= lint
::Allow
)
366 let treat_err_as_bug
= sopts
.debugging_opts
.treat_err_as_bug
;
368 let emitter
: Box
<Emitter
> = match sopts
.error_format
{
369 config
::ErrorOutputType
::HumanReadable(color_config
) => {
370 Box
::new(EmitterWriter
::stderr(color_config
,
371 Some(codemap
.clone())))
373 config
::ErrorOutputType
::Json
=> {
374 Box
::new(JsonEmitter
::stderr(Some(registry
), codemap
.clone()))
378 let diagnostic_handler
=
379 errors
::Handler
::with_emitter(can_print_warnings
,
383 build_session_(sopts
,
385 local_crate_source_file
,
391 pub fn build_session_(sopts
: config
::Options
,
392 dep_graph
: &DepGraph
,
393 local_crate_source_file
: Option
<PathBuf
>,
394 span_diagnostic
: errors
::Handler
,
395 codemap
: Rc
<codemap
::CodeMap
>,
396 cstore
: Rc
<for<'a
> CrateStore
<'a
>>)
398 let host
= match Target
::search(config
::host_triple()) {
401 panic
!(span_diagnostic
.fatal(&format
!("Error loading host specification: {}", e
)));
404 let target_cfg
= config
::build_target_config(&sopts
, &span_diagnostic
);
405 let p_s
= parse
::ParseSess
::with_span_handler(span_diagnostic
, codemap
);
406 let default_sysroot
= match sopts
.maybe_sysroot
{
408 None
=> Some(filesearch
::get_or_default_sysroot())
411 // Make the path absolute, if necessary
412 let local_crate_source_file
= local_crate_source_file
.map(|path
|
413 if path
.is_absolute() {
416 env
::current_dir().unwrap().join(&path
)
421 dep_graph
: dep_graph
.clone(),
427 // For a library crate, this is always none
428 entry_fn
: RefCell
::new(None
),
429 entry_type
: Cell
::new(None
),
430 plugin_registrar_fn
: Cell
::new(None
),
431 default_sysroot
: default_sysroot
,
432 local_crate_source_file
: local_crate_source_file
,
433 working_dir
: env
::current_dir().unwrap(),
434 lint_store
: RefCell
::new(lint
::LintStore
::new()),
435 lints
: RefCell
::new(NodeMap()),
436 plugin_llvm_passes
: RefCell
::new(Vec
::new()),
437 mir_passes
: RefCell
::new(mir_pass
::Passes
::new()),
438 plugin_attributes
: RefCell
::new(Vec
::new()),
439 crate_types
: RefCell
::new(Vec
::new()),
440 dependency_formats
: RefCell
::new(FnvHashMap()),
441 crate_disambiguator
: RefCell
::new(token
::intern("").as_str()),
442 features
: RefCell
::new(feature_gate
::Features
::new()),
443 recursion_limit
: Cell
::new(64),
444 next_node_id
: Cell
::new(1),
445 injected_allocator
: Cell
::new(None
),
446 injected_panic_runtime
: Cell
::new(None
),
447 available_macros
: RefCell
::new(HashSet
::new()),
448 imported_macro_spans
: RefCell
::new(HashMap
::new()),
456 fn init_llvm(sess
: &Session
) {
458 // Before we touch LLVM, make sure that multithreading is enabled.
460 static INIT
: Once
= Once
::new();
461 static mut POISONED
: bool
= false;
463 if llvm
::LLVMStartMultithreaded() != 1 {
464 // use an extra bool to make sure that all future usage of LLVM
465 // cannot proceed despite the Once not running more than once.
469 configure_llvm(sess
);
473 bug
!("couldn't enable multi-threaded LLVM");
478 unsafe fn configure_llvm(sess
: &Session
) {
479 let mut llvm_c_strs
= Vec
::new();
480 let mut llvm_args
= Vec
::new();
483 let mut add
= |arg
: &str| {
484 let s
= CString
::new(arg
).unwrap();
485 llvm_args
.push(s
.as_ptr());
488 add("rustc"); // fake program name
489 if sess
.time_llvm_passes() { add("-time-passes"); }
490 if sess
.print_llvm_passes() { add("-debug-pass=Structure"); }
492 for arg
in &sess
.opts
.cg
.llvm_args
{
497 llvm
::LLVMInitializePasses();
499 llvm
::initialize_available_targets();
501 llvm
::LLVMRustSetLLVMOptions(llvm_args
.len() as c_int
,
505 pub fn early_error(output
: config
::ErrorOutputType
, msg
: &str) -> ! {
506 let emitter
: Box
<Emitter
> = match output
{
507 config
::ErrorOutputType
::HumanReadable(color_config
) => {
508 Box
::new(EmitterWriter
::stderr(color_config
,
511 config
::ErrorOutputType
::Json
=> Box
::new(JsonEmitter
::basic()),
513 let handler
= errors
::Handler
::with_emitter(true, false, emitter
);
514 handler
.emit(&MultiSpan
::new(), msg
, errors
::Level
::Fatal
);
515 panic
!(errors
::FatalError
);
518 pub fn early_warn(output
: config
::ErrorOutputType
, msg
: &str) {
519 let emitter
: Box
<Emitter
> = match output
{
520 config
::ErrorOutputType
::HumanReadable(color_config
) => {
521 Box
::new(EmitterWriter
::stderr(color_config
,
524 config
::ErrorOutputType
::Json
=> Box
::new(JsonEmitter
::basic()),
526 let handler
= errors
::Handler
::with_emitter(true, false, emitter
);
527 handler
.emit(&MultiSpan
::new(), msg
, errors
::Level
::Warning
);
530 // Err(0) means compilation was stopped, but no errors were found.
531 // This would be better as a dedicated enum, but using try! is so convenient.
532 pub type CompileResult
= Result
<(), usize>;
534 pub fn compile_result_from_err_count(err_count
: usize) -> CompileResult
{
544 pub fn bug_fmt(file
: &'
static str, line
: u32, args
: fmt
::Arguments
) -> ! {
545 // this wrapper mostly exists so I don't have to write a fully
546 // qualified path of None::<Span> inside the bug!() macro defintion
547 opt_span_bug_fmt(file
, line
, None
::<Span
>, args
);
552 pub fn span_bug_fmt
<S
: Into
<MultiSpan
>>(file
: &'
static str,
555 args
: fmt
::Arguments
) -> ! {
556 opt_span_bug_fmt(file
, line
, Some(span
), args
);
559 fn opt_span_bug_fmt
<S
: Into
<MultiSpan
>>(file
: &'
static str,
562 args
: fmt
::Arguments
) -> ! {
563 tls
::with_opt(move |tcx
| {
564 let msg
= format
!("{}:{}: {}", file
, line
, args
);
566 (Some(tcx
), Some(span
)) => tcx
.sess
.diagnostic().span_bug(span
, &msg
),
567 (Some(tcx
), None
) => tcx
.sess
.diagnostic().bug(&msg
),
568 (None
, _
) => panic
!(msg
)