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::HashMap;
70 use syntax::codemap::{respan, Spanned, Span};
71 use syntax::owned_slice::OwnedSlice;
72 use syntax::parse::token::{self, str_to_ident};
73 use syntax::std_inject;
74 use syntax::visit::{self, Visitor};
75 use rustc_data_structures::fnv::FnvHashMap;
77 use std::cell::{Cell, RefCell};
79 pub struct LoweringContext<'a> {
80 crate_root: Option<&'static str>,
81 // Map AST ids to ids used for expanded nodes.
82 id_cache: RefCell<HashMap<NodeId, NodeId>>,
83 // Use if there are no cached ids for the current node.
84 id_assigner: &'a NodeIdAssigner,
85 // 0 == no cached id. Must be incremented to align with previous id
88 // Keep track of gensym'ed idents.
89 gensym_cache: RefCell<HashMap<(NodeId, &'static str), Ident>>,
90 // A copy of cached_id, but is also set to an id while it is being cached.
91 gensym_key: Cell<u32>,
94 impl<'a, 'hir> LoweringContext<'a> {
95 pub fn new(id_assigner: &'a NodeIdAssigner, c: Option<&Crate>) -> LoweringContext<'a> {
96 let crate_root = c.and_then(|c| {
97 if std_inject::no_core(c) {
99 } else if std_inject::no_std(c) {
107 crate_root: crate_root,
108 id_cache: RefCell::new(HashMap::new()),
109 id_assigner: id_assigner,
110 cached_id: Cell::new(0),
111 gensym_cache: RefCell::new(HashMap::new()),
112 gensym_key: Cell::new(0),
116 fn next_id(&self) -> NodeId {
117 let cached = self.cached_id.get();
119 return self.id_assigner.next_node_id();
122 self.cached_id.set(cached + 1);
126 fn str_to_ident(&self, s: &'static str) -> Ident {
127 let cached_id = self.gensym_key.get();
129 return token::gensym_ident(s);
132 let cached = self.gensym_cache.borrow().contains_key(&(cached_id, s));
134 self.gensym_cache.borrow()[&(cached_id, s)]
136 let result = token::gensym_ident(s);
137 self.gensym_cache.borrow_mut().insert((cached_id, s), result);
143 pub fn lower_view_path(lctx: &LoweringContext, view_path: &ViewPath) -> P<hir::ViewPath> {
145 node: match view_path.node {
146 ViewPathSimple(ident, ref path) => {
147 hir::ViewPathSimple(ident.name, lower_path(lctx, path))
149 ViewPathGlob(ref path) => {
150 hir::ViewPathGlob(lower_path(lctx, path))
152 ViewPathList(ref path, ref path_list_idents) => {
153 hir::ViewPathList(lower_path(lctx, path),
154 path_list_idents.iter()
155 .map(|path_list_ident| {
157 node: match path_list_ident.node {
158 PathListIdent { id, name, rename } =>
162 rename: rename.map(|x| x.name),
164 PathListMod { id, rename } =>
167 rename: rename.map(|x| x.name),
170 span: path_list_ident.span,
176 span: view_path.span,
180 pub fn lower_arm(lctx: &LoweringContext, arm: &Arm) -> hir::Arm {
182 attrs: arm.attrs.clone(),
183 pats: arm.pats.iter().map(|x| lower_pat(lctx, x)).collect(),
184 guard: arm.guard.as_ref().map(|ref x| lower_expr(lctx, x)),
185 body: lower_expr(lctx, &arm.body),
189 pub fn lower_decl(lctx: &LoweringContext, d: &Decl) -> P<hir::Decl> {
191 DeclLocal(ref l) => P(Spanned {
192 node: hir::DeclLocal(lower_local(lctx, l)),
195 DeclItem(ref it) => P(Spanned {
196 node: hir::DeclItem(lower_item_id(lctx, it)),
202 pub fn lower_ty_binding(lctx: &LoweringContext, b: &TypeBinding) -> P<hir::TypeBinding> {
206 ty: lower_ty(lctx, &b.ty),
211 pub fn lower_ty(lctx: &LoweringContext, t: &Ty) -> P<hir::Ty> {
215 TyInfer => hir::TyInfer,
216 TyVec(ref ty) => hir::TyVec(lower_ty(lctx, ty)),
217 TyPtr(ref mt) => hir::TyPtr(lower_mt(lctx, mt)),
218 TyRptr(ref region, ref mt) => {
219 hir::TyRptr(lower_opt_lifetime(lctx, region), lower_mt(lctx, mt))
222 hir::TyBareFn(P(hir::BareFnTy {
223 lifetimes: lower_lifetime_defs(lctx, &f.lifetimes),
224 unsafety: lower_unsafety(lctx, f.unsafety),
226 decl: lower_fn_decl(lctx, &f.decl),
229 TyTup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(lctx, ty)).collect()),
231 return lower_ty(lctx, ty);
233 TyPath(ref qself, ref path) => {
234 let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
236 ty: lower_ty(lctx, ty),
240 hir::TyPath(qself, lower_path(lctx, path))
242 TyObjectSum(ref ty, ref bounds) => {
243 hir::TyObjectSum(lower_ty(lctx, ty), lower_bounds(lctx, bounds))
245 TyFixedLengthVec(ref ty, ref e) => {
246 hir::TyFixedLengthVec(lower_ty(lctx, ty), lower_expr(lctx, e))
248 TyTypeof(ref expr) => {
249 hir::TyTypeof(lower_expr(lctx, expr))
251 TyPolyTraitRef(ref bounds) => {
252 hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(lctx, b)).collect())
254 TyMac(_) => panic!("TyMac should have been expanded by now."),
260 pub fn lower_foreign_mod(lctx: &LoweringContext, fm: &ForeignMod) -> hir::ForeignMod {
263 items: fm.items.iter().map(|x| lower_foreign_item(lctx, x)).collect(),
267 pub fn lower_variant(lctx: &LoweringContext, v: &Variant) -> P<hir::Variant> {
269 node: hir::Variant_ {
270 name: v.node.name.name,
271 attrs: v.node.attrs.clone(),
272 data: lower_variant_data(lctx, &v.node.data),
273 disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(lctx, e)),
279 pub fn lower_path(lctx: &LoweringContext, p: &Path) -> hir::Path {
284 .map(|&PathSegment { identifier, ref parameters }| {
286 identifier: identifier,
287 parameters: lower_path_parameters(lctx, parameters),
295 pub fn lower_path_parameters(lctx: &LoweringContext,
296 path_parameters: &PathParameters)
297 -> hir::PathParameters {
298 match *path_parameters {
299 AngleBracketedParameters(ref data) =>
300 hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(lctx, data)),
301 ParenthesizedParameters(ref data) =>
302 hir::ParenthesizedParameters(lower_parenthesized_parameter_data(lctx, data)),
306 pub fn lower_angle_bracketed_parameter_data(lctx: &LoweringContext,
307 data: &AngleBracketedParameterData)
308 -> hir::AngleBracketedParameterData {
309 let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
310 hir::AngleBracketedParameterData {
311 lifetimes: lower_lifetimes(lctx, lifetimes),
312 types: types.iter().map(|ty| lower_ty(lctx, ty)).collect(),
313 bindings: bindings.iter().map(|b| lower_ty_binding(lctx, b)).collect(),
317 pub fn lower_parenthesized_parameter_data(lctx: &LoweringContext,
318 data: &ParenthesizedParameterData)
319 -> hir::ParenthesizedParameterData {
320 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
321 hir::ParenthesizedParameterData {
322 inputs: inputs.iter().map(|ty| lower_ty(lctx, ty)).collect(),
323 output: output.as_ref().map(|ty| lower_ty(lctx, ty)),
328 pub fn lower_local(lctx: &LoweringContext, l: &Local) -> P<hir::Local> {
331 ty: l.ty.as_ref().map(|t| lower_ty(lctx, t)),
332 pat: lower_pat(lctx, &l.pat),
333 init: l.init.as_ref().map(|e| lower_expr(lctx, e)),
338 pub fn lower_explicit_self_underscore(lctx: &LoweringContext,
340 -> hir::ExplicitSelf_ {
342 SelfStatic => hir::SelfStatic,
343 SelfValue(v) => hir::SelfValue(v.name),
344 SelfRegion(ref lifetime, m, ident) => {
345 hir::SelfRegion(lower_opt_lifetime(lctx, lifetime),
346 lower_mutability(lctx, m),
349 SelfExplicit(ref typ, ident) => {
350 hir::SelfExplicit(lower_ty(lctx, typ), ident.name)
355 pub fn lower_mutability(_lctx: &LoweringContext, m: Mutability) -> hir::Mutability {
357 MutMutable => hir::MutMutable,
358 MutImmutable => hir::MutImmutable,
362 pub fn lower_explicit_self(lctx: &LoweringContext, s: &ExplicitSelf) -> hir::ExplicitSelf {
364 node: lower_explicit_self_underscore(lctx, &s.node),
369 pub fn lower_arg(lctx: &LoweringContext, arg: &Arg) -> hir::Arg {
372 pat: lower_pat(lctx, &arg.pat),
373 ty: lower_ty(lctx, &arg.ty),
377 pub fn lower_fn_decl(lctx: &LoweringContext, decl: &FnDecl) -> P<hir::FnDecl> {
379 inputs: decl.inputs.iter().map(|x| lower_arg(lctx, x)).collect(),
380 output: match decl.output {
381 Return(ref ty) => hir::Return(lower_ty(lctx, ty)),
382 DefaultReturn(span) => hir::DefaultReturn(span),
383 NoReturn(span) => hir::NoReturn(span),
385 variadic: decl.variadic,
389 pub fn lower_ty_param_bound(lctx: &LoweringContext, tpb: &TyParamBound) -> hir::TyParamBound {
391 TraitTyParamBound(ref ty, modifier) => {
392 hir::TraitTyParamBound(lower_poly_trait_ref(lctx, ty),
393 lower_trait_bound_modifier(lctx, modifier))
395 RegionTyParamBound(ref lifetime) => {
396 hir::RegionTyParamBound(lower_lifetime(lctx, lifetime))
401 pub fn lower_ty_param(lctx: &LoweringContext, tp: &TyParam) -> hir::TyParam {
405 bounds: lower_bounds(lctx, &tp.bounds),
406 default: tp.default.as_ref().map(|x| lower_ty(lctx, x)),
411 pub fn lower_ty_params(lctx: &LoweringContext,
412 tps: &OwnedSlice<TyParam>)
413 -> OwnedSlice<hir::TyParam> {
414 tps.iter().map(|tp| lower_ty_param(lctx, tp)).collect()
417 pub fn lower_lifetime(_lctx: &LoweringContext, l: &Lifetime) -> hir::Lifetime {
425 pub fn lower_lifetime_def(lctx: &LoweringContext, l: &LifetimeDef) -> hir::LifetimeDef {
427 lifetime: lower_lifetime(lctx, &l.lifetime),
428 bounds: lower_lifetimes(lctx, &l.bounds),
432 pub fn lower_lifetimes(lctx: &LoweringContext, lts: &Vec<Lifetime>) -> Vec<hir::Lifetime> {
433 lts.iter().map(|l| lower_lifetime(lctx, l)).collect()
436 pub fn lower_lifetime_defs(lctx: &LoweringContext,
437 lts: &Vec<LifetimeDef>)
438 -> Vec<hir::LifetimeDef> {
439 lts.iter().map(|l| lower_lifetime_def(lctx, l)).collect()
442 pub fn lower_opt_lifetime(lctx: &LoweringContext,
443 o_lt: &Option<Lifetime>)
444 -> Option<hir::Lifetime> {
445 o_lt.as_ref().map(|lt| lower_lifetime(lctx, lt))
448 pub fn lower_generics(lctx: &LoweringContext, g: &Generics) -> hir::Generics {
450 ty_params: lower_ty_params(lctx, &g.ty_params),
451 lifetimes: lower_lifetime_defs(lctx, &g.lifetimes),
452 where_clause: lower_where_clause(lctx, &g.where_clause),
456 pub fn lower_where_clause(lctx: &LoweringContext, wc: &WhereClause) -> hir::WhereClause {
459 predicates: wc.predicates
461 .map(|predicate| lower_where_predicate(lctx, predicate))
466 pub fn lower_where_predicate(lctx: &LoweringContext,
467 pred: &WherePredicate)
468 -> hir::WherePredicate {
470 WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
474 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
475 bound_lifetimes: lower_lifetime_defs(lctx, bound_lifetimes),
476 bounded_ty: lower_ty(lctx, bounded_ty),
477 bounds: bounds.iter().map(|x| lower_ty_param_bound(lctx, x)).collect(),
481 WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
484 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
486 lifetime: lower_lifetime(lctx, lifetime),
487 bounds: bounds.iter().map(|bound| lower_lifetime(lctx, bound)).collect(),
490 WherePredicate::EqPredicate(WhereEqPredicate{ id,
494 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
496 path: lower_path(lctx, path),
497 ty: lower_ty(lctx, ty),
504 pub fn lower_variant_data(lctx: &LoweringContext, vdata: &VariantData) -> hir::VariantData {
506 VariantData::Struct(ref fields, id) => {
507 hir::VariantData::Struct(fields.iter()
508 .map(|f| lower_struct_field(lctx, f))
512 VariantData::Tuple(ref fields, id) => {
513 hir::VariantData::Tuple(fields.iter()
514 .map(|f| lower_struct_field(lctx, f))
518 VariantData::Unit(id) => hir::VariantData::Unit(id),
522 pub fn lower_trait_ref(lctx: &LoweringContext, p: &TraitRef) -> hir::TraitRef {
524 path: lower_path(lctx, &p.path),
529 pub fn lower_poly_trait_ref(lctx: &LoweringContext, p: &PolyTraitRef) -> hir::PolyTraitRef {
531 bound_lifetimes: lower_lifetime_defs(lctx, &p.bound_lifetimes),
532 trait_ref: lower_trait_ref(lctx, &p.trait_ref),
537 pub fn lower_struct_field(lctx: &LoweringContext, f: &StructField) -> hir::StructField {
539 node: hir::StructField_ {
541 kind: lower_struct_field_kind(lctx, &f.node.kind),
542 ty: lower_ty(lctx, &f.node.ty),
543 attrs: f.node.attrs.clone(),
549 pub fn lower_field(lctx: &LoweringContext, f: &Field) -> hir::Field {
551 name: respan(f.ident.span, f.ident.node.name),
552 expr: lower_expr(lctx, &f.expr),
557 pub fn lower_mt(lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy {
559 ty: lower_ty(lctx, &mt.ty),
560 mutbl: lower_mutability(lctx, mt.mutbl),
564 pub fn lower_opt_bounds(lctx: &LoweringContext,
565 b: &Option<OwnedSlice<TyParamBound>>)
566 -> Option<OwnedSlice<hir::TyParamBound>> {
567 b.as_ref().map(|ref bounds| lower_bounds(lctx, bounds))
570 fn lower_bounds(lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParamBounds {
571 bounds.iter().map(|bound| lower_ty_param_bound(lctx, bound)).collect()
574 pub fn lower_block(lctx: &LoweringContext, b: &Block) -> P<hir::Block> {
577 stmts: b.stmts.iter().map(|s| lower_stmt(lctx, s)).collect(),
578 expr: b.expr.as_ref().map(|ref x| lower_expr(lctx, x)),
579 rules: lower_block_check_mode(lctx, &b.rules),
584 pub fn lower_item_underscore(lctx: &LoweringContext, i: &Item_) -> hir::Item_ {
586 ItemExternCrate(string) => hir::ItemExternCrate(string),
587 ItemUse(ref view_path) => {
588 hir::ItemUse(lower_view_path(lctx, view_path))
590 ItemStatic(ref t, m, ref e) => {
591 hir::ItemStatic(lower_ty(lctx, t),
592 lower_mutability(lctx, m),
595 ItemConst(ref t, ref e) => {
596 hir::ItemConst(lower_ty(lctx, t), lower_expr(lctx, e))
598 ItemFn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
599 hir::ItemFn(lower_fn_decl(lctx, decl),
600 lower_unsafety(lctx, unsafety),
601 lower_constness(lctx, constness),
603 lower_generics(lctx, generics),
604 lower_block(lctx, body))
606 ItemMod(ref m) => hir::ItemMod(lower_mod(lctx, m)),
607 ItemForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(lctx, nm)),
608 ItemTy(ref t, ref generics) => {
609 hir::ItemTy(lower_ty(lctx, t), lower_generics(lctx, generics))
611 ItemEnum(ref enum_definition, ref generics) => {
612 hir::ItemEnum(hir::EnumDef {
613 variants: enum_definition.variants
615 .map(|x| lower_variant(lctx, x))
618 lower_generics(lctx, generics))
620 ItemStruct(ref struct_def, ref generics) => {
621 let struct_def = lower_variant_data(lctx, struct_def);
622 hir::ItemStruct(struct_def, lower_generics(lctx, generics))
624 ItemDefaultImpl(unsafety, ref trait_ref) => {
625 hir::ItemDefaultImpl(lower_unsafety(lctx, unsafety),
626 lower_trait_ref(lctx, trait_ref))
628 ItemImpl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
629 let new_impl_items = impl_items.iter()
630 .map(|item| lower_impl_item(lctx, item))
632 let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(lctx, trait_ref));
633 hir::ItemImpl(lower_unsafety(lctx, unsafety),
634 lower_impl_polarity(lctx, polarity),
635 lower_generics(lctx, generics),
640 ItemTrait(unsafety, ref generics, ref bounds, ref items) => {
641 let bounds = lower_bounds(lctx, bounds);
642 let items = items.iter().map(|item| lower_trait_item(lctx, item)).collect();
643 hir::ItemTrait(lower_unsafety(lctx, unsafety),
644 lower_generics(lctx, generics),
648 ItemMac(_) => panic!("Shouldn't still be around"),
652 pub fn lower_trait_item(lctx: &LoweringContext, i: &TraitItem) -> P<hir::TraitItem> {
656 attrs: i.attrs.clone(),
658 ConstTraitItem(ref ty, ref default) => {
659 hir::ConstTraitItem(lower_ty(lctx, ty),
660 default.as_ref().map(|x| lower_expr(lctx, x)))
662 MethodTraitItem(ref sig, ref body) => {
663 hir::MethodTraitItem(lower_method_sig(lctx, sig),
664 body.as_ref().map(|x| lower_block(lctx, x)))
666 TypeTraitItem(ref bounds, ref default) => {
667 hir::TypeTraitItem(lower_bounds(lctx, bounds),
668 default.as_ref().map(|x| lower_ty(lctx, x)))
675 pub fn lower_impl_item(lctx: &LoweringContext, i: &ImplItem) -> P<hir::ImplItem> {
679 attrs: i.attrs.clone(),
680 vis: lower_visibility(lctx, i.vis),
682 ImplItemKind::Const(ref ty, ref expr) => {
683 hir::ImplItemKind::Const(lower_ty(lctx, ty), lower_expr(lctx, expr))
685 ImplItemKind::Method(ref sig, ref body) => {
686 hir::ImplItemKind::Method(lower_method_sig(lctx, sig), lower_block(lctx, body))
688 ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(lower_ty(lctx, ty)),
689 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
695 pub fn lower_mod(lctx: &LoweringContext, m: &Mod) -> hir::Mod {
698 item_ids: m.items.iter().map(|x| lower_item_id(lctx, x)).collect(),
702 struct ItemLowerer<'lcx, 'interner: 'lcx> {
703 items: FnvHashMap<NodeId, hir::Item>,
704 lctx: &'lcx LoweringContext<'interner>,
707 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
708 fn visit_item(&mut self, item: &'lcx Item) {
709 self.items.insert(item.id, lower_item(self.lctx, item));
710 visit::walk_item(self, item);
714 pub fn lower_crate(lctx: &LoweringContext, c: &Crate) -> hir::Crate {
716 let mut item_lowerer = ItemLowerer { items: FnvHashMap(), lctx: lctx };
717 visit::walk_crate(&mut item_lowerer, c);
722 module: lower_mod(lctx, &c.module),
723 attrs: c.attrs.clone(),
724 config: c.config.clone(),
726 exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(lctx, m)).collect(),
731 pub fn lower_macro_def(_lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef {
734 attrs: m.attrs.clone(),
737 imported_from: m.imported_from.map(|x| x.name),
739 use_locally: m.use_locally,
740 allow_internal_unstable: m.allow_internal_unstable,
741 body: m.body.clone(),
745 pub fn lower_item_id(_lctx: &LoweringContext, i: &Item) -> hir::ItemId {
746 hir::ItemId { id: i.id }
749 pub fn lower_item(lctx: &LoweringContext, i: &Item) -> hir::Item {
750 let node = lower_item_underscore(lctx, &i.node);
755 attrs: i.attrs.clone(),
757 vis: lower_visibility(lctx, i.vis),
762 pub fn lower_foreign_item(lctx: &LoweringContext, i: &ForeignItem) -> P<hir::ForeignItem> {
766 attrs: i.attrs.clone(),
768 ForeignItemFn(ref fdec, ref generics) => {
769 hir::ForeignItemFn(lower_fn_decl(lctx, fdec), lower_generics(lctx, generics))
771 ForeignItemStatic(ref t, m) => {
772 hir::ForeignItemStatic(lower_ty(lctx, t), m)
775 vis: lower_visibility(lctx, i.vis),
780 pub fn lower_method_sig(lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig {
782 generics: lower_generics(lctx, &sig.generics),
784 explicit_self: lower_explicit_self(lctx, &sig.explicit_self),
785 unsafety: lower_unsafety(lctx, sig.unsafety),
786 constness: lower_constness(lctx, sig.constness),
787 decl: lower_fn_decl(lctx, &sig.decl),
791 pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety {
793 Unsafety::Unsafe => hir::Unsafety::Unsafe,
794 Unsafety::Normal => hir::Unsafety::Normal,
798 pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness {
800 Constness::Const => hir::Constness::Const,
801 Constness::NotConst => hir::Constness::NotConst,
805 pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp {
807 UnDeref => hir::UnDeref,
813 pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp {
823 BiBitXor => hir::BiBitXor,
824 BiBitAnd => hir::BiBitAnd,
825 BiBitOr => hir::BiBitOr,
839 pub fn lower_pat(lctx: &LoweringContext, p: &Pat) -> P<hir::Pat> {
843 PatWild => hir::PatWild,
844 PatIdent(ref binding_mode, pth1, ref sub) => {
845 hir::PatIdent(lower_binding_mode(lctx, binding_mode),
847 sub.as_ref().map(|x| lower_pat(lctx, x)))
849 PatLit(ref e) => hir::PatLit(lower_expr(lctx, e)),
850 PatEnum(ref pth, ref pats) => {
851 hir::PatEnum(lower_path(lctx, pth),
853 .map(|pats| pats.iter().map(|x| lower_pat(lctx, x)).collect()))
855 PatQPath(ref qself, ref pth) => {
856 let qself = hir::QSelf {
857 ty: lower_ty(lctx, &qself.ty),
858 position: qself.position,
860 hir::PatQPath(qself, lower_path(lctx, pth))
862 PatStruct(ref pth, ref fields, etc) => {
863 let pth = lower_path(lctx, pth);
864 let fs = fields.iter()
868 node: hir::FieldPat {
869 name: f.node.ident.name,
870 pat: lower_pat(lctx, &f.node.pat),
871 is_shorthand: f.node.is_shorthand,
876 hir::PatStruct(pth, fs, etc)
878 PatTup(ref elts) => hir::PatTup(elts.iter().map(|x| lower_pat(lctx, x)).collect()),
879 PatBox(ref inner) => hir::PatBox(lower_pat(lctx, inner)),
880 PatRegion(ref inner, mutbl) => {
881 hir::PatRegion(lower_pat(lctx, inner), lower_mutability(lctx, mutbl))
883 PatRange(ref e1, ref e2) => {
884 hir::PatRange(lower_expr(lctx, e1), lower_expr(lctx, e2))
886 PatVec(ref before, ref slice, ref after) => {
887 hir::PatVec(before.iter().map(|x| lower_pat(lctx, x)).collect(),
888 slice.as_ref().map(|x| lower_pat(lctx, x)),
889 after.iter().map(|x| lower_pat(lctx, x)).collect())
891 PatMac(_) => panic!("Shouldn't exist here"),
897 // Utility fn for setting and unsetting the cached id.
898 fn cache_ids<'a, OP, R>(lctx: &LoweringContext, expr_id: NodeId, op: OP) -> R
899 where OP: FnOnce(&LoweringContext) -> R
901 // Only reset the id if it was previously 0, i.e., was not cached.
902 // If it was cached, we are in a nested node, but our id count will
903 // still count towards the parent's count.
904 let reset_cached_id = lctx.cached_id.get() == 0;
907 let id_cache: &mut HashMap<_, _> = &mut lctx.id_cache.borrow_mut();
909 if id_cache.contains_key(&expr_id) {
910 let cached_id = lctx.cached_id.get();
912 // We're entering a node where we need to track ids, but are not
914 lctx.cached_id.set(id_cache[&expr_id]);
915 lctx.gensym_key.set(id_cache[&expr_id]);
917 // We're already tracking - check that the tracked id is the same
918 // as the expected id.
919 assert!(cached_id == id_cache[&expr_id], "id mismatch");
922 let next_id = lctx.id_assigner.peek_node_id();
923 id_cache.insert(expr_id, next_id);
924 lctx.gensym_key.set(next_id);
928 let result = op(lctx);
931 lctx.cached_id.set(0);
932 lctx.gensym_key.set(0);
938 pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
943 // Eventually a desugaring for `box EXPR`
944 // (similar to the desugaring above for `in PLACE BLOCK`)
945 // should go here, desugaring
949 // let mut place = BoxPlace::make_place();
950 // let raw_place = Place::pointer(&mut place);
951 // let value = $value;
953 // ::std::ptr::write(raw_place, value);
954 // Boxed::finalize(place)
957 // But for now there are type-inference issues doing that.
959 hir::ExprBox(lower_expr(lctx, e))
962 // Desugar ExprBox: `in (PLACE) EXPR`
963 ExprInPlace(ref placer, ref value_expr) => {
967 // let mut place = Placer::make_place(p);
968 // let raw_place = Place::pointer(&mut place);
970 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
971 // InPlace::finalize(place)
973 return cache_ids(lctx, e.id, |lctx| {
974 let placer_expr = lower_expr(lctx, placer);
975 let value_expr = lower_expr(lctx, value_expr);
977 let placer_ident = lctx.str_to_ident("placer");
978 let place_ident = lctx.str_to_ident("place");
979 let p_ptr_ident = lctx.str_to_ident("p_ptr");
981 let make_place = ["ops", "Placer", "make_place"];
982 let place_pointer = ["ops", "Place", "pointer"];
983 let move_val_init = ["intrinsics", "move_val_init"];
984 let inplace_finalize = ["ops", "InPlace", "finalize"];
986 let make_call = |lctx: &LoweringContext, p, args| {
987 let path = core_path(lctx, e.span, p);
988 let path = expr_path(lctx, path);
989 expr_call(lctx, e.span, path, args)
992 let mk_stmt_let = |lctx: &LoweringContext, bind, expr| {
993 stmt_let(lctx, e.span, false, bind, expr)
996 let mk_stmt_let_mut = |lctx: &LoweringContext, bind, expr| {
997 stmt_let(lctx, e.span, true, bind, expr)
1000 // let placer = <placer_expr> ;
1002 let placer_expr = signal_block_expr(lctx,
1006 hir::PopUnstableBlock);
1007 mk_stmt_let(lctx, placer_ident, placer_expr)
1010 // let mut place = Placer::make_place(placer);
1012 let placer = expr_ident(lctx, e.span, placer_ident);
1013 let call = make_call(lctx, &make_place, vec![placer]);
1014 mk_stmt_let_mut(lctx, place_ident, call)
1017 // let p_ptr = Place::pointer(&mut place);
1019 let agent = expr_ident(lctx, e.span, place_ident);
1020 let args = vec![expr_mut_addr_of(lctx, e.span, agent)];
1021 let call = make_call(lctx, &place_pointer, args);
1022 mk_stmt_let(lctx, p_ptr_ident, call)
1025 // pop_unsafe!(EXPR));
1026 let pop_unsafe_expr = {
1027 let value_expr = signal_block_expr(lctx,
1031 hir::PopUnstableBlock);
1032 signal_block_expr(lctx,
1036 hir::PopUnsafeBlock(hir::CompilerGenerated))
1040 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1041 // InPlace::finalize(place)
1044 let ptr = expr_ident(lctx, e.span, p_ptr_ident);
1045 let call_move_val_init =
1047 make_call(lctx, &move_val_init, vec![ptr, pop_unsafe_expr]),
1049 let call_move_val_init = respan(e.span, call_move_val_init);
1051 let place = expr_ident(lctx, e.span, place_ident);
1052 let call = make_call(lctx, &inplace_finalize, vec![place]);
1053 signal_block_expr(lctx,
1054 vec![P(call_move_val_init)],
1057 hir::PushUnsafeBlock(hir::CompilerGenerated))
1060 signal_block_expr(lctx,
1064 hir::PushUnstableBlock)
1068 ExprVec(ref exprs) => {
1069 hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect())
1071 ExprRepeat(ref expr, ref count) => {
1072 let expr = lower_expr(lctx, expr);
1073 let count = lower_expr(lctx, count);
1074 hir::ExprRepeat(expr, count)
1076 ExprTup(ref elts) => {
1077 hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect())
1079 ExprCall(ref f, ref args) => {
1080 let f = lower_expr(lctx, f);
1081 hir::ExprCall(f, args.iter().map(|x| lower_expr(lctx, x)).collect())
1083 ExprMethodCall(i, ref tps, ref args) => {
1084 let tps = tps.iter().map(|x| lower_ty(lctx, x)).collect();
1085 let args = args.iter().map(|x| lower_expr(lctx, x)).collect();
1086 hir::ExprMethodCall(respan(i.span, i.node.name), tps, args)
1088 ExprBinary(binop, ref lhs, ref rhs) => {
1089 let binop = lower_binop(lctx, binop);
1090 let lhs = lower_expr(lctx, lhs);
1091 let rhs = lower_expr(lctx, rhs);
1092 hir::ExprBinary(binop, lhs, rhs)
1094 ExprUnary(op, ref ohs) => {
1095 let op = lower_unop(lctx, op);
1096 let ohs = lower_expr(lctx, ohs);
1097 hir::ExprUnary(op, ohs)
1099 ExprLit(ref l) => hir::ExprLit(P((**l).clone())),
1100 ExprCast(ref expr, ref ty) => {
1101 let expr = lower_expr(lctx, expr);
1102 hir::ExprCast(expr, lower_ty(lctx, ty))
1104 ExprAddrOf(m, ref ohs) => {
1105 let m = lower_mutability(lctx, m);
1106 let ohs = lower_expr(lctx, ohs);
1107 hir::ExprAddrOf(m, ohs)
1109 // More complicated than you might expect because the else branch
1110 // might be `if let`.
1111 ExprIf(ref cond, ref blk, ref else_opt) => {
1112 let else_opt = else_opt.as_ref().map(|els| {
1115 cache_ids(lctx, e.id, |lctx| {
1116 // wrap the if-let expr in a block
1117 let span = els.span;
1118 let els = lower_expr(lctx, els);
1119 let id = lctx.next_id();
1120 let blk = P(hir::Block {
1124 rules: hir::DefaultBlock,
1127 expr_block(lctx, blk)
1130 _ => lower_expr(lctx, els),
1134 hir::ExprIf(lower_expr(lctx, cond), lower_block(lctx, blk), else_opt)
1136 ExprWhile(ref cond, ref body, opt_ident) => {
1137 hir::ExprWhile(lower_expr(lctx, cond), lower_block(lctx, body), opt_ident)
1139 ExprLoop(ref body, opt_ident) => {
1140 hir::ExprLoop(lower_block(lctx, body), opt_ident)
1142 ExprMatch(ref expr, ref arms) => {
1143 hir::ExprMatch(lower_expr(lctx, expr),
1144 arms.iter().map(|x| lower_arm(lctx, x)).collect(),
1145 hir::MatchSource::Normal)
1147 ExprClosure(capture_clause, ref decl, ref body) => {
1148 hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
1149 lower_fn_decl(lctx, decl),
1150 lower_block(lctx, body))
1152 ExprBlock(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
1153 ExprAssign(ref el, ref er) => {
1154 hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
1156 ExprAssignOp(op, ref el, ref er) => {
1157 hir::ExprAssignOp(lower_binop(lctx, op),
1158 lower_expr(lctx, el),
1159 lower_expr(lctx, er))
1161 ExprField(ref el, ident) => {
1162 hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
1164 ExprTupField(ref el, ident) => {
1165 hir::ExprTupField(lower_expr(lctx, el), ident)
1167 ExprIndex(ref el, ref er) => {
1168 hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
1170 ExprRange(ref e1, ref e2) => {
1171 hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)),
1172 e2.as_ref().map(|x| lower_expr(lctx, x)))
1174 ExprPath(ref qself, ref path) => {
1175 let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
1177 ty: lower_ty(lctx, ty),
1181 hir::ExprPath(qself, lower_path(lctx, path))
1183 ExprBreak(opt_ident) => hir::ExprBreak(opt_ident),
1184 ExprAgain(opt_ident) => hir::ExprAgain(opt_ident),
1185 ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
1186 ExprInlineAsm(InlineAsm {
1196 }) => hir::ExprInlineAsm(hir::InlineAsm {
1197 inputs: inputs.iter()
1198 .map(|&(ref c, ref input)| (c.clone(), lower_expr(lctx, input)))
1200 outputs: outputs.iter()
1201 .map(|&(ref c, ref out, ref is_rw)| {
1202 (c.clone(), lower_expr(lctx, out), *is_rw)
1206 asm_str_style: asm_str_style,
1207 clobbers: clobbers.clone(),
1209 alignstack: alignstack,
1213 ExprStruct(ref path, ref fields, ref maybe_expr) => {
1214 hir::ExprStruct(lower_path(lctx, path),
1215 fields.iter().map(|x| lower_field(lctx, x)).collect(),
1216 maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
1218 ExprParen(ref ex) => {
1219 return lower_expr(lctx, ex);
1222 // Desugar ExprIfLet
1223 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
1224 ExprIfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
1227 // match <sub_expr> {
1229 // [_ if <else_opt_if_cond> => <else_opt_if_body>,]
1230 // _ => [<else_opt> | ()]
1233 return cache_ids(lctx, e.id, |lctx| {
1234 // `<pat> => <body>`
1236 let body = lower_block(lctx, body);
1237 let body_expr = expr_block(lctx, body);
1238 arm(vec![lower_pat(lctx, pat)], body_expr)
1241 // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
1242 let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
1243 let else_if_arms = {
1244 let mut arms = vec![];
1246 let else_opt_continue = else_opt.and_then(|els| {
1247 els.and_then(|els| {
1250 hir::ExprIf(cond, then, else_opt) => {
1251 let pat_under = pat_wild(lctx, e.span);
1252 arms.push(hir::Arm {
1254 pats: vec![pat_under],
1256 body: expr_block(lctx, then),
1258 else_opt.map(|else_opt| (else_opt, true))
1260 _ => Some((P(els), false)),
1264 match else_opt_continue {
1265 Some((e, true)) => {
1268 Some((e, false)) => {
1281 let contains_else_clause = else_opt.is_some();
1283 // `_ => [<else_opt> | ()]`
1285 let pat_under = pat_wild(lctx, e.span);
1287 else_opt.unwrap_or_else(
1288 || expr_tuple(lctx, e.span, vec![]));
1289 arm(vec![pat_under], else_expr)
1292 let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
1294 arms.extend(else_if_arms);
1295 arms.push(else_arm);
1297 let sub_expr = lower_expr(lctx, sub_expr);
1300 hir::ExprMatch(sub_expr,
1302 hir::MatchSource::IfLetDesugar {
1303 contains_else_clause: contains_else_clause,
1308 // Desugar ExprWhileLet
1309 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
1310 ExprWhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
1313 // [opt_ident]: loop {
1314 // match <sub_expr> {
1320 return cache_ids(lctx, e.id, |lctx| {
1321 // `<pat> => <body>`
1323 let body = lower_block(lctx, body);
1324 let body_expr = expr_block(lctx, body);
1325 arm(vec![lower_pat(lctx, pat)], body_expr)
1330 let pat_under = pat_wild(lctx, e.span);
1331 let break_expr = expr_break(lctx, e.span);
1332 arm(vec![pat_under], break_expr)
1335 // `match <sub_expr> { ... }`
1336 let arms = vec![pat_arm, break_arm];
1337 let sub_expr = lower_expr(lctx, sub_expr);
1338 let match_expr = expr(lctx,
1340 hir::ExprMatch(sub_expr,
1342 hir::MatchSource::WhileLetDesugar));
1344 // `[opt_ident]: loop { ... }`
1345 let loop_block = block_expr(lctx, match_expr);
1346 expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident))
1350 // Desugar ExprForLoop
1351 // From: `[opt_ident]: for <pat> in <head> <body>`
1352 ExprForLoop(ref pat, ref head, ref body, opt_ident) => {
1356 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1358 // [opt_ident]: loop {
1359 // match ::std::iter::Iterator::next(&mut iter) {
1360 // ::std::option::Option::Some(<pat>) => <body>,
1361 // ::std::option::Option::None => break
1369 return cache_ids(lctx, e.id, |lctx| {
1371 let head = lower_expr(lctx, head);
1373 let iter = lctx.str_to_ident("iter");
1375 // `::std::option::Option::Some(<pat>) => <body>`
1377 let body_block = lower_block(lctx, body);
1378 let body_span = body_block.span;
1379 let body_expr = P(hir::Expr {
1381 node: hir::ExprBlock(body_block),
1384 let pat = lower_pat(lctx, pat);
1385 let some_pat = pat_some(lctx, e.span, pat);
1387 arm(vec![some_pat], body_expr)
1390 // `::std::option::Option::None => break`
1392 let break_expr = expr_break(lctx, e.span);
1394 arm(vec![pat_none(lctx, e.span)], break_expr)
1397 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1400 let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1402 path_global(e.span, strs)
1404 let iter = expr_ident(lctx, e.span, iter);
1405 let ref_mut_iter = expr_mut_addr_of(lctx, e.span, iter);
1406 let next_path = expr_path(lctx, next_path);
1407 let next_expr = expr_call(lctx, e.span, next_path, vec![ref_mut_iter]);
1408 let arms = vec![pat_arm, break_arm];
1412 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar))
1415 // `[opt_ident]: loop { ... }`
1416 let loop_block = block_expr(lctx, match_expr);
1417 let loop_expr = expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident));
1419 // `mut iter => { ... }`
1421 let iter_pat = pat_ident_binding_mode(lctx,
1424 hir::BindByValue(hir::MutMutable));
1425 arm(vec![iter_pat], loop_expr)
1428 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1429 let into_iter_expr = {
1430 let into_iter_path = {
1431 let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1433 path_global(e.span, strs)
1436 let into_iter = expr_path(lctx, into_iter_path);
1437 expr_call(lctx, e.span, into_iter, vec![head])
1440 let match_expr = expr_match(lctx,
1444 hir::MatchSource::ForLoopDesugar);
1446 // `{ let result = ...; result }`
1447 let result_ident = lctx.str_to_ident("result");
1448 let let_stmt = stmt_let(lctx, e.span, false, result_ident, match_expr);
1449 let result = expr_ident(lctx, e.span, result_ident);
1450 let block = block_all(lctx, e.span, vec![let_stmt], Some(result));
1451 expr_block(lctx, block)
1455 ExprMac(_) => panic!("Shouldn't exist here"),
1461 pub fn lower_stmt(lctx: &LoweringContext, s: &Stmt) -> P<hir::Stmt> {
1463 StmtDecl(ref d, id) => {
1465 node: hir::StmtDecl(lower_decl(lctx, d), id),
1469 StmtExpr(ref e, id) => {
1471 node: hir::StmtExpr(lower_expr(lctx, e), id),
1475 StmtSemi(ref e, id) => {
1477 node: hir::StmtSemi(lower_expr(lctx, e), id),
1481 StmtMac(..) => panic!("Shouldn't exist here"),
1485 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureClause) -> hir::CaptureClause {
1487 CaptureByValue => hir::CaptureByValue,
1488 CaptureByRef => hir::CaptureByRef,
1492 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1494 Public => hir::Public,
1495 Inherited => hir::Inherited,
1499 pub fn lower_block_check_mode(lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1501 DefaultBlock => hir::DefaultBlock,
1502 UnsafeBlock(u) => hir::UnsafeBlock(lower_unsafe_source(lctx, u)),
1506 pub fn lower_binding_mode(lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1508 BindByRef(m) => hir::BindByRef(lower_mutability(lctx, m)),
1509 BindByValue(m) => hir::BindByValue(lower_mutability(lctx, m)),
1513 pub fn lower_struct_field_kind(lctx: &LoweringContext,
1514 s: &StructFieldKind)
1515 -> hir::StructFieldKind {
1517 NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(lctx, vis)),
1518 UnnamedField(vis) => hir::UnnamedField(lower_visibility(lctx, vis)),
1522 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1524 CompilerGenerated => hir::CompilerGenerated,
1525 UserProvided => hir::UserProvided,
1529 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1531 ImplPolarity::Positive => hir::ImplPolarity::Positive,
1532 ImplPolarity::Negative => hir::ImplPolarity::Negative,
1536 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1537 f: TraitBoundModifier)
1538 -> hir::TraitBoundModifier {
1540 TraitBoundModifier::None => hir::TraitBoundModifier::None,
1541 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1545 // Helper methods for building HIR.
1547 fn arm(pats: Vec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1556 fn expr_break(lctx: &LoweringContext, span: Span) -> P<hir::Expr> {
1557 expr(lctx, span, hir::ExprBreak(None))
1560 fn expr_call(lctx: &LoweringContext,
1563 args: Vec<P<hir::Expr>>)
1565 expr(lctx, span, hir::ExprCall(e, args))
1568 fn expr_ident(lctx: &LoweringContext, span: Span, id: Ident) -> P<hir::Expr> {
1569 expr_path(lctx, path_ident(span, id))
1572 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>) -> P<hir::Expr> {
1573 expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e))
1576 fn expr_path(lctx: &LoweringContext, path: hir::Path) -> P<hir::Expr> {
1577 expr(lctx, path.span, hir::ExprPath(None, path))
1580 fn expr_match(lctx: &LoweringContext,
1583 arms: Vec<hir::Arm>,
1584 source: hir::MatchSource)
1586 expr(lctx, span, hir::ExprMatch(arg, arms, source))
1589 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>) -> P<hir::Expr> {
1590 expr(lctx, b.span, hir::ExprBlock(b))
1593 fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: Vec<P<hir::Expr>>) -> P<hir::Expr> {
1594 expr(lctx, sp, hir::ExprTup(exprs))
1597 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_) -> P<hir::Expr> {
1605 fn stmt_let(lctx: &LoweringContext,
1611 let pat = if mutbl {
1612 pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1614 pat_ident(lctx, sp, ident)
1616 let local = P(hir::Local {
1623 let decl = respan(sp, hir::DeclLocal(local));
1624 P(respan(sp, hir::StmtDecl(P(decl), lctx.next_id())))
1627 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1628 block_all(lctx, expr.span, Vec::new(), Some(expr))
1631 fn block_all(lctx: &LoweringContext,
1633 stmts: Vec<P<hir::Stmt>>,
1634 expr: Option<P<hir::Expr>>)
1640 rules: hir::DefaultBlock,
1645 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1646 let some = std_path(lctx, &["option", "Option", "Some"]);
1647 let path = path_global(span, some);
1648 pat_enum(lctx, span, path, vec![pat])
1651 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1652 let none = std_path(lctx, &["option", "Option", "None"]);
1653 let path = path_global(span, none);
1654 pat_enum(lctx, span, path, vec![])
1657 fn pat_enum(lctx: &LoweringContext,
1660 subpats: Vec<P<hir::Pat>>)
1662 let pt = hir::PatEnum(path, Some(subpats));
1666 fn pat_ident(lctx: &LoweringContext, span: Span, ident: Ident) -> P<hir::Pat> {
1667 pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1670 fn pat_ident_binding_mode(lctx: &LoweringContext,
1673 bm: hir::BindingMode)
1675 let pat_ident = hir::PatIdent(bm,
1681 pat(lctx, span, pat_ident)
1684 fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1685 pat(lctx, span, hir::PatWild)
1688 fn pat(lctx: &LoweringContext, span: Span, pat: hir::Pat_) -> P<hir::Pat> {
1696 fn path_ident(span: Span, id: Ident) -> hir::Path {
1697 path(span, vec![id])
1700 fn path(span: Span, strs: Vec<Ident>) -> hir::Path {
1701 path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new())
1704 fn path_global(span: Span, strs: Vec<Ident>) -> hir::Path {
1705 path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new())
1708 fn path_all(sp: Span,
1710 mut idents: Vec<Ident>,
1711 lifetimes: Vec<hir::Lifetime>,
1712 types: Vec<P<hir::Ty>>,
1713 bindings: Vec<P<hir::TypeBinding>>)
1715 let last_identifier = idents.pop().unwrap();
1716 let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1720 parameters: hir::PathParameters::none(),
1724 segments.push(hir::PathSegment {
1725 identifier: last_identifier,
1726 parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1727 lifetimes: lifetimes,
1728 types: OwnedSlice::from_vec(types),
1729 bindings: OwnedSlice::from_vec(bindings),
1739 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<Ident> {
1740 let mut v = Vec::new();
1741 if let Some(s) = lctx.crate_root {
1742 v.push(str_to_ident(s));
1744 v.extend(components.iter().map(|s| str_to_ident(s)));
1748 // Given suffix ["b","c","d"], returns path `::std::b::c::d` when
1749 // `fld.cx.use_std`, and `::core::b::c::d` otherwise.
1750 fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path {
1751 let idents = std_path(lctx, components);
1752 path_global(span, idents)
1755 fn signal_block_expr(lctx: &LoweringContext,
1756 stmts: Vec<P<hir::Stmt>>,
1759 rule: hir::BlockCheckMode)
1761 let id = lctx.next_id();
1777 use syntax::ast::{self, NodeId, NodeIdAssigner};
1778 use syntax::{parse, codemap};
1779 use syntax::fold::Folder;
1780 use std::cell::Cell;
1782 struct MockAssigner {
1783 next_id: Cell<NodeId>,
1787 fn new() -> MockAssigner {
1788 MockAssigner { next_id: Cell::new(0) }
1793 fn call_site(&self) -> codemap::Span;
1794 fn cfg(&self) -> ast::CrateConfig;
1795 fn ident_of(&self, st: &str) -> ast::Ident;
1796 fn name_of(&self, st: &str) -> ast::Name;
1797 fn parse_sess(&self) -> &parse::ParseSess;
1800 impl FakeExtCtxt for parse::ParseSess {
1801 fn call_site(&self) -> codemap::Span {
1803 lo: codemap::BytePos(0),
1804 hi: codemap::BytePos(0),
1805 expn_id: codemap::NO_EXPANSION,
1808 fn cfg(&self) -> ast::CrateConfig {
1811 fn ident_of(&self, st: &str) -> ast::Ident {
1812 parse::token::str_to_ident(st)
1814 fn name_of(&self, st: &str) -> ast::Name {
1815 parse::token::intern(st)
1817 fn parse_sess(&self) -> &parse::ParseSess {
1822 impl NodeIdAssigner for MockAssigner {
1823 fn next_node_id(&self) -> NodeId {
1824 let result = self.next_id.get();
1825 self.next_id.set(result + 1);
1829 fn peek_node_id(&self) -> NodeId {
1834 impl Folder for MockAssigner {
1835 fn new_id(&mut self, old_id: NodeId) -> NodeId {
1836 assert_eq!(old_id, ast::DUMMY_NODE_ID);
1842 fn test_preserves_ids() {
1843 let cx = parse::ParseSess::new();
1844 let mut assigner = MockAssigner::new();
1846 let ast_if_let = quote_expr!(&cx,
1847 if let Some(foo) = baz {
1850 let ast_if_let = assigner.fold_expr(ast_if_let);
1851 let ast_while_let = quote_expr!(&cx,
1852 while let Some(foo) = baz {
1855 let ast_while_let = assigner.fold_expr(ast_while_let);
1856 let ast_for = quote_expr!(&cx,
1860 let ast_for = assigner.fold_expr(ast_for);
1861 let ast_in = quote_expr!(&cx, in HEAP { foo() });
1862 let ast_in = assigner.fold_expr(ast_in);
1864 let lctx = LoweringContext::new(&assigner, None);
1865 let hir1 = lower_expr(&lctx, &ast_if_let);
1866 let hir2 = lower_expr(&lctx, &ast_if_let);
1867 assert!(hir1 == hir2);
1869 let hir1 = lower_expr(&lctx, &ast_while_let);
1870 let hir2 = lower_expr(&lctx, &ast_while_let);
1871 assert!(hir1 == hir2);
1873 let hir1 = lower_expr(&lctx, &ast_for);
1874 let hir2 = lower_expr(&lctx, &ast_for);
1875 assert!(hir1 == hir2);
1877 let hir1 = lower_expr(&lctx, &ast_in);
1878 let hir2 = lower_expr(&lctx, &ast_in);
1879 assert!(hir1 == hir2);