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.
12 * The compiler code necessary to support the `push_unsafe!` and
13 * `pop_unsafe!` macros.
15 * This is a hack to allow a kind of "safety hygiene", where a macro
16 * can generate code with an interior expression that inherits the
17 * safety of some outer context.
22 * fn foo() { push_unsafe!( { EXPR_1; pop_unsafe!( EXPR_2 ) } ) }
25 * the `EXPR_1` is considered to be in an `unsafe` context,
26 * but `EXPR_2` is considered to be in a "safe" (i.e. checked) context.
31 * fn foo() { unsafe { push_unsafe!( { EXPR_1; pop_unsafe!( EXPR_2 ) } ) } }
34 * both `EXPR_1` and `EXPR_2` are considered to be in `unsafe`
43 use ext::build::AstBuilder;
47 enum PushPop { Push, Pop }
49 pub fn expand_push_unsafe<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
50 -> Box<base::MacResult+'cx> {
51 expand_pushpop_unsafe(cx, sp, tts, PushPop::Push)
54 pub fn expand_pop_unsafe<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
55 -> Box<base::MacResult+'cx> {
56 expand_pushpop_unsafe(cx, sp, tts, PushPop::Pop)
59 fn expand_pushpop_unsafe<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree],
60 pp: PushPop) -> Box<base::MacResult+'cx> {
61 feature_gate::check_for_pushpop_syntax(
62 cx.ecfg.features, &cx.parse_sess.span_diagnostic, sp);
64 let mut exprs = match get_exprs_from_tts(cx, sp, tts) {
65 Some(exprs) => exprs.into_iter(),
66 None => return DummyResult::expr(sp),
69 let expr = match (exprs.next(), exprs.next()) {
70 (Some(expr), None) => expr,
73 PushPop::Push => "push_unsafe! takes 1 arguments",
74 PushPop::Pop => "pop_unsafe! takes 1 arguments",
77 return DummyResult::expr(sp);
81 let source = ast::UnsafeSource::CompilerGenerated;
82 let check_mode = match pp {
83 PushPop::Push => ast::BlockCheckMode::PushUnsafeBlock(source),
84 PushPop::Pop => ast::BlockCheckMode::PopUnsafeBlock(source),
87 MacEager::expr(cx.expr_block(P(ast::Block {
90 id: ast::DUMMY_NODE_ID,