De-@ Session usage.

This commit is contained in:
Eduard Burtescu 2014-03-05 16:36:01 +02:00
parent eb68beec4b
commit 4fae06824c
48 changed files with 510 additions and 548 deletions

View File

@ -28,8 +28,8 @@ use syntax::abi;
pub static METADATA_FILENAME: &'static str = "rust.metadata.bin"; pub static METADATA_FILENAME: &'static str = "rust.metadata.bin";
pub struct Archive { pub struct Archive<'a> {
priv sess: Session, priv sess: &'a Session,
priv dst: Path, priv dst: Path,
} }
@ -37,8 +37,8 @@ pub struct ArchiveRO {
priv ptr: ArchiveRef, priv ptr: ArchiveRef,
} }
fn run_ar(sess: Session, args: &str, cwd: Option<&Path>, fn run_ar(sess: &Session, args: &str, cwd: Option<&Path>,
paths: &[&Path]) -> ProcessOutput { paths: &[&Path]) -> ProcessOutput {
let ar = get_ar_prog(sess); let ar = get_ar_prog(sess);
let mut args = vec!(args.to_owned()); let mut args = vec!(args.to_owned());
@ -74,16 +74,16 @@ fn run_ar(sess: Session, args: &str, cwd: Option<&Path>,
} }
} }
impl Archive { impl<'a> Archive<'a> {
/// Initializes a new static archive with the given object file /// Initializes a new static archive with the given object file
pub fn create<'a>(sess: Session, dst: &'a Path, pub fn create<'b>(sess: &'a Session, dst: &'b Path,
initial_object: &'a Path) -> Archive { initial_object: &'b Path) -> Archive<'a> {
run_ar(sess, "crus", None, [dst, initial_object]); run_ar(sess, "crus", None, [dst, initial_object]);
Archive { sess: sess, dst: dst.clone() } Archive { sess: sess, dst: dst.clone() }
} }
/// Opens an existing static archive /// Opens an existing static archive
pub fn open(sess: Session, dst: Path) -> Archive { pub fn open(sess: &'a Session, dst: Path) -> Archive<'a> {
assert!(dst.exists()); assert!(dst.exists());
Archive { sess: sess, dst: dst } Archive { sess: sess, dst: dst }
} }

View File

@ -54,7 +54,7 @@ pub enum OutputType {
OutputTypeExe, OutputTypeExe,
} }
pub fn llvm_err(sess: Session, msg: ~str) -> ! { pub fn llvm_err(sess: &Session, msg: ~str) -> ! {
unsafe { unsafe {
let cstr = llvm::LLVMRustGetLastError(); let cstr = llvm::LLVMRustGetLastError();
if cstr == ptr::null() { if cstr == ptr::null() {
@ -68,7 +68,7 @@ pub fn llvm_err(sess: Session, msg: ~str) -> ! {
} }
pub fn WriteOutputFile( pub fn WriteOutputFile(
sess: Session, sess: &Session,
target: lib::llvm::TargetMachineRef, target: lib::llvm::TargetMachineRef,
pm: lib::llvm::PassManagerRef, pm: lib::llvm::PassManagerRef,
m: ModuleRef, m: ModuleRef,
@ -125,7 +125,7 @@ pub mod write {
} }
} }
pub fn run_passes(sess: Session, pub fn run_passes(sess: &Session,
trans: &CrateTranslation, trans: &CrateTranslation,
output_types: &[OutputType], output_types: &[OutputType],
output: &OutputFilenames) { output: &OutputFilenames) {
@ -156,7 +156,7 @@ pub mod write {
let tm = sess.targ_cfg.target_strs.target_triple.with_c_str(|t| { let tm = sess.targ_cfg.target_strs.target_triple.with_c_str(|t| {
sess.opts.cg.target_cpu.with_c_str(|cpu| { sess.opts.cg.target_cpu.with_c_str(|cpu| {
target_feature(&sess).with_c_str(|features| { target_feature(sess).with_c_str(|features| {
llvm::LLVMRustCreateTargetMachine( llvm::LLVMRustCreateTargetMachine(
t, cpu, features, t, cpu, features,
lib::llvm::CodeModelDefault, lib::llvm::CodeModelDefault,
@ -323,7 +323,7 @@ pub mod write {
} }
} }
pub fn run_assembler(sess: Session, outputs: &OutputFilenames) { pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
let cc = super::get_cc_prog(sess); let cc = super::get_cc_prog(sess);
let assembly = outputs.temp_path(OutputTypeAssembly); let assembly = outputs.temp_path(OutputTypeAssembly);
let object = outputs.path(OutputTypeObject); let object = outputs.path(OutputTypeObject);
@ -351,7 +351,7 @@ pub mod write {
} }
} }
unsafe fn configure_llvm(sess: Session) { unsafe fn configure_llvm(sess: &Session) {
use sync::one::{Once, ONCE_INIT}; use sync::one::{Once, ONCE_INIT};
static mut INIT: Once = ONCE_INIT; static mut INIT: Once = ONCE_INIT;
@ -719,7 +719,7 @@ pub fn output_lib_filename(id: &CrateId) -> ~str {
format!("{}-{}-{}", id.name, crate_id_hash(id), id.version_or_default()) format!("{}-{}-{}", id.name, crate_id_hash(id), id.version_or_default())
} }
pub fn get_cc_prog(sess: Session) -> ~str { pub fn get_cc_prog(sess: &Session) -> ~str {
match sess.opts.cg.linker { match sess.opts.cg.linker {
Some(ref linker) => return linker.to_owned(), Some(ref linker) => return linker.to_owned(),
None => {} None => {}
@ -737,7 +737,7 @@ pub fn get_cc_prog(sess: Session) -> ~str {
get_system_tool(sess, "cc") get_system_tool(sess, "cc")
} }
pub fn get_ar_prog(sess: Session) -> ~str { pub fn get_ar_prog(sess: &Session) -> ~str {
match sess.opts.cg.ar { match sess.opts.cg.ar {
Some(ref ar) => return ar.to_owned(), Some(ref ar) => return ar.to_owned(),
None => {} None => {}
@ -746,7 +746,7 @@ pub fn get_ar_prog(sess: Session) -> ~str {
get_system_tool(sess, "ar") get_system_tool(sess, "ar")
} }
fn get_system_tool(sess: Session, tool: &str) -> ~str { fn get_system_tool(sess: &Session, tool: &str) -> ~str {
match sess.targ_cfg.os { match sess.targ_cfg.os {
abi::OsAndroid => match sess.opts.cg.android_cross_path { abi::OsAndroid => match sess.opts.cg.android_cross_path {
Some(ref path) => { Some(ref path) => {
@ -765,7 +765,7 @@ fn get_system_tool(sess: Session, tool: &str) -> ~str {
} }
} }
fn remove(sess: Session, path: &Path) { fn remove(sess: &Session, path: &Path) {
match fs::unlink(path) { match fs::unlink(path) {
Ok(..) => {} Ok(..) => {}
Err(e) => { Err(e) => {
@ -776,7 +776,7 @@ fn remove(sess: Session, path: &Path) {
/// Perform the linkage portion of the compilation phase. This will generate all /// Perform the linkage portion of the compilation phase. This will generate all
/// of the requested outputs for this compilation session. /// of the requested outputs for this compilation session.
pub fn link_binary(sess: Session, pub fn link_binary(sess: &Session,
trans: &CrateTranslation, trans: &CrateTranslation,
outputs: &OutputFilenames, outputs: &OutputFilenames,
id: &CrateId) -> Vec<Path> { id: &CrateId) -> Vec<Path> {
@ -830,7 +830,7 @@ pub fn filename_for_input(sess: &Session, crate_type: session::CrateType,
} }
} }
fn link_binary_output(sess: Session, fn link_binary_output(sess: &Session,
trans: &CrateTranslation, trans: &CrateTranslation,
crate_type: session::CrateType, crate_type: session::CrateType,
outputs: &OutputFilenames, outputs: &OutputFilenames,
@ -840,7 +840,7 @@ fn link_binary_output(sess: Session,
Some(ref file) => file.clone(), Some(ref file) => file.clone(),
None => { None => {
let out_filename = outputs.path(OutputTypeExe); let out_filename = outputs.path(OutputTypeExe);
filename_for_input(&sess, crate_type, id, &out_filename) filename_for_input(sess, crate_type, id, &out_filename)
} }
}; };
@ -883,10 +883,10 @@ fn link_binary_output(sess: Session,
// rlib primarily contains the object file of the crate, but it also contains // rlib primarily contains the object file of the crate, but it also contains
// all of the object files from native libraries. This is done by unzipping // all of the object files from native libraries. This is done by unzipping
// native libraries and inserting all of the contents into this archive. // native libraries and inserting all of the contents into this archive.
fn link_rlib(sess: Session, fn link_rlib<'a>(sess: &'a Session,
trans: Option<&CrateTranslation>, // None == no metadata/bytecode trans: Option<&CrateTranslation>, // None == no metadata/bytecode
obj_filename: &Path, obj_filename: &Path,
out_filename: &Path) -> Archive { out_filename: &Path) -> Archive<'a> {
let mut a = Archive::create(sess, out_filename, obj_filename); let mut a = Archive::create(sess, out_filename, obj_filename);
let used_libraries = sess.cstore.get_used_libraries(); let used_libraries = sess.cstore.get_used_libraries();
@ -985,7 +985,7 @@ fn link_rlib(sess: Session,
// There's no need to include metadata in a static archive, so ensure to not // There's no need to include metadata in a static archive, so ensure to not
// link in the metadata object file (and also don't prepare the archive with a // link in the metadata object file (and also don't prepare the archive with a
// metadata file). // metadata file).
fn link_staticlib(sess: Session, obj_filename: &Path, out_filename: &Path) { fn link_staticlib(sess: &Session, obj_filename: &Path, out_filename: &Path) {
let mut a = link_rlib(sess, None, obj_filename, out_filename); let mut a = link_rlib(sess, None, obj_filename, out_filename);
a.add_native_library("morestack").unwrap(); a.add_native_library("morestack").unwrap();
a.add_native_library("compiler-rt").unwrap(); a.add_native_library("compiler-rt").unwrap();
@ -1016,7 +1016,7 @@ fn link_staticlib(sess: Session, obj_filename: &Path, out_filename: &Path) {
// //
// This will invoke the system linker/cc to create the resulting file. This // This will invoke the system linker/cc to create the resulting file. This
// links to all upstream files as well. // links to all upstream files as well.
fn link_natively(sess: Session, dylib: bool, obj_filename: &Path, fn link_natively(sess: &Session, dylib: bool, obj_filename: &Path,
out_filename: &Path) { out_filename: &Path) {
let tmpdir = TempDir::new("rustc").expect("needs a temp dir"); let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
// The invocations of cc share some flags across platforms // The invocations of cc share some flags across platforms
@ -1066,7 +1066,7 @@ fn link_natively(sess: Session, dylib: bool, obj_filename: &Path,
} }
} }
fn link_args(sess: Session, fn link_args(sess: &Session,
dylib: bool, dylib: bool,
tmpdir: &Path, tmpdir: &Path,
obj_filename: &Path, obj_filename: &Path,
@ -1248,7 +1248,7 @@ fn link_args(sess: Session,
// Also note that the native libraries linked here are only the ones located // Also note that the native libraries linked here are only the ones located
// in the current crate. Upstream crates with native library dependencies // in the current crate. Upstream crates with native library dependencies
// may have their native library pulled in above. // may have their native library pulled in above.
fn add_local_native_libraries(args: &mut Vec<~str> , sess: Session) { fn add_local_native_libraries(args: &mut Vec<~str>, sess: &Session) {
let addl_lib_search_paths = sess.opts.addl_lib_search_paths.borrow(); let addl_lib_search_paths = sess.opts.addl_lib_search_paths.borrow();
for path in addl_lib_search_paths.get().iter() { for path in addl_lib_search_paths.get().iter() {
// FIXME (#9639): This needs to handle non-utf8 paths // FIXME (#9639): This needs to handle non-utf8 paths
@ -1281,7 +1281,7 @@ fn add_local_native_libraries(args: &mut Vec<~str> , sess: Session) {
// Rust crates are not considered at all when creating an rlib output. All // Rust crates are not considered at all when creating an rlib output. All
// dependencies will be linked when producing the final output (instead of // dependencies will be linked when producing the final output (instead of
// the intermediate rlib version) // the intermediate rlib version)
fn add_upstream_rust_crates(args: &mut Vec<~str> , sess: Session, fn add_upstream_rust_crates(args: &mut Vec<~str>, sess: &Session,
dylib: bool, tmpdir: &Path) { dylib: bool, tmpdir: &Path) {
// As a limitation of the current implementation, we require that everything // As a limitation of the current implementation, we require that everything
@ -1376,8 +1376,8 @@ fn add_upstream_rust_crates(args: &mut Vec<~str> , sess: Session,
} }
// Adds the static "rlib" versions of all crates to the command line. // Adds the static "rlib" versions of all crates to the command line.
fn add_static_crates(args: &mut Vec<~str> , sess: Session, tmpdir: &Path, fn add_static_crates(args: &mut Vec<~str>, sess: &Session, tmpdir: &Path,
crates: Vec<(ast::CrateNum, Path)> ) { crates: Vec<(ast::CrateNum, Path)>) {
for (cnum, cratepath) in crates.move_iter() { for (cnum, cratepath) in crates.move_iter() {
// When performing LTO on an executable output, all of the // When performing LTO on an executable output, all of the
// bytecode from the upstream libraries has already been // bytecode from the upstream libraries has already been
@ -1423,7 +1423,7 @@ fn add_upstream_rust_crates(args: &mut Vec<~str> , sess: Session,
} }
// Same thing as above, but for dynamic crates instead of static crates. // Same thing as above, but for dynamic crates instead of static crates.
fn add_dynamic_crates(args: &mut Vec<~str> , sess: Session, fn add_dynamic_crates(args: &mut Vec<~str>, sess: &Session,
crates: Vec<(ast::CrateNum, Path)> ) { crates: Vec<(ast::CrateNum, Path)> ) {
// If we're performing LTO, then it should have been previously required // If we're performing LTO, then it should have been previously required
// that all upstream rust dependencies were available in an rlib format. // that all upstream rust dependencies were available in an rlib format.
@ -1458,7 +1458,7 @@ fn add_upstream_rust_crates(args: &mut Vec<~str> , sess: Session,
// generic function calls a native function, then the generic function must // generic function calls a native function, then the generic function must
// be instantiated in the target crate, meaning that the native symbol must // be instantiated in the target crate, meaning that the native symbol must
// also be resolved in the target crate. // also be resolved in the target crate.
fn add_upstream_native_libraries(args: &mut Vec<~str> , sess: Session) { fn add_upstream_native_libraries(args: &mut Vec<~str>, sess: &Session) {
let cstore = sess.cstore; let cstore = sess.cstore;
cstore.iter_crate_data(|cnum, _| { cstore.iter_crate_data(|cnum, _| {
let libs = csearch::get_native_libraries(cstore, cnum); let libs = csearch::get_native_libraries(cstore, cnum);

View File

@ -18,7 +18,7 @@ use util::common::time;
use std::libc; use std::libc;
use flate; use flate;
pub fn run(sess: session::Session, llmod: ModuleRef, pub fn run(sess: &session::Session, llmod: ModuleRef,
tm: TargetMachineRef, reachable: &[~str]) { tm: TargetMachineRef, reachable: &[~str]) {
if sess.opts.cg.prefer_dynamic { if sess.opts.cg.prefer_dynamic {
sess.err("cannot prefer dynamic linking when performing LTO"); sess.err("cannot prefer dynamic linking when performing LTO");

View File

@ -9,7 +9,7 @@
// except according to those terms. // except according to those terms.
use driver::session; use driver::session::Session;
use metadata::cstore; use metadata::cstore;
use metadata::filesearch; use metadata::filesearch;
@ -22,7 +22,7 @@ fn not_win32(os: abi::Os) -> bool {
os != abi::OsWin32 os != abi::OsWin32
} }
pub fn get_rpath_flags(sess: session::Session, out_filename: &Path) -> Vec<~str> { pub fn get_rpath_flags(sess: &Session, out_filename: &Path) -> Vec<~str> {
let os = sess.targ_cfg.os; let os = sess.targ_cfg.os;
// No rpath on windows // No rpath on windows
@ -54,7 +54,7 @@ pub fn get_rpath_flags(sess: session::Session, out_filename: &Path) -> Vec<~str>
flags flags
} }
fn get_sysroot_absolute_rt_lib(sess: session::Session) -> Path { fn get_sysroot_absolute_rt_lib(sess: &Session) -> Path {
let r = filesearch::relative_target_lib_path(sess.opts.target_triple); let r = filesearch::relative_target_lib_path(sess.opts.target_triple);
let mut p = sess.filesearch.sysroot.join(&r); let mut p = sess.filesearch.sysroot.join(&r);
p.push(os::dll_filename("rustrt")); p.push(os::dll_filename("rustrt"));

View File

@ -13,7 +13,7 @@ use back::link;
use back::{arm, x86, x86_64, mips}; use back::{arm, x86, x86_64, mips};
use driver::session::{Aggressive, CrateTypeExecutable, CrateType, use driver::session::{Aggressive, CrateTypeExecutable, CrateType,
FullDebugInfo, LimitedDebugInfo, NoDebugInfo}; FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
use driver::session::{Session, Session_, No, Less, Default}; use driver::session::{Session, No, Less, Default};
use driver::session; use driver::session;
use front; use front;
use lib::llvm::llvm; use lib::llvm::llvm;
@ -80,7 +80,7 @@ pub fn source_name(input: &Input) -> ~str {
} }
} }
pub fn default_configuration(sess: Session) -> pub fn default_configuration(sess: &Session) ->
ast::CrateConfig { ast::CrateConfig {
let tos = match sess.targ_cfg.os { let tos = match sess.targ_cfg.os {
abi::OsWin32 => InternedString::new("win32"), abi::OsWin32 => InternedString::new("win32"),
@ -123,7 +123,7 @@ pub fn append_configuration(cfg: &mut ast::CrateConfig,
} }
} }
pub fn build_configuration(sess: Session) -> ast::CrateConfig { pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
// Combine the configuration requested by the session (command line) with // Combine the configuration requested by the session (command line) with
// some default and generated configuration items // some default and generated configuration items
let default_cfg = default_configuration(sess); let default_cfg = default_configuration(sess);
@ -170,7 +170,7 @@ impl Input {
} }
} }
pub fn phase_1_parse_input(sess: Session, cfg: ast::CrateConfig, input: &Input) pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
-> ast::Crate { -> ast::Crate {
let krate = time(sess.time_passes(), "parsing", (), |_| { let krate = time(sess.time_passes(), "parsing", (), |_| {
match *input { match *input {
@ -206,7 +206,7 @@ pub fn phase_1_parse_input(sess: Session, cfg: ast::CrateConfig, input: &Input)
/// syntax expansion, secondary `cfg` expansion, synthesis of a test /// syntax expansion, secondary `cfg` expansion, synthesis of a test
/// harness if one is to be provided and injection of a dependency on the /// harness if one is to be provided and injection of a dependency on the
/// standard library and prelude. /// standard library and prelude.
pub fn phase_2_configure_and_expand(sess: Session, pub fn phase_2_configure_and_expand(sess: &Session,
loader: &mut CrateLoader, loader: &mut CrateLoader,
mut krate: ast::Crate, mut krate: ast::Crate,
crate_id: &CrateId) crate_id: &CrateId)
@ -214,7 +214,7 @@ pub fn phase_2_configure_and_expand(sess: Session,
let time_passes = sess.time_passes(); let time_passes = sess.time_passes();
sess.building_library.set(session::building_library(sess.opts, &krate)); sess.building_library.set(session::building_library(sess.opts, &krate));
sess.crate_types.set(session::collect_crate_types(&sess, sess.crate_types.set(session::collect_crate_types(sess,
krate.attrs krate.attrs
.as_slice())); .as_slice()));
@ -289,12 +289,12 @@ pub fn phase_3_run_analysis_passes(sess: Session,
let time_passes = sess.time_passes(); let time_passes = sess.time_passes();
time(time_passes, "external crate/lib resolution", (), |_| time(time_passes, "external crate/lib resolution", (), |_|
creader::read_crates(sess, krate, creader::read_crates(&sess, krate,
session::sess_os_to_meta_os(sess.targ_cfg.os), session::sess_os_to_meta_os(sess.targ_cfg.os),
token::get_ident_interner())); token::get_ident_interner()));
let lang_items = time(time_passes, "language item collection", (), |_| let lang_items = time(time_passes, "language item collection", (), |_|
middle::lang_items::collect_language_items(krate, sess)); middle::lang_items::collect_language_items(krate, &sess));
let middle::resolve::CrateMap { let middle::resolve::CrateMap {
def_map: def_map, def_map: def_map,
@ -304,13 +304,13 @@ pub fn phase_3_run_analysis_passes(sess: Session,
last_private_map: last_private_map last_private_map: last_private_map
} = } =
time(time_passes, "resolution", (), |_| time(time_passes, "resolution", (), |_|
middle::resolve::resolve_crate(sess, lang_items, krate)); middle::resolve::resolve_crate(&sess, lang_items, krate));
let named_region_map = time(time_passes, "lifetime resolution", (), let named_region_map = time(time_passes, "lifetime resolution", (),
|_| middle::resolve_lifetime::krate(sess, krate)); |_| middle::resolve_lifetime::krate(&sess, krate));
time(time_passes, "looking for entry point", (), time(time_passes, "looking for entry point", (),
|_| middle::entry::find_entry_point(sess, krate, &ast_map)); |_| middle::entry::find_entry_point(&sess, krate, &ast_map));
sess.macro_registrar_fn.with_mut(|r| *r = sess.macro_registrar_fn.with_mut(|r| *r =
time(time_passes, "looking for macro registrar", (), |_| time(time_passes, "looking for macro registrar", (), |_|
@ -321,7 +321,7 @@ pub fn phase_3_run_analysis_passes(sess: Session,
freevars::annotate_freevars(def_map, krate)); freevars::annotate_freevars(def_map, krate));
let region_map = time(time_passes, "region resolution", (), |_| let region_map = time(time_passes, "region resolution", (), |_|
middle::region::resolve_crate(sess, krate)); middle::region::resolve_crate(&sess, krate));
let ty_cx = ty::mk_ctxt(sess, def_map, named_region_map, ast_map, let ty_cx = ty::mk_ctxt(sess, def_map, named_region_map, ast_map,
freevars, region_map, lang_items); freevars, region_map, lang_items);
@ -337,8 +337,7 @@ pub fn phase_3_run_analysis_passes(sess: Session,
middle::const_eval::process_crate(krate, ty_cx)); middle::const_eval::process_crate(krate, ty_cx));
time(time_passes, "const checking", (), |_| time(time_passes, "const checking", (), |_|
middle::check_const::check_crate(sess, krate, def_map, middle::check_const::check_crate(krate, def_map, method_map, ty_cx));
method_map, ty_cx));
let maps = (external_exports, last_private_map); let maps = (external_exports, last_private_map);
let (exported_items, public_items) = let (exported_items, public_items) =
@ -418,17 +417,16 @@ pub struct CrateTranslation {
/// Run the translation phase to LLVM, after which the AST and analysis can /// Run the translation phase to LLVM, after which the AST and analysis can
/// be discarded. /// be discarded.
pub fn phase_4_translate_to_llvm(sess: Session, pub fn phase_4_translate_to_llvm(krate: ast::Crate,
krate: ast::Crate,
analysis: &CrateAnalysis, analysis: &CrateAnalysis,
outputs: &OutputFilenames) -> CrateTranslation { outputs: &OutputFilenames) -> CrateTranslation {
time(sess.time_passes(), "translation", krate, |krate| time(analysis.ty_cx.sess.time_passes(), "translation", krate, |krate|
trans::base::trans_crate(sess, krate, analysis, outputs)) trans::base::trans_crate(krate, analysis, outputs))
} }
/// Run LLVM itself, producing a bitcode file, assembly file or object file /// Run LLVM itself, producing a bitcode file, assembly file or object file
/// as a side effect. /// as a side effect.
pub fn phase_5_run_llvm_passes(sess: Session, pub fn phase_5_run_llvm_passes(sess: &Session,
trans: &CrateTranslation, trans: &CrateTranslation,
outputs: &OutputFilenames) { outputs: &OutputFilenames) {
if sess.opts.cg.no_integrated_as { if sess.opts.cg.no_integrated_as {
@ -454,7 +452,7 @@ pub fn phase_5_run_llvm_passes(sess: Session,
/// Run the linker on any artifacts that resulted from the LLVM run. /// Run the linker on any artifacts that resulted from the LLVM run.
/// This should produce either a finished executable or library. /// This should produce either a finished executable or library.
pub fn phase_6_link_output(sess: Session, pub fn phase_6_link_output(sess: &Session,
trans: &CrateTranslation, trans: &CrateTranslation,
outputs: &OutputFilenames) { outputs: &OutputFilenames) {
time(sess.time_passes(), "linking", (), |_| time(sess.time_passes(), "linking", (), |_|
@ -464,7 +462,7 @@ pub fn phase_6_link_output(sess: Session,
&trans.link.crateid)); &trans.link.crateid));
} }
pub fn stop_after_phase_3(sess: Session) -> bool { pub fn stop_after_phase_3(sess: &Session) -> bool {
if sess.opts.no_trans { if sess.opts.no_trans {
debug!("invoked with --no-trans, returning early from compile_input"); debug!("invoked with --no-trans, returning early from compile_input");
return true; return true;
@ -472,7 +470,7 @@ pub fn stop_after_phase_3(sess: Session) -> bool {
return false; return false;
} }
pub fn stop_after_phase_1(sess: Session) -> bool { pub fn stop_after_phase_1(sess: &Session) -> bool {
if sess.opts.parse_only { if sess.opts.parse_only {
debug!("invoked with --parse-only, returning early from compile_input"); debug!("invoked with --parse-only, returning early from compile_input");
return true; return true;
@ -483,7 +481,7 @@ pub fn stop_after_phase_1(sess: Session) -> bool {
return sess.opts.debugging_opts & session::AST_JSON_NOEXPAND != 0; return sess.opts.debugging_opts & session::AST_JSON_NOEXPAND != 0;
} }
pub fn stop_after_phase_2(sess: Session) -> bool { pub fn stop_after_phase_2(sess: &Session) -> bool {
if sess.opts.no_analysis { if sess.opts.no_analysis {
debug!("invoked with --no-analysis, returning early from compile_input"); debug!("invoked with --no-analysis, returning early from compile_input");
return true; return true;
@ -491,7 +489,7 @@ pub fn stop_after_phase_2(sess: Session) -> bool {
return sess.opts.debugging_opts & session::AST_JSON != 0; return sess.opts.debugging_opts & session::AST_JSON != 0;
} }
pub fn stop_after_phase_5(sess: Session) -> bool { pub fn stop_after_phase_5(sess: &Session) -> bool {
if !sess.opts.output_types.iter().any(|&i| i == link::OutputTypeExe) { if !sess.opts.output_types.iter().any(|&i| i == link::OutputTypeExe) {
debug!("not building executable, returning early from compile_input"); debug!("not building executable, returning early from compile_input");
return true; return true;
@ -499,7 +497,7 @@ pub fn stop_after_phase_5(sess: Session) -> bool {
return false; return false;
} }
fn write_out_deps(sess: Session, fn write_out_deps(sess: &Session,
input: &Input, input: &Input,
outputs: &OutputFilenames, outputs: &OutputFilenames,
krate: &ast::Crate) -> io::IoResult<()> { krate: &ast::Crate) -> io::IoResult<()> {
@ -512,7 +510,7 @@ fn write_out_deps(sess: Session,
link::OutputTypeExe => { link::OutputTypeExe => {
let crate_types = sess.crate_types.borrow(); let crate_types = sess.crate_types.borrow();
for output in crate_types.get().iter() { for output in crate_types.get().iter() {
let p = link::filename_for_input(&sess, *output, &id, &file); let p = link::filename_for_input(sess, *output, &id, &file);
out_filenames.push(p); out_filenames.push(p);
} }
} }
@ -566,33 +564,35 @@ pub fn compile_input(sess: Session, cfg: ast::CrateConfig, input: &Input,
// We need nested scopes here, because the intermediate results can keep // We need nested scopes here, because the intermediate results can keep
// large chunks of memory alive and we want to free them as soon as // large chunks of memory alive and we want to free them as soon as
// possible to keep the peak memory usage low // possible to keep the peak memory usage low
let outputs; let (outputs, trans, sess) = {
let trans = { let (outputs, expanded_crate, ast_map) = {
let (expanded_crate, ast_map) = { let krate = phase_1_parse_input(&sess, cfg, input);
let krate = phase_1_parse_input(sess, cfg, input); if stop_after_phase_1(&sess) { return; }
if stop_after_phase_1(sess) { return; } let outputs = build_output_filenames(input,
outputs = build_output_filenames(input, outdir,
outdir, output,
output, krate.attrs.as_slice(),
krate.attrs.as_slice(), &sess);
sess); let loader = &mut Loader::new(&sess);
let loader = &mut Loader::new(sess);
let id = link::find_crate_id(krate.attrs.as_slice(), let id = link::find_crate_id(krate.attrs.as_slice(),
outputs.out_filestem); outputs.out_filestem);
phase_2_configure_and_expand(sess, loader, krate, &id) let (expanded_crate, ast_map) = phase_2_configure_and_expand(&sess, loader,
krate, &id);
(outputs, expanded_crate, ast_map)
}; };
write_out_deps(&sess, input, &outputs, &expanded_crate).unwrap();
write_out_deps(sess, input, &outputs, &expanded_crate).unwrap(); if stop_after_phase_2(&sess) { return; }
if stop_after_phase_2(sess) { return; }
let analysis = phase_3_run_analysis_passes(sess, &expanded_crate, ast_map); let analysis = phase_3_run_analysis_passes(sess, &expanded_crate, ast_map);
if stop_after_phase_3(sess) { return; } if stop_after_phase_3(&analysis.ty_cx.sess) { return; }
phase_4_translate_to_llvm(sess, expanded_crate, &analysis, &outputs) let trans = phase_4_translate_to_llvm(expanded_crate,
&analysis, &outputs);
(outputs, trans, analysis.ty_cx.sess)
}; };
phase_5_run_llvm_passes(sess, &trans, &outputs); phase_5_run_llvm_passes(&sess, &trans, &outputs);
if stop_after_phase_5(sess) { return; } if stop_after_phase_5(&sess) { return; }
phase_6_link_output(sess, &trans, &outputs); phase_6_link_output(&sess, &trans, &outputs);
} }
struct IdentifiedAnnotation; struct IdentifiedAnnotation;
@ -660,19 +660,22 @@ pub fn pretty_print_input(sess: Session,
cfg: ast::CrateConfig, cfg: ast::CrateConfig,
input: &Input, input: &Input,
ppm: PpMode) { ppm: PpMode) {
let krate = phase_1_parse_input(sess, cfg, input); let krate = phase_1_parse_input(&sess, cfg, input);
let id = link::find_crate_id(krate.attrs.as_slice(), input.filestem()); let id = link::find_crate_id(krate.attrs.as_slice(), input.filestem());
let (krate, ast_map, is_expanded) = match ppm { let (krate, ast_map, is_expanded) = match ppm {
PpmExpanded | PpmExpandedIdentified | PpmTyped => { PpmExpanded | PpmExpandedIdentified | PpmTyped => {
let loader = &mut Loader::new(sess); let loader = &mut Loader::new(&sess);
let (krate, ast_map) = phase_2_configure_and_expand(sess, loader, let (krate, ast_map) = phase_2_configure_and_expand(&sess, loader,
krate, &id); krate, &id);
(krate, Some(ast_map), true) (krate, Some(ast_map), true)
} }
_ => (krate, None, false) _ => (krate, None, false)
}; };
let codemap = sess.codemap;
let span_diagnostic = sess.span_diagnostic;
let annotation = match ppm { let annotation = match ppm {
PpmIdentified | PpmExpandedIdentified => { PpmIdentified | PpmExpandedIdentified => {
~IdentifiedAnnotation as ~pprust::PpAnn ~IdentifiedAnnotation as ~pprust::PpAnn
@ -687,11 +690,11 @@ pub fn pretty_print_input(sess: Session,
_ => ~pprust::NoAnn as ~pprust::PpAnn:, _ => ~pprust::NoAnn as ~pprust::PpAnn:,
}; };
let src = &sess.codemap.get_filemap(source_name(input)).src; let src = &codemap.get_filemap(source_name(input)).src;
let mut rdr = MemReader::new(src.as_bytes().to_owned()); let mut rdr = MemReader::new(src.as_bytes().to_owned());
let stdout = io::stdout(); let stdout = io::stdout();
pprust::print_crate(sess.codemap, pprust::print_crate(codemap,
sess.span_diagnostic, span_diagnostic,
&krate, &krate,
source_name(input), source_name(input),
&mut rdr, &mut rdr,
@ -1020,7 +1023,7 @@ pub fn build_session_(sopts: @session::Options,
} }
); );
@Session_ { Session {
targ_cfg: target_cfg, targ_cfg: target_cfg,
opts: sopts, opts: sopts,
cstore: cstore, cstore: cstore,
@ -1043,7 +1046,7 @@ pub fn build_session_(sopts: @session::Options,
} }
} }
pub fn parse_pretty(sess: Session, name: &str) -> PpMode { pub fn parse_pretty(sess: &Session, name: &str) -> PpMode {
match name { match name {
&"normal" => PpmNormal, &"normal" => PpmNormal,
&"expanded" => PpmExpanded, &"expanded" => PpmExpanded,
@ -1143,7 +1146,7 @@ pub fn build_output_filenames(input: &Input,
odir: &Option<Path>, odir: &Option<Path>,
ofile: &Option<Path>, ofile: &Option<Path>,
attrs: &[ast::Attribute], attrs: &[ast::Attribute],
sess: Session) sess: &Session)
-> OutputFilenames { -> OutputFilenames {
match *ofile { match *ofile {
None => { None => {
@ -1196,7 +1199,7 @@ pub fn early_error(msg: &str) -> ! {
fail!(diagnostic::FatalError); fail!(diagnostic::FatalError);
} }
pub fn list_metadata(sess: Session, path: &Path, pub fn list_metadata(sess: &Session, path: &Path,
out: &mut io::Writer) -> io::IoResult<()> { out: &mut io::Writer) -> io::IoResult<()> {
metadata::loader::list_file_metadata( metadata::loader::list_file_metadata(
session::sess_os_to_meta_os(sess.targ_cfg.os), path, out) session::sess_os_to_meta_os(sess.targ_cfg.os), path, out)

View File

@ -173,7 +173,7 @@ pub enum CrateType {
CrateTypeStaticlib, CrateTypeStaticlib,
} }
pub struct Session_ { pub struct Session {
targ_cfg: @Config, targ_cfg: @Config,
opts: @Options, opts: @Options,
cstore: @metadata::cstore::CStore, cstore: @metadata::cstore::CStore,
@ -201,9 +201,7 @@ pub struct Session_ {
recursion_limit: Cell<uint>, recursion_limit: Cell<uint>,
} }
pub type Session = @Session_; impl Session {
impl Session_ {
pub fn span_fatal(&self, sp: Span, msg: &str) -> ! { pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
self.span_diagnostic.span_fatal(sp, msg) self.span_diagnostic.span_fatal(sp, msg)
} }
@ -451,7 +449,7 @@ cgoptions!(
) )
// Seems out of place, but it uses session, so I'm putting it here // Seems out of place, but it uses session, so I'm putting it here
pub fn expect<T:Clone>(sess: Session, opt: Option<T>, msg: || -> ~str) -> T { pub fn expect<T:Clone>(sess: &Session, opt: Option<T>, msg: || -> ~str) -> T {
diagnostic::expect(sess.diagnostic(), opt, msg) diagnostic::expect(sess.diagnostic(), opt, msg)
} }

View File

@ -13,17 +13,17 @@ use driver::session::Session;
use syntax::ast; use syntax::ast;
use syntax::ast_map; use syntax::ast_map;
struct NodeIdAssigner { struct NodeIdAssigner<'a> {
sess: Session sess: &'a Session
} }
impl ast_map::FoldOps for NodeIdAssigner { impl<'a> ast_map::FoldOps for NodeIdAssigner<'a> {
fn new_id(&self, old_id: ast::NodeId) -> ast::NodeId { fn new_id(&self, old_id: ast::NodeId) -> ast::NodeId {
assert_eq!(old_id, ast::DUMMY_NODE_ID); assert_eq!(old_id, ast::DUMMY_NODE_ID);
self.sess.next_node_id() self.sess.next_node_id()
} }
} }
pub fn assign_node_ids_and_map(sess: Session, krate: ast::Crate) -> (ast::Crate, ast_map::Map) { pub fn assign_node_ids_and_map(sess: &Session, krate: ast::Crate) -> (ast::Crate, ast_map::Map) {
ast_map::map_crate(krate, NodeIdAssigner { sess: sess }) ast_map::map_crate(krate, NodeIdAssigner { sess: sess })
} }

View File

@ -86,12 +86,12 @@ impl Features {
} }
} }
struct Context { struct Context<'a> {
features: Vec<&'static str> , features: Vec<&'static str>,
sess: Session, sess: &'a Session,
} }
impl Context { impl<'a> Context<'a> {
fn gate_feature(&self, feature: &str, span: Span, explain: &str) { fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
if !self.has_feature(feature) { if !self.has_feature(feature) {
self.sess.span_err(span, explain); self.sess.span_err(span, explain);
@ -114,7 +114,7 @@ impl Context {
} }
} }
impl Visitor<()> for Context { impl<'a> Visitor<()> for Context<'a> {
fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) { fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) {
if !token::get_ident(id).get().is_ascii() { if !token::get_ident(id).get().is_ascii() {
self.gate_feature("non_ascii_idents", sp, self.gate_feature("non_ascii_idents", sp,
@ -293,7 +293,7 @@ impl Visitor<()> for Context {
} }
} }
pub fn check_crate(sess: Session, krate: &ast::Crate) { pub fn check_crate(sess: &Session, krate: &ast::Crate) {
let mut cx = Context { let mut cx = Context {
features: Vec::new(), features: Vec::new(),
sess: sess, sess: sess,

View File

@ -19,18 +19,18 @@ use syntax::visit::Visitor;
use driver::session::Session; use driver::session::Session;
struct ShowSpanVisitor { struct ShowSpanVisitor<'a> {
sess: Session sess: &'a Session
} }
impl Visitor<()> for ShowSpanVisitor { impl<'a> Visitor<()> for ShowSpanVisitor<'a> {
fn visit_expr(&mut self, e: &ast::Expr, _: ()) { fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
self.sess.span_note(e.span, "expression"); self.sess.span_note(e.span, "expression");
visit::walk_expr(self, e, ()); visit::walk_expr(self, e, ());
} }
} }
pub fn run(sess: Session, krate: &ast::Crate) { pub fn run(sess: &Session, krate: &ast::Crate) {
let mut v = ShowSpanVisitor { sess: sess }; let mut v = ShowSpanVisitor { sess: sess };
visit::walk_crate(&mut v, krate, ()); visit::walk_crate(&mut v, krate, ());
} }

View File

@ -26,7 +26,7 @@ use syntax::util::small_vector::SmallVector;
pub static VERSION: &'static str = "0.10-pre"; pub static VERSION: &'static str = "0.10-pre";
pub fn maybe_inject_crates_ref(sess: Session, krate: ast::Crate) pub fn maybe_inject_crates_ref(sess: &Session, krate: ast::Crate)
-> ast::Crate { -> ast::Crate {
if use_std(&krate) { if use_std(&krate) {
inject_crates_ref(sess, krate) inject_crates_ref(sess, krate)
@ -35,7 +35,7 @@ pub fn maybe_inject_crates_ref(sess: Session, krate: ast::Crate)
} }
} }
pub fn maybe_inject_prelude(sess: Session, krate: ast::Crate) -> ast::Crate { pub fn maybe_inject_prelude(sess: &Session, krate: ast::Crate) -> ast::Crate {
if use_std(&krate) { if use_std(&krate) {
inject_prelude(sess, krate) inject_prelude(sess, krate)
} else { } else {
@ -55,8 +55,8 @@ fn no_prelude(attrs: &[ast::Attribute]) -> bool {
attr::contains_name(attrs, "no_implicit_prelude") attr::contains_name(attrs, "no_implicit_prelude")
} }
struct StandardLibraryInjector { struct StandardLibraryInjector<'a> {
sess: Session, sess: &'a Session,
} }
pub fn with_version(krate: &str) -> Option<(InternedString, ast::StrStyle)> { pub fn with_version(krate: &str) -> Option<(InternedString, ast::StrStyle)> {
@ -71,7 +71,7 @@ pub fn with_version(krate: &str) -> Option<(InternedString, ast::StrStyle)> {
} }
} }
impl fold::Folder for StandardLibraryInjector { impl<'a> fold::Folder for StandardLibraryInjector<'a> {
fn fold_crate(&mut self, krate: ast::Crate) -> ast::Crate { fn fold_crate(&mut self, krate: ast::Crate) -> ast::Crate {
let mut vis = vec!(ast::ViewItem { let mut vis = vec!(ast::ViewItem {
node: ast::ViewItemExternCrate(token::str_to_ident("std"), node: ast::ViewItemExternCrate(token::str_to_ident("std"),
@ -120,19 +120,19 @@ impl fold::Folder for StandardLibraryInjector {
} }
} }
fn inject_crates_ref(sess: Session, krate: ast::Crate) -> ast::Crate { fn inject_crates_ref(sess: &Session, krate: ast::Crate) -> ast::Crate {
let mut fold = StandardLibraryInjector { let mut fold = StandardLibraryInjector {
sess: sess, sess: sess,
}; };
fold.fold_crate(krate) fold.fold_crate(krate)
} }
struct PreludeInjector { struct PreludeInjector<'a> {
sess: Session, sess: &'a Session,
} }
impl fold::Folder for PreludeInjector { impl<'a> fold::Folder for PreludeInjector<'a> {
fn fold_crate(&mut self, krate: ast::Crate) -> ast::Crate { fn fold_crate(&mut self, krate: ast::Crate) -> ast::Crate {
if !no_prelude(krate.attrs.as_slice()) { if !no_prelude(krate.attrs.as_slice()) {
// only add `use std::prelude::*;` if there wasn't a // only add `use std::prelude::*;` if there wasn't a
@ -193,7 +193,7 @@ impl fold::Folder for PreludeInjector {
} }
} }
fn inject_prelude(sess: Session, krate: ast::Crate) -> ast::Crate { fn inject_prelude(sess: &Session, krate: ast::Crate) -> ast::Crate {
let mut fold = PreludeInjector { let mut fold = PreludeInjector {
sess: sess, sess: sess,
}; };

View File

@ -13,7 +13,7 @@
#[allow(dead_code)]; #[allow(dead_code)];
#[allow(unused_imports)]; #[allow(unused_imports)];
use driver::session; use driver::session::Session;
use front::config; use front::config;
use front::std_inject::with_version; use front::std_inject::with_version;
use metadata::creader::Loader; use metadata::creader::Loader;
@ -47,8 +47,8 @@ struct Test {
} }
struct TestCtxt<'a> { struct TestCtxt<'a> {
sess: session::Session, sess: &'a Session,
path: RefCell<Vec<ast::Ident> >, path: RefCell<Vec<ast::Ident>>,
ext_cx: ExtCtxt<'a>, ext_cx: ExtCtxt<'a>,
testfns: RefCell<Vec<Test> >, testfns: RefCell<Vec<Test> >,
is_test_crate: bool, is_test_crate: bool,
@ -57,7 +57,7 @@ struct TestCtxt<'a> {
// Traverse the crate, collecting all the test functions, eliding any // Traverse the crate, collecting all the test functions, eliding any
// existing main functions, and synthesizing a main test harness // existing main functions, and synthesizing a main test harness
pub fn modify_for_testing(sess: session::Session, pub fn modify_for_testing(sess: &Session,
krate: ast::Crate) -> ast::Crate { krate: ast::Crate) -> ast::Crate {
// We generate the test harness when building in the 'test' // We generate the test harness when building in the 'test'
// configuration, either with the '--test' or '--cfg test' // configuration, either with the '--test' or '--cfg test'
@ -161,7 +161,7 @@ impl<'a> fold::Folder for TestHarnessGenerator<'a> {
} }
} }
fn generate_test_harness(sess: session::Session, krate: ast::Crate) fn generate_test_harness(sess: &Session, krate: ast::Crate)
-> ast::Crate { -> ast::Crate {
let loader = &mut Loader::new(sess); let loader = &mut Loader::new(sess);
let mut cx: TestCtxt = TestCtxt { let mut cx: TestCtxt = TestCtxt {

View File

@ -290,9 +290,9 @@ pub fn run_compiler(args: &[~str]) {
let sess = d::build_session(sopts, input_file_path); let sess = d::build_session(sopts, input_file_path);
let odir = matches.opt_str("out-dir").map(|o| Path::new(o)); let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
let ofile = matches.opt_str("o").map(|o| Path::new(o)); let ofile = matches.opt_str("o").map(|o| Path::new(o));
let cfg = d::build_configuration(sess); let cfg = d::build_configuration(&sess);
let pretty = matches.opt_default("pretty", "normal").map(|a| { let pretty = matches.opt_default("pretty", "normal").map(|a| {
d::parse_pretty(sess, a) d::parse_pretty(&sess, a)
}); });
match pretty { match pretty {
Some::<d::PpMode>(ppm) => { Some::<d::PpMode>(ppm) => {
@ -306,7 +306,7 @@ pub fn run_compiler(args: &[~str]) {
match input { match input {
d::FileInput(ref ifile) => { d::FileInput(ref ifile) => {
let mut stdout = io::stdout(); let mut stdout = io::stdout();
d::list_metadata(sess, &(*ifile), &mut stdout).unwrap(); d::list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
} }
d::StrInput(_) => { d::StrInput(_) => {
d::early_error("can not list metadata for stdin"); d::early_error("can not list metadata for stdin");
@ -317,9 +317,9 @@ pub fn run_compiler(args: &[~str]) {
let (crate_id, crate_name, crate_file_name) = sopts.print_metas; let (crate_id, crate_name, crate_file_name) = sopts.print_metas;
// these nasty nested conditions are to avoid doing extra work // these nasty nested conditions are to avoid doing extra work
if crate_id || crate_name || crate_file_name { if crate_id || crate_name || crate_file_name {
let attrs = parse_crate_attrs(sess, &input); let attrs = parse_crate_attrs(&sess, &input);
let t_outputs = d::build_output_filenames(&input, &odir, &ofile, let t_outputs = d::build_output_filenames(&input, &odir, &ofile,
attrs.as_slice(), sess); attrs.as_slice(), &sess);
let id = link::find_crate_id(attrs.as_slice(), t_outputs.out_filestem); let id = link::find_crate_id(attrs.as_slice(), t_outputs.out_filestem);
if crate_id { if crate_id {
@ -344,7 +344,7 @@ pub fn run_compiler(args: &[~str]) {
d::compile_input(sess, cfg, &input, &odir, &ofile); d::compile_input(sess, cfg, &input, &odir, &ofile);
} }
fn parse_crate_attrs(sess: session::Session, input: &d::Input) -> fn parse_crate_attrs(sess: &session::Session, input: &d::Input) ->
Vec<ast::Attribute> { Vec<ast::Attribute> {
let result = match *input { let result = match *input {
d::FileInput(ref ifile) => { d::FileInput(ref ifile) => {

View File

@ -39,7 +39,7 @@ use syntax::visit;
// Traverses an AST, reading all the information about use'd crates and extern // Traverses an AST, reading all the information about use'd crates and extern
// libraries necessary for later resolving, typechecking, linking, etc. // libraries necessary for later resolving, typechecking, linking, etc.
pub fn read_crates(sess: Session, pub fn read_crates(sess: &Session,
krate: &ast::Crate, krate: &ast::Crate,
os: loader::Os, os: loader::Os,
intr: @IdentInterner) { intr: @IdentInterner) {
@ -51,12 +51,7 @@ pub fn read_crates(sess: Session,
intr: intr intr: intr
}; };
visit_crate(&e, krate); visit_crate(&e, krate);
{ visit::walk_crate(&mut e, krate, ());
let mut v = ReadCrateVisitor {
e: &mut e
};
visit::walk_crate(&mut v, krate, ());
}
let crate_cache = e.crate_cache.borrow(); let crate_cache = e.crate_cache.borrow();
dump_crates(crate_cache.get().as_slice()); dump_crates(crate_cache.get().as_slice());
warn_if_multiple_versions(&mut e, warn_if_multiple_versions(&mut e,
@ -64,17 +59,13 @@ pub fn read_crates(sess: Session,
crate_cache.get().as_slice()); crate_cache.get().as_slice());
} }
struct ReadCrateVisitor<'a> { impl<'a> visit::Visitor<()> for Env<'a> {
e: &'a mut Env,
}
impl<'a> visit::Visitor<()> for ReadCrateVisitor<'a> {
fn visit_view_item(&mut self, a: &ast::ViewItem, _: ()) { fn visit_view_item(&mut self, a: &ast::ViewItem, _: ()) {
visit_view_item(self.e, a); visit_view_item(self, a);
visit::walk_view_item(self, a, ()); visit::walk_view_item(self, a, ());
} }
fn visit_item(&mut self, a: &ast::Item, _: ()) { fn visit_item(&mut self, a: &ast::Item, _: ()) {
visit_item(self.e, a); visit_item(self, a);
visit::walk_item(self, a, ()); visit::walk_item(self, a, ());
} }
} }
@ -120,8 +111,8 @@ fn warn_if_multiple_versions(e: &mut Env,
} }
} }
struct Env { struct Env<'a> {
sess: Session, sess: &'a Session,
os: loader::Os, os: loader::Os,
crate_cache: @RefCell<Vec<cache_entry>>, crate_cache: @RefCell<Vec<cache_entry>>,
next_crate_num: ast::CrateNum, next_crate_num: ast::CrateNum,
@ -391,12 +382,12 @@ fn resolve_crate_deps(e: &mut Env,
return @RefCell::new(cnum_map); return @RefCell::new(cnum_map);
} }
pub struct Loader { pub struct Loader<'a> {
priv env: Env, priv env: Env<'a>,
} }
impl Loader { impl<'a> Loader<'a> {
pub fn new(sess: Session) -> Loader { pub fn new(sess: &'a Session) -> Loader<'a> {
let os = driver::get_os(driver::host_triple()).unwrap(); let os = driver::get_os(driver::host_triple()).unwrap();
let os = session::sess_os_to_meta_os(os); let os = session::sess_os_to_meta_os(os);
Loader { Loader {
@ -411,7 +402,7 @@ impl Loader {
} }
} }
impl CrateLoader for Loader { impl<'a> CrateLoader for Loader<'a> {
fn load_crate(&mut self, krate: &ast::ViewItem) -> MacroCrate { fn load_crate(&mut self, krate: &ast::ViewItem) -> MacroCrate {
let info = extract_crate_info(&self.env, krate).unwrap(); let info = extract_crate_info(&self.env, krate).unwrap();
let cnum = resolve_crate(&mut self.env, None, info.ident, let cnum = resolve_crate(&mut self.env, None, info.ident,

View File

@ -46,7 +46,7 @@ pub enum Os {
} }
pub struct Context<'a> { pub struct Context<'a> {
sess: Session, sess: &'a Session,
span: Span, span: Span,
ident: &'a str, ident: &'a str,
crate_id: &'a CrateId, crate_id: &'a CrateId,

View File

@ -137,7 +137,7 @@ pub fn decode_inlined_item(cdata: @cstore::crate_metadata,
}); });
let mut ast_dsr = reader::Decoder(ast_doc); let mut ast_dsr = reader::Decoder(ast_doc);
let from_id_range = Decodable::decode(&mut ast_dsr); let from_id_range = Decodable::decode(&mut ast_dsr);
let to_id_range = reserve_id_range(dcx.tcx.sess, from_id_range); let to_id_range = reserve_id_range(&dcx.tcx.sess, from_id_range);
let xcx = @ExtendedDecodeContext { let xcx = @ExtendedDecodeContext {
dcx: dcx, dcx: dcx,
from_id_range: from_id_range, from_id_range: from_id_range,
@ -154,7 +154,7 @@ pub fn decode_inlined_item(cdata: @cstore::crate_metadata,
debug!("< Decoded inlined fn: {}::{}", debug!("< Decoded inlined fn: {}::{}",
path_as_str.unwrap(), path_as_str.unwrap(),
token::get_ident(ident)); token::get_ident(ident));
region::resolve_inlined_item(tcx.sess, &tcx.region_maps, &ii); region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, &ii);
decode_side_tables(xcx, ast_doc); decode_side_tables(xcx, ast_doc);
match ii { match ii {
ast::IIItem(i) => { ast::IIItem(i) => {
@ -178,7 +178,7 @@ pub fn decode_exported_macro(par_doc: ebml::Doc) -> @ast::Item {
// ______________________________________________________________________ // ______________________________________________________________________
// Enumerating the IDs which appear in an AST // Enumerating the IDs which appear in an AST
fn reserve_id_range(sess: Session, fn reserve_id_range(sess: &Session,
from_id_range: ast_util::IdRange) -> ast_util::IdRange { from_id_range: ast_util::IdRange) -> ast_util::IdRange {
// Handle the case of an empty range: // Handle the case of an empty range:
if from_id_range.empty() { return from_id_range; } if from_id_range.empty() { return from_id_range; }

View File

@ -22,7 +22,6 @@ use syntax::visit::Visitor;
use syntax::visit; use syntax::visit;
pub struct CheckCrateVisitor { pub struct CheckCrateVisitor {
sess: Session,
def_map: resolve::DefMap, def_map: resolve::DefMap,
method_map: typeck::MethodMap, method_map: typeck::MethodMap,
tcx: ty::ctxt, tcx: ty::ctxt,
@ -30,41 +29,34 @@ pub struct CheckCrateVisitor {
impl Visitor<bool> for CheckCrateVisitor { impl Visitor<bool> for CheckCrateVisitor {
fn visit_item(&mut self, i: &Item, env: bool) { fn visit_item(&mut self, i: &Item, env: bool) {
check_item(self, self.sess, self.def_map, i, env); check_item(self, i, env);
} }
fn visit_pat(&mut self, p: &Pat, env: bool) { fn visit_pat(&mut self, p: &Pat, env: bool) {
check_pat(self, p, env); check_pat(self, p, env);
} }
fn visit_expr(&mut self, ex: &Expr, env: bool) { fn visit_expr(&mut self, ex: &Expr, env: bool) {
check_expr(self, self.sess, self.def_map, self.method_map, check_expr(self, ex, env);
self.tcx, ex, env);
} }
} }
pub fn check_crate(sess: Session, pub fn check_crate(krate: &Crate,
krate: &Crate,
def_map: resolve::DefMap, def_map: resolve::DefMap,
method_map: typeck::MethodMap, method_map: typeck::MethodMap,
tcx: ty::ctxt) { tcx: ty::ctxt) {
let mut v = CheckCrateVisitor { let mut v = CheckCrateVisitor {
sess: sess,
def_map: def_map, def_map: def_map,
method_map: method_map, method_map: method_map,
tcx: tcx, tcx: tcx,
}; };
visit::walk_crate(&mut v, krate, false); visit::walk_crate(&mut v, krate, false);
sess.abort_if_errors(); tcx.sess.abort_if_errors();
} }
pub fn check_item(v: &mut CheckCrateVisitor, fn check_item(v: &mut CheckCrateVisitor, it: &Item, _is_const: bool) {
sess: Session,
def_map: resolve::DefMap,
it: &Item,
_is_const: bool) {
match it.node { match it.node {
ItemStatic(_, _, ex) => { ItemStatic(_, _, ex) => {
v.visit_expr(ex, true); v.visit_expr(ex, true);
check_item_recursion(sess, &v.tcx.map, def_map, it); check_item_recursion(&v.tcx.sess, &v.tcx.map, v.def_map, it);
} }
ItemEnum(ref enum_definition, _) => { ItemEnum(ref enum_definition, _) => {
for var in (*enum_definition).variants.iter() { for var in (*enum_definition).variants.iter() {
@ -77,8 +69,8 @@ pub fn check_item(v: &mut CheckCrateVisitor,
} }
} }
pub fn check_pat(v: &mut CheckCrateVisitor, p: &Pat, _is_const: bool) { fn check_pat(v: &mut CheckCrateVisitor, p: &Pat, _is_const: bool) {
fn is_str(e: @Expr) -> bool { fn is_str(e: &Expr) -> bool {
match e.node { match e.node {
ExprVstore(expr, ExprVstoreUniq) => { ExprVstore(expr, ExprVstoreUniq) => {
match expr.node { match expr.node {
@ -100,36 +92,30 @@ pub fn check_pat(v: &mut CheckCrateVisitor, p: &Pat, _is_const: bool) {
} }
} }
pub fn check_expr(v: &mut CheckCrateVisitor, fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) {
sess: Session,
def_map: resolve::DefMap,
method_map: typeck::MethodMap,
tcx: ty::ctxt,
e: &Expr,
is_const: bool) {
if is_const { if is_const {
match e.node { match e.node {
ExprUnary(UnDeref, _) => { } ExprUnary(UnDeref, _) => { }
ExprUnary(UnBox, _) | ExprUnary(UnUniq, _) => { ExprUnary(UnBox, _) | ExprUnary(UnUniq, _) => {
sess.span_err(e.span, v.tcx.sess.span_err(e.span,
"cannot do allocations in constant expressions"); "cannot do allocations in constant expressions");
return; return;
} }
ExprLit(lit) if ast_util::lit_is_str(lit) => {} ExprLit(lit) if ast_util::lit_is_str(lit) => {}
ExprBinary(..) | ExprUnary(..) => { ExprBinary(..) | ExprUnary(..) => {
let method_call = typeck::MethodCall::expr(e.id); let method_call = typeck::MethodCall::expr(e.id);
if method_map.borrow().get().contains_key(&method_call) { if v.method_map.borrow().get().contains_key(&method_call) {
sess.span_err(e.span, "user-defined operators are not \ v.tcx.sess.span_err(e.span, "user-defined operators are not \
allowed in constant expressions"); allowed in constant expressions");
} }
} }
ExprLit(_) => (), ExprLit(_) => (),
ExprCast(_, _) => { ExprCast(_, _) => {
let ety = ty::expr_ty(tcx, e); let ety = ty::expr_ty(v.tcx, e);
if !ty::type_is_numeric(ety) && !ty::type_is_unsafe_ptr(ety) { if !ty::type_is_numeric(ety) && !ty::type_is_unsafe_ptr(ety) {
sess.span_err(e.span, ~"can not cast to `" + v.tcx.sess.span_err(e.span, ~"can not cast to `" +
ppaux::ty_to_str(tcx, ety) + ppaux::ty_to_str(v.tcx, ety) +
"` in a constant expression"); "` in a constant expression");
} }
} }
ExprPath(ref pth) => { ExprPath(ref pth) => {
@ -138,12 +124,11 @@ pub fn check_expr(v: &mut CheckCrateVisitor,
// foo::<bar> in a const. Currently that is only done on // foo::<bar> in a const. Currently that is only done on
// a path in trans::callee that only works in block contexts. // a path in trans::callee that only works in block contexts.
if !pth.segments.iter().all(|segment| segment.types.is_empty()) { if !pth.segments.iter().all(|segment| segment.types.is_empty()) {
sess.span_err( v.tcx.sess.span_err(e.span,
e.span, "paths in constants may only refer to \ "paths in constants may only refer to \
items without type parameters"); items without type parameters");
} }
let def_map = def_map.borrow(); match v.def_map.borrow().get().find(&e.id) {
match def_map.get().find(&e.id) {
Some(&DefStatic(..)) | Some(&DefStatic(..)) |
Some(&DefFn(_, _)) | Some(&DefFn(_, _)) |
Some(&DefVariant(_, _, _)) | Some(&DefVariant(_, _, _)) |
@ -151,24 +136,21 @@ pub fn check_expr(v: &mut CheckCrateVisitor,
Some(&def) => { Some(&def) => {
debug!("(checking const) found bad def: {:?}", def); debug!("(checking const) found bad def: {:?}", def);
sess.span_err( v.tcx.sess.span_err(e.span,
e.span,
"paths in constants may only refer to \ "paths in constants may only refer to \
constants or functions"); constants or functions");
} }
None => { None => {
sess.span_bug(e.span, "unbound path in const?!"); v.tcx.sess.span_bug(e.span, "unbound path in const?!");
} }
} }
} }
ExprCall(callee, _) => { ExprCall(callee, _) => {
let def_map = def_map.borrow(); match v.def_map.borrow().get().find(&callee.id) {
match def_map.get().find(&callee.id) {
Some(&DefStruct(..)) => {} // OK. Some(&DefStruct(..)) => {} // OK.
Some(&DefVariant(..)) => {} // OK. Some(&DefVariant(..)) => {} // OK.
_ => { _ => {
sess.span_err( v.tcx.sess.span_err(e.span,
e.span,
"function calls in constants are limited to \ "function calls in constants are limited to \
struct and enum constructors"); struct and enum constructors");
} }
@ -184,18 +166,17 @@ pub fn check_expr(v: &mut CheckCrateVisitor,
ExprRepeat(..) | ExprRepeat(..) |
ExprStruct(..) => { } ExprStruct(..) => { }
ExprAddrOf(..) => { ExprAddrOf(..) => {
sess.span_err( v.tcx.sess.span_err(e.span,
e.span,
"references in constants may only refer to \ "references in constants may only refer to \
immutable values"); immutable values");
}, },
ExprVstore(_, ExprVstoreUniq) => { ExprVstore(_, ExprVstoreUniq) => {
sess.span_err(e.span, "cannot allocate vectors in constant expressions") v.tcx.sess.span_err(e.span, "cannot allocate vectors in constant expressions")
}, },
_ => { _ => {
sess.span_err(e.span, v.tcx.sess.span_err(e.span,
"constant contains unimplemented expression type"); "constant contains unimplemented expression type");
return; return;
} }
} }
@ -205,14 +186,14 @@ pub fn check_expr(v: &mut CheckCrateVisitor,
struct CheckItemRecursionVisitor<'a> { struct CheckItemRecursionVisitor<'a> {
root_it: &'a Item, root_it: &'a Item,
sess: Session, sess: &'a Session,
ast_map: &'a ast_map::Map, ast_map: &'a ast_map::Map,
def_map: resolve::DefMap, def_map: resolve::DefMap,
idstack: Vec<NodeId> } idstack: Vec<NodeId> }
// Make sure a const item doesn't recursively refer to itself // Make sure a const item doesn't recursively refer to itself
// FIXME: Should use the dependency graph when it's available (#1356) // FIXME: Should use the dependency graph when it's available (#1356)
pub fn check_item_recursion<'a>(sess: Session, pub fn check_item_recursion<'a>(sess: &'a Session,
ast_map: &'a ast_map::Map, ast_map: &'a ast_map::Map,
def_map: resolve::DefMap, def_map: resolve::DefMap,
it: &'a Item) { it: &'a Item) {

View File

@ -21,7 +21,7 @@ use syntax::visit;
use syntax::visit::Visitor; use syntax::visit::Visitor;
struct EntryContext<'a> { struct EntryContext<'a> {
session: Session, session: &'a Session,
ast_map: &'a ast_map::Map, ast_map: &'a ast_map::Map,
@ -48,7 +48,7 @@ impl<'a> Visitor<()> for EntryContext<'a> {
} }
} }
pub fn find_entry_point(session: Session, krate: &Crate, ast_map: &ast_map::Map) { pub fn find_entry_point(session: &Session, krate: &Crate, ast_map: &ast_map::Map) {
if session.building_library.get() { if session.building_library.get() {
// No need to find a main function // No need to find a main function
return; return;

View File

@ -103,27 +103,23 @@ impl LanguageItems {
)* )*
} }
struct LanguageItemCollector { struct LanguageItemCollector<'a> {
items: LanguageItems, items: LanguageItems,
session: Session, session: &'a Session,
item_refs: HashMap<&'static str, uint>, item_refs: HashMap<&'static str, uint>,
} }
struct LanguageItemVisitor<'a> { impl<'a> Visitor<()> for LanguageItemCollector<'a> {
this: &'a mut LanguageItemCollector,
}
impl<'a> Visitor<()> for LanguageItemVisitor<'a> {
fn visit_item(&mut self, item: &ast::Item, _: ()) { fn visit_item(&mut self, item: &ast::Item, _: ()) {
match extract(item.attrs.as_slice()) { match extract(item.attrs.as_slice()) {
Some(value) => { Some(value) => {
let item_index = self.this.item_refs.find_equiv(&value).map(|x| *x); let item_index = self.item_refs.find_equiv(&value).map(|x| *x);
match item_index { match item_index {
Some(item_index) => { Some(item_index) => {
self.this.collect_item(item_index, local_def(item.id)) self.collect_item(item_index, local_def(item.id))
} }
None => {} None => {}
} }
@ -135,8 +131,8 @@ impl<'a> Visitor<()> for LanguageItemVisitor<'a> {
} }
} }
impl LanguageItemCollector { impl<'a> LanguageItemCollector<'a> {
pub fn new(session: Session) -> LanguageItemCollector { pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
let mut item_refs = HashMap::new(); let mut item_refs = HashMap::new();
$( item_refs.insert($name, $variant as uint); )* $( item_refs.insert($name, $variant as uint); )*
@ -165,8 +161,7 @@ impl LanguageItemCollector {
} }
pub fn collect_local_language_items(&mut self, krate: &ast::Crate) { pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
let mut v = LanguageItemVisitor { this: self }; visit::walk_crate(self, krate, ());
visit::walk_crate(&mut v, krate, ());
} }
pub fn collect_external_language_items(&mut self) { pub fn collect_external_language_items(&mut self) {
@ -200,7 +195,7 @@ pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
} }
pub fn collect_language_items(krate: &ast::Crate, pub fn collect_language_items(krate: &ast::Crate,
session: Session) -> @LanguageItems { session: &Session) -> @LanguageItems {
let mut collector = LanguageItemCollector::new(session); let mut collector = LanguageItemCollector::new(session);
collector.collect(krate); collector.collect(krate);
let LanguageItemCollector { items, .. } = collector; let LanguageItemCollector { items, .. } = collector;

View File

@ -530,7 +530,7 @@ impl<'a> Context<'a> {
// of what we changed so we can roll everything back after invoking the // of what we changed so we can roll everything back after invoking the
// specified closure // specified closure
let mut pushed = 0u; let mut pushed = 0u;
each_lint(self.tcx.sess, attrs, |meta, level, lintname| { each_lint(&self.tcx.sess, attrs, |meta, level, lintname| {
match self.dict.find_equiv(&lintname) { match self.dict.find_equiv(&lintname) {
None => { None => {
self.span_lint( self.span_lint(
@ -594,7 +594,7 @@ impl<'a> Context<'a> {
// Check that every lint from the list of attributes satisfies `f`. // Check that every lint from the list of attributes satisfies `f`.
// Return true if that's the case. Otherwise return false. // Return true if that's the case. Otherwise return false.
pub fn each_lint(sess: session::Session, pub fn each_lint(sess: &session::Session,
attrs: &[ast::Attribute], attrs: &[ast::Attribute],
f: |@ast::MetaItem, level, InternedString| -> bool) f: |@ast::MetaItem, level, InternedString| -> bool)
-> bool { -> bool {

View File

@ -92,7 +92,7 @@ pub struct Context {
} }
struct RegionResolutionVisitor<'a> { struct RegionResolutionVisitor<'a> {
sess: Session, sess: &'a Session,
// Generated maps: // Generated maps:
region_maps: &'a RegionMaps, region_maps: &'a RegionMaps,
@ -909,7 +909,7 @@ impl<'a> Visitor<Context> for RegionResolutionVisitor<'a> {
} }
} }
pub fn resolve_crate(sess: Session, krate: &ast::Crate) -> RegionMaps { pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
let maps = RegionMaps { let maps = RegionMaps {
scope_map: RefCell::new(NodeMap::new()), scope_map: RefCell::new(NodeMap::new()),
var_map: RefCell::new(NodeMap::new()), var_map: RefCell::new(NodeMap::new()),
@ -928,7 +928,7 @@ pub fn resolve_crate(sess: Session, krate: &ast::Crate) -> RegionMaps {
return maps; return maps;
} }
pub fn resolve_inlined_item(sess: Session, pub fn resolve_inlined_item(sess: &Session,
region_maps: &RegionMaps, region_maps: &RegionMaps,
item: &ast::InlinedItem) { item: &ast::InlinedItem) {
let cx = Context {parent: None, let cx = Context {parent: None,

View File

@ -153,7 +153,7 @@ enum NameDefinition {
ImportNameDefinition(Def, LastPrivate) //< The name identifies an import. ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
} }
impl Visitor<()> for Resolver { impl<'a> Visitor<()> for Resolver<'a> {
fn visit_item(&mut self, item: &Item, _: ()) { fn visit_item(&mut self, item: &Item, _: ()) {
self.resolve_item(item); self.resolve_item(item);
} }
@ -787,9 +787,9 @@ fn namespace_error_to_str(ns: NamespaceError) -> &'static str {
} }
} }
fn Resolver(session: Session, fn Resolver<'a>(session: &'a Session,
lang_items: @LanguageItems, lang_items: @LanguageItems,
crate_span: Span) -> Resolver { crate_span: Span) -> Resolver<'a> {
let graph_root = @NameBindings(); let graph_root = @NameBindings();
graph_root.define_module(NoParentLink, graph_root.define_module(NoParentLink,
@ -802,7 +802,7 @@ fn Resolver(session: Session,
let current_module = graph_root.get_module(); let current_module = graph_root.get_module();
let this = Resolver { let this = Resolver {
session: @session, session: session,
lang_items: lang_items, lang_items: lang_items,
// The outermost module has def ID 0; this is not reflected in the // The outermost module has def ID 0; this is not reflected in the
@ -843,8 +843,8 @@ fn Resolver(session: Session,
} }
/// The main resolver class. /// The main resolver class.
struct Resolver { struct Resolver<'a> {
session: @Session, session: &'a Session,
lang_items: @LanguageItems, lang_items: @LanguageItems,
graph_root: @NameBindings, graph_root: @NameBindings,
@ -896,11 +896,11 @@ struct Resolver {
used_imports: HashSet<(NodeId, Namespace)>, used_imports: HashSet<(NodeId, Namespace)>,
} }
struct BuildReducedGraphVisitor<'a> { struct BuildReducedGraphVisitor<'a, 'b> {
resolver: &'a mut Resolver, resolver: &'a mut Resolver<'b>,
} }
impl<'a> Visitor<ReducedGraphParent> for BuildReducedGraphVisitor<'a> { impl<'a, 'b> Visitor<ReducedGraphParent> for BuildReducedGraphVisitor<'a, 'b> {
fn visit_item(&mut self, item: &Item, context: ReducedGraphParent) { fn visit_item(&mut self, item: &Item, context: ReducedGraphParent) {
let p = self.resolver.build_reduced_graph_for_item(item, context); let p = self.resolver.build_reduced_graph_for_item(item, context);
@ -928,16 +928,16 @@ impl<'a> Visitor<ReducedGraphParent> for BuildReducedGraphVisitor<'a> {
} }
struct UnusedImportCheckVisitor<'a> { resolver: &'a mut Resolver } struct UnusedImportCheckVisitor<'a, 'b> { resolver: &'a mut Resolver<'b> }
impl<'a> Visitor<()> for UnusedImportCheckVisitor<'a> { impl<'a, 'b> Visitor<()> for UnusedImportCheckVisitor<'a, 'b> {
fn visit_view_item(&mut self, vi: &ViewItem, _: ()) { fn visit_view_item(&mut self, vi: &ViewItem, _: ()) {
self.resolver.check_for_item_unused_imports(vi); self.resolver.check_for_item_unused_imports(vi);
visit::walk_view_item(self, vi, ()); visit::walk_view_item(self, vi, ());
} }
} }
impl Resolver { impl<'a> Resolver<'a> {
/// The main name resolution procedure. /// The main name resolution procedure.
fn resolve(&mut self, krate: &ast::Crate) { fn resolve(&mut self, krate: &ast::Crate) {
self.build_reduced_graph(krate); self.build_reduced_graph(krate);
@ -5571,7 +5571,7 @@ pub struct CrateMap {
} }
/// Entry point to crate resolution. /// Entry point to crate resolution.
pub fn resolve_crate(session: Session, pub fn resolve_crate(session: &Session,
lang_items: @LanguageItems, lang_items: @LanguageItems,
krate: &Crate) krate: &Crate)
-> CrateMap { -> CrateMap {

View File

@ -17,7 +17,7 @@
* way. Therefore we break lifetime name resolution into a separate pass. * way. Therefore we break lifetime name resolution into a separate pass.
*/ */
use driver::session; use driver::session::Session;
use std::cell::RefCell; use std::cell::RefCell;
use std::vec_ng::Vec; use std::vec_ng::Vec;
use util::nodemap::NodeMap; use util::nodemap::NodeMap;
@ -40,8 +40,8 @@ fn lifetime_show(lt_name: &ast::Name) -> token::InternedString {
token::get_name(*lt_name) token::get_name(*lt_name)
} }
struct LifetimeContext { struct LifetimeContext<'a> {
sess: session::Session, sess: &'a Session,
named_region_map: @RefCell<NamedRegionMap>, named_region_map: @RefCell<NamedRegionMap>,
} }
@ -60,8 +60,7 @@ enum ScopeChain<'a> {
type Scope<'a> = &'a ScopeChain<'a>; type Scope<'a> = &'a ScopeChain<'a>;
pub fn krate(sess: session::Session, krate: &ast::Crate) pub fn krate(sess: &Session, krate: &ast::Crate) -> @RefCell<NamedRegionMap> {
-> @RefCell<NamedRegionMap> {
let mut ctxt = LifetimeContext { let mut ctxt = LifetimeContext {
sess: sess, sess: sess,
named_region_map: @RefCell::new(NodeMap::new()) named_region_map: @RefCell::new(NodeMap::new())
@ -71,7 +70,7 @@ pub fn krate(sess: session::Session, krate: &ast::Crate)
ctxt.named_region_map ctxt.named_region_map
} }
impl<'a> Visitor<Scope<'a>> for LifetimeContext { impl<'a, 'b> Visitor<Scope<'a>> for LifetimeContext<'b> {
fn visit_item(&mut self, fn visit_item(&mut self,
item: &ast::Item, item: &ast::Item,
_: Scope<'a>) { _: Scope<'a>) {
@ -181,7 +180,7 @@ impl<'a> ScopeChain<'a> {
} }
} }
impl LifetimeContext { impl<'a> LifetimeContext<'a> {
/// Visits self by adding a scope and handling recursive walk over the contents with `walk`. /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
fn visit_fn_decl(&mut self, fn visit_fn_decl(&mut self,
n: ast::NodeId, n: ast::NodeId,

View File

@ -373,7 +373,7 @@ fn variant_opt(bcx: &Block, pat_id: ast::NodeId) -> Opt {
return lit(UnitLikeStructLit(pat_id)); return lit(UnitLikeStructLit(pat_id));
} }
_ => { _ => {
ccx.sess.bug("non-variant or struct in variant_opt()"); ccx.sess().bug("non-variant or struct in variant_opt()");
} }
} }
} }
@ -1324,8 +1324,7 @@ fn compare_values<'a>(
} }
} }
_ => { _ => {
cx.tcx().sess.bug("only scalars and strings supported in \ cx.sess().bug("only scalars and strings supported in compare_values");
compare_values");
} }
} }
} }
@ -1585,7 +1584,7 @@ fn compile_submatch_continue<'r,
let tup_repr = adt::represent_type(bcx.ccx(), tup_ty); let tup_repr = adt::represent_type(bcx.ccx(), tup_ty);
let n_tup_elts = match ty::get(tup_ty).sty { let n_tup_elts = match ty::get(tup_ty).sty {
ty::ty_tup(ref elts) => elts.len(), ty::ty_tup(ref elts) => elts.len(),
_ => ccx.sess.bug("non-tuple type in tuple pattern") _ => ccx.sess().bug("non-tuple type in tuple pattern")
}; };
let tup_vals = Vec::from_fn(n_tup_elts, |i| { let tup_vals = Vec::from_fn(n_tup_elts, |i| {
adt::trans_field_ptr(bcx, tup_repr, val, 0, i) adt::trans_field_ptr(bcx, tup_repr, val, 0, i)
@ -1612,7 +1611,7 @@ fn compile_submatch_continue<'r,
ty::lookup_struct_fields(tcx, struct_id).len(); ty::lookup_struct_fields(tcx, struct_id).len();
} }
_ => { _ => {
ccx.sess.bug("non-struct type in tuple struct pattern"); ccx.sess().bug("non-struct type in tuple struct pattern");
} }
} }
@ -2093,7 +2092,7 @@ pub fn store_arg<'a>(mut bcx: &'a Block<'a>,
// like `x: T` // like `x: T`
let arg_ty = node_id_type(bcx, pat.id); let arg_ty = node_id_type(bcx, pat.id);
if type_of::arg_is_indirect(bcx.ccx(), arg_ty) if type_of::arg_is_indirect(bcx.ccx(), arg_ty)
&& bcx.ccx().sess.opts.debuginfo != FullDebugInfo { && bcx.sess().opts.debuginfo != FullDebugInfo {
// Don't copy an indirect argument to an alloca, the caller // Don't copy an indirect argument to an alloca, the caller
// already put it in a temporary alloca and gave it up, unless // already put it in a temporary alloca and gave it up, unless
// we emit extra-debug-info, which requires local allocas :(. // we emit extra-debug-info, which requires local allocas :(.
@ -2297,8 +2296,7 @@ fn bind_irrefutable_pat<'a>(
bcx = bind_irrefutable_pat(bcx, inner, loaded_val, binding_mode, cleanup_scope); bcx = bind_irrefutable_pat(bcx, inner, loaded_val, binding_mode, cleanup_scope);
} }
ast::PatVec(..) => { ast::PatVec(..) => {
bcx.tcx().sess.span_bug( bcx.sess().span_bug(pat.span,
pat.span,
format!("vector patterns are never irrefutable!")); format!("vector patterns are never irrefutable!"));
} }
ast::PatWild | ast::PatWildMulti | ast::PatLit(_) | ast::PatRange(_, _) => () ast::PatWild | ast::PatWildMulti | ast::PatLit(_) | ast::PatRange(_, _) => ()

View File

@ -177,9 +177,9 @@ fn represent_type_uncached(cx: &CrateContext, t: ty::t) -> Repr {
// non-empty body, explicit discriminants should have // non-empty body, explicit discriminants should have
// been rejected by a checker before this point. // been rejected by a checker before this point.
if !cases.iter().enumerate().all(|(i,c)| c.discr == (i as Disr)) { if !cases.iter().enumerate().all(|(i,c)| c.discr == (i as Disr)) {
cx.sess.bug(format!("non-C-like enum {} with specified \ cx.sess().bug(format!("non-C-like enum {} with specified \
discriminants", discriminants",
ty::item_path_str(cx.tcx, def_id))) ty::item_path_str(cx.tcx, def_id)))
} }
if cases.len() == 1 { if cases.len() == 1 {
@ -230,7 +230,7 @@ fn represent_type_uncached(cx: &CrateContext, t: ty::t) -> Repr {
false) false)
})) }))
} }
_ => cx.sess.bug("adt::represent_type called on non-ADT type") _ => cx.sess().bug("adt::represent_type called on non-ADT type")
} }
} }
@ -324,12 +324,12 @@ fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntTyp
match hint { match hint {
attr::ReprInt(span, ity) => { attr::ReprInt(span, ity) => {
if !bounds_usable(cx, ity, bounds) { if !bounds_usable(cx, ity, bounds) {
cx.sess.span_bug(span, "representation hint insufficient for discriminant range") cx.sess().span_bug(span, "representation hint insufficient for discriminant range")
} }
return ity; return ity;
} }
attr::ReprExtern => { attr::ReprExtern => {
attempts = match cx.sess.targ_cfg.arch { attempts = match cx.sess().targ_cfg.arch {
X86 | X86_64 => at_least_32, X86 | X86_64 => at_least_32,
// WARNING: the ARM EABI has two variants; the one corresponding to `at_least_32` // WARNING: the ARM EABI has two variants; the one corresponding to `at_least_32`
// appears to be used on Linux and NetBSD, but some systems may use the variant // appears to be used on Linux and NetBSD, but some systems may use the variant
@ -577,7 +577,7 @@ pub fn trans_case<'a>(bcx: &'a Block<'a>, r: &Repr, discr: Disr)
discr as u64, true))) discr as u64, true)))
} }
Univariant(..) => { Univariant(..) => {
bcx.ccx().sess.bug("no cases for univariants or structs") bcx.ccx().sess().bug("no cases for univariants or structs")
} }
NullablePointer{ .. } => { NullablePointer{ .. } => {
assert!(discr == 0 || discr == 1); assert!(discr == 0 || discr == 1);
@ -651,7 +651,7 @@ pub fn num_args(r: &Repr, discr: Disr) -> uint {
pub fn deref_ty(ccx: &CrateContext, r: &Repr) -> ty::t { pub fn deref_ty(ccx: &CrateContext, r: &Repr) -> ty::t {
match *r { match *r {
CEnum(..) => { CEnum(..) => {
ccx.sess.bug("deref of c-like enum") ccx.sess().bug("deref of c-like enum")
} }
Univariant(ref st, _) => { Univariant(ref st, _) => {
*st.fields.get(0) *st.fields.get(0)
@ -661,7 +661,7 @@ pub fn deref_ty(ccx: &CrateContext, r: &Repr) -> ty::t {
*cases.get(0).fields.get(0) *cases.get(0).fields.get(0)
} }
NullablePointer{ .. } => { NullablePointer{ .. } => {
ccx.sess.bug("deref of nullable ptr") ccx.sess().bug("deref of nullable ptr")
} }
} }
} }
@ -674,7 +674,7 @@ pub fn trans_field_ptr(bcx: &Block, r: &Repr, val: ValueRef, discr: Disr,
// someday), it will need to return a possibly-new bcx as well. // someday), it will need to return a possibly-new bcx as well.
match *r { match *r {
CEnum(..) => { CEnum(..) => {
bcx.ccx().sess.bug("element access in C-like enum") bcx.ccx().sess().bug("element access in C-like enum")
} }
Univariant(ref st, _dtor) => { Univariant(ref st, _dtor) => {
assert_eq!(discr, 0); assert_eq!(discr, 0);
@ -719,7 +719,7 @@ fn struct_field_ptr(bcx: &Block, st: &Struct, val: ValueRef, ix: uint,
pub fn trans_drop_flag_ptr(bcx: &Block, r: &Repr, val: ValueRef) -> ValueRef { pub fn trans_drop_flag_ptr(bcx: &Block, r: &Repr, val: ValueRef) -> ValueRef {
match *r { match *r {
Univariant(ref st, true) => GEPi(bcx, val, [0, st.fields.len() - 1]), Univariant(ref st, true) => GEPi(bcx, val, [0, st.fields.len() - 1]),
_ => bcx.ccx().sess.bug("tried to get drop flag of non-droppable type") _ => bcx.ccx().sess().bug("tried to get drop flag of non-droppable type")
} }
} }
@ -874,7 +874,7 @@ pub fn const_get_discrim(ccx: &CrateContext, r: &Repr, val: ValueRef)
pub fn const_get_field(ccx: &CrateContext, r: &Repr, val: ValueRef, pub fn const_get_field(ccx: &CrateContext, r: &Repr, val: ValueRef,
_discr: Disr, ix: uint) -> ValueRef { _discr: Disr, ix: uint) -> ValueRef {
match *r { match *r {
CEnum(..) => ccx.sess.bug("element access in C-like enum const"), CEnum(..) => ccx.sess().bug("element access in C-like enum const"),
Univariant(..) => const_struct_field(ccx, val, ix), Univariant(..) => const_struct_field(ccx, val, ix),
General(..) => const_struct_field(ccx, val, ix + 1), General(..) => const_struct_field(ccx, val, ix + 1),
NullablePointer{ .. } => const_struct_field(ccx, val, ix) NullablePointer{ .. } => const_struct_field(ccx, val, ix)

View File

@ -144,7 +144,7 @@ pub struct StatRecorder {
impl StatRecorder { impl StatRecorder {
pub fn new(ccx: @CrateContext, name: ~str) -> StatRecorder { pub fn new(ccx: @CrateContext, name: ~str) -> StatRecorder {
let start = if ccx.sess.trans_stats() { let start = if ccx.sess().trans_stats() {
time::precise_time_ns() time::precise_time_ns()
} else { } else {
0 0
@ -162,7 +162,7 @@ impl StatRecorder {
#[unsafe_destructor] #[unsafe_destructor]
impl Drop for StatRecorder { impl Drop for StatRecorder {
fn drop(&mut self) { fn drop(&mut self) {
if self.ccx.sess.trans_stats() { if self.ccx.sess().trans_stats() {
let end = time::precise_time_ns(); let end = time::precise_time_ns();
let elapsed = ((end - self.start) / 1_000_000) as uint; let elapsed = ((end - self.start) / 1_000_000) as uint;
let iend = self.ccx.stats.n_llvm_insns.get(); let iend = self.ccx.stats.n_llvm_insns.get();
@ -355,8 +355,8 @@ pub fn malloc_raw_dyn<'a>(
match li.require(it) { match li.require(it) {
Ok(id) => id, Ok(id) => id,
Err(s) => { Err(s) => {
bcx.tcx().sess.fatal(format!("allocation of `{}` {}", bcx.sess().fatal(format!("allocation of `{}` {}",
bcx.ty_to_str(t), s)); bcx.ty_to_str(t), s));
} }
} }
} }
@ -522,7 +522,7 @@ pub fn set_no_split_stack(f: ValueRef) {
pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) { pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) {
let mut all_llvm_symbols = ccx.all_llvm_symbols.borrow_mut(); let mut all_llvm_symbols = ccx.all_llvm_symbols.borrow_mut();
if all_llvm_symbols.get().contains(&sym) { if all_llvm_symbols.get().contains(&sym) {
ccx.sess.bug(~"duplicate LLVM symbol: " + sym); ccx.sess().bug(~"duplicate LLVM symbol: " + sym);
} }
all_llvm_symbols.get().insert(sym); all_llvm_symbols.get().insert(sym);
} }
@ -555,7 +555,7 @@ pub fn get_res_dtor(ccx: @CrateContext,
get_item_val(ccx, did.node) get_item_val(ccx, did.node)
} else { } else {
let tcx = ccx.tcx; let tcx = ccx.tcx;
let name = csearch::get_symbol(ccx.sess.cstore, did); let name = csearch::get_symbol(ccx.sess().cstore, did);
let class_ty = ty::subst_tps(tcx, let class_ty = ty::subst_tps(tcx,
substs, substs,
None, None,
@ -572,7 +572,7 @@ pub fn get_res_dtor(ccx: @CrateContext,
// Structural comparison: a rather involved form of glue. // Structural comparison: a rather involved form of glue.
pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) { pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
if cx.sess.opts.cg.save_temps { if cx.sess().opts.cg.save_temps {
s.with_c_str(|buf| { s.with_c_str(|buf| {
unsafe { unsafe {
llvm::LLVMSetValueName(v, buf) llvm::LLVMSetValueName(v, buf)
@ -617,8 +617,7 @@ pub fn compare_scalar_values<'a>(
-> ValueRef { -> ValueRef {
let _icx = push_ctxt("compare_scalar_values"); let _icx = push_ctxt("compare_scalar_values");
fn die(cx: &Block) -> ! { fn die(cx: &Block) -> ! {
cx.tcx().sess.bug("compare_scalar_values: must be a\ cx.sess().bug("compare_scalar_values: must be a comparison operator");
comparison operator");
} }
match nt { match nt {
nil_type => { nil_type => {
@ -772,8 +771,8 @@ pub fn iter_structural_ty<'r,
_match::single_result(r) => { _match::single_result(r) => {
AddCase(llswitch, r.val, variant_cx.llbb) AddCase(llswitch, r.val, variant_cx.llbb)
} }
_ => ccx.sess.unimpl("value from adt::trans_case \ _ => ccx.sess().unimpl("value from adt::trans_case \
in iter_structural_ty") in iter_structural_ty")
} }
let variant_cx = let variant_cx =
iter_variant(variant_cx, iter_variant(variant_cx,
@ -786,8 +785,8 @@ pub fn iter_structural_ty<'r,
} }
cx = next_cx; cx = next_cx;
} }
_ => ccx.sess.unimpl("value from adt::trans_switch \ _ => ccx.sess().unimpl("value from adt::trans_switch \
in iter_structural_ty") in iter_structural_ty")
} }
} }
_ => cx.sess().unimpl("type in iter_structural_ty") _ => cx.sess().unimpl("type in iter_structural_ty")
@ -865,8 +864,8 @@ pub fn fail_if_zero<'a>(
ICmp(cx, lib::llvm::IntEQ, rhs, zero) ICmp(cx, lib::llvm::IntEQ, rhs, zero)
} }
_ => { _ => {
cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " + cx.sess().bug(~"fail-if-zero on unexpected type: " +
ty_to_str(cx.ccx().tcx, rhs_t)); ty_to_str(cx.ccx().tcx, rhs_t));
} }
}; };
with_cond(cx, is_zero, |bcx| { with_cond(cx, is_zero, |bcx| {
@ -875,11 +874,11 @@ pub fn fail_if_zero<'a>(
} }
pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef { pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
let name = csearch::get_symbol(ccx.sess.cstore, did); let name = csearch::get_symbol(ccx.sess().cstore, did);
match ty::get(t).sty { match ty::get(t).sty {
ty::ty_bare_fn(ref fn_ty) => { ty::ty_bare_fn(ref fn_ty) => {
match fn_ty.abis.for_target(ccx.sess.targ_cfg.os, match fn_ty.abis.for_target(ccx.sess().targ_cfg.os,
ccx.sess.targ_cfg.arch) { ccx.sess().targ_cfg.arch) {
Some(Rust) | Some(RustIntrinsic) => { Some(Rust) | Some(RustIntrinsic) => {
get_extern_rust_fn(ccx, get_extern_rust_fn(ccx,
fn_ty.sig.inputs.as_slice(), fn_ty.sig.inputs.as_slice(),
@ -970,7 +969,7 @@ pub fn invoke<'a>(
} }
pub fn need_invoke(bcx: &Block) -> bool { pub fn need_invoke(bcx: &Block) -> bool {
if bcx.ccx().sess.no_landing_pads() { if bcx.sess().no_landing_pads() {
return false; return false;
} }
@ -1081,7 +1080,7 @@ pub fn with_cond<'a>(
pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) { pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
let _icx = push_ctxt("call_memcpy"); let _icx = push_ctxt("call_memcpy");
let ccx = cx.ccx(); let ccx = cx.ccx();
let key = match ccx.sess.targ_cfg.arch { let key = match ccx.sess().targ_cfg.arch {
X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32", X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
X86_64 => "llvm.memcpy.p0i8.p0i8.i64" X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
}; };
@ -1125,7 +1124,7 @@ fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
let _icx = push_ctxt("memzero"); let _icx = push_ctxt("memzero");
let ccx = b.ccx; let ccx = b.ccx;
let intrinsic_key = match ccx.sess.targ_cfg.arch { let intrinsic_key = match ccx.sess().targ_cfg.arch {
X86 | Arm | Mips => "llvm.memset.p0i8.i32", X86 | Arm | Mips => "llvm.memset.p0i8.i32",
X86_64 => "llvm.memset.p0i8.i64" X86_64 => "llvm.memset.p0i8.i64"
}; };
@ -1384,7 +1383,7 @@ fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id); bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
if fcx.ccx.sess.opts.debuginfo == FullDebugInfo { if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
debuginfo::create_argument_metadata(bcx, &args[i]); debuginfo::create_argument_metadata(bcx, &args[i]);
} }
} }
@ -1615,7 +1614,7 @@ fn trans_enum_variant_or_tuple_like_struct(ccx: @CrateContext,
let result_ty = match ty::get(ctor_ty).sty { let result_ty = match ty::get(ctor_ty).sty {
ty::ty_bare_fn(ref bft) => bft.sig.output, ty::ty_bare_fn(ref bft) => bft.sig.output,
_ => ccx.sess.bug( _ => ccx.sess().bug(
format!("trans_enum_variant_or_tuple_like_struct: \ format!("trans_enum_variant_or_tuple_like_struct: \
unexpected ctor return type {}", unexpected ctor return type {}",
ty_to_str(ccx.tcx, ctor_ty))) ty_to_str(ccx.tcx, ctor_ty)))
@ -1724,16 +1723,16 @@ pub fn trans_item(ccx: @CrateContext, item: &ast::Item) {
// because we need to get the value of the bool out of LLVM // because we need to get the value of the bool out of LLVM
if attr::contains_name(item.attrs.as_slice(), "static_assert") { if attr::contains_name(item.attrs.as_slice(), "static_assert") {
if m == ast::MutMutable { if m == ast::MutMutable {
ccx.sess.span_fatal(expr.span, ccx.sess().span_fatal(expr.span,
"cannot have static_assert on a mutable \ "cannot have static_assert on a mutable \
static"); static");
} }
let const_values = ccx.const_values.borrow(); let const_values = ccx.const_values.borrow();
let v = const_values.get().get_copy(&item.id); let v = const_values.get().get_copy(&item.id);
unsafe { unsafe {
if !(llvm::LLVMConstIntGetZExtValue(v) != 0) { if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
ccx.sess.span_fatal(expr.span, "static assertion failed"); ccx.sess().span_fatal(expr.span, "static assertion failed");
} }
} }
} }
@ -1798,7 +1797,7 @@ fn finish_register_fn(ccx: @CrateContext, sp: Span, sym: ~str, node_id: ast::Nod
} }
} }
if is_entry_fn(&ccx.sess, node_id) && !ccx.sess.building_library.get() { if is_entry_fn(ccx.sess(), node_id) && !ccx.sess().building_library.get() {
create_entry_wrapper(ccx, sp, llfn); create_entry_wrapper(ccx, sp, llfn);
} }
} }
@ -1853,7 +1852,7 @@ pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
pub fn create_entry_wrapper(ccx: @CrateContext, pub fn create_entry_wrapper(ccx: @CrateContext,
_sp: Span, _sp: Span,
main_llfn: ValueRef) { main_llfn: ValueRef) {
let et = ccx.sess.entry_type.get().unwrap(); let et = ccx.sess().entry_type.get().unwrap();
match et { match et {
session::EntryMain => { session::EntryMain => {
create_entry_fn(ccx, main_llfn, true); create_entry_fn(ccx, main_llfn, true);
@ -1881,7 +1880,7 @@ pub fn create_entry_wrapper(ccx: @CrateContext,
let (start_fn, args) = if use_start_lang_item { let (start_fn, args) = if use_start_lang_item {
let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) { let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
Ok(id) => id, Ok(id) => id,
Err(s) => { ccx.tcx.sess.fatal(s); } Err(s) => { ccx.sess().fatal(s); }
}; };
let start_fn = if start_def_id.krate == ast::LOCAL_CRATE { let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
get_item_val(ccx, start_def_id.node) get_item_val(ccx, start_def_id.node)
@ -1973,7 +1972,7 @@ pub fn get_item_val(ccx: @CrateContext, id: ast::NodeId) -> ValueRef {
match external_srcs.get().find(&i.id) { match external_srcs.get().find(&i.id) {
Some(&did) => { Some(&did) => {
debug!("but found in other crate..."); debug!("but found in other crate...");
(csearch::get_symbol(ccx.sess.cstore, (csearch::get_symbol(ccx.sess().cstore,
did), false) did), false)
} }
None => (sym, true) None => (sym, true)
@ -2013,7 +2012,7 @@ pub fn get_item_val(ccx: @CrateContext, id: ast::NodeId) -> ValueRef {
let reachable = let reachable =
ccx.reachable.borrow(); ccx.reachable.borrow();
if reachable.get().contains(&id) { if reachable.get().contains(&id) {
ccx.sess.span_bug(i.span, ccx.sess().span_bug(i.span,
"insignificant static is \ "insignificant static is \
reachable"); reachable");
} }
@ -2093,8 +2092,8 @@ pub fn get_item_val(ccx: @CrateContext, id: ast::NodeId) -> ValueRef {
debug!("get_item_val(): processing a NodeTraitMethod"); debug!("get_item_val(): processing a NodeTraitMethod");
match *trait_method { match *trait_method {
ast::Required(_) => { ast::Required(_) => {
ccx.sess.bug("unexpected variant: required trait method in \ ccx.sess().bug("unexpected variant: required trait method in \
get_item_val()"); get_item_val()");
} }
ast::Provided(m) => { ast::Provided(m) => {
register_method(ccx, id, m) register_method(ccx, id, m)
@ -2152,8 +2151,8 @@ pub fn get_item_val(ccx: @CrateContext, id: ast::NodeId) -> ValueRef {
// Only register the constructor if this is a tuple-like struct. // Only register the constructor if this is a tuple-like struct.
match struct_def.ctor_id { match struct_def.ctor_id {
None => { None => {
ccx.tcx.sess.bug("attempt to register a constructor of \ ccx.sess().bug("attempt to register a constructor of \
a non-tuple-like struct") a non-tuple-like struct")
} }
Some(ctor_id) => { Some(ctor_id) => {
let parent = ccx.tcx.map.get_parent(id); let parent = ccx.tcx.map.get_parent(id);
@ -2173,8 +2172,8 @@ pub fn get_item_val(ccx: @CrateContext, id: ast::NodeId) -> ValueRef {
} }
ref variant => { ref variant => {
ccx.sess.bug(format!("get_item_val(): unexpected variant: {:?}", ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
variant)) variant))
} }
}; };
@ -2409,7 +2408,7 @@ pub fn symname(name: &str, hash: &str, vers: &str) -> ~str {
link::exported_name(ast_map::Values(path.iter()).chain(None), hash, vers) link::exported_name(ast_map::Values(path.iter()).chain(None), hash, vers)
} }
pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta, pub fn decl_crate_map(sess: &Session, mapmeta: LinkMeta,
llmod: ModuleRef) -> (~str, ValueRef) { llmod: ModuleRef) -> (~str, ValueRef) {
let targ_cfg = sess.targ_cfg; let targ_cfg = sess.targ_cfg;
let int_type = Type::int(targ_cfg.arch); let int_type = Type::int(targ_cfg.arch);
@ -2452,7 +2451,7 @@ pub fn fill_crate_map(ccx: @CrateContext, map: ValueRef) {
llvm::LLVMConstPointerCast(get_item_val(ccx, did.node), llvm::LLVMConstPointerCast(get_item_val(ccx, did.node),
ccx.int_type.ptr_to().to_ref()) ccx.int_type.ptr_to().to_ref())
} else { } else {
let name = csearch::get_symbol(ccx.sess.cstore, did); let name = csearch::get_symbol(ccx.sess().cstore, did);
let global = name.with_c_str(|buf| { let global = name.with_c_str(|buf| {
llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf) llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
}); });
@ -2472,7 +2471,7 @@ pub fn fill_crate_map(ccx: @CrateContext, map: ValueRef) {
pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>) pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
-> encoder::EncodeParams<'r> { -> encoder::EncodeParams<'r> {
let diag = cx.sess.diagnostic(); let diag = cx.sess().diagnostic();
let item_symbols = &cx.item_symbols; let item_symbols = &cx.item_symbols;
let link_meta = &cx.link_meta; let link_meta = &cx.link_meta;
encoder::EncodeParams { encoder::EncodeParams {
@ -2482,7 +2481,7 @@ pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeI
item_symbols: item_symbols, item_symbols: item_symbols,
non_inlineable_statics: &cx.non_inlineable_statics, non_inlineable_statics: &cx.non_inlineable_statics,
link_meta: link_meta, link_meta: link_meta,
cstore: cx.sess.cstore, cstore: cx.sess().cstore,
encode_inlined_item: ie, encode_inlined_item: ie,
} }
} }
@ -2490,7 +2489,7 @@ pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeI
pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> { pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
use flate; use flate;
if !cx.sess.building_library.get() { if !cx.sess().building_library.get() {
return Vec::new() return Vec::new()
} }
@ -2512,15 +2511,14 @@ pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
}); });
unsafe { unsafe {
llvm::LLVMSetInitializer(llglobal, llconst); llvm::LLVMSetInitializer(llglobal, llconst);
cx.sess.targ_cfg.target_strs.meta_sect_name.with_c_str(|buf| { cx.sess().targ_cfg.target_strs.meta_sect_name.with_c_str(|buf| {
llvm::LLVMSetSection(llglobal, buf) llvm::LLVMSetSection(llglobal, buf)
}); });
} }
return metadata; return metadata;
} }
pub fn trans_crate(sess: session::Session, pub fn trans_crate(krate: ast::Crate,
krate: ast::Crate,
analysis: &CrateAnalysis, analysis: &CrateAnalysis,
output: &OutputFilenames) -> CrateTranslation { output: &OutputFilenames) -> CrateTranslation {
// Before we touch LLVM, make sure that multithreading is enabled. // Before we touch LLVM, make sure that multithreading is enabled.
@ -2537,7 +2535,7 @@ pub fn trans_crate(sess: session::Session,
}); });
if POISONED { if POISONED {
sess.bug("couldn't enable multi-threaded LLVM"); analysis.ty_cx.sess.bug("couldn't enable multi-threaded LLVM");
} }
} }
@ -2553,8 +2551,7 @@ pub fn trans_crate(sess: session::Session,
// 1. http://llvm.org/bugs/show_bug.cgi?id=11479 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
let llmod_id = link_meta.crateid.name + ".rs"; let llmod_id = link_meta.crateid.name + ".rs";
let ccx = @CrateContext::new(sess, let ccx = @CrateContext::new(llmod_id,
llmod_id,
analysis.ty_cx, analysis.ty_cx,
analysis.exp_map2, analysis.exp_map2,
analysis.maps, analysis.maps,
@ -2574,7 +2571,7 @@ pub fn trans_crate(sess: session::Session,
// __rust_crate_map_toplevel symbol (extra underscore) which it will // __rust_crate_map_toplevel symbol (extra underscore) which it will
// subsequently fail to find. So to mitigate that we just introduce // subsequently fail to find. So to mitigate that we just introduce
// an alias from the symbol it expects to the one that actually exists. // an alias from the symbol it expects to the one that actually exists.
if ccx.sess.targ_cfg.os == OsWin32 && !ccx.sess.building_library.get() { if ccx.sess().targ_cfg.os == OsWin32 && !ccx.sess().building_library.get() {
let maptype = val_ty(ccx.crate_map).to_ref(); let maptype = val_ty(ccx.crate_map).to_ref();
@ -2587,13 +2584,13 @@ pub fn trans_crate(sess: session::Session,
} }
glue::emit_tydescs(ccx); glue::emit_tydescs(ccx);
if ccx.sess.opts.debuginfo != NoDebugInfo { if ccx.sess().opts.debuginfo != NoDebugInfo {
debuginfo::finalize(ccx); debuginfo::finalize(ccx);
} }
// Translate the metadata. // Translate the metadata.
let metadata = write_metadata(ccx, &krate); let metadata = write_metadata(ccx, &krate);
if ccx.sess.trans_stats() { if ccx.sess().trans_stats() {
println!("--- trans stats ---"); println!("--- trans stats ---");
println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get()); println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
println!("n_glues_created: {}", ccx.stats.n_glues_created.get()); println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
@ -2619,7 +2616,7 @@ pub fn trans_crate(sess: session::Session,
} }
} }
} }
if ccx.sess.count_llvm_insns() { if ccx.sess().count_llvm_insns() {
let llvm_insns = ccx.stats.llvm_insns.borrow(); let llvm_insns = ccx.stats.llvm_insns.borrow();
for (k, v) in llvm_insns.get().iter() { for (k, v) in llvm_insns.get().iter() {
println!("{:7u} {}", *v, *k); println!("{:7u} {}", *v, *k);

View File

@ -44,13 +44,13 @@ impl<'a> Builder<'a> {
} }
pub fn count_insn(&self, category: &str) { pub fn count_insn(&self, category: &str) {
if self.ccx.sess.trans_stats() { if self.ccx.sess().trans_stats() {
self.ccx.stats.n_llvm_insns.set(self.ccx self.ccx.stats.n_llvm_insns.set(self.ccx
.stats .stats
.n_llvm_insns .n_llvm_insns
.get() + 1); .get() + 1);
} }
if self.ccx.sess.count_llvm_insns() { if self.ccx.sess().count_llvm_insns() {
base::with_insn_ctxt(|v| { base::with_insn_ctxt(|v| {
let mut h = self.ccx.stats.llvm_insns.borrow_mut(); let mut h = self.ccx.stats.llvm_insns.borrow_mut();
@ -748,15 +748,15 @@ impl<'a> Builder<'a> {
} }
pub fn add_span_comment(&self, sp: Span, text: &str) { pub fn add_span_comment(&self, sp: Span, text: &str) {
if self.ccx.sess.asm_comments() { if self.ccx.sess().asm_comments() {
let s = format!("{} ({})", text, self.ccx.sess.codemap.span_to_str(sp)); let s = format!("{} ({})", text, self.ccx.sess().codemap.span_to_str(sp));
debug!("{}", s); debug!("{}", s);
self.add_comment(s); self.add_comment(s);
} }
} }
pub fn add_comment(&self, text: &str) { pub fn add_comment(&self, text: &str) {
if self.ccx.sess.asm_comments() { if self.ccx.sess().asm_comments() {
let sanitized = text.replace("$", ""); let sanitized = text.replace("$", "");
let comment_text = format!("\\# {}", sanitized.replace("\n", "\n\t# ")); let comment_text = format!("\\# {}", sanitized.replace("\n", "\n\t# "));
self.count_insn("inlineasm"); self.count_insn("inlineasm");

View File

@ -94,7 +94,7 @@ pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type], atys: &[Type],
rty: Type, rty: Type,
ret_def: bool) -> FnType { ret_def: bool) -> FnType {
match ccx.sess.targ_cfg.arch { match ccx.sess().targ_cfg.arch {
X86 => cabi_x86::compute_abi_info(ccx, atys, rty, ret_def), X86 => cabi_x86::compute_abi_info(ccx, atys, rty, ret_def),
X86_64 => cabi_x86_64::compute_abi_info(ccx, atys, rty, ret_def), X86_64 => cabi_x86_64::compute_abi_info(ccx, atys, rty, ret_def),
Arm => cabi_arm::compute_abi_info(ccx, atys, rty, ret_def), Arm => cabi_arm::compute_abi_info(ccx, atys, rty, ret_def),

View File

@ -36,7 +36,7 @@ pub fn compute_abi_info(ccx: &CrateContext,
// Clang's ABI handling is in lib/CodeGen/TargetInfo.cpp // Clang's ABI handling is in lib/CodeGen/TargetInfo.cpp
enum Strategy { RetValue(Type), RetPointer } enum Strategy { RetValue(Type), RetPointer }
let strategy = match ccx.sess.targ_cfg.os { let strategy = match ccx.sess().targ_cfg.os {
OsWin32 | OsMacos => { OsWin32 | OsMacos => {
match llsize_of_alloc(ccx, rty) { match llsize_of_alloc(ccx, rty) {
1 => RetValue(Type::i8()), 1 => RetValue(Type::i8()),

View File

@ -365,7 +365,7 @@ pub fn trans_fn_ref_with_vtables(
true true
} else if def_id.krate == ast::LOCAL_CRATE { } else if def_id.krate == ast::LOCAL_CRATE {
let map_node = session::expect( let map_node = session::expect(
ccx.sess, ccx.sess(),
ccx.tcx.map.find(def_id.node), ccx.tcx.map.find(def_id.node),
|| format!("local item should be in ast map")); || format!("local item should be in ast map"));

View File

@ -227,7 +227,7 @@ pub fn store_environment<'a>(
for (i, bv) in bound_values.move_iter().enumerate() { for (i, bv) in bound_values.move_iter().enumerate() {
debug!("Copy {} into closure", bv.to_str(ccx)); debug!("Copy {} into closure", bv.to_str(ccx));
if ccx.sess.asm_comments() { if ccx.sess().asm_comments() {
add_comment(bcx, format!("Copy {} into closure", add_comment(bcx, format!("Copy {} into closure",
bv.to_str(ccx))); bv.to_str(ccx)));
} }
@ -301,7 +301,7 @@ fn load_environment<'a>(bcx: &'a Block<'a>, cdata_ty: ty::t,
// Store the pointer to closure data in an alloca for debug info because that's what the // Store the pointer to closure data in an alloca for debug info because that's what the
// llvm.dbg.declare intrinsic expects // llvm.dbg.declare intrinsic expects
let env_pointer_alloca = if bcx.ccx().sess.opts.debuginfo == FullDebugInfo { let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr"); let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr");
Store(bcx, llcdata, alloc); Store(bcx, llcdata, alloc);
Some(alloc) Some(alloc)
@ -419,9 +419,9 @@ pub fn get_wrapper_for_bare_fn(ccx: @CrateContext,
ast::DefFn(did, _) | ast::DefStaticMethod(did, _, _) | ast::DefFn(did, _) | ast::DefStaticMethod(did, _, _) |
ast::DefVariant(_, did, _) | ast::DefStruct(did) => did, ast::DefVariant(_, did, _) | ast::DefStruct(did) => did,
_ => { _ => {
ccx.sess.bug(format!("get_wrapper_for_bare_fn: \ ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
expected a statically resolved fn, got {:?}", expected a statically resolved fn, got {:?}",
def)); def));
} }
}; };
@ -440,9 +440,9 @@ pub fn get_wrapper_for_bare_fn(ccx: @CrateContext,
let f = match ty::get(closure_ty).sty { let f = match ty::get(closure_ty).sty {
ty::ty_closure(ref f) => f, ty::ty_closure(ref f) => f,
_ => { _ => {
ccx.sess.bug(format!("get_wrapper_for_bare_fn: \ ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
expected a closure ty, got {}", expected a closure ty, got {}",
closure_ty.repr(tcx))); closure_ty.repr(tcx)));
} }
}; };

View File

@ -383,13 +383,6 @@ impl<'a> FunctionContext<'a> {
} }
} }
pub fn warn_not_to_commit(ccx: &mut CrateContext, msg: &str) {
if !ccx.do_not_commit_warning_issued.get() {
ccx.do_not_commit_warning_issued.set(true);
ccx.sess.warn(msg.to_str() + " -- do not commit like this!");
}
}
// Heap selectors. Indicate which heap something should go on. // Heap selectors. Indicate which heap something should go on.
#[deriving(Eq)] #[deriving(Eq)]
pub enum heap { pub enum heap {
@ -446,7 +439,7 @@ impl<'a> Block<'a> {
pub fn tcx(&self) -> ty::ctxt { pub fn tcx(&self) -> ty::ctxt {
self.fcx.ccx.tcx self.fcx.ccx.tcx
} }
pub fn sess(&self) -> Session { self.fcx.ccx.sess } pub fn sess(&self) -> &'a Session { self.fcx.ccx.sess() }
pub fn ident(&self, ident: Ident) -> ~str { pub fn ident(&self, ident: Ident) -> ~str {
token::get_ident(ident).get().to_str() token::get_ident(ident).get().to_str()

View File

@ -53,7 +53,7 @@ pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: ast::Lit)
ty::ty_uint(t) => { ty::ty_uint(t) => {
C_integral(Type::uint_from_ty(cx, t), i as u64, false) C_integral(Type::uint_from_ty(cx, t), i as u64, false)
} }
_ => cx.sess.span_bug(lit.span, _ => cx.sess().span_bug(lit.span,
format!("integer literal has type {} (expected int or uint)", format!("integer literal has type {} (expected int or uint)",
ty_to_str(cx.tcx, lit_int_ty))) ty_to_str(cx.tcx, lit_int_ty)))
} }
@ -68,7 +68,7 @@ pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: ast::Lit)
C_floating(fs.get(), Type::float_from_ty(t)) C_floating(fs.get(), Type::float_from_ty(t))
} }
_ => { _ => {
cx.sess.span_bug(lit.span, cx.sess().span_bug(lit.span,
"floating point literal doesn't have the right type"); "floating point literal doesn't have the right type");
} }
} }
@ -147,15 +147,15 @@ fn const_deref(cx: &CrateContext, v: ValueRef, t: ty::t, explicit: bool)
const_deref_newtype(cx, v, t) const_deref_newtype(cx, v, t)
} }
_ => { _ => {
cx.sess.bug(format!("unexpected dereferenceable type {}", cx.sess().bug(format!("unexpected dereferenceable type {}",
ty_to_str(cx.tcx, t))) ty_to_str(cx.tcx, t)))
} }
}; };
(dv, mt.ty) (dv, mt.ty)
} }
None => { None => {
cx.sess.bug(format!("can't dereference const of type {}", cx.sess().bug(format!("can't dereference const of type {}",
ty_to_str(cx.tcx, t))) ty_to_str(cx.tcx, t)))
} }
} }
} }
@ -210,7 +210,7 @@ pub fn const_expr(cx: @CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef
llconst = C_struct([wrapper, C_null(Type::i8p())], false) llconst = C_struct([wrapper, C_null(Type::i8p())], false)
} }
ty::AutoAddEnv(ref r, ref s) => { ty::AutoAddEnv(ref r, ref s) => {
cx.sess cx.sess()
.span_bug(e.span, .span_bug(e.span,
format!("unexpected static function: region \ format!("unexpected static function: region \
{:?} sigil {:?}", {:?} sigil {:?}",
@ -218,7 +218,7 @@ pub fn const_expr(cx: @CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef
*s)) *s))
} }
ty::AutoObject(..) => { ty::AutoObject(..) => {
cx.sess cx.sess()
.span_unimpl(e.span, .span_unimpl(e.span,
"unimplemented const coercion to trait \ "unimplemented const coercion to trait \
object"); object");
@ -266,11 +266,11 @@ pub fn const_expr(cx: @CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef
} }
} }
_ => { _ => {
cx.sess.span_bug(e.span, cx.sess().span_bug(e.span,
format!("unimplemented \ format!("unimplemented \
const autoref \ const autoref \
{:?}", {:?}",
autoref)) autoref))
} }
} }
} }
@ -289,7 +289,7 @@ pub fn const_expr(cx: @CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef
llvm::LLVMDumpValue(llconst); llvm::LLVMDumpValue(llconst);
llvm::LLVMDumpValue(C_undef(llty)); llvm::LLVMDumpValue(C_undef(llty));
} }
cx.sess.bug(format!("const {} of type {} has size {} instead of {}", cx.sess().bug(format!("const {} of type {} has size {} instead of {}",
e.repr(cx.tcx), ty_to_str(cx.tcx, ety), e.repr(cx.tcx), ty_to_str(cx.tcx, ety),
csize, tsize)); csize, tsize));
} }
@ -440,8 +440,8 @@ fn const_expr_unadjusted(cx: @CrateContext, e: &ast::Expr,
let iv = match const_eval::eval_const_expr(cx.tcx, index) { let iv = match const_eval::eval_const_expr(cx.tcx, index) {
const_eval::const_int(i) => i as u64, const_eval::const_int(i) => i as u64,
const_eval::const_uint(u) => u, const_eval::const_uint(u) => u,
_ => cx.sess.span_bug(index.span, _ => cx.sess().span_bug(index.span,
"index is not an integer-constant expression") "index is not an integer-constant expression")
}; };
let (arr, len) = match ty::get(bt).sty { let (arr, len) = match ty::get(bt).sty {
ty::ty_vec(_, vstore) | ty::ty_str(vstore) => ty::ty_vec(_, vstore) | ty::ty_str(vstore) =>
@ -453,11 +453,11 @@ fn const_expr_unadjusted(cx: @CrateContext, e: &ast::Expr,
let e1 = const_get_elt(cx, bv, [0]); let e1 = const_get_elt(cx, bv, [0]);
(const_deref_ptr(cx, e1), const_get_elt(cx, bv, [1])) (const_deref_ptr(cx, e1), const_get_elt(cx, bv, [1]))
}, },
_ => cx.sess.span_bug(base.span, _ => cx.sess().span_bug(base.span,
"index-expr base must be fixed-size or slice") "index-expr base must be fixed-size or slice")
}, },
_ => cx.sess.span_bug(base.span, _ => cx.sess().span_bug(base.span,
"index-expr base must be a vector or string type") "index-expr base must be a vector or string type")
}; };
let len = llvm::LLVMConstIntGetZExtValue(len) as u64; let len = llvm::LLVMConstIntGetZExtValue(len) as u64;
@ -468,8 +468,8 @@ fn const_expr_unadjusted(cx: @CrateContext, e: &ast::Expr,
if iv >= len { if iv >= len {
// FIXME #3170: report this earlier on in the const-eval // FIXME #3170: report this earlier on in the const-eval
// pass. Reporting here is a bit late. // pass. Reporting here is a bit late.
cx.sess.span_err(e.span, cx.sess().span_err(e.span,
"const index-expr is out of bounds"); "const index-expr is out of bounds");
} }
(const_get_elt(cx, arr, [iv as c_uint]), inlineable) (const_get_elt(cx, arr, [iv as c_uint]), inlineable)
} }
@ -511,8 +511,8 @@ fn const_expr_unadjusted(cx: @CrateContext, e: &ast::Expr,
llvm::LLVMConstIntCast(iv, llty.to_ref(), s) llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
} }
expr::cast_float => llvm::LLVMConstUIToFP(iv, llty.to_ref()), expr::cast_float => llvm::LLVMConstUIToFP(iv, llty.to_ref()),
_ => cx.sess.bug("enum cast destination is not \ _ => cx.sess().bug("enum cast destination is not \
integral or float") integral or float")
} }
} }
(expr::cast_pointer, expr::cast_pointer) => { (expr::cast_pointer, expr::cast_pointer) => {
@ -522,8 +522,8 @@ fn const_expr_unadjusted(cx: @CrateContext, e: &ast::Expr,
llvm::LLVMConstIntToPtr(v, llty.to_ref()) llvm::LLVMConstIntToPtr(v, llty.to_ref())
} }
_ => { _ => {
cx.sess.impossible_case(e.span, cx.sess().impossible_case(e.span,
"bad combination of types for cast") "bad combination of types for cast")
} }
}, inlineable) }, inlineable)
} }
@ -558,7 +558,7 @@ fn const_expr_unadjusted(cx: @CrateContext, e: &ast::Expr,
(adt::const_get_field(cx, repr, bv, discr, ix), (adt::const_get_field(cx, repr, bv, discr, ix),
inlineable) inlineable)
} }
None => cx.tcx.sess.span_bug(e.span, "missing struct field") None => cx.sess().span_bug(e.span, "missing struct field")
} }
} }
} }
@ -580,7 +580,7 @@ fn const_expr_unadjusted(cx: @CrateContext, e: &ast::Expr,
ast::ExprLit(ref lit) => { ast::ExprLit(ref lit) => {
match lit.node { match lit.node {
ast::LitStr(..) => { const_expr(cx, sub, is_local) } ast::LitStr(..) => { const_expr(cx, sub, is_local) }
_ => { cx.sess.span_bug(e.span, "bad const-slice lit") } _ => { cx.sess().span_bug(e.span, "bad const-slice lit") }
} }
} }
ast::ExprVec(ref es, ast::MutImmutable) => { ast::ExprVec(ref es, ast::MutImmutable) => {
@ -598,7 +598,7 @@ fn const_expr_unadjusted(cx: @CrateContext, e: &ast::Expr,
let p = const_ptrcast(cx, gv, llunitty); let p = const_ptrcast(cx, gv, llunitty);
(C_struct([p, C_uint(cx, es.len())], false), false) (C_struct([p, C_uint(cx, es.len())], false), false)
} }
_ => cx.sess.span_bug(e.span, "bad const-slice expr") _ => cx.sess().span_bug(e.span, "bad const-slice expr")
} }
} }
ast::ExprRepeat(elem, count, _) => { ast::ExprRepeat(elem, count, _) => {
@ -608,7 +608,7 @@ fn const_expr_unadjusted(cx: @CrateContext, e: &ast::Expr,
let n = match const_eval::eval_const_expr(cx.tcx, count) { let n = match const_eval::eval_const_expr(cx.tcx, count) {
const_eval::const_int(i) => i as uint, const_eval::const_int(i) => i as uint,
const_eval::const_uint(i) => i as uint, const_eval::const_uint(i) => i as uint,
_ => cx.sess.span_bug(count.span, "count must be integral const expression.") _ => cx.sess().span_bug(count.span, "count must be integral const expression.")
}; };
let vs = vec::from_elem(n, const_expr(cx, elem, is_local).val0()); let vs = vec::from_elem(n, const_expr(cx, elem, is_local).val0());
let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) { let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
@ -654,7 +654,7 @@ fn const_expr_unadjusted(cx: @CrateContext, e: &ast::Expr,
(C_null(llty), true) (C_null(llty), true)
} }
_ => { _ => {
cx.sess.span_bug(e.span, "expected a const, fn, struct, or variant def") cx.sess().span_bug(e.span, "expected a const, fn, struct, or variant def")
} }
} }
} }
@ -684,11 +684,11 @@ fn const_expr_unadjusted(cx: @CrateContext, e: &ast::Expr,
vinfo.disr_val, vinfo.disr_val,
arg_vals.as_slice()), inlineable) arg_vals.as_slice()), inlineable)
} }
_ => cx.sess.span_bug(e.span, "expected a struct or variant def") _ => cx.sess().span_bug(e.span, "expected a struct or variant def")
} }
} }
ast::ExprParen(e) => { const_expr(cx, e, is_local) } ast::ExprParen(e) => { const_expr(cx, e, is_local) }
_ => cx.sess.span_bug(e.span, _ => cx.sess().span_bug(e.span,
"bad constant expression type in consts::const_expr") "bad constant expression type in consts::const_expr")
}; };
} }

View File

@ -9,8 +9,8 @@
// except according to those terms. // except according to those terms.
use driver::session;
use driver::session::NoDebugInfo; use driver::session::NoDebugInfo;
use driver::session::Session;
use lib::llvm::{ContextRef, ModuleRef, ValueRef}; use lib::llvm::{ContextRef, ModuleRef, ValueRef};
use lib::llvm::{llvm, TargetData, TypeNames}; use lib::llvm::{llvm, TargetData, TypeNames};
use lib::llvm::mk_target_data; use lib::llvm::mk_target_data;
@ -39,7 +39,6 @@ use syntax::ast;
use syntax::parse::token::InternedString; use syntax::parse::token::InternedString;
pub struct CrateContext { pub struct CrateContext {
sess: session::Session,
llmod: ModuleRef, llmod: ModuleRef,
llcx: ContextRef, llcx: ContextRef,
metadata_llmod: ModuleRef, metadata_llmod: ModuleRef,
@ -115,12 +114,10 @@ pub struct CrateContext {
// is not emitted by LLVM's GC pass when no functions use GC. // is not emitted by LLVM's GC pass when no functions use GC.
uses_gc: bool, uses_gc: bool,
dbg_cx: Option<debuginfo::CrateDebugContext>, dbg_cx: Option<debuginfo::CrateDebugContext>,
do_not_commit_warning_issued: Cell<bool>,
} }
impl CrateContext { impl CrateContext {
pub fn new(sess: session::Session, pub fn new(name: &str,
name: &str,
tcx: ty::ctxt, tcx: ty::ctxt,
emap2: resolve::ExportMap2, emap2: resolve::ExportMap2,
maps: astencode::Maps, maps: astencode::Maps,
@ -137,8 +134,8 @@ impl CrateContext {
let metadata_llmod = format!("{}_metadata", name).with_c_str(|buf| { let metadata_llmod = format!("{}_metadata", name).with_c_str(|buf| {
llvm::LLVMModuleCreateWithNameInContext(buf, llcx) llvm::LLVMModuleCreateWithNameInContext(buf, llcx)
}); });
let data_layout: &str = sess.targ_cfg.target_strs.data_layout; let data_layout: &str = tcx.sess.targ_cfg.target_strs.data_layout;
let targ_triple: &str = sess.targ_cfg.target_strs.target_triple; let targ_triple: &str = tcx.sess.targ_cfg.target_strs.target_triple;
data_layout.with_c_str(|buf| { data_layout.with_c_str(|buf| {
llvm::LLVMSetDataLayout(llmod, buf); llvm::LLVMSetDataLayout(llmod, buf);
llvm::LLVMSetDataLayout(metadata_llmod, buf); llvm::LLVMSetDataLayout(metadata_llmod, buf);
@ -147,13 +144,13 @@ impl CrateContext {
llvm::LLVMRustSetNormalizedTarget(llmod, buf); llvm::LLVMRustSetNormalizedTarget(llmod, buf);
llvm::LLVMRustSetNormalizedTarget(metadata_llmod, buf); llvm::LLVMRustSetNormalizedTarget(metadata_llmod, buf);
}); });
let targ_cfg = sess.targ_cfg; let targ_cfg = tcx.sess.targ_cfg;
let td = mk_target_data(sess.targ_cfg.target_strs.data_layout); let td = mk_target_data(tcx.sess.targ_cfg.target_strs.data_layout);
let tn = TypeNames::new(); let tn = TypeNames::new();
let mut intrinsics = base::declare_intrinsics(llmod); let mut intrinsics = base::declare_intrinsics(llmod);
if sess.opts.debuginfo != NoDebugInfo { if tcx.sess.opts.debuginfo != NoDebugInfo {
base::declare_dbg_intrinsics(llmod, &mut intrinsics); base::declare_dbg_intrinsics(llmod, &mut intrinsics);
} }
let int_type = Type::int(targ_cfg.arch); let int_type = Type::int(targ_cfg.arch);
@ -166,19 +163,18 @@ impl CrateContext {
tn.associate_type("tydesc", &tydesc_type); tn.associate_type("tydesc", &tydesc_type);
tn.associate_type("str_slice", &str_slice_ty); tn.associate_type("str_slice", &str_slice_ty);
let (crate_map_name, crate_map) = decl_crate_map(sess, link_meta.clone(), llmod); let (crate_map_name, crate_map) = decl_crate_map(&tcx.sess, link_meta.clone(), llmod);
let dbg_cx = if sess.opts.debuginfo != NoDebugInfo { let dbg_cx = if tcx.sess.opts.debuginfo != NoDebugInfo {
Some(debuginfo::CrateDebugContext::new(llmod)) Some(debuginfo::CrateDebugContext::new(llmod))
} else { } else {
None None
}; };
if sess.count_llvm_insns() { if tcx.sess.count_llvm_insns() {
base::init_insn_ctxt() base::init_insn_ctxt()
} }
CrateContext { CrateContext {
sess: sess,
llmod: llmod, llmod: llmod,
llcx: llcx, llcx: llcx,
metadata_llmod: metadata_llmod, metadata_llmod: metadata_llmod,
@ -235,11 +231,14 @@ impl CrateContext {
crate_map_name: crate_map_name, crate_map_name: crate_map_name,
uses_gc: false, uses_gc: false,
dbg_cx: dbg_cx, dbg_cx: dbg_cx,
do_not_commit_warning_issued: Cell::new(false),
} }
} }
} }
pub fn sess<'a>(&'a self) -> &'a Session {
&self.tcx.sess
}
pub fn builder<'a>(&'a self) -> Builder<'a> { pub fn builder<'a>(&'a self) -> Builder<'a> {
Builder::new(self) Builder::new(self)
} }

View File

@ -213,10 +213,10 @@ impl FunctionDebugContext {
match *self { match *self {
FunctionDebugContext(~ref data) => data, FunctionDebugContext(~ref data) => data,
DebugInfoDisabled => { DebugInfoDisabled => {
cx.sess.span_bug(span, FunctionDebugContext::debuginfo_disabled_message()); cx.sess().span_bug(span, FunctionDebugContext::debuginfo_disabled_message());
} }
FunctionWithoutDebugInfo => { FunctionWithoutDebugInfo => {
cx.sess.span_bug(span, FunctionDebugContext::should_be_ignored_message()); cx.sess().span_bug(span, FunctionDebugContext::should_be_ignored_message());
} }
} }
} }
@ -268,7 +268,7 @@ pub fn finalize(cx: @CrateContext) {
// instruct LLVM to emit an older version of dwarf, however, // instruct LLVM to emit an older version of dwarf, however,
// for OS X to understand. For more info see #11352 // for OS X to understand. For more info see #11352
// This can be overridden using --llvm-opts -dwarf-version,N. // This can be overridden using --llvm-opts -dwarf-version,N.
if cx.sess.targ_cfg.os == abi::OsMacos { if cx.sess().targ_cfg.os == abi::OsMacos {
"Dwarf Version".with_c_str( "Dwarf Version".with_c_str(
|s| llvm::LLVMRustAddModuleFlag(cx.llmod, s, 2)); |s| llvm::LLVMRustAddModuleFlag(cx.llmod, s, 2));
} }
@ -299,7 +299,7 @@ pub fn create_local_var_metadata(bcx: &Block, local: &ast::Local) {
match lllocals.get().find_copy(&node_id) { match lllocals.get().find_copy(&node_id) {
Some(datum) => datum, Some(datum) => datum,
None => { None => {
bcx.tcx().sess.span_bug(span, bcx.sess().span_bug(span,
format!("no entry in lllocals table for {:?}", format!("no entry in lllocals table for {:?}",
node_id)); node_id));
} }
@ -338,7 +338,7 @@ pub fn create_captured_var_metadata(bcx: &Block,
let variable_ident = match ast_item { let variable_ident = match ast_item {
None => { None => {
cx.sess.span_bug(span, "debuginfo::create_captured_var_metadata() - NodeId not found"); cx.sess().span_bug(span, "debuginfo::create_captured_var_metadata: node not found");
} }
Some(ast_map::NodeLocal(pat)) | Some(ast_map::NodeArg(pat)) => { Some(ast_map::NodeLocal(pat)) | Some(ast_map::NodeArg(pat)) => {
match pat.node { match pat.node {
@ -346,7 +346,7 @@ pub fn create_captured_var_metadata(bcx: &Block,
ast_util::path_to_ident(path) ast_util::path_to_ident(path)
} }
_ => { _ => {
cx.sess cx.sess()
.span_bug(span, .span_bug(span,
format!( format!(
"debuginfo::create_captured_var_metadata() - \ "debuginfo::create_captured_var_metadata() - \
@ -357,7 +357,7 @@ pub fn create_captured_var_metadata(bcx: &Block,
} }
} }
_ => { _ => {
cx.sess.span_bug(span, format!("debuginfo::create_captured_var_metadata() - \ cx.sess().span_bug(span, format!("debuginfo::create_captured_var_metadata() - \
Captured var-id refers to unexpected ast_map variant: {:?}", ast_item)); Captured var-id refers to unexpected ast_map variant: {:?}", ast_item));
} }
}; };
@ -441,7 +441,7 @@ pub fn create_argument_metadata(bcx: &Block, arg: &ast::Arg) {
match llargs.get().find_copy(&node_id) { match llargs.get().find_copy(&node_id) {
Some(v) => v, Some(v) => v,
None => { None => {
bcx.tcx().sess.span_bug(span, bcx.sess().span_bug(span,
format!("no entry in llargs table for {:?}", format!("no entry in llargs table for {:?}",
node_id)); node_id));
} }
@ -449,7 +449,7 @@ pub fn create_argument_metadata(bcx: &Block, arg: &ast::Arg) {
}; };
if unsafe { llvm::LLVMIsAAllocaInst(llarg.val) } == ptr::null() { if unsafe { llvm::LLVMIsAAllocaInst(llarg.val) } == ptr::null() {
cx.sess.span_bug(span, "debuginfo::create_argument_metadata() - \ cx.sess().span_bug(span, "debuginfo::create_argument_metadata() - \
Referenced variable location is not an alloca!"); Referenced variable location is not an alloca!");
} }
@ -485,7 +485,7 @@ pub fn set_source_location(fcx: &FunctionContext,
let cx = fcx.ccx; let cx = fcx.ccx;
debug!("set_source_location: {}", cx.sess.codemap.span_to_str(span)); debug!("set_source_location: {}", cx.sess().codemap.span_to_str(span));
if fcx.debug_context.get_ref(cx, span).source_locations_enabled.get() { if fcx.debug_context.get_ref(cx, span).source_locations_enabled.get() {
let loc = span_start(cx, span); let loc = span_start(cx, span);
@ -532,7 +532,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
fn_ast_id: ast::NodeId, fn_ast_id: ast::NodeId,
param_substs: Option<@param_substs>, param_substs: Option<@param_substs>,
llfn: ValueRef) -> FunctionDebugContext { llfn: ValueRef) -> FunctionDebugContext {
if cx.sess.opts.debuginfo == NoDebugInfo { if cx.sess().opts.debuginfo == NoDebugInfo {
return DebugInfoDisabled; return DebugInfoDisabled;
} }
@ -551,7 +551,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
(item.ident, fn_decl, generics, top_level_block, item.span, true) (item.ident, fn_decl, generics, top_level_block, item.span, true)
} }
_ => { _ => {
cx.sess.span_bug(item.span, cx.sess().span_bug(item.span,
"create_function_debug_context: item bound to non-function"); "create_function_debug_context: item bound to non-function");
} }
} }
@ -579,7 +579,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
// Don't try to lookup the item path: // Don't try to lookup the item path:
false) false)
} }
_ => cx.sess.span_bug(expr.span, _ => cx.sess().span_bug(expr.span,
"create_function_debug_context: expected an expr_fn_block here") "create_function_debug_context: expected an expr_fn_block here")
} }
} }
@ -594,7 +594,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
true) true)
} }
_ => { _ => {
cx.sess cx.sess()
.bug(format!("create_function_debug_context: \ .bug(format!("create_function_debug_context: \
unexpected sort of node: {:?}", unexpected sort of node: {:?}",
fnitem)) fnitem))
@ -606,8 +606,8 @@ pub fn create_function_debug_context(cx: &CrateContext,
ast_map::NodeStructCtor(..) => { ast_map::NodeStructCtor(..) => {
return FunctionWithoutDebugInfo; return FunctionWithoutDebugInfo;
} }
_ => cx.sess.bug(format!("create_function_debug_context: \ _ => cx.sess().bug(format!("create_function_debug_context: \
unexpected sort of node: {:?}", fnitem)) unexpected sort of node: {:?}", fnitem))
}; };
// This can be the case for functions inlined from another crate // This can be the case for functions inlined from another crate
@ -672,7 +672,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
true, true,
scope_line as c_uint, scope_line as c_uint,
FlagPrototyped as c_uint, FlagPrototyped as c_uint,
cx.sess.opts.optimize != session::No, cx.sess().opts.optimize != session::No,
llfn, llfn,
template_parameters, template_parameters,
ptr::null()) ptr::null())
@ -708,7 +708,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
fn_decl: &ast::FnDecl, fn_decl: &ast::FnDecl,
param_substs: Option<@param_substs>, param_substs: Option<@param_substs>,
error_span: Span) -> DIArray { error_span: Span) -> DIArray {
if cx.sess.opts.debuginfo == LimitedDebugInfo { if cx.sess().opts.debuginfo == LimitedDebugInfo {
return create_DIArray(DIB(cx), []); return create_DIArray(DIB(cx), []);
} }
@ -793,7 +793,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
} }
// Only create type information if full debuginfo is enabled // Only create type information if full debuginfo is enabled
if cx.sess.opts.debuginfo == FullDebugInfo { if cx.sess().opts.debuginfo == FullDebugInfo {
let actual_self_type_metadata = type_metadata(cx, let actual_self_type_metadata = type_metadata(cx,
actual_self_type, actual_self_type,
codemap::DUMMY_SP); codemap::DUMMY_SP);
@ -837,7 +837,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
} }
// Again, only create type information if full debuginfo is enabled // Again, only create type information if full debuginfo is enabled
if cx.sess.opts.debuginfo == FullDebugInfo { if cx.sess().opts.debuginfo == FullDebugInfo {
let actual_type_metadata = type_metadata(cx, actual_type, codemap::DUMMY_SP); let actual_type_metadata = type_metadata(cx, actual_type, codemap::DUMMY_SP);
let param_metadata = token::get_ident(ident).get() let param_metadata = token::get_ident(ident).get()
.with_c_str(|name| { .with_c_str(|name| {
@ -873,12 +873,12 @@ fn create_DIArray(builder: DIBuilderRef, arr: &[DIDescriptor]) -> DIArray {
} }
fn compile_unit_metadata(cx: &CrateContext) { fn compile_unit_metadata(cx: &CrateContext) {
let work_dir = &cx.sess.working_dir; let work_dir = &cx.sess().working_dir;
let compile_unit_name = match cx.sess.local_crate_source_file { let compile_unit_name = match cx.sess().local_crate_source_file {
None => fallback_path(cx), None => fallback_path(cx),
Some(ref abs_path) => { Some(ref abs_path) => {
if abs_path.is_relative() { if abs_path.is_relative() {
cx.sess.warn("debuginfo: Invalid path to crate's local root source file!"); cx.sess().warn("debuginfo: Invalid path to crate's local root source file!");
fallback_path(cx) fallback_path(cx)
} else { } else {
match abs_path.path_relative_from(work_dir) { match abs_path.path_relative_from(work_dir) {
@ -917,7 +917,7 @@ fn compile_unit_metadata(cx: &CrateContext) {
compile_unit_name, compile_unit_name,
work_dir, work_dir,
producer, producer,
cx.sess.opts.optimize != session::No, cx.sess().opts.optimize != session::No,
flags, flags,
0, 0,
split_name); split_name);
@ -968,7 +968,7 @@ fn declare_local(bcx: &Block,
file_metadata, file_metadata,
loc.line as c_uint, loc.line as c_uint,
type_metadata, type_metadata,
cx.sess.opts.optimize != session::No, cx.sess().opts.optimize != session::No,
0, 0,
argument_index) argument_index)
} }
@ -1028,7 +1028,7 @@ fn file_metadata(cx: &CrateContext, full_path: &str) -> DIFile {
debug!("file_metadata: {}", full_path); debug!("file_metadata: {}", full_path);
// FIXME (#9639): This needs to handle non-utf8 paths // FIXME (#9639): This needs to handle non-utf8 paths
let work_dir = cx.sess.working_dir.as_str().unwrap(); let work_dir = cx.sess().working_dir.as_str().unwrap();
let file_name = let file_name =
if full_path.starts_with(work_dir) { if full_path.starts_with(work_dir) {
full_path.slice(work_dir.len() + 1u, full_path.len()) full_path.slice(work_dir.len() + 1u, full_path.len())
@ -1063,7 +1063,7 @@ fn scope_metadata(fcx: &FunctionContext,
None => { None => {
let node = fcx.ccx.tcx.map.get(node_id); let node = fcx.ccx.tcx.map.get(node_id);
fcx.ccx.sess.span_bug(span, fcx.ccx.sess().span_bug(span,
format!("debuginfo: Could not find scope info for node {:?}", node)); format!("debuginfo: Could not find scope info for node {:?}", node));
} }
} }
@ -1096,7 +1096,7 @@ fn basic_type_metadata(cx: &CrateContext, t: ty::t) -> DIType {
ast::TyF32 => (~"f32", DW_ATE_float), ast::TyF32 => (~"f32", DW_ATE_float),
ast::TyF64 => (~"f64", DW_ATE_float) ast::TyF64 => (~"f64", DW_ATE_float)
}, },
_ => cx.sess.bug("debuginfo::basic_type_metadata - t is invalid type") _ => cx.sess().bug("debuginfo::basic_type_metadata - t is invalid type")
}; };
let llvm_type = type_of::type_of(cx, t); let llvm_type = type_of::type_of(cx, t);
@ -1329,7 +1329,7 @@ impl GeneralMemberDescriptionFactory {
// Capture type_rep, so we don't have to copy the struct_defs array // Capture type_rep, so we don't have to copy the struct_defs array
let struct_defs = match *self.type_rep { let struct_defs = match *self.type_rep {
adt::General(_, ref struct_defs) => struct_defs, adt::General(_, ref struct_defs) => struct_defs,
_ => cx.sess.bug("unreachable") _ => cx.sess().bug("unreachable")
}; };
struct_defs struct_defs
@ -1653,9 +1653,9 @@ fn set_members_of_composite_type(cx: &CrateContext,
let mut composite_types_completed = let mut composite_types_completed =
debug_context(cx).composite_types_completed.borrow_mut(); debug_context(cx).composite_types_completed.borrow_mut();
if composite_types_completed.get().contains(&composite_type_metadata) { if composite_types_completed.get().contains(&composite_type_metadata) {
cx.sess.span_bug(definition_span, "debuginfo::set_members_of_composite_type() - \ cx.sess().span_bug(definition_span, "debuginfo::set_members_of_composite_type() - \
Already completed forward declaration \ Already completed forward declaration \
re-encountered."); re-encountered.");
} else { } else {
composite_types_completed.get().insert(composite_type_metadata); composite_types_completed.get().insert(composite_type_metadata);
} }
@ -1856,7 +1856,7 @@ fn vec_metadata(cx: &CrateContext,
let element_llvm_type = type_of::type_of(cx, element_type); let element_llvm_type = type_of::type_of(cx, element_type);
let (element_size, element_align) = size_and_align_of(cx, element_llvm_type); let (element_size, element_align) = size_and_align_of(cx, element_llvm_type);
let vec_llvm_type = Type::vec(cx.sess.targ_cfg.arch, &element_llvm_type); let vec_llvm_type = Type::vec(cx.sess().targ_cfg.arch, &element_llvm_type);
let vec_type_name: &str = format!("[{}]", ppaux::ty_to_str(cx.tcx, element_type)); let vec_type_name: &str = format!("[{}]", ppaux::ty_to_str(cx.tcx, element_type));
let member_llvm_types = vec_llvm_type.field_types(); let member_llvm_types = vec_llvm_type.field_types();
@ -2144,7 +2144,7 @@ fn type_metadata(cx: &CrateContext,
elements.as_slice(), elements.as_slice(),
usage_site_span).finalize(cx) usage_site_span).finalize(cx)
} }
_ => cx.sess.bug(format!("debuginfo: unexpected type in type_metadata: {:?}", sty)) _ => cx.sess().bug(format!("debuginfo: unexpected type in type_metadata: {:?}", sty))
}; };
let mut created_types = debug_context(cx).created_types.borrow_mut(); let mut created_types = debug_context(cx).created_types.borrow_mut();
@ -2218,7 +2218,7 @@ fn generate_unique_type_id(prefix: &'static str) -> ~str {
/// Return codemap::Loc corresponding to the beginning of the span /// Return codemap::Loc corresponding to the beginning of the span
fn span_start(cx: &CrateContext, span: Span) -> codemap::Loc { fn span_start(cx: &CrateContext, span: Span) -> codemap::Loc {
cx.sess.codemap.lookup_char_pos(span.lo) cx.sess().codemap.lookup_char_pos(span.lo)
} }
fn size_and_align_of(cx: &CrateContext, llvm_type: Type) -> (u64, u64) { fn size_and_align_of(cx: &CrateContext, llvm_type: Type) -> (u64, u64) {
@ -2250,7 +2250,7 @@ fn fn_should_be_ignored(fcx: &FunctionContext) -> bool {
fn assert_type_for_node_id(cx: &CrateContext, node_id: ast::NodeId, error_span: Span) { fn assert_type_for_node_id(cx: &CrateContext, node_id: ast::NodeId, error_span: Span) {
let node_types = cx.tcx.node_types.borrow(); let node_types = cx.tcx.node_types.borrow();
if !node_types.get().contains_key(&(node_id as uint)) { if !node_types.get().contains_key(&(node_id as uint)) {
cx.sess.span_bug(error_span, "debuginfo: Could not find type for node id!"); cx.sess().span_bug(error_span, "debuginfo: Could not find type for node id!");
} }
} }
@ -2315,7 +2315,7 @@ fn populate_scope_map(cx: &CrateContext,
&mut Vec<ScopeStackEntry> , &mut Vec<ScopeStackEntry> ,
&mut HashMap<ast::NodeId, DIScope>|) { &mut HashMap<ast::NodeId, DIScope>|) {
// Create a new lexical scope and push it onto the stack // Create a new lexical scope and push it onto the stack
let loc = cx.sess.codemap.lookup_char_pos(scope_span.lo); let loc = cx.sess().codemap.lookup_char_pos(scope_span.lo);
let file_metadata = file_metadata(cx, loc.file.name); let file_metadata = file_metadata(cx, loc.file.name);
let parent_scope = scope_stack.last().unwrap().scope_metadata; let parent_scope = scope_stack.last().unwrap().scope_metadata;
@ -2338,7 +2338,7 @@ fn populate_scope_map(cx: &CrateContext,
} }
if scope_stack.last().unwrap().scope_metadata != scope_metadata { if scope_stack.last().unwrap().scope_metadata != scope_metadata {
cx.sess.span_bug(scope_span, "debuginfo: Inconsistency in scope management."); cx.sess().span_bug(scope_span, "debuginfo: Inconsistency in scope management.");
} }
scope_stack.pop(); scope_stack.pop();
@ -2432,7 +2432,7 @@ fn populate_scope_map(cx: &CrateContext,
if need_new_scope { if need_new_scope {
// Create a new lexical scope and push it onto the stack // Create a new lexical scope and push it onto the stack
let loc = cx.sess.codemap.lookup_char_pos(pat.span.lo); let loc = cx.sess().codemap.lookup_char_pos(pat.span.lo);
let file_metadata = file_metadata(cx, loc.file.name); let file_metadata = file_metadata(cx, loc.file.name);
let parent_scope = scope_stack.last().unwrap().scope_metadata; let parent_scope = scope_stack.last().unwrap().scope_metadata;
@ -2614,13 +2614,13 @@ fn populate_scope_map(cx: &CrateContext,
} }
ast::ExprForLoop(_, _, _, _) => { ast::ExprForLoop(_, _, _, _) => {
cx.sess.span_bug(exp.span, "debuginfo::populate_scope_map() - \ cx.sess().span_bug(exp.span, "debuginfo::populate_scope_map() - \
Found unexpanded for-loop."); Found unexpanded for-loop.");
} }
ast::ExprMac(_) => { ast::ExprMac(_) => {
cx.sess.span_bug(exp.span, "debuginfo::populate_scope_map() - \ cx.sess().span_bug(exp.span, "debuginfo::populate_scope_map() - \
Found unexpanded macro."); Found unexpanded macro.");
} }
ast::ExprLoop(block, _) | ast::ExprLoop(block, _) |
@ -2827,7 +2827,7 @@ fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> @NamespaceTreeNo
match parent_node { match parent_node {
Some(node) => node, Some(node) => node,
None => { None => {
cx.sess.bug(format!("debuginfo::namespace_for_item(): \ cx.sess().bug(format!("debuginfo::namespace_for_item(): \
path too short for {:?}", def_id)); path too short for {:?}", def_id));
} }
} }

View File

@ -581,7 +581,7 @@ fn trans_def<'a>(bcx: &'a Block<'a>,
unsafe { unsafe {
let llty = type_of::type_of(bcx.ccx(), const_ty); let llty = type_of::type_of(bcx.ccx(), const_ty);
let symbol = csearch::get_symbol( let symbol = csearch::get_symbol(
bcx.ccx().sess.cstore, bcx.ccx().sess().cstore,
did); did);
let llval = symbol.with_c_str(|buf| { let llval = symbol.with_c_str(|buf| {
llvm::LLVMAddGlobal(bcx.ccx().llmod, llvm::LLVMAddGlobal(bcx.ccx().llmod,
@ -1618,16 +1618,16 @@ fn trans_imm_cast<'a>(bcx: &'a Block<'a>,
val_ty(lldiscrim_a), val_ty(lldiscrim_a),
lldiscrim_a, true), lldiscrim_a, true),
cast_float => SIToFP(bcx, lldiscrim_a, ll_t_out), cast_float => SIToFP(bcx, lldiscrim_a, ll_t_out),
_ => ccx.sess.bug(format!("translating unsupported cast: \ _ => ccx.sess().bug(format!("translating unsupported cast: \
{} ({:?}) -> {} ({:?})", {} ({:?}) -> {} ({:?})",
t_in.repr(ccx.tcx), k_in, t_in.repr(ccx.tcx), k_in,
t_out.repr(ccx.tcx), k_out)) t_out.repr(ccx.tcx), k_out))
} }
} }
_ => ccx.sess.bug(format!("translating unsupported cast: \ _ => ccx.sess().bug(format!("translating unsupported cast: \
{} ({:?}) -> {} ({:?})", {} ({:?}) -> {} ({:?})",
t_in.repr(ccx.tcx), k_in, t_in.repr(ccx.tcx), k_in,
t_out.repr(ccx.tcx), k_out)) t_out.repr(ccx.tcx), k_out))
}; };
return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock(); return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
} }
@ -1665,7 +1665,6 @@ fn trans_assign_op<'a>(
return result_datum.store_to(bcx, dst_datum.val); return result_datum.store_to(bcx, dst_datum.val);
} }
fn auto_ref<'a>(bcx: &'a Block<'a>, fn auto_ref<'a>(bcx: &'a Block<'a>,
datum: Datum<Expr>, datum: Datum<Expr>,
expr: &ast::Expr) expr: &ast::Expr)

View File

@ -75,23 +75,23 @@ struct LlvmSignature {
pub fn llvm_calling_convention(ccx: &CrateContext, pub fn llvm_calling_convention(ccx: &CrateContext,
abis: AbiSet) -> Option<CallConv> { abis: AbiSet) -> Option<CallConv> {
let os = ccx.sess.targ_cfg.os; let os = ccx.sess().targ_cfg.os;
let arch = ccx.sess.targ_cfg.arch; let arch = ccx.sess().targ_cfg.arch;
abis.for_target(os, arch).map(|abi| { abis.for_target(os, arch).map(|abi| {
match abi { match abi {
RustIntrinsic => { RustIntrinsic => {
// Intrinsics are emitted by monomorphic fn // Intrinsics are emitted by monomorphic fn
ccx.sess.bug(format!("asked to register intrinsic fn")); ccx.sess().bug(format!("asked to register intrinsic fn"));
} }
Rust => { Rust => {
// FIXME(#3678) Implement linking to foreign fns with Rust ABI // FIXME(#3678) Implement linking to foreign fns with Rust ABI
ccx.sess.unimpl( ccx.sess().unimpl(
format!("foreign functions with Rust ABI")); format!("foreign functions with Rust ABI"));
} }
// It's the ABI's job to select this, not us. // It's the ABI's job to select this, not us.
System => ccx.sess.bug("system abi should be selected elsewhere"), System => ccx.sess().bug("system abi should be selected elsewhere"),
Stdcall => lib::llvm::X86StdcallCallConv, Stdcall => lib::llvm::X86StdcallCallConv,
Fastcall => lib::llvm::X86FastcallCallConv, Fastcall => lib::llvm::X86FastcallCallConv,
@ -222,7 +222,7 @@ pub fn register_foreign_item_fn(ccx: @CrateContext, abis: AbiSet,
let cc = match llvm_calling_convention(ccx, abis) { let cc = match llvm_calling_convention(ccx, abis) {
Some(cc) => cc, Some(cc) => cc,
None => { None => {
ccx.sess.span_fatal(foreign_item.span, ccx.sess().span_fatal(foreign_item.span,
format!("ABI `{}` has no suitable calling convention \ format!("ABI `{}` has no suitable calling convention \
for target architecture", for target architecture",
abis.user_string(ccx.tcx))); abis.user_string(ccx.tcx)));
@ -294,7 +294,7 @@ pub fn trans_native_call<'a>(
let (fn_abis, fn_sig) = match ty::get(callee_ty).sty { let (fn_abis, fn_sig) = match ty::get(callee_ty).sty {
ty::ty_bare_fn(ref fn_ty) => (fn_ty.abis, fn_ty.sig.clone()), ty::ty_bare_fn(ref fn_ty) => (fn_ty.abis, fn_ty.sig.clone()),
_ => ccx.sess.bug("trans_native_call called on non-function type") _ => ccx.sess().bug("trans_native_call called on non-function type")
}; };
let llsig = foreign_signature(ccx, &fn_sig, passed_arg_tys.as_slice()); let llsig = foreign_signature(ccx, &fn_sig, passed_arg_tys.as_slice());
let ret_def = !return_type_is_void(bcx.ccx(), fn_sig.output); let ret_def = !return_type_is_void(bcx.ccx(), fn_sig.output);
@ -383,7 +383,7 @@ pub fn trans_native_call<'a>(
Some(cc) => cc, Some(cc) => cc,
None => { None => {
// FIXME(#8357) We really ought to report a span here // FIXME(#8357) We really ought to report a span here
ccx.sess.fatal( ccx.sess().fatal(
format!("ABI string `{}` has no suitable ABI \ format!("ABI string `{}` has no suitable ABI \
for target architecture", for target architecture",
fn_abis.user_string(ccx.tcx))); fn_abis.user_string(ccx.tcx)));
@ -563,10 +563,10 @@ pub fn trans_rust_fn_with_foreign_abi(ccx: @CrateContext,
f f
} }
_ => { _ => {
ccx.sess.bug(format!("build_rust_fn: extern fn {} has ty {}, \ ccx.sess().bug(format!("build_rust_fn: extern fn {} has ty {}, \
expected a bare fn ty", expected a bare fn ty",
ccx.tcx.map.path_to_str(id), ccx.tcx.map.path_to_str(id),
t.repr(tcx))); t.repr(tcx)));
} }
}; };
@ -860,7 +860,7 @@ fn foreign_types_for_fn_ty(ccx: &CrateContext,
ty: ty::t) -> ForeignTypes { ty: ty::t) -> ForeignTypes {
let fn_sig = match ty::get(ty).sty { let fn_sig = match ty::get(ty).sty {
ty::ty_bare_fn(ref fn_ty) => fn_ty.sig.clone(), ty::ty_bare_fn(ref fn_ty) => fn_ty.sig.clone(),
_ => ccx.sess.bug("foreign_types_for_fn_ty called on non-function type") _ => ccx.sess().bug("foreign_types_for_fn_ty called on non-function type")
}; };
let llsig = foreign_signature(ccx, &fn_sig, fn_sig.inputs.as_slice()); let llsig = foreign_signature(ccx, &fn_sig, fn_sig.inputs.as_slice());
let ret_def = !return_type_is_void(ccx, fn_sig.output); let ret_def = !return_type_is_void(ccx, fn_sig.output);

View File

@ -173,7 +173,7 @@ pub fn call_visit_glue(bcx: &Block, v: ValueRef, tydesc: ValueRef,
let ccx = bcx.ccx(); let ccx = bcx.ccx();
// NB: Don't short-circuit even if this block is unreachable because // NB: Don't short-circuit even if this block is unreachable because
// GC-based cleanup needs to the see that the roots are live. // GC-based cleanup needs to the see that the roots are live.
if bcx.unreachable.get() && !ccx.sess.no_landing_pads() { return; } if bcx.unreachable.get() && !ccx.sess().no_landing_pads() { return; }
let static_glue_fn = match static_ti { let static_glue_fn = match static_ti {
None => None, None => None,
@ -403,7 +403,7 @@ pub fn declare_tydesc(ccx: &CrateContext, t: ty::t) -> @tydesc_info {
let llty = type_of(ccx, t); let llty = type_of(ccx, t);
if ccx.sess.count_type_sizes() { if ccx.sess().count_type_sizes() {
println!("{}\t{}", llsize_of_real(ccx, llty), println!("{}\t{}", llsize_of_real(ccx, llty),
ppaux::ty_to_str(ccx.tcx, t)); ppaux::ty_to_str(ccx.tcx, t));
} }

View File

@ -122,14 +122,14 @@ pub fn maybe_instantiate_inline(ccx: @CrateContext, fn_id: ast::DefId)
} }
} }
} }
_ => ccx.sess.bug("maybe_instantiate_inline: item has a \ _ => ccx.sess().bug("maybe_instantiate_inline: item has a \
non-enum, non-struct parent") non-enum, non-struct parent")
} }
trans_item(ccx, item); trans_item(ccx, item);
local_def(my_id) local_def(my_id)
} }
csearch::found_parent(_, _) => { csearch::found_parent(_, _) => {
ccx.sess.bug("maybe_get_item_ast returned a found_parent \ ccx.sess().bug("maybe_get_item_ast returned a found_parent \
with a non-item parent"); with a non-item parent");
} }
csearch::found(ast::IIMethod(impl_did, is_provided, mth)) => { csearch::found(ast::IIMethod(impl_did, is_provided, mth)) => {

View File

@ -218,7 +218,7 @@ pub fn trans_intrinsic(ccx: @CrateContext,
"acq" => lib::llvm::Acquire, "acq" => lib::llvm::Acquire,
"rel" => lib::llvm::Release, "rel" => lib::llvm::Release,
"acqrel" => lib::llvm::AcquireRelease, "acqrel" => lib::llvm::AcquireRelease,
_ => ccx.sess.fatal("unknown ordering in atomic intrinsic") _ => ccx.sess().fatal("unknown ordering in atomic intrinsic")
} }
}; };
@ -259,7 +259,7 @@ pub fn trans_intrinsic(ccx: @CrateContext,
"min" => lib::llvm::Min, "min" => lib::llvm::Min,
"umax" => lib::llvm::UMax, "umax" => lib::llvm::UMax,
"umin" => lib::llvm::UMin, "umin" => lib::llvm::UMin,
_ => ccx.sess.fatal("unknown atomic operation") _ => ccx.sess().fatal("unknown atomic operation")
}; };
let old = AtomicRMW(bcx, atom_op, get_param(decl, first_real_arg), let old = AtomicRMW(bcx, atom_op, get_param(decl, first_real_arg),
@ -377,7 +377,7 @@ pub fn trans_intrinsic(ccx: @CrateContext,
ast_map::NodeExpr(e) => e.span, ast_map::NodeExpr(e) => e.span,
_ => fail!("transmute has non-expr arg"), _ => fail!("transmute has non-expr arg"),
}; };
ccx.sess.span_fatal(sp, ccx.sess().span_fatal(sp,
format!("transmute called on types with different sizes: \ format!("transmute called on types with different sizes: \
{intype} ({insize, plural, =1{# bit} other{# bits}}) to \ {intype} ({insize, plural, =1{# bit} other{# bits}}) to \
{outtype} ({outsize, plural, =1{# bit} other{# bits}})", {outtype} ({outsize, plural, =1{# bit} other{# bits}})",
@ -527,7 +527,7 @@ pub fn trans_intrinsic(ccx: @CrateContext,
_ => { _ => {
// Could we make this an enum rather than a string? does it get // Could we make this an enum rather than a string? does it get
// checked earlier? // checked earlier?
ccx.sess.span_bug(item.span, "unknown intrinsic"); ccx.sess().span_bug(item.span, "unknown intrinsic");
} }
} }
fcx.cleanup(); fcx.cleanup();

View File

@ -108,8 +108,8 @@ pub fn trans_method_callee<'a>(
(method.origin, method.ty) (method.origin, method.ty)
} }
None => { None => {
bcx.tcx().sess.span_bug(bcx.tcx().map.span(method_call.expr_id), bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
"method call expr wasn't in method map") "method call expr wasn't in method map")
} }
}; };
@ -145,9 +145,9 @@ pub fn trans_method_callee<'a>(
let self_expr = match self_expr { let self_expr = match self_expr {
Some(self_expr) => self_expr, Some(self_expr) => self_expr,
None => { None => {
bcx.tcx().sess.span_bug(bcx.tcx().map.span(method_call.expr_id), bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
"self expr wasn't provided for trait object \ "self expr wasn't provided for trait object \
callee (trying to call overloaded op?)") callee (trying to call overloaded op?)")
} }
}; };
trans_trait_callee(bcx, trans_trait_callee(bcx,
@ -425,7 +425,7 @@ pub fn trans_trait_callee_from_llval<'a>(bcx: &'a Block<'a>,
type_of_rust_fn(ccx, true, f.sig.inputs.slice_from(1), f.sig.output) type_of_rust_fn(ccx, true, f.sig.inputs.slice_from(1), f.sig.output)
} }
_ => { _ => {
ccx.sess.bug("meth::trans_trait_callee given non-bare-rust-fn"); ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn");
} }
}; };
let llvtable = Load(bcx, let llvtable = Load(bcx,
@ -500,7 +500,7 @@ pub fn get_vtable(bcx: &Block,
methods.push(vtable_method) methods.push(vtable_method)
} }
} }
_ => ccx.sess.bug("get_vtable: expected a static origin"), _ => ccx.sess().bug("get_vtable: expected a static origin"),
} }
} }
@ -548,8 +548,8 @@ fn emit_vtable_methods(bcx: &Block,
let trt_id = match ty::impl_trait_ref(tcx, impl_id) { let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
Some(t_id) => t_id.def_id, Some(t_id) => t_id.def_id,
None => ccx.sess.bug("make_impl_vtable: don't know how to \ None => ccx.sess().bug("make_impl_vtable: don't know how to \
make a vtable for a type impl!") make a vtable for a type impl!")
}; };
ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trt_id); ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trt_id);

View File

@ -95,7 +95,7 @@ pub fn monomorphic_fn(ccx: @CrateContext,
let mut is_static_provided = None; let mut is_static_provided = None;
let map_node = session::expect( let map_node = session::expect(
ccx.sess, ccx.sess(),
ccx.tcx.map.find(fn_id.node), ccx.tcx.map.find(fn_id.node),
|| format!("while monomorphizing {:?}, couldn't find it in the \ || format!("while monomorphizing {:?}, couldn't find it in the \
item map (may have attempted to monomorphize an item \ item map (may have attempted to monomorphize an item \
@ -172,8 +172,8 @@ pub fn monomorphic_fn(ccx: @CrateContext,
// Random cut-off -- code that needs to instantiate the same function // Random cut-off -- code that needs to instantiate the same function
// recursively more than thirty times can probably safely be assumed // recursively more than thirty times can probably safely be assumed
// to be causing an infinite expansion. // to be causing an infinite expansion.
if depth > ccx.sess.recursion_limit.get() { if depth > ccx.sess().recursion_limit.get() {
ccx.sess.span_fatal(ccx.tcx.map.span(fn_id.node), ccx.sess().span_fatal(ccx.tcx.map.span(fn_id.node),
"reached the recursion limit during monomorphization"); "reached the recursion limit during monomorphization");
} }
@ -207,7 +207,7 @@ pub fn monomorphic_fn(ccx: @CrateContext,
d d
} }
_ => { _ => {
ccx.tcx.sess.bug("Can't monomorphize this kind of item") ccx.sess().bug("Can't monomorphize this kind of item")
} }
} }
} }
@ -239,7 +239,7 @@ pub fn monomorphic_fn(ccx: @CrateContext,
d); d);
} }
ast::StructVariantKind(_) => ast::StructVariantKind(_) =>
ccx.tcx.sess.bug("can't monomorphize struct variants"), ccx.sess().bug("can't monomorphize struct variants"),
} }
d d
} }
@ -258,8 +258,8 @@ pub fn monomorphic_fn(ccx: @CrateContext,
d d
} }
_ => { _ => {
ccx.tcx.sess.bug(format!("can't monomorphize a {:?}", ccx.sess().bug(format!("can't monomorphize a {:?}",
map_node)) map_node))
} }
} }
} }
@ -281,7 +281,7 @@ pub fn monomorphic_fn(ccx: @CrateContext,
ast_map::NodeArg(..) | ast_map::NodeArg(..) |
ast_map::NodeBlock(..) | ast_map::NodeBlock(..) |
ast_map::NodeLocal(..) => { ast_map::NodeLocal(..) => {
ccx.tcx.sess.bug(format!("can't monomorphize a {:?}", map_node)) ccx.sess().bug(format!("can't monomorphize a {:?}", map_node))
} }
}; };

View File

@ -86,7 +86,7 @@ pub fn type_of_fn_from_ty(cx: &CrateContext, fty: ty::t) -> Type {
} }
} }
_ => { _ => {
cx.sess.bug("type_of_fn_from_ty given non-closure, non-bare-fn") cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn")
} }
} }
} }
@ -142,7 +142,7 @@ pub fn sizing_type_of(cx: &CrateContext, t: ty::t) -> Type {
ty::ty_unboxed_vec(mt) => { ty::ty_unboxed_vec(mt) => {
let sz_ty = sizing_type_of(cx, mt.ty); let sz_ty = sizing_type_of(cx, mt.ty);
Type::vec(cx.sess.targ_cfg.arch, &sz_ty) Type::vec(cx.sess().targ_cfg.arch, &sz_ty)
} }
ty::ty_tup(..) | ty::ty_enum(..) => { ty::ty_tup(..) | ty::ty_enum(..) => {
@ -162,7 +162,8 @@ pub fn sizing_type_of(cx: &CrateContext, t: ty::t) -> Type {
} }
ty::ty_self(_) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) => { ty::ty_self(_) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) => {
cx.tcx.sess.bug(format!("fictitious type {:?} in sizing_type_of()", ty::get(t).sty)) cx.sess().bug(format!("fictitious type {:?} in sizing_type_of()",
ty::get(t).sty))
} }
}; };
@ -212,7 +213,7 @@ pub fn type_of(cx: &CrateContext, t: ty::t) -> Type {
ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t),
ty::ty_float(t) => Type::float_from_ty(t), ty::ty_float(t) => Type::float_from_ty(t),
ty::ty_str(ty::vstore_uniq) => { ty::ty_str(ty::vstore_uniq) => {
Type::vec(cx.sess.targ_cfg.arch, &Type::i8()).ptr_to() Type::vec(cx.sess().targ_cfg.arch, &Type::i8()).ptr_to()
} }
ty::ty_enum(did, ref substs) => { ty::ty_enum(did, ref substs) => {
// Only create the named struct, but don't fill it in. We // Only create the named struct, but don't fill it in. We
@ -231,11 +232,11 @@ pub fn type_of(cx: &CrateContext, t: ty::t) -> Type {
} }
ty::ty_vec(ref mt, ty::vstore_uniq) => { ty::ty_vec(ref mt, ty::vstore_uniq) => {
let ty = type_of(cx, mt.ty); let ty = type_of(cx, mt.ty);
Type::vec(cx.sess.targ_cfg.arch, &ty).ptr_to() Type::vec(cx.sess().targ_cfg.arch, &ty).ptr_to()
} }
ty::ty_unboxed_vec(ref mt) => { ty::ty_unboxed_vec(ref mt) => {
let ty = type_of(cx, mt.ty); let ty = type_of(cx, mt.ty);
Type::vec(cx.sess.targ_cfg.arch, &ty) Type::vec(cx.sess().targ_cfg.arch, &ty)
} }
ty::ty_ptr(ref mt) => type_of(cx, mt.ty).ptr_to(), ty::ty_ptr(ref mt) => type_of(cx, mt.ty).ptr_to(),
ty::ty_rptr(_, ref mt) => type_of(cx, mt.ty).ptr_to(), ty::ty_rptr(_, ref mt) => type_of(cx, mt.ty).ptr_to(),
@ -288,10 +289,10 @@ pub fn type_of(cx: &CrateContext, t: ty::t) -> Type {
adt::incomplete_type_of(cx, repr, name) adt::incomplete_type_of(cx, repr, name)
} }
} }
ty::ty_self(..) => cx.tcx.sess.unimpl("type_of: ty_self"), ty::ty_self(..) => cx.sess().unimpl("type_of: ty_self"),
ty::ty_infer(..) => cx.tcx.sess.bug("type_of with ty_infer"), ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"),
ty::ty_param(..) => cx.tcx.sess.bug("type_of with ty_param"), ty::ty_param(..) => cx.sess().bug("type_of with ty_param"),
ty::ty_err(..) => cx.tcx.sess.bug("type_of with ty_err") ty::ty_err(..) => cx.sess().bug("type_of with ty_err")
}; };
debug!("--> mapped t={} {:?} to llty={}", debug!("--> mapped t={} {:?} to llty={}",

View File

@ -11,7 +11,7 @@
#[allow(non_camel_case_types)]; #[allow(non_camel_case_types)];
use back::svh::Svh; use back::svh::Svh;
use driver::session; use driver::session::Session;
use metadata::csearch; use metadata::csearch;
use metadata; use metadata;
use middle::const_eval; use middle::const_eval;
@ -262,7 +262,7 @@ pub struct ctxt_ {
interner: RefCell<FnvHashMap<intern_key, ~t_box_>>, interner: RefCell<FnvHashMap<intern_key, ~t_box_>>,
next_id: Cell<uint>, next_id: Cell<uint>,
cstore: @metadata::cstore::CStore, cstore: @metadata::cstore::CStore,
sess: session::Session, sess: Session,
def_map: resolve::DefMap, def_map: resolve::DefMap,
named_region_map: @RefCell<resolve_lifetime::NamedRegionMap>, named_region_map: @RefCell<resolve_lifetime::NamedRegionMap>,
@ -1081,7 +1081,7 @@ pub type type_cache = RefCell<DefIdMap<ty_param_bounds_and_ty>>;
pub type node_type_table = RefCell<HashMap<uint,t>>; pub type node_type_table = RefCell<HashMap<uint,t>>;
pub fn mk_ctxt(s: session::Session, pub fn mk_ctxt(s: Session,
dm: resolve::DefMap, dm: resolve::DefMap,
named_region_map: @RefCell<resolve_lifetime::NamedRegionMap>, named_region_map: @RefCell<resolve_lifetime::NamedRegionMap>,
map: ast_map::Map, map: ast_map::Map,

View File

@ -189,7 +189,7 @@ impl<'a> visit::Visitor<()> for PrivilegedScopeVisitor<'a> {
ItemImpl(_, None, ast_ty, _) => { ItemImpl(_, None, ast_ty, _) => {
if !self.cc.ast_type_is_defined_in_local_crate(ast_ty) { if !self.cc.ast_type_is_defined_in_local_crate(ast_ty) {
// This is an error. // This is an error.
let session = self.cc.crate_context.tcx.sess; let session = &self.cc.crate_context.tcx.sess;
session.span_err(item.span, session.span_err(item.span,
"cannot associate methods with a type outside the \ "cannot associate methods with a type outside the \
crate the type is defined in; define and implement \ crate the type is defined in; define and implement \
@ -210,7 +210,7 @@ impl<'a> visit::Visitor<()> for PrivilegedScopeVisitor<'a> {
self.cc.trait_ref_to_trait_def_id(trait_ref); self.cc.trait_ref_to_trait_def_id(trait_ref);
if trait_def_id.krate != LOCAL_CRATE { if trait_def_id.krate != LOCAL_CRATE {
let session = self.cc.crate_context.tcx.sess; let session = &self.cc.crate_context.tcx.sess;
session.span_err(item.span, session.span_err(item.span,
"cannot provide an extension implementation \ "cannot provide an extension implementation \
where both trait and type are not defined in this crate"); where both trait and type are not defined in this crate");
@ -274,7 +274,7 @@ impl CoherenceChecker {
item.span, item.span,
self_type.ty) { self_type.ty) {
None => { None => {
let session = self.crate_context.tcx.sess; let session = &self.crate_context.tcx.sess;
session.span_err(item.span, session.span_err(item.span,
"no base type found for inherent implementation; \ "no base type found for inherent implementation; \
implement a trait or new type instead"); implement a trait or new type instead");
@ -447,7 +447,7 @@ impl CoherenceChecker {
implementation_b); implementation_b);
if self.polytypes_unify(polytype_a.clone(), polytype_b) { if self.polytypes_unify(polytype_a.clone(), polytype_b) {
let session = self.crate_context.tcx.sess; let session = &self.crate_context.tcx.sess;
session.span_err( session.span_err(
self.span_of_impl(implementation_a), self.span_of_impl(implementation_a),
format!("conflicting implementations for trait `{}`", format!("conflicting implementations for trait `{}`",

View File

@ -26,6 +26,7 @@ use rustc::metadata::decoder;
use std; use std;
use core;
use doctree; use doctree;
use visit_ast; use visit_ast;
use std::local_data; use std::local_data;
@ -84,7 +85,7 @@ impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> {
let cx = local_data::get(super::ctxtkey, |x| *x.unwrap()); let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
let mut externs = ~[]; let mut externs = ~[];
cx.sess.cstore.iter_crate_data(|n, meta| { cx.sess().cstore.iter_crate_data(|n, meta| {
externs.push((n, meta.clean())); externs.push((n, meta.clean()));
}); });
@ -683,7 +684,7 @@ impl Clean<Type> for ast::Ty {
fn clean(&self) -> Type { fn clean(&self) -> Type {
use syntax::ast::*; use syntax::ast::*;
debug!("cleaning type `{:?}`", self); debug!("cleaning type `{:?}`", self);
let codemap = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess.codemap; let codemap = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess().codemap;
debug!("span corresponds to `{}`", codemap.span_to_str(self.span)); debug!("span corresponds to `{}`", codemap.span_to_str(self.span));
match self.node { match self.node {
TyNil => Unit, TyNil => Unit,
@ -865,7 +866,7 @@ pub struct Span {
impl Clean<Span> for syntax::codemap::Span { impl Clean<Span> for syntax::codemap::Span {
fn clean(&self) -> Span { fn clean(&self) -> Span {
let cm = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess.codemap; let cm = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess().codemap;
let filename = cm.span_to_filename(*self); let filename = cm.span_to_filename(*self);
let lo = cm.lookup_char_pos(self.lo); let lo = cm.lookup_char_pos(self.lo);
let hi = cm.lookup_char_pos(self.hi); let hi = cm.lookup_char_pos(self.hi);
@ -1179,7 +1180,7 @@ trait ToSource {
impl ToSource for syntax::codemap::Span { impl ToSource for syntax::codemap::Span {
fn to_src(&self) -> ~str { fn to_src(&self) -> ~str {
debug!("converting span {:?} to snippet", self.clean()); debug!("converting span {:?} to snippet", self.clean());
let cm = local_data::get(super::ctxtkey, |x| x.unwrap().clone()).sess.codemap.clone(); let cm = local_data::get(super::ctxtkey, |x| x.unwrap().clone()).sess().codemap.clone();
let sn = match cm.span_to_snippet(*self) { let sn = match cm.span_to_snippet(*self) {
Some(x) => x, Some(x) => x,
None => ~"" None => ~""
@ -1234,10 +1235,10 @@ fn name_from_pat(p: &ast::Pat) -> ~str {
fn resolve_type(path: Path, tpbs: Option<~[TyParamBound]>, fn resolve_type(path: Path, tpbs: Option<~[TyParamBound]>,
id: ast::NodeId) -> Type { id: ast::NodeId) -> Type {
let cx = local_data::get(super::ctxtkey, |x| *x.unwrap()); let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
let tycx = match cx.tycx { let tycx = match cx.maybe_typed {
Some(tycx) => tycx, core::Typed(ref tycx) => tycx,
// If we're extracting tests, this return value doesn't matter. // If we're extracting tests, this return value doesn't matter.
None => return Bool core::NotTyped(_) => return Bool
}; };
debug!("searching for {:?} in defmap", id); debug!("searching for {:?} in defmap", id);
let def_map = tycx.def_map.borrow(); let def_map = tycx.def_map.borrow();
@ -1289,12 +1290,12 @@ fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> { fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
let cx = local_data::get(super::ctxtkey, |x| *x.unwrap()); let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
match cx.tycx { match cx.maybe_typed {
Some(tcx) => { core::Typed(ref tcx) => {
let def_map = tcx.def_map.borrow(); let def_map = tcx.def_map.borrow();
def_map.get().find(&id).map(|&d| ast_util::def_id_of_def(d)) def_map.get().find(&id).map(|&d| ast_util::def_id_of_def(d))
} }
None => None core::NotTyped(_) => None
} }
} }

View File

@ -27,10 +27,23 @@ use visit_ast::RustdocVisitor;
use clean; use clean;
use clean::Clean; use clean::Clean;
pub enum MaybeTyped {
Typed(middle::ty::ctxt),
NotTyped(driver::session::Session)
}
pub struct DocContext { pub struct DocContext {
krate: ast::Crate, krate: ast::Crate,
tycx: Option<middle::ty::ctxt>, maybe_typed: MaybeTyped
sess: driver::session::Session }
impl DocContext {
pub fn sess<'a>(&'a self) -> &'a driver::session::Session {
match self.maybe_typed {
Typed(ref tcx) => &tcx.sess,
NotTyped(ref sess) => sess
}
}
} }
pub struct CrateAnalysis { pub struct CrateAnalysis {
@ -67,27 +80,27 @@ fn get_ast_and_resolve(cpath: &Path,
parsesess.cm, parsesess.cm,
span_diagnostic_handler); span_diagnostic_handler);
let mut cfg = build_configuration(sess); let mut cfg = build_configuration(&sess);
for cfg_ in cfgs.move_iter() { for cfg_ in cfgs.move_iter() {
let cfg_ = token::intern_and_get_ident(cfg_); let cfg_ = token::intern_and_get_ident(cfg_);
cfg.push(@dummy_spanned(ast::MetaWord(cfg_))); cfg.push(@dummy_spanned(ast::MetaWord(cfg_)));
} }
let krate = phase_1_parse_input(sess, cfg, &input); let krate = phase_1_parse_input(&sess, cfg, &input);
let loader = &mut Loader::new(sess); let (krate, ast_map) = phase_2_configure_and_expand(&sess, &mut Loader::new(sess),
let id = from_str("rustdoc").unwrap(); krate, &from_str("rustdoc").unwrap());
let (krate, ast_map) = phase_2_configure_and_expand(sess, loader,
krate, &id);
let driver::driver::CrateAnalysis { let driver::driver::CrateAnalysis {
exported_items, public_items, ty_cx, .. exported_items, public_items, ty_cx, ..
} = phase_3_run_analysis_passes(sess, &krate, ast_map); } = phase_3_run_analysis_passes(sess, &krate, ast_map);
debug!("crate: {:?}", krate); debug!("crate: {:?}", krate);
return (DocContext { krate: krate, tycx: Some(ty_cx), sess: sess }, (DocContext {
CrateAnalysis { krate: krate,
exported_items: exported_items, maybe_typed: Typed(ty_cx)
public_items: public_items, }, CrateAnalysis {
}); exported_items: exported_items,
public_items: public_items,
})
} }
pub fn run_core (libs: HashSet<Path>, cfgs: ~[~str], path: &Path) -> (clean::Crate, CrateAnalysis) { pub fn run_core (libs: HashSet<Path>, cfgs: ~[~str], path: &Path) -> (clean::Crate, CrateAnalysis) {

View File

@ -58,17 +58,14 @@ pub fn run(input: &str, libs: @RefCell<HashSet<Path>>, mut test_args: ~[~str]) -
parsesess.cm, parsesess.cm,
span_diagnostic_handler); span_diagnostic_handler);
let cfg = driver::build_configuration(sess); let cfg = driver::build_configuration(&sess);
let krate = driver::phase_1_parse_input(sess, cfg, &input); let krate = driver::phase_1_parse_input(&sess, cfg, &input);
let loader = &mut Loader::new(sess); let (krate, _) = driver::phase_2_configure_and_expand(sess, &mut Loader::new(sess), krate,
let id = from_str("rustdoc-test").unwrap(); &from_str("rustdoc-test").unwrap());
let (krate, _) = driver::phase_2_configure_and_expand(sess, loader, krate,
&id);
let ctx = @core::DocContext { let ctx = @core::DocContext {
krate: krate, krate: krate,
tycx: None, maybe_typed: core::NotTyped(sess),
sess: sess,
}; };
local_data::set(super::ctxtkey, ctx); local_data::set(super::ctxtkey, ctx);
@ -140,7 +137,7 @@ fn runtest(test: &str, cratename: &str, libs: HashSet<Path>, should_fail: bool,
let outdir = TempDir::new("rustdoctest").expect("rustdoc needs a tempdir"); let outdir = TempDir::new("rustdoctest").expect("rustdoc needs a tempdir");
let out = Some(outdir.path().clone()); let out = Some(outdir.path().clone());
let cfg = driver::build_configuration(sess); let cfg = driver::build_configuration(&sess);
driver::compile_input(sess, cfg, &input, &out, &None); driver::compile_input(sess, cfg, &input, &out, &None);
if no_run { return } if no_run { return }

View File

@ -183,21 +183,18 @@ impl<'a> RustdocVisitor<'a> {
fn resolve_id(&mut self, id: ast::NodeId, glob: bool, fn resolve_id(&mut self, id: ast::NodeId, glob: bool,
om: &mut Module) -> bool { om: &mut Module) -> bool {
let def = { let tcx = match self.cx.maybe_typed {
let dm = match self.cx.tycx { core::Typed(ref tcx) => tcx,
Some(tcx) => tcx.def_map.borrow(), core::NotTyped(_) => return false
None => return false,
};
ast_util::def_id_of_def(*dm.get().get(&id))
}; };
let def = ast_util::def_id_of_def(*tcx.def_map.borrow().get().get(&id));
if !ast_util::is_local(def) { return false } if !ast_util::is_local(def) { return false }
let analysis = match self.analysis { let analysis = match self.analysis {
Some(analysis) => analysis, None => return false Some(analysis) => analysis, None => return false
}; };
if analysis.public_items.contains(&def.node) { return false } if analysis.public_items.contains(&def.node) { return false }
let item = self.cx.tycx.unwrap().map.get(def.node); match tcx.map.get(def.node) {
match item {
ast_map::NodeItem(it) => { ast_map::NodeItem(it) => {
if glob { if glob {
match it.node { match it.node {