]>
Commit | Line | Data |
---|---|---|
f2b60f7d FG |
1 | use super::errors::{ |
2 | AsyncGeneratorsNotSupported, AsyncNonMoveClosureNotSupported, AwaitOnlyInAsyncFnAndBlocks, | |
353b0b11 | 3 | BaseExpressionDoubleDot, ClosureCannotBeStatic, FunctionalRecordUpdateDestructuringAssignment, |
f2b60f7d | 4 | GeneratorTooManyParameters, InclusiveRangeWithNoEnd, NotSupportedForLifetimeBinderAsyncClosure, |
9ffffee4 | 5 | UnderscoreExprLhsAssign, |
f2b60f7d | 6 | }; |
923072b8 | 7 | use super::ResolverAstLoweringExt; |
dfeec247 | 8 | use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs}; |
923072b8 | 9 | use crate::{FnDeclKind, ImplTraitPosition}; |
74b04a01 XL |
10 | use rustc_ast::attr; |
11 | use rustc_ast::ptr::P as AstP; | |
3dfed10e | 12 | use rustc_ast::*; |
f9f354fc | 13 | use rustc_data_structures::stack::ensure_sufficient_stack; |
dfeec247 XL |
14 | use rustc_hir as hir; |
15 | use rustc_hir::def::Res; | |
6a06907d | 16 | use rustc_hir::definitions::DefPathData; |
487cf647 | 17 | use rustc_session::errors::report_lit_error; |
3dfed10e | 18 | use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned}; |
9ffffee4 | 19 | use rustc_span::symbol::{sym, Ident, Symbol}; |
3c0e092e | 20 | use rustc_span::DUMMY_SP; |
9ffffee4 | 21 | use thin_vec::{thin_vec, ThinVec}; |
416331ca | 22 | |
dfeec247 XL |
23 | impl<'hir> LoweringContext<'_, 'hir> { |
24 | fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] { | |
25 | self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x))) | |
26 | } | |
60c5eb7d | 27 | |
dfeec247 XL |
28 | pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> { |
29 | self.arena.alloc(self.lower_expr_mut(e)) | |
416331ca XL |
30 | } |
31 | ||
dfeec247 | 32 | pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> { |
f9f354fc | 33 | ensure_sufficient_stack(|| { |
9c376795 | 34 | match &e.kind { |
353b0b11 | 35 | // Parenthesis expression does not have a HirId and is handled specially. |
9c376795 FG |
36 | ExprKind::Paren(ex) => { |
37 | let mut ex = self.lower_expr_mut(ex); | |
38 | // Include parens in span, but only if it is a super-span. | |
39 | if e.span.contains(ex.span) { | |
40 | ex.span = self.lower_span(e.span); | |
41 | } | |
42 | // Merge attributes into the inner expression. | |
43 | if !e.attrs.is_empty() { | |
44 | let old_attrs = | |
45 | self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]); | |
46 | self.attrs.insert( | |
47 | ex.hir_id.local_id, | |
48 | &*self.arena.alloc_from_iter( | |
49 | e.attrs | |
50 | .iter() | |
51 | .map(|a| self.lower_attr(a)) | |
52 | .chain(old_attrs.iter().cloned()), | |
53 | ), | |
54 | ); | |
55 | } | |
56 | return ex; | |
57 | } | |
58 | // Desugar `ExprForLoop` | |
59 | // from: `[opt_ident]: for <pat> in <head> <body>` | |
60 | // | |
61 | // This also needs special handling because the HirId of the returned `hir::Expr` will not | |
62 | // correspond to the `e.id`, so `lower_expr_for` handles attribute lowering itself. | |
63 | ExprKind::ForLoop(pat, head, body, opt_label) => { | |
64 | return self.lower_expr_for(e, pat, head, body, *opt_label); | |
65 | } | |
66 | _ => (), | |
67 | } | |
68 | ||
69 | let hir_id = self.lower_node_id(e.id); | |
70 | self.lower_attrs(hir_id, &e.attrs); | |
71 | ||
487cf647 | 72 | let kind = match &e.kind { |
487cf647 FG |
73 | ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)), |
74 | ExprKind::ConstBlock(anon_const) => { | |
29967ef6 XL |
75 | let anon_const = self.lower_anon_const(anon_const); |
76 | hir::ExprKind::ConstBlock(anon_const) | |
77 | } | |
487cf647 | 78 | ExprKind::Repeat(expr, count) => { |
f9f354fc | 79 | let expr = self.lower_expr(expr); |
a2a8927a | 80 | let count = self.lower_array_length(count); |
f9f354fc XL |
81 | hir::ExprKind::Repeat(expr, count) |
82 | } | |
487cf647 FG |
83 | ExprKind::Tup(elts) => hir::ExprKind::Tup(self.lower_exprs(elts)), |
84 | ExprKind::Call(f, args) => { | |
9ffffee4 | 85 | if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) { |
6a06907d XL |
86 | self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args) |
87 | } else { | |
88 | let f = self.lower_expr(f); | |
89 | hir::ExprKind::Call(f, self.lower_exprs(args)) | |
90 | } | |
f9f354fc | 91 | } |
487cf647 | 92 | ExprKind::MethodCall(box MethodCall { seg, receiver, args, span }) => { |
f9f354fc XL |
93 | let hir_seg = self.arena.alloc(self.lower_path_segment( |
94 | e.span, | |
95 | seg, | |
96 | ParamMode::Optional, | |
f9f354fc | 97 | ParenthesizedGenericArgs::Err, |
f2b60f7d | 98 | &ImplTraitContext::Disallowed(ImplTraitPosition::Path), |
f9f354fc | 99 | )); |
2b03887a | 100 | let receiver = self.lower_expr(receiver); |
f2b60f7d | 101 | let args = |
2b03887a | 102 | self.arena.alloc_from_iter(args.iter().map(|x| self.lower_expr_mut(x))); |
487cf647 | 103 | hir::ExprKind::MethodCall(hir_seg, receiver, args, self.lower_span(*span)) |
f9f354fc | 104 | } |
487cf647 FG |
105 | ExprKind::Binary(binop, lhs, rhs) => { |
106 | let binop = self.lower_binop(*binop); | |
f9f354fc XL |
107 | let lhs = self.lower_expr(lhs); |
108 | let rhs = self.lower_expr(rhs); | |
109 | hir::ExprKind::Binary(binop, lhs, rhs) | |
110 | } | |
487cf647 FG |
111 | ExprKind::Unary(op, ohs) => { |
112 | let op = self.lower_unop(*op); | |
f9f354fc XL |
113 | let ohs = self.lower_expr(ohs); |
114 | hir::ExprKind::Unary(op, ohs) | |
115 | } | |
487cf647 FG |
116 | ExprKind::Lit(token_lit) => { |
117 | let lit_kind = match LitKind::from_token_lit(*token_lit) { | |
118 | Ok(lit_kind) => lit_kind, | |
119 | Err(err) => { | |
120 | report_lit_error(&self.tcx.sess.parse_sess, err, *token_lit, e.span); | |
121 | LitKind::Err | |
122 | } | |
123 | }; | |
124 | hir::ExprKind::Lit(respan(self.lower_span(e.span), lit_kind)) | |
94222f64 | 125 | } |
487cf647 FG |
126 | ExprKind::IncludedBytes(bytes) => hir::ExprKind::Lit(respan( |
127 | self.lower_span(e.span), | |
9c376795 | 128 | LitKind::ByteStr(bytes.clone(), StrStyle::Cooked), |
487cf647 FG |
129 | )), |
130 | ExprKind::Cast(expr, ty) => { | |
f9f354fc | 131 | let expr = self.lower_expr(expr); |
5099ac24 | 132 | let ty = |
9ffffee4 | 133 | self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Cast)); |
f9f354fc XL |
134 | hir::ExprKind::Cast(expr, ty) |
135 | } | |
487cf647 | 136 | ExprKind::Type(expr, ty) => { |
f9f354fc | 137 | let expr = self.lower_expr(expr); |
5099ac24 | 138 | let ty = |
9ffffee4 | 139 | self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Cast)); |
f9f354fc XL |
140 | hir::ExprKind::Type(expr, ty) |
141 | } | |
487cf647 | 142 | ExprKind::AddrOf(k, m, ohs) => { |
f9f354fc | 143 | let ohs = self.lower_expr(ohs); |
487cf647 | 144 | hir::ExprKind::AddrOf(*k, *m, ohs) |
f9f354fc | 145 | } |
487cf647 | 146 | ExprKind::Let(pat, scrutinee, span) => { |
a2a8927a XL |
147 | hir::ExprKind::Let(self.arena.alloc(hir::Let { |
148 | hir_id: self.next_id(), | |
487cf647 | 149 | span: self.lower_span(*span), |
a2a8927a XL |
150 | pat: self.lower_pat(pat), |
151 | ty: None, | |
152 | init: self.lower_expr(scrutinee), | |
153 | })) | |
154 | } | |
487cf647 | 155 | ExprKind::If(cond, then, else_opt) => { |
94222f64 | 156 | self.lower_expr_if(cond, then, else_opt.as_deref()) |
f9f354fc | 157 | } |
487cf647 FG |
158 | ExprKind::While(cond, body, opt_label) => self.with_loop_scope(e.id, |this| { |
159 | let span = this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None); | |
160 | this.lower_expr_while_in_loop_scope(span, cond, body, *opt_label) | |
161 | }), | |
162 | ExprKind::Loop(body, opt_label, span) => self.with_loop_scope(e.id, |this| { | |
f9f354fc XL |
163 | hir::ExprKind::Loop( |
164 | this.lower_block(body, false), | |
487cf647 | 165 | this.lower_label(*opt_label), |
f9f354fc | 166 | hir::LoopSource::Loop, |
487cf647 | 167 | this.lower_span(*span), |
dfeec247 | 168 | ) |
f9f354fc | 169 | }), |
487cf647 FG |
170 | ExprKind::TryBlock(body) => self.lower_expr_try_block(body), |
171 | ExprKind::Match(expr, arms) => hir::ExprKind::Match( | |
f9f354fc XL |
172 | self.lower_expr(expr), |
173 | self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))), | |
174 | hir::MatchSource::Normal, | |
175 | ), | |
353b0b11 | 176 | ExprKind::Async(capture_clause, block) => self.make_async_expr( |
487cf647 | 177 | *capture_clause, |
353b0b11 | 178 | e.id, |
487cf647 FG |
179 | None, |
180 | e.span, | |
181 | hir::AsyncGeneratorKind::Block, | |
182 | |this| this.with_new_scopes(|this| this.lower_block_expr(block)), | |
183 | ), | |
184 | ExprKind::Await(expr) => { | |
f2b60f7d FG |
185 | let dot_await_span = if expr.span.hi() < e.span.hi() { |
186 | let span_with_whitespace = self | |
187 | .tcx | |
188 | .sess | |
189 | .source_map() | |
190 | .span_extend_while(expr.span, char::is_whitespace) | |
191 | .unwrap_or(expr.span); | |
192 | span_with_whitespace.shrink_to_hi().with_hi(e.span.hi()) | |
a2a8927a XL |
193 | } else { |
194 | // this is a recovered `await expr` | |
195 | e.span | |
196 | }; | |
f2b60f7d | 197 | self.lower_expr_await(dot_await_span, expr) |
a2a8927a | 198 | } |
487cf647 FG |
199 | ExprKind::Closure(box Closure { |
200 | binder, | |
f9f354fc | 201 | capture_clause, |
9c376795 | 202 | constness, |
f9f354fc XL |
203 | asyncness, |
204 | movability, | |
487cf647 FG |
205 | fn_decl, |
206 | body, | |
f9f354fc | 207 | fn_decl_span, |
487cf647 FG |
208 | fn_arg_span, |
209 | }) => { | |
f9f354fc XL |
210 | if let Async::Yes { closure_id, .. } = asyncness { |
211 | self.lower_expr_async_closure( | |
064997fb | 212 | binder, |
487cf647 | 213 | *capture_clause, |
923072b8 | 214 | e.id, |
9c376795 | 215 | hir_id, |
487cf647 FG |
216 | *closure_id, |
217 | fn_decl, | |
f9f354fc | 218 | body, |
487cf647 FG |
219 | *fn_decl_span, |
220 | *fn_arg_span, | |
f9f354fc XL |
221 | ) |
222 | } else { | |
223 | self.lower_expr_closure( | |
064997fb | 224 | binder, |
487cf647 | 225 | *capture_clause, |
923072b8 | 226 | e.id, |
9c376795 | 227 | *constness, |
487cf647 FG |
228 | *movability, |
229 | fn_decl, | |
f9f354fc | 230 | body, |
487cf647 FG |
231 | *fn_decl_span, |
232 | *fn_arg_span, | |
f9f354fc XL |
233 | ) |
234 | } | |
dfeec247 | 235 | } |
487cf647 FG |
236 | ExprKind::Block(blk, opt_label) => { |
237 | let opt_label = self.lower_label(*opt_label); | |
f9f354fc XL |
238 | hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label) |
239 | } | |
487cf647 FG |
240 | ExprKind::Assign(el, er, span) => self.lower_expr_assign(el, er, *span, e.span), |
241 | ExprKind::AssignOp(op, el, er) => hir::ExprKind::AssignOp( | |
242 | self.lower_binop(*op), | |
f9f354fc XL |
243 | self.lower_expr(el), |
244 | self.lower_expr(er), | |
245 | ), | |
487cf647 FG |
246 | ExprKind::Field(el, ident) => { |
247 | hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(*ident)) | |
94222f64 | 248 | } |
487cf647 | 249 | ExprKind::Index(el, er) => { |
f9f354fc XL |
250 | hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er)) |
251 | } | |
487cf647 | 252 | ExprKind::Range(Some(e1), Some(e2), RangeLimits::Closed) => { |
f9f354fc XL |
253 | self.lower_expr_range_closed(e.span, e1, e2) |
254 | } | |
487cf647 FG |
255 | ExprKind::Range(e1, e2, lims) => { |
256 | self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), *lims) | |
f9f354fc | 257 | } |
fc512014 | 258 | ExprKind::Underscore => { |
9ffffee4 FG |
259 | let guar = self.tcx.sess.emit_err(UnderscoreExprLhsAssign { span: e.span }); |
260 | hir::ExprKind::Err(guar) | |
fc512014 | 261 | } |
487cf647 | 262 | ExprKind::Path(qself, path) => { |
f9f354fc | 263 | let qpath = self.lower_qpath( |
dfeec247 | 264 | e.id, |
f9f354fc | 265 | qself, |
dfeec247 XL |
266 | path, |
267 | ParamMode::Optional, | |
f2b60f7d | 268 | &ImplTraitContext::Disallowed(ImplTraitPosition::Path), |
f9f354fc XL |
269 | ); |
270 | hir::ExprKind::Path(qpath) | |
271 | } | |
487cf647 | 272 | ExprKind::Break(opt_label, opt_expr) => { |
f9f354fc | 273 | let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x)); |
487cf647 | 274 | hir::ExprKind::Break(self.lower_jump_destination(e.id, *opt_label), opt_expr) |
f9f354fc XL |
275 | } |
276 | ExprKind::Continue(opt_label) => { | |
487cf647 | 277 | hir::ExprKind::Continue(self.lower_jump_destination(e.id, *opt_label)) |
f9f354fc | 278 | } |
487cf647 | 279 | ExprKind::Ret(e) => { |
f9f354fc XL |
280 | let e = e.as_ref().map(|x| self.lower_expr(x)); |
281 | hir::ExprKind::Ret(e) | |
282 | } | |
487cf647 FG |
283 | ExprKind::Yeet(sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref()), |
284 | ExprKind::InlineAsm(asm) => { | |
17df50a5 XL |
285 | hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm)) |
286 | } | |
9ffffee4 | 287 | ExprKind::FormatArgs(fmt) => self.lower_format_args(e.span, fmt), |
487cf647 | 288 | ExprKind::Struct(se) => { |
6a06907d | 289 | let rest = match &se.rest { |
29967ef6 XL |
290 | StructRest::Base(e) => Some(self.lower_expr(e)), |
291 | StructRest::Rest(sp) => { | |
9ffffee4 FG |
292 | let guar = |
293 | self.tcx.sess.emit_err(BaseExpressionDoubleDot { span: *sp }); | |
294 | Some(&*self.arena.alloc(self.expr_err(*sp, guar))) | |
29967ef6 XL |
295 | } |
296 | StructRest::None => None, | |
297 | }; | |
f9f354fc XL |
298 | hir::ExprKind::Struct( |
299 | self.arena.alloc(self.lower_qpath( | |
300 | e.id, | |
17df50a5 | 301 | &se.qself, |
6a06907d | 302 | &se.path, |
f9f354fc | 303 | ParamMode::Optional, |
f2b60f7d | 304 | &ImplTraitContext::Disallowed(ImplTraitPosition::Path), |
f9f354fc | 305 | )), |
6a06907d XL |
306 | self.arena |
307 | .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))), | |
29967ef6 | 308 | rest, |
f9f354fc XL |
309 | ) |
310 | } | |
487cf647 | 311 | ExprKind::Yield(opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()), |
9ffffee4 FG |
312 | ExprKind::Err => hir::ExprKind::Err( |
313 | self.tcx.sess.delay_span_bug(e.span, "lowered ExprKind::Err"), | |
314 | ), | |
487cf647 | 315 | ExprKind::Try(sub_expr) => self.lower_expr_try(e.span, sub_expr), |
416331ca | 316 | |
353b0b11 FG |
317 | ExprKind::Paren(_) | ExprKind::ForLoop(..) => { |
318 | unreachable!("already handled") | |
319 | } | |
9c376795 | 320 | |
f9f354fc XL |
321 | ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span), |
322 | }; | |
416331ca | 323 | |
94222f64 | 324 | hir::Expr { hir_id, kind, span: self.lower_span(e.span) } |
f9f354fc | 325 | }) |
416331ca XL |
326 | } |
327 | ||
328 | fn lower_unop(&mut self, u: UnOp) -> hir::UnOp { | |
329 | match u { | |
6a06907d XL |
330 | UnOp::Deref => hir::UnOp::Deref, |
331 | UnOp::Not => hir::UnOp::Not, | |
332 | UnOp::Neg => hir::UnOp::Neg, | |
416331ca XL |
333 | } |
334 | } | |
335 | ||
336 | fn lower_binop(&mut self, b: BinOp) -> hir::BinOp { | |
337 | Spanned { | |
338 | node: match b.node { | |
339 | BinOpKind::Add => hir::BinOpKind::Add, | |
340 | BinOpKind::Sub => hir::BinOpKind::Sub, | |
341 | BinOpKind::Mul => hir::BinOpKind::Mul, | |
342 | BinOpKind::Div => hir::BinOpKind::Div, | |
343 | BinOpKind::Rem => hir::BinOpKind::Rem, | |
344 | BinOpKind::And => hir::BinOpKind::And, | |
345 | BinOpKind::Or => hir::BinOpKind::Or, | |
346 | BinOpKind::BitXor => hir::BinOpKind::BitXor, | |
347 | BinOpKind::BitAnd => hir::BinOpKind::BitAnd, | |
348 | BinOpKind::BitOr => hir::BinOpKind::BitOr, | |
349 | BinOpKind::Shl => hir::BinOpKind::Shl, | |
350 | BinOpKind::Shr => hir::BinOpKind::Shr, | |
351 | BinOpKind::Eq => hir::BinOpKind::Eq, | |
352 | BinOpKind::Lt => hir::BinOpKind::Lt, | |
353 | BinOpKind::Le => hir::BinOpKind::Le, | |
354 | BinOpKind::Ne => hir::BinOpKind::Ne, | |
355 | BinOpKind::Ge => hir::BinOpKind::Ge, | |
356 | BinOpKind::Gt => hir::BinOpKind::Gt, | |
357 | }, | |
94222f64 | 358 | span: self.lower_span(b.span), |
416331ca XL |
359 | } |
360 | } | |
361 | ||
6a06907d XL |
362 | fn lower_legacy_const_generics( |
363 | &mut self, | |
364 | mut f: Expr, | |
9ffffee4 | 365 | args: ThinVec<AstP<Expr>>, |
6a06907d XL |
366 | legacy_args_idx: &[usize], |
367 | ) -> hir::ExprKind<'hir> { | |
487cf647 | 368 | let ExprKind::Path(None, path) = &mut f.kind else { |
5e7ed085 | 369 | unreachable!(); |
6a06907d XL |
370 | }; |
371 | ||
372 | // Split the arguments into const generics and normal arguments | |
373 | let mut real_args = vec![]; | |
9ffffee4 | 374 | let mut generic_args = ThinVec::new(); |
6a06907d XL |
375 | for (idx, arg) in args.into_iter().enumerate() { |
376 | if legacy_args_idx.contains(&idx) { | |
c295e0f8 | 377 | let parent_def_id = self.current_hir_id_owner; |
923072b8 | 378 | let node_id = self.next_node_id(); |
6a06907d XL |
379 | |
380 | // Add a definition for the in-band const def. | |
487cf647 | 381 | self.create_def(parent_def_id.def_id, node_id, DefPathData::AnonConst, f.span); |
6a06907d XL |
382 | |
383 | let anon_const = AnonConst { id: node_id, value: arg }; | |
384 | generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const))); | |
385 | } else { | |
386 | real_args.push(arg); | |
387 | } | |
388 | } | |
389 | ||
390 | // Add generic args to the last element of the path. | |
391 | let last_segment = path.segments.last_mut().unwrap(); | |
392 | assert!(last_segment.args.is_none()); | |
393 | last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs { | |
394 | span: DUMMY_SP, | |
395 | args: generic_args, | |
396 | }))); | |
397 | ||
398 | // Now lower everything as normal. | |
399 | let f = self.lower_expr(&f); | |
400 | hir::ExprKind::Call(f, self.lower_exprs(&real_args)) | |
401 | } | |
402 | ||
416331ca XL |
403 | fn lower_expr_if( |
404 | &mut self, | |
416331ca XL |
405 | cond: &Expr, |
406 | then: &Block, | |
407 | else_opt: Option<&Expr>, | |
5869c6ff | 408 | ) -> hir::ExprKind<'hir> { |
2b03887a | 409 | let lowered_cond = self.lower_cond(cond); |
94222f64 | 410 | let then_expr = self.lower_block_expr(then); |
5869c6ff | 411 | if let Some(rslt) = else_opt { |
2b03887a FG |
412 | hir::ExprKind::If( |
413 | lowered_cond, | |
414 | self.arena.alloc(then_expr), | |
415 | Some(self.lower_expr(rslt)), | |
416 | ) | |
5869c6ff | 417 | } else { |
2b03887a | 418 | hir::ExprKind::If(lowered_cond, self.arena.alloc(then_expr), None) |
5869c6ff XL |
419 | } |
420 | } | |
421 | ||
2b03887a FG |
422 | // Lowers a condition (i.e. `cond` in `if cond` or `while cond`), wrapping it in a terminating scope |
423 | // so that temporaries created in the condition don't live beyond it. | |
424 | fn lower_cond(&mut self, cond: &Expr) -> &'hir hir::Expr<'hir> { | |
425 | fn has_let_expr(expr: &Expr) -> bool { | |
426 | match &expr.kind { | |
427 | ExprKind::Binary(_, lhs, rhs) => has_let_expr(lhs) || has_let_expr(rhs), | |
428 | ExprKind::Let(..) => true, | |
5099ac24 | 429 | _ => false, |
94222f64 XL |
430 | } |
431 | } | |
2b03887a FG |
432 | |
433 | // We have to take special care for `let` exprs in the condition, e.g. in | |
434 | // `if let pat = val` or `if foo && let pat = val`, as we _do_ want `val` to live beyond the | |
435 | // condition in this case. | |
436 | // | |
353b0b11 | 437 | // In order to maintain the drop behavior for the non `let` parts of the condition, |
2b03887a FG |
438 | // we still wrap them in terminating scopes, e.g. `if foo && let pat = val` essentially |
439 | // gets transformed into `if { let _t = foo; _t } && let pat = val` | |
440 | match &cond.kind { | |
441 | ExprKind::Binary(op @ Spanned { node: ast::BinOpKind::And, .. }, lhs, rhs) | |
442 | if has_let_expr(cond) => | |
443 | { | |
444 | let op = self.lower_binop(*op); | |
445 | let lhs = self.lower_cond(lhs); | |
446 | let rhs = self.lower_cond(rhs); | |
447 | ||
487cf647 | 448 | self.arena.alloc(self.expr(cond.span, hir::ExprKind::Binary(op, lhs, rhs))) |
2b03887a FG |
449 | } |
450 | ExprKind::Let(..) => self.lower_expr(cond), | |
451 | _ => { | |
452 | let cond = self.lower_expr(cond); | |
453 | let reason = DesugaringKind::CondTemporary; | |
454 | let span_block = self.mark_span_with_reason(reason, cond.span, None); | |
487cf647 | 455 | self.expr_drop_temps(span_block, cond) |
2b03887a | 456 | } |
5099ac24 | 457 | } |
416331ca XL |
458 | } |
459 | ||
94222f64 XL |
460 | // We desugar: `'label: while $cond $body` into: |
461 | // | |
462 | // ``` | |
463 | // 'label: loop { | |
464 | // if { let _t = $cond; _t } { | |
465 | // $body | |
466 | // } | |
467 | // else { | |
468 | // break; | |
469 | // } | |
470 | // } | |
471 | // ``` | |
472 | // | |
473 | // Wrap in a construct equivalent to `{ let _t = $cond; _t }` | |
474 | // to preserve drop semantics since `while $cond { ... }` does not | |
475 | // let temporaries live outside of `cond`. | |
416331ca XL |
476 | fn lower_expr_while_in_loop_scope( |
477 | &mut self, | |
478 | span: Span, | |
479 | cond: &Expr, | |
480 | body: &Block, | |
dfeec247 XL |
481 | opt_label: Option<Label>, |
482 | ) -> hir::ExprKind<'hir> { | |
2b03887a | 483 | let lowered_cond = self.with_loop_condition_scope(|t| t.lower_cond(cond)); |
94222f64 | 484 | let then = self.lower_block_expr(body); |
487cf647 | 485 | let expr_break = self.expr_break(span); |
94222f64 XL |
486 | let stmt_break = self.stmt_expr(span, expr_break); |
487 | let else_blk = self.block_all(span, arena_vec![self; stmt_break], None); | |
487cf647 | 488 | let else_expr = self.arena.alloc(self.expr_block(else_blk)); |
2b03887a | 489 | let if_kind = hir::ExprKind::If(lowered_cond, self.arena.alloc(then), Some(else_expr)); |
487cf647 | 490 | let if_expr = self.expr(span, if_kind); |
94222f64 | 491 | let block = self.block_expr(self.arena.alloc(if_expr)); |
c295e0f8 XL |
492 | let span = self.lower_span(span.with_hi(cond.span.hi())); |
493 | let opt_label = self.lower_label(opt_label); | |
494 | hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span) | |
416331ca XL |
495 | } |
496 | ||
17df50a5 XL |
497 | /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`, |
498 | /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }` | |
e74abb32 | 499 | /// and save the block id to use it as a break target for desugaring of the `?` operator. |
dfeec247 | 500 | fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> { |
416331ca | 501 | self.with_catch_scope(body.id, |this| { |
dfeec247 | 502 | let mut block = this.lower_block_noalloc(body, true); |
e74abb32 | 503 | |
e74abb32 | 504 | // Final expression of the block (if present) or `()` with span at the end of block |
29967ef6 XL |
505 | let (try_span, tail_expr) = if let Some(expr) = block.expr.take() { |
506 | ( | |
507 | this.mark_span_with_reason( | |
508 | DesugaringKind::TryBlock, | |
509 | expr.span, | |
510 | this.allow_try_trait.clone(), | |
511 | ), | |
512 | expr, | |
513 | ) | |
514 | } else { | |
515 | let try_span = this.mark_span_with_reason( | |
516 | DesugaringKind::TryBlock, | |
064997fb | 517 | this.tcx.sess.source_map().end_point(body.span), |
29967ef6 XL |
518 | this.allow_try_trait.clone(), |
519 | ); | |
520 | ||
521 | (try_span, this.expr_unit(try_span)) | |
522 | }; | |
e74abb32 | 523 | |
dfeec247 XL |
524 | let ok_wrapped_span = |
525 | this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None); | |
e74abb32 | 526 | |
17df50a5 | 527 | // `::std::ops::Try::from_output($tail_expr)` |
e74abb32 | 528 | block.expr = Some(this.wrap_in_try_constructor( |
17df50a5 | 529 | hir::LangItem::TryTraitFromOutput, |
dfeec247 XL |
530 | try_span, |
531 | tail_expr, | |
532 | ok_wrapped_span, | |
533 | )); | |
e74abb32 | 534 | |
dfeec247 | 535 | hir::ExprKind::Block(this.arena.alloc(block), None) |
416331ca XL |
536 | }) |
537 | } | |
538 | ||
539 | fn wrap_in_try_constructor( | |
540 | &mut self, | |
3dfed10e | 541 | lang_item: hir::LangItem, |
e74abb32 | 542 | method_span: Span, |
dfeec247 | 543 | expr: &'hir hir::Expr<'hir>, |
e74abb32 | 544 | overall_span: Span, |
dfeec247 | 545 | ) -> &'hir hir::Expr<'hir> { |
487cf647 | 546 | let constructor = self.arena.alloc(self.expr_lang_item_path(method_span, lang_item, None)); |
dfeec247 | 547 | self.expr_call(overall_span, constructor, std::slice::from_ref(expr)) |
416331ca XL |
548 | } |
549 | ||
dfeec247 | 550 | fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> { |
fc512014 XL |
551 | let pat = self.lower_pat(&arm.pat); |
552 | let guard = arm.guard.as_ref().map(|cond| { | |
487cf647 | 553 | if let ExprKind::Let(pat, scrutinee, span) = &cond.kind { |
923072b8 FG |
554 | hir::Guard::IfLet(self.arena.alloc(hir::Let { |
555 | hir_id: self.next_id(), | |
487cf647 | 556 | span: self.lower_span(*span), |
923072b8 FG |
557 | pat: self.lower_pat(pat), |
558 | ty: None, | |
559 | init: self.lower_expr(scrutinee), | |
560 | })) | |
fc512014 XL |
561 | } else { |
562 | hir::Guard::If(self.lower_expr(cond)) | |
563 | } | |
564 | }); | |
6a06907d XL |
565 | let hir_id = self.next_id(); |
566 | self.lower_attrs(hir_id, &arm.attrs); | |
94222f64 XL |
567 | hir::Arm { |
568 | hir_id, | |
569 | pat, | |
570 | guard, | |
571 | body: self.lower_expr(&arm.body), | |
572 | span: self.lower_span(arm.span), | |
573 | } | |
416331ca XL |
574 | } |
575 | ||
487cf647 | 576 | /// Lower an `async` construct to a generator that implements `Future`. |
ba9703b0 XL |
577 | /// |
578 | /// This results in: | |
579 | /// | |
580 | /// ```text | |
353b0b11 | 581 | /// static move? |_task_context| -> <ret_ty> { |
ba9703b0 | 582 | /// <body> |
353b0b11 | 583 | /// } |
ba9703b0 | 584 | /// ``` |
416331ca XL |
585 | pub(super) fn make_async_expr( |
586 | &mut self, | |
587 | capture_clause: CaptureBy, | |
588 | closure_node_id: NodeId, | |
487cf647 | 589 | ret_ty: Option<hir::FnRetTy<'hir>>, |
416331ca | 590 | span: Span, |
e74abb32 | 591 | async_gen_kind: hir::AsyncGeneratorKind, |
dfeec247 XL |
592 | body: impl FnOnce(&mut Self) -> hir::Expr<'hir>, |
593 | ) -> hir::ExprKind<'hir> { | |
487cf647 | 594 | let output = ret_ty.unwrap_or_else(|| hir::FnRetTy::DefaultReturn(self.lower_span(span))); |
ba9703b0 | 595 | |
487cf647 FG |
596 | // Resume argument type: `ResumeTy` |
597 | let unstable_span = | |
598 | self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone()); | |
599 | let resume_ty = hir::QPath::LangItem(hir::LangItem::ResumeTy, unstable_span, None); | |
94222f64 XL |
600 | let input_ty = hir::Ty { |
601 | hir_id: self.next_id(), | |
487cf647 FG |
602 | kind: hir::TyKind::Path(resume_ty), |
603 | span: unstable_span, | |
94222f64 | 604 | }; |
ba9703b0 XL |
605 | |
606 | // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`. | |
923072b8 | 607 | let fn_decl = self.arena.alloc(hir::FnDecl { |
ba9703b0 XL |
608 | inputs: arena_vec![self; input_ty], |
609 | output, | |
610 | c_variadic: false, | |
611 | implicit_self: hir::ImplicitSelfKind::None, | |
487cf647 | 612 | lifetime_elision_allowed: false, |
ba9703b0 XL |
613 | }); |
614 | ||
615 | // Lower the argument pattern/ident. The ident is used again in the `.await` lowering. | |
616 | let (pat, task_context_hid) = self.pat_ident_binding_mode( | |
617 | span, | |
618 | Ident::with_dummy_span(sym::_task_context), | |
f2b60f7d | 619 | hir::BindingAnnotation::MUT, |
ba9703b0 | 620 | ); |
94222f64 XL |
621 | let param = hir::Param { |
622 | hir_id: self.next_id(), | |
623 | pat, | |
624 | ty_span: self.lower_span(span), | |
625 | span: self.lower_span(span), | |
626 | }; | |
ba9703b0 XL |
627 | let params = arena_vec![self; param]; |
628 | ||
923072b8 | 629 | let body = self.lower_body(move |this| { |
e74abb32 | 630 | this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind)); |
ba9703b0 XL |
631 | |
632 | let old_ctx = this.task_context; | |
633 | this.task_context = Some(task_context_hid); | |
634 | let res = body(this); | |
635 | this.task_context = old_ctx; | |
636 | (params, res) | |
416331ca XL |
637 | }); |
638 | ||
ba9703b0 | 639 | // `static |_task_context| -> <ret_ty> { body }`: |
353b0b11 FG |
640 | hir::ExprKind::Closure(self.arena.alloc(hir::Closure { |
641 | def_id: self.local_def_id(closure_node_id), | |
642 | binder: hir::ClosureBinder::Default, | |
643 | capture_clause, | |
644 | bound_generic_params: &[], | |
645 | fn_decl, | |
646 | body, | |
647 | fn_decl_span: self.lower_span(span), | |
648 | fn_arg_span: None, | |
649 | movability: Some(hir::Movability::Static), | |
650 | constness: hir::Constness::NotConst, | |
651 | })) | |
652 | } | |
416331ca | 653 | |
353b0b11 FG |
654 | /// Forwards a possible `#[track_caller]` annotation from `outer_hir_id` to |
655 | /// `inner_hir_id` in case the `closure_track_caller` feature is enabled. | |
656 | pub(super) fn maybe_forward_track_caller( | |
657 | &mut self, | |
658 | span: Span, | |
659 | outer_hir_id: hir::HirId, | |
660 | inner_hir_id: hir::HirId, | |
661 | ) { | |
487cf647 | 662 | if self.tcx.features().closure_track_caller |
487cf647 FG |
663 | && let Some(attrs) = self.attrs.get(&outer_hir_id.local_id) |
664 | && attrs.into_iter().any(|attr| attr.has_name(sym::track_caller)) | |
665 | { | |
353b0b11 FG |
666 | let unstable_span = |
667 | self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone()); | |
487cf647 | 668 | self.lower_attrs( |
353b0b11 | 669 | inner_hir_id, |
487cf647 FG |
670 | &[Attribute { |
671 | kind: AttrKind::Normal(ptr::P(NormalAttr { | |
672 | item: AttrItem { | |
673 | path: Path::from_ident(Ident::new(sym::track_caller, span)), | |
674 | args: AttrArgs::Empty, | |
675 | tokens: None, | |
676 | }, | |
677 | tokens: None, | |
678 | })), | |
679 | id: self.tcx.sess.parse_sess.attr_id_generator.mk_attr_id(), | |
680 | style: AttrStyle::Outer, | |
681 | span: unstable_span, | |
682 | }], | |
683 | ); | |
684 | } | |
416331ca XL |
685 | } |
686 | ||
687 | /// Desugar `<expr>.await` into: | |
04454e1e | 688 | /// ```ignore (pseudo-rust) |
a2a8927a | 689 | /// match ::std::future::IntoFuture::into_future(<expr>) { |
5e7ed085 | 690 | /// mut __awaitee => loop { |
ba9703b0 | 691 | /// match unsafe { ::std::future::Future::poll( |
5e7ed085 | 692 | /// <::std::pin::Pin>::new_unchecked(&mut __awaitee), |
ba9703b0 XL |
693 | /// ::std::future::get_context(task_context), |
694 | /// ) } { | |
416331ca | 695 | /// ::std::task::Poll::Ready(result) => break result, |
e1599b0c | 696 | /// ::std::task::Poll::Pending => {} |
416331ca | 697 | /// } |
ba9703b0 | 698 | /// task_context = yield (); |
416331ca XL |
699 | /// } |
700 | /// } | |
701 | /// ``` | |
5099ac24 FG |
702 | fn lower_expr_await(&mut self, dot_await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> { |
703 | let full_span = expr.span.to(dot_await_span); | |
416331ca | 704 | match self.generator_kind { |
dfeec247 XL |
705 | Some(hir::GeneratorKind::Async(_)) => {} |
706 | Some(hir::GeneratorKind::Gen) | None => { | |
f2b60f7d | 707 | self.tcx.sess.emit_err(AwaitOnlyInAsyncFnAndBlocks { |
5099ac24 | 708 | dot_await_span, |
f2b60f7d FG |
709 | item_span: self.current_item, |
710 | }); | |
416331ca XL |
711 | } |
712 | } | |
a2a8927a | 713 | let span = self.mark_span_with_reason(DesugaringKind::Await, dot_await_span, None); |
416331ca XL |
714 | let gen_future_span = self.mark_span_with_reason( |
715 | DesugaringKind::Await, | |
5099ac24 | 716 | full_span, |
416331ca XL |
717 | self.allow_gen_future.clone(), |
718 | ); | |
a2a8927a XL |
719 | let expr = self.lower_expr_mut(expr); |
720 | let expr_hir_id = expr.hir_id; | |
416331ca | 721 | |
5e7ed085 FG |
722 | // Note that the name of this binding must not be changed to something else because |
723 | // debuggers and debugger extensions expect it to be called `__awaitee`. They use | |
724 | // this name to identify what is being awaited by a suspended async functions. | |
725 | let awaitee_ident = Ident::with_dummy_span(sym::__awaitee); | |
726 | let (awaitee_pat, awaitee_pat_hid) = | |
f2b60f7d | 727 | self.pat_ident_binding_mode(span, awaitee_ident, hir::BindingAnnotation::MUT); |
416331ca | 728 | |
ba9703b0 XL |
729 | let task_context_ident = Ident::with_dummy_span(sym::_task_context); |
730 | ||
731 | // unsafe { | |
732 | // ::std::future::Future::poll( | |
5e7ed085 | 733 | // ::std::pin::Pin::new_unchecked(&mut __awaitee), |
ba9703b0 XL |
734 | // ::std::future::get_context(task_context), |
735 | // ) | |
736 | // } | |
416331ca | 737 | let poll_expr = { |
5e7ed085 FG |
738 | let awaitee = self.expr_ident(span, awaitee_ident, awaitee_pat_hid); |
739 | let ref_mut_awaitee = self.expr_mut_addr_of(span, awaitee); | |
ba9703b0 XL |
740 | let task_context = if let Some(task_context_hid) = self.task_context { |
741 | self.expr_ident_mut(span, task_context_ident, task_context_hid) | |
742 | } else { | |
743 | // Use of `await` outside of an async context, we cannot use `task_context` here. | |
9ffffee4 | 744 | self.expr_err(span, self.tcx.sess.delay_span_bug(span, "no task_context hir id")) |
ba9703b0 | 745 | }; |
3dfed10e | 746 | let new_unchecked = self.expr_call_lang_item_fn_mut( |
416331ca | 747 | span, |
3dfed10e | 748 | hir::LangItem::PinNewUnchecked, |
5e7ed085 | 749 | arena_vec![self; ref_mut_awaitee], |
a2a8927a | 750 | Some(expr_hir_id), |
416331ca | 751 | ); |
3dfed10e | 752 | let get_context = self.expr_call_lang_item_fn_mut( |
416331ca | 753 | gen_future_span, |
3dfed10e | 754 | hir::LangItem::GetContext, |
ba9703b0 | 755 | arena_vec![self; task_context], |
a2a8927a | 756 | Some(expr_hir_id), |
ba9703b0 | 757 | ); |
3dfed10e | 758 | let call = self.expr_call_lang_item_fn( |
ba9703b0 | 759 | span, |
3dfed10e | 760 | hir::LangItem::FuturePoll, |
ba9703b0 | 761 | arena_vec![self; new_unchecked, get_context], |
a2a8927a | 762 | Some(expr_hir_id), |
ba9703b0 XL |
763 | ); |
764 | self.arena.alloc(self.expr_unsafe(call)) | |
416331ca XL |
765 | }; |
766 | ||
767 | // `::std::task::Poll::Ready(result) => break result` | |
923072b8 | 768 | let loop_node_id = self.next_node_id(); |
416331ca XL |
769 | let loop_hir_id = self.lower_node_id(loop_node_id); |
770 | let ready_arm = { | |
e1599b0c | 771 | let x_ident = Ident::with_dummy_span(sym::result); |
5099ac24 FG |
772 | let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident); |
773 | let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid); | |
774 | let ready_field = self.single_pat_field(gen_future_span, x_pat); | |
a2a8927a XL |
775 | let ready_pat = self.pat_lang_item_variant( |
776 | span, | |
777 | hir::LangItem::PollReady, | |
778 | ready_field, | |
779 | Some(expr_hir_id), | |
780 | ); | |
dfeec247 XL |
781 | let break_x = self.with_loop_scope(loop_node_id, move |this| { |
782 | let expr_break = | |
783 | hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr)); | |
487cf647 | 784 | this.arena.alloc(this.expr(gen_future_span, expr_break)) |
416331ca | 785 | }); |
e74abb32 | 786 | self.arm(ready_pat, break_x) |
416331ca XL |
787 | }; |
788 | ||
789 | // `::std::task::Poll::Pending => {}` | |
790 | let pending_arm = { | |
a2a8927a XL |
791 | let pending_pat = self.pat_lang_item_variant( |
792 | span, | |
793 | hir::LangItem::PollPending, | |
794 | &[], | |
795 | Some(expr_hir_id), | |
796 | ); | |
dfeec247 | 797 | let empty_block = self.expr_block_empty(span); |
e74abb32 | 798 | self.arm(pending_pat, empty_block) |
416331ca XL |
799 | }; |
800 | ||
e1599b0c | 801 | let inner_match_stmt = { |
416331ca XL |
802 | let match_expr = self.expr_match( |
803 | span, | |
804 | poll_expr, | |
dfeec247 | 805 | arena_vec![self; ready_arm, pending_arm], |
416331ca XL |
806 | hir::MatchSource::AwaitDesugar, |
807 | ); | |
808 | self.stmt_expr(span, match_expr) | |
809 | }; | |
810 | ||
ba9703b0 | 811 | // task_context = yield (); |
416331ca XL |
812 | let yield_stmt = { |
813 | let unit = self.expr_unit(span); | |
814 | let yield_expr = self.expr( | |
815 | span, | |
a2a8927a | 816 | hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr_hir_id) }), |
416331ca | 817 | ); |
ba9703b0 XL |
818 | let yield_expr = self.arena.alloc(yield_expr); |
819 | ||
820 | if let Some(task_context_hid) = self.task_context { | |
821 | let lhs = self.expr_ident(span, task_context_ident, task_context_hid); | |
487cf647 FG |
822 | let assign = |
823 | self.expr(span, hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span))); | |
ba9703b0 XL |
824 | self.stmt_expr(span, assign) |
825 | } else { | |
826 | // Use of `await` outside of an async context. Return `yield_expr` so that we can | |
827 | // proceed with type checking. | |
828 | self.stmt(span, hir::StmtKind::Semi(yield_expr)) | |
829 | } | |
416331ca XL |
830 | }; |
831 | ||
dfeec247 | 832 | let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None); |
416331ca | 833 | |
e1599b0c | 834 | // loop { .. } |
dfeec247 | 835 | let loop_expr = self.arena.alloc(hir::Expr { |
416331ca | 836 | hir_id: loop_hir_id, |
94222f64 XL |
837 | kind: hir::ExprKind::Loop( |
838 | loop_block, | |
839 | None, | |
840 | hir::LoopSource::Loop, | |
841 | self.lower_span(span), | |
842 | ), | |
843 | span: self.lower_span(span), | |
416331ca XL |
844 | }); |
845 | ||
5e7ed085 FG |
846 | // mut __awaitee => loop { ... } |
847 | let awaitee_arm = self.arm(awaitee_pat, loop_expr); | |
e1599b0c | 848 | |
a2a8927a XL |
849 | // `match ::std::future::IntoFuture::into_future(<expr>) { ... }` |
850 | let into_future_span = self.mark_span_with_reason( | |
851 | DesugaringKind::Await, | |
5099ac24 | 852 | dot_await_span, |
a2a8927a XL |
853 | self.allow_into_future.clone(), |
854 | ); | |
855 | let into_future_expr = self.expr_call_lang_item_fn( | |
856 | into_future_span, | |
857 | hir::LangItem::IntoFutureIntoFuture, | |
858 | arena_vec![self; expr], | |
859 | Some(expr_hir_id), | |
860 | ); | |
861 | ||
862 | // match <into_future_expr> { | |
5e7ed085 | 863 | // mut __awaitee => loop { .. } |
e1599b0c | 864 | // } |
a2a8927a XL |
865 | hir::ExprKind::Match( |
866 | into_future_expr, | |
5e7ed085 | 867 | arena_vec![self; awaitee_arm], |
a2a8927a XL |
868 | hir::MatchSource::AwaitDesugar, |
869 | ) | |
416331ca XL |
870 | } |
871 | ||
872 | fn lower_expr_closure( | |
873 | &mut self, | |
064997fb | 874 | binder: &ClosureBinder, |
416331ca | 875 | capture_clause: CaptureBy, |
923072b8 | 876 | closure_id: NodeId, |
9c376795 | 877 | constness: Const, |
416331ca XL |
878 | movability: Movability, |
879 | decl: &FnDecl, | |
880 | body: &Expr, | |
881 | fn_decl_span: Span, | |
487cf647 | 882 | fn_arg_span: Span, |
dfeec247 | 883 | ) -> hir::ExprKind<'hir> { |
064997fb FG |
884 | let (binder_clause, generic_params) = self.lower_closure_binder(binder); |
885 | ||
886 | let (body_id, generator_option) = self.with_new_scopes(move |this| { | |
e1599b0c | 887 | let prev = this.current_item; |
416331ca XL |
888 | this.current_item = Some(fn_decl_span); |
889 | let mut generator_kind = None; | |
890 | let body_id = this.lower_fn_body(decl, |this| { | |
dfeec247 | 891 | let e = this.lower_expr_mut(body); |
416331ca XL |
892 | generator_kind = this.generator_kind; |
893 | e | |
894 | }); | |
dfeec247 XL |
895 | let generator_option = |
896 | this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability); | |
e1599b0c | 897 | this.current_item = prev; |
5869c6ff XL |
898 | (body_id, generator_option) |
899 | }); | |
900 | ||
064997fb FG |
901 | let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params); |
902 | // Lower outside new scope to preserve `is_in_loop_condition`. | |
487cf647 | 903 | let fn_decl = self.lower_fn_decl(decl, closure_id, fn_decl_span, FnDeclKind::Closure, None); |
923072b8 | 904 | |
064997fb | 905 | let c = self.arena.alloc(hir::Closure { |
487cf647 | 906 | def_id: self.local_def_id(closure_id), |
064997fb FG |
907 | binder: binder_clause, |
908 | capture_clause, | |
909 | bound_generic_params, | |
910 | fn_decl, | |
911 | body: body_id, | |
912 | fn_decl_span: self.lower_span(fn_decl_span), | |
487cf647 | 913 | fn_arg_span: Some(self.lower_span(fn_arg_span)), |
064997fb | 914 | movability: generator_option, |
9c376795 | 915 | constness: self.lower_constness(constness), |
064997fb FG |
916 | }); |
917 | ||
918 | hir::ExprKind::Closure(c) | |
416331ca XL |
919 | } |
920 | ||
416331ca XL |
921 | fn generator_movability_for_fn( |
922 | &mut self, | |
923 | decl: &FnDecl, | |
924 | fn_decl_span: Span, | |
925 | generator_kind: Option<hir::GeneratorKind>, | |
926 | movability: Movability, | |
60c5eb7d | 927 | ) -> Option<hir::Movability> { |
416331ca | 928 | match generator_kind { |
dfeec247 | 929 | Some(hir::GeneratorKind::Gen) => { |
74b04a01 | 930 | if decl.inputs.len() > 1 { |
f2b60f7d | 931 | self.tcx.sess.emit_err(GeneratorTooManyParameters { fn_decl_span }); |
416331ca | 932 | } |
60c5eb7d | 933 | Some(movability) |
dfeec247 | 934 | } |
e74abb32 | 935 | Some(hir::GeneratorKind::Async(_)) => { |
ba9703b0 | 936 | panic!("non-`async` closure body turned `async` during lowering"); |
dfeec247 | 937 | } |
416331ca XL |
938 | None => { |
939 | if movability == Movability::Static { | |
f2b60f7d | 940 | self.tcx.sess.emit_err(ClosureCannotBeStatic { fn_decl_span }); |
416331ca XL |
941 | } |
942 | None | |
dfeec247 | 943 | } |
416331ca XL |
944 | } |
945 | } | |
946 | ||
064997fb FG |
947 | fn lower_closure_binder<'c>( |
948 | &mut self, | |
949 | binder: &'c ClosureBinder, | |
950 | ) -> (hir::ClosureBinder, &'c [GenericParam]) { | |
951 | let (binder, params) = match binder { | |
952 | ClosureBinder::NotPresent => (hir::ClosureBinder::Default, &[][..]), | |
487cf647 FG |
953 | ClosureBinder::For { span, generic_params } => { |
954 | let span = self.lower_span(*span); | |
064997fb FG |
955 | (hir::ClosureBinder::For { span }, &**generic_params) |
956 | } | |
957 | }; | |
958 | ||
959 | (binder, params) | |
960 | } | |
961 | ||
416331ca XL |
962 | fn lower_expr_async_closure( |
963 | &mut self, | |
064997fb | 964 | binder: &ClosureBinder, |
416331ca XL |
965 | capture_clause: CaptureBy, |
966 | closure_id: NodeId, | |
9c376795 | 967 | closure_hir_id: hir::HirId, |
923072b8 | 968 | inner_closure_id: NodeId, |
416331ca XL |
969 | decl: &FnDecl, |
970 | body: &Expr, | |
971 | fn_decl_span: Span, | |
487cf647 | 972 | fn_arg_span: Span, |
dfeec247 | 973 | ) -> hir::ExprKind<'hir> { |
064997fb | 974 | if let &ClosureBinder::For { span, .. } = binder { |
f2b60f7d | 975 | self.tcx.sess.emit_err(NotSupportedForLifetimeBinderAsyncClosure { span }); |
064997fb FG |
976 | } |
977 | ||
978 | let (binder_clause, generic_params) = self.lower_closure_binder(binder); | |
979 | ||
dfeec247 | 980 | let outer_decl = |
74b04a01 | 981 | FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) }; |
416331ca | 982 | |
923072b8 | 983 | let body = self.with_new_scopes(|this| { |
416331ca XL |
984 | // FIXME(cramertj): allow `async` non-`move` closures with arguments. |
985 | if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() { | |
f2b60f7d | 986 | this.tcx.sess.emit_err(AsyncNonMoveClosureNotSupported { fn_decl_span }); |
416331ca XL |
987 | } |
988 | ||
989 | // Transform `async |x: u8| -> X { ... }` into | |
353b0b11 | 990 | // `|x: u8| || -> X { ... }`. |
416331ca | 991 | let body_id = this.lower_fn_body(&outer_decl, |this| { |
487cf647 FG |
992 | let async_ret_ty = if let FnRetTy::Ty(ty) = &decl.output { |
993 | let itctx = ImplTraitContext::Disallowed(ImplTraitPosition::AsyncBlock); | |
994 | Some(hir::FnRetTy::Return(this.lower_ty(&ty, &itctx))) | |
995 | } else { | |
996 | None | |
997 | }; | |
998 | ||
416331ca | 999 | let async_body = this.make_async_expr( |
e74abb32 | 1000 | capture_clause, |
923072b8 | 1001 | inner_closure_id, |
e74abb32 XL |
1002 | async_ret_ty, |
1003 | body.span, | |
1004 | hir::AsyncGeneratorKind::Closure, | |
dfeec247 | 1005 | |this| this.with_new_scopes(|this| this.lower_expr_mut(body)), |
416331ca | 1006 | ); |
353b0b11 FG |
1007 | let hir_id = this.lower_node_id(inner_closure_id); |
1008 | this.maybe_forward_track_caller(body.span, closure_hir_id, hir_id); | |
1009 | hir::Expr { hir_id, kind: async_body, span: this.lower_span(body.span) } | |
416331ca | 1010 | }); |
5869c6ff XL |
1011 | body_id |
1012 | }); | |
1013 | ||
064997fb | 1014 | let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params); |
064997fb FG |
1015 | // We need to lower the declaration outside the new scope, because we |
1016 | // have to conserve the state of being inside a loop condition for the | |
1017 | // closure argument types. | |
f2b60f7d | 1018 | let fn_decl = |
487cf647 | 1019 | self.lower_fn_decl(&outer_decl, closure_id, fn_decl_span, FnDeclKind::Closure, None); |
064997fb FG |
1020 | |
1021 | let c = self.arena.alloc(hir::Closure { | |
487cf647 | 1022 | def_id: self.local_def_id(closure_id), |
064997fb FG |
1023 | binder: binder_clause, |
1024 | capture_clause, | |
1025 | bound_generic_params, | |
1026 | fn_decl, | |
1027 | body, | |
1028 | fn_decl_span: self.lower_span(fn_decl_span), | |
487cf647 | 1029 | fn_arg_span: Some(self.lower_span(fn_arg_span)), |
064997fb | 1030 | movability: None, |
9c376795 | 1031 | constness: hir::Constness::NotConst, |
064997fb FG |
1032 | }); |
1033 | hir::ExprKind::Closure(c) | |
416331ca XL |
1034 | } |
1035 | ||
29967ef6 XL |
1036 | /// Destructure the LHS of complex assignments. |
1037 | /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`. | |
1038 | fn lower_expr_assign( | |
1039 | &mut self, | |
1040 | lhs: &Expr, | |
1041 | rhs: &Expr, | |
1042 | eq_sign_span: Span, | |
1043 | whole_span: Span, | |
1044 | ) -> hir::ExprKind<'hir> { | |
1045 | // Return early in case of an ordinary assignment. | |
1046 | fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool { | |
1047 | match &lhs.kind { | |
fc512014 XL |
1048 | ExprKind::Array(..) |
1049 | | ExprKind::Struct(..) | |
1050 | | ExprKind::Tup(..) | |
1051 | | ExprKind::Underscore => false, | |
29967ef6 XL |
1052 | // Check for tuple struct constructor. |
1053 | ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(), | |
1054 | ExprKind::Paren(e) => { | |
1055 | match e.kind { | |
1056 | // We special-case `(..)` for consistency with patterns. | |
1057 | ExprKind::Range(None, None, RangeLimits::HalfOpen) => false, | |
1058 | _ => is_ordinary(lower_ctx, e), | |
1059 | } | |
1060 | } | |
1061 | _ => true, | |
1062 | } | |
1063 | } | |
1064 | if is_ordinary(self, lhs) { | |
94222f64 XL |
1065 | return hir::ExprKind::Assign( |
1066 | self.lower_expr(lhs), | |
1067 | self.lower_expr(rhs), | |
1068 | self.lower_span(eq_sign_span), | |
1069 | ); | |
29967ef6 | 1070 | } |
29967ef6 XL |
1071 | |
1072 | let mut assignments = vec![]; | |
1073 | ||
1074 | // The LHS becomes a pattern: `(lhs1, lhs2)`. | |
1075 | let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments); | |
1076 | let rhs = self.lower_expr(rhs); | |
1077 | ||
1078 | // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`. | |
1079 | let destructure_let = self.stmt_let_pat( | |
6a06907d | 1080 | None, |
29967ef6 XL |
1081 | whole_span, |
1082 | Some(rhs), | |
1083 | pat, | |
94222f64 | 1084 | hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)), |
29967ef6 XL |
1085 | ); |
1086 | ||
1087 | // `a = lhs1; b = lhs2;`. | |
1088 | let stmts = self | |
1089 | .arena | |
1090 | .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter())); | |
1091 | ||
1092 | // Wrap everything in a block. | |
1093 | hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None) | |
1094 | } | |
1095 | ||
1096 | /// If the given expression is a path to a tuple struct, returns that path. | |
1097 | /// It is not a complete check, but just tries to reject most paths early | |
1098 | /// if they are not tuple structs. | |
1099 | /// Type checking will take care of the full validation later. | |
17df50a5 XL |
1100 | fn extract_tuple_struct_path<'a>( |
1101 | &mut self, | |
1102 | expr: &'a Expr, | |
487cf647 | 1103 | ) -> Option<(&'a Option<AstP<QSelf>>, &'a Path)> { |
17df50a5 XL |
1104 | if let ExprKind::Path(qself, path) = &expr.kind { |
1105 | // Does the path resolve to something disallowed in a tuple struct/variant pattern? | |
29967ef6 | 1106 | if let Some(partial_res) = self.resolver.get_partial_res(expr.id) { |
2b03887a | 1107 | if let Some(res) = partial_res.full_res() && !res.expected_in_tuple_struct_pat() { |
29967ef6 XL |
1108 | return None; |
1109 | } | |
1110 | } | |
17df50a5 | 1111 | return Some((qself, path)); |
29967ef6 XL |
1112 | } |
1113 | None | |
1114 | } | |
1115 | ||
04454e1e FG |
1116 | /// If the given expression is a path to a unit struct, returns that path. |
1117 | /// It is not a complete check, but just tries to reject most paths early | |
1118 | /// if they are not unit structs. | |
1119 | /// Type checking will take care of the full validation later. | |
1120 | fn extract_unit_struct_path<'a>( | |
1121 | &mut self, | |
1122 | expr: &'a Expr, | |
487cf647 | 1123 | ) -> Option<(&'a Option<AstP<QSelf>>, &'a Path)> { |
04454e1e FG |
1124 | if let ExprKind::Path(qself, path) = &expr.kind { |
1125 | // Does the path resolve to something disallowed in a unit struct/variant pattern? | |
1126 | if let Some(partial_res) = self.resolver.get_partial_res(expr.id) { | |
2b03887a | 1127 | if let Some(res) = partial_res.full_res() && !res.expected_in_unit_struct_pat() { |
04454e1e FG |
1128 | return None; |
1129 | } | |
1130 | } | |
1131 | return Some((qself, path)); | |
1132 | } | |
1133 | None | |
1134 | } | |
1135 | ||
29967ef6 XL |
1136 | /// Convert the LHS of a destructuring assignment to a pattern. |
1137 | /// Each sub-assignment is recorded in `assignments`. | |
1138 | fn destructure_assign( | |
1139 | &mut self, | |
1140 | lhs: &Expr, | |
1141 | eq_sign_span: Span, | |
1142 | assignments: &mut Vec<hir::Stmt<'hir>>, | |
1143 | ) -> &'hir hir::Pat<'hir> { | |
136023e0 XL |
1144 | self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments)) |
1145 | } | |
1146 | ||
1147 | fn destructure_assign_mut( | |
1148 | &mut self, | |
1149 | lhs: &Expr, | |
1150 | eq_sign_span: Span, | |
1151 | assignments: &mut Vec<hir::Stmt<'hir>>, | |
1152 | ) -> hir::Pat<'hir> { | |
29967ef6 | 1153 | match &lhs.kind { |
fc512014 XL |
1154 | // Underscore pattern. |
1155 | ExprKind::Underscore => { | |
1156 | return self.pat_without_dbm(lhs.span, hir::PatKind::Wild); | |
1157 | } | |
29967ef6 XL |
1158 | // Slice patterns. |
1159 | ExprKind::Array(elements) => { | |
1160 | let (pats, rest) = | |
1161 | self.destructure_sequence(elements, "slice", eq_sign_span, assignments); | |
1162 | let slice_pat = if let Some((i, span)) = rest { | |
1163 | let (before, after) = pats.split_at(i); | |
1164 | hir::PatKind::Slice( | |
1165 | before, | |
136023e0 | 1166 | Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))), |
29967ef6 XL |
1167 | after, |
1168 | ) | |
1169 | } else { | |
1170 | hir::PatKind::Slice(pats, None, &[]) | |
1171 | }; | |
1172 | return self.pat_without_dbm(lhs.span, slice_pat); | |
1173 | } | |
1174 | // Tuple structs. | |
1175 | ExprKind::Call(callee, args) => { | |
17df50a5 | 1176 | if let Some((qself, path)) = self.extract_tuple_struct_path(callee) { |
29967ef6 XL |
1177 | let (pats, rest) = self.destructure_sequence( |
1178 | args, | |
1179 | "tuple struct or variant", | |
1180 | eq_sign_span, | |
1181 | assignments, | |
1182 | ); | |
1183 | let qpath = self.lower_qpath( | |
1184 | callee.id, | |
17df50a5 | 1185 | qself, |
29967ef6 XL |
1186 | path, |
1187 | ParamMode::Optional, | |
f2b60f7d | 1188 | &ImplTraitContext::Disallowed(ImplTraitPosition::Path), |
29967ef6 XL |
1189 | ); |
1190 | // Destructure like a tuple struct. | |
f2b60f7d FG |
1191 | let tuple_struct_pat = hir::PatKind::TupleStruct( |
1192 | qpath, | |
1193 | pats, | |
1194 | hir::DotDotPos::new(rest.map(|r| r.0)), | |
1195 | ); | |
29967ef6 XL |
1196 | return self.pat_without_dbm(lhs.span, tuple_struct_pat); |
1197 | } | |
1198 | } | |
04454e1e FG |
1199 | // Unit structs and enum variants. |
1200 | ExprKind::Path(..) => { | |
1201 | if let Some((qself, path)) = self.extract_unit_struct_path(lhs) { | |
1202 | let qpath = self.lower_qpath( | |
1203 | lhs.id, | |
1204 | qself, | |
1205 | path, | |
1206 | ParamMode::Optional, | |
f2b60f7d | 1207 | &ImplTraitContext::Disallowed(ImplTraitPosition::Path), |
04454e1e FG |
1208 | ); |
1209 | // Destructure like a unit struct. | |
1210 | let unit_struct_pat = hir::PatKind::Path(qpath); | |
1211 | return self.pat_without_dbm(lhs.span, unit_struct_pat); | |
1212 | } | |
1213 | } | |
29967ef6 | 1214 | // Structs. |
6a06907d XL |
1215 | ExprKind::Struct(se) => { |
1216 | let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| { | |
29967ef6 | 1217 | let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments); |
6a06907d | 1218 | hir::PatField { |
29967ef6 | 1219 | hir_id: self.next_id(), |
94222f64 | 1220 | ident: self.lower_ident(f.ident), |
29967ef6 XL |
1221 | pat, |
1222 | is_shorthand: f.is_shorthand, | |
94222f64 | 1223 | span: self.lower_span(f.span), |
29967ef6 XL |
1224 | } |
1225 | })); | |
1226 | let qpath = self.lower_qpath( | |
1227 | lhs.id, | |
17df50a5 | 1228 | &se.qself, |
6a06907d | 1229 | &se.path, |
29967ef6 | 1230 | ParamMode::Optional, |
f2b60f7d | 1231 | &ImplTraitContext::Disallowed(ImplTraitPosition::Path), |
29967ef6 | 1232 | ); |
6a06907d | 1233 | let fields_omitted = match &se.rest { |
29967ef6 | 1234 | StructRest::Base(e) => { |
353b0b11 | 1235 | self.tcx.sess.emit_err(FunctionalRecordUpdateDestructuringAssignment { |
f2b60f7d FG |
1236 | span: e.span, |
1237 | }); | |
29967ef6 XL |
1238 | true |
1239 | } | |
1240 | StructRest::Rest(_) => true, | |
1241 | StructRest::None => false, | |
1242 | }; | |
1243 | let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted); | |
1244 | return self.pat_without_dbm(lhs.span, struct_pat); | |
1245 | } | |
1246 | // Tuples. | |
1247 | ExprKind::Tup(elements) => { | |
1248 | let (pats, rest) = | |
1249 | self.destructure_sequence(elements, "tuple", eq_sign_span, assignments); | |
f2b60f7d | 1250 | let tuple_pat = hir::PatKind::Tuple(pats, hir::DotDotPos::new(rest.map(|r| r.0))); |
29967ef6 XL |
1251 | return self.pat_without_dbm(lhs.span, tuple_pat); |
1252 | } | |
1253 | ExprKind::Paren(e) => { | |
1254 | // We special-case `(..)` for consistency with patterns. | |
1255 | if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind { | |
f2b60f7d | 1256 | let tuple_pat = hir::PatKind::Tuple(&[], hir::DotDotPos::new(Some(0))); |
29967ef6 XL |
1257 | return self.pat_without_dbm(lhs.span, tuple_pat); |
1258 | } else { | |
136023e0 | 1259 | return self.destructure_assign_mut(e, eq_sign_span, assignments); |
29967ef6 XL |
1260 | } |
1261 | } | |
1262 | _ => {} | |
1263 | } | |
1264 | // Treat all other cases as normal lvalue. | |
94222f64 | 1265 | let ident = Ident::new(sym::lhs, self.lower_span(lhs.span)); |
136023e0 | 1266 | let (pat, binding) = self.pat_ident_mut(lhs.span, ident); |
29967ef6 | 1267 | let ident = self.expr_ident(lhs.span, ident, binding); |
94222f64 XL |
1268 | let assign = |
1269 | hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span)); | |
487cf647 | 1270 | let expr = self.expr(lhs.span, assign); |
29967ef6 XL |
1271 | assignments.push(self.stmt_expr(lhs.span, expr)); |
1272 | pat | |
1273 | } | |
1274 | ||
1275 | /// Destructure a sequence of expressions occurring on the LHS of an assignment. | |
1276 | /// Such a sequence occurs in a tuple (struct)/slice. | |
1277 | /// Return a sequence of corresponding patterns, and the index and the span of `..` if it | |
1278 | /// exists. | |
1279 | /// Each sub-assignment is recorded in `assignments`. | |
1280 | fn destructure_sequence( | |
1281 | &mut self, | |
1282 | elements: &[AstP<Expr>], | |
1283 | ctx: &str, | |
1284 | eq_sign_span: Span, | |
1285 | assignments: &mut Vec<hir::Stmt<'hir>>, | |
136023e0 | 1286 | ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) { |
29967ef6 XL |
1287 | let mut rest = None; |
1288 | let elements = | |
1289 | self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| { | |
1290 | // Check for `..` pattern. | |
1291 | if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind { | |
1292 | if let Some((_, prev_span)) = rest { | |
1293 | self.ban_extra_rest_pat(e.span, prev_span, ctx); | |
1294 | } else { | |
1295 | rest = Some((i, e.span)); | |
1296 | } | |
1297 | None | |
1298 | } else { | |
136023e0 | 1299 | Some(self.destructure_assign_mut(e, eq_sign_span, assignments)) |
29967ef6 XL |
1300 | } |
1301 | })); | |
1302 | (elements, rest) | |
1303 | } | |
1304 | ||
416331ca | 1305 | /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`. |
dfeec247 | 1306 | fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> { |
dfeec247 XL |
1307 | let e1 = self.lower_expr_mut(e1); |
1308 | let e2 = self.lower_expr_mut(e2); | |
a2a8927a XL |
1309 | let fn_path = |
1310 | hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span), None); | |
487cf647 | 1311 | let fn_expr = self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path))); |
3dfed10e | 1312 | hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2]) |
416331ca XL |
1313 | } |
1314 | ||
1315 | fn lower_expr_range( | |
1316 | &mut self, | |
1317 | span: Span, | |
1318 | e1: Option<&Expr>, | |
1319 | e2: Option<&Expr>, | |
1320 | lims: RangeLimits, | |
dfeec247 | 1321 | ) -> hir::ExprKind<'hir> { |
3dfed10e XL |
1322 | use rustc_ast::RangeLimits::*; |
1323 | ||
1324 | let lang_item = match (e1, e2, lims) { | |
1325 | (None, None, HalfOpen) => hir::LangItem::RangeFull, | |
1326 | (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom, | |
1327 | (None, Some(..), HalfOpen) => hir::LangItem::RangeTo, | |
1328 | (Some(..), Some(..), HalfOpen) => hir::LangItem::Range, | |
1329 | (None, Some(..), Closed) => hir::LangItem::RangeToInclusive, | |
416331ca | 1330 | (Some(..), Some(..), Closed) => unreachable!(), |
f2b60f7d FG |
1331 | (start, None, Closed) => { |
1332 | self.tcx.sess.emit_err(InclusiveRangeWithNoEnd { span }); | |
1333 | match start { | |
1334 | Some(..) => hir::LangItem::RangeFrom, | |
1335 | None => hir::LangItem::RangeFull, | |
1336 | } | |
1337 | } | |
416331ca XL |
1338 | }; |
1339 | ||
dfeec247 | 1340 | let fields = self.arena.alloc_from_iter( |
5099ac24 FG |
1341 | e1.iter().map(|e| (sym::start, e)).chain(e2.iter().map(|e| (sym::end, e))).map( |
1342 | |(s, e)| { | |
1343 | let expr = self.lower_expr(&e); | |
1344 | let ident = Ident::new(s, self.lower_span(e.span)); | |
1345 | self.expr_field(ident, expr, e.span) | |
1346 | }, | |
1347 | ), | |
dfeec247 | 1348 | ); |
416331ca | 1349 | |
94222f64 | 1350 | hir::ExprKind::Struct( |
a2a8927a | 1351 | self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span), None)), |
94222f64 XL |
1352 | fields, |
1353 | None, | |
1354 | ) | |
1355 | } | |
1356 | ||
1357 | fn lower_label(&self, opt_label: Option<Label>) -> Option<Label> { | |
1358 | let label = opt_label?; | |
1359 | Some(Label { ident: self.lower_ident(label.ident) }) | |
416331ca XL |
1360 | } |
1361 | ||
416331ca XL |
1362 | fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination { |
1363 | let target_id = match destination { | |
1364 | Some((id, _)) => { | |
1365 | if let Some(loop_id) = self.resolver.get_label_res(id) { | |
1366 | Ok(self.lower_node_id(loop_id)) | |
1367 | } else { | |
1368 | Err(hir::LoopIdError::UnresolvedLabel) | |
1369 | } | |
1370 | } | |
dfeec247 | 1371 | None => self |
c295e0f8 | 1372 | .loop_scope |
dfeec247 | 1373 | .map(|id| Ok(self.lower_node_id(id))) |
74b04a01 | 1374 | .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)), |
416331ca | 1375 | }; |
94222f64 XL |
1376 | let label = self.lower_label(destination.map(|(_, label)| label)); |
1377 | hir::Destination { label, target_id } | |
416331ca XL |
1378 | } |
1379 | ||
1380 | fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination { | |
1381 | if self.is_in_loop_condition && opt_label.is_none() { | |
1382 | hir::Destination { | |
1383 | label: None, | |
74b04a01 | 1384 | target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition), |
416331ca XL |
1385 | } |
1386 | } else { | |
1387 | self.lower_loop_destination(opt_label.map(|label| (id, label))) | |
1388 | } | |
1389 | } | |
1390 | ||
dfeec247 | 1391 | fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { |
c295e0f8 | 1392 | let old_scope = self.catch_scope.replace(catch_id); |
416331ca | 1393 | let result = f(self); |
c295e0f8 | 1394 | self.catch_scope = old_scope; |
416331ca XL |
1395 | result |
1396 | } | |
1397 | ||
dfeec247 | 1398 | fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { |
416331ca XL |
1399 | // We're no longer in the base loop's condition; we're in another loop. |
1400 | let was_in_loop_condition = self.is_in_loop_condition; | |
1401 | self.is_in_loop_condition = false; | |
1402 | ||
c295e0f8 | 1403 | let old_scope = self.loop_scope.replace(loop_id); |
416331ca | 1404 | let result = f(self); |
c295e0f8 | 1405 | self.loop_scope = old_scope; |
416331ca XL |
1406 | |
1407 | self.is_in_loop_condition = was_in_loop_condition; | |
1408 | ||
1409 | result | |
1410 | } | |
1411 | ||
dfeec247 | 1412 | fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T { |
416331ca XL |
1413 | let was_in_loop_condition = self.is_in_loop_condition; |
1414 | self.is_in_loop_condition = true; | |
1415 | ||
1416 | let result = f(self); | |
1417 | ||
1418 | self.is_in_loop_condition = was_in_loop_condition; | |
1419 | ||
1420 | result | |
1421 | } | |
1422 | ||
6a06907d | 1423 | fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> { |
f2b60f7d FG |
1424 | let hir_id = self.lower_node_id(f.id); |
1425 | self.lower_attrs(hir_id, &f.attrs); | |
6a06907d | 1426 | hir::ExprField { |
f2b60f7d | 1427 | hir_id, |
94222f64 | 1428 | ident: self.lower_ident(f.ident), |
dfeec247 | 1429 | expr: self.lower_expr(&f.expr), |
94222f64 | 1430 | span: self.lower_span(f.span), |
416331ca XL |
1431 | is_shorthand: f.is_shorthand, |
1432 | } | |
1433 | } | |
1434 | ||
dfeec247 | 1435 | fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> { |
416331ca | 1436 | match self.generator_kind { |
dfeec247 | 1437 | Some(hir::GeneratorKind::Gen) => {} |
e74abb32 | 1438 | Some(hir::GeneratorKind::Async(_)) => { |
f2b60f7d | 1439 | self.tcx.sess.emit_err(AsyncGeneratorsNotSupported { span }); |
dfeec247 | 1440 | } |
416331ca XL |
1441 | None => self.generator_kind = Some(hir::GeneratorKind::Gen), |
1442 | } | |
1443 | ||
dfeec247 XL |
1444 | let expr = |
1445 | opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span)); | |
416331ca | 1446 | |
dfeec247 | 1447 | hir::ExprKind::Yield(expr, hir::YieldSource::Yield) |
416331ca XL |
1448 | } |
1449 | ||
1450 | /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into: | |
04454e1e | 1451 | /// ```ignore (pseudo-rust) |
416331ca | 1452 | /// { |
3c0e092e | 1453 | /// let result = match IntoIterator::into_iter(<head>) { |
416331ca XL |
1454 | /// mut iter => { |
1455 | /// [opt_ident]: loop { | |
3c0e092e XL |
1456 | /// match Iterator::next(&mut iter) { |
1457 | /// None => break, | |
1458 | /// Some(<pat>) => <body>, | |
416331ca | 1459 | /// }; |
416331ca XL |
1460 | /// } |
1461 | /// } | |
1462 | /// }; | |
1463 | /// result | |
1464 | /// } | |
1465 | /// ``` | |
1466 | fn lower_expr_for( | |
1467 | &mut self, | |
1468 | e: &Expr, | |
1469 | pat: &Pat, | |
1470 | head: &Expr, | |
1471 | body: &Block, | |
1472 | opt_label: Option<Label>, | |
dfeec247 | 1473 | ) -> hir::Expr<'hir> { |
3c0e092e XL |
1474 | let head = self.lower_expr_mut(head); |
1475 | let pat = self.lower_pat(pat); | |
1476 | let for_span = | |
1477 | self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None); | |
1478 | let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None); | |
1479 | let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None); | |
416331ca | 1480 | |
3c0e092e XL |
1481 | // `None => break` |
1482 | let none_arm = { | |
487cf647 | 1483 | let break_expr = self.with_loop_scope(e.id, |this| this.expr_break_alloc(for_span)); |
3c0e092e | 1484 | let pat = self.pat_none(for_span); |
e74abb32 | 1485 | self.arm(pat, break_expr) |
416331ca XL |
1486 | }; |
1487 | ||
3c0e092e XL |
1488 | // Some(<pat>) => <body>, |
1489 | let some_arm = { | |
1490 | let some_pat = self.pat_some(pat_span, pat); | |
1491 | let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false)); | |
487cf647 | 1492 | let body_expr = self.arena.alloc(self.expr_block(body_block)); |
3c0e092e XL |
1493 | self.arm(some_pat, body_expr) |
1494 | }; | |
1495 | ||
416331ca | 1496 | // `mut iter` |
3c0e092e | 1497 | let iter = Ident::with_dummy_span(sym::iter); |
dfeec247 | 1498 | let (iter_pat, iter_pat_nid) = |
f2b60f7d | 1499 | self.pat_ident_binding_mode(head_span, iter, hir::BindingAnnotation::MUT); |
416331ca | 1500 | |
3c0e092e | 1501 | // `match Iterator::next(&mut iter) { ... }` |
416331ca | 1502 | let match_expr = { |
3c0e092e XL |
1503 | let iter = self.expr_ident(head_span, iter, iter_pat_nid); |
1504 | let ref_mut_iter = self.expr_mut_addr_of(head_span, iter); | |
3dfed10e | 1505 | let next_expr = self.expr_call_lang_item_fn( |
3c0e092e | 1506 | head_span, |
3dfed10e XL |
1507 | hir::LangItem::IteratorNext, |
1508 | arena_vec![self; ref_mut_iter], | |
a2a8927a | 1509 | None, |
3dfed10e | 1510 | ); |
3c0e092e | 1511 | let arms = arena_vec![self; none_arm, some_arm]; |
416331ca | 1512 | |
3c0e092e | 1513 | self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar) |
416331ca | 1514 | }; |
3c0e092e | 1515 | let match_stmt = self.stmt_expr(for_span, match_expr); |
416331ca | 1516 | |
3c0e092e | 1517 | let loop_block = self.block_all(for_span, arena_vec![self; match_stmt], None); |
416331ca XL |
1518 | |
1519 | // `[opt_ident]: loop { ... }` | |
5869c6ff XL |
1520 | let kind = hir::ExprKind::Loop( |
1521 | loop_block, | |
94222f64 | 1522 | self.lower_label(opt_label), |
5869c6ff | 1523 | hir::LoopSource::ForLoop, |
3c0e092e | 1524 | self.lower_span(for_span.with_hi(head.span.hi())), |
5869c6ff | 1525 | ); |
3c0e092e XL |
1526 | let loop_expr = |
1527 | self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: for_span }); | |
416331ca XL |
1528 | |
1529 | // `mut iter => { ... }` | |
e74abb32 | 1530 | let iter_arm = self.arm(iter_pat, loop_expr); |
416331ca XL |
1531 | |
1532 | // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }` | |
1533 | let into_iter_expr = { | |
3dfed10e | 1534 | self.expr_call_lang_item_fn( |
3c0e092e | 1535 | head_span, |
3dfed10e XL |
1536 | hir::LangItem::IntoIterIntoIter, |
1537 | arena_vec![self; head], | |
a2a8927a | 1538 | None, |
3dfed10e | 1539 | ) |
416331ca XL |
1540 | }; |
1541 | ||
dfeec247 | 1542 | let match_expr = self.arena.alloc(self.expr_match( |
3c0e092e | 1543 | for_span, |
416331ca | 1544 | into_iter_expr, |
dfeec247 | 1545 | arena_vec![self; iter_arm], |
416331ca XL |
1546 | hir::MatchSource::ForLoopDesugar, |
1547 | )); | |
1548 | ||
1549 | // This is effectively `{ let _result = ...; _result }`. | |
1550 | // The construct was introduced in #21984 and is necessary to make sure that | |
1551 | // temporaries in the `head` expression are dropped and do not leak to the | |
1552 | // surrounding scope of the `match` since the `match` is not a terminating scope. | |
1553 | // | |
1554 | // Also, add the attributes to the outer returned expr node. | |
487cf647 FG |
1555 | let expr = self.expr_drop_temps_mut(for_span, match_expr); |
1556 | self.lower_attrs(expr.hir_id, &e.attrs); | |
1557 | expr | |
416331ca XL |
1558 | } |
1559 | ||
1560 | /// Desugar `ExprKind::Try` from: `<expr>?` into: | |
04454e1e | 1561 | /// ```ignore (pseudo-rust) |
136023e0 XL |
1562 | /// match Try::branch(<expr>) { |
1563 | /// ControlFlow::Continue(val) => #[allow(unreachable_code)] val,, | |
1564 | /// ControlFlow::Break(residual) => | |
1565 | /// #[allow(unreachable_code)] | |
1566 | /// // If there is an enclosing `try {...}`: | |
1567 | /// break 'catch_target Try::from_residual(residual), | |
1568 | /// // Otherwise: | |
1569 | /// return Try::from_residual(residual), | |
416331ca XL |
1570 | /// } |
1571 | /// ``` | |
dfeec247 | 1572 | fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> { |
416331ca XL |
1573 | let unstable_span = self.mark_span_with_reason( |
1574 | DesugaringKind::QuestionMark, | |
1575 | span, | |
1576 | self.allow_try_trait.clone(), | |
1577 | ); | |
064997fb | 1578 | let try_span = self.tcx.sess.source_map().end_point(span); |
416331ca XL |
1579 | let try_span = self.mark_span_with_reason( |
1580 | DesugaringKind::QuestionMark, | |
1581 | try_span, | |
1582 | self.allow_try_trait.clone(), | |
1583 | ); | |
1584 | ||
17df50a5 | 1585 | // `Try::branch(<expr>)` |
416331ca XL |
1586 | let scrutinee = { |
1587 | // expand <expr> | |
dfeec247 | 1588 | let sub_expr = self.lower_expr_mut(sub_expr); |
416331ca | 1589 | |
3dfed10e XL |
1590 | self.expr_call_lang_item_fn( |
1591 | unstable_span, | |
17df50a5 | 1592 | hir::LangItem::TryTraitBranch, |
3dfed10e | 1593 | arena_vec![self; sub_expr], |
a2a8927a | 1594 | None, |
3dfed10e | 1595 | ) |
416331ca XL |
1596 | }; |
1597 | ||
1598 | // `#[allow(unreachable_code)]` | |
487cf647 FG |
1599 | let attr = attr::mk_attr_nested_word( |
1600 | &self.tcx.sess.parse_sess.attr_id_generator, | |
1601 | AttrStyle::Outer, | |
1602 | sym::allow, | |
1603 | sym::unreachable_code, | |
1604 | self.lower_span(span), | |
1605 | ); | |
f2b60f7d | 1606 | let attrs: AttrVec = thin_vec![attr]; |
416331ca | 1607 | |
17df50a5 XL |
1608 | // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,` |
1609 | let continue_arm = { | |
e1599b0c | 1610 | let val_ident = Ident::with_dummy_span(sym::val); |
416331ca | 1611 | let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident); |
487cf647 FG |
1612 | let val_expr = self.expr_ident(span, val_ident, val_pat_nid); |
1613 | self.lower_attrs(val_expr.hir_id, &attrs); | |
17df50a5 XL |
1614 | let continue_pat = self.pat_cf_continue(unstable_span, val_pat); |
1615 | self.arm(continue_pat, val_expr) | |
416331ca XL |
1616 | }; |
1617 | ||
17df50a5 XL |
1618 | // `ControlFlow::Break(residual) => |
1619 | // #[allow(unreachable_code)] | |
1620 | // return Try::from_residual(residual),` | |
1621 | let break_arm = { | |
1622 | let residual_ident = Ident::with_dummy_span(sym::residual); | |
1623 | let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident); | |
1624 | let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid); | |
1625 | let from_residual_expr = self.wrap_in_try_constructor( | |
1626 | hir::LangItem::TryTraitFromResidual, | |
1627 | try_span, | |
1628 | self.arena.alloc(residual_expr), | |
29967ef6 | 1629 | unstable_span, |
3dfed10e | 1630 | ); |
c295e0f8 | 1631 | let ret_expr = if let Some(catch_node) = self.catch_scope { |
416331ca | 1632 | let target_id = Ok(self.lower_node_id(catch_node)); |
dfeec247 | 1633 | self.arena.alloc(self.expr( |
416331ca XL |
1634 | try_span, |
1635 | hir::ExprKind::Break( | |
dfeec247 | 1636 | hir::Destination { label: None, target_id }, |
17df50a5 | 1637 | Some(from_residual_expr), |
416331ca | 1638 | ), |
416331ca XL |
1639 | )) |
1640 | } else { | |
487cf647 | 1641 | self.arena.alloc(self.expr(try_span, hir::ExprKind::Ret(Some(from_residual_expr)))) |
416331ca | 1642 | }; |
487cf647 | 1643 | self.lower_attrs(ret_expr.hir_id, &attrs); |
416331ca | 1644 | |
17df50a5 XL |
1645 | let break_pat = self.pat_cf_break(try_span, residual_local); |
1646 | self.arm(break_pat, ret_expr) | |
416331ca XL |
1647 | }; |
1648 | ||
1649 | hir::ExprKind::Match( | |
1650 | scrutinee, | |
17df50a5 | 1651 | arena_vec![self; break_arm, continue_arm], |
416331ca XL |
1652 | hir::MatchSource::TryDesugar, |
1653 | ) | |
1654 | } | |
1655 | ||
04454e1e | 1656 | /// Desugar `ExprKind::Yeet` from: `do yeet <expr>` into: |
2b03887a | 1657 | /// ```ignore(illustrative) |
04454e1e | 1658 | /// // If there is an enclosing `try {...}`: |
2b03887a | 1659 | /// break 'catch_target FromResidual::from_residual(Yeet(residual)); |
04454e1e | 1660 | /// // Otherwise: |
2b03887a | 1661 | /// return FromResidual::from_residual(Yeet(residual)); |
04454e1e FG |
1662 | /// ``` |
1663 | /// But to simplify this, there's a `from_yeet` lang item function which | |
1664 | /// handles the combined `FromResidual::from_residual(Yeet(residual))`. | |
1665 | fn lower_expr_yeet(&mut self, span: Span, sub_expr: Option<&Expr>) -> hir::ExprKind<'hir> { | |
1666 | // The expression (if present) or `()` otherwise. | |
1667 | let (yeeted_span, yeeted_expr) = if let Some(sub_expr) = sub_expr { | |
1668 | (sub_expr.span, self.lower_expr(sub_expr)) | |
1669 | } else { | |
1670 | (self.mark_span_with_reason(DesugaringKind::YeetExpr, span, None), self.expr_unit(span)) | |
1671 | }; | |
1672 | ||
1673 | let unstable_span = self.mark_span_with_reason( | |
1674 | DesugaringKind::YeetExpr, | |
1675 | span, | |
1676 | self.allow_try_trait.clone(), | |
1677 | ); | |
1678 | ||
1679 | let from_yeet_expr = self.wrap_in_try_constructor( | |
1680 | hir::LangItem::TryTraitFromYeet, | |
1681 | unstable_span, | |
1682 | yeeted_expr, | |
1683 | yeeted_span, | |
1684 | ); | |
1685 | ||
1686 | if let Some(catch_node) = self.catch_scope { | |
1687 | let target_id = Ok(self.lower_node_id(catch_node)); | |
1688 | hir::ExprKind::Break(hir::Destination { label: None, target_id }, Some(from_yeet_expr)) | |
1689 | } else { | |
1690 | hir::ExprKind::Ret(Some(from_yeet_expr)) | |
1691 | } | |
1692 | } | |
1693 | ||
416331ca XL |
1694 | // ========================================================================= |
1695 | // Helper methods for building HIR. | |
1696 | // ========================================================================= | |
1697 | ||
416331ca XL |
1698 | /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`. |
1699 | /// | |
1700 | /// In terms of drop order, it has the same effect as wrapping `expr` in | |
1701 | /// `{ let _t = $expr; _t }` but should provide better compile-time performance. | |
1702 | /// | |
1703 | /// The drop order can be important in e.g. `if expr { .. }`. | |
e1599b0c | 1704 | pub(super) fn expr_drop_temps( |
416331ca XL |
1705 | &mut self, |
1706 | span: Span, | |
dfeec247 | 1707 | expr: &'hir hir::Expr<'hir>, |
dfeec247 | 1708 | ) -> &'hir hir::Expr<'hir> { |
487cf647 | 1709 | self.arena.alloc(self.expr_drop_temps_mut(span, expr)) |
dfeec247 XL |
1710 | } |
1711 | ||
1712 | pub(super) fn expr_drop_temps_mut( | |
1713 | &mut self, | |
1714 | span: Span, | |
1715 | expr: &'hir hir::Expr<'hir>, | |
dfeec247 | 1716 | ) -> hir::Expr<'hir> { |
487cf647 | 1717 | self.expr(span, hir::ExprKind::DropTemps(expr)) |
416331ca XL |
1718 | } |
1719 | ||
9ffffee4 | 1720 | pub(super) fn expr_match( |
416331ca XL |
1721 | &mut self, |
1722 | span: Span, | |
dfeec247 XL |
1723 | arg: &'hir hir::Expr<'hir>, |
1724 | arms: &'hir [hir::Arm<'hir>], | |
416331ca | 1725 | source: hir::MatchSource, |
dfeec247 | 1726 | ) -> hir::Expr<'hir> { |
487cf647 | 1727 | self.expr(span, hir::ExprKind::Match(arg, arms, source)) |
416331ca XL |
1728 | } |
1729 | ||
487cf647 | 1730 | fn expr_break(&mut self, span: Span) -> hir::Expr<'hir> { |
416331ca | 1731 | let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None); |
487cf647 | 1732 | self.expr(span, expr_break) |
94222f64 XL |
1733 | } |
1734 | ||
487cf647 FG |
1735 | fn expr_break_alloc(&mut self, span: Span) -> &'hir hir::Expr<'hir> { |
1736 | let expr_break = self.expr_break(span); | |
94222f64 | 1737 | self.arena.alloc(expr_break) |
416331ca XL |
1738 | } |
1739 | ||
dfeec247 | 1740 | fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> { |
487cf647 | 1741 | self.expr(span, hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e)) |
416331ca XL |
1742 | } |
1743 | ||
dfeec247 | 1744 | fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> { |
487cf647 | 1745 | self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]))) |
416331ca XL |
1746 | } |
1747 | ||
9ffffee4 FG |
1748 | pub(super) fn expr_usize(&mut self, sp: Span, value: usize) -> hir::Expr<'hir> { |
1749 | self.expr( | |
1750 | sp, | |
1751 | hir::ExprKind::Lit(hir::Lit { | |
1752 | span: sp, | |
1753 | node: ast::LitKind::Int( | |
1754 | value as u128, | |
1755 | ast::LitIntType::Unsigned(ast::UintTy::Usize), | |
1756 | ), | |
1757 | }), | |
1758 | ) | |
1759 | } | |
1760 | ||
1761 | pub(super) fn expr_u32(&mut self, sp: Span, value: u32) -> hir::Expr<'hir> { | |
1762 | self.expr( | |
1763 | sp, | |
1764 | hir::ExprKind::Lit(hir::Lit { | |
1765 | span: sp, | |
1766 | node: ast::LitKind::Int(value.into(), ast::LitIntType::Unsigned(ast::UintTy::U32)), | |
1767 | }), | |
1768 | ) | |
1769 | } | |
1770 | ||
1771 | pub(super) fn expr_char(&mut self, sp: Span, value: char) -> hir::Expr<'hir> { | |
1772 | self.expr(sp, hir::ExprKind::Lit(hir::Lit { span: sp, node: ast::LitKind::Char(value) })) | |
1773 | } | |
1774 | ||
1775 | pub(super) fn expr_str(&mut self, sp: Span, value: Symbol) -> hir::Expr<'hir> { | |
1776 | self.expr( | |
1777 | sp, | |
1778 | hir::ExprKind::Lit(hir::Lit { | |
1779 | span: sp, | |
1780 | node: ast::LitKind::Str(value, ast::StrStyle::Cooked), | |
1781 | }), | |
1782 | ) | |
1783 | } | |
1784 | ||
1785 | pub(super) fn expr_call_mut( | |
ba9703b0 XL |
1786 | &mut self, |
1787 | span: Span, | |
1788 | e: &'hir hir::Expr<'hir>, | |
1789 | args: &'hir [hir::Expr<'hir>], | |
1790 | ) -> hir::Expr<'hir> { | |
487cf647 | 1791 | self.expr(span, hir::ExprKind::Call(e, args)) |
ba9703b0 XL |
1792 | } |
1793 | ||
9ffffee4 | 1794 | pub(super) fn expr_call( |
416331ca XL |
1795 | &mut self, |
1796 | span: Span, | |
dfeec247 XL |
1797 | e: &'hir hir::Expr<'hir>, |
1798 | args: &'hir [hir::Expr<'hir>], | |
1799 | ) -> &'hir hir::Expr<'hir> { | |
ba9703b0 | 1800 | self.arena.alloc(self.expr_call_mut(span, e, args)) |
416331ca XL |
1801 | } |
1802 | ||
3dfed10e | 1803 | fn expr_call_lang_item_fn_mut( |
416331ca XL |
1804 | &mut self, |
1805 | span: Span, | |
3dfed10e | 1806 | lang_item: hir::LangItem, |
dfeec247 | 1807 | args: &'hir [hir::Expr<'hir>], |
a2a8927a | 1808 | hir_id: Option<hir::HirId>, |
ba9703b0 | 1809 | ) -> hir::Expr<'hir> { |
487cf647 | 1810 | let path = self.arena.alloc(self.expr_lang_item_path(span, lang_item, hir_id)); |
ba9703b0 XL |
1811 | self.expr_call_mut(span, path, args) |
1812 | } | |
1813 | ||
3dfed10e | 1814 | fn expr_call_lang_item_fn( |
ba9703b0 XL |
1815 | &mut self, |
1816 | span: Span, | |
3dfed10e | 1817 | lang_item: hir::LangItem, |
ba9703b0 | 1818 | args: &'hir [hir::Expr<'hir>], |
a2a8927a | 1819 | hir_id: Option<hir::HirId>, |
ba9703b0 | 1820 | ) -> &'hir hir::Expr<'hir> { |
a2a8927a | 1821 | self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args, hir_id)) |
416331ca XL |
1822 | } |
1823 | ||
3dfed10e | 1824 | fn expr_lang_item_path( |
416331ca XL |
1825 | &mut self, |
1826 | span: Span, | |
3dfed10e | 1827 | lang_item: hir::LangItem, |
a2a8927a | 1828 | hir_id: Option<hir::HirId>, |
dfeec247 | 1829 | ) -> hir::Expr<'hir> { |
94222f64 XL |
1830 | self.expr( |
1831 | span, | |
a2a8927a | 1832 | hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id)), |
94222f64 | 1833 | ) |
416331ca XL |
1834 | } |
1835 | ||
9ffffee4 FG |
1836 | /// `<LangItem>::name` |
1837 | pub(super) fn expr_lang_item_type_relative( | |
1838 | &mut self, | |
1839 | span: Span, | |
1840 | lang_item: hir::LangItem, | |
1841 | name: Symbol, | |
1842 | ) -> hir::Expr<'hir> { | |
1843 | let path = hir::ExprKind::Path(hir::QPath::TypeRelative( | |
1844 | self.arena.alloc(self.ty( | |
1845 | span, | |
1846 | hir::TyKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), None)), | |
1847 | )), | |
1848 | self.arena.alloc(hir::PathSegment::new( | |
1849 | Ident::new(name, span), | |
1850 | self.next_id(), | |
1851 | Res::Err, | |
1852 | )), | |
1853 | )); | |
1854 | self.expr(span, path) | |
1855 | } | |
1856 | ||
dfeec247 XL |
1857 | pub(super) fn expr_ident( |
1858 | &mut self, | |
1859 | sp: Span, | |
1860 | ident: Ident, | |
1861 | binding: hir::HirId, | |
1862 | ) -> &'hir hir::Expr<'hir> { | |
1863 | self.arena.alloc(self.expr_ident_mut(sp, ident, binding)) | |
1864 | } | |
1865 | ||
1866 | pub(super) fn expr_ident_mut( | |
416331ca XL |
1867 | &mut self, |
1868 | span: Span, | |
1869 | ident: Ident, | |
1870 | binding: hir::HirId, | |
dfeec247 | 1871 | ) -> hir::Expr<'hir> { |
f2b60f7d FG |
1872 | let hir_id = self.next_id(); |
1873 | let res = Res::Local(binding); | |
416331ca XL |
1874 | let expr_path = hir::ExprKind::Path(hir::QPath::Resolved( |
1875 | None, | |
dfeec247 | 1876 | self.arena.alloc(hir::Path { |
94222f64 | 1877 | span: self.lower_span(span), |
f2b60f7d FG |
1878 | res, |
1879 | segments: arena_vec![self; hir::PathSegment::new(ident, hir_id, res)], | |
416331ca XL |
1880 | }), |
1881 | )); | |
1882 | ||
487cf647 | 1883 | self.expr(span, expr_path) |
416331ca XL |
1884 | } |
1885 | ||
dfeec247 | 1886 | fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> { |
416331ca XL |
1887 | let hir_id = self.next_id(); |
1888 | let span = expr.span; | |
1889 | self.expr( | |
1890 | span, | |
dfeec247 XL |
1891 | hir::ExprKind::Block( |
1892 | self.arena.alloc(hir::Block { | |
1893 | stmts: &[], | |
1894 | expr: Some(expr), | |
1895 | hir_id, | |
1896 | rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated), | |
94222f64 | 1897 | span: self.lower_span(span), |
dfeec247 XL |
1898 | targeted_by_break: false, |
1899 | }), | |
1900 | None, | |
1901 | ), | |
416331ca XL |
1902 | ) |
1903 | } | |
1904 | ||
dfeec247 XL |
1905 | fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> { |
1906 | let blk = self.block_all(span, &[], None); | |
487cf647 | 1907 | let expr = self.expr_block(blk); |
dfeec247 | 1908 | self.arena.alloc(expr) |
416331ca XL |
1909 | } |
1910 | ||
487cf647 FG |
1911 | pub(super) fn expr_block(&mut self, b: &'hir hir::Block<'hir>) -> hir::Expr<'hir> { |
1912 | self.expr(b.span, hir::ExprKind::Block(b, None)) | |
416331ca XL |
1913 | } |
1914 | ||
9ffffee4 FG |
1915 | pub(super) fn expr_array_ref( |
1916 | &mut self, | |
1917 | span: Span, | |
1918 | elements: &'hir [hir::Expr<'hir>], | |
1919 | ) -> hir::Expr<'hir> { | |
1920 | let addrof = hir::ExprKind::AddrOf( | |
1921 | hir::BorrowKind::Ref, | |
1922 | hir::Mutability::Not, | |
1923 | self.arena.alloc(self.expr(span, hir::ExprKind::Array(elements))), | |
1924 | ); | |
1925 | self.expr(span, addrof) | |
1926 | } | |
1927 | ||
487cf647 | 1928 | pub(super) fn expr(&mut self, span: Span, kind: hir::ExprKind<'hir>) -> hir::Expr<'hir> { |
6a06907d | 1929 | let hir_id = self.next_id(); |
94222f64 | 1930 | hir::Expr { hir_id, kind, span: self.lower_span(span) } |
416331ca XL |
1931 | } |
1932 | ||
9ffffee4 | 1933 | pub(super) fn expr_field( |
6a06907d XL |
1934 | &mut self, |
1935 | ident: Ident, | |
1936 | expr: &'hir hir::Expr<'hir>, | |
1937 | span: Span, | |
1938 | ) -> hir::ExprField<'hir> { | |
94222f64 XL |
1939 | hir::ExprField { |
1940 | hir_id: self.next_id(), | |
1941 | ident, | |
1942 | span: self.lower_span(span), | |
1943 | expr, | |
1944 | is_shorthand: false, | |
1945 | } | |
416331ca XL |
1946 | } |
1947 | ||
9ffffee4 FG |
1948 | pub(super) fn arm( |
1949 | &mut self, | |
1950 | pat: &'hir hir::Pat<'hir>, | |
1951 | expr: &'hir hir::Expr<'hir>, | |
1952 | ) -> hir::Arm<'hir> { | |
94222f64 XL |
1953 | hir::Arm { |
1954 | hir_id: self.next_id(), | |
1955 | pat, | |
1956 | guard: None, | |
1957 | span: self.lower_span(expr.span), | |
1958 | body: expr, | |
1959 | } | |
416331ca XL |
1960 | } |
1961 | } |