From 82ec34332f0ac7d03819c2fc25481d9f27a950fe Mon Sep 17 00:00:00 2001 From: Jose Narvaez Date: Tue, 13 Oct 2015 10:53:57 +0100 Subject: [PATCH 01/12] Rustfmt-ing libarena. --- src/libarena/lib.rs | 139 ++++++++++++++++++++------------------------ 1 file changed, 62 insertions(+), 77 deletions(-) diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index 62463ecabbf55..4c383edd5d7ce 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -105,7 +105,7 @@ pub struct Arena<'longer_than_self> { head: RefCell, copy_head: RefCell, chunks: RefCell>, - _marker: marker::PhantomData<*mut &'longer_than_self()>, + _marker: marker::PhantomData<*mut &'longer_than_self ()>, } impl<'a> Arena<'a> { @@ -197,10 +197,11 @@ fn un_bitpack_tydesc_ptr(p: usize) -> (*const TyDesc, bool) { struct TyDesc { drop_glue: fn(*const i8), size: usize, - align: usize + align: usize, } -trait AllTypes { fn dummy(&self) { } } +trait AllTypes { fn dummy(&self) { + } } impl AllTypes for T { } unsafe fn get_tydesc() -> *const TyDesc { @@ -224,8 +225,7 @@ impl<'longer_than_self> Arena<'longer_than_self> { let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.copy_head.borrow().clone()); - *self.copy_head.borrow_mut() = - chunk((new_min_chunk_size + 1).next_power_of_two(), true); + *self.copy_head.borrow_mut() = chunk((new_min_chunk_size + 1).next_power_of_two(), true); self.alloc_copy_inner(n_bytes, align) } @@ -242,16 +242,15 @@ impl<'longer_than_self> Arena<'longer_than_self> { let copy_head = self.copy_head.borrow(); copy_head.fill.set(end); - unsafe { - copy_head.as_ptr().offset(start as isize) - } + unsafe { copy_head.as_ptr().offset(start as isize) } } #[inline] - fn alloc_copy(&self, op: F) -> &mut T where F: FnOnce() -> T { + fn alloc_copy(&self, op: F) -> &mut T + where F: FnOnce() -> T + { unsafe { - let ptr = self.alloc_copy_inner(mem::size_of::(), - mem::align_of::()); + let ptr = self.alloc_copy_inner(mem::size_of::(), mem::align_of::()); let ptr = ptr as *mut T; ptr::write(&mut (*ptr), op()); &mut *ptr @@ -259,21 +258,18 @@ impl<'longer_than_self> Arena<'longer_than_self> { } // Functions for the non-POD part of the arena - fn alloc_noncopy_grow(&self, n_bytes: usize, - align: usize) -> (*const u8, *const u8) { + fn alloc_noncopy_grow(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.head.borrow().clone()); - *self.head.borrow_mut() = - chunk((new_min_chunk_size + 1).next_power_of_two(), false); + *self.head.borrow_mut() = chunk((new_min_chunk_size + 1).next_power_of_two(), false); self.alloc_noncopy_inner(n_bytes, align) } #[inline] - fn alloc_noncopy_inner(&self, n_bytes: usize, - align: usize) -> (*const u8, *const u8) { + fn alloc_noncopy_inner(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) { // Be careful to not maintain any `head` borrows active, because // `alloc_noncopy_grow` borrows it mutably. let (start, end, tydesc_start, head_capacity) = { @@ -297,24 +293,25 @@ impl<'longer_than_self> Arena<'longer_than_self> { unsafe { let buf = head.as_ptr(); - (buf.offset(tydesc_start as isize), buf.offset(start as isize)) + (buf.offset(tydesc_start as isize), + buf.offset(start as isize)) } } #[inline] - fn alloc_noncopy(&self, op: F) -> &mut T where F: FnOnce() -> T { + fn alloc_noncopy(&self, op: F) -> &mut T + where F: FnOnce() -> T + { unsafe { let tydesc = get_tydesc::(); - let (ty_ptr, ptr) = - self.alloc_noncopy_inner(mem::size_of::(), - mem::align_of::()); + let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::(), mem::align_of::()); let ty_ptr = ty_ptr as *mut usize; let ptr = ptr as *mut T; // Write in our tydesc along with a bit indicating that it // has *not* been initialized yet. *ty_ptr = bitpack_tydesc_ptr(tydesc, false); // Actually initialize it - ptr::write(&mut(*ptr), op()); + ptr::write(&mut (*ptr), op()); // Now that we are done, update the tydesc to indicate that // the object is there. *ty_ptr = bitpack_tydesc_ptr(tydesc, true); @@ -326,7 +323,9 @@ impl<'longer_than_self> Arena<'longer_than_self> { /// Allocates a new item in the arena, using `op` to initialize the value, /// and returns a reference to it. #[inline] - pub fn alloc(&self, op: F) -> &mut T where F: FnOnce() -> T { + pub fn alloc(&self, op: F) -> &mut T + where F: FnOnce() -> T + { unsafe { if intrinsics::needs_drop::() { self.alloc_noncopy(op) @@ -358,10 +357,10 @@ fn test_arena_destructors_fail() { for i in 0..10 { // Arena allocate something with drop glue to make sure it // doesn't leak. - arena.alloc(|| { Rc::new(i) }); + arena.alloc(|| Rc::new(i)); // Allocate something with funny size and alignment, to keep // things interesting. - arena.alloc(|| { [0u8, 1, 2] }); + arena.alloc(|| [0u8, 1, 2]); } // Now, panic while allocating arena.alloc::, _>(|| { @@ -393,9 +392,7 @@ struct TypedArenaChunk { next: *mut TypedArenaChunk, /// The number of elements that this chunk can hold. - capacity: usize, - - // Objects follow here, suitably aligned. + capacity: usize, // Objects follow here, suitably aligned. } fn calculate_size(capacity: usize) -> usize { @@ -409,12 +406,13 @@ fn calculate_size(capacity: usize) -> usize { impl TypedArenaChunk { #[inline] - unsafe fn new(next: *mut TypedArenaChunk, capacity: usize) - -> *mut TypedArenaChunk { + unsafe fn new(next: *mut TypedArenaChunk, capacity: usize) -> *mut TypedArenaChunk { let size = calculate_size::(capacity); - let chunk = allocate(size, mem::align_of::>()) - as *mut TypedArenaChunk; - if chunk.is_null() { alloc::oom() } + let chunk = + allocate(size, mem::align_of::>()) as *mut TypedArenaChunk; + if chunk.is_null() { + alloc::oom() + } (*chunk).next = next; (*chunk).capacity = capacity; chunk @@ -437,7 +435,8 @@ impl TypedArenaChunk { let next = self.next; let size = calculate_size::(self.capacity); let self_ptr: *mut TypedArenaChunk = self; - deallocate(self_ptr as *mut u8, size, + deallocate(self_ptr as *mut u8, + size, mem::align_of::>()); if !next.is_null() { let capacity = (*next).capacity; @@ -449,9 +448,7 @@ impl TypedArenaChunk { #[inline] fn start(&self) -> *const u8 { let this: *const TypedArenaChunk = self; - unsafe { - round_up(this.offset(1) as usize, mem::align_of::()) as *const u8 - } + unsafe { round_up(this.offset(1) as usize, mem::align_of::()) as *const u8 } } // Returns a pointer to the end of the allocated space. @@ -545,14 +542,21 @@ mod tests { #[test] fn test_arena_alloc_nested() { - struct Inner { value: u8 } - struct Outer<'a> { inner: &'a Inner } - enum EI<'e> { I(Inner), O(Outer<'e>) } + struct Inner { + value: u8, + } + struct Outer<'a> { + inner: &'a Inner, + } + enum EI<'e> { + I(Inner), + O(Outer<'e>), + } struct Wrap<'a>(TypedArena>); impl<'a> Wrap<'a> { - fn alloc_inner Inner>(&self, f: F) -> &Inner { + fn alloc_inner Inner>(&self, f: F) -> &Inner { let r: &EI = self.0.alloc(EI::I(f())); if let &EI::I(ref i) = r { i @@ -560,7 +564,7 @@ mod tests { panic!("mismatch"); } } - fn alloc_outer Outer<'a>>(&self, f: F) -> &Outer { + fn alloc_outer Outer<'a>>(&self, f: F) -> &Outer { let r: &EI = self.0.alloc(EI::O(f())); if let &EI::O(ref o) = r { o @@ -572,8 +576,9 @@ mod tests { let arena = Wrap(TypedArena::new()); - let result = arena.alloc_outer(|| Outer { - inner: arena.alloc_inner(|| Inner { value: 10 }) }); + let result = arena.alloc_outer(|| { + Outer { inner: arena.alloc_inner(|| Inner { value: 10 }) } + }); assert_eq!(result.inner.value, 10); } @@ -582,49 +587,27 @@ mod tests { pub fn test_copy() { let arena = TypedArena::new(); for _ in 0..100000 { - arena.alloc(Point { - x: 1, - y: 2, - z: 3, - }); + arena.alloc(Point { x: 1, y: 2, z: 3 }); } } #[bench] pub fn bench_copy(b: &mut Bencher) { let arena = TypedArena::new(); - b.iter(|| { - arena.alloc(Point { - x: 1, - y: 2, - z: 3, - }) - }) + b.iter(|| arena.alloc(Point { x: 1, y: 2, z: 3 })) } #[bench] pub fn bench_copy_nonarena(b: &mut Bencher) { b.iter(|| { - let _: Box<_> = box Point { - x: 1, - y: 2, - z: 3, - }; + let _: Box<_> = box Point { x: 1, y: 2, z: 3 }; }) } #[bench] pub fn bench_copy_old_arena(b: &mut Bencher) { let arena = Arena::new(); - b.iter(|| { - arena.alloc(|| { - Point { - x: 1, - y: 2, - z: 3, - } - }) - }) + b.iter(|| arena.alloc(|| Point { x: 1, y: 2, z: 3 })) } #[allow(dead_code)] @@ -639,7 +622,7 @@ mod tests { for _ in 0..100000 { arena.alloc(Noncopy { string: "hello world".to_string(), - array: vec!( 1, 2, 3, 4, 5 ), + array: vec!(1, 2, 3, 4, 5), }); } } @@ -650,7 +633,7 @@ mod tests { b.iter(|| { arena.alloc(Noncopy { string: "hello world".to_string(), - array: vec!( 1, 2, 3, 4, 5 ), + array: vec!(1, 2, 3, 4, 5), }) }) } @@ -660,7 +643,7 @@ mod tests { b.iter(|| { let _: Box<_> = box Noncopy { string: "hello world".to_string(), - array: vec!( 1, 2, 3, 4, 5 ), + array: vec!(1, 2, 3, 4, 5), }; }) } @@ -669,9 +652,11 @@ mod tests { pub fn bench_noncopy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| { - arena.alloc(|| Noncopy { - string: "hello world".to_string(), - array: vec!( 1, 2, 3, 4, 5 ), + arena.alloc(|| { + Noncopy { + string: "hello world".to_string(), + array: vec!(1, 2, 3, 4, 5), + } }) }) } From 4f16396560a855eaec1a478c08c9bc8b2249a905 Mon Sep 17 00:00:00 2001 From: Jose Narvaez Date: Tue, 13 Oct 2015 23:24:47 +0100 Subject: [PATCH 02/12] Rustfmt-ing librustc_driver. --- src/librustc_driver/driver.rs | 599 +++++++++++++------------ src/librustc_driver/lib.rs | 251 ++++++----- src/librustc_driver/pretty.rs | 307 +++++++------ src/librustc_driver/target_features.rs | 31 +- src/librustc_driver/test.rs | 213 ++++----- 5 files changed, 720 insertions(+), 681 deletions(-) diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index 619fcd3406cbc..fff91c3731af8 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -77,27 +77,17 @@ pub fn compile_input(sess: Session, controller_entry_point!(after_parse, sess, - CompileState::state_after_parse(input, - &sess, - outdir, - &krate)); - - let outputs = build_output_filenames(input, - outdir, - output, - &krate.attrs, - &sess); - let id = link::find_crate_name(Some(&sess), - &krate.attrs, - input); - let expanded_crate - = match phase_2_configure_and_expand(&sess, - krate, - &id[..], - addl_plugins) { - None => return, - Some(k) => k - }; + CompileState::state_after_parse(input, &sess, outdir, &krate)); + + let outputs = build_output_filenames(input, outdir, output, &krate.attrs, &sess); + let id = link::find_crate_name(Some(&sess), &krate.attrs, input); + let expanded_crate = match phase_2_configure_and_expand(&sess, + krate, + &id[..], + addl_plugins) { + None => return, + Some(k) => k, + }; (outputs, expanded_crate, id) }; @@ -136,9 +126,9 @@ pub fn compile_input(sess: Session, front::check_attr::check_crate(&sess, &expanded_crate); }); - time(sess.time_passes(), "early lint checks", || { - lint::check_ast_crate(&sess, &expanded_crate) - }); + time(sess.time_passes(), + "early lint checks", + || lint::check_ast_crate(&sess, &expanded_crate)); phase_3_run_analysis_passes(&sess, ast_map, @@ -147,39 +137,40 @@ pub fn compile_input(sess: Session, control.make_glob_map, |tcx, analysis| { - { - let state = CompileState::state_after_analysis(input, - &tcx.sess, - outdir, - &expanded_crate, - tcx.map.krate(), - &analysis, - tcx, - &lcx); - (control.after_analysis.callback)(state); - - tcx.sess.abort_if_errors(); - if control.after_analysis.stop == Compilation::Stop { - return Err(()); - } - } - - if log_enabled!(::log::INFO) { - println!("Pre-trans"); - tcx.print_debug_stats(); - } - let trans = phase_4_translate_to_llvm(tcx, analysis); - - if log_enabled!(::log::INFO) { - println!("Post-trans"); - tcx.print_debug_stats(); - } + { + let state = + CompileState::state_after_analysis(input, + &tcx.sess, + outdir, + &expanded_crate, + tcx.map.krate(), + &analysis, + tcx, + &lcx); + (control.after_analysis.callback)(state); + + tcx.sess.abort_if_errors(); + if control.after_analysis.stop == Compilation::Stop { + return Err(()); + } + } + + if log_enabled!(::log::INFO) { + println!("Pre-trans"); + tcx.print_debug_stats(); + } + let trans = phase_4_translate_to_llvm(tcx, analysis); + + if log_enabled!(::log::INFO) { + println!("Post-trans"); + tcx.print_debug_stats(); + } // Discard interned strings as they are no longer required. - token::get_ident_interner().clear(); + token::get_ident_interner().clear(); - Ok((outputs, trans)) - }) + Ok((outputs, trans)) + }) }; let (outputs, trans) = if let Ok(out) = result { @@ -192,10 +183,7 @@ pub fn compile_input(sess: Session, controller_entry_point!(after_llvm, sess, - CompileState::state_after_llvm(input, - &sess, - outdir, - &trans)); + CompileState::state_after_llvm(input, &sess, outdir, &trans)); phase_6_link_output(&sess, &trans, &outputs); } @@ -210,7 +198,7 @@ pub fn source_name(input: &Input) -> String { match *input { // FIXME (#9639): This needs to handle non-utf8 paths Input::File(ref ifile) => ifile.to_str().unwrap().to_string(), - Input::Str(_) => anon_src() + Input::Str(_) => anon_src(), } } @@ -243,7 +231,7 @@ impl<'a> CompileController<'a> { CompileController { after_parse: PhaseController::basic(), after_expand: PhaseController::basic(), - after_write_deps: PhaseController::basic(), + after_write_deps: PhaseController::basic(), after_analysis: PhaseController::basic(), after_llvm: PhaseController::basic(), make_glob_map: resolve::MakeGlobMap::No, @@ -313,10 +301,7 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> { out_dir: &'a Option, krate: &'a ast::Crate) -> CompileState<'a, 'ast, 'tcx> { - CompileState { - krate: Some(krate), - .. CompileState::empty(input, session, out_dir) - } + CompileState { krate: Some(krate), ..CompileState::empty(input, session, out_dir) } } fn state_after_expand(input: &'a Input, @@ -328,7 +313,7 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> { CompileState { crate_name: Some(crate_name), expanded_crate: Some(expanded_crate), - .. CompileState::empty(input, session, out_dir) + ..CompileState::empty(input, session, out_dir) } } @@ -347,7 +332,7 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> { krate: Some(krate), hir_crate: Some(hir_crate), lcx: Some(lcx), - .. CompileState::empty(input, session, out_dir) + ..CompileState::empty(input, session, out_dir) } } @@ -366,7 +351,7 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> { krate: Some(krate), hir_crate: Some(hir_crate), lcx: Some(lcx), - .. CompileState::empty(input, session, out_dir) + ..CompileState::empty(input, session, out_dir) } } @@ -376,15 +361,11 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> { out_dir: &'a Option, trans: &'a trans::CrateTranslation) -> CompileState<'a, 'ast, 'tcx> { - CompileState { - trans: Some(trans), - .. CompileState::empty(input, session, out_dir) - } + CompileState { trans: Some(trans), ..CompileState::empty(input, session, out_dir) } } } -pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input) - -> ast::Crate { +pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input) -> ast::Crate { // These may be left in an incoherent state after a previous compile. // `clear_tables` and `get_ident_interner().clear()` can be used to free // memory, but they do not restore the initial state. @@ -442,24 +423,21 @@ pub fn phase_2_configure_and_expand(sess: &Session, // baz! should not use this definition unless foo is enabled. let mut feature_gated_cfgs = vec![]; - krate = time(time_passes, "configuration 1", || - syntax::config::strip_unconfigured_items(sess.diagnostic(), krate, - &mut feature_gated_cfgs)); + krate = time(time_passes, "configuration 1", || { + syntax::config::strip_unconfigured_items(sess.diagnostic(), krate, &mut feature_gated_cfgs) + }); - *sess.crate_types.borrow_mut() = - collect_crate_types(sess, &krate.attrs); - *sess.crate_metadata.borrow_mut() = - collect_crate_metadata(sess, &krate.attrs); + *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs); + *sess.crate_metadata.borrow_mut() = collect_crate_metadata(sess, &krate.attrs); time(time_passes, "recursion limit", || { middle::recursion_limit::update_recursion_limit(sess, &krate); }); time(time_passes, "gated macro checking", || { - let features = - syntax::feature_gate::check_crate_macros(sess.codemap(), - &sess.parse_sess.span_diagnostic, - &krate); + let features = syntax::feature_gate::check_crate_macros(sess.codemap(), + &sess.parse_sess.span_diagnostic, + &krate); // these need to be set "early" so that expansion sees `quote` if enabled. *sess.features.borrow_mut() = features; @@ -467,27 +445,29 @@ pub fn phase_2_configure_and_expand(sess: &Session, }); - krate = time(time_passes, "crate injection", || - syntax::std_inject::maybe_inject_crates_ref(krate, - sess.opts.alt_std_name.clone())); + krate = time(time_passes, "crate injection", || { + syntax::std_inject::maybe_inject_crates_ref(krate, sess.opts.alt_std_name.clone()) + }); - let macros = time(time_passes, "macro loading", || - metadata::macro_import::read_macro_defs(sess, &krate)); + let macros = time(time_passes, + "macro loading", + || metadata::macro_import::read_macro_defs(sess, &krate)); let mut addl_plugins = Some(addl_plugins); - let registrars = time(time_passes, "plugin loading", || - plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap())); + let registrars = time(time_passes, "plugin loading", || { + plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap()) + }); let mut registry = Registry::new(sess, &krate); time(time_passes, "plugin registration", || { if sess.features.borrow().rustc_diagnostic_macros { registry.register_macro("__diagnostic_used", - diagnostics::plugin::expand_diagnostic_used); + diagnostics::plugin::expand_diagnostic_used); registry.register_macro("__register_diagnostic", - diagnostics::plugin::expand_register_diagnostic); + diagnostics::plugin::expand_register_diagnostic); registry.register_macro("__build_diagnostic_array", - diagnostics::plugin::expand_build_diagnostic_array); + diagnostics::plugin::expand_build_diagnostic_array); } for registrar in registrars { @@ -535,8 +515,7 @@ pub fn phase_2_configure_and_expand(sess: &Session, let mut _old_path = OsString::new(); if cfg!(windows) { _old_path = env::var_os("PATH").unwrap_or(_old_path); - let mut new_path = sess.host_filesearch(PathKind::All) - .get_dylib_search_paths(); + let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths(); new_path.extend(env::split_paths(&_old_path)); env::set_var("PATH", &env::join_paths(new_path).unwrap()); } @@ -548,11 +527,11 @@ pub fn phase_2_configure_and_expand(sess: &Session, trace_mac: sess.opts.debugging_opts.trace_macros, }; let ret = syntax::ext::expand::expand_crate(&sess.parse_sess, - cfg, - macros, - syntax_exts, - &mut feature_gated_cfgs, - krate); + cfg, + macros, + syntax_exts, + &mut feature_gated_cfgs, + krate); if cfg!(windows) { env::set_var("PATH", &_old_path); } @@ -564,11 +543,11 @@ pub fn phase_2_configure_and_expand(sess: &Session, // much as possible (e.g. help the programmer avoid platform // specific differences) time(time_passes, "complete gated feature checking 1", || { - let features = - syntax::feature_gate::check_crate(sess.codemap(), - &sess.parse_sess.span_diagnostic, - &krate, &attributes, - sess.opts.unstable_features); + let features = syntax::feature_gate::check_crate(sess.codemap(), + &sess.parse_sess.span_diagnostic, + &krate, + &attributes, + sess.opts.unstable_features); *sess.features.borrow_mut() = features; sess.abort_if_errors(); }); @@ -576,9 +555,9 @@ pub fn phase_2_configure_and_expand(sess: &Session, // JBC: make CFG processing part of expansion to avoid this problem: // strip again, in case expansion added anything with a #[cfg]. - krate = time(time_passes, "configuration 2", || - syntax::config::strip_unconfigured_items(sess.diagnostic(), krate, - &mut feature_gated_cfgs)); + krate = time(time_passes, "configuration 2", || { + syntax::config::strip_unconfigured_items(sess.diagnostic(), krate, &mut feature_gated_cfgs) + }); time(time_passes, "gated configuration checking", || { let features = sess.features.borrow(); @@ -589,30 +568,31 @@ pub fn phase_2_configure_and_expand(sess: &Session, } }); - krate = time(time_passes, "maybe building test harness", || - syntax::test::modify_for_testing(&sess.parse_sess, - &sess.opts.cfg, - krate, - sess.diagnostic())); + krate = time(time_passes, "maybe building test harness", || { + syntax::test::modify_for_testing(&sess.parse_sess, &sess.opts.cfg, krate, sess.diagnostic()) + }); - krate = time(time_passes, "prelude injection", || - syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate)); + krate = time(time_passes, + "prelude injection", + || syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate)); - time(time_passes, "checking that all macro invocations are gone", || - syntax::ext::expand::check_for_macros(&sess.parse_sess, &krate)); + time(time_passes, + "checking that all macro invocations are gone", + || syntax::ext::expand::check_for_macros(&sess.parse_sess, &krate)); - time(time_passes, "checking for inline asm in case the target doesn't support it", || - middle::check_no_asm::check_crate(sess, &krate)); + time(time_passes, + "checking for inline asm in case the target doesn't support it", + || middle::check_no_asm::check_crate(sess, &krate)); // One final feature gating of the true AST that gets compiled // later, to make sure we've got everything (e.g. configuration // can insert new attributes via `cfg_attr`) time(time_passes, "complete gated feature checking 2", || { - let features = - syntax::feature_gate::check_crate(sess.codemap(), - &sess.parse_sess.span_diagnostic, - &krate, &attributes, - sess.opts.unstable_features); + let features = syntax::feature_gate::check_crate(sess.codemap(), + &sess.parse_sess.span_diagnostic, + &krate, + &attributes, + sess.opts.unstable_features); *sess.features.borrow_mut() = features; sess.abort_if_errors(); }); @@ -620,10 +600,9 @@ pub fn phase_2_configure_and_expand(sess: &Session, Some(krate) } -pub fn assign_node_ids(sess: &Session, - krate: ast::Crate) -> ast::Crate { +pub fn assign_node_ids(sess: &Session, krate: ast::Crate) -> ast::Crate { struct NodeIdAssigner<'a> { - sess: &'a Session + sess: &'a Session, } impl<'a> Folder for NodeIdAssigner<'a> { @@ -665,17 +644,18 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session, make_glob_map: resolve::MakeGlobMap, f: F) -> R - where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>, - ty::CrateAnalysis) -> R + where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>, ty::CrateAnalysis) -> R { let time_passes = sess.time_passes(); let krate = ast_map.krate(); - time(time_passes, "external crate/lib resolution", || - LocalCrateReader::new(sess, &ast_map).read_crates(krate)); + time(time_passes, + "external crate/lib resolution", + || LocalCrateReader::new(sess, &ast_map).read_crates(krate)); - let lang_items = time(time_passes, "language item collection", || - middle::lang_items::collect_language_items(&sess, &ast_map)); + let lang_items = time(time_passes, + "language item collection", + || middle::lang_items::collect_language_items(&sess, &ast_map)); let resolve::CrateMap { def_map, @@ -693,25 +673,29 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session, syntax::ext::mtwt::clear_tables(); } - let named_region_map = time(time_passes, "lifetime resolution", + let named_region_map = time(time_passes, + "lifetime resolution", || middle::resolve_lifetime::krate(sess, krate, &def_map)); - time(time_passes, "looking for entry point", + time(time_passes, + "looking for entry point", || middle::entry::find_entry_point(sess, &ast_map)); - sess.plugin_registrar_fn.set( - time(time_passes, "looking for plugin registrar", || - plugin::build::find_plugin_registrar( - sess.diagnostic(), krate))); + sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || { + plugin::build::find_plugin_registrar(sess.diagnostic(), krate) + })); - let region_map = time(time_passes, "region resolution", || - middle::region::resolve_crate(sess, krate)); + let region_map = time(time_passes, + "region resolution", + || middle::region::resolve_crate(sess, krate)); - time(time_passes, "loop checking", || - middle::check_loop::check_crate(sess, krate)); + time(time_passes, + "loop checking", + || middle::check_loop::check_crate(sess, krate)); - time(time_passes, "static item recursion checking", || - middle::check_static_recursion::check_crate(sess, krate, &def_map, &ast_map)); + time(time_passes, + "static item recursion checking", + || middle::check_static_recursion::check_crate(sess, krate, &def_map, &ast_map)); ty::ctxt::create_and_enter(sess, arenas, @@ -725,95 +709,114 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session, |tcx| { // passes are timed inside typeck - typeck::check_crate(tcx, trait_map); + typeck::check_crate(tcx, trait_map); - time(time_passes, "const checking", || - middle::check_const::check_crate(tcx)); + time(time_passes, + "const checking", + || middle::check_const::check_crate(tcx)); - let (exported_items, public_items) = - time(time_passes, "privacy checking", || - rustc_privacy::check_crate(tcx, &export_map, external_exports)); + let (exported_items, public_items) = + time(time_passes, "privacy checking", || { + rustc_privacy::check_crate(tcx, + &export_map, + external_exports) + }); // Do not move this check past lint - time(time_passes, "stability index", || - tcx.stability.borrow_mut().build(tcx, krate, &public_items)); + time(time_passes, "stability index", || { + tcx.stability.borrow_mut().build(tcx, krate, &public_items) + }); - time(time_passes, "intrinsic checking", || - middle::intrinsicck::check_crate(tcx)); + time(time_passes, + "intrinsic checking", + || middle::intrinsicck::check_crate(tcx)); - time(time_passes, "effect checking", || - middle::effect::check_crate(tcx)); + time(time_passes, + "effect checking", + || middle::effect::check_crate(tcx)); - time(time_passes, "match checking", || - middle::check_match::check_crate(tcx)); + time(time_passes, + "match checking", + || middle::check_match::check_crate(tcx)); - let _mir_map = - time(time_passes, "MIR dump", || - mir::mir_map::build_mir_for_crate(tcx)); + let _mir_map = time(time_passes, + "MIR dump", + || mir::mir_map::build_mir_for_crate(tcx)); - time(time_passes, "liveness checking", || - middle::liveness::check_crate(tcx)); + time(time_passes, + "liveness checking", + || middle::liveness::check_crate(tcx)); - time(time_passes, "borrow checking", || - borrowck::check_crate(tcx)); + time(time_passes, + "borrow checking", + || borrowck::check_crate(tcx)); - time(time_passes, "rvalue checking", || - middle::check_rvalues::check_crate(tcx, krate)); + time(time_passes, + "rvalue checking", + || middle::check_rvalues::check_crate(tcx, krate)); // Avoid overwhelming user with errors if type checking failed. // I'm not sure how helpful this is, to be honest, but it avoids a // lot of annoying errors in the compile-fail tests (basically, // lint warnings and so on -- kindck used to do this abort, but // kindck is gone now). -nmatsakis - tcx.sess.abort_if_errors(); + tcx.sess.abort_if_errors(); - let reachable_map = - time(time_passes, "reachability checking", || - reachable::find_reachable(tcx, &exported_items)); + let reachable_map = + time(time_passes, + "reachability checking", + || reachable::find_reachable(tcx, &exported_items)); - time(time_passes, "death checking", || { - middle::dead::check_crate(tcx, - &exported_items, - &reachable_map) - }); + time(time_passes, "death checking", || { + middle::dead::check_crate(tcx, + &exported_items, + &reachable_map) + }); - let ref lib_features_used = - time(time_passes, "stability checking", || - stability::check_unstable_api_usage(tcx)); + let ref lib_features_used = + time(time_passes, + "stability checking", + || stability::check_unstable_api_usage(tcx)); - time(time_passes, "unused lib feature checking", || - stability::check_unused_or_stable_features( - &tcx.sess, lib_features_used)); + time(time_passes, "unused lib feature checking", || { + stability::check_unused_or_stable_features(&tcx.sess, + lib_features_used) + }); - time(time_passes, "lint checking", || - lint::check_crate(tcx, krate, &exported_items)); + time(time_passes, + "lint checking", + || lint::check_crate(tcx, krate, &exported_items)); // The above three passes generate errors w/o aborting - tcx.sess.abort_if_errors(); - - f(tcx, ty::CrateAnalysis { - export_map: export_map, - exported_items: exported_items, - public_items: public_items, - reachable: reachable_map, - name: name, - glob_map: glob_map, - }) - }) + tcx.sess.abort_if_errors(); + + f(tcx, + ty::CrateAnalysis { + export_map: export_map, + exported_items: exported_items, + public_items: public_items, + reachable: reachable_map, + name: name, + glob_map: glob_map, + }) + }) } /// Run the translation phase to LLVM, after which the AST and analysis can /// be discarded. -pub fn phase_4_translate_to_llvm(tcx: &ty::ctxt, analysis: ty::CrateAnalysis) +pub fn phase_4_translate_to_llvm(tcx: &ty::ctxt, + analysis: ty::CrateAnalysis) -> trans::CrateTranslation { let time_passes = tcx.sess.time_passes(); - time(time_passes, "resolving dependency formats", || - dependency_format::calculate(&tcx.sess)); + time(time_passes, + "resolving dependency formats", + || dependency_format::calculate(&tcx.sess)); // Option dance to work around the lack of stack once closures. - time(time_passes, "translation", move || - trans::trans_crate(tcx, analysis)) + time(time_passes, + "translation", + move || trans::trans_crate(tcx, analysis)) } /// Run LLVM itself, producing a bitcode file, assembly file or object file @@ -824,8 +827,9 @@ pub fn phase_5_run_llvm_passes(sess: &Session, if sess.opts.cg.no_integrated_as { let mut map = HashMap::new(); map.insert(OutputType::Assembly, None); - time(sess.time_passes(), "LLVM passes", || - write::run_passes(sess, trans, &map, outputs)); + time(sess.time_passes(), + "LLVM passes", + || write::run_passes(sess, trans, &map, outputs)); write::run_assembler(sess, outputs); @@ -834,11 +838,9 @@ pub fn phase_5_run_llvm_passes(sess: &Session, fs::remove_file(&outputs.temp_path(OutputType::Assembly)).unwrap(); } } else { - time(sess.time_passes(), "LLVM passes", || - write::run_passes(sess, - trans, - &sess.opts.output_types, - outputs)); + time(sess.time_passes(), + "LLVM passes", + || write::run_passes(sess, trans, &sess.opts.output_types, outputs)); } sess.abort_if_errors(); @@ -849,17 +851,15 @@ pub fn phase_5_run_llvm_passes(sess: &Session, pub fn phase_6_link_output(sess: &Session, trans: &trans::CrateTranslation, outputs: &OutputFilenames) { - time(sess.time_passes(), "linking", || - link::link_binary(sess, - trans, - outputs, - &trans.link.crate_name)); + time(sess.time_passes(), + "linking", + || link::link_binary(sess, trans, outputs, &trans.link.crate_name)); } fn escape_dep_filename(filename: &str) -> String { // Apparently clang and gcc *only* escape spaces: // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4 - filename.replace(" ", "\\ ") + filename.replace(" ", "\") } fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) { @@ -869,12 +869,13 @@ fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) { match *output_type { OutputType::Exe => { for output in sess.crate_types.borrow().iter() { - let p = link::filename_for_input(sess, *output, id, - outputs); + let p = link::filename_for_input(sess, *output, id, outputs); out_filenames.push(p); } } - _ => { out_filenames.push(file); } + _ => { + out_filenames.push(file); + } } } @@ -884,76 +885,80 @@ fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) { } let deps_filename = outputs.path(OutputType::DepInfo); - let result = (|| -> io::Result<()> { + let result = + (|| -> io::Result<()> { // Build a list of files used to compile the output and // write Makefile-compatible dependency rules - let files: Vec = sess.codemap().files.borrow() - .iter() - .filter(|fmap| fmap.is_real_file()) - .filter(|fmap| !fmap.is_imported()) - .map(|fmap| escape_dep_filename(&fmap.name)) - .collect(); - let mut file = try!(fs::File::create(&deps_filename)); - for path in &out_filenames { - try!(write!(file, - "{}: {}\n\n", path.display(), files.join(" "))); - } + let files: Vec = sess.codemap() + .files + .borrow() + .iter() + .filter(|fmap| fmap.is_real_file()) + .filter(|fmap| !fmap.is_imported()) + .map(|fmap| escape_dep_filename(&fmap.name)) + .collect(); + let mut file = try!(fs::File::create(&deps_filename)); + for path in &out_filenames { + try!(write!(file, "{}: {}\n\n", path.display(), files.join(" "))); + } // Emit a fake target for each input file to the compilation. This // prevents `make` from spitting out an error if a file is later // deleted. For more info see #28735 - for path in files { - try!(writeln!(file, "{}:", path)); - } - Ok(()) - })(); + for path in files { + try!(writeln!(file, "{}:", path)); + } + Ok(()) + })(); match result { Ok(()) => {} Err(e) => { sess.fatal(&format!("error writing dependencies to `{}`: {}", - deps_filename.display(), e)); + deps_filename.display(), + e)); } } } -pub fn collect_crate_types(session: &Session, - attrs: &[ast::Attribute]) -> Vec { +pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec { // Unconditionally collect crate types from attributes to make them used - let attr_types: Vec = attrs.iter().filter_map(|a| { - if a.check_name("crate_type") { - match a.value_str() { - Some(ref n) if *n == "rlib" => { - Some(config::CrateTypeRlib) - } - Some(ref n) if *n == "dylib" => { - Some(config::CrateTypeDylib) - } - Some(ref n) if *n == "lib" => { - Some(config::default_lib_output()) - } - Some(ref n) if *n == "staticlib" => { - Some(config::CrateTypeStaticlib) - } - Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable), - Some(_) => { - session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES, - ast::CRATE_NODE_ID, - a.span, - "invalid `crate_type` \ - value".to_string()); - None - } - _ => { - session.span_err(a.span, "`crate_type` requires a value"); - session.note("for example: `#![crate_type=\"lib\"]`"); - None - } - } - } else { - None - } - }).collect(); + let attr_types: Vec = + attrs.iter() + .filter_map(|a| { + if a.check_name("crate_type") { + match a.value_str() { + Some(ref n) if *n == "rlib" => { + Some(config::CrateTypeRlib) + } + Some(ref n) if *n == "dylib" => { + Some(config::CrateTypeDylib) + } + Some(ref n) if *n == "lib" => { + Some(config::default_lib_output()) + } + Some(ref n) if *n == "staticlib" => { + Some(config::CrateTypeStaticlib) + } + Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable), + Some(_) => { + session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES, + ast::CRATE_NODE_ID, + a.span, + "invalid `crate_type` value".to_string()); + None + } + _ => { + session.span_err(a.span, "`crate_type` requires a value"); + session.note("for example: `#![crate_type=\"lib\"]`"); + None + } + } + } else { + None + } + }) + .collect(); // If we're generating a test executable, then ignore all other output // styles at all other locations @@ -974,21 +979,22 @@ pub fn collect_crate_types(session: &Session, base.dedup(); } - base.into_iter().filter(|crate_type| { - let res = !link::invalid_output_for_target(session, *crate_type); + base.into_iter() + .filter(|crate_type| { + let res = !link::invalid_output_for_target(session, *crate_type); - if !res { - session.warn(&format!("dropping unsupported crate type `{}` \ - for target `{}`", - *crate_type, session.opts.target_triple)); - } + if !res { + session.warn(&format!("dropping unsupported crate type `{}` for target `{}`", + *crate_type, + session.opts.target_triple)); + } - res - }).collect() + res + }) + .collect() } -pub fn collect_crate_metadata(session: &Session, - _attrs: &[ast::Attribute]) -> Vec { +pub fn collect_crate_metadata(session: &Session, _attrs: &[ast::Attribute]) -> Vec { session.opts.cg.metadata.clone() } @@ -997,7 +1003,7 @@ pub fn build_output_filenames(input: &Input, ofile: &Option, attrs: &[ast::Attribute], sess: &Session) - -> OutputFilenames { + -> OutputFilenames { match *ofile { None => { // "-" as input file will cause the parser to read from stdin so we @@ -1005,13 +1011,15 @@ pub fn build_output_filenames(input: &Input, // We want to toss everything after the final '.' let dirpath = match *odir { Some(ref d) => d.clone(), - None => PathBuf::new() + None => PathBuf::new(), }; // If a crate name is present, we use it as the link name - let stem = sess.opts.crate_name.clone().or_else(|| { - attr::find_crate_name(attrs).map(|n| n.to_string()) - }).unwrap_or(input.filestem()); + let stem = sess.opts + .crate_name + .clone() + .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string())) + .unwrap_or(input.filestem()); OutputFilenames { out_directory: dirpath, @@ -1023,12 +1031,14 @@ pub fn build_output_filenames(input: &Input, } Some(ref out_file) => { - let unnamed_output_types = sess.opts.output_types.values() + let unnamed_output_types = sess.opts + .output_types + .values() .filter(|a| a.is_none()) .count(); let ofile = if unnamed_output_types > 1 { - sess.warn("ignoring specified output filename because multiple \ - outputs were requested"); + sess.warn("ignoring specified output filename because multiple outputs were \ + requested"); None } else { Some(out_file.clone()) @@ -1041,8 +1051,11 @@ pub fn build_output_filenames(input: &Input, OutputFilenames { out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(), - out_filestem: out_file.file_stem().unwrap_or(OsStr::new("")) - .to_str().unwrap().to_string(), + out_filestem: out_file.file_stem() + .unwrap_or(OsStr::new("")) + .to_str() + .unwrap() + .to_string(), single_output_file: ofile, extra: sess.opts.cg.extra_filename.clone(), outputs: sess.opts.output_types.clone(), diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 276b747feb204..09f1867de1f0c 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -51,8 +51,10 @@ extern crate rustc_trans; extern crate rustc_typeck; extern crate serialize; extern crate rustc_llvm as llvm; -#[macro_use] extern crate log; -#[macro_use] extern crate syntax; +#[macro_use] +extern crate log; +#[macro_use] +extern crate syntax; pub use syntax::diagnostic; @@ -105,8 +107,7 @@ pub fn run(args: Vec) -> isize { // Parse args and run the compiler. This is the primary entry point for rustc. // See comments on CompilerCalls below for details about the callbacks argument. -pub fn run_compiler<'a>(args: &[String], - callbacks: &mut CompilerCalls<'a>) { +pub fn run_compiler<'a>(args: &[String], callbacks: &mut CompilerCalls<'a>) { macro_rules! do_or_return {($expr: expr) => { match $expr { Compilation::Stop => return, @@ -116,7 +117,7 @@ pub fn run_compiler<'a>(args: &[String], let matches = match handle_options(args.to_vec()) { Some(matches) => matches, - None => return + None => return, }; let sopts = config::build_session_options(&matches); @@ -130,8 +131,8 @@ pub fn run_compiler<'a>(args: &[String], Some((input, input_file_path)) => callbacks.some_input(input, input_file_path), None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) { Some((input, input_file_path)) => (input, input_file_path), - None => return - } + None => return, + }, }; let mut sess = build_session(sopts, input_file_path, descriptions); @@ -152,7 +153,8 @@ pub fn run_compiler<'a>(args: &[String], pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile); return; } - None => {/* continue */ } + None => {/* continue */ + } } let plugins = sess.opts.debugging_opts.extra_plugins.clone(); @@ -176,7 +178,8 @@ fn make_input(free_matches: &[String]) -> Option<(Input, Option)> { io::stdin().read_to_string(&mut src).unwrap(); Some((Input::Str(src), None)) } else { - Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))) + Some((Input::File(PathBuf::from(ifile)), + Some(PathBuf::from(ifile)))) } } else { None @@ -194,7 +197,7 @@ impl Compilation { pub fn and_then Compilation>(self, next: F) -> Compilation { match self { Compilation::Stop => Compilation::Stop, - Compilation::Continue => next() + Compilation::Continue => next(), } } } @@ -229,7 +232,9 @@ pub trait CompilerCalls<'a> { // Called after we extract the input from the arguments. Gives the implementer // an opportunity to change the inputs or to add some custom input handling. // The default behaviour is to simply pass through the inputs. - fn some_input(&mut self, input: Input, input_path: Option) + fn some_input(&mut self, + input: Input, + input_path: Option) -> (Input, Option) { (input, input_path) } @@ -300,8 +305,8 @@ impl<'a> CompilerCalls<'a> for RustcDefaultCalls { } } return Compilation::Stop; - }, - None => () + } + None => (), } return Compilation::Continue; @@ -331,7 +336,7 @@ impl<'a> CompilerCalls<'a> for RustcDefaultCalls { early_error(sopts.color, "no input filename given"); } 1 => panic!("make_input should have provided valid inputs"), - _ => early_error(sopts.color, "multiple input filenames provided") + _ => early_error(sopts.color, "multiple input filenames provided"), } None @@ -366,15 +371,14 @@ impl<'a> CompilerCalls<'a> for RustcDefaultCalls { odir: &Option, ofile: &Option) -> Compilation { - RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile).and_then( - || RustcDefaultCalls::list_metadata(sess, matches, input)) + RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile) + .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input)) } fn build_controller(&mut self, sess: &Session) -> CompileController<'a> { let mut control = CompileController::basic(); - if sess.opts.parse_only || - sess.opts.show_span.is_some() || + if sess.opts.parse_only || sess.opts.show_span.is_some() || sess.opts.debugging_opts.ast_json_noexpand { control.after_parse.stop = Compilation::Stop; } @@ -393,13 +397,13 @@ impl<'a> CompilerCalls<'a> for RustcDefaultCalls { if sess.opts.debugging_opts.save_analysis { control.after_analysis.callback = box |state| { - time(state.session.time_passes(), - "save analysis", - || save::process_crate(state.tcx.unwrap(), - state.lcx.unwrap(), - state.krate.unwrap(), - state.analysis.unwrap(), - state.out_dir)); + time(state.session.time_passes(), "save analysis", || { + save::process_crate(state.tcx.unwrap(), + state.lcx.unwrap(), + state.krate.unwrap(), + state.analysis.unwrap(), + state.out_dir) + }); }; control.make_glob_map = resolve::MakeGlobMap::Yes; } @@ -409,19 +413,15 @@ impl<'a> CompilerCalls<'a> for RustcDefaultCalls { } impl RustcDefaultCalls { - pub fn list_metadata(sess: &Session, - matches: &getopts::Matches, - input: &Input) - -> Compilation { + pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation { let r = matches.opt_strs("Z"); if r.contains(&("ls".to_string())) { match input { &Input::File(ref ifile) => { let path = &(*ifile); let mut v = Vec::new(); - metadata::loader::list_file_metadata(&sess.target.target, - path, - &mut v).unwrap(); + metadata::loader::list_file_metadata(&sess.target.target, path, &mut v) + .unwrap(); println!("{}", String::from_utf8(v).unwrap()); } &Input::Str(_) => { @@ -455,14 +455,8 @@ impl RustcDefaultCalls { None => early_error(sess.opts.color, "no input file provided"), }; let attrs = attrs.as_ref().unwrap(); - let t_outputs = driver::build_output_filenames(input, - odir, - ofile, - attrs, - sess); - let id = link::find_crate_name(Some(sess), - attrs, - input); + let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess); + let id = link::find_crate_name(Some(sess), attrs, input); if *req == PrintRequest::CrateName { println!("{}", id); continue @@ -471,10 +465,8 @@ impl RustcDefaultCalls { let metadata = driver::collect_crate_metadata(sess, attrs); *sess.crate_metadata.borrow_mut() = metadata; for &style in &crate_types { - let fname = link::filename_for_input(sess, style, &id, - &t_outputs); - println!("{}", fname.file_name().unwrap() - .to_string_lossy()); + let fname = link::filename_for_input(sess, style, &id, &t_outputs); + println!("{}", fname.file_name().unwrap().to_string_lossy()); } } } @@ -502,9 +494,13 @@ pub fn commit_date_str() -> Option<&'static str> { pub fn version(binary: &str, matches: &getopts::Matches) { let verbose = matches.opt_present("verbose"); - println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version")); + println!("{} {}", + binary, + option_env!("CFG_VERSION").unwrap_or("unknown version")); if verbose { - fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") } + fn unw(x: Option<&str>) -> &str { + x.unwrap_or("unknown") + } println!("binary: {}", binary); println!("commit-hash: {}", unw(commit_hash_str())); println!("commit-date: {}", unw(commit_date_str())); @@ -519,32 +515,35 @@ fn usage(verbose: bool, include_unstable_options: bool) { } else { config::rustc_short_optgroups() }; - let groups : Vec<_> = groups.into_iter() - .filter(|x| include_unstable_options || x.is_stable()) - .map(|x|x.opt_group) - .collect(); + let groups: Vec<_> = groups.into_iter() + .filter(|x| include_unstable_options || x.is_stable()) + .map(|x| x.opt_group) + .collect(); let message = format!("Usage: rustc [OPTIONS] INPUT"); let extra_help = if verbose { "" } else { "\n --help -v Print the full set of options rustc accepts" }; - println!("{}\n\ -Additional help: + println!("{}\nAdditional help: -C help Print codegen options - -W help Print 'lint' options and default settings - -Z help Print internal options for debugging rustc{}\n", - getopts::usage(&message, &groups), - extra_help); + -W help \ + Print 'lint' options and default settings + -Z help Print internal \ + options for debugging rustc{}\n", + getopts::usage(&message, &groups), + extra_help); } fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) { println!(" Available lint options: -W Warn about - -A Allow + -A \ + Allow -D Deny - -F Forbid (deny, and deny all overrides) + -F Forbid \ + (deny, and deny all overrides) "); @@ -561,7 +560,7 @@ Available lint options: } fn sort_lint_groups(lints: Vec<(&'static str, Vec, bool)>) - -> Vec<(&'static str, Vec)> { + -> Vec<(&'static str, Vec)> { let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect(); lints.sort_by(|&(x, _): &(&'static str, Vec), &(y, _): &(&'static str, Vec)| { @@ -571,21 +570,26 @@ Available lint options: } let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints() - .iter().cloned().partition(|&(_, p)| p); + .iter() + .cloned() + .partition(|&(_, p)| p); let plugin = sort_lints(plugin); let builtin = sort_lints(builtin); let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups() - .iter().cloned().partition(|&(_, _, p)| p); + .iter() + .cloned() + .partition(|&(_, _, p)| p); let plugin_groups = sort_lint_groups(plugin_groups); let builtin_groups = sort_lint_groups(builtin_groups); - let max_name_len = plugin.iter().chain(&builtin) - .map(|&s| s.name.chars().count()) - .max().unwrap_or(0); + let max_name_len = plugin.iter() + .chain(&builtin) + .map(|&s| s.name.chars().count()) + .max() + .unwrap_or(0); let padded = |x: &str| { - let mut s = repeat(" ").take(max_name_len - x.chars().count()) - .collect::(); + let mut s = repeat(" ").take(max_name_len - x.chars().count()).collect::(); s.push_str(x); s }; @@ -598,7 +602,9 @@ Available lint options: for lint in lints { let name = lint.name_lower().replace("_", "-"); println!(" {} {:7.7} {}", - padded(&name[..]), lint.default_level.as_str(), lint.desc); + padded(&name[..]), + lint.default_level.as_str(), + lint.desc); } println!("\n"); }; @@ -607,12 +613,13 @@ Available lint options: - let max_name_len = plugin_groups.iter().chain(&builtin_groups) - .map(|&(s, _)| s.chars().count()) - .max().unwrap_or(0); + let max_name_len = plugin_groups.iter() + .chain(&builtin_groups) + .map(|&(s, _)| s.chars().count()) + .max() + .unwrap_or(0); let padded = |x: &str| { - let mut s = repeat(" ").take(max_name_len - x.chars().count()) - .collect::(); + let mut s = repeat(" ").take(max_name_len - x.chars().count()).collect::(); s.push_str(x); s }; @@ -624,10 +631,11 @@ Available lint options: let print_lint_groups = |lints: Vec<(&'static str, Vec)>| { for (name, to) in lints { let name = name.to_lowercase().replace("_", "-"); - let desc = to.into_iter().map(|x| x.as_str().replace("_", "-")) - .collect::>().join(", "); - println!(" {} {}", - padded(&name[..]), desc); + let desc = to.into_iter() + .map(|x| x.as_str().replace("_", "-")) + .collect::>() + .join(", "); + println!(" {} {}", padded(&name[..]), desc); } println!("\n"); }; @@ -659,10 +667,13 @@ fn describe_debug_flags() { for &(name, _, opt_type_desc, desc) in config::DB_OPTIONS { let (width, extra) = match opt_type_desc { Some(..) => (21, "=val"), - None => (25, "") + None => (25, ""), }; - println!(" -Z {:>width$}{} -- {}", name.replace("_", "-"), - extra, desc, width=width); + println!(" -Z {:>width$}{} -- {}", + name.replace("_", "-"), + extra, + desc, + width = width); } } @@ -671,10 +682,13 @@ fn describe_codegen_flags() { for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS { let (width, extra) = match opt_type_desc { Some(..) => (21, "=val"), - None => (25, "") + None => (25, ""), }; - println!(" -C {:>width$}{} -- {}", name.replace("_", "-"), - extra, desc, width=width); + println!(" -C {:>width$}{} -- {}", + name.replace("_", "-"), + extra, + desc, + width = width); } } @@ -698,8 +712,10 @@ pub fn handle_options(mut args: Vec) -> Option { } fn parse_all_options(args: &Vec) -> getopts::Matches { - let all_groups : Vec - = config::rustc_optgroups().into_iter().map(|x|x.opt_group).collect(); + let all_groups: Vec = config::rustc_optgroups() + .into_iter() + .map(|x| x.opt_group) + .collect(); match getopts::getopts(&args[..], &all_groups) { Ok(m) => { if !allows_unstable_options(&m) { @@ -712,15 +728,16 @@ pub fn handle_options(mut args: Vec) -> Option { &opt.opt_group.short_name }; if m.opt_present(opt_name) { - early_error(diagnostic::Auto, &format!("use of unstable option '{}' \ - requires -Z unstable-options", - opt_name)); + early_error(diagnostic::Auto, + &format!("use of unstable option '{}' requires -Z \ + unstable-options", + opt_name)); } } } m } - Err(f) => early_error(diagnostic::Auto, &f.to_string()) + Err(f) => early_error(diagnostic::Auto, &f.to_string()), } } @@ -743,7 +760,8 @@ pub fn handle_options(mut args: Vec) -> Option { }; if matches.opt_present("h") || matches.opt_present("help") { - usage(matches.opt_present("verbose"), allows_unstable_options(&matches)); + usage(matches.opt_present("verbose"), + allows_unstable_options(&matches)); return None; } @@ -762,7 +780,9 @@ pub fn handle_options(mut args: Vec) -> Option { } if cg_flags.contains(&"passes=list".to_string()) { - unsafe { ::llvm::LLVMRustPrintPasses(); } + unsafe { + ::llvm::LLVMRustPrintPasses(); + } return None; } @@ -774,20 +794,16 @@ pub fn handle_options(mut args: Vec) -> Option { Some(matches) } -fn parse_crate_attrs(sess: &Session, input: &Input) -> - Vec { +fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec { let result = match *input { Input::File(ref ifile) => { - parse::parse_crate_attrs_from_file(ifile, - Vec::new(), - &sess.parse_sess) + parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess) } Input::Str(ref src) => { - parse::parse_crate_attrs_from_source_str( - driver::anon_src().to_string(), - src.to_string(), - Vec::new(), - &sess.parse_sess) + parse::parse_crate_attrs_from_source_str(driver::anon_src().to_string(), + src.to_string(), + Vec::new(), + &sess.parse_sess) } }; result.into_iter().collect() @@ -798,7 +814,7 @@ fn parse_crate_attrs(sess: &Session, input: &Input) -> /// /// The diagnostic emitter yielded to the procedure should be used for reporting /// errors of the compiler. -pub fn monitor(f: F) { +pub fn monitor(f: F) { const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB struct Sink(Arc>>); @@ -806,7 +822,9 @@ pub fn monitor(f: F) { fn write(&mut self, data: &[u8]) -> io::Result { Write::write(&mut *self.0.lock().unwrap(), data) } - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } let data = Arc::new(Mutex::new(Vec::new())); @@ -820,8 +838,14 @@ pub fn monitor(f: F) { cfg = cfg.stack_size(STACK_SIZE); } - match cfg.spawn(move || { io::set_panic(box err); f() }).unwrap().join() { - Ok(()) => { /* fallthrough */ } + match cfg.spawn(move || { + io::set_panic(box err); + f() + }) + .unwrap() + .join() { + Ok(()) => { /* fallthrough */ + } Err(value) => { // Thread panicked without emitting a fatal diagnostic if !value.is::() { @@ -830,24 +854,19 @@ pub fn monitor(f: F) { // a .span_bug or .bug call has already printed what // it wants to print. if !value.is::() { - emitter.emit( - None, - "unexpected panic", - None, - diagnostic::Bug); + emitter.emit(None, "unexpected panic", None, diagnostic::Bug); } - let xs = [ - "the compiler unexpectedly panicked. this is a bug.".to_string(), - format!("we would appreciate a bug report: {}", - BUG_REPORT_URL), - ]; + let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(), + format!("we would appreciate a bug report: {}", BUG_REPORT_URL)]; for note in &xs { emitter.emit(None, ¬e[..], None, diagnostic::Note) } if let None = env::var_os("RUST_BACKTRACE") { - emitter.emit(None, "run with `RUST_BACKTRACE=1` for a backtrace", - None, diagnostic::Note); + emitter.emit(None, + "run with `RUST_BACKTRACE=1` for a backtrace", + None, + diagnostic::Note); } println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap()); diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 57186cb6ce837..c05993dc15d2a 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -79,33 +79,34 @@ pub enum PpMode { pub fn parse_pretty(sess: &Session, name: &str, - extended: bool) -> (PpMode, Option) { + extended: bool) + -> (PpMode, Option) { let mut split = name.splitn(2, '='); let first = split.next().unwrap(); let opt_second = split.next(); let first = match (first, extended) { - ("normal", _) => PpmSource(PpmNormal), - ("identified", _) => PpmSource(PpmIdentified), + ("normal", _) => PpmSource(PpmNormal), + ("identified", _) => PpmSource(PpmIdentified), ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops), - ("expanded", _) => PpmSource(PpmExpanded), + ("expanded", _) => PpmSource(PpmExpanded), ("expanded,identified", _) => PpmSource(PpmExpandedIdentified), ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene), - ("hir", true) => PpmHir(PpmNormal), + ("hir", true) => PpmHir(PpmNormal), ("hir,identified", true) => PpmHir(PpmExpandedIdentified), - ("hir,typed", true) => PpmHir(PpmTyped), - ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default), - ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges), + ("hir,typed", true) => PpmHir(PpmTyped), + ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default), + ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges), _ => { if extended { - sess.fatal(&format!( - "argument to `unpretty` must be one of `normal`, \ - `expanded`, `flowgraph[,unlabelled]=`, `identified`, \ - `expanded,identified`, `everybody_loops`, `hir`, \ - `hir,identified`, or `hir,typed`; got {}", name)); + sess.fatal(&format!("argument to `unpretty` must be one of `normal`, \ + `expanded`, `flowgraph[,unlabelled]=`, \ + `identified`, `expanded,identified`, `everybody_loops`, \ + `hir`, `hir,identified`, or `hir,typed`; got {}", + name)); } else { - sess.fatal(&format!( - "argument to `pretty` must be one of `normal`, `expanded`, \ - `identified`, or `expanded,identified`; got {}", name)); + sess.fatal(&format!("argument to `pretty` must be one of `normal`, `expanded`, \ + `identified`, or `expanded,identified`; got {}", + name)); } } }; @@ -134,21 +135,31 @@ impl PpSourceMode { sess: &'tcx Session, ast_map: Option>, payload: B, - f: F) -> A where - F: FnOnce(&PrinterSupport, B) -> A, + f: F) + -> A + where F: FnOnce(&PrinterSupport, B) -> A { match *self { PpmNormal | PpmEveryBodyLoops | PpmExpanded => { - let annotation = NoAnn { sess: sess, ast_map: ast_map }; + let annotation = NoAnn { + sess: sess, + ast_map: ast_map, + }; f(&annotation, payload) } PpmIdentified | PpmExpandedIdentified => { - let annotation = IdentifiedAnnotation { sess: sess, ast_map: ast_map }; + let annotation = IdentifiedAnnotation { + sess: sess, + ast_map: ast_map, + }; f(&annotation, payload) } PpmExpandedHygiene => { - let annotation = HygieneAnnotation { sess: sess, ast_map: ast_map }; + let annotation = HygieneAnnotation { + sess: sess, + ast_map: ast_map, + }; f(&annotation, payload) } _ => panic!("Should use call_with_pp_support_hir"), @@ -160,19 +171,23 @@ impl PpSourceMode { arenas: &'tcx ty::CtxtArenas<'tcx>, id: String, payload: B, - f: F) -> A where - F: FnOnce(&HirPrinterSupport, B, &hir::Crate) -> A, + f: F) + -> A + where F: FnOnce(&HirPrinterSupport, B, &hir::Crate) -> A { match *self { PpmNormal => { - let annotation = NoAnn { sess: sess, ast_map: Some(ast_map.clone()) }; + let annotation = NoAnn { + sess: sess, + ast_map: Some(ast_map.clone()), + }; f(&annotation, payload, &ast_map.forest.krate) } PpmIdentified => { let annotation = IdentifiedAnnotation { sess: sess, - ast_map: Some(ast_map.clone()) + ast_map: Some(ast_map.clone()), }; f(&annotation, payload, &ast_map.forest.krate) } @@ -183,9 +198,13 @@ impl PpSourceMode { id, resolve::MakeGlobMap::No, |tcx, _| { - let annotation = TypedAnnotation { tcx: tcx }; - f(&annotation, payload, &ast_map.forest.krate) - }) + let annotation = TypedAnnotation { + tcx: tcx, + }; + f(&annotation, + payload, + &ast_map.forest.krate) + }) } _ => panic!("Should use call_with_pp_support"), } @@ -226,27 +245,35 @@ trait HirPrinterSupport<'ast>: pprust_hir::PpAnn { struct NoAnn<'ast> { sess: &'ast Session, - ast_map: Option> + ast_map: Option>, } impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> { - fn sess<'a>(&'a self) -> &'a Session { self.sess } + fn sess<'a>(&'a self) -> &'a Session { + self.sess + } fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> { self.ast_map.as_ref() } - fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self } + fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { + self + } } impl<'ast> HirPrinterSupport<'ast> for NoAnn<'ast> { - fn sess<'a>(&'a self) -> &'a Session { self.sess } + fn sess<'a>(&'a self) -> &'a Session { + self.sess + } fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> { self.ast_map.as_ref() } - fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { self } + fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { + self + } } impl<'ast> pprust::PpAnn for NoAnn<'ast> {} @@ -258,27 +285,27 @@ struct IdentifiedAnnotation<'ast> { } impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> { - fn sess<'a>(&'a self) -> &'a Session { self.sess } + fn sess<'a>(&'a self) -> &'a Session { + self.sess + } fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> { self.ast_map.as_ref() } - fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self } + fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { + self + } } impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> { - fn pre(&self, - s: &mut pprust::State, - node: pprust::AnnNode) -> io::Result<()> { + fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> { match node { pprust::NodeExpr(_) => s.popen(), - _ => Ok(()) + _ => Ok(()), } } - fn post(&self, - s: &mut pprust::State, - node: pprust::AnnNode) -> io::Result<()> { + fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> { match node { pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()), @@ -308,27 +335,27 @@ impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> { } impl<'ast> HirPrinterSupport<'ast> for IdentifiedAnnotation<'ast> { - fn sess<'a>(&'a self) -> &'a Session { self.sess } + fn sess<'a>(&'a self) -> &'a Session { + self.sess + } fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> { self.ast_map.as_ref() } - fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { self } + fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { + self + } } impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> { - fn pre(&self, - s: &mut pprust_hir::State, - node: pprust_hir::AnnNode) -> io::Result<()> { + fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> { match node { pprust_hir::NodeExpr(_) => s.popen(), - _ => Ok(()) + _ => Ok(()), } } - fn post(&self, - s: &mut pprust_hir::State, - node: pprust_hir::AnnNode) -> io::Result<()> { + fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> { match node { pprust_hir::NodeName(_) => Ok(()), pprust_hir::NodeItem(item) => { @@ -362,19 +389,21 @@ struct HygieneAnnotation<'ast> { } impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> { - fn sess<'a>(&'a self) -> &'a Session { self.sess } + fn sess<'a>(&'a self) -> &'a Session { + self.sess + } fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> { self.ast_map.as_ref() } - fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self } + fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { + self + } } impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> { - fn post(&self, - s: &mut pprust::State, - node: pprust::AnnNode) -> io::Result<()> { + fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> { match node { pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => { try!(pp::space(&mut s.s)); @@ -386,7 +415,7 @@ impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> { try!(pp::space(&mut s.s)); s.synth_comment(nm.to_string()) } - _ => Ok(()) + _ => Ok(()), } } } @@ -397,37 +426,36 @@ struct TypedAnnotation<'a, 'tcx: 'a> { } impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> { - fn sess<'a>(&'a self) -> &'a Session { &self.tcx.sess } + fn sess<'a>(&'a self) -> &'a Session { + &self.tcx.sess + } fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> { Some(&self.tcx.map) } - fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { self } + fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { + self + } } impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> { - fn pre(&self, - s: &mut pprust_hir::State, - node: pprust_hir::AnnNode) -> io::Result<()> { + fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> { match node { pprust_hir::NodeExpr(_) => s.popen(), - _ => Ok(()) + _ => Ok(()), } } - fn post(&self, - s: &mut pprust_hir::State, - node: pprust_hir::AnnNode) -> io::Result<()> { + fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> { match node { pprust_hir::NodeExpr(expr) => { try!(pp::space(&mut s.s)); try!(pp::word(&mut s.s, "as")); try!(pp::space(&mut s.s)); - try!(pp::word(&mut s.s, - &self.tcx.expr_ty(expr).to_string())); + try!(pp::word(&mut s.s, &self.tcx.expr_ty(expr).to_string())); s.pclose() } - _ => Ok(()) + _ => Ok(()), } } } @@ -459,9 +487,9 @@ pub enum UserIdentifiedItem { impl FromStr for UserIdentifiedItem { type Err = (); fn from_str(s: &str) -> Result { - Ok(s.parse().map(ItemViaNode).unwrap_or_else(|_| { - ItemViaPath(s.split("::").map(|s| s.to_string()).collect()) - })) + Ok(s.parse() + .map(ItemViaNode) + .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect()))) } } @@ -489,24 +517,22 @@ impl UserIdentifiedItem { } } - fn all_matching_node_ids<'a, 'ast>(&'a self, map: &'a hir_map::Map<'ast>) + fn all_matching_node_ids<'a, 'ast>(&'a self, + map: &'a hir_map::Map<'ast>) -> NodesMatchingUII<'a, 'ast> { match *self { - ItemViaNode(node_id) => - NodesMatchingDirect(Some(node_id).into_iter()), - ItemViaPath(ref parts) => - NodesMatchingSuffix(map.nodes_matching_suffix(&parts[..])), + ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()), + ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts[..])), } } fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId { let fail_because = |is_wrong_because| -> ast::NodeId { - let message = - format!("{} needs NodeId (int) or unique \ - path suffix (b::c::d); got {}, which {}", - user_option, - self.reconstructed_input(), - is_wrong_because); + let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \ + {}, which {}", + user_option, + self.reconstructed_input(), + is_wrong_because); sess.fatal(&message[..]) }; @@ -608,12 +634,13 @@ impl fold::Folder for ReplaceBodyWithLoop { } fn fold_block(&mut self, b: P) -> P { - fn expr_to_block(rules: ast::BlockCheckMode, - e: Option>) -> P { + fn expr_to_block(rules: ast::BlockCheckMode, e: Option>) -> P { P(ast::Block { expr: e, - stmts: vec![], rules: rules, - id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP, + stmts: vec![], + rules: rules, + id: ast::DUMMY_NODE_ID, + span: codemap::DUMMY_SP, }) } @@ -622,7 +649,8 @@ impl fold::Folder for ReplaceBodyWithLoop { let empty_block = expr_to_block(ast::DefaultBlock, None); let loop_expr = P(ast::Expr { node: ast::ExprLoop(empty_block, None), - id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP + id: ast::DUMMY_NODE_ID, + span: codemap::DUMMY_SP, }); expr_to_block(b.rules, Some(loop_expr)) @@ -661,7 +689,7 @@ pub fn pretty_print_input(sess: Session, let krate = if compute_ast_map { match driver::phase_2_configure_and_expand(&sess, krate, &id[..], None) { None => return, - Some(k) => driver::assign_node_ids(&sess, k) + Some(k) => driver::assign_node_ids(&sess, k), } } else { krate @@ -681,12 +709,13 @@ pub fn pretty_print_input(sess: Session, }; let src_name = driver::source_name(input); - let src = sess.codemap().get_filemap(&src_name[..]) - .src - .as_ref() - .unwrap() - .as_bytes() - .to_vec(); + let src = sess.codemap() + .get_filemap(&src_name[..]) + .src + .as_ref() + .unwrap() + .as_bytes() + .to_vec(); let mut rdr = &src[..]; let mut out = Vec::new(); @@ -695,36 +724,39 @@ pub fn pretty_print_input(sess: Session, (PpmSource(s), _) => { // Silently ignores an identified node. let out: &mut Write = &mut out; - s.call_with_pp_support( - &sess, ast_map, box out, |annotation, out| { - debug!("pretty printing source code {:?}", s); - let sess = annotation.sess(); - pprust::print_crate(sess.codemap(), - sess.diagnostic(), - &krate, - src_name.to_string(), - &mut rdr, - out, - annotation.pp_ann(), - is_expanded) + s.call_with_pp_support(&sess, ast_map, box out, |annotation, out| { + debug!("pretty printing source code {:?}", s); + let sess = annotation.sess(); + pprust::print_crate(sess.codemap(), + sess.diagnostic(), + &krate, + src_name.to_string(), + &mut rdr, + out, + annotation.pp_ann(), + is_expanded) }) } (PpmHir(s), None) => { let out: &mut Write = &mut out; - s.call_with_pp_support_hir( - &sess, &ast_map.unwrap(), &arenas, id, box out, |annotation, out, krate| { - debug!("pretty printing source code {:?}", s); - let sess = annotation.sess(); - pprust_hir::print_crate(sess.codemap(), - sess.diagnostic(), - krate, - src_name.to_string(), - &mut rdr, - out, - annotation.pp_ann(), - is_expanded) - }) + s.call_with_pp_support_hir(&sess, + &ast_map.unwrap(), + &arenas, + id, + box out, + |annotation, out, krate| { + debug!("pretty printing source code {:?}", s); + let sess = annotation.sess(); + pprust_hir::print_crate(sess.codemap(), + sess.diagnostic(), + krate, + src_name.to_string(), + &mut rdr, + out, + annotation.pp_ann(), + is_expanded) + }) } (PpmHir(s), Some(uii)) => { @@ -761,6 +793,7 @@ pub fn pretty_print_input(sess: Session, debug!("pretty printing flow graph for {:?}", opt_uii); let uii = opt_uii.unwrap_or_else(|| { sess.fatal(&format!("`pretty flowgraph=..` needs NodeId (int) or + \ unique path suffix (b::c::d)")) }); @@ -768,8 +801,7 @@ pub fn pretty_print_input(sess: Session, let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map); let node = ast_map.find(nodeid).unwrap_or_else(|| { - sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", - nodeid)) + sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid)) }); let code = blocks::Code::from_node(node); @@ -783,32 +815,36 @@ pub fn pretty_print_input(sess: Session, id, resolve::MakeGlobMap::No, |tcx, _| { - print_flowgraph(variants, tcx, code, mode, out) - }) + print_flowgraph(variants, + tcx, + code, + mode, + out) + }) } None => { - let message = format!("--pretty=flowgraph needs \ - block, fn, or method; got {:?}", + let message = format!("--pretty=flowgraph needs block, fn, or method; got \ + {:?}", node); // point to what was found, if there's an // accessible span. match ast_map.opt_span(nodeid) { Some(sp) => sess.span_fatal(sp, &message[..]), - None => sess.fatal(&message[..]) + None => sess.fatal(&message[..]), } } } } - }.unwrap(); + } + .unwrap(); match ofile { None => print!("{}", String::from_utf8(out).unwrap()), Some(p) => { match File::create(&p) { Ok(mut w) => w.write_all(&out).unwrap(), - Err(e) => panic!("print-print failed to open {} due to {}", - p.display(), e), + Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e), } } } @@ -818,7 +854,8 @@ fn print_flowgraph(variants: Vec, tcx: &ty::ctxt, code: blocks::Code, mode: PpFlowGraphMode, - mut out: W) -> io::Result<()> { + mut out: W) + -> io::Result<()> { let cfg = match code { blocks::BlockCode(block) => cfg::CFG::new(tcx, &*block), blocks::FnLikeCode(fn_like) => cfg::CFG::new(tcx, &*fn_like.body()), @@ -837,14 +874,14 @@ fn print_flowgraph(variants: Vec, return expand_err_details(r); } blocks::BlockCode(_) => { - tcx.sess.err("--pretty flowgraph with -Z flowgraph-print \ - annotations requires fn-like node id."); + tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \ + fn-like node id."); return Ok(()) } blocks::FnLikeCode(fn_like) => { let fn_parts = borrowck::FnPartsWithCFG::from_fn_like(&fn_like, &cfg); - let (bccx, analysis_data) = - borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_parts); + let (bccx, analysis_data) = borrowck::build_borrowck_dataflow_data_for_fn(tcx, + fn_parts); let lcfg = borrowck_dot::DataflowLabeller { inner: lcfg, diff --git a/src/librustc_driver/target_features.rs b/src/librustc_driver/target_features.rs index ca76046acf0fb..27ffb595a4051 100644 --- a/src/librustc_driver/target_features.rs +++ b/src/librustc_driver/target_features.rs @@ -48,39 +48,30 @@ pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session) { fn features_contain(sess: &Session, s: &str) -> bool { - sess.target.target.options.features.contains(s) || - sess.opts.cg.target_feature.contains(s) + sess.target.target.options.features.contains(s) || sess.opts.cg.target_feature.contains(s) } pub fn has_sse(sess: &Session) -> bool { - features_contain(sess, "+sse") || - has_sse2(sess) + features_contain(sess, "+sse") || has_sse2(sess) } pub fn has_sse2(sess: &Session) -> bool { // x86-64 requires at least SSE2 support - sess.target.target.arch == "x86_64" || - features_contain(sess, "+sse2") || - has_sse3(sess) + sess.target.target.arch == "x86_64" || features_contain(sess, "+sse2") || has_sse3(sess) } pub fn has_sse3(sess: &Session) -> bool { - features_contain(sess, "+sse3") || - has_ssse3(sess) + features_contain(sess, "+sse3") || has_ssse3(sess) } pub fn has_ssse3(sess: &Session) -> bool { - features_contain(sess, "+ssse3") || - has_sse41(sess) + features_contain(sess, "+ssse3") || has_sse41(sess) } pub fn has_sse41(sess: &Session) -> bool { - features_contain(sess, "+sse4.1") || - has_sse42(sess) + features_contain(sess, "+sse4.1") || has_sse42(sess) } pub fn has_sse42(sess: &Session) -> bool { - features_contain(sess, "+sse4.2") || - has_avx(sess) + features_contain(sess, "+sse4.2") || has_avx(sess) } pub fn has_avx(sess: &Session) -> bool { - features_contain(sess, "+avx") || - has_avx2(sess) + features_contain(sess, "+avx") || has_avx2(sess) } pub fn has_avx2(sess: &Session) -> bool { features_contain(sess, "+avx2") @@ -88,11 +79,9 @@ pub fn has_avx2(sess: &Session) -> bool { pub fn has_neon(sess: &Session) -> bool { // AArch64 requires NEON support - sess.target.target.arch == "aarch64" || - features_contain(sess, "+neon") + sess.target.target.arch == "aarch64" || features_contain(sess, "+neon") } pub fn has_vfp(sess: &Session) -> bool { // AArch64 requires VFP support - sess.target.target.arch == "aarch64" || - features_contain(sess, "+vfp") + sess.target.target.arch == "aarch64" || features_contain(sess, "+vfp") } diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index 0c83851ba002a..6385408b27b81 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -30,7 +30,7 @@ use rustc_typeck::middle::infer::lub::Lub; use rustc_typeck::middle::infer::glb::Glb; use rustc_typeck::middle::infer::sub::Sub; use rustc::front::map as hir_map; -use rustc::session::{self,config}; +use rustc::session::{self, config}; use syntax::{abi, ast}; use syntax::codemap; use syntax::codemap::{Span, CodeMap, DUMMY_SP}; @@ -47,19 +47,21 @@ struct Env<'a, 'tcx: 'a> { struct RH<'a> { id: ast::NodeId, - sub: &'a [RH<'a>] + sub: &'a [RH<'a>], } const EMPTY_SOURCE_STR: &'static str = "#![feature(no_core)] #![no_core]"; struct ExpectErrorEmitter { - messages: Vec + messages: Vec, } fn remove_message(e: &mut ExpectErrorEmitter, msg: &str, lvl: Level) { match lvl { - Bug | Fatal | Error => { } - Warning | Note | Help => { return; } + Bug | Fatal | Error => {} + Warning | Note | Help => { + return; + } } debug!("Error: {}", msg); @@ -68,8 +70,7 @@ fn remove_message(e: &mut ExpectErrorEmitter, msg: &str, lvl: Level) { e.messages.remove(i); } None => { - panic!("Unexpected error: {} Expected: {:?}", - msg, e.messages); + panic!("Unexpected error: {} Expected: {:?}", msg, e.messages); } } } @@ -79,41 +80,32 @@ impl Emitter for ExpectErrorEmitter { _cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, _: Option<&str>, - lvl: Level) - { + lvl: Level) { remove_message(self, msg, lvl); } - fn custom_emit(&mut self, - _cm: &codemap::CodeMap, - _sp: RenderSpan, - msg: &str, - lvl: Level) - { + fn custom_emit(&mut self, _cm: &codemap::CodeMap, _sp: RenderSpan, msg: &str, lvl: Level) { remove_message(self, msg, lvl); } } -fn errors(msgs: &[&str]) -> (Box, usize) { +fn errors(msgs: &[&str]) -> (Box, usize) { let v = msgs.iter().map(|m| m.to_string()).collect(); - (box ExpectErrorEmitter { messages: v } as Box, msgs.len()) + (box ExpectErrorEmitter { messages: v } as Box, + msgs.len()) } fn test_env(source_string: &str, - (emitter, expected_err_count): (Box, usize), - body: F) where - F: FnOnce(Env), + (emitter, expected_err_count): (Box, usize), + body: F) + where F: FnOnce(Env) { - let mut options = - config::basic_options(); + let mut options = config::basic_options(); options.debugging_opts.verbose = true; options.unstable_features = UnstableFeatures::Allow; - let codemap = - CodeMap::new(); - let diagnostic_handler = - diagnostic::Handler::with_emitter(true, emitter); - let span_diagnostic_handler = - diagnostic::SpanHandler::new(diagnostic_handler, codemap); + let codemap = CodeMap::new(); + let diagnostic_handler = diagnostic::Handler::with_emitter(true, emitter); + let span_diagnostic_handler = diagnostic::SpanHandler::new(diagnostic_handler, codemap); let sess = session::build_session_(options, None, span_diagnostic_handler); rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess)); @@ -146,12 +138,13 @@ fn test_env(source_string: &str, lang_items, stability::Index::new(krate), |tcx| { - let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, None, false); - body(Env { infcx: &infcx }); - let free_regions = FreeRegionMap::new(); - infcx.resolve_regions_and_report_errors(&free_regions, ast::CRATE_NODE_ID); - assert_eq!(tcx.sess.err_count(), expected_err_count); - }); + let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, None, false); + body(Env { infcx: &infcx }); + let free_regions = FreeRegionMap::new(); + infcx.resolve_regions_and_report_errors(&free_regions, + ast::CRATE_NODE_ID); + assert_eq!(tcx.sess.err_count(), expected_err_count); + }); } impl<'a, 'tcx> Env<'a, 'tcx> { @@ -169,15 +162,16 @@ impl<'a, 'tcx> Env<'a, 'tcx> { pub fn create_simple_region_hierarchy(&self) { // creates a region hierarchy where 1 is root, 10 and 11 are // children of 1, etc - let dscope = self.infcx.tcx.region_maps.intern_code_extent( - CodeExtentData::DestructionScope(1), region::ROOT_CODE_EXTENT); - self.create_region_hierarchy( - &RH {id: 1, - sub: &[RH {id: 10, - sub: &[]}, - RH {id: 11, - sub: &[]}]}, - dscope); + let dscope = self.infcx + .tcx + .region_maps + .intern_code_extent(CodeExtentData::DestructionScope(1), + region::ROOT_CODE_EXTENT); + self.create_region_hierarchy(&RH { + id: 1, + sub: &[RH { id: 10, sub: &[] }, RH { id: 11, sub: &[] }], + }, + dscope); } #[allow(dead_code)] // this seems like it could be useful, even if we don't use it now @@ -197,30 +191,32 @@ impl<'a, 'tcx> Env<'a, 'tcx> { assert!(idx < names.len()); for item in &m.items { if item.name.to_string() == names[idx] { - return search(this, &**item, idx+1, names); + return search(this, &**item, idx + 1, names); } } return None; } - fn search(this: &Env, - it: &hir::Item, - idx: usize, - names: &[String]) - -> Option { + fn search(this: &Env, it: &hir::Item, idx: usize, names: &[String]) -> Option { if idx == names.len() { return Some(it.id); } return match it.node { - hir::ItemUse(..) | hir::ItemExternCrate(..) | - hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) | - hir::ItemForeignMod(..) | hir::ItemTy(..) => { + hir::ItemUse(..) | + hir::ItemExternCrate(..) | + hir::ItemConst(..) | + hir::ItemStatic(..) | + hir::ItemFn(..) | + hir::ItemForeignMod(..) | + hir::ItemTy(..) => { None } - hir::ItemEnum(..) | hir::ItemStruct(..) | - hir::ItemTrait(..) | hir::ItemImpl(..) | + hir::ItemEnum(..) | + hir::ItemStruct(..) | + hir::ItemTrait(..) | + hir::ItemImpl(..) | hir::ItemDefaultImpl(..) => { None } @@ -235,14 +231,14 @@ impl<'a, 'tcx> Env<'a, 'tcx> { pub fn make_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool { match infer::mk_subty(self.infcx, true, infer::Misc(DUMMY_SP), a, b) { Ok(_) => true, - Err(ref e) => panic!("Encountered error: {}", e) + Err(ref e) => panic!("Encountered error: {}", e), } } pub fn is_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool { match infer::can_mk_subty(self.infcx, a, b) { Ok(_) => true, - Err(_) => false + Err(_) => false, } } @@ -257,22 +253,18 @@ impl<'a, 'tcx> Env<'a, 'tcx> { self.assert_subtype(b, a); } - pub fn t_fn(&self, - input_tys: &[Ty<'tcx>], - output_ty: Ty<'tcx>) - -> Ty<'tcx> - { + pub fn t_fn(&self, input_tys: &[Ty<'tcx>], output_ty: Ty<'tcx>) -> Ty<'tcx> { let input_args = input_tys.iter().cloned().collect(); self.infcx.tcx.mk_fn(None, - self.infcx.tcx.mk_bare_fn(ty::BareFnTy { - unsafety: hir::Unsafety::Normal, - abi: abi::Rust, - sig: ty::Binder(ty::FnSig { - inputs: input_args, - output: ty::FnConverging(output_ty), - variadic: false - }) - })) + self.infcx.tcx.mk_bare_fn(ty::BareFnTy { + unsafety: hir::Unsafety::Normal, + abi: abi::Rust, + sig: ty::Binder(ty::FnSig { + inputs: input_args, + output: ty::FnConverging(output_ty), + variadic: false, + }), + })) } pub fn t_nil(&self) -> Ty<'tcx> { @@ -292,14 +284,13 @@ impl<'a, 'tcx> Env<'a, 'tcx> { space: subst::ParamSpace, index: u32, name: &'static str) - -> ty::Region - { + -> ty::Region { let name = token::intern(name); ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: self.infcx.tcx.map.local_def_id(ast::DUMMY_NODE_ID), space: space, index: index, - name: name + name: name, }) } @@ -308,14 +299,12 @@ impl<'a, 'tcx> Env<'a, 'tcx> { } pub fn t_rptr(&self, r: ty::Region) -> Ty<'tcx> { - self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), - self.tcx().types.isize) + self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), self.tcx().types.isize) } pub fn t_rptr_late_bound(&self, id: u32) -> Ty<'tcx> { let r = self.re_late_bound_with_debruijn(id, ty::DebruijnIndex::new(1)); - self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), - self.tcx().types.isize) + self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), self.tcx().types.isize) } pub fn t_rptr_late_bound_with_debruijn(&self, @@ -323,32 +312,29 @@ impl<'a, 'tcx> Env<'a, 'tcx> { debruijn: ty::DebruijnIndex) -> Ty<'tcx> { let r = self.re_late_bound_with_debruijn(id, debruijn); - self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), - self.tcx().types.isize) + self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), self.tcx().types.isize) } pub fn t_rptr_scope(&self, id: ast::NodeId) -> Ty<'tcx> { let r = ty::ReScope(self.tcx().region_maps.node_extent(id)); - self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), - self.tcx().types.isize) + self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), self.tcx().types.isize) } pub fn re_free(&self, nid: ast::NodeId, id: u32) -> ty::Region { ty::ReFree(ty::FreeRegion { scope: self.tcx().region_maps.item_extent(nid), - bound_region: ty::BrAnon(id) + bound_region: ty::BrAnon(id), }) } pub fn t_rptr_free(&self, nid: ast::NodeId, id: u32) -> Ty<'tcx> { let r = self.re_free(nid, id); - self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), - self.tcx().types.isize) + self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), self.tcx().types.isize) } pub fn t_rptr_static(&self) -> Ty<'tcx> { self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(ty::ReStatic), - self.tcx().types.isize) + self.tcx().types.isize) } pub fn dummy_type_trace(&self) -> infer::TypeTrace<'tcx> { @@ -373,7 +359,7 @@ impl<'a, 'tcx> Env<'a, 'tcx> { pub fn make_lub_ty(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> Ty<'tcx> { match self.lub().relate(&t1, &t2) { Ok(t) => t, - Err(ref e) => panic!("unexpected error computing LUB: {}", e) + Err(ref e) => panic!("unexpected error computing LUB: {}", e), } } @@ -381,12 +367,9 @@ impl<'a, 'tcx> Env<'a, 'tcx> { /// region checks). pub fn check_sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) { match self.sub().relate(&t1, &t2) { - Ok(_) => { } + Ok(_) => {} Err(ref e) => { - panic!("unexpected error computing sub({:?},{:?}): {}", - t1, - t2, - e); + panic!("unexpected error computing sub({:?},{:?}): {}", t1, t2, e); } } } @@ -395,11 +378,9 @@ impl<'a, 'tcx> Env<'a, 'tcx> { /// region checks). pub fn check_not_sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) { match self.sub().relate(&t1, &t2) { - Err(_) => { } + Err(_) => {} Ok(_) => { - panic!("unexpected success computing sub({:?},{:?})", - t1, - t2); + panic!("unexpected success computing sub({:?},{:?})", t1, t2); } } } @@ -448,18 +429,16 @@ fn contravariant_region_ptr_ok() { #[test] fn contravariant_region_ptr_err() { - test_env(EMPTY_SOURCE_STR, - errors(&["lifetime mismatch"]), - |env| { - env.create_simple_region_hierarchy(); - let t_rptr1 = env.t_rptr_scope(1); - let t_rptr10 = env.t_rptr_scope(10); - env.assert_eq(t_rptr1, t_rptr1); - env.assert_eq(t_rptr10, t_rptr10); + test_env(EMPTY_SOURCE_STR, errors(&["lifetime mismatch"]), |env| { + env.create_simple_region_hierarchy(); + let t_rptr1 = env.t_rptr_scope(1); + let t_rptr10 = env.t_rptr_scope(10); + env.assert_eq(t_rptr1, t_rptr1); + env.assert_eq(t_rptr10, t_rptr10); // will cause an error when regions are resolved - env.make_subtype(t_rptr10, t_rptr1); - }) + env.make_subtype(t_rptr10, t_rptr1); + }) } #[test] @@ -594,14 +573,14 @@ fn lub_free_free() { #[test] fn lub_returning_scope() { test_env(EMPTY_SOURCE_STR, - errors(&["cannot infer an appropriate lifetime"]), |env| { + errors(&["cannot infer an appropriate lifetime"]), + |env| { env.create_simple_region_hierarchy(); let t_rptr_scope10 = env.t_rptr_scope(10); let t_rptr_scope11 = env.t_rptr_scope(11); // this should generate an error when regions are resolved - env.make_lub_ty(env.t_fn(&[], t_rptr_scope10), - env.t_fn(&[], t_rptr_scope11)); + env.make_lub_ty(env.t_fn(&[], t_rptr_scope10), env.t_fn(&[], t_rptr_scope11)); }) } @@ -657,8 +636,10 @@ fn glb_bound_free_infer() { // `&'_ isize` let t_resolve1 = env.infcx.shallow_resolve(t_infer1); match t_resolve1.sty { - ty::TyRef(..) => { } - _ => { panic!("t_resolve1={:?}", t_resolve1); } + ty::TyRef(..) => {} + _ => { + panic!("t_resolve1={:?}", t_resolve1); + } } }) } @@ -819,11 +800,9 @@ fn walk_ty() { let tup2_ty = tcx.mk_tup(vec!(tup1_ty, tup1_ty, uint_ty)); let uniq_ty = tcx.mk_box(tup2_ty); let walked: Vec<_> = uniq_ty.walk().collect(); - assert_eq!(walked, [uniq_ty, - tup2_ty, - tup1_ty, int_ty, uint_ty, int_ty, uint_ty, - tup1_ty, int_ty, uint_ty, int_ty, uint_ty, - uint_ty]); + assert_eq!(walked, + [uniq_ty, tup2_ty, tup1_ty, int_ty, uint_ty, int_ty, uint_ty, tup1_ty, int_ty, + uint_ty, int_ty, uint_ty, uint_ty]); }) } @@ -855,7 +834,9 @@ fn walk_ty_skip_subtree() { debug!("walked to {:?}", t); let (expected_ty, skip) = expected.pop().unwrap(); assert_eq!(t, expected_ty); - if skip { walker.skip_current_subtree(); } + if skip { + walker.skip_current_subtree(); + } } assert!(expected.is_empty()); From 59a3518f1276bed45f36b4d3e50063c7e10eba95 Mon Sep 17 00:00:00 2001 From: Jose Narvaez Date: Wed, 14 Oct 2015 18:33:08 +0100 Subject: [PATCH 03/12] Manual fixups done. --- src/librustc_driver/driver.rs | 90 +++++++++++++++++------------------ src/librustc_driver/lib.rs | 17 ++++--- src/librustc_driver/pretty.rs | 3 +- 3 files changed, 54 insertions(+), 56 deletions(-) diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index fff91c3731af8..aa16555a56cb3 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -137,40 +137,40 @@ pub fn compile_input(sess: Session, control.make_glob_map, |tcx, analysis| { - { - let state = - CompileState::state_after_analysis(input, - &tcx.sess, - outdir, - &expanded_crate, - tcx.map.krate(), - &analysis, - tcx, - &lcx); - (control.after_analysis.callback)(state); - - tcx.sess.abort_if_errors(); - if control.after_analysis.stop == Compilation::Stop { - return Err(()); - } - } - - if log_enabled!(::log::INFO) { - println!("Pre-trans"); - tcx.print_debug_stats(); - } - let trans = phase_4_translate_to_llvm(tcx, analysis); - - if log_enabled!(::log::INFO) { - println!("Post-trans"); - tcx.print_debug_stats(); - } + { + let state = + CompileState::state_after_analysis(input, + &tcx.sess, + outdir, + &expanded_crate, + tcx.map.krate(), + &analysis, + tcx, + &lcx); + (control.after_analysis.callback)(state); + + tcx.sess.abort_if_errors(); + if control.after_analysis.stop == Compilation::Stop { + return Err(()); + } + } + + if log_enabled!(::log::INFO) { + println!("Pre-trans"); + tcx.print_debug_stats(); + } + let trans = phase_4_translate_to_llvm(tcx, analysis); + + if log_enabled!(::log::INFO) { + println!("Post-trans"); + tcx.print_debug_stats(); + } // Discard interned strings as they are no longer required. - token::get_ident_interner().clear(); + token::get_ident_interner().clear(); - Ok((outputs, trans)) - }) + Ok((outputs, trans)) + }) }; let (outputs, trans) = if let Ok(out) = result { @@ -708,7 +708,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session, stability::Index::new(krate), |tcx| { - // passes are timed inside typeck + // passes are timed inside typeck typeck::check_crate(tcx, trait_map); time(time_passes, @@ -722,7 +722,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session, external_exports) }); - // Do not move this check past lint + // Do not move this check past lint time(time_passes, "stability index", || { tcx.stability.borrow_mut().build(tcx, krate, &public_items) }); @@ -755,11 +755,11 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session, "rvalue checking", || middle::check_rvalues::check_crate(tcx, krate)); - // Avoid overwhelming user with errors if type checking failed. - // I'm not sure how helpful this is, to be honest, but it avoids a - // lot of annoying errors in the compile-fail tests (basically, - // lint warnings and so on -- kindck used to do this abort, but - // kindck is gone now). -nmatsakis + // Avoid overwhelming user with errors if type checking failed. + // I'm not sure how helpful this is, to be honest, but it avoids a + // lot of annoying errors in the compile-fail tests (basically, + // lint warnings and so on -- kindck used to do this abort, but + // kindck is gone now). -nmatsakis tcx.sess.abort_if_errors(); let reachable_map = @@ -787,7 +787,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session, "lint checking", || lint::check_crate(tcx, krate, &exported_items)); - // The above three passes generate errors w/o aborting + // The above three passes generate errors w/o aborting tcx.sess.abort_if_errors(); f(tcx, @@ -859,7 +859,7 @@ pub fn phase_6_link_output(sess: &Session, fn escape_dep_filename(filename: &str) -> String { // Apparently clang and gcc *only* escape spaces: // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4 - filename.replace(" ", "\") + filename.replace(" ", "\\") } fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) { @@ -887,8 +887,8 @@ fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) { let result = (|| -> io::Result<()> { - // Build a list of files used to compile the output and - // write Makefile-compatible dependency rules + // Build a list of files used to compile the output and + // write Makefile-compatible dependency rules let files: Vec = sess.codemap() .files .borrow() @@ -902,9 +902,9 @@ fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) { try!(write!(file, "{}: {}\n\n", path.display(), files.join(" "))); } - // Emit a fake target for each input file to the compilation. This - // prevents `make` from spitting out an error if a file is later - // deleted. For more info see #28735 + // Emit a fake target for each input file to the compilation. This + // prevents `make` from spitting out an error if a file is later + // deleted. For more info see #28735 for path in files { try!(writeln!(file, "{}:", path)); } diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 09f1867de1f0c..b3aaba61de568 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -153,7 +153,8 @@ pub fn run_compiler<'a>(args: &[String], callbacks: &mut CompilerCalls<'a>) { pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile); return; } - None => {/* continue */ + // continue + None => { } } @@ -509,6 +510,7 @@ pub fn version(binary: &str, matches: &getopts::Matches) { } } +#[rustfmt_skip] fn usage(verbose: bool, include_unstable_options: bool) { let groups = if verbose { config::rustc_optgroups() @@ -527,23 +529,20 @@ fn usage(verbose: bool, include_unstable_options: bool) { }; println!("{}\nAdditional help: -C help Print codegen options - -W help \ - Print 'lint' options and default settings - -Z help Print internal \ - options for debugging rustc{}\n", + -W help Print 'lint' options and default settings + -Z help Print internal options for debugging rustc{}\n", getopts::usage(&message, &groups), extra_help); } +#[rustfmt_skip] fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) { println!(" Available lint options: -W Warn about - -A \ - Allow + -A Allow -D Deny - -F Forbid \ - (deny, and deny all overrides) + -F Forbid deny, and deny all overrides) "); diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index c05993dc15d2a..03c8ac8bf2d58 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -793,8 +793,7 @@ pub fn pretty_print_input(sess: Session, debug!("pretty printing flow graph for {:?}", opt_uii); let uii = opt_uii.unwrap_or_else(|| { sess.fatal(&format!("`pretty flowgraph=..` needs NodeId (int) or - \ - unique path suffix (b::c::d)")) + unique path suffix (b::c::d)")) }); let ast_map = ast_map.expect("--pretty flowgraph missing ast_map"); From 00c4f06292d707b18990a326c51d90b8273ef20a Mon Sep 17 00:00:00 2001 From: Jose Narvaez Date: Wed, 14 Oct 2015 18:43:36 +0100 Subject: [PATCH 04/12] Manual fixups. --- src/libarena/lib.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index 4c383edd5d7ce..0d599f736e622 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -200,8 +200,7 @@ struct TyDesc { align: usize, } -trait AllTypes { fn dummy(&self) { - } } +trait AllTypes { fn dummy(&self) { } } impl AllTypes for T { } unsafe fn get_tydesc() -> *const TyDesc { @@ -293,8 +292,7 @@ impl<'longer_than_self> Arena<'longer_than_self> { unsafe { let buf = head.as_ptr(); - (buf.offset(tydesc_start as isize), - buf.offset(start as isize)) + (buf.offset(tydesc_start as isize), buf.offset(start as isize)) } } @@ -392,7 +390,8 @@ struct TypedArenaChunk { next: *mut TypedArenaChunk, /// The number of elements that this chunk can hold. - capacity: usize, // Objects follow here, suitably aligned. + // Objects follow here, suitably aligned. + capacity: usize, } fn calculate_size(capacity: usize) -> usize { From 605fef297440b566e37299bb2d4b31743b634dcf Mon Sep 17 00:00:00 2001 From: Jose Narvaez Date: Thu, 15 Oct 2015 11:00:01 +0100 Subject: [PATCH 05/12] Added attributes to allow custom attibutes in librustc_driver. --- src/librustc_driver/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index b3aaba61de568..3af0dec809ad2 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -33,6 +33,8 @@ #![feature(set_stdio)] #![feature(staged_api)] #![feature(vec_push_all)] +#![feature(custom_attribute)] +#![allow(unused_attributes)] extern crate arena; extern crate flate; From e7be2c3e99d3bf7287906c4c35c6822784924b10 Mon Sep 17 00:00:00 2001 From: Jose Narvaez Date: Thu, 15 Oct 2015 14:56:03 +0100 Subject: [PATCH 06/12] Fixed comment. --- src/libarena/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index 0d599f736e622..7faaf5d332e32 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -390,8 +390,9 @@ struct TypedArenaChunk { next: *mut TypedArenaChunk, /// The number of elements that this chunk can hold. - // Objects follow here, suitably aligned. capacity: usize, + + // Objects follow here, suitably aligned. } fn calculate_size(capacity: usize) -> usize { From b8e8561e1a67e8d3d82a2450f288438004aba1c5 Mon Sep 17 00:00:00 2001 From: Cristi Cobzarenco Date: Tue, 13 Oct 2015 21:55:34 +0100 Subject: [PATCH 07/12] std: add into_inner and get_mut to mutex --- src/libstd/sync/mutex.rs | 115 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index f1d264b38a0c7..aabc06b1986f5 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -13,7 +13,9 @@ use prelude::v1::*; use cell::UnsafeCell; use fmt; use marker; +use mem; use ops::{Deref, DerefMut}; +use ptr; use sys_common::mutex as sys; use sys_common::poison::{self, TryLockError, TryLockResult, LockResult}; @@ -243,6 +245,50 @@ impl Mutex { pub fn is_poisoned(&self) -> bool { self.inner.poison.get() } + + /// Consumes this mutex, returning the underlying data. + /// + /// # Failure + /// + /// If another user of this mutex panicked while holding the mutex, then + /// this call will return an error instead. + #[unstable(feature = "mutex_into_inner", reason = "recently added", issue = "28968")] + pub fn into_inner(self) -> LockResult where T: Sized { + // We know statically that there are no outstanding references to + // `self` so there's no need to lock the inner StaticMutex. + // + // To get the inner value, we'd like to call `data.into_inner()`, + // but because `Mutex` impl-s `Drop`, we can't move out of it, so + // we'll have to destructure it manually instead. + unsafe { + // Like `let Mutex { inner, data } = self`. + let (inner, data) = { + let Mutex { ref inner, ref data } = self; + (ptr::read(inner), ptr::read(data)) + }; + mem::forget(self); + inner.lock.destroy(); // Keep in sync with the `Drop` impl. + + poison::map_result(inner.poison.borrow(), |_| data.into_inner()) + } + } + + /// Returns a mutable reference to the underlying data. + /// + /// Since this call borrows the `Mutex` mutably, no actual locking needs to + /// take place---the mutable borrow statically guarantees no locks exist. + /// + /// # Failure + /// + /// If another user of this mutex panicked while holding the mutex, then + /// this call will return an error instead. + #[unstable(feature = "mutex_get_mut", reason = "recently added", issue = "28968")] + pub fn get_mut(&mut self) -> LockResult<&mut T> { + // We know statically that there are no other references to `self`, so + // there's no need to lock the inner StaticMutex. + let data = unsafe { &mut *self.data.get() }; + poison::map_result(self.inner.poison.borrow(), |_| data ) + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -251,6 +297,8 @@ impl Drop for Mutex { // This is actually safe b/c we know that there is no further usage of // this mutex (it's up to the user to arrange for a mutex to get // dropped, that's not our job) + // + // IMPORTANT: This code must be kept in sync with `Mutex::into_inner`. unsafe { self.inner.lock.destroy() } } } @@ -371,10 +419,14 @@ mod tests { use sync::mpsc::channel; use sync::{Arc, Mutex, StaticMutex, Condvar}; + use sync::atomic::{AtomicUsize, Ordering}; use thread; struct Packet(Arc<(Mutex, Condvar)>); + #[derive(Eq, PartialEq, Debug)] + struct NonCopy(i32); + unsafe impl Send for Packet {} unsafe impl Sync for Packet {} @@ -435,6 +487,69 @@ mod tests { *m.try_lock().unwrap() = (); } + #[test] + fn test_into_inner() { + let m = Mutex::new(NonCopy(10)); + assert_eq!(m.into_inner().unwrap(), NonCopy(10)); + } + + #[test] + fn test_into_inner_drop() { + struct Foo(Arc); + impl Drop for Foo { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + let num_drops = Arc::new(AtomicUsize::new(0)); + let m = Mutex::new(Foo(num_drops.clone())); + assert_eq!(num_drops.load(Ordering::SeqCst), 0); + { + let _inner = m.into_inner().unwrap(); + assert_eq!(num_drops.load(Ordering::SeqCst), 0); + } + assert_eq!(num_drops.load(Ordering::SeqCst), 1); + } + + #[test] + fn test_into_inner_poison() { + let m = Arc::new(Mutex::new(NonCopy(10))); + let m2 = m.clone(); + let _ = thread::spawn(move || { + let _lock = m2.lock().unwrap(); + panic!("test panic in inner thread to poison mutex"); + }).join(); + + assert!(m.is_poisoned()); + match Arc::try_unwrap(m).unwrap().into_inner() { + Err(e) => assert_eq!(e.into_inner(), NonCopy(10)), + Ok(x) => panic!("into_inner of poisoned Mutex is Ok: {:?}", x), + } + } + + #[test] + fn test_get_mut() { + let mut m = Mutex::new(NonCopy(10)); + *m.get_mut().unwrap() = NonCopy(20); + assert_eq!(m.into_inner().unwrap(), NonCopy(20)); + } + + #[test] + fn test_get_mut_poison() { + let m = Arc::new(Mutex::new(NonCopy(10))); + let m2 = m.clone(); + let _ = thread::spawn(move || { + let _lock = m2.lock().unwrap(); + panic!("test panic in inner thread to poison mutex"); + }).join(); + + assert!(m.is_poisoned()); + match Arc::try_unwrap(m).unwrap().get_mut() { + Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)), + Ok(x) => panic!("get_mut of poisoned Mutex is Ok: {:?}", x), + } + } + #[test] fn test_mutex_arc_condvar() { let packet = Packet(Arc::new((Mutex::new(false), Condvar::new()))); From 90ccefd16e1eeec1a616aa3ba9aa710d954231ef Mon Sep 17 00:00:00 2001 From: Cristi Cobzarenco Date: Thu, 15 Oct 2015 17:14:06 +0100 Subject: [PATCH 08/12] std: add into_inner and get_mut to RwLock --- src/libstd/sync/rwlock.rs | 118 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 04ad47082464e..9278481f2d62b 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -13,7 +13,9 @@ use prelude::v1::*; use cell::UnsafeCell; use fmt; use marker; +use mem; use ops::{Deref, DerefMut}; +use ptr; use sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; use sys_common::rwlock as sys; @@ -260,11 +262,60 @@ impl RwLock { pub fn is_poisoned(&self) -> bool { self.inner.poison.get() } + + /// Consumes this `RwLock`, returning the underlying data. + /// + /// # Failure + /// + /// This function will return an error if the RwLock is poisoned. An RwLock + /// is poisoned whenever a writer panics while holding an exclusive lock. An + /// error will only be returned if the lock would have otherwise been + /// acquired. + #[unstable(feature = "rwlock_into_inner", reason = "recently added", issue = "28968")] + pub fn into_inner(self) -> LockResult where T: Sized { + // We know statically that there are no outstanding references to + // `self` so there's no need to lock the inner StaticRwLock. + // + // To get the inner value, we'd like to call `data.into_inner()`, + // but because `RwLock` impl-s `Drop`, we can't move out of it, so + // we'll have to destructure it manually instead. + unsafe { + // Like `let RwLock { inner, data } = self`. + let (inner, data) = { + let RwLock { ref inner, ref data } = self; + (ptr::read(inner), ptr::read(data)) + }; + mem::forget(self); + inner.lock.destroy(); // Keep in sync with the `Drop` impl. + + poison::map_result(inner.poison.borrow(), |_| data.into_inner()) + } + } + + /// Returns a mutable reference to the underlying data. + /// + /// Since this call borrows the `RwLock` mutably, no actual locking needs to + /// take place---the mutable borrow statically guarantees no locks exist. + /// + /// # Failure + /// + /// This function will return an error if the RwLock is poisoned. An RwLock + /// is poisoned whenever a writer panics while holding an exclusive lock. An + /// error will only be returned if the lock would have otherwise been + /// acquired. + #[unstable(feature = "rwlock_get_mut", reason = "recently added", issue = "28968")] + pub fn get_mut(&mut self) -> LockResult<&mut T> { + // We know statically that there are no other references to `self`, so + // there's no need to lock the inner StaticRwLock. + let data = unsafe { &mut *self.data.get() }; + poison::map_result(self.inner.poison.borrow(), |_| data ) + } } #[stable(feature = "rust1", since = "1.0.0")] impl Drop for RwLock { fn drop(&mut self) { + // IMPORTANT: This code needs to be kept in sync with `RwLock::into_inner`. unsafe { self.inner.lock.destroy() } } } @@ -426,6 +477,10 @@ mod tests { use sync::mpsc::channel; use thread; use sync::{Arc, RwLock, StaticRwLock, TryLockError}; + use sync::atomic::{AtomicUsize, Ordering}; + + #[derive(Eq, PartialEq, Debug)] + struct NonCopy(i32); #[test] fn smoke() { @@ -606,4 +661,67 @@ mod tests { drop(read_guard); } + + #[test] + fn test_into_inner() { + let m = RwLock::new(NonCopy(10)); + assert_eq!(m.into_inner().unwrap(), NonCopy(10)); + } + + #[test] + fn test_into_inner_drop() { + struct Foo(Arc); + impl Drop for Foo { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + let num_drops = Arc::new(AtomicUsize::new(0)); + let m = RwLock::new(Foo(num_drops.clone())); + assert_eq!(num_drops.load(Ordering::SeqCst), 0); + { + let _inner = m.into_inner().unwrap(); + assert_eq!(num_drops.load(Ordering::SeqCst), 0); + } + assert_eq!(num_drops.load(Ordering::SeqCst), 1); + } + + #[test] + fn test_into_inner_poison() { + let m = Arc::new(RwLock::new(NonCopy(10))); + let m2 = m.clone(); + let _ = thread::spawn(move || { + let _lock = m2.write().unwrap(); + panic!("test panic in inner thread to poison RwLock"); + }).join(); + + assert!(m.is_poisoned()); + match Arc::try_unwrap(m).unwrap().into_inner() { + Err(e) => assert_eq!(e.into_inner(), NonCopy(10)), + Ok(x) => panic!("into_inner of poisoned RwLock is Ok: {:?}", x), + } + } + + #[test] + fn test_get_mut() { + let mut m = RwLock::new(NonCopy(10)); + *m.get_mut().unwrap() = NonCopy(20); + assert_eq!(m.into_inner().unwrap(), NonCopy(20)); + } + + #[test] + fn test_get_mut_poison() { + let m = Arc::new(RwLock::new(NonCopy(10))); + let m2 = m.clone(); + let _ = thread::spawn(move || { + let _lock = m2.write().unwrap(); + panic!("test panic in inner thread to poison RwLock"); + }).join(); + + assert!(m.is_poisoned()); + match Arc::try_unwrap(m).unwrap().get_mut() { + Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)), + Ok(x) => panic!("get_mut of poisoned RwLock is Ok: {:?}", x), + } + } } From 48c90a38c10ea29897bb4b1f62b2765fca0c293d Mon Sep 17 00:00:00 2001 From: "Ryan Scheel (Havvy)" Date: Thu, 15 Oct 2015 19:35:39 +0000 Subject: [PATCH 09/12] Remove outdated Changing directory. --- src/doc/style/SUMMARY.md | 4 ---- src/doc/style/changing/README.md | 5 ----- src/doc/style/changing/post-1-0.md | 12 ------------ src/doc/style/changing/pre-1-0.md | 17 ----------------- src/doc/style/changing/unclear.md | 28 ---------------------------- 5 files changed, 66 deletions(-) delete mode 100644 src/doc/style/changing/README.md delete mode 100644 src/doc/style/changing/post-1-0.md delete mode 100644 src/doc/style/changing/pre-1-0.md delete mode 100644 src/doc/style/changing/unclear.md diff --git a/src/doc/style/SUMMARY.md b/src/doc/style/SUMMARY.md index 41bc08f229e7c..508ede6c4a0ac 100644 --- a/src/doc/style/SUMMARY.md +++ b/src/doc/style/SUMMARY.md @@ -48,7 +48,3 @@ * [Testing](testing/README.md) * [Unit testing](testing/unit.md) * [FFI, platform-specific code](platform.md) -* [APIs for a changing Rust](changing/README.md) - * [Pre-1.0 changes](changing/pre-1-0.md) - * [Post-1.0 changes](changing/post-1-0.md) - * [Timing unclear](changing/unclear.md) diff --git a/src/doc/style/changing/README.md b/src/doc/style/changing/README.md deleted file mode 100644 index 38e76f6970c81..0000000000000 --- a/src/doc/style/changing/README.md +++ /dev/null @@ -1,5 +0,0 @@ -% API design for a changing Rust - -A number of planned Rust features will drastically affect the API design -story. This section collects some of the biggest features with concrete examples -of how the API will change. diff --git a/src/doc/style/changing/post-1-0.md b/src/doc/style/changing/post-1-0.md deleted file mode 100644 index 7ac1c837c071f..0000000000000 --- a/src/doc/style/changing/post-1-0.md +++ /dev/null @@ -1,12 +0,0 @@ -% Post-1.0 changes - -### Higher-kinded types - -* A trait encompassing both `Iterable` for some fixed `T` and - `FromIterator` for _all_ `U` (where HKT comes in). The train - could provide e.g. a default `map` method producing the same kind of - the container, but with a new type parameter. - -* **Monadic-generic programming**? Can we add this without deprecating - huge swaths of the API (including `Option::map`, `option::collect`, - `result::collect`, `try!` etc. diff --git a/src/doc/style/changing/pre-1-0.md b/src/doc/style/changing/pre-1-0.md deleted file mode 100644 index adadfe31a59d1..0000000000000 --- a/src/doc/style/changing/pre-1-0.md +++ /dev/null @@ -1,17 +0,0 @@ -% Pre-1.0 changes - -### `std` facade - -We should revisit some APIs in `libstd` now that the facade effort is complete. - -For example, the treatment of environment variables in the new -`Command` API is waiting on access to hashtables before being -approved. - -### Trait reform - -Potential for standard conversion traits (`to`, `into`, `as`). - -Probably many other opportunities here. - -### Unboxed closures diff --git a/src/doc/style/changing/unclear.md b/src/doc/style/changing/unclear.md deleted file mode 100644 index e4b8a98e1a162..0000000000000 --- a/src/doc/style/changing/unclear.md +++ /dev/null @@ -1,28 +0,0 @@ -% Changes with unclear timing - -### Associated items - -* Many traits that currently take type parameters should instead use associated - types; this will _drastically_ simplify signatures in some cases. - -* Associated constants would be useful in a few places, e.g. traits for - numerics, traits for paths. - -### Anonymous, unboxed return types (aka `impl Trait` types) - -* See https://github.com/rust-lang/rfcs/pull/105 - -* Could affect API design in several places, e.g. the `Iterator` trait. - -### Default type parameters - -We are already using this in a few places (e.g. `HashMap`), but it's -feature-gated. - -### Compile-time function evaluation (CTFE) - -https://github.com/mozilla/rust/issues/11621 - -### Improved constant folding - -https://github.com/rust-lang/rust/issues/7834 From 11e65ebe31751484a82e64e76326b24aa6e69a42 Mon Sep 17 00:00:00 2001 From: Matt Brubeck Date: Thu, 15 Oct 2015 13:52:51 -0700 Subject: [PATCH 10/12] Fix minor error in Arc docs The text says it's a vector of floats, but the code actually uses a vector of integers. The type of the Vec doesn't really matter, so I just cut it from the text. --- src/liballoc/arc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 8c12b9d94ba91..d8f10e6780f88 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -93,7 +93,7 @@ const MAX_REFCOUNT: usize = (isize::MAX) as usize; /// /// # Examples /// -/// In this example, a large vector of floats is shared between several threads. +/// In this example, a large vector is shared between several threads. /// With simple pipes, without `Arc`, a copy would have to be made for each /// thread. /// From 6aa5237e279498a36d58da7e3589cc2570a2b3ce Mon Sep 17 00:00:00 2001 From: Florian Hahn Date: Thu, 15 Oct 2015 21:07:20 +0200 Subject: [PATCH 11/12] Add unused modules to libcoretest --- src/libcoretest/clone.rs | 20 +++----------------- src/libcoretest/fmt/mod.rs | 3 ++- src/libcoretest/intrinsics.rs | 2 +- src/libcoretest/lib.rs | 2 ++ 4 files changed, 8 insertions(+), 19 deletions(-) diff --git a/src/libcoretest/clone.rs b/src/libcoretest/clone.rs index 5ab6ab27ba1d0..91d68ba33447a 100644 --- a/src/libcoretest/clone.rs +++ b/src/libcoretest/clone.rs @@ -1,4 +1,4 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -11,8 +11,8 @@ #[test] fn test_borrowed_clone() { let x = 5; - let y: &int = &x; - let z: &int = (&y).clone(); + let y: &i32 = &x; + let z: &i32 = (&y).clone(); assert_eq!(*z, 5); } @@ -23,17 +23,3 @@ fn test_clone_from() { b.clone_from(&a); assert_eq!(*b, 5); } - -#[test] -fn test_extern_fn_clone() { - trait Empty {} - impl Empty for int {} - - fn test_fn_a() -> f64 { 1.0 } - fn test_fn_b(x: T) -> T { x } - fn test_fn_c(_: int, _: f64, _: int, _: int, _: int) {} - - let _ = test_fn_a.clone(); - let _ = test_fn_b::.clone(); - let _ = test_fn_c.clone(); -} diff --git a/src/libcoretest/fmt/mod.rs b/src/libcoretest/fmt/mod.rs index 42872589bb01f..99ea39c619f77 100644 --- a/src/libcoretest/fmt/mod.rs +++ b/src/libcoretest/fmt/mod.rs @@ -8,8 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -mod num; mod builders; +mod float; +mod num; #[test] fn test_format_flags() { diff --git a/src/libcoretest/intrinsics.rs b/src/libcoretest/intrinsics.rs index c99fb8c197d83..2b380abf63c58 100644 --- a/src/libcoretest/intrinsics.rs +++ b/src/libcoretest/intrinsics.rs @@ -12,7 +12,7 @@ use core::any::TypeId; #[test] fn test_typeid_sized_types() { - struct X; struct Y(uint); + struct X; struct Y(u32); assert_eq!(TypeId::of::(), TypeId::of::()); assert_eq!(TypeId::of::(), TypeId::of::()); diff --git a/src/libcoretest/lib.rs b/src/libcoretest/lib.rs index 22b285b034399..96886c9104876 100644 --- a/src/libcoretest/lib.rs +++ b/src/libcoretest/lib.rs @@ -54,9 +54,11 @@ mod array; mod atomic; mod cell; mod char; +mod clone; mod cmp; mod fmt; mod hash; +mod intrinsics; mod iter; mod mem; mod nonzero; From 128ded71100f02026fd03a4c13e1333cd633cac9 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Fri, 16 Oct 2015 00:33:45 +0300 Subject: [PATCH 12/12] Make NonZero::new const function --- src/libcore/nonzero.rs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/libcore/nonzero.rs b/src/libcore/nonzero.rs index c945e4e066159..2cf8bad60cd41 100644 --- a/src/libcore/nonzero.rs +++ b/src/libcore/nonzero.rs @@ -38,13 +38,31 @@ unsafe impl Zeroable for u64 {} #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)] pub struct NonZero(T); +#[cfg(stage0)] +macro_rules! nonzero_new { + () => ( + /// Creates an instance of NonZero with the provided value. + /// You must indeed ensure that the value is actually "non-zero". + #[inline(always)] + pub unsafe fn new(inner: T) -> NonZero { + NonZero(inner) + } + ) +} +#[cfg(not(stage0))] +macro_rules! nonzero_new { + () => ( + /// Creates an instance of NonZero with the provided value. + /// You must indeed ensure that the value is actually "non-zero". + #[inline(always)] + pub unsafe const fn new(inner: T) -> NonZero { + NonZero(inner) + } + ) +} + impl NonZero { - /// Creates an instance of NonZero with the provided value. - /// You must indeed ensure that the value is actually "non-zero". - #[inline(always)] - pub unsafe fn new(inner: T) -> NonZero { - NonZero(inner) - } + nonzero_new!{} } impl Deref for NonZero {