1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Lowers the AST to the HIR.
13 // Since the AST and HIR are fairly similar, this is mostly a simple procedure,
14 // much like a fold. Where lowering involves a bit more work things get more
15 // interesting and there are some invariants you should know about. These mostly
16 // concern spans and ids.
18 // Spans are assigned to AST nodes during parsing and then are modified during
19 // expansion to indicate the origin of a node and the process it went through
20 // being expanded. Ids are assigned to AST nodes just before lowering.
22 // For the simpler lowering steps, ids and spans should be preserved. Unlike
23 // expansion we do not preserve the process of lowering in the spans, so spans
24 // should not be modified here. When creating a new node (as opposed to
25 // 'folding' an existing one), then you create a new id using `next_id()`.
27 // You must ensure that ids are unique. That means that you should only use the
28 // id from an AST node in a single HIR node (you can assume that AST node ids
29 // are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
30 // If you do, you must then set the new node's id to a fresh one.
32 // Lowering must be reproducable (the compiler only lowers once, but tools and
33 // custom lints may lower an AST node to a HIR node to interact with the
34 // compiler). The most interesting bit of this is ids - if you lower an AST node
35 // and create new HIR nodes with fresh ids, when re-lowering the same node, you
36 // must ensure you get the same ids! To do this, we keep track of the next id
37 // when we translate a node which requires new ids. By checking this cache and
38 // using node ids starting with the cached id, we ensure ids are reproducible.
39 // To use this system, you just need to hold on to a CachedIdSetter object
40 // whilst lowering. This is an RAII object that takes care of setting and
41 // restoring the cached id, etc.
43 // This whole system relies on node ids being incremented one at a time and
44 // all increments being for lowering. This means that you should not call any
45 // non-lowering function which will use new node ids.
47 // We must also cache gensym'ed Idents to ensure that we get the same Ident
48 // every time we lower a node with gensym'ed names. One consequence of this is
49 // that you can only gensym a name once in a lowering (you don't need to worry
50 // about nested lowering though). That's because we cache based on the name and
51 // the currently cached node id, which is unique per lowered node.
53 // Spans are used for error messages and for tools to map semantics back to
54 // source code. It is therefore not as important with spans as ids to be strict
55 // about use (you can't break the compiler by screwing up a span). Obviously, a
56 // HIR node can only have a single span. But multiple nodes can have the same
57 // span and spans don't need to be kept in order, etc. Where code is preserved
58 // by lowering, it should have the same span as in the AST. Where HIR nodes are
59 // new it is probably best to give a span for the whole AST node being lowered.
60 // All nodes should have real spans, don't use dummy spans. Tools are likely to
61 // get confused if the spans from leaf AST nodes occur in multiple places
62 // in the HIR, especially for multiple identifiers.
66 use std::collections::BTreeMap;
67 use std::collections::HashMap;
69 use syntax::attr::{ThinAttributes, ThinAttributesExt};
70 use syntax::ext::mtwt;
72 use syntax::codemap::{respan, Spanned, Span};
73 use syntax::parse::token;
74 use syntax::std_inject;
75 use syntax::visit::{self, Visitor};
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), hir::Ident>>,
90 // A copy of cached_id, but is also set to an id while a node is lowered for
92 gensym_key: Cell<u32>,
95 impl<'a, 'hir> LoweringContext<'a> {
96 pub fn new(id_assigner: &'a NodeIdAssigner, c: Option<&Crate>) -> LoweringContext<'a> {
97 let crate_root = c.and_then(|c| {
98 if std_inject::no_core(c) {
100 } else if std_inject::no_std(c) {
108 crate_root: crate_root,
109 id_cache: RefCell::new(HashMap::new()),
110 id_assigner: id_assigner,
111 cached_id: Cell::new(0),
112 gensym_cache: RefCell::new(HashMap::new()),
113 gensym_key: Cell::new(0),
117 fn next_id(&self) -> NodeId {
118 let cached_id = self.cached_id.get();
120 return self.id_assigner.next_node_id();
123 self.cached_id.set(cached_id + 1);
127 fn str_to_ident(&self, s: &'static str) -> hir::Ident {
128 let gensym_key = self.gensym_key.get();
130 return hir::Ident::from_name(token::gensym(s));
133 let cached = self.gensym_cache.borrow().contains_key(&(gensym_key, s));
135 self.gensym_cache.borrow()[&(gensym_key, s)]
137 let result = hir::Ident::from_name(token::gensym(s));
138 self.gensym_cache.borrow_mut().insert((gensym_key, s), result);
144 // Utility fn for setting and unsetting the cached id.
145 fn cache_ids<'a, OP, R>(lctx: &LoweringContext, expr_id: NodeId, op: OP) -> R
146 where OP: FnOnce(&LoweringContext) -> R
148 // Only reset the id if it was previously 0, i.e., was not cached.
149 // If it was cached, we are in a nested node, but our id count will
150 // still count towards the parent's count.
151 let reset_cached_id = lctx.cached_id.get() == 0;
152 // We always reset gensym_key so that if we use the same name in a nested
153 // node and after that node, they get different values.
154 let old_gensym_key = lctx.gensym_key.get();
157 let id_cache: &mut HashMap<_, _> = &mut lctx.id_cache.borrow_mut();
159 if id_cache.contains_key(&expr_id) {
160 let cached_id = lctx.cached_id.get();
162 // We're entering a node where we need to track ids, but are not
164 lctx.cached_id.set(id_cache[&expr_id]);
166 // We're already tracking - check that the tracked id is the same
167 // as the expected id.
168 assert!(cached_id == id_cache[&expr_id], "id mismatch");
170 lctx.gensym_key.set(id_cache[&expr_id]);
172 // We've never lowered this node before, remember it for next time.
173 let next_id = lctx.id_assigner.peek_node_id();
174 id_cache.insert(expr_id, next_id);
175 lctx.gensym_key.set(next_id);
176 // self.cached_id is not set when we lower a node for the first time,
177 // only on re-lowering.
181 let result = op(lctx);
184 lctx.cached_id.set(0);
186 lctx.gensym_key.set(old_gensym_key);
191 pub fn lower_ident(_lctx: &LoweringContext, ident: Ident) -> hir::Ident {
193 name: mtwt::resolve(ident),
194 unhygienic_name: ident.name,
198 pub fn lower_attrs(_lctx: &LoweringContext, attrs: &Vec<Attribute>) -> hir::HirVec<Attribute> {
202 pub fn lower_view_path(lctx: &LoweringContext, view_path: &ViewPath) -> P<hir::ViewPath> {
204 node: match view_path.node {
205 ViewPathSimple(ident, ref path) => {
206 hir::ViewPathSimple(ident.name, lower_path(lctx, path))
208 ViewPathGlob(ref path) => {
209 hir::ViewPathGlob(lower_path(lctx, path))
211 ViewPathList(ref path, ref path_list_idents) => {
212 hir::ViewPathList(lower_path(lctx, path),
213 path_list_idents.iter()
214 .map(lower_path_list_item)
218 span: view_path.span,
222 fn lower_path_list_item(path_list_ident: &PathListItem) -> hir::PathListItem {
224 node: match path_list_ident.node {
225 PathListItemKind::Ident { id, name, rename } => hir::PathListIdent {
228 rename: rename.map(|x| x.name),
230 PathListItemKind::Mod { id, rename } => hir::PathListMod {
232 rename: rename.map(|x| x.name),
235 span: path_list_ident.span,
239 pub fn lower_arm(lctx: &LoweringContext, arm: &Arm) -> hir::Arm {
241 attrs: lower_attrs(lctx, &arm.attrs),
242 pats: arm.pats.iter().map(|x| lower_pat(lctx, x)).collect(),
243 guard: arm.guard.as_ref().map(|ref x| lower_expr(lctx, x)),
244 body: lower_expr(lctx, &arm.body),
248 pub fn lower_decl(lctx: &LoweringContext, d: &Decl) -> P<hir::Decl> {
250 DeclKind::Local(ref l) => P(Spanned {
251 node: hir::DeclLocal(lower_local(lctx, l)),
254 DeclKind::Item(ref it) => P(Spanned {
255 node: hir::DeclItem(lower_item_id(lctx, it)),
261 pub fn lower_ty_binding(lctx: &LoweringContext, b: &TypeBinding) -> hir::TypeBinding {
265 ty: lower_ty(lctx, &b.ty),
270 pub fn lower_ty(lctx: &LoweringContext, t: &Ty) -> P<hir::Ty> {
271 use syntax::ast::TyKind::*;
275 Infer => hir::TyInfer,
276 Vec(ref ty) => hir::TyVec(lower_ty(lctx, ty)),
277 Ptr(ref mt) => hir::TyPtr(lower_mt(lctx, mt)),
278 Rptr(ref region, ref mt) => {
279 hir::TyRptr(lower_opt_lifetime(lctx, region), lower_mt(lctx, mt))
282 hir::TyBareFn(P(hir::BareFnTy {
283 lifetimes: lower_lifetime_defs(lctx, &f.lifetimes),
284 unsafety: lower_unsafety(lctx, f.unsafety),
286 decl: lower_fn_decl(lctx, &f.decl),
289 Tup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(lctx, ty)).collect()),
291 return lower_ty(lctx, ty);
293 Path(ref qself, ref path) => {
294 let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
296 ty: lower_ty(lctx, ty),
300 hir::TyPath(qself, lower_path(lctx, path))
302 ObjectSum(ref ty, ref bounds) => {
303 hir::TyObjectSum(lower_ty(lctx, ty), lower_bounds(lctx, bounds))
305 FixedLengthVec(ref ty, ref e) => {
306 hir::TyFixedLengthVec(lower_ty(lctx, ty), lower_expr(lctx, e))
308 Typeof(ref expr) => {
309 hir::TyTypeof(lower_expr(lctx, expr))
311 PolyTraitRef(ref bounds) => {
312 hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(lctx, b)).collect())
314 Mac(_) => panic!("TyMac should have been expanded by now."),
320 pub fn lower_foreign_mod(lctx: &LoweringContext, fm: &ForeignMod) -> hir::ForeignMod {
323 items: fm.items.iter().map(|x| lower_foreign_item(lctx, x)).collect(),
327 pub fn lower_variant(lctx: &LoweringContext, v: &Variant) -> hir::Variant {
329 node: hir::Variant_ {
330 name: v.node.name.name,
331 attrs: lower_attrs(lctx, &v.node.attrs),
332 data: lower_variant_data(lctx, &v.node.data),
333 disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(lctx, e)),
339 // Path segments are usually unhygienic, hygienic path segments can occur only in
340 // identifier-like paths originating from `ExprPath`.
341 // Make life simpler for rustc_resolve by renaming only such segments.
342 pub fn lower_path_full(lctx: &LoweringContext, p: &Path, maybe_hygienic: bool) -> hir::Path {
343 let maybe_hygienic = maybe_hygienic && !p.global && p.segments.len() == 1;
348 .map(|&PathSegment { identifier, ref parameters }| {
350 identifier: if maybe_hygienic {
351 lower_ident(lctx, identifier)
353 hir::Ident::from_name(identifier.name)
355 parameters: lower_path_parameters(lctx, parameters),
363 pub fn lower_path(lctx: &LoweringContext, p: &Path) -> hir::Path {
364 lower_path_full(lctx, p, false)
367 pub fn lower_path_parameters(lctx: &LoweringContext,
368 path_parameters: &PathParameters)
369 -> hir::PathParameters {
370 match *path_parameters {
371 PathParameters::AngleBracketed(ref data) =>
372 hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(lctx, data)),
373 PathParameters::Parenthesized(ref data) =>
374 hir::ParenthesizedParameters(lower_parenthesized_parameter_data(lctx, data)),
378 pub fn lower_angle_bracketed_parameter_data(lctx: &LoweringContext,
379 data: &AngleBracketedParameterData)
380 -> hir::AngleBracketedParameterData {
381 let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
382 hir::AngleBracketedParameterData {
383 lifetimes: lower_lifetimes(lctx, lifetimes),
384 types: types.iter().map(|ty| lower_ty(lctx, ty)).collect(),
385 bindings: bindings.iter().map(|b| lower_ty_binding(lctx, b)).collect(),
389 pub fn lower_parenthesized_parameter_data(lctx: &LoweringContext,
390 data: &ParenthesizedParameterData)
391 -> hir::ParenthesizedParameterData {
392 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
393 hir::ParenthesizedParameterData {
394 inputs: inputs.iter().map(|ty| lower_ty(lctx, ty)).collect(),
395 output: output.as_ref().map(|ty| lower_ty(lctx, ty)),
400 pub fn lower_local(lctx: &LoweringContext, l: &Local) -> P<hir::Local> {
403 ty: l.ty.as_ref().map(|t| lower_ty(lctx, t)),
404 pat: lower_pat(lctx, &l.pat),
405 init: l.init.as_ref().map(|e| lower_expr(lctx, e)),
407 attrs: l.attrs.clone(),
411 pub fn lower_explicit_self_underscore(lctx: &LoweringContext,
413 -> hir::ExplicitSelf_ {
415 SelfKind::Static => hir::SelfStatic,
416 SelfKind::Value(v) => hir::SelfValue(v.name),
417 SelfKind::Region(ref lifetime, m, ident) => {
418 hir::SelfRegion(lower_opt_lifetime(lctx, lifetime),
419 lower_mutability(lctx, m),
422 SelfKind::Explicit(ref typ, ident) => {
423 hir::SelfExplicit(lower_ty(lctx, typ), ident.name)
428 pub fn lower_mutability(_lctx: &LoweringContext, m: Mutability) -> hir::Mutability {
430 Mutability::Mutable => hir::MutMutable,
431 Mutability::Immutable => hir::MutImmutable,
435 pub fn lower_explicit_self(lctx: &LoweringContext, s: &ExplicitSelf) -> hir::ExplicitSelf {
437 node: lower_explicit_self_underscore(lctx, &s.node),
442 pub fn lower_arg(lctx: &LoweringContext, arg: &Arg) -> hir::Arg {
445 pat: lower_pat(lctx, &arg.pat),
446 ty: lower_ty(lctx, &arg.ty),
450 pub fn lower_fn_decl(lctx: &LoweringContext, decl: &FnDecl) -> P<hir::FnDecl> {
452 inputs: decl.inputs.iter().map(|x| lower_arg(lctx, x)).collect(),
453 output: match decl.output {
454 FunctionRetTy::Ty(ref ty) => hir::Return(lower_ty(lctx, ty)),
455 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
456 FunctionRetTy::None(span) => hir::NoReturn(span),
458 variadic: decl.variadic,
462 pub fn lower_ty_param_bound(lctx: &LoweringContext, tpb: &TyParamBound) -> hir::TyParamBound {
464 TraitTyParamBound(ref ty, modifier) => {
465 hir::TraitTyParamBound(lower_poly_trait_ref(lctx, ty),
466 lower_trait_bound_modifier(lctx, modifier))
468 RegionTyParamBound(ref lifetime) => {
469 hir::RegionTyParamBound(lower_lifetime(lctx, lifetime))
474 pub fn lower_ty_param(lctx: &LoweringContext, tp: &TyParam) -> hir::TyParam {
478 bounds: lower_bounds(lctx, &tp.bounds),
479 default: tp.default.as_ref().map(|x| lower_ty(lctx, x)),
484 pub fn lower_ty_params(lctx: &LoweringContext,
486 -> hir::HirVec<hir::TyParam> {
487 tps.iter().map(|tp| lower_ty_param(lctx, tp)).collect()
490 pub fn lower_lifetime(_lctx: &LoweringContext, l: &Lifetime) -> hir::Lifetime {
498 pub fn lower_lifetime_def(lctx: &LoweringContext, l: &LifetimeDef) -> hir::LifetimeDef {
500 lifetime: lower_lifetime(lctx, &l.lifetime),
501 bounds: lower_lifetimes(lctx, &l.bounds),
505 pub fn lower_lifetimes(lctx: &LoweringContext, lts: &Vec<Lifetime>) -> hir::HirVec<hir::Lifetime> {
506 lts.iter().map(|l| lower_lifetime(lctx, l)).collect()
509 pub fn lower_lifetime_defs(lctx: &LoweringContext,
510 lts: &Vec<LifetimeDef>)
511 -> hir::HirVec<hir::LifetimeDef> {
512 lts.iter().map(|l| lower_lifetime_def(lctx, l)).collect()
515 pub fn lower_opt_lifetime(lctx: &LoweringContext,
516 o_lt: &Option<Lifetime>)
517 -> Option<hir::Lifetime> {
518 o_lt.as_ref().map(|lt| lower_lifetime(lctx, lt))
521 pub fn lower_generics(lctx: &LoweringContext, g: &Generics) -> hir::Generics {
523 ty_params: lower_ty_params(lctx, &g.ty_params),
524 lifetimes: lower_lifetime_defs(lctx, &g.lifetimes),
525 where_clause: lower_where_clause(lctx, &g.where_clause),
529 pub fn lower_where_clause(lctx: &LoweringContext, wc: &WhereClause) -> hir::WhereClause {
532 predicates: wc.predicates
534 .map(|predicate| lower_where_predicate(lctx, predicate))
539 pub fn lower_where_predicate(lctx: &LoweringContext,
540 pred: &WherePredicate)
541 -> hir::WherePredicate {
543 WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
547 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
548 bound_lifetimes: lower_lifetime_defs(lctx, bound_lifetimes),
549 bounded_ty: lower_ty(lctx, bounded_ty),
550 bounds: bounds.iter().map(|x| lower_ty_param_bound(lctx, x)).collect(),
554 WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
557 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
559 lifetime: lower_lifetime(lctx, lifetime),
560 bounds: bounds.iter().map(|bound| lower_lifetime(lctx, bound)).collect(),
563 WherePredicate::EqPredicate(WhereEqPredicate{ id,
567 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
569 path: lower_path(lctx, path),
570 ty: lower_ty(lctx, ty),
577 pub fn lower_variant_data(lctx: &LoweringContext, vdata: &VariantData) -> hir::VariantData {
579 VariantData::Struct(ref fields, id) => {
580 hir::VariantData::Struct(fields.iter()
581 .map(|f| lower_struct_field(lctx, f))
585 VariantData::Tuple(ref fields, id) => {
586 hir::VariantData::Tuple(fields.iter()
587 .map(|f| lower_struct_field(lctx, f))
591 VariantData::Unit(id) => hir::VariantData::Unit(id),
595 pub fn lower_trait_ref(lctx: &LoweringContext, p: &TraitRef) -> hir::TraitRef {
597 path: lower_path(lctx, &p.path),
602 pub fn lower_poly_trait_ref(lctx: &LoweringContext, p: &PolyTraitRef) -> hir::PolyTraitRef {
604 bound_lifetimes: lower_lifetime_defs(lctx, &p.bound_lifetimes),
605 trait_ref: lower_trait_ref(lctx, &p.trait_ref),
610 pub fn lower_struct_field(lctx: &LoweringContext, f: &StructField) -> hir::StructField {
612 node: hir::StructField_ {
614 kind: lower_struct_field_kind(lctx, &f.node.kind),
615 ty: lower_ty(lctx, &f.node.ty),
616 attrs: lower_attrs(lctx, &f.node.attrs),
622 pub fn lower_field(lctx: &LoweringContext, f: &Field) -> hir::Field {
624 name: respan(f.ident.span, f.ident.node.name),
625 expr: lower_expr(lctx, &f.expr),
630 pub fn lower_mt(lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy {
632 ty: lower_ty(lctx, &mt.ty),
633 mutbl: lower_mutability(lctx, mt.mutbl),
637 pub fn lower_opt_bounds(lctx: &LoweringContext,
638 b: &Option<TyParamBounds>)
639 -> Option<hir::TyParamBounds> {
640 b.as_ref().map(|ref bounds| lower_bounds(lctx, bounds))
643 fn lower_bounds(lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParamBounds {
644 bounds.iter().map(|bound| lower_ty_param_bound(lctx, bound)).collect()
647 pub fn lower_block(lctx: &LoweringContext, b: &Block) -> P<hir::Block> {
650 stmts: b.stmts.iter().map(|s| lower_stmt(lctx, s)).collect(),
651 expr: b.expr.as_ref().map(|ref x| lower_expr(lctx, x)),
652 rules: lower_block_check_mode(lctx, &b.rules),
657 pub fn lower_item_kind(lctx: &LoweringContext, i: &ItemKind) -> hir::Item_ {
659 ItemKind::ExternCrate(string) => hir::ItemExternCrate(string),
660 ItemKind::Use(ref view_path) => {
661 hir::ItemUse(lower_view_path(lctx, view_path))
663 ItemKind::Static(ref t, m, ref e) => {
664 hir::ItemStatic(lower_ty(lctx, t),
665 lower_mutability(lctx, m),
668 ItemKind::Const(ref t, ref e) => {
669 hir::ItemConst(lower_ty(lctx, t), lower_expr(lctx, e))
671 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
672 hir::ItemFn(lower_fn_decl(lctx, decl),
673 lower_unsafety(lctx, unsafety),
674 lower_constness(lctx, constness),
676 lower_generics(lctx, generics),
677 lower_block(lctx, body))
679 ItemKind::Mod(ref m) => hir::ItemMod(lower_mod(lctx, m)),
680 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(lctx, nm)),
681 ItemKind::Ty(ref t, ref generics) => {
682 hir::ItemTy(lower_ty(lctx, t), lower_generics(lctx, generics))
684 ItemKind::Enum(ref enum_definition, ref generics) => {
685 hir::ItemEnum(hir::EnumDef {
686 variants: enum_definition.variants
688 .map(|x| lower_variant(lctx, x))
691 lower_generics(lctx, generics))
693 ItemKind::Struct(ref struct_def, ref generics) => {
694 let struct_def = lower_variant_data(lctx, struct_def);
695 hir::ItemStruct(struct_def, lower_generics(lctx, generics))
697 ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
698 hir::ItemDefaultImpl(lower_unsafety(lctx, unsafety),
699 lower_trait_ref(lctx, trait_ref))
701 ItemKind::Impl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
702 let new_impl_items = impl_items.iter()
703 .map(|item| lower_impl_item(lctx, item))
705 let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(lctx, trait_ref));
706 hir::ItemImpl(lower_unsafety(lctx, unsafety),
707 lower_impl_polarity(lctx, polarity),
708 lower_generics(lctx, generics),
713 ItemKind::Trait(unsafety, ref generics, ref bounds, ref items) => {
714 let bounds = lower_bounds(lctx, bounds);
715 let items = items.iter().map(|item| lower_trait_item(lctx, item)).collect();
716 hir::ItemTrait(lower_unsafety(lctx, unsafety),
717 lower_generics(lctx, generics),
721 ItemKind::Mac(_) => panic!("Shouldn't still be around"),
725 pub fn lower_trait_item(lctx: &LoweringContext, i: &TraitItem) -> hir::TraitItem {
729 attrs: lower_attrs(lctx, &i.attrs),
731 TraitItemKind::Const(ref ty, ref default) => {
732 hir::ConstTraitItem(lower_ty(lctx, ty),
733 default.as_ref().map(|x| lower_expr(lctx, x)))
735 TraitItemKind::Method(ref sig, ref body) => {
736 hir::MethodTraitItem(lower_method_sig(lctx, sig),
737 body.as_ref().map(|x| lower_block(lctx, x)))
739 TraitItemKind::Type(ref bounds, ref default) => {
740 hir::TypeTraitItem(lower_bounds(lctx, bounds),
741 default.as_ref().map(|x| lower_ty(lctx, x)))
748 pub fn lower_impl_item(lctx: &LoweringContext, i: &ImplItem) -> hir::ImplItem {
752 attrs: lower_attrs(lctx, &i.attrs),
753 vis: lower_visibility(lctx, i.vis),
755 ImplItemKind::Const(ref ty, ref expr) => {
756 hir::ImplItemKind::Const(lower_ty(lctx, ty), lower_expr(lctx, expr))
758 ImplItemKind::Method(ref sig, ref body) => {
759 hir::ImplItemKind::Method(lower_method_sig(lctx, sig), lower_block(lctx, body))
761 ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(lower_ty(lctx, ty)),
762 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
768 pub fn lower_mod(lctx: &LoweringContext, m: &Mod) -> hir::Mod {
771 item_ids: m.items.iter().map(|x| lower_item_id(lctx, x)).collect(),
775 struct ItemLowerer<'lcx, 'interner: 'lcx> {
776 items: BTreeMap<NodeId, hir::Item>,
777 lctx: &'lcx LoweringContext<'interner>,
780 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
781 fn visit_item(&mut self, item: &'lcx Item) {
782 self.items.insert(item.id, lower_item(self.lctx, item));
783 visit::walk_item(self, item);
787 pub fn lower_crate(lctx: &LoweringContext, c: &Crate) -> hir::Crate {
789 let mut item_lowerer = ItemLowerer { items: BTreeMap::new(), lctx: lctx };
790 visit::walk_crate(&mut item_lowerer, c);
795 module: lower_mod(lctx, &c.module),
796 attrs: lower_attrs(lctx, &c.attrs),
797 config: c.config.clone().into(),
799 exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(lctx, m)).collect(),
804 pub fn lower_macro_def(lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef {
807 attrs: lower_attrs(lctx, &m.attrs),
810 imported_from: m.imported_from.map(|x| x.name),
812 use_locally: m.use_locally,
813 allow_internal_unstable: m.allow_internal_unstable,
814 body: m.body.clone().into(),
818 pub fn lower_item_id(_lctx: &LoweringContext, i: &Item) -> hir::ItemId {
819 hir::ItemId { id: i.id }
822 pub fn lower_item(lctx: &LoweringContext, i: &Item) -> hir::Item {
823 let node = lower_item_kind(lctx, &i.node);
828 attrs: lower_attrs(lctx, &i.attrs),
830 vis: lower_visibility(lctx, i.vis),
835 pub fn lower_foreign_item(lctx: &LoweringContext, i: &ForeignItem) -> hir::ForeignItem {
839 attrs: lower_attrs(lctx, &i.attrs),
841 ForeignItemKind::Fn(ref fdec, ref generics) => {
842 hir::ForeignItemFn(lower_fn_decl(lctx, fdec), lower_generics(lctx, generics))
844 ForeignItemKind::Static(ref t, m) => {
845 hir::ForeignItemStatic(lower_ty(lctx, t), m)
848 vis: lower_visibility(lctx, i.vis),
853 pub fn lower_method_sig(lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig {
855 generics: lower_generics(lctx, &sig.generics),
857 explicit_self: lower_explicit_self(lctx, &sig.explicit_self),
858 unsafety: lower_unsafety(lctx, sig.unsafety),
859 constness: lower_constness(lctx, sig.constness),
860 decl: lower_fn_decl(lctx, &sig.decl),
864 pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety {
866 Unsafety::Unsafe => hir::Unsafety::Unsafe,
867 Unsafety::Normal => hir::Unsafety::Normal,
871 pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness {
873 Constness::Const => hir::Constness::Const,
874 Constness::NotConst => hir::Constness::NotConst,
878 pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp {
880 UnOp::Deref => hir::UnDeref,
881 UnOp::Not => hir::UnNot,
882 UnOp::Neg => hir::UnNeg,
886 pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp {
889 BinOpKind::Add => hir::BiAdd,
890 BinOpKind::Sub => hir::BiSub,
891 BinOpKind::Mul => hir::BiMul,
892 BinOpKind::Div => hir::BiDiv,
893 BinOpKind::Rem => hir::BiRem,
894 BinOpKind::And => hir::BiAnd,
895 BinOpKind::Or => hir::BiOr,
896 BinOpKind::BitXor => hir::BiBitXor,
897 BinOpKind::BitAnd => hir::BiBitAnd,
898 BinOpKind::BitOr => hir::BiBitOr,
899 BinOpKind::Shl => hir::BiShl,
900 BinOpKind::Shr => hir::BiShr,
901 BinOpKind::Eq => hir::BiEq,
902 BinOpKind::Lt => hir::BiLt,
903 BinOpKind::Le => hir::BiLe,
904 BinOpKind::Ne => hir::BiNe,
905 BinOpKind::Ge => hir::BiGe,
906 BinOpKind::Gt => hir::BiGt,
912 pub fn lower_pat(lctx: &LoweringContext, p: &Pat) -> P<hir::Pat> {
916 PatKind::Wild => hir::PatKind::Wild,
917 PatKind::Ident(ref binding_mode, pth1, ref sub) => {
918 hir::PatKind::Ident(lower_binding_mode(lctx, binding_mode),
919 respan(pth1.span, lower_ident(lctx, pth1.node)),
920 sub.as_ref().map(|x| lower_pat(lctx, x)))
922 PatKind::Lit(ref e) => hir::PatKind::Lit(lower_expr(lctx, e)),
923 PatKind::TupleStruct(ref pth, ref pats) => {
924 hir::PatKind::TupleStruct(lower_path(lctx, pth),
926 .map(|pats| pats.iter().map(|x| lower_pat(lctx, x)).collect()))
928 PatKind::Path(ref pth) => {
929 hir::PatKind::Path(lower_path(lctx, pth))
931 PatKind::QPath(ref qself, ref pth) => {
932 let qself = hir::QSelf {
933 ty: lower_ty(lctx, &qself.ty),
934 position: qself.position,
936 hir::PatKind::QPath(qself, lower_path(lctx, pth))
938 PatKind::Struct(ref pth, ref fields, etc) => {
939 let pth = lower_path(lctx, pth);
940 let fs = fields.iter()
944 node: hir::FieldPat {
945 name: f.node.ident.name,
946 pat: lower_pat(lctx, &f.node.pat),
947 is_shorthand: f.node.is_shorthand,
952 hir::PatKind::Struct(pth, fs, etc)
954 PatKind::Tup(ref elts) => {
955 hir::PatKind::Tup(elts.iter().map(|x| lower_pat(lctx, x)).collect())
957 PatKind::Box(ref inner) => hir::PatKind::Box(lower_pat(lctx, inner)),
958 PatKind::Ref(ref inner, mutbl) => {
959 hir::PatKind::Ref(lower_pat(lctx, inner), lower_mutability(lctx, mutbl))
961 PatKind::Range(ref e1, ref e2) => {
962 hir::PatKind::Range(lower_expr(lctx, e1), lower_expr(lctx, e2))
964 PatKind::Vec(ref before, ref slice, ref after) => {
965 hir::PatKind::Vec(before.iter().map(|x| lower_pat(lctx, x)).collect(),
966 slice.as_ref().map(|x| lower_pat(lctx, x)),
967 after.iter().map(|x| lower_pat(lctx, x)).collect())
969 PatKind::Mac(_) => panic!("Shouldn't exist here"),
975 pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
980 // Eventually a desugaring for `box EXPR`
981 // (similar to the desugaring above for `in PLACE BLOCK`)
982 // should go here, desugaring
986 // let mut place = BoxPlace::make_place();
987 // let raw_place = Place::pointer(&mut place);
988 // let value = $value;
990 // ::std::ptr::write(raw_place, value);
991 // Boxed::finalize(place)
994 // But for now there are type-inference issues doing that.
995 ExprKind::Box(ref e) => {
996 hir::ExprBox(lower_expr(lctx, e))
999 // Desugar ExprBox: `in (PLACE) EXPR`
1000 ExprKind::InPlace(ref placer, ref value_expr) => {
1004 // let mut place = Placer::make_place(p);
1005 // let raw_place = Place::pointer(&mut place);
1007 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1008 // InPlace::finalize(place)
1010 return cache_ids(lctx, e.id, |lctx| {
1011 let placer_expr = lower_expr(lctx, placer);
1012 let value_expr = lower_expr(lctx, value_expr);
1014 let placer_ident = lctx.str_to_ident("placer");
1015 let place_ident = lctx.str_to_ident("place");
1016 let p_ptr_ident = lctx.str_to_ident("p_ptr");
1018 let make_place = ["ops", "Placer", "make_place"];
1019 let place_pointer = ["ops", "Place", "pointer"];
1020 let move_val_init = ["intrinsics", "move_val_init"];
1021 let inplace_finalize = ["ops", "InPlace", "finalize"];
1023 let make_call = |lctx: &LoweringContext, p, args| {
1024 let path = core_path(lctx, e.span, p);
1025 let path = expr_path(lctx, path, None);
1026 expr_call(lctx, e.span, path, args, None)
1029 let mk_stmt_let = |lctx: &LoweringContext, bind, expr| {
1030 stmt_let(lctx, e.span, false, bind, expr, None)
1033 let mk_stmt_let_mut = |lctx: &LoweringContext, bind, expr| {
1034 stmt_let(lctx, e.span, true, bind, expr, None)
1037 // let placer = <placer_expr> ;
1039 let placer_expr = signal_block_expr(lctx,
1043 hir::PopUnstableBlock,
1045 mk_stmt_let(lctx, placer_ident, placer_expr)
1048 // let mut place = Placer::make_place(placer);
1050 let placer = expr_ident(lctx, e.span, placer_ident, None);
1051 let call = make_call(lctx, &make_place, hir_vec![placer]);
1052 mk_stmt_let_mut(lctx, place_ident, call)
1055 // let p_ptr = Place::pointer(&mut place);
1057 let agent = expr_ident(lctx, e.span, place_ident, None);
1058 let args = hir_vec![expr_mut_addr_of(lctx, e.span, agent, None)];
1059 let call = make_call(lctx, &place_pointer, args);
1060 mk_stmt_let(lctx, p_ptr_ident, call)
1063 // pop_unsafe!(EXPR));
1064 let pop_unsafe_expr = {
1065 let value_expr = signal_block_expr(lctx,
1069 hir::PopUnstableBlock,
1071 signal_block_expr(lctx,
1075 hir::PopUnsafeBlock(hir::CompilerGenerated), None)
1079 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1080 // InPlace::finalize(place)
1083 let ptr = expr_ident(lctx, e.span, p_ptr_ident, None);
1084 let call_move_val_init =
1086 make_call(lctx, &move_val_init, hir_vec![ptr, pop_unsafe_expr]),
1088 let call_move_val_init = respan(e.span, call_move_val_init);
1090 let place = expr_ident(lctx, e.span, place_ident, None);
1091 let call = make_call(lctx, &inplace_finalize, hir_vec![place]);
1092 signal_block_expr(lctx,
1093 hir_vec![call_move_val_init],
1096 hir::PushUnsafeBlock(hir::CompilerGenerated), None)
1099 signal_block_expr(lctx,
1100 hir_vec![s1, s2, s3],
1103 hir::PushUnstableBlock,
1108 ExprKind::Vec(ref exprs) => {
1109 hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect())
1111 ExprKind::Repeat(ref expr, ref count) => {
1112 let expr = lower_expr(lctx, expr);
1113 let count = lower_expr(lctx, count);
1114 hir::ExprRepeat(expr, count)
1116 ExprKind::Tup(ref elts) => {
1117 hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect())
1119 ExprKind::Call(ref f, ref args) => {
1120 let f = lower_expr(lctx, f);
1121 hir::ExprCall(f, args.iter().map(|x| lower_expr(lctx, x)).collect())
1123 ExprKind::MethodCall(i, ref tps, ref args) => {
1124 let tps = tps.iter().map(|x| lower_ty(lctx, x)).collect();
1125 let args = args.iter().map(|x| lower_expr(lctx, x)).collect();
1126 hir::ExprMethodCall(respan(i.span, i.node.name), tps, args)
1128 ExprKind::Binary(binop, ref lhs, ref rhs) => {
1129 let binop = lower_binop(lctx, binop);
1130 let lhs = lower_expr(lctx, lhs);
1131 let rhs = lower_expr(lctx, rhs);
1132 hir::ExprBinary(binop, lhs, rhs)
1134 ExprKind::Unary(op, ref ohs) => {
1135 let op = lower_unop(lctx, op);
1136 let ohs = lower_expr(lctx, ohs);
1137 hir::ExprUnary(op, ohs)
1139 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
1140 ExprKind::Cast(ref expr, ref ty) => {
1141 let expr = lower_expr(lctx, expr);
1142 hir::ExprCast(expr, lower_ty(lctx, ty))
1144 ExprKind::Type(ref expr, ref ty) => {
1145 let expr = lower_expr(lctx, expr);
1146 hir::ExprType(expr, lower_ty(lctx, ty))
1148 ExprKind::AddrOf(m, ref ohs) => {
1149 let m = lower_mutability(lctx, m);
1150 let ohs = lower_expr(lctx, ohs);
1151 hir::ExprAddrOf(m, ohs)
1153 // More complicated than you might expect because the else branch
1154 // might be `if let`.
1155 ExprKind::If(ref cond, ref blk, ref else_opt) => {
1156 let else_opt = else_opt.as_ref().map(|els| {
1158 ExprKind::IfLet(..) => {
1159 cache_ids(lctx, e.id, |lctx| {
1160 // wrap the if-let expr in a block
1161 let span = els.span;
1162 let els = lower_expr(lctx, els);
1163 let id = lctx.next_id();
1164 let blk = P(hir::Block {
1168 rules: hir::DefaultBlock,
1171 expr_block(lctx, blk, None)
1174 _ => lower_expr(lctx, els),
1178 hir::ExprIf(lower_expr(lctx, cond), lower_block(lctx, blk), else_opt)
1180 ExprKind::While(ref cond, ref body, opt_ident) => {
1181 hir::ExprWhile(lower_expr(lctx, cond), lower_block(lctx, body),
1182 opt_ident.map(|ident| lower_ident(lctx, ident)))
1184 ExprKind::Loop(ref body, opt_ident) => {
1185 hir::ExprLoop(lower_block(lctx, body),
1186 opt_ident.map(|ident| lower_ident(lctx, ident)))
1188 ExprKind::Match(ref expr, ref arms) => {
1189 hir::ExprMatch(lower_expr(lctx, expr),
1190 arms.iter().map(|x| lower_arm(lctx, x)).collect(),
1191 hir::MatchSource::Normal)
1193 ExprKind::Closure(capture_clause, ref decl, ref body) => {
1194 hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
1195 lower_fn_decl(lctx, decl),
1196 lower_block(lctx, body))
1198 ExprKind::Block(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
1199 ExprKind::Assign(ref el, ref er) => {
1200 hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
1202 ExprKind::AssignOp(op, ref el, ref er) => {
1203 hir::ExprAssignOp(lower_binop(lctx, op),
1204 lower_expr(lctx, el),
1205 lower_expr(lctx, er))
1207 ExprKind::Field(ref el, ident) => {
1208 hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
1210 ExprKind::TupField(ref el, ident) => {
1211 hir::ExprTupField(lower_expr(lctx, el), ident)
1213 ExprKind::Index(ref el, ref er) => {
1214 hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
1216 ExprKind::Range(ref e1, ref e2) => {
1217 hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)),
1218 e2.as_ref().map(|x| lower_expr(lctx, x)))
1220 ExprKind::Path(ref qself, ref path) => {
1221 let hir_qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
1223 ty: lower_ty(lctx, ty),
1227 hir::ExprPath(hir_qself, lower_path_full(lctx, path, qself.is_none()))
1229 ExprKind::Break(opt_ident) => hir::ExprBreak(opt_ident.map(|sp_ident| {
1230 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1232 ExprKind::Again(opt_ident) => hir::ExprAgain(opt_ident.map(|sp_ident| {
1233 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1235 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
1236 ExprKind::InlineAsm(InlineAsm {
1246 }) => hir::ExprInlineAsm(hir::InlineAsm {
1247 inputs: inputs.iter()
1248 .map(|&(ref c, ref input)| (c.clone(), lower_expr(lctx, input)))
1250 outputs: outputs.iter()
1252 hir::InlineAsmOutput {
1253 constraint: out.constraint.clone(),
1254 expr: lower_expr(lctx, &out.expr),
1256 is_indirect: out.is_indirect,
1261 asm_str_style: asm_str_style,
1262 clobbers: clobbers.clone().into(),
1264 alignstack: alignstack,
1268 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
1269 hir::ExprStruct(lower_path(lctx, path),
1270 fields.iter().map(|x| lower_field(lctx, x)).collect(),
1271 maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
1273 ExprKind::Paren(ref ex) => {
1274 // merge attributes into the inner expression.
1275 return lower_expr(lctx, ex).map(|mut ex| {
1276 ex.attrs.update(|attrs| {
1277 attrs.prepend(e.attrs.clone())
1283 // Desugar ExprIfLet
1284 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
1285 ExprKind::IfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
1288 // match <sub_expr> {
1290 // [_ if <else_opt_if_cond> => <else_opt_if_body>,]
1291 // _ => [<else_opt> | ()]
1294 return cache_ids(lctx, e.id, |lctx| {
1295 // `<pat> => <body>`
1297 let body = lower_block(lctx, body);
1298 let body_expr = expr_block(lctx, body, None);
1299 arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1302 // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
1303 let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
1304 let else_if_arms = {
1305 let mut arms = vec![];
1307 let else_opt_continue = else_opt.and_then(|els| {
1308 els.and_then(|els| {
1311 hir::ExprIf(cond, then, else_opt) => {
1312 let pat_under = pat_wild(lctx, e.span);
1313 arms.push(hir::Arm {
1315 pats: hir_vec![pat_under],
1317 body: expr_block(lctx, then, None),
1319 else_opt.map(|else_opt| (else_opt, true))
1321 _ => Some((P(els), false)),
1325 match else_opt_continue {
1326 Some((e, true)) => {
1329 Some((e, false)) => {
1342 let contains_else_clause = else_opt.is_some();
1344 // `_ => [<else_opt> | ()]`
1346 let pat_under = pat_wild(lctx, e.span);
1348 else_opt.unwrap_or_else(
1349 || expr_tuple(lctx, e.span, hir_vec![], None));
1350 arm(hir_vec![pat_under], else_expr)
1353 let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
1355 arms.extend(else_if_arms);
1356 arms.push(else_arm);
1358 let sub_expr = lower_expr(lctx, sub_expr);
1359 // add attributes to the outer returned expr node
1362 hir::ExprMatch(sub_expr,
1364 hir::MatchSource::IfLetDesugar {
1365 contains_else_clause: contains_else_clause,
1371 // Desugar ExprWhileLet
1372 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
1373 ExprKind::WhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
1376 // [opt_ident]: loop {
1377 // match <sub_expr> {
1383 return cache_ids(lctx, e.id, |lctx| {
1384 // `<pat> => <body>`
1386 let body = lower_block(lctx, body);
1387 let body_expr = expr_block(lctx, body, None);
1388 arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1393 let pat_under = pat_wild(lctx, e.span);
1394 let break_expr = expr_break(lctx, e.span, None);
1395 arm(hir_vec![pat_under], break_expr)
1398 // `match <sub_expr> { ... }`
1399 let arms = hir_vec![pat_arm, break_arm];
1400 let sub_expr = lower_expr(lctx, sub_expr);
1401 let match_expr = expr(lctx,
1403 hir::ExprMatch(sub_expr,
1405 hir::MatchSource::WhileLetDesugar),
1408 // `[opt_ident]: loop { ... }`
1409 let loop_block = block_expr(lctx, match_expr);
1410 let loop_expr = hir::ExprLoop(loop_block,
1411 opt_ident.map(|ident| lower_ident(lctx, ident)));
1412 // add attributes to the outer returned expr node
1413 expr(lctx, e.span, loop_expr, e.attrs.clone())
1417 // Desugar ExprForLoop
1418 // From: `[opt_ident]: for <pat> in <head> <body>`
1419 ExprKind::ForLoop(ref pat, ref head, ref body, opt_ident) => {
1423 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1425 // [opt_ident]: loop {
1426 // match ::std::iter::Iterator::next(&mut iter) {
1427 // ::std::option::Option::Some(<pat>) => <body>,
1428 // ::std::option::Option::None => break
1436 return cache_ids(lctx, e.id, |lctx| {
1438 let head = lower_expr(lctx, head);
1440 let iter = lctx.str_to_ident("iter");
1442 // `::std::option::Option::Some(<pat>) => <body>`
1444 let body_block = lower_block(lctx, body);
1445 let body_span = body_block.span;
1446 let body_expr = P(hir::Expr {
1448 node: hir::ExprBlock(body_block),
1452 let pat = lower_pat(lctx, pat);
1453 let some_pat = pat_some(lctx, e.span, pat);
1455 arm(hir_vec![some_pat], body_expr)
1458 // `::std::option::Option::None => break`
1460 let break_expr = expr_break(lctx, e.span, None);
1462 arm(hir_vec![pat_none(lctx, e.span)], break_expr)
1465 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1468 let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1470 path_global(e.span, strs)
1472 let iter = expr_ident(lctx, e.span, iter, None);
1473 let ref_mut_iter = expr_mut_addr_of(lctx, e.span, iter, None);
1474 let next_path = expr_path(lctx, next_path, None);
1475 let next_expr = expr_call(lctx,
1478 hir_vec![ref_mut_iter],
1480 let arms = hir_vec![pat_arm, break_arm];
1484 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
1488 // `[opt_ident]: loop { ... }`
1489 let loop_block = block_expr(lctx, match_expr);
1490 let loop_expr = hir::ExprLoop(loop_block,
1491 opt_ident.map(|ident| lower_ident(lctx, ident)));
1492 let loop_expr = expr(lctx, e.span, loop_expr, None);
1494 // `mut iter => { ... }`
1496 let iter_pat = pat_ident_binding_mode(lctx,
1499 hir::BindByValue(hir::MutMutable));
1500 arm(hir_vec![iter_pat], loop_expr)
1503 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1504 let into_iter_expr = {
1505 let into_iter_path = {
1506 let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1508 path_global(e.span, strs)
1511 let into_iter = expr_path(lctx, into_iter_path, None);
1512 expr_call(lctx, e.span, into_iter, hir_vec![head], None)
1515 let match_expr = expr_match(lctx,
1519 hir::MatchSource::ForLoopDesugar,
1522 // `{ let _result = ...; _result }`
1523 // underscore prevents an unused_variables lint if the head diverges
1524 let result_ident = lctx.str_to_ident("_result");
1525 let let_stmt = stmt_let(lctx, e.span, false, result_ident, match_expr, None);
1526 let result = expr_ident(lctx, e.span, result_ident, None);
1527 let block = block_all(lctx, e.span, hir_vec![let_stmt], Some(result));
1528 // add the attributes to the outer returned expr node
1529 expr_block(lctx, block, e.attrs.clone())
1533 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
1536 attrs: e.attrs.clone(),
1540 pub fn lower_stmt(lctx: &LoweringContext, s: &Stmt) -> hir::Stmt {
1542 StmtKind::Decl(ref d, id) => {
1544 node: hir::StmtDecl(lower_decl(lctx, d), id),
1548 StmtKind::Expr(ref e, id) => {
1550 node: hir::StmtExpr(lower_expr(lctx, e), id),
1554 StmtKind::Semi(ref e, id) => {
1556 node: hir::StmtSemi(lower_expr(lctx, e), id),
1560 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
1564 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureBy) -> hir::CaptureClause {
1566 CaptureBy::Value => hir::CaptureByValue,
1567 CaptureBy::Ref => hir::CaptureByRef,
1571 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1573 Visibility::Public => hir::Public,
1574 Visibility::Inherited => hir::Inherited,
1578 pub fn lower_block_check_mode(lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1580 BlockCheckMode::Default => hir::DefaultBlock,
1581 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(lower_unsafe_source(lctx, u)),
1585 pub fn lower_binding_mode(lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1587 BindingMode::ByRef(m) => hir::BindByRef(lower_mutability(lctx, m)),
1588 BindingMode::ByValue(m) => hir::BindByValue(lower_mutability(lctx, m)),
1592 pub fn lower_struct_field_kind(lctx: &LoweringContext,
1593 s: &StructFieldKind)
1594 -> hir::StructFieldKind {
1596 NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(lctx, vis)),
1597 UnnamedField(vis) => hir::UnnamedField(lower_visibility(lctx, vis)),
1601 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1603 CompilerGenerated => hir::CompilerGenerated,
1604 UserProvided => hir::UserProvided,
1608 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1610 ImplPolarity::Positive => hir::ImplPolarity::Positive,
1611 ImplPolarity::Negative => hir::ImplPolarity::Negative,
1615 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1616 f: TraitBoundModifier)
1617 -> hir::TraitBoundModifier {
1619 TraitBoundModifier::None => hir::TraitBoundModifier::None,
1620 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1624 // Helper methods for building HIR.
1626 fn arm(pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1635 fn expr_break(lctx: &LoweringContext, span: Span,
1636 attrs: ThinAttributes) -> P<hir::Expr> {
1637 expr(lctx, span, hir::ExprBreak(None), attrs)
1640 fn expr_call(lctx: &LoweringContext,
1643 args: hir::HirVec<P<hir::Expr>>,
1644 attrs: ThinAttributes)
1646 expr(lctx, span, hir::ExprCall(e, args), attrs)
1649 fn expr_ident(lctx: &LoweringContext, span: Span, id: hir::Ident,
1650 attrs: ThinAttributes) -> P<hir::Expr> {
1651 expr_path(lctx, path_ident(span, id), attrs)
1654 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>,
1655 attrs: ThinAttributes) -> P<hir::Expr> {
1656 expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e), attrs)
1659 fn expr_path(lctx: &LoweringContext, path: hir::Path,
1660 attrs: ThinAttributes) -> P<hir::Expr> {
1661 expr(lctx, path.span, hir::ExprPath(None, path), attrs)
1664 fn expr_match(lctx: &LoweringContext,
1667 arms: hir::HirVec<hir::Arm>,
1668 source: hir::MatchSource,
1669 attrs: ThinAttributes)
1671 expr(lctx, span, hir::ExprMatch(arg, arms, source), attrs)
1674 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>,
1675 attrs: ThinAttributes) -> P<hir::Expr> {
1676 expr(lctx, b.span, hir::ExprBlock(b), attrs)
1679 fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: hir::HirVec<P<hir::Expr>>,
1680 attrs: ThinAttributes) -> P<hir::Expr> {
1681 expr(lctx, sp, hir::ExprTup(exprs), attrs)
1684 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_,
1685 attrs: ThinAttributes) -> P<hir::Expr> {
1694 fn stmt_let(lctx: &LoweringContext,
1699 attrs: ThinAttributes)
1701 let pat = if mutbl {
1702 pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1704 pat_ident(lctx, sp, ident)
1706 let local = P(hir::Local {
1714 let decl = respan(sp, hir::DeclLocal(local));
1715 respan(sp, hir::StmtDecl(P(decl), lctx.next_id()))
1718 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1719 block_all(lctx, expr.span, hir::HirVec::new(), Some(expr))
1722 fn block_all(lctx: &LoweringContext,
1724 stmts: hir::HirVec<hir::Stmt>,
1725 expr: Option<P<hir::Expr>>)
1731 rules: hir::DefaultBlock,
1736 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1737 let some = std_path(lctx, &["option", "Option", "Some"]);
1738 let path = path_global(span, some);
1739 pat_enum(lctx, span, path, hir_vec![pat])
1742 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1743 let none = std_path(lctx, &["option", "Option", "None"]);
1744 let path = path_global(span, none);
1745 pat_enum(lctx, span, path, hir_vec![])
1748 fn pat_enum(lctx: &LoweringContext,
1751 subpats: hir::HirVec<P<hir::Pat>>)
1753 let pt = if subpats.is_empty() {
1754 hir::PatKind::Path(path)
1756 hir::PatKind::TupleStruct(path, Some(subpats))
1761 fn pat_ident(lctx: &LoweringContext, span: Span, ident: hir::Ident) -> P<hir::Pat> {
1762 pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1765 fn pat_ident_binding_mode(lctx: &LoweringContext,
1768 bm: hir::BindingMode)
1770 let pat_ident = hir::PatKind::Ident(bm,
1776 pat(lctx, span, pat_ident)
1779 fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1780 pat(lctx, span, hir::PatKind::Wild)
1783 fn pat(lctx: &LoweringContext, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
1791 fn path_ident(span: Span, id: hir::Ident) -> hir::Path {
1792 path(span, vec![id])
1795 fn path(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1796 path_all(span, false, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1799 fn path_global(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1800 path_all(span, true, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1803 fn path_all(sp: Span,
1805 mut idents: Vec<hir::Ident>,
1806 lifetimes: hir::HirVec<hir::Lifetime>,
1807 types: hir::HirVec<P<hir::Ty>>,
1808 bindings: hir::HirVec<hir::TypeBinding>)
1810 let last_identifier = idents.pop().unwrap();
1811 let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1815 parameters: hir::PathParameters::none(),
1819 segments.push(hir::PathSegment {
1820 identifier: last_identifier,
1821 parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1822 lifetimes: lifetimes,
1830 segments: segments.into(),
1834 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<hir::Ident> {
1835 let mut v = Vec::new();
1836 if let Some(s) = lctx.crate_root {
1837 v.push(hir::Ident::from_name(token::intern(s)));
1839 v.extend(components.iter().map(|s| hir::Ident::from_name(token::intern(s))));
1843 // Given suffix ["b","c","d"], returns path `::std::b::c::d` when
1844 // `fld.cx.use_std`, and `::core::b::c::d` otherwise.
1845 fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path {
1846 let idents = std_path(lctx, components);
1847 path_global(span, idents)
1850 fn signal_block_expr(lctx: &LoweringContext,
1851 stmts: hir::HirVec<hir::Stmt>,
1854 rule: hir::BlockCheckMode,
1855 attrs: ThinAttributes)
1857 let id = lctx.next_id();
1874 use syntax::ast::{self, NodeId, NodeIdAssigner};
1875 use syntax::{parse, codemap};
1876 use syntax::fold::Folder;
1877 use std::cell::Cell;
1879 struct MockAssigner {
1880 next_id: Cell<NodeId>,
1884 fn new() -> MockAssigner {
1885 MockAssigner { next_id: Cell::new(0) }
1890 fn call_site(&self) -> codemap::Span;
1891 fn cfg(&self) -> ast::CrateConfig;
1892 fn ident_of(&self, st: &str) -> ast::Ident;
1893 fn name_of(&self, st: &str) -> ast::Name;
1894 fn parse_sess(&self) -> &parse::ParseSess;
1897 impl FakeExtCtxt for parse::ParseSess {
1898 fn call_site(&self) -> codemap::Span {
1900 lo: codemap::BytePos(0),
1901 hi: codemap::BytePos(0),
1902 expn_id: codemap::NO_EXPANSION,
1905 fn cfg(&self) -> ast::CrateConfig {
1908 fn ident_of(&self, st: &str) -> ast::Ident {
1909 parse::token::str_to_ident(st)
1911 fn name_of(&self, st: &str) -> ast::Name {
1912 parse::token::intern(st)
1914 fn parse_sess(&self) -> &parse::ParseSess {
1919 impl NodeIdAssigner for MockAssigner {
1920 fn next_node_id(&self) -> NodeId {
1921 let result = self.next_id.get();
1922 self.next_id.set(result + 1);
1926 fn peek_node_id(&self) -> NodeId {
1931 impl Folder for MockAssigner {
1932 fn new_id(&mut self, old_id: NodeId) -> NodeId {
1933 assert_eq!(old_id, ast::DUMMY_NODE_ID);
1939 fn test_preserves_ids() {
1940 let cx = parse::ParseSess::new();
1941 let mut assigner = MockAssigner::new();
1943 let ast_if_let = quote_expr!(&cx,
1944 if let Some(foo) = baz {
1947 let ast_if_let = assigner.fold_expr(ast_if_let);
1948 let ast_while_let = quote_expr!(&cx,
1949 while let Some(foo) = baz {
1952 let ast_while_let = assigner.fold_expr(ast_while_let);
1953 let ast_for = quote_expr!(&cx,
1959 let ast_for = assigner.fold_expr(ast_for);
1960 let ast_in = quote_expr!(&cx, in HEAP { foo() });
1961 let ast_in = assigner.fold_expr(ast_in);
1963 let lctx = LoweringContext::new(&assigner, None);
1964 let hir1 = lower_expr(&lctx, &ast_if_let);
1965 let hir2 = lower_expr(&lctx, &ast_if_let);
1966 assert!(hir1 == hir2);
1968 let hir1 = lower_expr(&lctx, &ast_while_let);
1969 let hir2 = lower_expr(&lctx, &ast_while_let);
1970 assert!(hir1 == hir2);
1972 let hir1 = lower_expr(&lctx, &ast_for);
1973 let hir2 = lower_expr(&lctx, &ast_for);
1974 assert!(hir1 == hir2);
1976 let hir1 = lower_expr(&lctx, &ast_in);
1977 let hir2 = lower_expr(&lctx, &ast_in);
1978 assert!(hir1 == hir2);