|
| 1 | +use rustc_ast::ptr::P; |
| 2 | +use rustc_ast::tokenstream::TokenStream; |
| 3 | +use rustc_ast::{ |
| 4 | + CaptureBy, ClosureBinder, Const, CoroutineKind, DUMMY_NODE_ID, Expr, ExprKind, ast, token, |
| 5 | +}; |
| 6 | +use rustc_errors::PResult; |
| 7 | +use rustc_expand::base::{self, DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; |
| 8 | +use rustc_span::Span; |
| 9 | + |
| 10 | +pub(crate) fn expand<'cx>( |
| 11 | + cx: &'cx mut ExtCtxt<'_>, |
| 12 | + sp: Span, |
| 13 | + tts: TokenStream, |
| 14 | +) -> MacroExpanderResult<'cx> { |
| 15 | + let closure = match parse_closure(cx, sp, tts) { |
| 16 | + Ok(parsed) => parsed, |
| 17 | + Err(err) => { |
| 18 | + return ExpandResult::Ready(DummyResult::any(sp, err.emit())); |
| 19 | + } |
| 20 | + }; |
| 21 | + |
| 22 | + ExpandResult::Ready(base::MacEager::expr(closure)) |
| 23 | +} |
| 24 | + |
| 25 | +fn parse_closure<'a>( |
| 26 | + cx: &mut ExtCtxt<'a>, |
| 27 | + span: Span, |
| 28 | + stream: TokenStream, |
| 29 | +) -> PResult<'a, P<Expr>> { |
| 30 | + let mut parser = cx.new_parser_from_tts(stream); |
| 31 | + let mut closure_parser = parser.clone(); |
| 32 | + |
| 33 | + let coroutine_kind = Some(CoroutineKind::Gen { |
| 34 | + span, |
| 35 | + closure_id: DUMMY_NODE_ID, |
| 36 | + return_impl_trait_id: DUMMY_NODE_ID, |
| 37 | + }); |
| 38 | + |
| 39 | + match closure_parser.parse_expr() { |
| 40 | + Ok(mut closure) => { |
| 41 | + if let ast::ExprKind::Closure(c) = &mut closure.kind { |
| 42 | + if let Some(kind) = c.coroutine_kind { |
| 43 | + cx.dcx().span_err(kind.span(), "only plain closures allowed in `iter!`"); |
| 44 | + } |
| 45 | + c.coroutine_kind = coroutine_kind; |
| 46 | + if closure_parser.token != token::Eof { |
| 47 | + closure_parser.unexpected()?; |
| 48 | + } |
| 49 | + return Ok(closure); |
| 50 | + } |
| 51 | + } |
| 52 | + Err(diag) => diag.cancel(), |
| 53 | + } |
| 54 | + |
| 55 | + let lo = parser.token.span.shrink_to_lo(); |
| 56 | + let block = parser.parse_block_tail( |
| 57 | + lo, |
| 58 | + ast::BlockCheckMode::Default, |
| 59 | + rustc_parse::parser::AttemptLocalParseRecovery::No, |
| 60 | + )?; |
| 61 | + let fn_decl = cx.fn_decl(Default::default(), ast::FnRetTy::Default(span)); |
| 62 | + let closure = ast::Closure { |
| 63 | + binder: ClosureBinder::NotPresent, |
| 64 | + capture_clause: CaptureBy::Ref, |
| 65 | + constness: Const::No, |
| 66 | + coroutine_kind, |
| 67 | + movability: ast::Movability::Movable, |
| 68 | + fn_decl, |
| 69 | + body: cx.expr_block(block), |
| 70 | + fn_decl_span: span, |
| 71 | + fn_arg_span: span, |
| 72 | + }; |
| 73 | + if parser.token != token::Eof { |
| 74 | + parser.unexpected()?; |
| 75 | + } |
| 76 | + let span = lo.to(parser.token.span); |
| 77 | + Ok(cx.expr(span, ExprKind::Closure(Box::new(closure)))) |
| 78 | +} |
0 commit comments