]> git.lizzy.rs Git - rust.git/blob - src/test/auxiliary/procedural_mbe_matching.rs
Tell LLVM when a match is exhaustive
[rust.git] / src / test / auxiliary / procedural_mbe_matching.rs
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.
4 //
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.
10
11 // force-host
12
13 #![crate_type="dylib"]
14 #![feature(plugin_registrar, quote, rustc_private)]
15
16 extern crate syntax;
17 extern crate rustc;
18
19 use syntax::codemap::Span;
20 use syntax::parse::token::{self, str_to_ident, NtExpr, NtPat};
21 use syntax::ast::{TokenTree, TtToken, Pat};
22 use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacEager};
23 use syntax::ext::build::AstBuilder;
24 use syntax::ext::tt::macro_parser::{MatchedSeq, MatchedNonterminal};
25 use syntax::ext::tt::macro_parser::{Success, Failure, Error};
26 use syntax::ptr::P;
27 use rustc::plugin::Registry;
28
29 fn expand_mbe_matches(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
30         -> Box<MacResult + 'static> {
31
32     let mbe_matcher = quote_matcher!(cx, $matched:expr, $($pat:pat)|+);
33
34     let mac_expr = match TokenTree::parse(cx, &mbe_matcher[..], args) {
35         Success(map) => {
36             match (&*map[&str_to_ident("matched")], &*map[&str_to_ident("pat")]) {
37                 (&MatchedNonterminal(NtExpr(ref matched_expr)),
38                  &MatchedSeq(ref pats, seq_sp)) => {
39                     let pats: Vec<P<Pat>> = pats.iter().map(|pat_nt|
40                         if let &MatchedNonterminal(NtPat(ref pat)) = &**pat_nt {
41                             pat.clone()
42                         } else {
43                             unreachable!()
44                         }
45                     ).collect();
46                     let arm = cx.arm(seq_sp, pats, cx.expr_bool(seq_sp, true));
47
48                     quote_expr!(cx,
49                         match $matched_expr {
50                             $arm
51                             _ => false
52                         }
53                     )
54                 }
55                 _ => unreachable!()
56             }
57         }
58         Failure(_, s) | Error(_, s) => {
59             panic!("expected Success, but got Error/Failure: {}", s);
60         }
61     };
62
63     MacEager::expr(mac_expr)
64 }
65
66 #[plugin_registrar]
67 pub fn plugin_registrar(reg: &mut Registry) {
68     reg.register_macro("matches", expand_mbe_matches);
69 }