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::attr::{ThinAttributes, ThinAttributesExt};
71 use syntax::ext::mtwt;
73 use syntax::codemap::{respan, Spanned, Span};
74 use syntax::parse::token;
75 use syntax::std_inject;
76 use syntax::visit::{self, Visitor};
78 use std::cell::{Cell, RefCell};
80 pub struct LoweringContext<'a> {
81 crate_root: Option<&'static str>,
82 // Map AST ids to ids used for expanded nodes.
83 id_cache: RefCell<HashMap<NodeId, NodeId>>,
84 // Use if there are no cached ids for the current node.
85 id_assigner: &'a NodeIdAssigner,
86 // 0 == no cached id. Must be incremented to align with previous id
89 // Keep track of gensym'ed idents.
90 gensym_cache: RefCell<HashMap<(NodeId, &'static str), hir::Ident>>,
91 // A copy of cached_id, but is also set to an id while a node is lowered for
93 gensym_key: Cell<u32>,
96 impl<'a, 'hir> LoweringContext<'a> {
97 pub fn new(id_assigner: &'a NodeIdAssigner, c: Option<&Crate>) -> LoweringContext<'a> {
98 let crate_root = c.and_then(|c| {
99 if std_inject::no_core(c) {
101 } else if std_inject::no_std(c) {
109 crate_root: crate_root,
110 id_cache: RefCell::new(HashMap::new()),
111 id_assigner: id_assigner,
112 cached_id: Cell::new(0),
113 gensym_cache: RefCell::new(HashMap::new()),
114 gensym_key: Cell::new(0),
118 fn next_id(&self) -> NodeId {
119 let cached_id = self.cached_id.get();
121 return self.id_assigner.next_node_id();
124 self.cached_id.set(cached_id + 1);
128 fn str_to_ident(&self, s: &'static str) -> hir::Ident {
129 let gensym_key = self.gensym_key.get();
131 return hir::Ident::from_name(token::gensym(s));
134 let cached = self.gensym_cache.borrow().contains_key(&(gensym_key, s));
136 self.gensym_cache.borrow()[&(gensym_key, s)]
138 let result = hir::Ident::from_name(token::gensym(s));
139 self.gensym_cache.borrow_mut().insert((gensym_key, s), result);
145 // Utility fn for setting and unsetting the cached id.
146 fn cache_ids<'a, OP, R>(lctx: &LoweringContext, expr_id: NodeId, op: OP) -> R
147 where OP: FnOnce(&LoweringContext) -> R
149 // Only reset the id if it was previously 0, i.e., was not cached.
150 // If it was cached, we are in a nested node, but our id count will
151 // still count towards the parent's count.
152 let reset_cached_id = lctx.cached_id.get() == 0;
153 // We always reset gensym_key so that if we use the same name in a nested
154 // node and after that node, they get different values.
155 let old_gensym_key = lctx.gensym_key.get();
158 let id_cache: &mut HashMap<_, _> = &mut lctx.id_cache.borrow_mut();
160 if id_cache.contains_key(&expr_id) {
161 let cached_id = lctx.cached_id.get();
163 // We're entering a node where we need to track ids, but are not
165 lctx.cached_id.set(id_cache[&expr_id]);
167 // We're already tracking - check that the tracked id is the same
168 // as the expected id.
169 assert!(cached_id == id_cache[&expr_id], "id mismatch");
171 lctx.gensym_key.set(id_cache[&expr_id]);
173 // We've never lowered this node before, remember it for next time.
174 let next_id = lctx.id_assigner.peek_node_id();
175 id_cache.insert(expr_id, next_id);
176 lctx.gensym_key.set(next_id);
177 // self.cached_id is not set when we lower a node for the first time,
178 // only on re-lowering.
182 let result = op(lctx);
185 lctx.cached_id.set(0);
187 lctx.gensym_key.set(old_gensym_key);
192 pub fn lower_ident(_lctx: &LoweringContext, ident: Ident) -> hir::Ident {
194 name: mtwt::resolve(ident),
195 unhygienic_name: ident.name,
199 pub fn lower_attrs(_lctx: &LoweringContext, attrs: &Vec<Attribute>) -> hir::HirVec<Attribute> {
203 pub fn lower_view_path(lctx: &LoweringContext, view_path: &ViewPath) -> P<hir::ViewPath> {
205 node: match view_path.node {
206 ViewPathSimple(ident, ref path) => {
207 hir::ViewPathSimple(ident.name, lower_path(lctx, path))
209 ViewPathGlob(ref path) => {
210 hir::ViewPathGlob(lower_path(lctx, path))
212 ViewPathList(ref path, ref path_list_idents) => {
213 hir::ViewPathList(lower_path(lctx, path),
214 path_list_idents.iter()
215 .map(lower_path_list_item)
219 span: view_path.span,
223 fn lower_path_list_item(path_list_ident: &PathListItem) -> hir::PathListItem {
225 node: match path_list_ident.node {
226 PathListItemKind::Ident { id, name, rename } => hir::PathListIdent {
229 rename: rename.map(|x| x.name),
231 PathListItemKind::Mod { id, rename } => hir::PathListMod {
233 rename: rename.map(|x| x.name),
236 span: path_list_ident.span,
240 pub fn lower_arm(lctx: &LoweringContext, arm: &Arm) -> hir::Arm {
242 attrs: lower_attrs(lctx, &arm.attrs),
243 pats: arm.pats.iter().map(|x| lower_pat(lctx, x)).collect(),
244 guard: arm.guard.as_ref().map(|ref x| lower_expr(lctx, x)),
245 body: lower_expr(lctx, &arm.body),
249 pub fn lower_decl(lctx: &LoweringContext, d: &Decl) -> P<hir::Decl> {
251 DeclKind::Local(ref l) => P(Spanned {
252 node: hir::DeclLocal(lower_local(lctx, l)),
255 DeclKind::Item(ref it) => P(Spanned {
256 node: hir::DeclItem(lower_item_id(lctx, it)),
262 pub fn lower_ty_binding(lctx: &LoweringContext, b: &TypeBinding) -> hir::TypeBinding {
266 ty: lower_ty(lctx, &b.ty),
271 pub fn lower_ty(lctx: &LoweringContext, t: &Ty) -> P<hir::Ty> {
272 use syntax::ast::TyKind::*;
276 Infer => hir::TyInfer,
277 Vec(ref ty) => hir::TyVec(lower_ty(lctx, ty)),
278 Ptr(ref mt) => hir::TyPtr(lower_mt(lctx, mt)),
279 Rptr(ref region, ref mt) => {
280 hir::TyRptr(lower_opt_lifetime(lctx, region), lower_mt(lctx, mt))
283 hir::TyBareFn(P(hir::BareFnTy {
284 lifetimes: lower_lifetime_defs(lctx, &f.lifetimes),
285 unsafety: lower_unsafety(lctx, f.unsafety),
287 decl: lower_fn_decl(lctx, &f.decl),
290 Tup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(lctx, ty)).collect()),
292 return lower_ty(lctx, ty);
294 Path(ref qself, ref path) => {
295 let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
297 ty: lower_ty(lctx, ty),
301 hir::TyPath(qself, lower_path(lctx, path))
303 ObjectSum(ref ty, ref bounds) => {
304 hir::TyObjectSum(lower_ty(lctx, ty), lower_bounds(lctx, bounds))
306 FixedLengthVec(ref ty, ref e) => {
307 hir::TyFixedLengthVec(lower_ty(lctx, ty), lower_expr(lctx, e))
309 Typeof(ref expr) => {
310 hir::TyTypeof(lower_expr(lctx, expr))
312 PolyTraitRef(ref bounds) => {
313 hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(lctx, b)).collect())
315 Mac(_) => panic!("TyMac should have been expanded by now."),
321 pub fn lower_foreign_mod(lctx: &LoweringContext, fm: &ForeignMod) -> hir::ForeignMod {
324 items: fm.items.iter().map(|x| lower_foreign_item(lctx, x)).collect(),
328 pub fn lower_variant(lctx: &LoweringContext, v: &Variant) -> hir::Variant {
330 node: hir::Variant_ {
331 name: v.node.name.name,
332 attrs: lower_attrs(lctx, &v.node.attrs),
333 data: lower_variant_data(lctx, &v.node.data),
334 disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(lctx, e)),
340 // Path segments are usually unhygienic, hygienic path segments can occur only in
341 // identifier-like paths originating from `ExprPath`.
342 // Make life simpler for rustc_resolve by renaming only such segments.
343 pub fn lower_path_full(lctx: &LoweringContext, p: &Path, maybe_hygienic: bool) -> hir::Path {
344 let maybe_hygienic = maybe_hygienic && !p.global && p.segments.len() == 1;
349 .map(|&PathSegment { identifier, ref parameters }| {
351 identifier: if maybe_hygienic {
352 lower_ident(lctx, identifier)
354 hir::Ident::from_name(identifier.name)
356 parameters: lower_path_parameters(lctx, parameters),
364 pub fn lower_path(lctx: &LoweringContext, p: &Path) -> hir::Path {
365 lower_path_full(lctx, p, false)
368 pub fn lower_path_parameters(lctx: &LoweringContext,
369 path_parameters: &PathParameters)
370 -> hir::PathParameters {
371 match *path_parameters {
372 PathParameters::AngleBracketed(ref data) =>
373 hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(lctx, data)),
374 PathParameters::Parenthesized(ref data) =>
375 hir::ParenthesizedParameters(lower_parenthesized_parameter_data(lctx, data)),
379 pub fn lower_angle_bracketed_parameter_data(lctx: &LoweringContext,
380 data: &AngleBracketedParameterData)
381 -> hir::AngleBracketedParameterData {
382 let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
383 hir::AngleBracketedParameterData {
384 lifetimes: lower_lifetimes(lctx, lifetimes),
385 types: types.iter().map(|ty| lower_ty(lctx, ty)).collect(),
386 bindings: bindings.iter().map(|b| lower_ty_binding(lctx, b)).collect(),
390 pub fn lower_parenthesized_parameter_data(lctx: &LoweringContext,
391 data: &ParenthesizedParameterData)
392 -> hir::ParenthesizedParameterData {
393 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
394 hir::ParenthesizedParameterData {
395 inputs: inputs.iter().map(|ty| lower_ty(lctx, ty)).collect(),
396 output: output.as_ref().map(|ty| lower_ty(lctx, ty)),
401 pub fn lower_local(lctx: &LoweringContext, l: &Local) -> P<hir::Local> {
404 ty: l.ty.as_ref().map(|t| lower_ty(lctx, t)),
405 pat: lower_pat(lctx, &l.pat),
406 init: l.init.as_ref().map(|e| lower_expr(lctx, e)),
408 attrs: l.attrs.clone(),
412 pub fn lower_explicit_self_underscore(lctx: &LoweringContext,
414 -> hir::ExplicitSelf_ {
416 SelfKind::Static => hir::SelfStatic,
417 SelfKind::Value(v) => hir::SelfValue(v.name),
418 SelfKind::Region(ref lifetime, m, ident) => {
419 hir::SelfRegion(lower_opt_lifetime(lctx, lifetime),
420 lower_mutability(lctx, m),
423 SelfKind::Explicit(ref typ, ident) => {
424 hir::SelfExplicit(lower_ty(lctx, typ), ident.name)
429 pub fn lower_mutability(_lctx: &LoweringContext, m: Mutability) -> hir::Mutability {
431 Mutability::Mutable => hir::MutMutable,
432 Mutability::Immutable => hir::MutImmutable,
436 pub fn lower_explicit_self(lctx: &LoweringContext, s: &ExplicitSelf) -> hir::ExplicitSelf {
438 node: lower_explicit_self_underscore(lctx, &s.node),
443 pub fn lower_arg(lctx: &LoweringContext, arg: &Arg) -> hir::Arg {
446 pat: lower_pat(lctx, &arg.pat),
447 ty: lower_ty(lctx, &arg.ty),
451 pub fn lower_fn_decl(lctx: &LoweringContext, decl: &FnDecl) -> P<hir::FnDecl> {
453 inputs: decl.inputs.iter().map(|x| lower_arg(lctx, x)).collect(),
454 output: match decl.output {
455 FunctionRetTy::Ty(ref ty) => hir::Return(lower_ty(lctx, ty)),
456 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
457 FunctionRetTy::None(span) => hir::NoReturn(span),
459 variadic: decl.variadic,
463 pub fn lower_ty_param_bound(lctx: &LoweringContext, tpb: &TyParamBound) -> hir::TyParamBound {
465 TraitTyParamBound(ref ty, modifier) => {
466 hir::TraitTyParamBound(lower_poly_trait_ref(lctx, ty),
467 lower_trait_bound_modifier(lctx, modifier))
469 RegionTyParamBound(ref lifetime) => {
470 hir::RegionTyParamBound(lower_lifetime(lctx, lifetime))
475 pub fn lower_ty_param(lctx: &LoweringContext, tp: &TyParam) -> hir::TyParam {
479 bounds: lower_bounds(lctx, &tp.bounds),
480 default: tp.default.as_ref().map(|x| lower_ty(lctx, x)),
485 pub fn lower_ty_params(lctx: &LoweringContext,
487 -> hir::HirVec<hir::TyParam> {
488 tps.iter().map(|tp| lower_ty_param(lctx, tp)).collect()
491 pub fn lower_lifetime(_lctx: &LoweringContext, l: &Lifetime) -> hir::Lifetime {
499 pub fn lower_lifetime_def(lctx: &LoweringContext, l: &LifetimeDef) -> hir::LifetimeDef {
501 lifetime: lower_lifetime(lctx, &l.lifetime),
502 bounds: lower_lifetimes(lctx, &l.bounds),
506 pub fn lower_lifetimes(lctx: &LoweringContext, lts: &Vec<Lifetime>) -> hir::HirVec<hir::Lifetime> {
507 lts.iter().map(|l| lower_lifetime(lctx, l)).collect()
510 pub fn lower_lifetime_defs(lctx: &LoweringContext,
511 lts: &Vec<LifetimeDef>)
512 -> hir::HirVec<hir::LifetimeDef> {
513 lts.iter().map(|l| lower_lifetime_def(lctx, l)).collect()
516 pub fn lower_opt_lifetime(lctx: &LoweringContext,
517 o_lt: &Option<Lifetime>)
518 -> Option<hir::Lifetime> {
519 o_lt.as_ref().map(|lt| lower_lifetime(lctx, lt))
522 pub fn lower_generics(lctx: &LoweringContext, g: &Generics) -> hir::Generics {
524 ty_params: lower_ty_params(lctx, &g.ty_params),
525 lifetimes: lower_lifetime_defs(lctx, &g.lifetimes),
526 where_clause: lower_where_clause(lctx, &g.where_clause),
530 pub fn lower_where_clause(lctx: &LoweringContext, wc: &WhereClause) -> hir::WhereClause {
533 predicates: wc.predicates
535 .map(|predicate| lower_where_predicate(lctx, predicate))
540 pub fn lower_where_predicate(lctx: &LoweringContext,
541 pred: &WherePredicate)
542 -> hir::WherePredicate {
544 WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
548 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
549 bound_lifetimes: lower_lifetime_defs(lctx, bound_lifetimes),
550 bounded_ty: lower_ty(lctx, bounded_ty),
551 bounds: bounds.iter().map(|x| lower_ty_param_bound(lctx, x)).collect(),
555 WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
558 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
560 lifetime: lower_lifetime(lctx, lifetime),
561 bounds: bounds.iter().map(|bound| lower_lifetime(lctx, bound)).collect(),
564 WherePredicate::EqPredicate(WhereEqPredicate{ id,
568 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
570 path: lower_path(lctx, path),
571 ty: lower_ty(lctx, ty),
578 pub fn lower_variant_data(lctx: &LoweringContext, vdata: &VariantData) -> hir::VariantData {
580 VariantData::Struct(ref fields, id) => {
581 hir::VariantData::Struct(fields.iter()
583 .map(|f| lower_struct_field(lctx, f))
587 VariantData::Tuple(ref fields, id) => {
588 hir::VariantData::Tuple(fields.iter()
590 .map(|f| lower_struct_field(lctx, f))
594 VariantData::Unit(id) => hir::VariantData::Unit(id),
598 pub fn lower_trait_ref(lctx: &LoweringContext, p: &TraitRef) -> hir::TraitRef {
600 path: lower_path(lctx, &p.path),
605 pub fn lower_poly_trait_ref(lctx: &LoweringContext, p: &PolyTraitRef) -> hir::PolyTraitRef {
607 bound_lifetimes: lower_lifetime_defs(lctx, &p.bound_lifetimes),
608 trait_ref: lower_trait_ref(lctx, &p.trait_ref),
613 pub fn lower_struct_field(lctx: &LoweringContext,
614 (index, f): (usize, &StructField))
615 -> hir::StructField {
619 name: f.node.ident().map(|ident| ident.name)
620 .unwrap_or(token::intern(&index.to_string())),
621 vis: lower_visibility(lctx, f.node.kind.visibility()),
622 ty: lower_ty(lctx, &f.node.ty),
623 attrs: lower_attrs(lctx, &f.node.attrs),
627 pub fn lower_field(lctx: &LoweringContext, f: &Field) -> hir::Field {
629 name: respan(f.ident.span, f.ident.node.name),
630 expr: lower_expr(lctx, &f.expr),
635 pub fn lower_mt(lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy {
637 ty: lower_ty(lctx, &mt.ty),
638 mutbl: lower_mutability(lctx, mt.mutbl),
642 pub fn lower_opt_bounds(lctx: &LoweringContext,
643 b: &Option<TyParamBounds>)
644 -> Option<hir::TyParamBounds> {
645 b.as_ref().map(|ref bounds| lower_bounds(lctx, bounds))
648 fn lower_bounds(lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParamBounds {
649 bounds.iter().map(|bound| lower_ty_param_bound(lctx, bound)).collect()
652 pub fn lower_block(lctx: &LoweringContext, b: &Block) -> P<hir::Block> {
655 stmts: b.stmts.iter().map(|s| lower_stmt(lctx, s)).collect(),
656 expr: b.expr.as_ref().map(|ref x| lower_expr(lctx, x)),
657 rules: lower_block_check_mode(lctx, &b.rules),
662 pub fn lower_item_kind(lctx: &LoweringContext, i: &ItemKind) -> hir::Item_ {
664 ItemKind::ExternCrate(string) => hir::ItemExternCrate(string),
665 ItemKind::Use(ref view_path) => {
666 hir::ItemUse(lower_view_path(lctx, view_path))
668 ItemKind::Static(ref t, m, ref e) => {
669 hir::ItemStatic(lower_ty(lctx, t),
670 lower_mutability(lctx, m),
673 ItemKind::Const(ref t, ref e) => {
674 hir::ItemConst(lower_ty(lctx, t), lower_expr(lctx, e))
676 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
677 hir::ItemFn(lower_fn_decl(lctx, decl),
678 lower_unsafety(lctx, unsafety),
679 lower_constness(lctx, constness),
681 lower_generics(lctx, generics),
682 lower_block(lctx, body))
684 ItemKind::Mod(ref m) => hir::ItemMod(lower_mod(lctx, m)),
685 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(lctx, nm)),
686 ItemKind::Ty(ref t, ref generics) => {
687 hir::ItemTy(lower_ty(lctx, t), lower_generics(lctx, generics))
689 ItemKind::Enum(ref enum_definition, ref generics) => {
690 hir::ItemEnum(hir::EnumDef {
691 variants: enum_definition.variants
693 .map(|x| lower_variant(lctx, x))
696 lower_generics(lctx, generics))
698 ItemKind::Struct(ref struct_def, ref generics) => {
699 let struct_def = lower_variant_data(lctx, struct_def);
700 hir::ItemStruct(struct_def, lower_generics(lctx, generics))
702 ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
703 hir::ItemDefaultImpl(lower_unsafety(lctx, unsafety),
704 lower_trait_ref(lctx, trait_ref))
706 ItemKind::Impl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
707 let new_impl_items = impl_items.iter()
708 .map(|item| lower_impl_item(lctx, item))
710 let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(lctx, trait_ref));
711 hir::ItemImpl(lower_unsafety(lctx, unsafety),
712 lower_impl_polarity(lctx, polarity),
713 lower_generics(lctx, generics),
718 ItemKind::Trait(unsafety, ref generics, ref bounds, ref items) => {
719 let bounds = lower_bounds(lctx, bounds);
720 let items = items.iter().map(|item| lower_trait_item(lctx, item)).collect();
721 hir::ItemTrait(lower_unsafety(lctx, unsafety),
722 lower_generics(lctx, generics),
726 ItemKind::Mac(_) => panic!("Shouldn't still be around"),
730 pub fn lower_trait_item(lctx: &LoweringContext, i: &TraitItem) -> hir::TraitItem {
734 attrs: lower_attrs(lctx, &i.attrs),
736 TraitItemKind::Const(ref ty, ref default) => {
737 hir::ConstTraitItem(lower_ty(lctx, ty),
738 default.as_ref().map(|x| lower_expr(lctx, x)))
740 TraitItemKind::Method(ref sig, ref body) => {
741 hir::MethodTraitItem(lower_method_sig(lctx, sig),
742 body.as_ref().map(|x| lower_block(lctx, x)))
744 TraitItemKind::Type(ref bounds, ref default) => {
745 hir::TypeTraitItem(lower_bounds(lctx, bounds),
746 default.as_ref().map(|x| lower_ty(lctx, x)))
753 pub fn lower_impl_item(lctx: &LoweringContext, i: &ImplItem) -> hir::ImplItem {
757 attrs: lower_attrs(lctx, &i.attrs),
758 vis: lower_visibility(lctx, i.vis),
760 ImplItemKind::Const(ref ty, ref expr) => {
761 hir::ImplItemKind::Const(lower_ty(lctx, ty), lower_expr(lctx, expr))
763 ImplItemKind::Method(ref sig, ref body) => {
764 hir::ImplItemKind::Method(lower_method_sig(lctx, sig), lower_block(lctx, body))
766 ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(lower_ty(lctx, ty)),
767 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
773 pub fn lower_mod(lctx: &LoweringContext, m: &Mod) -> hir::Mod {
776 item_ids: m.items.iter().map(|x| lower_item_id(lctx, x)).collect(),
780 struct ItemLowerer<'lcx, 'interner: 'lcx> {
781 items: BTreeMap<NodeId, hir::Item>,
782 lctx: &'lcx LoweringContext<'interner>,
785 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
786 fn visit_item(&mut self, item: &'lcx Item) {
787 self.items.insert(item.id, lower_item(self.lctx, item));
788 visit::walk_item(self, item);
792 pub fn lower_crate(lctx: &LoweringContext, c: &Crate) -> hir::Crate {
794 let mut item_lowerer = ItemLowerer { items: BTreeMap::new(), lctx: lctx };
795 visit::walk_crate(&mut item_lowerer, c);
800 module: lower_mod(lctx, &c.module),
801 attrs: lower_attrs(lctx, &c.attrs),
802 config: c.config.clone().into(),
804 exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(lctx, m)).collect(),
809 pub fn lower_macro_def(lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef {
812 attrs: lower_attrs(lctx, &m.attrs),
815 imported_from: m.imported_from.map(|x| x.name),
817 use_locally: m.use_locally,
818 allow_internal_unstable: m.allow_internal_unstable,
819 body: m.body.clone().into(),
823 pub fn lower_item_id(_lctx: &LoweringContext, i: &Item) -> hir::ItemId {
824 hir::ItemId { id: i.id }
827 pub fn lower_item(lctx: &LoweringContext, i: &Item) -> hir::Item {
828 let node = lower_item_kind(lctx, &i.node);
833 attrs: lower_attrs(lctx, &i.attrs),
835 vis: lower_visibility(lctx, i.vis),
840 pub fn lower_foreign_item(lctx: &LoweringContext, i: &ForeignItem) -> hir::ForeignItem {
844 attrs: lower_attrs(lctx, &i.attrs),
846 ForeignItemKind::Fn(ref fdec, ref generics) => {
847 hir::ForeignItemFn(lower_fn_decl(lctx, fdec), lower_generics(lctx, generics))
849 ForeignItemKind::Static(ref t, m) => {
850 hir::ForeignItemStatic(lower_ty(lctx, t), m)
853 vis: lower_visibility(lctx, i.vis),
858 pub fn lower_method_sig(lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig {
860 generics: lower_generics(lctx, &sig.generics),
862 explicit_self: lower_explicit_self(lctx, &sig.explicit_self),
863 unsafety: lower_unsafety(lctx, sig.unsafety),
864 constness: lower_constness(lctx, sig.constness),
865 decl: lower_fn_decl(lctx, &sig.decl),
869 pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety {
871 Unsafety::Unsafe => hir::Unsafety::Unsafe,
872 Unsafety::Normal => hir::Unsafety::Normal,
876 pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness {
878 Constness::Const => hir::Constness::Const,
879 Constness::NotConst => hir::Constness::NotConst,
883 pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp {
885 UnOp::Deref => hir::UnDeref,
886 UnOp::Not => hir::UnNot,
887 UnOp::Neg => hir::UnNeg,
891 pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp {
894 BinOpKind::Add => hir::BiAdd,
895 BinOpKind::Sub => hir::BiSub,
896 BinOpKind::Mul => hir::BiMul,
897 BinOpKind::Div => hir::BiDiv,
898 BinOpKind::Rem => hir::BiRem,
899 BinOpKind::And => hir::BiAnd,
900 BinOpKind::Or => hir::BiOr,
901 BinOpKind::BitXor => hir::BiBitXor,
902 BinOpKind::BitAnd => hir::BiBitAnd,
903 BinOpKind::BitOr => hir::BiBitOr,
904 BinOpKind::Shl => hir::BiShl,
905 BinOpKind::Shr => hir::BiShr,
906 BinOpKind::Eq => hir::BiEq,
907 BinOpKind::Lt => hir::BiLt,
908 BinOpKind::Le => hir::BiLe,
909 BinOpKind::Ne => hir::BiNe,
910 BinOpKind::Ge => hir::BiGe,
911 BinOpKind::Gt => hir::BiGt,
917 pub fn lower_pat(lctx: &LoweringContext, p: &Pat) -> P<hir::Pat> {
921 PatKind::Wild => hir::PatKind::Wild,
922 PatKind::Ident(ref binding_mode, pth1, ref sub) => {
923 hir::PatKind::Ident(lower_binding_mode(lctx, binding_mode),
924 respan(pth1.span, lower_ident(lctx, pth1.node)),
925 sub.as_ref().map(|x| lower_pat(lctx, x)))
927 PatKind::Lit(ref e) => hir::PatKind::Lit(lower_expr(lctx, e)),
928 PatKind::TupleStruct(ref pth, ref pats) => {
929 hir::PatKind::TupleStruct(lower_path(lctx, pth),
931 .map(|pats| pats.iter().map(|x| lower_pat(lctx, x)).collect()))
933 PatKind::Path(ref pth) => {
934 hir::PatKind::Path(lower_path(lctx, pth))
936 PatKind::QPath(ref qself, ref pth) => {
937 let qself = hir::QSelf {
938 ty: lower_ty(lctx, &qself.ty),
939 position: qself.position,
941 hir::PatKind::QPath(qself, lower_path(lctx, pth))
943 PatKind::Struct(ref pth, ref fields, etc) => {
944 let pth = lower_path(lctx, pth);
945 let fs = fields.iter()
949 node: hir::FieldPat {
950 name: f.node.ident.name,
951 pat: lower_pat(lctx, &f.node.pat),
952 is_shorthand: f.node.is_shorthand,
957 hir::PatKind::Struct(pth, fs, etc)
959 PatKind::Tup(ref elts) => {
960 hir::PatKind::Tup(elts.iter().map(|x| lower_pat(lctx, x)).collect())
962 PatKind::Box(ref inner) => hir::PatKind::Box(lower_pat(lctx, inner)),
963 PatKind::Ref(ref inner, mutbl) => {
964 hir::PatKind::Ref(lower_pat(lctx, inner), lower_mutability(lctx, mutbl))
966 PatKind::Range(ref e1, ref e2) => {
967 hir::PatKind::Range(lower_expr(lctx, e1), lower_expr(lctx, e2))
969 PatKind::Vec(ref before, ref slice, ref after) => {
970 hir::PatKind::Vec(before.iter().map(|x| lower_pat(lctx, x)).collect(),
971 slice.as_ref().map(|x| lower_pat(lctx, x)),
972 after.iter().map(|x| lower_pat(lctx, x)).collect())
974 PatKind::Mac(_) => panic!("Shouldn't exist here"),
980 pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
985 // Eventually a desugaring for `box EXPR`
986 // (similar to the desugaring above for `in PLACE BLOCK`)
987 // should go here, desugaring
991 // let mut place = BoxPlace::make_place();
992 // let raw_place = Place::pointer(&mut place);
993 // let value = $value;
995 // ::std::ptr::write(raw_place, value);
996 // Boxed::finalize(place)
999 // But for now there are type-inference issues doing that.
1000 ExprKind::Box(ref e) => {
1001 hir::ExprBox(lower_expr(lctx, e))
1004 // Desugar ExprBox: `in (PLACE) EXPR`
1005 ExprKind::InPlace(ref placer, ref value_expr) => {
1009 // let mut place = Placer::make_place(p);
1010 // let raw_place = Place::pointer(&mut place);
1012 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1013 // InPlace::finalize(place)
1015 return cache_ids(lctx, e.id, |lctx| {
1016 let placer_expr = lower_expr(lctx, placer);
1017 let value_expr = lower_expr(lctx, value_expr);
1019 let placer_ident = lctx.str_to_ident("placer");
1020 let place_ident = lctx.str_to_ident("place");
1021 let p_ptr_ident = lctx.str_to_ident("p_ptr");
1023 let make_place = ["ops", "Placer", "make_place"];
1024 let place_pointer = ["ops", "Place", "pointer"];
1025 let move_val_init = ["intrinsics", "move_val_init"];
1026 let inplace_finalize = ["ops", "InPlace", "finalize"];
1028 let make_call = |lctx: &LoweringContext, p, args| {
1029 let path = core_path(lctx, e.span, p);
1030 let path = expr_path(lctx, path, None);
1031 expr_call(lctx, e.span, path, args, None)
1034 let mk_stmt_let = |lctx: &LoweringContext, bind, expr| {
1035 stmt_let(lctx, e.span, false, bind, expr, None)
1038 let mk_stmt_let_mut = |lctx: &LoweringContext, bind, expr| {
1039 stmt_let(lctx, e.span, true, bind, expr, None)
1042 // let placer = <placer_expr> ;
1044 let placer_expr = signal_block_expr(lctx,
1048 hir::PopUnstableBlock,
1050 mk_stmt_let(lctx, placer_ident, placer_expr)
1053 // let mut place = Placer::make_place(placer);
1055 let placer = expr_ident(lctx, e.span, placer_ident, None);
1056 let call = make_call(lctx, &make_place, hir_vec![placer]);
1057 mk_stmt_let_mut(lctx, place_ident, call)
1060 // let p_ptr = Place::pointer(&mut place);
1062 let agent = expr_ident(lctx, e.span, place_ident, None);
1063 let args = hir_vec![expr_mut_addr_of(lctx, e.span, agent, None)];
1064 let call = make_call(lctx, &place_pointer, args);
1065 mk_stmt_let(lctx, p_ptr_ident, call)
1068 // pop_unsafe!(EXPR));
1069 let pop_unsafe_expr = {
1070 let value_expr = signal_block_expr(lctx,
1074 hir::PopUnstableBlock,
1076 signal_block_expr(lctx,
1080 hir::PopUnsafeBlock(hir::CompilerGenerated), None)
1084 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1085 // InPlace::finalize(place)
1088 let ptr = expr_ident(lctx, e.span, p_ptr_ident, None);
1089 let call_move_val_init =
1091 make_call(lctx, &move_val_init, hir_vec![ptr, pop_unsafe_expr]),
1093 let call_move_val_init = respan(e.span, call_move_val_init);
1095 let place = expr_ident(lctx, e.span, place_ident, None);
1096 let call = make_call(lctx, &inplace_finalize, hir_vec![place]);
1097 signal_block_expr(lctx,
1098 hir_vec![call_move_val_init],
1101 hir::PushUnsafeBlock(hir::CompilerGenerated), None)
1104 signal_block_expr(lctx,
1105 hir_vec![s1, s2, s3],
1108 hir::PushUnstableBlock,
1113 ExprKind::Vec(ref exprs) => {
1114 hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect())
1116 ExprKind::Repeat(ref expr, ref count) => {
1117 let expr = lower_expr(lctx, expr);
1118 let count = lower_expr(lctx, count);
1119 hir::ExprRepeat(expr, count)
1121 ExprKind::Tup(ref elts) => {
1122 hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect())
1124 ExprKind::Call(ref f, ref args) => {
1125 let f = lower_expr(lctx, f);
1126 hir::ExprCall(f, args.iter().map(|x| lower_expr(lctx, x)).collect())
1128 ExprKind::MethodCall(i, ref tps, ref args) => {
1129 let tps = tps.iter().map(|x| lower_ty(lctx, x)).collect();
1130 let args = args.iter().map(|x| lower_expr(lctx, x)).collect();
1131 hir::ExprMethodCall(respan(i.span, i.node.name), tps, args)
1133 ExprKind::Binary(binop, ref lhs, ref rhs) => {
1134 let binop = lower_binop(lctx, binop);
1135 let lhs = lower_expr(lctx, lhs);
1136 let rhs = lower_expr(lctx, rhs);
1137 hir::ExprBinary(binop, lhs, rhs)
1139 ExprKind::Unary(op, ref ohs) => {
1140 let op = lower_unop(lctx, op);
1141 let ohs = lower_expr(lctx, ohs);
1142 hir::ExprUnary(op, ohs)
1144 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
1145 ExprKind::Cast(ref expr, ref ty) => {
1146 let expr = lower_expr(lctx, expr);
1147 hir::ExprCast(expr, lower_ty(lctx, ty))
1149 ExprKind::Type(ref expr, ref ty) => {
1150 let expr = lower_expr(lctx, expr);
1151 hir::ExprType(expr, lower_ty(lctx, ty))
1153 ExprKind::AddrOf(m, ref ohs) => {
1154 let m = lower_mutability(lctx, m);
1155 let ohs = lower_expr(lctx, ohs);
1156 hir::ExprAddrOf(m, ohs)
1158 // More complicated than you might expect because the else branch
1159 // might be `if let`.
1160 ExprKind::If(ref cond, ref blk, ref else_opt) => {
1161 let else_opt = else_opt.as_ref().map(|els| {
1163 ExprKind::IfLet(..) => {
1164 cache_ids(lctx, e.id, |lctx| {
1165 // wrap the if-let expr in a block
1166 let span = els.span;
1167 let els = lower_expr(lctx, els);
1168 let id = lctx.next_id();
1169 let blk = P(hir::Block {
1173 rules: hir::DefaultBlock,
1176 expr_block(lctx, blk, None)
1179 _ => lower_expr(lctx, els),
1183 hir::ExprIf(lower_expr(lctx, cond), lower_block(lctx, blk), else_opt)
1185 ExprKind::While(ref cond, ref body, opt_ident) => {
1186 hir::ExprWhile(lower_expr(lctx, cond), lower_block(lctx, body),
1187 opt_ident.map(|ident| lower_ident(lctx, ident)))
1189 ExprKind::Loop(ref body, opt_ident) => {
1190 hir::ExprLoop(lower_block(lctx, body),
1191 opt_ident.map(|ident| lower_ident(lctx, ident)))
1193 ExprKind::Match(ref expr, ref arms) => {
1194 hir::ExprMatch(lower_expr(lctx, expr),
1195 arms.iter().map(|x| lower_arm(lctx, x)).collect(),
1196 hir::MatchSource::Normal)
1198 ExprKind::Closure(capture_clause, ref decl, ref body) => {
1199 hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
1200 lower_fn_decl(lctx, decl),
1201 lower_block(lctx, body))
1203 ExprKind::Block(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
1204 ExprKind::Assign(ref el, ref er) => {
1205 hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
1207 ExprKind::AssignOp(op, ref el, ref er) => {
1208 hir::ExprAssignOp(lower_binop(lctx, op),
1209 lower_expr(lctx, el),
1210 lower_expr(lctx, er))
1212 ExprKind::Field(ref el, ident) => {
1213 hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
1215 ExprKind::TupField(ref el, ident) => {
1216 hir::ExprTupField(lower_expr(lctx, el), ident)
1218 ExprKind::Index(ref el, ref er) => {
1219 hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
1221 ExprKind::Range(ref e1, ref e2, lims) => {
1222 fn make_struct(lctx: &LoweringContext,
1225 fields: &[(&str, &P<Expr>)]) -> P<hir::Expr> {
1226 let strs = std_path(lctx, &iter::once(&"ops")
1229 .collect::<Vec<_>>());
1231 let structpath = path_global(ast_expr.span, strs);
1233 let hir_expr = if fields.len() == 0 {
1236 ast_expr.attrs.clone())
1241 fields.into_iter().map(|&(s, e)| {
1242 field(token::intern(s),
1243 signal_block_expr(lctx,
1245 lower_expr(lctx, &**e),
1247 hir::PopUnstableBlock,
1252 ast_expr.attrs.clone())
1255 signal_block_expr(lctx,
1259 hir::PushUnstableBlock,
1263 return cache_ids(lctx, e.id, |lctx| {
1264 use syntax::ast::RangeLimits::*;
1266 match (e1, e2, lims) {
1267 (&None, &None, HalfOpen) =>
1268 make_struct(lctx, e, &["RangeFull"],
1271 (&Some(ref e1), &None, HalfOpen) =>
1272 make_struct(lctx, e, &["RangeFrom"],
1275 (&None, &Some(ref e2), HalfOpen) =>
1276 make_struct(lctx, e, &["RangeTo"],
1279 (&Some(ref e1), &Some(ref e2), HalfOpen) =>
1280 make_struct(lctx, e, &["Range"],
1281 &[("start", e1), ("end", e2)]),
1283 (&None, &Some(ref e2), Closed) =>
1284 make_struct(lctx, e, &["RangeToInclusive"],
1287 (&Some(ref e1), &Some(ref e2), Closed) =>
1288 make_struct(lctx, e, &["RangeInclusive", "NonEmpty"],
1289 &[("start", e1), ("end", e2)]),
1291 _ => panic!("impossible range in AST"),
1295 ExprKind::Path(ref qself, ref path) => {
1296 let hir_qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
1298 ty: lower_ty(lctx, ty),
1302 hir::ExprPath(hir_qself, lower_path_full(lctx, path, qself.is_none()))
1304 ExprKind::Break(opt_ident) => hir::ExprBreak(opt_ident.map(|sp_ident| {
1305 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1307 ExprKind::Again(opt_ident) => hir::ExprAgain(opt_ident.map(|sp_ident| {
1308 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1310 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
1311 ExprKind::InlineAsm(InlineAsm {
1321 }) => hir::ExprInlineAsm(hir::InlineAsm {
1322 inputs: inputs.iter()
1323 .map(|&(ref c, ref input)| (c.clone(), lower_expr(lctx, input)))
1325 outputs: outputs.iter()
1327 hir::InlineAsmOutput {
1328 constraint: out.constraint.clone(),
1329 expr: lower_expr(lctx, &out.expr),
1331 is_indirect: out.is_indirect,
1336 asm_str_style: asm_str_style,
1337 clobbers: clobbers.clone().into(),
1339 alignstack: alignstack,
1343 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
1344 hir::ExprStruct(lower_path(lctx, path),
1345 fields.iter().map(|x| lower_field(lctx, x)).collect(),
1346 maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
1348 ExprKind::Paren(ref ex) => {
1349 // merge attributes into the inner expression.
1350 return lower_expr(lctx, ex).map(|mut ex| {
1351 ex.attrs.update(|attrs| {
1352 attrs.prepend(e.attrs.clone())
1358 // Desugar ExprIfLet
1359 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
1360 ExprKind::IfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
1363 // match <sub_expr> {
1365 // [_ if <else_opt_if_cond> => <else_opt_if_body>,]
1366 // _ => [<else_opt> | ()]
1369 return cache_ids(lctx, e.id, |lctx| {
1370 // `<pat> => <body>`
1372 let body = lower_block(lctx, body);
1373 let body_expr = expr_block(lctx, body, None);
1374 arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1377 // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
1378 let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
1379 let else_if_arms = {
1380 let mut arms = vec![];
1382 let else_opt_continue = else_opt.and_then(|els| {
1383 els.and_then(|els| {
1386 hir::ExprIf(cond, then, else_opt) => {
1387 let pat_under = pat_wild(lctx, e.span);
1388 arms.push(hir::Arm {
1390 pats: hir_vec![pat_under],
1392 body: expr_block(lctx, then, None),
1394 else_opt.map(|else_opt| (else_opt, true))
1396 _ => Some((P(els), false)),
1400 match else_opt_continue {
1401 Some((e, true)) => {
1404 Some((e, false)) => {
1417 let contains_else_clause = else_opt.is_some();
1419 // `_ => [<else_opt> | ()]`
1421 let pat_under = pat_wild(lctx, e.span);
1423 else_opt.unwrap_or_else(
1424 || expr_tuple(lctx, e.span, hir_vec![], None));
1425 arm(hir_vec![pat_under], else_expr)
1428 let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
1430 arms.extend(else_if_arms);
1431 arms.push(else_arm);
1433 let sub_expr = lower_expr(lctx, sub_expr);
1434 // add attributes to the outer returned expr node
1437 hir::ExprMatch(sub_expr,
1439 hir::MatchSource::IfLetDesugar {
1440 contains_else_clause: contains_else_clause,
1446 // Desugar ExprWhileLet
1447 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
1448 ExprKind::WhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
1451 // [opt_ident]: loop {
1452 // match <sub_expr> {
1458 return cache_ids(lctx, e.id, |lctx| {
1459 // `<pat> => <body>`
1461 let body = lower_block(lctx, body);
1462 let body_expr = expr_block(lctx, body, None);
1463 arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1468 let pat_under = pat_wild(lctx, e.span);
1469 let break_expr = expr_break(lctx, e.span, None);
1470 arm(hir_vec![pat_under], break_expr)
1473 // `match <sub_expr> { ... }`
1474 let arms = hir_vec![pat_arm, break_arm];
1475 let sub_expr = lower_expr(lctx, sub_expr);
1476 let match_expr = expr(lctx,
1478 hir::ExprMatch(sub_expr,
1480 hir::MatchSource::WhileLetDesugar),
1483 // `[opt_ident]: loop { ... }`
1484 let loop_block = block_expr(lctx, match_expr);
1485 let loop_expr = hir::ExprLoop(loop_block,
1486 opt_ident.map(|ident| lower_ident(lctx, ident)));
1487 // add attributes to the outer returned expr node
1488 expr(lctx, e.span, loop_expr, e.attrs.clone())
1492 // Desugar ExprForLoop
1493 // From: `[opt_ident]: for <pat> in <head> <body>`
1494 ExprKind::ForLoop(ref pat, ref head, ref body, opt_ident) => {
1498 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1500 // [opt_ident]: loop {
1501 // match ::std::iter::Iterator::next(&mut iter) {
1502 // ::std::option::Option::Some(<pat>) => <body>,
1503 // ::std::option::Option::None => break
1511 return cache_ids(lctx, e.id, |lctx| {
1513 let head = lower_expr(lctx, head);
1515 let iter = lctx.str_to_ident("iter");
1517 // `::std::option::Option::Some(<pat>) => <body>`
1519 let body_block = lower_block(lctx, body);
1520 let body_span = body_block.span;
1521 let body_expr = P(hir::Expr {
1523 node: hir::ExprBlock(body_block),
1527 let pat = lower_pat(lctx, pat);
1528 let some_pat = pat_some(lctx, e.span, pat);
1530 arm(hir_vec![some_pat], body_expr)
1533 // `::std::option::Option::None => break`
1535 let break_expr = expr_break(lctx, e.span, None);
1537 arm(hir_vec![pat_none(lctx, e.span)], break_expr)
1540 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1543 let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1545 path_global(e.span, strs)
1547 let iter = expr_ident(lctx, e.span, iter, None);
1548 let ref_mut_iter = expr_mut_addr_of(lctx, e.span, iter, None);
1549 let next_path = expr_path(lctx, next_path, None);
1550 let next_expr = expr_call(lctx,
1553 hir_vec![ref_mut_iter],
1555 let arms = hir_vec![pat_arm, break_arm];
1559 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
1563 // `[opt_ident]: loop { ... }`
1564 let loop_block = block_expr(lctx, match_expr);
1565 let loop_expr = hir::ExprLoop(loop_block,
1566 opt_ident.map(|ident| lower_ident(lctx, ident)));
1567 let loop_expr = expr(lctx, e.span, loop_expr, None);
1569 // `mut iter => { ... }`
1571 let iter_pat = pat_ident_binding_mode(lctx,
1574 hir::BindByValue(hir::MutMutable));
1575 arm(hir_vec![iter_pat], loop_expr)
1578 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1579 let into_iter_expr = {
1580 let into_iter_path = {
1581 let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1583 path_global(e.span, strs)
1586 let into_iter = expr_path(lctx, into_iter_path, None);
1587 expr_call(lctx, e.span, into_iter, hir_vec![head], None)
1590 let match_expr = expr_match(lctx,
1594 hir::MatchSource::ForLoopDesugar,
1597 // `{ let _result = ...; _result }`
1598 // underscore prevents an unused_variables lint if the head diverges
1599 let result_ident = lctx.str_to_ident("_result");
1600 let let_stmt = stmt_let(lctx, e.span, false, result_ident, match_expr, None);
1601 let result = expr_ident(lctx, e.span, result_ident, None);
1602 let block = block_all(lctx, e.span, hir_vec![let_stmt], Some(result));
1603 // add the attributes to the outer returned expr node
1604 expr_block(lctx, block, e.attrs.clone())
1608 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
1611 attrs: e.attrs.clone(),
1615 pub fn lower_stmt(lctx: &LoweringContext, s: &Stmt) -> hir::Stmt {
1617 StmtKind::Decl(ref d, id) => {
1619 node: hir::StmtDecl(lower_decl(lctx, d), id),
1623 StmtKind::Expr(ref e, id) => {
1625 node: hir::StmtExpr(lower_expr(lctx, e), id),
1629 StmtKind::Semi(ref e, id) => {
1631 node: hir::StmtSemi(lower_expr(lctx, e), id),
1635 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
1639 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureBy) -> hir::CaptureClause {
1641 CaptureBy::Value => hir::CaptureByValue,
1642 CaptureBy::Ref => hir::CaptureByRef,
1646 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1648 Visibility::Public => hir::Public,
1649 Visibility::Inherited => hir::Inherited,
1653 pub fn lower_block_check_mode(lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1655 BlockCheckMode::Default => hir::DefaultBlock,
1656 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(lower_unsafe_source(lctx, u)),
1660 pub fn lower_binding_mode(lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1662 BindingMode::ByRef(m) => hir::BindByRef(lower_mutability(lctx, m)),
1663 BindingMode::ByValue(m) => hir::BindByValue(lower_mutability(lctx, m)),
1667 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1669 CompilerGenerated => hir::CompilerGenerated,
1670 UserProvided => hir::UserProvided,
1674 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1676 ImplPolarity::Positive => hir::ImplPolarity::Positive,
1677 ImplPolarity::Negative => hir::ImplPolarity::Negative,
1681 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1682 f: TraitBoundModifier)
1683 -> hir::TraitBoundModifier {
1685 TraitBoundModifier::None => hir::TraitBoundModifier::None,
1686 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1690 // Helper methods for building HIR.
1692 fn arm(pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1701 fn field(name: Name, expr: P<hir::Expr>, span: Span) -> hir::Field {
1712 fn expr_break(lctx: &LoweringContext, span: Span,
1713 attrs: ThinAttributes) -> P<hir::Expr> {
1714 expr(lctx, span, hir::ExprBreak(None), attrs)
1717 fn expr_call(lctx: &LoweringContext,
1720 args: hir::HirVec<P<hir::Expr>>,
1721 attrs: ThinAttributes)
1723 expr(lctx, span, hir::ExprCall(e, args), attrs)
1726 fn expr_ident(lctx: &LoweringContext, span: Span, id: hir::Ident,
1727 attrs: ThinAttributes) -> P<hir::Expr> {
1728 expr_path(lctx, path_ident(span, id), attrs)
1731 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>,
1732 attrs: ThinAttributes) -> P<hir::Expr> {
1733 expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e), attrs)
1736 fn expr_path(lctx: &LoweringContext, path: hir::Path,
1737 attrs: ThinAttributes) -> P<hir::Expr> {
1738 expr(lctx, path.span, hir::ExprPath(None, path), attrs)
1741 fn expr_match(lctx: &LoweringContext,
1744 arms: hir::HirVec<hir::Arm>,
1745 source: hir::MatchSource,
1746 attrs: ThinAttributes)
1748 expr(lctx, span, hir::ExprMatch(arg, arms, source), attrs)
1751 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>,
1752 attrs: ThinAttributes) -> P<hir::Expr> {
1753 expr(lctx, b.span, hir::ExprBlock(b), attrs)
1756 fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: hir::HirVec<P<hir::Expr>>,
1757 attrs: ThinAttributes) -> P<hir::Expr> {
1758 expr(lctx, sp, hir::ExprTup(exprs), attrs)
1761 fn expr_struct(lctx: &LoweringContext,
1764 fields: hir::HirVec<hir::Field>,
1765 e: Option<P<hir::Expr>>,
1766 attrs: ThinAttributes) -> P<hir::Expr> {
1767 expr(lctx, sp, hir::ExprStruct(path, fields, e), attrs)
1770 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_,
1771 attrs: ThinAttributes) -> P<hir::Expr> {
1780 fn stmt_let(lctx: &LoweringContext,
1785 attrs: ThinAttributes)
1787 let pat = if mutbl {
1788 pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1790 pat_ident(lctx, sp, ident)
1792 let local = P(hir::Local {
1800 let decl = respan(sp, hir::DeclLocal(local));
1801 respan(sp, hir::StmtDecl(P(decl), lctx.next_id()))
1804 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1805 block_all(lctx, expr.span, hir::HirVec::new(), Some(expr))
1808 fn block_all(lctx: &LoweringContext,
1810 stmts: hir::HirVec<hir::Stmt>,
1811 expr: Option<P<hir::Expr>>)
1817 rules: hir::DefaultBlock,
1822 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1823 let some = std_path(lctx, &["option", "Option", "Some"]);
1824 let path = path_global(span, some);
1825 pat_enum(lctx, span, path, hir_vec![pat])
1828 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1829 let none = std_path(lctx, &["option", "Option", "None"]);
1830 let path = path_global(span, none);
1831 pat_enum(lctx, span, path, hir_vec![])
1834 fn pat_enum(lctx: &LoweringContext,
1837 subpats: hir::HirVec<P<hir::Pat>>)
1839 let pt = if subpats.is_empty() {
1840 hir::PatKind::Path(path)
1842 hir::PatKind::TupleStruct(path, Some(subpats))
1847 fn pat_ident(lctx: &LoweringContext, span: Span, ident: hir::Ident) -> P<hir::Pat> {
1848 pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1851 fn pat_ident_binding_mode(lctx: &LoweringContext,
1854 bm: hir::BindingMode)
1856 let pat_ident = hir::PatKind::Ident(bm,
1862 pat(lctx, span, pat_ident)
1865 fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1866 pat(lctx, span, hir::PatKind::Wild)
1869 fn pat(lctx: &LoweringContext, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
1877 fn path_ident(span: Span, id: hir::Ident) -> hir::Path {
1878 path(span, vec![id])
1881 fn path(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1882 path_all(span, false, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1885 fn path_global(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1886 path_all(span, true, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1889 fn path_all(sp: Span,
1891 mut idents: Vec<hir::Ident>,
1892 lifetimes: hir::HirVec<hir::Lifetime>,
1893 types: hir::HirVec<P<hir::Ty>>,
1894 bindings: hir::HirVec<hir::TypeBinding>)
1896 let last_identifier = idents.pop().unwrap();
1897 let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1901 parameters: hir::PathParameters::none(),
1905 segments.push(hir::PathSegment {
1906 identifier: last_identifier,
1907 parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1908 lifetimes: lifetimes,
1916 segments: segments.into(),
1920 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<hir::Ident> {
1921 let mut v = Vec::new();
1922 if let Some(s) = lctx.crate_root {
1923 v.push(hir::Ident::from_name(token::intern(s)));
1925 v.extend(components.iter().map(|s| hir::Ident::from_name(token::intern(s))));
1929 // Given suffix ["b","c","d"], returns path `::std::b::c::d` when
1930 // `fld.cx.use_std`, and `::core::b::c::d` otherwise.
1931 fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path {
1932 let idents = std_path(lctx, components);
1933 path_global(span, idents)
1936 fn signal_block_expr(lctx: &LoweringContext,
1937 stmts: hir::HirVec<hir::Stmt>,
1940 rule: hir::BlockCheckMode,
1941 attrs: ThinAttributes)
1943 let id = lctx.next_id();
1960 use syntax::ast::{self, NodeId, NodeIdAssigner};
1961 use syntax::{parse, codemap};
1962 use syntax::fold::Folder;
1963 use std::cell::Cell;
1965 struct MockAssigner {
1966 next_id: Cell<NodeId>,
1970 fn new() -> MockAssigner {
1971 MockAssigner { next_id: Cell::new(0) }
1976 fn call_site(&self) -> codemap::Span;
1977 fn cfg(&self) -> ast::CrateConfig;
1978 fn ident_of(&self, st: &str) -> ast::Ident;
1979 fn name_of(&self, st: &str) -> ast::Name;
1980 fn parse_sess(&self) -> &parse::ParseSess;
1983 impl FakeExtCtxt for parse::ParseSess {
1984 fn call_site(&self) -> codemap::Span {
1986 lo: codemap::BytePos(0),
1987 hi: codemap::BytePos(0),
1988 expn_id: codemap::NO_EXPANSION,
1991 fn cfg(&self) -> ast::CrateConfig {
1994 fn ident_of(&self, st: &str) -> ast::Ident {
1995 parse::token::str_to_ident(st)
1997 fn name_of(&self, st: &str) -> ast::Name {
1998 parse::token::intern(st)
2000 fn parse_sess(&self) -> &parse::ParseSess {
2005 impl NodeIdAssigner for MockAssigner {
2006 fn next_node_id(&self) -> NodeId {
2007 let result = self.next_id.get();
2008 self.next_id.set(result + 1);
2012 fn peek_node_id(&self) -> NodeId {
2017 impl Folder for MockAssigner {
2018 fn new_id(&mut self, old_id: NodeId) -> NodeId {
2019 assert_eq!(old_id, ast::DUMMY_NODE_ID);
2025 fn test_preserves_ids() {
2026 let cx = parse::ParseSess::new();
2027 let mut assigner = MockAssigner::new();
2029 let ast_if_let = quote_expr!(&cx,
2030 if let Some(foo) = baz {
2033 let ast_if_let = assigner.fold_expr(ast_if_let);
2034 let ast_while_let = quote_expr!(&cx,
2035 while let Some(foo) = baz {
2038 let ast_while_let = assigner.fold_expr(ast_while_let);
2039 let ast_for = quote_expr!(&cx,
2045 let ast_for = assigner.fold_expr(ast_for);
2046 let ast_in = quote_expr!(&cx, in HEAP { foo() });
2047 let ast_in = assigner.fold_expr(ast_in);
2049 let lctx = LoweringContext::new(&assigner, None);
2050 let hir1 = lower_expr(&lctx, &ast_if_let);
2051 let hir2 = lower_expr(&lctx, &ast_if_let);
2052 assert!(hir1 == hir2);
2054 let hir1 = lower_expr(&lctx, &ast_while_let);
2055 let hir2 = lower_expr(&lctx, &ast_while_let);
2056 assert!(hir1 == hir2);
2058 let hir1 = lower_expr(&lctx, &ast_for);
2059 let hir2 = lower_expr(&lctx, &ast_for);
2060 assert!(hir1 == hir2);
2062 let hir1 = lower_expr(&lctx, &ast_in);
2063 let hir2 = lower_expr(&lctx, &ast_in);
2064 assert!(hir1 == hir2);