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}
;
26 use syntax
::feature_gate
::AttributeType
;
28 use rustc_back
::target
::Target
;
30 use std
::path
::{Path, PathBuf}
;
31 use std
::cell
::{Cell, RefCell}
;
37 // Represents the data associated with a compilation
38 // session for a single crate.
40 pub target
: config
::Config
,
42 pub opts
: config
::Options
,
44 pub parse_sess
: ParseSess
,
45 // For a library crate, this is always none
46 pub entry_fn
: RefCell
<Option
<(NodeId
, codemap
::Span
)>>,
47 pub entry_type
: Cell
<Option
<config
::EntryFnType
>>,
48 pub plugin_registrar_fn
: Cell
<Option
<ast
::NodeId
>>,
49 pub default_sysroot
: Option
<PathBuf
>,
50 // The name of the root source file of the crate, in the local file system.
51 // The path is always expected to be absolute. `None` means that there is no
53 pub local_crate_source_file
: Option
<PathBuf
>,
54 pub working_dir
: PathBuf
,
55 pub lint_store
: RefCell
<lint
::LintStore
>,
56 pub lints
: RefCell
<NodeMap
<Vec
<(lint
::LintId
, codemap
::Span
, String
)>>>,
57 pub plugin_llvm_passes
: RefCell
<Vec
<String
>>,
58 pub plugin_attributes
: RefCell
<Vec
<(String
, AttributeType
)>>,
59 pub crate_types
: RefCell
<Vec
<config
::CrateType
>>,
60 pub crate_metadata
: RefCell
<Vec
<String
>>,
61 pub features
: RefCell
<feature_gate
::Features
>,
63 pub delayed_span_bug
: RefCell
<Option
<(codemap
::Span
, String
)>>,
65 /// The maximum recursion limit for potentially infinitely recursive
66 /// operations such as auto-dereference and monomorphization.
67 pub recursion_limit
: Cell
<usize>,
69 pub can_print_warnings
: bool
,
71 next_node_id
: Cell
<ast
::NodeId
>
75 pub fn span_fatal(&self, sp
: Span
, msg
: &str) -> ! {
76 if self.opts
.treat_err_as_bug
{
77 self.span_bug(sp
, msg
);
79 panic
!(self.diagnostic().span_fatal(sp
, msg
))
81 pub fn span_fatal_with_code(&self, sp
: Span
, msg
: &str, code
: &str) -> ! {
82 if self.opts
.treat_err_as_bug
{
83 self.span_bug(sp
, msg
);
85 panic
!(self.diagnostic().span_fatal_with_code(sp
, msg
, code
))
87 pub fn fatal(&self, msg
: &str) -> ! {
88 if self.opts
.treat_err_as_bug
{
91 self.diagnostic().handler().fatal(msg
)
93 pub fn span_err(&self, sp
: Span
, msg
: &str) {
94 if self.opts
.treat_err_as_bug
{
95 self.span_bug(sp
, msg
);
97 match split_msg_into_multilines(msg
) {
98 Some(msg
) => self.diagnostic().span_err(sp
, &msg
[..]),
99 None
=> self.diagnostic().span_err(sp
, msg
)
102 pub fn span_err_with_code(&self, sp
: Span
, msg
: &str, code
: &str) {
103 if self.opts
.treat_err_as_bug
{
104 self.span_bug(sp
, msg
);
106 match split_msg_into_multilines(msg
) {
107 Some(msg
) => self.diagnostic().span_err_with_code(sp
, &msg
[..], code
),
108 None
=> self.diagnostic().span_err_with_code(sp
, msg
, code
)
111 pub fn err(&self, msg
: &str) {
112 if self.opts
.treat_err_as_bug
{
115 self.diagnostic().handler().err(msg
)
117 pub fn err_count(&self) -> usize {
118 self.diagnostic().handler().err_count()
120 pub fn has_errors(&self) -> bool
{
121 self.diagnostic().handler().has_errors()
123 pub fn abort_if_errors(&self) {
124 self.diagnostic().handler().abort_if_errors();
126 let delayed_bug
= self.delayed_span_bug
.borrow();
128 Some((span
, ref errmsg
)) => {
129 self.diagnostic().span_bug(span
, errmsg
);
134 pub fn span_warn(&self, sp
: Span
, msg
: &str) {
135 if self.can_print_warnings
{
136 self.diagnostic().span_warn(sp
, msg
)
139 pub fn span_warn_with_code(&self, sp
: Span
, msg
: &str, code
: &str) {
140 if self.can_print_warnings
{
141 self.diagnostic().span_warn_with_code(sp
, msg
, code
)
144 pub fn warn(&self, msg
: &str) {
145 if self.can_print_warnings
{
146 self.diagnostic().handler().warn(msg
)
149 pub fn opt_span_warn(&self, opt_sp
: Option
<Span
>, msg
: &str) {
151 Some(sp
) => self.span_warn(sp
, msg
),
152 None
=> self.warn(msg
),
155 pub fn span_note(&self, sp
: Span
, msg
: &str) {
156 self.diagnostic().span_note(sp
, msg
)
158 pub fn span_end_note(&self, sp
: Span
, msg
: &str) {
159 self.diagnostic().span_end_note(sp
, msg
)
162 /// Prints out a message with a suggested edit of the code.
164 /// See `diagnostic::RenderSpan::Suggestion` for more information.
165 pub fn span_suggestion(&self, sp
: Span
, msg
: &str, suggestion
: String
) {
166 self.diagnostic().span_suggestion(sp
, msg
, suggestion
)
168 pub fn span_help(&self, sp
: Span
, msg
: &str) {
169 self.diagnostic().span_help(sp
, msg
)
171 pub fn fileline_note(&self, sp
: Span
, msg
: &str) {
172 self.diagnostic().fileline_note(sp
, msg
)
174 pub fn fileline_help(&self, sp
: Span
, msg
: &str) {
175 self.diagnostic().fileline_help(sp
, msg
)
177 pub fn note(&self, msg
: &str) {
178 self.diagnostic().handler().note(msg
)
180 pub fn help(&self, msg
: &str) {
181 self.diagnostic().handler().help(msg
)
183 pub fn opt_span_bug(&self, opt_sp
: Option
<Span
>, msg
: &str) -> ! {
185 Some(sp
) => self.span_bug(sp
, msg
),
186 None
=> self.bug(msg
),
189 /// Delay a span_bug() call until abort_if_errors()
190 pub fn delay_span_bug(&self, sp
: Span
, msg
: &str) {
191 let mut delayed
= self.delayed_span_bug
.borrow_mut();
192 *delayed
= Some((sp
, msg
.to_string()));
194 pub fn span_bug(&self, sp
: Span
, msg
: &str) -> ! {
195 self.diagnostic().span_bug(sp
, msg
)
197 pub fn bug(&self, msg
: &str) -> ! {
198 self.diagnostic().handler().bug(msg
)
200 pub fn span_unimpl(&self, sp
: Span
, msg
: &str) -> ! {
201 self.diagnostic().span_unimpl(sp
, msg
)
203 pub fn unimpl(&self, msg
: &str) -> ! {
204 self.diagnostic().handler().unimpl(msg
)
206 pub fn add_lint(&self,
207 lint
: &'
static lint
::Lint
,
211 let lint_id
= lint
::LintId
::of(lint
);
212 let mut lints
= self.lints
.borrow_mut();
213 match lints
.get_mut(&id
) {
214 Some(arr
) => { arr.push((lint_id, sp, msg)); return; }
217 lints
.insert(id
, vec
!((lint_id
, sp
, msg
)));
219 pub fn next_node_id(&self) -> ast
::NodeId
{
220 self.reserve_node_ids(1)
222 pub fn reserve_node_ids(&self, count
: ast
::NodeId
) -> ast
::NodeId
{
223 let id
= self.next_node_id
.get();
225 match id
.checked_add(count
) {
226 Some(next
) => self.next_node_id
.set(next
),
227 None
=> self.bug("Input too large, ran out of node ids!")
232 pub fn diagnostic
<'a
>(&'a
self) -> &'a diagnostic
::SpanHandler
{
233 &self.parse_sess
.span_diagnostic
235 pub fn codemap
<'a
>(&'a
self) -> &'a codemap
::CodeMap
{
236 self.parse_sess
.codemap()
238 // This exists to help with refactoring to eliminate impossible
240 pub fn impossible_case(&self, sp
: Span
, msg
: &str) -> ! {
242 &format
!("impossible case reached: {}", msg
));
244 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
245 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
246 pub fn count_llvm_insns(&self) -> bool
{
247 self.opts
.debugging_opts
.count_llvm_insns
249 pub fn count_type_sizes(&self) -> bool
{
250 self.opts
.debugging_opts
.count_type_sizes
252 pub fn time_llvm_passes(&self) -> bool
{
253 self.opts
.debugging_opts
.time_llvm_passes
255 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
256 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
257 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
258 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
259 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
260 pub fn print_llvm_passes(&self) -> bool
{
261 self.opts
.debugging_opts
.print_llvm_passes
263 pub fn lto(&self) -> bool
{
266 pub fn no_landing_pads(&self) -> bool
{
267 self.opts
.debugging_opts
.no_landing_pads
269 pub fn unstable_options(&self) -> bool
{
270 self.opts
.debugging_opts
.unstable_options
272 pub fn print_enum_sizes(&self) -> bool
{
273 self.opts
.debugging_opts
.print_enum_sizes
275 pub fn nonzeroing_move_hints(&self) -> bool
{
276 self.opts
.debugging_opts
.enable_nonzeroing_move_hints
278 pub fn sysroot
<'a
>(&'a
self) -> &'a Path
{
279 match self.opts
.maybe_sysroot
{
280 Some (ref sysroot
) => sysroot
,
281 None
=> self.default_sysroot
.as_ref()
282 .expect("missing sysroot and default_sysroot in Session")
285 pub fn target_filesearch(&self, kind
: PathKind
) -> filesearch
::FileSearch
{
286 filesearch
::FileSearch
::new(self.sysroot(),
287 &self.opts
.target_triple
,
288 &self.opts
.search_paths
,
291 pub fn host_filesearch(&self, kind
: PathKind
) -> filesearch
::FileSearch
{
292 filesearch
::FileSearch
::new(
294 config
::host_triple(),
295 &self.opts
.search_paths
,
300 fn split_msg_into_multilines(msg
: &str) -> Option
<String
> {
301 // Conditions for enabling multi-line errors:
302 if !msg
.contains("mismatched types") &&
303 !msg
.contains("type mismatch resolving") &&
304 !msg
.contains("if and else have incompatible types") &&
305 !msg
.contains("if may be missing an else clause") &&
306 !msg
.contains("match arms have incompatible types") &&
307 !msg
.contains("structure constructor specifies a structure of type") &&
308 !msg
.contains("has an incompatible type for trait") {
311 let first
= msg
.match_indices("expected").filter(|s
| {
312 s
.0 > 0 && (msg
.char_at_reverse(s
.0) == ' '
||
313 msg
.char_at_reverse(s
.0) == '
('
)
314 }).map(|(a
, b
)| (a
- 1, b
));
315 let second
= msg
.match_indices("found").filter(|s
| {
316 msg
.char_at_reverse(s
.0) == ' '
317 }).map(|(a
, b
)| (a
- 1, b
));
319 let mut new_msg
= String
::new();
322 // Insert `\n` before expected and found.
323 for (pos1
, pos2
) in first
.zip(second
) {
325 // A `(` may be preceded by a space and it should be trimmed
326 msg
[head
..pos1
.0
].trim_right() + // prefix
327 "\n" + // insert before first
328 &msg
[pos1
.0
..pos1
.1
] + // insert what first matched
329 &msg
[pos1
.1
..pos2
.0
] + // between matches
330 "\n " + // insert before second
332 // `expected` is 3 char longer than `found`. To align the types,
333 // `found` gets 3 spaces prepended.
334 &msg
[pos2
.0
..pos2
.1
]; // insert what second matched
339 let mut tail
= &msg
[head
..];
340 let third
= tail
.find("(values differ")
341 .or(tail
.find("(lifetime"))
342 .or(tail
.find("(cyclic type of infinite size"));
343 // Insert `\n` before any remaining messages which match.
344 if let Some(pos
) = third
{
345 // The end of the message may just be wrapped in `()` without
346 // `expected`/`found`. Push this also to a new line and add the
349 // `(` is usually preceded by a space and should be trimmed.
350 tail
[..pos
].trim_right() + // prefix
351 "\n" + // insert before paren
352 &tail
[pos
..]; // append the tail
357 new_msg
.push_str(tail
);
358 return Some(new_msg
);
361 pub fn build_session(sopts
: config
::Options
,
362 local_crate_source_file
: Option
<PathBuf
>,
363 registry
: diagnostics
::registry
::Registry
)
365 // FIXME: This is not general enough to make the warning lint completely override
366 // normal diagnostic warnings, since the warning lint can also be denied and changed
367 // later via the source code.
368 let can_print_warnings
= sopts
.lint_opts
370 .filter(|&&(ref key
, _
)| *key
== "warnings")
371 .map(|&(_
, ref level
)| *level
!= lint
::Allow
)
375 let codemap
= codemap
::CodeMap
::new();
376 let diagnostic_handler
=
377 diagnostic
::Handler
::new(sopts
.color
, Some(registry
), can_print_warnings
);
378 let span_diagnostic_handler
=
379 diagnostic
::SpanHandler
::new(diagnostic_handler
, codemap
);
381 build_session_(sopts
, local_crate_source_file
, span_diagnostic_handler
)
384 pub fn build_session_(sopts
: config
::Options
,
385 local_crate_source_file
: Option
<PathBuf
>,
386 span_diagnostic
: diagnostic
::SpanHandler
)
388 let host
= match Target
::search(config
::host_triple()) {
391 span_diagnostic
.handler()
392 .fatal(&format
!("Error loading host specification: {}", e
));
395 let target_cfg
= config
::build_target_config(&sopts
, &span_diagnostic
);
396 let p_s
= parse
::ParseSess
::with_span_handler(span_diagnostic
);
397 let default_sysroot
= match sopts
.maybe_sysroot
{
399 None
=> Some(filesearch
::get_or_default_sysroot())
402 // Make the path absolute, if necessary
403 let local_crate_source_file
= local_crate_source_file
.map(|path
|
404 if path
.is_absolute() {
407 env
::current_dir().unwrap().join(&path
)
411 let can_print_warnings
= sopts
.lint_opts
413 .filter(|&&(ref key
, _
)| *key
== "warnings")
414 .map(|&(_
, ref level
)| *level
!= lint
::Allow
)
422 cstore
: CStore
::new(token
::get_ident_interner()),
424 // For a library crate, this is always none
425 entry_fn
: RefCell
::new(None
),
426 entry_type
: Cell
::new(None
),
427 plugin_registrar_fn
: Cell
::new(None
),
428 default_sysroot
: default_sysroot
,
429 local_crate_source_file
: local_crate_source_file
,
430 working_dir
: env
::current_dir().unwrap(),
431 lint_store
: RefCell
::new(lint
::LintStore
::new()),
432 lints
: RefCell
::new(NodeMap()),
433 plugin_llvm_passes
: RefCell
::new(Vec
::new()),
434 plugin_attributes
: RefCell
::new(Vec
::new()),
435 crate_types
: RefCell
::new(Vec
::new()),
436 crate_metadata
: RefCell
::new(Vec
::new()),
437 delayed_span_bug
: RefCell
::new(None
),
438 features
: RefCell
::new(feature_gate
::Features
::new()),
439 recursion_limit
: Cell
::new(64),
440 can_print_warnings
: can_print_warnings
,
441 next_node_id
: Cell
::new(1)
447 // Seems out of place, but it uses session, so I'm putting it here
448 pub fn expect
<T
, M
>(sess
: &Session
, opt
: Option
<T
>, msg
: M
) -> T
where
449 M
: FnOnce() -> String
,
451 diagnostic
::expect(sess
.diagnostic(), opt
, msg
)
454 pub fn early_error(msg
: &str) -> ! {
455 let mut emitter
= diagnostic
::EmitterWriter
::stderr(diagnostic
::Auto
, None
);
456 emitter
.emit(None
, msg
, None
, diagnostic
::Fatal
);
457 panic
!(diagnostic
::FatalError
);
460 pub fn early_warn(msg
: &str) {
461 let mut emitter
= diagnostic
::EmitterWriter
::stderr(diagnostic
::Auto
, None
);
462 emitter
.emit(None
, msg
, None
, diagnostic
::Warning
);