Auto merge of #28857 - nrc:lowering, r=nikomatsakis

r? @nikomatsakis
This commit is contained in:
bors 2015-10-09 08:53:45 +00:00
commit c14609035d
39 changed files with 1603 additions and 889 deletions

View File

@ -61,51 +61,55 @@ HOST_CRATES := syntax $(RUSTC_CRATES) rustdoc fmt_macros
TOOLS := compiletest rustdoc rustc rustbook error-index-generator
DEPS_core :=
DEPS_libc := core
DEPS_rustc_unicode := core
DEPS_alloc := core libc alloc_system
DEPS_alloc_system := core libc
DEPS_collections := core alloc rustc_unicode
DEPS_libc := core
DEPS_rand := core
DEPS_rustc_bitflags := core
DEPS_rustc_unicode := core
DEPS_std := core libc rand alloc collections rustc_unicode \
native:rust_builtin native:backtrace \
alloc_system
DEPS_arena := std
DEPS_glob := std
DEPS_flate := std native:miniz
DEPS_fmt_macros = std
DEPS_getopts := std
DEPS_graphviz := std
DEPS_log := std
DEPS_num := std
DEPS_rbml := std log serialize
DEPS_serialize := std log
DEPS_term := std log
DEPS_test := std getopts serialize rbml term native:rust_test_helpers
DEPS_syntax := std term serialize log fmt_macros arena libc rustc_bitflags
DEPS_rustc := syntax flate arena serialize getopts rbml rustc_front\
log graphviz rustc_llvm rustc_back rustc_data_structures
DEPS_rustc_back := std syntax rustc_llvm rustc_front flate log libc
DEPS_rustc_borrowck := rustc rustc_front log graphviz syntax
DEPS_rustc_data_structures := std log serialize
DEPS_rustc_driver := arena flate getopts graphviz libc rustc rustc_back rustc_borrowck \
rustc_typeck rustc_mir rustc_resolve log syntax serialize rustc_llvm \
rustc_trans rustc_privacy rustc_lint rustc_front
DEPS_rustc_trans := arena flate getopts graphviz libc rustc rustc_back \
log syntax serialize rustc_llvm rustc_front rustc_platform_intrinsics
DEPS_rustc_mir := rustc rustc_front syntax
DEPS_rustc_typeck := rustc syntax rustc_front rustc_platform_intrinsics
DEPS_rustc_borrowck := rustc rustc_front log graphviz syntax
DEPS_rustc_resolve := rustc rustc_front log syntax
DEPS_rustc_privacy := rustc rustc_front log syntax
DEPS_rustc_lint := rustc log syntax
DEPS_rustc := syntax flate arena serialize getopts rbml \
log graphviz rustc_llvm rustc_back rustc_data_structures
DEPS_rustc_llvm := native:rustllvm libc std rustc_bitflags
DEPS_rustc_platform_intrinsics := rustc rustc_llvm
DEPS_rustc_back := std syntax rustc_llvm rustc_front flate log libc
DEPS_rustc_front := std syntax log serialize
DEPS_rustc_data_structures := std log serialize
DEPS_rustc_lint := rustc log syntax
DEPS_rustc_llvm := native:rustllvm libc std rustc_bitflags
DEPS_rustc_mir := rustc rustc_front syntax
DEPS_rustc_resolve := rustc rustc_front log syntax
DEPS_rustc_platform_intrinsics := rustc rustc_llvm
DEPS_rustc_privacy := rustc rustc_front log syntax
DEPS_rustc_trans := arena flate getopts graphviz libc rustc rustc_back \
log syntax serialize rustc_llvm rustc_front rustc_platform_intrinsics
DEPS_rustc_typeck := rustc syntax rustc_front rustc_platform_intrinsics
DEPS_rustdoc := rustc rustc_driver native:hoedown serialize getopts \
test rustc_lint rustc_front
DEPS_rustc_bitflags := core
DEPS_flate := std native:miniz
DEPS_arena := std
DEPS_graphviz := std
DEPS_glob := std
DEPS_serialize := std log
DEPS_rbml := std log serialize
DEPS_term := std log
DEPS_getopts := std
DEPS_collections := core alloc rustc_unicode
DEPS_num := std
DEPS_test := std getopts serialize rbml term native:rust_test_helpers
DEPS_rand := core
DEPS_log := std
DEPS_fmt_macros = std
DEPS_alloc_system := core libc
TOOL_DEPS_compiletest := test getopts
TOOL_DEPS_rustdoc := rustdoc

View File

