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.
13 #![crate_type="dylib"]
14 #![feature(plugin_registrar, quote, rustc_private)]
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};
27 use rustc::plugin::Registry;
29 fn expand_mbe_matches(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
30 -> Box<MacResult + 'static> {
32 let mbe_matcher = quote_matcher!(cx, $matched:expr, $($pat:pat)|+);
34 let mac_expr = match TokenTree::parse(cx, &mbe_matcher[..], args) {
36 match (&*map[&str_to_ident("matched").name], &*map[&str_to_ident("pat").name]) {
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 {
46 let arm = cx.arm(seq_sp, pats, cx.expr_bool(seq_sp, true));
58 Failure(_, s) | Error(_, s) => {
59 panic!("expected Success, but got Error/Failure: {}", s);
63 MacEager::expr(mac_expr)
67 pub fn plugin_registrar(reg: &mut Registry) {
68 reg.register_macro("matches", expand_mbe_matches);