rust/src/librustc/lib.rs

443 lines
13 KiB
Rust
Raw Normal View History

2013-02-28 07:15:32 -06:00
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
2014-01-07 23:17:52 -06:00
/*!
The Rust compiler.
# Note
This API is completely unstable and subject to change.
*/
#![crate_id = "rustc#0.11-pre"]
#![comment = "The Rust compiler"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
2014-01-07 23:17:52 -06:00
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://static.rust-lang.org/doc/master")]
2011-05-05 21:44:00 -05:00
#![allow(deprecated)]
#![feature(macro_rules, globs, struct_variant, managed_boxes, quote,
default_type_params, phase)]
extern crate flate;
extern crate arena;
extern crate syntax;
extern crate serialize;
extern crate sync;
extern crate getopts;
extern crate collections;
2014-02-19 21:08:12 -06:00
extern crate time;
2014-02-26 11:58:41 -06:00
extern crate libc;
log: Introduce liblog, the old std::logging This commit moves all logging out of the standard library into an external crate. This crate is the new crate which is responsible for all logging macros and logging implementation. A few reasons for this change are: * The crate map has always been a bit of a code smell among rust programs. It has difficulty being loaded on almost all platforms, and it's used almost exclusively for logging and only logging. Removing the crate map is one of the end goals of this movement. * The compiler has a fair bit of special support for logging. It has the __log_level() expression as well as generating a global word per module specifying the log level. This is unfairly favoring the built-in logging system, and is much better done purely in libraries instead of the compiler itself. * Initialization of logging is much easier to do if there is no reliance on a magical crate map being available to set module log levels. * If the logging library can be written outside of the standard library, there's no reason that it shouldn't be. It's likely that we're not going to build the highest quality logging library of all time, so third-party libraries should be able to provide just as high-quality logging systems as the default one provided in the rust distribution. With a migration such as this, the change does not come for free. There are some subtle changes in the behavior of liblog vs the previous logging macros: * The core change of this migration is that there is no longer a physical log-level per module. This concept is still emulated (it is quite useful), but there is now only a global log level, not a local one. This global log level is a reflection of the maximum of all log levels specified. The previously generated logging code looked like: if specified_level <= __module_log_level() { println!(...) } The newly generated code looks like: if specified_level <= ::log::LOG_LEVEL { if ::log::module_enabled(module_path!()) { println!(...) } } Notably, the first layer of checking is still intended to be "super fast" in that it's just a load of a global word and a compare. The second layer of checking is executed to determine if the current module does indeed have logging turned on. This means that if any module has a debug log level turned on, all modules with debug log levels get a little bit slower (they all do more expensive dynamic checks to determine if they're turned on or not). Semantically, this migration brings no change in this respect, but runtime-wise, this will have a perf impact on some code. * A `RUST_LOG=::help` directive will no longer print out a list of all modules that can be logged. This is because the crate map will no longer specify the log levels of all modules, so the list of modules is not known. Additionally, warnings can no longer be provided if a malformed logging directive was supplied. The new "hello world" for logging looks like: #[phase(syntax, link)] extern crate log; fn main() { debug!("Hello, world!"); }
2014-03-09 00:11:44 -06:00
#[phase(syntax, link)]
extern crate log;
use back::link;
use driver::session;
use middle::lint;
use d = driver::driver;
use std::any::AnyRefExt;
2014-02-06 01:34:33 -06:00
use std::cmp;
2013-11-11 00:46:32 -06:00
use std::io;
use std::os;
use std::str;
use std::task;
use syntax::ast;
use syntax::diagnostic::Emitter;
use syntax::diagnostic;
use syntax::parse;
pub mod middle {
2013-06-12 18:18:58 -05:00
pub mod trans;
pub mod ty;
pub mod ty_fold;
pub mod subst;
pub mod resolve;
pub mod resolve_lifetime;
2012-11-28 14:33:00 -06:00
pub mod typeck;
pub mod check_loop;
pub mod check_match;
pub mod check_const;
pub mod check_static;
pub mod lint;
pub mod borrowck;
2013-04-17 17:05:17 -05:00
pub mod dataflow;
pub mod mem_categorization;
pub mod liveness;
pub mod kind;
pub mod freevars;
pub mod pat_util;
pub mod region;
pub mod const_eval;
pub mod astencode;
pub mod lang_items;
pub mod privacy;
pub mod moves;
pub mod entry;
pub mod effect;
pub mod reachable;
pub mod graph;
pub mod cfg;
2013-12-08 01:55:27 -06:00
pub mod dead;
2011-04-19 18:40:46 -05:00
}
pub mod front {
pub mod config;
pub mod test;
pub mod std_inject;
2014-01-06 06:00:46 -06:00
pub mod assign_node_ids_and_map;
pub mod feature_gate;
2014-02-07 04:50:07 -06:00
pub mod show_span;
2010-06-23 23:03:09 -05:00
}
pub mod back {
pub mod abi;
pub mod archive;
pub mod arm;
pub mod link;
pub mod lto;
2013-01-29 08:28:08 -06:00
pub mod mips;
pub mod rpath;
pub mod svh;
pub mod target_strs;
pub mod x86;
pub mod x86_64;
}
pub mod metadata;
pub mod driver;
2010-06-23 23:03:09 -05:00
pub mod util {
pub mod common;
pub mod ppaux;
pub mod sha2;
pub mod nodemap;
pub mod fs;
2010-08-18 13:34:47 -05:00
}
pub mod lib {
pub mod llvm;
pub mod llvmdeps;
2010-07-12 19:47:40 -05:00
}
static BUG_REPORT_URL: &'static str =
"http://static.rust-lang.org/doc/master/complement-bugreport.html";
pub fn version(argv0: &str) {
let vers = match option_env!("CFG_VERSION") {
Some(vers) => vers,
None => "unknown version"
};
println!("{} {}", argv0, vers);
println!("host: {}", d::host_triple());
}
pub fn usage(argv0: &str) {
2013-09-28 00:38:08 -05:00
let message = format!("Usage: {} [OPTIONS] INPUT", argv0);
println!("{}\n\
2013-06-21 18:08:37 -05:00
Additional help:
-C help Print codegen options
2013-06-21 18:08:37 -05:00
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc\n",
getopts::usage(message, d::optgroups().as_slice()));
2012-11-28 14:33:00 -06:00
}
pub fn describe_warnings() {
println!("
2012-11-28 14:33:00 -06:00
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
2012-11-28 14:33:00 -06:00
let lint_dict = lint::get_lint_dict();
let mut lint_dict = lint_dict.move_iter()
.map(|(k, v)| (v, k))
.collect::<Vec<(lint::LintSpec, &'static str)> >();
lint_dict.as_mut_slice().sort();
2012-11-28 14:33:00 -06:00
let mut max_key = 0;
for &(_, name) in lint_dict.iter() {
2014-02-06 01:34:33 -06:00
max_key = cmp::max(name.len(), max_key);
}
2012-11-28 14:33:00 -06:00
fn padded(max: uint, s: &str) -> ~str {
" ".repeat(max - s.len()) + s
2012-11-28 14:33:00 -06:00
}
println!("\nAvailable lint checks:\n");
println!(" {} {:7.7s} {}",
padded(max_key, "name"), "default", "meaning");
println!(" {} {:7.7s} {}\n",
padded(max_key, "----"), "-------", "-------");
for (spec, name) in lint_dict.move_iter() {
let name = name.replace("_", "-");
println!(" {} {:7.7s} {}",
padded(max_key, name),
lint::level_to_str(spec.default),
spec.desc);
2012-11-28 14:33:00 -06:00
}
println!("");
2012-11-28 14:33:00 -06:00
}
pub fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
let r = session::debugging_opts_map();
for tuple in r.iter() {
2013-07-02 14:47:32 -05:00
match *tuple {
(ref name, ref desc, _) => {
println!(" -Z {:>20s} -- {}", *name, *desc);
2013-07-02 14:47:32 -05:00
}
}
2012-11-28 14:33:00 -06:00
}
}
pub fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
let mut cg = session::basic_codegen_options();
for &(name, parser, desc) in session::CG_OPTIONS.iter() {
// we invoke the parser function on `None` to see if this option needs
// an argument or not.
let (width, extra) = if parser(&mut cg, None) {
(25, "")
} else {
(21, "=val")
};
println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
2014-02-06 16:38:33 -06:00
pub fn run_compiler(args: &[~str]) {
let mut args = args.to_owned();
let binary = args.shift().unwrap();
2012-11-28 14:33:00 -06:00
if args.is_empty() { usage(binary); return; }
2012-11-28 14:33:00 -06:00
let matches =
&match getopts::getopts(args, d::optgroups().as_slice()) {
Ok(m) => m,
Err(f) => {
2014-02-06 16:38:33 -06:00
d::early_error(f.to_err_msg());
2012-11-28 14:33:00 -06:00
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage(binary);
2012-11-28 14:33:00 -06:00
return;
}
let lint_flags = matches.opt_strs("W").move_iter().collect::<Vec<_>>().append(
matches.opt_strs("warn").as_slice());
if lint_flags.iter().any(|x| x == &~"help") {
2012-11-28 14:33:00 -06:00
describe_warnings();
return;
}
let r = matches.opt_strs("Z");
2013-07-04 21:13:26 -05:00
if r.iter().any(|x| x == &~"help") {
2012-11-28 14:33:00 -06:00
describe_debug_flags();
return;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| x == &~"help") {
describe_codegen_flags();
return;
}
if cg_flags.contains(&~"passes=list") {
2013-08-22 22:58:42 -05:00
unsafe { lib::llvm::llvm::LLVMRustPrintPasses(); }
return;
}
if matches.opt_present("v") || matches.opt_present("version") {
version(binary);
2012-11-28 14:33:00 -06:00
return;
}
let (input, input_file_path) = match matches.free.len() {
2014-02-06 16:38:33 -06:00
0u => d::early_error("no input filename given"),
2012-11-28 14:33:00 -06:00
1u => {
let ifile = matches.free.get(0).as_slice();
2014-01-21 12:08:10 -06:00
if ifile == "-" {
let contents = io::stdin().read_to_end().unwrap();
let src = str::from_utf8(contents.as_slice()).unwrap().to_owned();
(d::StrInput(src), None)
2012-11-28 14:33:00 -06:00
} else {
(d::FileInput(Path::new(ifile)), Some(Path::new(ifile)))
2012-11-28 14:33:00 -06:00
}
}
2014-02-06 16:38:33 -06:00
_ => d::early_error("multiple input filenames provided")
2012-11-28 14:33:00 -06:00
};
2014-02-10 10:10:26 -06:00
let sopts = d::build_session_options(matches);
2014-02-06 16:38:33 -06:00
let sess = d::build_session(sopts, input_file_path);
let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
let ofile = matches.opt_str("o").map(|o| Path::new(o));
2014-03-05 08:36:01 -06:00
let cfg = d::build_configuration(&sess);
let pretty = matches.opt_default("pretty", "normal").map(|a| {
2014-03-05 08:36:01 -06:00
d::parse_pretty(&sess, a)
});
2012-11-28 14:33:00 -06:00
match pretty {
2014-03-16 13:56:24 -05:00
Some::<d::PpMode>(ppm) => {
d::pretty_print_input(sess, cfg, &input, ppm, ofile);
2014-03-16 13:56:24 -05:00
return;
}
None::<d::PpMode> => {/* continue */ }
2012-11-28 14:33:00 -06:00
}
let ls = matches.opt_present("ls");
2012-11-28 14:33:00 -06:00
if ls {
match input {
2014-03-16 13:56:24 -05:00
d::FileInput(ref ifile) => {
let mut stdout = io::stdout();
d::list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
}
d::StrInput(_) => {
d::early_error("can not list metadata for stdin");
}
2012-11-28 14:33:00 -06:00
}
return;
}
2014-03-16 13:56:24 -05:00
let (crate_id, crate_name, crate_file_name) = sess.opts.print_metas;
// these nasty nested conditions are to avoid doing extra work
if crate_id || crate_name || crate_file_name {
2014-03-05 08:36:01 -06:00
let attrs = parse_crate_attrs(&sess, &input);
let t_outputs = d::build_output_filenames(&input, &odir, &ofile,
2014-03-05 08:36:01 -06:00
attrs.as_slice(), &sess);
log: Introduce liblog, the old std::logging This commit moves all logging out of the standard library into an external crate. This crate is the new crate which is responsible for all logging macros and logging implementation. A few reasons for this change are: * The crate map has always been a bit of a code smell among rust programs. It has difficulty being loaded on almost all platforms, and it's used almost exclusively for logging and only logging. Removing the crate map is one of the end goals of this movement. * The compiler has a fair bit of special support for logging. It has the __log_level() expression as well as generating a global word per module specifying the log level. This is unfairly favoring the built-in logging system, and is much better done purely in libraries instead of the compiler itself. * Initialization of logging is much easier to do if there is no reliance on a magical crate map being available to set module log levels. * If the logging library can be written outside of the standard library, there's no reason that it shouldn't be. It's likely that we're not going to build the highest quality logging library of all time, so third-party libraries should be able to provide just as high-quality logging systems as the default one provided in the rust distribution. With a migration such as this, the change does not come for free. There are some subtle changes in the behavior of liblog vs the previous logging macros: * The core change of this migration is that there is no longer a physical log-level per module. This concept is still emulated (it is quite useful), but there is now only a global log level, not a local one. This global log level is a reflection of the maximum of all log levels specified. The previously generated logging code looked like: if specified_level <= __module_log_level() { println!(...) } The newly generated code looks like: if specified_level <= ::log::LOG_LEVEL { if ::log::module_enabled(module_path!()) { println!(...) } } Notably, the first layer of checking is still intended to be "super fast" in that it's just a load of a global word and a compare. The second layer of checking is executed to determine if the current module does indeed have logging turned on. This means that if any module has a debug log level turned on, all modules with debug log levels get a little bit slower (they all do more expensive dynamic checks to determine if they're turned on or not). Semantically, this migration brings no change in this respect, but runtime-wise, this will have a perf impact on some code. * A `RUST_LOG=::help` directive will no longer print out a list of all modules that can be logged. This is because the crate map will no longer specify the log levels of all modules, so the list of modules is not known. Additionally, warnings can no longer be provided if a malformed logging directive was supplied. The new "hello world" for logging looks like: #[phase(syntax, link)] extern crate log; fn main() { debug!("Hello, world!"); }
2014-03-09 00:11:44 -06:00
let id = link::find_crate_id(attrs.as_slice(), t_outputs.out_filestem);
2012-11-28 14:33:00 -06:00
if crate_id {
println!("{}", id.to_str());
}
if crate_name {
println!("{}", id.name);
}
if crate_file_name {
let crate_types = session::collect_crate_types(&sess,
attrs.as_slice());
Redesign output flags for rustc This commit removes the -c, --emit-llvm, -s, --rlib, --dylib, --staticlib, --lib, and --bin flags from rustc, adding the following flags: * --emit=[asm,ir,bc,obj,link] * --crate-type=[dylib,rlib,staticlib,bin,lib] The -o option has also been redefined to be used for *all* flavors of outputs. This means that we no longer ignore it for libraries. The --out-dir remains the same as before. The new logic for files that rustc emits is as follows: 1. Output types are dictated by the --emit flag. The default value is --emit=link, and this option can be passed multiple times and have all options stacked on one another. 2. Crate types are dictated by the --crate-type flag and the #[crate_type] attribute. The flags can be passed many times and stack with the crate attribute. 3. If the -o flag is specified, and only one output type is specified, the output will be emitted at this location. If more than one output type is specified, then the filename of -o is ignored, and all output goes in the directory that -o specifies. The -o option always ignores the --out-dir option. 4. If the --out-dir flag is specified, all output goes in this directory. 5. If -o and --out-dir are both not present, all output goes in the current directory of the process. 6. When multiple output types are specified, the filestem of all output is the same as the name of the CrateId (derived from a crate attribute or from the filestem of the crate file). Closes #7791 Closes #11056 Closes #11667
2014-02-03 17:27:54 -06:00
for &style in crate_types.iter() {
let fname = link::filename_for_input(&sess, style, &id,
Redesign output flags for rustc This commit removes the -c, --emit-llvm, -s, --rlib, --dylib, --staticlib, --lib, and --bin flags from rustc, adding the following flags: * --emit=[asm,ir,bc,obj,link] * --crate-type=[dylib,rlib,staticlib,bin,lib] The -o option has also been redefined to be used for *all* flavors of outputs. This means that we no longer ignore it for libraries. The --out-dir remains the same as before. The new logic for files that rustc emits is as follows: 1. Output types are dictated by the --emit flag. The default value is --emit=link, and this option can be passed multiple times and have all options stacked on one another. 2. Crate types are dictated by the --crate-type flag and the #[crate_type] attribute. The flags can be passed many times and stack with the crate attribute. 3. If the -o flag is specified, and only one output type is specified, the output will be emitted at this location. If more than one output type is specified, then the filename of -o is ignored, and all output goes in the directory that -o specifies. The -o option always ignores the --out-dir option. 4. If the --out-dir flag is specified, all output goes in this directory. 5. If -o and --out-dir are both not present, all output goes in the current directory of the process. 6. When multiple output types are specified, the filestem of all output is the same as the name of the CrateId (derived from a crate attribute or from the filestem of the crate file). Closes #7791 Closes #11056 Closes #11667
2014-02-03 17:27:54 -06:00
&t_outputs.with_extension(""));
println!("{}", fname.filename_display());
}
}
return;
}
d::compile_input(sess, cfg, &input, &odir, &ofile);
}
2014-03-05 08:36:01 -06:00
fn parse_crate_attrs(sess: &session::Session, input: &d::Input) ->
Vec<ast::Attribute> {
let result = match *input {
d::FileInput(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
2014-03-09 09:54:34 -05:00
&sess.parse_sess)
}
d::StrInput(ref src) => {
parse::parse_crate_attrs_from_source_str(d::anon_src(),
(*src).clone(),
Vec::new(),
2014-03-09 09:54:34 -05:00
&sess.parse_sess)
}
};
result.move_iter().collect()
2012-11-28 14:33:00 -06:00
}
/// Run a procedure which will detect failures in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
2014-04-07 15:30:48 -05:00
pub fn monitor(f: proc():Send) {
// FIXME: This is a hack for newsched since it doesn't support split stacks.
// rustc needs a lot of stack! When optimizations are disabled, it needs
// even *more* stack than usual as well.
#[cfg(rtopt)]
static STACK_SIZE: uint = 6000000; // 6MB
#[cfg(not(rtopt))]
static STACK_SIZE: uint = 20000000; // 20MB
2014-02-13 00:03:36 -06:00
let mut task_builder = task::task().named("rustc");
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if os::getenv("RUST_MIN_STACK").is_none() {
task_builder.opts.stack_size = Some(STACK_SIZE);
}
let (tx, rx) = channel();
let w = io::ChanWriter::new(tx);
let mut r = io::ChanReader::new(rx);
match task_builder.try(proc() {
io::stdio::set_stderr(~w);
2014-02-06 16:38:33 -06:00
f()
}) {
Ok(()) => { /* fallthrough */ }
Err(value) => {
2012-11-28 14:33:00 -06:00
// Task failed without emitting a fatal diagnostic
if !value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr();
// a .span_bug or .bug call has already printed what
// it wants to print.
if !value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected failure",
diagnostic::Bug);
}
2012-11-28 14:33:00 -06:00
let xs = [
~"the compiler hit an unexpected failure path. this is a bug.",
"we would appreciate a bug report: " + BUG_REPORT_URL,
~"run with `RUST_BACKTRACE=1` for a backtrace",
];
for note in xs.iter() {
emitter.emit(None, *note, diagnostic::Note)
2012-11-28 14:33:00 -06:00
}
match r.read_to_str() {
Ok(s) => println!("{}", s),
Err(e) => emitter.emit(None,
format!("failed to read internal stderr: {}", e),
diagnostic::Error),
}
2012-11-28 14:33:00 -06:00
}
// Fail so the process returns a failure code, but don't pollute the
// output with some unnecessary failure messages, we've already
// printed everything that we needed to.
io::stdio::set_stderr(~io::util::NullWriter);
fail!();
2012-11-28 14:33:00 -06:00
}
}
}
pub fn main() {
std::os::set_exit_status(main_args(std::os::args()));
}
pub fn main_args(args: &[~str]) -> int {
let owned_args = args.to_owned();
2014-02-06 16:38:33 -06:00
monitor(proc() run_compiler(owned_args));
0
2012-11-28 14:33:00 -06:00
}