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;
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};
76 use std::cell::{Cell, RefCell};
78 pub struct LoweringContext<'a> {
79 crate_root: Option<&'static str>,
80 // Map AST ids to ids used for expanded nodes.
81 id_cache: RefCell<HashMap<NodeId, NodeId>>,
82 // Use if there are no cached ids for the current node.
83 id_assigner: &'a NodeIdAssigner,
84 // 0 == no cached id. Must be incremented to align with previous id
87 // Keep track of gensym'ed idents.
88 gensym_cache: RefCell<HashMap<(NodeId, &'static str), Ident>>,
89 // A copy of cached_id, but is also set to an id while it is being cached.
90 gensym_key: Cell<u32>,
93 impl<'a, 'hir> LoweringContext<'a> {
94 pub fn new(id_assigner: &'a NodeIdAssigner, c: Option<&Crate>) -> LoweringContext<'a> {
95 let crate_root = c.and_then(|c| {
96 if std_inject::no_core(c) {
98 } else if std_inject::no_std(c) {
106 crate_root: crate_root,
107 id_cache: RefCell::new(HashMap::new()),
108 id_assigner: id_assigner,
109 cached_id: Cell::new(0),
110 gensym_cache: RefCell::new(HashMap::new()),
111 gensym_key: Cell::new(0),
115 fn next_id(&self) -> NodeId {
116 let cached = self.cached_id.get();
118 return self.id_assigner.next_node_id();
121 self.cached_id.set(cached + 1);
125 fn str_to_ident(&self, s: &'static str) -> Ident {
126 let cached_id = self.gensym_key.get();
128 return token::gensym_ident(s);
131 let cached = self.gensym_cache.borrow().contains_key(&(cached_id, s));
133 self.gensym_cache.borrow()[&(cached_id, s)]
135 let result = token::gensym_ident(s);
136 self.gensym_cache.borrow_mut().insert((cached_id, s), result);
142 pub fn lower_view_path(lctx: &LoweringContext, view_path: &ViewPath) -> P<hir::ViewPath> {
144 node: match view_path.node {
145 ViewPathSimple(ident, ref path) => {
146 hir::ViewPathSimple(ident.name, lower_path(lctx, path))
148 ViewPathGlob(ref path) => {
149 hir::ViewPathGlob(lower_path(lctx, path))
151 ViewPathList(ref path, ref path_list_idents) => {
152 hir::ViewPathList(lower_path(lctx, path),
153 path_list_idents.iter()
154 .map(|path_list_ident| {
156 node: match path_list_ident.node {
157 PathListIdent { id, name, rename } =>
161 rename: rename.map(|x| x.name),
163 PathListMod { id, rename } =>
166 rename: rename.map(|x| x.name),
169 span: path_list_ident.span,
175 span: view_path.span,
179 pub fn lower_arm(lctx: &LoweringContext, arm: &Arm) -> hir::Arm {
181 attrs: arm.attrs.clone(),
182 pats: arm.pats.iter().map(|x| lower_pat(lctx, x)).collect(),
183 guard: arm.guard.as_ref().map(|ref x| lower_expr(lctx, x)),
184 body: lower_expr(lctx, &arm.body),
188 pub fn lower_decl(lctx: &LoweringContext, d: &Decl) -> P<hir::Decl> {
190 DeclLocal(ref l) => P(Spanned {
191 node: hir::DeclLocal(lower_local(lctx, l)),
194 DeclItem(ref it) => P(Spanned {
195 node: hir::DeclItem(lower_item_id(lctx, it)),
201 pub fn lower_ty_binding(lctx: &LoweringContext, b: &TypeBinding) -> P<hir::TypeBinding> {
205 ty: lower_ty(lctx, &b.ty),
210 pub fn lower_ty(lctx: &LoweringContext, t: &Ty) -> P<hir::Ty> {
214 TyInfer => hir::TyInfer,
215 TyVec(ref ty) => hir::TyVec(lower_ty(lctx, ty)),
216 TyPtr(ref mt) => hir::TyPtr(lower_mt(lctx, mt)),
217 TyRptr(ref region, ref mt) => {
218 hir::TyRptr(lower_opt_lifetime(lctx, region), lower_mt(lctx, mt))
221 hir::TyBareFn(P(hir::BareFnTy {
222 lifetimes: lower_lifetime_defs(lctx, &f.lifetimes),
223 unsafety: lower_unsafety(lctx, f.unsafety),
225 decl: lower_fn_decl(lctx, &f.decl),
228 TyTup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(lctx, ty)).collect()),
230 return lower_ty(lctx, ty);
232 TyPath(ref qself, ref path) => {
233 let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
235 ty: lower_ty(lctx, ty),
239 hir::TyPath(qself, lower_path(lctx, path))
241 TyObjectSum(ref ty, ref bounds) => {
242 hir::TyObjectSum(lower_ty(lctx, ty), lower_bounds(lctx, bounds))
244 TyFixedLengthVec(ref ty, ref e) => {
245 hir::TyFixedLengthVec(lower_ty(lctx, ty), lower_expr(lctx, e))
247 TyTypeof(ref expr) => {
248 hir::TyTypeof(lower_expr(lctx, expr))
250 TyPolyTraitRef(ref bounds) => {
251 hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(lctx, b)).collect())
253 TyMac(_) => panic!("TyMac should have been expanded by now."),
259 pub fn lower_foreign_mod(lctx: &LoweringContext, fm: &ForeignMod) -> hir::ForeignMod {
262 items: fm.items.iter().map(|x| lower_foreign_item(lctx, x)).collect(),
266 pub fn lower_variant(lctx: &LoweringContext, v: &Variant) -> P<hir::Variant> {
268 node: hir::Variant_ {
269 name: v.node.name.name,
270 attrs: v.node.attrs.clone(),
271 data: lower_variant_data(lctx, &v.node.data),
272 disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(lctx, e)),
278 pub fn lower_path(lctx: &LoweringContext, p: &Path) -> hir::Path {
283 .map(|&PathSegment { identifier, ref parameters }| {
285 identifier: identifier,
286 parameters: lower_path_parameters(lctx, parameters),
294 pub fn lower_path_parameters(lctx: &LoweringContext,
295 path_parameters: &PathParameters)
296 -> hir::PathParameters {
297 match *path_parameters {
298 AngleBracketedParameters(ref data) =>
299 hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(lctx, data)),
300 ParenthesizedParameters(ref data) =>
301 hir::ParenthesizedParameters(lower_parenthesized_parameter_data(lctx, data)),
305 pub fn lower_angle_bracketed_parameter_data(lctx: &LoweringContext,
306 data: &AngleBracketedParameterData)
307 -> hir::AngleBracketedParameterData {
308 let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
309 hir::AngleBracketedParameterData {
310 lifetimes: lower_lifetimes(lctx, lifetimes),
311 types: types.iter().map(|ty| lower_ty(lctx, ty)).collect(),
312 bindings: bindings.iter().map(|b| lower_ty_binding(lctx, b)).collect(),
316 pub fn lower_parenthesized_parameter_data(lctx: &LoweringContext,
317 data: &ParenthesizedParameterData)
318 -> hir::ParenthesizedParameterData {
319 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
320 hir::ParenthesizedParameterData {
321 inputs: inputs.iter().map(|ty| lower_ty(lctx, ty)).collect(),
322 output: output.as_ref().map(|ty| lower_ty(lctx, ty)),
327 pub fn lower_local(lctx: &LoweringContext, l: &Local) -> P<hir::Local> {
330 ty: l.ty.as_ref().map(|t| lower_ty(lctx, t)),
331 pat: lower_pat(lctx, &l.pat),
332 init: l.init.as_ref().map(|e| lower_expr(lctx, e)),
337 pub fn lower_explicit_self_underscore(lctx: &LoweringContext,
339 -> hir::ExplicitSelf_ {
341 SelfStatic => hir::SelfStatic,
342 SelfValue(v) => hir::SelfValue(v.name),
343 SelfRegion(ref lifetime, m, ident) => {
344 hir::SelfRegion(lower_opt_lifetime(lctx, lifetime),
345 lower_mutability(lctx, m),
348 SelfExplicit(ref typ, ident) => {
349 hir::SelfExplicit(lower_ty(lctx, typ), ident.name)
354 pub fn lower_mutability(_lctx: &LoweringContext, m: Mutability) -> hir::Mutability {
356 MutMutable => hir::MutMutable,
357 MutImmutable => hir::MutImmutable,
361 pub fn lower_explicit_self(lctx: &LoweringContext, s: &ExplicitSelf) -> hir::ExplicitSelf {
363 node: lower_explicit_self_underscore(lctx, &s.node),
368 pub fn lower_arg(lctx: &LoweringContext, arg: &Arg) -> hir::Arg {
371 pat: lower_pat(lctx, &arg.pat),
372 ty: lower_ty(lctx, &arg.ty),
376 pub fn lower_fn_decl(lctx: &LoweringContext, decl: &FnDecl) -> P<hir::FnDecl> {
378 inputs: decl.inputs.iter().map(|x| lower_arg(lctx, x)).collect(),
379 output: match decl.output {
380 Return(ref ty) => hir::Return(lower_ty(lctx, ty)),
381 DefaultReturn(span) => hir::DefaultReturn(span),
382 NoReturn(span) => hir::NoReturn(span),
384 variadic: decl.variadic,
388 pub fn lower_ty_param_bound(lctx: &LoweringContext, tpb: &TyParamBound) -> hir::TyParamBound {
390 TraitTyParamBound(ref ty, modifier) => {
391 hir::TraitTyParamBound(lower_poly_trait_ref(lctx, ty),
392 lower_trait_bound_modifier(lctx, modifier))
394 RegionTyParamBound(ref lifetime) => {
395 hir::RegionTyParamBound(lower_lifetime(lctx, lifetime))
400 pub fn lower_ty_param(lctx: &LoweringContext, tp: &TyParam) -> hir::TyParam {
404 bounds: lower_bounds(lctx, &tp.bounds),
405 default: tp.default.as_ref().map(|x| lower_ty(lctx, x)),
410 pub fn lower_ty_params(lctx: &LoweringContext,
411 tps: &OwnedSlice<TyParam>)
412 -> OwnedSlice<hir::TyParam> {
413 tps.iter().map(|tp| lower_ty_param(lctx, tp)).collect()
416 pub fn lower_lifetime(_lctx: &LoweringContext, l: &Lifetime) -> hir::Lifetime {
424 pub fn lower_lifetime_def(lctx: &LoweringContext, l: &LifetimeDef) -> hir::LifetimeDef {
426 lifetime: lower_lifetime(lctx, &l.lifetime),
427 bounds: lower_lifetimes(lctx, &l.bounds),
431 pub fn lower_lifetimes(lctx: &LoweringContext, lts: &Vec<Lifetime>) -> Vec<hir::Lifetime> {
432 lts.iter().map(|l| lower_lifetime(lctx, l)).collect()
435 pub fn lower_lifetime_defs(lctx: &LoweringContext,
436 lts: &Vec<LifetimeDef>)
437 -> Vec<hir::LifetimeDef> {
438 lts.iter().map(|l| lower_lifetime_def(lctx, l)).collect()
441 pub fn lower_opt_lifetime(lctx: &LoweringContext,
442 o_lt: &Option<Lifetime>)
443 -> Option<hir::Lifetime> {
444 o_lt.as_ref().map(|lt| lower_lifetime(lctx, lt))
447 pub fn lower_generics(lctx: &LoweringContext, g: &Generics) -> hir::Generics {
449 ty_params: lower_ty_params(lctx, &g.ty_params),
450 lifetimes: lower_lifetime_defs(lctx, &g.lifetimes),
451 where_clause: lower_where_clause(lctx, &g.where_clause),
455 pub fn lower_where_clause(lctx: &LoweringContext, wc: &WhereClause) -> hir::WhereClause {
458 predicates: wc.predicates
460 .map(|predicate| lower_where_predicate(lctx, predicate))
465 pub fn lower_where_predicate(lctx: &LoweringContext,
466 pred: &WherePredicate)
467 -> hir::WherePredicate {
469 WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
473 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
474 bound_lifetimes: lower_lifetime_defs(lctx, bound_lifetimes),
475 bounded_ty: lower_ty(lctx, bounded_ty),
476 bounds: bounds.iter().map(|x| lower_ty_param_bound(lctx, x)).collect(),
480 WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
483 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
485 lifetime: lower_lifetime(lctx, lifetime),
486 bounds: bounds.iter().map(|bound| lower_lifetime(lctx, bound)).collect(),
489 WherePredicate::EqPredicate(WhereEqPredicate{ id,
493 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
495 path: lower_path(lctx, path),
496 ty: lower_ty(lctx, ty),
503 pub fn lower_variant_data(lctx: &LoweringContext, vdata: &VariantData) -> hir::VariantData {
505 VariantData::Struct(ref fields, id) => {
506 hir::VariantData::Struct(fields.iter()
507 .map(|f| lower_struct_field(lctx, f))
511 VariantData::Tuple(ref fields, id) => {
512 hir::VariantData::Tuple(fields.iter()
513 .map(|f| lower_struct_field(lctx, f))
517 VariantData::Unit(id) => hir::VariantData::Unit(id),
521 pub fn lower_trait_ref(lctx: &LoweringContext, p: &TraitRef) -> hir::TraitRef {
523 path: lower_path(lctx, &p.path),
528 pub fn lower_poly_trait_ref(lctx: &LoweringContext, p: &PolyTraitRef) -> hir::PolyTraitRef {
530 bound_lifetimes: lower_lifetime_defs(lctx, &p.bound_lifetimes),
531 trait_ref: lower_trait_ref(lctx, &p.trait_ref),
536 pub fn lower_struct_field(lctx: &LoweringContext, f: &StructField) -> hir::StructField {
538 node: hir::StructField_ {
540 kind: lower_struct_field_kind(lctx, &f.node.kind),
541 ty: lower_ty(lctx, &f.node.ty),
542 attrs: f.node.attrs.clone(),
548 pub fn lower_field(lctx: &LoweringContext, f: &Field) -> hir::Field {
550 name: respan(f.ident.span, f.ident.node.name),
551 expr: lower_expr(lctx, &f.expr),
556 pub fn lower_mt(lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy {
558 ty: lower_ty(lctx, &mt.ty),
559 mutbl: lower_mutability(lctx, mt.mutbl),
563 pub fn lower_opt_bounds(lctx: &LoweringContext,
564 b: &Option<OwnedSlice<TyParamBound>>)
565 -> Option<OwnedSlice<hir::TyParamBound>> {
566 b.as_ref().map(|ref bounds| lower_bounds(lctx, bounds))
569 fn lower_bounds(lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParamBounds {
570 bounds.iter().map(|bound| lower_ty_param_bound(lctx, bound)).collect()
573 pub fn lower_block(lctx: &LoweringContext, b: &Block) -> P<hir::Block> {
576 stmts: b.stmts.iter().map(|s| lower_stmt(lctx, s)).collect(),
577 expr: b.expr.as_ref().map(|ref x| lower_expr(lctx, x)),
578 rules: lower_block_check_mode(lctx, &b.rules),
583 pub fn lower_item_underscore(lctx: &LoweringContext, i: &Item_) -> hir::Item_ {
585 ItemExternCrate(string) => hir::ItemExternCrate(string),
586 ItemUse(ref view_path) => {
587 hir::ItemUse(lower_view_path(lctx, view_path))
589 ItemStatic(ref t, m, ref e) => {
590 hir::ItemStatic(lower_ty(lctx, t),
591 lower_mutability(lctx, m),
594 ItemConst(ref t, ref e) => {
595 hir::ItemConst(lower_ty(lctx, t), lower_expr(lctx, e))
597 ItemFn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
598 hir::ItemFn(lower_fn_decl(lctx, decl),
599 lower_unsafety(lctx, unsafety),
600 lower_constness(lctx, constness),
602 lower_generics(lctx, generics),
603 lower_block(lctx, body))
605 ItemMod(ref m) => hir::ItemMod(lower_mod(lctx, m)),
606 ItemForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(lctx, nm)),
607 ItemTy(ref t, ref generics) => {
608 hir::ItemTy(lower_ty(lctx, t), lower_generics(lctx, generics))
610 ItemEnum(ref enum_definition, ref generics) => {
611 hir::ItemEnum(hir::EnumDef {
612 variants: enum_definition.variants
614 .map(|x| lower_variant(lctx, x))
617 lower_generics(lctx, generics))
619 ItemStruct(ref struct_def, ref generics) => {
620 let struct_def = lower_variant_data(lctx, struct_def);
621 hir::ItemStruct(struct_def, lower_generics(lctx, generics))
623 ItemDefaultImpl(unsafety, ref trait_ref) => {
624 hir::ItemDefaultImpl(lower_unsafety(lctx, unsafety),
625 lower_trait_ref(lctx, trait_ref))
627 ItemImpl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
628 let new_impl_items = impl_items.iter()
629 .map(|item| lower_impl_item(lctx, item))
631 let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(lctx, trait_ref));
632 hir::ItemImpl(lower_unsafety(lctx, unsafety),
633 lower_impl_polarity(lctx, polarity),
634 lower_generics(lctx, generics),
639 ItemTrait(unsafety, ref generics, ref bounds, ref items) => {
640 let bounds = lower_bounds(lctx, bounds);
641 let items = items.iter().map(|item| lower_trait_item(lctx, item)).collect();
642 hir::ItemTrait(lower_unsafety(lctx, unsafety),
643 lower_generics(lctx, generics),
647 ItemMac(_) => panic!("Shouldn't still be around"),
651 pub fn lower_trait_item(lctx: &LoweringContext, i: &TraitItem) -> P<hir::TraitItem> {
655 attrs: i.attrs.clone(),
657 ConstTraitItem(ref ty, ref default) => {
658 hir::ConstTraitItem(lower_ty(lctx, ty),
659 default.as_ref().map(|x| lower_expr(lctx, x)))
661 MethodTraitItem(ref sig, ref body) => {
662 hir::MethodTraitItem(lower_method_sig(lctx, sig),
663 body.as_ref().map(|x| lower_block(lctx, x)))
665 TypeTraitItem(ref bounds, ref default) => {
666 hir::TypeTraitItem(lower_bounds(lctx, bounds),
667 default.as_ref().map(|x| lower_ty(lctx, x)))
674 pub fn lower_impl_item(lctx: &LoweringContext, i: &ImplItem) -> P<hir::ImplItem> {
678 attrs: i.attrs.clone(),
679 vis: lower_visibility(lctx, i.vis),
681 ImplItemKind::Const(ref ty, ref expr) => {
682 hir::ImplItemKind::Const(lower_ty(lctx, ty), lower_expr(lctx, expr))
684 ImplItemKind::Method(ref sig, ref body) => {
685 hir::ImplItemKind::Method(lower_method_sig(lctx, sig), lower_block(lctx, body))
687 ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(lower_ty(lctx, ty)),
688 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
694 pub fn lower_mod(lctx: &LoweringContext, m: &Mod) -> hir::Mod {
697 item_ids: m.items.iter().map(|x| lower_item_id(lctx, x)).collect(),
701 struct ItemLowerer<'lcx, 'interner: 'lcx> {
702 items: BTreeMap<NodeId, hir::Item>,
703 lctx: &'lcx LoweringContext<'interner>,
706 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
707 fn visit_item(&mut self, item: &'lcx Item) {
708 self.items.insert(item.id, lower_item(self.lctx, item));
709 visit::walk_item(self, item);
713 pub fn lower_crate(lctx: &LoweringContext, c: &Crate) -> hir::Crate {
715 let mut item_lowerer = ItemLowerer { items: BTreeMap::new(), lctx: lctx };
716 visit::walk_crate(&mut item_lowerer, c);
721 module: lower_mod(lctx, &c.module),
722 attrs: c.attrs.clone(),
723 config: c.config.clone(),
725 exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(lctx, m)).collect(),
730 pub fn lower_macro_def(_lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef {
733 attrs: m.attrs.clone(),
736 imported_from: m.imported_from.map(|x| x.name),
738 use_locally: m.use_locally,
739 allow_internal_unstable: m.allow_internal_unstable,
740 body: m.body.clone(),
744 pub fn lower_item_id(_lctx: &LoweringContext, i: &Item) -> hir::ItemId {
745 hir::ItemId { id: i.id }
748 pub fn lower_item(lctx: &LoweringContext, i: &Item) -> hir::Item {
749 let node = lower_item_underscore(lctx, &i.node);
754 attrs: i.attrs.clone(),
756 vis: lower_visibility(lctx, i.vis),
761 pub fn lower_foreign_item(lctx: &LoweringContext, i: &ForeignItem) -> P<hir::ForeignItem> {
765 attrs: i.attrs.clone(),
767 ForeignItemFn(ref fdec, ref generics) => {
768 hir::ForeignItemFn(lower_fn_decl(lctx, fdec), lower_generics(lctx, generics))
770 ForeignItemStatic(ref t, m) => {
771 hir::ForeignItemStatic(lower_ty(lctx, t), m)
774 vis: lower_visibility(lctx, i.vis),
779 pub fn lower_method_sig(lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig {
781 generics: lower_generics(lctx, &sig.generics),
783 explicit_self: lower_explicit_self(lctx, &sig.explicit_self),
784 unsafety: lower_unsafety(lctx, sig.unsafety),
785 constness: lower_constness(lctx, sig.constness),
786 decl: lower_fn_decl(lctx, &sig.decl),
790 pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety {
792 Unsafety::Unsafe => hir::Unsafety::Unsafe,
793 Unsafety::Normal => hir::Unsafety::Normal,
797 pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness {
799 Constness::Const => hir::Constness::Const,
800 Constness::NotConst => hir::Constness::NotConst,
804 pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp {
806 UnDeref => hir::UnDeref,
812 pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp {
822 BiBitXor => hir::BiBitXor,
823 BiBitAnd => hir::BiBitAnd,
824 BiBitOr => hir::BiBitOr,
838 pub fn lower_pat(lctx: &LoweringContext, p: &Pat) -> P<hir::Pat> {
842 PatWild => hir::PatWild,
843 PatIdent(ref binding_mode, pth1, ref sub) => {
844 hir::PatIdent(lower_binding_mode(lctx, binding_mode),
846 sub.as_ref().map(|x| lower_pat(lctx, x)))
848 PatLit(ref e) => hir::PatLit(lower_expr(lctx, e)),
849 PatEnum(ref pth, ref pats) => {
850 hir::PatEnum(lower_path(lctx, pth),
852 .map(|pats| pats.iter().map(|x| lower_pat(lctx, x)).collect()))
854 PatQPath(ref qself, ref pth) => {
855 let qself = hir::QSelf {
856 ty: lower_ty(lctx, &qself.ty),
857 position: qself.position,
859 hir::PatQPath(qself, lower_path(lctx, pth))
861 PatStruct(ref pth, ref fields, etc) => {
862 let pth = lower_path(lctx, pth);
863 let fs = fields.iter()
867 node: hir::FieldPat {
868 name: f.node.ident.name,
869 pat: lower_pat(lctx, &f.node.pat),
870 is_shorthand: f.node.is_shorthand,
875 hir::PatStruct(pth, fs, etc)
877 PatTup(ref elts) => hir::PatTup(elts.iter().map(|x| lower_pat(lctx, x)).collect()),
878 PatBox(ref inner) => hir::PatBox(lower_pat(lctx, inner)),
879 PatRegion(ref inner, mutbl) => {
880 hir::PatRegion(lower_pat(lctx, inner), lower_mutability(lctx, mutbl))
882 PatRange(ref e1, ref e2) => {
883 hir::PatRange(lower_expr(lctx, e1), lower_expr(lctx, e2))
885 PatVec(ref before, ref slice, ref after) => {
886 hir::PatVec(before.iter().map(|x| lower_pat(lctx, x)).collect(),
887 slice.as_ref().map(|x| lower_pat(lctx, x)),
888 after.iter().map(|x| lower_pat(lctx, x)).collect())
890 PatMac(_) => panic!("Shouldn't exist here"),
896 // Utility fn for setting and unsetting the cached id.
897 fn cache_ids<'a, OP, R>(lctx: &LoweringContext, expr_id: NodeId, op: OP) -> R
898 where OP: FnOnce(&LoweringContext) -> R
900 // Only reset the id if it was previously 0, i.e., was not cached.
901 // If it was cached, we are in a nested node, but our id count will
902 // still count towards the parent's count.
903 let reset_cached_id = lctx.cached_id.get() == 0;
906 let id_cache: &mut HashMap<_, _> = &mut lctx.id_cache.borrow_mut();
908 if id_cache.contains_key(&expr_id) {
909 let cached_id = lctx.cached_id.get();
911 // We're entering a node where we need to track ids, but are not
913 lctx.cached_id.set(id_cache[&expr_id]);
914 lctx.gensym_key.set(id_cache[&expr_id]);
916 // We're already tracking - check that the tracked id is the same
917 // as the expected id.
918 assert!(cached_id == id_cache[&expr_id], "id mismatch");
921 let next_id = lctx.id_assigner.peek_node_id();
922 id_cache.insert(expr_id, next_id);
923 lctx.gensym_key.set(next_id);
927 let result = op(lctx);
930 lctx.cached_id.set(0);
931 lctx.gensym_key.set(0);
937 pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
942 // Eventually a desugaring for `box EXPR`
943 // (similar to the desugaring above for `in PLACE BLOCK`)
944 // should go here, desugaring
948 // let mut place = BoxPlace::make_place();
949 // let raw_place = Place::pointer(&mut place);
950 // let value = $value;
952 // ::std::ptr::write(raw_place, value);
953 // Boxed::finalize(place)
956 // But for now there are type-inference issues doing that.
958 hir::ExprBox(lower_expr(lctx, e))
961 // Desugar ExprBox: `in (PLACE) EXPR`
962 ExprInPlace(ref placer, ref value_expr) => {
966 // let mut place = Placer::make_place(p);
967 // let raw_place = Place::pointer(&mut place);
969 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
970 // InPlace::finalize(place)
972 return cache_ids(lctx, e.id, |lctx| {
973 let placer_expr = lower_expr(lctx, placer);
974 let value_expr = lower_expr(lctx, value_expr);
976 let placer_ident = lctx.str_to_ident("placer");
977 let place_ident = lctx.str_to_ident("place");
978 let p_ptr_ident = lctx.str_to_ident("p_ptr");
980 let make_place = ["ops", "Placer", "make_place"];
981 let place_pointer = ["ops", "Place", "pointer"];
982 let move_val_init = ["intrinsics", "move_val_init"];
983 let inplace_finalize = ["ops", "InPlace", "finalize"];
985 let make_call = |lctx: &LoweringContext, p, args| {
986 let path = core_path(lctx, e.span, p);
987 let path = expr_path(lctx, path);
988 expr_call(lctx, e.span, path, args)
991 let mk_stmt_let = |lctx: &LoweringContext, bind, expr| {
992 stmt_let(lctx, e.span, false, bind, expr)
995 let mk_stmt_let_mut = |lctx: &LoweringContext, bind, expr| {
996 stmt_let(lctx, e.span, true, bind, expr)
999 // let placer = <placer_expr> ;
1001 let placer_expr = signal_block_expr(lctx,
1005 hir::PopUnstableBlock);
1006 mk_stmt_let(lctx, placer_ident, placer_expr)
1009 // let mut place = Placer::make_place(placer);
1011 let placer = expr_ident(lctx, e.span, placer_ident);
1012 let call = make_call(lctx, &make_place, vec![placer]);
1013 mk_stmt_let_mut(lctx, place_ident, call)
1016 // let p_ptr = Place::pointer(&mut place);
1018 let agent = expr_ident(lctx, e.span, place_ident);
1019 let args = vec![expr_mut_addr_of(lctx, e.span, agent)];
1020 let call = make_call(lctx, &place_pointer, args);
1021 mk_stmt_let(lctx, p_ptr_ident, call)
1024 // pop_unsafe!(EXPR));
1025 let pop_unsafe_expr = {
1026 let value_expr = signal_block_expr(lctx,
1030 hir::PopUnstableBlock);
1031 signal_block_expr(lctx,
1035 hir::PopUnsafeBlock(hir::CompilerGenerated))
1039 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1040 // InPlace::finalize(place)
1043 let ptr = expr_ident(lctx, e.span, p_ptr_ident);
1044 let call_move_val_init =
1046 make_call(lctx, &move_val_init, vec![ptr, pop_unsafe_expr]),
1048 let call_move_val_init = respan(e.span, call_move_val_init);
1050 let place = expr_ident(lctx, e.span, place_ident);
1051 let call = make_call(lctx, &inplace_finalize, vec![place]);
1052 signal_block_expr(lctx,
1053 vec![P(call_move_val_init)],
1056 hir::PushUnsafeBlock(hir::CompilerGenerated))
1059 signal_block_expr(lctx,
1063 hir::PushUnstableBlock)
1067 ExprVec(ref exprs) => {
1068 hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect())
1070 ExprRepeat(ref expr, ref count) => {
1071 let expr = lower_expr(lctx, expr);
1072 let count = lower_expr(lctx, count);
1073 hir::ExprRepeat(expr, count)
1075 ExprTup(ref elts) => {
1076 hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect())
1078 ExprCall(ref f, ref args) => {
1079 let f = lower_expr(lctx, f);
1080 hir::ExprCall(f, args.iter().map(|x| lower_expr(lctx, x)).collect())
1082 ExprMethodCall(i, ref tps, ref args) => {
1083 let tps = tps.iter().map(|x| lower_ty(lctx, x)).collect();
1084 let args = args.iter().map(|x| lower_expr(lctx, x)).collect();
1085 hir::ExprMethodCall(respan(i.span, i.node.name), tps, args)
1087 ExprBinary(binop, ref lhs, ref rhs) => {
1088 let binop = lower_binop(lctx, binop);
1089 let lhs = lower_expr(lctx, lhs);
1090 let rhs = lower_expr(lctx, rhs);
1091 hir::ExprBinary(binop, lhs, rhs)
1093 ExprUnary(op, ref ohs) => {
1094 let op = lower_unop(lctx, op);
1095 let ohs = lower_expr(lctx, ohs);
1096 hir::ExprUnary(op, ohs)
1098 ExprLit(ref l) => hir::ExprLit(P((**l).clone())),
1099 ExprCast(ref expr, ref ty) => {
1100 let expr = lower_expr(lctx, expr);
1101 hir::ExprCast(expr, lower_ty(lctx, ty))
1103 ExprAddrOf(m, ref ohs) => {
1104 let m = lower_mutability(lctx, m);
1105 let ohs = lower_expr(lctx, ohs);
1106 hir::ExprAddrOf(m, ohs)
1108 // More complicated than you might expect because the else branch
1109 // might be `if let`.
1110 ExprIf(ref cond, ref blk, ref else_opt) => {
1111 let else_opt = else_opt.as_ref().map(|els| {
1114 cache_ids(lctx, e.id, |lctx| {
1115 // wrap the if-let expr in a block
1116 let span = els.span;
1117 let els = lower_expr(lctx, els);
1118 let id = lctx.next_id();
1119 let blk = P(hir::Block {
1123 rules: hir::DefaultBlock,
1126 expr_block(lctx, blk)
1129 _ => lower_expr(lctx, els),
1133 hir::ExprIf(lower_expr(lctx, cond), lower_block(lctx, blk), else_opt)
1135 ExprWhile(ref cond, ref body, opt_ident) => {
1136 hir::ExprWhile(lower_expr(lctx, cond), lower_block(lctx, body), opt_ident)
1138 ExprLoop(ref body, opt_ident) => {
1139 hir::ExprLoop(lower_block(lctx, body), opt_ident)
1141 ExprMatch(ref expr, ref arms) => {
1142 hir::ExprMatch(lower_expr(lctx, expr),
1143 arms.iter().map(|x| lower_arm(lctx, x)).collect(),
1144 hir::MatchSource::Normal)
1146 ExprClosure(capture_clause, ref decl, ref body) => {
1147 hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
1148 lower_fn_decl(lctx, decl),
1149 lower_block(lctx, body))
1151 ExprBlock(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
1152 ExprAssign(ref el, ref er) => {
1153 hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
1155 ExprAssignOp(op, ref el, ref er) => {
1156 hir::ExprAssignOp(lower_binop(lctx, op),
1157 lower_expr(lctx, el),
1158 lower_expr(lctx, er))
1160 ExprField(ref el, ident) => {
1161 hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
1163 ExprTupField(ref el, ident) => {
1164 hir::ExprTupField(lower_expr(lctx, el), ident)
1166 ExprIndex(ref el, ref er) => {
1167 hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
1169 ExprRange(ref e1, ref e2) => {
1170 hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)),
1171 e2.as_ref().map(|x| lower_expr(lctx, x)))
1173 ExprPath(ref qself, ref path) => {
1174 let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
1176 ty: lower_ty(lctx, ty),
1180 hir::ExprPath(qself, lower_path(lctx, path))
1182 ExprBreak(opt_ident) => hir::ExprBreak(opt_ident),
1183 ExprAgain(opt_ident) => hir::ExprAgain(opt_ident),
1184 ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
1185 ExprInlineAsm(InlineAsm {
1195 }) => hir::ExprInlineAsm(hir::InlineAsm {
1196 inputs: inputs.iter()
1197 .map(|&(ref c, ref input)| (c.clone(), lower_expr(lctx, input)))
1199 outputs: outputs.iter()
1200 .map(|&(ref c, ref out, ref is_rw)| {
1201 (c.clone(), lower_expr(lctx, out), *is_rw)
1205 asm_str_style: asm_str_style,
1206 clobbers: clobbers.clone(),
1208 alignstack: alignstack,
1212 ExprStruct(ref path, ref fields, ref maybe_expr) => {
1213 hir::ExprStruct(lower_path(lctx, path),
1214 fields.iter().map(|x| lower_field(lctx, x)).collect(),
1215 maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
1217 ExprParen(ref ex) => {
1218 return lower_expr(lctx, ex);
1221 // Desugar ExprIfLet
1222 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
1223 ExprIfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
1226 // match <sub_expr> {
1228 // [_ if <else_opt_if_cond> => <else_opt_if_body>,]
1229 // _ => [<else_opt> | ()]
1232 return cache_ids(lctx, e.id, |lctx| {
1233 // `<pat> => <body>`
1235 let body = lower_block(lctx, body);
1236 let body_expr = expr_block(lctx, body);
1237 arm(vec![lower_pat(lctx, pat)], body_expr)
1240 // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
1241 let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
1242 let else_if_arms = {
1243 let mut arms = vec![];
1245 let else_opt_continue = else_opt.and_then(|els| {
1246 els.and_then(|els| {
1249 hir::ExprIf(cond, then, else_opt) => {
1250 let pat_under = pat_wild(lctx, e.span);
1251 arms.push(hir::Arm {
1253 pats: vec![pat_under],
1255 body: expr_block(lctx, then),
1257 else_opt.map(|else_opt| (else_opt, true))
1259 _ => Some((P(els), false)),
1263 match else_opt_continue {
1264 Some((e, true)) => {
1267 Some((e, false)) => {
1280 let contains_else_clause = else_opt.is_some();
1282 // `_ => [<else_opt> | ()]`
1284 let pat_under = pat_wild(lctx, e.span);
1286 else_opt.unwrap_or_else(
1287 || expr_tuple(lctx, e.span, vec![]));
1288 arm(vec![pat_under], else_expr)
1291 let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
1293 arms.extend(else_if_arms);
1294 arms.push(else_arm);
1296 let sub_expr = lower_expr(lctx, sub_expr);
1299 hir::ExprMatch(sub_expr,
1301 hir::MatchSource::IfLetDesugar {
1302 contains_else_clause: contains_else_clause,
1307 // Desugar ExprWhileLet
1308 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
1309 ExprWhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
1312 // [opt_ident]: loop {
1313 // match <sub_expr> {
1319 return cache_ids(lctx, e.id, |lctx| {
1320 // `<pat> => <body>`
1322 let body = lower_block(lctx, body);
1323 let body_expr = expr_block(lctx, body);
1324 arm(vec![lower_pat(lctx, pat)], body_expr)
1329 let pat_under = pat_wild(lctx, e.span);
1330 let break_expr = expr_break(lctx, e.span);
1331 arm(vec![pat_under], break_expr)
1334 // `match <sub_expr> { ... }`
1335 let arms = vec![pat_arm, break_arm];
1336 let sub_expr = lower_expr(lctx, sub_expr);
1337 let match_expr = expr(lctx,
1339 hir::ExprMatch(sub_expr,
1341 hir::MatchSource::WhileLetDesugar));
1343 // `[opt_ident]: loop { ... }`
1344 let loop_block = block_expr(lctx, match_expr);
1345 expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident))
1349 // Desugar ExprForLoop
1350 // From: `[opt_ident]: for <pat> in <head> <body>`
1351 ExprForLoop(ref pat, ref head, ref body, opt_ident) => {
1355 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1357 // [opt_ident]: loop {
1358 // match ::std::iter::Iterator::next(&mut iter) {
1359 // ::std::option::Option::Some(<pat>) => <body>,
1360 // ::std::option::Option::None => break
1368 return cache_ids(lctx, e.id, |lctx| {
1370 let head = lower_expr(lctx, head);
1372 let iter = lctx.str_to_ident("iter");
1374 // `::std::option::Option::Some(<pat>) => <body>`
1376 let body_block = lower_block(lctx, body);
1377 let body_span = body_block.span;
1378 let body_expr = P(hir::Expr {
1380 node: hir::ExprBlock(body_block),
1383 let pat = lower_pat(lctx, pat);
1384 let some_pat = pat_some(lctx, e.span, pat);
1386 arm(vec![some_pat], body_expr)
1389 // `::std::option::Option::None => break`
1391 let break_expr = expr_break(lctx, e.span);
1393 arm(vec![pat_none(lctx, e.span)], break_expr)
1396 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1399 let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1401 path_global(e.span, strs)
1403 let iter = expr_ident(lctx, e.span, iter);
1404 let ref_mut_iter = expr_mut_addr_of(lctx, e.span, iter);
1405 let next_path = expr_path(lctx, next_path);
1406 let next_expr = expr_call(lctx, e.span, next_path, vec![ref_mut_iter]);
1407 let arms = vec![pat_arm, break_arm];
1411 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar))
1414 // `[opt_ident]: loop { ... }`
1415 let loop_block = block_expr(lctx, match_expr);
1416 let loop_expr = expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident));
1418 // `mut iter => { ... }`
1420 let iter_pat = pat_ident_binding_mode(lctx,
1423 hir::BindByValue(hir::MutMutable));
1424 arm(vec![iter_pat], loop_expr)
1427 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1428 let into_iter_expr = {
1429 let into_iter_path = {
1430 let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1432 path_global(e.span, strs)
1435 let into_iter = expr_path(lctx, into_iter_path);
1436 expr_call(lctx, e.span, into_iter, vec![head])
1439 let match_expr = expr_match(lctx,
1443 hir::MatchSource::ForLoopDesugar);
1445 // `{ let result = ...; result }`
1446 let result_ident = lctx.str_to_ident("result");
1447 let let_stmt = stmt_let(lctx, e.span, false, result_ident, match_expr);
1448 let result = expr_ident(lctx, e.span, result_ident);
1449 let block = block_all(lctx, e.span, vec![let_stmt], Some(result));
1450 expr_block(lctx, block)
1454 ExprMac(_) => panic!("Shouldn't exist here"),
1460 pub fn lower_stmt(lctx: &LoweringContext, s: &Stmt) -> P<hir::Stmt> {
1462 StmtDecl(ref d, id) => {
1464 node: hir::StmtDecl(lower_decl(lctx, d), id),
1468 StmtExpr(ref e, id) => {
1470 node: hir::StmtExpr(lower_expr(lctx, e), id),
1474 StmtSemi(ref e, id) => {
1476 node: hir::StmtSemi(lower_expr(lctx, e), id),
1480 StmtMac(..) => panic!("Shouldn't exist here"),
1484 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureClause) -> hir::CaptureClause {
1486 CaptureByValue => hir::CaptureByValue,
1487 CaptureByRef => hir::CaptureByRef,
1491 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1493 Public => hir::Public,
1494 Inherited => hir::Inherited,
1498 pub fn lower_block_check_mode(lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1500 DefaultBlock => hir::DefaultBlock,
1501 UnsafeBlock(u) => hir::UnsafeBlock(lower_unsafe_source(lctx, u)),
1505 pub fn lower_binding_mode(lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1507 BindByRef(m) => hir::BindByRef(lower_mutability(lctx, m)),
1508 BindByValue(m) => hir::BindByValue(lower_mutability(lctx, m)),
1512 pub fn lower_struct_field_kind(lctx: &LoweringContext,
1513 s: &StructFieldKind)
1514 -> hir::StructFieldKind {
1516 NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(lctx, vis)),
1517 UnnamedField(vis) => hir::UnnamedField(lower_visibility(lctx, vis)),
1521 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1523 CompilerGenerated => hir::CompilerGenerated,
1524 UserProvided => hir::UserProvided,
1528 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1530 ImplPolarity::Positive => hir::ImplPolarity::Positive,
1531 ImplPolarity::Negative => hir::ImplPolarity::Negative,
1535 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1536 f: TraitBoundModifier)
1537 -> hir::TraitBoundModifier {
1539 TraitBoundModifier::None => hir::TraitBoundModifier::None,
1540 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1544 // Helper methods for building HIR.
1546 fn arm(pats: Vec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1555 fn expr_break(lctx: &LoweringContext, span: Span) -> P<hir::Expr> {
1556 expr(lctx, span, hir::ExprBreak(None))
1559 fn expr_call(lctx: &LoweringContext,
1562 args: Vec<P<hir::Expr>>)
1564 expr(lctx, span, hir::ExprCall(e, args))
1567 fn expr_ident(lctx: &LoweringContext, span: Span, id: Ident) -> P<hir::Expr> {
1568 expr_path(lctx, path_ident(span, id))
1571 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>) -> P<hir::Expr> {
1572 expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e))
1575 fn expr_path(lctx: &LoweringContext, path: hir::Path) -> P<hir::Expr> {
1576 expr(lctx, path.span, hir::ExprPath(None, path))
1579 fn expr_match(lctx: &LoweringContext,
1582 arms: Vec<hir::Arm>,
1583 source: hir::MatchSource)
1585 expr(lctx, span, hir::ExprMatch(arg, arms, source))
1588 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>) -> P<hir::Expr> {
1589 expr(lctx, b.span, hir::ExprBlock(b))
1592 fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: Vec<P<hir::Expr>>) -> P<hir::Expr> {
1593 expr(lctx, sp, hir::ExprTup(exprs))
1596 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_) -> P<hir::Expr> {
1604 fn stmt_let(lctx: &LoweringContext,
1610 let pat = if mutbl {
1611 pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1613 pat_ident(lctx, sp, ident)
1615 let local = P(hir::Local {
1622 let decl = respan(sp, hir::DeclLocal(local));
1623 P(respan(sp, hir::StmtDecl(P(decl), lctx.next_id())))
1626 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1627 block_all(lctx, expr.span, Vec::new(), Some(expr))
1630 fn block_all(lctx: &LoweringContext,
1632 stmts: Vec<P<hir::Stmt>>,
1633 expr: Option<P<hir::Expr>>)
1639 rules: hir::DefaultBlock,
1644 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1645 let some = std_path(lctx, &["option", "Option", "Some"]);
1646 let path = path_global(span, some);
1647 pat_enum(lctx, span, path, vec![pat])
1650 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1651 let none = std_path(lctx, &["option", "Option", "None"]);
1652 let path = path_global(span, none);
1653 pat_enum(lctx, span, path, vec![])
1656 fn pat_enum(lctx: &LoweringContext,
1659 subpats: Vec<P<hir::Pat>>)
1661 let pt = hir::PatEnum(path, Some(subpats));
1665 fn pat_ident(lctx: &LoweringContext, span: Span, ident: Ident) -> P<hir::Pat> {
1666 pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1669 fn pat_ident_binding_mode(lctx: &LoweringContext,
1672 bm: hir::BindingMode)
1674 let pat_ident = hir::PatIdent(bm,
1680 pat(lctx, span, pat_ident)
1683 fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1684 pat(lctx, span, hir::PatWild)
1687 fn pat(lctx: &LoweringContext, span: Span, pat: hir::Pat_) -> P<hir::Pat> {
1695 fn path_ident(span: Span, id: Ident) -> hir::Path {
1696 path(span, vec![id])
1699 fn path(span: Span, strs: Vec<Ident>) -> hir::Path {
1700 path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new())
1703 fn path_global(span: Span, strs: Vec<Ident>) -> hir::Path {
1704 path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new())
1707 fn path_all(sp: Span,
1709 mut idents: Vec<Ident>,
1710 lifetimes: Vec<hir::Lifetime>,
1711 types: Vec<P<hir::Ty>>,
1712 bindings: Vec<P<hir::TypeBinding>>)
1714 let last_identifier = idents.pop().unwrap();
1715 let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1719 parameters: hir::PathParameters::none(),
1723 segments.push(hir::PathSegment {
1724 identifier: last_identifier,
1725 parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1726 lifetimes: lifetimes,
1727 types: OwnedSlice::from_vec(types),
1728 bindings: OwnedSlice::from_vec(bindings),
1738 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<Ident> {
1739 let mut v = Vec::new();
1740 if let Some(s) = lctx.crate_root {
1741 v.push(str_to_ident(s));
1743 v.extend(components.iter().map(|s| str_to_ident(s)));
1747 // Given suffix ["b","c","d"], returns path `::std::b::c::d` when
1748 // `fld.cx.use_std`, and `::core::b::c::d` otherwise.
1749 fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path {
1750 let idents = std_path(lctx, components);
1751 path_global(span, idents)
1754 fn signal_block_expr(lctx: &LoweringContext,
1755 stmts: Vec<P<hir::Stmt>>,
1758 rule: hir::BlockCheckMode)
1760 let id = lctx.next_id();
1776 use syntax::ast::{self, NodeId, NodeIdAssigner};
1777 use syntax::{parse, codemap};
1778 use syntax::fold::Folder;
1779 use std::cell::Cell;
1781 struct MockAssigner {
1782 next_id: Cell<NodeId>,
1786 fn new() -> MockAssigner {
1787 MockAssigner { next_id: Cell::new(0) }
1792 fn call_site(&self) -> codemap::Span;
1793 fn cfg(&self) -> ast::CrateConfig;
1794 fn ident_of(&self, st: &str) -> ast::Ident;
1795 fn name_of(&self, st: &str) -> ast::Name;
1796 fn parse_sess(&self) -> &parse::ParseSess;
1799 impl FakeExtCtxt for parse::ParseSess {
1800 fn call_site(&self) -> codemap::Span {
1802 lo: codemap::BytePos(0),
1803 hi: codemap::BytePos(0),
1804 expn_id: codemap::NO_EXPANSION,
1807 fn cfg(&self) -> ast::CrateConfig {
1810 fn ident_of(&self, st: &str) -> ast::Ident {
1811 parse::token::str_to_ident(st)
1813 fn name_of(&self, st: &str) -> ast::Name {
1814 parse::token::intern(st)
1816 fn parse_sess(&self) -> &parse::ParseSess {
1821 impl NodeIdAssigner for MockAssigner {
1822 fn next_node_id(&self) -> NodeId {
1823 let result = self.next_id.get();
1824 self.next_id.set(result + 1);
1828 fn peek_node_id(&self) -> NodeId {
1833 impl Folder for MockAssigner {
1834 fn new_id(&mut self, old_id: NodeId) -> NodeId {
1835 assert_eq!(old_id, ast::DUMMY_NODE_ID);
1841 fn test_preserves_ids() {
1842 let cx = parse::ParseSess::new();
1843 let mut assigner = MockAssigner::new();
1845 let ast_if_let = quote_expr!(&cx,
1846 if let Some(foo) = baz {
1849 let ast_if_let = assigner.fold_expr(ast_if_let);
1850 let ast_while_let = quote_expr!(&cx,
1851 while let Some(foo) = baz {
1854 let ast_while_let = assigner.fold_expr(ast_while_let);
1855 let ast_for = quote_expr!(&cx,
1859 let ast_for = assigner.fold_expr(ast_for);
1860 let ast_in = quote_expr!(&cx, in HEAP { foo() });
1861 let ast_in = assigner.fold_expr(ast_in);
1863 let lctx = LoweringContext::new(&assigner, None);
1864 let hir1 = lower_expr(&lctx, &ast_if_let);
1865 let hir2 = lower_expr(&lctx, &ast_if_let);
1866 assert!(hir1 == hir2);
1868 let hir1 = lower_expr(&lctx, &ast_while_let);
1869 let hir2 = lower_expr(&lctx, &ast_while_let);
1870 assert!(hir1 == hir2);
1872 let hir1 = lower_expr(&lctx, &ast_for);
1873 let hir2 = lower_expr(&lctx, &ast_for);
1874 assert!(hir1 == hir2);
1876 let hir1 = lower_expr(&lctx, &ast_in);
1877 let hir2 = lower_expr(&lctx, &ast_in);
1878 assert!(hir1 == hir2);