From 56713a1684c22742a3a4d3d2b19fa09fa6832024 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Fri, 25 Sep 2015 16:03:28 +1200 Subject: [PATCH 01/15] Add a lowering context --- src/librustc_driver/driver.rs | 22 +- src/librustc_driver/lib.rs | 1 + src/librustc_driver/pretty.rs | 6 +- src/librustc_front/lowering.rs | 890 ++++++++++++++-------------- src/librustc_trans/save/dump_csv.rs | 9 +- src/librustc_trans/save/mod.rs | 22 +- 6 files changed, 487 insertions(+), 463 deletions(-) diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index 91843d23cab..a3055d6d67c 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -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; @@ -112,9 +112,11 @@ pub fn compile_input(sess: Session, let expanded_crate = assign_node_ids(&sess, expanded_crate); // Lower ast -> hir. + let foo = &42; + let lcx = LoweringContext::new(foo); 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 +130,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); @@ -152,7 +155,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 +282,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<'tcx>>, pub trans: Option<&'a trans::CrateTranslation>, } @@ -299,6 +304,7 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> { ast_map: None, analysis: None, tcx: None, + lcx: None, trans: None, } } @@ -333,13 +339,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<'tcx>) -> 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 +358,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<'tcx>) -> 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) } } diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index e4f033efb58..276b747feb2 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -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)); diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index f0fa1ff70c6..53b940c57a7 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -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)] @@ -670,9 +670,11 @@ 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 foo = &42; + let lcx = LoweringContext::new(foo); 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 { diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index d1026f1dfb2..c3544ff1aa0 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -17,115 +17,121 @@ use syntax::ptr::P; use syntax::codemap::{respan, Spanned}; use syntax::owned_slice::OwnedSlice; +pub struct LoweringContext<'hir> { + // TODO + foo: &'hir i32, +} -pub fn lower_view_path(view_path: &ViewPath) -> P { +impl<'hir> LoweringContext<'hir> { + pub fn new(foo: &'hir i32) -> LoweringContext<'hir> { + LoweringContext { + foo: foo, + } + } +} + +pub fn lower_view_path(_lctx: &LoweringContext, view_path: &ViewPath) -> P { P(Spanned { node: match view_path.node { ViewPathSimple(ident, ref path) => { - hir::ViewPathSimple(ident.name, lower_path(path)) + hir::ViewPathSimple(ident.name, lower_path(_lctx, path)) } ViewPathGlob(ref path) => { - hir::ViewPathGlob(lower_path(path)) + hir::ViewPathGlob(lower_path(_lctx, path)) } ViewPathList(ref path, ref path_list_idents) => { - hir::ViewPathList(lower_path(path), - path_list_idents.iter() - .map(|path_list_ident| { - Spanned { - node: match path_list_ident.node { - PathListIdent { id, name, rename } => - hir::PathListIdent { - id: id, - name: name.name, - rename: rename.map(|x| x.name), - }, - PathListMod { id, rename } => - hir::PathListMod { - id: id, - rename: rename.map(|x| x.name), - }, - }, - span: path_list_ident.span, - } - }) - .collect()) + hir::ViewPathList(lower_path(_lctx, path), + path_list_idents.iter().map(|path_list_ident| { + Spanned { + node: match path_list_ident.node { + PathListIdent { id, name, rename } => + hir::PathListIdent { + id: id, + name: name.name, + rename: rename.map(|x| x.name), + }, + PathListMod { id, rename } => + hir::PathListMod { + id: id, + rename: rename.map(|x| x.name) + } + }, + span: path_list_ident.span + } + }).collect()) } }, span: view_path.span, }) } -pub fn lower_arm(arm: &Arm) -> hir::Arm { +pub fn lower_arm(_lctx: &LoweringContext, arm: &Arm) -> hir::Arm { hir::Arm { attrs: arm.attrs.clone(), - pats: arm.pats.iter().map(|x| lower_pat(x)).collect(), - guard: arm.guard.as_ref().map(|ref x| lower_expr(x)), - body: lower_expr(&arm.body), + pats: arm.pats.iter().map(|x| lower_pat(_lctx, x)).collect(), + guard: arm.guard.as_ref().map(|ref x| lower_expr(_lctx, x)), + body: lower_expr(_lctx, &arm.body), } } -pub fn lower_decl(d: &Decl) -> P { +pub fn lower_decl(_lctx: &LoweringContext, d: &Decl) -> P { match d.node { DeclLocal(ref l) => P(Spanned { - node: hir::DeclLocal(lower_local(l)), - span: d.span, + node: hir::DeclLocal(lower_local(_lctx, l)), + span: d.span }), DeclItem(ref it) => P(Spanned { - node: hir::DeclItem(lower_item(it)), - span: d.span, + node: hir::DeclItem(lower_item(_lctx, it)), + span: d.span }), } } -pub fn lower_ty_binding(b: &TypeBinding) -> P { - P(hir::TypeBinding { - id: b.id, - name: b.ident.name, - ty: lower_ty(&b.ty), - span: b.span, - }) +pub fn lower_ty_binding(_lctx: &LoweringContext, b: &TypeBinding) -> P { + P(hir::TypeBinding { id: b.id, name: b.ident.name, ty: lower_ty(_lctx, &b.ty), span: b.span }) } -pub fn lower_ty(t: &Ty) -> P { +pub fn lower_ty(_lctx: &LoweringContext, t: &Ty) -> P { P(hir::Ty { id: t.id, node: match t.node { TyInfer => hir::TyInfer, - TyVec(ref ty) => hir::TyVec(lower_ty(ty)), - TyPtr(ref mt) => hir::TyPtr(lower_mt(mt)), + TyVec(ref ty) => hir::TyVec(lower_ty(_lctx, ty)), + TyPtr(ref mt) => hir::TyPtr(lower_mt(_lctx, mt)), TyRptr(ref region, ref mt) => { - hir::TyRptr(lower_opt_lifetime(region), lower_mt(mt)) + hir::TyRptr(lower_opt_lifetime(_lctx, region), lower_mt(_lctx, mt)) } TyBareFn(ref f) => { hir::TyBareFn(P(hir::BareFnTy { - lifetimes: lower_lifetime_defs(&f.lifetimes), - unsafety: lower_unsafety(f.unsafety), + lifetimes: lower_lifetime_defs(_lctx, &f.lifetimes), + unsafety: lower_unsafety(_lctx, f.unsafety), abi: f.abi, - decl: lower_fn_decl(&f.decl), + decl: lower_fn_decl(_lctx, &f.decl), })) } - TyTup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(ty)).collect()), - TyParen(ref ty) => hir::TyParen(lower_ty(ty)), + TyTup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(_lctx, ty)).collect()), + TyParen(ref ty) => hir::TyParen(lower_ty(_lctx, ty)), TyPath(ref qself, ref path) => { let qself = qself.as_ref().map(|&QSelf { ref ty, position }| { hir::QSelf { - ty: lower_ty(ty), + ty: lower_ty(_lctx, ty), position: position, } }); - hir::TyPath(qself, lower_path(path)) + hir::TyPath(qself, lower_path(_lctx, path)) } TyObjectSum(ref ty, ref bounds) => { - hir::TyObjectSum(lower_ty(ty), lower_bounds(bounds)) + hir::TyObjectSum(lower_ty(_lctx, ty), + lower_bounds(_lctx, bounds)) } TyFixedLengthVec(ref ty, ref e) => { - hir::TyFixedLengthVec(lower_ty(ty), lower_expr(e)) + hir::TyFixedLengthVec(lower_ty(_lctx, ty), lower_expr(_lctx, e)) } TyTypeof(ref expr) => { - hir::TyTypeof(lower_expr(expr)) + hir::TyTypeof(lower_expr(_lctx, expr)) } TyPolyTraitRef(ref bounds) => { - hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(b)).collect()) + hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(_lctx, b)).collect()) } TyMac(_) => panic!("TyMac should have been expanded by now."), }, @@ -133,14 +139,14 @@ pub fn lower_ty(t: &Ty) -> P { }) } -pub fn lower_foreign_mod(fm: &ForeignMod) -> hir::ForeignMod { +pub fn lower_foreign_mod(_lctx: &LoweringContext, fm: &ForeignMod) -> hir::ForeignMod { hir::ForeignMod { abi: fm.abi, - items: fm.items.iter().map(|x| lower_foreign_item(x)).collect(), + items: fm.items.iter().map(|x| lower_foreign_item(_lctx, x)).collect(), } } -pub fn lower_variant(v: &Variant) -> P { +pub fn lower_variant(_lctx: &LoweringContext, v: &Variant) -> P { P(Spanned { node: hir::Variant_ { id: v.node.id, @@ -148,117 +154,111 @@ pub fn lower_variant(v: &Variant) -> P { attrs: v.node.attrs.clone(), kind: match v.node.kind { TupleVariantKind(ref variant_args) => { - hir::TupleVariantKind(variant_args.iter() - .map(|ref x| lower_variant_arg(x)) - .collect()) + hir::TupleVariantKind(variant_args.iter().map(|ref x| + lower_variant_arg(_lctx, x)).collect()) } StructVariantKind(ref struct_def) => { - hir::StructVariantKind(lower_struct_def(struct_def)) + hir::StructVariantKind(lower_struct_def(_lctx, struct_def)) } }, - disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(e)), + disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(_lctx, e)), }, span: v.span, }) } -pub fn lower_path(p: &Path) -> hir::Path { +pub fn lower_path(_lctx: &LoweringContext, p: &Path) -> hir::Path { hir::Path { global: p.global, - segments: p.segments - .iter() - .map(|&PathSegment { identifier, ref parameters }| { - hir::PathSegment { - identifier: identifier, - parameters: lower_path_parameters(parameters), - } - }) - .collect(), + segments: p.segments.iter().map(|&PathSegment {identifier, ref parameters}| + hir::PathSegment { + identifier: identifier, + parameters: lower_path_parameters(_lctx, parameters), + }).collect(), span: p.span, } } -pub fn lower_path_parameters(path_parameters: &PathParameters) -> hir::PathParameters { +pub fn lower_path_parameters(_lctx: &LoweringContext, + path_parameters: &PathParameters) + -> hir::PathParameters { match *path_parameters { AngleBracketedParameters(ref data) => - hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(data)), + hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(_lctx, data)), ParenthesizedParameters(ref data) => - hir::ParenthesizedParameters(lower_parenthesized_parameter_data(data)), + hir::ParenthesizedParameters(lower_parenthesized_parameter_data(_lctx, data)), } } -pub fn lower_angle_bracketed_parameter_data(data: &AngleBracketedParameterData) +pub fn lower_angle_bracketed_parameter_data(_lctx: &LoweringContext, + data: &AngleBracketedParameterData) -> hir::AngleBracketedParameterData { let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data; hir::AngleBracketedParameterData { - lifetimes: lower_lifetimes(lifetimes), - types: types.iter().map(|ty| lower_ty(ty)).collect(), - bindings: bindings.iter().map(|b| lower_ty_binding(b)).collect(), + lifetimes: lower_lifetimes(_lctx, lifetimes), + types: types.iter().map(|ty| lower_ty(_lctx, ty)).collect(), + bindings: bindings.iter().map(|b| lower_ty_binding(_lctx, b)).collect(), } } -pub fn lower_parenthesized_parameter_data(data: &ParenthesizedParameterData) +pub fn lower_parenthesized_parameter_data(_lctx: &LoweringContext, + data: &ParenthesizedParameterData) -> hir::ParenthesizedParameterData { let &ParenthesizedParameterData { ref inputs, ref output, span } = data; hir::ParenthesizedParameterData { - inputs: inputs.iter().map(|ty| lower_ty(ty)).collect(), - output: output.as_ref().map(|ty| lower_ty(ty)), + inputs: inputs.iter().map(|ty| lower_ty(_lctx, ty)).collect(), + output: output.as_ref().map(|ty| lower_ty(_lctx, ty)), span: span, } } -pub fn lower_local(l: &Local) -> P { +pub fn lower_local(_lctx: &LoweringContext, l: &Local) -> P { P(hir::Local { - id: l.id, - ty: l.ty.as_ref().map(|t| lower_ty(t)), - pat: lower_pat(&l.pat), - init: l.init.as_ref().map(|e| lower_expr(e)), - span: l.span, - }) + id: l.id, + ty: l.ty.as_ref().map(|t| lower_ty(_lctx, t)), + pat: lower_pat(_lctx, &l.pat), + init: l.init.as_ref().map(|e| lower_expr(_lctx, e)), + span: l.span, + }) } -pub fn lower_explicit_self_underscore(es: &ExplicitSelf_) -> hir::ExplicitSelf_ { +pub fn lower_explicit_self_underscore(_lctx: &LoweringContext, + es: &ExplicitSelf_) + -> hir::ExplicitSelf_ { match *es { SelfStatic => hir::SelfStatic, SelfValue(v) => hir::SelfValue(v.name), SelfRegion(ref lifetime, m, ident) => { - hir::SelfRegion(lower_opt_lifetime(lifetime), - lower_mutability(m), + hir::SelfRegion(lower_opt_lifetime(_lctx, lifetime), + lower_mutability(_lctx, m), ident.name) } SelfExplicit(ref typ, ident) => { - hir::SelfExplicit(lower_ty(typ), ident.name) + hir::SelfExplicit(lower_ty(_lctx, typ), ident.name) } } } -pub fn lower_mutability(m: Mutability) -> hir::Mutability { +pub fn lower_mutability(_lctx: &LoweringContext, m: Mutability) -> hir::Mutability { match m { MutMutable => hir::MutMutable, MutImmutable => hir::MutImmutable, } } -pub fn lower_explicit_self(s: &ExplicitSelf) -> hir::ExplicitSelf { - Spanned { - node: lower_explicit_self_underscore(&s.node), - span: s.span, - } +pub fn lower_explicit_self(_lctx: &LoweringContext, s: &ExplicitSelf) -> hir::ExplicitSelf { + Spanned { node: lower_explicit_self_underscore(_lctx, &s.node), span: s.span } } -pub fn lower_arg(arg: &Arg) -> hir::Arg { - hir::Arg { - id: arg.id, - pat: lower_pat(&arg.pat), - ty: lower_ty(&arg.ty), - } +pub fn lower_arg(_lctx: &LoweringContext, arg: &Arg) -> hir::Arg { + hir::Arg { id: arg.id, pat: lower_pat(_lctx, &arg.pat), ty: lower_ty(_lctx, &arg.ty) } } -pub fn lower_fn_decl(decl: &FnDecl) -> P { +pub fn lower_fn_decl(_lctx: &LoweringContext, decl: &FnDecl) -> P { P(hir::FnDecl { - inputs: decl.inputs.iter().map(|x| lower_arg(x)).collect(), + inputs: decl.inputs.iter().map(|x| lower_arg(_lctx, x)).collect(), output: match decl.output { - Return(ref ty) => hir::Return(lower_ty(ty)), + Return(ref ty) => hir::Return(lower_ty(_lctx, ty)), DefaultReturn(span) => hir::DefaultReturn(span), NoReturn(span) => hir::NoReturn(span), }, @@ -266,86 +266,90 @@ pub fn lower_fn_decl(decl: &FnDecl) -> P { }) } -pub fn lower_ty_param_bound(tpb: &TyParamBound) -> hir::TyParamBound { +pub fn lower_ty_param_bound(_lctx: &LoweringContext, tpb: &TyParamBound) -> hir::TyParamBound { match *tpb { TraitTyParamBound(ref ty, modifier) => { - hir::TraitTyParamBound(lower_poly_trait_ref(ty), - lower_trait_bound_modifier(modifier)) + hir::TraitTyParamBound(lower_poly_trait_ref(_lctx, ty), + lower_trait_bound_modifier(_lctx, modifier)) + } + RegionTyParamBound(ref lifetime) => { + hir::RegionTyParamBound(lower_lifetime(_lctx, lifetime)) } - RegionTyParamBound(ref lifetime) => hir::RegionTyParamBound(lower_lifetime(lifetime)), } } -pub fn lower_ty_param(tp: &TyParam) -> hir::TyParam { +pub fn lower_ty_param(_lctx: &LoweringContext, tp: &TyParam) -> hir::TyParam { hir::TyParam { id: tp.id, name: tp.ident.name, - bounds: lower_bounds(&tp.bounds), - default: tp.default.as_ref().map(|x| lower_ty(x)), + bounds: lower_bounds(_lctx, &tp.bounds), + default: tp.default.as_ref().map(|x| lower_ty(_lctx, x)), span: tp.span, } } -pub fn lower_ty_params(tps: &OwnedSlice) -> OwnedSlice { - tps.iter().map(|tp| lower_ty_param(tp)).collect() +pub fn lower_ty_params(_lctx: &LoweringContext, + tps: &OwnedSlice) + -> OwnedSlice { + tps.iter().map(|tp| lower_ty_param(_lctx, tp)).collect() } -pub fn lower_lifetime(l: &Lifetime) -> hir::Lifetime { - hir::Lifetime { - id: l.id, - name: l.name, - span: l.span, - } +pub fn lower_lifetime(_lctx: &LoweringContext, l: &Lifetime) -> hir::Lifetime { + hir::Lifetime { id: l.id, name: l.name, span: l.span } } -pub fn lower_lifetime_def(l: &LifetimeDef) -> hir::LifetimeDef { +pub fn lower_lifetime_def(_lctx: &LoweringContext, l: &LifetimeDef) -> hir::LifetimeDef { hir::LifetimeDef { - lifetime: lower_lifetime(&l.lifetime), - bounds: lower_lifetimes(&l.bounds), + lifetime: lower_lifetime(_lctx, &l.lifetime), + bounds: lower_lifetimes(_lctx, &l.bounds) } } -pub fn lower_lifetimes(lts: &Vec) -> Vec { - lts.iter().map(|l| lower_lifetime(l)).collect() +pub fn lower_lifetimes(_lctx: &LoweringContext, lts: &Vec) -> Vec { + lts.iter().map(|l| lower_lifetime(_lctx, l)).collect() } -pub fn lower_lifetime_defs(lts: &Vec) -> Vec { - lts.iter().map(|l| lower_lifetime_def(l)).collect() +pub fn lower_lifetime_defs(_lctx: &LoweringContext, + lts: &Vec) + -> Vec { + lts.iter().map(|l| lower_lifetime_def(_lctx, l)).collect() } -pub fn lower_opt_lifetime(o_lt: &Option) -> Option { - o_lt.as_ref().map(|lt| lower_lifetime(lt)) +pub fn lower_opt_lifetime(_lctx: &LoweringContext, + o_lt: &Option) + -> Option { + o_lt.as_ref().map(|lt| lower_lifetime(_lctx, lt)) } -pub fn lower_generics(g: &Generics) -> hir::Generics { +pub fn lower_generics(_lctx: &LoweringContext, g: &Generics) -> hir::Generics { hir::Generics { - ty_params: lower_ty_params(&g.ty_params), - lifetimes: lower_lifetime_defs(&g.lifetimes), - where_clause: lower_where_clause(&g.where_clause), + ty_params: lower_ty_params(_lctx, &g.ty_params), + lifetimes: lower_lifetime_defs(_lctx, &g.lifetimes), + where_clause: lower_where_clause(_lctx, &g.where_clause), } } -pub fn lower_where_clause(wc: &WhereClause) -> hir::WhereClause { +pub fn lower_where_clause(_lctx: &LoweringContext, wc: &WhereClause) -> hir::WhereClause { hir::WhereClause { id: wc.id, - predicates: wc.predicates - .iter() - .map(|predicate| lower_where_predicate(predicate)) - .collect(), + predicates: wc.predicates.iter().map(|predicate| + lower_where_predicate(_lctx, predicate)).collect(), } } -pub fn lower_where_predicate(pred: &WherePredicate) -> hir::WherePredicate { +pub fn lower_where_predicate(_lctx: &LoweringContext, + pred: &WherePredicate) + -> hir::WherePredicate { match *pred { WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes, ref bounded_ty, ref bounds, span}) => { hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate { - bound_lifetimes: lower_lifetime_defs(bound_lifetimes), - bounded_ty: lower_ty(bounded_ty), - bounds: bounds.iter().map(|x| lower_ty_param_bound(x)).collect(), - span: span, + bound_lifetimes: lower_lifetime_defs(_lctx, bound_lifetimes), + bounded_ty: lower_ty(_lctx, bounded_ty), + bounds: bounds.iter().map(|x| lower_ty_param_bound(_lctx, x)).collect(), + span: span }) } WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime, @@ -353,8 +357,8 @@ pub fn lower_where_predicate(pred: &WherePredicate) -> hir::WherePredicate { span}) => { hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate { span: span, - lifetime: lower_lifetime(lifetime), - bounds: bounds.iter().map(|bound| lower_lifetime(bound)).collect(), + lifetime: lower_lifetime(_lctx, lifetime), + bounds: bounds.iter().map(|bound| lower_lifetime(_lctx, bound)).collect() }) } WherePredicate::EqPredicate(WhereEqPredicate{ id, @@ -363,145 +367,138 @@ pub fn lower_where_predicate(pred: &WherePredicate) -> hir::WherePredicate { span}) => { hir::WherePredicate::EqPredicate(hir::WhereEqPredicate { id: id, - path: lower_path(path), - ty: lower_ty(ty), - span: span, + path: lower_path(_lctx, path), + ty:lower_ty(_lctx, ty), + span: span }) } } } -pub fn lower_struct_def(sd: &StructDef) -> P { +pub fn lower_struct_def(_lctx: &LoweringContext, sd: &StructDef) -> P { P(hir::StructDef { - fields: sd.fields.iter().map(|f| lower_struct_field(f)).collect(), + fields: sd.fields.iter().map(|f| lower_struct_field(_lctx, f)).collect(), ctor_id: sd.ctor_id, }) } -pub fn lower_trait_ref(p: &TraitRef) -> hir::TraitRef { - hir::TraitRef { - path: lower_path(&p.path), - ref_id: p.ref_id, - } +pub fn lower_trait_ref(_lctx: &LoweringContext, p: &TraitRef) -> hir::TraitRef { + hir::TraitRef { path: lower_path(_lctx, &p.path), ref_id: p.ref_id } } -pub fn lower_poly_trait_ref(p: &PolyTraitRef) -> hir::PolyTraitRef { +pub fn lower_poly_trait_ref(_lctx: &LoweringContext, p: &PolyTraitRef) -> hir::PolyTraitRef { hir::PolyTraitRef { - bound_lifetimes: lower_lifetime_defs(&p.bound_lifetimes), - trait_ref: lower_trait_ref(&p.trait_ref), + bound_lifetimes: lower_lifetime_defs(_lctx, &p.bound_lifetimes), + trait_ref: lower_trait_ref(_lctx, &p.trait_ref), span: p.span, } } -pub fn lower_struct_field(f: &StructField) -> hir::StructField { +pub fn lower_struct_field(_lctx: &LoweringContext, f: &StructField) -> hir::StructField { Spanned { node: hir::StructField_ { id: f.node.id, - kind: lower_struct_field_kind(&f.node.kind), - ty: lower_ty(&f.node.ty), + kind: lower_struct_field_kind(_lctx, &f.node.kind), + ty: lower_ty(_lctx, &f.node.ty), attrs: f.node.attrs.clone(), }, span: f.span, } } -pub fn lower_field(f: &Field) -> hir::Field { +pub fn lower_field(_lctx: &LoweringContext, f: &Field) -> hir::Field { hir::Field { name: respan(f.ident.span, f.ident.node.name), - expr: lower_expr(&f.expr), - span: f.span, + expr: lower_expr(_lctx, &f.expr), span: f.span } } -pub fn lower_mt(mt: &MutTy) -> hir::MutTy { - hir::MutTy { - ty: lower_ty(&mt.ty), - mutbl: lower_mutability(mt.mutbl), - } +pub fn lower_mt(_lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy { + hir::MutTy { ty: lower_ty(_lctx, &mt.ty), mutbl: lower_mutability(_lctx, mt.mutbl) } } -pub fn lower_opt_bounds(b: &Option>) +pub fn lower_opt_bounds(_lctx: &LoweringContext, b: &Option>) -> Option> { - b.as_ref().map(|ref bounds| lower_bounds(bounds)) + b.as_ref().map(|ref bounds| lower_bounds(_lctx, bounds)) } -fn lower_bounds(bounds: &TyParamBounds) -> hir::TyParamBounds { - bounds.iter().map(|bound| lower_ty_param_bound(bound)).collect() +fn lower_bounds(_lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParamBounds { + bounds.iter().map(|bound| lower_ty_param_bound(_lctx, bound)).collect() } -fn lower_variant_arg(va: &VariantArg) -> hir::VariantArg { - hir::VariantArg { - id: va.id, - ty: lower_ty(&va.ty), - } +fn lower_variant_arg(_lctx: &LoweringContext, va: &VariantArg) -> hir::VariantArg { + hir::VariantArg { id: va.id, ty: lower_ty(_lctx, &va.ty) } } -pub fn lower_block(b: &Block) -> P { +pub fn lower_block(_lctx: &LoweringContext, b: &Block) -> P { P(hir::Block { id: b.id, - stmts: b.stmts.iter().map(|s| lower_stmt(s)).collect(), - expr: b.expr.as_ref().map(|ref x| lower_expr(x)), - rules: lower_block_check_mode(&b.rules), + stmts: b.stmts.iter().map(|s| lower_stmt(_lctx, s)).collect(), + expr: b.expr.as_ref().map(|ref x| lower_expr(_lctx, x)), + rules: lower_block_check_mode(_lctx, &b.rules), span: b.span, }) } -pub fn lower_item_underscore(i: &Item_) -> hir::Item_ { +pub fn lower_item_underscore(_lctx: &LoweringContext, i: &Item_) -> hir::Item_ { match *i { ItemExternCrate(string) => hir::ItemExternCrate(string), ItemUse(ref view_path) => { - hir::ItemUse(lower_view_path(view_path)) + hir::ItemUse(lower_view_path(_lctx, view_path)) } ItemStatic(ref t, m, ref e) => { - hir::ItemStatic(lower_ty(t), lower_mutability(m), lower_expr(e)) + hir::ItemStatic(lower_ty(_lctx, t), lower_mutability(_lctx, m), lower_expr(_lctx, e)) } ItemConst(ref t, ref e) => { - hir::ItemConst(lower_ty(t), lower_expr(e)) + hir::ItemConst(lower_ty(_lctx, t), lower_expr(_lctx, e)) } ItemFn(ref decl, unsafety, constness, abi, ref generics, ref body) => { - hir::ItemFn(lower_fn_decl(decl), - lower_unsafety(unsafety), - lower_constness(constness), - abi, - lower_generics(generics), - lower_block(body)) + hir::ItemFn( + lower_fn_decl(_lctx, decl), + lower_unsafety(_lctx, unsafety), + lower_constness(_lctx, constness), + abi, + lower_generics(_lctx, generics), + lower_block(_lctx, body) + ) } - ItemMod(ref m) => hir::ItemMod(lower_mod(m)), - ItemForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(nm)), + ItemMod(ref m) => hir::ItemMod(lower_mod(_lctx, m)), + ItemForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(_lctx, nm)), ItemTy(ref t, ref generics) => { - hir::ItemTy(lower_ty(t), lower_generics(generics)) + hir::ItemTy(lower_ty(_lctx, t), lower_generics(_lctx, generics)) } ItemEnum(ref enum_definition, ref generics) => { - hir::ItemEnum(hir::EnumDef { - variants: enum_definition.variants - .iter() - .map(|x| lower_variant(x)) - .collect(), - }, - lower_generics(generics)) + hir::ItemEnum( + hir::EnumDef { + variants: enum_definition.variants.iter().map(|x| { + lower_variant(_lctx, x) + }).collect(), + }, + lower_generics(_lctx, generics)) } ItemStruct(ref struct_def, ref generics) => { - let struct_def = lower_struct_def(struct_def); - hir::ItemStruct(struct_def, lower_generics(generics)) + let struct_def = lower_struct_def(_lctx, struct_def); + hir::ItemStruct(struct_def, lower_generics(_lctx, generics)) } ItemDefaultImpl(unsafety, ref trait_ref) => { - hir::ItemDefaultImpl(lower_unsafety(unsafety), lower_trait_ref(trait_ref)) + hir::ItemDefaultImpl(lower_unsafety(_lctx, unsafety), lower_trait_ref(_lctx, trait_ref)) } ItemImpl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => { - let new_impl_items = impl_items.iter().map(|item| lower_impl_item(item)).collect(); - let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(trait_ref)); - hir::ItemImpl(lower_unsafety(unsafety), - lower_impl_polarity(polarity), - lower_generics(generics), + let new_impl_items = + impl_items.iter().map(|item| lower_impl_item(_lctx, item)).collect(); + let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(_lctx, trait_ref)); + hir::ItemImpl(lower_unsafety(_lctx, unsafety), + lower_impl_polarity(_lctx, polarity), + lower_generics(_lctx, generics), ifce, - lower_ty(ty), + lower_ty(_lctx, ty), new_impl_items) } ItemTrait(unsafety, ref generics, ref bounds, ref items) => { - let bounds = lower_bounds(bounds); - let items = items.iter().map(|item| lower_trait_item(item)).collect(); - hir::ItemTrait(lower_unsafety(unsafety), - lower_generics(generics), + let bounds = lower_bounds(_lctx, bounds); + let items = items.iter().map(|item| lower_trait_item(_lctx, item)).collect(); + hir::ItemTrait(lower_unsafety(_lctx, unsafety), + lower_generics(_lctx, generics), bounds, items) } @@ -509,67 +506,65 @@ pub fn lower_item_underscore(i: &Item_) -> hir::Item_ { } } -pub fn lower_trait_item(i: &TraitItem) -> P { +pub fn lower_trait_item(_lctx: &LoweringContext, i: &TraitItem) -> P { P(hir::TraitItem { id: i.id, name: i.ident.name, attrs: i.attrs.clone(), node: match i.node { ConstTraitItem(ref ty, ref default) => { - hir::ConstTraitItem(lower_ty(ty), - default.as_ref().map(|x| lower_expr(x))) + hir::ConstTraitItem(lower_ty(_lctx, ty), + default.as_ref().map(|x| lower_expr(_lctx, x))) } MethodTraitItem(ref sig, ref body) => { - hir::MethodTraitItem(lower_method_sig(sig), - body.as_ref().map(|x| lower_block(x))) + hir::MethodTraitItem(lower_method_sig(_lctx, sig), + body.as_ref().map(|x| lower_block(_lctx, x))) } TypeTraitItem(ref bounds, ref default) => { - hir::TypeTraitItem(lower_bounds(bounds), - default.as_ref().map(|x| lower_ty(x))) + hir::TypeTraitItem(lower_bounds(_lctx, bounds), + default.as_ref().map(|x| lower_ty(_lctx, x))) } }, span: i.span, }) } -pub fn lower_impl_item(i: &ImplItem) -> P { +pub fn lower_impl_item(_lctx: &LoweringContext, i: &ImplItem) -> P { P(hir::ImplItem { - id: i.id, - name: i.ident.name, - attrs: i.attrs.clone(), - vis: lower_visibility(i.vis), - node: match i.node { + id: i.id, + name: i.ident.name, + attrs: i.attrs.clone(), + vis: lower_visibility(_lctx, i.vis), + node: match i.node { ConstImplItem(ref ty, ref expr) => { - hir::ConstImplItem(lower_ty(ty), lower_expr(expr)) + hir::ConstImplItem(lower_ty(_lctx, ty), lower_expr(_lctx, expr)) } MethodImplItem(ref sig, ref body) => { - hir::MethodImplItem(lower_method_sig(sig), lower_block(body)) + hir::MethodImplItem(lower_method_sig(_lctx, sig), + lower_block(_lctx, body)) } - TypeImplItem(ref ty) => hir::TypeImplItem(lower_ty(ty)), + TypeImplItem(ref ty) => hir::TypeImplItem(lower_ty(_lctx, ty)), MacImplItem(..) => panic!("Shouldn't exist any more"), }, span: i.span, }) } -pub fn lower_mod(m: &Mod) -> hir::Mod { - hir::Mod { - inner: m.inner, - items: m.items.iter().map(|x| lower_item(x)).collect(), - } +pub fn lower_mod(_lctx: &LoweringContext, m: &Mod) -> hir::Mod { + hir::Mod { inner: m.inner, items: m.items.iter().map(|x| lower_item(_lctx, x)).collect() } } -pub fn lower_crate(c: &Crate) -> hir::Crate { +pub fn lower_crate(_lctx: &LoweringContext, c: &Crate) -> hir::Crate { hir::Crate { - module: lower_mod(&c.module), + module: lower_mod(_lctx, &c.module), attrs: c.attrs.clone(), config: c.config.clone(), span: c.span, - exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(m)).collect(), + exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(_lctx, m)).collect(), } } -pub fn lower_macro_def(m: &MacroDef) -> hir::MacroDef { +pub fn lower_macro_def(_lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef { hir::MacroDef { name: m.ident.name, attrs: m.attrs.clone(), @@ -584,68 +579,68 @@ pub fn lower_macro_def(m: &MacroDef) -> hir::MacroDef { } // fold one item into possibly many items -pub fn lower_item(i: &Item) -> P { - P(lower_item_simple(i)) +pub fn lower_item(_lctx: &LoweringContext, i: &Item) -> P { + P(lower_item_simple(_lctx, i)) } // fold one item into exactly one item -pub fn lower_item_simple(i: &Item) -> hir::Item { - let node = lower_item_underscore(&i.node); +pub fn lower_item_simple(_lctx: &LoweringContext, i: &Item) -> hir::Item { + let node = lower_item_underscore(_lctx, &i.node); hir::Item { id: i.id, name: i.ident.name, attrs: i.attrs.clone(), node: node, - vis: lower_visibility(i.vis), + vis: lower_visibility(_lctx, i.vis), span: i.span, } } -pub fn lower_foreign_item(i: &ForeignItem) -> P { +pub fn lower_foreign_item(_lctx: &LoweringContext, i: &ForeignItem) -> P { P(hir::ForeignItem { id: i.id, name: i.ident.name, attrs: i.attrs.clone(), node: match i.node { ForeignItemFn(ref fdec, ref generics) => { - hir::ForeignItemFn(lower_fn_decl(fdec), lower_generics(generics)) + hir::ForeignItemFn(lower_fn_decl(_lctx, fdec), lower_generics(_lctx, generics)) } ForeignItemStatic(ref t, m) => { - hir::ForeignItemStatic(lower_ty(t), m) + hir::ForeignItemStatic(lower_ty(_lctx, t), m) } }, - vis: lower_visibility(i.vis), - span: i.span, - }) + vis: lower_visibility(_lctx, i.vis), + span: i.span, + }) } -pub fn lower_method_sig(sig: &MethodSig) -> hir::MethodSig { +pub fn lower_method_sig(_lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig { hir::MethodSig { - generics: lower_generics(&sig.generics), + generics: lower_generics(_lctx, &sig.generics), abi: sig.abi, - explicit_self: lower_explicit_self(&sig.explicit_self), - unsafety: lower_unsafety(sig.unsafety), - constness: lower_constness(sig.constness), - decl: lower_fn_decl(&sig.decl), + explicit_self: lower_explicit_self(_lctx, &sig.explicit_self), + unsafety: lower_unsafety(_lctx, sig.unsafety), + constness: lower_constness(_lctx, sig.constness), + decl: lower_fn_decl(_lctx, &sig.decl), } } -pub fn lower_unsafety(u: Unsafety) -> hir::Unsafety { +pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety { match u { Unsafety::Unsafe => hir::Unsafety::Unsafe, Unsafety::Normal => hir::Unsafety::Normal, } } -pub fn lower_constness(c: Constness) -> hir::Constness { +pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness { match c { Constness::Const => hir::Constness::Const, Constness::NotConst => hir::Constness::NotConst, } } -pub fn lower_unop(u: UnOp) -> hir::UnOp { +pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp { match u { UnDeref => hir::UnDeref, UnNot => hir::UnNot, @@ -653,7 +648,7 @@ pub fn lower_unop(u: UnOp) -> hir::UnOp { } } -pub fn lower_binop(b: BinOp) -> hir::BinOp { +pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp { Spanned { node: match b.node { BiAdd => hir::BiAdd, @@ -679,55 +674,52 @@ pub fn lower_binop(b: BinOp) -> hir::BinOp { } } -pub fn lower_pat(p: &Pat) -> P { +pub fn lower_pat(_lctx: &LoweringContext, p: &Pat) -> P { P(hir::Pat { - id: p.id, - node: match p.node { - PatWild(k) => hir::PatWild(lower_pat_wild_kind(k)), + id: p.id, + node: match p.node { + PatWild(k) => hir::PatWild(lower_pat_wild_kind(_lctx, k)), PatIdent(ref binding_mode, pth1, ref sub) => { - hir::PatIdent(lower_binding_mode(binding_mode), - pth1, - sub.as_ref().map(|x| lower_pat(x))) + hir::PatIdent(lower_binding_mode(_lctx, binding_mode), + pth1, + sub.as_ref().map(|x| lower_pat(_lctx, x))) } - PatLit(ref e) => hir::PatLit(lower_expr(e)), + PatLit(ref e) => hir::PatLit(lower_expr(_lctx, e)), PatEnum(ref pth, ref pats) => { - hir::PatEnum(lower_path(pth), - pats.as_ref().map(|pats| pats.iter().map(|x| lower_pat(x)).collect())) + hir::PatEnum(lower_path(_lctx, pth), + pats.as_ref() + .map(|pats| pats.iter().map(|x| lower_pat(_lctx, x)).collect())) } PatQPath(ref qself, ref pth) => { let qself = hir::QSelf { - ty: lower_ty(&qself.ty), + ty: lower_ty(_lctx, &qself.ty), position: qself.position, }; - hir::PatQPath(qself, lower_path(pth)) + hir::PatQPath(qself, lower_path(_lctx, pth)) } PatStruct(ref pth, ref fields, etc) => { - let pth = lower_path(pth); - let fs = fields.iter() - .map(|f| { - Spanned { - span: f.span, - node: hir::FieldPat { - name: f.node.ident.name, - pat: lower_pat(&f.node.pat), - is_shorthand: f.node.is_shorthand, - }, - } - }) - .collect(); + let pth = lower_path(_lctx, pth); + let fs = fields.iter().map(|f| { + Spanned { span: f.span, + node: hir::FieldPat { + name: f.node.ident.name, + pat: lower_pat(_lctx, &f.node.pat), + is_shorthand: f.node.is_shorthand, + }} + }).collect(); hir::PatStruct(pth, fs, etc) } - PatTup(ref elts) => hir::PatTup(elts.iter().map(|x| lower_pat(x)).collect()), - PatBox(ref inner) => hir::PatBox(lower_pat(inner)), - PatRegion(ref inner, mutbl) => - hir::PatRegion(lower_pat(inner), lower_mutability(mutbl)), + PatTup(ref elts) => hir::PatTup(elts.iter().map(|x| lower_pat(_lctx, x)).collect()), + PatBox(ref inner) => hir::PatBox(lower_pat(_lctx, inner)), + PatRegion(ref inner, mutbl) => hir::PatRegion(lower_pat(_lctx, inner), + lower_mutability(_lctx, mutbl)), PatRange(ref e1, ref e2) => { - hir::PatRange(lower_expr(e1), lower_expr(e2)) - } + hir::PatRange(lower_expr(_lctx, e1), lower_expr(_lctx, e2)) + }, PatVec(ref before, ref slice, ref after) => { - hir::PatVec(before.iter().map(|x| lower_pat(x)).collect(), - slice.as_ref().map(|x| lower_pat(x)), - after.iter().map(|x| lower_pat(x)).collect()) + hir::PatVec(before.iter().map(|x| lower_pat(_lctx, x)).collect(), + slice.as_ref().map(|x| lower_pat(_lctx, x)), + after.iter().map(|x| lower_pat(_lctx, x)).collect()) } PatMac(_) => panic!("Shouldn't exist here"), }, @@ -735,94 +727,106 @@ pub fn lower_pat(p: &Pat) -> P { }) } -pub fn lower_expr(e: &Expr) -> P { +pub fn lower_expr(_lctx: &LoweringContext, e: &Expr) -> P { P(hir::Expr { - id: e.id, - node: match e.node { - ExprBox(ref e) => { - hir::ExprBox(lower_expr(e)) - } - ExprVec(ref exprs) => { - hir::ExprVec(exprs.iter().map(|x| lower_expr(x)).collect()) - } - ExprRepeat(ref expr, ref count) => { - hir::ExprRepeat(lower_expr(expr), lower_expr(count)) - } - ExprTup(ref elts) => hir::ExprTup(elts.iter().map(|x| lower_expr(x)).collect()), - ExprCall(ref f, ref args) => { - hir::ExprCall(lower_expr(f), - args.iter().map(|x| lower_expr(x)).collect()) - } - ExprMethodCall(i, ref tps, ref args) => { - hir::ExprMethodCall(respan(i.span, i.node.name), - tps.iter().map(|x| lower_ty(x)).collect(), - args.iter().map(|x| lower_expr(x)).collect()) - } - ExprBinary(binop, ref lhs, ref rhs) => { - hir::ExprBinary(lower_binop(binop), lower_expr(lhs), lower_expr(rhs)) - } - ExprUnary(op, ref ohs) => { - hir::ExprUnary(lower_unop(op), lower_expr(ohs)) - } - ExprLit(ref l) => hir::ExprLit(P((**l).clone())), - ExprCast(ref expr, ref ty) => { - hir::ExprCast(lower_expr(expr), lower_ty(ty)) - } - ExprAddrOf(m, ref ohs) => hir::ExprAddrOf(lower_mutability(m), lower_expr(ohs)), - ExprIf(ref cond, ref tr, ref fl) => { - hir::ExprIf(lower_expr(cond), - lower_block(tr), - fl.as_ref().map(|x| lower_expr(x))) - } - ExprWhile(ref cond, ref body, opt_ident) => { - hir::ExprWhile(lower_expr(cond), lower_block(body), opt_ident) - } - ExprLoop(ref body, opt_ident) => { - hir::ExprLoop(lower_block(body), opt_ident) - } - ExprMatch(ref expr, ref arms, ref source) => { - hir::ExprMatch(lower_expr(expr), - arms.iter().map(|x| lower_arm(x)).collect(), - lower_match_source(source)) - } - ExprClosure(capture_clause, ref decl, ref body) => { - hir::ExprClosure(lower_capture_clause(capture_clause), - lower_fn_decl(decl), - lower_block(body)) - } - ExprBlock(ref blk) => hir::ExprBlock(lower_block(blk)), - ExprAssign(ref el, ref er) => { - hir::ExprAssign(lower_expr(el), lower_expr(er)) - } - ExprAssignOp(op, ref el, ref er) => { - hir::ExprAssignOp(lower_binop(op), lower_expr(el), lower_expr(er)) - } - ExprField(ref el, ident) => { - hir::ExprField(lower_expr(el), respan(ident.span, ident.node.name)) - } - ExprTupField(ref el, ident) => { - hir::ExprTupField(lower_expr(el), ident) - } - ExprIndex(ref el, ref er) => { - hir::ExprIndex(lower_expr(el), lower_expr(er)) - } - ExprRange(ref e1, ref e2) => { - hir::ExprRange(e1.as_ref().map(|x| lower_expr(x)), - e2.as_ref().map(|x| lower_expr(x))) - } - ExprPath(ref qself, ref path) => { - let qself = qself.as_ref().map(|&QSelf { ref ty, position }| { - hir::QSelf { - ty: lower_ty(ty), - position: position, - } - }); - hir::ExprPath(qself, lower_path(path)) - } - ExprBreak(opt_ident) => hir::ExprBreak(opt_ident), - ExprAgain(opt_ident) => hir::ExprAgain(opt_ident), - ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(x))), - ExprInlineAsm(InlineAsm { + id: e.id, + node: match e.node { + ExprBox(ref e) => { + hir::ExprBox(lower_expr(_lctx, e)) + } + ExprVec(ref exprs) => { + hir::ExprVec(exprs.iter().map(|x| lower_expr(_lctx, x)).collect()) + } + ExprRepeat(ref expr, ref count) => { + hir::ExprRepeat(lower_expr(_lctx, expr), lower_expr(_lctx, count)) + } + ExprTup(ref elts) => { + hir::ExprTup(elts.iter().map(|x| lower_expr(_lctx, x)).collect()) + } + ExprCall(ref f, ref args) => { + hir::ExprCall(lower_expr(_lctx, f), + args.iter().map(|x| lower_expr(_lctx, x)).collect()) + } + ExprMethodCall(i, ref tps, ref args) => { + hir::ExprMethodCall( + respan(i.span, i.node.name), + tps.iter().map(|x| lower_ty(_lctx, x)).collect(), + args.iter().map(|x| lower_expr(_lctx, x)).collect()) + } + ExprBinary(binop, ref lhs, ref rhs) => { + hir::ExprBinary(lower_binop(_lctx, binop), + lower_expr(_lctx, lhs), + lower_expr(_lctx, rhs)) + } + ExprUnary(op, ref ohs) => { + hir::ExprUnary(lower_unop(_lctx, op), lower_expr(_lctx, ohs)) + } + ExprLit(ref l) => hir::ExprLit(P((**l).clone())), + ExprCast(ref expr, ref ty) => { + hir::ExprCast(lower_expr(_lctx, expr), lower_ty(_lctx, ty)) + } + ExprAddrOf(m, ref ohs) => { + hir::ExprAddrOf(lower_mutability(_lctx, m), lower_expr(_lctx, ohs)) + } + ExprIf(ref cond, ref tr, ref fl) => { + hir::ExprIf(lower_expr(_lctx, cond), + lower_block(_lctx, tr), + fl.as_ref().map(|x| lower_expr(_lctx, x))) + } + ExprWhile(ref cond, ref body, opt_ident) => { + hir::ExprWhile(lower_expr(_lctx, cond), + lower_block(_lctx, body), + opt_ident) + } + ExprLoop(ref body, opt_ident) => { + hir::ExprLoop(lower_block(_lctx, body), + opt_ident) + } + ExprMatch(ref expr, ref arms, ref source) => { + hir::ExprMatch(lower_expr(_lctx, expr), + arms.iter().map(|x| lower_arm(_lctx, x)).collect(), + lower_match_source(_lctx, source)) + } + ExprClosure(capture_clause, ref decl, ref body) => { + hir::ExprClosure(lower_capture_clause(_lctx, capture_clause), + lower_fn_decl(_lctx, decl), + lower_block(_lctx, body)) + } + ExprBlock(ref blk) => hir::ExprBlock(lower_block(_lctx, blk)), + ExprAssign(ref el, ref er) => { + hir::ExprAssign(lower_expr(_lctx, el), lower_expr(_lctx, er)) + } + ExprAssignOp(op, ref el, ref er) => { + hir::ExprAssignOp(lower_binop(_lctx, op), + lower_expr(_lctx, el), + lower_expr(_lctx, er)) + } + ExprField(ref el, ident) => { + hir::ExprField(lower_expr(_lctx, el), respan(ident.span, ident.node.name)) + } + ExprTupField(ref el, ident) => { + hir::ExprTupField(lower_expr(_lctx, el), ident) + } + ExprIndex(ref el, ref er) => { + hir::ExprIndex(lower_expr(_lctx, el), lower_expr(_lctx, er)) + } + ExprRange(ref e1, ref e2) => { + hir::ExprRange(e1.as_ref().map(|x| lower_expr(_lctx, x)), + e2.as_ref().map(|x| lower_expr(_lctx, x))) + } + ExprPath(ref qself, ref path) => { + let qself = qself.as_ref().map(|&QSelf { ref ty, position }| { + hir::QSelf { + ty: lower_ty(_lctx, ty), + position: position + } + }); + hir::ExprPath(qself, lower_path(_lctx, path)) + } + ExprBreak(opt_ident) => hir::ExprBreak(opt_ident), + ExprAgain(opt_ident) => hir::ExprAgain(opt_ident), + ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(_lctx, x))), + ExprInlineAsm(InlineAsm { ref inputs, ref outputs, ref asm, @@ -833,65 +837,63 @@ pub fn lower_expr(e: &Expr) -> P { dialect, expn_id, }) => hir::ExprInlineAsm(hir::InlineAsm { - inputs: inputs.iter() - .map(|&(ref c, ref input)| (c.clone(), lower_expr(input))) - .collect(), - outputs: outputs.iter() - .map(|&(ref c, ref out, ref is_rw)| { - (c.clone(), lower_expr(out), *is_rw) - }) - .collect(), - asm: asm.clone(), - asm_str_style: asm_str_style, - clobbers: clobbers.clone(), - volatile: volatile, - alignstack: alignstack, - dialect: dialect, - expn_id: expn_id, - }), - ExprStruct(ref path, ref fields, ref maybe_expr) => { - hir::ExprStruct(lower_path(path), - fields.iter().map(|x| lower_field(x)).collect(), - maybe_expr.as_ref().map(|x| lower_expr(x))) - } - ExprParen(ref ex) => { - return lower_expr(ex); - } - ExprInPlace(..) | - ExprIfLet(..) | - ExprWhileLet(..) | - ExprForLoop(..) | - ExprMac(_) => panic!("Shouldn't exist here"), - }, - span: e.span, - }) + inputs: inputs.iter().map(|&(ref c, ref input)| { + (c.clone(), lower_expr(_lctx, input)) + }).collect(), + outputs: outputs.iter().map(|&(ref c, ref out, ref is_rw)| { + (c.clone(), lower_expr(_lctx, out), *is_rw) + }).collect(), + asm: asm.clone(), + asm_str_style: asm_str_style, + clobbers: clobbers.clone(), + volatile: volatile, + alignstack: alignstack, + dialect: dialect, + expn_id: expn_id, + }), + ExprStruct(ref path, ref fields, ref maybe_expr) => { + hir::ExprStruct(lower_path(_lctx, path), + fields.iter().map(|x| lower_field(_lctx, x)).collect(), + maybe_expr.as_ref().map(|x| lower_expr(_lctx, x))) + }, + ExprParen(ref ex) => { + return lower_expr(_lctx, ex); + } + ExprInPlace(..) | + ExprIfLet(..) | + ExprWhileLet(..) | + ExprForLoop(..) | + ExprMac(_) => panic!("Shouldn't exist here"), + }, + span: e.span, + }) } -pub fn lower_stmt(s: &Stmt) -> P { +pub fn lower_stmt(_lctx: &LoweringContext, s: &Stmt) -> P { match s.node { StmtDecl(ref d, id) => { P(Spanned { - node: hir::StmtDecl(lower_decl(d), id), - span: s.span, + node: hir::StmtDecl(lower_decl(_lctx, d), id), + span: s.span }) } StmtExpr(ref e, id) => { P(Spanned { - node: hir::StmtExpr(lower_expr(e), id), - span: s.span, + node: hir::StmtExpr(lower_expr(_lctx, e), id), + span: s.span }) } StmtSemi(ref e, id) => { P(Spanned { - node: hir::StmtSemi(lower_expr(e), id), - span: s.span, + node: hir::StmtSemi(lower_expr(_lctx, e), id), + span: s.span }) } StmtMac(..) => panic!("Shouldn't exist here"), } } -pub fn lower_match_source(m: &MatchSource) -> hir::MatchSource { +pub fn lower_match_source(_lctx: &LoweringContext, m: &MatchSource) -> hir::MatchSource { match *m { MatchSource::Normal => hir::MatchSource::Normal, MatchSource::IfLetDesugar { contains_else_clause } => { @@ -902,65 +904,69 @@ pub fn lower_match_source(m: &MatchSource) -> hir::MatchSource { } } -pub fn lower_capture_clause(c: CaptureClause) -> hir::CaptureClause { +pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureClause) -> hir::CaptureClause { match c { CaptureByValue => hir::CaptureByValue, CaptureByRef => hir::CaptureByRef, } } -pub fn lower_visibility(v: Visibility) -> hir::Visibility { +pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility { match v { Public => hir::Public, Inherited => hir::Inherited, } } -pub fn lower_block_check_mode(b: &BlockCheckMode) -> hir::BlockCheckMode { +pub fn lower_block_check_mode(_lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode { match *b { DefaultBlock => hir::DefaultBlock, - UnsafeBlock(u) => hir::UnsafeBlock(lower_unsafe_source(u)), - PushUnsafeBlock(u) => hir::PushUnsafeBlock(lower_unsafe_source(u)), - PopUnsafeBlock(u) => hir::PopUnsafeBlock(lower_unsafe_source(u)), + UnsafeBlock(u) => hir::UnsafeBlock(lower_unsafe_source(_lctx, u)), + PushUnsafeBlock(u) => hir::PushUnsafeBlock(lower_unsafe_source(_lctx, u)), + PopUnsafeBlock(u) => hir::PopUnsafeBlock(lower_unsafe_source(_lctx, u)), } } -pub fn lower_pat_wild_kind(p: PatWildKind) -> hir::PatWildKind { +pub fn lower_pat_wild_kind(_lctx: &LoweringContext, p: PatWildKind) -> hir::PatWildKind { match p { PatWildSingle => hir::PatWildSingle, PatWildMulti => hir::PatWildMulti, } } -pub fn lower_binding_mode(b: &BindingMode) -> hir::BindingMode { +pub fn lower_binding_mode(_lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode { match *b { - BindByRef(m) => hir::BindByRef(lower_mutability(m)), - BindByValue(m) => hir::BindByValue(lower_mutability(m)), + BindByRef(m) => hir::BindByRef(lower_mutability(_lctx, m)), + BindByValue(m) => hir::BindByValue(lower_mutability(_lctx, m)), } } -pub fn lower_struct_field_kind(s: &StructFieldKind) -> hir::StructFieldKind { +pub fn lower_struct_field_kind(_lctx: &LoweringContext, + s: &StructFieldKind) + -> hir::StructFieldKind { match *s { - NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(vis)), - UnnamedField(vis) => hir::UnnamedField(lower_visibility(vis)), + NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(_lctx, vis)), + UnnamedField(vis) => hir::UnnamedField(lower_visibility(_lctx, vis)), } } -pub fn lower_unsafe_source(u: UnsafeSource) -> hir::UnsafeSource { +pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource { match u { CompilerGenerated => hir::CompilerGenerated, UserProvided => hir::UserProvided, } } -pub fn lower_impl_polarity(i: ImplPolarity) -> hir::ImplPolarity { +pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity { match i { ImplPolarity::Positive => hir::ImplPolarity::Positive, ImplPolarity::Negative => hir::ImplPolarity::Negative, } } -pub fn lower_trait_bound_modifier(f: TraitBoundModifier) -> hir::TraitBoundModifier { +pub fn lower_trait_bound_modifier(_lctx: &LoweringContext, + f: TraitBoundModifier) + -> hir::TraitBoundModifier { match f { TraitBoundModifier::None => hir::TraitBoundModifier::None, TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe, diff --git a/src/librustc_trans/save/dump_csv.rs b/src/librustc_trans/save/dump_csv.rs index ae85730a876..296dd44a9bc 100644 --- a/src/librustc_trans/save/dump_csv.rs +++ b/src/librustc_trans/save/dump_csv.rs @@ -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<'tcx>, analysis: &'l ty::CrateAnalysis, output_file: Box) -> 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 { @@ -1035,7 +1036,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 +1065,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, _) => { diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index e7a3739cb3f..0d4d97d2b6a 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -38,6 +38,7 @@ mod dump_csv; pub struct SaveContext<'l, 'tcx: 'l> { tcx: &'l ty::ctxt<'tcx>, + lcx: &'l lowering::LoweringContext<'tcx>, span_utils: SpanUtils<'l>, } @@ -176,16 +177,18 @@ 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<'tcx>) -> 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<'tcx>, span_utils: SpanUtils<'l>) -> SaveContext<'l, 'tcx> { SaveContext { tcx: tcx, + lcx: lcx, span_utils: span_utils, } } @@ -454,7 +457,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { pub fn get_expr_data(&self, expr: &ast::Expr) -> Option { 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 +477,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 +708,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<'tcx>, + krate: &ast::Crate, + analysis: &ty::CrateAnalysis, + odir: Option<&Path>) { if generated_code(krate.span) { return; } @@ -757,7 +761,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); From 20083c1e1f6916eb79e3d967c1c9ab63342c71ae Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Mon, 28 Sep 2015 15:00:15 +1300 Subject: [PATCH 02/15] Move `for` loop desugaring to lowering --- mk/crates.mk | 4 +- src/librustc/middle/astencode.rs | 1 + src/librustc/middle/ty/context.rs | 15 +- src/librustc/session/mod.rs | 11 +- src/librustc_driver/driver.rs | 32 +-- src/librustc_driver/pretty.rs | 60 ++-- src/librustc_front/lowering.rs | 398 +++++++++++++++++++++++---- src/librustc_trans/save/dump_csv.rs | 2 +- src/librustc_trans/save/mod.rs | 10 +- src/librustc_typeck/coherence/mod.rs | 1 + src/libsyntax/ast.rs | 4 + src/libsyntax/ext/expand.rs | 96 +------ 12 files changed, 420 insertions(+), 214 deletions(-) diff --git a/mk/crates.mk b/mk/crates.mk index b424c1d8779..0213070d786 100644 --- a/mk/crates.mk +++ b/mk/crates.mk @@ -80,13 +80,13 @@ 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_front := std syntax log serialize DEPS_rustc_lint := rustc log syntax -DEPS_rustc := syntax flate arena serialize getopts rbml \ +DEPS_rustc := syntax flate arena serialize getopts rbml rustc_front\ 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_rustdoc := rustc rustc_driver native:hoedown serialize getopts \ test rustc_lint rustc_front diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 6c23307c677..985a517d8d9 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -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; diff --git a/src/librustc/middle/ty/context.rs b/src/librustc/middle/ty/context.rs index e506e5b2c07..830232cf373 100644 --- a/src/librustc/middle/ty/context.rs +++ b/src/librustc/middle/ty/context.rs @@ -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(s: Session, + pub fn create_and_enter(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 R, R>(f: F) -> R { diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 9d1674b74d1..1eb90580b48 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -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,12 @@ impl Session { } } +impl NodeIdAssigner for Session { + fn next_node_id(&self) -> NodeId { + self.reserve_node_ids(1) + } +} + fn split_msg_into_multilines(msg: &str) -> Option { // Conditions for enabling multi-line errors: if !msg.contains("mismatched types") && diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index a3055d6d67c..6f989811ed2 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -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); @@ -113,7 +113,7 @@ pub fn compile_input(sess: Session, let expanded_crate = assign_node_ids(&sess, expanded_crate); // Lower ast -> hir. let foo = &42; - let lcx = LoweringContext::new(foo); + let lcx = LoweringContext::new(foo, &sess, &expanded_crate); let mut hir_forest = time(sess.time_passes(), "lowering ast -> hir", || hir_map::Forest::new(lower_crate(&lcx, &expanded_crate))); @@ -141,7 +141,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, @@ -282,7 +282,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<'tcx>>, + pub lcx: Option<&'a LoweringContext<'a, 'tcx>>, pub trans: Option<&'a trans::CrateTranslation>, } @@ -340,7 +340,7 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> { krate: &'a ast::Crate, hir_crate: &'a hir::Crate, crate_name: &'a str, - lcx: &'a LoweringContext<'tcx>) + lcx: &'a LoweringContext<'a, 'tcx>) -> CompileState<'a, 'ast, 'tcx> { CompileState { crate_name: Some(crate_name), @@ -359,7 +359,7 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> { hir_crate: &'a hir::Crate, analysis: &'a ty::CrateAnalysis, tcx: &'a ty::ctxt<'tcx>, - lcx: &'a LoweringContext<'tcx>) + lcx: &'a LoweringContext<'a, 'tcx>) -> CompileState<'a, 'ast, 'tcx> { CompileState { analysis: Some(analysis), @@ -659,13 +659,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 { @@ -673,7 +673,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)); @@ -687,7 +687,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 { @@ -695,10 +695,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", || @@ -706,13 +706,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, diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 53b940c57a7..09a1d6f6851 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -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>, 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"), } @@ -224,13 +224,13 @@ trait HirPrinterSupport<'ast>: pprust_hir::PpAnn { fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn; } -struct NoAnn<'ast> { - sess: Session, +struct NoAnn<'ast, 'tcx> { + sess: &'tcx Session, ast_map: Option> } -impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> { - fn sess<'a>(&'a self) -> &'a Session { &self.sess } +impl<'ast, 'tcx> PrinterSupport<'ast> for NoAnn<'ast, 'tcx> { + 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() @@ -239,8 +239,8 @@ impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> { 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 } +impl<'ast, 'tcx> HirPrinterSupport<'ast> for NoAnn<'ast, 'tcx> { + 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() @@ -249,16 +249,16 @@ impl<'ast> HirPrinterSupport<'ast> for NoAnn<'ast> { fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { self } } -impl<'ast> pprust::PpAnn for NoAnn<'ast> {} -impl<'ast> pprust_hir::PpAnn for NoAnn<'ast> {} +impl<'ast, 'tcx> pprust::PpAnn for NoAnn<'ast, 'tcx> {} +impl<'ast, 'tcx> pprust_hir::PpAnn for NoAnn<'ast, 'tcx> {} -struct IdentifiedAnnotation<'ast> { - sess: Session, +struct IdentifiedAnnotation<'ast, 'tcx> { + sess: &'tcx Session, ast_map: Option>, } -impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> { - fn sess<'a>(&'a self) -> &'a Session { &self.sess } +impl<'ast, 'tcx> PrinterSupport<'ast> for IdentifiedAnnotation<'ast, 'tcx> { + 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() @@ -267,7 +267,7 @@ impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> { fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self } } -impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> { +impl<'ast, 'tcx> pprust::PpAnn for IdentifiedAnnotation<'ast, 'tcx> { fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> { @@ -307,8 +307,8 @@ impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> { } } -impl<'ast> HirPrinterSupport<'ast> for IdentifiedAnnotation<'ast> { - fn sess<'a>(&'a self) -> &'a Session { &self.sess } +impl<'ast, 'tcx> HirPrinterSupport<'ast> for IdentifiedAnnotation<'ast, 'tcx> { + 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() @@ -317,7 +317,7 @@ impl<'ast> HirPrinterSupport<'ast> for IdentifiedAnnotation<'ast> { fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { self } } -impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> { +impl<'ast, 'tcx> pprust_hir::PpAnn for IdentifiedAnnotation<'ast, 'tcx> { fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> { @@ -356,13 +356,13 @@ impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> { } } -struct HygieneAnnotation<'ast> { - sess: Session, +struct HygieneAnnotation<'ast, 'tcx> { + sess: &'tcx Session, ast_map: Option>, } -impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> { - fn sess<'a>(&'a self) -> &'a Session { &self.sess } +impl<'ast, 'tcx> PrinterSupport<'ast> for HygieneAnnotation<'ast, 'tcx> { + 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() @@ -371,7 +371,7 @@ impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> { fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self } } -impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> { +impl<'ast, 'tcx> pprust::PpAnn for HygieneAnnotation<'ast, 'tcx> { fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> { @@ -671,7 +671,7 @@ pub fn pretty_print_input(sess: Session, // the ordering of stuff super-finicky. let mut hir_forest; let foo = &42; - let lcx = LoweringContext::new(foo); + let lcx = LoweringContext::new(foo, &sess, &krate); let arenas = ty::CtxtArenas::new(); let ast_map = if compute_ast_map { hir_forest = hir_map::Forest::new(lower_crate(&lcx, &krate)); @@ -697,7 +697,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(), @@ -714,7 +714,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(), @@ -730,7 +730,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, @@ -778,14 +778,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 \ diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index c3544ff1aa0..c8f5f89b669 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -14,20 +14,38 @@ use hir; use syntax::ast::*; use syntax::ptr::P; -use syntax::codemap::{respan, Spanned}; +use syntax::codemap::{respan, Spanned, Span}; use syntax::owned_slice::OwnedSlice; +use syntax::parse::token::{self, str_to_ident}; +use syntax::std_inject; -pub struct LoweringContext<'hir> { +pub struct LoweringContext<'a, 'hir> { // TODO foo: &'hir i32, + id_assigner: &'a NodeIdAssigner, + crate_root: Option<&'static str>, } -impl<'hir> LoweringContext<'hir> { - pub fn new(foo: &'hir i32) -> LoweringContext<'hir> { +impl<'a, 'hir> LoweringContext<'a, 'hir> { + pub fn new(foo: &'hir i32, id_assigner: &'a NodeIdAssigner, c: &Crate) -> LoweringContext<'a, 'hir> { + let crate_root = if std_inject::no_core(c) { + None + } else if std_inject::no_std(c) { + Some("core") + } else { + Some("std") + }; + LoweringContext { foo: foo, + id_assigner: id_assigner, + crate_root: crate_root, } } + + fn next_id(&self) -> NodeId { + self.id_assigner.next_node_id() + } } pub fn lower_view_path(_lctx: &LoweringContext, view_path: &ViewPath) -> P { @@ -727,105 +745,105 @@ pub fn lower_pat(_lctx: &LoweringContext, p: &Pat) -> P { }) } -pub fn lower_expr(_lctx: &LoweringContext, e: &Expr) -> P { +pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { P(hir::Expr { id: e.id, node: match e.node { ExprBox(ref e) => { - hir::ExprBox(lower_expr(_lctx, e)) + hir::ExprBox(lower_expr(lctx, e)) } ExprVec(ref exprs) => { - hir::ExprVec(exprs.iter().map(|x| lower_expr(_lctx, x)).collect()) + hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect()) } ExprRepeat(ref expr, ref count) => { - hir::ExprRepeat(lower_expr(_lctx, expr), lower_expr(_lctx, count)) + hir::ExprRepeat(lower_expr(lctx, expr), lower_expr(lctx, count)) } ExprTup(ref elts) => { - hir::ExprTup(elts.iter().map(|x| lower_expr(_lctx, x)).collect()) + hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect()) } ExprCall(ref f, ref args) => { - hir::ExprCall(lower_expr(_lctx, f), - args.iter().map(|x| lower_expr(_lctx, x)).collect()) + hir::ExprCall(lower_expr(lctx, f), + args.iter().map(|x| lower_expr(lctx, x)).collect()) } ExprMethodCall(i, ref tps, ref args) => { hir::ExprMethodCall( respan(i.span, i.node.name), - tps.iter().map(|x| lower_ty(_lctx, x)).collect(), - args.iter().map(|x| lower_expr(_lctx, x)).collect()) + tps.iter().map(|x| lower_ty(lctx, x)).collect(), + args.iter().map(|x| lower_expr(lctx, x)).collect()) } ExprBinary(binop, ref lhs, ref rhs) => { - hir::ExprBinary(lower_binop(_lctx, binop), - lower_expr(_lctx, lhs), - lower_expr(_lctx, rhs)) + hir::ExprBinary(lower_binop(lctx, binop), + lower_expr(lctx, lhs), + lower_expr(lctx, rhs)) } ExprUnary(op, ref ohs) => { - hir::ExprUnary(lower_unop(_lctx, op), lower_expr(_lctx, ohs)) + hir::ExprUnary(lower_unop(lctx, op), lower_expr(lctx, ohs)) } ExprLit(ref l) => hir::ExprLit(P((**l).clone())), ExprCast(ref expr, ref ty) => { - hir::ExprCast(lower_expr(_lctx, expr), lower_ty(_lctx, ty)) + hir::ExprCast(lower_expr(lctx, expr), lower_ty(lctx, ty)) } ExprAddrOf(m, ref ohs) => { - hir::ExprAddrOf(lower_mutability(_lctx, m), lower_expr(_lctx, ohs)) + hir::ExprAddrOf(lower_mutability(lctx, m), lower_expr(lctx, ohs)) } ExprIf(ref cond, ref tr, ref fl) => { - hir::ExprIf(lower_expr(_lctx, cond), - lower_block(_lctx, tr), - fl.as_ref().map(|x| lower_expr(_lctx, x))) + hir::ExprIf(lower_expr(lctx, cond), + lower_block(lctx, tr), + fl.as_ref().map(|x| lower_expr(lctx, x))) } ExprWhile(ref cond, ref body, opt_ident) => { - hir::ExprWhile(lower_expr(_lctx, cond), - lower_block(_lctx, body), + hir::ExprWhile(lower_expr(lctx, cond), + lower_block(lctx, body), opt_ident) } ExprLoop(ref body, opt_ident) => { - hir::ExprLoop(lower_block(_lctx, body), + hir::ExprLoop(lower_block(lctx, body), opt_ident) } ExprMatch(ref expr, ref arms, ref source) => { - hir::ExprMatch(lower_expr(_lctx, expr), - arms.iter().map(|x| lower_arm(_lctx, x)).collect(), - lower_match_source(_lctx, source)) + hir::ExprMatch(lower_expr(lctx, expr), + arms.iter().map(|x| lower_arm(lctx, x)).collect(), + lower_match_source(lctx, source)) } ExprClosure(capture_clause, ref decl, ref body) => { - hir::ExprClosure(lower_capture_clause(_lctx, capture_clause), - lower_fn_decl(_lctx, decl), - lower_block(_lctx, body)) + hir::ExprClosure(lower_capture_clause(lctx, capture_clause), + lower_fn_decl(lctx, decl), + lower_block(lctx, body)) } - ExprBlock(ref blk) => hir::ExprBlock(lower_block(_lctx, blk)), + ExprBlock(ref blk) => hir::ExprBlock(lower_block(lctx, blk)), ExprAssign(ref el, ref er) => { - hir::ExprAssign(lower_expr(_lctx, el), lower_expr(_lctx, er)) + hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er)) } ExprAssignOp(op, ref el, ref er) => { - hir::ExprAssignOp(lower_binop(_lctx, op), - lower_expr(_lctx, el), - lower_expr(_lctx, er)) + hir::ExprAssignOp(lower_binop(lctx, op), + lower_expr(lctx, el), + lower_expr(lctx, er)) } ExprField(ref el, ident) => { - hir::ExprField(lower_expr(_lctx, el), respan(ident.span, ident.node.name)) + hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name)) } ExprTupField(ref el, ident) => { - hir::ExprTupField(lower_expr(_lctx, el), ident) + hir::ExprTupField(lower_expr(lctx, el), ident) } ExprIndex(ref el, ref er) => { - hir::ExprIndex(lower_expr(_lctx, el), lower_expr(_lctx, er)) + hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er)) } ExprRange(ref e1, ref e2) => { - hir::ExprRange(e1.as_ref().map(|x| lower_expr(_lctx, x)), - e2.as_ref().map(|x| lower_expr(_lctx, x))) + hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)), + e2.as_ref().map(|x| lower_expr(lctx, x))) } ExprPath(ref qself, ref path) => { let qself = qself.as_ref().map(|&QSelf { ref ty, position }| { hir::QSelf { - ty: lower_ty(_lctx, ty), + ty: lower_ty(lctx, ty), position: position } }); - hir::ExprPath(qself, lower_path(_lctx, path)) + hir::ExprPath(qself, lower_path(lctx, path)) } ExprBreak(opt_ident) => hir::ExprBreak(opt_ident), ExprAgain(opt_ident) => hir::ExprAgain(opt_ident), - ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(_lctx, x))), + ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))), ExprInlineAsm(InlineAsm { ref inputs, ref outputs, @@ -838,10 +856,10 @@ pub fn lower_expr(_lctx: &LoweringContext, e: &Expr) -> P { expn_id, }) => hir::ExprInlineAsm(hir::InlineAsm { inputs: inputs.iter().map(|&(ref c, ref input)| { - (c.clone(), lower_expr(_lctx, input)) + (c.clone(), lower_expr(lctx, input)) }).collect(), outputs: outputs.iter().map(|&(ref c, ref out, ref is_rw)| { - (c.clone(), lower_expr(_lctx, out), *is_rw) + (c.clone(), lower_expr(lctx, out), *is_rw) }).collect(), asm: asm.clone(), asm_str_style: asm_str_style, @@ -852,17 +870,124 @@ pub fn lower_expr(_lctx: &LoweringContext, e: &Expr) -> P { expn_id: expn_id, }), ExprStruct(ref path, ref fields, ref maybe_expr) => { - hir::ExprStruct(lower_path(_lctx, path), - fields.iter().map(|x| lower_field(_lctx, x)).collect(), - maybe_expr.as_ref().map(|x| lower_expr(_lctx, x))) + hir::ExprStruct(lower_path(lctx, path), + fields.iter().map(|x| lower_field(lctx, x)).collect(), + maybe_expr.as_ref().map(|x| lower_expr(lctx, x))) }, ExprParen(ref ex) => { - return lower_expr(_lctx, ex); + return lower_expr(lctx, ex); } - ExprInPlace(..) | - ExprIfLet(..) | - ExprWhileLet(..) | - ExprForLoop(..) | + ExprInPlace(..) => { + panic!("todo"); + } + ExprIfLet(..) => { + panic!("todo"); + } + ExprWhileLet(..) => { + panic!("todo"); + } + + // Desugar ExprForLoop + // From: `[opt_ident]: for in ` + ExprForLoop(ref pat, ref head, ref body, ref opt_ident) => { + // to: + // + // { + // let result = match ::std::iter::IntoIterator::into_iter() { + // mut iter => { + // [opt_ident]: loop { + // match ::std::iter::Iterator::next(&mut iter) { + // ::std::option::Option::Some() => , + // ::std::option::Option::None => break + // } + // } + // } + // }; + // result + // } + + // expand + let head = lower_expr(lctx, head); + + let iter = token::gensym_ident("iter"); + + // `::std::option::Option::Some() => ` + let pat_arm = { + let body_block = lower_block(lctx, body); + let body_span = body_block.span; + let body_expr = P(hir::Expr { + id: lctx.next_id(), + node: hir::ExprBlock(body_block), + span: body_span, + }); + let pat = lower_pat(lctx, pat); + let some_pat = pat_some(lctx, e.span, pat); + + arm(vec![some_pat], body_expr) + }; + + // `::std::option::Option::None => break` + let break_arm = { + let break_expr = expr_break(lctx, e.span); + + arm(vec![pat_none(lctx, e.span)], break_expr) + }; + + // `match ::std::iter::Iterator::next(&mut iter) { ... }` + let match_expr = { + let next_path = { + let strs = std_path(lctx, &["iter", "Iterator", "next"]); + + path_global(e.span, strs) + }; + let ref_mut_iter = expr_mut_addr_of(lctx, e.span, expr_ident(lctx, e.span, iter)); + let next_expr = + expr_call(lctx, e.span, expr_path(lctx, next_path), vec![ref_mut_iter]); + let arms = vec![pat_arm, break_arm]; + + expr(lctx, + e.span, + hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar)) + }; + + // `[opt_ident]: loop { ... }` + let loop_block = block_expr(lctx, match_expr); + let loop_expr = expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident.clone())); + + // `mut iter => { ... }` + let iter_arm = { + let iter_pat = + pat_ident_binding_mode(lctx, e.span, iter, hir::BindByValue(hir::MutMutable)); + arm(vec![iter_pat], loop_expr) + }; + + // `match ::std::iter::IntoIterator::into_iter() { ... }` + let into_iter_expr = { + let into_iter_path = { + let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]); + + path_global(e.span, strs) + }; + + expr_call(lctx, e.span, expr_path(lctx, into_iter_path), vec![head]) + }; + + let match_expr = expr_match(lctx, e.span, into_iter_expr, vec![iter_arm]); + + // `{ let result = ...; result }` + let result_ident = token::gensym_ident("result"); + let result = expr_block(lctx, + block_all(lctx, + e.span, + vec![stmt_let(lctx, + e.span, + false, + result_ident, + match_expr)], + Some(expr_ident(lctx, e.span, result_ident)))); + return result; + } + ExprMac(_) => panic!("Shouldn't exist here"), }, span: e.span, @@ -972,3 +1097,168 @@ pub fn lower_trait_bound_modifier(_lctx: &LoweringContext, TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe, } } + +// Helper methods for building HIR. + +fn arm(pats: Vec>, expr: P) -> hir::Arm { + hir::Arm { + attrs: vec!(), + pats: pats, + guard: None, + body: expr + } +} + +fn expr_break(lctx: &LoweringContext, span: Span) -> P { + expr(lctx, span, hir::ExprBreak(None)) +} + +fn expr_call(lctx: &LoweringContext, span: Span, e: P, args: Vec>) -> P { + expr(lctx, span, hir::ExprCall(e, args)) +} + +fn expr_ident(lctx: &LoweringContext, span: Span, id: Ident) -> P { + expr_path(lctx, path_ident(span, id)) +} + +fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P) -> P { + expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e)) +} + +fn expr_path(lctx: &LoweringContext, path: hir::Path) -> P { + expr(lctx, path.span, hir::ExprPath(None, path)) +} + +fn expr_match(lctx: &LoweringContext, span: Span, arg: P, arms: Vec) -> P { + expr(lctx, span, hir::ExprMatch(arg, arms, hir::MatchSource::Normal)) +} + +fn expr_block(lctx: &LoweringContext, b: P) -> P { + expr(lctx, b.span, hir::ExprBlock(b)) +} + +fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_) -> P { + P(hir::Expr { + id: lctx.next_id(), + node: node, + span: span, + }) +} + +fn stmt_let(lctx: &LoweringContext, sp: Span, mutbl: bool, ident: Ident, ex: P) -> P { + let pat = if mutbl { + pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable)) + } else { + pat_ident(lctx, sp, ident) + }; + let local = P(hir::Local { + pat: pat, + ty: None, + init: Some(ex), + id: lctx.next_id(), + span: sp, + }); + let decl = respan(sp, hir::DeclLocal(local)); + P(respan(sp, hir::StmtDecl(P(decl), lctx.next_id()))) +} + +fn block_expr(lctx: &LoweringContext, expr: P) -> P { + block_all(lctx, expr.span, Vec::new(), Some(expr)) +} + +fn block_all(lctx: &LoweringContext, + span: Span, + stmts: Vec>, + expr: Option>) -> P { + P(hir::Block { + stmts: stmts, + expr: expr, + id: lctx.next_id(), + rules: hir::DefaultBlock, + span: span, + }) +} + +fn pat_some(lctx: &LoweringContext, span: Span, pat: P) -> P { + let some = std_path(lctx, &["option", "Option", "Some"]); + let path = path_global(span, some); + pat_enum(lctx, span, path, vec!(pat)) +} + +fn pat_none(lctx: &LoweringContext, span: Span) -> P { + let none = std_path(lctx, &["option", "Option", "None"]); + let path = path_global(span, none); + pat_enum(lctx, span, path, vec![]) +} + +fn pat_enum(lctx: &LoweringContext, span: Span, path: hir::Path, subpats: Vec>) -> P { + let pt = hir::PatEnum(path, Some(subpats)); + pat(lctx, span, pt) +} + +fn pat_ident(lctx: &LoweringContext, span: Span, ident: Ident) -> P { + pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable)) +} + +fn pat_ident_binding_mode(lctx: &LoweringContext, + span: Span, + ident: Ident, + bm: hir::BindingMode) -> P { + let pat_ident = hir::PatIdent(bm, Spanned{span: span, node: ident}, None); + pat(lctx, span, pat_ident) +} + +fn pat(lctx: &LoweringContext, span: Span, pat: hir::Pat_) -> P { + P(hir::Pat { id: lctx.next_id(), node: pat, span: span }) +} + +fn path_ident(span: Span, id: Ident) -> hir::Path { + path(span, vec!(id)) +} + +fn path(span: Span, strs: Vec ) -> hir::Path { + path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new()) +} + +fn path_global(span: Span, strs: Vec ) -> hir::Path { + path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new()) +} + +fn path_all(sp: Span, + global: bool, + mut idents: Vec , + lifetimes: Vec, + types: Vec>, + bindings: Vec> ) + -> hir::Path { + let last_identifier = idents.pop().unwrap(); + let mut segments: Vec = idents.into_iter() + .map(|ident| { + hir::PathSegment { + identifier: ident, + parameters: hir::PathParameters::none(), + } + }).collect(); + segments.push(hir::PathSegment { + identifier: last_identifier, + parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData { + lifetimes: lifetimes, + types: OwnedSlice::from_vec(types), + bindings: OwnedSlice::from_vec(bindings), + }) + }); + hir::Path { + span: sp, + global: global, + segments: segments, + } +} + +fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec { + let mut v = Vec::new(); + if let Some(s) = lctx.crate_root { + v.push(str_to_ident(s)); + } + v.extend(components.iter().map(|s| str_to_ident(s))); + return v +} diff --git a/src/librustc_trans/save/dump_csv.rs b/src/librustc_trans/save/dump_csv.rs index 296dd44a9bc..6a6d0b3bdca 100644 --- a/src/librustc_trans/save/dump_csv.rs +++ b/src/librustc_trans/save/dump_csv.rs @@ -76,7 +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<'tcx>, + lcx: &'l LoweringContext<'l, 'tcx>, analysis: &'l ty::CrateAnalysis, output_file: Box) -> DumpCsvVisitor<'l, 'tcx> { diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index 0d4d97d2b6a..5e26322ebda 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -38,7 +38,7 @@ mod dump_csv; pub struct SaveContext<'l, 'tcx: 'l> { tcx: &'l ty::ctxt<'tcx>, - lcx: &'l lowering::LoweringContext<'tcx>, + lcx: &'l lowering::LoweringContext<'l, 'tcx>, span_utils: SpanUtils<'l>, } @@ -177,13 +177,15 @@ pub struct MethodCallData { impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { - pub fn new(tcx: &'l ty::ctxt<'tcx>, lcx: &'l lowering::LoweringContext<'tcx>) -> SaveContext<'l, 'tcx> { + pub fn new(tcx: &'l ty::ctxt<'tcx>, + lcx: &'l lowering::LoweringContext<'l, 'tcx>) + -> SaveContext<'l, 'tcx> { let span_utils = SpanUtils::new(&tcx.sess); SaveContext::from_span_utils(tcx, lcx, span_utils) } pub fn from_span_utils(tcx: &'l ty::ctxt<'tcx>, - lcx: &'l lowering::LoweringContext<'tcx>, + lcx: &'l lowering::LoweringContext<'l, 'tcx>, span_utils: SpanUtils<'l>) -> SaveContext<'l, 'tcx> { SaveContext { @@ -709,7 +711,7 @@ impl<'v> Visitor<'v> for PathCollector { } pub fn process_crate<'l, 'tcx>(tcx: &'l ty::ctxt<'tcx>, - lcx: &'l lowering::LoweringContext<'tcx>, + lcx: &'l lowering::LoweringContext<'l, 'tcx>, krate: &ast::Crate, analysis: &ty::CrateAnalysis, odir: Option<&Path>) { diff --git a/src/librustc_typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs index b3ec10a8941..5afcdbc8c13 100644 --- a/src/librustc_typeck/coherence/mod.rs +++ b/src/librustc_typeck/coherence/mod.rs @@ -38,6 +38,7 @@ use std::cell::RefCell; use std::rc::Rc; use syntax::codemap::Span; use syntax::parse::token; +use syntax::ast::NodeIdAssigner; use util::nodemap::{DefIdMap, FnvHashMap}; use rustc::front::map as hir_map; use rustc::front::map::NodeItem; diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index ce00505b0b4..bf43b87b267 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -375,6 +375,10 @@ 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; +} + /// 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 diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index b15c51490a1..8cfad6341de 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -360,102 +360,10 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident)) } - // Desugar ExprForLoop - // From: `[opt_ident]: for in ` ast::ExprForLoop(pat, head, body, opt_ident) => { - // to: - // - // { - // let result = match ::std::iter::IntoIterator::into_iter() { - // mut iter => { - // [opt_ident]: loop { - // match ::std::iter::Iterator::next(&mut iter) { - // ::std::option::Option::Some() => , - // ::std::option::Option::None => break - // } - // } - // } - // }; - // result - // } - - push_compiler_expansion(fld, span, CompilerExpansionFormat::ForLoop); - - let span = fld.new_span(span); - - // expand let head = fld.fold_expr(head); - - let iter = token::gensym_ident("iter"); - - let pat_span = fld.new_span(pat.span); - // `::std::option::Option::Some() => ` - 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); - - 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() { ... }` - 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 (body, opt_ident) = expand_loop_block(body, opt_ident, fld); + fld.cx.expr(span, ast::ExprForLoop(pat, head, body, opt_ident)) } ast::ExprClosure(capture_clause, fn_decl, block) => { From 04a7675d222bcba021886bd5f21d7c6b33273811 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Mon, 28 Sep 2015 16:24:08 +1300 Subject: [PATCH 03/15] For loops in save-analysis --- src/librustc_trans/save/dump_csv.rs | 58 ++++++++++++++++++----------- 1 file changed, 37 insertions(+), 21 deletions(-) diff --git a/src/librustc_trans/save/dump_csv.rs b/src/librustc_trans/save/dump_csv.rs index 6a6d0b3bdca..c0021bdc060 100644 --- a/src/librustc_trans/save/dump_csv.rs +++ b/src/librustc_trans/save/dump_csv.rs @@ -796,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 { + "".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> { @@ -1103,6 +1132,12 @@ 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, _) => { + 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); + } _ => { visit::walk_expr(self, ex) } @@ -1180,31 +1215,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 { - "".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); } } + From bc364b4a0d678b29cba92ce948d948aee9d76b25 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Mon, 28 Sep 2015 17:24:42 +1300 Subject: [PATCH 04/15] if let and while let --- src/librustc_front/lowering.rs | 169 +++++++++++++++++++++++++++++---- src/libsyntax/ext/expand.rs | 144 +--------------------------- 2 files changed, 154 insertions(+), 159 deletions(-) diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index c8f5f89b669..d9b834fe9fc 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -786,10 +786,28 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { ExprAddrOf(m, ref ohs) => { hir::ExprAddrOf(lower_mutability(lctx, m), lower_expr(lctx, ohs)) } - ExprIf(ref cond, ref tr, ref fl) => { + // More complicated than you might expect because the else branch + // might be `if let`. + ExprIf(ref cond, ref blk, ref else_opt) => { + let else_opt = else_opt.as_ref().map(|els| match els.node { + ExprIfLet(..) => { + // wrap the if-let expr in a block + let span = els.span; + let blk = P(hir::Block { + stmts: vec![], + expr: Some(lower_expr(lctx, els)), + id: lctx.next_id(), + rules: hir::DefaultBlock, + span: span + }); + expr_block(lctx, blk) + } + _ => lower_expr(lctx, els) + }); + hir::ExprIf(lower_expr(lctx, cond), - lower_block(lctx, tr), - fl.as_ref().map(|x| lower_expr(lctx, x))) + lower_block(lctx, blk), + else_opt) } ExprWhile(ref cond, ref body, opt_ident) => { hir::ExprWhile(lower_expr(lctx, cond), @@ -880,16 +898,123 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { ExprInPlace(..) => { panic!("todo"); } - ExprIfLet(..) => { - panic!("todo"); + + // Desugar ExprIfLet + // From: `if let = []` + ExprIfLet(ref pat, ref sub_expr, ref body, ref else_opt) => { + // to: + // + // match { + // => , + // [_ if => ,] + // _ => [ | ()] + // } + + // ` => ` + let pat_arm = { + let body_expr = expr_block(lctx, lower_block(lctx, body)); + arm(vec![lower_pat(lctx, pat)], body_expr) + }; + + // `[_ if => ,]` + let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e)); + let else_if_arms = { + let mut arms = vec![]; + loop { + let else_opt_continue = else_opt + .and_then(|els| els.and_then(|els| match els.node { + // else if + hir::ExprIf(cond, then, else_opt) => { + let pat_under = pat_wild(lctx, e.span); + arms.push(hir::Arm { + attrs: vec![], + pats: vec![pat_under], + guard: Some(cond), + body: expr_block(lctx, then) + }); + else_opt.map(|else_opt| (else_opt, true)) + } + _ => Some((P(els), false)) + })); + match else_opt_continue { + Some((e, true)) => { + else_opt = Some(e); + } + Some((e, false)) => { + else_opt = Some(e); + break; + } + None => { + else_opt = None; + break; + } + } + } + arms + }; + + let contains_else_clause = else_opt.is_some(); + + // `_ => [ | ()]` + let else_arm = { + let pat_under = pat_wild(lctx, e.span); + let else_expr = else_opt.unwrap_or_else(|| expr_tuple(lctx, e.span, vec![])); + arm(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 = expr(lctx, + e.span, + hir::ExprMatch(lower_expr(lctx, sub_expr), arms, + hir::MatchSource::IfLetDesugar { + contains_else_clause: contains_else_clause, + })); + return match_expr; } - ExprWhileLet(..) => { - panic!("todo"); + + // Desugar ExprWhileLet + // From: `[opt_ident]: while let = ` + ExprWhileLet(ref pat, ref sub_expr, ref body, opt_ident) => { + // to: + // + // [opt_ident]: loop { + // match { + // => , + // _ => break + // } + // } + + // ` => ` + let pat_arm = { + let body_expr = expr_block(lctx, lower_block(lctx, body)); + arm(vec![lower_pat(lctx, pat)], body_expr) + }; + + // `_ => break` + let break_arm = { + let pat_under = pat_wild(lctx, e.span); + let break_expr = expr_break(lctx, e.span); + arm(vec![pat_under], break_expr) + }; + + // // `match { ... }` + let arms = vec![pat_arm, break_arm]; + let match_expr = expr(lctx, + e.span, + hir::ExprMatch(lower_expr(lctx, sub_expr), arms, hir::MatchSource::WhileLetDesugar)); + + // `[opt_ident]: loop { ... }` + let loop_block = block_expr(lctx, match_expr); + return expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident)); } // Desugar ExprForLoop // From: `[opt_ident]: for in ` - ExprForLoop(ref pat, ref head, ref body, ref opt_ident) => { + ExprForLoop(ref pat, ref head, ref body, opt_ident) => { // to: // // { @@ -952,7 +1077,7 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { // `[opt_ident]: loop { ... }` let loop_block = block_expr(lctx, match_expr); - let loop_expr = expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident.clone())); + let loop_expr = expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident)); // `mut iter => { ... }` let iter_arm = { @@ -976,16 +1101,14 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { // `{ let result = ...; result }` let result_ident = token::gensym_ident("result"); - let result = expr_block(lctx, - block_all(lctx, - e.span, - vec![stmt_let(lctx, - e.span, - false, - result_ident, - match_expr)], - Some(expr_ident(lctx, e.span, result_ident)))); - return result; + return expr_block(lctx, + block_all(lctx, + e.span, + vec![stmt_let(lctx, e.span, + false, + result_ident, + match_expr)], + Some(expr_ident(lctx, e.span, result_ident)))) } ExprMac(_) => panic!("Shouldn't exist here"), @@ -1137,6 +1260,10 @@ fn expr_block(lctx: &LoweringContext, b: P) -> P { expr(lctx, b.span, hir::ExprBlock(b)) } +fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: Vec>) -> P { + expr(lctx, sp, hir::ExprTup(exprs)) +} + fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_) -> P { P(hir::Expr { id: lctx.next_id(), @@ -1208,6 +1335,10 @@ fn pat_ident_binding_mode(lctx: &LoweringContext, pat(lctx, span, pat_ident) } +fn pat_wild(lctx: &LoweringContext, span: Span) -> P { + pat(lctx, span, hir::PatWild(hir::PatWildSingle)) +} + fn pat(lctx: &LoweringContext, span: Span, pat: hir::Pat_) -> P { P(hir::Pat { id: lctx.next_id(), node: pat, span: span }) } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 8cfad6341de..f6767bc4e47 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -212,147 +212,11 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { fld.cx.expr(span, ast::ExprWhile(cond, body, opt_ident)) } - // Desugar ExprWhileLet - // From: `[opt_ident]: while let = ` ast::ExprWhileLet(pat, expr, body, opt_ident) => { - // to: - // - // [opt_ident]: loop { - // match { - // => , - // _ => break - // } - // } - - push_compiler_expansion(fld, span, CompilerExpansionFormat::WhileLet); - - // ` => ` - 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 { ... }` - 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 = []` - ast::ExprIfLet(pat, expr, body, mut elseopt) => { - // to: - // - // match { - // => , - // [_ if => ,] - // _ => [ | ()] - // } - - push_compiler_expansion(fld, span, CompilerExpansionFormat::IfLet); - - // ` => ` - let pat_arm = { - let body_expr = fld.cx.expr_block(body); - fld.cx.arm(pat.span, vec![pat], body_expr) - }; - - // `[_ if => ,]` - 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(); - - // `_ => [ | ()]` - 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)) + let pat = fld.fold_pat(pat); + let expr = fld.fold_expr(expr); + let (body, opt_ident) = expand_loop_block(body, opt_ident, fld); + fld.cx.expr(span, ast::ExprWhileLet(pat, expr, body, opt_ident)) } ast::ExprLoop(loop_block, opt_ident) => { From 7f469ba6c5b0167949540d6c2afe51a0454767f5 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Tue, 29 Sep 2015 13:17:46 +1300 Subject: [PATCH 05/15] Move placement in desugaring to lowering --- src/librustc_front/lowering.rs | 106 +++++++++++++++++++++- src/libsyntax/ext/expand.rs | 157 +-------------------------------- 2 files changed, 106 insertions(+), 157 deletions(-) diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index d9b834fe9fc..8a8620cbcca 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -752,6 +752,83 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { ExprBox(ref e) => { hir::ExprBox(lower_expr(lctx, e)) } + + // Desugar ExprBox: `in (PLACE) EXPR` + ExprInPlace(Some(ref placer), ref 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) + // }) + + // TODO + println!("{}", lctx.foo); + + let placer_expr = lower_expr(lctx, placer); + let value_expr = lower_expr(lctx, 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 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 = |lctx, p, args| { + let path = core_path(lctx, e.span, p); + let path = expr_path(lctx, path); + expr_call(lctx, e.span, path, args) + }; + + let mk_stmt_let = |lctx, bind, expr| { + stmt_let(lctx, e.span, false, bind, expr) + }; + let mk_stmt_let_mut = |lctx, bind, expr| { + stmt_let(lctx, e.span, true, bind, expr) + }; + + // let placer = ; + let s1 = mk_stmt_let(lctx, placer_ident, placer_expr); + + // let mut place = Placer::make_place(placer); + let s2 = { + let call = make_call(lctx, &make_place, vec![expr_ident(lctx, e.span, placer_ident)]); + mk_stmt_let_mut(lctx, agent_ident, call) + }; + + // let p_ptr = Place::pointer(&mut place); + let s3 = { + let args = vec![expr_mut_addr_of(lctx, e.span, expr_ident(lctx, e.span, agent_ident))]; + let call = make_call(lctx, &place_pointer, args); + mk_stmt_let(lctx, p_ptr_ident, call) + }; + + // pop_unsafe!(EXPR)); + let pop_unsafe_expr = pop_unsafe_expr(lctx, value_expr, e.span); + + // push_unsafe!({ + // ptr::write(p_ptr, pop_unsafe!()); + // InPlace::finalize(place) + // }) + let expr = { + let call_move_val_init = hir::StmtSemi(make_call( + lctx, &move_val_init, vec![expr_ident(lctx, e.span, p_ptr_ident), pop_unsafe_expr]), lctx.next_id()); + let call_move_val_init = respan(e.span, call_move_val_init); + + let call = make_call(lctx, &inplace_finalize, vec![expr_ident(lctx, e.span, agent_ident)]); + Some(push_unsafe_expr(lctx, vec![P(call_move_val_init)], call, e.span)) + }; + + let block = block_all(lctx, e.span, vec![s1, s2, s3], expr); + return expr_block(lctx, block); + } + ExprVec(ref exprs) => { hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect()) } @@ -895,9 +972,6 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { ExprParen(ref ex) => { return lower_expr(lctx, ex); } - ExprInPlace(..) => { - panic!("todo"); - } // Desugar ExprIfLet // From: `if let = []` @@ -1393,3 +1467,29 @@ fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec { v.extend(components.iter().map(|s| str_to_ident(s))); return v } + +// Given suffix ["b","c","d"], returns path `::std::b::c::d` when +// `fld.cx.use_std`, and `::core::b::c::d` otherwise. +fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path { + let idents = std_path(lctx, components); + path_global(span, idents) +} + +fn push_unsafe_expr(lctx: &LoweringContext, stmts: Vec>, + expr: P, span: Span) + -> P { + let rules = hir::PushUnsafeBlock(hir::CompilerGenerated); + expr_block(lctx, P(hir::Block { + rules: rules, span: span, id: lctx.next_id(), + stmts: stmts, expr: Some(expr), + })) +} + +fn pop_unsafe_expr(lctx: &LoweringContext, expr: P, span: Span) + -> P { + let rules = hir::PopUnsafeBlock(hir::CompilerGenerated); + expr_block(lctx, P(hir::Block { + rules: rules, span: span, id: lctx.next_id(), + stmts: vec![], expr: Some(expr), + })) +} diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index f6767bc4e47..abda406dcc8 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -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, fld: &mut MacroExpander) -> P { - 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,118 +61,18 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { }) } - // 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 = ; - 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!()); - // 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::ExprBox(Some(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); @@ -225,6 +92,7 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { } ast::ExprForLoop(pat, head, body, opt_ident) => { + let pat = fld.fold_pat(pat); let head = fld.fold_expr(head); let (body, opt_ident) = expand_loop_block(body, opt_ident, fld); fld.cx.expr(span, ast::ExprForLoop(pat, head, body, opt_ident)) @@ -247,25 +115,6 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { }, fld)) } }); - - fn push_unsafe_expr(cx: &mut ExtCtxt, stmts: Vec>, - expr: P, span: Span) - -> P { - 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, span: Span) - -> P { - 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 From bfffa9ecfc5b0b50f1f99487a67697e16d6c8d34 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Tue, 29 Sep 2015 13:18:05 +1300 Subject: [PATCH 06/15] Fixes to rustdoc, etc. --- src/librustdoc/core.rs | 12 +++++++----- src/librustdoc/test.rs | 11 +++++++++-- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index c84a7e7c560..f62148c16fa 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -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, 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 foo = &42; + let lcx = LoweringContext::new(foo, &sess, &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 +196,5 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec, externs: Externs, *analysis.inlined.borrow_mut() = map; analysis.deref_trait_did = ctxt.deref_trait_did.get(); (krate, analysis) - }).1 + }) } diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 37669d5a9b1..dec2ed789e0 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -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,9 @@ 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 foo = &42; + let lcx = LoweringContext::new(foo, &sess, &krate); + let krate = lower_crate(&lcx, &krate); let opts = scrape_test_config(&krate); @@ -91,8 +93,13 @@ pub fn run(input: &str, let map = hir_map::map_crate(&mut forest); let ctx = core::DocContext { +<<<<<<< HEAD map: &map, maybe_typed: core::NotTyped(sess), +======= + krate: &krate, + maybe_typed: core::NotTyped(&sess), +>>>>>>> Fixes to rustdoc, etc. input: input, external_paths: RefCell::new(Some(HashMap::new())), external_traits: RefCell::new(None), From e0c74868c3964abdd6898886e7d12041c8b3139d Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Tue, 29 Sep 2015 13:46:01 +1300 Subject: [PATCH 07/15] Fix stability --- src/librustc/middle/effect.rs | 2 +- src/librustc/middle/stability.rs | 31 ++++++++++++-- src/librustc_front/hir.rs | 3 ++ src/librustc_front/lowering.rs | 68 ++++++++++++++++++++---------- src/librustc_front/print/pprust.rs | 8 +++- src/librustc_typeck/check/mod.rs | 2 +- src/libsyntax/ext/expand.rs | 2 +- src/libsyntax/feature_gate.rs | 2 +- 8 files changed, 87 insertions(+), 31 deletions(-) diff --git a/src/librustc/middle/effect.rs b/src/librustc/middle/effect.rs index 8a206e3d88e..f849580871c 100644 --- a/src/librustc/middle/effect.rs +++ b/src/librustc/middle/effect.rs @@ -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); diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index be227e620b8..c2235591cee 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -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, - used_features: FnvHashMap + used_features: FnvHashMap, + // 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 diff --git a/src/librustc_front/hir.rs b/src/librustc_front/hir.rs index a89bc26ec09..c9f13da0633 100644 --- a/src/librustc_front/hir.rs +++ b/src/librustc_front/hir.rs @@ -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)] diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index 8a8620cbcca..2b63e0615ee 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -749,12 +749,28 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { P(hir::Expr { id: e.id, node: match e.node { + // 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. ExprBox(ref e) => { hir::ExprBox(lower_expr(lctx, e)) } // Desugar ExprBox: `in (PLACE) EXPR` - ExprInPlace(Some(ref placer), ref value_expr) => { + ExprInPlace(ref placer, ref value_expr) => { // to: // // let p = PLACE; @@ -810,23 +826,43 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { }; // pop_unsafe!(EXPR)); - let pop_unsafe_expr = pop_unsafe_expr(lctx, value_expr, e.span); + let pop_unsafe_expr = + signal_block_expr(lctx, + vec![], + signal_block_expr(lctx, + vec![], + value_expr, + e.span, + hir::PopUnstableBlock), + e.span, + hir::PopUnsafeBlock(hir::CompilerGenerated)); // push_unsafe!({ - // ptr::write(p_ptr, pop_unsafe!()); + // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR )); // InPlace::finalize(place) // }) let expr = { - let call_move_val_init = hir::StmtSemi(make_call( - lctx, &move_val_init, vec![expr_ident(lctx, e.span, p_ptr_ident), pop_unsafe_expr]), lctx.next_id()); + let call_move_val_init = + hir::StmtSemi(make_call(lctx, + &move_val_init, + vec![expr_ident(lctx, e.span, p_ptr_ident), + pop_unsafe_expr]), + lctx.next_id()); let call_move_val_init = respan(e.span, call_move_val_init); let call = make_call(lctx, &inplace_finalize, vec![expr_ident(lctx, e.span, agent_ident)]); - Some(push_unsafe_expr(lctx, vec![P(call_move_val_init)], call, e.span)) + signal_block_expr(lctx, + vec![P(call_move_val_init)], + call, + e.span, + hir::PushUnsafeBlock(hir::CompilerGenerated)) }; - let block = block_all(lctx, e.span, vec![s1, s2, s3], expr); - return expr_block(lctx, block); + return signal_block_expr(lctx, + vec![s1, s2, s3], + expr, + e.span, + hir::PushUnstableBlock); } ExprVec(ref exprs) => { @@ -1475,21 +1511,9 @@ fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Pa path_global(span, idents) } -fn push_unsafe_expr(lctx: &LoweringContext, stmts: Vec>, - expr: P, span: Span) - -> P { - let rules = hir::PushUnsafeBlock(hir::CompilerGenerated); +fn signal_block_expr(lctx: &LoweringContext, stmts: Vec>, expr: P, span: Span, rule: hir::BlockCheckMode) -> P { expr_block(lctx, P(hir::Block { - rules: rules, span: span, id: lctx.next_id(), + rules: rule, span: span, id: lctx.next_id(), stmts: stmts, expr: Some(expr), })) } - -fn pop_unsafe_expr(lctx: &LoweringContext, expr: P, span: Span) - -> P { - let rules = hir::PopUnsafeBlock(hir::CompilerGenerated); - expr_block(lctx, P(hir::Block { - rules: rules, span: span, id: lctx.next_id(), - stmts: vec![], expr: Some(expr), - })) -} diff --git a/src/librustc_front/print/pprust.rs b/src/librustc_front/print/pprust.rs index db0981728ac..80b0a984681 100644 --- a/src/librustc_front/print/pprust.rs +++ b/src/librustc_front/print/pprust.rs @@ -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))); diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 278aa9450ee..0978ea2295b 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -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, diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index abda406dcc8..72d89e246ad 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -70,7 +70,7 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { let placer = fld.fold_expr(placer); let value_expr = fld.fold_expr(value_expr); - fld.cx.expr(span, ast::ExprBox(Some(placer), value_expr)) + fld.cx.expr(span, ast::ExprInPlace(placer, value_expr)) } ast::ExprWhile(cond, body, opt_ident) => { diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index 18c6d74d62e..49835afbfa5 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -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> { From 08f3752270098fb26ff41fc2e5cfbeca2dffeec0 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Wed, 30 Sep 2015 12:19:45 +1300 Subject: [PATCH 08/15] hygiene for `for` loops, `if let`, `while let` and some unrelated test cleanups --- src/librustc/middle/region.rs | 2 +- src/librustc_lint/unused.rs | 10 +-- src/librustc_typeck/check/mod.rs | 2 +- src/libsyntax/ext/expand.rs | 87 +++++++++++++++---- src/test/compile-fail/for-expn-2.rs | 18 ---- ...or-loop-refutable-pattern-error-message.rs | 4 +- src/test/compile-fail/issue-15167.rs | 13 +++ src/test/compile-fail/issue-15381.rs | 6 +- 8 files changed, 94 insertions(+), 48 deletions(-) delete mode 100644 src/test/compile-fail/for-expn-2.rs diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 0f9ba50e788..bdf01f941c4 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -377,7 +377,7 @@ impl RegionMaps { self.code_extents.borrow()[e.0 as usize] } pub fn each_encl_scope(&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) diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index e63bc5f7c4f..9c030d8892a 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -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), diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 0978ea2295b..705b564a1ad 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -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(); diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 72d89e246ad..b1b4605d5ec 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -82,8 +82,18 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { ast::ExprWhileLet(pat, expr, body, opt_ident) => { let pat = fld.fold_pat(pat); let expr = fld.fold_expr(expr); - let (body, opt_ident) = expand_loop_block(body, opt_ident, fld); - fld.cx.expr(span, ast::ExprWhileLet(pat, expr, body, opt_ident)) + + // 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); + + fld.cx.expr(span, ast::ExprWhileLet(rewritten_pats.remove(0), expr, body, opt_ident)) } ast::ExprLoop(loop_block, opt_ident) => { @@ -93,9 +103,37 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { ast::ExprForLoop(pat, head, body, opt_ident) => { let pat = fld.fold_pat(pat); + + // 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 head = fld.fold_expr(head); - let (body, opt_ident) = expand_loop_block(body, opt_ident, fld); - fld.cx.expr(span, ast::ExprForLoop(pat, head, body, opt_ident)) + fld.cx.expr(span, ast::ExprForLoop(rewritten_pats.remove(0), head, body, opt_ident)) + } + + ast::ExprIfLet(pat, sub_expr, body, else_opt) => { + let pat = fld.fold_pat(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); + + 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) => { @@ -569,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, @@ -589,6 +627,25 @@ fn expand_arm(arm: ast::Arm, fld: &mut MacroExpander) -> ast::Arm { } } +fn rename_in_scope(pats: Vec>, + fld: &mut MacroExpander, + x: X, + f: F) + -> (X, Vec>) + 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 diff --git a/src/test/compile-fail/for-expn-2.rs b/src/test/compile-fail/for-expn-2.rs deleted file mode 100644 index ce2315f3a38..00000000000 --- a/src/test/compile-fail/for-expn-2.rs +++ /dev/null @@ -1,18 +0,0 @@ -// 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 or the MIT license -// , at your -// 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. - -// error-pattern:in this expansion of for loop expansion - -fn main() { - for t in &foo { - } -} diff --git a/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs b/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs index ab6dc2bab3e..81c4db68628 100644 --- a/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs +++ b/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs @@ -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 } diff --git a/src/test/compile-fail/issue-15167.rs b/src/test/compile-fail/issue-15167.rs index a1663772bad..898e6be6fc8 100644 --- a/src/test/compile-fail/issue-15167.rs +++ b/src/test/compile-fail/issue-15167.rs @@ -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` + } } diff --git a/src/test/compile-fail/issue-15381.rs b/src/test/compile-fail/issue-15381.rs index 653ba165e74..ec29a84f44e 100644 --- a/src/test/compile-fail/issue-15381.rs +++ b/src/test/compile-fail/issue-15381.rs @@ -13,10 +13,8 @@ fn main() { let values: Vec = 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); } } From ce80094632c727ef87b465fc87873cce1c471ad6 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Wed, 30 Sep 2015 14:56:19 +1300 Subject: [PATCH 09/15] Make save-analysis work for `if let` etc. --- src/librustc_trans/save/dump_csv.rs | 10 +++++++++- src/test/run-make/save-analysis/foo.rs | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/librustc_trans/save/dump_csv.rs b/src/librustc_trans/save/dump_csv.rs index c0021bdc060..256774756b8 100644 --- a/src/librustc_trans/save/dump_csv.rs +++ b/src/librustc_trans/save/dump_csv.rs @@ -1132,12 +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::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) } diff --git a/src/test/run-make/save-analysis/foo.rs b/src/test/run-make/save-analysis/foo.rs index 4981ea475d3..3e4ba5af80c 100644 --- a/src/test/run-make/save-analysis/foo.rs +++ b/src/test/run-make/save-analysis/foo.rs @@ -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); From 21205f4f9e61469b55a853cf6be478cd6bc7a073 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Wed, 30 Sep 2015 16:17:37 +1300 Subject: [PATCH 10/15] Cache ids between lowering runs So that lowering is reproducible --- src/librustc/session/mod.rs | 4 ++ src/librustc_driver/driver.rs | 9 ++-- src/librustc_driver/pretty.rs | 3 +- src/librustc_front/lowering.rs | 83 ++++++++++++++++++++++++----- src/librustc_trans/save/dump_csv.rs | 2 +- src/librustc_trans/save/mod.rs | 8 +-- src/libsyntax/ast.rs | 1 + 7 files changed, 86 insertions(+), 24 deletions(-) diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 1eb90580b48..0a1df25f115 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -318,6 +318,10 @@ 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 { diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index 6f989811ed2..3db484ef930 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -112,8 +112,7 @@ pub fn compile_input(sess: Session, let expanded_crate = assign_node_ids(&sess, expanded_crate); // Lower ast -> hir. - let foo = &42; - let lcx = LoweringContext::new(foo, &sess, &expanded_crate); + let lcx = LoweringContext::new(&sess, &expanded_crate); let mut hir_forest = time(sess.time_passes(), "lowering ast -> hir", || hir_map::Forest::new(lower_crate(&lcx, &expanded_crate))); @@ -282,7 +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, 'tcx>>, + pub lcx: Option<&'a LoweringContext<'a>>, pub trans: Option<&'a trans::CrateTranslation>, } @@ -340,7 +339,7 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> { krate: &'a ast::Crate, hir_crate: &'a hir::Crate, crate_name: &'a str, - lcx: &'a LoweringContext<'a, 'tcx>) + lcx: &'a LoweringContext<'a>) -> CompileState<'a, 'ast, 'tcx> { CompileState { crate_name: Some(crate_name), @@ -359,7 +358,7 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> { hir_crate: &'a hir::Crate, analysis: &'a ty::CrateAnalysis, tcx: &'a ty::ctxt<'tcx>, - lcx: &'a LoweringContext<'a, 'tcx>) + lcx: &'a LoweringContext<'a>) -> CompileState<'a, 'ast, 'tcx> { CompileState { analysis: Some(analysis), diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 09a1d6f6851..73961c8d757 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -670,8 +670,7 @@ 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 foo = &42; - let lcx = LoweringContext::new(foo, &sess, &krate); + let lcx = LoweringContext::new(&sess, &krate); let arenas = ty::CtxtArenas::new(); let ast_map = if compute_ast_map { hir_forest = hir_map::Forest::new(lower_crate(&lcx, &krate)); diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index 2b63e0615ee..27ae39acbf4 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -12,6 +12,8 @@ use hir; +use std::collections::HashMap; + use syntax::ast::*; use syntax::ptr::P; use syntax::codemap::{respan, Spanned, Span}; @@ -19,15 +21,17 @@ use syntax::owned_slice::OwnedSlice; use syntax::parse::token::{self, str_to_ident}; use syntax::std_inject; -pub struct LoweringContext<'a, 'hir> { - // TODO - foo: &'hir i32, - id_assigner: &'a NodeIdAssigner, +use std::cell::{Cell, RefCell}; + +pub struct LoweringContext<'a> { crate_root: Option<&'static str>, + id_cache: RefCell>, + id_assigner: &'a NodeIdAssigner, + cached_id: Cell, } -impl<'a, 'hir> LoweringContext<'a, 'hir> { - pub fn new(foo: &'hir i32, id_assigner: &'a NodeIdAssigner, c: &Crate) -> LoweringContext<'a, 'hir> { +impl<'a, 'hir> LoweringContext<'a> { + pub fn new(id_assigner: &'a NodeIdAssigner, c: &Crate) -> LoweringContext<'a> { let crate_root = if std_inject::no_core(c) { None } else if std_inject::no_std(c) { @@ -37,14 +41,21 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; LoweringContext { - foo: foo, - id_assigner: id_assigner, crate_root: crate_root, + id_cache: RefCell::new(HashMap::new()), + id_assigner: id_assigner, + cached_id: Cell::new(0), } } fn next_id(&self) -> NodeId { - self.id_assigner.next_node_id() + let cached = self.cached_id.get(); + if cached == 0 { + return self.id_assigner.next_node_id() + } + + self.cached_id.set(cached + 1); + cached } } @@ -745,6 +756,49 @@ pub fn lower_pat(_lctx: &LoweringContext, p: &Pat) -> P { }) } +// RAII utility for setting and unsetting the cached id. +struct CachedIdSetter<'a> { + reset: bool, + lctx: &'a LoweringContext<'a>, +} + +impl<'a> CachedIdSetter<'a> { + fn new(lctx: &'a LoweringContext, expr_id: NodeId) -> CachedIdSetter<'a> { + let id_cache: &mut HashMap<_, _> = &mut lctx.id_cache.borrow_mut(); + + if id_cache.contains_key(&expr_id) { + let cached_id = lctx.cached_id.get(); + if cached_id == 0 { + // We're entering a node where we need to track ids, but are not + // yet tracking. + lctx.cached_id.set(id_cache[&expr_id]); + } else { + // We're already tracking - check that the tracked id is the same + // as the expected id. + assert!(cached_id == id_cache[&expr_id], "id mismatch"); + } + } else { + id_cache.insert(expr_id, lctx.id_assigner.peek_node_id()); + } + + CachedIdSetter { + // Only reset the id if it was previously 0, i.e., was not cached. + // If it was cached, we are in a nested node, but our id count will + // still count towards the parent's count. + reset: lctx.cached_id.get() == 0, + lctx: lctx, + } + } +} + +impl<'a> Drop for CachedIdSetter<'a> { + fn drop(&mut self) { + if self.reset { + self.lctx.cached_id.set(0); + } + } +} + pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { P(hir::Expr { id: e.id, @@ -780,9 +834,7 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR )); // InPlace::finalize(place) // }) - - // TODO - println!("{}", lctx.foo); + let _old_cached = CachedIdSetter::new(lctx, e.id); let placer_expr = lower_expr(lctx, placer); let value_expr = lower_expr(lctx, value_expr); @@ -903,6 +955,7 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { // might be `if let`. ExprIf(ref cond, ref blk, ref else_opt) => { let else_opt = else_opt.as_ref().map(|els| match els.node { + let _old_cached = CachedIdSetter::new(lctx, e.id); ExprIfLet(..) => { // wrap the if-let expr in a block let span = els.span; @@ -1019,6 +1072,8 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { // [_ if => ,] // _ => [ | ()] // } + + let _old_cached = CachedIdSetter::new(lctx, e.id); // ` => ` let pat_arm = { @@ -1098,6 +1153,8 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { // } // } + let _old_cached = CachedIdSetter::new(lctx, e.id); + // ` => ` let pat_arm = { let body_expr = expr_block(lctx, lower_block(lctx, body)); @@ -1141,6 +1198,8 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { // result // } + let _old_cached = CachedIdSetter::new(lctx, e.id); + // expand let head = lower_expr(lctx, head); diff --git a/src/librustc_trans/save/dump_csv.rs b/src/librustc_trans/save/dump_csv.rs index 256774756b8..09825f1f919 100644 --- a/src/librustc_trans/save/dump_csv.rs +++ b/src/librustc_trans/save/dump_csv.rs @@ -76,7 +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, 'tcx>, + lcx: &'l LoweringContext<'l>, analysis: &'l ty::CrateAnalysis, output_file: Box) -> DumpCsvVisitor<'l, 'tcx> { diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index 5e26322ebda..72f665f63bf 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -38,7 +38,7 @@ mod dump_csv; pub struct SaveContext<'l, 'tcx: 'l> { tcx: &'l ty::ctxt<'tcx>, - lcx: &'l lowering::LoweringContext<'l, 'tcx>, + lcx: &'l lowering::LoweringContext<'l>, span_utils: SpanUtils<'l>, } @@ -178,14 +178,14 @@ pub struct MethodCallData { impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { pub fn new(tcx: &'l ty::ctxt<'tcx>, - lcx: &'l lowering::LoweringContext<'l, 'tcx>) + lcx: &'l lowering::LoweringContext<'l>) -> SaveContext<'l, 'tcx> { let span_utils = SpanUtils::new(&tcx.sess); SaveContext::from_span_utils(tcx, lcx, span_utils) } pub fn from_span_utils(tcx: &'l ty::ctxt<'tcx>, - lcx: &'l lowering::LoweringContext<'l, 'tcx>, + lcx: &'l lowering::LoweringContext<'l>, span_utils: SpanUtils<'l>) -> SaveContext<'l, 'tcx> { SaveContext { @@ -711,7 +711,7 @@ impl<'v> Visitor<'v> for PathCollector { } pub fn process_crate<'l, 'tcx>(tcx: &'l ty::ctxt<'tcx>, - lcx: &'l lowering::LoweringContext<'l, 'tcx>, + lcx: &'l lowering::LoweringContext<'l>, krate: &ast::Crate, analysis: &ty::CrateAnalysis, odir: Option<&Path>) { diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index bf43b87b267..02cd648b6d8 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -377,6 +377,7 @@ 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. From ba43c228b55d9620d3d480246ee2d9295484a336 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Wed, 30 Sep 2015 17:18:09 +1300 Subject: [PATCH 11/15] Some cleanup of no longer used AST things --- src/librustc_front/lowering.rs | 17 +++-------------- src/librustc_lint/unused.rs | 2 +- src/librustdoc/core.rs | 3 +-- src/librustdoc/test.rs | 3 +-- src/libsyntax/ast.rs | 13 ++----------- src/libsyntax/codemap.rs | 22 ---------------------- src/libsyntax/config.rs | 4 ++-- src/libsyntax/diagnostic.rs | 1 - src/libsyntax/ext/base.rs | 7 ++----- src/libsyntax/ext/build.rs | 2 +- src/libsyntax/fold.rs | 5 ++--- src/libsyntax/parse/parser.rs | 4 ++-- src/libsyntax/print/pprust.rs | 2 +- src/libsyntax/visit.rs | 2 +- 14 files changed, 19 insertions(+), 68 deletions(-) diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index 27ae39acbf4..546b298a92b 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -955,8 +955,8 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { // might be `if let`. ExprIf(ref cond, ref blk, ref else_opt) => { let else_opt = else_opt.as_ref().map(|els| match els.node { - let _old_cached = CachedIdSetter::new(lctx, e.id); ExprIfLet(..) => { + let _old_cached = CachedIdSetter::new(lctx, e.id); // wrap the if-let expr in a block let span = els.span; let blk = P(hir::Block { @@ -984,10 +984,10 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { hir::ExprLoop(lower_block(lctx, body), opt_ident) } - ExprMatch(ref expr, ref arms, ref source) => { + ExprMatch(ref expr, ref arms) => { hir::ExprMatch(lower_expr(lctx, expr), arms.iter().map(|x| lower_arm(lctx, x)).collect(), - lower_match_source(lctx, source)) + hir::MatchSource::Normal) } ExprClosure(capture_clause, ref decl, ref body) => { hir::ExprClosure(lower_capture_clause(lctx, capture_clause), @@ -1310,17 +1310,6 @@ pub fn lower_stmt(_lctx: &LoweringContext, s: &Stmt) -> P { } } -pub fn lower_match_source(_lctx: &LoweringContext, m: &MatchSource) -> hir::MatchSource { - match *m { - MatchSource::Normal => hir::MatchSource::Normal, - MatchSource::IfLetDesugar { contains_else_clause } => { - hir::MatchSource::IfLetDesugar { contains_else_clause: contains_else_clause } - } - MatchSource::WhileLetDesugar => hir::MatchSource::WhileLetDesugar, - MatchSource::ForLoopDesugar => hir::MatchSource::ForLoopDesugar, - } -} - pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureClause) -> hir::CaptureClause { match c { CaptureByValue => hir::CaptureByValue, diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index 9c030d8892a..6eee6872be2 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -366,7 +366,7 @@ impl EarlyLintPass for UnusedParens { 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::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), diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index f62148c16fa..2ab4e6b9299 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -135,8 +135,7 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec, externs: Externs, let krate = driver::assign_node_ids(&sess, krate); // Lower ast -> hir. - let foo = &42; - let lcx = LoweringContext::new(foo, &sess, &krate); + let lcx = LoweringContext::new(&sess, &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); diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index dec2ed789e0..0dafc89a798 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -83,8 +83,7 @@ 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 foo = &42; - let lcx = LoweringContext::new(foo, &sess, &krate); + let lcx = LoweringContext::new(&sess, &krate); let krate = lower_crate(&lcx, &krate); let opts = scrape_test_config(&krate); diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 02cd648b6d8..34b99ab8cce 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -855,9 +855,8 @@ pub enum Expr_ { /// /// `'label: loop { block }` ExprLoop(P, Option), - /// 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, Vec, MatchSource), + /// A `match` block. + ExprMatch(P, Vec), /// A closure (for example, `move |a, b, c| {a + b + c}`) ExprClosure(CaptureClause, P, P), /// A block (`{ ... }`) @@ -936,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, diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index aa4dd1d53c5..a73fd4534c9 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -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()), } } } diff --git a/src/libsyntax/config.rs b/src/libsyntax/config.rs index 889a0d7e440..2d266be3242 100644 --- a/src/libsyntax/config.rs +++ b/src/libsyntax/config.rs @@ -225,10 +225,10 @@ fn fold_expr(cx: &mut Context, expr: P) -> P 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 }, diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 6b4a5538501..2a8cdf138b0 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -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 { diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index aaaca8bd4d8..a3df7727598 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -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() { diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index a20080dcbf0..efea85f9162 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -868,7 +868,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } fn expr_match(&self, span: Span, arg: P, arms: Vec) -> P { - 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, diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 914b08265fe..3c1aa992a3c 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -1256,10 +1256,9 @@ pub fn noop_fold_expr(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, diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index f47dfeb1d34..443cea696b6 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -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 { diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 405fd9b8cc7..f5f3907a4e6 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -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")); diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 67e4927a52f..091580b9bd8 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -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); } From 3d81f785441799edfbd005304a7ff56089a258c6 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Wed, 30 Sep 2015 18:23:52 +1300 Subject: [PATCH 12/15] Add a comment --- src/librustc_front/lowering.rs | 51 +++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index 546b298a92b..c2fbcf31596 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -8,7 +8,52 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Lowers the AST to the HIR +// Lowers the AST to the HIR. +// +// Since the AST and HIR are fairly similar, this is mostly a simple procedure, +// much like a fold. Where lowering involves a bit more work things get more +// interesting and there are some invariants you should know about. These mostly +// concern spans and ids. +// +// Spans are assigned to AST nodes during parsing and then are modified during +// expansion to indicate the origin of a node and the process it went through +// being expanded. Ids are assigned to AST nodes just before lowering. +// +// For the simpler lowering steps, ids and spans should be preserved. Unlike +// expansion we do not preserve the process of lowering in the spans, so spans +// should not be modified here. When creating a new node (as opposed to +// 'folding' an existing one), then you create a new id using `next_id()`. +// +// You must ensure that ids are unique. That means that you should only use the +// is from an AST node in a single HIR node (you can assume that AST node ids +// are unique). Every new node must have a unique id. Avoid cloning HIR nodes. +// If you do, you must then set one of the node's id to a fresh one. +// +// Lowering must be reproducable (the compiler only lowers once, but tools and +// custom lints may lower an AST node to a HIR node to interact with the +// compiler). The only interesting bit of this is ids - if you lower an AST node +// and create new HIR nodes with fresh ids, when re-lowering the same node, you +// must ensure you get the same ids! To do this, we keep track of the next id +// when we translate a node which requires new ids. By checking this cache and +// using node ids starting with the cached id, we ensure ids are reproducible. +// To use this system, you just need to hold on to a CachedIdSetter object +// whilst lowering. This is an RAII object that takes care of setting and +// restoring the cached id, etc. +// +// This whole system relies on node ids being incremented one at a time and +// all increments being for lowering. This means that you should not call any +// non-lowering function which will use new node ids. +// +// Spans are used for error messages and for tools to map semantics back to +// source code. It is therefore not as important with spans as ids to be strict +// about use (you can't break the compiler by screwing up a span). Obviously, a +// HIR node can only have a single span. But multiple nodes can have the same +// span and spans don't need to be kept in order, etc. Where code is preserved +// by lowering, it should have the same span as in the AST. Where HIR nodes are +// new it is probably best to give a span for the whole AST node being lowered. +// All nodes should have real spans, don't use dummy spans. Tools are likely to +// get confused if the spans from leaf AST nodes occur in multiple places +// in the HIR, especially for multiple identifiers. use hir; @@ -25,8 +70,12 @@ use std::cell::{Cell, RefCell}; pub struct LoweringContext<'a> { crate_root: Option<&'static str>, + // Map AST ids to ids used for expanded nodes. id_cache: RefCell>, + // Use if there are no cached ids for the current node. id_assigner: &'a NodeIdAssigner, + // 0 == no cached id. Must be incremented to align with previous id + // incrementing. cached_id: Cell, } From 2b4f28e531b7fa9ad6dd3cd14cd953a7bbf8b326 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Tue, 6 Oct 2015 15:31:43 +1300 Subject: [PATCH 13/15] Misc fixups --- src/librustc/middle/astencode.rs | 37 ++++++++++++++++++---- src/librustc_driver/driver.rs | 2 +- src/librustc_driver/pretty.rs | 2 +- src/librustc_driver/test.rs | 7 ++-- src/librustc_front/lowering.rs | 18 ++++++----- src/librustc_typeck/coherence/mod.rs | 1 - src/librustdoc/core.rs | 2 +- src/librustdoc/test.rs | 2 +- src/test/run-make/execution-engine/test.rs | 9 +++--- 9 files changed, 54 insertions(+), 26 deletions(-) diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 985a517d8d9..dd96ea0460b 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -54,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>, @@ -1374,6 +1375,22 @@ impl FakeExtCtxt for parse::ParseSess { fn parse_sess(&self) -> &parse::ParseSess { self } } +#[cfg(test)] +struct FakeNodeIdAssigner; + +#[cfg(test)] +// It should go without sayingt 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() @@ -1392,7 +1409,9 @@ fn roundtrip(in_item: P) { #[test] fn test_basic() { let cx = mk_ctxt(); - roundtrip(lower_item("e_item!(&cx, + let fnia = FakeNodeIdAssigner; + let lcx = LoweringContext::new(&fnia, None); + roundtrip(lower_item(&lcx, "e_item!(&cx, fn foo() {} ).unwrap())); } @@ -1400,7 +1419,9 @@ fn test_basic() { #[test] fn test_smalltalk() { let cx = mk_ctxt(); - roundtrip(lower_item("e_item!(&cx, + let fnia = FakeNodeIdAssigner; + let lcx = LoweringContext::new(&fnia, None); + roundtrip(lower_item(&lcx, "e_item!(&cx, fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed. ).unwrap())); } @@ -1408,7 +1429,9 @@ fn test_smalltalk() { #[test] fn test_more() { let cx = mk_ctxt(); - roundtrip(lower_item("e_item!(&cx, + let fnia = FakeNodeIdAssigner; + let lcx = LoweringContext::new(&fnia, None); + roundtrip(lower_item(&lcx, "e_item!(&cx, fn foo(x: usize, y: usize) -> usize { let z = x + y; return z; @@ -1425,10 +1448,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("e_item!(&cx, + let item_exp = InlinedItem::Item(lower_item(&lcx, "e_item!(&cx, fn new_int_alist() -> alist { return alist {eq_fn: eq_int, data: Vec::new()}; } diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index 3db484ef930..619fcd3406c 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -112,7 +112,7 @@ pub fn compile_input(sess: Session, let expanded_crate = assign_node_ids(&sess, expanded_crate); // Lower ast -> hir. - let lcx = LoweringContext::new(&sess, &expanded_crate); + 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(&lcx, &expanded_crate))); diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 73961c8d757..4e198a44b94 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -670,7 +670,7 @@ 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, &krate); + 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(&lcx, &krate)); diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index dc550bb698f..0c83851ba00 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -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(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(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, diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index c2fbcf31596..244d59887d7 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -80,14 +80,16 @@ pub struct LoweringContext<'a> { } impl<'a, 'hir> LoweringContext<'a> { - pub fn new(id_assigner: &'a NodeIdAssigner, c: &Crate) -> LoweringContext<'a> { - let crate_root = if std_inject::no_core(c) { - None - } else if std_inject::no_std(c) { - Some("core") - } else { - Some("std") - }; + pub fn new(id_assigner: &'a NodeIdAssigner, c: Option<&Crate>) -> LoweringContext<'a> { + let crate_root = c.and_then(|c| { + if std_inject::no_core(c) { + None + } else if std_inject::no_std(c) { + Some("core") + } else { + Some("std") + } + }); LoweringContext { crate_root: crate_root, diff --git a/src/librustc_typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs index 5afcdbc8c13..b3ec10a8941 100644 --- a/src/librustc_typeck/coherence/mod.rs +++ b/src/librustc_typeck/coherence/mod.rs @@ -38,7 +38,6 @@ use std::cell::RefCell; use std::rc::Rc; use syntax::codemap::Span; use syntax::parse::token; -use syntax::ast::NodeIdAssigner; use util::nodemap::{DefIdMap, FnvHashMap}; use rustc::front::map as hir_map; use rustc::front::map::NodeItem; diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 2ab4e6b9299..776917d6724 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -135,7 +135,7 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec, externs: Externs, let krate = driver::assign_node_ids(&sess, krate); // Lower ast -> hir. - let lcx = LoweringContext::new(&sess, &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); diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 0dafc89a798..87e1d8a0392 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -83,7 +83,7 @@ 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 lcx = LoweringContext::new(&sess, &krate); + let lcx = LoweringContext::new(&sess, Some(&krate)); let krate = lower_crate(&lcx, &krate); let opts = scrape_test_config(&krate); diff --git a/src/test/run-make/execution-engine/test.rs b/src/test/run-make/execution-engine/test.rs index 6fc12d3a750..bad0afe79d6 100644 --- a/src/test/run-make/execution-engine/test.rs +++ b/src/test/run-make/execution-engine/test.rs @@ -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() { From 87b0cf4541c319b6626c5583bfbeed6ece7306c1 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Tue, 6 Oct 2015 16:03:56 +1300 Subject: [PATCH 14/15] rustfmt'ing --- src/librustc_front/lowering.rs | 1216 +++++++++++++++++--------------- 1 file changed, 661 insertions(+), 555 deletions(-) diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index 244d59887d7..681fc6144f3 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -121,24 +121,26 @@ pub fn lower_view_path(_lctx: &LoweringContext, view_path: &ViewPath) -> P { hir::ViewPathList(lower_path(_lctx, path), - path_list_idents.iter().map(|path_list_ident| { - Spanned { - node: match path_list_ident.node { - PathListIdent { id, name, rename } => - hir::PathListIdent { - id: id, - name: name.name, - rename: rename.map(|x| x.name), - }, - PathListMod { id, rename } => - hir::PathListMod { - id: id, - rename: rename.map(|x| x.name) - } - }, - span: path_list_ident.span - } - }).collect()) + path_list_idents.iter() + .map(|path_list_ident| { + Spanned { + node: match path_list_ident.node { + PathListIdent { id, name, rename } => + hir::PathListIdent { + id: id, + name: name.name, + rename: rename.map(|x| x.name), + }, + PathListMod { id, rename } => + hir::PathListMod { + id: id, + rename: rename.map(|x| x.name), + }, + }, + span: path_list_ident.span, + } + }) + .collect()) } }, span: view_path.span, @@ -158,17 +160,22 @@ pub fn lower_decl(_lctx: &LoweringContext, d: &Decl) -> P { match d.node { DeclLocal(ref l) => P(Spanned { node: hir::DeclLocal(lower_local(_lctx, l)), - span: d.span + span: d.span, }), DeclItem(ref it) => P(Spanned { node: hir::DeclItem(lower_item(_lctx, it)), - span: d.span + span: d.span, }), } } pub fn lower_ty_binding(_lctx: &LoweringContext, b: &TypeBinding) -> P { - P(hir::TypeBinding { id: b.id, name: b.ident.name, ty: lower_ty(_lctx, &b.ty), span: b.span }) + P(hir::TypeBinding { + id: b.id, + name: b.ident.name, + ty: lower_ty(_lctx, &b.ty), + span: b.span, + }) } pub fn lower_ty(_lctx: &LoweringContext, t: &Ty) -> P { @@ -179,7 +186,8 @@ pub fn lower_ty(_lctx: &LoweringContext, t: &Ty) -> P { TyVec(ref ty) => hir::TyVec(lower_ty(_lctx, ty)), TyPtr(ref mt) => hir::TyPtr(lower_mt(_lctx, mt)), TyRptr(ref region, ref mt) => { - hir::TyRptr(lower_opt_lifetime(_lctx, region), lower_mt(_lctx, mt)) + hir::TyRptr(lower_opt_lifetime(_lctx, region), + lower_mt(_lctx, mt)) } TyBareFn(ref f) => { hir::TyBareFn(P(hir::BareFnTy { @@ -201,8 +209,7 @@ pub fn lower_ty(_lctx: &LoweringContext, t: &Ty) -> P { hir::TyPath(qself, lower_path(_lctx, path)) } TyObjectSum(ref ty, ref bounds) => { - hir::TyObjectSum(lower_ty(_lctx, ty), - lower_bounds(_lctx, bounds)) + hir::TyObjectSum(lower_ty(_lctx, ty), lower_bounds(_lctx, bounds)) } TyFixedLengthVec(ref ty, ref e) => { hir::TyFixedLengthVec(lower_ty(_lctx, ty), lower_expr(_lctx, e)) @@ -234,8 +241,9 @@ pub fn lower_variant(_lctx: &LoweringContext, v: &Variant) -> P { attrs: v.node.attrs.clone(), kind: match v.node.kind { TupleVariantKind(ref variant_args) => { - hir::TupleVariantKind(variant_args.iter().map(|ref x| - lower_variant_arg(_lctx, x)).collect()) + hir::TupleVariantKind(variant_args.iter() + .map(|ref x| lower_variant_arg(_lctx, x)) + .collect()) } StructVariantKind(ref struct_def) => { hir::StructVariantKind(lower_struct_def(_lctx, struct_def)) @@ -250,11 +258,15 @@ pub fn lower_variant(_lctx: &LoweringContext, v: &Variant) -> P { pub fn lower_path(_lctx: &LoweringContext, p: &Path) -> hir::Path { hir::Path { global: p.global, - segments: p.segments.iter().map(|&PathSegment {identifier, ref parameters}| - hir::PathSegment { - identifier: identifier, - parameters: lower_path_parameters(_lctx, parameters), - }).collect(), + segments: p.segments + .iter() + .map(|&PathSegment { identifier, ref parameters }| { + hir::PathSegment { + identifier: identifier, + parameters: lower_path_parameters(_lctx, parameters), + } + }) + .collect(), span: p.span, } } @@ -294,12 +306,12 @@ pub fn lower_parenthesized_parameter_data(_lctx: &LoweringContext, pub fn lower_local(_lctx: &LoweringContext, l: &Local) -> P { P(hir::Local { - id: l.id, - ty: l.ty.as_ref().map(|t| lower_ty(_lctx, t)), - pat: lower_pat(_lctx, &l.pat), - init: l.init.as_ref().map(|e| lower_expr(_lctx, e)), - span: l.span, - }) + id: l.id, + ty: l.ty.as_ref().map(|t| lower_ty(_lctx, t)), + pat: lower_pat(_lctx, &l.pat), + init: l.init.as_ref().map(|e| lower_expr(_lctx, e)), + span: l.span, + }) } pub fn lower_explicit_self_underscore(_lctx: &LoweringContext, @@ -327,11 +339,18 @@ pub fn lower_mutability(_lctx: &LoweringContext, m: Mutability) -> hir::Mutabili } pub fn lower_explicit_self(_lctx: &LoweringContext, s: &ExplicitSelf) -> hir::ExplicitSelf { - Spanned { node: lower_explicit_self_underscore(_lctx, &s.node), span: s.span } + Spanned { + node: lower_explicit_self_underscore(_lctx, &s.node), + span: s.span, + } } pub fn lower_arg(_lctx: &LoweringContext, arg: &Arg) -> hir::Arg { - hir::Arg { id: arg.id, pat: lower_pat(_lctx, &arg.pat), ty: lower_ty(_lctx, &arg.ty) } + hir::Arg { + id: arg.id, + pat: lower_pat(_lctx, &arg.pat), + ty: lower_ty(_lctx, &arg.ty), + } } pub fn lower_fn_decl(_lctx: &LoweringContext, decl: &FnDecl) -> P { @@ -375,13 +394,17 @@ pub fn lower_ty_params(_lctx: &LoweringContext, } pub fn lower_lifetime(_lctx: &LoweringContext, l: &Lifetime) -> hir::Lifetime { - hir::Lifetime { id: l.id, name: l.name, span: l.span } + hir::Lifetime { + id: l.id, + name: l.name, + span: l.span, + } } pub fn lower_lifetime_def(_lctx: &LoweringContext, l: &LifetimeDef) -> hir::LifetimeDef { hir::LifetimeDef { lifetime: lower_lifetime(_lctx, &l.lifetime), - bounds: lower_lifetimes(_lctx, &l.bounds) + bounds: lower_lifetimes(_lctx, &l.bounds), } } @@ -412,8 +435,10 @@ pub fn lower_generics(_lctx: &LoweringContext, g: &Generics) -> hir::Generics { pub fn lower_where_clause(_lctx: &LoweringContext, wc: &WhereClause) -> hir::WhereClause { hir::WhereClause { id: wc.id, - predicates: wc.predicates.iter().map(|predicate| - lower_where_predicate(_lctx, predicate)).collect(), + predicates: wc.predicates + .iter() + .map(|predicate| lower_where_predicate(_lctx, predicate)) + .collect(), } } @@ -429,7 +454,7 @@ pub fn lower_where_predicate(_lctx: &LoweringContext, bound_lifetimes: lower_lifetime_defs(_lctx, bound_lifetimes), bounded_ty: lower_ty(_lctx, bounded_ty), bounds: bounds.iter().map(|x| lower_ty_param_bound(_lctx, x)).collect(), - span: span + span: span, }) } WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime, @@ -438,7 +463,7 @@ pub fn lower_where_predicate(_lctx: &LoweringContext, hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate { span: span, lifetime: lower_lifetime(_lctx, lifetime), - bounds: bounds.iter().map(|bound| lower_lifetime(_lctx, bound)).collect() + bounds: bounds.iter().map(|bound| lower_lifetime(_lctx, bound)).collect(), }) } WherePredicate::EqPredicate(WhereEqPredicate{ id, @@ -448,8 +473,8 @@ pub fn lower_where_predicate(_lctx: &LoweringContext, hir::WherePredicate::EqPredicate(hir::WhereEqPredicate { id: id, path: lower_path(_lctx, path), - ty:lower_ty(_lctx, ty), - span: span + ty: lower_ty(_lctx, ty), + span: span, }) } } @@ -463,7 +488,10 @@ pub fn lower_struct_def(_lctx: &LoweringContext, sd: &StructDef) -> P hir::TraitRef { - hir::TraitRef { path: lower_path(_lctx, &p.path), ref_id: p.ref_id } + hir::TraitRef { + path: lower_path(_lctx, &p.path), + ref_id: p.ref_id, + } } pub fn lower_poly_trait_ref(_lctx: &LoweringContext, p: &PolyTraitRef) -> hir::PolyTraitRef { @@ -489,15 +517,20 @@ pub fn lower_struct_field(_lctx: &LoweringContext, f: &StructField) -> hir::Stru pub fn lower_field(_lctx: &LoweringContext, f: &Field) -> hir::Field { hir::Field { name: respan(f.ident.span, f.ident.node.name), - expr: lower_expr(_lctx, &f.expr), span: f.span + expr: lower_expr(_lctx, &f.expr), + span: f.span, } } pub fn lower_mt(_lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy { - hir::MutTy { ty: lower_ty(_lctx, &mt.ty), mutbl: lower_mutability(_lctx, mt.mutbl) } + hir::MutTy { + ty: lower_ty(_lctx, &mt.ty), + mutbl: lower_mutability(_lctx, mt.mutbl), + } } -pub fn lower_opt_bounds(_lctx: &LoweringContext, b: &Option>) +pub fn lower_opt_bounds(_lctx: &LoweringContext, + b: &Option>) -> Option> { b.as_ref().map(|ref bounds| lower_bounds(_lctx, bounds)) } @@ -507,7 +540,10 @@ fn lower_bounds(_lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParam } fn lower_variant_arg(_lctx: &LoweringContext, va: &VariantArg) -> hir::VariantArg { - hir::VariantArg { id: va.id, ty: lower_ty(_lctx, &va.ty) } + hir::VariantArg { + id: va.id, + ty: lower_ty(_lctx, &va.ty), + } } pub fn lower_block(_lctx: &LoweringContext, b: &Block) -> P { @@ -527,20 +563,20 @@ pub fn lower_item_underscore(_lctx: &LoweringContext, i: &Item_) -> hir::Item_ { hir::ItemUse(lower_view_path(_lctx, view_path)) } ItemStatic(ref t, m, ref e) => { - hir::ItemStatic(lower_ty(_lctx, t), lower_mutability(_lctx, m), lower_expr(_lctx, e)) + hir::ItemStatic(lower_ty(_lctx, t), + lower_mutability(_lctx, m), + lower_expr(_lctx, e)) } ItemConst(ref t, ref e) => { hir::ItemConst(lower_ty(_lctx, t), lower_expr(_lctx, e)) } ItemFn(ref decl, unsafety, constness, abi, ref generics, ref body) => { - hir::ItemFn( - lower_fn_decl(_lctx, decl), - lower_unsafety(_lctx, unsafety), - lower_constness(_lctx, constness), - abi, - lower_generics(_lctx, generics), - lower_block(_lctx, body) - ) + hir::ItemFn(lower_fn_decl(_lctx, decl), + lower_unsafety(_lctx, unsafety), + lower_constness(_lctx, constness), + abi, + lower_generics(_lctx, generics), + lower_block(_lctx, body)) } ItemMod(ref m) => hir::ItemMod(lower_mod(_lctx, m)), ItemForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(_lctx, nm)), @@ -548,24 +584,26 @@ pub fn lower_item_underscore(_lctx: &LoweringContext, i: &Item_) -> hir::Item_ { hir::ItemTy(lower_ty(_lctx, t), lower_generics(_lctx, generics)) } ItemEnum(ref enum_definition, ref generics) => { - hir::ItemEnum( - hir::EnumDef { - variants: enum_definition.variants.iter().map(|x| { - lower_variant(_lctx, x) - }).collect(), - }, - lower_generics(_lctx, generics)) + hir::ItemEnum(hir::EnumDef { + variants: enum_definition.variants + .iter() + .map(|x| lower_variant(_lctx, x)) + .collect(), + }, + lower_generics(_lctx, generics)) } ItemStruct(ref struct_def, ref generics) => { let struct_def = lower_struct_def(_lctx, struct_def); hir::ItemStruct(struct_def, lower_generics(_lctx, generics)) } ItemDefaultImpl(unsafety, ref trait_ref) => { - hir::ItemDefaultImpl(lower_unsafety(_lctx, unsafety), lower_trait_ref(_lctx, trait_ref)) + hir::ItemDefaultImpl(lower_unsafety(_lctx, unsafety), + lower_trait_ref(_lctx, trait_ref)) } ItemImpl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => { - let new_impl_items = - impl_items.iter().map(|item| lower_impl_item(_lctx, item)).collect(); + let new_impl_items = impl_items.iter() + .map(|item| lower_impl_item(_lctx, item)) + .collect(); let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(_lctx, trait_ref)); hir::ItemImpl(lower_unsafety(_lctx, unsafety), lower_impl_polarity(_lctx, polarity), @@ -611,11 +649,11 @@ pub fn lower_trait_item(_lctx: &LoweringContext, i: &TraitItem) -> P P { P(hir::ImplItem { - id: i.id, - name: i.ident.name, - attrs: i.attrs.clone(), - vis: lower_visibility(_lctx, i.vis), - node: match i.node { + id: i.id, + name: i.ident.name, + attrs: i.attrs.clone(), + vis: lower_visibility(_lctx, i.vis), + node: match i.node { ConstImplItem(ref ty, ref expr) => { hir::ConstImplItem(lower_ty(_lctx, ty), lower_expr(_lctx, expr)) } @@ -631,7 +669,10 @@ pub fn lower_impl_item(_lctx: &LoweringContext, i: &ImplItem) -> P hir::Mod { - hir::Mod { inner: m.inner, items: m.items.iter().map(|x| lower_item(_lctx, x)).collect() } + hir::Mod { + inner: m.inner, + items: m.items.iter().map(|x| lower_item(_lctx, x)).collect(), + } } pub fn lower_crate(_lctx: &LoweringContext, c: &Crate) -> hir::Crate { @@ -684,15 +725,16 @@ pub fn lower_foreign_item(_lctx: &LoweringContext, i: &ForeignItem) -> P { - hir::ForeignItemFn(lower_fn_decl(_lctx, fdec), lower_generics(_lctx, generics)) + hir::ForeignItemFn(lower_fn_decl(_lctx, fdec), + lower_generics(_lctx, generics)) } ForeignItemStatic(ref t, m) => { hir::ForeignItemStatic(lower_ty(_lctx, t), m) } }, - vis: lower_visibility(_lctx, i.vis), - span: i.span, - }) + vis: lower_visibility(_lctx, i.vis), + span: i.span, + }) } pub fn lower_method_sig(_lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig { @@ -756,13 +798,13 @@ pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp { pub fn lower_pat(_lctx: &LoweringContext, p: &Pat) -> P { P(hir::Pat { - id: p.id, - node: match p.node { + id: p.id, + node: match p.node { PatWild(k) => hir::PatWild(lower_pat_wild_kind(_lctx, k)), PatIdent(ref binding_mode, pth1, ref sub) => { hir::PatIdent(lower_binding_mode(_lctx, binding_mode), - pth1, - sub.as_ref().map(|x| lower_pat(_lctx, x))) + pth1, + sub.as_ref().map(|x| lower_pat(_lctx, x))) } PatLit(ref e) => hir::PatLit(lower_expr(_lctx, e)), PatEnum(ref pth, ref pats) => { @@ -779,14 +821,18 @@ pub fn lower_pat(_lctx: &LoweringContext, p: &Pat) -> P { } PatStruct(ref pth, ref fields, etc) => { let pth = lower_path(_lctx, pth); - let fs = fields.iter().map(|f| { - Spanned { span: f.span, - node: hir::FieldPat { - name: f.node.ident.name, - pat: lower_pat(_lctx, &f.node.pat), - is_shorthand: f.node.is_shorthand, - }} - }).collect(); + let fs = fields.iter() + .map(|f| { + Spanned { + span: f.span, + node: hir::FieldPat { + name: f.node.ident.name, + pat: lower_pat(_lctx, &f.node.pat), + is_shorthand: f.node.is_shorthand, + }, + } + }) + .collect(); hir::PatStruct(pth, fs, etc) } PatTup(ref elts) => hir::PatTup(elts.iter().map(|x| lower_pat(_lctx, x)).collect()), @@ -795,11 +841,11 @@ pub fn lower_pat(_lctx: &LoweringContext, p: &Pat) -> P { lower_mutability(_lctx, mutbl)), PatRange(ref e1, ref e2) => { hir::PatRange(lower_expr(_lctx, e1), lower_expr(_lctx, e2)) - }, + } PatVec(ref before, ref slice, ref after) => { hir::PatVec(before.iter().map(|x| lower_pat(_lctx, x)).collect(), - slice.as_ref().map(|x| lower_pat(_lctx, x)), - after.iter().map(|x| lower_pat(_lctx, x)).collect()) + slice.as_ref().map(|x| lower_pat(_lctx, x)), + after.iter().map(|x| lower_pat(_lctx, x)).collect()) } PatMac(_) => panic!("Shouldn't exist here"), }, @@ -852,160 +898,161 @@ impl<'a> Drop for CachedIdSetter<'a> { pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { P(hir::Expr { - id: e.id, - node: match e.node { - // Issue #22181: - // Eventually a desugaring for `box EXPR` - // (similar to the desugaring above for `in PLACE BLOCK`) - // should go here, desugaring - // + id: e.id, + node: match e.node { + // 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. + ExprBox(ref e) => { + hir::ExprBox(lower_expr(lctx, e)) + } + + // Desugar ExprBox: `in (PLACE) EXPR` + ExprInPlace(ref placer, ref value_expr) => { // to: // - // let mut place = BoxPlace::make_place(); + // let p = PLACE; + // let mut place = Placer::make_place(p); // 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. - ExprBox(ref e) => { - hir::ExprBox(lower_expr(lctx, e)) - } + // push_unsafe!({ + // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR )); + // InPlace::finalize(place) + // }) + let _old_cached = CachedIdSetter::new(lctx, e.id); - // Desugar ExprBox: `in (PLACE) EXPR` - ExprInPlace(ref placer, ref 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) - // }) - let _old_cached = CachedIdSetter::new(lctx, e.id); + let placer_expr = lower_expr(lctx, placer); + let value_expr = lower_expr(lctx, value_expr); - let placer_expr = lower_expr(lctx, placer); - let value_expr = lower_expr(lctx, 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_ident = token::gensym_ident("placer"); - let agent_ident = token::gensym_ident("place"); - let p_ptr_ident = token::gensym_ident("p_ptr"); + 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_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 = |lctx, p, args| { + let path = core_path(lctx, e.span, p); + let path = expr_path(lctx, path); + expr_call(lctx, e.span, path, args) + }; - let make_call = |lctx, p, args| { - let path = core_path(lctx, e.span, p); - let path = expr_path(lctx, path); - expr_call(lctx, e.span, path, args) - }; + let mk_stmt_let = |lctx, bind, expr| stmt_let(lctx, e.span, false, bind, expr); + let mk_stmt_let_mut = |lctx, bind, expr| stmt_let(lctx, e.span, true, bind, expr); - let mk_stmt_let = |lctx, bind, expr| { - stmt_let(lctx, e.span, false, bind, expr) - }; - let mk_stmt_let_mut = |lctx, bind, expr| { - stmt_let(lctx, e.span, true, bind, expr) - }; + // let placer = ; + let s1 = mk_stmt_let(lctx, placer_ident, placer_expr); - // let placer = ; - let s1 = mk_stmt_let(lctx, placer_ident, placer_expr); + // let mut place = Placer::make_place(placer); + let s2 = { + let call = make_call(lctx, + &make_place, + vec![expr_ident(lctx, e.span, placer_ident)]); + mk_stmt_let_mut(lctx, agent_ident, call) + }; - // let mut place = Placer::make_place(placer); - let s2 = { - let call = make_call(lctx, &make_place, vec![expr_ident(lctx, e.span, placer_ident)]); - mk_stmt_let_mut(lctx, agent_ident, call) - }; + // let p_ptr = Place::pointer(&mut place); + let s3 = { + let args = vec![expr_mut_addr_of(lctx, + e.span, + expr_ident(lctx, e.span, agent_ident))]; + let call = make_call(lctx, &place_pointer, args); + mk_stmt_let(lctx, p_ptr_ident, call) + }; - // let p_ptr = Place::pointer(&mut place); - let s3 = { - let args = vec![expr_mut_addr_of(lctx, e.span, expr_ident(lctx, e.span, agent_ident))]; - let call = make_call(lctx, &place_pointer, args); - mk_stmt_let(lctx, p_ptr_ident, call) - }; + // pop_unsafe!(EXPR)); + let pop_unsafe_expr = + signal_block_expr(lctx, + vec![], + signal_block_expr(lctx, + vec![], + value_expr, + e.span, + hir::PopUnstableBlock), + e.span, + hir::PopUnsafeBlock(hir::CompilerGenerated)); - // pop_unsafe!(EXPR)); - let pop_unsafe_expr = - signal_block_expr(lctx, - vec![], - signal_block_expr(lctx, - vec![], - value_expr, - e.span, - hir::PopUnstableBlock), - e.span, - hir::PopUnsafeBlock(hir::CompilerGenerated)); - - // push_unsafe!({ - // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR )); - // InPlace::finalize(place) - // }) - let expr = { - let call_move_val_init = - hir::StmtSemi(make_call(lctx, + // push_unsafe!({ + // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR )); + // InPlace::finalize(place) + // }) + let expr = { + let call_move_val_init = hir::StmtSemi(make_call(lctx, &move_val_init, vec![expr_ident(lctx, e.span, p_ptr_ident), pop_unsafe_expr]), - lctx.next_id()); - let call_move_val_init = respan(e.span, call_move_val_init); + lctx.next_id()); + let call_move_val_init = respan(e.span, call_move_val_init); - let call = make_call(lctx, &inplace_finalize, vec![expr_ident(lctx, e.span, agent_ident)]); - signal_block_expr(lctx, - vec![P(call_move_val_init)], - call, - e.span, - hir::PushUnsafeBlock(hir::CompilerGenerated)) - }; + let call = make_call(lctx, + &inplace_finalize, + vec![expr_ident(lctx, e.span, agent_ident)]); + signal_block_expr(lctx, + vec![P(call_move_val_init)], + call, + e.span, + hir::PushUnsafeBlock(hir::CompilerGenerated)) + }; - return signal_block_expr(lctx, - vec![s1, s2, s3], - expr, - e.span, - hir::PushUnstableBlock); - } - - ExprVec(ref exprs) => { - hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect()) - } - ExprRepeat(ref expr, ref count) => { - hir::ExprRepeat(lower_expr(lctx, expr), lower_expr(lctx, count)) - } - ExprTup(ref elts) => { - hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect()) - } - ExprCall(ref f, ref args) => { - hir::ExprCall(lower_expr(lctx, f), - args.iter().map(|x| lower_expr(lctx, x)).collect()) - } - ExprMethodCall(i, ref tps, ref args) => { - hir::ExprMethodCall( - respan(i.span, i.node.name), - tps.iter().map(|x| lower_ty(lctx, x)).collect(), - args.iter().map(|x| lower_expr(lctx, x)).collect()) - } - ExprBinary(binop, ref lhs, ref rhs) => { - hir::ExprBinary(lower_binop(lctx, binop), - lower_expr(lctx, lhs), - lower_expr(lctx, rhs)) - } - ExprUnary(op, ref ohs) => { - hir::ExprUnary(lower_unop(lctx, op), lower_expr(lctx, ohs)) - } - ExprLit(ref l) => hir::ExprLit(P((**l).clone())), - ExprCast(ref expr, ref ty) => { - hir::ExprCast(lower_expr(lctx, expr), lower_ty(lctx, ty)) - } - ExprAddrOf(m, ref ohs) => { - hir::ExprAddrOf(lower_mutability(lctx, m), lower_expr(lctx, ohs)) - } - // More complicated than you might expect because the else branch - // might be `if let`. - ExprIf(ref cond, ref blk, ref else_opt) => { - let else_opt = else_opt.as_ref().map(|els| match els.node { + return signal_block_expr(lctx, + vec![s1, s2, s3], + expr, + e.span, + hir::PushUnstableBlock); + } + + ExprVec(ref exprs) => { + hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect()) + } + ExprRepeat(ref expr, ref count) => { + hir::ExprRepeat(lower_expr(lctx, expr), lower_expr(lctx, count)) + } + ExprTup(ref elts) => { + hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect()) + } + ExprCall(ref f, ref args) => { + hir::ExprCall(lower_expr(lctx, f), + args.iter().map(|x| lower_expr(lctx, x)).collect()) + } + ExprMethodCall(i, ref tps, ref args) => { + hir::ExprMethodCall(respan(i.span, i.node.name), + tps.iter().map(|x| lower_ty(lctx, x)).collect(), + args.iter().map(|x| lower_expr(lctx, x)).collect()) + } + ExprBinary(binop, ref lhs, ref rhs) => { + hir::ExprBinary(lower_binop(lctx, binop), + lower_expr(lctx, lhs), + lower_expr(lctx, rhs)) + } + ExprUnary(op, ref ohs) => { + hir::ExprUnary(lower_unop(lctx, op), lower_expr(lctx, ohs)) + } + ExprLit(ref l) => hir::ExprLit(P((**l).clone())), + ExprCast(ref expr, ref ty) => { + hir::ExprCast(lower_expr(lctx, expr), lower_ty(lctx, ty)) + } + ExprAddrOf(m, ref ohs) => { + hir::ExprAddrOf(lower_mutability(lctx, m), lower_expr(lctx, ohs)) + } + // More complicated than you might expect because the else branch + // might be `if let`. + ExprIf(ref cond, ref blk, ref else_opt) => { + let else_opt = else_opt.as_ref().map(|els| { + match els.node { ExprIfLet(..) => { let _old_cached = CachedIdSetter::new(lctx, e.id); // wrap the if-let expr in a block @@ -1015,71 +1062,72 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { expr: Some(lower_expr(lctx, els)), id: lctx.next_id(), rules: hir::DefaultBlock, - span: span + span: span, }); expr_block(lctx, blk) } - _ => lower_expr(lctx, els) - }); + _ => lower_expr(lctx, els), + } + }); - hir::ExprIf(lower_expr(lctx, cond), - lower_block(lctx, blk), - else_opt) - } - ExprWhile(ref cond, ref body, opt_ident) => { - hir::ExprWhile(lower_expr(lctx, cond), - lower_block(lctx, body), - opt_ident) - } - ExprLoop(ref body, opt_ident) => { - hir::ExprLoop(lower_block(lctx, body), - opt_ident) - } - ExprMatch(ref expr, ref arms) => { - hir::ExprMatch(lower_expr(lctx, expr), - arms.iter().map(|x| lower_arm(lctx, x)).collect(), - hir::MatchSource::Normal) - } - ExprClosure(capture_clause, ref decl, ref body) => { - hir::ExprClosure(lower_capture_clause(lctx, capture_clause), - lower_fn_decl(lctx, decl), - lower_block(lctx, body)) - } - ExprBlock(ref blk) => hir::ExprBlock(lower_block(lctx, blk)), - ExprAssign(ref el, ref er) => { - hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er)) - } - ExprAssignOp(op, ref el, ref er) => { - hir::ExprAssignOp(lower_binop(lctx, op), - lower_expr(lctx, el), - lower_expr(lctx, er)) - } - ExprField(ref el, ident) => { - hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name)) - } - ExprTupField(ref el, ident) => { - hir::ExprTupField(lower_expr(lctx, el), ident) - } - ExprIndex(ref el, ref er) => { - hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er)) - } - ExprRange(ref e1, ref e2) => { - hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)), - e2.as_ref().map(|x| lower_expr(lctx, x))) - } - ExprPath(ref qself, ref path) => { - let qself = qself.as_ref().map(|&QSelf { ref ty, position }| { - hir::QSelf { - ty: lower_ty(lctx, ty), - position: position - } - }); - hir::ExprPath(qself, lower_path(lctx, path)) - } - ExprBreak(opt_ident) => hir::ExprBreak(opt_ident), - ExprAgain(opt_ident) => hir::ExprAgain(opt_ident), - ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))), - ExprInlineAsm(InlineAsm { + hir::ExprIf(lower_expr(lctx, cond), + lower_block(lctx, blk), + else_opt) + } + ExprWhile(ref cond, ref body, opt_ident) => { + hir::ExprWhile(lower_expr(lctx, cond), + lower_block(lctx, body), + opt_ident) + } + ExprLoop(ref body, opt_ident) => { + hir::ExprLoop(lower_block(lctx, body), opt_ident) + } + ExprMatch(ref expr, ref arms) => { + hir::ExprMatch(lower_expr(lctx, expr), + arms.iter().map(|x| lower_arm(lctx, x)).collect(), + hir::MatchSource::Normal) + } + ExprClosure(capture_clause, ref decl, ref body) => { + hir::ExprClosure(lower_capture_clause(lctx, capture_clause), + lower_fn_decl(lctx, decl), + lower_block(lctx, body)) + } + ExprBlock(ref blk) => hir::ExprBlock(lower_block(lctx, blk)), + ExprAssign(ref el, ref er) => { + hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er)) + } + ExprAssignOp(op, ref el, ref er) => { + hir::ExprAssignOp(lower_binop(lctx, op), + lower_expr(lctx, el), + lower_expr(lctx, er)) + } + ExprField(ref el, ident) => { + hir::ExprField(lower_expr(lctx, el), + respan(ident.span, ident.node.name)) + } + ExprTupField(ref el, ident) => { + hir::ExprTupField(lower_expr(lctx, el), ident) + } + ExprIndex(ref el, ref er) => { + hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er)) + } + ExprRange(ref e1, ref e2) => { + hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)), + e2.as_ref().map(|x| lower_expr(lctx, x))) + } + ExprPath(ref qself, ref path) => { + let qself = qself.as_ref().map(|&QSelf { ref ty, position }| { + hir::QSelf { + ty: lower_ty(lctx, ty), + position: position, + } + }); + hir::ExprPath(qself, lower_path(lctx, path)) + } + ExprBreak(opt_ident) => hir::ExprBreak(opt_ident), + ExprAgain(opt_ident) => hir::ExprAgain(opt_ident), + ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))), + ExprInlineAsm(InlineAsm { ref inputs, ref outputs, ref asm, @@ -1090,251 +1138,269 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { dialect, expn_id, }) => hir::ExprInlineAsm(hir::InlineAsm { - inputs: inputs.iter().map(|&(ref c, ref input)| { - (c.clone(), lower_expr(lctx, input)) - }).collect(), - outputs: outputs.iter().map(|&(ref c, ref out, ref is_rw)| { - (c.clone(), lower_expr(lctx, out), *is_rw) - }).collect(), - asm: asm.clone(), - asm_str_style: asm_str_style, - clobbers: clobbers.clone(), - volatile: volatile, - alignstack: alignstack, - dialect: dialect, - expn_id: expn_id, - }), - ExprStruct(ref path, ref fields, ref maybe_expr) => { - hir::ExprStruct(lower_path(lctx, path), - fields.iter().map(|x| lower_field(lctx, x)).collect(), - maybe_expr.as_ref().map(|x| lower_expr(lctx, x))) - }, - ExprParen(ref ex) => { - return lower_expr(lctx, ex); - } + inputs: inputs.iter() + .map(|&(ref c, ref input)| (c.clone(), lower_expr(lctx, input))) + .collect(), + outputs: outputs.iter() + .map(|&(ref c, ref out, ref is_rw)| { + (c.clone(), lower_expr(lctx, out), *is_rw) + }) + .collect(), + asm: asm.clone(), + asm_str_style: asm_str_style, + clobbers: clobbers.clone(), + volatile: volatile, + alignstack: alignstack, + dialect: dialect, + expn_id: expn_id, + }), + ExprStruct(ref path, ref fields, ref maybe_expr) => { + hir::ExprStruct(lower_path(lctx, path), + fields.iter().map(|x| lower_field(lctx, x)).collect(), + maybe_expr.as_ref().map(|x| lower_expr(lctx, x))) + } + ExprParen(ref ex) => { + return lower_expr(lctx, ex); + } - // Desugar ExprIfLet - // From: `if let = []` - ExprIfLet(ref pat, ref sub_expr, ref body, ref else_opt) => { - // to: - // - // match { - // => , - // [_ if => ,] - // _ => [ | ()] - // } - - let _old_cached = CachedIdSetter::new(lctx, e.id); + // Desugar ExprIfLet + // From: `if let = []` + ExprIfLet(ref pat, ref sub_expr, ref body, ref else_opt) => { + // to: + // + // match { + // => , + // [_ if => ,] + // _ => [ | ()] + // } - // ` => ` - let pat_arm = { - let body_expr = expr_block(lctx, lower_block(lctx, body)); - arm(vec![lower_pat(lctx, pat)], body_expr) - }; + let _old_cached = CachedIdSetter::new(lctx, e.id); - // `[_ if => ,]` - let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e)); - let else_if_arms = { - let mut arms = vec![]; - loop { - let else_opt_continue = else_opt - .and_then(|els| els.and_then(|els| match els.node { - // else if - hir::ExprIf(cond, then, else_opt) => { - let pat_under = pat_wild(lctx, e.span); - arms.push(hir::Arm { - attrs: vec![], - pats: vec![pat_under], - guard: Some(cond), - body: expr_block(lctx, then) - }); - else_opt.map(|else_opt| (else_opt, true)) - } - _ => Some((P(els), false)) - })); - match else_opt_continue { - Some((e, true)) => { - else_opt = Some(e); - } - Some((e, false)) => { - else_opt = Some(e); - break; - } - None => { - else_opt = None; - break; + // ` => ` + let pat_arm = { + let body_expr = expr_block(lctx, lower_block(lctx, body)); + arm(vec![lower_pat(lctx, pat)], body_expr) + }; + + // `[_ if => ,]` + let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e)); + let else_if_arms = { + let mut arms = vec![]; + loop { + let else_opt_continue = else_opt.and_then(|els| { + els.and_then(|els| { + match els.node { + // else if + hir::ExprIf(cond, then, else_opt) => { + let pat_under = pat_wild(lctx, e.span); + arms.push(hir::Arm { + attrs: vec![], + pats: vec![pat_under], + guard: Some(cond), + body: expr_block(lctx, then), + }); + else_opt.map(|else_opt| (else_opt, true)) + } + _ => Some((P(els), false)), } + }) + }); + match else_opt_continue { + Some((e, true)) => { + else_opt = Some(e); + } + Some((e, false)) => { + else_opt = Some(e); + break; + } + None => { + else_opt = None; + break; } } - arms + } + arms + }; + + let contains_else_clause = else_opt.is_some(); + + // `_ => [ | ()]` + let else_arm = { + let pat_under = pat_wild(lctx, e.span); + let else_expr = else_opt.unwrap_or_else(|| expr_tuple(lctx, e.span, vec![])); + arm(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 = expr(lctx, + e.span, + hir::ExprMatch(lower_expr(lctx, sub_expr), + arms, + hir::MatchSource::IfLetDesugar { + contains_else_clause: contains_else_clause, + })); + return match_expr; + } + + // Desugar ExprWhileLet + // From: `[opt_ident]: while let = ` + ExprWhileLet(ref pat, ref sub_expr, ref body, opt_ident) => { + // to: + // + // [opt_ident]: loop { + // match { + // => , + // _ => break + // } + // } + + let _old_cached = CachedIdSetter::new(lctx, e.id); + + // ` => ` + let pat_arm = { + let body_expr = expr_block(lctx, lower_block(lctx, body)); + arm(vec![lower_pat(lctx, pat)], body_expr) + }; + + // `_ => break` + let break_arm = { + let pat_under = pat_wild(lctx, e.span); + let break_expr = expr_break(lctx, e.span); + arm(vec![pat_under], break_expr) + }; + + // `match { ... }` + let arms = vec![pat_arm, break_arm]; + let match_expr = expr(lctx, + e.span, + hir::ExprMatch(lower_expr(lctx, sub_expr), + arms, + hir::MatchSource::WhileLetDesugar)); + + // `[opt_ident]: loop { ... }` + let loop_block = block_expr(lctx, match_expr); + return expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident)); + } + + // Desugar ExprForLoop + // From: `[opt_ident]: for in ` + ExprForLoop(ref pat, ref head, ref body, opt_ident) => { + // to: + // + // { + // let result = match ::std::iter::IntoIterator::into_iter() { + // mut iter => { + // [opt_ident]: loop { + // match ::std::iter::Iterator::next(&mut iter) { + // ::std::option::Option::Some() => , + // ::std::option::Option::None => break + // } + // } + // } + // }; + // result + // } + + let _old_cached = CachedIdSetter::new(lctx, e.id); + + // expand + let head = lower_expr(lctx, head); + + let iter = token::gensym_ident("iter"); + + // `::std::option::Option::Some() => ` + let pat_arm = { + let body_block = lower_block(lctx, body); + let body_span = body_block.span; + let body_expr = P(hir::Expr { + id: lctx.next_id(), + node: hir::ExprBlock(body_block), + span: body_span, + }); + let pat = lower_pat(lctx, pat); + let some_pat = pat_some(lctx, e.span, pat); + + arm(vec![some_pat], body_expr) + }; + + // `::std::option::Option::None => break` + let break_arm = { + let break_expr = expr_break(lctx, e.span); + + arm(vec![pat_none(lctx, e.span)], break_expr) + }; + + // `match ::std::iter::Iterator::next(&mut iter) { ... }` + let match_expr = { + let next_path = { + let strs = std_path(lctx, &["iter", "Iterator", "next"]); + + path_global(e.span, strs) }; - - let contains_else_clause = else_opt.is_some(); - - // `_ => [ | ()]` - let else_arm = { - let pat_under = pat_wild(lctx, e.span); - let else_expr = else_opt.unwrap_or_else(|| expr_tuple(lctx, e.span, vec![])); - arm(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 = expr(lctx, - e.span, - hir::ExprMatch(lower_expr(lctx, sub_expr), arms, - hir::MatchSource::IfLetDesugar { - contains_else_clause: contains_else_clause, - })); - return match_expr; - } - - // Desugar ExprWhileLet - // From: `[opt_ident]: while let = ` - ExprWhileLet(ref pat, ref sub_expr, ref body, opt_ident) => { - // to: - // - // [opt_ident]: loop { - // match { - // => , - // _ => break - // } - // } - - let _old_cached = CachedIdSetter::new(lctx, e.id); - - // ` => ` - let pat_arm = { - let body_expr = expr_block(lctx, lower_block(lctx, body)); - arm(vec![lower_pat(lctx, pat)], body_expr) - }; - - // `_ => break` - let break_arm = { - let pat_under = pat_wild(lctx, e.span); - let break_expr = expr_break(lctx, e.span); - arm(vec![pat_under], break_expr) - }; - - // // `match { ... }` + let ref_mut_iter = expr_mut_addr_of(lctx, + e.span, + expr_ident(lctx, e.span, iter)); + let next_expr = expr_call(lctx, + e.span, + expr_path(lctx, next_path), + vec![ref_mut_iter]); let arms = vec![pat_arm, break_arm]; - let match_expr = expr(lctx, - e.span, - hir::ExprMatch(lower_expr(lctx, sub_expr), arms, hir::MatchSource::WhileLetDesugar)); - // `[opt_ident]: loop { ... }` - let loop_block = block_expr(lctx, match_expr); - return expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident)); - } + expr(lctx, + e.span, + hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar)) + }; - // Desugar ExprForLoop - // From: `[opt_ident]: for in ` - ExprForLoop(ref pat, ref head, ref body, opt_ident) => { - // to: - // - // { - // let result = match ::std::iter::IntoIterator::into_iter() { - // mut iter => { - // [opt_ident]: loop { - // match ::std::iter::Iterator::next(&mut iter) { - // ::std::option::Option::Some() => , - // ::std::option::Option::None => break - // } - // } - // } - // }; - // result - // } + // `[opt_ident]: loop { ... }` + let loop_block = block_expr(lctx, match_expr); + let loop_expr = expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident)); - let _old_cached = CachedIdSetter::new(lctx, e.id); + // `mut iter => { ... }` + let iter_arm = { + let iter_pat = pat_ident_binding_mode(lctx, + e.span, + iter, + hir::BindByValue(hir::MutMutable)); + arm(vec![iter_pat], loop_expr) + }; - // expand - let head = lower_expr(lctx, head); + // `match ::std::iter::IntoIterator::into_iter() { ... }` + let into_iter_expr = { + let into_iter_path = { + let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]); - let iter = token::gensym_ident("iter"); - - // `::std::option::Option::Some() => ` - let pat_arm = { - let body_block = lower_block(lctx, body); - let body_span = body_block.span; - let body_expr = P(hir::Expr { - id: lctx.next_id(), - node: hir::ExprBlock(body_block), - span: body_span, - }); - let pat = lower_pat(lctx, pat); - let some_pat = pat_some(lctx, e.span, pat); - - arm(vec![some_pat], body_expr) + path_global(e.span, strs) }; - // `::std::option::Option::None => break` - let break_arm = { - let break_expr = expr_break(lctx, e.span); + expr_call(lctx, + e.span, + expr_path(lctx, into_iter_path), + vec![head]) + }; - arm(vec![pat_none(lctx, e.span)], break_expr) - }; + let match_expr = expr_match(lctx, e.span, into_iter_expr, vec![iter_arm]); - // `match ::std::iter::Iterator::next(&mut iter) { ... }` - let match_expr = { - let next_path = { - let strs = std_path(lctx, &["iter", "Iterator", "next"]); + // `{ let result = ...; result }` + let result_ident = token::gensym_ident("result"); + return expr_block(lctx, + block_all(lctx, + e.span, + vec![stmt_let(lctx, + e.span, + false, + result_ident, + match_expr)], + Some(expr_ident(lctx, e.span, result_ident)))) + } - path_global(e.span, strs) - }; - let ref_mut_iter = expr_mut_addr_of(lctx, e.span, expr_ident(lctx, e.span, iter)); - let next_expr = - expr_call(lctx, e.span, expr_path(lctx, next_path), vec![ref_mut_iter]); - let arms = vec![pat_arm, break_arm]; - - expr(lctx, - e.span, - hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar)) - }; - - // `[opt_ident]: loop { ... }` - let loop_block = block_expr(lctx, match_expr); - let loop_expr = expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident)); - - // `mut iter => { ... }` - let iter_arm = { - let iter_pat = - pat_ident_binding_mode(lctx, e.span, iter, hir::BindByValue(hir::MutMutable)); - arm(vec![iter_pat], loop_expr) - }; - - // `match ::std::iter::IntoIterator::into_iter() { ... }` - let into_iter_expr = { - let into_iter_path = { - let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]); - - path_global(e.span, strs) - }; - - expr_call(lctx, e.span, expr_path(lctx, into_iter_path), vec![head]) - }; - - let match_expr = expr_match(lctx, e.span, into_iter_expr, vec![iter_arm]); - - // `{ let result = ...; result }` - let result_ident = token::gensym_ident("result"); - return expr_block(lctx, - block_all(lctx, - e.span, - vec![stmt_let(lctx, e.span, - false, - result_ident, - match_expr)], - Some(expr_ident(lctx, e.span, result_ident)))) - } - - ExprMac(_) => panic!("Shouldn't exist here"), - }, - span: e.span, - }) + ExprMac(_) => panic!("Shouldn't exist here"), + }, + span: e.span, + }) } pub fn lower_stmt(_lctx: &LoweringContext, s: &Stmt) -> P { @@ -1342,19 +1408,19 @@ pub fn lower_stmt(_lctx: &LoweringContext, s: &Stmt) -> P { StmtDecl(ref d, id) => { P(Spanned { node: hir::StmtDecl(lower_decl(_lctx, d), id), - span: s.span + span: s.span, }) } StmtExpr(ref e, id) => { P(Spanned { node: hir::StmtExpr(lower_expr(_lctx, e), id), - span: s.span + span: s.span, }) } StmtSemi(ref e, id) => { P(Spanned { node: hir::StmtSemi(lower_expr(_lctx, e), id), - span: s.span + span: s.span, }) } StmtMac(..) => panic!("Shouldn't exist here"), @@ -1437,7 +1503,7 @@ fn arm(pats: Vec>, expr: P) -> hir::Arm { attrs: vec!(), pats: pats, guard: None, - body: expr + body: expr, } } @@ -1445,7 +1511,11 @@ fn expr_break(lctx: &LoweringContext, span: Span) -> P { expr(lctx, span, hir::ExprBreak(None)) } -fn expr_call(lctx: &LoweringContext, span: Span, e: P, args: Vec>) -> P { +fn expr_call(lctx: &LoweringContext, + span: Span, + e: P, + args: Vec>) + -> P { expr(lctx, span, hir::ExprCall(e, args)) } @@ -1461,8 +1531,14 @@ fn expr_path(lctx: &LoweringContext, path: hir::Path) -> P { expr(lctx, path.span, hir::ExprPath(None, path)) } -fn expr_match(lctx: &LoweringContext, span: Span, arg: P, arms: Vec) -> P { - expr(lctx, span, hir::ExprMatch(arg, arms, hir::MatchSource::Normal)) +fn expr_match(lctx: &LoweringContext, + span: Span, + arg: P, + arms: Vec) + -> P { + expr(lctx, + span, + hir::ExprMatch(arg, arms, hir::MatchSource::Normal)) } fn expr_block(lctx: &LoweringContext, b: P) -> P { @@ -1481,7 +1557,12 @@ fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_) -> P { }) } -fn stmt_let(lctx: &LoweringContext, sp: Span, mutbl: bool, ident: Ident, ex: P) -> P { +fn stmt_let(lctx: &LoweringContext, + sp: Span, + mutbl: bool, + ident: Ident, + ex: P) + -> P { let pat = if mutbl { pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable)) } else { @@ -1505,14 +1586,15 @@ fn block_expr(lctx: &LoweringContext, expr: P) -> P { fn block_all(lctx: &LoweringContext, span: Span, stmts: Vec>, - expr: Option>) -> P { - P(hir::Block { - stmts: stmts, - expr: expr, - id: lctx.next_id(), - rules: hir::DefaultBlock, - span: span, - }) + expr: Option>) + -> P { + P(hir::Block { + stmts: stmts, + expr: expr, + id: lctx.next_id(), + rules: hir::DefaultBlock, + span: span, + }) } fn pat_some(lctx: &LoweringContext, span: Span, pat: P) -> P { @@ -1527,7 +1609,11 @@ fn pat_none(lctx: &LoweringContext, span: Span) -> P { pat_enum(lctx, span, path, vec![]) } -fn pat_enum(lctx: &LoweringContext, span: Span, path: hir::Path, subpats: Vec>) -> P { +fn pat_enum(lctx: &LoweringContext, + span: Span, + path: hir::Path, + subpats: Vec>) + -> P { let pt = hir::PatEnum(path, Some(subpats)); pat(lctx, span, pt) } @@ -1539,8 +1625,14 @@ fn pat_ident(lctx: &LoweringContext, span: Span, ident: Ident) -> P { fn pat_ident_binding_mode(lctx: &LoweringContext, span: Span, ident: Ident, - bm: hir::BindingMode) -> P { - let pat_ident = hir::PatIdent(bm, Spanned{span: span, node: ident}, None); + bm: hir::BindingMode) + -> P { + let pat_ident = hir::PatIdent(bm, + Spanned { + span: span, + node: ident, + }, + None); pat(lctx, span, pat_ident) } @@ -1549,43 +1641,48 @@ fn pat_wild(lctx: &LoweringContext, span: Span) -> P { } fn pat(lctx: &LoweringContext, span: Span, pat: hir::Pat_) -> P { - P(hir::Pat { id: lctx.next_id(), node: pat, span: span }) + P(hir::Pat { + id: lctx.next_id(), + node: pat, + span: span, + }) } fn path_ident(span: Span, id: Ident) -> hir::Path { path(span, vec!(id)) } -fn path(span: Span, strs: Vec ) -> hir::Path { +fn path(span: Span, strs: Vec) -> hir::Path { path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new()) } -fn path_global(span: Span, strs: Vec ) -> hir::Path { +fn path_global(span: Span, strs: Vec) -> hir::Path { path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new()) } fn path_all(sp: Span, global: bool, - mut idents: Vec , + mut idents: Vec, lifetimes: Vec, types: Vec>, - bindings: Vec> ) + bindings: Vec>) -> hir::Path { let last_identifier = idents.pop().unwrap(); let mut segments: Vec = idents.into_iter() .map(|ident| { - hir::PathSegment { - identifier: ident, - parameters: hir::PathParameters::none(), - } - }).collect(); + hir::PathSegment { + identifier: ident, + parameters: hir::PathParameters::none(), + } + }) + .collect(); segments.push(hir::PathSegment { identifier: last_identifier, parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData { lifetimes: lifetimes, types: OwnedSlice::from_vec(types), bindings: OwnedSlice::from_vec(bindings), - }) + }), }); hir::Path { span: sp, @@ -1610,9 +1707,18 @@ fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Pa path_global(span, idents) } -fn signal_block_expr(lctx: &LoweringContext, stmts: Vec>, expr: P, span: Span, rule: hir::BlockCheckMode) -> P { - expr_block(lctx, P(hir::Block { - rules: rule, span: span, id: lctx.next_id(), - stmts: stmts, expr: Some(expr), - })) +fn signal_block_expr(lctx: &LoweringContext, + stmts: Vec>, + expr: P, + span: Span, + rule: hir::BlockCheckMode) + -> P { + expr_block(lctx, + P(hir::Block { + rules: rule, + span: span, + id: lctx.next_id(), + stmts: stmts, + expr: Some(expr), + })) } From a62a529eea3e00b3ce9e659daa4235add2cb8551 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Wed, 7 Oct 2015 08:26:22 +1300 Subject: [PATCH 15/15] review comments --- mk/crates.mk | 62 ++++--- src/librustc/middle/astencode.rs | 2 +- src/librustc_driver/pretty.rs | 32 ++-- src/librustc_front/hir.rs | 2 +- src/librustc_front/lowering.rs | 168 ++++++++++++++++-- src/librustdoc/test.rs | 5 - .../compile-fail/placement-expr-unsafe.rs | 24 +++ .../compile-fail/placement-expr-unstable.rs | 27 +++ 8 files changed, 256 insertions(+), 66 deletions(-) create mode 100644 src/test/compile-fail/placement-expr-unsafe.rs create mode 100644 src/test/compile-fail/placement-expr-unstable.rs diff --git a/mk/crates.mk b/mk/crates.mk index 0213070d786..6673b9b28e7 100644 --- a/mk/crates.mk +++ b/mk/crates.mk @@ -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_front := std syntax log serialize DEPS_rustc_lint := rustc log syntax -DEPS_rustc := syntax flate arena serialize getopts rbml rustc_front\ - log graphviz rustc_llvm rustc_back rustc_data_structures 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_back := std syntax rustc_llvm rustc_front flate log libc -DEPS_rustc_data_structures := std log serialize +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 diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index dd96ea0460b..98f35ca5280 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -1379,7 +1379,7 @@ impl FakeExtCtxt for parse::ParseSess { struct FakeNodeIdAssigner; #[cfg(test)] -// It should go without sayingt that this may give unexpected results. Avoid +// 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 { diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 4e198a44b94..57186cb6ce8 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -224,12 +224,12 @@ trait HirPrinterSupport<'ast>: pprust_hir::PpAnn { fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn; } -struct NoAnn<'ast, 'tcx> { - sess: &'tcx Session, +struct NoAnn<'ast> { + sess: &'ast Session, ast_map: Option> } -impl<'ast, 'tcx> PrinterSupport<'ast> for NoAnn<'ast, 'tcx> { +impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> { fn sess<'a>(&'a self) -> &'a Session { self.sess } fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> { @@ -239,7 +239,7 @@ impl<'ast, 'tcx> PrinterSupport<'ast> for NoAnn<'ast, 'tcx> { fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self } } -impl<'ast, 'tcx> HirPrinterSupport<'ast> for NoAnn<'ast, 'tcx> { +impl<'ast> HirPrinterSupport<'ast> for NoAnn<'ast> { fn sess<'a>(&'a self) -> &'a Session { self.sess } fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> { @@ -249,15 +249,15 @@ impl<'ast, 'tcx> HirPrinterSupport<'ast> for NoAnn<'ast, 'tcx> { fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { self } } -impl<'ast, 'tcx> pprust::PpAnn for NoAnn<'ast, 'tcx> {} -impl<'ast, 'tcx> pprust_hir::PpAnn for NoAnn<'ast, 'tcx> {} +impl<'ast> pprust::PpAnn for NoAnn<'ast> {} +impl<'ast> pprust_hir::PpAnn for NoAnn<'ast> {} -struct IdentifiedAnnotation<'ast, 'tcx> { - sess: &'tcx Session, +struct IdentifiedAnnotation<'ast> { + sess: &'ast Session, ast_map: Option>, } -impl<'ast, 'tcx> PrinterSupport<'ast> for IdentifiedAnnotation<'ast, 'tcx> { +impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> { fn sess<'a>(&'a self) -> &'a Session { self.sess } fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> { @@ -267,7 +267,7 @@ impl<'ast, 'tcx> PrinterSupport<'ast> for IdentifiedAnnotation<'ast, 'tcx> { fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self } } -impl<'ast, 'tcx> pprust::PpAnn for IdentifiedAnnotation<'ast, 'tcx> { +impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> { fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> { @@ -307,7 +307,7 @@ impl<'ast, 'tcx> pprust::PpAnn for IdentifiedAnnotation<'ast, 'tcx> { } } -impl<'ast, 'tcx> HirPrinterSupport<'ast> for IdentifiedAnnotation<'ast, 'tcx> { +impl<'ast> HirPrinterSupport<'ast> for IdentifiedAnnotation<'ast> { fn sess<'a>(&'a self) -> &'a Session { self.sess } fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> { @@ -317,7 +317,7 @@ impl<'ast, 'tcx> HirPrinterSupport<'ast> for IdentifiedAnnotation<'ast, 'tcx> { fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { self } } -impl<'ast, 'tcx> pprust_hir::PpAnn for IdentifiedAnnotation<'ast, 'tcx> { +impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> { fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> { @@ -356,12 +356,12 @@ impl<'ast, 'tcx> pprust_hir::PpAnn for IdentifiedAnnotation<'ast, 'tcx> { } } -struct HygieneAnnotation<'ast, 'tcx> { - sess: &'tcx Session, +struct HygieneAnnotation<'ast> { + sess: &'ast Session, ast_map: Option>, } -impl<'ast, 'tcx> PrinterSupport<'ast> for HygieneAnnotation<'ast, 'tcx> { +impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> { fn sess<'a>(&'a self) -> &'a Session { self.sess } fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> { @@ -371,7 +371,7 @@ impl<'ast, 'tcx> PrinterSupport<'ast> for HygieneAnnotation<'ast, 'tcx> { fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self } } -impl<'ast, 'tcx> pprust::PpAnn for HygieneAnnotation<'ast, 'tcx> { +impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> { fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> { diff --git a/src/librustc_front/hir.rs b/src/librustc_front/hir.rs index c9f13da0633..9066b93262c 100644 --- a/src/librustc_front/hir.rs +++ b/src/librustc_front/hir.rs @@ -586,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_, diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index 681fc6144f3..4ee5fa2c1e9 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -25,13 +25,13 @@ // 'folding' an existing one), then you create a new id using `next_id()`. // // You must ensure that ids are unique. That means that you should only use the -// is from an AST node in a single HIR node (you can assume that AST node ids +// id from an AST node in a single HIR node (you can assume that AST node ids // are unique). Every new node must have a unique id. Avoid cloning HIR nodes. -// If you do, you must then set one of the node's id to a fresh one. +// If you do, you must then set the new node's id to a fresh one. // // Lowering must be reproducable (the compiler only lowers once, but tools and // custom lints may lower an AST node to a HIR node to interact with the -// compiler). The only interesting bit of this is ids - if you lower an AST node +// compiler). The most interesting bit of this is ids - if you lower an AST node // and create new HIR nodes with fresh ids, when re-lowering the same node, you // must ensure you get the same ids! To do this, we keep track of the next id // when we translate a node which requires new ids. By checking this cache and @@ -44,6 +44,12 @@ // all increments being for lowering. This means that you should not call any // non-lowering function which will use new node ids. // +// We must also cache gensym'ed Idents to ensure that we get the same Ident +// every time we lower a node with gensym'ed names. One consequence of this is +// that you can only gensym a name once in a lowering (you don't need to worry +// about nested lowering though). That's because we cache based on the name and +// the currently cached node id, which is unique per lowered node. +// // Spans are used for error messages and for tools to map semantics back to // source code. It is therefore not as important with spans as ids to be strict // about use (you can't break the compiler by screwing up a span). Obviously, a @@ -77,6 +83,10 @@ pub struct LoweringContext<'a> { // 0 == no cached id. Must be incremented to align with previous id // incrementing. cached_id: Cell, + // Keep track of gensym'ed idents. + gensym_cache: RefCell>, + // A copy of cached_id, but is also set to an id while it is being cached. + gensym_key: Cell, } impl<'a, 'hir> LoweringContext<'a> { @@ -96,6 +106,8 @@ impl<'a, 'hir> LoweringContext<'a> { id_cache: RefCell::new(HashMap::new()), id_assigner: id_assigner, cached_id: Cell::new(0), + gensym_cache: RefCell::new(HashMap::new()), + gensym_key: Cell::new(0), } } @@ -108,6 +120,22 @@ impl<'a, 'hir> LoweringContext<'a> { self.cached_id.set(cached + 1); cached } + + fn str_to_ident(&self, s: &'static str) -> Ident { + let cached_id = self.gensym_key.get(); + if cached_id == 0 { + return token::gensym_ident(s); + } + + let cached = self.gensym_cache.borrow().contains_key(&(cached_id, s)); + if cached { + self.gensym_cache.borrow()[&(cached_id, s)] + } else { + let result = token::gensym_ident(s); + self.gensym_cache.borrow_mut().insert((cached_id, s), result); + result + } + } } pub fn lower_view_path(_lctx: &LoweringContext, view_path: &ViewPath) -> P { @@ -861,6 +889,11 @@ struct CachedIdSetter<'a> { impl<'a> CachedIdSetter<'a> { fn new(lctx: &'a LoweringContext, expr_id: NodeId) -> CachedIdSetter<'a> { + // Only reset the id if it was previously 0, i.e., was not cached. + // If it was cached, we are in a nested node, but our id count will + // still count towards the parent's count. + let reset_cached_id = lctx.cached_id.get() == 0; + let id_cache: &mut HashMap<_, _> = &mut lctx.id_cache.borrow_mut(); if id_cache.contains_key(&expr_id) { @@ -869,20 +902,20 @@ impl<'a> CachedIdSetter<'a> { // We're entering a node where we need to track ids, but are not // yet tracking. lctx.cached_id.set(id_cache[&expr_id]); + lctx.gensym_key.set(id_cache[&expr_id]); } else { // We're already tracking - check that the tracked id is the same // as the expected id. assert!(cached_id == id_cache[&expr_id], "id mismatch"); } } else { - id_cache.insert(expr_id, lctx.id_assigner.peek_node_id()); + let next_id = lctx.id_assigner.peek_node_id(); + id_cache.insert(expr_id, next_id); + lctx.gensym_key.set(next_id); } CachedIdSetter { - // Only reset the id if it was previously 0, i.e., was not cached. - // If it was cached, we are in a nested node, but our id count will - // still count towards the parent's count. - reset: lctx.cached_id.get() == 0, + reset: reset_cached_id, lctx: lctx, } } @@ -892,6 +925,7 @@ impl<'a> Drop for CachedIdSetter<'a> { fn drop(&mut self) { if self.reset { self.lctx.cached_id.set(0); + self.lctx.gensym_key.set(0); } } } @@ -936,9 +970,9 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { let placer_expr = lower_expr(lctx, placer); let value_expr = lower_expr(lctx, 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_ident = lctx.str_to_ident("placer"); + let agent_ident = lctx.str_to_ident("place"); + let p_ptr_ident = lctx.str_to_ident("p_ptr"); let make_place = ["ops", "Placer", "make_place"]; let place_pointer = ["ops", "Place", "pointer"]; @@ -955,7 +989,13 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { let mk_stmt_let_mut = |lctx, bind, expr| stmt_let(lctx, e.span, true, bind, expr); // let placer = ; - let s1 = mk_stmt_let(lctx, placer_ident, placer_expr); + let s1 = mk_stmt_let(lctx, + placer_ident, + signal_block_expr(lctx, + vec![], + placer_expr, + e.span, + hir::PopUnstableBlock)); // let mut place = Placer::make_place(placer); let s2 = { @@ -1310,7 +1350,7 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { // expand let head = lower_expr(lctx, head); - let iter = token::gensym_ident("iter"); + let iter = lctx.str_to_ident("iter"); // `::std::option::Option::Some() => ` let pat_arm = { @@ -1385,7 +1425,7 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P { let match_expr = expr_match(lctx, e.span, into_iter_expr, vec![iter_arm]); // `{ let result = ...; result }` - let result_ident = token::gensym_ident("result"); + let result_ident = lctx.str_to_ident("result"); return expr_block(lctx, block_all(lctx, e.span, @@ -1722,3 +1762,103 @@ fn signal_block_expr(lctx: &LoweringContext, expr: Some(expr), })) } + + + +#[cfg(test)] +mod test { + use super::*; + use syntax::ast::{self, NodeId, NodeIdAssigner}; + use syntax::{parse, codemap}; + use syntax::fold::Folder; + use std::cell::Cell; + + struct MockAssigner { + next_id: Cell, + } + + impl MockAssigner { + fn new() -> MockAssigner { + MockAssigner { + next_id: Cell::new(0), + } + } + } + + trait FakeExtCtxt { + fn call_site(&self) -> codemap::Span; + fn cfg(&self) -> ast::CrateConfig; + fn ident_of(&self, st: &str) -> ast::Ident; + fn name_of(&self, st: &str) -> ast::Name; + fn parse_sess(&self) -> &parse::ParseSess; + } + + impl FakeExtCtxt for parse::ParseSess { + fn call_site(&self) -> codemap::Span { + codemap::Span { + lo: codemap::BytePos(0), + hi: codemap::BytePos(0), + expn_id: codemap::NO_EXPANSION, + } + } + fn cfg(&self) -> ast::CrateConfig { Vec::new() } + fn ident_of(&self, st: &str) -> ast::Ident { + parse::token::str_to_ident(st) + } + fn name_of(&self, st: &str) -> ast::Name { + parse::token::intern(st) + } + fn parse_sess(&self) -> &parse::ParseSess { self } + } + + impl NodeIdAssigner for MockAssigner { + fn next_node_id(&self) -> NodeId { + let result = self.next_id.get(); + self.next_id.set(result + 1); + result + } + + fn peek_node_id(&self) -> NodeId { + self.next_id.get() + } + } + + impl Folder for MockAssigner { + fn new_id(&mut self, old_id: NodeId) -> NodeId { + assert_eq!(old_id, ast::DUMMY_NODE_ID); + self.next_node_id() + } + } + + #[test] + fn test_preserves_ids() { + let cx = parse::ParseSess::new(); + let mut assigner = MockAssigner::new(); + + let ast_if_let = quote_expr!(&cx, if let Some(foo) = baz { bar(foo); }); + let ast_if_let = assigner.fold_expr(ast_if_let); + let ast_while_let = quote_expr!(&cx, while let Some(foo) = baz { bar(foo); }); + let ast_while_let = assigner.fold_expr(ast_while_let); + let ast_for = quote_expr!(&cx, for i in 0..10 { foo(i); }); + let ast_for = assigner.fold_expr(ast_for); + let ast_in = quote_expr!(&cx, in HEAP { foo() }); + let ast_in = assigner.fold_expr(ast_in); + + let lctx = LoweringContext::new(&assigner, None); + let hir1 = lower_expr(&lctx, &ast_if_let); + let hir2 = lower_expr(&lctx, &ast_if_let); + assert!(hir1 == hir2); + + let hir1 = lower_expr(&lctx, &ast_while_let); + let hir2 = lower_expr(&lctx, &ast_while_let); + assert!(hir1 == hir2); + + let hir1 = lower_expr(&lctx, &ast_for); + let hir2 = lower_expr(&lctx, &ast_for); + assert!(hir1 == hir2); + + let hir1 = lower_expr(&lctx, &ast_in); + let hir2 = lower_expr(&lctx, &ast_in); + assert!(hir1 == hir2); + } +} diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 87e1d8a0392..d6114737ab5 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -92,13 +92,8 @@ pub fn run(input: &str, let map = hir_map::map_crate(&mut forest); let ctx = core::DocContext { -<<<<<<< HEAD map: &map, - maybe_typed: core::NotTyped(sess), -======= - krate: &krate, maybe_typed: core::NotTyped(&sess), ->>>>>>> Fixes to rustdoc, etc. input: input, external_paths: RefCell::new(Some(HashMap::new())), external_traits: RefCell::new(None), diff --git a/src/test/compile-fail/placement-expr-unsafe.rs b/src/test/compile-fail/placement-expr-unsafe.rs new file mode 100644 index 00000000000..50a840e6c9b --- /dev/null +++ b/src/test/compile-fail/placement-expr-unsafe.rs @@ -0,0 +1,24 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Check that placement in respects unsafe code checks. + +#![feature(box_heap)] +#![feature(placement_in_syntax)] + +fn main() { + 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 +} diff --git a/src/test/compile-fail/placement-expr-unstable.rs b/src/test/compile-fail/placement-expr-unstable.rs new file mode 100644 index 00000000000..d981b71a813 --- /dev/null +++ b/src/test/compile-fail/placement-expr-unstable.rs @@ -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 or the MIT license +// , 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 + } + }; +}