1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Lowers the AST to the HIR.
13 // Since the AST and HIR are fairly similar, this is mostly a simple procedure,
14 // much like a fold. Where lowering involves a bit more work things get more
15 // interesting and there are some invariants you should know about. These mostly
16 // concern spans and ids.
18 // Spans are assigned to AST nodes during parsing and then are modified during
19 // expansion to indicate the origin of a node and the process it went through
20 // being expanded. Ids are assigned to AST nodes just before lowering.
22 // For the simpler lowering steps, ids and spans should be preserved. Unlike
23 // expansion we do not preserve the process of lowering in the spans, so spans
24 // should not be modified here. When creating a new node (as opposed to
25 // 'folding' an existing one), then you create a new id using `next_id()`.
27 // You must ensure that ids are unique. That means that you should only use the
28 // id from an AST node in a single HIR node (you can assume that AST node ids
29 // are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
30 // If you do, you must then set the new node's id to a fresh one.
32 // Lowering must be reproducable (the compiler only lowers once, but tools and
33 // custom lints may lower an AST node to a HIR node to interact with the
34 // compiler). The most interesting bit of this is ids - if you lower an AST node
35 // and create new HIR nodes with fresh ids, when re-lowering the same node, you
36 // must ensure you get the same ids! To do this, we keep track of the next id
37 // when we translate a node which requires new ids. By checking this cache and
38 // using node ids starting with the cached id, we ensure ids are reproducible.
39 // To use this system, you just need to hold on to a CachedIdSetter object
40 // whilst lowering. This is an RAII object that takes care of setting and
41 // restoring the cached id, etc.
43 // This whole system relies on node ids being incremented one at a time and
44 // all increments being for lowering. This means that you should not call any
45 // non-lowering function which will use new node ids.
47 // We must also cache gensym'ed Idents to ensure that we get the same Ident
48 // every time we lower a node with gensym'ed names. One consequence of this is
49 // that you can only gensym a name once in a lowering (you don't need to worry
50 // about nested lowering though). That's because we cache based on the name and
51 // the currently cached node id, which is unique per lowered node.
53 // Spans are used for error messages and for tools to map semantics back to
54 // source code. It is therefore not as important with spans as ids to be strict
55 // about use (you can't break the compiler by screwing up a span). Obviously, a
56 // HIR node can only have a single span. But multiple nodes can have the same
57 // span and spans don't need to be kept in order, etc. Where code is preserved
58 // by lowering, it should have the same span as in the AST. Where HIR nodes are
59 // new it is probably best to give a span for the whole AST node being lowered.
60 // All nodes should have real spans, don't use dummy spans. Tools are likely to
61 // get confused if the spans from leaf AST nodes occur in multiple places
62 // in the HIR, especially for multiple identifiers.
66 use std::collections::BTreeMap;
67 use std::collections::HashMap;
69 use syntax::attr::{ThinAttributes, ThinAttributesExt};
70 use syntax::ext::mtwt;
72 use syntax::codemap::{respan, Spanned, Span};
73 use syntax::owned_slice::OwnedSlice;
74 use syntax::parse::token;
75 use syntax::std_inject;
76 use syntax::visit::{self, Visitor};
78 use std::cell::{Cell, RefCell};
80 pub struct LoweringContext<'a> {
81 crate_root: Option<&'static str>,
82 // Map AST ids to ids used for expanded nodes.
83 id_cache: RefCell<HashMap<NodeId, NodeId>>,
84 // Use if there are no cached ids for the current node.
85 id_assigner: &'a NodeIdAssigner,
86 // 0 == no cached id. Must be incremented to align with previous id
89 // Keep track of gensym'ed idents.
90 gensym_cache: RefCell<HashMap<(NodeId, &'static str), hir::Ident>>,
91 // A copy of cached_id, but is also set to an id while it is being cached.
92 gensym_key: Cell<u32>,
95 impl<'a, 'hir> LoweringContext<'a> {
96 pub fn new(id_assigner: &'a NodeIdAssigner, c: Option<&Crate>) -> LoweringContext<'a> {
97 let crate_root = c.and_then(|c| {
98 if std_inject::no_core(c) {
100 } else if std_inject::no_std(c) {
108 crate_root: crate_root,
109 id_cache: RefCell::new(HashMap::new()),
110 id_assigner: id_assigner,
111 cached_id: Cell::new(0),
112 gensym_cache: RefCell::new(HashMap::new()),
113 gensym_key: Cell::new(0),
117 fn next_id(&self) -> NodeId {
118 let cached = self.cached_id.get();
120 return self.id_assigner.next_node_id();
123 self.cached_id.set(cached + 1);
127 fn str_to_ident(&self, s: &'static str) -> hir::Ident {
128 let cached_id = self.gensym_key.get();
130 return hir::Ident::from_name(token::gensym(s));
133 let cached = self.gensym_cache.borrow().contains_key(&(cached_id, s));
135 self.gensym_cache.borrow()[&(cached_id, s)]
137 let result = hir::Ident::from_name(token::gensym(s));
138 self.gensym_cache.borrow_mut().insert((cached_id, s), result);
144 pub fn lower_ident(_lctx: &LoweringContext, ident: Ident) -> hir::Ident {
146 name: mtwt::resolve(ident),
147 unhygienic_name: ident.name,
151 pub fn lower_view_path(lctx: &LoweringContext, view_path: &ViewPath) -> P<hir::ViewPath> {
153 node: match view_path.node {
154 ViewPathSimple(ident, ref path) => {
155 hir::ViewPathSimple(ident.name, lower_path(lctx, path))
157 ViewPathGlob(ref path) => {
158 hir::ViewPathGlob(lower_path(lctx, path))
160 ViewPathList(ref path, ref path_list_idents) => {
161 hir::ViewPathList(lower_path(lctx, path),
162 path_list_idents.iter()
163 .map(|path_list_ident| {
165 node: match path_list_ident.node {
166 PathListIdent { id, name, rename } =>
170 rename: rename.map(|x| x.name),
172 PathListMod { id, rename } =>
175 rename: rename.map(|x| x.name),
178 span: path_list_ident.span,
184 span: view_path.span,
188 pub fn lower_arm(lctx: &LoweringContext, arm: &Arm) -> hir::Arm {
190 attrs: arm.attrs.clone(),
191 pats: arm.pats.iter().map(|x| lower_pat(lctx, x)).collect(),
192 guard: arm.guard.as_ref().map(|ref x| lower_expr(lctx, x)),
193 body: lower_expr(lctx, &arm.body),
197 pub fn lower_decl(lctx: &LoweringContext, d: &Decl) -> P<hir::Decl> {
199 DeclLocal(ref l) => P(Spanned {
200 node: hir::DeclLocal(lower_local(lctx, l)),
203 DeclItem(ref it) => P(Spanned {
204 node: hir::DeclItem(lower_item_id(lctx, it)),
210 pub fn lower_ty_binding(lctx: &LoweringContext, b: &TypeBinding) -> hir::TypeBinding {
214 ty: lower_ty(lctx, &b.ty),
219 pub fn lower_ty(lctx: &LoweringContext, t: &Ty) -> P<hir::Ty> {
223 TyInfer => hir::TyInfer,
224 TyVec(ref ty) => hir::TyVec(lower_ty(lctx, ty)),
225 TyPtr(ref mt) => hir::TyPtr(lower_mt(lctx, mt)),
226 TyRptr(ref region, ref mt) => {
227 hir::TyRptr(lower_opt_lifetime(lctx, region), lower_mt(lctx, mt))
230 hir::TyBareFn(P(hir::BareFnTy {
231 lifetimes: lower_lifetime_defs(lctx, &f.lifetimes),
232 unsafety: lower_unsafety(lctx, f.unsafety),
234 decl: lower_fn_decl(lctx, &f.decl),
237 TyTup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(lctx, ty)).collect()),
239 return lower_ty(lctx, ty);
241 TyPath(ref qself, ref path) => {
242 let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
244 ty: lower_ty(lctx, ty),
248 hir::TyPath(qself, lower_path(lctx, path))
250 TyObjectSum(ref ty, ref bounds) => {
251 hir::TyObjectSum(lower_ty(lctx, ty), lower_bounds(lctx, bounds))
253 TyFixedLengthVec(ref ty, ref e) => {
254 hir::TyFixedLengthVec(lower_ty(lctx, ty), lower_expr(lctx, e))
256 TyTypeof(ref expr) => {
257 hir::TyTypeof(lower_expr(lctx, expr))
259 TyPolyTraitRef(ref bounds) => {
260 hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(lctx, b)).collect())
262 TyMac(_) => panic!("TyMac should have been expanded by now."),
268 pub fn lower_foreign_mod(lctx: &LoweringContext, fm: &ForeignMod) -> hir::ForeignMod {
271 items: fm.items.iter().map(|x| lower_foreign_item(lctx, x)).collect(),
275 pub fn lower_variant(lctx: &LoweringContext, v: &Variant) -> hir::Variant {
277 node: hir::Variant_ {
278 name: v.node.name.name,
279 attrs: v.node.attrs.clone(),
280 data: lower_variant_data(lctx, &v.node.data),
281 disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(lctx, e)),
287 // Path segments are usually unhygienic, hygienic path segments can occur only in
288 // identifier-like paths originating from `ExprPath`.
289 // Make life simpler for rustc_resolve by renaming only such segments.
290 pub fn lower_path_full(lctx: &LoweringContext, p: &Path, maybe_hygienic: bool) -> hir::Path {
291 let maybe_hygienic = maybe_hygienic && !p.global && p.segments.len() == 1;
296 .map(|&PathSegment { identifier, ref parameters }| {
298 identifier: if maybe_hygienic {
299 lower_ident(lctx, identifier)
301 hir::Ident::from_name(identifier.name)
303 parameters: lower_path_parameters(lctx, parameters),
311 pub fn lower_path(lctx: &LoweringContext, p: &Path) -> hir::Path {
312 lower_path_full(lctx, p, false)
315 pub fn lower_path_parameters(lctx: &LoweringContext,
316 path_parameters: &PathParameters)
317 -> hir::PathParameters {
318 match *path_parameters {
319 AngleBracketedParameters(ref data) =>
320 hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(lctx, data)),
321 ParenthesizedParameters(ref data) =>
322 hir::ParenthesizedParameters(lower_parenthesized_parameter_data(lctx, data)),
326 pub fn lower_angle_bracketed_parameter_data(lctx: &LoweringContext,
327 data: &AngleBracketedParameterData)
328 -> hir::AngleBracketedParameterData {
329 let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
330 hir::AngleBracketedParameterData {
331 lifetimes: lower_lifetimes(lctx, lifetimes),
332 types: types.iter().map(|ty| lower_ty(lctx, ty)).collect(),
333 bindings: bindings.iter().map(|b| lower_ty_binding(lctx, b)).collect(),
337 pub fn lower_parenthesized_parameter_data(lctx: &LoweringContext,
338 data: &ParenthesizedParameterData)
339 -> hir::ParenthesizedParameterData {
340 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
341 hir::ParenthesizedParameterData {
342 inputs: inputs.iter().map(|ty| lower_ty(lctx, ty)).collect(),
343 output: output.as_ref().map(|ty| lower_ty(lctx, ty)),
348 pub fn lower_local(lctx: &LoweringContext, l: &Local) -> P<hir::Local> {
351 ty: l.ty.as_ref().map(|t| lower_ty(lctx, t)),
352 pat: lower_pat(lctx, &l.pat),
353 init: l.init.as_ref().map(|e| lower_expr(lctx, e)),
355 attrs: l.attrs.clone(),
359 pub fn lower_explicit_self_underscore(lctx: &LoweringContext,
361 -> hir::ExplicitSelf_ {
363 SelfStatic => hir::SelfStatic,
364 SelfValue(v) => hir::SelfValue(v.name),
365 SelfRegion(ref lifetime, m, ident) => {
366 hir::SelfRegion(lower_opt_lifetime(lctx, lifetime),
367 lower_mutability(lctx, m),
370 SelfExplicit(ref typ, ident) => {
371 hir::SelfExplicit(lower_ty(lctx, typ), ident.name)
376 pub fn lower_mutability(_lctx: &LoweringContext, m: Mutability) -> hir::Mutability {
378 MutMutable => hir::MutMutable,
379 MutImmutable => hir::MutImmutable,
383 pub fn lower_explicit_self(lctx: &LoweringContext, s: &ExplicitSelf) -> hir::ExplicitSelf {
385 node: lower_explicit_self_underscore(lctx, &s.node),
390 pub fn lower_arg(lctx: &LoweringContext, arg: &Arg) -> hir::Arg {
393 pat: lower_pat(lctx, &arg.pat),
394 ty: lower_ty(lctx, &arg.ty),
398 pub fn lower_fn_decl(lctx: &LoweringContext, decl: &FnDecl) -> P<hir::FnDecl> {
400 inputs: decl.inputs.iter().map(|x| lower_arg(lctx, x)).collect(),
401 output: match decl.output {
402 Return(ref ty) => hir::Return(lower_ty(lctx, ty)),
403 DefaultReturn(span) => hir::DefaultReturn(span),
404 NoReturn(span) => hir::NoReturn(span),
406 variadic: decl.variadic,
410 pub fn lower_ty_param_bound(lctx: &LoweringContext, tpb: &TyParamBound) -> hir::TyParamBound {
412 TraitTyParamBound(ref ty, modifier) => {
413 hir::TraitTyParamBound(lower_poly_trait_ref(lctx, ty),
414 lower_trait_bound_modifier(lctx, modifier))
416 RegionTyParamBound(ref lifetime) => {
417 hir::RegionTyParamBound(lower_lifetime(lctx, lifetime))
422 pub fn lower_ty_param(lctx: &LoweringContext, tp: &TyParam) -> hir::TyParam {
426 bounds: lower_bounds(lctx, &tp.bounds),
427 default: tp.default.as_ref().map(|x| lower_ty(lctx, x)),
432 pub fn lower_ty_params(lctx: &LoweringContext,
433 tps: &OwnedSlice<TyParam>)
434 -> OwnedSlice<hir::TyParam> {
435 tps.iter().map(|tp| lower_ty_param(lctx, tp)).collect()
438 pub fn lower_lifetime(_lctx: &LoweringContext, l: &Lifetime) -> hir::Lifetime {
446 pub fn lower_lifetime_def(lctx: &LoweringContext, l: &LifetimeDef) -> hir::LifetimeDef {
448 lifetime: lower_lifetime(lctx, &l.lifetime),
449 bounds: lower_lifetimes(lctx, &l.bounds),
453 pub fn lower_lifetimes(lctx: &LoweringContext, lts: &Vec<Lifetime>) -> Vec<hir::Lifetime> {
454 lts.iter().map(|l| lower_lifetime(lctx, l)).collect()
457 pub fn lower_lifetime_defs(lctx: &LoweringContext,
458 lts: &Vec<LifetimeDef>)
459 -> Vec<hir::LifetimeDef> {
460 lts.iter().map(|l| lower_lifetime_def(lctx, l)).collect()
463 pub fn lower_opt_lifetime(lctx: &LoweringContext,
464 o_lt: &Option<Lifetime>)
465 -> Option<hir::Lifetime> {
466 o_lt.as_ref().map(|lt| lower_lifetime(lctx, lt))
469 pub fn lower_generics(lctx: &LoweringContext, g: &Generics) -> hir::Generics {
471 ty_params: lower_ty_params(lctx, &g.ty_params),
472 lifetimes: lower_lifetime_defs(lctx, &g.lifetimes),
473 where_clause: lower_where_clause(lctx, &g.where_clause),
477 pub fn lower_where_clause(lctx: &LoweringContext, wc: &WhereClause) -> hir::WhereClause {
480 predicates: wc.predicates
482 .map(|predicate| lower_where_predicate(lctx, predicate))
487 pub fn lower_where_predicate(lctx: &LoweringContext,
488 pred: &WherePredicate)
489 -> hir::WherePredicate {
491 WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
495 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
496 bound_lifetimes: lower_lifetime_defs(lctx, bound_lifetimes),
497 bounded_ty: lower_ty(lctx, bounded_ty),
498 bounds: bounds.iter().map(|x| lower_ty_param_bound(lctx, x)).collect(),
502 WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
505 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
507 lifetime: lower_lifetime(lctx, lifetime),
508 bounds: bounds.iter().map(|bound| lower_lifetime(lctx, bound)).collect(),
511 WherePredicate::EqPredicate(WhereEqPredicate{ id,
515 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
517 path: lower_path(lctx, path),
518 ty: lower_ty(lctx, ty),
525 pub fn lower_variant_data(lctx: &LoweringContext, vdata: &VariantData) -> hir::VariantData {
527 VariantData::Struct(ref fields, id) => {
528 hir::VariantData::Struct(fields.iter()
529 .map(|f| lower_struct_field(lctx, f))
533 VariantData::Tuple(ref fields, id) => {
534 hir::VariantData::Tuple(fields.iter()
535 .map(|f| lower_struct_field(lctx, f))
539 VariantData::Unit(id) => hir::VariantData::Unit(id),
543 pub fn lower_trait_ref(lctx: &LoweringContext, p: &TraitRef) -> hir::TraitRef {
545 path: lower_path(lctx, &p.path),
550 pub fn lower_poly_trait_ref(lctx: &LoweringContext, p: &PolyTraitRef) -> hir::PolyTraitRef {
552 bound_lifetimes: lower_lifetime_defs(lctx, &p.bound_lifetimes),
553 trait_ref: lower_trait_ref(lctx, &p.trait_ref),
558 pub fn lower_struct_field(lctx: &LoweringContext, f: &StructField) -> hir::StructField {
560 node: hir::StructField_ {
562 kind: lower_struct_field_kind(lctx, &f.node.kind),
563 ty: lower_ty(lctx, &f.node.ty),
564 attrs: f.node.attrs.clone(),
570 pub fn lower_field(lctx: &LoweringContext, f: &Field) -> hir::Field {
572 name: respan(f.ident.span, f.ident.node.name),
573 expr: lower_expr(lctx, &f.expr),
578 pub fn lower_mt(lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy {
580 ty: lower_ty(lctx, &mt.ty),
581 mutbl: lower_mutability(lctx, mt.mutbl),
585 pub fn lower_opt_bounds(lctx: &LoweringContext,
586 b: &Option<OwnedSlice<TyParamBound>>)
587 -> Option<OwnedSlice<hir::TyParamBound>> {
588 b.as_ref().map(|ref bounds| lower_bounds(lctx, bounds))
591 fn lower_bounds(lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParamBounds {
592 bounds.iter().map(|bound| lower_ty_param_bound(lctx, bound)).collect()
595 pub fn lower_block(lctx: &LoweringContext, b: &Block) -> P<hir::Block> {
598 stmts: b.stmts.iter().map(|s| lower_stmt(lctx, s)).collect(),
599 expr: b.expr.as_ref().map(|ref x| lower_expr(lctx, x)),
600 rules: lower_block_check_mode(lctx, &b.rules),
605 pub fn lower_item_underscore(lctx: &LoweringContext, i: &Item_) -> hir::Item_ {
607 ItemExternCrate(string) => hir::ItemExternCrate(string),
608 ItemUse(ref view_path) => {
609 hir::ItemUse(lower_view_path(lctx, view_path))
611 ItemStatic(ref t, m, ref e) => {
612 hir::ItemStatic(lower_ty(lctx, t),
613 lower_mutability(lctx, m),
616 ItemConst(ref t, ref e) => {
617 hir::ItemConst(lower_ty(lctx, t), lower_expr(lctx, e))
619 ItemFn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
620 hir::ItemFn(lower_fn_decl(lctx, decl),
621 lower_unsafety(lctx, unsafety),
622 lower_constness(lctx, constness),
624 lower_generics(lctx, generics),
625 lower_block(lctx, body))
627 ItemMod(ref m) => hir::ItemMod(lower_mod(lctx, m)),
628 ItemForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(lctx, nm)),
629 ItemTy(ref t, ref generics) => {
630 hir::ItemTy(lower_ty(lctx, t), lower_generics(lctx, generics))
632 ItemEnum(ref enum_definition, ref generics) => {
633 hir::ItemEnum(hir::EnumDef {
634 variants: enum_definition.variants
636 .map(|x| lower_variant(lctx, x))
639 lower_generics(lctx, generics))
641 ItemStruct(ref struct_def, ref generics) => {
642 let struct_def = lower_variant_data(lctx, struct_def);
643 hir::ItemStruct(struct_def, lower_generics(lctx, generics))
645 ItemDefaultImpl(unsafety, ref trait_ref) => {
646 hir::ItemDefaultImpl(lower_unsafety(lctx, unsafety),
647 lower_trait_ref(lctx, trait_ref))
649 ItemImpl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
650 let new_impl_items = impl_items.iter()
651 .map(|item| lower_impl_item(lctx, item))
653 let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(lctx, trait_ref));
654 hir::ItemImpl(lower_unsafety(lctx, unsafety),
655 lower_impl_polarity(lctx, polarity),
656 lower_generics(lctx, generics),
661 ItemTrait(unsafety, ref generics, ref bounds, ref items) => {
662 let bounds = lower_bounds(lctx, bounds);
663 let items = items.iter().map(|item| lower_trait_item(lctx, item)).collect();
664 hir::ItemTrait(lower_unsafety(lctx, unsafety),
665 lower_generics(lctx, generics),
669 ItemMac(_) => panic!("Shouldn't still be around"),
673 pub fn lower_trait_item(lctx: &LoweringContext, i: &TraitItem) -> hir::TraitItem {
677 attrs: i.attrs.clone(),
679 ConstTraitItem(ref ty, ref default) => {
680 hir::ConstTraitItem(lower_ty(lctx, ty),
681 default.as_ref().map(|x| lower_expr(lctx, x)))
683 MethodTraitItem(ref sig, ref body) => {
684 hir::MethodTraitItem(lower_method_sig(lctx, sig),
685 body.as_ref().map(|x| lower_block(lctx, x)))
687 TypeTraitItem(ref bounds, ref default) => {
688 hir::TypeTraitItem(lower_bounds(lctx, bounds),
689 default.as_ref().map(|x| lower_ty(lctx, x)))
696 pub fn lower_impl_item(lctx: &LoweringContext, i: &ImplItem) -> hir::ImplItem {
700 attrs: i.attrs.clone(),
701 vis: lower_visibility(lctx, i.vis),
703 ImplItemKind::Const(ref ty, ref expr) => {
704 hir::ImplItemKind::Const(lower_ty(lctx, ty), lower_expr(lctx, expr))
706 ImplItemKind::Method(ref sig, ref body) => {
707 hir::ImplItemKind::Method(lower_method_sig(lctx, sig), lower_block(lctx, body))
709 ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(lower_ty(lctx, ty)),
710 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
716 pub fn lower_mod(lctx: &LoweringContext, m: &Mod) -> hir::Mod {
719 item_ids: m.items.iter().map(|x| lower_item_id(lctx, x)).collect(),
723 struct ItemLowerer<'lcx, 'interner: 'lcx> {
724 items: BTreeMap<NodeId, hir::Item>,
725 lctx: &'lcx LoweringContext<'interner>,
728 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
729 fn visit_item(&mut self, item: &'lcx Item) {
730 self.items.insert(item.id, lower_item(self.lctx, item));
731 visit::walk_item(self, item);
735 pub fn lower_crate(lctx: &LoweringContext, c: &Crate) -> hir::Crate {
737 let mut item_lowerer = ItemLowerer { items: BTreeMap::new(), lctx: lctx };
738 visit::walk_crate(&mut item_lowerer, c);
743 module: lower_mod(lctx, &c.module),
744 attrs: c.attrs.clone(),
745 config: c.config.clone(),
747 exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(lctx, m)).collect(),
752 pub fn lower_macro_def(_lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef {
755 attrs: m.attrs.clone(),
758 imported_from: m.imported_from.map(|x| x.name),
760 use_locally: m.use_locally,
761 allow_internal_unstable: m.allow_internal_unstable,
762 body: m.body.clone(),
766 pub fn lower_item_id(_lctx: &LoweringContext, i: &Item) -> hir::ItemId {
767 hir::ItemId { id: i.id }
770 pub fn lower_item(lctx: &LoweringContext, i: &Item) -> hir::Item {
771 let node = lower_item_underscore(lctx, &i.node);
776 attrs: i.attrs.clone(),
778 vis: lower_visibility(lctx, i.vis),
783 pub fn lower_foreign_item(lctx: &LoweringContext, i: &ForeignItem) -> hir::ForeignItem {
787 attrs: i.attrs.clone(),
789 ForeignItemFn(ref fdec, ref generics) => {
790 hir::ForeignItemFn(lower_fn_decl(lctx, fdec), lower_generics(lctx, generics))
792 ForeignItemStatic(ref t, m) => {
793 hir::ForeignItemStatic(lower_ty(lctx, t), m)
796 vis: lower_visibility(lctx, i.vis),
801 pub fn lower_method_sig(lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig {
803 generics: lower_generics(lctx, &sig.generics),
805 explicit_self: lower_explicit_self(lctx, &sig.explicit_self),
806 unsafety: lower_unsafety(lctx, sig.unsafety),
807 constness: lower_constness(lctx, sig.constness),
808 decl: lower_fn_decl(lctx, &sig.decl),
812 pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety {
814 Unsafety::Unsafe => hir::Unsafety::Unsafe,
815 Unsafety::Normal => hir::Unsafety::Normal,
819 pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness {
821 Constness::Const => hir::Constness::Const,
822 Constness::NotConst => hir::Constness::NotConst,
826 pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp {
828 UnDeref => hir::UnDeref,
834 pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp {
844 BiBitXor => hir::BiBitXor,
845 BiBitAnd => hir::BiBitAnd,
846 BiBitOr => hir::BiBitOr,
860 pub fn lower_pat(lctx: &LoweringContext, p: &Pat) -> P<hir::Pat> {
864 PatWild => hir::PatWild,
865 PatIdent(ref binding_mode, pth1, ref sub) => {
866 hir::PatIdent(lower_binding_mode(lctx, binding_mode),
867 respan(pth1.span, lower_ident(lctx, pth1.node)),
868 sub.as_ref().map(|x| lower_pat(lctx, x)))
870 PatLit(ref e) => hir::PatLit(lower_expr(lctx, e)),
871 PatEnum(ref pth, ref pats) => {
872 hir::PatEnum(lower_path(lctx, pth),
874 .map(|pats| pats.iter().map(|x| lower_pat(lctx, x)).collect()))
876 PatQPath(ref qself, ref pth) => {
877 let qself = hir::QSelf {
878 ty: lower_ty(lctx, &qself.ty),
879 position: qself.position,
881 hir::PatQPath(qself, lower_path(lctx, pth))
883 PatStruct(ref pth, ref fields, etc) => {
884 let pth = lower_path(lctx, pth);
885 let fs = fields.iter()
889 node: hir::FieldPat {
890 name: f.node.ident.name,
891 pat: lower_pat(lctx, &f.node.pat),
892 is_shorthand: f.node.is_shorthand,
897 hir::PatStruct(pth, fs, etc)
899 PatTup(ref elts) => hir::PatTup(elts.iter().map(|x| lower_pat(lctx, x)).collect()),
900 PatBox(ref inner) => hir::PatBox(lower_pat(lctx, inner)),
901 PatRegion(ref inner, mutbl) => {
902 hir::PatRegion(lower_pat(lctx, inner), lower_mutability(lctx, mutbl))
904 PatRange(ref e1, ref e2) => {
905 hir::PatRange(lower_expr(lctx, e1), lower_expr(lctx, e2))
907 PatVec(ref before, ref slice, ref after) => {
908 hir::PatVec(before.iter().map(|x| lower_pat(lctx, x)).collect(),
909 slice.as_ref().map(|x| lower_pat(lctx, x)),
910 after.iter().map(|x| lower_pat(lctx, x)).collect())
912 PatMac(_) => panic!("Shouldn't exist here"),
918 // Utility fn for setting and unsetting the cached id.
919 fn cache_ids<'a, OP, R>(lctx: &LoweringContext, expr_id: NodeId, op: OP) -> R
920 where OP: FnOnce(&LoweringContext) -> R
922 // Only reset the id if it was previously 0, i.e., was not cached.
923 // If it was cached, we are in a nested node, but our id count will
924 // still count towards the parent's count.
925 let reset_cached_id = lctx.cached_id.get() == 0;
928 let id_cache: &mut HashMap<_, _> = &mut lctx.id_cache.borrow_mut();
930 if id_cache.contains_key(&expr_id) {
931 let cached_id = lctx.cached_id.get();
933 // We're entering a node where we need to track ids, but are not
935 lctx.cached_id.set(id_cache[&expr_id]);
936 lctx.gensym_key.set(id_cache[&expr_id]);
938 // We're already tracking - check that the tracked id is the same
939 // as the expected id.
940 assert!(cached_id == id_cache[&expr_id], "id mismatch");
943 let next_id = lctx.id_assigner.peek_node_id();
944 id_cache.insert(expr_id, next_id);
945 lctx.gensym_key.set(next_id);
949 let result = op(lctx);
952 lctx.cached_id.set(0);
953 lctx.gensym_key.set(0);
959 pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
964 // Eventually a desugaring for `box EXPR`
965 // (similar to the desugaring above for `in PLACE BLOCK`)
966 // should go here, desugaring
970 // let mut place = BoxPlace::make_place();
971 // let raw_place = Place::pointer(&mut place);
972 // let value = $value;
974 // ::std::ptr::write(raw_place, value);
975 // Boxed::finalize(place)
978 // But for now there are type-inference issues doing that.
980 hir::ExprBox(lower_expr(lctx, e))
983 // Desugar ExprBox: `in (PLACE) EXPR`
984 ExprInPlace(ref placer, ref value_expr) => {
988 // let mut place = Placer::make_place(p);
989 // let raw_place = Place::pointer(&mut place);
991 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
992 // InPlace::finalize(place)
994 return cache_ids(lctx, e.id, |lctx| {
995 let placer_expr = lower_expr(lctx, placer);
996 let value_expr = lower_expr(lctx, value_expr);
998 let placer_ident = lctx.str_to_ident("placer");
999 let place_ident = lctx.str_to_ident("place");
1000 let p_ptr_ident = lctx.str_to_ident("p_ptr");
1002 let make_place = ["ops", "Placer", "make_place"];
1003 let place_pointer = ["ops", "Place", "pointer"];
1004 let move_val_init = ["intrinsics", "move_val_init"];
1005 let inplace_finalize = ["ops", "InPlace", "finalize"];
1007 let make_call = |lctx: &LoweringContext, p, args| {
1008 let path = core_path(lctx, e.span, p);
1009 let path = expr_path(lctx, path, None);
1010 expr_call(lctx, e.span, path, args, None)
1013 let mk_stmt_let = |lctx: &LoweringContext, bind, expr| {
1014 stmt_let(lctx, e.span, false, bind, expr, None)
1017 let mk_stmt_let_mut = |lctx: &LoweringContext, bind, expr| {
1018 stmt_let(lctx, e.span, true, bind, expr, None)
1021 // let placer = <placer_expr> ;
1023 let placer_expr = signal_block_expr(lctx,
1027 hir::PopUnstableBlock,
1029 mk_stmt_let(lctx, placer_ident, placer_expr)
1032 // let mut place = Placer::make_place(placer);
1034 let placer = expr_ident(lctx, e.span, placer_ident, None);
1035 let call = make_call(lctx, &make_place, vec![placer]);
1036 mk_stmt_let_mut(lctx, place_ident, call)
1039 // let p_ptr = Place::pointer(&mut place);
1041 let agent = expr_ident(lctx, e.span, place_ident, None);
1042 let args = vec![expr_mut_addr_of(lctx, e.span, agent, None)];
1043 let call = make_call(lctx, &place_pointer, args);
1044 mk_stmt_let(lctx, p_ptr_ident, call)
1047 // pop_unsafe!(EXPR));
1048 let pop_unsafe_expr = {
1049 let value_expr = signal_block_expr(lctx,
1053 hir::PopUnstableBlock,
1055 signal_block_expr(lctx,
1059 hir::PopUnsafeBlock(hir::CompilerGenerated), None)
1063 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1064 // InPlace::finalize(place)
1067 let ptr = expr_ident(lctx, e.span, p_ptr_ident, None);
1068 let call_move_val_init =
1070 make_call(lctx, &move_val_init, vec![ptr, pop_unsafe_expr]),
1072 let call_move_val_init = respan(e.span, call_move_val_init);
1074 let place = expr_ident(lctx, e.span, place_ident, None);
1075 let call = make_call(lctx, &inplace_finalize, vec![place]);
1076 signal_block_expr(lctx,
1077 vec![call_move_val_init],
1080 hir::PushUnsafeBlock(hir::CompilerGenerated), None)
1083 signal_block_expr(lctx,
1087 hir::PushUnstableBlock,
1092 ExprVec(ref exprs) => {
1093 hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect())
1095 ExprRepeat(ref expr, ref count) => {
1096 let expr = lower_expr(lctx, expr);
1097 let count = lower_expr(lctx, count);
1098 hir::ExprRepeat(expr, count)
1100 ExprTup(ref elts) => {
1101 hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect())
1103 ExprCall(ref f, ref args) => {
1104 let f = lower_expr(lctx, f);
1105 hir::ExprCall(f, args.iter().map(|x| lower_expr(lctx, x)).collect())
1107 ExprMethodCall(i, ref tps, ref args) => {
1108 let tps = tps.iter().map(|x| lower_ty(lctx, x)).collect();
1109 let args = args.iter().map(|x| lower_expr(lctx, x)).collect();
1110 hir::ExprMethodCall(respan(i.span, i.node.name), tps, args)
1112 ExprBinary(binop, ref lhs, ref rhs) => {
1113 let binop = lower_binop(lctx, binop);
1114 let lhs = lower_expr(lctx, lhs);
1115 let rhs = lower_expr(lctx, rhs);
1116 hir::ExprBinary(binop, lhs, rhs)
1118 ExprUnary(op, ref ohs) => {
1119 let op = lower_unop(lctx, op);
1120 let ohs = lower_expr(lctx, ohs);
1121 hir::ExprUnary(op, ohs)
1123 ExprLit(ref l) => hir::ExprLit(P((**l).clone())),
1124 ExprCast(ref expr, ref ty) => {
1125 let expr = lower_expr(lctx, expr);
1126 hir::ExprCast(expr, lower_ty(lctx, ty))
1128 ExprAddrOf(m, ref ohs) => {
1129 let m = lower_mutability(lctx, m);
1130 let ohs = lower_expr(lctx, ohs);
1131 hir::ExprAddrOf(m, ohs)
1133 // More complicated than you might expect because the else branch
1134 // might be `if let`.
1135 ExprIf(ref cond, ref blk, ref else_opt) => {
1136 let else_opt = else_opt.as_ref().map(|els| {
1139 cache_ids(lctx, e.id, |lctx| {
1140 // wrap the if-let expr in a block
1141 let span = els.span;
1142 let els = lower_expr(lctx, els);
1143 let id = lctx.next_id();
1144 let blk = P(hir::Block {
1148 rules: hir::DefaultBlock,
1151 expr_block(lctx, blk, None)
1154 _ => lower_expr(lctx, els),
1158 hir::ExprIf(lower_expr(lctx, cond), lower_block(lctx, blk), else_opt)
1160 ExprWhile(ref cond, ref body, opt_ident) => {
1161 hir::ExprWhile(lower_expr(lctx, cond), lower_block(lctx, body),
1162 opt_ident.map(|ident| lower_ident(lctx, ident)))
1164 ExprLoop(ref body, opt_ident) => {
1165 hir::ExprLoop(lower_block(lctx, body),
1166 opt_ident.map(|ident| lower_ident(lctx, ident)))
1168 ExprMatch(ref expr, ref arms) => {
1169 hir::ExprMatch(lower_expr(lctx, expr),
1170 arms.iter().map(|x| lower_arm(lctx, x)).collect(),
1171 hir::MatchSource::Normal)
1173 ExprClosure(capture_clause, ref decl, ref body) => {
1174 hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
1175 lower_fn_decl(lctx, decl),
1176 lower_block(lctx, body))
1178 ExprBlock(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
1179 ExprAssign(ref el, ref er) => {
1180 hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
1182 ExprAssignOp(op, ref el, ref er) => {
1183 hir::ExprAssignOp(lower_binop(lctx, op),
1184 lower_expr(lctx, el),
1185 lower_expr(lctx, er))
1187 ExprField(ref el, ident) => {
1188 hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
1190 ExprTupField(ref el, ident) => {
1191 hir::ExprTupField(lower_expr(lctx, el), ident)
1193 ExprIndex(ref el, ref er) => {
1194 hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
1196 ExprRange(ref e1, ref e2) => {
1197 hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)),
1198 e2.as_ref().map(|x| lower_expr(lctx, x)))
1200 ExprPath(ref qself, ref path) => {
1201 let hir_qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
1203 ty: lower_ty(lctx, ty),
1207 hir::ExprPath(hir_qself, lower_path_full(lctx, path, qself.is_none()))
1209 ExprBreak(opt_ident) => hir::ExprBreak(opt_ident.map(|sp_ident| {
1210 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1212 ExprAgain(opt_ident) => hir::ExprAgain(opt_ident.map(|sp_ident| {
1213 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1215 ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
1216 ExprInlineAsm(InlineAsm {
1226 }) => hir::ExprInlineAsm(hir::InlineAsm {
1227 inputs: inputs.iter()
1228 .map(|&(ref c, ref input)| (c.clone(), lower_expr(lctx, input)))
1230 outputs: outputs.iter()
1232 hir::InlineAsmOutput {
1233 constraint: out.constraint.clone(),
1234 expr: lower_expr(lctx, &out.expr),
1236 is_indirect: out.is_indirect,
1241 asm_str_style: asm_str_style,
1242 clobbers: clobbers.clone(),
1244 alignstack: alignstack,
1248 ExprStruct(ref path, ref fields, ref maybe_expr) => {
1249 hir::ExprStruct(lower_path(lctx, path),
1250 fields.iter().map(|x| lower_field(lctx, x)).collect(),
1251 maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
1253 ExprParen(ref ex) => {
1254 // merge attributes into the inner expression.
1255 return lower_expr(lctx, ex).map(|mut ex| {
1256 ex.attrs.update(|attrs| {
1257 attrs.prepend(e.attrs.clone())
1263 // Desugar ExprIfLet
1264 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
1265 ExprIfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
1268 // match <sub_expr> {
1270 // [_ if <else_opt_if_cond> => <else_opt_if_body>,]
1271 // _ => [<else_opt> | ()]
1274 return cache_ids(lctx, e.id, |lctx| {
1275 // `<pat> => <body>`
1277 let body = lower_block(lctx, body);
1278 let body_expr = expr_block(lctx, body, None);
1279 arm(vec![lower_pat(lctx, pat)], body_expr)
1282 // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
1283 let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
1284 let else_if_arms = {
1285 let mut arms = vec![];
1287 let else_opt_continue = else_opt.and_then(|els| {
1288 els.and_then(|els| {
1291 hir::ExprIf(cond, then, else_opt) => {
1292 let pat_under = pat_wild(lctx, e.span);
1293 arms.push(hir::Arm {
1295 pats: vec![pat_under],
1297 body: expr_block(lctx, then, None),
1299 else_opt.map(|else_opt| (else_opt, true))
1301 _ => Some((P(els), false)),
1305 match else_opt_continue {
1306 Some((e, true)) => {
1309 Some((e, false)) => {
1322 let contains_else_clause = else_opt.is_some();
1324 // `_ => [<else_opt> | ()]`
1326 let pat_under = pat_wild(lctx, e.span);
1328 else_opt.unwrap_or_else(
1329 || expr_tuple(lctx, e.span, vec![], None));
1330 arm(vec![pat_under], else_expr)
1333 let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
1335 arms.extend(else_if_arms);
1336 arms.push(else_arm);
1338 let sub_expr = lower_expr(lctx, sub_expr);
1339 // add attributes to the outer returned expr node
1342 hir::ExprMatch(sub_expr,
1344 hir::MatchSource::IfLetDesugar {
1345 contains_else_clause: contains_else_clause,
1351 // Desugar ExprWhileLet
1352 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
1353 ExprWhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
1356 // [opt_ident]: loop {
1357 // match <sub_expr> {
1363 return cache_ids(lctx, e.id, |lctx| {
1364 // `<pat> => <body>`
1366 let body = lower_block(lctx, body);
1367 let body_expr = expr_block(lctx, body, None);
1368 arm(vec![lower_pat(lctx, pat)], body_expr)
1373 let pat_under = pat_wild(lctx, e.span);
1374 let break_expr = expr_break(lctx, e.span, None);
1375 arm(vec![pat_under], break_expr)
1378 // `match <sub_expr> { ... }`
1379 let arms = vec![pat_arm, break_arm];
1380 let sub_expr = lower_expr(lctx, sub_expr);
1381 let match_expr = expr(lctx,
1383 hir::ExprMatch(sub_expr,
1385 hir::MatchSource::WhileLetDesugar),
1388 // `[opt_ident]: loop { ... }`
1389 let loop_block = block_expr(lctx, match_expr);
1390 let loop_expr = hir::ExprLoop(loop_block,
1391 opt_ident.map(|ident| lower_ident(lctx, ident)));
1392 // add attributes to the outer returned expr node
1393 expr(lctx, e.span, loop_expr, e.attrs.clone())
1397 // Desugar ExprForLoop
1398 // From: `[opt_ident]: for <pat> in <head> <body>`
1399 ExprForLoop(ref pat, ref head, ref body, opt_ident) => {
1403 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1405 // [opt_ident]: loop {
1406 // match ::std::iter::Iterator::next(&mut iter) {
1407 // ::std::option::Option::Some(<pat>) => <body>,
1408 // ::std::option::Option::None => break
1416 return cache_ids(lctx, e.id, |lctx| {
1418 let head = lower_expr(lctx, head);
1420 let iter = lctx.str_to_ident("iter");
1422 // `::std::option::Option::Some(<pat>) => <body>`
1424 let body_block = lower_block(lctx, body);
1425 let body_span = body_block.span;
1426 let body_expr = P(hir::Expr {
1428 node: hir::ExprBlock(body_block),
1432 let pat = lower_pat(lctx, pat);
1433 let some_pat = pat_some(lctx, e.span, pat);
1435 arm(vec![some_pat], body_expr)
1438 // `::std::option::Option::None => break`
1440 let break_expr = expr_break(lctx, e.span, None);
1442 arm(vec![pat_none(lctx, e.span)], break_expr)
1445 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1448 let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1450 path_global(e.span, strs)
1452 let iter = expr_ident(lctx, e.span, iter, None);
1453 let ref_mut_iter = expr_mut_addr_of(lctx, e.span, iter, None);
1454 let next_path = expr_path(lctx, next_path, None);
1455 let next_expr = expr_call(lctx,
1460 let arms = vec![pat_arm, break_arm];
1464 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
1468 // `[opt_ident]: loop { ... }`
1469 let loop_block = block_expr(lctx, match_expr);
1470 let loop_expr = hir::ExprLoop(loop_block,
1471 opt_ident.map(|ident| lower_ident(lctx, ident)));
1472 let loop_expr = expr(lctx, e.span, loop_expr, None);
1474 // `mut iter => { ... }`
1476 let iter_pat = pat_ident_binding_mode(lctx,
1479 hir::BindByValue(hir::MutMutable));
1480 arm(vec![iter_pat], loop_expr)
1483 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1484 let into_iter_expr = {
1485 let into_iter_path = {
1486 let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1488 path_global(e.span, strs)
1491 let into_iter = expr_path(lctx, into_iter_path, None);
1492 expr_call(lctx, e.span, into_iter, vec![head], None)
1495 let match_expr = expr_match(lctx,
1499 hir::MatchSource::ForLoopDesugar,
1502 // `{ let result = ...; result }`
1503 let result_ident = lctx.str_to_ident("result");
1504 let let_stmt = stmt_let(lctx, e.span, false, result_ident, match_expr, None);
1505 let result = expr_ident(lctx, e.span, result_ident, None);
1506 let block = block_all(lctx, e.span, vec![let_stmt], Some(result));
1507 // add the attributes to the outer returned expr node
1508 expr_block(lctx, block, e.attrs.clone())
1512 ExprMac(_) => panic!("Shouldn't exist here"),
1515 attrs: e.attrs.clone(),
1519 pub fn lower_stmt(lctx: &LoweringContext, s: &Stmt) -> hir::Stmt {
1521 StmtDecl(ref d, id) => {
1523 node: hir::StmtDecl(lower_decl(lctx, d), id),
1527 StmtExpr(ref e, id) => {
1529 node: hir::StmtExpr(lower_expr(lctx, e), id),
1533 StmtSemi(ref e, id) => {
1535 node: hir::StmtSemi(lower_expr(lctx, e), id),
1539 StmtMac(..) => panic!("Shouldn't exist here"),
1543 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureClause) -> hir::CaptureClause {
1545 CaptureByValue => hir::CaptureByValue,
1546 CaptureByRef => hir::CaptureByRef,
1550 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1552 Public => hir::Public,
1553 Inherited => hir::Inherited,
1557 pub fn lower_block_check_mode(lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1559 DefaultBlock => hir::DefaultBlock,
1560 UnsafeBlock(u) => hir::UnsafeBlock(lower_unsafe_source(lctx, u)),
1564 pub fn lower_binding_mode(lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1566 BindByRef(m) => hir::BindByRef(lower_mutability(lctx, m)),
1567 BindByValue(m) => hir::BindByValue(lower_mutability(lctx, m)),
1571 pub fn lower_struct_field_kind(lctx: &LoweringContext,
1572 s: &StructFieldKind)
1573 -> hir::StructFieldKind {
1575 NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(lctx, vis)),
1576 UnnamedField(vis) => hir::UnnamedField(lower_visibility(lctx, vis)),
1580 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1582 CompilerGenerated => hir::CompilerGenerated,
1583 UserProvided => hir::UserProvided,
1587 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1589 ImplPolarity::Positive => hir::ImplPolarity::Positive,
1590 ImplPolarity::Negative => hir::ImplPolarity::Negative,
1594 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1595 f: TraitBoundModifier)
1596 -> hir::TraitBoundModifier {
1598 TraitBoundModifier::None => hir::TraitBoundModifier::None,
1599 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1603 // Helper methods for building HIR.
1605 fn arm(pats: Vec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1614 fn expr_break(lctx: &LoweringContext, span: Span,
1615 attrs: ThinAttributes) -> P<hir::Expr> {
1616 expr(lctx, span, hir::ExprBreak(None), attrs)
1619 fn expr_call(lctx: &LoweringContext,
1622 args: Vec<P<hir::Expr>>,
1623 attrs: ThinAttributes)
1625 expr(lctx, span, hir::ExprCall(e, args), attrs)
1628 fn expr_ident(lctx: &LoweringContext, span: Span, id: hir::Ident,
1629 attrs: ThinAttributes) -> P<hir::Expr> {
1630 expr_path(lctx, path_ident(span, id), attrs)
1633 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>,
1634 attrs: ThinAttributes) -> P<hir::Expr> {
1635 expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e), attrs)
1638 fn expr_path(lctx: &LoweringContext, path: hir::Path,
1639 attrs: ThinAttributes) -> P<hir::Expr> {
1640 expr(lctx, path.span, hir::ExprPath(None, path), attrs)
1643 fn expr_match(lctx: &LoweringContext,
1646 arms: Vec<hir::Arm>,
1647 source: hir::MatchSource,
1648 attrs: ThinAttributes)
1650 expr(lctx, span, hir::ExprMatch(arg, arms, source), attrs)
1653 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>,
1654 attrs: ThinAttributes) -> P<hir::Expr> {
1655 expr(lctx, b.span, hir::ExprBlock(b), attrs)
1658 fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: Vec<P<hir::Expr>>,
1659 attrs: ThinAttributes) -> P<hir::Expr> {
1660 expr(lctx, sp, hir::ExprTup(exprs), attrs)
1663 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_,
1664 attrs: ThinAttributes) -> P<hir::Expr> {
1673 fn stmt_let(lctx: &LoweringContext,
1678 attrs: ThinAttributes)
1680 let pat = if mutbl {
1681 pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1683 pat_ident(lctx, sp, ident)
1685 let local = P(hir::Local {
1693 let decl = respan(sp, hir::DeclLocal(local));
1694 respan(sp, hir::StmtDecl(P(decl), lctx.next_id()))
1697 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1698 block_all(lctx, expr.span, Vec::new(), Some(expr))
1701 fn block_all(lctx: &LoweringContext,
1703 stmts: Vec<hir::Stmt>,
1704 expr: Option<P<hir::Expr>>)
1710 rules: hir::DefaultBlock,
1715 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1716 let some = std_path(lctx, &["option", "Option", "Some"]);
1717 let path = path_global(span, some);
1718 pat_enum(lctx, span, path, vec![pat])
1721 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1722 let none = std_path(lctx, &["option", "Option", "None"]);
1723 let path = path_global(span, none);
1724 pat_enum(lctx, span, path, vec![])
1727 fn pat_enum(lctx: &LoweringContext,
1730 subpats: Vec<P<hir::Pat>>)
1732 let pt = hir::PatEnum(path, Some(subpats));
1736 fn pat_ident(lctx: &LoweringContext, span: Span, ident: hir::Ident) -> P<hir::Pat> {
1737 pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1740 fn pat_ident_binding_mode(lctx: &LoweringContext,
1743 bm: hir::BindingMode)
1745 let pat_ident = hir::PatIdent(bm,
1751 pat(lctx, span, pat_ident)
1754 fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1755 pat(lctx, span, hir::PatWild)
1758 fn pat(lctx: &LoweringContext, span: Span, pat: hir::Pat_) -> P<hir::Pat> {
1766 fn path_ident(span: Span, id: hir::Ident) -> hir::Path {
1767 path(span, vec![id])
1770 fn path(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1771 path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new())
1774 fn path_global(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1775 path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new())
1778 fn path_all(sp: Span,
1780 mut idents: Vec<hir::Ident>,
1781 lifetimes: Vec<hir::Lifetime>,
1782 types: Vec<P<hir::Ty>>,
1783 bindings: Vec<hir::TypeBinding>)
1785 let last_identifier = idents.pop().unwrap();
1786 let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1790 parameters: hir::PathParameters::none(),
1794 segments.push(hir::PathSegment {
1795 identifier: last_identifier,
1796 parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1797 lifetimes: lifetimes,
1798 types: OwnedSlice::from_vec(types),
1799 bindings: OwnedSlice::from_vec(bindings),
1809 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<hir::Ident> {
1810 let mut v = Vec::new();
1811 if let Some(s) = lctx.crate_root {
1812 v.push(hir::Ident::from_name(token::intern(s)));
1814 v.extend(components.iter().map(|s| hir::Ident::from_name(token::intern(s))));
1818 // Given suffix ["b","c","d"], returns path `::std::b::c::d` when
1819 // `fld.cx.use_std`, and `::core::b::c::d` otherwise.
1820 fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path {
1821 let idents = std_path(lctx, components);
1822 path_global(span, idents)
1825 fn signal_block_expr(lctx: &LoweringContext,
1826 stmts: Vec<hir::Stmt>,
1829 rule: hir::BlockCheckMode,
1830 attrs: ThinAttributes)
1832 let id = lctx.next_id();
1849 use syntax::ast::{self, NodeId, NodeIdAssigner};
1850 use syntax::{parse, codemap};
1851 use syntax::fold::Folder;
1852 use std::cell::Cell;
1854 struct MockAssigner {
1855 next_id: Cell<NodeId>,
1859 fn new() -> MockAssigner {
1860 MockAssigner { next_id: Cell::new(0) }
1865 fn call_site(&self) -> codemap::Span;
1866 fn cfg(&self) -> ast::CrateConfig;
1867 fn ident_of(&self, st: &str) -> ast::Ident;
1868 fn name_of(&self, st: &str) -> ast::Name;
1869 fn parse_sess(&self) -> &parse::ParseSess;
1872 impl FakeExtCtxt for parse::ParseSess {
1873 fn call_site(&self) -> codemap::Span {
1875 lo: codemap::BytePos(0),
1876 hi: codemap::BytePos(0),
1877 expn_id: codemap::NO_EXPANSION,
1880 fn cfg(&self) -> ast::CrateConfig {
1883 fn ident_of(&self, st: &str) -> ast::Ident {
1884 parse::token::str_to_ident(st)
1886 fn name_of(&self, st: &str) -> ast::Name {
1887 parse::token::intern(st)
1889 fn parse_sess(&self) -> &parse::ParseSess {
1894 impl NodeIdAssigner for MockAssigner {
1895 fn next_node_id(&self) -> NodeId {
1896 let result = self.next_id.get();
1897 self.next_id.set(result + 1);
1901 fn peek_node_id(&self) -> NodeId {
1906 impl Folder for MockAssigner {
1907 fn new_id(&mut self, old_id: NodeId) -> NodeId {
1908 assert_eq!(old_id, ast::DUMMY_NODE_ID);
1914 fn test_preserves_ids() {
1915 let cx = parse::ParseSess::new();
1916 let mut assigner = MockAssigner::new();
1918 let ast_if_let = quote_expr!(&cx,
1919 if let Some(foo) = baz {
1922 let ast_if_let = assigner.fold_expr(ast_if_let);
1923 let ast_while_let = quote_expr!(&cx,
1924 while let Some(foo) = baz {
1927 let ast_while_let = assigner.fold_expr(ast_while_let);
1928 let ast_for = quote_expr!(&cx,
1932 let ast_for = assigner.fold_expr(ast_for);
1933 let ast_in = quote_expr!(&cx, in HEAP { foo() });
1934 let ast_in = assigner.fold_expr(ast_in);
1936 let lctx = LoweringContext::new(&assigner, None);
1937 let hir1 = lower_expr(&lctx, &ast_if_let);
1938 let hir2 = lower_expr(&lctx, &ast_if_let);
1939 assert!(hir1 == hir2);
1941 let hir1 = lower_expr(&lctx, &ast_while_let);
1942 let hir2 = lower_expr(&lctx, &ast_while_let);
1943 assert!(hir1 == hir2);
1945 let hir1 = lower_expr(&lctx, &ast_for);
1946 let hir2 = lower_expr(&lctx, &ast_for);
1947 assert!(hir1 == hir2);
1949 let hir1 = lower_expr(&lctx, &ast_in);
1950 let hir2 = lower_expr(&lctx, &ast_in);
1951 assert!(hir1 == hir2);