1 // Copyright 2012 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.
11 use ast::{Ident, Matcher_, Matcher, MatchTok, MatchNonterminal, MatchSeq};
14 use codemap::{Span, Spanned, DUMMY_SP};
15 use ext::base::{ExtCtxt, MacResult, MacroDef};
16 use ext::base::{NormalTT, TTMacroExpander};
18 use ext::tt::macro_parser::{Success, Error, Failure};
19 use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
20 use ext::tt::macro_parser::{parse, parse_or_else};
21 use parse::lexer::new_tt_reader;
22 use parse::parser::Parser;
23 use parse::attr::ParserAttr;
24 use parse::token::{special_idents, gensym_ident};
25 use parse::token::{FAT_ARROW, SEMI, NtMatchers, NtTT, EOF};
28 use util::small_vector::SmallVector;
30 use std::cell::RefCell;
34 struct ParserAnyMacro<'a> {
35 parser: RefCell<Parser<'a>>,
38 impl<'a> ParserAnyMacro<'a> {
39 /// Make sure we don't have any tokens left to parse, so we don't
40 /// silently drop anything. `allow_semi` is so that "optional"
41 /// semilons at the end of normal expressions aren't complained
42 /// about e.g. the semicolon in `macro_rules! kapow( () => {
43 /// fail!(); } )` doesn't get picked up by .parse_expr(), but it's
44 /// allowed to be there.
45 fn ensure_complete_parse(&self, allow_semi: bool) {
46 let mut parser = self.parser.borrow_mut();
47 if allow_semi && parser.token == SEMI {
50 if parser.token != EOF {
51 let token_str = parser.this_token_to_string();
52 let msg = format!("macro expansion ignores token `{}` and any \
55 let span = parser.span;
56 parser.span_err(span, msg.as_slice());
61 impl<'a> MacResult for ParserAnyMacro<'a> {
62 fn make_expr(&self) -> Option<Gc<ast::Expr>> {
63 let ret = self.parser.borrow_mut().parse_expr();
64 self.ensure_complete_parse(true);
67 fn make_pat(&self) -> Option<Gc<ast::Pat>> {
68 let ret = self.parser.borrow_mut().parse_pat();
69 self.ensure_complete_parse(false);
72 fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
73 let mut ret = SmallVector::zero();
75 let mut parser = self.parser.borrow_mut();
76 match parser.parse_item_with_outer_attributes() {
77 Some(item) => ret.push(item),
81 self.ensure_complete_parse(false);
84 fn make_stmt(&self) -> Option<Gc<ast::Stmt>> {
85 let attrs = self.parser.borrow_mut().parse_outer_attributes();
86 let ret = self.parser.borrow_mut().parse_stmt(attrs);
87 self.ensure_complete_parse(true);
92 struct MacroRulesMacroExpander {
94 lhses: Vec<Rc<NamedMatch>>,
95 rhses: Vec<Rc<NamedMatch>>,
98 impl TTMacroExpander for MacroRulesMacroExpander {
102 arg: &[ast::TokenTree])
104 generic_extension(cx,
108 self.lhses.as_slice(),
109 self.rhses.as_slice())
113 struct MacroRulesDefiner {
114 def: RefCell<Option<MacroDef>>
116 impl MacResult for MacroRulesDefiner {
117 fn make_def(&self) -> Option<MacroDef> {
118 Some(self.def.borrow_mut().take().expect("MacroRulesDefiner expanded twice"))
122 /// Given `lhses` and `rhses`, this is the new macro we create
123 fn generic_extension(cx: &ExtCtxt,
126 arg: &[ast::TokenTree],
127 lhses: &[Rc<NamedMatch>],
128 rhses: &[Rc<NamedMatch>])
130 if cx.trace_macros() {
131 println!("{}! {} {} {}",
132 token::get_ident(name),
134 print::pprust::tt_to_string(&TTDelim(Rc::new(arg.iter()
135 .map(|x| (*x).clone())
140 // Which arm's failure should we report? (the one furthest along)
141 let mut best_fail_spot = DUMMY_SP;
142 let mut best_fail_msg = "internal error: ran no matchers".to_string();
144 for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
146 MatchedNonterminal(NtMatchers(ref mtcs)) => {
147 // `None` is because we're not interpolating
148 let arg_rdr = new_tt_reader(&cx.parse_sess().span_diagnostic,
151 .map(|x| (*x).clone())
153 match parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtcs.as_slice()) {
154 Success(named_matches) => {
155 let rhs = match *rhses[i] {
156 // okay, what's your transcriber?
157 MatchedNonterminal(NtTT(tt)) => {
159 // cut off delimiters; don't parse 'em
160 TTDelim(ref tts) => {
161 (*tts).slice(1u,(*tts).len()-1u)
163 .map(|x| (*x).clone())
167 sp, "macro rhs must be delimited")
170 _ => cx.span_bug(sp, "bad thing in rhs")
172 // rhs has holes ( `$id` and `$(...)` that need filled)
173 let trncbr = new_tt_reader(&cx.parse_sess().span_diagnostic,
176 let p = Parser::new(cx.parse_sess(), cx.cfg(), box trncbr);
177 // Let the context choose how to interpret the result.
178 // Weird, but useful for X-macros.
179 return box ParserAnyMacro {
180 parser: RefCell::new(p),
183 Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo {
185 best_fail_msg = (*msg).clone();
187 Error(sp, ref msg) => cx.span_fatal(sp, msg.as_slice())
190 _ => cx.bug("non-matcher found in parsed lhses")
193 cx.span_fatal(best_fail_spot, best_fail_msg.as_slice());
196 /// This procedure performs the expansion of the
197 /// macro_rules! macro. It parses the RHS and adds
198 /// an extension to the current context.
199 pub fn add_new_extension(cx: &mut ExtCtxt,
202 arg: Vec<ast::TokenTree> )
203 -> Box<base::MacResult> {
204 // these spans won't matter, anyways
205 fn ms(m: Matcher_) -> Matcher {
212 let lhs_nm = gensym_ident("lhs");
213 let rhs_nm = gensym_ident("rhs");
215 // The pattern that macro_rules matches.
216 // The grammar for macro_rules! is:
217 // $( $lhs:mtcs => $rhs:tt );+
218 // ...quasiquoting this would be nice.
219 let argument_gram = vec!(
221 ms(MatchNonterminal(lhs_nm, special_idents::matchers, 0u)),
222 ms(MatchTok(FAT_ARROW)),
223 ms(MatchNonterminal(rhs_nm, special_idents::tt, 1u))), Some(SEMI), false, 0u, 2u)),
224 //to phase into semicolon-termination instead of
225 //semicolon-separation
226 ms(MatchSeq(vec!(ms(MatchTok(SEMI))), None, true, 2u, 2u)));
229 // Parse the macro_rules! invocation (`none` is for no interpolations):
230 let arg_reader = new_tt_reader(&cx.parse_sess().span_diagnostic,
233 let argument_map = parse_or_else(cx.parse_sess(),
238 // Extract the arguments:
239 let lhses = match **argument_map.get(&lhs_nm) {
240 MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(),
241 _ => cx.span_bug(sp, "wrong-structured lhs")
244 let rhses = match **argument_map.get(&rhs_nm) {
245 MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(),
246 _ => cx.span_bug(sp, "wrong-structured rhs")
249 let exp = box MacroRulesMacroExpander {
255 box MacroRulesDefiner {
256 def: RefCell::new(Some(MacroDef {
257 name: token::get_ident(name).to_string(),
258 ext: NormalTT(exp, Some(sp))