@ -36,6 +36,7 @@ use middle::subst;
use middle::ty::{self, Ty};
use syntax::{ast, ast_util, codemap};
use syntax::ast::NodeIdAssigner;
use syntax::codemap::Span;
use syntax::ptr::P;
@ -53,8 +54,9 @@ use serialize::EncoderHelpers;
#[cfg(test)] use std::io::Cursor;
#[cfg(test)] use syntax::parse;
#[cfg(test)] use syntax::ast::NodeId;
#[cfg(test)] use rustc_front::print::pprust;
#[cfg(test)] use rustc_front::lowering::lower_item;
#[cfg(test)] use rustc_front::lowering::{lower_item, LoweringContext};
struct DecodeContext<'a, 'b, 'tcx: 'a> {
tcx: &'a ty::ctxt<'tcx>,
@ -1376,6 +1378,22 @@ impl FakeExtCtxt for parse::ParseSess {
fn parse_sess(&self) -> &parse::ParseSess { self }
}
#[cfg(test)]
struct FakeNodeIdAssigner;
#[cfg(test)]
// It should go without saying that this may give unexpected results. Avoid
// lowering anything which needs new nodes.
impl NodeIdAssigner for FakeNodeIdAssigner {
fn next_node_id(&self) -> NodeId {
0
}
fn peek_node_id(&self) -> NodeId {
0
}
}
#[cfg(test)]
fn mk_ctxt() -> parse::ParseSess {
parse::ParseSess::new()
@ -1394,7 +1412,9 @@ fn roundtrip(in_item: P<hir::Item>) {
#[test]
fn test_basic() {
let cx = mk_ctxt();
roundtrip(lower_item(&quote_item!(&cx,
let fnia = FakeNodeIdAssigner;
let lcx = LoweringContext::new(&fnia, None);
roundtrip(lower_item(&lcx, &quote_item!(&cx,
fn foo() {}
).unwrap()));
}
@ -1402,7 +1422,9 @@ fn test_basic() {
#[test]
fn test_smalltalk() {
let cx = mk_ctxt();
roundtrip(lower_item(&quote_item!(&cx,
let fnia = FakeNodeIdAssigner;
let lcx = LoweringContext::new(&fnia, None);
roundtrip(lower_item(&lcx, &quote_item!(&cx,
fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
).unwrap()));
}
@ -1410,7 +1432,9 @@ fn test_smalltalk() {
#[test]
fn test_more() {
let cx = mk_ctxt();
roundtrip(lower_item(&quote_item!(&cx,
let fnia = FakeNodeIdAssigner;
let lcx = LoweringContext::new(&fnia, None);
roundtrip(lower_item(&lcx, &quote_item!(&cx,
fn foo(x: usize, y: usize) -> usize {
let z = x + y;
return z;
@ -1427,10 +1451,12 @@ fn test_simplification() {
return alist {eq_fn: eq_int, data: Vec::new()};
}
).unwrap();
let hir_item = lower_item(&item);
let fnia = FakeNodeIdAssigner;
let lcx = LoweringContext::new(&fnia, None);
let hir_item = lower_item(&lcx, &item);
let item_in = InlinedItemRef::Item(&hir_item);
let item_out = simplify_ast(item_in);
let item_exp = InlinedItem::Item(lower_item(&quote_item!(&cx,
let item_exp = InlinedItem::Item(lower_item(&lcx, &quote_item!(&cx,
fn new_int_alist<B>() -> alist<isize, B> {
return alist {eq_fn: eq_int, data: Vec::new()};
}

View File

@ -102,7 +102,6 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EffectCheckVisitor<'a, 'tcx> {
fn visit_block(&mut self, block: &hir::Block) {
let old_unsafe_context = self.unsafe_context;
match block.rules {
hir::DefaultBlock => {}
hir::UnsafeBlock(source) => {
// By default only the outermost `unsafe` block is
// "used" and so nested unsafe blocks are pointless
@ -131,6 +130,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EffectCheckVisitor<'a, 'tcx> {
self.unsafe_context.push_unsafe_count =
self.unsafe_context.push_unsafe_count.checked_sub(1).unwrap();
}
hir::DefaultBlock | hir::PushUnstableBlock | hir:: PopUnstableBlock => {}
}
visit::walk_block(self, block);

View File

@ -377,7 +377,7 @@ impl RegionMaps {
self.code_extents.borrow()[e.0 as usize]
}
pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent, &CodeExtent) {
for child_id in (1..self.code_extents.borrow().len()) {
for child_id in 1..self.code_extents.borrow().len() {
let child = CodeExtent(child_id as u32);
if let Some(parent) = self.opt_encl_scope(child) {
e(&child, &parent)

View File

@ -270,7 +270,8 @@ pub fn check_unstable_api_usage(tcx: &ty::ctxt)
let mut checker = Checker {
tcx: tcx,
active_features: active_features,
used_features: FnvHashMap()
used_features: FnvHashMap(),
in_skip_block: 0,
};
let krate = tcx.map.krate();
@ -283,14 +284,23 @@ pub fn check_unstable_api_usage(tcx: &ty::ctxt)
struct Checker<'a, 'tcx: 'a> {
tcx: &'a ty::ctxt<'tcx>,
active_features: FnvHashSet<InternedString>,
used_features: FnvHashMap<InternedString, attr::StabilityLevel>
used_features: FnvHashMap<InternedString, attr::StabilityLevel>,
// Within a block where feature gate checking can be skipped.
in_skip_block: u32,
}
impl<'a, 'tcx> Checker<'a, 'tcx> {
fn check(&mut self, id: DefId, span: Span, stab: &Option<&Stability>) {
// Only the cross-crate scenario matters when checking unstable APIs
let cross_crate = !id.is_local();
if !cross_crate { return }
if !cross_crate {
return
}
// We don't need to check for stability - presumably compiler generated code.
if self.in_skip_block > 0 {
return;
}
match *stab {
Some(&Stability { level: attr::Unstable, ref feature, ref reason, issue, .. }) => {
@ -369,6 +379,21 @@ impl<'a, 'v, 'tcx> Visitor<'v> for Checker<'a, 'tcx> {
&mut |id, sp, stab| self.check(id, sp, stab));
visit::walk_pat(self, pat)
}
fn visit_block(&mut self, b: &hir::Block) {
let old_skip_count = self.in_skip_block;
match b.rules {
hir::BlockCheckMode::PushUnstableBlock => {
self.in_skip_block += 1;
}
hir::BlockCheckMode::PopUnstableBlock => {
self.in_skip_block = self.in_skip_block.checked_sub(1).unwrap();
}
_ => {}
}
visit::walk_block(self, b);
self.in_skip_block = old_skip_count;
}
}
/// Helper for discovering nodes to check for stability

View File

@ -219,7 +219,7 @@ pub struct ctxt<'tcx> {
/// Common types, pre-interned for your convenience.
pub types: CommonTypes<'tcx>,
pub sess: Session,
pub sess: &'tcx Session,
pub def_map: DefMap,
pub named_region_map: resolve_lifetime::NamedRegionMap,
@ -443,7 +443,7 @@ impl<'tcx> ctxt<'tcx> {
/// to the context. The closure enforces that the type context and any interned
/// value (types, substs, etc.) can only be used while `ty::tls` has a valid
/// reference to the context, to allow formatting values that need it.
pub fn create_and_enter<F, R>(s: Session,
pub fn create_and_enter<F, R>(s: &'tcx Session,
arenas: &'tcx CtxtArenas<'tcx>,
def_map: DefMap,
named_region_map: resolve_lifetime::NamedRegionMap,
@ -452,7 +452,7 @@ impl<'tcx> ctxt<'tcx> {
region_maps: RegionMaps,
lang_items: middle::lang_items::LanguageItems,
stability: stability::Index<'tcx>,
f: F) -> (Session, R)
f: F) -> R
where F: FnOnce(&ctxt<'tcx>) -> R
{
let interner = RefCell::new(FnvHashMap());
@ -556,7 +556,6 @@ impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
pub mod tls {
use middle::ty;
use session::Session;
use std::fmt;
use syntax::codemap;
@ -574,17 +573,15 @@ pub mod tls {
})
}
pub fn enter<'tcx, F: FnOnce(&ty::ctxt<'tcx>) -> R, R>(tcx: ty::ctxt<'tcx>, f: F)
-> (Session, R) {
let result = codemap::SPAN_DEBUG.with(|span_dbg| {
pub fn enter<'tcx, F: FnOnce(&ty::ctxt<'tcx>) -> R, R>(tcx: ty::ctxt<'tcx>, f: F) -> R {
codemap::SPAN_DEBUG.with(|span_dbg| {
let original_span_debug = span_dbg.get();
span_dbg.set(span_debug);
let tls_ptr = &tcx as *const _ as *const ThreadLocalTyCx;
let result = TLS_TCX.set(unsafe { &*tls_ptr }, || f(&tcx));
span_dbg.set(original_span_debug);
result
});
(tcx.sess, result)
})
}
pub fn with<F: FnOnce(&ty::ctxt) -> R, R>(f: F) -> R {

View File

@ -15,7 +15,7 @@ use middle::dependency_format;
use session::search_paths::PathKind;
use util::nodemap::{NodeMap, FnvHashMap};
use syntax::ast::NodeId;
use syntax::ast::{NodeId, NodeIdAssigner};
use syntax::codemap::Span;
use syntax::diagnostic::{self, Emitter};
use syntax::diagnostics;
@ -236,9 +236,6 @@ impl Session {
}
lints.insert(id, vec!((lint_id, sp, msg)));
}
pub fn next_node_id(&self) -> ast::NodeId {
self.reserve_node_ids(1)
}
pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
let id = self.next_node_id.get();
@ -317,6 +314,16 @@ impl Session {
}
}
impl NodeIdAssigner for Session {
fn next_node_id(&self) -> NodeId {
self.reserve_node_ids(1)
}
fn peek_node_id(&self) -> NodeId {
self.next_node_id.get().checked_add(1).unwrap()
}
}
fn split_msg_into_multilines(msg: &str) -> Option<String> {
// Conditions for enabling multi-line errors:
if !msg.contains("mismatched types") &&

View File

@ -31,7 +31,7 @@ use rustc_trans::trans;
use rustc_typeck as typeck;
use rustc_privacy;
use rustc_front::hir;
use rustc_front::lowering::lower_crate;
use rustc_front::lowering::{lower_crate, LoweringContext};
use super::Compilation;
use serialize::json;
@ -42,7 +42,7 @@ use std::ffi::{OsString, OsStr};
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use syntax::ast;
use syntax::ast::{self, NodeIdAssigner};
use syntax::attr;
use syntax::attr::AttrMetaMethods;
use syntax::diagnostics;
@ -71,7 +71,7 @@ pub fn compile_input(sess: Session,
// We need nested scopes here, because the intermediate results can keep
// large chunks of memory alive and we want to free them as soon as
// possible to keep the peak memory usage low
let (sess, result) = {
let result = {
let (outputs, expanded_crate, id) = {
let krate = phase_1_parse_input(&sess, cfg, input);
@ -112,9 +112,10 @@ pub fn compile_input(sess: Session,
let expanded_crate = assign_node_ids(&sess, expanded_crate);
// Lower ast -> hir.
let lcx = LoweringContext::new(&sess, Some(&expanded_crate));
let mut hir_forest = time(sess.time_passes(),
"lowering ast -> hir",
|| hir_map::Forest::new(lower_crate(&expanded_crate)));
|| hir_map::Forest::new(lower_crate(&lcx, &expanded_crate)));
let arenas = ty::CtxtArenas::new();
let ast_map = make_map(&sess, &mut hir_forest);
@ -128,7 +129,8 @@ pub fn compile_input(sess: Session,
&ast_map,
&expanded_crate,
&ast_map.krate(),
&id[..]));
&id[..],
&lcx));
time(sess.time_passes(), "attribute checking", || {
front::check_attr::check_crate(&sess, &expanded_crate);
@ -138,7 +140,7 @@ pub fn compile_input(sess: Session,
lint::check_ast_crate(&sess, &expanded_crate)
});
phase_3_run_analysis_passes(sess,
phase_3_run_analysis_passes(&sess,
ast_map,
&arenas,
id,
@ -152,7 +154,8 @@ pub fn compile_input(sess: Session,
&expanded_crate,
tcx.map.krate(),
&analysis,
tcx);
tcx,
&lcx);
(control.after_analysis.callback)(state);
tcx.sess.abort_if_errors();
@ -278,6 +281,7 @@ pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
pub ast_map: Option<&'a hir_map::Map<'ast>>,
pub analysis: Option<&'a ty::CrateAnalysis>,
pub tcx: Option<&'a ty::ctxt<'tcx>>,
pub lcx: Option<&'a LoweringContext<'a>>,
pub trans: Option<&'a trans::CrateTranslation>,
}
@ -299,6 +303,7 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
ast_map: None,
analysis: None,
tcx: None,
lcx: None,
trans: None,
}
}
@ -333,13 +338,15 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
ast_map: &'a hir_map::Map<'ast>,
krate: &'a ast::Crate,
hir_crate: &'a hir::Crate,
crate_name: &'a str)
crate_name: &'a str,
lcx: &'a LoweringContext<'a>)
-> CompileState<'a, 'ast, 'tcx> {
CompileState {
crate_name: Some(crate_name),
ast_map: Some(ast_map),
krate: Some(krate),
hir_crate: Some(hir_crate),
lcx: Some(lcx),
.. CompileState::empty(input, session, out_dir)
}
}
@ -350,13 +357,15 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
krate: &'a ast::Crate,
hir_crate: &'a hir::Crate,
analysis: &'a ty::CrateAnalysis,
tcx: &'a ty::ctxt<'tcx>)
tcx: &'a ty::ctxt<'tcx>,
lcx: &'a LoweringContext<'a>)
-> CompileState<'a, 'ast, 'tcx> {
CompileState {
analysis: Some(analysis),
tcx: Some(tcx),
krate: Some(krate),
hir_crate: Some(hir_crate),
lcx: Some(lcx),
.. CompileState::empty(input, session, out_dir)
}
}
@ -649,13 +658,13 @@ pub fn make_map<'ast>(sess: &Session,
/// Run the resolution, typechecking, region checking and other
/// miscellaneous analysis passes on the crate. Return various
/// structures carrying the results of the analysis.
pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session,
pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
ast_map: front::map::Map<'tcx>,
arenas: &'tcx ty::CtxtArenas<'tcx>,
name: String,
make_glob_map: resolve::MakeGlobMap,
f: F)
-> (Session, R)
-> R
where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>,
ty::CrateAnalysis) -> R
{
@ -663,7 +672,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session,
let krate = ast_map.krate();
time(time_passes, "external crate/lib resolution", ||
LocalCrateReader::new(&sess, &ast_map).read_crates(krate));
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));
@ -677,7 +686,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session,
glob_map,
} =
time(time_passes, "resolution",
|| resolve::resolve_crate(&sess, &ast_map, make_glob_map));
|| resolve::resolve_crate(sess, &ast_map, make_glob_map));
// Discard MTWT tables that aren't required past resolution.
if !sess.opts.debugging_opts.keep_mtwt_tables {
@ -685,10 +694,10 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session,
}
let named_region_map = time(time_passes, "lifetime resolution",
|| middle::resolve_lifetime::krate(&sess, krate, &def_map));
|| middle::resolve_lifetime::krate(sess, krate, &def_map));
time(time_passes, "looking for entry point",
|| middle::entry::find_entry_point(&sess, &ast_map));
|| middle::entry::find_entry_point(sess, &ast_map));
sess.plugin_registrar_fn.set(
time(time_passes, "looking for plugin registrar", ||
@ -696,13 +705,13 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session,
sess.diagnostic(), krate)));
let region_map = time(time_passes, "region resolution", ||
middle::region::resolve_crate(&sess, krate));
middle::region::resolve_crate(sess, krate));
time(time_passes, "loop checking", ||
middle::check_loop::check_crate(&sess, krate));
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));
middle::check_static_recursion::check_crate(sess, krate, &def_map, &ast_map));
ty::ctxt::create_and_enter(sess,
arenas,

View File

@ -396,6 +396,7 @@ impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
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));

View File

@ -47,7 +47,7 @@ use std::str::FromStr;
use rustc::front::map as hir_map;
use rustc::front::map::{blocks, NodePrinter};
use rustc_front::hir;
use rustc_front::lowering::lower_crate;
use rustc_front::lowering::{lower_crate, LoweringContext};
use rustc_front::print::pprust as pprust_hir;
#[derive(Copy, Clone, PartialEq, Debug)]
@ -131,7 +131,7 @@ pub fn parse_pretty(sess: &Session,
impl PpSourceMode {
/// Constructs a `PrinterSupport` object and passes it to `f`.
fn call_with_pp_support<'tcx, A, B, F>(&self,
sess: Session,
sess: &'tcx Session,
ast_map: Option<hir_map::Map<'tcx>>,
payload: B,
f: F) -> A where
@ -155,7 +155,7 @@ impl PpSourceMode {
}
}
fn call_with_pp_support_hir<'tcx, A, B, F>(&self,
sess: Session,
sess: &'tcx Session,
ast_map: &hir_map::Map<'tcx>,
arenas: &'tcx ty::CtxtArenas<'tcx>,
id: String,
@ -185,7 +185,7 @@ impl PpSourceMode {
|tcx, _| {
let annotation = TypedAnnotation { tcx: tcx };
f(&annotation, payload, &ast_map.forest.krate)
}).1
})
}
_ => panic!("Should use call_with_pp_support"),
}
@ -225,12 +225,12 @@ trait HirPrinterSupport<'ast>: pprust_hir::PpAnn {
}
struct NoAnn<'ast> {
sess: Session,
sess: &'ast Session,
ast_map: Option<hir_map::Map<'ast>>
}
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()
@ -240,7 +240,7 @@ impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
}
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()
@ -253,12 +253,12 @@ impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
impl<'ast> pprust_hir::PpAnn for NoAnn<'ast> {}
struct IdentifiedAnnotation<'ast> {
sess: Session,
sess: &'ast Session,
ast_map: Option<hir_map::Map<'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()
@ -308,7 +308,7 @@ 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()
@ -357,12 +357,12 @@ impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> {
}
struct HygieneAnnotation<'ast> {
sess: Session,
sess: &'ast Session,
ast_map: Option<hir_map::Map<'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()
@ -670,9 +670,10 @@ pub fn pretty_print_input(sess: Session,
// There is some twisted, god-forsaken tangle of lifetimes here which makes
// the ordering of stuff super-finicky.
let mut hir_forest;
let lcx = LoweringContext::new(&sess, Some(&krate));
let arenas = ty::CtxtArenas::new();
let ast_map = if compute_ast_map {
hir_forest = hir_map::Forest::new(lower_crate(&krate));
hir_forest = hir_map::Forest::new(lower_crate(&lcx, &krate));
let map = driver::make_map(&sess, &mut hir_forest);
Some(map)
} else {
@ -695,7 +696,7 @@ pub fn pretty_print_input(sess: Session,
// Silently ignores an identified node.
let out: &mut Write = &mut out;
s.call_with_pp_support(
sess, ast_map, box out, |annotation, out| {
&sess, ast_map, box out, |annotation, out| {
debug!("pretty printing source code {:?}", s);
let sess = annotation.sess();
pprust::print_crate(sess.codemap(),
@ -712,7 +713,7 @@ pub fn pretty_print_input(sess: Session,
(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| {
&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(),
@ -728,7 +729,7 @@ pub fn pretty_print_input(sess: Session,
(PpmHir(s), Some(uii)) => {
let out: &mut Write = &mut out;
s.call_with_pp_support_hir(sess,
s.call_with_pp_support_hir(&sess,
&ast_map.unwrap(),
&arenas,
id,
@ -776,14 +777,14 @@ pub fn pretty_print_input(sess: Session,
match code {
Some(code) => {
let variants = gather_flowgraph_variants(&sess);
driver::phase_3_run_analysis_passes(sess,
driver::phase_3_run_analysis_passes(&sess,
ast_map,
&arenas,
id,
resolve::MakeGlobMap::No,
|tcx, _| {
print_flowgraph(variants, tcx, code, mode, out)
}).1
})
}
None => {
let message = format!("--pretty=flowgraph needs \

View File

@ -38,7 +38,7 @@ use syntax::diagnostic::{Level, RenderSpan, Bug, Fatal, Error, Warning, Note, He
use syntax::parse::token;
use syntax::feature_gate::UnstableFeatures;
use rustc_front::lowering::lower_crate;
use rustc_front::lowering::{lower_crate, LoweringContext};
use rustc_front::hir;
struct Env<'a, 'tcx: 'a> {
@ -124,7 +124,8 @@ fn test_env<F>(source_string: &str,
.expect("phase 2 aborted");
let krate = driver::assign_node_ids(&sess, krate);
let mut hir_forest = hir_map::Forest::new(lower_crate(&krate));
let lcx = LoweringContext::new(&sess, Some(&krate));
let mut hir_forest = hir_map::Forest::new(lower_crate(&lcx, &krate));
let arenas = ty::CtxtArenas::new();
let ast_map = driver::make_map(&sess, &mut hir_forest);
let krate = ast_map.krate();
@ -135,7 +136,7 @@ fn test_env<F>(source_string: &str,
resolve::resolve_crate(&sess, &ast_map, resolve::MakeGlobMap::No);
let named_region_map = resolve_lifetime::krate(&sess, krate, &def_map);
let region_map = region::resolve_crate(&sess, krate);
ty::ctxt::create_and_enter(sess,
ty::ctxt::create_and_enter(&sess,
&arenas,
def_map,
named_region_map,

View File

@ -574,6 +574,9 @@ pub enum BlockCheckMode {
UnsafeBlock(UnsafeSource),
PushUnsafeBlock(UnsafeSource),
PopUnsafeBlock(UnsafeSource),
// Within this block (but outside a PopUnstableBlock), we suspend checking of stability.
PushUnstableBlock,
PopUnstableBlock,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
@ -583,7 +586,7 @@ pub enum UnsafeSource {
}
/// An expression
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
pub struct Expr {
pub id: NodeId,
pub node: Expr_,

File diff suppressed because it is too large Load Diff

View File

@ -1089,8 +1089,12 @@ impl<'a> State<'a> {
close_box: bool)
-> io::Result<()> {
match blk.rules {
hir::UnsafeBlock(..) | hir::PushUnsafeBlock(..) => try!(self.word_space("unsafe")),
hir::DefaultBlock | hir::PopUnsafeBlock(..) => (),
hir::UnsafeBlock(..) => try!(self.word_space("unsafe")),
hir::PushUnsafeBlock(..) => try!(self.word_space("push_unsafe")),
hir::PopUnsafeBlock(..) => try!(self.word_space("pop_unsafe")),
hir::PushUnstableBlock => try!(self.word_space("push_unstable")),
hir::PopUnstableBlock => try!(self.word_space("pop_unstable")),
hir::DefaultBlock => (),
}
try!(self.maybe_print_comment(blk.span.lo));
try!(self.ann.pre(self, NodeBlock(blk)));

View File

@ -363,12 +363,10 @@ impl EarlyLintPass for UnusedParens {
let (value, msg, struct_lit_needs_parens) = match e.node {
ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
ast::ExprMatch(ref head, _, source) => match source {
ast::MatchSource::Normal => (head, "`match` head expression", true),
ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
},
ast::ExprIfLet(_, ref cond, _, _) => (cond, "`if let` head expression", true),
ast::ExprWhileLet(_, ref cond, _, _) => (cond, "`while let` head expression", true),
ast::ExprForLoop(_, ref cond, _, _) => (cond, "`for` head expression", true),
ast::ExprMatch(ref head, _) => (head, "`match` head expression", true),
ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
ast::ExprAssign(_, ref value) => (value, "assigned value", false),
ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),

View File

@ -47,7 +47,7 @@ use syntax::visit::{self, Visitor};
use syntax::print::pprust::{path_to_string, ty_to_string};
use syntax::ptr::P;
use rustc_front::lowering::lower_expr;
use rustc_front::lowering::{lower_expr, LoweringContext};
use super::span_utils::SpanUtils;
use super::recorder::{Recorder, FmtStrs};
@ -76,6 +76,7 @@ pub struct DumpCsvVisitor<'l, 'tcx: 'l> {
impl <'l, 'tcx> DumpCsvVisitor<'l, 'tcx> {
pub fn new(tcx: &'l ty::ctxt<'tcx>,
lcx: &'l LoweringContext<'l>,
analysis: &'l ty::CrateAnalysis,
output_file: Box<File>)
-> DumpCsvVisitor<'l, 'tcx> {
@ -83,7 +84,7 @@ impl <'l, 'tcx> DumpCsvVisitor<'l, 'tcx> {
DumpCsvVisitor {
sess: &tcx.sess,
tcx: tcx,
save_ctxt: SaveContext::from_span_utils(tcx, span_utils.clone()),
save_ctxt: SaveContext::from_span_utils(tcx, lcx, span_utils.clone()),
analysis: analysis,
span: span_utils.clone(),
fmt: FmtStrs::new(box Recorder {
@ -795,6 +796,35 @@ impl <'l, 'tcx> DumpCsvVisitor<'l, 'tcx> {
_ => visit::walk_pat(self, p),
}
}
fn process_var_decl(&mut self, p: &ast::Pat, value: String) {
// The local could declare multiple new vars, we must walk the
// pattern and collect them all.
let mut collector = PathCollector::new();
collector.visit_pat(&p);
self.visit_pat(&p);
for &(id, ref p, immut, _) in &collector.collected_paths {
let value = if immut == ast::MutImmutable {
value.to_string()
} else {
"<mutable>".to_string()
};
let types = self.tcx.node_types();
let typ = types.get(&id).unwrap().to_string();
// Get the span only for the name of the variable (I hope the path
// is only ever a variable name, but who knows?).
let sub_span = self.span.span_for_last_ident(p.span);
// Rust uses the id of the pattern for var lookups, so we'll use it too.
self.fmt.variable_str(p.span,
sub_span,
id,
&path_to_string(p),
&value,
&typ);
}
}
}
impl<'l, 'tcx, 'v> Visitor<'v> for DumpCsvVisitor<'l, 'tcx> {
@ -1035,7 +1065,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DumpCsvVisitor<'l, 'tcx> {
visit::walk_expr(self, ex);
}
ast::ExprStruct(ref path, ref fields, ref base) => {
let hir_expr = lower_expr(ex);
let hir_expr = lower_expr(self.save_ctxt.lcx, ex);
let adt = self.tcx.expr_ty(&hir_expr).ty_adt_def().unwrap();
let def = self.tcx.resolve_expr(&hir_expr);
self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
@ -1064,7 +1094,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DumpCsvVisitor<'l, 'tcx> {
self.visit_expr(&**sub_ex);
let hir_node = lower_expr(sub_ex);
let hir_node = lower_expr(self.save_ctxt.lcx, sub_ex);
let ty = &self.tcx.expr_ty_adjusted(&hir_node).sty;
match *ty {
ty::TyStruct(def, _) => {
@ -1102,6 +1132,20 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DumpCsvVisitor<'l, 'tcx> {
// walk the body
self.nest(ex.id, |v| v.visit_block(&**body));
}
ast::ExprForLoop(ref pattern, ref subexpression, ref block, _) |
ast::ExprWhileLet(ref pattern, ref subexpression, ref block, _) => {
let value = self.span.snippet(mk_sp(ex.span.lo, subexpression.span.hi));
self.process_var_decl(pattern, value);
visit::walk_expr(self, subexpression);
visit::walk_block(self, block);
}
ast::ExprIfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
let value = self.span.snippet(mk_sp(ex.span.lo, subexpression.span.hi));
self.process_var_decl(pattern, value);
visit::walk_expr(self, subexpression);
visit::walk_block(self, block);
opt_else.as_ref().map(|el| visit::walk_expr(self, el));
}
_ => {
visit::walk_expr(self, ex)
}
@ -1179,31 +1223,12 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DumpCsvVisitor<'l, 'tcx> {
return
}
// The local could declare multiple new vars, we must walk the
// pattern and collect them all.
let mut collector = PathCollector::new();
collector.visit_pat(&l.pat);
self.visit_pat(&l.pat);
let value = self.span.snippet(l.span);
for &(id, ref p, immut, _) in &collector.collected_paths {
let value = if immut == ast::MutImmutable {
value.to_string()
} else {
"<mutable>".to_string()
};
let types = self.tcx.node_types();
let typ = types.get(&id).unwrap().to_string();
// Get the span only for the name of the variable (I hope the path
// is only ever a variable name, but who knows?).
let sub_span = self.span.span_for_last_ident(p.span);
// Rust uses the id of the pattern for var lookups, so we'll use it too.
self.fmt.variable_str(p.span, sub_span, id, &path_to_string(p), &value, &typ);
}
self.process_var_decl(&l.pat, value);
// Just walk the initialiser and type (don't want to walk the pattern again).
walk_list!(self, visit_ty, &l.ty);
walk_list!(self, visit_expr, &l.init);
}
}

View File

@ -38,6 +38,7 @@ mod dump_csv;
pub struct SaveContext<'l, 'tcx: 'l> {
tcx: &'l ty::ctxt<'tcx>,
lcx: &'l lowering::LoweringContext<'l>,
span_utils: SpanUtils<'l>,
}
@ -176,16 +177,20 @@ pub struct MethodCallData {
impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
pub fn new(tcx: &'l ty::ctxt<'tcx>) -> SaveContext<'l, 'tcx> {
pub fn new(tcx: &'l ty::ctxt<'tcx>,
lcx: &'l lowering::LoweringContext<'l>)
-> SaveContext<'l, 'tcx> {
let span_utils = SpanUtils::new(&tcx.sess);
SaveContext::from_span_utils(tcx, span_utils)
SaveContext::from_span_utils(tcx, lcx, span_utils)
}
pub fn from_span_utils(tcx: &'l ty::ctxt<'tcx>,
lcx: &'l lowering::LoweringContext<'l>,
span_utils: SpanUtils<'l>)
-> SaveContext<'l, 'tcx> {
SaveContext {
tcx: tcx,
lcx: lcx,
span_utils: span_utils,
}
}
@ -454,7 +459,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
match expr.node {
ast::ExprField(ref sub_ex, ident) => {
let hir_node = lowering::lower_expr(sub_ex);
let hir_node = lowering::lower_expr(self.lcx, sub_ex);
let ty = &self.tcx.expr_ty_adjusted(&hir_node).sty;
match *ty {
ty::TyStruct(def, _) => {
@ -474,7 +479,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
}
}
ast::ExprStruct(ref path, _, _) => {
let hir_node = lowering::lower_expr(expr);
let hir_node = lowering::lower_expr(self.lcx, expr);
let ty = &self.tcx.expr_ty_adjusted(&hir_node).sty;
match *ty {
ty::TyStruct(def, _) => {
@ -705,10 +710,11 @@ impl<'v> Visitor<'v> for PathCollector {
}
}
pub fn process_crate(tcx: &ty::ctxt,
krate: &ast::Crate,
analysis: &ty::CrateAnalysis,
odir: Option<&Path>) {
pub fn process_crate<'l, 'tcx>(tcx: &'l ty::ctxt<'tcx>,
lcx: &'l lowering::LoweringContext<'l>,
krate: &ast::Crate,
analysis: &ty::CrateAnalysis,
odir: Option<&Path>) {
if generated_code(krate.span) {
return;
}
@ -757,7 +763,7 @@ pub fn process_crate(tcx: &ty::ctxt,
};
root_path.pop();
let mut visitor = dump_csv::DumpCsvVisitor::new(tcx, analysis, output_file);
let mut visitor = dump_csv::DumpCsvVisitor::new(tcx, lcx, analysis, output_file);
visitor.dump_crate_info(&cratename, krate);
visit::walk_crate(&mut visitor, krate);

View File

@ -269,7 +269,7 @@ impl UnsafetyState {
(unsafety, blk.id, self.unsafe_push_count.checked_sub(1).unwrap()),
hir::UnsafeBlock(..) =>
(hir::Unsafety::Unsafe, blk.id, self.unsafe_push_count),
hir::DefaultBlock =>
hir::DefaultBlock | hir::PushUnstableBlock | hir:: PopUnstableBlock =>
(unsafety, self.def, self.unsafe_push_count),
};
UnsafetyState{ def: def,
@ -1810,7 +1810,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// There is a possibility that this algorithm will have to run an arbitrary number of times
// to terminate so we bound it by the compiler's recursion limit.
for _ in (0..self.tcx().sess.recursion_limit.get()) {
for _ in 0..self.tcx().sess.recursion_limit.get() {
// First we try to solve all obligations, it is possible that the last iteration
// has made it possible to make more progress.
self.select_obligations_where_possible();

View File

@ -19,7 +19,7 @@ use rustc::lint;
use rustc::util::nodemap::DefIdSet;
use rustc_trans::back::link;
use rustc_resolve as resolve;
use rustc_front::lowering::lower_crate;
use rustc_front::lowering::{lower_crate, LoweringContext};
use syntax::{ast, codemap, diagnostic};
use syntax::feature_gate::UnstableFeatures;
@ -37,7 +37,7 @@ pub use rustc::session::search_paths::SearchPaths;
/// Are we generating documentation (`Typed`) or tests (`NotTyped`)?
pub enum MaybeTyped<'a, 'tcx: 'a> {
Typed(&'a ty::ctxt<'tcx>),
NotTyped(session::Session)
NotTyped(&'a session::Session)
}
pub type ExternalPaths = RefCell<Option<HashMap<DefId,
@ -135,11 +135,12 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec<String>, externs: Externs,
let krate = driver::assign_node_ids(&sess, krate);
// Lower ast -> hir.
let mut hir_forest = hir_map::Forest::new(lower_crate(&krate));
let lcx = LoweringContext::new(&sess, Some(&krate));
let mut hir_forest = hir_map::Forest::new(lower_crate(&lcx, &krate));
let arenas = ty::CtxtArenas::new();
let hir_map = driver::make_map(&sess, &mut hir_forest);
driver::phase_3_run_analysis_passes(sess,
driver::phase_3_run_analysis_passes(&sess,
hir_map,
&arenas,
name,
@ -194,5 +195,5 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec<String>, externs: Externs,
*analysis.inlined.borrow_mut() = map;
analysis.deref_trait_did = ctxt.deref_trait_did.get();
(krate, analysis)
}).1
})
}

View File

@ -26,7 +26,7 @@ use rustc::front::map as hir_map;
use rustc::session::{self, config};
use rustc::session::config::{get_unstable_features_setting, OutputType};
use rustc::session::search_paths::{SearchPaths, PathKind};
use rustc_front::lowering::lower_crate;
use rustc_front::lowering::{lower_crate, LoweringContext};
use rustc_back::tempdir::TempDir;
use rustc_driver::{driver, Compilation};
use syntax::codemap::CodeMap;
@ -83,7 +83,8 @@ pub fn run(input: &str,
"rustdoc-test", None)
.expect("phase_2_configure_and_expand aborted in rustdoc!");
let krate = driver::assign_node_ids(&sess, krate);
let krate = lower_crate(&krate);
let lcx = LoweringContext::new(&sess, Some(&krate));
let krate = lower_crate(&lcx, &krate);
let opts = scrape_test_config(&krate);
@ -92,7 +93,7 @@ pub fn run(input: &str,
let ctx = core::DocContext {
map: &map,
maybe_typed: core::NotTyped(sess),
maybe_typed: core::NotTyped(&sess),
input: input,
external_paths: RefCell::new(Some(HashMap::new())),
external_traits: RefCell::new(None),

View File

@ -375,6 +375,11 @@ pub const CRATE_NODE_ID: NodeId = 0;
/// small, positive ids.
pub const DUMMY_NODE_ID: NodeId = !0;
pub trait NodeIdAssigner {
fn next_node_id(&self) -> NodeId;
fn peek_node_id(&self) -> NodeId;
}
/// The AST represents all type param bounds as types.
/// typeck::collect::compute_bounds matches these against
/// the "special" built-in traits (see middle::lang_items) and
@ -850,9 +855,8 @@ pub enum Expr_ {
///
/// `'label: loop { block }`
ExprLoop(P<Block>, Option<Ident>),
/// A `match` block, with a source that indicates whether or not it is
/// the result of a desugaring, and if so, which kind.
ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
/// A `match` block.
ExprMatch(P<Expr>, Vec<Arm>),
/// A closure (for example, `move |a, b, c| {a + b + c}`)
ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
/// A block (`{ ... }`)
@ -931,14 +935,6 @@ pub struct QSelf {
pub position: usize
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum MatchSource {
Normal,
IfLetDesugar { contains_else_clause: bool },
WhileLetDesugar,
ForLoopDesugar,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum CaptureClause {
CaptureByValue,

View File

@ -29,7 +29,6 @@ use std::io::{self, Read};
use serialize::{Encodable, Decodable, Encoder, Decoder};
use parse::token::intern;
use ast::Name;
// _____________________________________________________________________________
@ -269,28 +268,8 @@ pub enum ExpnFormat {
MacroAttribute(Name),
/// e.g. `format!()`
MacroBang(Name),
/// Syntax sugar expansion performed by the compiler (libsyntax::expand).
CompilerExpansion(CompilerExpansionFormat),
}
#[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
pub enum CompilerExpansionFormat {
IfLet,
PlacementIn,
WhileLet,
ForLoop,
}
impl CompilerExpansionFormat {
pub fn name(self) -> &'static str {
match self {
CompilerExpansionFormat::IfLet => "if let expansion",
CompilerExpansionFormat::PlacementIn => "placement-in expansion",
CompilerExpansionFormat::WhileLet => "while let expansion",
CompilerExpansionFormat::ForLoop => "for loop expansion",
}
}
}
#[derive(Clone, Hash, Debug)]
pub struct NameAndSpan {
/// The format with which the macro was invoked.
@ -310,7 +289,6 @@ impl NameAndSpan {
match self.format {
ExpnFormat::MacroAttribute(s) => s,
ExpnFormat::MacroBang(s) => s,
ExpnFormat::CompilerExpansion(ce) => intern(ce.name()),
}
}
}

View File

@ -225,10 +225,10 @@ fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where
fold::noop_fold_expr(ast::Expr {
id: id,
node: match node {
ast::ExprMatch(m, arms, source) => {
ast::ExprMatch(m, arms) => {
ast::ExprMatch(m, arms.into_iter()
.filter(|a| (cx.in_cfg)(&a.attrs))
.collect(), source)
.collect())
}
_ => node
},

View File

@ -737,7 +737,6 @@ impl EmitterWriter {
let (pre, post) = match ei.callee.format {
codemap::MacroAttribute(..) => ("#[", "]"),
codemap::MacroBang(..) => ("", "!"),
codemap::CompilerExpansion(..) => ("", ""),
};
// Don't print recursive invocations
if ei.call_site != last_span {

View File

@ -13,7 +13,7 @@ pub use self::SyntaxExtension::*;
use ast;
use ast::Name;
use codemap;
use codemap::{CodeMap, Span, ExpnId, ExpnInfo, NO_EXPANSION, CompilerExpansion};
use codemap::{CodeMap, Span, ExpnId, ExpnInfo, NO_EXPANSION};
use ext;
use ext::expand;
use ext::tt::macro_rules;
@ -651,10 +651,7 @@ impl<'a> ExtCtxt<'a> {
return None;
}
expn_id = i.call_site.expn_id;
match i.callee.format {
CompilerExpansion(..) => (),
_ => last_macro = Some(i.call_site),
}
last_macro = Some(i.call_site);
return Some(());
})
}).is_none() {

View File

@ -868,7 +868,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
}
fn expr_match(&self, span: Span, arg: P<ast::Expr>, arms: Vec<ast::Arm>) -> P<Expr> {
self.expr(span, ast::ExprMatch(arg, arms, ast::MatchSource::Normal))
self.expr(span, ast::ExprMatch(arg, arms))
}
fn expr_if(&self, span: Span, cond: P<ast::Expr>,

View File

@ -20,53 +20,20 @@ use attr;
use attr::AttrMetaMethods;
use codemap;
use codemap::{Span, Spanned, ExpnInfo, NameAndSpan, MacroBang, MacroAttribute};
use codemap::{CompilerExpansion, CompilerExpansionFormat};
use ext::base::*;
use feature_gate::{self, Features, GatedCfg};
use fold;
use fold::*;
use parse;
use parse::token::{fresh_mark, fresh_name, intern};
use parse::token;
use ptr::P;
use util::small_vector::SmallVector;
use visit;
use visit::Visitor;
use std_inject;
// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
fn mk_core_path(fld: &mut MacroExpander,
span: Span,
suffix: &[&'static str]) -> ast::Path {
let idents = fld.cx.std_path(suffix);
fld.cx.path_global(span, idents)
}
pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
fn push_compiler_expansion(fld: &mut MacroExpander, span: Span,
expansion_type: CompilerExpansionFormat) {
fld.cx.bt_push(ExpnInfo {
call_site: span,
callee: NameAndSpan {
format: CompilerExpansion(expansion_type),
// This does *not* mean code generated after
// `push_compiler_expansion` is automatically exempt
// from stability lints; must also tag such code with
// an appropriate span from `fld.cx.backtrace()`.
allow_internal_unstable: true,
span: None,
},
});
}
// Sets the expn_id so that we can use unstable methods.
fn allow_unstable(fld: &mut MacroExpander, span: Span) -> Span {
Span { expn_id: fld.cx.backtrace(), ..span }
}
let expr_span = e.span;
return e.and_then(|ast::Expr {id, node, span}| match node {
@ -94,265 +61,39 @@ pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
})
}
// Desugar ExprInPlace: `in PLACE { EXPR }`
ast::ExprInPlace(placer, value_expr) => {
// to:
//
// let p = PLACE;
// let mut place = Placer::make_place(p);
// let raw_place = Place::pointer(&mut place);
// push_unsafe!({
// std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
// InPlace::finalize(place)
// })
// Ensure feature-gate is enabled
feature_gate::check_for_placement_in(
fld.cx.ecfg.features,
&fld.cx.parse_sess.span_diagnostic,
expr_span);
push_compiler_expansion(fld, expr_span, CompilerExpansionFormat::PlacementIn);
let value_span = value_expr.span;
let placer_span = placer.span;
let placer_expr = fld.fold_expr(placer);
let placer = fld.fold_expr(placer);
let value_expr = fld.fold_expr(value_expr);
let placer_ident = token::gensym_ident("placer");
let agent_ident = token::gensym_ident("place");
let p_ptr_ident = token::gensym_ident("p_ptr");
let placer = fld.cx.expr_ident(span, placer_ident);
let agent = fld.cx.expr_ident(span, agent_ident);
let p_ptr = fld.cx.expr_ident(span, p_ptr_ident);
let make_place = ["ops", "Placer", "make_place"];
let place_pointer = ["ops", "Place", "pointer"];
let move_val_init = ["intrinsics", "move_val_init"];
let inplace_finalize = ["ops", "InPlace", "finalize"];
let make_call = |fld: &mut MacroExpander, p, args| {
// We feed in the `expr_span` because codemap's span_allows_unstable
// allows the call_site span to inherit the `allow_internal_unstable`
// setting.
let span_unstable = allow_unstable(fld, expr_span);
let path = mk_core_path(fld, span_unstable, p);
let path = fld.cx.expr_path(path);
let expr_span_unstable = allow_unstable(fld, span);
fld.cx.expr_call(expr_span_unstable, path, args)
};
let stmt_let = |fld: &mut MacroExpander, bind, expr| {
fld.cx.stmt_let(placer_span, false, bind, expr)
};
let stmt_let_mut = |fld: &mut MacroExpander, bind, expr| {
fld.cx.stmt_let(placer_span, true, bind, expr)
};
// let placer = <placer_expr> ;
let s1 = stmt_let(fld, placer_ident, placer_expr);
// let mut place = Placer::make_place(placer);
let s2 = {
let call = make_call(fld, &make_place, vec![placer]);
stmt_let_mut(fld, agent_ident, call)
};
// let p_ptr = Place::pointer(&mut place);
let s3 = {
let args = vec![fld.cx.expr_mut_addr_of(placer_span, agent.clone())];
let call = make_call(fld, &place_pointer, args);
stmt_let(fld, p_ptr_ident, call)
};
// pop_unsafe!(EXPR));
let pop_unsafe_expr = pop_unsafe_expr(fld.cx, value_expr, value_span);
// push_unsafe!({
// ptr::write(p_ptr, pop_unsafe!(<value_expr>));
// InPlace::finalize(place)
// })
let expr = {
let call_move_val_init = StmtSemi(make_call(
fld, &move_val_init, vec![p_ptr, pop_unsafe_expr]), ast::DUMMY_NODE_ID);
let call_move_val_init = codemap::respan(value_span, call_move_val_init);
let call = make_call(fld, &inplace_finalize, vec![agent]);
Some(push_unsafe_expr(fld.cx, vec![P(call_move_val_init)], call, span))
};
let block = fld.cx.block_all(span, vec![s1, s2, s3], expr);
let result = fld.cx.expr_block(block);
fld.cx.bt_pop();
result
fld.cx.expr(span, ast::ExprInPlace(placer, value_expr))
}
// Issue #22181:
// Eventually a desugaring for `box EXPR`
// (similar to the desugaring above for `in PLACE BLOCK`)
// should go here, desugaring
//
// to:
//
// let mut place = BoxPlace::make_place();
// let raw_place = Place::pointer(&mut place);
// let value = $value;
// unsafe {
// ::std::ptr::write(raw_place, value);
// Boxed::finalize(place)
// }
//
// But for now there are type-inference issues doing that.
ast::ExprWhile(cond, body, opt_ident) => {
let cond = fld.fold_expr(cond);
let (body, opt_ident) = expand_loop_block(body, opt_ident, fld);
fld.cx.expr(span, ast::ExprWhile(cond, body, opt_ident))
}
// Desugar ExprWhileLet
// From: `[opt_ident]: while let <pat> = <expr> <body>`
ast::ExprWhileLet(pat, expr, body, opt_ident) => {
// to:
//
// [opt_ident]: loop {
// match <expr> {
// <pat> => <body>,
// _ => break
// }
// }
let pat = fld.fold_pat(pat);
let expr = fld.fold_expr(expr);
push_compiler_expansion(fld, span, CompilerExpansionFormat::WhileLet);
// Hygienic renaming of the body.
let ((body, opt_ident), mut rewritten_pats) =
rename_in_scope(vec![pat],
fld,
(body, opt_ident),
|rename_fld, fld, (body, opt_ident)| {
expand_loop_block(rename_fld.fold_block(body), opt_ident, fld)
});
assert!(rewritten_pats.len() == 1);
// `<pat> => <body>`
let pat_arm = {
let body_expr = fld.cx.expr_block(body);
fld.cx.arm(pat.span, vec![pat], body_expr)
};
// `_ => break`
let break_arm = {
let pat_under = fld.cx.pat_wild(span);
let break_expr = fld.cx.expr_break(span);
fld.cx.arm(span, vec![pat_under], break_expr)
};
// `match <expr> { ... }`
let arms = vec![pat_arm, break_arm];
let match_expr = fld.cx.expr(span,
ast::ExprMatch(expr, arms, ast::MatchSource::WhileLetDesugar));
// `[opt_ident]: loop { ... }`
let loop_block = fld.cx.block_expr(match_expr);
let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
let result = fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident));
fld.cx.bt_pop();
result
}
// Desugar ExprIfLet
// From: `if let <pat> = <expr> <body> [<elseopt>]`
ast::ExprIfLet(pat, expr, body, mut elseopt) => {
// to:
//
// match <expr> {
// <pat> => <body>,
// [_ if <elseopt_if_cond> => <elseopt_if_body>,]
// _ => [<elseopt> | ()]
// }
push_compiler_expansion(fld, span, CompilerExpansionFormat::IfLet);
// `<pat> => <body>`
let pat_arm = {
let body_expr = fld.cx.expr_block(body);
fld.cx.arm(pat.span, vec![pat], body_expr)
};
// `[_ if <elseopt_if_cond> => <elseopt_if_body>,]`
let else_if_arms = {
let mut arms = vec![];
loop {
let elseopt_continue = elseopt
.and_then(|els| els.and_then(|els| match els.node {
// else if
ast::ExprIf(cond, then, elseopt) => {
let pat_under = fld.cx.pat_wild(span);
arms.push(ast::Arm {
attrs: vec![],
pats: vec![pat_under],
guard: Some(cond),
body: fld.cx.expr_block(then)
});
elseopt.map(|elseopt| (elseopt, true))
}
_ => Some((P(els), false))
}));
match elseopt_continue {
Some((e, true)) => {
elseopt = Some(e);
}
Some((e, false)) => {
elseopt = Some(e);
break;
}
None => {
elseopt = None;
break;
}
}
}
arms
};
let contains_else_clause = elseopt.is_some();
// `_ => [<elseopt> | ()]`
let else_arm = {
let pat_under = fld.cx.pat_wild(span);
let else_expr = elseopt.unwrap_or_else(|| fld.cx.expr_tuple(span, vec![]));
fld.cx.arm(span, vec![pat_under], else_expr)
};
let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
arms.push(pat_arm);
arms.extend(else_if_arms);
arms.push(else_arm);
let match_expr = fld.cx.expr(span,
ast::ExprMatch(expr, arms,
ast::MatchSource::IfLetDesugar {
contains_else_clause: contains_else_clause,
}));
let result = fld.fold_expr(match_expr);
fld.cx.bt_pop();
result
}
// Desugar support for ExprIfLet in the ExprIf else position
ast::ExprIf(cond, blk, elseopt) => {
let elseopt = elseopt.map(|els| els.and_then(|els| match els.node {
ast::ExprIfLet(..) => {
push_compiler_expansion(fld, span, CompilerExpansionFormat::IfLet);
// wrap the if-let expr in a block
let span = els.span;
let blk = P(ast::Block {
stmts: vec![],
expr: Some(P(els)),
id: ast::DUMMY_NODE_ID,
rules: ast::DefaultBlock,
span: span
});
let result = fld.cx.expr_block(blk);
fld.cx.bt_pop();
result
}
_ => P(els)
}));
let if_expr = fld.cx.expr(span, ast::ExprIf(cond, blk, elseopt));
if_expr.map(|e| noop_fold_expr(e, fld))
fld.cx.expr(span, ast::ExprWhileLet(rewritten_pats.remove(0), expr, body, opt_ident))
}
ast::ExprLoop(loop_block, opt_ident) => {
@ -360,102 +101,39 @@ pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident))
}
// Desugar ExprForLoop
// From: `[opt_ident]: for <pat> in <head> <body>`
ast::ExprForLoop(pat, head, body, opt_ident) => {
// to:
//
// {
// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
// mut iter => {
// [opt_ident]: loop {
// match ::std::iter::Iterator::next(&mut iter) {
// ::std::option::Option::Some(<pat>) => <body>,
// ::std::option::Option::None => break
// }
// }
// }
// };
// result
// }
let pat = fld.fold_pat(pat);
push_compiler_expansion(fld, span, CompilerExpansionFormat::ForLoop);
// Hygienic renaming of the for loop body (for loop binds its pattern).
let ((body, opt_ident), mut rewritten_pats) =
rename_in_scope(vec![pat],
fld,
(body, opt_ident),
|rename_fld, fld, (body, opt_ident)| {
expand_loop_block(rename_fld.fold_block(body), opt_ident, fld)
});
assert!(rewritten_pats.len() == 1);
let span = fld.new_span(span);
// expand <head>
let head = fld.fold_expr(head);
fld.cx.expr(span, ast::ExprForLoop(rewritten_pats.remove(0), head, body, opt_ident))
}
let iter = token::gensym_ident("iter");
ast::ExprIfLet(pat, sub_expr, body, else_opt) => {
let pat = fld.fold_pat(pat);
let pat_span = fld.new_span(pat.span);
// `::std::option::Option::Some(<pat>) => <body>`
let pat_arm = {
let body_expr = fld.cx.expr_block(body);
let pat = fld.fold_pat(pat);
let some_pat = fld.cx.pat_some(pat_span, pat);
// Hygienic renaming of the body.
let (body, mut rewritten_pats) =
rename_in_scope(vec![pat],
fld,
body,
|rename_fld, fld, body| {
fld.fold_block(rename_fld.fold_block(body))
});
assert!(rewritten_pats.len() == 1);
fld.cx.arm(pat_span, vec![some_pat], body_expr)
};
// `::std::option::Option::None => break`
let break_arm = {
let break_expr = fld.cx.expr_break(span);
fld.cx.arm(span, vec![fld.cx.pat_none(span)], break_expr)
};
// `match ::std::iter::Iterator::next(&mut iter) { ... }`
let match_expr = {
let next_path = {
let strs = fld.cx.std_path(&["iter", "Iterator", "next"]);
fld.cx.path_global(span, strs)
};
let ref_mut_iter = fld.cx.expr_mut_addr_of(span, fld.cx.expr_ident(span, iter));
let next_expr =
fld.cx.expr_call(span, fld.cx.expr_path(next_path), vec![ref_mut_iter]);
let arms = vec![pat_arm, break_arm];
fld.cx.expr(pat_span,
ast::ExprMatch(next_expr, arms, ast::MatchSource::ForLoopDesugar))
};
// `[opt_ident]: loop { ... }`
let loop_block = fld.cx.block_expr(match_expr);
let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
let loop_expr = fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident));
// `mut iter => { ... }`
let iter_arm = {
let iter_pat =
fld.cx.pat_ident_binding_mode(span, iter, ast::BindByValue(ast::MutMutable));
fld.cx.arm(span, vec![iter_pat], loop_expr)
};
// `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
let into_iter_expr = {
let into_iter_path = {
let strs = fld.cx.std_path(&["iter", "IntoIterator",
"into_iter"]);
fld.cx.path_global(span, strs)
};
fld.cx.expr_call(span, fld.cx.expr_path(into_iter_path), vec![head])
};
let match_expr = fld.cx.expr_match(span, into_iter_expr, vec![iter_arm]);
// `{ let result = ...; result }`
let result_ident = token::gensym_ident("result");
let result = fld.cx.expr_block(
fld.cx.block_all(
span,
vec![fld.cx.stmt_let(span, false, result_ident, match_expr)],
Some(fld.cx.expr_ident(span, result_ident))));
fld.cx.bt_pop();
result
let else_opt = else_opt.map(|else_opt| fld.fold_expr(else_opt));
let sub_expr = fld.fold_expr(sub_expr);
fld.cx.expr(span, ast::ExprIfLet(rewritten_pats.remove(0), sub_expr, body, else_opt))
}
ast::ExprClosure(capture_clause, fn_decl, block) => {
@ -475,25 +153,6 @@ pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
}, fld))
}
});
fn push_unsafe_expr(cx: &mut ExtCtxt, stmts: Vec<P<ast::Stmt>>,
expr: P<ast::Expr>, span: Span)
-> P<ast::Expr> {
let rules = ast::PushUnsafeBlock(ast::CompilerGenerated);
cx.expr_block(P(ast::Block {
rules: rules, span: span, id: ast::DUMMY_NODE_ID,
stmts: stmts, expr: Some(expr),
}))
}
fn pop_unsafe_expr(cx: &mut ExtCtxt, expr: P<ast::Expr>, span: Span)
-> P<ast::Expr> {
let rules = ast::PopUnsafeBlock(ast::CompilerGenerated);
cx.expr_block(P(ast::Block {
rules: rules, span: span, id: ast::DUMMY_NODE_ID,
stmts: vec![], expr: Some(expr),
}))
}
}
/// Expand a (not-ident-style) macro invocation. Returns the result
@ -948,18 +607,18 @@ fn expand_arm(arm: ast::Arm, fld: &mut MacroExpander) -> ast::Arm {
if expanded_pats.is_empty() {
panic!("encountered match arm with 0 patterns");
}
// all of the pats must have the same set of bindings, so use the
// first one to extract them and generate new names:
let idents = pattern_bindings(&*expanded_pats[0]);
let new_renames = idents.into_iter().map(|id| (id, fresh_name(id))).collect();
// apply the renaming, but only to the PatIdents:
let mut rename_pats_fld = PatIdentRenamer{renames:&new_renames};
let rewritten_pats = expanded_pats.move_map(|pat| rename_pats_fld.fold_pat(pat));
// apply renaming and then expansion to the guard and the body:
let mut rename_fld = IdentRenamer{renames:&new_renames};
let rewritten_guard =
arm.guard.map(|g| fld.fold_expr(rename_fld.fold_expr(g)));
let rewritten_body = fld.fold_expr(rename_fld.fold_expr(arm.body));
let ((rewritten_guard, rewritten_body), rewritten_pats) =
rename_in_scope(expanded_pats,
fld,
(arm.guard, arm.body),
|rename_fld, fld, (ag, ab)|{
let rewritten_guard = ag.map(|g| fld.fold_expr(rename_fld.fold_expr(g)));
let rewritten_body = fld.fold_expr(rename_fld.fold_expr(ab));
(rewritten_guard, rewritten_body)
});
ast::Arm {
attrs: fold::fold_attrs(arm.attrs, fld),
pats: rewritten_pats,
@ -968,6 +627,25 @@ fn expand_arm(arm: ast::Arm, fld: &mut MacroExpander) -> ast::Arm {
}
}
fn rename_in_scope<X, F>(pats: Vec<P<ast::Pat>>,
fld: &mut MacroExpander,
x: X,
f: F)
-> (X, Vec<P<ast::Pat>>)
where F: Fn(&mut IdentRenamer, &mut MacroExpander, X) -> X
{
// all of the pats must have the same set of bindings, so use the
// first one to extract them and generate new names:
let idents = pattern_bindings(&*pats[0]);
let new_renames = idents.into_iter().map(|id| (id, fresh_name(id))).collect();
// apply the renaming, but only to the PatIdents:
let mut rename_pats_fld = PatIdentRenamer{renames:&new_renames};
let rewritten_pats = pats.move_map(|pat| rename_pats_fld.fold_pat(pat));
let mut rename_fld = IdentRenamer{ renames:&new_renames };
(f(&mut rename_fld, fld, x), rewritten_pats)
}
/// A visitor that extracts the PatIdent (binding) paths
/// from a given thingy and puts them in a mutable
/// array

View File

@ -726,7 +726,7 @@ impl<'a, 'v> Visitor<'v> for MacroVisitor<'a> {
}
struct PostExpansionVisitor<'a> {
context: &'a Context<'a>
context: &'a Context<'a>,
}
impl<'a> PostExpansionVisitor<'a> {

View File

@ -1256,10 +1256,9 @@ pub fn noop_fold_expr<T: Folder>(Expr {id, node, span}: Expr, folder: &mut T) ->
ExprLoop(folder.fold_block(body),
opt_ident.map(|i| folder.fold_ident(i)))
}
ExprMatch(expr, arms, source) => {
ExprMatch(expr, arms) => {
ExprMatch(folder.fold_expr(expr),
arms.move_map(|x| folder.fold_arm(x)),
source)
arms.move_map(|x| folder.fold_arm(x)))
}
ExprClosure(capture_clause, decl, body) => {
ExprClosure(capture_clause,

View File

@ -37,7 +37,7 @@ use ast::{LifetimeDef, Lit, Lit_};
use ast::{LitBool, LitChar, LitByte, LitByteStr};
use ast::{LitStr, LitInt, Local};
use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
use ast::{MutImmutable, MutMutable, Mac_, MatchSource};
use ast::{MutImmutable, MutMutable, Mac_};
use ast::{MutTy, BiMul, Mutability};
use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, UnNot};
use ast::{Pat, PatBox, PatEnum, PatIdent, PatLit, PatQPath, PatMac, PatRange};
@ -2927,7 +2927,7 @@ impl<'a> Parser<'a> {
}
let hi = self.span.hi;
try!(self.bump());
return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal)));
return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms)));
}
pub fn parse_arm_nopanic(&mut self) -> PResult<Arm> {

View File

@ -2045,7 +2045,7 @@ impl<'a> State<'a> {
try!(space(&mut self.s));
try!(self.print_block(&**blk));
}
ast::ExprMatch(ref expr, ref arms, _) => {
ast::ExprMatch(ref expr, ref arms) => {
try!(self.cbox(indent_unit));
try!(self.ibox(4));
try!(self.word_nbsp("match"));

View File

@ -731,7 +731,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) {
visitor.visit_block(block);
walk_opt_ident(visitor, expression.span, opt_ident)
}
ExprMatch(ref subexpression, ref arms, _) => {
ExprMatch(ref subexpression, ref arms) => {
visitor.visit_expr(subexpression);
walk_list!(visitor, visit_arm, arms);
}

View File

@ -9,7 +9,5 @@
// except according to those terms.
fn main() {
for
&1 //~ ERROR refutable pattern in `for` loop binding
in [1].iter() {}
for &1 in [1].iter() {} //~ ERROR refutable pattern in `for` loop binding
}

View File

@ -16,4 +16,17 @@ fn main() -> (){
for n in 0..1 {
println!("{}", f!()); //~ ERROR unresolved name `n`
}
if let Some(n) = None {
println!("{}", f!()); //~ ERROR unresolved name `n`
}
if false {
} else if let Some(n) = None {
println!("{}", f!()); //~ ERROR unresolved name `n`
}
while let Some(n) = None {
println!("{}", f!()); //~ ERROR unresolved name `n`
}
}

View File

@ -13,10 +13,8 @@
fn main() {
let values: Vec<u8> = vec![1,2,3,4,5,6,7,8];
for
[x,y,z]
//~^ ERROR refutable pattern in `for` loop binding: `[]` not covered
in values.chunks(3).filter(|&xs| xs.len() == 3) {
for [x,y,z] in values.chunks(3).filter(|&xs| xs.len() == 3) {
//~^ ERROR refutable pattern in `for` loop binding: `[]` not covered
println!("y={}", y);
}
}

View File

@ -8,11 +8,17 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we get an expansion stack for `for` loops.
// Check that placement in respects unsafe code checks.
// error-pattern:in this expansion of for loop expansion
#![feature(box_heap)]
#![feature(placement_in_syntax)]
fn main() {
for t in &foo {
}
use std::boxed::HEAP;
let p: *const i32 = &42;
let _ = in HEAP { *p }; //~ ERROR requires unsafe
let p: *const _ = &HEAP;
let _ = in *p { 42 }; //~ ERROR requires unsafe
}

View File

@ -0,0 +1,27 @@
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that placement in respects unstable code checks.
#![feature(placement_in_syntax)]
#![feature(core)]
extern crate core;
fn main() {
use std::boxed::HEAP; //~ ERROR use of unstable library feature
let _ = in HEAP { //~ ERROR use of unstable library feature
::core::raw::Slice { //~ ERROR use of unstable library feature
data: &42, //~ ERROR use of unstable library feature
len: 1 //~ ERROR use of unstable library feature
}
};
}

View File

@ -31,7 +31,7 @@ use rustc::middle::ty;
use rustc::session::config::{self, basic_options, build_configuration, Input, Options};
use rustc::session::build_session;
use rustc_driver::driver;
use rustc_front::lowering::lower_crate;
use rustc_front::lowering::{lower_crate, LoweringContext};
use rustc_resolve::MakeGlobMap;
use libc::c_void;
@ -223,12 +223,13 @@ fn compile_program(input: &str, sysroot: PathBuf)
.expect("phase_2 returned `None`");
let krate = driver::assign_node_ids(&sess, krate);
let mut hir_forest = ast_map::Forest::new(lower_crate(&krate));
let lcx = LoweringContext::new(&sess, Some(&krate));
let mut hir_forest = ast_map::Forest::new(lower_crate(&lcx, &krate));
let arenas = ty::CtxtArenas::new();
let ast_map = driver::make_map(&sess, &mut hir_forest);
driver::phase_3_run_analysis_passes(
sess, ast_map, &arenas, id, MakeGlobMap::No, |tcx, analysis| {
&sess, ast_map, &arenas, id, MakeGlobMap::No, |tcx, analysis| {
let trans = driver::phase_4_translate_to_llvm(tcx, analysis);
@ -246,7 +247,7 @@ fn compile_program(input: &str, sysroot: PathBuf)
let modp = llmod as usize;
(modp, deps)
}).1
})
}).unwrap();
match handle.join() {

View File

@ -339,8 +339,27 @@ fn main() { // foo
if let SomeEnum::Strings(..) = s7 {
println!("hello!");
}
for i in 0..5 {
foo_foo(i);
}
if let Some(x) = None {
foo_foo(x);
}
if false {
} else if let Some(y) = None {
foo_foo(y);
}
while let Some(z) = None {
foo_foo(z);
}
}
fn foo_foo(_: i32) {}
impl Iterator for nofields {
type Item = (usize, usize);